blob: a0def8d5125ad7269d5fc2891a0678e2e3ca18e5 [file] [log] [blame]
Reid Spencerb89a2232004-08-25 06:20:07 +00001//===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencerb89a2232004-08-25 06:20:07 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific portion of the Path class.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
Reid Spencer8e665952004-08-29 05:24:01 +000016//=== is guaranteed to work on *all* UNIX variants.
Reid Spencerb89a2232004-08-25 06:20:07 +000017//===----------------------------------------------------------------------===//
18
Misha Brukman210b32b2004-12-20 00:16:38 +000019#include "llvm/Config/alloca.h"
Reid Spencerb89a2232004-08-25 06:20:07 +000020#include "Unix.h"
Reid Spenceraf2f2082004-12-27 06:17:15 +000021#if HAVE_SYS_STAT_H
Reid Spencerb89a2232004-08-25 06:20:07 +000022#include <sys/stat.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000023#endif
24#if HAVE_FCNTL_H
Reid Spencerb89a2232004-08-25 06:20:07 +000025#include <fcntl.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000026#endif
Chris Lattner14c762d2008-04-01 06:25:23 +000027#ifdef HAVE_SYS_MMAN_H
28#include <sys/mman.h>
29#endif
30#ifdef HAVE_SYS_STAT_H
31#include <sys/stat.h>
32#endif
Reid Spenceraf2f2082004-12-27 06:17:15 +000033#if HAVE_UTIME_H
Reid Spencereaf18152004-11-14 22:08:36 +000034#include <utime.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000035#endif
36#if HAVE_TIME_H
Reid Spencer69a16162004-12-24 06:29:42 +000037#include <time.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000038#endif
39#if HAVE_DIRENT_H
40# include <dirent.h>
41# define NAMLEN(dirent) strlen((dirent)->d_name)
42#else
43# define dirent direct
44# define NAMLEN(dirent) (dirent)->d_namlen
45# if HAVE_SYS_NDIR_H
46# include <sys/ndir.h>
47# endif
48# if HAVE_SYS_DIR_H
49# include <sys/dir.h>
50# endif
51# if HAVE_NDIR_H
52# include <ndir.h>
53# endif
54#endif
55
Chris Lattner1a091442008-03-03 02:55:43 +000056#if HAVE_DLFCN_H
57#include <dlfcn.h>
58#endif
59
Reid Spencer932e2e32005-06-02 05:38:20 +000060// Put in a hack for Cygwin which falsely reports that the mkdtemp function
61// is available when it is not.
62#ifdef __CYGWIN__
63# undef HAVE_MKDTEMP
64#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000065
Reid Spencer3be872e2005-07-28 16:25:57 +000066namespace {
67inline bool lastIsSlash(const std::string& path) {
68 return !path.empty() && path[path.length() - 1] == '/';
69}
70
71}
72
Reid Spencer8e665952004-08-29 05:24:01 +000073namespace llvm {
74using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000075
Chris Lattnere1b332a2008-02-27 06:17:10 +000076extern const char sys::PathSeparator = ':';
77
Nick Lewyckyfff116f2008-05-11 17:37:40 +000078Path::Path(const std::string& p)
79 : path(p) {}
80
81Path::Path(const char *StrStart, unsigned StrLen)
82 : path(StrStart, StrLen) {}
83
Reid Spencer69a16162004-12-24 06:29:42 +000084bool
85Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000086 // Check some obvious things
Reid Spencer69a16162004-12-24 06:29:42 +000087 if (path.empty())
88 return false;
89 else if (path.length() >= MAXPATHLEN)
90 return false;
Reid Spencer6371ccb2005-07-08 06:53:26 +000091
92 // Check that the characters are ascii chars
93 size_t len = path.length();
94 unsigned i = 0;
95 while (i < len && isascii(path[i]))
96 ++i;
97 return i >= len;
Reid Spencer69a16162004-12-24 06:29:42 +000098}
99
Reid Spencer69cce812007-03-29 16:43:20 +0000100bool
101Path::isAbsolute() const {
102 if (path.empty())
103 return false;
104 return path[0] == '/';
105}
Reid Spencer8e665952004-08-29 05:24:01 +0000106Path
107Path::GetRootDirectory() {
108 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000109 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000110 return result;
111}
112
Reid Spencer69a16162004-12-24 06:29:42 +0000113Path
Reid Spencer48744762006-08-22 19:01:30 +0000114Path::GetTemporaryDirectory(std::string* ErrMsg ) {
Reid Spencer69a16162004-12-24 06:29:42 +0000115#if defined(HAVE_MKDTEMP)
116 // The best way is with mkdtemp but that's not available on many systems,
117 // Linux and FreeBSD have it. Others probably won't.
118 char pathname[MAXPATHLEN];
119 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000120 if (0 == mkdtemp(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 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000126 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000127 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
128 return result;
129#elif defined(HAVE_MKSTEMP)
130 // If no mkdtemp is available, mkstemp can be used to create a temporary file
131 // which is then removed and created as a directory. We prefer this over
132 // mktemp because of mktemp's inherent security and threading risks. We still
133 // have a slight race condition from the time the temporary file is created to
134 // the time it is re-created as a directoy.
135 char pathname[MAXPATHLEN];
136 strcpy(pathname, "/tmp/llvm_XXXXXX");
137 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000138 if (-1 == (fd = mkstemp(pathname))) {
139 MakeErrMsg(ErrMsg,
140 std::string(pathname) + ": can't create temporary directory");
141 return Path();
142 }
Reid Spencer69a16162004-12-24 06:29:42 +0000143 ::close(fd);
144 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000145 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
146 MakeErrMsg(ErrMsg,
147 std::string(pathname) + ": can't create temporary directory");
148 return Path();
149 }
Reid Spencer69a16162004-12-24 06:29:42 +0000150 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000151 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000152 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
153 return result;
154#elif defined(HAVE_MKTEMP)
155 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
156 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
157 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
158 // the XXXXXX with the pid of the process and a letter. That leads to only
159 // twenty six temporary files that can be generated.
160 char pathname[MAXPATHLEN];
161 strcpy(pathname, "/tmp/llvm_XXXXXX");
162 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000163 if (TmpName == 0) {
164 MakeErrMsg(ErrMsg,
165 std::string(TmpName) + ": can't create unique directory name");
166 return Path();
167 }
168 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
169 MakeErrMsg(ErrMsg,
170 std::string(TmpName) + ": can't create temporary directory");
171 return Path();
172 }
Reid Spencer69a16162004-12-24 06:29:42 +0000173 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000174 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000175 assert(result.isValid() && "mktemp didn't create a valid pathname!");
176 return result;
177#else
178 // This is the worst case implementation. tempnam(3) leaks memory unless its
179 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
180 // issues. The mktemp(3) function doesn't have enough variability in the
181 // temporary name generated. So, we provide our own implementation that
182 // increments an integer from a random number seeded by the current time. This
183 // should be sufficiently unique that we don't have many collisions between
184 // processes. Generally LLVM processes don't run very long and don't use very
185 // many temporary files so this shouldn't be a big issue for LLVM.
186 static time_t num = ::time(0);
187 char pathname[MAXPATHLEN];
188 do {
189 num++;
190 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
191 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000192 if (-1 == ::mkdir(pathname, S_IRWXU)) {
193 MakeErrMsg(ErrMsg,
194 std::string(pathname) + ": can't create temporary directory");
195 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000196 }
Reid Spencer69a16162004-12-24 06:29:42 +0000197 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000198 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000199 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
200 return result;
201#endif
202}
203
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000204void
205Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
206#ifdef LTDL_SHLIBPATH_VAR
207 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
208 if (env_var != 0) {
209 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000210 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000211#endif
212 // FIXME: Should this look at LD_LIBRARY_PATH too?
213 Paths.push_back(sys::Path("/usr/local/lib/"));
214 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
215 Paths.push_back(sys::Path("/usr/lib/"));
216 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000217}
218
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000219void
Gabor Greifa99be512007-07-05 17:07:56 +0000220Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000221 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
222 if (env_var != 0) {
223 getPathList(env_var,Paths);
224 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000225#ifdef LLVM_LIBDIR
226 {
227 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000228 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000229 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000230 Paths.push_back(tmpPath);
231 }
232#endif
233 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000234}
235
236Path
237Path::GetLLVMDefaultConfigDir() {
238 return Path("/etc/llvm/");
239}
240
Reid Spencer8e665952004-08-29 05:24:01 +0000241Path
242Path::GetUserHomeDirectory() {
243 const char* home = getenv("HOME");
244 if (home) {
245 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000246 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000247 return result;
248 }
249 return GetRootDirectory();
250}
251
Ted Kremenek79200782007-12-18 22:07:33 +0000252Path
253Path::GetCurrentDirectory() {
254 char pathname[MAXPATHLEN];
255 if (!getcwd(pathname,MAXPATHLEN)) {
256 assert (false && "Could not query current working directory.");
257 return Path("");
258 }
259
260 return Path(pathname);
261}
Reid Spencera229c5c2005-07-08 03:08:58 +0000262
Chris Lattner1a091442008-03-03 02:55:43 +0000263/// GetMainExecutable - Return the path to the main executable, given the
264/// value of argv[0] from program startup.
265Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Seo Sanghyeonfd6437f2008-06-27 22:55:30 +0000266#if defined(__linux__) || defined(__CYGWIN__)
Chris Lattner3bdfa042008-03-13 05:22:05 +0000267 char exe_path[MAXPATHLEN];
Seo Sanghyeonfd6437f2008-06-27 22:55:30 +0000268 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Chris Lattner3bdfa042008-03-13 05:22:05 +0000269 if (len > 0 && len < MAXPATHLEN - 1) {
270 exe_path[len] = '\0';
271 return Path(std::string(exe_path));
272 }
273#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000274 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000275 Dl_info DLInfo;
276 int err = dladdr(MainAddr, &DLInfo);
277 if (err != 0)
278 return Path(std::string(DLInfo.dli_fname));
279#endif
280 return Path();
281}
282
283
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000284std::string Path::getDirname() const {
285 return getDirnameCharSep(path, '/');
286}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000287
Reid Spencer1b554b42004-09-11 04:55:08 +0000288std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000289Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000290 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000291 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000292 if (slash == std::string::npos)
293 slash = 0;
294 else
295 slash++;
296
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000297 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000298 if (dot == std::string::npos || dot < slash)
299 return path.substr(slash);
300 else
301 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000302}
303
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000304std::string
305Path::getSuffix() const {
306 // Find the last slash
307 std::string::size_type slash = path.rfind('/');
308 if (slash == std::string::npos)
309 slash = 0;
310 else
311 slash++;
312
313 std::string::size_type dot = path.rfind('.');
314 if (dot == std::string::npos || dot < slash)
Wojciech Matyjewicz93c53462008-06-15 18:02:47 +0000315 return std::string();
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000316 else
317 return path.substr(dot + 1);
318}
319
Reid Spencereaf18152004-11-14 22:08:36 +0000320bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000321 assert(len < 1024 && "Request for magic string too long");
322 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000323 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000324 if (fd < 0)
325 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000326 ssize_t bytes_read = ::read(fd, buf, len);
327 ::close(fd);
328 if (ssize_t(len) != bytes_read) {
329 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000330 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000331 }
332 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000333 return true;
334}
335
Reid Spencer1b554b42004-09-11 04:55:08 +0000336bool
Reid Spencer8e665952004-08-29 05:24:01 +0000337Path::exists() const {
338 return 0 == access(path.c_str(), F_OK );
339}
340
341bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000342Path::isDirectory() const {
343 struct stat buf;
344 if (0 != stat(path.c_str(), &buf))
345 return false;
346 return buf.st_mode & S_IFDIR ? true : false;
347}
348
349bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000350Path::canRead() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000351 return 0 == access(path.c_str(), F_OK | R_OK );
352}
353
354bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000355Path::canWrite() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000356 return 0 == access(path.c_str(), F_OK | W_OK );
357}
358
359bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000360Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000361 if (0 != access(path.c_str(), R_OK | X_OK ))
362 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000363 struct stat buf;
364 if (0 != stat(path.c_str(), &buf))
365 return false;
366 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000367 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000368 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000369}
370
371std::string
372Path::getLast() const {
373 // Find the last slash
374 size_t pos = path.rfind('/');
375
376 // Handle the corner cases
377 if (pos == std::string::npos)
378 return path;
379
380 // If the last character is a slash
381 if (pos == path.length()-1) {
382 // Find the second to last slash
383 size_t pos2 = path.rfind('/', pos-1);
384 if (pos2 == std::string::npos)
385 return path.substr(0,pos);
386 else
387 return path.substr(pos2+1,pos-pos2-1);
388 }
389 // Return everything after the last slash
390 return path.substr(pos+1);
391}
392
Reid Spencer2ae9d112007-04-07 18:52:17 +0000393const FileStatus *
394PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
395 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000396 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000397 if (0 != stat(path.c_str(), &buf)) {
398 MakeErrMsg(ErrStr, path + ": can't get status of file");
399 return 0;
400 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000401 status.fileSize = buf.st_size;
402 status.modTime.fromEpochTime(buf.st_mtime);
403 status.mode = buf.st_mode;
404 status.user = buf.st_uid;
405 status.group = buf.st_gid;
406 status.uniqueID = uint64_t(buf.st_ino);
407 status.isDir = S_ISDIR(buf.st_mode);
408 status.isFile = S_ISREG(buf.st_mode);
409 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000410 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000411 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000412}
413
Chris Lattner252ad032006-07-28 22:03:44 +0000414static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000415 // Get the umask value from the operating system. We want to use it
416 // when changing the file's permissions. Since calling umask() sets
417 // the umask and returns its old value, we must call it a second
418 // time to reset it to the user's preference.
419 int mask = umask(0777); // The arg. to umask is arbitrary.
420 umask(mask); // Restore the umask.
421
422 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000423 struct stat buf;
424 if (0 != stat(File.toString().c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000425 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000426 // Change the file to have whichever permissions bits from 'bits'
427 // that the umask would not disable.
428 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
429 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000430 return true;
431}
432
Reid Spencere1647f42006-08-22 23:27:23 +0000433bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000434 if (!AddPermissionBits(*this, 0444))
435 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000436 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000437}
438
Reid Spencere1647f42006-08-22 23:27:23 +0000439bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000440 if (!AddPermissionBits(*this, 0222))
441 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000442 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000443}
444
Reid Spencere1647f42006-08-22 23:27:23 +0000445bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000446 if (!AddPermissionBits(*this, 0111))
447 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000448 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000449}
450
Reid Spencereaf18152004-11-14 22:08:36 +0000451bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000452Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000453 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000454 if (direntries == 0)
455 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000456
Reid Spencer3be872e2005-07-28 16:25:57 +0000457 std::string dirPath = path;
458 if (!lastIsSlash(dirPath))
459 dirPath += '/';
460
Reid Spencereaf18152004-11-14 22:08:36 +0000461 result.clear();
462 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000463 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000464 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000465 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000466 struct stat st;
467 if (0 != lstat(aPath.path.c_str(), &st)) {
468 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000469 continue; // dangling symlink -- ignore
Reid Spencer5a060772006-08-23 07:30:48 +0000470 return MakeErrMsg(ErrMsg,
471 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000472 }
Reid Spencerb608a812004-11-16 06:15:19 +0000473 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000474 }
Reid Spencereaf18152004-11-14 22:08:36 +0000475 }
476
477 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000478 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000479}
480
Reid Spencer8e665952004-08-29 05:24:01 +0000481bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000482Path::set(const std::string& a_path) {
483 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000484 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000485 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000486 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000487 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000488 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000489 return false;
490 }
491 return true;
492}
493
494bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000495Path::appendComponent(const std::string& name) {
496 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000497 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000498 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000499 if (!lastIsSlash(path))
500 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000501 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000502 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000503 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000504 return false;
505 }
506 return true;
507}
508
509bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000510Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000511 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000512 if (slashpos == 0 || slashpos == std::string::npos) {
513 path.erase();
514 return true;
515 }
Reid Spencer8e665952004-08-29 05:24:01 +0000516 if (slashpos == path.size() - 1)
517 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000518 if (slashpos == std::string::npos) {
519 path.erase();
520 return true;
521 }
Reid Spencer8e665952004-08-29 05:24:01 +0000522 path.erase(slashpos);
523 return true;
524}
525
526bool
Reid Spencer07adb282004-11-05 22:15:36 +0000527Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000528 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000529 path.append(".");
530 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000531 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000532 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000533 return false;
534 }
535 return true;
536}
537
Reid Spencerdd04df02005-07-07 23:21:43 +0000538bool
539Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000540 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000541 size_t dotpos = path.rfind('.',path.size());
542 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000543 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000544 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000545 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000546 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000547 }
Reid Spencer8e665952004-08-29 05:24:01 +0000548 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000549 if (!isValid())
550 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000551 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000552}
553
Ted Kremenekc5412c52008-04-03 16:11:31 +0000554static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
555
556 if (access(beg, F_OK | R_OK | W_OK) == 0)
557 return false;
558
559 if (create_parents) {
560
561 char* c = end;
562
563 for (; c != beg; --c)
564 if (*c == '/') {
565
566 // Recurse to handling the parent directory.
567 *c = '\0';
568 bool x = createDirectoryHelper(beg, c, create_parents);
569 *c = '/';
570
571 // Return if we encountered an error.
572 if (x)
573 return true;
574
575 break;
576 }
577 }
578
579 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
580}
581
Reid Spencer8e665952004-08-29 05:24:01 +0000582bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000583Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000584 // Get a writeable copy of the path name
585 char pathname[MAXPATHLEN];
586 path.copy(pathname,MAXPATHLEN);
587
588 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000589 size_t lastchar = path.length() - 1 ;
Ted Kremenekc5412c52008-04-03 16:11:31 +0000590
591 if (pathname[lastchar] != '/')
592 ++lastchar;
593
594 pathname[lastchar] = 0;
595
596 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
597 return MakeErrMsg(ErrMsg,
598 std::string(pathname) + ": can't create directory");
599
Reid Spencere5c9cb52006-08-23 00:39:35 +0000600 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000601}
602
603bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000604Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000605 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000606 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000607 if (fd < 0)
608 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000609 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000610 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000611}
612
Reid Spencer8e665952004-08-29 05:24:01 +0000613bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000614Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000615 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000616 if (makeUnique( reuse_current, ErrMsg ))
617 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000618
619 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000620 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Reid Spencer5a060772006-08-23 07:30:48 +0000621 if (fd < 0)
622 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000623 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000624 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000625}
626
627bool
Chris Lattner0c332312006-07-28 22:29:50 +0000628Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Reid Spencer2ae9d112007-04-07 18:52:17 +0000629 // Get the status so we can determin if its a file or directory
630 struct stat buf;
631 if (0 != stat(path.c_str(), &buf)) {
632 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000633 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000634 }
635
636 // Note: this check catches strange situations. In all cases, LLVM should
637 // only be involved in the creation and deletion of regular files. This
638 // check ensures that what we're trying to erase is a regular file. It
639 // effectively prevents LLVM from erasing things like /dev/null, any block
640 // special file, or other things that aren't "regular" files.
641 if (S_ISREG(buf.st_mode)) {
642 if (unlink(path.c_str()) != 0)
643 return MakeErrMsg(ErrStr, path + ": can't destroy file");
644 return false;
645 }
646
647 if (!S_ISDIR(buf.st_mode)) {
648 if (ErrStr) *ErrStr = "not a file or directory";
649 return true;
650 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000651
Chris Lattner0c332312006-07-28 22:29:50 +0000652 if (remove_contents) {
653 // Recursively descend the directory to remove its contents.
654 std::string cmd = "/bin/rm -rf " + path;
655 system(cmd.c_str());
656 return false;
657 }
658
659 // Otherwise, try to just remove the one directory.
660 char pathname[MAXPATHLEN];
661 path.copy(pathname, MAXPATHLEN);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000662 size_t lastchar = path.length() - 1;
Chris Lattner0c332312006-07-28 22:29:50 +0000663 if (pathname[lastchar] == '/')
664 pathname[lastchar] = 0;
665 else
666 pathname[lastchar+1] = 0;
667
668 if (rmdir(pathname) != 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000669 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000670 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000671 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000672}
673
674bool
Reid Spencer5a060772006-08-23 07:30:48 +0000675Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000676 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer5a060772006-08-23 07:30:48 +0000677 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Reid Spencer2aafadc2005-04-21 02:50:10 +0000678 newName.toString() + "' ");
Reid Spencer5a060772006-08-23 07:30:48 +0000679 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000680}
681
Reid Spencer2ae9d112007-04-07 18:52:17 +0000682bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000683Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000684 struct utimbuf utb;
685 utb.actime = si.modTime.toPosixTime();
686 utb.modtime = utb.actime;
687 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000688 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000689 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000690 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000691 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000692}
693
Reid Spencer51c5a282006-08-23 20:34:57 +0000694bool
695sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000696 int inFile = -1;
697 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000698 inFile = ::open(Src.c_str(), O_RDONLY);
699 if (inFile == -1)
700 return MakeErrMsg(ErrMsg, Src.toString() +
701 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000702
Reid Spencer51c5a282006-08-23 20:34:57 +0000703 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
704 if (outFile == -1) {
705 ::close(inFile);
706 return MakeErrMsg(ErrMsg, Dest.toString() +
707 ": can't create destination file for copy");
708 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000709
Reid Spencer51c5a282006-08-23 20:34:57 +0000710 char Buffer[16*1024];
711 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
712 if (Amt == -1) {
713 if (errno != EINTR && errno != EAGAIN) {
714 ::close(inFile);
715 ::close(outFile);
716 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
717 }
718 } else {
719 char *BufPtr = Buffer;
720 while (Amt) {
721 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
722 if (AmtWritten == -1) {
723 if (errno != EINTR && errno != EAGAIN) {
724 ::close(inFile);
725 ::close(outFile);
726 return MakeErrMsg(ErrMsg, Dest.toString() +
727 ": can't write destination file: ");
Reid Spencerc29befb2004-12-15 01:50:13 +0000728 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000729 } else {
730 Amt -= AmtWritten;
731 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000732 }
733 }
734 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000735 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000736 ::close(inFile);
737 ::close(outFile);
738 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000739}
740
Reid Spencer51c5a282006-08-23 20:34:57 +0000741bool
742Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000743 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000744 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000745
746 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
747 // mktemp or our own implementation.
748 char *FNBuffer = (char*) alloca(path.size()+8);
Devang Patelce8fdf12008-07-22 20:02:39 +0000749 if (isDirectory()) {
750 std::string dirPath = getDirname();
751 strcpy(FNBuffer, dirPath.c_str());
752 strcpy(FNBuffer+dirPath.size(), "XXXXXX");
753 } else {
754 path.copy(FNBuffer,path.size());
755 strcpy(FNBuffer+path.size(), "-XXXXXX");
756 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000757
758#if defined(HAVE_MKSTEMP)
759 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000760 if ((TempFD = mkstemp(FNBuffer)) == -1)
761 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000762
763 // We don't need to hold the temp file descriptor... we will trust that no one
764 // will overwrite/delete the file before we can open it again.
765 close(TempFD);
766
767 // Save the name
768 path = FNBuffer;
769#elif defined(HAVE_MKTEMP)
770 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000771 if (mktemp(FNBuffer) == 0)
772 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000773
774 // Save the name
775 path = FNBuffer;
776#else
777 // Okay, looks like we have to do it all by our lonesome.
778 static unsigned FCounter = 0;
779 unsigned offset = path.size() + 1;
780 while ( FCounter < 999999 && exists()) {
781 sprintf(FNBuffer+offset,"%06u",++FCounter);
782 path = FNBuffer;
783 }
784 if (FCounter > 999999)
Reid Spencer51c5a282006-08-23 20:34:57 +0000785 return MakeErrMsg(ErrMsg,
786 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000787#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000788 return false;
789}
Reid Spencerc29befb2004-12-15 01:50:13 +0000790
Chris Lattner799ed102008-04-01 06:00:12 +0000791const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000792 int Flags = MAP_PRIVATE;
793#ifdef MAP_FILE
794 Flags |= MAP_FILE;
795#endif
796 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
797 if (BasePtr == MAP_FAILED)
798 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000799 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000800}
801
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000802void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000803 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000804}
805
Reid Spencer51c5a282006-08-23 20:34:57 +0000806} // end llvm namespace
Reid Spencerb89a2232004-08-25 06:20:07 +0000807