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);
70 Path::isValid() const {
74 size_t len = path.size();
75 // If there is a null character, it and all its successors are ignored.
76 size_t pos = path.find_first_of('\0');
77 if (pos != std::string::npos)
80 // If there is a colon, it must be the second character, preceded by a letter
81 // and followed by something.
82 pos = path.rfind(':',len);
84 if (pos != std::string::npos) {
85 if (pos != 1 || !isalpha(static_cast<unsigned char>(path[0])) || len < 3)
90 // Look for a UNC path, and if found adjust our notion of the root slash.
91 if (len > 3 && path[0] == '/' && path[1] == '/') {
92 rootslash = path.find('/', 2);
93 if (rootslash == std::string::npos)
97 // Check for illegal characters.
98 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
99 "\013\014\015\016\017\020\021\022\023\024\025\026"
100 "\027\030\031\032\033\034\035\036\037")
101 != std::string::npos)
104 // Remove trailing slash, unless it's a root slash.
105 if (len > rootslash+1 && path[len-1] == '/')
108 // Check each component for legality.
109 for (pos = 0; pos < len; ++pos) {
110 // A component may not end in a space.
111 if (path[pos] == ' ') {
112 if (pos+1 == len || path[pos+1] == '/' || path[pos+1] == '\0')
116 // A component may not end in a period.
117 if (path[pos] == '.') {
118 if (pos+1 == len || path[pos+1] == '/') {
119 // Unless it is the pseudo-directory "."...
120 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
123 if (pos > 0 && path[pos-1] == '.') {
124 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
135 void Path::makeAbsolute() {
136 TCHAR FullPath[MAX_PATH + 1] = {0};
137 LPTSTR FilePart = NULL;
139 DWORD RetLength = ::GetFullPathNameA(path.c_str(),
140 sizeof(FullPath)/sizeof(FullPath[0]),
141 FullPath, &FilePart);
143 if (0 == RetLength) {
144 // FIXME: Report the error GetLastError()
145 assert(0 && "Unable to make absolute path!");
146 } else if (RetLength > MAX_PATH) {
147 // FIXME: Report too small buffer (needed RetLength bytes).
148 assert(0 && "Unable to make absolute path!");
155 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
157 // FIXME: This does not handle correctly an absolute path starting from
158 // a drive letter or in UNC format.
164 return NameStart[0] == '/';
167 (NameStart[0] == '/' || (NameStart[1] == ':' && NameStart[2] == '/')) ||
168 (NameStart[0] == '\\' || (NameStart[1] == ':' && NameStart[2] == '\\'));
173 Path::isAbsolute() const {
174 // FIXME: This does not handle correctly an absolute path starting from
175 // a drive letter or in UNC format.
176 switch (path.length()) {
181 return path[0] == '/';
183 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
187 static Path *TempDirectory;
190 Path::GetTemporaryDirectory(std::string* ErrMsg) {
192 #if defined(_MSC_VER)
193 // Visual Studio gets confused and emits a diagnostic about calling exists,
194 // even though this is the implementation for PathV1. Temporarily
195 // disable the deprecated warning message
196 #pragma warning(push)
197 #pragma warning(disable:4996)
199 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
200 #if defined(_MSC_VER)
203 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 based 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;
237 Path::GetCurrentDirectory() {
238 char pathname[MAX_PATH];
239 ::GetCurrentDirectoryA(MAX_PATH,pathname);
240 return Path(pathname);
243 /// GetMainExecutable - Return the path to the main executable, given the
244 /// value of argv[0] from program startup.
245 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
246 char pathname[MAX_PATH];
247 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
248 return ret != MAX_PATH ? Path(pathname) : Path();
252 // FIXME: the above set of functions don't map to Windows very well.
255 Path::getSuffix() const {
256 // Find the last slash
257 size_t slash = path.rfind('/');
258 if (slash == std::string::npos)
263 size_t dot = path.rfind('.');
264 if (dot == std::string::npos || dot < slash)
265 return StringRef("");
267 return StringRef(path).substr(dot + 1);
271 Path::exists() const {
272 DWORD attr = GetFileAttributes(path.c_str());
273 return attr != INVALID_FILE_ATTRIBUTES;
277 Path::isDirectory() const {
278 DWORD attr = GetFileAttributes(path.c_str());
279 return (attr != INVALID_FILE_ATTRIBUTES) &&
280 (attr & FILE_ATTRIBUTE_DIRECTORY);
284 Path::isSymLink() const {
285 DWORD attributes = GetFileAttributes(path.c_str());
287 if (attributes == INVALID_FILE_ATTRIBUTES)
288 // There's no sane way to report this :(.
289 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
291 // This isn't exactly what defines a NTFS symlink, but it is only true for
292 // paths that act like a symlink.
293 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
297 Path::canRead() const {
298 // FIXME: take security attributes into account.
299 DWORD attr = GetFileAttributes(path.c_str());
300 return attr != INVALID_FILE_ATTRIBUTES;
304 Path::canWrite() const {
305 // FIXME: take security attributes into account.
306 DWORD attr = GetFileAttributes(path.c_str());
307 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
311 Path::canExecute() const {
312 // FIXME: take security attributes into account.
313 DWORD attr = GetFileAttributes(path.c_str());
314 return attr != INVALID_FILE_ATTRIBUTES;
318 Path::isRegularFile() const {
320 if (fs::is_regular_file(path, res))
326 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
327 if (!fsIsValid || update) {
328 WIN32_FILE_ATTRIBUTE_DATA fi;
329 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
330 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
331 ": Can't get status: ");
335 status.fileSize = fi.nFileSizeHigh;
336 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
337 status.fileSize += fi.nFileSizeLow;
339 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
340 status.user = 9999; // Not applicable to Windows, so...
341 status.group = 9999; // Not applicable to Windows, so...
343 // FIXME: this is only unique if the file is accessed by the same file path.
344 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
345 // numbers, but the concept doesn't exist in Windows.
347 for (unsigned i = 0; i < path.length(); ++i)
348 status.uniqueID += path[i];
351 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
352 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
353 status.modTime.fromWin32Time(ui.QuadPart);
355 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
361 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
362 // All files are readable on Windows (ignoring security attributes).
366 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
367 DWORD attr = GetFileAttributes(path.c_str());
369 // If it doesn't exist, we're done.
370 if (attr == INVALID_FILE_ATTRIBUTES)
373 if (attr & FILE_ATTRIBUTE_READONLY) {
374 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
375 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
382 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
383 // All files are executable on Windows (ignoring security attributes).
388 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
389 WIN32_FILE_ATTRIBUTE_DATA fi;
390 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
391 MakeErrMsg(ErrMsg, path + ": can't get status of file");
395 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
397 *ErrMsg = path + ": not a directory";
403 std::string searchpath = path;
404 if (path.size() == 0 || searchpath[path.size()-1] == '/')
409 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
410 if (h == INVALID_HANDLE_VALUE) {
411 if (GetLastError() == ERROR_FILE_NOT_FOUND)
412 return true; // not really an error, now is it?
413 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
418 if (fd.cFileName[0] == '.')
421 aPath.appendComponent(&fd.cFileName[0]);
422 result.insert(aPath);
423 } while (FindNextFile(h, &fd));
425 DWORD err = GetLastError();
427 if (err != ERROR_NO_MORE_FILES) {
429 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
436 Path::set(StringRef a_path) {
439 std::string save(path);
441 FlipBackSlashes(path);
450 Path::appendComponent(StringRef name) {
453 std::string save(path);
455 size_t last = path.size() - 1;
456 if (path[last] != '/')
468 Path::eraseComponent() {
469 size_t slashpos = path.rfind('/',path.size());
470 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
472 std::string save(path);
473 path.erase(slashpos);
482 Path::eraseSuffix() {
483 size_t dotpos = path.rfind('.',path.size());
484 size_t slashpos = path.rfind('/',path.size());
485 if (dotpos != std::string::npos) {
486 if (slashpos == std::string::npos || dotpos > slashpos+1) {
487 std::string save(path);
488 path.erase(dotpos, path.size()-dotpos);
499 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
501 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
506 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
507 // Get a writeable copy of the path name
508 size_t len = path.length();
509 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
510 path.copy(pathname, len);
513 // Make sure it ends with a slash.
514 if (len == 0 || pathname[len - 1] != '/') {
519 // Determine starting point for initial / search.
520 char *next = pathname;
521 if (pathname[0] == '/' && pathname[1] == '/') {
523 next = strchr(pathname+2, '/');
525 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
528 next = strchr(next+1, '/');
530 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
534 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
537 if (pathname[1] == ':')
538 next += 2; // skip drive letter
540 next++; // skip root directory
543 // If we're supposed to create intermediate directories
544 if (create_parents) {
545 // Loop through the directory components until we're done
547 next = strchr(next, '/');
549 if (!CreateDirectory(pathname, NULL) &&
550 GetLastError() != ERROR_ALREADY_EXISTS)
551 return MakeErrMsg(ErrMsg,
552 std::string(pathname) + ": Can't create directory: ");
556 // Drop trailing slash.
558 if (!CreateDirectory(pathname, NULL) &&
559 GetLastError() != ERROR_ALREADY_EXISTS) {
560 return MakeErrMsg(ErrMsg, std::string(pathname) +
561 ": Can't create directory: ");
568 Path::createFileOnDisk(std::string* ErrMsg) {
570 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
571 FILE_ATTRIBUTE_NORMAL, NULL);
572 if (h == INVALID_HANDLE_VALUE)
573 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
580 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
581 WIN32_FILE_ATTRIBUTE_DATA fi;
582 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
585 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
586 // If it doesn't exist, we're done.
588 if (fs::exists(path, Exists) || !Exists)
591 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
592 int lastchar = path.length() - 1 ;
593 path.copy(pathname, lastchar+1);
595 // Make path end with '/*'.
596 if (pathname[lastchar] != '/')
597 pathname[++lastchar] = '/';
598 pathname[lastchar+1] = '*';
599 pathname[lastchar+2] = 0;
601 if (remove_contents) {
603 HANDLE h = FindFirstFile(pathname, &fd);
605 // It's a bad idea to alter the contents of a directory while enumerating
606 // its contents. So build a list of its contents first, then destroy them.
608 if (h != INVALID_HANDLE_VALUE) {
609 std::vector<Path> list;
612 if (strcmp(fd.cFileName, ".") == 0)
614 if (strcmp(fd.cFileName, "..") == 0)
618 aPath.appendComponent(&fd.cFileName[0]);
619 list.push_back(aPath);
620 } while (FindNextFile(h, &fd));
622 DWORD err = GetLastError();
624 if (err != ERROR_NO_MORE_FILES) {
626 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
629 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
632 aPath.eraseFromDisk(true);
635 if (GetLastError() != ERROR_FILE_NOT_FOUND)
636 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
640 pathname[lastchar] = 0;
641 if (!RemoveDirectory(pathname))
642 return MakeErrMsg(ErrStr,
643 std::string(pathname) + ": Can't destroy directory: ");
646 // Read-only files cannot be deleted on Windows. Must remove the read-only
648 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
649 if (!SetFileAttributes(path.c_str(),
650 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
651 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
654 if (!DeleteFile(path.c_str()))
655 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
660 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
661 assert(len < 1024 && "Request for magic string too long");
662 char* buf = reinterpret_cast<char*>(alloca(len));
664 HANDLE h = CreateFile(path.c_str(),
669 FILE_ATTRIBUTE_NORMAL,
671 if (h == INVALID_HANDLE_VALUE)
675 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
678 if (!ret || nRead != len)
681 Magic = std::string(buf, len);
686 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
687 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
688 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
694 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
695 // FIXME: should work on directories also.
700 HANDLE h = CreateFile(path.c_str(),
701 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
702 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
705 FILE_ATTRIBUTE_NORMAL,
707 if (h == INVALID_HANDLE_VALUE)
710 BY_HANDLE_FILE_INFORMATION bhfi;
711 if (!GetFileInformationByHandle(h, &bhfi)) {
712 DWORD err = GetLastError();
715 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
719 ui.QuadPart = si.modTime.toWin32Time();
721 ft.dwLowDateTime = ui.LowPart;
722 ft.dwHighDateTime = ui.HighPart;
723 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
724 DWORD err = GetLastError();
728 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
731 // Best we can do with Unix permission bits is to interpret the owner
733 if (si.mode & 0200) {
734 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
735 if (!SetFileAttributes(path.c_str(),
736 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
737 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
740 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
741 if (!SetFileAttributes(path.c_str(),
742 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
743 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
751 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
752 // Can't use CopyFile macro defined in Windows.h because it would mess up the
753 // above line. We use the expansion it would have in a non-UNICODE build.
754 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
755 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.str() +
756 "' to '" + Dest.str() + "': ");
761 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
763 if (reuse_current && (fs::exists(path, Exists) || !Exists))
764 return false; // File doesn't exist already, just use it!
766 // Reserve space for -XXXXXX at the end.
767 char *FNBuffer = (char*) alloca(path.size()+8);
768 unsigned offset = path.size();
769 path.copy(FNBuffer, offset);
771 // Find a numeric suffix that isn't used by an existing file. Assume there
772 // won't be more than 1 million files with the same prefix. Probably a safe
774 static int FCounter = -1;
776 // Give arbitrary initial seed.
777 // FIXME: We should use sys::fs::unique_file() in future.
779 DWORD x = GetCurrentProcessId();
780 x = (x << 16) | (x >> 16);
781 if (QueryPerformanceCounter(&cnt64)) // RDTSC
782 x ^= cnt64.HighPart ^ cnt64.LowPart;
783 FCounter = x % 1000000;
786 sprintf(FNBuffer+offset, "-%06u", FCounter);
787 if (++FCounter > 999999)
790 } while (!fs::exists(path, Exists) && Exists);
795 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
796 // Make this into a unique file name
797 makeUnique(reuse_current, ErrMsg);
799 // Now go and create it
800 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
801 FILE_ATTRIBUTE_NORMAL, NULL);
802 if (h == INVALID_HANDLE_VALUE)
803 return MakeErrMsg(ErrMsg, path + ": can't create file");
809 /// MapInFilePages - Not yet implemented on win32.
810 const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
814 /// MapInFilePages - Not yet implemented on win32.
815 void Path::UnMapFilePages(const char *Base, size_t FileSize) {
816 assert(0 && "NOT IMPLEMENTED");