Path.inc revision 6cbae0160600086e271904d7339c46f34ff57e73
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
37static void FlipBackSlashes(std::string& s) {
38  for (size_t i = 0; i < s.size(); i++)
39    if (s[i] == '\\')
40      s[i] = '/';
41}
42
43namespace llvm {
44namespace sys {
45
46const char PathSeparator = ';';
47
48StringRef Path::GetEXESuffix() {
49  return "exe";
50}
51
52Path::Path(llvm::StringRef p)
53  : path(p) {
54  FlipBackSlashes(path);
55}
56
57Path::Path(const char *StrStart, unsigned StrLen)
58  : path(StrStart, StrLen) {
59  FlipBackSlashes(path);
60}
61
62Path&
63Path::operator=(StringRef that) {
64  path.assign(that.data(), that.size());
65  FlipBackSlashes(path);
66  return *this;
67}
68
69bool
70Path::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
135void 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
154bool
155Path::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
172bool
173Path::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
187static Path *TempDirectory;
188
189Path
190Path::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
236Path
237Path::GetCurrentDirectory() {
238  char pathname[MAX_PATH];
239  ::GetCurrentDirectoryA(MAX_PATH,pathname);
240  return Path(pathname);
241}
242
243/// GetMainExecutable - Return the path to the main executable, given the
244/// value of argv[0] from program startup.
245Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
246  char pathname[MAX_PATH];
247  DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
248  return ret != MAX_PATH ? Path(pathname) : Path();
249}
250
251
252// FIXME: the above set of functions don't map to Windows very well.
253
254
255StringRef Path::getDirname() const {
256  return getDirnameCharSep(path, "/");
257}
258
259StringRef
260Path::getBasename() const {
261  // Find the last slash
262  size_t slash = path.rfind('/');
263  if (slash == std::string::npos)
264    slash = 0;
265  else
266    slash++;
267
268  size_t dot = path.rfind('.');
269  if (dot == std::string::npos || dot < slash)
270    return StringRef(path).substr(slash);
271  else
272    return StringRef(path).substr(slash, dot - slash);
273}
274
275StringRef
276Path::getSuffix() const {
277  // Find the last slash
278  size_t slash = path.rfind('/');
279  if (slash == std::string::npos)
280    slash = 0;
281  else
282    slash++;
283
284  size_t dot = path.rfind('.');
285  if (dot == std::string::npos || dot < slash)
286    return StringRef("");
287  else
288    return StringRef(path).substr(dot + 1);
289}
290
291bool
292Path::exists() const {
293  DWORD attr = GetFileAttributes(path.c_str());
294  return attr != INVALID_FILE_ATTRIBUTES;
295}
296
297bool
298Path::isDirectory() const {
299  DWORD attr = GetFileAttributes(path.c_str());
300  return (attr != INVALID_FILE_ATTRIBUTES) &&
301         (attr & FILE_ATTRIBUTE_DIRECTORY);
302}
303
304bool
305Path::isSymLink() const {
306  DWORD attributes = GetFileAttributes(path.c_str());
307
308  if (attributes == INVALID_FILE_ATTRIBUTES)
309    // There's no sane way to report this :(.
310    assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
311
312  // This isn't exactly what defines a NTFS symlink, but it is only true for
313  // paths that act like a symlink.
314  return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
315}
316
317bool
318Path::canRead() const {
319  // FIXME: take security attributes into account.
320  DWORD attr = GetFileAttributes(path.c_str());
321  return attr != INVALID_FILE_ATTRIBUTES;
322}
323
324bool
325Path::canWrite() const {
326  // FIXME: take security attributes into account.
327  DWORD attr = GetFileAttributes(path.c_str());
328  return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
329}
330
331bool
332Path::canExecute() const {
333  // FIXME: take security attributes into account.
334  DWORD attr = GetFileAttributes(path.c_str());
335  return attr != INVALID_FILE_ATTRIBUTES;
336}
337
338bool
339Path::isRegularFile() const {
340  bool res;
341  if (fs::is_regular_file(path, res))
342    return false;
343  return res;
344}
345
346StringRef
347Path::getLast() const {
348  // Find the last slash
349  size_t pos = path.rfind('/');
350
351  // Handle the corner cases
352  if (pos == std::string::npos)
353    return path;
354
355  // If the last character is a slash, we have a root directory
356  if (pos == path.length()-1)
357    return path;
358
359  // Return everything after the last slash
360  return StringRef(path).substr(pos+1);
361}
362
363const FileStatus *
364PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
365  if (!fsIsValid || update) {
366    WIN32_FILE_ATTRIBUTE_DATA fi;
367    if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
368      MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
369                      ": Can't get status: ");
370      return 0;
371    }
372
373    status.fileSize = fi.nFileSizeHigh;
374    status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
375    status.fileSize += fi.nFileSizeLow;
376
377    status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
378    status.user = 9999;    // Not applicable to Windows, so...
379    status.group = 9999;   // Not applicable to Windows, so...
380
381    // FIXME: this is only unique if the file is accessed by the same file path.
382    // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
383    // numbers, but the concept doesn't exist in Windows.
384    status.uniqueID = 0;
385    for (unsigned i = 0; i < path.length(); ++i)
386      status.uniqueID += path[i];
387
388    ULARGE_INTEGER ui;
389    ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
390    ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
391    status.modTime.fromWin32Time(ui.QuadPart);
392
393    status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
394    fsIsValid = true;
395  }
396  return &status;
397}
398
399bool Path::makeReadableOnDisk(std::string* ErrMsg) {
400  // All files are readable on Windows (ignoring security attributes).
401  return false;
402}
403
404bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
405  DWORD attr = GetFileAttributes(path.c_str());
406
407  // If it doesn't exist, we're done.
408  if (attr == INVALID_FILE_ATTRIBUTES)
409    return false;
410
411  if (attr & FILE_ATTRIBUTE_READONLY) {
412    if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
413      MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
414      return true;
415    }
416  }
417  return false;
418}
419
420bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
421  // All files are executable on Windows (ignoring security attributes).
422  return false;
423}
424
425bool
426Path::getDirectoryContents(std::set& result, std::string* ErrMsg) const {
427  WIN32_FILE_ATTRIBUTE_DATA fi;
428  if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
429    MakeErrMsg(ErrMsg, path + ": can't get status of file");
430    return true;
431  }
432
433  if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
434    if (ErrMsg)
435      *ErrMsg = path + ": not a directory";
436    return true;
437  }
438
439  result.clear();
440  WIN32_FIND_DATA fd;
441  std::string searchpath = path;
442  if (path.size() == 0 || searchpath[path.size()-1] == '/')
443    searchpath += "*";
444  else
445    searchpath += "/*";
446
447  HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
448  if (h == INVALID_HANDLE_VALUE) {
449    if (GetLastError() == ERROR_FILE_NOT_FOUND)
450      return true; // not really an error, now is it?
451    MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
452    return true;
453  }
454
455  do {
456    if (fd.cFileName[0] == '.')
457      continue;
458    Path aPath(path);
459    aPath.appendComponent(&fd.cFileName[0]);
460    result.insert(aPath);
461  } while (FindNextFile(h, &fd));
462
463  DWORD err = GetLastError();
464  FindClose(h);
465  if (err != ERROR_NO_MORE_FILES) {
466    SetLastError(err);
467    MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
468    return true;
469  }
470  return false;
471}
472
473bool
474Path::set(StringRef a_path) {
475  if (a_path.empty())
476    return false;
477  std::string save(path);
478  path = a_path;
479  FlipBackSlashes(path);
480  if (!isValid()) {
481    path = save;
482    return false;
483  }
484  return true;
485}
486
487bool
488Path::appendComponent(StringRef name) {
489  if (name.empty())
490    return false;
491  std::string save(path);
492  if (!path.empty()) {
493    size_t last = path.size() - 1;
494    if (path[last] != '/')
495      path += '/';
496  }
497  path += name;
498  if (!isValid()) {
499    path = save;
500    return false;
501  }
502  return true;
503}
504
505bool
506Path::eraseComponent() {
507  size_t slashpos = path.rfind('/',path.size());
508  if (slashpos == path.size() - 1 || slashpos == std::string::npos)
509    return false;
510  std::string save(path);
511  path.erase(slashpos);
512  if (!isValid()) {
513    path = save;
514    return false;
515  }
516  return true;
517}
518
519bool
520Path::eraseSuffix() {
521  size_t dotpos = path.rfind('.',path.size());
522  size_t slashpos = path.rfind('/',path.size());
523  if (dotpos != std::string::npos) {
524    if (slashpos == std::string::npos || dotpos > slashpos+1) {
525      std::string save(path);
526      path.erase(dotpos, path.size()-dotpos);
527      if (!isValid()) {
528        path = save;
529        return false;
530      }
531      return true;
532    }
533  }
534  return false;
535}
536
537inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
538  if (ErrMsg)
539    *ErrMsg = std::string(pathname) + ": " + std::string(msg);
540  return true;
541}
542
543bool
544Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
545  // Get a writeable copy of the path name
546  size_t len = path.length();
547  char *pathname = reinterpret_cast<char *>(_alloca(len+2));
548  path.copy(pathname, len);
549  pathname[len] = 0;
550
551  // Make sure it ends with a slash.
552  if (len == 0 || pathname[len - 1] != '/') {
553    pathname[len] = '/';
554    pathname[++len] = 0;
555  }
556
557  // Determine starting point for initial / search.
558  char *next = pathname;
559  if (pathname[0] == '/' && pathname[1] == '/') {
560    // Skip host name.
561    next = strchr(pathname+2, '/');
562    if (next == NULL)
563      return PathMsg(ErrMsg, pathname, "badly formed remote directory");
564
565    // Skip share name.
566    next = strchr(next+1, '/');
567    if (next == NULL)
568      return PathMsg(ErrMsg, pathname,"badly formed remote directory");
569
570    next++;
571    if (*next == 0)
572      return PathMsg(ErrMsg, pathname, "badly formed remote directory");
573
574  } else {
575    if (pathname[1] == ':')
576      next += 2;    // skip drive letter
577    if (*next == '/')
578      next++;       // skip root directory
579  }
580
581  // If we're supposed to create intermediate directories
582  if (create_parents) {
583    // Loop through the directory components until we're done
584    while (*next) {
585      next = strchr(next, '/');
586      *next = 0;
587      if (!CreateDirectory(pathname, NULL) &&
588          GetLastError() != ERROR_ALREADY_EXISTS)
589          return MakeErrMsg(ErrMsg,
590            std::string(pathname) + ": Can't create directory: ");
591      *next++ = '/';
592    }
593  } else {
594    // Drop trailing slash.
595    pathname[len-1] = 0;
596    if (!CreateDirectory(pathname, NULL) &&
597        GetLastError() != ERROR_ALREADY_EXISTS) {
598      return MakeErrMsg(ErrMsg, std::string(pathname) +
599                        ": Can't create directory: ");
600    }
601  }
602  return false;
603}
604
605bool
606Path::createFileOnDisk(std::string* ErrMsg) {
607  // Create the file
608  HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
609                        FILE_ATTRIBUTE_NORMAL, NULL);
610  if (h == INVALID_HANDLE_VALUE)
611    return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
612
613  CloseHandle(h);
614  return false;
615}
616
617bool
618Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
619  WIN32_FILE_ATTRIBUTE_DATA fi;
620  if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
621    return true;
622
623  if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
624    // If it doesn't exist, we're done.
625    bool Exists;
626    if (fs::exists(path, Exists) || !Exists)
627      return false;
628
629    char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
630    int lastchar = path.length() - 1 ;
631    path.copy(pathname, lastchar+1);
632
633    // Make path end with '/*'.
634    if (pathname[lastchar] != '/')
635      pathname[++lastchar] = '/';
636    pathname[lastchar+1] = '*';
637    pathname[lastchar+2] = 0;
638
639    if (remove_contents) {
640      WIN32_FIND_DATA fd;
641      HANDLE h = FindFirstFile(pathname, &fd);
642
643      // It's a bad idea to alter the contents of a directory while enumerating
644      // its contents. So build a list of its contents first, then destroy them.
645
646      if (h != INVALID_HANDLE_VALUE) {
647        std::vector<Path> list;
648
649        do {
650          if (strcmp(fd.cFileName, ".") == 0)
651            continue;
652          if (strcmp(fd.cFileName, "..") == 0)
653            continue;
654
655          Path aPath(path);
656          aPath.appendComponent(&fd.cFileName[0]);
657          list.push_back(aPath);
658        } while (FindNextFile(h, &fd));
659
660        DWORD err = GetLastError();
661        FindClose(h);
662        if (err != ERROR_NO_MORE_FILES) {
663          SetLastError(err);
664          return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
665        }
666
667        for (std::vector<Path>::iterator I = list.begin(); I != list.end();
668             ++I) {
669          Path &aPath = *I;
670          aPath.eraseFromDisk(true);
671        }
672      } else {
673        if (GetLastError() != ERROR_FILE_NOT_FOUND)
674          return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
675      }
676    }
677
678    pathname[lastchar] = 0;
679    if (!RemoveDirectory(pathname))
680      return MakeErrMsg(ErrStr,
681        std::string(pathname) + ": Can't destroy directory: ");
682    return false;
683  } else {
684    // Read-only files cannot be deleted on Windows.  Must remove the read-only
685    // attribute first.
686    if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
687      if (!SetFileAttributes(path.c_str(),
688                             fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
689        return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
690    }
691
692    if (!DeleteFile(path.c_str()))
693      return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
694    return false;
695  }
696}
697
698bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
699  assert(len < 1024 && "Request for magic string too long");
700  char* buf = reinterpret_cast<char*>(alloca(len));
701
702  HANDLE h = CreateFile(path.c_str(),
703                        GENERIC_READ,
704                        FILE_SHARE_READ,
705                        NULL,
706                        OPEN_EXISTING,
707                        FILE_ATTRIBUTE_NORMAL,
708                        NULL);
709  if (h == INVALID_HANDLE_VALUE)
710    return false;
711
712  DWORD nRead = 0;
713  BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
714  CloseHandle(h);
715
716  if (!ret || nRead != len)
717    return false;
718
719  Magic = std::string(buf, len);
720  return true;
721}
722
723bool
724Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
725  if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
726    return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
727        + "': ");
728  return false;
729}
730
731bool
732Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
733  // FIXME: should work on directories also.
734  if (!si.isFile) {
735    return true;
736  }
737
738  HANDLE h = CreateFile(path.c_str(),
739                        FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
740                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
741                        NULL,
742                        OPEN_EXISTING,
743                        FILE_ATTRIBUTE_NORMAL,
744                        NULL);
745  if (h == INVALID_HANDLE_VALUE)
746    return true;
747
748  BY_HANDLE_FILE_INFORMATION bhfi;
749  if (!GetFileInformationByHandle(h, &bhfi)) {
750    DWORD err = GetLastError();
751    CloseHandle(h);
752    SetLastError(err);
753    return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
754  }
755
756  ULARGE_INTEGER ui;
757  ui.QuadPart = si.modTime.toWin32Time();
758  FILETIME ft;
759  ft.dwLowDateTime = ui.LowPart;
760  ft.dwHighDateTime = ui.HighPart;
761  BOOL ret = SetFileTime(h, NULL, &ft, &ft);
762  DWORD err = GetLastError();
763  CloseHandle(h);
764  if (!ret) {
765    SetLastError(err);
766    return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
767  }
768
769  // Best we can do with Unix permission bits is to interpret the owner
770  // writable bit.
771  if (si.mode & 0200) {
772    if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
773      if (!SetFileAttributes(path.c_str(),
774              bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
775        return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
776    }
777  } else {
778    if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
779      if (!SetFileAttributes(path.c_str(),
780              bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
781        return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
782    }
783  }
784
785  return false;
786}
787
788bool
789CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
790  // Can't use CopyFile macro defined in Windows.h because it would mess up the
791  // above line.  We use the expansion it would have in a non-UNICODE build.
792  if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
793    return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
794               "' to '" + Dest.str() + "': ");
795  return false;
796}
797
798bool
799Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
800  bool Exists;
801  if (reuse_current && (fs::exists(path, Exists) || !Exists))
802    return false; // File doesn't exist already, just use it!
803
804  // Reserve space for -XXXXXX at the end.
805  char *FNBuffer = (char*) alloca(path.size()+8);
806  unsigned offset = path.size();
807  path.copy(FNBuffer, offset);
808
809  // Find a numeric suffix that isn't used by an existing file.  Assume there
810  // won't be more than 1 million files with the same prefix.  Probably a safe
811  // bet.
812  static int FCounter = -1;
813  if (FCounter < 0) {
814    // Give arbitrary initial seed.
815    // FIXME: We should use sys::fs::unique_file() in future.
816    LARGE_INTEGER cnt64;
817    DWORD x = GetCurrentProcessId();
818    x = (x << 16) | (x >> 16);
819    if (QueryPerformanceCounter(&cnt64))    // RDTSC
820      x ^= cnt64.HighPart ^ cnt64.LowPart;
821    FCounter = x % 1000000;
822  }
823  do {
824    sprintf(FNBuffer+offset, "-%06u", FCounter);
825    if (++FCounter > 999999)
826      FCounter = 0;
827    path = FNBuffer;
828  } while (!fs::exists(path, Exists) && Exists);
829  return false;
830}
831
832bool
833Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
834  // Make this into a unique file name
835  makeUnique(reuse_current, ErrMsg);
836
837  // Now go and create it
838  HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
839                        FILE_ATTRIBUTE_NORMAL, NULL);
840  if (h == INVALID_HANDLE_VALUE)
841    return MakeErrMsg(ErrMsg, path + ": can't create file");
842
843  CloseHandle(h);
844  return false;
845}
846
847/// MapInFilePages - Not yet implemented on win32.
848const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
849  return 0;
850}
851
852/// MapInFilePages - Not yet implemented on win32.
853void Path::UnMapFilePages(const char *Base, size_t FileSize) {
854  assert(0 && "NOT IMPLEMENTED");
855}
856
857}
858}
859