blob: db95e3c216c83ea7f13d7cdcb580631b4a001098 [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//
5// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific portion of the Path class.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
Reid Spencer8e665952004-08-29 05:24:01 +000016//=== is guaranteed to work on *all* UNIX variants.
Reid Spencerb89a2232004-08-25 06:20:07 +000017//===----------------------------------------------------------------------===//
18
Misha Brukman210b32b2004-12-20 00:16:38 +000019#include "llvm/Config/alloca.h"
Reid Spencerb89a2232004-08-25 06:20:07 +000020#include "Unix.h"
Reid Spenceraf2f2082004-12-27 06:17:15 +000021#if HAVE_SYS_STAT_H
Reid Spencerb89a2232004-08-25 06:20:07 +000022#include <sys/stat.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000023#endif
24#if HAVE_FCNTL_H
Reid Spencerb89a2232004-08-25 06:20:07 +000025#include <fcntl.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000026#endif
27#if HAVE_UTIME_H
Reid Spencereaf18152004-11-14 22:08:36 +000028#include <utime.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000029#endif
30#if HAVE_TIME_H
Reid Spencer69a16162004-12-24 06:29:42 +000031#include <time.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000032#endif
33#if HAVE_DIRENT_H
34# include <dirent.h>
35# define NAMLEN(dirent) strlen((dirent)->d_name)
36#else
37# define dirent direct
38# define NAMLEN(dirent) (dirent)->d_namlen
39# if HAVE_SYS_NDIR_H
40# include <sys/ndir.h>
41# endif
42# if HAVE_SYS_DIR_H
43# include <sys/dir.h>
44# endif
45# if HAVE_NDIR_H
46# include <ndir.h>
47# endif
48#endif
49
Reid Spencer932e2e32005-06-02 05:38:20 +000050// Put in a hack for Cygwin which falsely reports that the mkdtemp function
51// is available when it is not.
52#ifdef __CYGWIN__
53# undef HAVE_MKDTEMP
54#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000055
Reid Spencer3be872e2005-07-28 16:25:57 +000056namespace {
57inline bool lastIsSlash(const std::string& path) {
58 return !path.empty() && path[path.length() - 1] == '/';
59}
60
61}
62
Reid Spencer8e665952004-08-29 05:24:01 +000063namespace llvm {
64using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000065
Reid Spencer69a16162004-12-24 06:29:42 +000066bool
67Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000068 // Check some obvious things
Reid Spencer69a16162004-12-24 06:29:42 +000069 if (path.empty())
70 return false;
71 else if (path.length() >= MAXPATHLEN)
72 return false;
Reid Spencer6371ccb2005-07-08 06:53:26 +000073
74 // Check that the characters are ascii chars
75 size_t len = path.length();
76 unsigned i = 0;
77 while (i < len && isascii(path[i]))
78 ++i;
79 return i >= len;
Reid Spencer69a16162004-12-24 06:29:42 +000080}
81
Reid Spencer69cce812007-03-29 16:43:20 +000082bool
83Path::isAbsolute() const {
84 if (path.empty())
85 return false;
86 return path[0] == '/';
87}
Reid Spencer8e665952004-08-29 05:24:01 +000088Path
89Path::GetRootDirectory() {
90 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +000091 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +000092 return result;
93}
94
Reid Spencer69a16162004-12-24 06:29:42 +000095Path
Reid Spencer48744762006-08-22 19:01:30 +000096Path::GetTemporaryDirectory(std::string* ErrMsg ) {
Reid Spencer69a16162004-12-24 06:29:42 +000097#if defined(HAVE_MKDTEMP)
98 // The best way is with mkdtemp but that's not available on many systems,
99 // Linux and FreeBSD have it. Others probably won't.
100 char pathname[MAXPATHLEN];
101 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000102 if (0 == mkdtemp(pathname)) {
103 MakeErrMsg(ErrMsg,
104 std::string(pathname) + ": can't create temporary directory");
105 return Path();
106 }
Reid Spencer69a16162004-12-24 06:29:42 +0000107 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000108 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000109 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
110 return result;
111#elif defined(HAVE_MKSTEMP)
112 // If no mkdtemp is available, mkstemp can be used to create a temporary file
113 // which is then removed and created as a directory. We prefer this over
114 // mktemp because of mktemp's inherent security and threading risks. We still
115 // have a slight race condition from the time the temporary file is created to
116 // the time it is re-created as a directoy.
117 char pathname[MAXPATHLEN];
118 strcpy(pathname, "/tmp/llvm_XXXXXX");
119 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000120 if (-1 == (fd = mkstemp(pathname))) {
121 MakeErrMsg(ErrMsg,
122 std::string(pathname) + ": can't create temporary directory");
123 return Path();
124 }
Reid Spencer69a16162004-12-24 06:29:42 +0000125 ::close(fd);
126 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000127 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
128 MakeErrMsg(ErrMsg,
129 std::string(pathname) + ": can't create temporary directory");
130 return Path();
131 }
Reid Spencer69a16162004-12-24 06:29:42 +0000132 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000133 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000134 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
135 return result;
136#elif defined(HAVE_MKTEMP)
137 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
138 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
139 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
140 // the XXXXXX with the pid of the process and a letter. That leads to only
141 // twenty six temporary files that can be generated.
142 char pathname[MAXPATHLEN];
143 strcpy(pathname, "/tmp/llvm_XXXXXX");
144 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000145 if (TmpName == 0) {
146 MakeErrMsg(ErrMsg,
147 std::string(TmpName) + ": can't create unique directory name");
148 return Path();
149 }
150 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
151 MakeErrMsg(ErrMsg,
152 std::string(TmpName) + ": can't create temporary directory");
153 return Path();
154 }
Reid Spencer69a16162004-12-24 06:29:42 +0000155 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000156 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000157 assert(result.isValid() && "mktemp didn't create a valid pathname!");
158 return result;
159#else
160 // This is the worst case implementation. tempnam(3) leaks memory unless its
161 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
162 // issues. The mktemp(3) function doesn't have enough variability in the
163 // temporary name generated. So, we provide our own implementation that
164 // increments an integer from a random number seeded by the current time. This
165 // should be sufficiently unique that we don't have many collisions between
166 // processes. Generally LLVM processes don't run very long and don't use very
167 // many temporary files so this shouldn't be a big issue for LLVM.
168 static time_t num = ::time(0);
169 char pathname[MAXPATHLEN];
170 do {
171 num++;
172 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
173 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000174 if (-1 == ::mkdir(pathname, S_IRWXU)) {
175 MakeErrMsg(ErrMsg,
176 std::string(pathname) + ": can't create temporary directory");
177 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000178 }
Reid Spencer69a16162004-12-24 06:29:42 +0000179 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000180 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000181 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
182 return result;
183#endif
184}
185
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000186static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
187 const char* at = path;
188 const char* delim = strchr(at, ':');
189 Path tmpPath;
190 while( delim != 0 ) {
191 std::string tmp(at, size_t(delim-at));
Reid Spencerdd04df02005-07-07 23:21:43 +0000192 if (tmpPath.set(tmp))
Reid Spencerc7f08322005-07-07 18:21:42 +0000193 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000194 Paths.push_back(tmpPath);
195 at = delim + 1;
196 delim = strchr(at, ':');
Reid Spencer74e72612004-09-14 00:16:39 +0000197 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000198 if (*at != 0)
Reid Spencerdd04df02005-07-07 23:21:43 +0000199 if (tmpPath.set(std::string(at)))
Reid Spencerc7f08322005-07-07 18:21:42 +0000200 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000201 Paths.push_back(tmpPath);
202
Reid Spencer74e72612004-09-14 00:16:39 +0000203}
Misha Brukman210b32b2004-12-20 00:16:38 +0000204
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000205void
206Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
207#ifdef LTDL_SHLIBPATH_VAR
208 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
209 if (env_var != 0) {
210 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000211 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000212#endif
213 // FIXME: Should this look at LD_LIBRARY_PATH too?
214 Paths.push_back(sys::Path("/usr/local/lib/"));
215 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
216 Paths.push_back(sys::Path("/usr/lib/"));
217 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000218}
219
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000220void
221Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
222 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
223 if (env_var != 0) {
224 getPathList(env_var,Paths);
225 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000226#ifdef LLVM_LIBDIR
227 {
228 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000229 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000230 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000231 Paths.push_back(tmpPath);
232 }
233#endif
234 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000235}
236
237Path
238Path::GetLLVMDefaultConfigDir() {
239 return Path("/etc/llvm/");
240}
241
Reid Spencer8e665952004-08-29 05:24:01 +0000242Path
243Path::GetUserHomeDirectory() {
244 const char* home = getenv("HOME");
245 if (home) {
246 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000247 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000248 return result;
249 }
250 return GetRootDirectory();
251}
252
Reid Spencera229c5c2005-07-08 03:08:58 +0000253
Reid Spencer1b554b42004-09-11 04:55:08 +0000254std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000255Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000256 // Find the last slash
257 size_t slash = path.rfind('/');
258 if (slash == std::string::npos)
259 slash = 0;
260 else
261 slash++;
262
Jeff Cohen73f36672005-07-09 18:42:02 +0000263 size_t dot = path.rfind('.');
264 if (dot == std::string::npos || dot < slash)
265 return path.substr(slash);
266 else
267 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000268}
269
Reid Spencereaf18152004-11-14 22:08:36 +0000270bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000271 assert(len < 1024 && "Request for magic string too long");
272 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000273 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000274 if (fd < 0)
275 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000276 ssize_t bytes_read = ::read(fd, buf, len);
277 ::close(fd);
278 if (ssize_t(len) != bytes_read) {
279 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000280 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000281 }
282 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000283 return true;
284}
285
Reid Spencer1b554b42004-09-11 04:55:08 +0000286bool
Reid Spencer8e665952004-08-29 05:24:01 +0000287Path::exists() const {
288 return 0 == access(path.c_str(), F_OK );
289}
290
291bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000292Path::canRead() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000293 return 0 == access(path.c_str(), F_OK | R_OK );
294}
295
296bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000297Path::canWrite() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000298 return 0 == access(path.c_str(), F_OK | W_OK );
299}
300
301bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000302Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000303 if (0 != access(path.c_str(), R_OK | X_OK ))
304 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000305 struct stat buf;
306 if (0 != stat(path.c_str(), &buf))
307 return false;
308 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000309 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000310 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000311}
312
313std::string
314Path::getLast() const {
315 // Find the last slash
316 size_t pos = path.rfind('/');
317
318 // Handle the corner cases
319 if (pos == std::string::npos)
320 return path;
321
322 // If the last character is a slash
323 if (pos == path.length()-1) {
324 // Find the second to last slash
325 size_t pos2 = path.rfind('/', pos-1);
326 if (pos2 == std::string::npos)
327 return path.substr(0,pos);
328 else
329 return path.substr(pos2+1,pos-pos2-1);
330 }
331 // Return everything after the last slash
332 return path.substr(pos+1);
333}
334
Reid Spencer2ae9d112007-04-07 18:52:17 +0000335const FileStatus *
336PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
337 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000338 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000339 if (0 != stat(path.c_str(), &buf)) {
340 MakeErrMsg(ErrStr, path + ": can't get status of file");
341 return 0;
342 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000343 status.fileSize = buf.st_size;
344 status.modTime.fromEpochTime(buf.st_mtime);
345 status.mode = buf.st_mode;
346 status.user = buf.st_uid;
347 status.group = buf.st_gid;
348 status.uniqueID = uint64_t(buf.st_ino);
349 status.isDir = S_ISDIR(buf.st_mode);
350 status.isFile = S_ISREG(buf.st_mode);
351 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000352 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000353 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000354}
355
Chris Lattner252ad032006-07-28 22:03:44 +0000356static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000357 // Get the umask value from the operating system. We want to use it
358 // when changing the file's permissions. Since calling umask() sets
359 // the umask and returns its old value, we must call it a second
360 // time to reset it to the user's preference.
361 int mask = umask(0777); // The arg. to umask is arbitrary.
362 umask(mask); // Restore the umask.
363
364 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000365 struct stat buf;
366 if (0 != stat(File.toString().c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000367 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000368 // Change the file to have whichever permissions bits from 'bits'
369 // that the umask would not disable.
370 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
371 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000372 return true;
373}
374
Reid Spencere1647f42006-08-22 23:27:23 +0000375bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000376 if (!AddPermissionBits(*this, 0444))
377 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000378 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000379}
380
Reid Spencere1647f42006-08-22 23:27:23 +0000381bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000382 if (!AddPermissionBits(*this, 0222))
383 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000384 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000385}
386
Reid Spencere1647f42006-08-22 23:27:23 +0000387bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000388 if (!AddPermissionBits(*this, 0111))
389 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000390 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000391}
392
Reid Spencereaf18152004-11-14 22:08:36 +0000393bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000394Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000395 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000396 if (direntries == 0)
397 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000398
Reid Spencer3be872e2005-07-28 16:25:57 +0000399 std::string dirPath = path;
400 if (!lastIsSlash(dirPath))
401 dirPath += '/';
402
Reid Spencereaf18152004-11-14 22:08:36 +0000403 result.clear();
404 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000405 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000406 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000407 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000408 struct stat st;
409 if (0 != lstat(aPath.path.c_str(), &st)) {
410 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000411 continue; // dangling symlink -- ignore
Reid Spencer5a060772006-08-23 07:30:48 +0000412 return MakeErrMsg(ErrMsg,
413 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000414 }
Reid Spencerb608a812004-11-16 06:15:19 +0000415 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000416 }
Reid Spencereaf18152004-11-14 22:08:36 +0000417 }
418
419 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000420 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000421}
422
Reid Spencer8e665952004-08-29 05:24:01 +0000423bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000424Path::set(const std::string& a_path) {
425 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000426 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000427 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000428 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000429 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000430 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000431 return false;
432 }
433 return true;
434}
435
436bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000437Path::appendComponent(const std::string& name) {
438 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000439 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000440 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000441 if (!lastIsSlash(path))
442 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000443 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000444 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000445 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000446 return false;
447 }
448 return true;
449}
450
451bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000452Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000453 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000454 if (slashpos == 0 || slashpos == std::string::npos) {
455 path.erase();
456 return true;
457 }
Reid Spencer8e665952004-08-29 05:24:01 +0000458 if (slashpos == path.size() - 1)
459 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000460 if (slashpos == std::string::npos) {
461 path.erase();
462 return true;
463 }
Reid Spencer8e665952004-08-29 05:24:01 +0000464 path.erase(slashpos);
465 return true;
466}
467
468bool
Reid Spencer07adb282004-11-05 22:15:36 +0000469Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000470 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000471 path.append(".");
472 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000473 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000474 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000475 return false;
476 }
477 return true;
478}
479
Reid Spencerdd04df02005-07-07 23:21:43 +0000480bool
481Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000482 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000483 size_t dotpos = path.rfind('.',path.size());
484 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000485 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000486 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000487 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000488 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000489 }
Reid Spencer8e665952004-08-29 05:24:01 +0000490 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000491 if (!isValid())
492 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000493 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000494}
495
Reid Spencer8e665952004-08-29 05:24:01 +0000496bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000497Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000498 // Get a writeable copy of the path name
499 char pathname[MAXPATHLEN];
500 path.copy(pathname,MAXPATHLEN);
501
502 // Null-terminate the last component
503 int lastchar = path.length() - 1 ;
504 if (pathname[lastchar] == '/')
505 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000506 else
507 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000508
509 // If we're supposed to create intermediate directories
510 if ( create_parents ) {
511 // Find the end of the initial name component
512 char * next = strchr(pathname,'/');
513 if ( pathname[0] == '/')
514 next = strchr(&pathname[1],'/');
515
516 // Loop through the directory components until we're done
517 while ( next != 0 ) {
518 *next = 0;
519 if (0 != access(pathname, F_OK | R_OK | W_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000520 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000521 return MakeErrMsg(ErrMsg,
522 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000523 }
Reid Spencer8e665952004-08-29 05:24:01 +0000524 char* save = next;
Reid Spencereaf18152004-11-14 22:08:36 +0000525 next = strchr(next+1,'/');
Reid Spencer8e665952004-08-29 05:24:01 +0000526 *save = '/';
527 }
Reid Spencer8e665952004-08-29 05:24:01 +0000528 }
Reid Spencereaf18152004-11-14 22:08:36 +0000529
530 if (0 != access(pathname, F_OK | R_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000531 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000532 return MakeErrMsg(ErrMsg,
533 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000534 }
535 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000536}
537
538bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000539Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000540 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000541 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000542 if (fd < 0)
543 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000544 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000545 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000546}
547
Reid Spencer8e665952004-08-29 05:24:01 +0000548bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000549Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000550 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000551 if (makeUnique( reuse_current, ErrMsg ))
552 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000553
554 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000555 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Reid Spencer5a060772006-08-23 07:30:48 +0000556 if (fd < 0)
557 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000558 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000559 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000560}
561
562bool
Chris Lattner0c332312006-07-28 22:29:50 +0000563Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Reid Spencer2ae9d112007-04-07 18:52:17 +0000564 // Get the status so we can determin if its a file or directory
565 struct stat buf;
566 if (0 != stat(path.c_str(), &buf)) {
567 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000568 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000569 }
570
571 // Note: this check catches strange situations. In all cases, LLVM should
572 // only be involved in the creation and deletion of regular files. This
573 // check ensures that what we're trying to erase is a regular file. It
574 // effectively prevents LLVM from erasing things like /dev/null, any block
575 // special file, or other things that aren't "regular" files.
576 if (S_ISREG(buf.st_mode)) {
577 if (unlink(path.c_str()) != 0)
578 return MakeErrMsg(ErrStr, path + ": can't destroy file");
579 return false;
580 }
581
582 if (!S_ISDIR(buf.st_mode)) {
583 if (ErrStr) *ErrStr = "not a file or directory";
584 return true;
585 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000586
Chris Lattner0c332312006-07-28 22:29:50 +0000587 if (remove_contents) {
588 // Recursively descend the directory to remove its contents.
589 std::string cmd = "/bin/rm -rf " + path;
590 system(cmd.c_str());
591 return false;
592 }
593
594 // Otherwise, try to just remove the one directory.
595 char pathname[MAXPATHLEN];
596 path.copy(pathname, MAXPATHLEN);
597 int lastchar = path.length() - 1 ;
598 if (pathname[lastchar] == '/')
599 pathname[lastchar] = 0;
600 else
601 pathname[lastchar+1] = 0;
602
603 if (rmdir(pathname) != 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000604 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000605 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000606 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000607}
608
609bool
Reid Spencer5a060772006-08-23 07:30:48 +0000610Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000611 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer5a060772006-08-23 07:30:48 +0000612 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Reid Spencer2aafadc2005-04-21 02:50:10 +0000613 newName.toString() + "' ");
Reid Spencer5a060772006-08-23 07:30:48 +0000614 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000615}
616
Reid Spencer2ae9d112007-04-07 18:52:17 +0000617bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000618Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000619 struct utimbuf utb;
620 utb.actime = si.modTime.toPosixTime();
621 utb.modtime = utb.actime;
622 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000623 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000624 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000625 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000626 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000627}
628
Reid Spencer51c5a282006-08-23 20:34:57 +0000629bool
630sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000631 int inFile = -1;
632 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000633 inFile = ::open(Src.c_str(), O_RDONLY);
634 if (inFile == -1)
635 return MakeErrMsg(ErrMsg, Src.toString() +
636 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000637
Reid Spencer51c5a282006-08-23 20:34:57 +0000638 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
639 if (outFile == -1) {
640 ::close(inFile);
641 return MakeErrMsg(ErrMsg, Dest.toString() +
642 ": can't create destination file for copy");
643 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000644
Reid Spencer51c5a282006-08-23 20:34:57 +0000645 char Buffer[16*1024];
646 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
647 if (Amt == -1) {
648 if (errno != EINTR && errno != EAGAIN) {
649 ::close(inFile);
650 ::close(outFile);
651 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
652 }
653 } else {
654 char *BufPtr = Buffer;
655 while (Amt) {
656 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
657 if (AmtWritten == -1) {
658 if (errno != EINTR && errno != EAGAIN) {
659 ::close(inFile);
660 ::close(outFile);
661 return MakeErrMsg(ErrMsg, Dest.toString() +
662 ": can't write destination file: ");
Reid Spencerc29befb2004-12-15 01:50:13 +0000663 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000664 } else {
665 Amt -= AmtWritten;
666 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000667 }
668 }
669 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000670 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000671 ::close(inFile);
672 ::close(outFile);
673 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000674}
675
Reid Spencer51c5a282006-08-23 20:34:57 +0000676bool
677Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000678 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000679 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000680
681 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
682 // mktemp or our own implementation.
683 char *FNBuffer = (char*) alloca(path.size()+8);
684 path.copy(FNBuffer,path.size());
685 strcpy(FNBuffer+path.size(), "-XXXXXX");
686
687#if defined(HAVE_MKSTEMP)
688 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000689 if ((TempFD = mkstemp(FNBuffer)) == -1)
690 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000691
692 // We don't need to hold the temp file descriptor... we will trust that no one
693 // will overwrite/delete the file before we can open it again.
694 close(TempFD);
695
696 // Save the name
697 path = FNBuffer;
698#elif defined(HAVE_MKTEMP)
699 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000700 if (mktemp(FNBuffer) == 0)
701 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000702
703 // Save the name
704 path = FNBuffer;
705#else
706 // Okay, looks like we have to do it all by our lonesome.
707 static unsigned FCounter = 0;
708 unsigned offset = path.size() + 1;
709 while ( FCounter < 999999 && exists()) {
710 sprintf(FNBuffer+offset,"%06u",++FCounter);
711 path = FNBuffer;
712 }
713 if (FCounter > 999999)
Reid Spencer51c5a282006-08-23 20:34:57 +0000714 return MakeErrMsg(ErrMsg,
715 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000716#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000717 return false;
718}
Reid Spencerc29befb2004-12-15 01:50:13 +0000719
Reid Spencer51c5a282006-08-23 20:34:57 +0000720} // end llvm namespace
Reid Spencerb89a2232004-08-25 06:20:07 +0000721