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 // We need to undo a macro defined in Windows.h, otherwise we won't compile:
24 #undef GetCurrentDirectory
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.
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.
36 static void FlipBackSlashes(std::string& s) {
37 for (size_t i = 0; i < s.size(); i++)
45 const char PathSeparator = ';';
47 StringRef Path::GetEXESuffix() {
51 Path::Path(llvm::StringRef p)
53 FlipBackSlashes(path);
56 Path::Path(const char *StrStart, unsigned StrLen)
57 : path(StrStart, StrLen) {
58 FlipBackSlashes(path);
62 Path::operator=(StringRef that) {
63 path.assign(that.data(), that.size());
64 FlipBackSlashes(path);
69 Path::isValid() const {
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)
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);
83 if (pos != std::string::npos) {
84 if (pos != 1 || !isalpha(static_cast<unsigned char>(path[0])) || len < 3)
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)
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)
103 // Remove trailing slash, unless it's a root slash.
104 if (len > rootslash+1 && path[len-1] == '/')
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')
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] == ':')
122 if (pos > 0 && path[pos-1] == '.') {
123 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
134 void Path::makeAbsolute() {
135 TCHAR FullPath[MAX_PATH + 1] = {0};
136 LPTSTR FilePart = NULL;
138 DWORD RetLength = ::GetFullPathNameA(path.c_str(),
139 sizeof(FullPath)/sizeof(FullPath[0]),
140 FullPath, &FilePart);
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!");
153 static Path *TempDirectory;
156 Path::GetTemporaryDirectory(std::string* ErrMsg) {
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)
165 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
166 #if defined(_MSC_VER)
169 return *TempDirectory;
172 char pathname[MAX_PATH];
173 if (!GetTempPath(MAX_PATH, pathname)) {
175 *ErrMsg = "Can't determine temporary directory";
180 result.set(pathname);
182 // Append a subdirectory based on our process id so multiple LLVMs don't
183 // step on each other's toes.
185 // Mingw's Win32 header files are broken.
186 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
188 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
190 result.appendComponent(pathname);
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);
196 // And finally (re-)create the empty directory.
197 result.createDirectoryOnDisk(false);
198 TempDirectory = new Path(result);
199 return *TempDirectory;
203 Path::GetCurrentDirectory() {
204 char pathname[MAX_PATH];
205 ::GetCurrentDirectoryA(MAX_PATH,pathname);
206 return Path(pathname);
209 /// GetMainExecutable - Return the path to the main executable, given the
210 /// value of argv[0] from program startup.
211 Path 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();
218 // FIXME: the above set of functions don't map to Windows very well.
221 Path::exists() const {
222 DWORD attr = GetFileAttributes(path.c_str());
223 return attr != INVALID_FILE_ATTRIBUTES;
227 Path::isDirectory() const {
228 DWORD attr = GetFileAttributes(path.c_str());
229 return (attr != INVALID_FILE_ATTRIBUTES) &&
230 (attr & FILE_ATTRIBUTE_DIRECTORY);
234 Path::isSymLink() const {
235 DWORD attributes = GetFileAttributes(path.c_str());
237 if (attributes == INVALID_FILE_ATTRIBUTES)
238 // There's no sane way to report this :(.
239 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
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;
247 Path::canExecute() const {
248 // FIXME: take security attributes into account.
249 DWORD attr = GetFileAttributes(path.c_str());
250 return attr != INVALID_FILE_ATTRIBUTES;
254 Path::isRegularFile() const {
256 if (fs::is_regular_file(path, res))
262 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
263 if (!fsIsValid || update) {
264 WIN32_FILE_ATTRIBUTE_DATA fi;
265 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
266 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
267 ": Can't get status: ");
271 status.fileSize = fi.nFileSizeHigh;
272 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
273 status.fileSize += fi.nFileSizeLow;
275 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
276 status.user = 9999; // Not applicable to Windows, so...
277 status.group = 9999; // Not applicable to Windows, so...
280 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
281 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
282 status.modTime.fromWin32Time(ui.QuadPart);
284 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
290 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
291 // All files are readable on Windows (ignoring security attributes).
295 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
296 DWORD attr = GetFileAttributes(path.c_str());
298 // If it doesn't exist, we're done.
299 if (attr == INVALID_FILE_ATTRIBUTES)
302 if (attr & FILE_ATTRIBUTE_READONLY) {
303 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
304 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
312 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
313 WIN32_FILE_ATTRIBUTE_DATA fi;
314 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
315 MakeErrMsg(ErrMsg, path + ": can't get status of file");
319 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
321 *ErrMsg = path + ": not a directory";
327 std::string searchpath = path;
328 if (path.size() == 0 || searchpath[path.size()-1] == '/')
333 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
334 if (h == INVALID_HANDLE_VALUE) {
335 if (GetLastError() == ERROR_FILE_NOT_FOUND)
336 return true; // not really an error, now is it?
337 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
342 if (fd.cFileName[0] == '.')
345 aPath.appendComponent(&fd.cFileName[0]);
346 result.insert(aPath);
347 } while (FindNextFile(h, &fd));
349 DWORD err = GetLastError();
351 if (err != ERROR_NO_MORE_FILES) {
353 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
360 Path::set(StringRef a_path) {
363 std::string save(path);
365 FlipBackSlashes(path);
374 Path::appendComponent(StringRef name) {
377 std::string save(path);
379 size_t last = path.size() - 1;
380 if (path[last] != '/')
392 Path::eraseComponent() {
393 size_t slashpos = path.rfind('/',path.size());
394 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
396 std::string save(path);
397 path.erase(slashpos);
406 Path::eraseSuffix() {
407 size_t dotpos = path.rfind('.',path.size());
408 size_t slashpos = path.rfind('/',path.size());
409 if (dotpos != std::string::npos) {
410 if (slashpos == std::string::npos || dotpos > slashpos+1) {
411 std::string save(path);
412 path.erase(dotpos, path.size()-dotpos);
423 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
425 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
430 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
431 // Get a writeable copy of the path name
432 size_t len = path.length();
433 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
434 path.copy(pathname, len);
437 // Make sure it ends with a slash.
438 if (len == 0 || pathname[len - 1] != '/') {
443 // Determine starting point for initial / search.
444 char *next = pathname;
445 if (pathname[0] == '/' && pathname[1] == '/') {
447 next = strchr(pathname+2, '/');
449 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
452 next = strchr(next+1, '/');
454 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
458 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
461 if (pathname[1] == ':')
462 next += 2; // skip drive letter
464 next++; // skip root directory
467 // If we're supposed to create intermediate directories
468 if (create_parents) {
469 // Loop through the directory components until we're done
471 next = strchr(next, '/');
473 if (!CreateDirectory(pathname, NULL) &&
474 GetLastError() != ERROR_ALREADY_EXISTS)
475 return MakeErrMsg(ErrMsg,
476 std::string(pathname) + ": Can't create directory: ");
480 // Drop trailing slash.
482 if (!CreateDirectory(pathname, NULL) &&
483 GetLastError() != ERROR_ALREADY_EXISTS) {
484 return MakeErrMsg(ErrMsg, std::string(pathname) +
485 ": Can't create directory: ");
492 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
493 WIN32_FILE_ATTRIBUTE_DATA fi;
494 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
497 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
498 // If it doesn't exist, we're done.
500 if (fs::exists(path, Exists) || !Exists)
503 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
504 int lastchar = path.length() - 1 ;
505 path.copy(pathname, lastchar+1);
507 // Make path end with '/*'.
508 if (pathname[lastchar] != '/')
509 pathname[++lastchar] = '/';
510 pathname[lastchar+1] = '*';
511 pathname[lastchar+2] = 0;
513 if (remove_contents) {
515 HANDLE h = FindFirstFile(pathname, &fd);
517 // It's a bad idea to alter the contents of a directory while enumerating
518 // its contents. So build a list of its contents first, then destroy them.
520 if (h != INVALID_HANDLE_VALUE) {
521 std::vector<Path> list;
524 if (strcmp(fd.cFileName, ".") == 0)
526 if (strcmp(fd.cFileName, "..") == 0)
530 aPath.appendComponent(&fd.cFileName[0]);
531 list.push_back(aPath);
532 } while (FindNextFile(h, &fd));
534 DWORD err = GetLastError();
536 if (err != ERROR_NO_MORE_FILES) {
538 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
541 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
544 aPath.eraseFromDisk(true);
547 if (GetLastError() != ERROR_FILE_NOT_FOUND)
548 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
552 pathname[lastchar] = 0;
553 if (!RemoveDirectory(pathname))
554 return MakeErrMsg(ErrStr,
555 std::string(pathname) + ": Can't destroy directory: ");
558 // Read-only files cannot be deleted on Windows. Must remove the read-only
560 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
561 if (!SetFileAttributes(path.c_str(),
562 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
563 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
566 if (!DeleteFile(path.c_str()))
567 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
573 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
574 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
575 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
581 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
582 // FIXME: should work on directories also.
587 HANDLE h = CreateFile(path.c_str(),
588 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
589 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
592 FILE_ATTRIBUTE_NORMAL,
594 if (h == INVALID_HANDLE_VALUE)
597 BY_HANDLE_FILE_INFORMATION bhfi;
598 if (!GetFileInformationByHandle(h, &bhfi)) {
599 DWORD err = GetLastError();
602 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
606 ui.QuadPart = si.modTime.toWin32Time();
608 ft.dwLowDateTime = ui.LowPart;
609 ft.dwHighDateTime = ui.HighPart;
610 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
611 DWORD err = GetLastError();
615 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
618 // Best we can do with Unix permission bits is to interpret the owner
620 if (si.mode & 0200) {
621 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
622 if (!SetFileAttributes(path.c_str(),
623 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
624 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
627 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
628 if (!SetFileAttributes(path.c_str(),
629 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
630 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
638 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
640 if (reuse_current && (fs::exists(path, Exists) || !Exists))
641 return false; // File doesn't exist already, just use it!
643 // Reserve space for -XXXXXX at the end.
644 char *FNBuffer = (char*) alloca(path.size()+8);
645 unsigned offset = path.size();
646 path.copy(FNBuffer, offset);
648 // Find a numeric suffix that isn't used by an existing file. Assume there
649 // won't be more than 1 million files with the same prefix. Probably a safe
651 static int FCounter = -1;
653 // Give arbitrary initial seed.
654 // FIXME: We should use sys::fs::unique_file() in future.
656 DWORD x = GetCurrentProcessId();
657 x = (x << 16) | (x >> 16);
658 if (QueryPerformanceCounter(&cnt64)) // RDTSC
659 x ^= cnt64.HighPart ^ cnt64.LowPart;
660 FCounter = x % 1000000;
663 sprintf(FNBuffer+offset, "-%06u", FCounter);
664 if (++FCounter > 999999)
667 } while (!fs::exists(path, Exists) && Exists);
672 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
673 // Make this into a unique file name
674 makeUnique(reuse_current, ErrMsg);
676 // Now go and create it
677 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
678 FILE_ATTRIBUTE_NORMAL, NULL);
679 if (h == INVALID_HANDLE_VALUE)
680 return MakeErrMsg(ErrMsg, path + ": can't create file");