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