blob: 8e76b543ff3befbbd25b88e1506dbfff10da1bc2 [file] [log] [blame]
Reid Spencer814ba572004-08-25 06:20:07 +00001//===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Spencer814ba572004-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 Spencer6df221d2004-08-29 05:24:01 +000016//=== is guaranteed to work on *all* UNIX variants.
Reid Spencer814ba572004-08-25 06:20:07 +000017//===----------------------------------------------------------------------===//
18
Misha Brukmanf06cb1d2004-12-20 00:16:38 +000019#include "llvm/Config/alloca.h"
Reid Spencer814ba572004-08-25 06:20:07 +000020#include "Unix.h"
Reid Spencerd103e082004-12-27 06:17:15 +000021#if HAVE_SYS_STAT_H
Reid Spencer814ba572004-08-25 06:20:07 +000022#include <sys/stat.h>
Reid Spencerd103e082004-12-27 06:17:15 +000023#endif
24#if HAVE_FCNTL_H
Reid Spencer814ba572004-08-25 06:20:07 +000025#include <fcntl.h>
Reid Spencerd103e082004-12-27 06:17:15 +000026#endif
27#if HAVE_UTIME_H
Reid Spencerc1d474f2004-11-14 22:08:36 +000028#include <utime.h>
Reid Spencerd103e082004-12-27 06:17:15 +000029#endif
30#if HAVE_TIME_H
Reid Spencer20540312004-12-24 06:29:42 +000031#include <time.h>
Reid Spencerd103e082004-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 Lattnere209be42008-03-03 02:55:43 +000050#if HAVE_DLFCN_H
51#include <dlfcn.h>
52#endif
53
Reid Spencerd1ef1df2005-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 Spencer814ba572004-08-25 06:20:07 +000059
Reid Spencer29f83e02005-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 Spencer6df221d2004-08-29 05:24:01 +000067namespace llvm {
68using namespace sys;
Reid Spencer814ba572004-08-25 06:20:07 +000069
Chris Lattner6fca9382008-02-27 06:17:10 +000070extern const char sys::PathSeparator = ':';
71
Reid Spencer20540312004-12-24 06:29:42 +000072bool
73Path::isValid() const {
Reid Spencerd28e432c2005-07-08 06:53:26 +000074 // Check some obvious things
Reid Spencer20540312004-12-24 06:29:42 +000075 if (path.empty())
76 return false;
77 else if (path.length() >= MAXPATHLEN)
78 return false;
Reid Spencerd28e432c2005-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 Spencer20540312004-12-24 06:29:42 +000086}
87
Reid Spencer0f92f0e2007-03-29 16:43:20 +000088bool
89Path::isAbsolute() const {
90 if (path.empty())
91 return false;
92 return path[0] == '/';
93}
Reid Spencer6df221d2004-08-29 05:24:01 +000094Path
95Path::GetRootDirectory() {
96 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +000097 result.set("/");
Reid Spencer6df221d2004-08-29 05:24:01 +000098 return result;
99}
100
Reid Spencer20540312004-12-24 06:29:42 +0000101Path
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000102Path::GetTemporaryDirectory(std::string* ErrMsg ) {
Reid Spencer20540312004-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 Spencer6ba87bb2006-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 Spencer20540312004-12-24 06:29:42 +0000113 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000114 result.set(pathname);
Reid Spencer20540312004-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 Spencer6ba87bb2006-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 Spencer20540312004-12-24 06:29:42 +0000131 ::close(fd);
132 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer6ba87bb2006-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 Spencer20540312004-12-24 06:29:42 +0000138 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000139 result.set(pathname);
Reid Spencer20540312004-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 Spencer6ba87bb2006-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 Spencer20540312004-12-24 06:29:42 +0000161 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000162 result.set(TmpName);
Reid Spencer20540312004-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 Spencer6ba87bb2006-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 Spencere4ca7222006-08-23 20:34:57 +0000184 }
Reid Spencer20540312004-12-24 06:29:42 +0000185 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000186 result.set(pathname);
Reid Spencer20540312004-12-24 06:29:42 +0000187 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
188 return result;
189#endif
190}
191
Reid Spencer9b155dc2004-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 Spencerdf05ec72004-09-14 00:16:39 +0000198 }
Reid Spencer9b155dc2004-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 Spencerdf05ec72004-09-14 00:16:39 +0000205}
206
Reid Spencer9b155dc2004-12-13 03:00:51 +0000207void
Gabor Greife16561c2007-07-05 17:07:56 +0000208Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer9b155dc2004-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 Spencer9b155dc2004-12-13 03:00:51 +0000213#ifdef LLVM_LIBDIR
214 {
215 Path tmpPath;
Reid Spencerc9c04732005-07-07 23:21:43 +0000216 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencer5b891e92005-07-07 18:21:42 +0000217 if (tmpPath.canRead())
Reid Spencer9b155dc2004-12-13 03:00:51 +0000218 Paths.push_back(tmpPath);
219 }
220#endif
221 GetSystemLibraryPaths(Paths);
Reid Spencer6df221d2004-08-29 05:24:01 +0000222}
223
224Path
225Path::GetLLVMDefaultConfigDir() {
226 return Path("/etc/llvm/");
227}
228
Reid Spencer6df221d2004-08-29 05:24:01 +0000229Path
230Path::GetUserHomeDirectory() {
231 const char* home = getenv("HOME");
232 if (home) {
233 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000234 if (result.set(home))
Reid Spencer6df221d2004-08-29 05:24:01 +0000235 return result;
236 }
237 return GetRootDirectory();
238}
239
Ted Kremenek14020702007-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 Spenceraf48d862005-07-08 03:08:58 +0000250
Chris Lattnere209be42008-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) {
254 // Use dladdr to get executable path if available.
255#ifdef HAVE_DLFCN_H
256 Dl_info DLInfo;
257 int err = dladdr(MainAddr, &DLInfo);
258 if (err != 0)
259 return Path(std::string(DLInfo.dli_fname));
260#endif
261 return Path();
262}
263
264
Reid Spencerae9bbda2004-09-11 04:55:08 +0000265std::string
Reid Spencer0c6a2832004-11-05 22:15:36 +0000266Path::getBasename() const {
Reid Spencerae9bbda2004-09-11 04:55:08 +0000267 // Find the last slash
268 size_t slash = path.rfind('/');
269 if (slash == std::string::npos)
270 slash = 0;
271 else
272 slash++;
273
Jeff Cohen5b106d02005-07-09 18:42:02 +0000274 size_t dot = path.rfind('.');
275 if (dot == std::string::npos || dot < slash)
276 return path.substr(slash);
277 else
278 return path.substr(slash, dot - slash);
Reid Spencerae9bbda2004-09-11 04:55:08 +0000279}
280
Reid Spencerc1d474f2004-11-14 22:08:36 +0000281bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000282 assert(len < 1024 && "Request for magic string too long");
283 char* buf = (char*) alloca(1 + len);
Chris Lattnerbe119d42006-08-01 17:51:09 +0000284 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000285 if (fd < 0)
286 return false;
Reid Spencerf4731852004-12-02 09:09:48 +0000287 ssize_t bytes_read = ::read(fd, buf, len);
288 ::close(fd);
289 if (ssize_t(len) != bytes_read) {
290 Magic.clear();
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000291 return false;
Reid Spencerf4731852004-12-02 09:09:48 +0000292 }
293 Magic.assign(buf,len);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000294 return true;
295}
296
Reid Spencerae9bbda2004-09-11 04:55:08 +0000297bool
Reid Spencer6df221d2004-08-29 05:24:01 +0000298Path::exists() const {
299 return 0 == access(path.c_str(), F_OK );
300}
301
302bool
Ted Kremenek74db0422007-12-18 19:46:22 +0000303Path::isDirectory() const {
304 struct stat buf;
305 if (0 != stat(path.c_str(), &buf))
306 return false;
307 return buf.st_mode & S_IFDIR ? true : false;
308}
309
310bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000311Path::canRead() const {
Reid Spencer6df221d2004-08-29 05:24:01 +0000312 return 0 == access(path.c_str(), F_OK | R_OK );
313}
314
315bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000316Path::canWrite() const {
Reid Spencer6df221d2004-08-29 05:24:01 +0000317 return 0 == access(path.c_str(), F_OK | W_OK );
318}
319
320bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000321Path::canExecute() const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000322 if (0 != access(path.c_str(), R_OK | X_OK ))
323 return false;
Reid Spencerceeb9182007-04-07 18:52:17 +0000324 struct stat buf;
325 if (0 != stat(path.c_str(), &buf))
326 return false;
327 if (!S_ISREG(buf.st_mode))
Misha Brukmana9a8c1b2005-04-20 15:33:22 +0000328 return false;
Reid Spencer2d85f562005-07-08 17:46:10 +0000329 return true;
Reid Spencer6df221d2004-08-29 05:24:01 +0000330}
331
332std::string
333Path::getLast() const {
334 // Find the last slash
335 size_t pos = path.rfind('/');
336
337 // Handle the corner cases
338 if (pos == std::string::npos)
339 return path;
340
341 // If the last character is a slash
342 if (pos == path.length()-1) {
343 // Find the second to last slash
344 size_t pos2 = path.rfind('/', pos-1);
345 if (pos2 == std::string::npos)
346 return path.substr(0,pos);
347 else
348 return path.substr(pos2+1,pos-pos2-1);
349 }
350 // Return everything after the last slash
351 return path.substr(pos+1);
352}
353
Reid Spencerceeb9182007-04-07 18:52:17 +0000354const FileStatus *
355PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
356 if (!fsIsValid || update) {
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000357 struct stat buf;
Reid Spencer200c6f92007-03-29 19:05:44 +0000358 if (0 != stat(path.c_str(), &buf)) {
359 MakeErrMsg(ErrStr, path + ": can't get status of file");
360 return 0;
361 }
Reid Spencerceeb9182007-04-07 18:52:17 +0000362 status.fileSize = buf.st_size;
363 status.modTime.fromEpochTime(buf.st_mtime);
364 status.mode = buf.st_mode;
365 status.user = buf.st_uid;
366 status.group = buf.st_gid;
367 status.uniqueID = uint64_t(buf.st_ino);
368 status.isDir = S_ISDIR(buf.st_mode);
369 status.isFile = S_ISREG(buf.st_mode);
370 fsIsValid = true;
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000371 }
Reid Spencerceeb9182007-04-07 18:52:17 +0000372 return &status;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000373}
374
Chris Lattner48572532006-07-28 22:03:44 +0000375static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer94bf2262004-12-13 19:59:50 +0000376 // Get the umask value from the operating system. We want to use it
377 // when changing the file's permissions. Since calling umask() sets
378 // the umask and returns its old value, we must call it a second
379 // time to reset it to the user's preference.
380 int mask = umask(0777); // The arg. to umask is arbitrary.
381 umask(mask); // Restore the umask.
382
383 // Get the file's current mode.
Reid Spencerceeb9182007-04-07 18:52:17 +0000384 struct stat buf;
385 if (0 != stat(File.toString().c_str(), &buf))
Reid Spencer94bf2262004-12-13 19:59:50 +0000386 return false;
Reid Spencerceeb9182007-04-07 18:52:17 +0000387 // Change the file to have whichever permissions bits from 'bits'
388 // that the umask would not disable.
389 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
390 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000391 return true;
392}
393
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000394bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Reid Spencer879ed5a2006-08-23 07:30:48 +0000395 if (!AddPermissionBits(*this, 0444))
396 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000397 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000398}
399
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000400bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer879ed5a2006-08-23 07:30:48 +0000401 if (!AddPermissionBits(*this, 0222))
402 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000403 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000404}
405
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000406bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer879ed5a2006-08-23 07:30:48 +0000407 if (!AddPermissionBits(*this, 0111))
408 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000409 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000410}
411
Reid Spencerc1d474f2004-11-14 22:08:36 +0000412bool
Reid Spencer51edba12006-08-23 06:56:27 +0000413Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000414 DIR* direntries = ::opendir(path.c_str());
Reid Spencer879ed5a2006-08-23 07:30:48 +0000415 if (direntries == 0)
416 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencerc1d474f2004-11-14 22:08:36 +0000417
Reid Spencer29f83e02005-07-28 16:25:57 +0000418 std::string dirPath = path;
419 if (!lastIsSlash(dirPath))
420 dirPath += '/';
421
Reid Spencerc1d474f2004-11-14 22:08:36 +0000422 result.clear();
423 struct dirent* de = ::readdir(direntries);
Misha Brukman1001aea2005-04-20 04:04:07 +0000424 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000425 if (de->d_name[0] != '.') {
Reid Spencer29f83e02005-07-28 16:25:57 +0000426 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattner0b2890e2006-07-07 21:21:06 +0000427 struct stat st;
428 if (0 != lstat(aPath.path.c_str(), &st)) {
429 if (S_ISLNK(st.st_mode))
Misha Brukman1001aea2005-04-20 04:04:07 +0000430 continue; // dangling symlink -- ignore
Reid Spencer879ed5a2006-08-23 07:30:48 +0000431 return MakeErrMsg(ErrMsg,
432 aPath.path + ": can't determine file object type");
Misha Brukman1001aea2005-04-20 04:04:07 +0000433 }
Reid Spencer91f505e2004-11-16 06:15:19 +0000434 result.insert(aPath);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000435 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000436 }
437
438 closedir(direntries);
Reid Spencer51edba12006-08-23 06:56:27 +0000439 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000440}
441
Reid Spencer6df221d2004-08-29 05:24:01 +0000442bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000443Path::set(const std::string& a_path) {
444 if (a_path.empty())
Reid Spencer6df221d2004-08-29 05:24:01 +0000445 return false;
Reid Spencerc9c04732005-07-07 23:21:43 +0000446 std::string save(path);
Reid Spencer6df221d2004-08-29 05:24:01 +0000447 path = a_path;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000448 if (!isValid()) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000449 path = save;
Reid Spencer6df221d2004-08-29 05:24:01 +0000450 return false;
451 }
452 return true;
453}
454
455bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000456Path::appendComponent(const std::string& name) {
457 if (name.empty())
Reid Spencer6df221d2004-08-29 05:24:01 +0000458 return false;
Reid Spencerc9c04732005-07-07 23:21:43 +0000459 std::string save(path);
Reid Spencer29f83e02005-07-28 16:25:57 +0000460 if (!lastIsSlash(path))
461 path += '/';
Reid Spencerc9c04732005-07-07 23:21:43 +0000462 path += name;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000463 if (!isValid()) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000464 path = save;
Reid Spencer6df221d2004-08-29 05:24:01 +0000465 return false;
466 }
467 return true;
468}
469
470bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000471Path::eraseComponent() {
Reid Spencer6df221d2004-08-29 05:24:01 +0000472 size_t slashpos = path.rfind('/',path.size());
Reid Spencerc9c04732005-07-07 23:21:43 +0000473 if (slashpos == 0 || slashpos == std::string::npos) {
474 path.erase();
475 return true;
476 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000477 if (slashpos == path.size() - 1)
478 slashpos = path.rfind('/',slashpos-1);
Reid Spencerc9c04732005-07-07 23:21:43 +0000479 if (slashpos == std::string::npos) {
480 path.erase();
481 return true;
482 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000483 path.erase(slashpos);
484 return true;
485}
486
487bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000488Path::appendSuffix(const std::string& suffix) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000489 std::string save(path);
Reid Spencer6df221d2004-08-29 05:24:01 +0000490 path.append(".");
491 path.append(suffix);
Reid Spencer0c6a2832004-11-05 22:15:36 +0000492 if (!isValid()) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000493 path = save;
Reid Spencer6df221d2004-08-29 05:24:01 +0000494 return false;
495 }
496 return true;
497}
498
Reid Spencerc9c04732005-07-07 23:21:43 +0000499bool
500Path::eraseSuffix() {
Reid Spencerd28e432c2005-07-08 06:53:26 +0000501 std::string save = path;
Reid Spencer6df221d2004-08-29 05:24:01 +0000502 size_t dotpos = path.rfind('.',path.size());
503 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen4c241442005-07-08 04:49:16 +0000504 if (dotpos != std::string::npos) {
Jeff Cohen5b106d02005-07-09 18:42:02 +0000505 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen4c241442005-07-08 04:49:16 +0000506 path.erase(dotpos, path.size()-dotpos);
Jeff Cohenf5067762005-07-08 05:02:13 +0000507 return true;
Jeff Cohen4c241442005-07-08 04:49:16 +0000508 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000509 }
Reid Spencerd28e432c2005-07-08 06:53:26 +0000510 if (!isValid())
511 path = save;
Jeff Cohen4c241442005-07-08 04:49:16 +0000512 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000513}
514
Reid Spencer6df221d2004-08-29 05:24:01 +0000515bool
Reid Spencer8db84422006-08-23 00:39:35 +0000516Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000517 // Get a writeable copy of the path name
518 char pathname[MAXPATHLEN];
519 path.copy(pathname,MAXPATHLEN);
520
521 // Null-terminate the last component
522 int lastchar = path.length() - 1 ;
523 if (pathname[lastchar] == '/')
524 pathname[lastchar] = 0;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000525 else
526 pathname[lastchar+1] = 0;
Reid Spencer6df221d2004-08-29 05:24:01 +0000527
528 // If we're supposed to create intermediate directories
529 if ( create_parents ) {
530 // Find the end of the initial name component
531 char * next = strchr(pathname,'/');
532 if ( pathname[0] == '/')
533 next = strchr(&pathname[1],'/');
534
535 // Loop through the directory components until we're done
536 while ( next != 0 ) {
537 *next = 0;
538 if (0 != access(pathname, F_OK | R_OK | W_OK))
Reid Spencer8db84422006-08-23 00:39:35 +0000539 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer879ed5a2006-08-23 07:30:48 +0000540 return MakeErrMsg(ErrMsg,
541 std::string(pathname) + ": can't create directory");
Reid Spencer8db84422006-08-23 00:39:35 +0000542 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000543 char* save = next;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000544 next = strchr(next+1,'/');
Reid Spencer6df221d2004-08-29 05:24:01 +0000545 *save = '/';
546 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000547 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000548
549 if (0 != access(pathname, F_OK | R_OK))
Reid Spencer8db84422006-08-23 00:39:35 +0000550 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer879ed5a2006-08-23 07:30:48 +0000551 return MakeErrMsg(ErrMsg,
552 std::string(pathname) + ": can't create directory");
Reid Spencer8db84422006-08-23 00:39:35 +0000553 }
554 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000555}
556
557bool
Reid Spencer8db84422006-08-23 00:39:35 +0000558Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000559 // Create the file
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000560 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer879ed5a2006-08-23 07:30:48 +0000561 if (fd < 0)
562 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000563 ::close(fd);
Reid Spencer8db84422006-08-23 00:39:35 +0000564 return false;
Reid Spencer814ba572004-08-25 06:20:07 +0000565}
566
Reid Spencer6df221d2004-08-29 05:24:01 +0000567bool
Reid Spencer8db84422006-08-23 00:39:35 +0000568Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerf66d9322004-12-15 01:50:13 +0000569 // Make this into a unique file name
Reid Spencere4ca7222006-08-23 20:34:57 +0000570 if (makeUnique( reuse_current, ErrMsg ))
571 return true;
Reid Spencerf66d9322004-12-15 01:50:13 +0000572
573 // create the file
Reid Spencer8db84422006-08-23 00:39:35 +0000574 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Reid Spencer879ed5a2006-08-23 07:30:48 +0000575 if (fd < 0)
576 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencer8db84422006-08-23 00:39:35 +0000577 ::close(fd);
Reid Spencerf66d9322004-12-15 01:50:13 +0000578 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000579}
580
581bool
Chris Lattner3cec1092006-07-28 22:29:50 +0000582Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Reid Spencerceeb9182007-04-07 18:52:17 +0000583 // Get the status so we can determin if its a file or directory
584 struct stat buf;
585 if (0 != stat(path.c_str(), &buf)) {
586 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner3cec1092006-07-28 22:29:50 +0000587 return true;
Reid Spencerceeb9182007-04-07 18:52:17 +0000588 }
589
590 // Note: this check catches strange situations. In all cases, LLVM should
591 // only be involved in the creation and deletion of regular files. This
592 // check ensures that what we're trying to erase is a regular file. It
593 // effectively prevents LLVM from erasing things like /dev/null, any block
594 // special file, or other things that aren't "regular" files.
595 if (S_ISREG(buf.st_mode)) {
596 if (unlink(path.c_str()) != 0)
597 return MakeErrMsg(ErrStr, path + ": can't destroy file");
598 return false;
599 }
600
601 if (!S_ISDIR(buf.st_mode)) {
602 if (ErrStr) *ErrStr = "not a file or directory";
603 return true;
604 }
Reid Spencer200c6f92007-03-29 19:05:44 +0000605
Chris Lattner3cec1092006-07-28 22:29:50 +0000606 if (remove_contents) {
607 // Recursively descend the directory to remove its contents.
608 std::string cmd = "/bin/rm -rf " + path;
609 system(cmd.c_str());
610 return false;
611 }
612
613 // Otherwise, try to just remove the one directory.
614 char pathname[MAXPATHLEN];
615 path.copy(pathname, MAXPATHLEN);
616 int lastchar = path.length() - 1 ;
617 if (pathname[lastchar] == '/')
618 pathname[lastchar] = 0;
619 else
620 pathname[lastchar+1] = 0;
621
622 if (rmdir(pathname) != 0)
Reid Spencere4ca7222006-08-23 20:34:57 +0000623 return MakeErrMsg(ErrStr,
Reid Spencer200c6f92007-03-29 19:05:44 +0000624 std::string(pathname) + ": can't erase directory");
Chris Lattner3cec1092006-07-28 22:29:50 +0000625 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000626}
627
628bool
Reid Spencer879ed5a2006-08-23 07:30:48 +0000629Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000630 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer879ed5a2006-08-23 07:30:48 +0000631 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Reid Spencer8424ba32005-04-21 02:50:10 +0000632 newName.toString() + "' ");
Reid Spencer879ed5a2006-08-23 07:30:48 +0000633 return false;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000634}
635
Reid Spencerceeb9182007-04-07 18:52:17 +0000636bool
Chris Lattner60c50642006-07-28 22:36:17 +0000637Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000638 struct utimbuf utb;
639 utb.actime = si.modTime.toPosixTime();
640 utb.modtime = utb.actime;
641 if (0 != ::utime(path.c_str(),&utb))
Reid Spencere4ca7222006-08-23 20:34:57 +0000642 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencerc1d474f2004-11-14 22:08:36 +0000643 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencere4ca7222006-08-23 20:34:57 +0000644 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner60c50642006-07-28 22:36:17 +0000645 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000646}
647
Reid Spencere4ca7222006-08-23 20:34:57 +0000648bool
649sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerf66d9322004-12-15 01:50:13 +0000650 int inFile = -1;
651 int outFile = -1;
Reid Spencere4ca7222006-08-23 20:34:57 +0000652 inFile = ::open(Src.c_str(), O_RDONLY);
653 if (inFile == -1)
654 return MakeErrMsg(ErrMsg, Src.toString() +
655 ": can't open source file to copy");
Reid Spencerf66d9322004-12-15 01:50:13 +0000656
Reid Spencere4ca7222006-08-23 20:34:57 +0000657 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
658 if (outFile == -1) {
659 ::close(inFile);
660 return MakeErrMsg(ErrMsg, Dest.toString() +
661 ": can't create destination file for copy");
662 }
Reid Spencerf66d9322004-12-15 01:50:13 +0000663
Reid Spencere4ca7222006-08-23 20:34:57 +0000664 char Buffer[16*1024];
665 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
666 if (Amt == -1) {
667 if (errno != EINTR && errno != EAGAIN) {
668 ::close(inFile);
669 ::close(outFile);
670 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
671 }
672 } else {
673 char *BufPtr = Buffer;
674 while (Amt) {
675 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
676 if (AmtWritten == -1) {
677 if (errno != EINTR && errno != EAGAIN) {
678 ::close(inFile);
679 ::close(outFile);
680 return MakeErrMsg(ErrMsg, Dest.toString() +
681 ": can't write destination file: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000682 }
Reid Spencere4ca7222006-08-23 20:34:57 +0000683 } else {
684 Amt -= AmtWritten;
685 BufPtr += AmtWritten;
Reid Spencerf66d9322004-12-15 01:50:13 +0000686 }
687 }
688 }
Reid Spencerf66d9322004-12-15 01:50:13 +0000689 }
Reid Spencere4ca7222006-08-23 20:34:57 +0000690 ::close(inFile);
691 ::close(outFile);
692 return false;
Reid Spencerf66d9322004-12-15 01:50:13 +0000693}
694
Reid Spencere4ca7222006-08-23 20:34:57 +0000695bool
696Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer98ce23f2004-12-15 08:32:45 +0000697 if (reuse_current && !exists())
Reid Spencere4ca7222006-08-23 20:34:57 +0000698 return false; // File doesn't exist already, just use it!
Reid Spencerf66d9322004-12-15 01:50:13 +0000699
700 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
701 // mktemp or our own implementation.
702 char *FNBuffer = (char*) alloca(path.size()+8);
703 path.copy(FNBuffer,path.size());
704 strcpy(FNBuffer+path.size(), "-XXXXXX");
705
706#if defined(HAVE_MKSTEMP)
707 int TempFD;
Reid Spencere4ca7222006-08-23 20:34:57 +0000708 if ((TempFD = mkstemp(FNBuffer)) == -1)
709 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000710
711 // We don't need to hold the temp file descriptor... we will trust that no one
712 // will overwrite/delete the file before we can open it again.
713 close(TempFD);
714
715 // Save the name
716 path = FNBuffer;
717#elif defined(HAVE_MKTEMP)
718 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencere4ca7222006-08-23 20:34:57 +0000719 if (mktemp(FNBuffer) == 0)
720 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000721
722 // Save the name
723 path = FNBuffer;
724#else
725 // Okay, looks like we have to do it all by our lonesome.
726 static unsigned FCounter = 0;
727 unsigned offset = path.size() + 1;
728 while ( FCounter < 999999 && exists()) {
729 sprintf(FNBuffer+offset,"%06u",++FCounter);
730 path = FNBuffer;
731 }
732 if (FCounter > 999999)
Reid Spencere4ca7222006-08-23 20:34:57 +0000733 return MakeErrMsg(ErrMsg,
734 path + ": can't make unique filename: too many files");
Reid Spencerf66d9322004-12-15 01:50:13 +0000735#endif
Reid Spencere4ca7222006-08-23 20:34:57 +0000736 return false;
737}
Reid Spencerf66d9322004-12-15 01:50:13 +0000738
Reid Spencere4ca7222006-08-23 20:34:57 +0000739} // end llvm namespace
Reid Spencer814ba572004-08-25 06:20:07 +0000740