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!");
154 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
156 // FIXME: This does not handle correctly an absolute path starting from
157 // a drive letter or in UNC format.
163 return NameStart[0] == '/';
166 (NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/')) ||
167 (NameStart[0] == '\\' || (NameStart[1] == ':' && NameStart[2] == '\\'));
171 static Path *TempDirectory;
174 Path::GetTemporaryDirectory(std::string* ErrMsg) {
176 #if defined(_MSC_VER)
177 // Visual Studio gets confused and emits a diagnostic about calling exists,
178 // even though this is the implementation for PathV1. Temporarily
179 // disable the deprecated warning message
180 #pragma warning(push)
181 #pragma warning(disable:4996)
183 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
184 #if defined(_MSC_VER)
187 return *TempDirectory;
190 char pathname[MAX_PATH];
191 if (!GetTempPath(MAX_PATH, pathname)) {
193 *ErrMsg = "Can't determine temporary directory";
198 result.set(pathname);
200 // Append a subdirectory based on our process id so multiple LLVMs don't
201 // step on each other's toes.
203 // Mingw's Win32 header files are broken.
204 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
206 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
208 result.appendComponent(pathname);
210 // If there's a directory left over from a previous LLVM execution that
211 // happened to have the same process id, get rid of it.
212 result.eraseFromDisk(true);
214 // And finally (re-)create the empty directory.
215 result.createDirectoryOnDisk(false);
216 TempDirectory = new Path(result);
217 return *TempDirectory;
221 Path::GetCurrentDirectory() {
222 char pathname[MAX_PATH];
223 ::GetCurrentDirectoryA(MAX_PATH,pathname);
224 return Path(pathname);
227 /// GetMainExecutable - Return the path to the main executable, given the
228 /// value of argv[0] from program startup.
229 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
230 char pathname[MAX_PATH];
231 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
232 return ret != MAX_PATH ? Path(pathname) : Path();
236 // FIXME: the above set of functions don't map to Windows very well.
239 Path::exists() const {
240 DWORD attr = GetFileAttributes(path.c_str());
241 return attr != INVALID_FILE_ATTRIBUTES;
245 Path::isDirectory() const {
246 DWORD attr = GetFileAttributes(path.c_str());
247 return (attr != INVALID_FILE_ATTRIBUTES) &&
248 (attr & FILE_ATTRIBUTE_DIRECTORY);
252 Path::isSymLink() const {
253 DWORD attributes = GetFileAttributes(path.c_str());
255 if (attributes == INVALID_FILE_ATTRIBUTES)
256 // There's no sane way to report this :(.
257 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
259 // This isn't exactly what defines a NTFS symlink, but it is only true for
260 // paths that act like a symlink.
261 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
265 Path::canRead() const {
266 // FIXME: take security attributes into account.
267 DWORD attr = GetFileAttributes(path.c_str());
268 return attr != INVALID_FILE_ATTRIBUTES;
272 Path::canWrite() const {
273 // FIXME: take security attributes into account.
274 DWORD attr = GetFileAttributes(path.c_str());
275 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
279 Path::canExecute() const {
280 // FIXME: take security attributes into account.
281 DWORD attr = GetFileAttributes(path.c_str());
282 return attr != INVALID_FILE_ATTRIBUTES;
286 Path::isRegularFile() const {
288 if (fs::is_regular_file(path, res))
294 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
295 if (!fsIsValid || update) {
296 WIN32_FILE_ATTRIBUTE_DATA fi;
297 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
298 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
299 ": Can't get status: ");
303 status.fileSize = fi.nFileSizeHigh;
304 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
305 status.fileSize += fi.nFileSizeLow;
307 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
308 status.user = 9999; // Not applicable to Windows, so...
309 status.group = 9999; // Not applicable to Windows, so...
311 // FIXME: this is only unique if the file is accessed by the same file path.
312 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
313 // numbers, but the concept doesn't exist in Windows.
315 for (unsigned i = 0; i < path.length(); ++i)
316 status.uniqueID += path[i];
319 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
320 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
321 status.modTime.fromWin32Time(ui.QuadPart);
323 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
329 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
330 // All files are readable on Windows (ignoring security attributes).
334 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
335 DWORD attr = GetFileAttributes(path.c_str());
337 // If it doesn't exist, we're done.
338 if (attr == INVALID_FILE_ATTRIBUTES)
341 if (attr & FILE_ATTRIBUTE_READONLY) {
342 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
343 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
351 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
352 WIN32_FILE_ATTRIBUTE_DATA fi;
353 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
354 MakeErrMsg(ErrMsg, path + ": can't get status of file");
358 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
360 *ErrMsg = path + ": not a directory";
366 std::string searchpath = path;
367 if (path.size() == 0 || searchpath[path.size()-1] == '/')
372 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
373 if (h == INVALID_HANDLE_VALUE) {
374 if (GetLastError() == ERROR_FILE_NOT_FOUND)
375 return true; // not really an error, now is it?
376 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
381 if (fd.cFileName[0] == '.')
384 aPath.appendComponent(&fd.cFileName[0]);
385 result.insert(aPath);
386 } while (FindNextFile(h, &fd));
388 DWORD err = GetLastError();
390 if (err != ERROR_NO_MORE_FILES) {
392 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
399 Path::set(StringRef a_path) {
402 std::string save(path);
404 FlipBackSlashes(path);
413 Path::appendComponent(StringRef name) {
416 std::string save(path);
418 size_t last = path.size() - 1;
419 if (path[last] != '/')
431 Path::eraseComponent() {
432 size_t slashpos = path.rfind('/',path.size());
433 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
435 std::string save(path);
436 path.erase(slashpos);
445 Path::eraseSuffix() {
446 size_t dotpos = path.rfind('.',path.size());
447 size_t slashpos = path.rfind('/',path.size());
448 if (dotpos != std::string::npos) {
449 if (slashpos == std::string::npos || dotpos > slashpos+1) {
450 std::string save(path);
451 path.erase(dotpos, path.size()-dotpos);
462 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
464 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
469 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
470 // Get a writeable copy of the path name
471 size_t len = path.length();
472 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
473 path.copy(pathname, len);
476 // Make sure it ends with a slash.
477 if (len == 0 || pathname[len - 1] != '/') {
482 // Determine starting point for initial / search.
483 char *next = pathname;
484 if (pathname[0] == '/' && pathname[1] == '/') {
486 next = strchr(pathname+2, '/');
488 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
491 next = strchr(next+1, '/');
493 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
497 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
500 if (pathname[1] == ':')
501 next += 2; // skip drive letter
503 next++; // skip root directory
506 // If we're supposed to create intermediate directories
507 if (create_parents) {
508 // Loop through the directory components until we're done
510 next = strchr(next, '/');
512 if (!CreateDirectory(pathname, NULL) &&
513 GetLastError() != ERROR_ALREADY_EXISTS)
514 return MakeErrMsg(ErrMsg,
515 std::string(pathname) + ": Can't create directory: ");
519 // Drop trailing slash.
521 if (!CreateDirectory(pathname, NULL) &&
522 GetLastError() != ERROR_ALREADY_EXISTS) {
523 return MakeErrMsg(ErrMsg, std::string(pathname) +
524 ": Can't create directory: ");
531 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
532 WIN32_FILE_ATTRIBUTE_DATA fi;
533 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
536 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
537 // If it doesn't exist, we're done.
539 if (fs::exists(path, Exists) || !Exists)
542 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
543 int lastchar = path.length() - 1 ;
544 path.copy(pathname, lastchar+1);
546 // Make path end with '/*'.
547 if (pathname[lastchar] != '/')
548 pathname[++lastchar] = '/';
549 pathname[lastchar+1] = '*';
550 pathname[lastchar+2] = 0;
552 if (remove_contents) {
554 HANDLE h = FindFirstFile(pathname, &fd);
556 // It's a bad idea to alter the contents of a directory while enumerating
557 // its contents. So build a list of its contents first, then destroy them.
559 if (h != INVALID_HANDLE_VALUE) {
560 std::vector<Path> list;
563 if (strcmp(fd.cFileName, ".") == 0)
565 if (strcmp(fd.cFileName, "..") == 0)
569 aPath.appendComponent(&fd.cFileName[0]);
570 list.push_back(aPath);
571 } while (FindNextFile(h, &fd));
573 DWORD err = GetLastError();
575 if (err != ERROR_NO_MORE_FILES) {
577 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
580 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
583 aPath.eraseFromDisk(true);
586 if (GetLastError() != ERROR_FILE_NOT_FOUND)
587 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
591 pathname[lastchar] = 0;
592 if (!RemoveDirectory(pathname))
593 return MakeErrMsg(ErrStr,
594 std::string(pathname) + ": Can't destroy directory: ");
597 // Read-only files cannot be deleted on Windows. Must remove the read-only
599 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
600 if (!SetFileAttributes(path.c_str(),
601 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
602 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
605 if (!DeleteFile(path.c_str()))
606 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
611 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
612 assert(len < 1024 && "Request for magic string too long");
613 char* buf = reinterpret_cast<char*>(alloca(len));
615 HANDLE h = CreateFile(path.c_str(),
620 FILE_ATTRIBUTE_NORMAL,
622 if (h == INVALID_HANDLE_VALUE)
626 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
629 if (!ret || nRead != len)
632 Magic = std::string(buf, len);
637 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
638 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
639 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
645 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
646 // FIXME: should work on directories also.
651 HANDLE h = CreateFile(path.c_str(),
652 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
653 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
656 FILE_ATTRIBUTE_NORMAL,
658 if (h == INVALID_HANDLE_VALUE)
661 BY_HANDLE_FILE_INFORMATION bhfi;
662 if (!GetFileInformationByHandle(h, &bhfi)) {
663 DWORD err = GetLastError();
666 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
670 ui.QuadPart = si.modTime.toWin32Time();
672 ft.dwLowDateTime = ui.LowPart;
673 ft.dwHighDateTime = ui.HighPart;
674 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
675 DWORD err = GetLastError();
679 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
682 // Best we can do with Unix permission bits is to interpret the owner
684 if (si.mode & 0200) {
685 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
686 if (!SetFileAttributes(path.c_str(),
687 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
688 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
691 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
692 if (!SetFileAttributes(path.c_str(),
693 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
694 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
702 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
704 if (reuse_current && (fs::exists(path, Exists) || !Exists))
705 return false; // File doesn't exist already, just use it!
707 // Reserve space for -XXXXXX at the end.
708 char *FNBuffer = (char*) alloca(path.size()+8);
709 unsigned offset = path.size();
710 path.copy(FNBuffer, offset);
712 // Find a numeric suffix that isn't used by an existing file. Assume there
713 // won't be more than 1 million files with the same prefix. Probably a safe
715 static int FCounter = -1;
717 // Give arbitrary initial seed.
718 // FIXME: We should use sys::fs::unique_file() in future.
720 DWORD x = GetCurrentProcessId();
721 x = (x << 16) | (x >> 16);
722 if (QueryPerformanceCounter(&cnt64)) // RDTSC
723 x ^= cnt64.HighPart ^ cnt64.LowPart;
724 FCounter = x % 1000000;
727 sprintf(FNBuffer+offset, "-%06u", FCounter);
728 if (++FCounter > 999999)
731 } while (!fs::exists(path, Exists) && Exists);
736 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
737 // Make this into a unique file name
738 makeUnique(reuse_current, ErrMsg);
740 // Now go and create it
741 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
742 FILE_ATTRIBUTE_NORMAL, NULL);
743 if (h == INVALID_HANDLE_VALUE)
744 return MakeErrMsg(ErrMsg, path + ": can't create file");