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++)
48 extern const char sys::PathSeparator = ';';
51 Path::isValid() const {
55 // If there is a colon, it must be the second character, preceded by a letter
56 // and followed by something.
57 size_t len = path.size();
58 size_t pos = path.rfind(':',len);
60 if (pos != std::string::npos) {
61 if (pos != 1 || !isalpha(path[0]) || len < 3)
66 // Look for a UNC path, and if found adjust our notion of the root slash.
67 if (len > 3 && path[0] == '/' && path[1] == '/') {
68 rootslash = path.find('/', 2);
69 if (rootslash == std::string::npos)
73 // Check for illegal characters.
74 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
75 "\013\014\015\016\017\020\021\022\023\024\025\026"
76 "\027\030\031\032\033\034\035\036\037")
80 // Remove trailing slash, unless it's a root slash.
81 if (len > rootslash+1 && path[len-1] == '/')
84 // Check each component for legality.
85 for (pos = 0; pos < len; ++pos) {
86 // A component may not end in a space.
87 if (path[pos] == ' ') {
88 if (path[pos+1] == '/' || path[pos+1] == '\0')
92 // A component may not end in a period.
93 if (path[pos] == '.') {
94 if (path[pos+1] == '/' || path[pos+1] == '\0') {
95 // Unless it is the pseudo-directory "."...
96 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
99 if (pos > 0 && path[pos-1] == '.') {
100 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
112 Path::isAbsolute() const {
113 switch (path.length()) {
118 return path[0] == '/';
120 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
124 static Path *TempDirectory = NULL;
127 Path::GetTemporaryDirectory(std::string* ErrMsg) {
129 return *TempDirectory;
131 char pathname[MAX_PATH];
132 if (!GetTempPath(MAX_PATH, pathname)) {
134 *ErrMsg = "Can't determine temporary directory";
139 result.set(pathname);
141 // Append a subdirectory passed on our process id so multiple LLVMs don't
142 // step on each other's toes.
144 // Mingw's Win32 header files are broken.
145 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
147 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
149 result.appendComponent(pathname);
151 // If there's a directory left over from a previous LLVM execution that
152 // happened to have the same process id, get rid of it.
153 result.eraseFromDisk(true);
155 // And finally (re-)create the empty directory.
156 result.createDirectoryOnDisk(false);
157 TempDirectory = new Path(result);
158 return *TempDirectory;
161 // FIXME: the following set of functions don't map to Windows very well.
163 Path::GetRootDirectory() {
170 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
171 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
172 Paths.push_back(sys::Path("C:/WINDOWS"));
176 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
177 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
179 getPathList(env_var,Paths);
184 if (tmpPath.set(LLVM_LIBDIR))
185 if (tmpPath.canRead())
186 Paths.push_back(tmpPath);
189 GetSystemLibraryPaths(Paths);
193 Path::GetLLVMDefaultConfigDir() {
194 // TODO: this isn't going to fly on Windows
195 return Path("/etc/llvm");
199 Path::GetUserHomeDirectory() {
200 // TODO: Typical Windows setup doesn't define HOME.
201 const char* home = getenv("HOME");
204 if (result.set(home))
207 return GetRootDirectory();
211 Path::GetCurrentDirectory() {
212 char pathname[MAX_PATH];
213 ::GetCurrentDirectoryA(MAX_PATH,pathname);
214 return Path(pathname);
218 // FIXME: the above set of functions don't map to Windows very well.
222 Path::isRootDirectory() const {
223 size_t len = path.size();
224 return len > 0 && path[len-1] == '/';
228 Path::getBasename() const {
229 // Find the last slash
230 size_t slash = path.rfind('/');
231 if (slash == std::string::npos)
236 size_t dot = path.rfind('.');
237 if (dot == std::string::npos || dot < slash)
238 return path.substr(slash);
240 return path.substr(slash, dot - slash);
244 Path::exists() const {
245 DWORD attr = GetFileAttributes(path.c_str());
246 return attr != INVALID_FILE_ATTRIBUTES;
250 Path::isDirectory() const {
251 DWORD attr = GetFileAttributes(path.c_str());
252 return (attr != INVALID_FILE_ATTRIBUTES) &&
253 (attr & FILE_ATTRIBUTE_DIRECTORY);
257 Path::canRead() const {
258 // FIXME: take security attributes into account.
259 DWORD attr = GetFileAttributes(path.c_str());
260 return attr != INVALID_FILE_ATTRIBUTES;
264 Path::canWrite() const {
265 // FIXME: take security attributes into account.
266 DWORD attr = GetFileAttributes(path.c_str());
267 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
271 Path::canExecute() const {
272 // FIXME: take security attributes into account.
273 DWORD attr = GetFileAttributes(path.c_str());
274 return attr != INVALID_FILE_ATTRIBUTES;
278 Path::getLast() const {
279 // Find the last slash
280 size_t pos = path.rfind('/');
282 // Handle the corner cases
283 if (pos == std::string::npos)
286 // If the last character is a slash, we have a root directory
287 if (pos == path.length()-1)
290 // Return everything after the last slash
291 return path.substr(pos+1);
295 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
296 if (!fsIsValid || update) {
297 WIN32_FILE_ATTRIBUTE_DATA fi;
298 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
299 MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
300 ": Can't get status: ");
304 status.fileSize = fi.nFileSizeHigh;
305 status.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
306 status.fileSize += fi.nFileSizeLow;
308 status.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
309 status.user = 9999; // Not applicable to Windows, so...
310 status.group = 9999; // Not applicable to Windows, so...
312 // FIXME: this is only unique if the file is accessed by the same file path.
313 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
314 // numbers, but the concept doesn't exist in Windows.
316 for (unsigned i = 0; i < path.length(); ++i)
317 status.uniqueID += path[i];
319 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
320 status.modTime.fromWin32Time(ft);
322 status.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
328 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
329 // All files are readable on Windows (ignoring security attributes).
333 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
334 DWORD attr = GetFileAttributes(path.c_str());
336 // If it doesn't exist, we're done.
337 if (attr == INVALID_FILE_ATTRIBUTES)
340 if (attr & FILE_ATTRIBUTE_READONLY) {
341 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
342 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
349 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
350 // All files are executable on Windows (ignoring security attributes).
355 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
356 WIN32_FILE_ATTRIBUTE_DATA fi;
357 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
358 MakeErrMsg(ErrMsg, path + ": can't get status of file");
362 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
364 *ErrMsg = path + ": not a directory";
370 std::string searchpath = path;
371 if (path.size() == 0 || searchpath[path.size()-1] == '/')
376 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
377 if (h == INVALID_HANDLE_VALUE) {
378 if (GetLastError() == ERROR_FILE_NOT_FOUND)
379 return true; // not really an error, now is it?
380 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
385 if (fd.cFileName[0] == '.')
388 aPath.appendComponent(&fd.cFileName[0]);
389 result.insert(aPath);
390 } while (FindNextFile(h, &fd));
392 DWORD err = GetLastError();
394 if (err != ERROR_NO_MORE_FILES) {
396 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
403 Path::set(const std::string& a_path) {
406 std::string save(path);
408 FlipBackSlashes(path);
417 Path::appendComponent(const std::string& name) {
420 std::string save(path);
422 size_t last = path.size() - 1;
423 if (path[last] != '/')
435 Path::eraseComponent() {
436 size_t slashpos = path.rfind('/',path.size());
437 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
439 std::string save(path);
440 path.erase(slashpos);
449 Path::appendSuffix(const std::string& suffix) {
450 std::string save(path);
461 Path::eraseSuffix() {
462 size_t dotpos = path.rfind('.',path.size());
463 size_t slashpos = path.rfind('/',path.size());
464 if (dotpos != std::string::npos) {
465 if (slashpos == std::string::npos || dotpos > slashpos+1) {
466 std::string save(path);
467 path.erase(dotpos, path.size()-dotpos);
478 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
480 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
485 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
486 // Get a writeable copy of the path name
487 size_t len = path.length();
488 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
489 path.copy(pathname, len);
492 // Make sure it ends with a slash.
493 if (len == 0 || pathname[len - 1] != '/') {
498 // Determine starting point for initial / search.
499 char *next = pathname;
500 if (pathname[0] == '/' && pathname[1] == '/') {
502 next = strchr(pathname+2, '/');
504 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
507 next = strchr(next+1, '/');
509 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
513 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
516 if (pathname[1] == ':')
517 next += 2; // skip drive letter
519 next++; // skip root directory
522 // If we're supposed to create intermediate directories
523 if (create_parents) {
524 // Loop through the directory components until we're done
526 next = strchr(next, '/');
528 if (!CreateDirectory(pathname, NULL))
529 return MakeErrMsg(ErrMsg,
530 std::string(pathname) + ": Can't create directory: ");
534 // Drop trailing slash.
536 if (!CreateDirectory(pathname, NULL)) {
537 return MakeErrMsg(ErrMsg, std::string(pathname) + ": Can't create directory: ");
544 Path::createFileOnDisk(std::string* ErrMsg) {
546 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
547 FILE_ATTRIBUTE_NORMAL, NULL);
548 if (h == INVALID_HANDLE_VALUE)
549 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
556 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
557 WIN32_FILE_ATTRIBUTE_DATA fi;
558 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
561 if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
562 // If it doesn't exist, we're done.
566 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
567 int lastchar = path.length() - 1 ;
568 path.copy(pathname, lastchar+1);
570 // Make path end with '/*'.
571 if (pathname[lastchar] != '/')
572 pathname[++lastchar] = '/';
573 pathname[lastchar+1] = '*';
574 pathname[lastchar+2] = 0;
576 if (remove_contents) {
578 HANDLE h = FindFirstFile(pathname, &fd);
580 // It's a bad idea to alter the contents of a directory while enumerating
581 // its contents. So build a list of its contents first, then destroy them.
583 if (h != INVALID_HANDLE_VALUE) {
584 std::vector<Path> list;
587 if (strcmp(fd.cFileName, ".") == 0)
589 if (strcmp(fd.cFileName, "..") == 0)
593 aPath.appendComponent(&fd.cFileName[0]);
594 list.push_back(aPath);
595 } while (FindNextFile(h, &fd));
597 DWORD err = GetLastError();
599 if (err != ERROR_NO_MORE_FILES) {
601 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
604 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
607 aPath.eraseFromDisk(true);
610 if (GetLastError() != ERROR_FILE_NOT_FOUND)
611 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
615 pathname[lastchar] = 0;
616 if (!RemoveDirectory(pathname))
617 return MakeErrMsg(ErrStr,
618 std::string(pathname) + ": Can't destroy directory: ");
621 // Read-only files cannot be deleted on Windows. Must remove the read-only
623 if (fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
624 if (!SetFileAttributes(path.c_str(),
625 fi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
626 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
629 if (!DeleteFile(path.c_str()))
630 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
635 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
636 assert(len < 1024 && "Request for magic string too long");
637 char* buf = (char*) alloca(1 + len);
639 HANDLE h = CreateFile(path.c_str(),
644 FILE_ATTRIBUTE_NORMAL,
646 if (h == INVALID_HANDLE_VALUE)
650 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
653 if (!ret || nRead != len)
662 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
663 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
664 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
670 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
671 // FIXME: should work on directories also.
676 HANDLE h = CreateFile(path.c_str(),
677 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
678 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
681 FILE_ATTRIBUTE_NORMAL,
683 if (h == INVALID_HANDLE_VALUE)
686 BY_HANDLE_FILE_INFORMATION bhfi;
687 if (!GetFileInformationByHandle(h, &bhfi)) {
688 DWORD err = GetLastError();
691 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
695 (uint64_t&)ft = si.modTime.toWin32Time();
696 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
697 DWORD err = GetLastError();
701 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
704 // Best we can do with Unix permission bits is to interpret the owner
706 if (si.mode & 0200) {
707 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
708 if (!SetFileAttributes(path.c_str(),
709 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
710 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
713 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
714 if (!SetFileAttributes(path.c_str(),
715 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
716 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
724 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
725 // Can't use CopyFile macro defined in Windows.h because it would mess up the
726 // above line. We use the expansion it would have in a non-UNICODE build.
727 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
728 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.toString() +
729 "' to '" + Dest.toString() + "': ");
734 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
735 if (reuse_current && !exists())
736 return false; // File doesn't exist already, just use it!
738 // Reserve space for -XXXXXX at the end.
739 char *FNBuffer = (char*) alloca(path.size()+8);
740 unsigned offset = path.size();
741 path.copy(FNBuffer, offset);
743 // Find a numeric suffix that isn't used by an existing file. Assume there
744 // won't be more than 1 million files with the same prefix. Probably a safe
746 static unsigned FCounter = 0;
748 sprintf(FNBuffer+offset, "-%06u", FCounter);
749 if (++FCounter > 999999)
757 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
758 // Make this into a unique file name
759 makeUnique(reuse_current, ErrMsg);
761 // Now go and create it
762 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
763 FILE_ATTRIBUTE_NORMAL, NULL);
764 if (h == INVALID_HANDLE_VALUE)
765 return MakeErrMsg(ErrMsg, path + ": can't create file");