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] == ':')
109 Path::isAbsolute() const {
110 switch (path.length()) {
115 return path[0] == '/';
117 return path[0] == '/' || (path[1] == ':' && path[2] == '/');
121 static Path *TempDirectory = NULL;
124 Path::GetTemporaryDirectory(std::string* ErrMsg) {
126 return *TempDirectory;
128 char pathname[MAX_PATH];
129 if (!GetTempPath(MAX_PATH, pathname)) {
131 *ErrMsg = "Can't determine temporary directory";
136 result.set(pathname);
138 // Append a subdirectory passed on our process id so multiple LLVMs don't
139 // step on each other's toes.
141 // Mingw's Win32 header files are broken.
142 sprintf(pathname, "LLVM_%u", unsigned(GetCurrentProcessId()));
144 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
146 result.appendComponent(pathname);
148 // If there's a directory left over from a previous LLVM execution that
149 // happened to have the same process id, get rid of it.
150 result.eraseFromDisk(true);
152 // And finally (re-)create the empty directory.
153 result.createDirectoryOnDisk(false);
154 TempDirectory = new Path(result);
155 return *TempDirectory;
158 // FIXME: the following set of functions don't map to Windows very well.
160 Path::GetRootDirectory() {
166 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
167 const char* at = path;
168 const char* delim = strchr(at, ';');
171 std::string tmp(at, size_t(delim-at));
172 if (tmpPath.set(tmp))
173 if (tmpPath.canRead())
174 Paths.push_back(tmpPath);
176 delim = strchr(at, ';');
180 if (tmpPath.set(std::string(at)))
181 if (tmpPath.canRead())
182 Paths.push_back(tmpPath);
186 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
187 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
188 Paths.push_back(sys::Path("C:/WINDOWS"));
192 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
193 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
195 getPathList(env_var,Paths);
200 if (tmpPath.set(LLVM_LIBDIR))
201 if (tmpPath.canRead())
202 Paths.push_back(tmpPath);
205 GetSystemLibraryPaths(Paths);
209 Path::GetLLVMDefaultConfigDir() {
210 // TODO: this isn't going to fly on Windows
211 return Path("/etc/llvm");
215 Path::GetUserHomeDirectory() {
216 // TODO: Typical Windows setup doesn't define HOME.
217 const char* home = getenv("HOME");
220 if (result.set(home))
223 return GetRootDirectory();
225 // FIXME: the above set of functions don't map to Windows very well.
229 Path::isRootDirectory() const {
230 size_t len = path.size();
231 return len > 0 && path[len-1] == '/';
235 Path::getBasename() const {
236 // Find the last slash
237 size_t slash = path.rfind('/');
238 if (slash == std::string::npos)
243 size_t dot = path.rfind('.');
244 if (dot == std::string::npos || dot < slash)
245 return path.substr(slash);
247 return path.substr(slash, dot - slash);
250 bool Path::hasMagicNumber(const std::string &Magic) const {
251 std::string actualMagic;
252 if (getMagicNumber(actualMagic, Magic.size()))
253 return Magic == actualMagic;
258 Path::isBytecodeFile() const {
259 std::string actualMagic;
260 if (!getMagicNumber(actualMagic, 4))
262 return actualMagic == "llvc" || actualMagic == "llvm";
266 Path::exists() const {
267 DWORD attr = GetFileAttributes(path.c_str());
268 return attr != INVALID_FILE_ATTRIBUTES;
272 Path::canRead() const {
273 // FIXME: take security attributes into account.
274 DWORD attr = GetFileAttributes(path.c_str());
275 return attr != INVALID_FILE_ATTRIBUTES;
279 Path::canWrite() const {
280 // FIXME: take security attributes into account.
281 DWORD attr = GetFileAttributes(path.c_str());
282 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
286 Path::canExecute() const {
287 // FIXME: take security attributes into account.
288 DWORD attr = GetFileAttributes(path.c_str());
289 return attr != INVALID_FILE_ATTRIBUTES;
293 Path::getLast() const {
294 // Find the last slash
295 size_t pos = path.rfind('/');
297 // Handle the corner cases
298 if (pos == std::string::npos)
301 // If the last character is a slash, we have a root directory
302 if (pos == path.length()-1)
305 // Return everything after the last slash
306 return path.substr(pos+1);
310 Path::getFileStatus(FileStatus &info, bool update, std::string *ErrStr) const {
311 if (status == 0 || update) {
312 WIN32_FILE_ATTRIBUTE_DATA fi;
313 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
314 return MakeErrMsg(ErrStr, "getStatusInfo():" + std::string(path) +
315 ": Can't get status: ");
318 status = new FileStatus;
320 status->fileSize = fi.nFileSizeHigh;
321 status->fileSize <<= sizeof(fi.nFileSizeHigh)*8;
322 status->fileSize += fi.nFileSizeLow;
324 status->mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
325 status->user = 9999; // Not applicable to Windows, so...
326 status->group = 9999; // Not applicable to Windows, so...
328 // FIXME: this is only unique if the file is accessed by the same file path.
329 // How do we do this for C:\dir\file and ..\dir\file ? Unix has inode
330 // numbers, but the concept doesn't exist in Windows.
331 status->uniqueID = 0;
332 for (unsigned i = 0; i < path.length(); ++i)
333 status->uniqueID += path[i];
335 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
336 status->modTime.fromWin32Time(ft);
338 status->isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
344 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
345 // All files are readable on Windows (ignoring security attributes).
349 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
350 DWORD attr = GetFileAttributes(path.c_str());
352 // If it doesn't exist, we're done.
353 if (attr == INVALID_FILE_ATTRIBUTES)
356 if (attr & FILE_ATTRIBUTE_READONLY) {
357 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY)) {
358 MakeErrMsg(ErrMsg, std::string(path) + ": Can't make file writable: ");
365 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
366 // All files are executable on Windows (ignoring security attributes).
371 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
373 if (getFileStatus(Status, ErrMsg))
377 MakeErrMsg(ErrMsg, path + ": not a directory");
383 std::string searchpath = path;
384 if (path.size() == 0 || searchpath[path.size()-1] == '/')
389 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
390 if (h == INVALID_HANDLE_VALUE) {
391 if (GetLastError() == ERROR_FILE_NOT_FOUND)
392 return true; // not really an error, now is it?
393 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
398 if (fd.cFileName[0] == '.')
401 aPath.appendComponent(&fd.cFileName[0]);
402 result.insert(aPath);
403 } while (FindNextFile(h, &fd));
405 DWORD err = GetLastError();
407 if (err != ERROR_NO_MORE_FILES) {
409 MakeErrMsg(ErrMsg, path + ": Can't read directory: ");
416 Path::set(const std::string& a_path) {
417 if (a_path.size() == 0)
419 std::string save(path);
421 FlipBackSlashes(path);
430 Path::appendComponent(const std::string& name) {
433 std::string save(path);
435 size_t last = path.size() - 1;
436 if (path[last] != '/')
448 Path::eraseComponent() {
449 size_t slashpos = path.rfind('/',path.size());
450 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
452 std::string save(path);
453 path.erase(slashpos);
462 Path::appendSuffix(const std::string& suffix) {
463 std::string save(path);
474 Path::eraseSuffix() {
475 size_t dotpos = path.rfind('.',path.size());
476 size_t slashpos = path.rfind('/',path.size());
477 if (dotpos != std::string::npos) {
478 if (slashpos == std::string::npos || dotpos > slashpos+1) {
479 std::string save(path);
480 path.erase(dotpos, path.size()-dotpos);
491 inline bool PathMsg(std::string* ErrMsg, const char* pathname, const char*msg) {
493 *ErrMsg = std::string(pathname) + ": " + std::string(msg);
498 Path::createDirectoryOnDisk(bool create_parents, std::string* ErrMsg) {
499 // Get a writeable copy of the path name
500 size_t len = path.length();
501 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
502 path.copy(pathname, len);
505 // Make sure it ends with a slash.
506 if (len == 0 || pathname[len - 1] != '/') {
511 // Determine starting point for initial / search.
512 char *next = pathname;
513 if (pathname[0] == '/' && pathname[1] == '/') {
515 next = strchr(pathname+2, '/');
517 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
520 next = strchr(next+1, '/');
522 return PathMsg(ErrMsg, pathname,"badly formed remote directory");
526 return PathMsg(ErrMsg, pathname, "badly formed remote directory");
529 if (pathname[1] == ':')
530 next += 2; // skip drive letter
532 next++; // skip root directory
535 // If we're supposed to create intermediate directories
536 if (create_parents) {
537 // Loop through the directory components until we're done
539 next = strchr(next, '/');
541 if (!CreateDirectory(pathname, NULL))
542 return MakeErrMsg(ErrMsg,
543 std::string(pathname) + ": Can't create directory: ");
547 // Drop trailing slash.
549 if (!CreateDirectory(pathname, NULL)) {
550 return MakeErrMsg(ErrMsg, std::string(pathname) + ": Can't create directory: ");
557 Path::createFileOnDisk(std::string* ErrMsg) {
559 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
560 FILE_ATTRIBUTE_NORMAL, NULL);
561 if (h == INVALID_HANDLE_VALUE)
562 return MakeErrMsg(ErrMsg, path + ": Can't create file: ");
569 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
571 if (getFileStatus(Status, ErrStr))
575 DWORD attr = GetFileAttributes(path.c_str());
577 // If it doesn't exist, we're done.
578 if (attr == INVALID_FILE_ATTRIBUTES)
581 // Read-only files cannot be deleted on Windows. Must remove the read-only
583 if (attr & FILE_ATTRIBUTE_READONLY) {
584 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
585 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
588 if (!DeleteFile(path.c_str()))
589 return MakeErrMsg(ErrStr, path + ": Can't destroy file: ");
591 } else if (Status.isDir) {
592 // If it doesn't exist, we're done.
596 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
597 int lastchar = path.length() - 1 ;
598 path.copy(pathname, lastchar+1);
600 // Make path end with '/*'.
601 if (pathname[lastchar] != '/')
602 pathname[++lastchar] = '/';
603 pathname[lastchar+1] = '*';
604 pathname[lastchar+2] = 0;
606 if (remove_contents) {
608 HANDLE h = FindFirstFile(pathname, &fd);
610 // It's a bad idea to alter the contents of a directory while enumerating
611 // its contents. So build a list of its contents first, then destroy them.
613 if (h != INVALID_HANDLE_VALUE) {
614 std::vector<Path> list;
617 if (strcmp(fd.cFileName, ".") == 0)
619 if (strcmp(fd.cFileName, "..") == 0)
623 aPath.appendComponent(&fd.cFileName[0]);
624 list.push_back(aPath);
625 } while (FindNextFile(h, &fd));
627 DWORD err = GetLastError();
629 if (err != ERROR_NO_MORE_FILES) {
631 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
634 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
637 aPath.eraseFromDisk(true);
640 if (GetLastError() != ERROR_FILE_NOT_FOUND)
641 return MakeErrMsg(ErrStr, path + ": Can't read directory: ");
645 pathname[lastchar] = 0;
646 if (!RemoveDirectory(pathname))
647 return MakeErrMsg(ErrStr,
648 std::string(pathname) + ": Can't destroy directory: ");
651 // It appears the path doesn't exist.
655 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
656 assert(len < 1024 && "Request for magic string too long");
657 char* buf = (char*) alloca(1 + len);
659 HANDLE h = CreateFile(path.c_str(),
664 FILE_ATTRIBUTE_NORMAL,
666 if (h == INVALID_HANDLE_VALUE)
670 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
673 if (!ret || nRead != len)
682 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
683 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
684 return MakeErrMsg(ErrMsg, "Can't move '" + path + "' to '" + newName.path
690 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrMsg) const {
691 // FIXME: should work on directories also.
696 HANDLE h = CreateFile(path.c_str(),
697 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
698 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
701 FILE_ATTRIBUTE_NORMAL,
703 if (h == INVALID_HANDLE_VALUE)
706 BY_HANDLE_FILE_INFORMATION bhfi;
707 if (!GetFileInformationByHandle(h, &bhfi)) {
708 DWORD err = GetLastError();
711 return MakeErrMsg(ErrMsg, path + ": GetFileInformationByHandle: ");
715 (uint64_t&)ft = si.modTime.toWin32Time();
716 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
717 DWORD err = GetLastError();
721 return MakeErrMsg(ErrMsg, path + ": SetFileTime: ");
724 // Best we can do with Unix permission bits is to interpret the owner
726 if (si.mode & 0200) {
727 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
728 if (!SetFileAttributes(path.c_str(),
729 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
730 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
733 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
734 if (!SetFileAttributes(path.c_str(),
735 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
736 return MakeErrMsg(ErrMsg, path + ": SetFileAttributes: ");
744 CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg) {
745 // Can't use CopyFile macro defined in Windows.h because it would mess up the
746 // above line. We use the expansion it would have in a non-UNICODE build.
747 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
748 return MakeErrMsg(ErrMsg, "Can't copy '" + Src.toString() +
749 "' to '" + Dest.toString() + "': ");
754 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
755 if (reuse_current && !exists())
756 return false; // File doesn't exist already, just use it!
758 // Reserve space for -XXXXXX at the end.
759 char *FNBuffer = (char*) alloca(path.size()+8);
760 unsigned offset = path.size();
761 path.copy(FNBuffer, offset);
763 // Find a numeric suffix that isn't used by an existing file. Assume there
764 // won't be more than 1 million files with the same prefix. Probably a safe
766 static unsigned FCounter = 0;
768 sprintf(FNBuffer+offset, "-%06u", FCounter);
769 if (++FCounter > 999999)
777 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
778 // Make this into a unique file name
779 makeUnique(reuse_current, ErrMsg);
781 // Now go and create it
782 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
783 FILE_ATTRIBUTE_NORMAL, NULL);
784 if (h == INVALID_HANDLE_VALUE)
785 return MakeErrMsg(ErrMsg, path + ": can't create file");