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