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++)
48 const char PathSeparator = ';';
50 Path::Path(const std::string& p)
52 FlipBackSlashes(path);
55 Path::Path(const char *StrStart, unsigned StrLen)
56 : path(StrStart, StrLen) {
57 FlipBackSlashes(path);
61 Path::operator=(const std::string &that) {
63 FlipBackSlashes(path);
68 Path::isValid() const {
72 // If there is a colon, it must be the second character, preceded by a letter
73 // and followed by something.
74 size_t len = path.size();
75 size_t pos = path.rfind(':',len);
77 if (pos != std::string::npos) {
78 if (pos != 1 || !isalpha(path[0]) || len < 3)
83 // Look for a UNC path, and if found adjust our notion of the root slash.
84 if (len > 3 && path[0] == '/' && path[1] == '/') {
85 rootslash = path.find('/', 2);
86 if (rootslash == std::string::npos)
90 // Check for illegal characters.
91 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
92 "\013\014\015\016\017\020\021\022\023\024\025\026"
93 "\027\030\031\032\033\034\035\036\037")
97 // Remove trailing slash, unless it's a root slash.
98 if (len > rootslash+1 && path[len-1] == '/')
101 // Check each component for legality.
102 for (pos = 0; pos < len; ++pos) {
103 // A component may not end in a space.
104 if (path[pos] == ' ') {
105 if (path[pos+1] == '/' || path[pos+1] == '\0')
109 // A component may not end in a period.
110 if (path[pos] == '.') {
111 if (path[pos+1] == '/' || path[pos+1] == '\0') {
112 // Unless it is the pseudo-directory "."...
113 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
116 if (pos > 0 && path[pos-1] == '.') {
117 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
129 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
136 return NameStart[0] == '/';
138 return NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/');
143 Path::isAbsolute() const {
144 switch (path.length()) {
149 return path[0] == '/';
151 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
155 static Path *TempDirectory = NULL;
158 Path::GetTemporaryDirectory(std::string* ErrMsg) {
160 return *TempDirectory;
162 char pathname[MAX_PATH];
163 if (!GetTempPath(MAX_PATH, pathname)) {
165 *ErrMsg = "Can't determine temporary directory";
170 result.set(pathname);
172 // Append a subdirectory passed on our process id so multiple LLVMs don't
173 // step on each other's toes.
175 // Mingw's Win32 header files are broken.
176 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
178 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
180 result.appendComponent(pathname);
182 // If there's a directory left over from a previous LLVM execution that
183 // happened to have the same process id, get rid of it.
184 result.eraseFromDisk(true);
186 // And finally (re-)create the empty directory.
187 result.createDirectoryOnDisk(false);
188 TempDirectory = new Path(result);
189 return *TempDirectory;
192 // FIXME: the following set of functions don't map to Windows very well.
194 Path::GetRootDirectory() {
201 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
202 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
203 Paths.push_back(sys::Path("C:/WINDOWS"));
207 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
208 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
210 getPathList(env_var,Paths);
215 if (tmpPath.set(LLVM_LIBDIR))
216 if (tmpPath.canRead())
217 Paths.push_back(tmpPath);
220 GetSystemLibraryPaths(Paths);
224 Path::GetLLVMDefaultConfigDir() {
225 // TODO: this isn't going to fly on Windows
226 return Path("/etc/llvm");
230 Path::GetUserHomeDirectory() {
231 // TODO: Typical Windows setup doesn't define HOME.
232 const char* home = getenv("HOME");
235 if (result.set(home))
238 return GetRootDirectory();
242 Path::GetCurrentDirectory() {
243 char pathname[MAX_PATH];
244 ::GetCurrentDirectoryA(MAX_PATH,pathname);
245 return Path(pathname);
248 /// GetMainExecutable - Return the path to the main executable, given the
249 /// value of argv[0] from program startup.
250 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
251 char pathname[MAX_PATH];
252 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
253 return ret != MAX_PATH ? Path(pathname) : Path();
257 // FIXME: the above set of functions don't map to Windows very well.
261 Path::isRootDirectory() const {
262 size_t len = path.size();
263 return len > 0 && path[len-1] == '/';
266 std::string Path::getDirname() const {
267 return getDirnameCharSep(path, '/');
271 Path::getBasename() const {
272 // Find the last slash
273 size_t slash = path.rfind('/');
274 if (slash == std::string::npos)
279 size_t dot = path.rfind('.');
280 if (dot == std::string::npos || dot < slash)
281 return path.substr(slash);
283 return path.substr(slash, dot - slash);
287 Path::getSuffix() const {
288 // Find the last slash
289 size_t slash = path.rfind('/');
290 if (slash == std::string::npos)
295 size_t dot = path.rfind('.');
296 if (dot == std::string::npos || dot < slash)
297 return std::string();
299 return path.substr(dot + 1);
303 Path::exists() const {
304 DWORD attr = GetFileAttributes(path.c_str());
305 return attr != INVALID_FILE_ATTRIBUTES;
309 Path::isDirectory() const {
310 DWORD attr = GetFileAttributes(path.c_str());
311 return (attr != INVALID_FILE_ATTRIBUTES) &&
312 (attr & FILE_ATTRIBUTE_DIRECTORY);
316 Path::canRead() const {
317 // FIXME: take security attributes into account.
318 DWORD attr = GetFileAttributes(path.c_str());
319 return attr != INVALID_FILE_ATTRIBUTES;
323 Path::canWrite() const {
324 // FIXME: take security attributes into account.
325 DWORD attr = GetFileAttributes(path.c_str());
326 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
330 Path::canExecute() const {
331 // FIXME: take security attributes into account.
332 DWORD attr = GetFileAttributes(path.c_str());
333 return attr != INVALID_FILE_ATTRIBUTES;
337 Path::getLast() const {
338 // Find the last slash
339 size_t pos = path.rfind('/');
341 // Handle the corner cases
342 if (pos == std::string::npos)
345 // If the last character is a slash, we have a root directory
346 if (pos == path.length()-1)
349 // Return everything after the last slash
350 return path.substr(pos+1);
354 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
355 if (!fsIsValid || update) {
356 WIN32_FILE_ATTRIBUTE_DATA fi;
357 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
358 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
359 ": Can't get status: ");
363 status.fileSize = fi.nFileSizeHigh;
364 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
365 status.fileSize += fi.nFileSizeLow;
367 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
368 status.user = 9999; // Not applicable to Windows, so...
369 status.group = 9999; // Not applicable to Windows, so...
371 // FIXME: this is only unique if the file is accessed by the same file path.
372 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
373 // numbers, but the concept doesn't exist in Windows.
375 for (unsigned i = 0; i < path.length(); ++i)
376 status.uniqueID += path[i];
378 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
379 status.modTime.fromWin32Time(ft);
381 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
387 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
388 // All files are readable on Windows (ignoring security attributes).
392 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
393 DWORD attr = GetFileAttributes(path.c_str());
395 // If it doesn't exist, we're done.
396 if (attr == INVALID_FILE_ATTRIBUTES)
399 if (attr & FILE_ATTRIBUTE_READONLY) {
400 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
401 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
408 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
409 // All files are executable on Windows (ignoring security attributes).
414 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
415 WIN32_FILE_ATTRIBUTE_DATA fi;
416 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
417 MakeErrMsg(ErrMsg, path + ": can't get status of file");
421 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
423 *ErrMsg = path + ": not a directory";
429 std::string searchpath = path;
430 if (path.size() == 0 || searchpath[path.size()-1] == '/')
435 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
436 if (h == INVALID_HANDLE_VALUE) {
437 if (GetLastError() == ERROR_FILE_NOT_FOUND)
438 return true; // not really an error, now is it?
439 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
444 if (fd.cFileName[0] == '.')
447 aPath.appendComponent(&fd.cFileName[0]);
448 result.insert(aPath);
449 } while (FindNextFile(h, &fd));
451 DWORD err = GetLastError();
453 if (err != ERROR_NO_MORE_FILES) {
455 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
462 Path::set(const std::string& a_path) {
465 std::string save(path);
467 FlipBackSlashes(path);
476 Path::appendComponent(const std::string& name) {
479 std::string save(path);
481 size_t last = path.size() - 1;
482 if (path[last] != '/')
494 Path::eraseComponent() {
495 size_t slashpos = path.rfind('/',path.size());
496 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
498 std::string save(path);
499 path.erase(slashpos);
508 Path::appendSuffix(const std::string& suffix) {
509 std::string save(path);
520 Path::eraseSuffix() {
521 size_t dotpos = path.rfind('.',path.size());
522 size_t slashpos = path.rfind('/',path.size());
523 if (dotpos != std::string::npos) {
524 if (slashpos == std::string::npos || dotpos > slashpos+1) {
525 std::string save(path);
526 path.erase(dotpos, path.size()-dotpos);
537 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
539 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
544 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
545 // Get a writeable copy of the path name
546 size_t len = path.length();
547 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
548 path.copy(pathname, len);
551 // Make sure it ends with a slash.
552 if (len == 0 || pathname[len - 1] != '/') {
557 // Determine starting point for initial / search.
558 char *next = pathname;
559 if (pathname[0] == '/' && pathname[1] == '/') {
561 next = strchr(pathname+2, '/');
563 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
566 next = strchr(next+1, '/');
568 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
572 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
575 if (pathname[1] == ':')
576 next += 2; // skip drive letter
578 next++; // skip root directory
581 // If we're supposed to create intermediate directories
582 if (create_parents) {
583 // Loop through the directory components until we're done
585 next = strchr(next, '/');
587 if (!CreateDirectory(pathname, NULL))
588 return MakeErrMsg(ErrMsg,
589 std::string(pathname) + ": Can't create directory: ");
593 // Drop trailing slash.
595 if (!CreateDirectory(pathname, NULL)) {
596 return MakeErrMsg(ErrMsg, std::string(pathname) + ": Can't create directory: ");
603 Path::createFileOnDisk(std::string* ErrMsg) {
605 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
606 FILE_ATTRIBUTE_NORMAL, NULL);
607 if (h == INVALID_HANDLE_VALUE)
608 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
615 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
616 WIN32_FILE_ATTRIBUTE_DATA fi;
617 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
620 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
621 // If it doesn't exist, we're done.
625 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
626 int lastchar = path.length() - 1 ;
627 path.copy(pathname, lastchar+1);
629 // Make path end with '/*'.
630 if (pathname[lastchar] != '/')
631 pathname[++lastchar] = '/';
632 pathname[lastchar+1] = '*';
633 pathname[lastchar+2] = 0;
635 if (remove_contents) {
637 HANDLE h = FindFirstFile(pathname, &fd);
639 // It's a bad idea to alter the contents of a directory while enumerating
640 // its contents. So build a list of its contents first, then destroy them.
642 if (h != INVALID_HANDLE_VALUE) {
643 std::vector<Path> list;
646 if (strcmp(fd.cFileName, ".") == 0)
648 if (strcmp(fd.cFileName, "..") == 0)
652 aPath.appendComponent(&fd.cFileName[0]);
653 list.push_back(aPath);
654 } while (FindNextFile(h, &fd));
656 DWORD err = GetLastError();
658 if (err != ERROR_NO_MORE_FILES) {
660 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
663 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
666 aPath.eraseFromDisk(true);
669 if (GetLastError() != ERROR_FILE_NOT_FOUND)
670 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
674 pathname[lastchar] = 0;
675 if (!RemoveDirectory(pathname))
676 return MakeErrMsg(ErrStr,
677 std::string(pathname) + ": Can't destroy directory: ");
680 // Read-only files cannot be deleted on Windows. Must remove the read-only
682 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
683 if (!SetFileAttributes(path.c_str(),
684 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
685 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
688 if (!DeleteFile(path.c_str()))
689 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
694 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
695 assert(len < 1024 && "Request for magic string too long");
696 char* buf = (char*) alloca(1 + len);
698 HANDLE h = CreateFile(path.c_str(),
703 FILE_ATTRIBUTE_NORMAL,
705 if (h == INVALID_HANDLE_VALUE)
709 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
712 if (!ret || nRead != len)
721 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
722 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
723 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
729 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
730 // FIXME: should work on directories also.
735 HANDLE h = CreateFile(path.c_str(),
736 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
737 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
740 FILE_ATTRIBUTE_NORMAL,
742 if (h == INVALID_HANDLE_VALUE)
745 BY_HANDLE_FILE_INFORMATION bhfi;
746 if (!GetFileInformationByHandle(h, &bhfi)) {
747 DWORD err = GetLastError();
750 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
754 (uint64_t&)ft = si.modTime.toWin32Time();
755 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
756 DWORD err = GetLastError();
760 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
763 // Best we can do with Unix permission bits is to interpret the owner
765 if (si.mode & 0200) {
766 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
767 if (!SetFileAttributes(path.c_str(),
768 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
769 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
772 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
773 if (!SetFileAttributes(path.c_str(),
774 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
775 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
783 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
784 // Can't use CopyFile macro defined in Windows.h because it would mess up the
785 // above line. We use the expansion it would have in a non-UNICODE build.
786 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
787 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.toString() +
788 "' to '" + Dest.toString() + "': ");
793 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
794 if (reuse_current && !exists())
795 return false; // File doesn't exist already, just use it!
797 // Reserve space for -XXXXXX at the end.
798 char *FNBuffer = (char*) alloca(path.size()+8);
799 unsigned offset = path.size();
800 path.copy(FNBuffer, offset);
802 // Find a numeric suffix that isn't used by an existing file. Assume there
803 // won't be more than 1 million files with the same prefix. Probably a safe
805 static unsigned FCounter = 0;
807 sprintf(FNBuffer+offset, "-%06u", FCounter);
808 if (++FCounter > 999999)
816 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
817 // Make this into a unique file name
818 makeUnique(reuse_current, ErrMsg);
820 // Now go and create it
821 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
822 FILE_ATTRIBUTE_NORMAL, NULL);
823 if (h == INVALID_HANDLE_VALUE)
824 return MakeErrMsg(ErrMsg, path + ": can't create file");
830 /// MapInFilePages - Not yet implemented on win32.
831 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
835 /// MapInFilePages - Not yet implemented on win32.
836 void Path::UnMapFilePages(const char *Base, uint64_t FileSize) {
837 assert(0 && "NOT IMPLEMENTED");