blob: c3d06a3fa1d573fe63f47ea3fe4e46ab02b956d1 [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
Chris Lattner14c762d2008-04-01 06:25:23 +000027#ifdef HAVE_SYS_MMAN_H
28#include <sys/mman.h>
29#endif
30#ifdef HAVE_SYS_STAT_H
31#include <sys/stat.h>
32#endif
Reid Spenceraf2f2082004-12-27 06:17:15 +000033#if HAVE_UTIME_H
Reid Spencereaf18152004-11-14 22:08:36 +000034#include <utime.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000035#endif
36#if HAVE_TIME_H
Reid Spencer69a16162004-12-24 06:29:42 +000037#include <time.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000038#endif
39#if HAVE_DIRENT_H
40# include <dirent.h>
41# define NAMLEN(dirent) strlen((dirent)->d_name)
42#else
43# define dirent direct
44# define NAMLEN(dirent) (dirent)->d_namlen
45# if HAVE_SYS_NDIR_H
46# include <sys/ndir.h>
47# endif
48# if HAVE_SYS_DIR_H
49# include <sys/dir.h>
50# endif
51# if HAVE_NDIR_H
52# include <ndir.h>
53# endif
54#endif
55
Chris Lattner1a091442008-03-03 02:55:43 +000056#if HAVE_DLFCN_H
57#include <dlfcn.h>
58#endif
59
Reid Spencer932e2e32005-06-02 05:38:20 +000060// Put in a hack for Cygwin which falsely reports that the mkdtemp function
61// is available when it is not.
62#ifdef __CYGWIN__
63# undef HAVE_MKDTEMP
64#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000065
Reid Spencer3be872e2005-07-28 16:25:57 +000066namespace {
67inline bool lastIsSlash(const std::string& path) {
68 return !path.empty() && path[path.length() - 1] == '/';
69}
70
71}
72
Reid Spencer8e665952004-08-29 05:24:01 +000073namespace llvm {
74using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000075
Chris Lattnere1b332a2008-02-27 06:17:10 +000076extern const char sys::PathSeparator = ':';
77
Reid Spencer69a16162004-12-24 06:29:42 +000078bool
79Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000080 // Check some obvious things
Reid Spencer69a16162004-12-24 06:29:42 +000081 if (path.empty())
82 return false;
83 else if (path.length() >= MAXPATHLEN)
84 return false;
Reid Spencer6371ccb2005-07-08 06:53:26 +000085
86 // Check that the characters are ascii chars
87 size_t len = path.length();
88 unsigned i = 0;
89 while (i < len && isascii(path[i]))
90 ++i;
91 return i >= len;
Reid Spencer69a16162004-12-24 06:29:42 +000092}
93
Reid Spencer69cce812007-03-29 16:43:20 +000094bool
95Path::isAbsolute() const {
96 if (path.empty())
97 return false;
98 return path[0] == '/';
99}
Reid Spencer8e665952004-08-29 05:24:01 +0000100Path
101Path::GetRootDirectory() {
102 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000103 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000104 return result;
105}
106
Reid Spencer69a16162004-12-24 06:29:42 +0000107Path
Reid Spencer48744762006-08-22 19:01:30 +0000108Path::GetTemporaryDirectory(std::string* ErrMsg ) {
Reid Spencer69a16162004-12-24 06:29:42 +0000109#if defined(HAVE_MKDTEMP)
110 // The best way is with mkdtemp but that's not available on many systems,
111 // Linux and FreeBSD have it. Others probably won't.
112 char pathname[MAXPATHLEN];
113 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000114 if (0 == mkdtemp(pathname)) {
115 MakeErrMsg(ErrMsg,
116 std::string(pathname) + ": can't create temporary directory");
117 return Path();
118 }
Reid Spencer69a16162004-12-24 06:29:42 +0000119 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000120 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000121 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
122 return result;
123#elif defined(HAVE_MKSTEMP)
124 // If no mkdtemp is available, mkstemp can be used to create a temporary file
125 // which is then removed and created as a directory. We prefer this over
126 // mktemp because of mktemp's inherent security and threading risks. We still
127 // have a slight race condition from the time the temporary file is created to
128 // the time it is re-created as a directoy.
129 char pathname[MAXPATHLEN];
130 strcpy(pathname, "/tmp/llvm_XXXXXX");
131 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000132 if (-1 == (fd = mkstemp(pathname))) {
133 MakeErrMsg(ErrMsg,
134 std::string(pathname) + ": can't create temporary directory");
135 return Path();
136 }
Reid Spencer69a16162004-12-24 06:29:42 +0000137 ::close(fd);
138 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000139 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
140 MakeErrMsg(ErrMsg,
141 std::string(pathname) + ": can't create temporary directory");
142 return Path();
143 }
Reid Spencer69a16162004-12-24 06:29:42 +0000144 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000145 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000146 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
147 return result;
148#elif defined(HAVE_MKTEMP)
149 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
150 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
151 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
152 // the XXXXXX with the pid of the process and a letter. That leads to only
153 // twenty six temporary files that can be generated.
154 char pathname[MAXPATHLEN];
155 strcpy(pathname, "/tmp/llvm_XXXXXX");
156 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000157 if (TmpName == 0) {
158 MakeErrMsg(ErrMsg,
159 std::string(TmpName) + ": can't create unique directory name");
160 return Path();
161 }
162 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
163 MakeErrMsg(ErrMsg,
164 std::string(TmpName) + ": can't create temporary directory");
165 return Path();
166 }
Reid Spencer69a16162004-12-24 06:29:42 +0000167 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000168 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000169 assert(result.isValid() && "mktemp didn't create a valid pathname!");
170 return result;
171#else
172 // This is the worst case implementation. tempnam(3) leaks memory unless its
173 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
174 // issues. The mktemp(3) function doesn't have enough variability in the
175 // temporary name generated. So, we provide our own implementation that
176 // increments an integer from a random number seeded by the current time. This
177 // should be sufficiently unique that we don't have many collisions between
178 // processes. Generally LLVM processes don't run very long and don't use very
179 // many temporary files so this shouldn't be a big issue for LLVM.
180 static time_t num = ::time(0);
181 char pathname[MAXPATHLEN];
182 do {
183 num++;
184 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
185 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000186 if (-1 == ::mkdir(pathname, S_IRWXU)) {
187 MakeErrMsg(ErrMsg,
188 std::string(pathname) + ": can't create temporary directory");
189 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000190 }
Reid Spencer69a16162004-12-24 06:29:42 +0000191 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000192 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000193 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
194 return result;
195#endif
196}
197
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000198void
199Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
200#ifdef LTDL_SHLIBPATH_VAR
201 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
202 if (env_var != 0) {
203 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000204 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000205#endif
206 // FIXME: Should this look at LD_LIBRARY_PATH too?
207 Paths.push_back(sys::Path("/usr/local/lib/"));
208 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
209 Paths.push_back(sys::Path("/usr/lib/"));
210 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000211}
212
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000213void
Gabor Greifa99be512007-07-05 17:07:56 +0000214Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000215 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
216 if (env_var != 0) {
217 getPathList(env_var,Paths);
218 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000219#ifdef LLVM_LIBDIR
220 {
221 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000222 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000223 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000224 Paths.push_back(tmpPath);
225 }
226#endif
227 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000228}
229
230Path
231Path::GetLLVMDefaultConfigDir() {
232 return Path("/etc/llvm/");
233}
234
Reid Spencer8e665952004-08-29 05:24:01 +0000235Path
236Path::GetUserHomeDirectory() {
237 const char* home = getenv("HOME");
238 if (home) {
239 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000240 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000241 return result;
242 }
243 return GetRootDirectory();
244}
245
Ted Kremenek79200782007-12-18 22:07:33 +0000246Path
247Path::GetCurrentDirectory() {
248 char pathname[MAXPATHLEN];
249 if (!getcwd(pathname,MAXPATHLEN)) {
250 assert (false && "Could not query current working directory.");
251 return Path("");
252 }
253
254 return Path(pathname);
255}
Reid Spencera229c5c2005-07-08 03:08:58 +0000256
Chris Lattner1a091442008-03-03 02:55:43 +0000257/// GetMainExecutable - Return the path to the main executable, given the
258/// value of argv[0] from program startup.
259Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Chris Lattner3bdfa042008-03-13 05:22:05 +0000260#if defined(__CYGWIN__)
261 char exe_link[64];
262 snprintf(exe_link, sizeof(exe_link), "/proc/%d/exe", getpid());
263 char exe_path[MAXPATHLEN];
264 ssize_t len = readlink(exe_link, exe_path, sizeof(exe_path));
265 if (len > 0 && len < MAXPATHLEN - 1) {
266 exe_path[len] = '\0';
267 return Path(std::string(exe_path));
268 }
269#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000270 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000271 Dl_info DLInfo;
272 int err = dladdr(MainAddr, &DLInfo);
273 if (err != 0)
274 return Path(std::string(DLInfo.dli_fname));
275#endif
276 return Path();
277}
278
279
Reid Spencer1b554b42004-09-11 04:55:08 +0000280std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000281Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000282 // Find the last slash
283 size_t slash = path.rfind('/');
284 if (slash == std::string::npos)
285 slash = 0;
286 else
287 slash++;
288
Jeff Cohen73f36672005-07-09 18:42:02 +0000289 size_t dot = path.rfind('.');
290 if (dot == std::string::npos || dot < slash)
291 return path.substr(slash);
292 else
293 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000294}
295
Reid Spencereaf18152004-11-14 22:08:36 +0000296bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000297 assert(len < 1024 && "Request for magic string too long");
298 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000299 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000300 if (fd < 0)
301 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000302 ssize_t bytes_read = ::read(fd, buf, len);
303 ::close(fd);
304 if (ssize_t(len) != bytes_read) {
305 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000306 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000307 }
308 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000309 return true;
310}
311
Reid Spencer1b554b42004-09-11 04:55:08 +0000312bool
Reid Spencer8e665952004-08-29 05:24:01 +0000313Path::exists() const {
314 return 0 == access(path.c_str(), F_OK );
315}
316
317bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000318Path::isDirectory() const {
319 struct stat buf;
320 if (0 != stat(path.c_str(), &buf))
321 return false;
322 return buf.st_mode & S_IFDIR ? true : false;
323}
324
325bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000326Path::canRead() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000327 return 0 == access(path.c_str(), F_OK | R_OK );
328}
329
330bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000331Path::canWrite() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000332 return 0 == access(path.c_str(), F_OK | W_OK );
333}
334
335bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000336Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000337 if (0 != access(path.c_str(), R_OK | X_OK ))
338 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000339 struct stat buf;
340 if (0 != stat(path.c_str(), &buf))
341 return false;
342 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000343 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000344 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000345}
346
347std::string
348Path::getLast() const {
349 // Find the last slash
350 size_t pos = path.rfind('/');
351
352 // Handle the corner cases
353 if (pos == std::string::npos)
354 return path;
355
356 // If the last character is a slash
357 if (pos == path.length()-1) {
358 // Find the second to last slash
359 size_t pos2 = path.rfind('/', pos-1);
360 if (pos2 == std::string::npos)
361 return path.substr(0,pos);
362 else
363 return path.substr(pos2+1,pos-pos2-1);
364 }
365 // Return everything after the last slash
366 return path.substr(pos+1);
367}
368
Reid Spencer2ae9d112007-04-07 18:52:17 +0000369const FileStatus *
370PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
371 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000372 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000373 if (0 != stat(path.c_str(), &buf)) {
374 MakeErrMsg(ErrStr, path + ": can't get status of file");
375 return 0;
376 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000377 status.fileSize = buf.st_size;
378 status.modTime.fromEpochTime(buf.st_mtime);
379 status.mode = buf.st_mode;
380 status.user = buf.st_uid;
381 status.group = buf.st_gid;
382 status.uniqueID = uint64_t(buf.st_ino);
383 status.isDir = S_ISDIR(buf.st_mode);
384 status.isFile = S_ISREG(buf.st_mode);
385 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000386 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000387 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000388}
389
Chris Lattner252ad032006-07-28 22:03:44 +0000390static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000391 // Get the umask value from the operating system. We want to use it
392 // when changing the file's permissions. Since calling umask() sets
393 // the umask and returns its old value, we must call it a second
394 // time to reset it to the user's preference.
395 int mask = umask(0777); // The arg. to umask is arbitrary.
396 umask(mask); // Restore the umask.
397
398 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000399 struct stat buf;
400 if (0 != stat(File.toString().c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000401 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000402 // Change the file to have whichever permissions bits from 'bits'
403 // that the umask would not disable.
404 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
405 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000406 return true;
407}
408
Reid Spencere1647f42006-08-22 23:27:23 +0000409bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000410 if (!AddPermissionBits(*this, 0444))
411 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
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::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000416 if (!AddPermissionBits(*this, 0222))
417 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000418 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000419}
420
Reid Spencere1647f42006-08-22 23:27:23 +0000421bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000422 if (!AddPermissionBits(*this, 0111))
423 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000424 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000425}
426
Reid Spencereaf18152004-11-14 22:08:36 +0000427bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000428Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000429 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000430 if (direntries == 0)
431 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000432
Reid Spencer3be872e2005-07-28 16:25:57 +0000433 std::string dirPath = path;
434 if (!lastIsSlash(dirPath))
435 dirPath += '/';
436
Reid Spencereaf18152004-11-14 22:08:36 +0000437 result.clear();
438 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000439 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000440 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000441 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000442 struct stat st;
443 if (0 != lstat(aPath.path.c_str(), &st)) {
444 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000445 continue; // dangling symlink -- ignore
Reid Spencer5a060772006-08-23 07:30:48 +0000446 return MakeErrMsg(ErrMsg,
447 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000448 }
Reid Spencerb608a812004-11-16 06:15:19 +0000449 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000450 }
Reid Spencereaf18152004-11-14 22:08:36 +0000451 }
452
453 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000454 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000455}
456
Reid Spencer8e665952004-08-29 05:24:01 +0000457bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000458Path::set(const std::string& a_path) {
459 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000460 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000461 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000462 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000463 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000464 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000465 return false;
466 }
467 return true;
468}
469
470bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000471Path::appendComponent(const std::string& name) {
472 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000473 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000474 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000475 if (!lastIsSlash(path))
476 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000477 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000478 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000479 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000480 return false;
481 }
482 return true;
483}
484
485bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000486Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000487 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000488 if (slashpos == 0 || slashpos == std::string::npos) {
489 path.erase();
490 return true;
491 }
Reid Spencer8e665952004-08-29 05:24:01 +0000492 if (slashpos == path.size() - 1)
493 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000494 if (slashpos == std::string::npos) {
495 path.erase();
496 return true;
497 }
Reid Spencer8e665952004-08-29 05:24:01 +0000498 path.erase(slashpos);
499 return true;
500}
501
502bool
Reid Spencer07adb282004-11-05 22:15:36 +0000503Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000504 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000505 path.append(".");
506 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000507 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000508 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000509 return false;
510 }
511 return true;
512}
513
Reid Spencerdd04df02005-07-07 23:21:43 +0000514bool
515Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000516 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000517 size_t dotpos = path.rfind('.',path.size());
518 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000519 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000520 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000521 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000522 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000523 }
Reid Spencer8e665952004-08-29 05:24:01 +0000524 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000525 if (!isValid())
526 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000527 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000528}
529
Ted Kremenekc5412c52008-04-03 16:11:31 +0000530static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
531
532 if (access(beg, F_OK | R_OK | W_OK) == 0)
533 return false;
534
535 if (create_parents) {
536
537 char* c = end;
538
539 for (; c != beg; --c)
540 if (*c == '/') {
541
542 // Recurse to handling the parent directory.
543 *c = '\0';
544 bool x = createDirectoryHelper(beg, c, create_parents);
545 *c = '/';
546
547 // Return if we encountered an error.
548 if (x)
549 return true;
550
551 break;
552 }
553 }
554
555 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
556}
557
Reid Spencer8e665952004-08-29 05:24:01 +0000558bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000559Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000560 // Get a writeable copy of the path name
561 char pathname[MAXPATHLEN];
562 path.copy(pathname,MAXPATHLEN);
563
564 // Null-terminate the last component
Ted Kremenekc5412c52008-04-03 16:11:31 +0000565 int lastchar = path.length() - 1 ;
566
567 if (pathname[lastchar] != '/')
568 ++lastchar;
569
570 pathname[lastchar] = 0;
571
572 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
573 return MakeErrMsg(ErrMsg,
574 std::string(pathname) + ": can't create directory");
575
Reid Spencere5c9cb52006-08-23 00:39:35 +0000576 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000577}
578
579bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000580Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000581 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000582 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000583 if (fd < 0)
584 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000585 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000586 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000587}
588
Reid Spencer8e665952004-08-29 05:24:01 +0000589bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000590Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000591 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000592 if (makeUnique( reuse_current, ErrMsg ))
593 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000594
595 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000596 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Reid Spencer5a060772006-08-23 07:30:48 +0000597 if (fd < 0)
598 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000599 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000600 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000601}
602
603bool
Chris Lattner0c332312006-07-28 22:29:50 +0000604Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Reid Spencer2ae9d112007-04-07 18:52:17 +0000605 // Get the status so we can determin if its a file or directory
606 struct stat buf;
607 if (0 != stat(path.c_str(), &buf)) {
608 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000609 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000610 }
611
612 // Note: this check catches strange situations. In all cases, LLVM should
613 // only be involved in the creation and deletion of regular files. This
614 // check ensures that what we're trying to erase is a regular file. It
615 // effectively prevents LLVM from erasing things like /dev/null, any block
616 // special file, or other things that aren't "regular" files.
617 if (S_ISREG(buf.st_mode)) {
618 if (unlink(path.c_str()) != 0)
619 return MakeErrMsg(ErrStr, path + ": can't destroy file");
620 return false;
621 }
622
623 if (!S_ISDIR(buf.st_mode)) {
624 if (ErrStr) *ErrStr = "not a file or directory";
625 return true;
626 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000627
Chris Lattner0c332312006-07-28 22:29:50 +0000628 if (remove_contents) {
629 // Recursively descend the directory to remove its contents.
630 std::string cmd = "/bin/rm -rf " + path;
631 system(cmd.c_str());
632 return false;
633 }
634
635 // Otherwise, try to just remove the one directory.
636 char pathname[MAXPATHLEN];
637 path.copy(pathname, MAXPATHLEN);
638 int lastchar = path.length() - 1 ;
639 if (pathname[lastchar] == '/')
640 pathname[lastchar] = 0;
641 else
642 pathname[lastchar+1] = 0;
643
644 if (rmdir(pathname) != 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000645 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000646 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000647 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000648}
649
650bool
Reid Spencer5a060772006-08-23 07:30:48 +0000651Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000652 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer5a060772006-08-23 07:30:48 +0000653 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Reid Spencer2aafadc2005-04-21 02:50:10 +0000654 newName.toString() + "' ");
Reid Spencer5a060772006-08-23 07:30:48 +0000655 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000656}
657
Reid Spencer2ae9d112007-04-07 18:52:17 +0000658bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000659Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000660 struct utimbuf utb;
661 utb.actime = si.modTime.toPosixTime();
662 utb.modtime = utb.actime;
663 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000664 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000665 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000666 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000667 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000668}
669
Reid Spencer51c5a282006-08-23 20:34:57 +0000670bool
671sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000672 int inFile = -1;
673 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000674 inFile = ::open(Src.c_str(), O_RDONLY);
675 if (inFile == -1)
676 return MakeErrMsg(ErrMsg, Src.toString() +
677 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000678
Reid Spencer51c5a282006-08-23 20:34:57 +0000679 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
680 if (outFile == -1) {
681 ::close(inFile);
682 return MakeErrMsg(ErrMsg, Dest.toString() +
683 ": can't create destination file for copy");
684 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000685
Reid Spencer51c5a282006-08-23 20:34:57 +0000686 char Buffer[16*1024];
687 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
688 if (Amt == -1) {
689 if (errno != EINTR && errno != EAGAIN) {
690 ::close(inFile);
691 ::close(outFile);
692 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
693 }
694 } else {
695 char *BufPtr = Buffer;
696 while (Amt) {
697 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
698 if (AmtWritten == -1) {
699 if (errno != EINTR && errno != EAGAIN) {
700 ::close(inFile);
701 ::close(outFile);
702 return MakeErrMsg(ErrMsg, Dest.toString() +
703 ": can't write destination file: ");
Reid Spencerc29befb2004-12-15 01:50:13 +0000704 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000705 } else {
706 Amt -= AmtWritten;
707 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000708 }
709 }
710 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000711 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000712 ::close(inFile);
713 ::close(outFile);
714 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000715}
716
Reid Spencer51c5a282006-08-23 20:34:57 +0000717bool
718Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000719 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000720 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000721
722 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
723 // mktemp or our own implementation.
724 char *FNBuffer = (char*) alloca(path.size()+8);
725 path.copy(FNBuffer,path.size());
726 strcpy(FNBuffer+path.size(), "-XXXXXX");
727
728#if defined(HAVE_MKSTEMP)
729 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000730 if ((TempFD = mkstemp(FNBuffer)) == -1)
731 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000732
733 // We don't need to hold the temp file descriptor... we will trust that no one
734 // will overwrite/delete the file before we can open it again.
735 close(TempFD);
736
737 // Save the name
738 path = FNBuffer;
739#elif defined(HAVE_MKTEMP)
740 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000741 if (mktemp(FNBuffer) == 0)
742 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000743
744 // Save the name
745 path = FNBuffer;
746#else
747 // Okay, looks like we have to do it all by our lonesome.
748 static unsigned FCounter = 0;
749 unsigned offset = path.size() + 1;
750 while ( FCounter < 999999 && exists()) {
751 sprintf(FNBuffer+offset,"%06u",++FCounter);
752 path = FNBuffer;
753 }
754 if (FCounter > 999999)
Reid Spencer51c5a282006-08-23 20:34:57 +0000755 return MakeErrMsg(ErrMsg,
756 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000757#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000758 return false;
759}
Reid Spencerc29befb2004-12-15 01:50:13 +0000760
Chris Lattner799ed102008-04-01 06:00:12 +0000761const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000762 int Flags = MAP_PRIVATE;
763#ifdef MAP_FILE
764 Flags |= MAP_FILE;
765#endif
766 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
767 if (BasePtr == MAP_FAILED)
768 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000769 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000770}
771
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000772void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000773 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000774}
775
Reid Spencer51c5a282006-08-23 20:34:57 +0000776} // end llvm namespace
Reid Spencerb89a2232004-08-25 06:20:07 +0000777