1 //===- llvm/Support/Win32/Path.cpp - Win32 Path Implementation ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the Win32 specific implementation of the Path class.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic Win32 code that
16 //=== is guaranteed to work on *all* Win32 variants.
17 //===----------------------------------------------------------------------===//
23 // Windows happily accepts either forward or backward slashes, though any path
24 // returned by a Win32 API will have backward slashes. As LLVM code basically
25 // assumes forward slashes are used, backward slashs are converted where they
26 // can be introduced into a path.
28 // Another invariant is that a path ends with a slash if and only if the path
29 // is a root directory. Any other use of a trailing slash is stripped. Unlike
30 // in Unix, Windows has a rather complicated notion of a root path and this
31 // invariant helps simply the code.
33 static void FlipBackSlashes(std::string& s) {
34 for (size_t i = 0; i < s.size(); i++)
42 const char PathSeparator = ';';
44 StringRef Path::GetEXESuffix() {
48 Path::Path(llvm::StringRef p)
50 FlipBackSlashes(path);
53 Path::Path(const char *StrStart, unsigned StrLen)
54 : path(StrStart, StrLen) {
55 FlipBackSlashes(path);
59 Path::operator=(StringRef that) {
60 path.assign(that.data(), that.size());
61 FlipBackSlashes(path);
66 Path::isValid() const {
70 size_t len = path.size();
71 // If there is a null character, it and all its successors are ignored.
72 size_t pos = path.find_first_of('\0');
73 if (pos != std::string::npos)
76 // If there is a colon, it must be the second character, preceded by a letter
77 // and followed by something.
78 pos = path.rfind(':',len);
80 if (pos != std::string::npos) {
81 if (pos != 1 || !isalpha(static_cast<unsigned char>(path[0])) || len < 3)
86 // Look for a UNC path, and if found adjust our notion of the root slash.
87 if (len > 3 && path[0] == '/' && path[1] == '/') {
88 rootslash = path.find('/', 2);
89 if (rootslash == std::string::npos)
93 // Check for illegal characters.
94 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
95 "\013\014\015\016\017\020\021\022\023\024\025\026"
96 "\027\030\031\032\033\034\035\036\037")
100 // Remove trailing slash, unless it's a root slash.
101 if (len > rootslash+1 && path[len-1] == '/')
104 // Check each component for legality.
105 for (pos = 0; pos < len; ++pos) {
106 // A component may not end in a space.
107 if (path[pos] == ' ') {
108 if (pos+1 == len || path[pos+1] == '/' || path[pos+1] == '\0')
112 // A component may not end in a period.
113 if (path[pos] == '.') {
114 if (pos+1 == len || path[pos+1] == '/') {
115 // Unless it is the pseudo-directory "."...
116 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
119 if (pos > 0 && path[pos-1] == '.') {
120 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
131 void Path::makeAbsolute() {
132 TCHAR FullPath[MAX_PATH + 1] = {0};
133 LPTSTR FilePart = NULL;
135 DWORD RetLength = ::GetFullPathNameA(path.c_str(),
136 sizeof(FullPath)/sizeof(FullPath[0]),
137 FullPath, &FilePart);
139 if (0 == RetLength) {
140 // FIXME: Report the error GetLastError()
141 assert(0 && "Unable to make absolute path!");
142 } else if (RetLength > MAX_PATH) {
143 // FIXME: Report too small buffer (needed RetLength bytes).
144 assert(0 && "Unable to make absolute path!");
150 static Path *TempDirectory;
153 Path::GetTemporaryDirectory(std::string* ErrMsg) {
155 #if defined(_MSC_VER)
156 // Visual Studio gets confused and emits a diagnostic about calling exists,
157 // even though this is the implementation for PathV1. Temporarily
158 // disable the deprecated warning message
159 #pragma warning(push)
160 #pragma warning(disable:4996)
162 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
163 #if defined(_MSC_VER)
166 return *TempDirectory;
169 char pathname[MAX_PATH];
170 if (!GetTempPath(MAX_PATH, pathname)) {
172 *ErrMsg = "Can't determine temporary directory";
177 result.set(pathname);
179 // Append a subdirectory based on our process id so multiple LLVMs don't
180 // step on each other's toes.
182 // Mingw's Win32 header files are broken.
183 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
185 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
187 result.appendComponent(pathname);
189 // If there's a directory left over from a previous LLVM execution that
190 // happened to have the same process id, get rid of it.
191 result.eraseFromDisk(true);
193 // And finally (re-)create the empty directory.
194 result.createDirectoryOnDisk(false);
195 TempDirectory = new Path(result);
196 return *TempDirectory;
199 /// GetMainExecutable - Return the path to the main executable, given the
200 /// value of argv[0] from program startup.
201 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
202 char pathname[MAX_PATH];
203 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
204 return ret != MAX_PATH ? Path(pathname) : Path();
208 // FIXME: the above set of functions don't map to Windows very well.
211 Path::exists() const {
212 DWORD attr = GetFileAttributes(path.c_str());
213 return attr != INVALID_FILE_ATTRIBUTES;
217 Path::isDirectory() const {
218 DWORD attr = GetFileAttributes(path.c_str());
219 return (attr != INVALID_FILE_ATTRIBUTES) &&
220 (attr & FILE_ATTRIBUTE_DIRECTORY);
224 Path::isSymLink() const {
225 DWORD attributes = GetFileAttributes(path.c_str());
227 if (attributes == INVALID_FILE_ATTRIBUTES)
228 // There's no sane way to report this :(.
229 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
231 // This isn't exactly what defines a NTFS symlink, but it is only true for
232 // paths that act like a symlink.
233 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
237 Path::canRead() const {
238 // FIXME: take security attributes into account.
239 DWORD attr = GetFileAttributes(path.c_str());
240 return attr != INVALID_FILE_ATTRIBUTES;
244 Path::canWrite() const {
245 // FIXME: take security attributes into account.
246 DWORD attr = GetFileAttributes(path.c_str());
247 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
251 Path::canExecute() const {
252 // FIXME: take security attributes into account.
253 DWORD attr = GetFileAttributes(path.c_str());
254 return attr != INVALID_FILE_ATTRIBUTES;
258 Path::isRegularFile() const {
260 if (fs::is_regular_file(path, res))
266 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
267 if (!fsIsValid || update) {
268 WIN32_FILE_ATTRIBUTE_DATA fi;
269 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
270 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
271 ": Can't get status: ");
275 status.fileSize = fi.nFileSizeHigh;
276 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
277 status.fileSize += fi.nFileSizeLow;
279 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
280 status.user = 9999; // Not applicable to Windows, so...
281 status.group = 9999; // Not applicable to Windows, so...
283 // FIXME: this is only unique if the file is accessed by the same file path.
284 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
285 // numbers, but the concept doesn't exist in Windows.
287 for (unsigned i = 0; i < path.length(); ++i)
288 status.uniqueID += path[i];
291 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
292 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
293 status.modTime.fromWin32Time(ui.QuadPart);
295 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
301 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
302 // All files are readable on Windows (ignoring security attributes).
306 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
307 DWORD attr = GetFileAttributes(path.c_str());
309 // If it doesn't exist, we're done.
310 if (attr == INVALID_FILE_ATTRIBUTES)
313 if (attr & FILE_ATTRIBUTE_READONLY) {
314 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
315 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
323 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
324 WIN32_FILE_ATTRIBUTE_DATA fi;
325 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
326 MakeErrMsg(ErrMsg, path + ": can't get status of file");
330 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
332 *ErrMsg = path + ": not a directory";
338 std::string searchpath = path;
339 if (path.size() == 0 || searchpath[path.size()-1] == '/')
344 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
345 if (h == INVALID_HANDLE_VALUE) {
346 if (GetLastError() == ERROR_FILE_NOT_FOUND)
347 return true; // not really an error, now is it?
348 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
353 if (fd.cFileName[0] == '.')
356 aPath.appendComponent(&fd.cFileName[0]);
357 result.insert(aPath);
358 } while (FindNextFile(h, &fd));
360 DWORD err = GetLastError();
362 if (err != ERROR_NO_MORE_FILES) {
364 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
371 Path::set(StringRef a_path) {
374 std::string save(path);
376 FlipBackSlashes(path);
385 Path::appendComponent(StringRef name) {
388 std::string save(path);
390 size_t last = path.size() - 1;
391 if (path[last] != '/')
403 Path::eraseComponent() {
404 size_t slashpos = path.rfind('/',path.size());
405 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
407 std::string save(path);
408 path.erase(slashpos);
417 Path::eraseSuffix() {
418 size_t dotpos = path.rfind('.',path.size());
419 size_t slashpos = path.rfind('/',path.size());
420 if (dotpos != std::string::npos) {
421 if (slashpos == std::string::npos || dotpos > slashpos+1) {
422 std::string save(path);
423 path.erase(dotpos, path.size()-dotpos);
434 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
436 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
441 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
442 // Get a writeable copy of the path name
443 size_t len = path.length();
444 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
445 path.copy(pathname, len);
448 // Make sure it ends with a slash.
449 if (len == 0 || pathname[len - 1] != '/') {
454 // Determine starting point for initial / search.
455 char *next = pathname;
456 if (pathname[0] == '/' && pathname[1] == '/') {
458 next = strchr(pathname+2, '/');
460 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
463 next = strchr(next+1, '/');
465 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
469 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
472 if (pathname[1] == ':')
473 next += 2; // skip drive letter
475 next++; // skip root directory
478 // If we're supposed to create intermediate directories
479 if (create_parents) {
480 // Loop through the directory components until we're done
482 next = strchr(next, '/');
484 if (!CreateDirectory(pathname, NULL) &&
485 GetLastError() != ERROR_ALREADY_EXISTS)
486 return MakeErrMsg(ErrMsg,
487 std::string(pathname) + ": Can't create directory: ");
491 // Drop trailing slash.
493 if (!CreateDirectory(pathname, NULL) &&
494 GetLastError() != ERROR_ALREADY_EXISTS) {
495 return MakeErrMsg(ErrMsg, std::string(pathname) +
496 ": Can't create directory: ");
503 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
504 WIN32_FILE_ATTRIBUTE_DATA fi;
505 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
508 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
509 // If it doesn't exist, we're done.
511 if (fs::exists(path, Exists) || !Exists)
514 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
515 int lastchar = path.length() - 1 ;
516 path.copy(pathname, lastchar+1);
518 // Make path end with '/*'.
519 if (pathname[lastchar] != '/')
520 pathname[++lastchar] = '/';
521 pathname[lastchar+1] = '*';
522 pathname[lastchar+2] = 0;
524 if (remove_contents) {
526 HANDLE h = FindFirstFile(pathname, &fd);
528 // It's a bad idea to alter the contents of a directory while enumerating
529 // its contents. So build a list of its contents first, then destroy them.
531 if (h != INVALID_HANDLE_VALUE) {
532 std::vector<Path> list;
535 if (strcmp(fd.cFileName, ".") == 0)
537 if (strcmp(fd.cFileName, "..") == 0)
541 aPath.appendComponent(&fd.cFileName[0]);
542 list.push_back(aPath);
543 } while (FindNextFile(h, &fd));
545 DWORD err = GetLastError();
547 if (err != ERROR_NO_MORE_FILES) {
549 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
552 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
555 aPath.eraseFromDisk(true);
558 if (GetLastError() != ERROR_FILE_NOT_FOUND)
559 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
563 pathname[lastchar] = 0;
564 if (!RemoveDirectory(pathname))
565 return MakeErrMsg(ErrStr,
566 std::string(pathname) + ": Can't destroy directory: ");
569 // Read-only files cannot be deleted on Windows. Must remove the read-only
571 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
572 if (!SetFileAttributes(path.c_str(),
573 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
574 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
577 if (!DeleteFile(path.c_str()))
578 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
584 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
585 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
586 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
592 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
593 // FIXME: should work on directories also.
598 HANDLE h = CreateFile(path.c_str(),
599 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
600 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
603 FILE_ATTRIBUTE_NORMAL,
605 if (h == INVALID_HANDLE_VALUE)
608 BY_HANDLE_FILE_INFORMATION bhfi;
609 if (!GetFileInformationByHandle(h, &bhfi)) {
610 DWORD err = GetLastError();
613 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
617 ui.QuadPart = si.modTime.toWin32Time();
619 ft.dwLowDateTime = ui.LowPart;
620 ft.dwHighDateTime = ui.HighPart;
621 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
622 DWORD err = GetLastError();
626 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
629 // Best we can do with Unix permission bits is to interpret the owner
631 if (si.mode & 0200) {
632 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
633 if (!SetFileAttributes(path.c_str(),
634 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
635 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
638 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
639 if (!SetFileAttributes(path.c_str(),
640 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
641 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
649 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
651 if (reuse_current && (fs::exists(path, Exists) || !Exists))
652 return false; // File doesn't exist already, just use it!
654 // Reserve space for -XXXXXX at the end.
655 char *FNBuffer = (char*) alloca(path.size()+8);
656 unsigned offset = path.size();
657 path.copy(FNBuffer, offset);
659 // Find a numeric suffix that isn't used by an existing file. Assume there
660 // won't be more than 1 million files with the same prefix. Probably a safe
662 static int FCounter = -1;
664 // Give arbitrary initial seed.
665 // FIXME: We should use sys::fs::unique_file() in future.
667 DWORD x = GetCurrentProcessId();
668 x = (x << 16) | (x >> 16);
669 if (QueryPerformanceCounter(&cnt64)) // RDTSC
670 x ^= cnt64.HighPart ^ cnt64.LowPart;
671 FCounter = x % 1000000;
674 sprintf(FNBuffer+offset, "-%06u", FCounter);
675 if (++FCounter > 999999)
678 } while (!fs::exists(path, Exists) && Exists);
683 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
684 // Make this into a unique file name
685 makeUnique(reuse_current, ErrMsg);
687 // Now go and create it
688 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
689 FILE_ATTRIBUTE_NORMAL, NULL);
690 if (h == INVALID_HANDLE_VALUE)
691 return MakeErrMsg(ErrMsg, path + ": can't create file");