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:
25 #undef GetCurrentDirectory
27 // Windows happily accepts either forward or backward slashes, though any path
28 // returned by a Win32 API will have backward slashes. As LLVM code basically
29 // assumes forward slashes are used, backward slashs are converted where they
30 // can be introduced into a path.
32 // Another invariant is that a path ends with a slash if and only if the path
33 // is a root directory. Any other use of a trailing slash is stripped. Unlike
34 // in Unix, Windows has a rather complicated notion of a root path and this
35 // invariant helps simply the code.
37 static void FlipBackSlashes(std::string& s) {
38 for (size_t i = 0; i < s.size(); i++)
46 const char PathSeparator = ';';
48 StringRef Path::GetEXESuffix() {
52 Path::Path(llvm::StringRef p)
54 FlipBackSlashes(path);
57 Path::Path(const char *StrStart, unsigned StrLen)
58 : path(StrStart, StrLen) {
59 FlipBackSlashes(path);
63 Path::operator=(StringRef that) {
64 path.assign(that.data(), that.size());
65 FlipBackSlashes(path);
69 // push_back 0 on create, and pop_back on delete.
70 struct ScopedNullTerminator {
72 ScopedNullTerminator(std::string &s) : str(s) { str.push_back(0); }
73 ~ScopedNullTerminator() {
74 // str.pop_back(); But wait, C++03 doesn't have this...
75 assert(!str.empty() && str[str.size() - 1] == 0
76 && "Null char not present!");
77 str.resize(str.size() - 1);
82 Path::isValid() const {
86 // If there is a colon, it must be the second character, preceded by a letter
87 // and followed by something.
88 size_t len = path.size();
89 // This code assumes that path is null terminated, so make sure it is.
90 ScopedNullTerminator snt(path);
91 size_t pos = path.rfind(':',len);
93 if (pos != std::string::npos) {
94 if (pos != 1 || !isalpha(path[0]) || len < 3)
99 // Look for a UNC path, and if found adjust our notion of the root slash.
100 if (len > 3 && path[0] == '/' && path[1] == '/') {
101 rootslash = path.find('/', 2);
102 if (rootslash == std::string::npos)
106 // Check for illegal characters.
107 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
108 "\013\014\015\016\017\020\021\022\023\024\025\026"
109 "\027\030\031\032\033\034\035\036\037")
110 != std::string::npos)
113 // Remove trailing slash, unless it's a root slash.
114 if (len > rootslash+1 && path[len-1] == '/')
117 // Check each component for legality.
118 for (pos = 0; pos < len; ++pos) {
119 // A component may not end in a space.
120 if (path[pos] == ' ') {
121 if (path[pos+1] == '/' || path[pos+1] == '\0')
125 // A component may not end in a period.
126 if (path[pos] == '.') {
127 if (path[pos+1] == '/' || path[pos+1] == '\0') {
128 // Unless it is the pseudo-directory "."...
129 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
132 if (pos > 0 && path[pos-1] == '.') {
133 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
144 void Path::makeAbsolute() {
145 TCHAR FullPath[MAX_PATH + 1] = {0};
146 LPTSTR FilePart = NULL;
148 DWORD RetLength = ::GetFullPathNameA(path.c_str(),
149 sizeof(FullPath)/sizeof(FullPath[0]),
150 FullPath, &FilePart);
152 if (0 == RetLength) {
153 // FIXME: Report the error GetLastError()
154 assert(0 && "Unable to make absolute path!");
155 } else if (RetLength > MAX_PATH) {
156 // FIXME: Report too small buffer (needed RetLength bytes).
157 assert(0 && "Unable to make absolute path!");
164 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
166 // FIXME: This does not handle correctly an absolute path starting from
167 // a drive letter or in UNC format.
173 return NameStart[0] == '/';
176 (NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/')) ||
177 (NameStart[0] == '\\' || (NameStart[1] == ':' && NameStart[2] == '\\'));
182 Path::isAbsolute() const {
183 // FIXME: This does not handle correctly an absolute path starting from
184 // a drive letter or in UNC format.
185 switch (path.length()) {
190 return path[0] == '/';
192 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
196 static Path *TempDirectory;
199 Path::GetTemporaryDirectory(std::string* ErrMsg) {
201 return *TempDirectory;
203 char pathname[MAX_PATH];
204 if (!GetTempPath(MAX_PATH, pathname)) {
206 *ErrMsg = "Can't determine temporary directory";
211 result.set(pathname);
213 // Append a subdirectory passed on our process id so multiple LLVMs don't
214 // step on each other's toes.
216 // Mingw's Win32 header files are broken.
217 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
219 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
221 result.appendComponent(pathname);
223 // If there's a directory left over from a previous LLVM execution that
224 // happened to have the same process id, get rid of it.
225 result.eraseFromDisk(true);
227 // And finally (re-)create the empty directory.
228 result.createDirectoryOnDisk(false);
229 TempDirectory = new Path(result);
230 return *TempDirectory;
233 // FIXME: the following set of functions don't map to Windows very well.
235 Path::GetRootDirectory() {
236 // This is the only notion that that Windows has of a root directory. Nothing
237 // is here except for drives.
238 return Path("file:///");
242 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
244 // Generic form of C:\Windows\System32
245 HRESULT res = SHGetFolderPathA(NULL,
246 CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
251 assert(0 && "Failed to get system directory");
254 Paths.push_back(sys::Path(buff));
258 // Generic form of C:\Windows
259 res = SHGetFolderPathA(NULL,
260 CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
265 assert(0 && "Failed to get windows directory");
268 Paths.push_back(sys::Path(buff));
272 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
273 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
275 getPathList(env_var,Paths);
280 if (tmpPath.set(LLVM_LIBDIR))
281 if (tmpPath.canRead())
282 Paths.push_back(tmpPath);
285 GetSystemLibraryPaths(Paths);
289 Path::GetLLVMDefaultConfigDir() {
290 Path ret = GetUserHomeDirectory();
291 if (!ret.appendComponent(".llvm"))
292 assert(0 && "Failed to append .llvm");
297 Path::GetUserHomeDirectory() {
299 HRESULT res = SHGetFolderPathA(NULL,
300 CSIDL_FLAG_CREATE | CSIDL_APPDATA,
305 assert(0 && "Failed to get user home directory");
310 Path::GetCurrentDirectory() {
311 char pathname[MAX_PATH];
312 ::GetCurrentDirectoryA(MAX_PATH,pathname);
313 return Path(pathname);
316 /// GetMainExecutable - Return the path to the main executable, given the
317 /// value of argv[0] from program startup.
318 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
319 char pathname[MAX_PATH];
320 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
321 return ret != MAX_PATH ? Path(pathname) : Path();
325 // FIXME: the above set of functions don't map to Windows very well.
328 StringRef Path::getDirname() const {
329 return getDirnameCharSep(path, "/");
333 Path::getBasename() const {
334 // Find the last slash
335 size_t slash = path.rfind('/');
336 if (slash == std::string::npos)
341 size_t dot = path.rfind('.');
342 if (dot == std::string::npos || dot < slash)
343 return StringRef(path).substr(slash);
345 return StringRef(path).substr(slash, dot - slash);
349 Path::getSuffix() const {
350 // Find the last slash
351 size_t slash = path.rfind('/');
352 if (slash == std::string::npos)
357 size_t dot = path.rfind('.');
358 if (dot == std::string::npos || dot < slash)
359 return StringRef("");
361 return StringRef(path).substr(dot + 1);
365 Path::exists() const {
366 DWORD attr = GetFileAttributes(path.c_str());
367 return attr != INVALID_FILE_ATTRIBUTES;
371 Path::isDirectory() const {
372 DWORD attr = GetFileAttributes(path.c_str());
373 return (attr != INVALID_FILE_ATTRIBUTES) &&
374 (attr & FILE_ATTRIBUTE_DIRECTORY);
378 Path::isSymLink() const {
379 DWORD attributes = GetFileAttributes(path.c_str());
381 if (attributes == INVALID_FILE_ATTRIBUTES)
382 // There's no sane way to report this :(.
383 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
385 // This isn't exactly what defines a NTFS symlink, but it is only true for
386 // paths that act like a symlink.
387 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
391 Path::canRead() const {
392 // FIXME: take security attributes into account.
393 DWORD attr = GetFileAttributes(path.c_str());
394 return attr != INVALID_FILE_ATTRIBUTES;
398 Path::canWrite() const {
399 // FIXME: take security attributes into account.
400 DWORD attr = GetFileAttributes(path.c_str());
401 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
405 Path::canExecute() const {
406 // FIXME: take security attributes into account.
407 DWORD attr = GetFileAttributes(path.c_str());
408 return attr != INVALID_FILE_ATTRIBUTES;
412 Path::isRegularFile() const {
419 Path::getLast() const {
420 // Find the last slash
421 size_t pos = path.rfind('/');
423 // Handle the corner cases
424 if (pos == std::string::npos)
427 // If the last character is a slash, we have a root directory
428 if (pos == path.length()-1)
431 // Return everything after the last slash
432 return StringRef(path).substr(pos+1);
436 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
437 if (!fsIsValid || update) {
438 WIN32_FILE_ATTRIBUTE_DATA fi;
439 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
440 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
441 ": Can't get status: ");
445 status.fileSize = fi.nFileSizeHigh;
446 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
447 status.fileSize += fi.nFileSizeLow;
449 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
450 status.user = 9999; // Not applicable to Windows, so...
451 status.group = 9999; // Not applicable to Windows, so...
453 // FIXME: this is only unique if the file is accessed by the same file path.
454 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
455 // numbers, but the concept doesn't exist in Windows.
457 for (unsigned i = 0; i < path.length(); ++i)
458 status.uniqueID += path[i];
461 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
462 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
463 status.modTime.fromWin32Time(ui.QuadPart);
465 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
471 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
472 // All files are readable on Windows (ignoring security attributes).
476 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
477 DWORD attr = GetFileAttributes(path.c_str());
479 // If it doesn't exist, we're done.
480 if (attr == INVALID_FILE_ATTRIBUTES)
483 if (attr & FILE_ATTRIBUTE_READONLY) {
484 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
485 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
492 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
493 // All files are executable on Windows (ignoring security attributes).
498 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
499 WIN32_FILE_ATTRIBUTE_DATA fi;
500 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
501 MakeErrMsg(ErrMsg, path + ": can't get status of file");
505 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
507 *ErrMsg = path + ": not a directory";
513 std::string searchpath = path;
514 if (path.size() == 0 || searchpath[path.size()-1] == '/')
519 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
520 if (h == INVALID_HANDLE_VALUE) {
521 if (GetLastError() == ERROR_FILE_NOT_FOUND)
522 return true; // not really an error, now is it?
523 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
528 if (fd.cFileName[0] == '.')
531 aPath.appendComponent(&fd.cFileName[0]);
532 result.insert(aPath);
533 } while (FindNextFile(h, &fd));
535 DWORD err = GetLastError();
537 if (err != ERROR_NO_MORE_FILES) {
539 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
546 Path::set(StringRef a_path) {
549 std::string save(path);
551 FlipBackSlashes(path);
560 Path::appendComponent(StringRef name) {
563 std::string save(path);
565 size_t last = path.size() - 1;
566 if (path[last] != '/')
578 Path::eraseComponent() {
579 size_t slashpos = path.rfind('/',path.size());
580 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
582 std::string save(path);
583 path.erase(slashpos);
592 Path::eraseSuffix() {
593 size_t dotpos = path.rfind('.',path.size());
594 size_t slashpos = path.rfind('/',path.size());
595 if (dotpos != std::string::npos) {
596 if (slashpos == std::string::npos || dotpos > slashpos+1) {
597 std::string save(path);
598 path.erase(dotpos, path.size()-dotpos);
609 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
611 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
616 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
617 // Get a writeable copy of the path name
618 size_t len = path.length();
619 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
620 path.copy(pathname, len);
623 // Make sure it ends with a slash.
624 if (len == 0 || pathname[len - 1] != '/') {
629 // Determine starting point for initial / search.
630 char *next = pathname;
631 if (pathname[0] == '/' && pathname[1] == '/') {
633 next = strchr(pathname+2, '/');
635 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
638 next = strchr(next+1, '/');
640 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
644 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
647 if (pathname[1] == ':')
648 next += 2; // skip drive letter
650 next++; // skip root directory
653 // If we're supposed to create intermediate directories
654 if (create_parents) {
655 // Loop through the directory components until we're done
657 next = strchr(next, '/');
659 if (!CreateDirectory(pathname, NULL) &&
660 GetLastError() != ERROR_ALREADY_EXISTS)
661 return MakeErrMsg(ErrMsg,
662 std::string(pathname) + ": Can't create directory: ");
666 // Drop trailing slash.
668 if (!CreateDirectory(pathname, NULL) &&
669 GetLastError() != ERROR_ALREADY_EXISTS) {
670 return MakeErrMsg(ErrMsg, std::string(pathname) +
671 ": Can't create directory: ");
678 Path::createFileOnDisk(std::string* ErrMsg) {
680 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
681 FILE_ATTRIBUTE_NORMAL, NULL);
682 if (h == INVALID_HANDLE_VALUE)
683 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
690 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
691 WIN32_FILE_ATTRIBUTE_DATA fi;
692 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
695 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
696 // If it doesn't exist, we're done.
700 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
701 int lastchar = path.length() - 1 ;
702 path.copy(pathname, lastchar+1);
704 // Make path end with '/*'.
705 if (pathname[lastchar] != '/')
706 pathname[++lastchar] = '/';
707 pathname[lastchar+1] = '*';
708 pathname[lastchar+2] = 0;
710 if (remove_contents) {
712 HANDLE h = FindFirstFile(pathname, &fd);
714 // It's a bad idea to alter the contents of a directory while enumerating
715 // its contents. So build a list of its contents first, then destroy them.
717 if (h != INVALID_HANDLE_VALUE) {
718 std::vector<Path> list;
721 if (strcmp(fd.cFileName, ".") == 0)
723 if (strcmp(fd.cFileName, "..") == 0)
727 aPath.appendComponent(&fd.cFileName[0]);
728 list.push_back(aPath);
729 } while (FindNextFile(h, &fd));
731 DWORD err = GetLastError();
733 if (err != ERROR_NO_MORE_FILES) {
735 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
738 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
741 aPath.eraseFromDisk(true);
744 if (GetLastError() != ERROR_FILE_NOT_FOUND)
745 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
749 pathname[lastchar] = 0;
750 if (!RemoveDirectory(pathname))
751 return MakeErrMsg(ErrStr,
752 std::string(pathname) + ": Can't destroy directory: ");
755 // Read-only files cannot be deleted on Windows. Must remove the read-only
757 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
758 if (!SetFileAttributes(path.c_str(),
759 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
760 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
763 if (!DeleteFile(path.c_str()))
764 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
769 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
770 assert(len < 1024 && "Request for magic string too long");
771 char* buf = reinterpret_cast<char*>(alloca(len));
773 HANDLE h = CreateFile(path.c_str(),
778 FILE_ATTRIBUTE_NORMAL,
780 if (h == INVALID_HANDLE_VALUE)
784 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
787 if (!ret || nRead != len)
790 Magic = std::string(buf, len);
795 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
796 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
797 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
803 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
804 // FIXME: should work on directories also.
809 HANDLE h = CreateFile(path.c_str(),
810 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
811 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
814 FILE_ATTRIBUTE_NORMAL,
816 if (h == INVALID_HANDLE_VALUE)
819 BY_HANDLE_FILE_INFORMATION bhfi;
820 if (!GetFileInformationByHandle(h, &bhfi)) {
821 DWORD err = GetLastError();
824 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
828 ui.QuadPart = si.modTime.toWin32Time();
830 ft.dwLowDateTime = ui.LowPart;
831 ft.dwHighDateTime = ui.HighPart;
832 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
833 DWORD err = GetLastError();
837 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
840 // Best we can do with Unix permission bits is to interpret the owner
842 if (si.mode & 0200) {
843 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
844 if (!SetFileAttributes(path.c_str(),
845 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
846 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
849 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
850 if (!SetFileAttributes(path.c_str(),
851 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
852 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
860 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
861 // Can't use CopyFile macro defined in Windows.h because it would mess up the
862 // above line. We use the expansion it would have in a non-UNICODE build.
863 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
864 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
865 "' to '" + Dest.str() + "': ");
870 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
871 if (reuse_current && !exists())
872 return false; // File doesn't exist already, just use it!
874 // Reserve space for -XXXXXX at the end.
875 char *FNBuffer = (char*) alloca(path.size()+8);
876 unsigned offset = path.size();
877 path.copy(FNBuffer, offset);
879 // Find a numeric suffix that isn't used by an existing file. Assume there
880 // won't be more than 1 million files with the same prefix. Probably a safe
882 static unsigned FCounter = 0;
884 sprintf(FNBuffer+offset, "-%06u", FCounter);
885 if (++FCounter > 999999)
893 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
894 // Make this into a unique file name
895 makeUnique(reuse_current, ErrMsg);
897 // Now go and create it
898 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
899 FILE_ATTRIBUTE_NORMAL, NULL);
900 if (h == INVALID_HANDLE_VALUE)
901 return MakeErrMsg(ErrMsg, path + ": can't create file");
907 /// MapInFilePages - Not yet implemented on win32.
908 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
912 /// MapInFilePages - Not yet implemented on win32.
913 void Path::UnMapFilePages(const char *Base, uint64_t FileSize) {
914 assert(0 && "NOT IMPLEMENTED");