blob: 9802b7e00da753cb9e01d4b9b0461412f26a3640 [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 Spencer8e665952004-08-29 05:24:01 +000082Path
83Path::GetRootDirectory() {
84 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +000085 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +000086 return result;
87}
88
Reid Spencer69a16162004-12-24 06:29:42 +000089Path
Reid Spencer48744762006-08-22 19:01:30 +000090Path::GetTemporaryDirectory(std::string* ErrMsg ) {
Reid Spencer69a16162004-12-24 06:29:42 +000091#if defined(HAVE_MKDTEMP)
92 // The best way is with mkdtemp but that's not available on many systems,
93 // Linux and FreeBSD have it. Others probably won't.
94 char pathname[MAXPATHLEN];
95 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +000096 if (0 == mkdtemp(pathname)) {
97 MakeErrMsg(ErrMsg,
98 std::string(pathname) + ": can't create temporary directory");
99 return Path();
100 }
Reid Spencer69a16162004-12-24 06:29:42 +0000101 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000102 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000103 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
104 return result;
105#elif defined(HAVE_MKSTEMP)
106 // If no mkdtemp is available, mkstemp can be used to create a temporary file
107 // which is then removed and created as a directory. We prefer this over
108 // mktemp because of mktemp's inherent security and threading risks. We still
109 // have a slight race condition from the time the temporary file is created to
110 // the time it is re-created as a directoy.
111 char pathname[MAXPATHLEN];
112 strcpy(pathname, "/tmp/llvm_XXXXXX");
113 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000114 if (-1 == (fd = mkstemp(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 ::close(fd);
120 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000121 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
122 MakeErrMsg(ErrMsg,
123 std::string(pathname) + ": can't create temporary directory");
124 return Path();
125 }
Reid Spencer69a16162004-12-24 06:29:42 +0000126 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000127 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000128 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
129 return result;
130#elif defined(HAVE_MKTEMP)
131 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
132 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
133 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
134 // the XXXXXX with the pid of the process and a letter. That leads to only
135 // twenty six temporary files that can be generated.
136 char pathname[MAXPATHLEN];
137 strcpy(pathname, "/tmp/llvm_XXXXXX");
138 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000139 if (TmpName == 0) {
140 MakeErrMsg(ErrMsg,
141 std::string(TmpName) + ": can't create unique directory name");
142 return Path();
143 }
144 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
145 MakeErrMsg(ErrMsg,
146 std::string(TmpName) + ": can't create temporary directory");
147 return Path();
148 }
Reid Spencer69a16162004-12-24 06:29:42 +0000149 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000150 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000151 assert(result.isValid() && "mktemp didn't create a valid pathname!");
152 return result;
153#else
154 // This is the worst case implementation. tempnam(3) leaks memory unless its
155 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
156 // issues. The mktemp(3) function doesn't have enough variability in the
157 // temporary name generated. So, we provide our own implementation that
158 // increments an integer from a random number seeded by the current time. This
159 // should be sufficiently unique that we don't have many collisions between
160 // processes. Generally LLVM processes don't run very long and don't use very
161 // many temporary files so this shouldn't be a big issue for LLVM.
162 static time_t num = ::time(0);
163 char pathname[MAXPATHLEN];
164 do {
165 num++;
166 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
167 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000168 if (-1 == ::mkdir(pathname, S_IRWXU)) {
169 MakeErrMsg(ErrMsg,
170 std::string(pathname) + ": can't create temporary directory");
171 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000172 }
Reid Spencer69a16162004-12-24 06:29:42 +0000173 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000174 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000175 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
176 return result;
177#endif
178}
179
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000180static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
181 const char* at = path;
182 const char* delim = strchr(at, ':');
183 Path tmpPath;
184 while( delim != 0 ) {
185 std::string tmp(at, size_t(delim-at));
Reid Spencerdd04df02005-07-07 23:21:43 +0000186 if (tmpPath.set(tmp))
Reid Spencerc7f08322005-07-07 18:21:42 +0000187 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000188 Paths.push_back(tmpPath);
189 at = delim + 1;
190 delim = strchr(at, ':');
Reid Spencer74e72612004-09-14 00:16:39 +0000191 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000192 if (*at != 0)
Reid Spencerdd04df02005-07-07 23:21:43 +0000193 if (tmpPath.set(std::string(at)))
Reid Spencerc7f08322005-07-07 18:21:42 +0000194 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000195 Paths.push_back(tmpPath);
196
Reid Spencer74e72612004-09-14 00:16:39 +0000197}
Misha Brukman210b32b2004-12-20 00:16:38 +0000198
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000199void
200Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
201#ifdef LTDL_SHLIBPATH_VAR
202 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
203 if (env_var != 0) {
204 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000205 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000206#endif
207 // FIXME: Should this look at LD_LIBRARY_PATH too?
208 Paths.push_back(sys::Path("/usr/local/lib/"));
209 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
210 Paths.push_back(sys::Path("/usr/lib/"));
211 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000212}
213
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000214void
215Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
216 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
217 if (env_var != 0) {
218 getPathList(env_var,Paths);
219 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000220#ifdef LLVM_LIBDIR
221 {
222 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000223 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000224 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000225 Paths.push_back(tmpPath);
226 }
227#endif
228 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000229}
230
231Path
232Path::GetLLVMDefaultConfigDir() {
233 return Path("/etc/llvm/");
234}
235
Reid Spencer8e665952004-08-29 05:24:01 +0000236Path
237Path::GetUserHomeDirectory() {
238 const char* home = getenv("HOME");
239 if (home) {
240 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000241 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000242 return result;
243 }
244 return GetRootDirectory();
245}
246
Reid Spencera229c5c2005-07-08 03:08:58 +0000247
Reid Spencer1b554b42004-09-11 04:55:08 +0000248std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000249Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000250 // Find the last slash
251 size_t slash = path.rfind('/');
252 if (slash == std::string::npos)
253 slash = 0;
254 else
255 slash++;
256
Jeff Cohen73f36672005-07-09 18:42:02 +0000257 size_t dot = path.rfind('.');
258 if (dot == std::string::npos || dot < slash)
259 return path.substr(slash);
260 else
261 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000262}
263
Reid Spencer07adb282004-11-05 22:15:36 +0000264bool Path::hasMagicNumber(const std::string &Magic) const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000265 size_t len = Magic.size();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000266 assert(len < 1024 && "Request for magic string too long");
267 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000268 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000269 if (fd < 0)
270 return false;
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000271 size_t read_len = ::read(fd, buf, len);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000272 close(fd);
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000273 if (len != read_len)
274 return false;
Reid Spencer1b554b42004-09-11 04:55:08 +0000275 buf[len] = '\0';
276 return Magic == buf;
277}
278
Reid Spencereaf18152004-11-14 22:08:36 +0000279bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000280 assert(len < 1024 && "Request for magic string too long");
281 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000282 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000283 if (fd < 0)
284 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000285 ssize_t bytes_read = ::read(fd, buf, len);
286 ::close(fd);
287 if (ssize_t(len) != bytes_read) {
288 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000289 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000290 }
291 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000292 return true;
293}
294
Reid Spencer1b554b42004-09-11 04:55:08 +0000295bool
Reid Spencer07adb282004-11-05 22:15:36 +0000296Path::isBytecodeFile() const {
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000297 char buffer[4];
Reid Spencer9195f372004-11-09 20:26:31 +0000298 buffer[0] = 0;
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000299 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencer1fce0912004-12-11 00:14:15 +0000300 if (fd < 0)
301 return false;
302 ssize_t bytes_read = ::read(fd, buffer, 4);
303 ::close(fd);
304 if (4 != bytes_read)
305 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000306
307 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000308 (buffer[3] == 'c' || buffer[3] == 'm'));
Reid Spencer1b554b42004-09-11 04:55:08 +0000309}
310
311bool
Reid Spencer8e665952004-08-29 05:24:01 +0000312Path::exists() const {
313 return 0 == access(path.c_str(), F_OK );
314}
315
316bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000317Path::canRead() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000318 return 0 == access(path.c_str(), F_OK | R_OK );
319}
320
321bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000322Path::canWrite() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000323 return 0 == access(path.c_str(), F_OK | W_OK );
324}
325
326bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000327Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000328 if (0 != access(path.c_str(), R_OK | X_OK ))
329 return false;
Misha Brukman8177bf82005-04-20 15:33:22 +0000330 struct stat st;
331 int r = stat(path.c_str(), &st);
332 if (r != 0 || !S_ISREG(st.st_mode))
333 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000334 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000335}
336
337std::string
338Path::getLast() const {
339 // Find the last slash
340 size_t pos = path.rfind('/');
341
342 // Handle the corner cases
343 if (pos == std::string::npos)
344 return path;
345
346 // If the last character is a slash
347 if (pos == path.length()-1) {
348 // Find the second to last slash
349 size_t pos2 = path.rfind('/', pos-1);
350 if (pos2 == std::string::npos)
351 return path.substr(0,pos);
352 else
353 return path.substr(pos2+1,pos-pos2-1);
354 }
355 // Return everything after the last slash
356 return path.substr(pos+1);
357}
358
Chris Lattner252ad032006-07-28 22:03:44 +0000359bool
360Path::getFileStatus(FileStatus &info, std::string *ErrStr) const {
Reid Spencer9195f372004-11-09 20:26:31 +0000361 struct stat buf;
Chris Lattner252ad032006-07-28 22:03:44 +0000362 if (0 != stat(path.c_str(), &buf))
Reid Spencer51c5a282006-08-23 20:34:57 +0000363 return MakeErrMsg(ErrStr,
364 path + ": can't get status of file '" + path + "'");
Reid Spencer9195f372004-11-09 20:26:31 +0000365 info.fileSize = buf.st_size;
Reid Spencereaf18152004-11-14 22:08:36 +0000366 info.modTime.fromEpochTime(buf.st_mtime);
Reid Spencer9195f372004-11-09 20:26:31 +0000367 info.mode = buf.st_mode;
368 info.user = buf.st_uid;
369 info.group = buf.st_gid;
Chris Lattner252ad032006-07-28 22:03:44 +0000370 info.isDir = S_ISDIR(buf.st_mode);
371 info.isFile = S_ISREG(buf.st_mode);
372 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000373}
374
Chris Lattner252ad032006-07-28 22:03:44 +0000375static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-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.
Chris Lattner252ad032006-07-28 22:03:44 +0000384 FileStatus Stat;
385 if (File.getFileStatus(Stat)) return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000386
387 // Change the file to have whichever permissions bits from 'bits'
388 // that the umask would not disable.
Chris Lattner252ad032006-07-28 22:03:44 +0000389 if ((chmod(File.c_str(), (Stat.getMode() | (bits & ~mask)))) == -1)
Reid Spencer77cc91d2004-12-13 19:59:50 +0000390 return false;
391
392 return true;
393}
394
Reid Spencere1647f42006-08-22 23:27:23 +0000395bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000396 if (!AddPermissionBits(*this, 0444))
397 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000398 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000399}
400
Reid Spencere1647f42006-08-22 23:27:23 +0000401bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000402 if (!AddPermissionBits(*this, 0222))
403 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000404 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000405}
406
Reid Spencere1647f42006-08-22 23:27:23 +0000407bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000408 if (!AddPermissionBits(*this, 0111))
409 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000410 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000411}
412
Reid Spencereaf18152004-11-14 22:08:36 +0000413bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000414Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000415 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000416 if (direntries == 0)
417 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000418
Reid Spencer3be872e2005-07-28 16:25:57 +0000419 std::string dirPath = path;
420 if (!lastIsSlash(dirPath))
421 dirPath += '/';
422
Reid Spencereaf18152004-11-14 22:08:36 +0000423 result.clear();
424 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000425 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000426 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000427 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000428 struct stat st;
429 if (0 != lstat(aPath.path.c_str(), &st)) {
430 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000431 continue; // dangling symlink -- ignore
Reid Spencer5a060772006-08-23 07:30:48 +0000432 return MakeErrMsg(ErrMsg,
433 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000434 }
Reid Spencerb608a812004-11-16 06:15:19 +0000435 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000436 }
Reid Spencereaf18152004-11-14 22:08:36 +0000437 }
438
439 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000440 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000441}
442
Reid Spencer8e665952004-08-29 05:24:01 +0000443bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000444Path::set(const std::string& a_path) {
445 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000446 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000447 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000448 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000449 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000450 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000451 return false;
452 }
453 return true;
454}
455
456bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000457Path::appendComponent(const std::string& name) {
458 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000459 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000460 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000461 if (!lastIsSlash(path))
462 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000463 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000464 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000465 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000466 return false;
467 }
468 return true;
469}
470
471bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000472Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000473 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000474 if (slashpos == 0 || slashpos == std::string::npos) {
475 path.erase();
476 return true;
477 }
Reid Spencer8e665952004-08-29 05:24:01 +0000478 if (slashpos == path.size() - 1)
479 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000480 if (slashpos == std::string::npos) {
481 path.erase();
482 return true;
483 }
Reid Spencer8e665952004-08-29 05:24:01 +0000484 path.erase(slashpos);
485 return true;
486}
487
488bool
Reid Spencer07adb282004-11-05 22:15:36 +0000489Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000490 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000491 path.append(".");
492 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000493 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000494 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000495 return false;
496 }
497 return true;
498}
499
Reid Spencerdd04df02005-07-07 23:21:43 +0000500bool
501Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000502 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000503 size_t dotpos = path.rfind('.',path.size());
504 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000505 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000506 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000507 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000508 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000509 }
Reid Spencer8e665952004-08-29 05:24:01 +0000510 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000511 if (!isValid())
512 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000513 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000514}
515
Reid Spencer8e665952004-08-29 05:24:01 +0000516bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000517Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000518 // Get a writeable copy of the path name
519 char pathname[MAXPATHLEN];
520 path.copy(pathname,MAXPATHLEN);
521
522 // Null-terminate the last component
523 int lastchar = path.length() - 1 ;
524 if (pathname[lastchar] == '/')
525 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000526 else
527 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000528
529 // If we're supposed to create intermediate directories
530 if ( create_parents ) {
531 // Find the end of the initial name component
532 char * next = strchr(pathname,'/');
533 if ( pathname[0] == '/')
534 next = strchr(&pathname[1],'/');
535
536 // Loop through the directory components until we're done
537 while ( next != 0 ) {
538 *next = 0;
539 if (0 != access(pathname, F_OK | R_OK | W_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000540 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000541 return MakeErrMsg(ErrMsg,
542 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000543 }
Reid Spencer8e665952004-08-29 05:24:01 +0000544 char* save = next;
Reid Spencereaf18152004-11-14 22:08:36 +0000545 next = strchr(next+1,'/');
Reid Spencer8e665952004-08-29 05:24:01 +0000546 *save = '/';
547 }
Reid Spencer8e665952004-08-29 05:24:01 +0000548 }
Reid Spencereaf18152004-11-14 22:08:36 +0000549
550 if (0 != access(pathname, F_OK | R_OK))
Reid Spencere5c9cb52006-08-23 00:39:35 +0000551 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
Reid Spencer5a060772006-08-23 07:30:48 +0000552 return MakeErrMsg(ErrMsg,
553 std::string(pathname) + ": can't create directory");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000554 }
555 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000556}
557
558bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000559Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000560 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000561 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000562 if (fd < 0)
563 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000564 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000565 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000566}
567
Reid Spencer8e665952004-08-29 05:24:01 +0000568bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000569Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000570 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000571 if (makeUnique( reuse_current, ErrMsg ))
572 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000573
574 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000575 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Reid Spencer5a060772006-08-23 07:30:48 +0000576 if (fd < 0)
577 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000578 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000579 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000580}
581
582bool
Chris Lattner0c332312006-07-28 22:29:50 +0000583Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000584 FileStatus Status;
585 if (getFileStatus(Status, ErrStr))
586 return true;
587
Reid Spencerbffdc362006-08-07 05:20:05 +0000588 // Note: this check catches strange situations. In all cases, LLVM should only
589 // be involved in the creation and deletion of regular files. This check
590 // ensures that what we're trying to erase is a regular file. It effectively
591 // prevents LLVM from erasing things like /dev/null, any block special file,
592 // or other things that aren't "regular" files.
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000593 if (Status.isFile) {
Chris Lattner0c332312006-07-28 22:29:50 +0000594 if (unlink(path.c_str()) != 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000595 return MakeErrMsg(ErrStr, path + ": can't destroy file");
Reid Spencerdd04df02005-07-07 23:21:43 +0000596 return false;
Chris Lattner0c332312006-07-28 22:29:50 +0000597 }
598
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000599 if (!Status.isDir) {
Chris Lattner0c332312006-07-28 22:29:50 +0000600 if (ErrStr) *ErrStr = "not a file or directory";
601 return true;
602 }
603 if (remove_contents) {
604 // Recursively descend the directory to remove its contents.
605 std::string cmd = "/bin/rm -rf " + path;
606 system(cmd.c_str());
607 return false;
608 }
609
610 // Otherwise, try to just remove the one directory.
611 char pathname[MAXPATHLEN];
612 path.copy(pathname, MAXPATHLEN);
613 int lastchar = path.length() - 1 ;
614 if (pathname[lastchar] == '/')
615 pathname[lastchar] = 0;
616 else
617 pathname[lastchar+1] = 0;
618
619 if (rmdir(pathname) != 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000620 return MakeErrMsg(ErrStr,
621 std::string(pathname) + ": can't destroy directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000622 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000623}
624
625bool
Reid Spencer5a060772006-08-23 07:30:48 +0000626Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000627 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer5a060772006-08-23 07:30:48 +0000628 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Reid Spencer2aafadc2005-04-21 02:50:10 +0000629 newName.toString() + "' ");
Reid Spencer5a060772006-08-23 07:30:48 +0000630 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000631}
632
633bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000634Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000635 struct utimbuf utb;
636 utb.actime = si.modTime.toPosixTime();
637 utb.modtime = utb.actime;
638 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000639 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000640 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000641 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000642 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000643}
644
Reid Spencer51c5a282006-08-23 20:34:57 +0000645bool
646sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000647 int inFile = -1;
648 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000649 inFile = ::open(Src.c_str(), O_RDONLY);
650 if (inFile == -1)
651 return MakeErrMsg(ErrMsg, Src.toString() +
652 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000653
Reid Spencer51c5a282006-08-23 20:34:57 +0000654 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
655 if (outFile == -1) {
656 ::close(inFile);
657 return MakeErrMsg(ErrMsg, Dest.toString() +
658 ": can't create destination file for copy");
659 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000660
Reid Spencer51c5a282006-08-23 20:34:57 +0000661 char Buffer[16*1024];
662 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
663 if (Amt == -1) {
664 if (errno != EINTR && errno != EAGAIN) {
665 ::close(inFile);
666 ::close(outFile);
667 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
668 }
669 } else {
670 char *BufPtr = Buffer;
671 while (Amt) {
672 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
673 if (AmtWritten == -1) {
674 if (errno != EINTR && errno != EAGAIN) {
675 ::close(inFile);
676 ::close(outFile);
677 return MakeErrMsg(ErrMsg, Dest.toString() +
678 ": can't write destination file: ");
Reid Spencerc29befb2004-12-15 01:50:13 +0000679 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000680 } else {
681 Amt -= AmtWritten;
682 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000683 }
684 }
685 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000686 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000687 ::close(inFile);
688 ::close(outFile);
689 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000690}
691
Reid Spencer51c5a282006-08-23 20:34:57 +0000692bool
693Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000694 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000695 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000696
697 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
698 // mktemp or our own implementation.
699 char *FNBuffer = (char*) alloca(path.size()+8);
700 path.copy(FNBuffer,path.size());
701 strcpy(FNBuffer+path.size(), "-XXXXXX");
702
703#if defined(HAVE_MKSTEMP)
704 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000705 if ((TempFD = mkstemp(FNBuffer)) == -1)
706 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000707
708 // We don't need to hold the temp file descriptor... we will trust that no one
709 // will overwrite/delete the file before we can open it again.
710 close(TempFD);
711
712 // Save the name
713 path = FNBuffer;
714#elif defined(HAVE_MKTEMP)
715 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000716 if (mktemp(FNBuffer) == 0)
717 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000718
719 // Save the name
720 path = FNBuffer;
721#else
722 // Okay, looks like we have to do it all by our lonesome.
723 static unsigned FCounter = 0;
724 unsigned offset = path.size() + 1;
725 while ( FCounter < 999999 && exists()) {
726 sprintf(FNBuffer+offset,"%06u",++FCounter);
727 path = FNBuffer;
728 }
729 if (FCounter > 999999)
Reid Spencer51c5a282006-08-23 20:34:57 +0000730 return MakeErrMsg(ErrMsg,
731 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000732#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000733 return false;
734}
Reid Spencerc29befb2004-12-15 01:50:13 +0000735
Reid Spencer51c5a282006-08-23 20:34:57 +0000736} // end llvm namespace
Reid Spencerb89a2232004-08-25 06:20:07 +0000737