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 //===----------------------------------------------------------------------===//
26 static void FlipBackSlashes(std::string& s) {
27 for (size_t i = 0; i < s.size(); i++)
36 Path::isValid() const {
40 // If there is a colon, it must be the second character, preceded by a letter
41 // and followed by something.
42 size_t len = path.size();
43 size_t pos = path.rfind(':',len);
44 if (pos != std::string::npos) {
45 if (pos != 1 || !isalpha(path[0]) || len < 3)
49 // Check for illegal characters.
50 if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
51 "\013\014\015\016\017\020\021\022\023\024\025\026"
52 "\027\030\031\032\033\034\035\036\037")
56 // A file or directory name may not end in a period.
57 if (path[len-1] == '.')
59 if (len >= 2 && path[len-2] == '.' && path[len-1] == '/')
62 // A file or directory name may not end in a space.
63 if (path[len-1] == ' ')
65 if (len >= 2 && path[len-2] == ' ' && path[len-1] == '/')
71 static Path *TempDirectory = NULL;
74 Path::GetTemporaryDirectory() {
76 return *TempDirectory;
78 char pathname[MAX_PATH];
79 if (!GetTempPath(MAX_PATH, pathname))
80 throw std::string("Can't determine temporary directory");
83 result.setDirectory(pathname);
85 // Append a subdirectory passed on our process id so multiple LLVMs don't
86 // step on each other's toes.
87 sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
88 result.appendDirectory(pathname);
90 // If there's a directory left over from a previous LLVM execution that
91 // happened to have the same process id, get rid of it.
92 result.destroyDirectory(true);
94 // And finally (re-)create the empty directory.
95 result.createDirectory(false);
96 TempDirectory = new Path(result);
97 return *TempDirectory;
100 Path::Path(const std::string& unverified_path)
101 : path(unverified_path)
103 FlipBackSlashes(path);
104 if (unverified_path.empty())
110 throw std::string(unverified_path + ": path is not valid");
113 // FIXME: the following set of functions don't map to Windows very well.
115 Path::GetRootDirectory() {
117 result.setDirectory("/");
121 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
122 const char* at = path;
123 const char* delim = strchr(at, ';');
125 while( delim != 0 ) {
126 std::string tmp(at, size_t(delim-at));
127 if (tmpPath.setDirectory(tmp))
128 if (tmpPath.readable())
129 Paths.push_back(tmpPath);
131 delim = strchr(at, ';');
134 if (tmpPath.setDirectory(std::string(at)))
135 if (tmpPath.readable())
136 Paths.push_back(tmpPath);
141 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
142 #ifdef LTDL_SHLIBPATH_VAR
143 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
145 getPathList(env_var,Paths);
148 // FIXME: Should this look at LD_LIBRARY_PATH too?
149 Paths.push_back(sys::Path("C:\\WINDOWS\\SYSTEM32\\"));
150 Paths.push_back(sys::Path("C:\\WINDOWS\\"));
154 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
155 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
157 getPathList(env_var,Paths);
162 if (tmpPath.setDirectory(LLVM_LIBDIR))
163 if (tmpPath.readable())
164 Paths.push_back(tmpPath);
167 GetSystemLibraryPaths(Paths);
171 Path::GetLLVMDefaultConfigDir() {
172 return Path("/etc/llvm/");
176 Path::GetUserHomeDirectory() {
177 const char* home = getenv("HOME");
180 if (result.setDirectory(home))
183 return GetRootDirectory();
185 // FIXME: the above set of functions don't map to Windows very well.
188 Path::isFile() const {
189 return (isValid() && path[path.length()-1] != '/');
193 Path::isDirectory() const {
194 return (isValid() && path[path.length()-1] == '/');
198 Path::getBasename() const {
199 // Find the last slash
200 size_t slash = path.rfind('/');
201 if (slash == std::string::npos)
206 return path.substr(slash, path.rfind('.'));
209 bool Path::hasMagicNumber(const std::string &Magic) const {
210 size_t len = Magic.size();
211 char *buf = reinterpret_cast<char *>(_alloca(len+1));
212 std::ifstream f(path.c_str());
219 Path::isBytecodeFile() const {
222 std::ifstream f(path.c_str());
225 ThrowErrno("can't read file signature");
226 return 0 == memcmp(buffer,"llvc",4) || 0 == memcmp(buffer,"llvm",4);
230 Path::exists() const {
231 DWORD attr = GetFileAttributes(path.c_str());
232 return attr != INVALID_FILE_ATTRIBUTES;
236 Path::readable() const {
237 // FIXME: take security attributes into account.
238 DWORD attr = GetFileAttributes(path.c_str());
239 return attr != INVALID_FILE_ATTRIBUTES;
243 Path::writable() const {
244 // FIXME: take security attributes into account.
245 DWORD attr = GetFileAttributes(path.c_str());
246 return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
250 Path::executable() const {
251 // FIXME: take security attributes into account.
252 DWORD attr = GetFileAttributes(path.c_str());
253 return attr != INVALID_FILE_ATTRIBUTES;
257 Path::getLast() const {
258 // Find the last slash
259 size_t pos = path.rfind('/');
261 // Handle the corner cases
262 if (pos == std::string::npos)
265 // If the last character is a slash
266 if (pos == path.length()-1) {
267 // Find the second to last slash
268 size_t pos2 = path.rfind('/', pos-1);
269 if (pos2 == std::string::npos)
270 return path.substr(0,pos);
272 return path.substr(pos2+1,pos-pos2-1);
274 // Return everything after the last slash
275 return path.substr(pos+1);
279 Path::getStatusInfo(StatusInfo& info) const {
280 WIN32_FILE_ATTRIBUTE_DATA fi;
281 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
282 ThrowError(std::string(path) + ": Can't get status: ");
284 info.fileSize = fi.nFileSizeHigh;
285 info.fileSize <<= 32;
286 info.fileSize += fi.nFileSizeLow;
288 info.mode = 0777; // Not applicable to Windows, so...
289 info.user = 9999; // Not applicable to Windows, so...
290 info.group = 9999; // Not applicable to Windows, so...
292 __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
293 info.modTime.fromWin32Time(ft);
295 info.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
296 if (info.isDir && path[path.length() - 1] != '/')
298 else if (!info.isDir && path[path.length() - 1] == '/')
299 path.erase(path.length() - 1);
302 void Path::makeReadable() {
303 // All files are readable on Windows (ignoring security attributes).
306 void Path::makeWriteable() {
307 DWORD attr = GetFileAttributes(path.c_str());
309 // If it doesn't exist, we're done.
310 if (attr == INVALID_FILE_ATTRIBUTES)
313 if (attr & FILE_ATTRIBUTE_READONLY) {
314 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
315 ThrowError(std::string(path) + ": Can't make file writable: ");
319 void Path::makeExecutable() {
320 // All files are executable on Windows (ignoring security attributes).
324 Path::setDirectory(const std::string& a_path) {
325 if (a_path.size() == 0)
329 FlipBackSlashes(path);
330 size_t last = a_path.size() -1;
331 if (a_path[last] != '/')
341 Path::setFile(const std::string& a_path) {
342 if (a_path.size() == 0)
346 FlipBackSlashes(path);
347 size_t last = a_path.size() - 1;
348 while (last > 0 && a_path[last] == '/')
359 Path::appendDirectory(const std::string& dir) {
373 Path::elideDirectory() {
376 size_t slashpos = path.rfind('/',path.size());
377 if (slashpos == 0 || slashpos == std::string::npos)
379 if (slashpos == path.size() - 1)
380 slashpos = path.rfind('/',slashpos-1);
381 if (slashpos == std::string::npos)
383 path.erase(slashpos);
388 Path::appendFile(const std::string& file) {
404 size_t slashpos = path.rfind('/',path.size());
405 if (slashpos == std::string::npos)
407 path.erase(slashpos+1);
412 Path::appendSuffix(const std::string& suffix) {
426 Path::elideSuffix() {
427 if (isDirectory()) return false;
428 size_t dotpos = path.rfind('.',path.size());
429 size_t slashpos = path.rfind('/',path.size());
430 if (slashpos != std::string::npos && dotpos != std::string::npos &&
432 path.erase(dotpos, path.size()-dotpos);
440 Path::createDirectory( bool create_parents) {
441 // Make sure we're dealing with a directory
442 if (!isDirectory()) return false;
444 // Get a writeable copy of the path name
445 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+1));
446 path.copy(pathname,path.length());
447 pathname[path.length()] = 0;
449 // Determine starting point for initial / search.
450 char *next = pathname;
451 if (pathname[0] == '/' && pathname[1] == '/') {
453 next = strchr(pathname+2, '/');
455 throw std::string(pathname) + ": badly formed remote directory";
457 next = strchr(next+1, '/');
459 throw std::string(pathname) + ": badly formed remote directory";
462 throw std::string(pathname) + ": badly formed remote directory";
464 if (pathname[1] == ':')
465 next += 2; // skip drive letter
467 next++; // skip root directory
470 // If we're supposed to create intermediate directories
471 if (create_parents) {
472 // Loop through the directory components until we're done
474 next = strchr(next, '/');
476 if (!CreateDirectory(pathname, NULL))
477 ThrowError(std::string(pathname) + ": Can't create directory: ");
481 // Drop trailing slash.
482 pathname[path.size()-1] = 0;
483 if (!CreateDirectory(pathname, NULL)) {
484 ThrowError(std::string(pathname) + ": Can't create directory: ");
492 // Make sure we're dealing with a file
493 if (!isFile()) return false;
496 HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
497 FILE_ATTRIBUTE_NORMAL, NULL);
498 if (h == INVALID_HANDLE_VALUE)
499 ThrowError(std::string(path.c_str()) + ": Can't create file: ");
506 Path::destroyDirectory(bool remove_contents) const {
507 // Make sure we're dealing with a directory
508 if (!isDirectory()) return false;
510 // If it doesn't exist, we're done.
511 if (!exists()) return true;
513 char *pathname = reinterpret_cast<char *>(_alloca(path.length()+1));
514 path.copy(pathname,path.length()+1);
515 int lastchar = path.length() - 1 ;
516 if (pathname[lastchar] == '/')
517 pathname[lastchar] = 0;
519 if (remove_contents) {
520 // Recursively descend the directory to remove its content
521 // FIXME: The correct way of doing this on Windows isn't pretty...
522 // but this may work if unix-like utils are present.
523 std::string cmd("rm -rf ");
527 // Otherwise, try to just remove the one directory
528 if (!RemoveDirectory(pathname))
529 ThrowError(std::string(pathname) + ": Can't destroy directory: ");
535 Path::destroyFile() const {
536 if (!isFile()) return false;
538 DWORD attr = GetFileAttributes(path.c_str());
540 // If it doesn't exist, we're done.
541 if (attr == INVALID_FILE_ATTRIBUTES)
544 // Read-only files cannot be deleted on Windows. Must remove the read-only
546 if (attr & FILE_ATTRIBUTE_READONLY) {
547 if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
548 ThrowError(std::string(path.c_str()) + ": Can't destroy file: ");
551 if (!DeleteFile(path.c_str()))
552 ThrowError(std::string(path.c_str()) + ": Can't destroy file: ");
556 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
559 assert(len < 1024 && "Request for magic string too long");
560 char* buf = (char*) alloca(1 + len);
561 std::ofstream ofs(path.c_str(),std::ofstream::in);
564 std::ifstream ifs(path.c_str());
576 CopyFile(const sys::Path &Dest, const sys::Path &Src) {
577 if (!::CopyFile(Src.c_str(), Dest.c_str(), false))
578 ThrowError("Can't copy '" + Src.toString() +
579 "' to '" + Dest.toString() + "'");
583 Path::makeUnique( bool reuse_current ) {
584 if (reuse_current && !exists())
585 return; // File doesn't exist already, just use it!
589 std::string fname = this->getLast();
591 char newName[MAX_PATH + 1];
592 if (!GetTempFileName(dir.c_str(), fname.c_str(), 0, newName))
593 ThrowError("Cannot make unique filename for '" + path + "'");
599 Path::createTemporaryFile(bool reuse_current) {
600 // Make sure we're dealing with a file
604 // Make this into a unique file name
605 makeUnique( reuse_current );
611 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab