blob: c8bdd088c3250df14f94332cf4492eff2d112bef [file] [log] [blame]
Reid Spencerb89a2232004-08-25 06:20:07 +00001//===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencerb89a2232004-08-25 06:20:07 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific portion of the Path class.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
Reid Spencer8e665952004-08-29 05:24:01 +000016//=== is guaranteed to work on *all* UNIX variants.
Reid Spencerb89a2232004-08-25 06:20:07 +000017//===----------------------------------------------------------------------===//
18
Misha Brukman210b32b2004-12-20 00:16:38 +000019#include "llvm/Config/alloca.h"
Reid Spencerb89a2232004-08-25 06:20:07 +000020#include "Unix.h"
Reid Spenceraf2f2082004-12-27 06:17:15 +000021#if HAVE_SYS_STAT_H
Reid Spencerb89a2232004-08-25 06:20:07 +000022#include <sys/stat.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000023#endif
24#if HAVE_FCNTL_H
Reid Spencerb89a2232004-08-25 06:20:07 +000025#include <fcntl.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000026#endif
27#if HAVE_UTIME_H
Reid Spencereaf18152004-11-14 22:08:36 +000028#include <utime.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000029#endif
30#if HAVE_TIME_H
Reid Spencer69a16162004-12-24 06:29:42 +000031#include <time.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000032#endif
33#if HAVE_DIRENT_H
34# include <dirent.h>
35# define NAMLEN(dirent) strlen((dirent)->d_name)
36#else
37# define dirent direct
38# define NAMLEN(dirent) (dirent)->d_namlen
39# if HAVE_SYS_NDIR_H
40# include <sys/ndir.h>
41# endif
42# if HAVE_SYS_DIR_H
43# include <sys/dir.h>
44# endif
45# if HAVE_NDIR_H
46# include <ndir.h>
47# endif
48#endif
49
Reid Spencer932e2e32005-06-02 05:38:20 +000050// Put in a hack for Cygwin which falsely reports that the mkdtemp function
51// is available when it is not.
52#ifdef __CYGWIN__
53# undef HAVE_MKDTEMP
54#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000055
Reid Spencer3be872e2005-07-28 16:25:57 +000056namespace {
57inline bool lastIsSlash(const std::string& path) {
58 return !path.empty() && path[path.length() - 1] == '/';
59}
60
61}
62
Reid Spencer8e665952004-08-29 05:24:01 +000063namespace llvm {
64using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000065
Chris Lattnere1b332a2008-02-27 06:17:10 +000066extern const char sys::PathSeparator = ':';
67
Reid Spencer69a16162004-12-24 06:29:42 +000068bool
69Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000070 // Check some obvious things
Reid Spencer69a16162004-12-24 06:29:42 +000071 if (path.empty())
72 return false;
73 else if (path.length() >= MAXPATHLEN)
74 return false;
Reid Spencer6371ccb2005-07-08 06:53:26 +000075
76 // Check that the characters are ascii chars
77 size_t len = path.length();
78 unsigned i = 0;
79 while (i < len && isascii(path[i]))
80 ++i;
81 return i >= len;
Reid Spencer69a16162004-12-24 06:29:42 +000082}
83
Reid Spencer69cce812007-03-29 16:43:20 +000084bool
85Path::isAbsolute() const {
86 if (path.empty())
87 return false;
88 return path[0] == '/';
89}
Reid Spencer8e665952004-08-29 05:24:01 +000090Path
91Path::GetRootDirectory() {
92 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +000093 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +000094 return result;
95}
96
Reid Spencer69a16162004-12-24 06:29:42 +000097Path
Reid Spencer48744762006-08-22 19:01:30 +000098Path::GetTemporaryDirectory(std::string* ErrMsg ) {
Reid Spencer69a16162004-12-24 06:29:42 +000099#if defined(HAVE_MKDTEMP)
100 // The best way is with mkdtemp but that's not available on many systems,
101 // Linux and FreeBSD have it. Others probably won't.
102 char pathname[MAXPATHLEN];
103 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000104 if (0 == mkdtemp(pathname)) {
105 MakeErrMsg(ErrMsg,
106 std::string(pathname) + ": can't create temporary directory");
107 return Path();
108 }
Reid Spencer69a16162004-12-24 06:29:42 +0000109 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000110 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000111 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
112 return result;
113#elif defined(HAVE_MKSTEMP)
114 // If no mkdtemp is available, mkstemp can be used to create a temporary file
115 // which is then removed and created as a directory. We prefer this over
116 // mktemp because of mktemp's inherent security and threading risks. We still
117 // have a slight race condition from the time the temporary file is created to
118 // the time it is re-created as a directoy.
119 char pathname[MAXPATHLEN];
120 strcpy(pathname, "/tmp/llvm_XXXXXX");
121 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000122 if (-1 == (fd = mkstemp(pathname))) {
123 MakeErrMsg(ErrMsg,
124 std::string(pathname) + ": can't create temporary directory");
125 return Path();
126 }
Reid Spencer69a16162004-12-24 06:29:42 +0000127 ::close(fd);
128 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000129 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
130 MakeErrMsg(ErrMsg,
131 std::string(pathname) + ": can't create temporary directory");
132 return Path();
133 }
Reid Spencer69a16162004-12-24 06:29:42 +0000134 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000135 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000136 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
137 return result;
138#elif defined(HAVE_MKTEMP)
139 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
140 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
141 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
142 // the XXXXXX with the pid of the process and a letter. That leads to only
143 // twenty six temporary files that can be generated.
144 char pathname[MAXPATHLEN];
145 strcpy(pathname, "/tmp/llvm_XXXXXX");
146 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000147 if (TmpName == 0) {
148 MakeErrMsg(ErrMsg,
149 std::string(TmpName) + ": can't create unique directory name");
150 return Path();
151 }
152 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
153 MakeErrMsg(ErrMsg,
154 std::string(TmpName) + ": can't create temporary directory");
155 return Path();
156 }
Reid Spencer69a16162004-12-24 06:29:42 +0000157 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000158 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000159 assert(result.isValid() && "mktemp didn't create a valid pathname!");
160 return result;
161#else
162 // This is the worst case implementation. tempnam(3) leaks memory unless its
163 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
164 // issues. The mktemp(3) function doesn't have enough variability in the
165 // temporary name generated. So, we provide our own implementation that
166 // increments an integer from a random number seeded by the current time. This
167 // should be sufficiently unique that we don't have many collisions between
168 // processes. Generally LLVM processes don't run very long and don't use very
169 // many temporary files so this shouldn't be a big issue for LLVM.
170 static time_t num = ::time(0);
171 char pathname[MAXPATHLEN];
172 do {
173 num++;
174 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
175 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000176 if (-1 == ::mkdir(pathname, S_IRWXU)) {
177 MakeErrMsg(ErrMsg,
178 std::string(pathname) + ": can't create temporary directory");
179 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000180 }
Reid Spencer69a16162004-12-24 06:29:42 +0000181 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000182 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000183 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
184 return result;
185#endif
186}
187
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000188void
189Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
190#ifdef LTDL_SHLIBPATH_VAR
191 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
192 if (env_var != 0) {
193 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000194 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000195#endif
196 // FIXME: Should this look at LD_LIBRARY_PATH too?
197 Paths.push_back(sys::Path("/usr/local/lib/"));
198 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
199 Paths.push_back(sys::Path("/usr/lib/"));
200 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000201}
202
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000203void
Gabor Greifa99be512007-07-05 17:07:56 +0000204Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000205 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
206 if (env_var != 0) {
207 getPathList(env_var,Paths);
208 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000209#ifdef LLVM_LIBDIR
210 {
211 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000212 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000213 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000214 Paths.push_back(tmpPath);
215 }
216#endif
217 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000218}
219
220Path
221Path::GetLLVMDefaultConfigDir() {
222 return Path("/etc/llvm/");
223}
224
Reid Spencer8e665952004-08-29 05:24:01 +0000225Path
226Path::GetUserHomeDirectory() {
227 const char* home = getenv("HOME");
228 if (home) {
229 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000230 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000231 return result;
232 }
233 return GetRootDirectory();
234}
235
Ted Kremenek79200782007-12-18 22:07:33 +0000236Path
237Path::GetCurrentDirectory() {
238 char pathname[MAXPATHLEN];
239 if (!getcwd(pathname,MAXPATHLEN)) {
240 assert (false && "Could not query current working directory.");
241 return Path("");
242 }
243
244 return Path(pathname);
245}
Reid Spencera229c5c2005-07-08 03:08:58 +0000246
Reid Spencer1b554b42004-09-11 04:55:08 +0000247std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000248Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000249 // Find the last slash
250 size_t slash = path.rfind('/');
251 if (slash == std::string::npos)
252 slash = 0;
253 else
254 slash++;
255
Jeff Cohen73f36672005-07-09 18:42:02 +0000256 size_t dot = path.rfind('.');
257 if (dot == std::string::npos || dot < slash)
258 return path.substr(slash);
259 else
260 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000261}
262
Reid Spencereaf18152004-11-14 22:08:36 +0000263bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000264 assert(len < 1024 && "Request for magic string too long");
265 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000266 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000267 if (fd < 0)
268 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000269 ssize_t bytes_read = ::read(fd, buf, len);
270 ::close(fd);
271 if (ssize_t(len) != bytes_read) {
272 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000273 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000274 }
275 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000276 return true;
277}
278
Reid Spencer1b554b42004-09-11 04:55:08 +0000279bool
Reid Spencer8e665952004-08-29 05:24:01 +0000280Path::exists() const {
281 return 0 == access(path.c_str(), F_OK );
282}
283
284bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000285Path::isDirectory() const {
286 struct stat buf;
287 if (0 != stat(path.c_str(), &buf))
288 return false;
289 return buf.st_mode & S_IFDIR ? true : false;
290}
291
292bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000293Path::canRead() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000294 return 0 == access(path.c_str(), F_OK | R_OK );
295}
296
297bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000298Path::canWrite() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000299 return 0 == access(path.c_str(), F_OK | W_OK );
300}
301
302bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000303Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000304 if (0 != access(path.c_str(), R_OK | X_OK ))
305 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000306 struct stat buf;
307 if (0 != stat(path.c_str(), &buf))
308 return false;
309 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000310 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000311 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000312}
313
314std::string
315Path::getLast() const {
316 // Find the last slash
317 size_t pos = path.rfind('/');
318
319 // Handle the corner cases
320 if (pos == std::string::npos)
321 return path;
322
323 // If the last character is a slash
324 if (pos == path.length()-1) {
325 // Find the second to last slash
326 size_t pos2 = path.rfind('/', pos-1);
327 if (pos2 == std::string::npos)
328 return path.substr(0,pos);
329 else
330 return path.substr(pos2+1,pos-pos2-1);
331 }
332 // Return everything after the last slash
333 return path.substr(pos+1);
334}
335
Reid Spencer2ae9d112007-04-07 18:52:17 +0000336const FileStatus *
337PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
338 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000339 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000340 if (0 != stat(path.c_str(), &buf)) {
341 MakeErrMsg(ErrStr, path + ": can't get status of file");
342 return 0;
343 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000344 status.fileSize = buf.st_size;
345 status.modTime.fromEpochTime(buf.st_mtime);
346 status.mode = buf.st_mode;
347 status.user = buf.st_uid;
348 status.group = buf.st_gid;
349 status.uniqueID = uint64_t(buf.st_ino);
350 status.isDir = S_ISDIR(buf.st_mode);
351 status.isFile = S_ISREG(buf.st_mode);
352 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000353 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000354 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000355}
356
Chris Lattner252ad032006-07-28 22:03:44 +0000357static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000358 // Get the umask value from the operating system. We want to use it
359 // when changing the file's permissions. Since calling umask() sets
360 // the umask and returns its old value, we must call it a second
361 // time to reset it to the user's preference.
362 int mask = umask(0777); // The arg. to umask is arbitrary.
363 umask(mask); // Restore the umask.
364
365 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000366 struct stat buf;
367 if (0 != stat(File.toString().c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000368 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000369 // Change the file to have whichever permissions bits from 'bits'
370 // that the umask would not disable.
371 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
372 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000373 return true;
374}
375
Reid Spencere1647f42006-08-22 23:27:23 +0000376bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000377 if (!AddPermissionBits(*this, 0444))
378 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000379 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000380}
381
Reid Spencere1647f42006-08-22 23:27:23 +0000382bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000383 if (!AddPermissionBits(*this, 0222))
384 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000385 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000386}
387
Reid Spencere1647f42006-08-22 23:27:23 +0000388bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000389 if (!AddPermissionBits(*this, 0111))
390 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000391 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000392}
393
Reid Spencereaf18152004-11-14 22:08:36 +0000394bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000395Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000396 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000397 if (direntries == 0)
398 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000399
Reid Spencer3be872e2005-07-28 16:25:57 +0000400 std::string dirPath = path;
401 if (!lastIsSlash(dirPath))
402 dirPath += '/';
403
Reid Spencereaf18152004-11-14 22:08:36 +0000404 result.clear();
405 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000406 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000407 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000408 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000409 struct stat st;
410 if (0 != lstat(aPath.path.c_str(), &st)) {
411 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000412 continue; // dangling symlink -- ignore
Reid Spencer5a060772006-08-23 07:30:48 +0000413 return MakeErrMsg(ErrMsg,
414 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000415 }
Reid Spencerb608a812004-11-16 06:15:19 +0000416 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000417 }
Reid Spencereaf18152004-11-14 22:08:36 +0000418 }
419
420 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000421 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000422}
423
Reid Spencer8e665952004-08-29 05:24:01 +0000424bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000425Path::set(const std::string& a_path) {
426 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000427 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000428 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000429 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000430 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000431 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000432 return false;
433 }
434 return true;
435}
436
437bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000438Path::appendComponent(const std::string& name) {
439 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000440 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000441 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000442 if (!lastIsSlash(path))
443 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000444 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000445 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000446 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000447 return false;
448 }
449 return true;
450}
451
452bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000453Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000454 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000455 if (slashpos == 0 || slashpos == std::string::npos) {
456 path.erase();
457 return true;
458 }
Reid Spencer8e665952004-08-29 05:24:01 +0000459 if (slashpos == path.size() - 1)
460 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000461 if (slashpos == std::string::npos) {
462 path.erase();
463 return true;
464 }
Reid Spencer8e665952004-08-29 05:24:01 +0000465 path.erase(slashpos);
466 return true;
467}
468
469bool
Reid Spencer07adb282004-11-05 22:15:36 +0000470Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000471 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000472 path.append(".");
473 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000474 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000475 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000476 return false;
477 }
478 return true;
479}
480
Reid Spencerdd04df02005-07-07 23:21:43 +0000481bool
482Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000483 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000484 size_t dotpos = path.rfind('.',path.size());
485 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000486 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000487 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000488 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000489 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000490 }
Reid Spencer8e665952004-08-29 05:24:01 +0000491 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000492 if (!isValid())
493 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000494 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000495}
496
Reid Spencer8e665952004-08-29 05:24:01 +0000497bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000498Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000499 // Get a writeable copy of the path name
500 char pathname[MAXPATHLEN];
501 path.copy(pathname,MAXPATHLEN);
502
503 // Null-terminate the last component
504 int lastchar = path.length() - 1 ;
505 if (pathname[lastchar] == '/')
506 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000507 else
508 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000509
510 // If we're supposed to create intermediate directories
511 if ( create_parents ) {
512 // Find the end of the initial name component
513 char * next = strchr(pathname,'/');
514 if ( pathname[0] == '/')
515 next = strchr(&pathname[1],'/');
516
517 // Loop through the directory components until we're done
518 while ( next != 0 ) {
519 *next = 0;
520 if (0 != access(pathname, F_OK | R_OK | W_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000521 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000522 return MakeErrMsg(ErrMsg,
523 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000524 }
Reid Spencer8e665952004-08-29 05:24:01 +0000525 char* save = next;
Reid Spencereaf18152004-11-14 22:08:36 +0000526 next = strchr(next+1,'/');
Reid Spencer8e665952004-08-29 05:24:01 +0000527 *save = '/';
528 }
Reid Spencer8e665952004-08-29 05:24:01 +0000529 }
Reid Spencereaf18152004-11-14 22:08:36 +0000530
531 if (0 != access(pathname, F_OK | R_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000532 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000533 return MakeErrMsg(ErrMsg,
534 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000535 }
536 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000537}
538
539bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000540Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000541 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000542 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000543 if (fd < 0)
544 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000545 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000546 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000547}
548
Reid Spencer8e665952004-08-29 05:24:01 +0000549bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000550Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000551 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000552 if (makeUnique( reuse_current, ErrMsg ))
553 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000554
555 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000556 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Reid Spencer5a060772006-08-23 07:30:48 +0000557 if (fd < 0)
558 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000559 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000560 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000561}
562
563bool
Chris Lattner0c332312006-07-28 22:29:50 +0000564Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Reid Spencer2ae9d112007-04-07 18:52:17 +0000565 // Get the status so we can determin if its a file or directory
566 struct stat buf;
567 if (0 != stat(path.c_str(), &buf)) {
568 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000569 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000570 }
571
572 // Note: this check catches strange situations. In all cases, LLVM should
573 // only be involved in the creation and deletion of regular files. This
574 // check ensures that what we're trying to erase is a regular file. It
575 // effectively prevents LLVM from erasing things like /dev/null, any block
576 // special file, or other things that aren't "regular" files.
577 if (S_ISREG(buf.st_mode)) {
578 if (unlink(path.c_str()) != 0)
579 return MakeErrMsg(ErrStr, path + ": can't destroy file");
580 return false;
581 }
582
583 if (!S_ISDIR(buf.st_mode)) {
584 if (ErrStr) *ErrStr = "not a file or directory";
585 return true;
586 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000587
Chris Lattner0c332312006-07-28 22:29:50 +0000588 if (remove_contents) {
589 // Recursively descend the directory to remove its contents.
590 std::string cmd = "/bin/rm -rf " + path;
591 system(cmd.c_str());
592 return false;
593 }
594
595 // Otherwise, try to just remove the one directory.
596 char pathname[MAXPATHLEN];
597 path.copy(pathname, MAXPATHLEN);
598 int lastchar = path.length() - 1 ;
599 if (pathname[lastchar] == '/')
600 pathname[lastchar] = 0;
601 else
602 pathname[lastchar+1] = 0;
603
604 if (rmdir(pathname) != 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000605 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000606 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000607 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000608}
609
610bool
Reid Spencer5a060772006-08-23 07:30:48 +0000611Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000612 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer5a060772006-08-23 07:30:48 +0000613 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Reid Spencer2aafadc2005-04-21 02:50:10 +0000614 newName.toString() + "' ");
Reid Spencer5a060772006-08-23 07:30:48 +0000615 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000616}
617
Reid Spencer2ae9d112007-04-07 18:52:17 +0000618bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000619Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000620 struct utimbuf utb;
621 utb.actime = si.modTime.toPosixTime();
622 utb.modtime = utb.actime;
623 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000624 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000625 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000626 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000627 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000628}
629
Reid Spencer51c5a282006-08-23 20:34:57 +0000630bool
631sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000632 int inFile = -1;
633 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000634 inFile = ::open(Src.c_str(), O_RDONLY);
635 if (inFile == -1)
636 return MakeErrMsg(ErrMsg, Src.toString() +
637 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000638
Reid Spencer51c5a282006-08-23 20:34:57 +0000639 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
640 if (outFile == -1) {
641 ::close(inFile);
642 return MakeErrMsg(ErrMsg, Dest.toString() +
643 ": can't create destination file for copy");
644 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000645
Reid Spencer51c5a282006-08-23 20:34:57 +0000646 char Buffer[16*1024];
647 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
648 if (Amt == -1) {
649 if (errno != EINTR && errno != EAGAIN) {
650 ::close(inFile);
651 ::close(outFile);
652 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
653 }
654 } else {
655 char *BufPtr = Buffer;
656 while (Amt) {
657 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
658 if (AmtWritten == -1) {
659 if (errno != EINTR && errno != EAGAIN) {
660 ::close(inFile);
661 ::close(outFile);
662 return MakeErrMsg(ErrMsg, Dest.toString() +
663 ": can't write destination file: ");
Reid Spencerc29befb2004-12-15 01:50:13 +0000664 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000665 } else {
666 Amt -= AmtWritten;
667 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000668 }
669 }
670 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000671 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000672 ::close(inFile);
673 ::close(outFile);
674 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000675}
676
Reid Spencer51c5a282006-08-23 20:34:57 +0000677bool
678Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000679 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000680 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000681
682 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
683 // mktemp or our own implementation.
684 char *FNBuffer = (char*) alloca(path.size()+8);
685 path.copy(FNBuffer,path.size());
686 strcpy(FNBuffer+path.size(), "-XXXXXX");
687
688#if defined(HAVE_MKSTEMP)
689 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000690 if ((TempFD = mkstemp(FNBuffer)) == -1)
691 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000692
693 // We don't need to hold the temp file descriptor... we will trust that no one
694 // will overwrite/delete the file before we can open it again.
695 close(TempFD);
696
697 // Save the name
698 path = FNBuffer;
699#elif defined(HAVE_MKTEMP)
700 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000701 if (mktemp(FNBuffer) == 0)
702 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000703
704 // Save the name
705 path = FNBuffer;
706#else
707 // Okay, looks like we have to do it all by our lonesome.
708 static unsigned FCounter = 0;
709 unsigned offset = path.size() + 1;
710 while ( FCounter < 999999 && exists()) {
711 sprintf(FNBuffer+offset,"%06u",++FCounter);
712 path = FNBuffer;
713 }
714 if (FCounter > 999999)
Reid Spencer51c5a282006-08-23 20:34:57 +0000715 return MakeErrMsg(ErrMsg,
716 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000717#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000718 return false;
719}
Reid Spencerc29befb2004-12-15 01:50:13 +0000720
Reid Spencer51c5a282006-08-23 20:34:57 +0000721} // end llvm namespace
Reid Spencerb89a2232004-08-25 06:20:07 +0000722