blob: e11213294c63c36064958241bf860f0db2045fed [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
Chris Lattner1a091442008-03-03 02:55:43 +000050#if HAVE_DLFCN_H
51#include <dlfcn.h>
52#endif
53
Reid Spencer932e2e32005-06-02 05:38:20 +000054// Put in a hack for Cygwin which falsely reports that the mkdtemp function
55// is available when it is not.
56#ifdef __CYGWIN__
57# undef HAVE_MKDTEMP
58#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000059
Reid Spencer3be872e2005-07-28 16:25:57 +000060namespace {
61inline bool lastIsSlash(const std::string& path) {
62 return !path.empty() && path[path.length() - 1] == '/';
63}
64
65}
66
Reid Spencer8e665952004-08-29 05:24:01 +000067namespace llvm {
68using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000069
Chris Lattnere1b332a2008-02-27 06:17:10 +000070extern const char sys::PathSeparator = ':';
71
Reid Spencer69a16162004-12-24 06:29:42 +000072bool
73Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000074 // Check some obvious things
Reid Spencer69a16162004-12-24 06:29:42 +000075 if (path.empty())
76 return false;
77 else if (path.length() >= MAXPATHLEN)
78 return false;
Reid Spencer6371ccb2005-07-08 06:53:26 +000079
80 // Check that the characters are ascii chars
81 size_t len = path.length();
82 unsigned i = 0;
83 while (i < len && isascii(path[i]))
84 ++i;
85 return i >= len;
Reid Spencer69a16162004-12-24 06:29:42 +000086}
87
Reid Spencer69cce812007-03-29 16:43:20 +000088bool
89Path::isAbsolute() const {
90 if (path.empty())
91 return false;
92 return path[0] == '/';
93}
Reid Spencer8e665952004-08-29 05:24:01 +000094Path
95Path::GetRootDirectory() {
96 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +000097 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +000098 return result;
99}
100
Reid Spencer69a16162004-12-24 06:29:42 +0000101Path
Reid Spencer48744762006-08-22 19:01:30 +0000102Path::GetTemporaryDirectory(std::string* ErrMsg ) {
Reid Spencer69a16162004-12-24 06:29:42 +0000103#if defined(HAVE_MKDTEMP)
104 // The best way is with mkdtemp but that's not available on many systems,
105 // Linux and FreeBSD have it. Others probably won't.
106 char pathname[MAXPATHLEN];
107 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000108 if (0 == mkdtemp(pathname)) {
109 MakeErrMsg(ErrMsg,
110 std::string(pathname) + ": can't create temporary directory");
111 return Path();
112 }
Reid Spencer69a16162004-12-24 06:29:42 +0000113 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000114 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000115 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
116 return result;
117#elif defined(HAVE_MKSTEMP)
118 // If no mkdtemp is available, mkstemp can be used to create a temporary file
119 // which is then removed and created as a directory. We prefer this over
120 // mktemp because of mktemp's inherent security and threading risks. We still
121 // have a slight race condition from the time the temporary file is created to
122 // the time it is re-created as a directoy.
123 char pathname[MAXPATHLEN];
124 strcpy(pathname, "/tmp/llvm_XXXXXX");
125 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000126 if (-1 == (fd = mkstemp(pathname))) {
127 MakeErrMsg(ErrMsg,
128 std::string(pathname) + ": can't create temporary directory");
129 return Path();
130 }
Reid Spencer69a16162004-12-24 06:29:42 +0000131 ::close(fd);
132 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000133 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
134 MakeErrMsg(ErrMsg,
135 std::string(pathname) + ": can't create temporary directory");
136 return Path();
137 }
Reid Spencer69a16162004-12-24 06:29:42 +0000138 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000139 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000140 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
141 return result;
142#elif defined(HAVE_MKTEMP)
143 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
144 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
145 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
146 // the XXXXXX with the pid of the process and a letter. That leads to only
147 // twenty six temporary files that can be generated.
148 char pathname[MAXPATHLEN];
149 strcpy(pathname, "/tmp/llvm_XXXXXX");
150 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000151 if (TmpName == 0) {
152 MakeErrMsg(ErrMsg,
153 std::string(TmpName) + ": can't create unique directory name");
154 return Path();
155 }
156 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
157 MakeErrMsg(ErrMsg,
158 std::string(TmpName) + ": can't create temporary directory");
159 return Path();
160 }
Reid Spencer69a16162004-12-24 06:29:42 +0000161 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000162 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000163 assert(result.isValid() && "mktemp didn't create a valid pathname!");
164 return result;
165#else
166 // This is the worst case implementation. tempnam(3) leaks memory unless its
167 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
168 // issues. The mktemp(3) function doesn't have enough variability in the
169 // temporary name generated. So, we provide our own implementation that
170 // increments an integer from a random number seeded by the current time. This
171 // should be sufficiently unique that we don't have many collisions between
172 // processes. Generally LLVM processes don't run very long and don't use very
173 // many temporary files so this shouldn't be a big issue for LLVM.
174 static time_t num = ::time(0);
175 char pathname[MAXPATHLEN];
176 do {
177 num++;
178 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
179 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000180 if (-1 == ::mkdir(pathname, S_IRWXU)) {
181 MakeErrMsg(ErrMsg,
182 std::string(pathname) + ": can't create temporary directory");
183 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000184 }
Reid Spencer69a16162004-12-24 06:29:42 +0000185 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000186 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000187 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
188 return result;
189#endif
190}
191
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000192void
193Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
194#ifdef LTDL_SHLIBPATH_VAR
195 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
196 if (env_var != 0) {
197 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000198 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000199#endif
200 // FIXME: Should this look at LD_LIBRARY_PATH too?
201 Paths.push_back(sys::Path("/usr/local/lib/"));
202 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
203 Paths.push_back(sys::Path("/usr/lib/"));
204 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000205}
206
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000207void
Gabor Greifa99be512007-07-05 17:07:56 +0000208Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000209 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
210 if (env_var != 0) {
211 getPathList(env_var,Paths);
212 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000213#ifdef LLVM_LIBDIR
214 {
215 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000216 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000217 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000218 Paths.push_back(tmpPath);
219 }
220#endif
221 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000222}
223
224Path
225Path::GetLLVMDefaultConfigDir() {
226 return Path("/etc/llvm/");
227}
228
Reid Spencer8e665952004-08-29 05:24:01 +0000229Path
230Path::GetUserHomeDirectory() {
231 const char* home = getenv("HOME");
232 if (home) {
233 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000234 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000235 return result;
236 }
237 return GetRootDirectory();
238}
239
Ted Kremenek79200782007-12-18 22:07:33 +0000240Path
241Path::GetCurrentDirectory() {
242 char pathname[MAXPATHLEN];
243 if (!getcwd(pathname,MAXPATHLEN)) {
244 assert (false && "Could not query current working directory.");
245 return Path("");
246 }
247
248 return Path(pathname);
249}
Reid Spencera229c5c2005-07-08 03:08:58 +0000250
Chris Lattner1a091442008-03-03 02:55:43 +0000251/// GetMainExecutable - Return the path to the main executable, given the
252/// value of argv[0] from program startup.
253Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Chris Lattner3bdfa042008-03-13 05:22:05 +0000254#if defined(__CYGWIN__)
255 char exe_link[64];
256 snprintf(exe_link, sizeof(exe_link), "/proc/%d/exe", getpid());
257 char exe_path[MAXPATHLEN];
258 ssize_t len = readlink(exe_link, exe_path, sizeof(exe_path));
259 if (len > 0 && len < MAXPATHLEN - 1) {
260 exe_path[len] = '\0';
261 return Path(std::string(exe_path));
262 }
263#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000264 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000265 Dl_info DLInfo;
266 int err = dladdr(MainAddr, &DLInfo);
267 if (err != 0)
268 return Path(std::string(DLInfo.dli_fname));
269#endif
270 return Path();
271}
272
273
Reid Spencer1b554b42004-09-11 04:55:08 +0000274std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000275Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000276 // Find the last slash
277 size_t slash = path.rfind('/');
278 if (slash == std::string::npos)
279 slash = 0;
280 else
281 slash++;
282
Jeff Cohen73f36672005-07-09 18:42:02 +0000283 size_t dot = path.rfind('.');
284 if (dot == std::string::npos || dot < slash)
285 return path.substr(slash);
286 else
287 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000288}
289
Reid Spencereaf18152004-11-14 22:08:36 +0000290bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000291 assert(len < 1024 && "Request for magic string too long");
292 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000293 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000294 if (fd < 0)
295 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000296 ssize_t bytes_read = ::read(fd, buf, len);
297 ::close(fd);
298 if (ssize_t(len) != bytes_read) {
299 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000300 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000301 }
302 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000303 return true;
304}
305
Reid Spencer1b554b42004-09-11 04:55:08 +0000306bool
Reid Spencer8e665952004-08-29 05:24:01 +0000307Path::exists() const {
308 return 0 == access(path.c_str(), F_OK );
309}
310
311bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000312Path::isDirectory() const {
313 struct stat buf;
314 if (0 != stat(path.c_str(), &buf))
315 return false;
316 return buf.st_mode & S_IFDIR ? true : false;
317}
318
319bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000320Path::canRead() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000321 return 0 == access(path.c_str(), F_OK | R_OK );
322}
323
324bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000325Path::canWrite() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000326 return 0 == access(path.c_str(), F_OK | W_OK );
327}
328
329bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000330Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000331 if (0 != access(path.c_str(), R_OK | X_OK ))
332 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000333 struct stat buf;
334 if (0 != stat(path.c_str(), &buf))
335 return false;
336 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000337 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000338 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000339}
340
341std::string
342Path::getLast() const {
343 // Find the last slash
344 size_t pos = path.rfind('/');
345
346 // Handle the corner cases
347 if (pos == std::string::npos)
348 return path;
349
350 // If the last character is a slash
351 if (pos == path.length()-1) {
352 // Find the second to last slash
353 size_t pos2 = path.rfind('/', pos-1);
354 if (pos2 == std::string::npos)
355 return path.substr(0,pos);
356 else
357 return path.substr(pos2+1,pos-pos2-1);
358 }
359 // Return everything after the last slash
360 return path.substr(pos+1);
361}
362
Reid Spencer2ae9d112007-04-07 18:52:17 +0000363const FileStatus *
364PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
365 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000366 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000367 if (0 != stat(path.c_str(), &buf)) {
368 MakeErrMsg(ErrStr, path + ": can't get status of file");
369 return 0;
370 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000371 status.fileSize = buf.st_size;
372 status.modTime.fromEpochTime(buf.st_mtime);
373 status.mode = buf.st_mode;
374 status.user = buf.st_uid;
375 status.group = buf.st_gid;
376 status.uniqueID = uint64_t(buf.st_ino);
377 status.isDir = S_ISDIR(buf.st_mode);
378 status.isFile = S_ISREG(buf.st_mode);
379 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000380 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000381 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000382}
383
Chris Lattner252ad032006-07-28 22:03:44 +0000384static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000385 // Get the umask value from the operating system. We want to use it
386 // when changing the file's permissions. Since calling umask() sets
387 // the umask and returns its old value, we must call it a second
388 // time to reset it to the user's preference.
389 int mask = umask(0777); // The arg. to umask is arbitrary.
390 umask(mask); // Restore the umask.
391
392 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000393 struct stat buf;
394 if (0 != stat(File.toString().c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000395 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000396 // Change the file to have whichever permissions bits from 'bits'
397 // that the umask would not disable.
398 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
399 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000400 return true;
401}
402
Reid Spencere1647f42006-08-22 23:27:23 +0000403bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000404 if (!AddPermissionBits(*this, 0444))
405 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000406 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000407}
408
Reid Spencere1647f42006-08-22 23:27:23 +0000409bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000410 if (!AddPermissionBits(*this, 0222))
411 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000412 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000413}
414
Reid Spencere1647f42006-08-22 23:27:23 +0000415bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000416 if (!AddPermissionBits(*this, 0111))
417 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000418 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000419}
420
Reid Spencereaf18152004-11-14 22:08:36 +0000421bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000422Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000423 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000424 if (direntries == 0)
425 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000426
Reid Spencer3be872e2005-07-28 16:25:57 +0000427 std::string dirPath = path;
428 if (!lastIsSlash(dirPath))
429 dirPath += '/';
430
Reid Spencereaf18152004-11-14 22:08:36 +0000431 result.clear();
432 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000433 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000434 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000435 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000436 struct stat st;
437 if (0 != lstat(aPath.path.c_str(), &st)) {
438 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000439 continue; // dangling symlink -- ignore
Reid Spencer5a060772006-08-23 07:30:48 +0000440 return MakeErrMsg(ErrMsg,
441 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000442 }
Reid Spencerb608a812004-11-16 06:15:19 +0000443 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000444 }
Reid Spencereaf18152004-11-14 22:08:36 +0000445 }
446
447 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000448 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000449}
450
Reid Spencer8e665952004-08-29 05:24:01 +0000451bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000452Path::set(const std::string& a_path) {
453 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000454 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000455 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000456 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000457 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000458 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000459 return false;
460 }
461 return true;
462}
463
464bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000465Path::appendComponent(const std::string& name) {
466 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000467 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000468 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000469 if (!lastIsSlash(path))
470 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000471 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000472 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000473 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000474 return false;
475 }
476 return true;
477}
478
479bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000480Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000481 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000482 if (slashpos == 0 || slashpos == std::string::npos) {
483 path.erase();
484 return true;
485 }
Reid Spencer8e665952004-08-29 05:24:01 +0000486 if (slashpos == path.size() - 1)
487 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000488 if (slashpos == std::string::npos) {
489 path.erase();
490 return true;
491 }
Reid Spencer8e665952004-08-29 05:24:01 +0000492 path.erase(slashpos);
493 return true;
494}
495
496bool
Reid Spencer07adb282004-11-05 22:15:36 +0000497Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000498 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000499 path.append(".");
500 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000501 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000502 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000503 return false;
504 }
505 return true;
506}
507
Reid Spencerdd04df02005-07-07 23:21:43 +0000508bool
509Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000510 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000511 size_t dotpos = path.rfind('.',path.size());
512 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000513 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000514 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000515 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000516 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000517 }
Reid Spencer8e665952004-08-29 05:24:01 +0000518 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000519 if (!isValid())
520 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000521 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000522}
523
Reid Spencer8e665952004-08-29 05:24:01 +0000524bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000525Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000526 // Get a writeable copy of the path name
527 char pathname[MAXPATHLEN];
528 path.copy(pathname,MAXPATHLEN);
529
530 // Null-terminate the last component
531 int lastchar = path.length() - 1 ;
532 if (pathname[lastchar] == '/')
533 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000534 else
535 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000536
537 // If we're supposed to create intermediate directories
538 if ( create_parents ) {
539 // Find the end of the initial name component
540 char * next = strchr(pathname,'/');
541 if ( pathname[0] == '/')
542 next = strchr(&pathname[1],'/');
543
544 // Loop through the directory components until we're done
545 while ( next != 0 ) {
546 *next = 0;
547 if (0 != access(pathname, F_OK | R_OK | W_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000548 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000549 return MakeErrMsg(ErrMsg,
550 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000551 }
Reid Spencer8e665952004-08-29 05:24:01 +0000552 char* save = next;
Reid Spencereaf18152004-11-14 22:08:36 +0000553 next = strchr(next+1,'/');
Reid Spencer8e665952004-08-29 05:24:01 +0000554 *save = '/';
555 }
Reid Spencer8e665952004-08-29 05:24:01 +0000556 }
Reid Spencereaf18152004-11-14 22:08:36 +0000557
558 if (0 != access(pathname, F_OK | R_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000559 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000560 return MakeErrMsg(ErrMsg,
561 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000562 }
563 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000564}
565
566bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000567Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000568 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000569 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000570 if (fd < 0)
571 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000572 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000573 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000574}
575
Reid Spencer8e665952004-08-29 05:24:01 +0000576bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000577Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000578 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000579 if (makeUnique( reuse_current, ErrMsg ))
580 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000581
582 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000583 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Reid Spencer5a060772006-08-23 07:30:48 +0000584 if (fd < 0)
585 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000586 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000587 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000588}
589
590bool
Chris Lattner0c332312006-07-28 22:29:50 +0000591Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Reid Spencer2ae9d112007-04-07 18:52:17 +0000592 // Get the status so we can determin if its a file or directory
593 struct stat buf;
594 if (0 != stat(path.c_str(), &buf)) {
595 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000596 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000597 }
598
599 // Note: this check catches strange situations. In all cases, LLVM should
600 // only be involved in the creation and deletion of regular files. This
601 // check ensures that what we're trying to erase is a regular file. It
602 // effectively prevents LLVM from erasing things like /dev/null, any block
603 // special file, or other things that aren't "regular" files.
604 if (S_ISREG(buf.st_mode)) {
605 if (unlink(path.c_str()) != 0)
606 return MakeErrMsg(ErrStr, path + ": can't destroy file");
607 return false;
608 }
609
610 if (!S_ISDIR(buf.st_mode)) {
611 if (ErrStr) *ErrStr = "not a file or directory";
612 return true;
613 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000614
Chris Lattner0c332312006-07-28 22:29:50 +0000615 if (remove_contents) {
616 // Recursively descend the directory to remove its contents.
617 std::string cmd = "/bin/rm -rf " + path;
618 system(cmd.c_str());
619 return false;
620 }
621
622 // Otherwise, try to just remove the one directory.
623 char pathname[MAXPATHLEN];
624 path.copy(pathname, MAXPATHLEN);
625 int lastchar = path.length() - 1 ;
626 if (pathname[lastchar] == '/')
627 pathname[lastchar] = 0;
628 else
629 pathname[lastchar+1] = 0;
630
631 if (rmdir(pathname) != 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000632 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000633 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000634 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000635}
636
637bool
Reid Spencer5a060772006-08-23 07:30:48 +0000638Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000639 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer5a060772006-08-23 07:30:48 +0000640 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Reid Spencer2aafadc2005-04-21 02:50:10 +0000641 newName.toString() + "' ");
Reid Spencer5a060772006-08-23 07:30:48 +0000642 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000643}
644
Reid Spencer2ae9d112007-04-07 18:52:17 +0000645bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000646Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000647 struct utimbuf utb;
648 utb.actime = si.modTime.toPosixTime();
649 utb.modtime = utb.actime;
650 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000651 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000652 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000653 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000654 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000655}
656
Reid Spencer51c5a282006-08-23 20:34:57 +0000657bool
658sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000659 int inFile = -1;
660 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000661 inFile = ::open(Src.c_str(), O_RDONLY);
662 if (inFile == -1)
663 return MakeErrMsg(ErrMsg, Src.toString() +
664 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000665
Reid Spencer51c5a282006-08-23 20:34:57 +0000666 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
667 if (outFile == -1) {
668 ::close(inFile);
669 return MakeErrMsg(ErrMsg, Dest.toString() +
670 ": can't create destination file for copy");
671 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000672
Reid Spencer51c5a282006-08-23 20:34:57 +0000673 char Buffer[16*1024];
674 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
675 if (Amt == -1) {
676 if (errno != EINTR && errno != EAGAIN) {
677 ::close(inFile);
678 ::close(outFile);
679 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
680 }
681 } else {
682 char *BufPtr = Buffer;
683 while (Amt) {
684 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
685 if (AmtWritten == -1) {
686 if (errno != EINTR && errno != EAGAIN) {
687 ::close(inFile);
688 ::close(outFile);
689 return MakeErrMsg(ErrMsg, Dest.toString() +
690 ": can't write destination file: ");
Reid Spencerc29befb2004-12-15 01:50:13 +0000691 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000692 } else {
693 Amt -= AmtWritten;
694 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000695 }
696 }
697 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000698 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000699 ::close(inFile);
700 ::close(outFile);
701 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000702}
703
Reid Spencer51c5a282006-08-23 20:34:57 +0000704bool
705Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000706 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000707 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000708
709 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
710 // mktemp or our own implementation.
711 char *FNBuffer = (char*) alloca(path.size()+8);
712 path.copy(FNBuffer,path.size());
713 strcpy(FNBuffer+path.size(), "-XXXXXX");
714
715#if defined(HAVE_MKSTEMP)
716 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000717 if ((TempFD = mkstemp(FNBuffer)) == -1)
718 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000719
720 // We don't need to hold the temp file descriptor... we will trust that no one
721 // will overwrite/delete the file before we can open it again.
722 close(TempFD);
723
724 // Save the name
725 path = FNBuffer;
726#elif defined(HAVE_MKTEMP)
727 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000728 if (mktemp(FNBuffer) == 0)
729 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000730
731 // Save the name
732 path = FNBuffer;
733#else
734 // Okay, looks like we have to do it all by our lonesome.
735 static unsigned FCounter = 0;
736 unsigned offset = path.size() + 1;
737 while ( FCounter < 999999 && exists()) {
738 sprintf(FNBuffer+offset,"%06u",++FCounter);
739 path = FNBuffer;
740 }
741 if (FCounter > 999999)
Reid Spencer51c5a282006-08-23 20:34:57 +0000742 return MakeErrMsg(ErrMsg,
743 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000744#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000745 return false;
746}
Reid Spencerc29befb2004-12-15 01:50:13 +0000747
Reid Spencer51c5a282006-08-23 20:34:57 +0000748} // end llvm namespace
Reid Spencerb89a2232004-08-25 06:20:07 +0000749