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