1 //===- llvm/System/Linux/Path.cpp - Linux 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 //===----------------------------------------------------------------------===//
25 // We need to undo a macro defined in Windows.h, otherwise we won't compile:
27 #undef GetCurrentDirectory
29 // Windows happily accepts either forward or backward slashes, though any path
30 // returned by a Win32 API will have backward slashes. As LLVM code basically
31 // assumes forward slashes are used, backward slashs are converted where they
32 // can be introduced into a path.
34 // Another invariant is that a path ends with a slash if and only if the path
35 // is a root directory. Any other use of a trailing slash is stripped. Unlike
36 // in Unix, Windows has a rather complicated notion of a root path and this
37 // invariant helps simply the code.
39 static void FlipBackSlashes(std::string& s) {
40 for (size_t i = 0; i < s.size(); i++)
47 const char PathSeparator = ';';
50 Path::isValid() const {
54 // If there is a colon, it must be the second character, preceded by a letter
55 // and followed by something.
56 size_t len = path.size();
57 size_t pos = path.rfind(':',len);
59 if (pos != std::string::npos) {
60 if (pos != 1 || !isalpha(path[0]) || len < 3)
65 // Look for a UNC path, and if found adjust our notion of the root slash.
66 if (len > 3 && path[0] == '/' && path[1] == '/') {
67 rootslash = path.find('/', 2);
68 if (rootslash == std::string::npos)
72 // Check for illegal characters.
73 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
74 "\013\014\015\016\017\020\021\022\023\024\025\026"
75 "\027\030\031\032\033\034\035\036\037")
79 // Remove trailing slash, unless it's a root slash.
80 if (len > rootslash+1 && path[len-1] == '/')
83 // Check each component for legality.
84 for (pos = 0; pos < len; ++pos) {
85 // A component may not end in a space.
86 if (path[pos] == ' ') {
87 if (path[pos+1] == '/' || path[pos+1] == '\0')
91 // A component may not end in a period.
92 if (path[pos] == '.') {
93 if (path[pos+1] == '/' || path[pos+1] == '\0') {
94 // Unless it is the pseudo-directory "."...
95 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
98 if (pos > 0 && path[pos-1] == '.') {
99 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
111 Path::isAbsolute() const {
112 switch (path.length()) {
117 return path[0] == '/';
119 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
123 static Path *TempDirectory = NULL;
126 Path::GetTemporaryDirectory(std::string* ErrMsg) {
128 return *TempDirectory;
130 char pathname[MAX_PATH];
131 if (!GetTempPath(MAX_PATH, pathname)) {
133 *ErrMsg = "Can't determine temporary directory";
138 result.set(pathname);
140 // Append a subdirectory passed on our process id so multiple LLVMs don't
141 // step on each other's toes.
143 // Mingw's Win32 header files are broken.
144 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
146 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
148 result.appendComponent(pathname);
150 // If there's a directory left over from a previous LLVM execution that
151 // happened to have the same process id, get rid of it.
152 result.eraseFromDisk(true);
154 // And finally (re-)create the empty directory.
155 result.createDirectoryOnDisk(false);
156 TempDirectory = new Path(result);
157 return *TempDirectory;
160 // FIXME: the following set of functions don't map to Windows very well.
162 Path::GetRootDirectory() {
169 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
170 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
171 Paths.push_back(sys::Path("C:/WINDOWS"));
175 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
176 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
178 getPathList(env_var,Paths);
183 if (tmpPath.set(LLVM_LIBDIR))
184 if (tmpPath.canRead())
185 Paths.push_back(tmpPath);
188 GetSystemLibraryPaths(Paths);
192 Path::GetLLVMDefaultConfigDir() {
193 // TODO: this isn't going to fly on Windows
194 return Path("/etc/llvm");
198 Path::GetUserHomeDirectory() {
199 // TODO: Typical Windows setup doesn't define HOME.
200 const char* home = getenv("HOME");
203 if (result.set(home))
206 return GetRootDirectory();
210 Path::GetCurrentDirectory() {
211 char pathname[MAX_PATH];
212 ::GetCurrentDirectoryA(MAX_PATH,pathname);
213 return Path(pathname);
216 /// GetMainExecutable - Return the path to the main executable, given the
217 /// value of argv[0] from program startup.
218 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
223 // FIXME: the above set of functions don't map to Windows very well.
227 Path::isRootDirectory() const {
228 size_t len = path.size();
229 return len > 0 && path[len-1] == '/';
233 Path::getBasename() const {
234 // Find the last slash
235 size_t slash = path.rfind('/');
236 if (slash == std::string::npos)
241 size_t dot = path.rfind('.');
242 if (dot == std::string::npos || dot < slash)
243 return path.substr(slash);
245 return path.substr(slash, dot - slash);
249 Path::exists() const {
250 DWORD attr = GetFileAttributes(path.c_str());
251 return attr != INVALID_FILE_ATTRIBUTES;
255 Path::isDirectory() const {
256 DWORD attr = GetFileAttributes(path.c_str());
257 return (attr != INVALID_FILE_ATTRIBUTES) &&
258 (attr & FILE_ATTRIBUTE_DIRECTORY);
262 Path::canRead() const {
263 // FIXME: take security attributes into account.
264 DWORD attr = GetFileAttributes(path.c_str());
265 return attr != INVALID_FILE_ATTRIBUTES;
269 Path::canWrite() const {
270 // FIXME: take security attributes into account.
271 DWORD attr = GetFileAttributes(path.c_str());
272 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
276 Path::canExecute() const {
277 // FIXME: take security attributes into account.
278 DWORD attr = GetFileAttributes(path.c_str());
279 return attr != INVALID_FILE_ATTRIBUTES;
283 Path::getLast() const {
284 // Find the last slash
285 size_t pos = path.rfind('/');
287 // Handle the corner cases
288 if (pos == std::string::npos)
291 // If the last character is a slash, we have a root directory
292 if (pos == path.length()-1)
295 // Return everything after the last slash
296 return path.substr(pos+1);
300 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
301 if (!fsIsValid || update) {
302 WIN32_FILE_ATTRIBUTE_DATA fi;
303 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
304 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
305 ": Can't get status: ");
309 status.fileSize = fi.nFileSizeHigh;
310 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
311 status.fileSize += fi.nFileSizeLow;
313 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
314 status.user = 9999; // Not applicable to Windows, so...
315 status.group = 9999; // Not applicable to Windows, so...
317 // FIXME: this is only unique if the file is accessed by the same file path.
318 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
319 // numbers, but the concept doesn't exist in Windows.
321 for (unsigned i = 0; i < path.length(); ++i)
322 status.uniqueID += path[i];
324 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
325 status.modTime.fromWin32Time(ft);
327 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
333 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
334 // All files are readable on Windows (ignoring security attributes).
338 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
339 DWORD attr = GetFileAttributes(path.c_str());
341 // If it doesn't exist, we're done.
342 if (attr == INVALID_FILE_ATTRIBUTES)
345 if (attr & FILE_ATTRIBUTE_READONLY) {
346 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
347 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
354 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
355 // All files are executable on Windows (ignoring security attributes).
360 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
361 WIN32_FILE_ATTRIBUTE_DATA fi;
362 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
363 MakeErrMsg(ErrMsg, path + ": can't get status of file");
367 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
369 *ErrMsg = path + ": not a directory";
375 std::string searchpath = path;
376 if (path.size() == 0 || searchpath[path.size()-1] == '/')
381 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
382 if (h == INVALID_HANDLE_VALUE) {
383 if (GetLastError() == ERROR_FILE_NOT_FOUND)
384 return true; // not really an error, now is it?
385 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
390 if (fd.cFileName[0] == '.')
393 aPath.appendComponent(&fd.cFileName[0]);
394 result.insert(aPath);
395 } while (FindNextFile(h, &fd));
397 DWORD err = GetLastError();
399 if (err != ERROR_NO_MORE_FILES) {
401 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
408 Path::set(const std::string& a_path) {
411 std::string save(path);
413 FlipBackSlashes(path);
422 Path::appendComponent(const std::string& name) {
425 std::string save(path);
427 size_t last = path.size() - 1;
428 if (path[last] != '/')
440 Path::eraseComponent() {
441 size_t slashpos = path.rfind('/',path.size());
442 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
444 std::string save(path);
445 path.erase(slashpos);
454 Path::appendSuffix(const std::string& suffix) {
455 std::string save(path);
466 Path::eraseSuffix() {
467 size_t dotpos = path.rfind('.',path.size());
468 size_t slashpos = path.rfind('/',path.size());
469 if (dotpos != std::string::npos) {
470 if (slashpos == std::string::npos || dotpos > slashpos+1) {
471 std::string save(path);
472 path.erase(dotpos, path.size()-dotpos);
483 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
485 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
490 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
491 // Get a writeable copy of the path name
492 size_t len = path.length();
493 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
494 path.copy(pathname, len);
497 // Make sure it ends with a slash.
498 if (len == 0 || pathname[len - 1] != '/') {
503 // Determine starting point for initial / search.
504 char *next = pathname;
505 if (pathname[0] == '/' && pathname[1] == '/') {
507 next = strchr(pathname+2, '/');
509 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
512 next = strchr(next+1, '/');
514 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
518 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
521 if (pathname[1] == ':')
522 next += 2; // skip drive letter
524 next++; // skip root directory
527 // If we're supposed to create intermediate directories
528 if (create_parents) {
529 // Loop through the directory components until we're done
531 next = strchr(next, '/');
533 if (!CreateDirectory(pathname, NULL))
534 return MakeErrMsg(ErrMsg,
535 std::string(pathname) + ": Can't create directory: ");
539 // Drop trailing slash.
541 if (!CreateDirectory(pathname, NULL)) {
542 return MakeErrMsg(ErrMsg, std::string(pathname) + ": Can't create directory: ");
549 Path::createFileOnDisk(std::string* ErrMsg) {
551 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
552 FILE_ATTRIBUTE_NORMAL, NULL);
553 if (h == INVALID_HANDLE_VALUE)
554 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
561 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
562 WIN32_FILE_ATTRIBUTE_DATA fi;
563 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
566 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
567 // If it doesn't exist, we're done.
571 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
572 int lastchar = path.length() - 1 ;
573 path.copy(pathname, lastchar+1);
575 // Make path end with '/*'.
576 if (pathname[lastchar] != '/')
577 pathname[++lastchar] = '/';
578 pathname[lastchar+1] = '*';
579 pathname[lastchar+2] = 0;
581 if (remove_contents) {
583 HANDLE h = FindFirstFile(pathname, &fd);
585 // It's a bad idea to alter the contents of a directory while enumerating
586 // its contents. So build a list of its contents first, then destroy them.
588 if (h != INVALID_HANDLE_VALUE) {
589 std::vector<Path> list;
592 if (strcmp(fd.cFileName, ".") == 0)
594 if (strcmp(fd.cFileName, "..") == 0)
598 aPath.appendComponent(&fd.cFileName[0]);
599 list.push_back(aPath);
600 } while (FindNextFile(h, &fd));
602 DWORD err = GetLastError();
604 if (err != ERROR_NO_MORE_FILES) {
606 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
609 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
612 aPath.eraseFromDisk(true);
615 if (GetLastError() != ERROR_FILE_NOT_FOUND)
616 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
620 pathname[lastchar] = 0;
621 if (!RemoveDirectory(pathname))
622 return MakeErrMsg(ErrStr,
623 std::string(pathname) + ": Can't destroy directory: ");
626 // Read-only files cannot be deleted on Windows. Must remove the read-only
628 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
629 if (!SetFileAttributes(path.c_str(),
630 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
631 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
634 if (!DeleteFile(path.c_str()))
635 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
640 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
641 assert(len < 1024 && "Request for magic string too long");
642 char* buf = (char*) alloca(1 + len);
644 HANDLE h = CreateFile(path.c_str(),
649 FILE_ATTRIBUTE_NORMAL,
651 if (h == INVALID_HANDLE_VALUE)
655 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
658 if (!ret || nRead != len)
667 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
668 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
669 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
675 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
676 // FIXME: should work on directories also.
681 HANDLE h = CreateFile(path.c_str(),
682 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
683 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
686 FILE_ATTRIBUTE_NORMAL,
688 if (h == INVALID_HANDLE_VALUE)
691 BY_HANDLE_FILE_INFORMATION bhfi;
692 if (!GetFileInformationByHandle(h, &bhfi)) {
693 DWORD err = GetLastError();
696 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
700 (uint64_t&)ft = si.modTime.toWin32Time();
701 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
702 DWORD err = GetLastError();
706 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
709 // Best we can do with Unix permission bits is to interpret the owner
711 if (si.mode & 0200) {
712 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
713 if (!SetFileAttributes(path.c_str(),
714 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
715 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
718 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
719 if (!SetFileAttributes(path.c_str(),
720 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
721 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
729 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
730 // Can't use CopyFile macro defined in Windows.h because it would mess up the
731 // above line. We use the expansion it would have in a non-UNICODE build.
732 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
733 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.toString() +
734 "' to '" + Dest.toString() + "': ");
739 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
740 if (reuse_current && !exists())
741 return false; // File doesn't exist already, just use it!
743 // Reserve space for -XXXXXX at the end.
744 char *FNBuffer = (char*) alloca(path.size()+8);
745 unsigned offset = path.size();
746 path.copy(FNBuffer, offset);
748 // Find a numeric suffix that isn't used by an existing file. Assume there
749 // won't be more than 1 million files with the same prefix. Probably a safe
751 static unsigned FCounter = 0;
753 sprintf(FNBuffer+offset, "-%06u", FCounter);
754 if (++FCounter > 999999)
762 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
763 // Make this into a unique file name
764 makeUnique(reuse_current, ErrMsg);
766 // Now go and create it
767 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
768 FILE_ATTRIBUTE_NORMAL, NULL);
769 if (h == INVALID_HANDLE_VALUE)
770 return MakeErrMsg(ErrMsg, path + ": can't create file");