Fixing a typo in the comments.
[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 <malloc.h>
21 #include <cstdio>
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(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     assert(TempDirectory->exists() && "Who has removed TempDirectory?");
193     return *TempDirectory;
194   }
195
196   char pathname[MAX_PATH];
197   if (!GetTempPath(MAX_PATH, pathname)) {
198     if (ErrMsg)
199       *ErrMsg = "Can't determine temporary directory";
200     return Path();
201   }
202
203   Path result;
204   result.set(pathname);
205
206   // Append a subdirectory based on our process id so multiple LLVMs don't
207   // step on each other's toes.
208 #ifdef __MINGW32__
209   // Mingw's Win32 header files are broken.
210   sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
211 #else
212   sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
213 #endif
214   result.appendComponent(pathname);
215
216   // If there's a directory left over from a previous LLVM execution that
217   // happened to have the same process id, get rid of it.
218   result.eraseFromDisk(true);
219
220   // And finally (re-)create the empty directory.
221   result.createDirectoryOnDisk(false);
222   TempDirectory = new Path(result);
223   return *TempDirectory;
224 }
225
226 // FIXME: the following set of functions don't map to Windows very well.
227 Path
228 Path::GetRootDirectory() {
229   // This is the only notion that that Windows has of a root directory. Nothing
230   // is here except for drives.
231   return Path("file:///");
232 }
233
234 void
235 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
236   char buff[MAX_PATH];
237   // Generic form of C:\Windows\System32
238   HRESULT res =  SHGetFolderPathA(NULL,
239                                   CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
240                                   NULL,
241                                   SHGFP_TYPE_CURRENT,
242                                   buff);
243   if (res != S_OK) {
244     assert(0 && "Failed to get system directory");
245     return;
246   }
247   Paths.push_back(sys::Path(buff));
248
249   // Reset buff.
250   buff[0] = 0;
251   // Generic form of C:\Windows
252   res =  SHGetFolderPathA(NULL,
253                           CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
254                           NULL,
255                           SHGFP_TYPE_CURRENT,
256                           buff);
257   if (res != S_OK) {
258     assert(0 && "Failed to get windows directory");
259     return;
260   }
261   Paths.push_back(sys::Path(buff));
262 }
263
264 void
265 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
266   char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
267   if (env_var != 0) {
268     getPathList(env_var,Paths);
269   }
270 #ifdef LLVM_LIBDIR
271   {
272     Path tmpPath;
273     if (tmpPath.set(LLVM_LIBDIR))
274       if (tmpPath.canRead())
275         Paths.push_back(tmpPath);
276   }
277 #endif
278   GetSystemLibraryPaths(Paths);
279 }
280
281 Path
282 Path::GetUserHomeDirectory() {
283   char buff[MAX_PATH];
284   HRESULT res = SHGetFolderPathA(NULL,
285                                  CSIDL_FLAG_CREATE | CSIDL_APPDATA,
286                                  NULL,
287                                  SHGFP_TYPE_CURRENT,
288                                  buff);
289   if (res != S_OK)
290     assert(0 && "Failed to get user home directory");
291   return Path(buff);
292 }
293
294 Path
295 Path::GetCurrentDirectory() {
296   char pathname[MAX_PATH];
297   ::GetCurrentDirectoryA(MAX_PATH,pathname);
298   return Path(pathname);
299 }
300
301 /// GetMainExecutable - Return the path to the main executable, given the
302 /// value of argv[0] from program startup.
303 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
304   char pathname[MAX_PATH];
305   DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
306   return ret != MAX_PATH ? Path(pathname) : Path();
307 }
308
309
310 // FIXME: the above set of functions don't map to Windows very well.
311
312
313 StringRef Path::getDirname() const {
314   return getDirnameCharSep(path, "/");
315 }
316
317 StringRef
318 Path::getBasename() const {
319   // Find the last slash
320   size_t slash = path.rfind('/');
321   if (slash == std::string::npos)
322     slash = 0;
323   else
324     slash++;
325
326   size_t dot = path.rfind('.');
327   if (dot == std::string::npos || dot < slash)
328     return StringRef(path).substr(slash);
329   else
330     return StringRef(path).substr(slash, dot - slash);
331 }
332
333 StringRef
334 Path::getSuffix() const {
335   // Find the last slash
336   size_t slash = path.rfind('/');
337   if (slash == std::string::npos)
338     slash = 0;
339   else
340     slash++;
341
342   size_t dot = path.rfind('.');
343   if (dot == std::string::npos || dot < slash)
344     return StringRef("");
345   else
346     return StringRef(path).substr(dot + 1);
347 }
348
349 bool
350 Path::exists() const {
351   DWORD attr = GetFileAttributes(path.c_str());
352   return attr != INVALID_FILE_ATTRIBUTES;
353 }
354
355 bool
356 Path::isDirectory() const {
357   DWORD attr = GetFileAttributes(path.c_str());
358   return (attr != INVALID_FILE_ATTRIBUTES) &&
359          (attr & FILE_ATTRIBUTE_DIRECTORY);
360 }
361
362 bool
363 Path::isSymLink() const {
364   DWORD attributes = GetFileAttributes(path.c_str());
365
366   if (attributes == INVALID_FILE_ATTRIBUTES)
367     // There's no sane way to report this :(.
368     assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
369
370   // This isn't exactly what defines a NTFS symlink, but it is only true for
371   // paths that act like a symlink.
372   return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
373 }
374
375 bool
376 Path::canRead() const {
377   // FIXME: take security attributes into account.
378   DWORD attr = GetFileAttributes(path.c_str());
379   return attr != INVALID_FILE_ATTRIBUTES;
380 }
381
382 bool
383 Path::canWrite() const {
384   // FIXME: take security attributes into account.
385   DWORD attr = GetFileAttributes(path.c_str());
386   return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
387 }
388
389 bool
390 Path::canExecute() const {
391   // FIXME: take security attributes into account.
392   DWORD attr = GetFileAttributes(path.c_str());
393   return attr != INVALID_FILE_ATTRIBUTES;
394 }
395
396 bool
397 Path::isRegularFile() const {
398   bool res;
399   if (fs::is_regular_file(path, res))
400     return false;
401   return res;
402 }
403
404 StringRef
405 Path::getLast() const {
406   // Find the last slash
407   size_t pos = path.rfind('/');
408
409   // Handle the corner cases
410   if (pos == std::string::npos)
411     return path;
412
413   // If the last character is a slash, we have a root directory
414   if (pos == path.length()-1)
415     return path;
416
417   // Return everything after the last slash
418   return StringRef(path).substr(pos+1);
419 }
420
421 const FileStatus *
422 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
423   if (!fsIsValid || update) {
424     WIN32_FILE_ATTRIBUTE_DATA fi;
425     if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
426       MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
427                       ": Can't get status: ");
428       return 0;
429     }
430
431     status.fileSize = fi.nFileSizeHigh;
432     status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
433     status.fileSize += fi.nFileSizeLow;
434
435     status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
436     status.user = 9999;    // Not applicable to Windows, so...
437     status.group = 9999;   // Not applicable to Windows, so...
438
439     // FIXME: this is only unique if the file is accessed by the same file path.
440     // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
441     // numbers, but the concept doesn't exist in Windows.
442     status.uniqueID = 0;
443     for (unsigned i = 0; i < path.length(); ++i)
444       status.uniqueID += path[i];
445
446     ULARGE_INTEGER ui;
447     ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
448     ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
449     status.modTime.fromWin32Time(ui.QuadPart);
450
451     status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
452     fsIsValid = true;
453   }
454   return &status;
455 }
456
457 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
458   // All files are readable on Windows (ignoring security attributes).
459   return false;
460 }
461
462 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
463   DWORD attr = GetFileAttributes(path.c_str());
464
465   // If it doesn't exist, we're done.
466   if (attr == INVALID_FILE_ATTRIBUTES)
467     return false;
468
469   if (attr & FILE_ATTRIBUTE_READONLY) {
470     if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
471       MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
472       return true;
473     }
474   }
475   return false;
476 }
477
478 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
479   // All files are executable on Windows (ignoring security attributes).
480   return false;
481 }
482
483 bool
484 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
485   WIN32_FILE_ATTRIBUTE_DATA fi;
486   if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
487     MakeErrMsg(ErrMsg, path + ": can't get status of file");
488     return true;
489   }
490
491   if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
492     if (ErrMsg)
493       *ErrMsg = path + ": not a directory";
494     return true;
495   }
496
497   result.clear();
498   WIN32_FIND_DATA fd;
499   std::string searchpath = path;
500   if (path.size() == 0 || searchpath[path.size()-1] == '/')
501     searchpath += "*";
502   else
503     searchpath += "/*";
504
505   HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
506   if (h == INVALID_HANDLE_VALUE) {
507     if (GetLastError() == ERROR_FILE_NOT_FOUND)
508       return true; // not really an error, now is it?
509     MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
510     return true;
511   }
512
513   do {
514     if (fd.cFileName[0] == '.')
515       continue;
516     Path aPath(path);
517     aPath.appendComponent(&fd.cFileName[0]);
518     result.insert(aPath);
519   } while (FindNextFile(h, &fd));
520
521   DWORD err = GetLastError();
522   FindClose(h);
523   if (err != ERROR_NO_MORE_FILES) {
524     SetLastError(err);
525     MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
526     return true;
527   }
528   return false;
529 }
530
531 bool
532 Path::set(StringRef a_path) {
533   if (a_path.empty())
534     return false;
535   std::string save(path);
536   path = a_path;
537   FlipBackSlashes(path);
538   if (!isValid()) {
539     path = save;
540     return false;
541   }
542   return true;
543 }
544
545 bool
546 Path::appendComponent(StringRef name) {
547   if (name.empty())
548     return false;
549   std::string save(path);
550   if (!path.empty()) {
551     size_t last = path.size() - 1;
552     if (path[last] != '/')
553       path += '/';
554   }
555   path += name;
556   if (!isValid()) {
557     path = save;
558     return false;
559   }
560   return true;
561 }
562
563 bool
564 Path::eraseComponent() {
565   size_t slashpos = path.rfind('/',path.size());
566   if (slashpos == path.size() - 1 || slashpos == std::string::npos)
567     return false;
568   std::string save(path);
569   path.erase(slashpos);
570   if (!isValid()) {
571     path = save;
572     return false;
573   }
574   return true;
575 }
576
577 bool
578 Path::eraseSuffix() {
579   size_t dotpos = path.rfind('.',path.size());
580   size_t slashpos = path.rfind('/',path.size());
581   if (dotpos != std::string::npos) {
582     if (slashpos == std::string::npos || dotpos > slashpos+1) {
583       std::string save(path);
584       path.erase(dotpos, path.size()-dotpos);
585       if (!isValid()) {
586         path = save;
587         return false;
588       }
589       return true;
590     }
591   }
592   return false;
593 }
594
595 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
596   if (ErrMsg)
597     *ErrMsg = std::string(pathname) + ": " + std::string(msg);
598   return true;
599 }
600
601 bool
602 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
603   // Get a writeable copy of the path name
604   size_t len = path.length();
605   char *pathname = reinterpret_cast<char *>(_alloca(len+2));
606   path.copy(pathname, len);
607   pathname[len] = 0;
608
609   // Make sure it ends with a slash.
610   if (len == 0 || pathname[len - 1] != '/') {
611     pathname[len] = '/';
612     pathname[++len] = 0;
613   }
614
615   // Determine starting point for initial / search.
616   char *next = pathname;
617   if (pathname[0] == '/' && pathname[1] == '/') {
618     // Skip host name.
619     next = strchr(pathname+2, '/');
620     if (next == NULL)
621       return PathMsg(ErrMsg, pathname, "badly formed remote directory");
622
623     // Skip share name.
624     next = strchr(next+1, '/');
625     if (next == NULL)
626       return PathMsg(ErrMsg, pathname,"badly formed remote directory");
627
628     next++;
629     if (*next == 0)
630       return PathMsg(ErrMsg, pathname, "badly formed remote directory");
631
632   } else {
633     if (pathname[1] == ':')
634       next += 2;    // skip drive letter
635     if (*next == '/')
636       next++;       // skip root directory
637   }
638
639   // If we're supposed to create intermediate directories
640   if (create_parents) {
641     // Loop through the directory components until we're done
642     while (*next) {
643       next = strchr(next, '/');
644       *next = 0;
645       if (!CreateDirectory(pathname, NULL) &&
646           GetLastError() != ERROR_ALREADY_EXISTS)
647           return MakeErrMsg(ErrMsg,
648             std::string(pathname) + ": Can't create directory: ");
649       *next++ = '/';
650     }
651   } else {
652     // Drop trailing slash.
653     pathname[len-1] = 0;
654     if (!CreateDirectory(pathname, NULL) &&
655         GetLastError() != ERROR_ALREADY_EXISTS) {
656       return MakeErrMsg(ErrMsg, std::string(pathname) +
657                         ": Can't create directory: ");
658     }
659   }
660   return false;
661 }
662
663 bool
664 Path::createFileOnDisk(std::string* ErrMsg) {
665   // Create the file
666   HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
667                         FILE_ATTRIBUTE_NORMAL, NULL);
668   if (h == INVALID_HANDLE_VALUE)
669     return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
670
671   CloseHandle(h);
672   return false;
673 }
674
675 bool
676 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
677   WIN32_FILE_ATTRIBUTE_DATA fi;
678   if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
679     return true;
680
681   if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
682     // If it doesn't exist, we're done.
683     bool Exists;
684     if (fs::exists(path, Exists) || !Exists)
685       return false;
686
687     char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
688     int lastchar = path.length() - 1 ;
689     path.copy(pathname, lastchar+1);
690
691     // Make path end with '/*'.
692     if (pathname[lastchar] != '/')
693       pathname[++lastchar] = '/';
694     pathname[lastchar+1] = '*';
695     pathname[lastchar+2] = 0;
696
697     if (remove_contents) {
698       WIN32_FIND_DATA fd;
699       HANDLE h = FindFirstFile(pathname, &fd);
700
701       // It's a bad idea to alter the contents of a directory while enumerating
702       // its contents. So build a list of its contents first, then destroy them.
703
704       if (h != INVALID_HANDLE_VALUE) {
705         std::vector<Path> list;
706
707         do {
708           if (strcmp(fd.cFileName, ".") == 0)
709             continue;
710           if (strcmp(fd.cFileName, "..") == 0)
711             continue;
712
713           Path aPath(path);
714           aPath.appendComponent(&fd.cFileName[0]);
715           list.push_back(aPath);
716         } while (FindNextFile(h, &fd));
717
718         DWORD err = GetLastError();
719         FindClose(h);
720         if (err != ERROR_NO_MORE_FILES) {
721           SetLastError(err);
722           return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
723         }
724
725         for (std::vector<Path>::iterator I = list.begin(); I != list.end();
726              ++I) {
727           Path &aPath = *I;
728           aPath.eraseFromDisk(true);
729         }
730       } else {
731         if (GetLastError() != ERROR_FILE_NOT_FOUND)
732           return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
733       }
734     }
735
736     pathname[lastchar] = 0;
737     if (!RemoveDirectory(pathname))
738       return MakeErrMsg(ErrStr,
739         std::string(pathname) + ": Can't destroy directory: ");
740     return false;
741   } else {
742     // Read-only files cannot be deleted on Windows.  Must remove the read-only
743     // attribute first.
744     if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
745       if (!SetFileAttributes(path.c_str(),
746                              fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
747         return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
748     }
749
750     if (!DeleteFile(path.c_str()))
751       return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
752     return false;
753   }
754 }
755
756 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
757   assert(len < 1024 && "Request for magic string too long");
758   char* buf = reinterpret_cast<char*>(alloca(len));
759
760   HANDLE h = CreateFile(path.c_str(),
761                         GENERIC_READ,
762                         FILE_SHARE_READ,
763                         NULL,
764                         OPEN_EXISTING,
765                         FILE_ATTRIBUTE_NORMAL,
766                         NULL);
767   if (h == INVALID_HANDLE_VALUE)
768     return false;
769
770   DWORD nRead = 0;
771   BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
772   CloseHandle(h);
773
774   if (!ret || nRead != len)
775     return false;
776
777   Magic = std::string(buf, len);
778   return true;
779 }
780
781 bool
782 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
783   if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
784     return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
785         + "': ");
786   return false;
787 }
788
789 bool
790 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
791   // FIXME: should work on directories also.
792   if (!si.isFile) {
793     return true;
794   }
795
796   HANDLE h = CreateFile(path.c_str(),
797                         FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
798                         FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
799                         NULL,
800                         OPEN_EXISTING,
801                         FILE_ATTRIBUTE_NORMAL,
802                         NULL);
803   if (h == INVALID_HANDLE_VALUE)
804     return true;
805
806   BY_HANDLE_FILE_INFORMATION bhfi;
807   if (!GetFileInformationByHandle(h, &bhfi)) {
808     DWORD err = GetLastError();
809     CloseHandle(h);
810     SetLastError(err);
811     return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
812   }
813
814   ULARGE_INTEGER ui;
815   ui.QuadPart = si.modTime.toWin32Time();
816   FILETIME ft;
817   ft.dwLowDateTime = ui.LowPart;
818   ft.dwHighDateTime = ui.HighPart;
819   BOOL ret = SetFileTime(h, NULL, &ft, &ft);
820   DWORD err = GetLastError();
821   CloseHandle(h);
822   if (!ret) {
823     SetLastError(err);
824     return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
825   }
826
827   // Best we can do with Unix permission bits is to interpret the owner
828   // writable bit.
829   if (si.mode & 0200) {
830     if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
831       if (!SetFileAttributes(path.c_str(),
832               bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
833         return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
834     }
835   } else {
836     if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
837       if (!SetFileAttributes(path.c_str(),
838               bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
839         return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
840     }
841   }
842
843   return false;
844 }
845
846 bool
847 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
848   // Can't use CopyFile macro defined in Windows.h because it would mess up the
849   // above line.  We use the expansion it would have in a non-UNICODE build.
850   if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
851     return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
852                "' to '" + Dest.str() + "': ");
853   return false;
854 }
855
856 bool
857 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
858   bool Exists;
859   if (reuse_current && (fs::exists(path, Exists) || !Exists))
860     return false; // File doesn't exist already, just use it!
861
862   // Reserve space for -XXXXXX at the end.
863   char *FNBuffer = (char*) alloca(path.size()+8);
864   unsigned offset = path.size();
865   path.copy(FNBuffer, offset);
866
867   // Find a numeric suffix that isn't used by an existing file.  Assume there
868   // won't be more than 1 million files with the same prefix.  Probably a safe
869   // bet.
870   static int FCounter = -1;
871   if (FCounter < 0) {
872     // Give arbitrary initial seed.
873     // FIXME: We should use sys::fs::unique_file() in future.
874     LARGE_INTEGER cnt64;
875     DWORD x = GetCurrentProcessId();
876     x = (x << 16) | (x >> 16);
877     if (QueryPerformanceCounter(&cnt64))    // RDTSC
878       x ^= cnt64.HighPart ^ cnt64.LowPart;
879     FCounter = x % 1000000;
880   }
881   do {
882     sprintf(FNBuffer+offset, "-%06u", FCounter);
883     if (++FCounter > 999999)
884       FCounter = 0;
885     path = FNBuffer;
886   } while (!fs::exists(path, Exists) && Exists);
887   return false;
888 }
889
890 bool
891 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
892   // Make this into a unique file name
893   makeUnique(reuse_current, ErrMsg);
894
895   // Now go and create it
896   HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
897                         FILE_ATTRIBUTE_NORMAL, NULL);
898   if (h == INVALID_HANDLE_VALUE)
899     return MakeErrMsg(ErrMsg, path + ": can't create file");
900
901   CloseHandle(h);
902   return false;
903 }
904
905 /// MapInFilePages - Not yet implemented on win32.
906 const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
907   return 0;
908 }
909
910 /// MapInFilePages - Not yet implemented on win32.
911 void Path::UnMapFilePages(const char *Base, size_t FileSize) {
912   assert(0 && "NOT IMPLEMENTED");
913 }
914
915 }
916 }