Path.inc revision 2e0f70bdd8814eefb752f1d0221800cbdbd8d1f5
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
36static void FlipBackSlashes(std::string& s) {
37  for (size_t i = 0; i < s.size(); i++)
38    if (s[i] == '\\')
39      s[i] = '/';
40}
41
42namespace llvm {
43namespace sys {
44
45const char PathSeparator = ';';
46
47StringRef Path::GetEXESuffix() {
48  return "exe";
49}
50
51Path::Path(llvm::StringRef p)
52  : path(p) {
53  FlipBackSlashes(path);
54}
55
56Path::Path(const char *StrStart, unsigned StrLen)
57  : path(StrStart, StrLen) {
58  FlipBackSlashes(path);
59}
60
61Path&
62Path::operator=(StringRef that) {
63  path.assign(that.data(), that.size());
64  FlipBackSlashes(path);
65  return *this;
66}
67
68bool
69Path::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
134void 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
153static Path *TempDirectory;
154
155Path
156Path::GetTemporaryDirectory(std::string* ErrMsg) {
157  if (TempDirectory) {
158#if defined(_MSC_VER)
159    // Visual Studio gets confused and emits a diagnostic about calling exists,
160    // even though this is the implementation for PathV1.  Temporarily
161    // disable the deprecated warning message
162    #pragma warning(push)
163    #pragma warning(disable:4996)
164#endif
165    assert(TempDirectory->exists() && "Who has removed TempDirectory?");
166#if defined(_MSC_VER)
167    #pragma warning(pop)
168#endif
169    return *TempDirectory;
170  }
171
172  char pathname[MAX_PATH];
173  if (!GetTempPath(MAX_PATH, pathname)) {
174    if (ErrMsg)
175      *ErrMsg = "Can't determine temporary directory";
176    return Path();
177  }
178
179  Path result;
180  result.set(pathname);
181
182  // Append a subdirectory based on our process id so multiple LLVMs don't
183  // step on each other's toes.
184#ifdef __MINGW32__
185  // Mingw's Win32 header files are broken.
186  sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
187#else
188  sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
189#endif
190  result.appendComponent(pathname);
191
192  // If there's a directory left over from a previous LLVM execution that
193  // happened to have the same process id, get rid of it.
194  result.eraseFromDisk(true);
195
196  // And finally (re-)create the empty directory.
197  result.createDirectoryOnDisk(false);
198  TempDirectory = new Path(result);
199  return *TempDirectory;
200}
201
202Path
203Path::GetCurrentDirectory() {
204  char pathname[MAX_PATH];
205  ::GetCurrentDirectoryA(MAX_PATH,pathname);
206  return Path(pathname);
207}
208
209/// GetMainExecutable - Return the path to the main executable, given the
210/// value of argv[0] from program startup.
211Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
212  char pathname[MAX_PATH];
213  DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
214  return ret != MAX_PATH ? Path(pathname) : Path();
215}
216
217
218// FIXME: the above set of functions don't map to Windows very well.
219
220bool
221Path::exists() const {
222  DWORD attr = GetFileAttributes(path.c_str());
223  return attr != INVALID_FILE_ATTRIBUTES;
224}
225
226bool
227Path::isDirectory() const {
228  DWORD attr = GetFileAttributes(path.c_str());
229  return (attr != INVALID_FILE_ATTRIBUTES) &&
230         (attr & FILE_ATTRIBUTE_DIRECTORY);
231}
232
233bool
234Path::isSymLink() const {
235  DWORD attributes = GetFileAttributes(path.c_str());
236
237  if (attributes == INVALID_FILE_ATTRIBUTES)
238    // There's no sane way to report this :(.
239    assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
240
241  // This isn't exactly what defines a NTFS symlink, but it is only true for
242  // paths that act like a symlink.
243  return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
244}
245
246bool
247Path::canRead() const {
248  // FIXME: take security attributes into account.
249  DWORD attr = GetFileAttributes(path.c_str());
250  return attr != INVALID_FILE_ATTRIBUTES;
251}
252
253bool
254Path::canWrite() const {
255  // FIXME: take security attributes into account.
256  DWORD attr = GetFileAttributes(path.c_str());
257  return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
258}
259
260bool
261Path::canExecute() const {
262  // FIXME: take security attributes into account.
263  DWORD attr = GetFileAttributes(path.c_str());
264  return attr != INVALID_FILE_ATTRIBUTES;
265}
266
267bool
268Path::isRegularFile() const {
269  bool res;
270  if (fs::is_regular_file(path, res))
271    return false;
272  return res;
273}
274
275const FileStatus *
276PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
277  if (!fsIsValid || update) {
278    WIN32_FILE_ATTRIBUTE_DATA fi;
279    if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
280      MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
281                      ": Can't get status: ");
282      return 0;
283    }
284
285    status.fileSize = fi.nFileSizeHigh;
286    status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
287    status.fileSize += fi.nFileSizeLow;
288
289    status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
290    status.user = 9999;    // Not applicable to Windows, so...
291    status.group = 9999;   // Not applicable to Windows, so...
292
293    ULARGE_INTEGER ui;
294    ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
295    ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
296    status.modTime.fromWin32Time(ui.QuadPart);
297
298    status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
299    fsIsValid = true;
300  }
301  return &status;
302}
303
304bool Path::makeReadableOnDisk(std::string* ErrMsg) {
305  // All files are readable on Windows (ignoring security attributes).
306  return false;
307}
308
309bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
310  DWORD attr = GetFileAttributes(path.c_str());
311
312  // If it doesn't exist, we're done.
313  if (attr == INVALID_FILE_ATTRIBUTES)
314    return false;
315
316  if (attr & FILE_ATTRIBUTE_READONLY) {
317    if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
318      MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
319      return true;
320    }
321  }
322  return false;
323}
324
325bool
326Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
327  WIN32_FILE_ATTRIBUTE_DATA fi;
328  if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
329    MakeErrMsg(ErrMsg, path + ": can't get status of file");
330    return true;
331  }
332
333  if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
334    if (ErrMsg)
335      *ErrMsg = path + ": not a directory";
336    return true;
337  }
338
339  result.clear();
340  WIN32_FIND_DATA fd;
341  std::string searchpath = path;
342  if (path.size() == 0 || searchpath[path.size()-1] == '/')
343    searchpath += "*";
344  else
345    searchpath += "/*";
346
347  HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
348  if (h == INVALID_HANDLE_VALUE) {
349    if (GetLastError() == ERROR_FILE_NOT_FOUND)
350      return true; // not really an error, now is it?
351    MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
352    return true;
353  }
354
355  do {
356    if (fd.cFileName[0] == '.')
357      continue;
358    Path aPath(path);
359    aPath.appendComponent(&fd.cFileName[0]);
360    result.insert(aPath);
361  } while (FindNextFile(h, &fd));
362
363  DWORD err = GetLastError();
364  FindClose(h);
365  if (err != ERROR_NO_MORE_FILES) {
366    SetLastError(err);
367    MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
368    return true;
369  }
370  return false;
371}
372
373bool
374Path::set(StringRef a_path) {
375  if (a_path.empty())
376    return false;
377  std::string save(path);
378  path = a_path;
379  FlipBackSlashes(path);
380  if (!isValid()) {
381    path = save;
382    return false;
383  }
384  return true;
385}
386
387bool
388Path::appendComponent(StringRef name) {
389  if (name.empty())
390    return false;
391  std::string save(path);
392  if (!path.empty()) {
393    size_t last = path.size() - 1;
394    if (path[last] != '/')
395      path += '/';
396  }
397  path += name;
398  if (!isValid()) {
399    path = save;
400    return false;
401  }
402  return true;
403}
404
405bool
406Path::eraseComponent() {
407  size_t slashpos = path.rfind('/',path.size());
408  if (slashpos == path.size() - 1 || slashpos == std::string::npos)
409    return false;
410  std::string save(path);
411  path.erase(slashpos);
412  if (!isValid()) {
413    path = save;
414    return false;
415  }
416  return true;
417}
418
419bool
420Path::eraseSuffix() {
421  size_t dotpos = path.rfind('.',path.size());
422  size_t slashpos = path.rfind('/',path.size());
423  if (dotpos != std::string::npos) {
424    if (slashpos == std::string::npos || dotpos > slashpos+1) {
425      std::string save(path);
426      path.erase(dotpos, path.size()-dotpos);
427      if (!isValid()) {
428        path = save;
429        return false;
430      }
431      return true;
432    }
433  }
434  return false;
435}
436
437inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
438  if (ErrMsg)
439    *ErrMsg = std::string(pathname) + ": " + std::string(msg);
440  return true;
441}
442
443bool
444Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
445  // Get a writeable copy of the path name
446  size_t len = path.length();
447  char *pathname = reinterpret_cast<char *>(_alloca(len+2));
448  path.copy(pathname, len);
449  pathname[len] = 0;
450
451  // Make sure it ends with a slash.
452  if (len == 0 || pathname[len - 1] != '/') {
453    pathname[len] = '/';
454    pathname[++len] = 0;
455  }
456
457  // Determine starting point for initial / search.
458  char *next = pathname;
459  if (pathname[0] == '/' && pathname[1] == '/') {
460    // Skip host name.
461    next = strchr(pathname+2, '/');
462    if (next == NULL)
463      return PathMsg(ErrMsg, pathname, "badly formed remote directory");
464
465    // Skip share name.
466    next = strchr(next+1, '/');
467    if (next == NULL)
468      return PathMsg(ErrMsg, pathname,"badly formed remote directory");
469
470    next++;
471    if (*next == 0)
472      return PathMsg(ErrMsg, pathname, "badly formed remote directory");
473
474  } else {
475    if (pathname[1] == ':')
476      next += 2;    // skip drive letter
477    if (*next == '/')
478      next++;       // skip root directory
479  }
480
481  // If we're supposed to create intermediate directories
482  if (create_parents) {
483    // Loop through the directory components until we're done
484    while (*next) {
485      next = strchr(next, '/');
486      *next = 0;
487      if (!CreateDirectory(pathname, NULL) &&
488          GetLastError() != ERROR_ALREADY_EXISTS)
489          return MakeErrMsg(ErrMsg,
490            std::string(pathname) + ": Can't create directory: ");
491      *next++ = '/';
492    }
493  } else {
494    // Drop trailing slash.
495    pathname[len-1] = 0;
496    if (!CreateDirectory(pathname, NULL) &&
497        GetLastError() != ERROR_ALREADY_EXISTS) {
498      return MakeErrMsg(ErrMsg, std::string(pathname) +
499                        ": Can't create directory: ");
500    }
501  }
502  return false;
503}
504
505bool
506Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
507  WIN32_FILE_ATTRIBUTE_DATA fi;
508  if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
509    return true;
510
511  if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
512    // If it doesn't exist, we're done.
513    bool Exists;
514    if (fs::exists(path, Exists) || !Exists)
515      return false;
516
517    char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
518    int lastchar = path.length() - 1 ;
519    path.copy(pathname, lastchar+1);
520
521    // Make path end with '/*'.
522    if (pathname[lastchar] != '/')
523      pathname[++lastchar] = '/';
524    pathname[lastchar+1] = '*';
525    pathname[lastchar+2] = 0;
526
527    if (remove_contents) {
528      WIN32_FIND_DATA fd;
529      HANDLE h = FindFirstFile(pathname, &fd);
530
531      // It's a bad idea to alter the contents of a directory while enumerating
532      // its contents. So build a list of its contents first, then destroy them.
533
534      if (h != INVALID_HANDLE_VALUE) {
535        std::vector<Path> list;
536
537        do {
538          if (strcmp(fd.cFileName, ".") == 0)
539            continue;
540          if (strcmp(fd.cFileName, "..") == 0)
541            continue;
542
543          Path aPath(path);
544          aPath.appendComponent(&fd.cFileName[0]);
545          list.push_back(aPath);
546        } while (FindNextFile(h, &fd));
547
548        DWORD err = GetLastError();
549        FindClose(h);
550        if (err != ERROR_NO_MORE_FILES) {
551          SetLastError(err);
552          return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
553        }
554
555        for (std::vector<Path>::iterator I = list.begin(); I != list.end();
556             ++I) {
557          Path &aPath = *I;
558          aPath.eraseFromDisk(true);
559        }
560      } else {
561        if (GetLastError() != ERROR_FILE_NOT_FOUND)
562          return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
563      }
564    }
565
566    pathname[lastchar] = 0;
567    if (!RemoveDirectory(pathname))
568      return MakeErrMsg(ErrStr,
569        std::string(pathname) + ": Can't destroy directory: ");
570    return false;
571  } else {
572    // Read-only files cannot be deleted on Windows.  Must remove the read-only
573    // attribute first.
574    if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
575      if (!SetFileAttributes(path.c_str(),
576                             fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
577        return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
578    }
579
580    if (!DeleteFile(path.c_str()))
581      return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
582    return false;
583  }
584}
585
586bool
587Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
588  if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
589    return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
590        + "': ");
591  return false;
592}
593
594bool
595Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
596  // FIXME: should work on directories also.
597  if (!si.isFile) {
598    return true;
599  }
600
601  HANDLE h = CreateFile(path.c_str(),
602                        FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
603                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
604                        NULL,
605                        OPEN_EXISTING,
606                        FILE_ATTRIBUTE_NORMAL,
607                        NULL);
608  if (h == INVALID_HANDLE_VALUE)
609    return true;
610
611  BY_HANDLE_FILE_INFORMATION bhfi;
612  if (!GetFileInformationByHandle(h, &bhfi)) {
613    DWORD err = GetLastError();
614    CloseHandle(h);
615    SetLastError(err);
616    return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
617  }
618
619  ULARGE_INTEGER ui;
620  ui.QuadPart = si.modTime.toWin32Time();
621  FILETIME ft;
622  ft.dwLowDateTime = ui.LowPart;
623  ft.dwHighDateTime = ui.HighPart;
624  BOOL ret = SetFileTime(h, NULL, &ft, &ft);
625  DWORD err = GetLastError();
626  CloseHandle(h);
627  if (!ret) {
628    SetLastError(err);
629    return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
630  }
631
632  // Best we can do with Unix permission bits is to interpret the owner
633  // writable bit.
634  if (si.mode & 0200) {
635    if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
636      if (!SetFileAttributes(path.c_str(),
637              bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
638        return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
639    }
640  } else {
641    if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
642      if (!SetFileAttributes(path.c_str(),
643              bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
644        return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
645    }
646  }
647
648  return false;
649}
650
651bool
652Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
653  bool Exists;
654  if (reuse_current && (fs::exists(path, Exists) || !Exists))
655    return false; // File doesn't exist already, just use it!
656
657  // Reserve space for -XXXXXX at the end.
658  char *FNBuffer = (char*) alloca(path.size()+8);
659  unsigned offset = path.size();
660  path.copy(FNBuffer, offset);
661
662  // Find a numeric suffix that isn't used by an existing file.  Assume there
663  // won't be more than 1 million files with the same prefix.  Probably a safe
664  // bet.
665  static int FCounter = -1;
666  if (FCounter < 0) {
667    // Give arbitrary initial seed.
668    // FIXME: We should use sys::fs::unique_file() in future.
669    LARGE_INTEGER cnt64;
670    DWORD x = GetCurrentProcessId();
671    x = (x << 16) | (x >> 16);
672    if (QueryPerformanceCounter(&cnt64))    // RDTSC
673      x ^= cnt64.HighPart ^ cnt64.LowPart;
674    FCounter = x % 1000000;
675  }
676  do {
677    sprintf(FNBuffer+offset, "-%06u", FCounter);
678    if (++FCounter > 999999)
679      FCounter = 0;
680    path = FNBuffer;
681  } while (!fs::exists(path, Exists) && Exists);
682  return false;
683}
684
685bool
686Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
687  // Make this into a unique file name
688  makeUnique(reuse_current, ErrMsg);
689
690  // Now go and create it
691  HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
692                        FILE_ATTRIBUTE_NORMAL, NULL);
693  if (h == INVALID_HANDLE_VALUE)
694    return MakeErrMsg(ErrMsg, path + ": can't create file");
695
696  CloseHandle(h);
697  return false;
698}
699}
700}
701