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