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