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 Path::Path(llvm::StringRef p)
47 FlipBackSlashes(path);
50 Path::Path(const char *StrStart, unsigned StrLen)
51 : path(StrStart, StrLen) {
52 FlipBackSlashes(path);
56 Path::operator=(StringRef that) {
57 path.assign(that.data(), that.size());
58 FlipBackSlashes(path);
63 Path::isValid() const {
67 size_t len = path.size();
68 // If there is a null character, it and all its successors are ignored.
69 size_t pos = path.find_first_of('\0');
70 if (pos != std::string::npos)
73 // If there is a colon, it must be the second character, preceded by a letter
74 // and followed by something.
75 pos = path.rfind(':',len);
77 if (pos != std::string::npos) {
78 if (pos != 1 || !isalpha(static_cast<unsigned char>(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 (pos+1 == len || path[pos+1] == '/' || path[pos+1] == '\0')
109 // A component may not end in a period.
110 if (path[pos] == '.') {
111 if (pos+1 == len || path[pos+1] == '/') {
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] == ':')
128 void Path::makeAbsolute() {
129 TCHAR FullPath[MAX_PATH + 1] = {0};
130 LPTSTR FilePart = NULL;
132 DWORD RetLength = ::GetFullPathNameA(path.c_str(),
133 sizeof(FullPath)/sizeof(FullPath[0]),
134 FullPath, &FilePart);
136 if (0 == RetLength) {
137 // FIXME: Report the error GetLastError()
138 assert(0 && "Unable to make absolute path!");
139 } else if (RetLength > MAX_PATH) {
140 // FIXME: Report too small buffer (needed RetLength bytes).
141 assert(0 && "Unable to make absolute path!");
147 static Path *TempDirectory;
150 Path::GetTemporaryDirectory(std::string* ErrMsg) {
152 #if defined(_MSC_VER)
153 // Visual Studio gets confused and emits a diagnostic about calling exists,
154 // even though this is the implementation for PathV1. Temporarily
155 // disable the deprecated warning message
156 #pragma warning(push)
157 #pragma warning(disable:4996)
159 assert(TempDirectory->exists() && "Who has removed TempDirectory?");
160 #if defined(_MSC_VER)
163 return *TempDirectory;
166 char pathname[MAX_PATH];
167 if (!GetTempPath(MAX_PATH, pathname)) {
169 *ErrMsg = "Can't determine temporary directory";
174 result.set(pathname);
176 // Append a subdirectory based on our process id so multiple LLVMs don't
177 // step on each other's toes.
179 // Mingw's Win32 header files are broken.
180 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
182 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
184 result.appendComponent(pathname);
186 // If there's a directory left over from a previous LLVM execution that
187 // happened to have the same process id, get rid of it.
188 result.eraseFromDisk(true);
190 // And finally (re-)create the empty directory.
191 result.createDirectoryOnDisk(false);
192 TempDirectory = new Path(result);
193 return *TempDirectory;
197 Path::GetCurrentDirectory() {
198 char pathname[MAX_PATH];
199 ::GetCurrentDirectoryA(MAX_PATH,pathname);
200 return Path(pathname);
203 /// GetMainExecutable - Return the path to the main executable, given the
204 /// value of argv[0] from program startup.
205 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
206 char pathname[MAX_PATH];
207 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
208 return ret != MAX_PATH ? Path(pathname) : Path();
212 // FIXME: the above set of functions don't map to Windows very well.
215 Path::exists() const {
216 DWORD attr = GetFileAttributes(path.c_str());
217 return attr != INVALID_FILE_ATTRIBUTES;
221 Path::isDirectory() const {
222 DWORD attr = GetFileAttributes(path.c_str());
223 return (attr != INVALID_FILE_ATTRIBUTES) &&
224 (attr & FILE_ATTRIBUTE_DIRECTORY);
228 Path::isSymLink() const {
229 DWORD attributes = GetFileAttributes(path.c_str());
231 if (attributes == INVALID_FILE_ATTRIBUTES)
232 // There's no sane way to report this :(.
233 assert(0 && "GetFileAttributes returned INVALID_FILE_ATTRIBUTES");
235 // This isn't exactly what defines a NTFS symlink, but it is only true for
236 // paths that act like a symlink.
237 return attributes & FILE_ATTRIBUTE_REPARSE_POINT;
241 Path::isRegularFile() const {
243 if (fs::is_regular_file(path, res))
249 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
250 if (!fsIsValid || update) {
251 WIN32_FILE_ATTRIBUTE_DATA fi;
252 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
253 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
254 ": Can't get status: ");
258 status.fileSize = fi.nFileSizeHigh;
259 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
260 status.fileSize += fi.nFileSizeLow;
262 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
263 status.user = 9999; // Not applicable to Windows, so...
264 status.group = 9999; // Not applicable to Windows, so...
267 ui.LowPart = fi.ftLastWriteTime.dwLowDateTime;
268 ui.HighPart = fi.ftLastWriteTime.dwHighDateTime;
269 status.modTime.fromWin32Time(ui.QuadPart);
271 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
277 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
278 // All files are readable on Windows (ignoring security attributes).
282 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
283 DWORD attr = GetFileAttributes(path.c_str());
285 // If it doesn't exist, we're done.
286 if (attr == INVALID_FILE_ATTRIBUTES)
289 if (attr & FILE_ATTRIBUTE_READONLY) {
290 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
291 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
299 Path::set(StringRef a_path) {
302 std::string save(path);
304 FlipBackSlashes(path);
313 Path::appendComponent(StringRef name) {
316 std::string save(path);
318 size_t last = path.size() - 1;
319 if (path[last] != '/')
331 Path::eraseComponent() {
332 size_t slashpos = path.rfind('/',path.size());
333 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
335 std::string save(path);
336 path.erase(slashpos);
345 Path::eraseSuffix() {
346 size_t dotpos = path.rfind('.',path.size());
347 size_t slashpos = path.rfind('/',path.size());
348 if (dotpos != std::string::npos) {
349 if (slashpos == std::string::npos || dotpos > slashpos+1) {
350 std::string save(path);
351 path.erase(dotpos, path.size()-dotpos);
362 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
364 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
369 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
370 // Get a writeable copy of the path name
371 size_t len = path.length();
372 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
373 path.copy(pathname, len);
376 // Make sure it ends with a slash.
377 if (len == 0 || pathname[len - 1] != '/') {
382 // Determine starting point for initial / search.
383 char *next = pathname;
384 if (pathname[0] == '/' && pathname[1] == '/') {
386 next = strchr(pathname+2, '/');
388 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
391 next = strchr(next+1, '/');
393 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
397 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
400 if (pathname[1] == ':')
401 next += 2; // skip drive letter
403 next++; // skip root directory
406 // If we're supposed to create intermediate directories
407 if (create_parents) {
408 // Loop through the directory components until we're done
410 next = strchr(next, '/');
412 if (!CreateDirectory(pathname, NULL) &&
413 GetLastError() != ERROR_ALREADY_EXISTS)
414 return MakeErrMsg(ErrMsg,
415 std::string(pathname) + ": Can't create directory: ");
419 // Drop trailing slash.
421 if (!CreateDirectory(pathname, NULL) &&
422 GetLastError() != ERROR_ALREADY_EXISTS) {
423 return MakeErrMsg(ErrMsg, std::string(pathname) +
424 ": Can't create directory: ");
431 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
432 WIN32_FILE_ATTRIBUTE_DATA fi;
433 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
436 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
437 // If it doesn't exist, we're done.
439 if (fs::exists(path, Exists) || !Exists)
442 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
443 int lastchar = path.length() - 1 ;
444 path.copy(pathname, lastchar+1);
446 // Make path end with '/*'.
447 if (pathname[lastchar] != '/')
448 pathname[++lastchar] = '/';
449 pathname[lastchar+1] = '*';
450 pathname[lastchar+2] = 0;
452 if (remove_contents) {
454 HANDLE h = FindFirstFile(pathname, &fd);
456 // It's a bad idea to alter the contents of a directory while enumerating
457 // its contents. So build a list of its contents first, then destroy them.
459 if (h != INVALID_HANDLE_VALUE) {
460 std::vector<Path> list;
463 if (strcmp(fd.cFileName, ".") == 0)
465 if (strcmp(fd.cFileName, "..") == 0)
469 aPath.appendComponent(&fd.cFileName[0]);
470 list.push_back(aPath);
471 } while (FindNextFile(h, &fd));
473 DWORD err = GetLastError();
475 if (err != ERROR_NO_MORE_FILES) {
477 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
480 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
483 aPath.eraseFromDisk(true);
486 if (GetLastError() != ERROR_FILE_NOT_FOUND)
487 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
491 pathname[lastchar] = 0;
492 if (!RemoveDirectory(pathname))
493 return MakeErrMsg(ErrStr,
494 std::string(pathname) + ": Can't destroy directory: ");
497 // Read-only files cannot be deleted on Windows. Must remove the read-only
499 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
500 if (!SetFileAttributes(path.c_str(),
501 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
502 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
505 if (!DeleteFile(path.c_str()))
506 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
512 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
513 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
514 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
520 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
521 // FIXME: should work on directories also.
526 HANDLE h = CreateFile(path.c_str(),
527 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
528 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
531 FILE_ATTRIBUTE_NORMAL,
533 if (h == INVALID_HANDLE_VALUE)
536 BY_HANDLE_FILE_INFORMATION bhfi;
537 if (!GetFileInformationByHandle(h, &bhfi)) {
538 DWORD err = GetLastError();
541 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
545 ui.QuadPart = si.modTime.toWin32Time();
547 ft.dwLowDateTime = ui.LowPart;
548 ft.dwHighDateTime = ui.HighPart;
549 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
550 DWORD err = GetLastError();
554 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
557 // Best we can do with Unix permission bits is to interpret the owner
559 if (si.mode & 0200) {
560 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
561 if (!SetFileAttributes(path.c_str(),
562 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
563 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
566 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
567 if (!SetFileAttributes(path.c_str(),
568 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
569 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
577 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
579 if (reuse_current && (fs::exists(path, Exists) || !Exists))
580 return false; // File doesn't exist already, just use it!
582 // Reserve space for -XXXXXX at the end.
583 char *FNBuffer = (char*) alloca(path.size()+8);
584 unsigned offset = path.size();
585 path.copy(FNBuffer, offset);
587 // Find a numeric suffix that isn't used by an existing file. Assume there
588 // won't be more than 1 million files with the same prefix. Probably a safe
590 static int FCounter = -1;
592 // Give arbitrary initial seed.
593 // FIXME: We should use sys::fs::unique_file() in future.
595 DWORD x = GetCurrentProcessId();
596 x = (x << 16) | (x >> 16);
597 if (QueryPerformanceCounter(&cnt64)) // RDTSC
598 x ^= cnt64.HighPart ^ cnt64.LowPart;
599 FCounter = x % 1000000;
602 sprintf(FNBuffer+offset, "-%06u", FCounter);
603 if (++FCounter > 999999)
606 } while (!fs::exists(path, Exists) && Exists);
611 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
612 // Make this into a unique file name
613 makeUnique(reuse_current, ErrMsg);
615 // Now go and create it
616 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
617 FILE_ATTRIBUTE_NORMAL, NULL);
618 if (h == INVALID_HANDLE_VALUE)
619 return MakeErrMsg(ErrMsg, path + ": can't create file");