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