Remove Path::canExecute.
[oota-llvm.git] / lib / Support / Windows / Path.inc
1 //===- llvm/Support/Win32/Path.cpp - Win32 Path Implementation ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides the Win32 specific implementation of the Path class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic Win32 code that
16 //===          is guaranteed to work on *all* Win32 variants.
17 //===----------------------------------------------------------------------===//
18
19 #include "Windows.h"
20 #include <cstdio>
21 #include <malloc.h>
22
23 // We need to undo a macro defined in Windows.h, otherwise we won't compile:
24 #undef GetCurrentDirectory
25
26 // Windows happily accepts either forward or backward slashes, though any path
27 // returned by a Win32 API will have backward slashes.  As LLVM code basically
28 // assumes forward slashes are used, backward slashs are converted where they
29 // can be introduced into a path.
30 //
31 // Another invariant is that a path ends with a slash if and only if the path
32 // is a root directory.  Any other use of a trailing slash is stripped.  Unlike
33 // in Unix, Windows has a rather complicated notion of a root path and this
34 // invariant helps simply the code.
35
36 static void FlipBackSlashes(std::string& s) {
37   for (size_t i = 0; i < s.size(); i++)
38     if (s[i] == '\\')
39       s[i] = '/';
40 }
41
42 namespace llvm {
43 namespace sys {
44
45 const char PathSeparator = ';';
46
47 StringRef Path::GetEXESuffix() {
48   return "exe";
49 }
50
51 Path::Path(llvm::StringRef p)
52   : path(p) {
53   FlipBackSlashes(path);
54 }
55
56 Path::Path(const char *StrStart, unsigned StrLen)
57   : path(StrStart, StrLen) {
58   FlipBackSlashes(path);
59 }
60
61 Path&
62 Path::operator=(StringRef that) {
63   path.assign(that.data(), that.size());
64   FlipBackSlashes(path);
65   return *this;
66 }
67
68 bool
69 Path::isValid() const {
70   if (path.empty())
71     return false;
72
73   size_t len = path.size();
74   // If there is a null character, it and all its successors are ignored.
75   size_t pos = path.find_first_of('\0');
76   if (pos != std::string::npos)
77     len = pos;
78
79   // If there is a colon, it must be the second character, preceded by a letter
80   // and followed by something.
81   pos = path.rfind(':',len);
82   size_t rootslash = 0;
83   if (pos != std::string::npos) {
84     if (pos != 1 || !isalpha(static_cast<unsigned char>(path[0])) || len < 3)
85       return false;
86       rootslash = 2;
87   }
88
89   // Look for a UNC path, and if found adjust our notion of the root slash.
90   if (len > 3 && path[0] == '/' && path[1] == '/') {
91     rootslash = path.find('/', 2);
92     if (rootslash == std::string::npos)
93       rootslash = 0;
94   }
95
96   // Check for illegal characters.
97   if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
98                          "\013\014\015\016\017\020\021\022\023\024\025\026"
99                          "\027\030\031\032\033\034\035\036\037")
100       != std::string::npos)
101     return false;
102
103   // Remove trailing slash, unless it's a root slash.
104   if (len > rootslash+1 && path[len-1] == '/')
105     path.erase(--len);
106
107   // Check each component for legality.
108   for (pos = 0; pos < len; ++pos) {
109     // A component may not end in a space.
110     if (path[pos] == ' ') {
111       if (pos+1 == len || path[pos+1] == '/' || path[pos+1] == '\0')
112         return false;
113     }
114
115     // A component may not end in a period.
116     if (path[pos] == '.') {
117       if (pos+1 == len || path[pos+1] == '/') {
118         // Unless it is the pseudo-directory "."...
119         if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
120           return true;
121         // or "..".
122         if (pos > 0 && path[pos-1] == '.') {
123           if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
124             return true;
125         }
126         return false;
127       }
128     }
129   }
130
131   return true;
132 }
133
134 void Path::makeAbsolute() {
135   TCHAR  FullPath[MAX_PATH + 1] = {0};
136   LPTSTR FilePart = NULL;
137
138   DWORD RetLength = ::GetFullPathNameA(path.c_str(),
139                         sizeof(FullPath)/sizeof(FullPath[0]),
140                         FullPath, &FilePart);
141
142   if (0 == RetLength) {
143     // FIXME: Report the error GetLastError()
144     assert(0 && "Unable to make absolute path!");
145   } else if (RetLength > MAX_PATH) {
146     // FIXME: Report too small buffer (needed RetLength bytes).
147     assert(0 && "Unable to make absolute path!");
148   } else {
149     path = FullPath;
150   }
151 }
152
153 static Path *TempDirectory;
154
155 Path
156 Path::GetTemporaryDirectory(std::string* ErrMsg) {
157   if (TempDirectory) {
158 #if defined(_MSC_VER)
159     // Visual Studio gets confused and emits a diagnostic about calling exists,
160     // even though this is the implementation for PathV1.  Temporarily 
161     // disable the deprecated warning message
162     #pragma warning(push)
163     #pragma warning(disable:4996)
164 #endif
165     assert(TempDirectory->exists() && "Who has removed TempDirectory?");
166 #if defined(_MSC_VER)
167     #pragma warning(pop)
168 #endif
169     return *TempDirectory;
170   }
171
172   char pathname[MAX_PATH];
173   if (!GetTempPath(MAX_PATH, pathname)) {
174     if (ErrMsg)
175       *ErrMsg = "Can't determine temporary directory";
176     return Path();
177   }
178
179   Path result;
180   result.set(pathname);
181
182   // Append a subdirectory based on our process id so multiple LLVMs don't
183   // step on each other's toes.
184 #ifdef __MINGW32__
185   // Mingw's Win32 header files are broken.
186   sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
187 #else
188   sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
189 #endif
190   result.appendComponent(pathname);
191
192   // If there's a directory left over from a previous LLVM execution that
193   // happened to have the same process id, get rid of it.
194   result.eraseFromDisk(true);
195
196   // And finally (re-)create the empty directory.
197   result.createDirectoryOnDisk(false);
198   TempDirectory = new Path(result);
199   return *TempDirectory;
200 }
201
202 Path
203 Path::GetCurrentDirectory() {
204   char pathname[MAX_PATH];
205   ::GetCurrentDirectoryA(MAX_PATH,pathname);
206   return Path(pathname);
207 }
208
209 /// GetMainExecutable - Return the path to the main executable, given the
210 /// value of argv[0] from program startup.
211 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
212   char pathname[MAX_PATH];
213   DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
214   return ret != MAX_PATH ? Path(pathname) : Path();
215 }
216
217
218 // FIXME: the above set of functions don't map to Windows very well.
219
220 bool
221 Path::exists() const {
222   DWORD attr = GetFileAttributes(path.c_str());
223   return attr != INVALID_FILE_ATTRIBUTES;
224 }
225
226 bool
227 Path::isDirectory() const {
228   DWORD attr = GetFileAttributes(path.c_str());
229   return (attr != INVALID_FILE_ATTRIBUTES) &&
230          (attr & FILE_ATTRIBUTE_DIRECTORY);
231 }
232
233 bool
234 Path::isSymLink() const {
235   DWORD attributes = GetFileAttributes(path.c_str());
236
237   if (attributes == INVALID_FILE_ATTRIBUTES)
238     // There's no sane way to report this :(.
239     assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
240
241   // This isn't exactly what defines a NTFS symlink, but it is only true for
242   // paths that act like a symlink.
243   return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
244 }
245
246 bool
247 Path::isRegularFile() const {
248   bool res;
249   if (fs::is_regular_file(path, res))
250     return false;
251   return res;
252 }
253
254 const FileStatus *
255 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
256   if (!fsIsValid || update) {
257     WIN32_FILE_ATTRIBUTE_DATA fi;
258     if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
259       MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
260                       ": Can't get status: ");
261       return 0;
262     }
263
264     status.fileSize = fi.nFileSizeHigh;
265     status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
266     status.fileSize += fi.nFileSizeLow;
267
268     status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
269     status.user = 9999;    // Not applicable to Windows, so...
270     status.group = 9999;   // Not applicable to Windows, so...
271
272     ULARGE_INTEGER ui;
273     ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
274     ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
275     status.modTime.fromWin32Time(ui.QuadPart);
276
277     status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
278     fsIsValid = true;
279   }
280   return &status;
281 }
282
283 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
284   // All files are readable on Windows (ignoring security attributes).
285   return false;
286 }
287
288 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
289   DWORD attr = GetFileAttributes(path.c_str());
290
291   // If it doesn't exist, we're done.
292   if (attr == INVALID_FILE_ATTRIBUTES)
293     return false;
294
295   if (attr & FILE_ATTRIBUTE_READONLY) {
296     if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
297       MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
298       return true;
299     }
300   }
301   return false;
302 }
303
304 bool
305 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
306   WIN32_FILE_ATTRIBUTE_DATA fi;
307   if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
308     MakeErrMsg(ErrMsg, path + ": can't get status of file");
309     return true;
310   }
311
312   if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
313     if (ErrMsg)
314       *ErrMsg = path + ": not a directory";
315     return true;
316   }
317
318   result.clear();
319   WIN32_FIND_DATA fd;
320   std::string searchpath = path;
321   if (path.size() == 0 || searchpath[path.size()-1] == '/')
322     searchpath += "*";
323   else
324     searchpath += "/*";
325
326   HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
327   if (h == INVALID_HANDLE_VALUE) {
328     if (GetLastError() == ERROR_FILE_NOT_FOUND)
329       return true; // not really an error, now is it?
330     MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
331     return true;
332   }
333
334   do {
335     if (fd.cFileName[0] == '.')
336       continue;
337     Path aPath(path);
338     aPath.appendComponent(&fd.cFileName[0]);
339     result.insert(aPath);
340   } while (FindNextFile(h, &fd));
341
342   DWORD err = GetLastError();
343   FindClose(h);
344   if (err != ERROR_NO_MORE_FILES) {
345     SetLastError(err);
346     MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
347     return true;
348   }
349   return false;
350 }
351
352 bool
353 Path::set(StringRef a_path) {
354   if (a_path.empty())
355     return false;
356   std::string save(path);
357   path = a_path;
358   FlipBackSlashes(path);
359   if (!isValid()) {
360     path = save;
361     return false;
362   }
363   return true;
364 }
365
366 bool
367 Path::appendComponent(StringRef name) {
368   if (name.empty())
369     return false;
370   std::string save(path);
371   if (!path.empty()) {
372     size_t last = path.size() - 1;
373     if (path[last] != '/')
374       path += '/';
375   }
376   path += name;
377   if (!isValid()) {
378     path = save;
379     return false;
380   }
381   return true;
382 }
383
384 bool
385 Path::eraseComponent() {
386   size_t slashpos = path.rfind('/',path.size());
387   if (slashpos == path.size() - 1 || slashpos == std::string::npos)
388     return false;
389   std::string save(path);
390   path.erase(slashpos);
391   if (!isValid()) {
392     path = save;
393     return false;
394   }
395   return true;
396 }
397
398 bool
399 Path::eraseSuffix() {
400   size_t dotpos = path.rfind('.',path.size());
401   size_t slashpos = path.rfind('/',path.size());
402   if (dotpos != std::string::npos) {
403     if (slashpos == std::string::npos || dotpos > slashpos+1) {
404       std::string save(path);
405       path.erase(dotpos, path.size()-dotpos);
406       if (!isValid()) {
407         path = save;
408         return false;
409       }
410       return true;
411     }
412   }
413   return false;
414 }
415
416 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
417   if (ErrMsg)
418     *ErrMsg = std::string(pathname) + ": " + std::string(msg);
419   return true;
420 }
421
422 bool
423 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
424   // Get a writeable copy of the path name
425   size_t len = path.length();
426   char *pathname = reinterpret_cast<char *>(_alloca(len+2));
427   path.copy(pathname, len);
428   pathname[len] = 0;
429
430   // Make sure it ends with a slash.
431   if (len == 0 || pathname[len - 1] != '/') {
432     pathname[len] = '/';
433     pathname[++len] = 0;
434   }
435
436   // Determine starting point for initial / search.
437   char *next = pathname;
438   if (pathname[0] == '/' && pathname[1] == '/') {
439     // Skip host name.
440     next = strchr(pathname+2, '/');
441     if (next == NULL)
442       return PathMsg(ErrMsg, pathname, "badly formed remote directory");
443
444     // Skip share name.
445     next = strchr(next+1, '/');
446     if (next == NULL)
447       return PathMsg(ErrMsg, pathname,"badly formed remote directory");
448
449     next++;
450     if (*next == 0)
451       return PathMsg(ErrMsg, pathname, "badly formed remote directory");
452
453   } else {
454     if (pathname[1] == ':')
455       next += 2;    // skip drive letter
456     if (*next == '/')
457       next++;       // skip root directory
458   }
459
460   // If we're supposed to create intermediate directories
461   if (create_parents) {
462     // Loop through the directory components until we're done
463     while (*next) {
464       next = strchr(next, '/');
465       *next = 0;
466       if (!CreateDirectory(pathname, NULL) &&
467           GetLastError() != ERROR_ALREADY_EXISTS)
468           return MakeErrMsg(ErrMsg,
469             std::string(pathname) + ": Can't create directory: ");
470       *next++ = '/';
471     }
472   } else {
473     // Drop trailing slash.
474     pathname[len-1] = 0;
475     if (!CreateDirectory(pathname, NULL) &&
476         GetLastError() != ERROR_ALREADY_EXISTS) {
477       return MakeErrMsg(ErrMsg, std::string(pathname) +
478                         ": Can't create directory: ");
479     }
480   }
481   return false;
482 }
483
484 bool
485 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
486   WIN32_FILE_ATTRIBUTE_DATA fi;
487   if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
488     return true;
489
490   if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
491     // If it doesn't exist, we're done.
492     bool Exists;
493     if (fs::exists(path, Exists) || !Exists)
494       return false;
495
496     char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
497     int lastchar = path.length() - 1 ;
498     path.copy(pathname, lastchar+1);
499
500     // Make path end with '/*'.
501     if (pathname[lastchar] != '/')
502       pathname[++lastchar] = '/';
503     pathname[lastchar+1] = '*';
504     pathname[lastchar+2] = 0;
505
506     if (remove_contents) {
507       WIN32_FIND_DATA fd;
508       HANDLE h = FindFirstFile(pathname, &fd);
509
510       // It's a bad idea to alter the contents of a directory while enumerating
511       // its contents. So build a list of its contents first, then destroy them.
512
513       if (h != INVALID_HANDLE_VALUE) {
514         std::vector<Path> list;
515
516         do {
517           if (strcmp(fd.cFileName, ".") == 0)
518             continue;
519           if (strcmp(fd.cFileName, "..") == 0)
520             continue;
521
522           Path aPath(path);
523           aPath.appendComponent(&fd.cFileName[0]);
524           list.push_back(aPath);
525         } while (FindNextFile(h, &fd));
526
527         DWORD err = GetLastError();
528         FindClose(h);
529         if (err != ERROR_NO_MORE_FILES) {
530           SetLastError(err);
531           return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
532         }
533
534         for (std::vector<Path>::iterator I = list.begin(); I != list.end();
535              ++I) {
536           Path &aPath = *I;
537           aPath.eraseFromDisk(true);
538         }
539       } else {
540         if (GetLastError() != ERROR_FILE_NOT_FOUND)
541           return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
542       }
543     }
544
545     pathname[lastchar] = 0;
546     if (!RemoveDirectory(pathname))
547       return MakeErrMsg(ErrStr,
548         std::string(pathname) + ": Can't destroy directory: ");
549     return false;
550   } else {
551     // Read-only files cannot be deleted on Windows.  Must remove the read-only
552     // attribute first.
553     if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
554       if (!SetFileAttributes(path.c_str(),
555                              fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
556         return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
557     }
558
559     if (!DeleteFile(path.c_str()))
560       return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
561     return false;
562   }
563 }
564
565 bool
566 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
567   if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
568     return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
569         + "': ");
570   return false;
571 }
572
573 bool
574 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
575   // FIXME: should work on directories also.
576   if (!si.isFile) {
577     return true;
578   }
579
580   HANDLE h = CreateFile(path.c_str(),
581                         FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
582                         FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
583                         NULL,
584                         OPEN_EXISTING,
585                         FILE_ATTRIBUTE_NORMAL,
586                         NULL);
587   if (h == INVALID_HANDLE_VALUE)
588     return true;
589
590   BY_HANDLE_FILE_INFORMATION bhfi;
591   if (!GetFileInformationByHandle(h, &bhfi)) {
592     DWORD err = GetLastError();
593     CloseHandle(h);
594     SetLastError(err);
595     return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
596   }
597
598   ULARGE_INTEGER ui;
599   ui.QuadPart = si.modTime.toWin32Time();
600   FILETIME ft;
601   ft.dwLowDateTime = ui.LowPart;
602   ft.dwHighDateTime = ui.HighPart;
603   BOOL ret = SetFileTime(h, NULL, &ft, &ft);
604   DWORD err = GetLastError();
605   CloseHandle(h);
606   if (!ret) {
607     SetLastError(err);
608     return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
609   }
610
611   // Best we can do with Unix permission bits is to interpret the owner
612   // writable bit.
613   if (si.mode & 0200) {
614     if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
615       if (!SetFileAttributes(path.c_str(),
616               bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
617         return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
618     }
619   } else {
620     if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
621       if (!SetFileAttributes(path.c_str(),
622               bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
623         return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
624     }
625   }
626
627   return false;
628 }
629
630 bool
631 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
632   bool Exists;
633   if (reuse_current && (fs::exists(path, Exists) || !Exists))
634     return false; // File doesn't exist already, just use it!
635
636   // Reserve space for -XXXXXX at the end.
637   char *FNBuffer = (char*) alloca(path.size()+8);
638   unsigned offset = path.size();
639   path.copy(FNBuffer, offset);
640
641   // Find a numeric suffix that isn't used by an existing file.  Assume there
642   // won't be more than 1 million files with the same prefix.  Probably a safe
643   // bet.
644   static int FCounter = -1;
645   if (FCounter < 0) {
646     // Give arbitrary initial seed.
647     // FIXME: We should use sys::fs::unique_file() in future.
648     LARGE_INTEGER cnt64;
649     DWORD x = GetCurrentProcessId();
650     x = (x << 16) | (x >> 16);
651     if (QueryPerformanceCounter(&cnt64))    // RDTSC
652       x ^= cnt64.HighPart ^ cnt64.LowPart;
653     FCounter = x % 1000000;
654   }
655   do {
656     sprintf(FNBuffer+offset, "-%06u", FCounter);
657     if (++FCounter > 999999)
658       FCounter = 0;
659     path = FNBuffer;
660   } while (!fs::exists(path, Exists) && Exists);
661   return false;
662 }
663
664 bool
665 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
666   // Make this into a unique file name
667   makeUnique(reuse_current, ErrMsg);
668
669   // Now go and create it
670   HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
671                         FILE_ATTRIBUTE_NORMAL, NULL);
672   if (h == INVALID_HANDLE_VALUE)
673     return MakeErrMsg(ErrMsg, path + ": can't create file");
674
675   CloseHandle(h);
676   return false;
677 }
678 }
679 }