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::exists() const {
255 DWORD attr = GetFileAttributes(path.c_str());
256 return attr != INVALID_FILE_ATTRIBUTES;
260 Path::isDirectory() const {
261 DWORD attr = GetFileAttributes(path.c_str());
262 return (attr != INVALID_FILE_ATTRIBUTES) &&
263 (attr & FILE_ATTRIBUTE_DIRECTORY);
267 Path::isSymLink() const {
268 DWORD attributes = GetFileAttributes(path.c_str());
270 if (attributes == INVALID_FILE_ATTRIBUTES)
271 // There's no sane way to report this :(.
272 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
274 // This isn't exactly what defines a NTFS symlink, but it is only true for
275 // paths that act like a symlink.
276 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
280 Path::canRead() const {
281 // FIXME: take security attributes into account.
282 DWORD attr = GetFileAttributes(path.c_str());
283 return attr != INVALID_FILE_ATTRIBUTES;
287 Path::canWrite() const {
288 // FIXME: take security attributes into account.
289 DWORD attr = GetFileAttributes(path.c_str());
290 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
294 Path::canExecute() const {
295 // FIXME: take security attributes into account.
296 DWORD attr = GetFileAttributes(path.c_str());
297 return attr != INVALID_FILE_ATTRIBUTES;
301 Path::isRegularFile() const {
303 if (fs::is_regular_file(path, res))
309 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
310 if (!fsIsValid || update) {
311 WIN32_FILE_ATTRIBUTE_DATA fi;
312 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
313 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
314 ": Can't get status: ");
318 status.fileSize = fi.nFileSizeHigh;
319 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
320 status.fileSize += fi.nFileSizeLow;
322 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
323 status.user = 9999; // Not applicable to Windows, so...
324 status.group = 9999; // Not applicable to Windows, so...
326 // FIXME: this is only unique if the file is accessed by the same file path.
327 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
328 // numbers, but the concept doesn't exist in Windows.
330 for (unsigned i = 0; i < path.length(); ++i)
331 status.uniqueID += path[i];
334 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
335 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
336 status.modTime.fromWin32Time(ui.QuadPart);
338 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
344 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
345 // All files are readable on Windows (ignoring security attributes).
349 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
350 DWORD attr = GetFileAttributes(path.c_str());
352 // If it doesn't exist, we're done.
353 if (attr == INVALID_FILE_ATTRIBUTES)
356 if (attr & FILE_ATTRIBUTE_READONLY) {
357 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
358 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
366 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
367 WIN32_FILE_ATTRIBUTE_DATA fi;
368 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
369 MakeErrMsg(ErrMsg, path + ": can't get status of file");
373 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
375 *ErrMsg = path + ": not a directory";
381 std::string searchpath = path;
382 if (path.size() == 0 || searchpath[path.size()-1] == '/')
387 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
388 if (h == INVALID_HANDLE_VALUE) {
389 if (GetLastError() == ERROR_FILE_NOT_FOUND)
390 return true; // not really an error, now is it?
391 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
396 if (fd.cFileName[0] == '.')
399 aPath.appendComponent(&fd.cFileName[0]);
400 result.insert(aPath);
401 } while (FindNextFile(h, &fd));
403 DWORD err = GetLastError();
405 if (err != ERROR_NO_MORE_FILES) {
407 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
414 Path::set(StringRef a_path) {
417 std::string save(path);
419 FlipBackSlashes(path);
428 Path::appendComponent(StringRef name) {
431 std::string save(path);
433 size_t last = path.size() - 1;
434 if (path[last] != '/')
446 Path::eraseComponent() {
447 size_t slashpos = path.rfind('/',path.size());
448 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
450 std::string save(path);
451 path.erase(slashpos);
460 Path::eraseSuffix() {
461 size_t dotpos = path.rfind('.',path.size());
462 size_t slashpos = path.rfind('/',path.size());
463 if (dotpos != std::string::npos) {
464 if (slashpos == std::string::npos || dotpos > slashpos+1) {
465 std::string save(path);
466 path.erase(dotpos, path.size()-dotpos);
477 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
479 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
484 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
485 // Get a writeable copy of the path name
486 size_t len = path.length();
487 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
488 path.copy(pathname, len);
491 // Make sure it ends with a slash.
492 if (len == 0 || pathname[len - 1] != '/') {
497 // Determine starting point for initial / search.
498 char *next = pathname;
499 if (pathname[0] == '/' && pathname[1] == '/') {
501 next = strchr(pathname+2, '/');
503 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
506 next = strchr(next+1, '/');
508 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
512 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
515 if (pathname[1] == ':')
516 next += 2; // skip drive letter
518 next++; // skip root directory
521 // If we're supposed to create intermediate directories
522 if (create_parents) {
523 // Loop through the directory components until we're done
525 next = strchr(next, '/');
527 if (!CreateDirectory(pathname, NULL) &&
528 GetLastError() != ERROR_ALREADY_EXISTS)
529 return MakeErrMsg(ErrMsg,
530 std::string(pathname) + ": Can't create directory: ");
534 // Drop trailing slash.
536 if (!CreateDirectory(pathname, NULL) &&
537 GetLastError() != ERROR_ALREADY_EXISTS) {
538 return MakeErrMsg(ErrMsg, std::string(pathname) +
539 ": Can't create directory: ");
546 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
547 WIN32_FILE_ATTRIBUTE_DATA fi;
548 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
551 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
552 // If it doesn't exist, we're done.
554 if (fs::exists(path, Exists) || !Exists)
557 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
558 int lastchar = path.length() - 1 ;
559 path.copy(pathname, lastchar+1);
561 // Make path end with '/*'.
562 if (pathname[lastchar] != '/')
563 pathname[++lastchar] = '/';
564 pathname[lastchar+1] = '*';
565 pathname[lastchar+2] = 0;
567 if (remove_contents) {
569 HANDLE h = FindFirstFile(pathname, &fd);
571 // It's a bad idea to alter the contents of a directory while enumerating
572 // its contents. So build a list of its contents first, then destroy them.
574 if (h != INVALID_HANDLE_VALUE) {
575 std::vector<Path> list;
578 if (strcmp(fd.cFileName, ".") == 0)
580 if (strcmp(fd.cFileName, "..") == 0)
584 aPath.appendComponent(&fd.cFileName[0]);
585 list.push_back(aPath);
586 } while (FindNextFile(h, &fd));
588 DWORD err = GetLastError();
590 if (err != ERROR_NO_MORE_FILES) {
592 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
595 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
598 aPath.eraseFromDisk(true);
601 if (GetLastError() != ERROR_FILE_NOT_FOUND)
602 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
606 pathname[lastchar] = 0;
607 if (!RemoveDirectory(pathname))
608 return MakeErrMsg(ErrStr,
609 std::string(pathname) + ": Can't destroy directory: ");
612 // Read-only files cannot be deleted on Windows. Must remove the read-only
614 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
615 if (!SetFileAttributes(path.c_str(),
616 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
617 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
620 if (!DeleteFile(path.c_str()))
621 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
626 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
627 assert(len < 1024 && "Request for magic string too long");
628 char* buf = reinterpret_cast<char*>(alloca(len));
630 HANDLE h = CreateFile(path.c_str(),
635 FILE_ATTRIBUTE_NORMAL,
637 if (h == INVALID_HANDLE_VALUE)
641 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
644 if (!ret || nRead != len)
647 Magic = std::string(buf, len);
652 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
653 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
654 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
660 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
661 // FIXME: should work on directories also.
666 HANDLE h = CreateFile(path.c_str(),
667 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
668 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
671 FILE_ATTRIBUTE_NORMAL,
673 if (h == INVALID_HANDLE_VALUE)
676 BY_HANDLE_FILE_INFORMATION bhfi;
677 if (!GetFileInformationByHandle(h, &bhfi)) {
678 DWORD err = GetLastError();
681 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
685 ui.QuadPart = si.modTime.toWin32Time();
687 ft.dwLowDateTime = ui.LowPart;
688 ft.dwHighDateTime = ui.HighPart;
689 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
690 DWORD err = GetLastError();
694 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
697 // Best we can do with Unix permission bits is to interpret the owner
699 if (si.mode & 0200) {
700 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
701 if (!SetFileAttributes(path.c_str(),
702 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
703 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
706 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
707 if (!SetFileAttributes(path.c_str(),
708 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
709 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
717 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
719 if (reuse_current && (fs::exists(path, Exists) || !Exists))
720 return false; // File doesn't exist already, just use it!
722 // Reserve space for -XXXXXX at the end.
723 char *FNBuffer = (char*) alloca(path.size()+8);
724 unsigned offset = path.size();
725 path.copy(FNBuffer, offset);
727 // Find a numeric suffix that isn't used by an existing file. Assume there
728 // won't be more than 1 million files with the same prefix. Probably a safe
730 static int FCounter = -1;
732 // Give arbitrary initial seed.
733 // FIXME: We should use sys::fs::unique_file() in future.
735 DWORD x = GetCurrentProcessId();
736 x = (x << 16) | (x >> 16);
737 if (QueryPerformanceCounter(&cnt64)) // RDTSC
738 x ^= cnt64.HighPart ^ cnt64.LowPart;
739 FCounter = x % 1000000;
742 sprintf(FNBuffer+offset, "-%06u", FCounter);
743 if (++FCounter > 999999)
746 } while (!fs::exists(path, Exists) && Exists);
751 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
752 // Make this into a unique file name
753 makeUnique(reuse_current, ErrMsg);
755 // Now go and create it
756 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
757 FILE_ATTRIBUTE_NORMAL, NULL);
758 if (h == INVALID_HANDLE_VALUE)
759 return MakeErrMsg(ErrMsg, path + ": can't create file");