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() {
113 return *TempDirectory;
115 char pathname[MAX_PATH];
116 if (!GetTempPath(MAX_PATH, pathname))
117 throw std::string("Can't determine temporary directory");
120 result.set(pathname);
122 // Append a subdirectory passed on our process id so multiple LLVMs don't
123 // step on each other's toes.
124 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
125 result.appendComponent(pathname);
127 // If there's a directory left over from a previous LLVM execution that
128 // happened to have the same process id, get rid of it.
129 result.eraseFromDisk(true);
131 // And finally (re-)create the empty directory.
132 result.createDirectoryOnDisk(false);
133 TempDirectory = new Path(result);
134 return *TempDirectory;
137 Path::Path(const std::string& unverified_path)
138 : path(unverified_path)
140 FlipBackSlashes(path);
141 if (unverified_path.empty())
147 throw std::string(unverified_path + ": path is not valid");
150 // FIXME: the following set of functions don't map to Windows very well.
152 Path::GetRootDirectory() {
158 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
159 const char* at = path;
160 const char* delim = strchr(at, ';');
163 std::string tmp(at, size_t(delim-at));
164 if (tmpPath.set(tmp))
165 if (tmpPath.canRead())
166 Paths.push_back(tmpPath);
168 delim = strchr(at, ';');
172 if (tmpPath.set(std::string(at)))
173 if (tmpPath.canRead())
174 Paths.push_back(tmpPath);
178 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
179 Paths.push_back(sys::Path("C:/WINDOWS/SYSTEM32"));
180 Paths.push_back(sys::Path("C:/WINDOWS"));
184 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
185 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
187 getPathList(env_var,Paths);
192 if (tmpPath.set(LLVM_LIBDIR))
193 if (tmpPath.canRead())
194 Paths.push_back(tmpPath);
197 GetSystemLibraryPaths(Paths);
201 Path::GetLLVMDefaultConfigDir() {
202 // TODO: this isn't going to fly on Windows
203 return Path("/etc/llvm");
207 Path::GetUserHomeDirectory() {
208 // TODO: Typical Windows setup doesn't define HOME.
209 const char* home = getenv("HOME");
212 if (result.set(home))
215 return GetRootDirectory();
217 // FIXME: the above set of functions don't map to Windows very well.
220 Path::isFile() const {
221 WIN32_FILE_ATTRIBUTE_DATA fi;
222 BOOL rc = GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi);
224 return !(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
225 else if (GetLastError() != ERROR_FILE_NOT_FOUND) {
226 ThrowError("isFile(): " + std::string(path) + ": Can't get status: ");
232 Path::isDirectory() const {
233 WIN32_FILE_ATTRIBUTE_DATA fi;
234 BOOL rc = GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi);
236 return fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
237 else if (GetLastError() != ERROR_FILE_NOT_FOUND)
238 ThrowError("isDirectory(): " + std::string(path) + ": Can't get status: ");
243 Path::isHidden() const {
244 WIN32_FILE_ATTRIBUTE_DATA fi;
245 BOOL rc = GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi);
247 return fi.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN;
248 else if (GetLastError() != ERROR_FILE_NOT_FOUND)
249 ThrowError("isHidden(): " + std::string(path) + ": Can't get status: ");
254 Path::isRootDirectory() const {
255 size_t len = path.size();
256 return len > 0 && path[len-1] == '/';
260 Path::getBasename() const {
261 // Find the last slash
262 size_t slash = path.rfind('/');
263 if (slash == std::string::npos)
268 size_t dot = path.rfind('.');
269 if (dot == std::string::npos || dot < slash)
270 return path.substr(slash);
272 return path.substr(slash, dot - slash);
275 bool Path::hasMagicNumber(const std::string &Magic) const {
276 std::string actualMagic;
277 if (getMagicNumber(actualMagic, Magic.size()))
278 return Magic == actualMagic;
283 Path::isBytecodeFile() const {
286 std::string actualMagic;
287 if (!getMagicNumber(actualMagic, 4))
289 return actualMagic == "llvc" || actualMagic == "llvm";
293 Path::exists() const {
294 DWORD attr = GetFileAttributes(path.c_str());
295 return attr != INVALID_FILE_ATTRIBUTES;
299 Path::canRead() const {
300 // FIXME: take security attributes into account.
301 DWORD attr = GetFileAttributes(path.c_str());
302 return attr != INVALID_FILE_ATTRIBUTES;
306 Path::canWrite() const {
307 // FIXME: take security attributes into account.
308 DWORD attr = GetFileAttributes(path.c_str());
309 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
313 Path::canExecute() const {
314 // FIXME: take security attributes into account.
315 DWORD attr = GetFileAttributes(path.c_str());
316 return attr != INVALID_FILE_ATTRIBUTES;
320 Path::getLast() const {
321 // Find the last slash
322 size_t pos = path.rfind('/');
324 // Handle the corner cases
325 if (pos == std::string::npos)
328 // If the last character is a slash, we have a root directory
329 if (pos == path.length()-1)
332 // Return everything after the last slash
333 return path.substr(pos+1);
337 Path::getStatusInfo(StatusInfo& info) const {
338 WIN32_FILE_ATTRIBUTE_DATA fi;
339 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
340 ThrowError("getStatusInfo():" + std::string(path) + ": Can't get status: ");
342 info.fileSize = fi.nFileSizeHigh;
343 info.fileSize <<= 32;
344 info.fileSize += fi.nFileSizeLow;
346 info.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
347 info.user = 9999; // Not applicable to Windows, so...
348 info.group = 9999; // Not applicable to Windows, so...
350 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
351 info.modTime.fromWin32Time(ft);
353 info.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
356 static bool AddPermissionBits(const std::string& Filename, int bits) {
357 DWORD attr = GetFileAttributes(Filename.c_str());
359 // If it doesn't exist, we're done.
360 if (attr == INVALID_FILE_ATTRIBUTES)
363 // The best we can do to interpret Unix permission bits is to use
364 // the owner writable bit.
365 if ((attr & FILE_ATTRIBUTE_READONLY) && (bits & 0200)) {
366 if (!SetFileAttributes(Filename.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
367 ThrowError(Filename + ": SetFileAttributes: ");
372 void Path::makeReadableOnDisk() {
373 // All files are readable on Windows (ignoring security attributes).
376 void Path::makeWriteableOnDisk() {
377 DWORD attr = GetFileAttributes(path.c_str());
379 // If it doesn't exist, we're done.
380 if (attr == INVALID_FILE_ATTRIBUTES)
383 if (attr & FILE_ATTRIBUTE_READONLY) {
384 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
385 ThrowError(std::string(path) + ": Can't make file writable: ");
389 void Path::makeExecutableOnDisk() {
390 // All files are executable on Windows (ignoring security attributes).
394 Path::getDirectoryContents(std::set<Path>& result) const {
400 std::string searchpath = path;
401 if (path.size() == 0 || searchpath[path.size()-1] == '/')
406 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
407 if (h == INVALID_HANDLE_VALUE) {
408 if (GetLastError() == ERROR_FILE_NOT_FOUND)
409 return true; // not really an error, now is it?
410 ThrowError(path + ": Can't read directory: ");
414 if (fd.cFileName[0] == '.')
417 aPath.appendComponent(&fd.cFileName[0]);
418 result.insert(aPath);
419 } while (FindNextFile(h, &fd));
421 DWORD err = GetLastError();
423 if (err != ERROR_NO_MORE_FILES) {
425 ThrowError(path + ": Can't read directory: ");
431 Path::set(const std::string& a_path) {
432 if (a_path.size() == 0)
434 std::string save(path);
436 FlipBackSlashes(path);
445 Path::appendComponent(const std::string& name) {
448 std::string save(path);
450 size_t last = path.size() - 1;
451 if (path[last] != '/')
463 Path::eraseComponent() {
464 size_t slashpos = path.rfind('/',path.size());
465 if (slashpos == path.size() - 1 || slashpos == std::string::npos)
467 std::string save(path);
468 path.erase(slashpos);
477 Path::appendSuffix(const std::string& suffix) {
478 std::string save(path);
489 Path::eraseSuffix() {
490 size_t dotpos = path.rfind('.',path.size());
491 size_t slashpos = path.rfind('/',path.size());
492 if (dotpos != std::string::npos) {
493 if (slashpos == std::string::npos || dotpos > slashpos+1) {
494 std::string save(path);
495 path.erase(dotpos, path.size()-dotpos);
507 Path::createDirectoryOnDisk(bool create_parents) {
508 // Get a writeable copy of the path name
509 size_t len = path.length();
510 char *pathname = reinterpret_cast<char *>(_alloca(len+2));
511 path.copy(pathname, len);
514 // Make sure it ends with a slash.
515 if (len == 0 || pathname[len - 1] != '/') {
520 // Determine starting point for initial / search.
521 char *next = pathname;
522 if (pathname[0] == '/' && pathname[1] == '/') {
524 next = strchr(pathname+2, '/');
526 throw std::string(pathname) + ": badly formed remote directory";
528 next = strchr(next+1, '/');
530 throw std::string(pathname) + ": badly formed remote directory";
533 throw std::string(pathname) + ": badly formed remote directory";
535 if (pathname[1] == ':')
536 next += 2; // skip drive letter
538 next++; // skip root directory
541 // If we're supposed to create intermediate directories
542 if (create_parents) {
543 // Loop through the directory components until we're done
545 next = strchr(next, '/');
547 if (!CreateDirectory(pathname, NULL))
548 ThrowError(std::string(pathname) + ": Can't create directory: ");
552 // Drop trailing slash.
554 if (!CreateDirectory(pathname, NULL)) {
555 ThrowError(std::string(pathname) + ": Can't create directory: ");
562 Path::createFileOnDisk() {
564 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
565 FILE_ATTRIBUTE_NORMAL, NULL);
566 if (h == INVALID_HANDLE_VALUE)
567 ThrowError(path + ": Can't create file: ");
574 Path::eraseFromDisk(bool remove_contents) const {
576 DWORD attr = GetFileAttributes(path.c_str());
578 // If it doesn't exist, we're done.
579 if (attr == INVALID_FILE_ATTRIBUTES)
582 // Read-only files cannot be deleted on Windows. Must remove the read-only
584 if (attr & FILE_ATTRIBUTE_READONLY) {
585 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
586 ThrowError(path + ": Can't destroy file: ");
589 if (!DeleteFile(path.c_str()))
590 ThrowError(path + ": Can't destroy file: ");
592 } else if (isDirectory()) {
593 // If it doesn't exist, we're done.
597 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+3));
598 int lastchar = path.length() - 1 ;
599 path.copy(pathname, lastchar+1);
601 // Make path end with '/*'.
602 if (pathname[lastchar] != '/')
603 pathname[++lastchar] = '/';
604 pathname[lastchar+1] = '*';
605 pathname[lastchar+2] = 0;
607 if (remove_contents) {
609 HANDLE h = FindFirstFile(pathname, &fd);
611 // It's a bad idea to alter the contents of a directory while enumerating
612 // its contents. So build a list of its contents first, then destroy them.
614 if (h != INVALID_HANDLE_VALUE) {
615 std::vector<Path> list;
618 if (strcmp(fd.cFileName, ".") == 0)
620 if (strcmp(fd.cFileName, "..") == 0)
624 aPath.appendComponent(&fd.cFileName[0]);
625 list.push_back(aPath);
626 } while (FindNextFile(h, &fd));
628 DWORD err = GetLastError();
630 if (err != ERROR_NO_MORE_FILES) {
632 ThrowError(path + ": Can't read directory: ");
635 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
638 aPath.eraseFromDisk(true);
641 if (GetLastError() != ERROR_FILE_NOT_FOUND)
642 ThrowError(path + ": Can't read directory: ");
646 pathname[lastchar] = 0;
647 if (!RemoveDirectory(pathname))
648 ThrowError(std::string(pathname) + ": Can't destroy directory: ");
651 // It appears the path doesn't exist.
656 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
659 assert(len < 1024 && "Request for magic string too long");
660 char* buf = (char*) alloca(1 + len);
662 HANDLE h = CreateFile(path.c_str(),
667 FILE_ATTRIBUTE_NORMAL,
669 if (h == INVALID_HANDLE_VALUE)
673 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
676 if (!ret || nRead != len)
685 Path::renamePathOnDisk(const Path& newName) {
686 if (!MoveFileEx(path.c_str(), newName.c_str(), MOVEFILE_REPLACE_EXISTING))
687 ThrowError("Can't move '" + path +
688 "' to '" + newName.path + "': ");
693 Path::setStatusInfoOnDisk(const StatusInfo& si) const {
694 // FIXME: should work on directories also.
695 if (!isFile()) return false;
697 HANDLE h = CreateFile(path.c_str(),
698 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
699 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
702 FILE_ATTRIBUTE_NORMAL,
704 if (h == INVALID_HANDLE_VALUE)
707 BY_HANDLE_FILE_INFORMATION bhfi;
708 if (!GetFileInformationByHandle(h, &bhfi)) {
709 DWORD err = GetLastError();
712 ThrowError(path + ": GetFileInformationByHandle: ");
716 (uint64_t&)ft = si.modTime.toWin32Time();
717 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
718 DWORD err = GetLastError();
722 ThrowError(path + ": SetFileTime: ");
725 // Best we can do with Unix permission bits is to interpret the owner
727 if (si.mode & 0200) {
728 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
729 if (!SetFileAttributes(path.c_str(),
730 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
731 ThrowError(path + ": SetFileAttributes: ");
734 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
735 if (!SetFileAttributes(path.c_str(),
736 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
737 ThrowError(path + ": SetFileAttributes: ");
745 CopyFile(const sys::Path &Dest, const sys::Path &Src) {
746 // Can't use CopyFile macro defined in Windows.h because it would mess up the
747 // above line. We use the expansion it would have in a non-UNICODE build.
748 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
749 ThrowError("Can't copy '" + Src.toString() +
750 "' to '" + Dest.toString() + "': ");
754 Path::makeUnique(bool reuse_current) {
755 if (reuse_current && !exists())
756 return; // 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)
776 Path::createTemporaryFileOnDisk(bool reuse_current) {
777 // Make this into a unique file name
778 makeUnique(reuse_current);
780 // Now go and create it
781 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
782 FILE_ATTRIBUTE_NORMAL, NULL);
783 if (h == INVALID_HANDLE_VALUE)