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