1 //===- llvm/System/Linux/Path.cpp - Linux Path Implementation ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source 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:
28 // Windows happily accepts either forward or backward slashes, though any path
29 // returned by a Win32 API will have backward slashes. As LLVM code basically
30 // assumes forward slashes are used, backward slashs are converted where they
31 // can be introduced into a path.
33 // Another invariant is that a path ends with a slash if and only if the path
34 // is a root directory. Any other use of a trailing slash is stripped. Unlike
35 // in Unix, Windows has a rather complicated notion of a root path and this
36 // invariant helps simply the code.
38 static void FlipBackSlashes(std::string& s) {
39 for (size_t i = 0; i < s.size(); i++)
48 Path::isValid() const {
52 // If there is a colon, it must be the second character, preceded by a letter
53 // and followed by something.
54 size_t len = path.size();
55 size_t pos = path.rfind(':',len);
57 if (pos != std::string::npos) {
58 if (pos != 1 || !isalpha(path[0]) || len < 3)
63 // Look for a UNC path, and if found adjust our notion of the root slash.
64 if (len > 3 && path[0] == '/' && path[1] == '/') {
65 rootslash = path.find('/', 2);
66 if (rootslash == std::string::npos)
70 // Check for illegal characters.
71 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
72 "\013\014\015\016\017\020\021\022\023\024\025\026"
73 "\027\030\031\032\033\034\035\036\037")
77 // Remove trailing slash, unless it's a root slash.
78 if (len > rootslash+1 && path[len-1] == '/')
81 // Check each component for legality.
82 for (pos = 0; pos < len; ++pos) {
83 // A component may not end in a space.
84 if (path[pos] == ' ') {
85 if (path[pos+1] == '/' || path[pos+1] == '\0')
89 // A component may not end in a period.
90 if (path[pos] == '.') {
91 if (path[pos+1] == '/' || path[pos+1] == '\0') {
92 // Unless it is the pseudo-directory "."...
93 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
96 if (pos > 0 && path[pos-1] == '.') {
97 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
108 static Path *TempDirectory = NULL;
111 Path::GetTemporaryDirectory(std::string* ErrMsg) {
113 return *TempDirectory;
115 char pathname[MAX_PATH];
116 if (!GetTempPath(MAX_PATH, pathname)) {
118 *ErrMsg = "Can't determine temporary directory";
123 result.set(pathname);
125 // Append a subdirectory passed on our process id so multiple LLVMs don't
126 // step on each other's toes.
128 // Mingw's Win32 header files are broken.
129 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
131 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
133 result.appendComponent(pathname);
135 // If there's a directory left over from a previous LLVM execution that
136 // happened to have the same process id, get rid of it.
137 result.eraseFromDisk(true);
139 // And finally (re-)create the empty directory.
140 result.createDirectoryOnDisk(false);
141 TempDirectory = new Path(result);
142 return *TempDirectory;
145 // FIXME: the following set of functions don't map to Windows very well.
147 Path::GetRootDirectory() {
153 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
154 const char* at = path;
155 const char* delim = strchr(at, ';');
158 std::string tmp(at, size_t(delim-at));
159 if (tmpPath.set(tmp))
160 if (tmpPath.canRead())
161 Paths.push_back(tmpPath);
163 delim = strchr(at, ';');
167 if (tmpPath.set(std::string(at)))
168 if (tmpPath.canRead())
169 Paths.push_back(tmpPath);
173 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
174 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
175 Paths.push_back(sys::Path("C:/WINDOWS"));
179 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
180 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
182 getPathList(env_var,Paths);
187 if (tmpPath.set(LLVM_LIBDIR))
188 if (tmpPath.canRead())
189 Paths.push_back(tmpPath);
192 GetSystemLibraryPaths(Paths);
196 Path::GetLLVMDefaultConfigDir() {
197 // TODO: this isn't going to fly on Windows
198 return Path("/etc/llvm");
202 Path::GetUserHomeDirectory() {
203 // TODO: Typical Windows setup doesn't define HOME.
204 const char* home = getenv("HOME");
207 if (result.set(home))
210 return GetRootDirectory();
212 // FIXME: the above set of functions don't map to Windows very well.
216 Path::isRootDirectory() const {
217 size_t len = path.size();
218 return len > 0 && path[len-1] == '/';
222 Path::getBasename() const {
223 // Find the last slash
224 size_t slash = path.rfind('/');
225 if (slash == std::string::npos)
230 size_t dot = path.rfind('.');
231 if (dot == std::string::npos || dot < slash)
232 return path.substr(slash);
234 return path.substr(slash, dot - slash);
237 bool Path::hasMagicNumber(const std::string &Magic) const {
238 std::string actualMagic;
239 if (getMagicNumber(actualMagic, Magic.size()))
240 return Magic == actualMagic;
245 Path::isBytecodeFile() const {
246 std::string actualMagic;
247 if (!getMagicNumber(actualMagic, 4))
249 return actualMagic == "llvc" || actualMagic == "llvm";
253 Path::exists() const {
254 DWORD attr = GetFileAttributes(path.c_str());
255 return attr != INVALID_FILE_ATTRIBUTES;
259 Path::canRead() const {
260 // FIXME: take security attributes into account.
261 DWORD attr = GetFileAttributes(path.c_str());
262 return attr != INVALID_FILE_ATTRIBUTES;
266 Path::canWrite() const {
267 // FIXME: take security attributes into account.
268 DWORD attr = GetFileAttributes(path.c_str());
269 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
273 Path::canExecute() const {
274 // FIXME: take security attributes into account.
275 DWORD attr = GetFileAttributes(path.c_str());
276 return attr != INVALID_FILE_ATTRIBUTES;
280 Path::getLast() const {
281 // Find the last slash
282 size_t pos = path.rfind('/');
284 // Handle the corner cases
285 if (pos == std::string::npos)
288 // If the last character is a slash, we have a root directory
289 if (pos == path.length()-1)
292 // Return everything after the last slash
293 return path.substr(pos+1);
297 Path::getFileStatus(FileStatus &info, std::string *ErrStr) const {
298 WIN32_FILE_ATTRIBUTE_DATA fi;
299 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
300 return MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
301 ": Can't get status: ");
303 info.fileSize = fi.nFileSizeHigh;
304 info.fileSize <<= sizeof(fi.nFileSizeHigh)*8;
305 info.fileSize += fi.nFileSizeLow;
307 info.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
308 info.user = 9999; // Not applicable to Windows, so...
309 info.group = 9999; // Not applicable to Windows, so...
311 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
312 info.modTime.fromWin32Time(ft);
314 info.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
318 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
319 // All files are readable on Windows (ignoring security attributes).
323 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
324 DWORD attr = GetFileAttributes(path.c_str());
326 // If it doesn't exist, we're done.
327 if (attr == INVALID_FILE_ATTRIBUTES)
330 if (attr & FILE_ATTRIBUTE_READONLY) {
331 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
332 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
339 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
340 // All files are executable on Windows (ignoring security attributes).
345 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
347 if (getFileStatus(Status, ErrMsg))
351 MakeErrMsg(ErrMsg, path + ": not a directory");
357 std::string searchpath = path;
358 if (path.size() == 0 || searchpath[path.size()-1] == '/')
363 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
364 if (h == INVALID_HANDLE_VALUE) {
365 if (GetLastError() == ERROR_FILE_NOT_FOUND)
366 return true; // not really an error, now is it?
367 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
372 if (fd.cFileName[0] == '.')
375 aPath.appendComponent(&fd.cFileName[0]);
376 result.insert(aPath);
377 } while (FindNextFile(h, &fd));
379 DWORD err = GetLastError();
381 if (err != ERROR_NO_MORE_FILES) {
383 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
390 Path::set(const std::string& a_path) {
391 if (a_path.size() == 0)
393 std::string save(path);
395 FlipBackSlashes(path);
404 Path::appendComponent(const std::string& name) {
407 std::string save(path);
409 size_t last = path.size() - 1;
410 if (path[last] != '/')
422 Path::eraseComponent() {
423 size_t slashpos = path.rfind('/',path.size());
424 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
426 std::string save(path);
427 path.erase(slashpos);
436 Path::appendSuffix(const std::string& suffix) {
437 std::string save(path);
448 Path::eraseSuffix() {
449 size_t dotpos = path.rfind('.',path.size());
450 size_t slashpos = path.rfind('/',path.size());
451 if (dotpos != std::string::npos) {
452 if (slashpos == std::string::npos || dotpos > slashpos+1) {
453 std::string save(path);
454 path.erase(dotpos, path.size()-dotpos);
465 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
467 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
472 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
473 // Get a writeable copy of the path name
474 size_t len = path.length();
475 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
476 path.copy(pathname, len);
479 // Make sure it ends with a slash.
480 if (len == 0 || pathname[len - 1] != '/') {
485 // Determine starting point for initial / search.
486 char *next = pathname;
487 if (pathname[0] == '/' && pathname[1] == '/') {
489 next = strchr(pathname+2, '/');
491 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
494 next = strchr(next+1, '/');
496 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
500 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
503 if (pathname[1] == ':')
504 next += 2; // skip drive letter
506 next++; // skip root directory
509 // If we're supposed to create intermediate directories
510 if (create_parents) {
511 // Loop through the directory components until we're done
513 next = strchr(next, '/');
515 if (!CreateDirectory(pathname, NULL))
516 return MakeErrMsg(ErrMsg,
517 std::string(pathname) + ": Can't create directory: ");
521 // Drop trailing slash.
523 if (!CreateDirectory(pathname, NULL)) {
524 return MakeErrMsg(ErrMsg, std::string(pathname) + ": Can't create directory: ");
531 Path::createFileOnDisk(std::string* ErrMsg) {
533 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
534 FILE_ATTRIBUTE_NORMAL, NULL);
535 if (h == INVALID_HANDLE_VALUE)
536 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
543 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
545 if (getFileStatus(Status, ErrStr))
549 DWORD attr = GetFileAttributes(path.c_str());
551 // If it doesn't exist, we're done.
552 if (attr == INVALID_FILE_ATTRIBUTES)
555 // Read-only files cannot be deleted on Windows. Must remove the read-only
557 if (attr & FILE_ATTRIBUTE_READONLY) {
558 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
559 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
562 if (!DeleteFile(path.c_str()))
563 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
565 } else if (Status.isDir) {
566 // If it doesn't exist, we're done.
570 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
571 int lastchar = path.length() - 1 ;
572 path.copy(pathname, lastchar+1);
574 // Make path end with '/*'.
575 if (pathname[lastchar] != '/')
576 pathname[++lastchar] = '/';
577 pathname[lastchar+1] = '*';
578 pathname[lastchar+2] = 0;
580 if (remove_contents) {
582 HANDLE h = FindFirstFile(pathname, &fd);
584 // It's a bad idea to alter the contents of a directory while enumerating
585 // its contents. So build a list of its contents first, then destroy them.
587 if (h != INVALID_HANDLE_VALUE) {
588 std::vector<Path> list;
591 if (strcmp(fd.cFileName, ".") == 0)
593 if (strcmp(fd.cFileName, "..") == 0)
597 aPath.appendComponent(&fd.cFileName[0]);
598 list.push_back(aPath);
599 } while (FindNextFile(h, &fd));
601 DWORD err = GetLastError();
603 if (err != ERROR_NO_MORE_FILES) {
605 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
608 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
611 aPath.eraseFromDisk(true);
614 if (GetLastError() != ERROR_FILE_NOT_FOUND)
615 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
619 pathname[lastchar] = 0;
620 if (!RemoveDirectory(pathname))
621 return MakeErrMsg(ErrStr,
622 std::string(pathname) + ": Can't destroy directory: ");
625 // It appears the path doesn't exist.
629 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
630 assert(len < 1024 && "Request for magic string too long");
631 char* buf = (char*) alloca(1 + len);
633 HANDLE h = CreateFile(path.c_str(),
638 FILE_ATTRIBUTE_NORMAL,
640 if (h == INVALID_HANDLE_VALUE)
644 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
647 if (!ret || nRead != len)
656 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
657 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
658 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
664 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
665 // FIXME: should work on directories also.
670 HANDLE h = CreateFile(path.c_str(),
671 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
672 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
675 FILE_ATTRIBUTE_NORMAL,
677 if (h == INVALID_HANDLE_VALUE)
680 BY_HANDLE_FILE_INFORMATION bhfi;
681 if (!GetFileInformationByHandle(h, &bhfi)) {
682 DWORD err = GetLastError();
685 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
689 (uint64_t&)ft = si.modTime.toWin32Time();
690 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
691 DWORD err = GetLastError();
695 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
698 // Best we can do with Unix permission bits is to interpret the owner
700 if (si.mode & 0200) {
701 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
702 if (!SetFileAttributes(path.c_str(),
703 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
704 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
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: ");
718 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
719 // Can't use CopyFile macro defined in Windows.h because it would mess up the
720 // above line. We use the expansion it would have in a non-UNICODE build.
721 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
722 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.toString() +
723 "' to '" + Dest.toString() + "': ");
728 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
729 if (reuse_current && !exists())
730 return false; // File doesn't exist already, just use it!
732 // Reserve space for -XXXXXX at the end.
733 char *FNBuffer = (char*) alloca(path.size()+8);
734 unsigned offset = path.size();
735 path.copy(FNBuffer, offset);
737 // Find a numeric suffix that isn't used by an existing file. Assume there
738 // won't be more than 1 million files with the same prefix. Probably a safe
740 static unsigned FCounter = 0;
742 sprintf(FNBuffer+offset, "-%06u", FCounter);
743 if (++FCounter > 999999)
751 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
752 // Make this into a unique file name
753 makeUnique(reuse_current, ErrMsg);
755 // Now go and create it
756 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
757 FILE_ATTRIBUTE_NORMAL, NULL);
758 if (h == INVALID_HANDLE_VALUE)
759 return MakeErrMsg(ErrMsg, path + ": can't create file");