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] == '\\'));
172 Path::isAbsolute() const {
173 // FIXME: This does not handle correctly an absolute path starting from
174 // a drive letter or in UNC format.
175 switch (path.length()) {
180 return path[0] == '/';
182 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
186 static Path *TempDirectory;
189 Path::GetTemporaryDirectory(std::string* ErrMsg) {
191 #if defined(_MSC_VER)
192 // Visual Studio gets confused and emits a diagnostic about calling exists,
193 // even though this is the implementation for PathV1. Temporarily
194 // disable the deprecated warning message
195 #pragma warning(push)
196 #pragma warning(disable:4996)
198 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
199 #if defined(_MSC_VER)
202 return *TempDirectory;
205 char pathname[MAX_PATH];
206 if (!GetTempPath(MAX_PATH, pathname)) {
208 *ErrMsg = "Can't determine temporary directory";
213 result.set(pathname);
215 // Append a subdirectory based on our process id so multiple LLVMs don't
216 // step on each other's toes.
218 // Mingw's Win32 header files are broken.
219 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
221 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
223 result.appendComponent(pathname);
225 // If there's a directory left over from a previous LLVM execution that
226 // happened to have the same process id, get rid of it.
227 result.eraseFromDisk(true);
229 // And finally (re-)create the empty directory.
230 result.createDirectoryOnDisk(false);
231 TempDirectory = new Path(result);
232 return *TempDirectory;
236 Path::GetCurrentDirectory() {
237 char pathname[MAX_PATH];
238 ::GetCurrentDirectoryA(MAX_PATH,pathname);
239 return Path(pathname);
242 /// GetMainExecutable - Return the path to the main executable, given the
243 /// value of argv[0] from program startup.
244 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
245 char pathname[MAX_PATH];
246 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
247 return ret != MAX_PATH ? Path(pathname) : Path();
251 // FIXME: the above set of functions don't map to Windows very well.
254 Path::getSuffix() const {
255 // Find the last slash
256 size_t slash = path.rfind('/');
257 if (slash == std::string::npos)
262 size_t dot = path.rfind('.');
263 if (dot == std::string::npos || dot < slash)
264 return StringRef("");
266 return StringRef(path).substr(dot + 1);
270 Path::exists() const {
271 DWORD attr = GetFileAttributes(path.c_str());
272 return attr != INVALID_FILE_ATTRIBUTES;
276 Path::isDirectory() const {
277 DWORD attr = GetFileAttributes(path.c_str());
278 return (attr != INVALID_FILE_ATTRIBUTES) &&
279 (attr & FILE_ATTRIBUTE_DIRECTORY);
283 Path::isSymLink() const {
284 DWORD attributes = GetFileAttributes(path.c_str());
286 if (attributes == INVALID_FILE_ATTRIBUTES)
287 // There's no sane way to report this :(.
288 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
290 // This isn't exactly what defines a NTFS symlink, but it is only true for
291 // paths that act like a symlink.
292 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
296 Path::canRead() const {
297 // FIXME: take security attributes into account.
298 DWORD attr = GetFileAttributes(path.c_str());
299 return attr != INVALID_FILE_ATTRIBUTES;
303 Path::canWrite() const {
304 // FIXME: take security attributes into account.
305 DWORD attr = GetFileAttributes(path.c_str());
306 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
310 Path::canExecute() const {
311 // FIXME: take security attributes into account.
312 DWORD attr = GetFileAttributes(path.c_str());
313 return attr != INVALID_FILE_ATTRIBUTES;
317 Path::isRegularFile() const {
319 if (fs::is_regular_file(path, res))
325 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
326 if (!fsIsValid || update) {
327 WIN32_FILE_ATTRIBUTE_DATA fi;
328 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
329 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
330 ": Can't get status: ");
334 status.fileSize = fi.nFileSizeHigh;
335 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
336 status.fileSize += fi.nFileSizeLow;
338 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
339 status.user = 9999; // Not applicable to Windows, so...
340 status.group = 9999; // Not applicable to Windows, so...
342 // FIXME: this is only unique if the file is accessed by the same file path.
343 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
344 // numbers, but the concept doesn't exist in Windows.
346 for (unsigned i = 0; i < path.length(); ++i)
347 status.uniqueID += path[i];
350 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
351 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
352 status.modTime.fromWin32Time(ui.QuadPart);
354 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
360 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
361 // All files are readable on Windows (ignoring security attributes).
365 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
366 DWORD attr = GetFileAttributes(path.c_str());
368 // If it doesn't exist, we're done.
369 if (attr == INVALID_FILE_ATTRIBUTES)
372 if (attr & FILE_ATTRIBUTE_READONLY) {
373 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
374 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
382 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
383 WIN32_FILE_ATTRIBUTE_DATA fi;
384 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
385 MakeErrMsg(ErrMsg, path + ": can't get status of file");
389 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
391 *ErrMsg = path + ": not a directory";
397 std::string searchpath = path;
398 if (path.size() == 0 || searchpath[path.size()-1] == '/')
403 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
404 if (h == INVALID_HANDLE_VALUE) {
405 if (GetLastError() == ERROR_FILE_NOT_FOUND)
406 return true; // not really an error, now is it?
407 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
412 if (fd.cFileName[0] == '.')
415 aPath.appendComponent(&fd.cFileName[0]);
416 result.insert(aPath);
417 } while (FindNextFile(h, &fd));
419 DWORD err = GetLastError();
421 if (err != ERROR_NO_MORE_FILES) {
423 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
430 Path::set(StringRef a_path) {
433 std::string save(path);
435 FlipBackSlashes(path);
444 Path::appendComponent(StringRef name) {
447 std::string save(path);
449 size_t last = path.size() - 1;
450 if (path[last] != '/')
462 Path::eraseComponent() {
463 size_t slashpos = path.rfind('/',path.size());
464 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
466 std::string save(path);
467 path.erase(slashpos);
476 Path::eraseSuffix() {
477 size_t dotpos = path.rfind('.',path.size());
478 size_t slashpos = path.rfind('/',path.size());
479 if (dotpos != std::string::npos) {
480 if (slashpos == std::string::npos || dotpos > slashpos+1) {
481 std::string save(path);
482 path.erase(dotpos, path.size()-dotpos);
493 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
495 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
500 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
501 // Get a writeable copy of the path name
502 size_t len = path.length();
503 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
504 path.copy(pathname, len);
507 // Make sure it ends with a slash.
508 if (len == 0 || pathname[len - 1] != '/') {
513 // Determine starting point for initial / search.
514 char *next = pathname;
515 if (pathname[0] == '/' && pathname[1] == '/') {
517 next = strchr(pathname+2, '/');
519 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
522 next = strchr(next+1, '/');
524 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
528 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
531 if (pathname[1] == ':')
532 next += 2; // skip drive letter
534 next++; // skip root directory
537 // If we're supposed to create intermediate directories
538 if (create_parents) {
539 // Loop through the directory components until we're done
541 next = strchr(next, '/');
543 if (!CreateDirectory(pathname, NULL) &&
544 GetLastError() != ERROR_ALREADY_EXISTS)
545 return MakeErrMsg(ErrMsg,
546 std::string(pathname) + ": Can't create directory: ");
550 // Drop trailing slash.
552 if (!CreateDirectory(pathname, NULL) &&
553 GetLastError() != ERROR_ALREADY_EXISTS) {
554 return MakeErrMsg(ErrMsg, std::string(pathname) +
555 ": Can't create directory: ");
562 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
563 WIN32_FILE_ATTRIBUTE_DATA fi;
564 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
567 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
568 // If it doesn't exist, we're done.
570 if (fs::exists(path, Exists) || !Exists)
573 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
574 int lastchar = path.length() - 1 ;
575 path.copy(pathname, lastchar+1);
577 // Make path end with '/*'.
578 if (pathname[lastchar] != '/')
579 pathname[++lastchar] = '/';
580 pathname[lastchar+1] = '*';
581 pathname[lastchar+2] = 0;
583 if (remove_contents) {
585 HANDLE h = FindFirstFile(pathname, &fd);
587 // It's a bad idea to alter the contents of a directory while enumerating
588 // its contents. So build a list of its contents first, then destroy them.
590 if (h != INVALID_HANDLE_VALUE) {
591 std::vector<Path> list;
594 if (strcmp(fd.cFileName, ".") == 0)
596 if (strcmp(fd.cFileName, "..") == 0)
600 aPath.appendComponent(&fd.cFileName[0]);
601 list.push_back(aPath);
602 } while (FindNextFile(h, &fd));
604 DWORD err = GetLastError();
606 if (err != ERROR_NO_MORE_FILES) {
608 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
611 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
614 aPath.eraseFromDisk(true);
617 if (GetLastError() != ERROR_FILE_NOT_FOUND)
618 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
622 pathname[lastchar] = 0;
623 if (!RemoveDirectory(pathname))
624 return MakeErrMsg(ErrStr,
625 std::string(pathname) + ": Can't destroy directory: ");
628 // Read-only files cannot be deleted on Windows. Must remove the read-only
630 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
631 if (!SetFileAttributes(path.c_str(),
632 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
633 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
636 if (!DeleteFile(path.c_str()))
637 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
642 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
643 assert(len < 1024 && "Request for magic string too long");
644 char* buf = reinterpret_cast<char*>(alloca(len));
646 HANDLE h = CreateFile(path.c_str(),
651 FILE_ATTRIBUTE_NORMAL,
653 if (h == INVALID_HANDLE_VALUE)
657 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
660 if (!ret || nRead != len)
663 Magic = std::string(buf, len);
668 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
669 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
670 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
676 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
677 // FIXME: should work on directories also.
682 HANDLE h = CreateFile(path.c_str(),
683 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
684 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
687 FILE_ATTRIBUTE_NORMAL,
689 if (h == INVALID_HANDLE_VALUE)
692 BY_HANDLE_FILE_INFORMATION bhfi;
693 if (!GetFileInformationByHandle(h, &bhfi)) {
694 DWORD err = GetLastError();
697 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
701 ui.QuadPart = si.modTime.toWin32Time();
703 ft.dwLowDateTime = ui.LowPart;
704 ft.dwHighDateTime = ui.HighPart;
705 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
706 DWORD err = GetLastError();
710 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
713 // Best we can do with Unix permission bits is to interpret the owner
715 if (si.mode & 0200) {
716 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
717 if (!SetFileAttributes(path.c_str(),
718 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
719 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
722 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
723 if (!SetFileAttributes(path.c_str(),
724 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
725 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
733 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
735 if (reuse_current && (fs::exists(path, Exists) || !Exists))
736 return false; // File doesn't exist already, just use it!
738 // Reserve space for -XXXXXX at the end.
739 char *FNBuffer = (char*) alloca(path.size()+8);
740 unsigned offset = path.size();
741 path.copy(FNBuffer, offset);
743 // Find a numeric suffix that isn't used by an existing file. Assume there
744 // won't be more than 1 million files with the same prefix. Probably a safe
746 static int FCounter = -1;
748 // Give arbitrary initial seed.
749 // FIXME: We should use sys::fs::unique_file() in future.
751 DWORD x = GetCurrentProcessId();
752 x = (x << 16) | (x >> 16);
753 if (QueryPerformanceCounter(&cnt64)) // RDTSC
754 x ^= cnt64.HighPart ^ cnt64.LowPart;
755 FCounter = x % 1000000;
758 sprintf(FNBuffer+offset, "-%06u", FCounter);
759 if (++FCounter > 999999)
762 } while (!fs::exists(path, Exists) && Exists);
767 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
768 // Make this into a unique file name
769 makeUnique(reuse_current, ErrMsg);
771 // Now go and create it
772 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
773 FILE_ATTRIBUTE_NORMAL, NULL);
774 if (h == INVALID_HANDLE_VALUE)
775 return MakeErrMsg(ErrMsg, path + ": can't create file");