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