blob: 6a5ebb8cd9c7697e488519899b9cc900081047cb [file] [log] [blame]
Charles Davis53ca1f32010-11-29 19:44:50 +00001//===- llvm/Support/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +00002//
Reid Spencerb89a2232004-08-25 06:20:07 +00003// 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.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +00007//
Reid Spencerb89a2232004-08-25 06:20:07 +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
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
19#include "Unix.h"
Reid Spenceraf2f2082004-12-27 06:17:15 +000020#if HAVE_SYS_STAT_H
Reid Spencerb89a2232004-08-25 06:20:07 +000021#include <sys/stat.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000022#endif
23#if HAVE_FCNTL_H
Reid Spencerb89a2232004-08-25 06:20:07 +000024#include <fcntl.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000025#endif
Chris Lattner14c762d2008-04-01 06:25:23 +000026#ifdef HAVE_SYS_MMAN_H
27#include <sys/mman.h>
28#endif
29#ifdef HAVE_SYS_STAT_H
30#include <sys/stat.h>
31#endif
Reid Spenceraf2f2082004-12-27 06:17:15 +000032#if HAVE_UTIME_H
Reid Spencereaf18152004-11-14 22:08:36 +000033#include <utime.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000034#endif
35#if HAVE_TIME_H
Reid Spencer69a16162004-12-24 06:29:42 +000036#include <time.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000037#endif
38#if HAVE_DIRENT_H
39# include <dirent.h>
40# define NAMLEN(dirent) strlen((dirent)->d_name)
41#else
42# define dirent direct
43# define NAMLEN(dirent) (dirent)->d_namlen
44# if HAVE_SYS_NDIR_H
45# include <sys/ndir.h>
46# endif
47# if HAVE_SYS_DIR_H
48# include <sys/dir.h>
49# endif
50# if HAVE_NDIR_H
51# include <ndir.h>
52# endif
53#endif
54
Chris Lattner1a091442008-03-03 02:55:43 +000055#if HAVE_DLFCN_H
56#include <dlfcn.h>
57#endif
58
Benjamin Kramerd8b06302009-09-09 12:09:08 +000059#ifdef __APPLE__
60#include <mach-o/dyld.h>
61#endif
62
Sylvestre Ledru6fc30c22012-04-11 15:35:36 +000063// For GNU Hurd
64#if defined(__GNU__) && !defined(MAXPATHLEN)
65# define MAXPATHLEN 4096
66#endif
67
Reid Spencer932e2e32005-06-02 05:38:20 +000068// Put in a hack for Cygwin which falsely reports that the mkdtemp function
69// is available when it is not.
70#ifdef __CYGWIN__
71# undef HAVE_MKDTEMP
72#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000073
Reid Spencer3be872e2005-07-28 16:25:57 +000074namespace {
75inline bool lastIsSlash(const std::string& path) {
76 return !path.empty() && path[path.length() - 1] == '/';
77}
78
79}
80
Reid Spencer8e665952004-08-29 05:24:01 +000081namespace llvm {
82using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000083
Daniel Dunbar164c7ba2009-12-09 03:26:33 +000084const char sys::PathSeparator = ':';
Chris Lattnere1b332a2008-02-27 06:17:10 +000085
Mikhail Glushenkovf5a95ce2010-11-02 20:32:26 +000086StringRef Path::GetEXESuffix() {
Dan Gohman8eeb5ae2010-11-02 20:52:47 +000087 return StringRef();
Mikhail Glushenkovf5a95ce2010-11-02 20:32:26 +000088}
89
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +000090Path::Path(StringRef p)
Nick Lewyckyfff116f2008-05-11 17:37:40 +000091 : path(p) {}
92
93Path::Path(const char *StrStart, unsigned StrLen)
94 : path(StrStart, StrLen) {}
95
Chris Lattner0eab5e22008-08-11 23:39:47 +000096Path&
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +000097Path::operator=(StringRef that) {
98 path.assign(that.data(), that.size());
Chris Lattner0eab5e22008-08-11 23:39:47 +000099 return *this;
100}
101
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000102bool
Reid Spencer69a16162004-12-24 06:29:42 +0000103Path::isValid() const {
Dan Gohmanac793822010-11-02 23:19:55 +0000104 // Empty paths are considered invalid here.
105 // This code doesn't check MAXPATHLEN because there's no need. Nothing in
106 // LLVM manipulates Paths with fixed-sizes arrays, and if the OS can't
107 // handle names longer than some limit, it'll report this on demand using
108 // ENAMETOLONG.
109 return !path.empty();
Reid Spencer69a16162004-12-24 06:29:42 +0000110}
111
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000112bool
Chris Lattner88d7e402009-06-15 04:17:07 +0000113Path::isAbsolute(const char *NameStart, unsigned NameLen) {
114 assert(NameStart);
115 if (NameLen == 0)
116 return false;
117 return NameStart[0] == '/';
118}
119
120bool
Reid Spencer69cce812007-03-29 16:43:20 +0000121Path::isAbsolute() const {
122 if (path.empty())
123 return false;
124 return path[0] == '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000125}
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000126
Reid Spencer8e665952004-08-29 05:24:01 +0000127Path
128Path::GetRootDirectory() {
129 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000130 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000131 return result;
132}
133
Reid Spencer69a16162004-12-24 06:29:42 +0000134Path
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000135Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer69a16162004-12-24 06:29:42 +0000136#if defined(HAVE_MKDTEMP)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000137 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer69a16162004-12-24 06:29:42 +0000138 // Linux and FreeBSD have it. Others probably won't.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000139 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer48744762006-08-22 19:01:30 +0000140 if (0 == mkdtemp(pathname)) {
Dan Gohman6f6021e2010-11-02 22:56:51 +0000141 MakeErrMsg(ErrMsg,
142 std::string(pathname) + ": can't create temporary directory");
Reid Spencer48744762006-08-22 19:01:30 +0000143 return Path();
144 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000145 return Path(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000146#elif defined(HAVE_MKSTEMP)
147 // If no mkdtemp is available, mkstemp can be used to create a temporary file
148 // which is then removed and created as a directory. We prefer this over
149 // mktemp because of mktemp's inherent security and threading risks. We still
150 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000151 // the time it is re-created as a directoy.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000152 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer69a16162004-12-24 06:29:42 +0000153 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000154 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000155 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000156 std::string(pathname) + ": can't create temporary directory");
157 return Path();
158 }
Reid Spencer69a16162004-12-24 06:29:42 +0000159 ::close(fd);
160 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000161 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000162 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000163 std::string(pathname) + ": can't create temporary directory");
164 return Path();
165 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000166 return Path(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000167#elif defined(HAVE_MKTEMP)
168 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
169 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
170 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
171 // the XXXXXX with the pid of the process and a letter. That leads to only
172 // twenty six temporary files that can be generated.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000173 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer69a16162004-12-24 06:29:42 +0000174 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000175 if (TmpName == 0) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000176 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000177 std::string(TmpName) + ": can't create unique directory name");
178 return Path();
179 }
180 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000181 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000182 std::string(TmpName) + ": can't create temporary directory");
183 return Path();
184 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000185 return Path(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000186#else
187 // This is the worst case implementation. tempnam(3) leaks memory unless its
188 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
189 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000190 // temporary name generated. So, we provide our own implementation that
Reid Spencer69a16162004-12-24 06:29:42 +0000191 // increments an integer from a random number seeded by the current time. This
192 // should be sufficiently unique that we don't have many collisions between
193 // processes. Generally LLVM processes don't run very long and don't use very
194 // many temporary files so this shouldn't be a big issue for LLVM.
195 static time_t num = ::time(0);
196 char pathname[MAXPATHLEN];
197 do {
198 num++;
199 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
200 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000201 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000202 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000203 std::string(pathname) + ": can't create temporary directory");
204 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000205 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000206 return Path(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000207#endif
208}
209
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000210void
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000211Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
212#ifdef LTDL_SHLIBPATH_VAR
213 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
214 if (env_var != 0) {
215 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000216 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000217#endif
218 // FIXME: Should this look at LD_LIBRARY_PATH too?
219 Paths.push_back(sys::Path("/usr/local/lib/"));
220 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
221 Paths.push_back(sys::Path("/usr/lib/"));
222 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000223}
224
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000225void
Gabor Greifa99be512007-07-05 17:07:56 +0000226Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000227 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
228 if (env_var != 0) {
229 getPathList(env_var,Paths);
230 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000231#ifdef LLVM_LIBDIR
232 {
233 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000234 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000235 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000236 Paths.push_back(tmpPath);
237 }
238#endif
239 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000240}
241
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000242Path
Reid Spencer8e665952004-08-29 05:24:01 +0000243Path::GetUserHomeDirectory() {
244 const char* home = getenv("HOME");
Michael J. Spencer9170a0f2010-12-27 03:21:41 +0000245 Path result;
246 if (home && result.set(home))
247 return result;
248 result.set("/");
249 return result;
Reid Spencer8e665952004-08-29 05:24:01 +0000250}
251
Ted Kremenek79200782007-12-18 22:07:33 +0000252Path
253Path::GetCurrentDirectory() {
254 char pathname[MAXPATHLEN];
Nick Lewycky3c036e52011-07-29 04:42:39 +0000255 if (!getcwd(pathname, MAXPATHLEN)) {
256 assert(false && "Could not query current working directory.");
Dan Gohmand98af0a2010-08-04 01:39:08 +0000257 return Path();
Ted Kremenek79200782007-12-18 22:07:33 +0000258 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000259
Ted Kremenek79200782007-12-18 22:07:33 +0000260 return Path(pathname);
261}
Reid Spencera229c5c2005-07-08 03:08:58 +0000262
Eric Christopherb0f67592012-08-06 20:52:18 +0000263#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Sylvestre Ledrubec3ce02012-09-26 08:30:35 +0000264 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
265 defined(__linux__) || defined(__CYGWIN__)
Chris Lattner893a0f92009-03-02 22:17:15 +0000266static int
267test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
268 const char *dir, const char *bin)
269{
Bill Wendling51b16f42009-05-30 01:09:53 +0000270 struct stat sb;
Chris Lattner893a0f92009-03-02 22:17:15 +0000271
Dan Gohman86759ac2010-09-02 18:24:46 +0000272 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
Bill Wendling51b16f42009-05-30 01:09:53 +0000273 if (realpath(buf, ret) == NULL)
274 return (1);
275 if (stat(buf, &sb) != 0)
276 return (1);
277
278 return (0);
Chris Lattner893a0f92009-03-02 22:17:15 +0000279}
280
281static char *
282getprogpath(char ret[PATH_MAX], const char *bin)
283{
Bill Wendling51b16f42009-05-30 01:09:53 +0000284 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner893a0f92009-03-02 22:17:15 +0000285
Bill Wendling51b16f42009-05-30 01:09:53 +0000286 /* First approach: absolute path. */
287 if (bin[0] == '/') {
288 if (test_dir(buf, ret, "/", bin) == 0)
289 return (ret);
290 return (NULL);
291 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000292
Bill Wendling51b16f42009-05-30 01:09:53 +0000293 /* Second approach: relative path. */
294 if (strchr(bin, '/') != NULL) {
295 if (getcwd(buf, PATH_MAX) == NULL)
296 return (NULL);
297 if (test_dir(buf, ret, buf, bin) == 0)
298 return (ret);
299 return (NULL);
300 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000301
Bill Wendling51b16f42009-05-30 01:09:53 +0000302 /* Third approach: $PATH */
303 if ((pv = getenv("PATH")) == NULL)
304 return (NULL);
305 s = pv = strdup(pv);
306 if (pv == NULL)
307 return (NULL);
308 while ((t = strsep(&s, ":")) != NULL) {
309 if (test_dir(buf, ret, t, bin) == 0) {
310 free(pv);
311 return (ret);
312 }
313 }
314 free(pv);
315 return (NULL);
Chris Lattner893a0f92009-03-02 22:17:15 +0000316}
Anton Korobeynikova3ad5852012-03-26 12:05:51 +0000317#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
Chris Lattner893a0f92009-03-02 22:17:15 +0000318
Chris Lattner1a091442008-03-03 02:55:43 +0000319/// GetMainExecutable - Return the path to the main executable, given the
320/// value of argv[0] from program startup.
321Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000322#if defined(__APPLE__)
323 // On OS X the executable path is saved to the stack by dyld. Reading it
324 // from there is much faster than calling dladdr, especially for large
325 // binaries with symbols.
326 char exe_path[MAXPATHLEN];
327 uint32_t size = sizeof(exe_path);
328 if (_NSGetExecutablePath(exe_path, &size) == 0) {
329 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000330 if (realpath(exe_path, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000331 return Path(link_path);
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000332 }
Eric Christopherb0f67592012-08-06 20:52:18 +0000333#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Anton Korobeynikova3ad5852012-03-26 12:05:51 +0000334 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
Chris Lattner893a0f92009-03-02 22:17:15 +0000335 char exe_path[PATH_MAX];
336
337 if (getprogpath(exe_path, argv0) != NULL)
Dan Gohman8d4fd962010-11-02 22:07:47 +0000338 return Path(exe_path);
Chris Lattner893a0f92009-03-02 22:17:15 +0000339#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattner3bdfa042008-03-13 05:22:05 +0000340 char exe_path[MAXPATHLEN];
Sylvestre Ledrubec3ce02012-09-26 08:30:35 +0000341 StringRef aPath("/proc/self/exe");
342 if (sys::fs::exists(aPath)) {
343 // /proc is not always mounted under Linux (chroot for example).
344 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
345 if (len >= 0)
346 return Path(StringRef(exe_path, len));
347 } else {
348 // Fall back to the classical detection.
349 if (getprogpath(exe_path, argv0) != NULL)
350 return Path(exe_path);
351 }
Chris Lattner3bdfa042008-03-13 05:22:05 +0000352#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000353 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000354 Dl_info DLInfo;
355 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000356 if (err == 0)
357 return Path();
Bill Wendling51b16f42009-05-30 01:09:53 +0000358
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000359 // If the filename is a symlink, we need to resolve and return the location of
360 // the actual executable.
361 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000362 if (realpath(DLInfo.dli_fname, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000363 return Path(link_path);
Dan Gohmanb52d44a2010-09-07 18:26:49 +0000364#else
365#error GetMainExecutable is not implemented on this host yet.
Chris Lattner1a091442008-03-03 02:55:43 +0000366#endif
367 return Path();
368}
369
370
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000371StringRef Path::getDirname() const {
372 return getDirnameCharSep(path, "/");
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000373}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000374
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000375StringRef
Reid Spencer07adb282004-11-05 22:15:36 +0000376Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000377 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000378 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000379 if (slash == std::string::npos)
380 slash = 0;
381 else
382 slash++;
383
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000384 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000385 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000386 return StringRef(path).substr(slash);
Jeff Cohen73f36672005-07-09 18:42:02 +0000387 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000388 return StringRef(path).substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000389}
390
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000391StringRef
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000392Path::getSuffix() const {
393 // Find the last slash
394 std::string::size_type slash = path.rfind('/');
395 if (slash == std::string::npos)
396 slash = 0;
397 else
398 slash++;
399
400 std::string::size_type dot = path.rfind('.');
401 if (dot == std::string::npos || dot < slash)
Dan Gohmand98af0a2010-08-04 01:39:08 +0000402 return StringRef();
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000403 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000404 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000405}
406
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000407bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000408 assert(len < 1024 && "Request for magic string too long");
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000409 char Buf[1025];
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000410 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000411 if (fd < 0)
412 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000413 ssize_t bytes_read = ::read(fd, Buf, len);
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000414 ::close(fd);
Dan Gohman02d58242010-05-27 17:14:10 +0000415 if (ssize_t(len) != bytes_read)
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000416 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000417 Magic.assign(Buf, len);
Reid Spencereaf18152004-11-14 22:08:36 +0000418 return true;
419}
420
Reid Spencer1b554b42004-09-11 04:55:08 +0000421bool
Reid Spencer8e665952004-08-29 05:24:01 +0000422Path::exists() const {
423 return 0 == access(path.c_str(), F_OK );
424}
425
426bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000427Path::isDirectory() const {
428 struct stat buf;
429 if (0 != stat(path.c_str(), &buf))
430 return false;
Evan Chenga98111c2010-10-07 22:05:57 +0000431 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
Ted Kremenekfd527112007-12-18 19:46:22 +0000432}
433
434bool
Rafael Espindola9e07a142010-11-07 04:36:50 +0000435Path::isSymLink() const {
436 struct stat buf;
437 if (0 != lstat(path.c_str(), &buf))
438 return false;
439 return S_ISLNK(buf.st_mode);
440}
441
442
443bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000444Path::canRead() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000445 return 0 == access(path.c_str(), R_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000446}
447
448bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000449Path::canWrite() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000450 return 0 == access(path.c_str(), W_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000451}
452
453bool
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000454Path::isRegularFile() const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000455 // Get the status so we can determine if it's a file or directory
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000456 struct stat buf;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000457
Daniel Dunbar98e46d82009-11-24 19:03:33 +0000458 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000459 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000460
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000461 if (S_ISREG(buf.st_mode))
462 return true;
463
464 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000465}
466
467bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000468Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000469 if (0 != access(path.c_str(), R_OK | X_OK ))
470 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000471 struct stat buf;
472 if (0 != stat(path.c_str(), &buf))
473 return false;
474 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000475 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000476 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000477}
478
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000479StringRef
Reid Spencer8e665952004-08-29 05:24:01 +0000480Path::getLast() const {
481 // Find the last slash
482 size_t pos = path.rfind('/');
483
484 // Handle the corner cases
485 if (pos == std::string::npos)
486 return path;
487
488 // If the last character is a slash
489 if (pos == path.length()-1) {
490 // Find the second to last slash
491 size_t pos2 = path.rfind('/', pos-1);
492 if (pos2 == std::string::npos)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000493 return StringRef(path).substr(0,pos);
Reid Spencer8e665952004-08-29 05:24:01 +0000494 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000495 return StringRef(path).substr(pos2+1,pos-pos2-1);
Reid Spencer8e665952004-08-29 05:24:01 +0000496 }
497 // Return everything after the last slash
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000498 return StringRef(path).substr(pos+1);
Reid Spencer8e665952004-08-29 05:24:01 +0000499}
500
Reid Spencer2ae9d112007-04-07 18:52:17 +0000501const FileStatus *
502PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
503 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000504 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000505 if (0 != stat(path.c_str(), &buf)) {
506 MakeErrMsg(ErrStr, path + ": can't get status of file");
507 return 0;
508 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000509 status.fileSize = buf.st_size;
510 status.modTime.fromEpochTime(buf.st_mtime);
511 status.mode = buf.st_mode;
512 status.user = buf.st_uid;
513 status.group = buf.st_gid;
514 status.uniqueID = uint64_t(buf.st_ino);
515 status.isDir = S_ISDIR(buf.st_mode);
516 status.isFile = S_ISREG(buf.st_mode);
517 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000518 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000519 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000520}
521
Chris Lattner252ad032006-07-28 22:03:44 +0000522static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000523 // Get the umask value from the operating system. We want to use it
524 // when changing the file's permissions. Since calling umask() sets
525 // the umask and returns its old value, we must call it a second
526 // time to reset it to the user's preference.
527 int mask = umask(0777); // The arg. to umask is arbitrary.
528 umask(mask); // Restore the umask.
529
530 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000531 struct stat buf;
Chris Lattner74382b72009-08-23 22:45:37 +0000532 if (0 != stat(File.c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000533 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000534 // Change the file to have whichever permissions bits from 'bits'
535 // that the umask would not disable.
536 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
537 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000538 return true;
539}
540
Reid Spencere1647f42006-08-22 23:27:23 +0000541bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000542 if (!AddPermissionBits(*this, 0444))
Reid Spencer5a060772006-08-23 07:30:48 +0000543 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000544 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000545}
546
Reid Spencere1647f42006-08-22 23:27:23 +0000547bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000548 if (!AddPermissionBits(*this, 0222))
549 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000550 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000551}
552
Reid Spencere1647f42006-08-22 23:27:23 +0000553bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000554 if (!AddPermissionBits(*this, 0111))
555 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000556 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000557}
558
Reid Spencereaf18152004-11-14 22:08:36 +0000559bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000560Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000561 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000562 if (direntries == 0)
563 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000564
Reid Spencer3be872e2005-07-28 16:25:57 +0000565 std::string dirPath = path;
566 if (!lastIsSlash(dirPath))
567 dirPath += '/';
568
Reid Spencereaf18152004-11-14 22:08:36 +0000569 result.clear();
570 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000571 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000572 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000573 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000574 struct stat st;
575 if (0 != lstat(aPath.path.c_str(), &st)) {
576 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000577 continue; // dangling symlink -- ignore
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000578 return MakeErrMsg(ErrMsg,
Reid Spencer5a060772006-08-23 07:30:48 +0000579 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000580 }
Reid Spencerb608a812004-11-16 06:15:19 +0000581 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000582 }
Reid Spencereaf18152004-11-14 22:08:36 +0000583 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000584
Reid Spencereaf18152004-11-14 22:08:36 +0000585 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000586 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000587}
588
Reid Spencer8e665952004-08-29 05:24:01 +0000589bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000590Path::set(StringRef a_path) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000591 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000592 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000593 path = a_path;
Reid Spencer8e665952004-08-29 05:24:01 +0000594 return true;
595}
596
597bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000598Path::appendComponent(StringRef name) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000599 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000600 return false;
Reid Spencer3be872e2005-07-28 16:25:57 +0000601 if (!lastIsSlash(path))
602 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000603 path += name;
Reid Spencer8e665952004-08-29 05:24:01 +0000604 return true;
605}
606
607bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000608Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000609 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000610 if (slashpos == 0 || slashpos == std::string::npos) {
611 path.erase();
612 return true;
613 }
Reid Spencer8e665952004-08-29 05:24:01 +0000614 if (slashpos == path.size() - 1)
615 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000616 if (slashpos == std::string::npos) {
617 path.erase();
618 return true;
619 }
Reid Spencer8e665952004-08-29 05:24:01 +0000620 path.erase(slashpos);
621 return true;
622}
623
624bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000625Path::eraseSuffix() {
Reid Spencer8e665952004-08-29 05:24:01 +0000626 size_t dotpos = path.rfind('.',path.size());
627 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000628 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000629 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000630 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000631 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000632 }
Reid Spencer8e665952004-08-29 05:24:01 +0000633 }
Jeff Cohen563a17f2005-07-08 04:49:16 +0000634 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000635}
636
Ted Kremenekc5412c52008-04-03 16:11:31 +0000637static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000638
Dan Gohman28daa102009-07-29 00:02:58 +0000639 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenekc5412c52008-04-03 16:11:31 +0000640 return false;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000641
Ted Kremenekc5412c52008-04-03 16:11:31 +0000642 if (create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000643
Ted Kremenekc5412c52008-04-03 16:11:31 +0000644 char* c = end;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000645
Ted Kremenekc5412c52008-04-03 16:11:31 +0000646 for (; c != beg; --c)
647 if (*c == '/') {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000648
Ted Kremenekc5412c52008-04-03 16:11:31 +0000649 // Recurse to handling the parent directory.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000650 *c = '\0';
Ted Kremenekc5412c52008-04-03 16:11:31 +0000651 bool x = createDirectoryHelper(beg, c, create_parents);
652 *c = '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000653
Ted Kremenekc5412c52008-04-03 16:11:31 +0000654 // Return if we encountered an error.
655 if (x)
656 return true;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000657
Ted Kremenekc5412c52008-04-03 16:11:31 +0000658 break;
659 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000660 }
661
Ted Kremenekc5412c52008-04-03 16:11:31 +0000662 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
663}
664
Reid Spencer8e665952004-08-29 05:24:01 +0000665bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000666Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000667 // Get a writeable copy of the path name
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000668 std::string pathname(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000669
670 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000671 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000672
Ted Kremenekc5412c52008-04-03 16:11:31 +0000673 if (pathname[lastchar] != '/')
674 ++lastchar;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000675
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000676 pathname[lastchar] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000677
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000678 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
Dan Gohman9e2e0c32010-11-02 23:16:26 +0000679 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000680
Reid Spencere5c9cb52006-08-23 00:39:35 +0000681 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000682}
683
684bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000685Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000686 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000687 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000688 if (fd < 0)
689 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000690 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000691 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000692}
693
Reid Spencer8e665952004-08-29 05:24:01 +0000694bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000695Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000696 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000697 if (makeUnique( reuse_current, ErrMsg ))
698 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000699
700 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000701 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000702 if (fd < 0)
Reid Spencer5a060772006-08-23 07:30:48 +0000703 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000704 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000705 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000706}
707
708bool
Chris Lattner0c332312006-07-28 22:29:50 +0000709Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000710 // Get the status so we can determine if it's a file or directory.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000711 struct stat buf;
712 if (0 != stat(path.c_str(), &buf)) {
713 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000714 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000715 }
716
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000717 // Note: this check catches strange situations. In all cases, LLVM should
718 // only be involved in the creation and deletion of regular files. This
719 // check ensures that what we're trying to erase is a regular file. It
720 // effectively prevents LLVM from erasing things like /dev/null, any block
721 // special file, or other things that aren't "regular" files.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000722 if (S_ISREG(buf.st_mode)) {
723 if (unlink(path.c_str()) != 0)
724 return MakeErrMsg(ErrStr, path + ": can't destroy file");
725 return false;
726 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000727
Reid Spencer2ae9d112007-04-07 18:52:17 +0000728 if (!S_ISDIR(buf.st_mode)) {
729 if (ErrStr) *ErrStr = "not a file or directory";
730 return true;
731 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000732
Chris Lattner0c332312006-07-28 22:29:50 +0000733 if (remove_contents) {
734 // Recursively descend the directory to remove its contents.
735 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov8eada622009-02-15 03:20:32 +0000736 if (system(cmd.c_str()) != 0) {
737 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
738 return true;
739 }
Chris Lattner0c332312006-07-28 22:29:50 +0000740 return false;
741 }
742
743 // Otherwise, try to just remove the one directory.
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000744 std::string pathname(path);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000745 size_t lastchar = path.length() - 1;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000746 if (pathname[lastchar] == '/')
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000747 pathname[lastchar] = '\0';
Chris Lattner0c332312006-07-28 22:29:50 +0000748 else
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000749 pathname[lastchar+1] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000750
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000751 if (rmdir(pathname.c_str()) != 0)
752 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000753 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000754}
755
756bool
Reid Spencer5a060772006-08-23 07:30:48 +0000757Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000758 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000759 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattner74382b72009-08-23 22:45:37 +0000760 newName.str() + "'");
Reid Spencer5a060772006-08-23 07:30:48 +0000761 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000762}
763
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000764bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000765Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000766 struct utimbuf utb;
767 utb.actime = si.modTime.toPosixTime();
768 utb.modtime = utb.actime;
769 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000770 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000771 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000772 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000773 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000774}
775
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000776bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000777sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000778 int inFile = -1;
779 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000780 inFile = ::open(Src.c_str(), O_RDONLY);
781 if (inFile == -1)
Chris Lattner74382b72009-08-23 22:45:37 +0000782 return MakeErrMsg(ErrMsg, Src.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000783 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000784
Reid Spencer51c5a282006-08-23 20:34:57 +0000785 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
786 if (outFile == -1) {
787 ::close(inFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000788 return MakeErrMsg(ErrMsg, Dest.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000789 ": can't create destination file for copy");
790 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000791
Reid Spencer51c5a282006-08-23 20:34:57 +0000792 char Buffer[16*1024];
793 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
794 if (Amt == -1) {
795 if (errno != EINTR && errno != EAGAIN) {
796 ::close(inFile);
797 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000798 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Reid Spencer51c5a282006-08-23 20:34:57 +0000799 }
800 } else {
801 char *BufPtr = Buffer;
802 while (Amt) {
803 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
804 if (AmtWritten == -1) {
805 if (errno != EINTR && errno != EAGAIN) {
806 ::close(inFile);
807 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000808 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000809 ": can't write destination file");
Reid Spencerc29befb2004-12-15 01:50:13 +0000810 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000811 } else {
812 Amt -= AmtWritten;
813 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000814 }
815 }
816 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000817 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000818 ::close(inFile);
819 ::close(outFile);
820 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000821}
822
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000823bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000824Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Michael J. Spencer54453f22011-01-10 02:34:23 +0000825 bool Exists;
826 if (reuse_current && (fs::exists(path, Exists) || !Exists))
Reid Spencer51c5a282006-08-23 20:34:57 +0000827 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000828
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000829 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerc29befb2004-12-15 01:50:13 +0000830 // mktemp or our own implementation.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000831 // This uses std::vector instead of SmallVector to avoid a dependence on
832 // libSupport. And performance isn't critical here.
833 std::vector<char> Buf;
834 Buf.resize(path.size()+8);
Dan Gohman17192a12010-04-19 16:33:28 +0000835 char *FNBuffer = &Buf[0];
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000836 path.copy(FNBuffer,path.size());
Michael J. Spencer218dc3e2011-01-11 01:21:55 +0000837 bool isdir;
838 if (!fs::is_directory(path, isdir) && isdir)
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000839 strcpy(FNBuffer+path.size(), "/XXXXXX");
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000840 else
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000841 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerc29befb2004-12-15 01:50:13 +0000842
843#if defined(HAVE_MKSTEMP)
844 int TempFD;
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000845 if ((TempFD = mkstemp(FNBuffer)) == -1)
Reid Spencer51c5a282006-08-23 20:34:57 +0000846 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000847
848 // We don't need to hold the temp file descriptor... we will trust that no one
849 // will overwrite/delete the file before we can open it again.
850 close(TempFD);
851
852 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000853 path = FNBuffer;
Chad Rosier338398a2011-07-05 18:55:31 +0000854
855 // By default mkstemp sets the mode to 0600, so update mode bits now.
856 AddPermissionBits (*this, 0666);
Reid Spencerc29befb2004-12-15 01:50:13 +0000857#elif defined(HAVE_MKTEMP)
858 // If we don't have mkstemp, use the old and obsolete mktemp function.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000859 if (mktemp(FNBuffer) == 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000860 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000861
862 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000863 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000864#else
865 // Okay, looks like we have to do it all by our lonesome.
866 static unsigned FCounter = 0;
Chris Lattner1f011092010-07-12 00:09:55 +0000867 // Try to initialize with unique value.
868 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
869 char* pos = strstr(FNBuffer, "XXXXXX");
870 do {
871 if (++FCounter > 0xFFFFFF) {
872 return MakeErrMsg(ErrMsg,
873 path + ": can't make unique filename: too many files");
874 }
875 sprintf(pos, "%06X", FCounter);
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000876 path = FNBuffer;
Chris Lattner1f011092010-07-12 00:09:55 +0000877 } while (exists());
878 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
879 // LLVM.
Reid Spencerc29befb2004-12-15 01:50:13 +0000880#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000881 return false;
882}
Reid Spencerc29befb2004-12-15 01:50:13 +0000883
Rafael Espindolaf7fdad12011-03-10 18:33:29 +0000884const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000885 int Flags = MAP_PRIVATE;
886#ifdef MAP_FILE
887 Flags |= MAP_FILE;
888#endif
Rafael Espindolaf7fdad12011-03-10 18:33:29 +0000889 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, Offset);
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000890 if (BasePtr == MAP_FAILED)
891 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000892 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000893}
894
Rafael Espindolaf7fdad12011-03-10 18:33:29 +0000895void Path::UnMapFilePages(const char *BasePtr, size_t FileSize) {
Galina Kistanovad8975992012-07-12 20:45:36 +0000896 const void *Addr = static_cast<const void *>(BasePtr);
897 ::munmap(const_cast<void *>(Addr), FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000898}
899
Reid Spencer51c5a282006-08-23 20:34:57 +0000900} // end llvm namespace