1 //===- llvm/System/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 // Modified by Henrik Bach to comply with at least MinGW.
9 // Ported to Win32 by Jeff Cohen.
11 //===----------------------------------------------------------------------===//
13 // This file provides the Win32 specific implementation of the Path class.
15 //===----------------------------------------------------------------------===//
17 //===----------------------------------------------------------------------===//
18 //=== WARNING: Implementation here must contain only generic Win32 code that
19 //=== is guaranteed to work on *all* Win32 variants.
20 //===----------------------------------------------------------------------===//
26 // We need to undo a macro defined in Windows.h, otherwise we won't compile:
28 #undef GetCurrentDirectory
30 // Windows happily accepts either forward or backward slashes, though any path
31 // returned by a Win32 API will have backward slashes. As LLVM code basically
32 // assumes forward slashes are used, backward slashs are converted where they
33 // can be introduced into a path.
35 // Another invariant is that a path ends with a slash if and only if the path
36 // is a root directory. Any other use of a trailing slash is stripped. Unlike
37 // in Unix, Windows has a rather complicated notion of a root path and this
38 // invariant helps simply the code.
40 static void FlipBackSlashes(std::string& s) {
41 for (size_t i = 0; i < s.size(); i++)
49 const char PathSeparator = ';';
51 StringRef Path::GetEXESuffix() {
55 Path::Path(llvm::StringRef p)
57 FlipBackSlashes(path);
60 Path::Path(const char *StrStart, unsigned StrLen)
61 : path(StrStart, StrLen) {
62 FlipBackSlashes(path);
66 Path::operator=(StringRef that) {
67 path.assign(that.data(), that.size());
68 FlipBackSlashes(path);
72 // push_back 0 on create, and pop_back on delete.
73 struct ScopedNullTerminator {
75 ScopedNullTerminator(std::string &s) : str(s) { str.push_back(0); }
76 ~ScopedNullTerminator() {
77 // str.pop_back(); But wait, C++03 doesn't have this...
78 assert(!str.empty() && str[str.size() - 1] == 0
79 && "Null char not present!");
80 str.resize(str.size() - 1);
85 Path::isValid() const {
89 // If there is a colon, it must be the second character, preceded by a letter
90 // and followed by something.
91 size_t len = path.size();
92 // This code assumes that path is null terminated, so make sure it is.
93 ScopedNullTerminator snt(path);
94 size_t pos = path.rfind(':',len);
96 if (pos != std::string::npos) {
97 if (pos != 1 || !isalpha(path[0]) || len < 3)
102 // Look for a UNC path, and if found adjust our notion of the root slash.
103 if (len > 3 && path[0] == '/' && path[1] == '/') {
104 rootslash = path.find('/', 2);
105 if (rootslash == std::string::npos)
109 // Check for illegal characters.
110 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
111 "\013\014\015\016\017\020\021\022\023\024\025\026"
112 "\027\030\031\032\033\034\035\036\037")
113 != std::string::npos)
116 // Remove trailing slash, unless it's a root slash.
117 if (len > rootslash+1 && path[len-1] == '/')
120 // Check each component for legality.
121 for (pos = 0; pos < len; ++pos) {
122 // A component may not end in a space.
123 if (path[pos] == ' ') {
124 if (path[pos+1] == '/' || path[pos+1] == '\0')
128 // A component may not end in a period.
129 if (path[pos] == '.') {
130 if (path[pos+1] == '/' || path[pos+1] == '\0') {
131 // Unless it is the pseudo-directory "."...
132 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
135 if (pos > 0 && path[pos-1] == '.') {
136 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
147 void Path::makeAbsolute() {
148 TCHAR FullPath[MAX_PATH + 1] = {0};
149 LPTSTR FilePart = NULL;
151 DWORD RetLength = ::GetFullPathNameA(path.c_str(),
152 sizeof(FullPath)/sizeof(FullPath[0]),
153 FullPath, &FilePart);
155 if (0 == RetLength) {
156 // FIXME: Report the error GetLastError()
157 assert(0 && "Unable to make absolute path!");
158 } else if (RetLength > MAX_PATH) {
159 // FIXME: Report too small buffer (needed RetLength bytes).
160 assert(0 && "Unable to make absolute path!");
167 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
169 // FIXME: This does not handle correctly an absolute path starting from
170 // a drive letter or in UNC format.
176 return NameStart[0] == '/';
179 (NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/')) ||
180 (NameStart[0] == '\\' || (NameStart[1] == ':' && NameStart[2] == '\\'));
185 Path::isAbsolute() const {
186 // FIXME: This does not handle correctly an absolute path starting from
187 // a drive letter or in UNC format.
188 switch (path.length()) {
193 return path[0] == '/';
195 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
199 static Path *TempDirectory;
202 Path::GetTemporaryDirectory(std::string* ErrMsg) {
204 return *TempDirectory;
206 char pathname[MAX_PATH];
207 if (!GetTempPath(MAX_PATH, pathname)) {
209 *ErrMsg = "Can't determine temporary directory";
214 result.set(pathname);
216 // Append a subdirectory passed on our process id so multiple LLVMs don't
217 // step on each other's toes.
219 // Mingw's Win32 header files are broken.
220 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
222 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
224 result.appendComponent(pathname);
226 // If there's a directory left over from a previous LLVM execution that
227 // happened to have the same process id, get rid of it.
228 result.eraseFromDisk(true);
230 // And finally (re-)create the empty directory.
231 result.createDirectoryOnDisk(false);
232 TempDirectory = new Path(result);
233 return *TempDirectory;
236 // FIXME: the following set of functions don't map to Windows very well.
238 Path::GetRootDirectory() {
245 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
246 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
247 Paths.push_back(sys::Path("C:/WINDOWS"));
251 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
252 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
254 getPathList(env_var,Paths);
259 if (tmpPath.set(LLVM_LIBDIR))
260 if (tmpPath.canRead())
261 Paths.push_back(tmpPath);
264 GetSystemLibraryPaths(Paths);
268 Path::GetLLVMDefaultConfigDir() {
269 // TODO: this isn't going to fly on Windows
270 return Path("/etc/llvm");
274 Path::GetUserHomeDirectory() {
275 // TODO: Typical Windows setup doesn't define HOME.
276 const char* home = getenv("HOME");
279 if (result.set(home))
282 return GetRootDirectory();
286 Path::GetCurrentDirectory() {
287 char pathname[MAX_PATH];
288 ::GetCurrentDirectoryA(MAX_PATH,pathname);
289 return Path(pathname);
292 /// GetMainExecutable - Return the path to the main executable, given the
293 /// value of argv[0] from program startup.
294 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
295 char pathname[MAX_PATH];
296 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
297 return ret != MAX_PATH ? Path(pathname) : Path();
301 // FIXME: the above set of functions don't map to Windows very well.
304 StringRef Path::getDirname() const {
305 return getDirnameCharSep(path, "/");
309 Path::getBasename() const {
310 // Find the last slash
311 size_t slash = path.rfind('/');
312 if (slash == std::string::npos)
317 size_t dot = path.rfind('.');
318 if (dot == std::string::npos || dot < slash)
319 return StringRef(path).substr(slash);
321 return StringRef(path).substr(slash, dot - slash);
325 Path::getSuffix() const {
326 // Find the last slash
327 size_t slash = path.rfind('/');
328 if (slash == std::string::npos)
333 size_t dot = path.rfind('.');
334 if (dot == std::string::npos || dot < slash)
335 return StringRef("");
337 return StringRef(path).substr(dot + 1);
341 Path::exists() const {
342 DWORD attr = GetFileAttributes(path.c_str());
343 return attr != INVALID_FILE_ATTRIBUTES;
347 Path::isDirectory() const {
348 DWORD attr = GetFileAttributes(path.c_str());
349 return (attr != INVALID_FILE_ATTRIBUTES) &&
350 (attr & FILE_ATTRIBUTE_DIRECTORY);
354 Path::canRead() const {
355 // FIXME: take security attributes into account.
356 DWORD attr = GetFileAttributes(path.c_str());
357 return attr != INVALID_FILE_ATTRIBUTES;
361 Path::canWrite() const {
362 // FIXME: take security attributes into account.
363 DWORD attr = GetFileAttributes(path.c_str());
364 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
368 Path::canExecute() const {
369 // FIXME: take security attributes into account.
370 DWORD attr = GetFileAttributes(path.c_str());
371 return attr != INVALID_FILE_ATTRIBUTES;
375 Path::isRegularFile() const {
382 Path::getLast() const {
383 // Find the last slash
384 size_t pos = path.rfind('/');
386 // Handle the corner cases
387 if (pos == std::string::npos)
390 // If the last character is a slash, we have a root directory
391 if (pos == path.length()-1)
394 // Return everything after the last slash
395 return StringRef(path).substr(pos+1);
399 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
400 if (!fsIsValid || update) {
401 WIN32_FILE_ATTRIBUTE_DATA fi;
402 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
403 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
404 ": Can't get status: ");
408 status.fileSize = fi.nFileSizeHigh;
409 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
410 status.fileSize += fi.nFileSizeLow;
412 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
413 status.user = 9999; // Not applicable to Windows, so...
414 status.group = 9999; // Not applicable to Windows, so...
416 // FIXME: this is only unique if the file is accessed by the same file path.
417 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
418 // numbers, but the concept doesn't exist in Windows.
420 for (unsigned i = 0; i < path.length(); ++i)
421 status.uniqueID += path[i];
424 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
425 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
426 status.modTime.fromWin32Time(ui.QuadPart);
428 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
434 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
435 // All files are readable on Windows (ignoring security attributes).
439 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
440 DWORD attr = GetFileAttributes(path.c_str());
442 // If it doesn't exist, we're done.
443 if (attr == INVALID_FILE_ATTRIBUTES)
446 if (attr & FILE_ATTRIBUTE_READONLY) {
447 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
448 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
455 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
456 // All files are executable on Windows (ignoring security attributes).
461 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
462 WIN32_FILE_ATTRIBUTE_DATA fi;
463 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
464 MakeErrMsg(ErrMsg, path + ": can't get status of file");
468 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
470 *ErrMsg = path + ": not a directory";
476 std::string searchpath = path;
477 if (path.size() == 0 || searchpath[path.size()-1] == '/')
482 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
483 if (h == INVALID_HANDLE_VALUE) {
484 if (GetLastError() == ERROR_FILE_NOT_FOUND)
485 return true; // not really an error, now is it?
486 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
491 if (fd.cFileName[0] == '.')
494 aPath.appendComponent(&fd.cFileName[0]);
495 result.insert(aPath);
496 } while (FindNextFile(h, &fd));
498 DWORD err = GetLastError();
500 if (err != ERROR_NO_MORE_FILES) {
502 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
509 Path::set(StringRef a_path) {
512 std::string save(path);
514 FlipBackSlashes(path);
523 Path::appendComponent(StringRef name) {
526 std::string save(path);
528 size_t last = path.size() - 1;
529 if (path[last] != '/')
541 Path::eraseComponent() {
542 size_t slashpos = path.rfind('/',path.size());
543 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
545 std::string save(path);
546 path.erase(slashpos);
555 Path::eraseSuffix() {
556 size_t dotpos = path.rfind('.',path.size());
557 size_t slashpos = path.rfind('/',path.size());
558 if (dotpos != std::string::npos) {
559 if (slashpos == std::string::npos || dotpos > slashpos+1) {
560 std::string save(path);
561 path.erase(dotpos, path.size()-dotpos);
572 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
574 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
579 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
580 // Get a writeable copy of the path name
581 size_t len = path.length();
582 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
583 path.copy(pathname, len);
586 // Make sure it ends with a slash.
587 if (len == 0 || pathname[len - 1] != '/') {
592 // Determine starting point for initial / search.
593 char *next = pathname;
594 if (pathname[0] == '/' && pathname[1] == '/') {
596 next = strchr(pathname+2, '/');
598 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
601 next = strchr(next+1, '/');
603 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
607 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
610 if (pathname[1] == ':')
611 next += 2; // skip drive letter
613 next++; // skip root directory
616 // If we're supposed to create intermediate directories
617 if (create_parents) {
618 // Loop through the directory components until we're done
620 next = strchr(next, '/');
622 if (!CreateDirectory(pathname, NULL) &&
623 GetLastError() != ERROR_ALREADY_EXISTS)
624 return MakeErrMsg(ErrMsg,
625 std::string(pathname) + ": Can't create directory: ");
629 // Drop trailing slash.
631 if (!CreateDirectory(pathname, NULL) &&
632 GetLastError() != ERROR_ALREADY_EXISTS) {
633 return MakeErrMsg(ErrMsg, std::string(pathname) +
634 ": Can't create directory: ");
641 Path::createFileOnDisk(std::string* ErrMsg) {
643 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
644 FILE_ATTRIBUTE_NORMAL, NULL);
645 if (h == INVALID_HANDLE_VALUE)
646 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
653 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
654 WIN32_FILE_ATTRIBUTE_DATA fi;
655 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
658 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
659 // If it doesn't exist, we're done.
663 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
664 int lastchar = path.length() - 1 ;
665 path.copy(pathname, lastchar+1);
667 // Make path end with '/*'.
668 if (pathname[lastchar] != '/')
669 pathname[++lastchar] = '/';
670 pathname[lastchar+1] = '*';
671 pathname[lastchar+2] = 0;
673 if (remove_contents) {
675 HANDLE h = FindFirstFile(pathname, &fd);
677 // It's a bad idea to alter the contents of a directory while enumerating
678 // its contents. So build a list of its contents first, then destroy them.
680 if (h != INVALID_HANDLE_VALUE) {
681 std::vector<Path> list;
684 if (strcmp(fd.cFileName, ".") == 0)
686 if (strcmp(fd.cFileName, "..") == 0)
690 aPath.appendComponent(&fd.cFileName[0]);
691 list.push_back(aPath);
692 } while (FindNextFile(h, &fd));
694 DWORD err = GetLastError();
696 if (err != ERROR_NO_MORE_FILES) {
698 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
701 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
704 aPath.eraseFromDisk(true);
707 if (GetLastError() != ERROR_FILE_NOT_FOUND)
708 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
712 pathname[lastchar] = 0;
713 if (!RemoveDirectory(pathname))
714 return MakeErrMsg(ErrStr,
715 std::string(pathname) + ": Can't destroy directory: ");
718 // Read-only files cannot be deleted on Windows. Must remove the read-only
720 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
721 if (!SetFileAttributes(path.c_str(),
722 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
723 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
726 if (!DeleteFile(path.c_str()))
727 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
732 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
733 assert(len < 1024 && "Request for magic string too long");
734 char* buf = reinterpret_cast<char*>(alloca(len));
736 HANDLE h = CreateFile(path.c_str(),
741 FILE_ATTRIBUTE_NORMAL,
743 if (h == INVALID_HANDLE_VALUE)
747 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
750 if (!ret || nRead != len)
753 Magic = std::string(buf, len);
758 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
759 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
760 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
766 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
767 // FIXME: should work on directories also.
772 HANDLE h = CreateFile(path.c_str(),
773 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
774 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
777 FILE_ATTRIBUTE_NORMAL,
779 if (h == INVALID_HANDLE_VALUE)
782 BY_HANDLE_FILE_INFORMATION bhfi;
783 if (!GetFileInformationByHandle(h, &bhfi)) {
784 DWORD err = GetLastError();
787 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
791 ui.QuadPart = si.modTime.toWin32Time();
793 ft.dwLowDateTime = ui.LowPart;
794 ft.dwHighDateTime = ui.HighPart;
795 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
796 DWORD err = GetLastError();
800 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
803 // Best we can do with Unix permission bits is to interpret the owner
805 if (si.mode & 0200) {
806 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
807 if (!SetFileAttributes(path.c_str(),
808 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
809 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
812 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
813 if (!SetFileAttributes(path.c_str(),
814 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
815 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
823 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
824 // Can't use CopyFile macro defined in Windows.h because it would mess up the
825 // above line. We use the expansion it would have in a non-UNICODE build.
826 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
827 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
828 "' to '" + Dest.str() + "': ");
833 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
834 if (reuse_current && !exists())
835 return false; // File doesn't exist already, just use it!
837 // Reserve space for -XXXXXX at the end.
838 char *FNBuffer = (char*) alloca(path.size()+8);
839 unsigned offset = path.size();
840 path.copy(FNBuffer, offset);
842 // Find a numeric suffix that isn't used by an existing file. Assume there
843 // won't be more than 1 million files with the same prefix. Probably a safe
845 static unsigned FCounter = 0;
847 sprintf(FNBuffer+offset, "-%06u", FCounter);
848 if (++FCounter > 999999)
856 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
857 // Make this into a unique file name
858 makeUnique(reuse_current, ErrMsg);
860 // Now go and create it
861 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
862 FILE_ATTRIBUTE_NORMAL, NULL);
863 if (h == INVALID_HANDLE_VALUE)
864 return MakeErrMsg(ErrMsg, path + ": can't create file");
870 /// MapInFilePages - Not yet implemented on win32.
871 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
875 /// MapInFilePages - Not yet implemented on win32.
876 void Path::UnMapFilePages(const char *Base, uint64_t FileSize) {
877 assert(0 && "NOT IMPLEMENTED");