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