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 static void FlipBackSlashes(std::string& s) {
29 for (size_t i = 0; i < s.size(); i++)
38 Path::isValid() const {
42 // If there is a colon, it must be the second character, preceded by a letter
43 // and followed by something.
44 size_t len = path.size();
45 size_t pos = path.rfind(':',len);
46 if (pos != std::string::npos) {
47 if (pos != 1 || !isalpha(path[0]) || len < 3)
51 // Check for illegal characters.
52 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
53 "\013\014\015\016\017\020\021\022\023\024\025\026"
54 "\027\030\031\032\033\034\035\036\037")
58 // Check each component for legality.
59 for (pos = 0; pos < len; ++pos) {
60 // A component may not end in a space.
61 if (path[pos] == ' ') {
62 if (path[pos+1] == '/' || path[pos+1] == '\0')
66 // A component may not end in a period.
67 if (path[pos] == '.') {
68 if (path[pos+1] == '/' || path[pos+1] == '\0') {
69 // Unless it is the pseudo-directory "."...
70 if (pos == 0 || path[pos-1] == '/' || path[pos-1] == ':')
73 if (pos > 0 && path[pos-1] == '.') {
74 if (pos == 1 || path[pos-2] == '/' || path[pos-2] == ':')
85 static Path *TempDirectory = NULL;
88 Path::GetTemporaryDirectory() {
90 return *TempDirectory;
92 char pathname[MAX_PATH];
93 if (!GetTempPath(MAX_PATH, pathname))
94 throw std::string("Can't determine temporary directory");
99 // Append a subdirectory passed on our process id so multiple LLVMs don't
100 // step on each other's toes.
101 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
102 result.appendComponent(pathname);
104 // If there's a directory left over from a previous LLVM execution that
105 // happened to have the same process id, get rid of it.
106 result.eraseFromDisk(true);
108 // And finally (re-)create the empty directory.
109 result.createDirectoryOnDisk(false);
110 TempDirectory = new Path(result);
111 return *TempDirectory;
114 Path::Path(const std::string& unverified_path)
115 : path(unverified_path)
117 FlipBackSlashes(path);
118 if (unverified_path.empty())
124 throw std::string(unverified_path + ": path is not valid");
127 // FIXME: the following set of functions don't map to Windows very well.
129 Path::GetRootDirectory() {
135 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
136 const char* at = path;
137 const char* delim = strchr(at, ';');
139 while( delim != 0 ) {
140 std::string tmp(at, size_t(delim-at));
141 if (tmpPath.set(tmp))
142 if (tmpPath.canRead())
143 Paths.push_back(tmpPath);
145 delim = strchr(at, ';');
148 if (tmpPath.set(std::string(at)))
149 if (tmpPath.canRead())
150 Paths.push_back(tmpPath);
155 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
156 Paths.push_back(sys::Path("C:\\WINDOWS\\SYSTEM32\\"));
157 Paths.push_back(sys::Path("C:\\WINDOWS\\"));
161 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
162 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
164 getPathList(env_var,Paths);
169 if (tmpPath.set(LLVM_LIBDIR))
170 if (tmpPath.canRead())
171 Paths.push_back(tmpPath);
174 GetSystemLibraryPaths(Paths);
178 Path::GetLLVMDefaultConfigDir() {
179 // TODO: this isn't going to fly on Windows
180 return Path("/etc/llvm/");
184 Path::GetUserHomeDirectory() {
185 // TODO: Typical Windows setup doesn't define HOME.
186 const char* home = getenv("HOME");
189 if (result.set(home))
192 return GetRootDirectory();
194 // FIXME: the above set of functions don't map to Windows very well.
197 Path::isFile() const {
198 return !isDirectory();
202 Path::isDirectory() const {
203 WIN32_FILE_ATTRIBUTE_DATA fi;
204 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
205 ThrowError(std::string(path) + ": Can't get status: ");
206 return fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
210 Path::isHidden() const {
211 // FIXME: implement this correctly for Win32. It should check the hidden file
217 Path::getBasename() const {
218 // Find the last slash
219 size_t slash = path.rfind('/');
220 if (slash == std::string::npos)
225 return path.substr(slash, path.rfind('.'));
228 bool Path::hasMagicNumber(const std::string &Magic) const {
229 std::string actualMagic;
230 if (getMagicNumber(actualMagic, Magic.size()))
231 return Magic == actualMagic;
236 Path::isBytecodeFile() const {
237 std::string actualMagic;
238 if (!getMagicNumber(actualMagic, 4))
240 return actualMagic == "llvc" || actualMagic == "llvm";
244 Path::exists() const {
245 DWORD attr = GetFileAttributes(path.c_str());
246 return attr != INVALID_FILE_ATTRIBUTES;
250 Path::canRead() const {
251 // FIXME: take security attributes into account.
252 DWORD attr = GetFileAttributes(path.c_str());
253 return attr != INVALID_FILE_ATTRIBUTES;
257 Path::canWrite() const {
258 // FIXME: take security attributes into account.
259 DWORD attr = GetFileAttributes(path.c_str());
260 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
264 Path::canExecute() const {
265 // FIXME: take security attributes into account.
266 DWORD attr = GetFileAttributes(path.c_str());
267 return attr != INVALID_FILE_ATTRIBUTES;
271 Path::getLast() const {
272 // Find the last slash
273 size_t pos = path.rfind('/');
275 // Handle the corner cases
276 if (pos == std::string::npos)
279 // If the last character is a slash
280 if (pos == path.length()-1) {
281 // Find the second to last slash
282 size_t pos2 = path.rfind('/', pos-1);
283 if (pos2 == std::string::npos)
284 return path.substr(0,pos);
286 return path.substr(pos2+1,pos-pos2-1);
288 // Return everything after the last slash
289 return path.substr(pos+1);
293 Path::getStatusInfo(StatusInfo& info) const {
294 WIN32_FILE_ATTRIBUTE_DATA fi;
295 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
296 ThrowError(std::string(path) + ": Can't get status: ");
298 info.fileSize = fi.nFileSizeHigh;
299 info.fileSize <<= 32;
300 info.fileSize += fi.nFileSizeLow;
302 info.mode = fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ? 0555 : 0777;
303 info.user = 9999; // Not applicable to Windows, so...
304 info.group = 9999; // Not applicable to Windows, so...
306 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
307 info.modTime.fromWin32Time(ft);
309 info.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
310 if (info.isDir && path[path.length() - 1] != '/')
312 else if (!info.isDir && path[path.length() - 1] == '/')
313 path.erase(path.length() - 1);
316 static bool AddPermissionBits(const std::string& Filename, int bits) {
317 DWORD attr = GetFileAttributes(Filename.c_str());
319 // If it doesn't exist, we're done.
320 if (attr == INVALID_FILE_ATTRIBUTES)
323 // The best we can do to interpret Unix permission bits is to use
324 // the owner writable bit.
325 if ((attr & FILE_ATTRIBUTE_READONLY) && (bits & 0200)) {
326 if (!SetFileAttributes(Filename.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
327 ThrowError(Filename + ": SetFileAttributes: ");
332 void Path::makeReadableOnDisk() {
333 // All files are readable on Windows (ignoring security attributes).
336 void Path::makeWriteableOnDisk() {
337 DWORD attr = GetFileAttributes(path.c_str());
339 // If it doesn't exist, we're done.
340 if (attr == INVALID_FILE_ATTRIBUTES)
343 if (attr & FILE_ATTRIBUTE_READONLY) {
344 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
345 ThrowError(std::string(path) + ": Can't make file writable: ");
349 void Path::makeExecutableOnDisk() {
350 // All files are executable on Windows (ignoring security attributes).
354 Path::getDirectoryContents(std::set<Path>& result) const {
360 std::string searchpath = path + "*";
361 HANDLE h = FindFirstFile(searchpath.c_str(), &fd);
362 if (h == INVALID_HANDLE_VALUE) {
363 if (GetLastError() == ERROR_FILE_NOT_FOUND)
364 return true; // not really an error, now is it?
365 ThrowError(path + ": Can't read directory: ");
369 if (fd.cFileName[0] == '.')
371 Path aPath(path + &fd.cFileName[0]);
372 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
374 result.insert(aPath);
375 } while (FindNextFile(h, &fd));
377 DWORD err = GetLastError();
379 if (err != ERROR_NO_MORE_FILES) {
381 ThrowError(path + ": Can't read directory: ");
387 Path::set(const std::string& a_path) {
388 if (a_path.size() == 0)
390 std::string save(path);
392 FlipBackSlashes(path);
393 size_t last = a_path.size() -1;
402 Path::appendComponent(const std::string& name) {
405 std::string save(path);
407 size_t last = path.size() - 1;
408 if (path[last] != '/')
420 Path::eraseComponent() {
421 size_t slashpos = path.rfind('/',path.size());
422 if (slashpos == 0 || slashpos == std::string::npos)
424 if (slashpos == path.size() - 1)
425 slashpos = path.rfind('/',slashpos-1);
426 if (slashpos == std::string::npos)
428 path.erase(slashpos);
433 Path::appendSuffix(const std::string& suffix) {
434 std::string save(path);
445 Path::eraseSuffix() {
446 size_t dotpos = path.rfind('.',path.size());
447 size_t slashpos = path.rfind('/',path.size());
448 if (slashpos != std::string::npos && dotpos != std::string::npos &&
450 path.erase(dotpos, path.size()-dotpos);
457 Path::createDirectoryOnDisk( bool create_parents) {
458 // Get a writeable copy of the path name
459 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+1));
460 path.copy(pathname,path.length());
461 pathname[path.length()] = 0;
463 // Determine starting point for initial / search.
464 char *next = pathname;
465 if (pathname[0] == '/' && pathname[1] == '/') {
467 next = strchr(pathname+2, '/');
469 throw std::string(pathname) + ": badly formed remote directory";
471 next = strchr(next+1, '/');
473 throw std::string(pathname) + ": badly formed remote directory";
476 throw std::string(pathname) + ": badly formed remote directory";
478 if (pathname[1] == ':')
479 next += 2; // skip drive letter
481 next++; // skip root directory
484 // If we're supposed to create intermediate directories
485 if (create_parents) {
486 // Loop through the directory components until we're done
488 next = strchr(next, '/');
490 if (!CreateDirectory(pathname, NULL))
491 ThrowError(std::string(pathname) + ": Can't create directory: ");
495 // Drop trailing slash.
496 pathname[path.size()-1] = 0;
497 if (!CreateDirectory(pathname, NULL)) {
498 ThrowError(std::string(pathname) + ": Can't create directory: ");
505 Path::createFileOnDisk() {
507 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
508 FILE_ATTRIBUTE_NORMAL, NULL);
509 if (h == INVALID_HANDLE_VALUE)
510 ThrowError(path + ": Can't create file: ");
517 Path::eraseFromDisk(bool remove_contents) const {
519 DWORD attr = GetFileAttributes(path.c_str());
521 // If it doesn't exist, we're done.
522 if (attr == INVALID_FILE_ATTRIBUTES)
525 // Read-only files cannot be deleted on Windows. Must remove the read-only
527 if (attr & FILE_ATTRIBUTE_READONLY) {
528 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
529 ThrowError(path + ": Can't destroy file: ");
532 if (!DeleteFile(path.c_str()))
533 ThrowError(path + ": Can't destroy file: ");
535 } else /* isDirectory() */ {
537 // If it doesn't exist, we're done.
541 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+2));
542 int lastchar = path.length() - 1 ;
543 path.copy(pathname,lastchar+2);
545 // Make path end with '/*'.
546 pathname[lastchar+1] = '*';
547 pathname[lastchar+2] = 0;
549 if (remove_contents) {
551 HANDLE h = FindFirstFile(pathname, &fd);
553 // It's a bad idea to alter the contents of a directory while enumerating
554 // its contents. So build a list of its contents first, then destroy them.
556 if (h != INVALID_HANDLE_VALUE) {
557 std::vector<Path> list;
560 if (strcmp(fd.cFileName, ".") == 0)
562 if (strcmp(fd.cFileName, "..") == 0)
565 Path aPath(path + &fd.cFileName[0]);
566 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
568 list.push_back(aPath);
569 } while (FindNextFile(h, &fd));
571 DWORD err = GetLastError();
573 if (err != ERROR_NO_MORE_FILES) {
575 ThrowError(path + ": Can't read directory: ");
578 for (std::vector<Path>::iterator I = list.begin(); I != list.end();
581 aPath.eraseFromDisk(true);
584 if (GetLastError() != ERROR_FILE_NOT_FOUND)
585 ThrowError(path + ": Can't read directory: ");
589 pathname[lastchar] = 0;
590 if (!RemoveDirectory(pathname))
591 ThrowError(std::string(pathname) + ": Can't destroy directory: ");
596 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
599 assert(len < 1024 && "Request for magic string too long");
600 char* buf = (char*) alloca(1 + len);
602 HANDLE h = CreateFile(path.c_str(),
607 FILE_ATTRIBUTE_NORMAL,
609 if (h == INVALID_HANDLE_VALUE)
613 BOOL ret = ReadFile(h, buf, len, &nRead, NULL);
616 if (!ret || nRead != len)
625 Path::renamePathOnDisk(const Path& newName) {
626 // FIXME: This should rename a directory too.
627 if (!isFile()) return false;
628 if (!MoveFile(path.c_str(), newName.c_str()))
629 ThrowError("Can't move '" + path +
630 "' to '" + newName.path + "': ");
635 Path::setStatusInfoOnDisk(const StatusInfo& si) const {
636 if (!isFile()) return false;
638 HANDLE h = CreateFile(path.c_str(),
639 FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
640 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
643 FILE_ATTRIBUTE_NORMAL,
645 if (h == INVALID_HANDLE_VALUE)
648 BY_HANDLE_FILE_INFORMATION bhfi;
649 if (!GetFileInformationByHandle(h, &bhfi)) {
650 DWORD err = GetLastError();
653 ThrowError(path + ": GetFileInformationByHandle: ");
657 (uint64_t&)ft = si.modTime.toWin32Time();
658 BOOL ret = SetFileTime(h, NULL, &ft, &ft);
659 DWORD err = GetLastError();
663 ThrowError(path + ": SetFileTime: ");
666 // Best we can do with Unix permission bits is to interpret the owner
668 if (si.mode & 0200) {
669 if (bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
670 if (!SetFileAttributes(path.c_str(),
671 bhfi.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY))
672 ThrowError(path + ": SetFileAttributes: ");
675 if (!(bhfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) {
676 if (!SetFileAttributes(path.c_str(),
677 bhfi.dwFileAttributes | FILE_ATTRIBUTE_READONLY))
678 ThrowError(path + ": SetFileAttributes: ");
686 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
687 // Can't use CopyFile macro defined in Windows.h because it would mess up the
688 // above line. We use the expansion it would have in a non-UNICODE build.
689 if (!::CopyFileA(Src.c_str(), Dest.c_str(), false))
690 ThrowError("Can't copy '" + Src.toString() +
691 "' to '" + Dest.toString() + "': ");
695 Path::makeUnique(bool reuse_current) {
696 if (reuse_current && !exists())
697 return; // File doesn't exist already, just use it!
699 // Reserve space for -XXXXXX at the end.
700 char *FNBuffer = (char*) alloca(path.size()+8);
701 unsigned offset = path.size();
702 path.copy(FNBuffer, offset);
704 // Find a numeric suffix that isn't used by an existing file.
705 static unsigned FCounter = 0;
707 sprintf(FNBuffer+offset, "-%06u", FCounter);
708 if (++FCounter > 999999)
715 Path::createTemporaryFileOnDisk(bool reuse_current) {
716 // Make this into a unique file name
717 makeUnique( reuse_current );
719 // Now go and create it
720 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
721 FILE_ATTRIBUTE_NORMAL, NULL);
722 if (h == INVALID_HANDLE_VALUE)