blob: ec2ba7cd9c338d0939690cae264b813ad529e395 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +00002//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +00007//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008//===----------------------------------------------------------------------===//
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
16//=== is guaranteed to work on *all* UNIX variants.
17//===----------------------------------------------------------------------===//
18
Chris Lattner8755dee2009-08-23 22:57:38 +000019#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "Unix.h"
21#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
Chris Lattner116abbf2008-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#if HAVE_UTIME_H
34#include <utime.h>
35#endif
36#if HAVE_TIME_H
37#include <time.h>
38#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 Lattner365f2202008-03-03 02:55:43 +000056#if HAVE_DLFCN_H
57#include <dlfcn.h>
58#endif
59
Benjamin Kramer76629852009-09-09 12:09:08 +000060#ifdef __APPLE__
61#include <mach-o/dyld.h>
62#endif
63
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064// Put in a hack for Cygwin which falsely reports that the mkdtemp function
65// is available when it is not.
66#ifdef __CYGWIN__
67# undef HAVE_MKDTEMP
68#endif
69
70namespace {
71inline bool lastIsSlash(const std::string& path) {
72 return !path.empty() && path[path.length() - 1] == '/';
73}
74
75}
76
77namespace llvm {
78using namespace sys;
79
Chris Lattner4b8f1c62008-02-27 06:17:10 +000080extern const char sys::PathSeparator = ':';
81
Nick Lewycky4fd4b462008-05-11 17:37:40 +000082Path::Path(const std::string& p)
83 : path(p) {}
84
85Path::Path(const char *StrStart, unsigned StrLen)
86 : path(StrStart, StrLen) {}
87
Chris Lattner43ac42b2008-08-11 23:39:47 +000088Path&
89Path::operator=(const std::string &that) {
90 path = that;
91 return *this;
92}
93
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +000094bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095Path::isValid() const {
96 // Check some obvious things
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +000097 if (path.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098 return false;
Chris Lattnerb898cff2009-07-12 19:01:16 +000099 return path.length() < MAXPATHLEN;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100}
101
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000102bool
Chris Lattnerd024d8d2009-06-15 04:17:07 +0000103Path::isAbsolute(const char *NameStart, unsigned NameLen) {
104 assert(NameStart);
105 if (NameLen == 0)
106 return false;
107 return NameStart[0] == '/';
108}
109
110bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111Path::isAbsolute() const {
112 if (path.empty())
113 return false;
114 return path[0] == '/';
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000115}
Daniel Dunbarbf8e8712009-07-12 20:23:56 +0000116
117void Path::makeAbsolute() {
118 if (isAbsolute())
119 return;
120
121 Path CWD = Path::GetCurrentDirectory();
122 assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
123
124 CWD.appendComponent(path);
125
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000126 path = CWD.str();
Daniel Dunbarbf8e8712009-07-12 20:23:56 +0000127}
128
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129Path
130Path::GetRootDirectory() {
131 Path result;
132 result.set("/");
133 return result;
134}
135
136Path
Chris Lattnera8164e42009-02-19 05:34:35 +0000137Path::GetTemporaryDirectory(std::string *ErrMsg) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138#if defined(HAVE_MKDTEMP)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000139 // The best way is with mkdtemp but that's not available on many systems,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 // Linux and FreeBSD have it. Others probably won't.
141 char pathname[MAXPATHLEN];
142 strcpy(pathname,"/tmp/llvm_XXXXXX");
143 if (0 == mkdtemp(pathname)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000144 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 std::string(pathname) + ": can't create temporary directory");
146 return Path();
147 }
148 Path result;
149 result.set(pathname);
150 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
151 return result;
152#elif defined(HAVE_MKSTEMP)
153 // If no mkdtemp is available, mkstemp can be used to create a temporary file
154 // which is then removed and created as a directory. We prefer this over
155 // mktemp because of mktemp's inherent security and threading risks. We still
156 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000157 // the time it is re-created as a directoy.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 char pathname[MAXPATHLEN];
159 strcpy(pathname, "/tmp/llvm_XXXXXX");
160 int fd = 0;
161 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000162 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 std::string(pathname) + ": can't create temporary directory");
164 return Path();
165 }
166 ::close(fd);
167 ::unlink(pathname); // start race condition, ignore errors
168 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000169 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 std::string(pathname) + ": can't create temporary directory");
171 return Path();
172 }
173 Path result;
174 result.set(pathname);
175 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
176 return result;
177#elif defined(HAVE_MKTEMP)
178 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
179 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
180 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
181 // the XXXXXX with the pid of the process and a letter. That leads to only
182 // twenty six temporary files that can be generated.
183 char pathname[MAXPATHLEN];
184 strcpy(pathname, "/tmp/llvm_XXXXXX");
185 char *TmpName = ::mktemp(pathname);
186 if (TmpName == 0) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000187 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 std::string(TmpName) + ": can't create unique directory name");
189 return Path();
190 }
191 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000192 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 std::string(TmpName) + ": can't create temporary directory");
194 return Path();
195 }
196 Path result;
197 result.set(TmpName);
198 assert(result.isValid() && "mktemp didn't create a valid pathname!");
199 return result;
200#else
201 // This is the worst case implementation. tempnam(3) leaks memory unless its
202 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
203 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000204 // temporary name generated. So, we provide our own implementation that
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 // increments an integer from a random number seeded by the current time. This
206 // should be sufficiently unique that we don't have many collisions between
207 // processes. Generally LLVM processes don't run very long and don't use very
208 // many temporary files so this shouldn't be a big issue for LLVM.
209 static time_t num = ::time(0);
210 char pathname[MAXPATHLEN];
211 do {
212 num++;
213 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
214 } while ( 0 == access(pathname, F_OK ) );
215 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000216 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 std::string(pathname) + ": can't create temporary directory");
218 return Path();
219 }
220 Path result;
221 result.set(pathname);
222 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
223 return result;
224#endif
225}
226
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000227void
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
229#ifdef LTDL_SHLIBPATH_VAR
230 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
231 if (env_var != 0) {
232 getPathList(env_var,Paths);
233 }
234#endif
235 // FIXME: Should this look at LD_LIBRARY_PATH too?
236 Paths.push_back(sys::Path("/usr/local/lib/"));
237 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
238 Paths.push_back(sys::Path("/usr/lib/"));
239 Paths.push_back(sys::Path("/lib/"));
240}
241
242void
243Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
244 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
245 if (env_var != 0) {
246 getPathList(env_var,Paths);
247 }
248#ifdef LLVM_LIBDIR
249 {
250 Path tmpPath;
251 if (tmpPath.set(LLVM_LIBDIR))
252 if (tmpPath.canRead())
253 Paths.push_back(tmpPath);
254 }
255#endif
256 GetSystemLibraryPaths(Paths);
257}
258
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000259Path
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260Path::GetLLVMDefaultConfigDir() {
261 return Path("/etc/llvm/");
262}
263
264Path
265Path::GetUserHomeDirectory() {
266 const char* home = getenv("HOME");
267 if (home) {
268 Path result;
269 if (result.set(home))
270 return result;
271 }
272 return GetRootDirectory();
273}
274
Ted Kremenekb05c9352007-12-18 22:07:33 +0000275Path
276Path::GetCurrentDirectory() {
277 char pathname[MAXPATHLEN];
278 if (!getcwd(pathname,MAXPATHLEN)) {
279 assert (false && "Could not query current working directory.");
280 return Path("");
281 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000282
Ted Kremenekb05c9352007-12-18 22:07:33 +0000283 return Path(pathname);
284}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285
Chris Lattner085fe052009-03-02 22:17:15 +0000286#ifdef __FreeBSD__
287static int
288test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
289 const char *dir, const char *bin)
290{
Bill Wendlingc1946742009-05-30 01:09:53 +0000291 struct stat sb;
Chris Lattner085fe052009-03-02 22:17:15 +0000292
Bill Wendlingc1946742009-05-30 01:09:53 +0000293 snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
294 if (realpath(buf, ret) == NULL)
295 return (1);
296 if (stat(buf, &sb) != 0)
297 return (1);
298
299 return (0);
Chris Lattner085fe052009-03-02 22:17:15 +0000300}
301
302static char *
303getprogpath(char ret[PATH_MAX], const char *bin)
304{
Bill Wendlingc1946742009-05-30 01:09:53 +0000305 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner085fe052009-03-02 22:17:15 +0000306
Bill Wendlingc1946742009-05-30 01:09:53 +0000307 /* First approach: absolute path. */
308 if (bin[0] == '/') {
309 if (test_dir(buf, ret, "/", bin) == 0)
310 return (ret);
311 return (NULL);
312 }
Chris Lattner085fe052009-03-02 22:17:15 +0000313
Bill Wendlingc1946742009-05-30 01:09:53 +0000314 /* Second approach: relative path. */
315 if (strchr(bin, '/') != NULL) {
316 if (getcwd(buf, PATH_MAX) == NULL)
317 return (NULL);
318 if (test_dir(buf, ret, buf, bin) == 0)
319 return (ret);
320 return (NULL);
321 }
Chris Lattner085fe052009-03-02 22:17:15 +0000322
Bill Wendlingc1946742009-05-30 01:09:53 +0000323 /* Third approach: $PATH */
324 if ((pv = getenv("PATH")) == NULL)
325 return (NULL);
326 s = pv = strdup(pv);
327 if (pv == NULL)
328 return (NULL);
329 while ((t = strsep(&s, ":")) != NULL) {
330 if (test_dir(buf, ret, t, bin) == 0) {
331 free(pv);
332 return (ret);
333 }
334 }
335 free(pv);
336 return (NULL);
Chris Lattner085fe052009-03-02 22:17:15 +0000337}
Edward O'Callaghanf21c0e12009-11-24 15:19:10 +0000338#endif // __FreeBSD__
Chris Lattner085fe052009-03-02 22:17:15 +0000339
Chris Lattner365f2202008-03-03 02:55:43 +0000340/// GetMainExecutable - Return the path to the main executable, given the
341/// value of argv[0] from program startup.
342Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramer76629852009-09-09 12:09:08 +0000343#if defined(__APPLE__)
344 // On OS X the executable path is saved to the stack by dyld. Reading it
345 // from there is much faster than calling dladdr, especially for large
346 // binaries with symbols.
347 char exe_path[MAXPATHLEN];
348 uint32_t size = sizeof(exe_path);
349 if (_NSGetExecutablePath(exe_path, &size) == 0) {
350 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamcfd64f92009-11-29 17:19:48 +0000351 if (realpath(exe_path, link_path))
352 return Path(std::string(link_path));
353 return Path();
Benjamin Kramer76629852009-09-09 12:09:08 +0000354 }
355#elif defined(__FreeBSD__)
Chris Lattner085fe052009-03-02 22:17:15 +0000356 char exe_path[PATH_MAX];
357
358 if (getprogpath(exe_path, argv0) != NULL)
359 return Path(std::string(exe_path));
360#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattnerc9aca312008-03-13 05:22:05 +0000361 char exe_path[MAXPATHLEN];
Seo Sanghyeon4d048212008-06-27 22:55:30 +0000362 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Dan Gohmand285c8f2009-08-05 20:16:55 +0000363 if (len >= 0)
364 return Path(std::string(exe_path, len));
Chris Lattnerc9aca312008-03-13 05:22:05 +0000365#elif defined(HAVE_DLFCN_H)
Chris Lattner365f2202008-03-03 02:55:43 +0000366 // Use dladdr to get executable path if available.
Chris Lattner365f2202008-03-03 02:55:43 +0000367 Dl_info DLInfo;
368 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnera8164e42009-02-19 05:34:35 +0000369 if (err == 0)
370 return Path();
Bill Wendlingc1946742009-05-30 01:09:53 +0000371
Chris Lattnera8164e42009-02-19 05:34:35 +0000372 // If the filename is a symlink, we need to resolve and return the location of
373 // the actual executable.
374 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamcfd64f92009-11-29 17:19:48 +0000375 if (realpath(DLInfo.dli_fname, link_path))
376 return Path(std::string(link_path));
377 return Path();
Chris Lattner365f2202008-03-03 02:55:43 +0000378#endif
379 return Path();
380}
381
382
Ted Kremenekb169dfa2008-04-07 22:01:32 +0000383std::string Path::getDirname() const {
384 return getDirnameCharSep(path, '/');
385}
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000386
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387std::string
388Path::getBasename() const {
389 // Find the last slash
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000390 std::string::size_type slash = path.rfind('/');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391 if (slash == std::string::npos)
392 slash = 0;
393 else
394 slash++;
395
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000396 std::string::size_type dot = path.rfind('.');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 if (dot == std::string::npos || dot < slash)
398 return path.substr(slash);
399 else
400 return path.substr(slash, dot - slash);
401}
402
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000403std::string
404Path::getSuffix() const {
405 // Find the last slash
406 std::string::size_type slash = path.rfind('/');
407 if (slash == std::string::npos)
408 slash = 0;
409 else
410 slash++;
411
412 std::string::size_type dot = path.rfind('.');
413 if (dot == std::string::npos || dot < slash)
Wojciech Matyjewiczce6f1372008-06-15 18:02:47 +0000414 return std::string();
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000415 else
416 return path.substr(dot + 1);
417}
418
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
420 assert(len < 1024 && "Request for magic string too long");
Chris Lattner8755dee2009-08-23 22:57:38 +0000421 SmallVector<char, 128> Buf;
422 Buf.resize(1 + len);
423 char* buf = Buf.data();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 int fd = ::open(path.c_str(), O_RDONLY);
425 if (fd < 0)
426 return false;
427 ssize_t bytes_read = ::read(fd, buf, len);
428 ::close(fd);
429 if (ssize_t(len) != bytes_read) {
430 Magic.clear();
431 return false;
432 }
433 Magic.assign(buf,len);
434 return true;
435}
436
437bool
438Path::exists() const {
439 return 0 == access(path.c_str(), F_OK );
440}
441
442bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000443Path::isDirectory() const {
444 struct stat buf;
445 if (0 != stat(path.c_str(), &buf))
446 return false;
447 return buf.st_mode & S_IFDIR ? true : false;
448}
449
450bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451Path::canRead() const {
Dan Gohman979c9d32009-07-28 23:22:01 +0000452 return 0 == access(path.c_str(), R_OK);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453}
454
455bool
456Path::canWrite() const {
Dan Gohman979c9d32009-07-28 23:22:01 +0000457 return 0 == access(path.c_str(), W_OK);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458}
459
460bool
Edward O'Callaghandf580132009-11-25 06:32:19 +0000461Path::isRegularFile() const {
Edward O'Callaghanf21c0e12009-11-24 15:19:10 +0000462 // Get the status so we can determine if its a file or directory
463 struct stat buf;
Edward O'Callaghanf21c0e12009-11-24 15:19:10 +0000464
Daniel Dunbar8bb85672009-11-24 19:03:33 +0000465 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghanf21c0e12009-11-24 15:19:10 +0000466 return false;
Edward O'Callaghanf21c0e12009-11-24 15:19:10 +0000467
Edward O'Callaghandf580132009-11-25 06:32:19 +0000468 if (S_ISREG(buf.st_mode))
469 return true;
470
471 return false;
Edward O'Callaghanf21c0e12009-11-24 15:19:10 +0000472}
473
474bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475Path::canExecute() const {
476 if (0 != access(path.c_str(), R_OK | X_OK ))
477 return false;
478 struct stat buf;
479 if (0 != stat(path.c_str(), &buf))
480 return false;
481 if (!S_ISREG(buf.st_mode))
482 return false;
483 return true;
484}
485
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000486std::string
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487Path::getLast() const {
488 // Find the last slash
489 size_t pos = path.rfind('/');
490
491 // Handle the corner cases
492 if (pos == std::string::npos)
493 return path;
494
495 // If the last character is a slash
496 if (pos == path.length()-1) {
497 // Find the second to last slash
498 size_t pos2 = path.rfind('/', pos-1);
499 if (pos2 == std::string::npos)
500 return path.substr(0,pos);
501 else
502 return path.substr(pos2+1,pos-pos2-1);
503 }
504 // Return everything after the last slash
505 return path.substr(pos+1);
506}
507
508const FileStatus *
509PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
510 if (!fsIsValid || update) {
511 struct stat buf;
512 if (0 != stat(path.c_str(), &buf)) {
513 MakeErrMsg(ErrStr, path + ": can't get status of file");
514 return 0;
515 }
516 status.fileSize = buf.st_size;
517 status.modTime.fromEpochTime(buf.st_mtime);
518 status.mode = buf.st_mode;
519 status.user = buf.st_uid;
520 status.group = buf.st_gid;
521 status.uniqueID = uint64_t(buf.st_ino);
522 status.isDir = S_ISDIR(buf.st_mode);
523 status.isFile = S_ISREG(buf.st_mode);
524 fsIsValid = true;
525 }
526 return &status;
527}
528
529static bool AddPermissionBits(const Path &File, int bits) {
530 // Get the umask value from the operating system. We want to use it
531 // when changing the file's permissions. Since calling umask() sets
532 // the umask and returns its old value, we must call it a second
533 // time to reset it to the user's preference.
534 int mask = umask(0777); // The arg. to umask is arbitrary.
535 umask(mask); // Restore the umask.
536
537 // Get the file's current mode.
538 struct stat buf;
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000539 if (0 != stat(File.c_str(), &buf))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 return false;
541 // Change the file to have whichever permissions bits from 'bits'
542 // that the umask would not disable.
543 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
544 return false;
545 return true;
546}
547
548bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000549 if (!AddPermissionBits(*this, 0444))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000550 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
551 return false;
552}
553
554bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
555 if (!AddPermissionBits(*this, 0222))
556 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
557 return false;
558}
559
560bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
561 if (!AddPermissionBits(*this, 0111))
562 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
563 return false;
564}
565
566bool
567Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
568 DIR* direntries = ::opendir(path.c_str());
569 if (direntries == 0)
570 return MakeErrMsg(ErrMsg, path + ": can't open directory");
571
572 std::string dirPath = path;
573 if (!lastIsSlash(dirPath))
574 dirPath += '/';
575
576 result.clear();
577 struct dirent* de = ::readdir(direntries);
578 for ( ; de != 0; de = ::readdir(direntries)) {
579 if (de->d_name[0] != '.') {
580 Path aPath(dirPath + (const char*)de->d_name);
581 struct stat st;
582 if (0 != lstat(aPath.path.c_str(), &st)) {
583 if (S_ISLNK(st.st_mode))
584 continue; // dangling symlink -- ignore
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000585 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 aPath.path + ": can't determine file object type");
587 }
588 result.insert(aPath);
589 }
590 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000591
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000592 closedir(direntries);
593 return false;
594}
595
596bool
597Path::set(const std::string& a_path) {
598 if (a_path.empty())
599 return false;
600 std::string save(path);
601 path = a_path;
602 if (!isValid()) {
603 path = save;
604 return false;
605 }
606 return true;
607}
608
609bool
610Path::appendComponent(const std::string& name) {
611 if (name.empty())
612 return false;
613 std::string save(path);
614 if (!lastIsSlash(path))
615 path += '/';
616 path += name;
617 if (!isValid()) {
618 path = save;
619 return false;
620 }
621 return true;
622}
623
624bool
625Path::eraseComponent() {
626 size_t slashpos = path.rfind('/',path.size());
627 if (slashpos == 0 || slashpos == std::string::npos) {
628 path.erase();
629 return true;
630 }
631 if (slashpos == path.size() - 1)
632 slashpos = path.rfind('/',slashpos-1);
633 if (slashpos == std::string::npos) {
634 path.erase();
635 return true;
636 }
637 path.erase(slashpos);
638 return true;
639}
640
641bool
642Path::appendSuffix(const std::string& suffix) {
643 std::string save(path);
644 path.append(".");
645 path.append(suffix);
646 if (!isValid()) {
647 path = save;
648 return false;
649 }
650 return true;
651}
652
653bool
654Path::eraseSuffix() {
655 std::string save = path;
656 size_t dotpos = path.rfind('.',path.size());
657 size_t slashpos = path.rfind('/',path.size());
658 if (dotpos != std::string::npos) {
659 if (slashpos == std::string::npos || dotpos > slashpos+1) {
660 path.erase(dotpos, path.size()-dotpos);
661 return true;
662 }
663 }
664 if (!isValid())
665 path = save;
666 return false;
667}
668
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000669static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000670
Dan Gohman54356b972009-07-29 00:02:58 +0000671 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000672 return false;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000673
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000674 if (create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000675
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000676 char* c = end;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000677
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000678 for (; c != beg; --c)
679 if (*c == '/') {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000680
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000681 // Recurse to handling the parent directory.
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000682 *c = '\0';
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000683 bool x = createDirectoryHelper(beg, c, create_parents);
684 *c = '/';
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000685
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000686 // Return if we encountered an error.
687 if (x)
688 return true;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000689
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000690 break;
691 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000692 }
693
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000694 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
695}
696
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697bool
698Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
699 // Get a writeable copy of the path name
700 char pathname[MAXPATHLEN];
701 path.copy(pathname,MAXPATHLEN);
702
703 // Null-terminate the last component
Evan Cheng591bfc82008-05-05 18:30:58 +0000704 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000705
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000706 if (pathname[lastchar] != '/')
707 ++lastchar;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000708
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000709 pathname[lastchar] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000710
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000711 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000712 return MakeErrMsg(ErrMsg,
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000713 std::string(pathname) + ": can't create directory");
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000714
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 return false;
716}
717
718bool
719Path::createFileOnDisk(std::string* ErrMsg) {
720 // Create the file
721 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
722 if (fd < 0)
723 return MakeErrMsg(ErrMsg, path + ": can't create file");
724 ::close(fd);
725 return false;
726}
727
728bool
729Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
730 // Make this into a unique file name
731 if (makeUnique( reuse_current, ErrMsg ))
732 return true;
733
734 // create the file
735 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000736 if (fd < 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
738 ::close(fd);
739 return false;
740}
741
742bool
743Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Edward O'Callaghanf21c0e12009-11-24 15:19:10 +0000744 // Get the status so we can determine if its a file or directory
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 struct stat buf;
746 if (0 != stat(path.c_str(), &buf)) {
747 MakeErrMsg(ErrStr, path + ": can't get status of file");
748 return true;
749 }
750
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000751 // Note: this check catches strange situations. In all cases, LLVM should
752 // only be involved in the creation and deletion of regular files. This
753 // check ensures that what we're trying to erase is a regular file. It
754 // effectively prevents LLVM from erasing things like /dev/null, any block
755 // special file, or other things that aren't "regular" files.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 if (S_ISREG(buf.st_mode)) {
757 if (unlink(path.c_str()) != 0)
758 return MakeErrMsg(ErrStr, path + ": can't destroy file");
759 return false;
760 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000761
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 if (!S_ISDIR(buf.st_mode)) {
763 if (ErrStr) *ErrStr = "not a file or directory";
764 return true;
765 }
766
767 if (remove_contents) {
768 // Recursively descend the directory to remove its contents.
769 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov61c9b982009-02-15 03:20:32 +0000770 if (system(cmd.c_str()) != 0) {
771 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
772 return true;
773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774 return false;
775 }
776
777 // Otherwise, try to just remove the one directory.
778 char pathname[MAXPATHLEN];
779 path.copy(pathname, MAXPATHLEN);
Evan Cheng591bfc82008-05-05 18:30:58 +0000780 size_t lastchar = path.length() - 1;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000781 if (pathname[lastchar] == '/')
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 pathname[lastchar] = 0;
783 else
784 pathname[lastchar+1] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000785
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 if (rmdir(pathname) != 0)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000787 return MakeErrMsg(ErrStr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 std::string(pathname) + ": can't erase directory");
789 return false;
790}
791
792bool
793Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
794 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000795 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000796 newName.str() + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 return false;
798}
799
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000800bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000801Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
802 struct utimbuf utb;
803 utb.actime = si.modTime.toPosixTime();
804 utb.modtime = utb.actime;
805 if (0 != ::utime(path.c_str(),&utb))
806 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
807 if (0 != ::chmod(path.c_str(),si.mode))
808 return MakeErrMsg(ErrStr, path + ": can't set mode");
809 return false;
810}
811
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000812bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
814 int inFile = -1;
815 int outFile = -1;
816 inFile = ::open(Src.c_str(), O_RDONLY);
817 if (inFile == -1)
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000818 return MakeErrMsg(ErrMsg, Src.str() +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 ": can't open source file to copy");
820
821 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
822 if (outFile == -1) {
823 ::close(inFile);
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000824 return MakeErrMsg(ErrMsg, Dest.str() +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 ": can't create destination file for copy");
826 }
827
828 char Buffer[16*1024];
829 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
830 if (Amt == -1) {
831 if (errno != EINTR && errno != EAGAIN) {
832 ::close(inFile);
833 ::close(outFile);
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000834 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 }
836 } else {
837 char *BufPtr = Buffer;
838 while (Amt) {
839 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
840 if (AmtWritten == -1) {
841 if (errno != EINTR && errno != EAGAIN) {
842 ::close(inFile);
843 ::close(outFile);
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000844 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000845 ": can't write destination file");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 }
847 } else {
848 Amt -= AmtWritten;
849 BufPtr += AmtWritten;
850 }
851 }
852 }
853 }
854 ::close(inFile);
855 ::close(outFile);
856 return false;
857}
858
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000859bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
861 if (reuse_current && !exists())
862 return false; // File doesn't exist already, just use it!
863
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000864 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 // mktemp or our own implementation.
Chris Lattner8755dee2009-08-23 22:57:38 +0000866 SmallVector<char, 128> Buf;
867 Buf.resize(path.size()+8);
868 char *FNBuffer = Buf.data();
Devang Patel79612e12008-07-22 20:02:39 +0000869 path.copy(FNBuffer,path.size());
Devang Pateldb08c702008-07-24 00:35:38 +0000870 if (isDirectory())
871 strcpy(FNBuffer+path.size(), "/XXXXXX");
872 else
Devang Patel79612e12008-07-22 20:02:39 +0000873 strcpy(FNBuffer+path.size(), "-XXXXXX");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874
875#if defined(HAVE_MKSTEMP)
876 int TempFD;
877 if ((TempFD = mkstemp(FNBuffer)) == -1)
878 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
879
880 // We don't need to hold the temp file descriptor... we will trust that no one
881 // will overwrite/delete the file before we can open it again.
882 close(TempFD);
883
884 // Save the name
885 path = FNBuffer;
886#elif defined(HAVE_MKTEMP)
887 // If we don't have mkstemp, use the old and obsolete mktemp function.
888 if (mktemp(FNBuffer) == 0)
889 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
890
891 // Save the name
892 path = FNBuffer;
893#else
894 // Okay, looks like we have to do it all by our lonesome.
895 static unsigned FCounter = 0;
896 unsigned offset = path.size() + 1;
897 while ( FCounter < 999999 && exists()) {
898 sprintf(FNBuffer+offset,"%06u",++FCounter);
899 path = FNBuffer;
900 }
901 if (FCounter > 999999)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000902 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 path + ": can't make unique filename: too many files");
904#endif
905 return false;
906}
907
Chris Lattner157d70a2008-04-01 06:00:12 +0000908const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000909 int Flags = MAP_PRIVATE;
910#ifdef MAP_FILE
911 Flags |= MAP_FILE;
912#endif
913 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
914 if (BasePtr == MAP_FAILED)
915 return 0;
Chris Lattner116abbf2008-04-01 06:25:23 +0000916 return (const char*)BasePtr;
Chris Lattner157d70a2008-04-01 06:00:12 +0000917}
918
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000919void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner116abbf2008-04-01 06:25:23 +0000920 ::munmap((void*)BasePtr, FileSize);
Chris Lattner157d70a2008-04-01 06:00:12 +0000921}
922
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923} // end llvm namespace