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