blob: a8ae1a756b43121658169b50503b41ebffa014d3 [file] [log] [blame]
Reid Spencerb89a2232004-08-25 06:20:07 +00001//===- llvm/System/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
Reid Spencer932e2e32005-06-02 05:38:20 +000063// Put in a hack for Cygwin which falsely reports that the mkdtemp function
64// is available when it is not.
65#ifdef __CYGWIN__
66# undef HAVE_MKDTEMP
67#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000068
Reid Spencer3be872e2005-07-28 16:25:57 +000069namespace {
70inline bool lastIsSlash(const std::string& path) {
71 return !path.empty() && path[path.length() - 1] == '/';
72}
73
74}
75
Reid Spencer8e665952004-08-29 05:24:01 +000076namespace llvm {
77using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000078
Daniel Dunbar164c7ba2009-12-09 03:26:33 +000079const char sys::PathSeparator = ':';
Chris Lattnere1b332a2008-02-27 06:17:10 +000080
Mikhail Glushenkovf5a95ce2010-11-02 20:32:26 +000081StringRef Path::GetEXESuffix() {
Dan Gohman8eeb5ae2010-11-02 20:52:47 +000082 return StringRef();
Mikhail Glushenkovf5a95ce2010-11-02 20:32:26 +000083}
84
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +000085Path::Path(StringRef p)
Nick Lewyckyfff116f2008-05-11 17:37:40 +000086 : path(p) {}
87
88Path::Path(const char *StrStart, unsigned StrLen)
89 : path(StrStart, StrLen) {}
90
Chris Lattner0eab5e22008-08-11 23:39:47 +000091Path&
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +000092Path::operator=(StringRef that) {
93 path.assign(that.data(), that.size());
Chris Lattner0eab5e22008-08-11 23:39:47 +000094 return *this;
95}
96
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +000097bool
Reid Spencer69a16162004-12-24 06:29:42 +000098Path::isValid() const {
Dan Gohmanac793822010-11-02 23:19:55 +000099 // Empty paths are considered invalid here.
100 // This code doesn't check MAXPATHLEN because there's no need. Nothing in
101 // LLVM manipulates Paths with fixed-sizes arrays, and if the OS can't
102 // handle names longer than some limit, it'll report this on demand using
103 // ENAMETOLONG.
104 return !path.empty();
Reid Spencer69a16162004-12-24 06:29:42 +0000105}
106
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000107bool
Chris Lattner88d7e402009-06-15 04:17:07 +0000108Path::isAbsolute(const char *NameStart, unsigned NameLen) {
109 assert(NameStart);
110 if (NameLen == 0)
111 return false;
112 return NameStart[0] == '/';
113}
114
115bool
Reid Spencer69cce812007-03-29 16:43:20 +0000116Path::isAbsolute() const {
117 if (path.empty())
118 return false;
119 return path[0] == '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000120}
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000121
122void Path::makeAbsolute() {
123 if (isAbsolute())
124 return;
125
126 Path CWD = Path::GetCurrentDirectory();
127 assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
128
129 CWD.appendComponent(path);
130
Chris Lattner74382b72009-08-23 22:45:37 +0000131 path = CWD.str();
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000132}
133
Reid Spencer8e665952004-08-29 05:24:01 +0000134Path
135Path::GetRootDirectory() {
136 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000137 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000138 return result;
139}
140
Reid Spencer69a16162004-12-24 06:29:42 +0000141Path
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000142Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer69a16162004-12-24 06:29:42 +0000143#if defined(HAVE_MKDTEMP)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000144 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer69a16162004-12-24 06:29:42 +0000145 // Linux and FreeBSD have it. Others probably won't.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000146 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer48744762006-08-22 19:01:30 +0000147 if (0 == mkdtemp(pathname)) {
Dan Gohman6f6021e2010-11-02 22:56:51 +0000148 MakeErrMsg(ErrMsg,
149 std::string(pathname) + ": can't create temporary directory");
Reid Spencer48744762006-08-22 19:01:30 +0000150 return Path();
151 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000152 return Path(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000153#elif defined(HAVE_MKSTEMP)
154 // If no mkdtemp is available, mkstemp can be used to create a temporary file
155 // which is then removed and created as a directory. We prefer this over
156 // mktemp because of mktemp's inherent security and threading risks. We still
157 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000158 // the time it is re-created as a directoy.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000159 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer69a16162004-12-24 06:29:42 +0000160 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000161 if (-1 == (fd = mkstemp(pathname))) {
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 }
Reid Spencer69a16162004-12-24 06:29:42 +0000166 ::close(fd);
167 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000168 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000169 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000170 std::string(pathname) + ": can't create temporary directory");
171 return Path();
172 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000173 return Path(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000174#elif defined(HAVE_MKTEMP)
175 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
176 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
177 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
178 // the XXXXXX with the pid of the process and a letter. That leads to only
179 // twenty six temporary files that can be generated.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000180 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer69a16162004-12-24 06:29:42 +0000181 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000182 if (TmpName == 0) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000183 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000184 std::string(TmpName) + ": can't create unique directory name");
185 return Path();
186 }
187 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000188 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000189 std::string(TmpName) + ": can't create temporary directory");
190 return Path();
191 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000192 return Path(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000193#else
194 // This is the worst case implementation. tempnam(3) leaks memory unless its
195 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
196 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000197 // temporary name generated. So, we provide our own implementation that
Reid Spencer69a16162004-12-24 06:29:42 +0000198 // increments an integer from a random number seeded by the current time. This
199 // should be sufficiently unique that we don't have many collisions between
200 // processes. Generally LLVM processes don't run very long and don't use very
201 // many temporary files so this shouldn't be a big issue for LLVM.
202 static time_t num = ::time(0);
203 char pathname[MAXPATHLEN];
204 do {
205 num++;
206 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
207 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000208 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000209 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000210 std::string(pathname) + ": can't create temporary directory");
211 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000212 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000213 return Path(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000214#endif
215}
216
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000217void
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000218Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
219#ifdef LTDL_SHLIBPATH_VAR
220 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
221 if (env_var != 0) {
222 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000223 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000224#endif
225 // FIXME: Should this look at LD_LIBRARY_PATH too?
226 Paths.push_back(sys::Path("/usr/local/lib/"));
227 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
228 Paths.push_back(sys::Path("/usr/lib/"));
229 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000230}
231
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000232void
Gabor Greifa99be512007-07-05 17:07:56 +0000233Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000234 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
235 if (env_var != 0) {
236 getPathList(env_var,Paths);
237 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000238#ifdef LLVM_LIBDIR
239 {
240 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000241 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000242 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000243 Paths.push_back(tmpPath);
244 }
245#endif
246 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000247}
248
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000249Path
Reid Spencer8e665952004-08-29 05:24:01 +0000250Path::GetLLVMDefaultConfigDir() {
251 return Path("/etc/llvm/");
252}
253
Reid Spencer8e665952004-08-29 05:24:01 +0000254Path
255Path::GetUserHomeDirectory() {
256 const char* home = getenv("HOME");
257 if (home) {
258 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000259 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000260 return result;
261 }
262 return GetRootDirectory();
263}
264
Ted Kremenek79200782007-12-18 22:07:33 +0000265Path
266Path::GetCurrentDirectory() {
267 char pathname[MAXPATHLEN];
268 if (!getcwd(pathname,MAXPATHLEN)) {
269 assert (false && "Could not query current working directory.");
Dan Gohmand98af0a2010-08-04 01:39:08 +0000270 return Path();
Ted Kremenek79200782007-12-18 22:07:33 +0000271 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000272
Ted Kremenek79200782007-12-18 22:07:33 +0000273 return Path(pathname);
274}
Reid Spencera229c5c2005-07-08 03:08:58 +0000275
Dan Gohman86759ac2010-09-02 18:24:46 +0000276#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
Chris Lattner893a0f92009-03-02 22:17:15 +0000277static int
278test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
279 const char *dir, const char *bin)
280{
Bill Wendling51b16f42009-05-30 01:09:53 +0000281 struct stat sb;
Chris Lattner893a0f92009-03-02 22:17:15 +0000282
Dan Gohman86759ac2010-09-02 18:24:46 +0000283 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
Bill Wendling51b16f42009-05-30 01:09:53 +0000284 if (realpath(buf, ret) == NULL)
285 return (1);
286 if (stat(buf, &sb) != 0)
287 return (1);
288
289 return (0);
Chris Lattner893a0f92009-03-02 22:17:15 +0000290}
291
292static char *
293getprogpath(char ret[PATH_MAX], const char *bin)
294{
Bill Wendling51b16f42009-05-30 01:09:53 +0000295 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner893a0f92009-03-02 22:17:15 +0000296
Bill Wendling51b16f42009-05-30 01:09:53 +0000297 /* First approach: absolute path. */
298 if (bin[0] == '/') {
299 if (test_dir(buf, ret, "/", bin) == 0)
300 return (ret);
301 return (NULL);
302 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000303
Bill Wendling51b16f42009-05-30 01:09:53 +0000304 /* Second approach: relative path. */
305 if (strchr(bin, '/') != NULL) {
306 if (getcwd(buf, PATH_MAX) == NULL)
307 return (NULL);
308 if (test_dir(buf, ret, buf, bin) == 0)
309 return (ret);
310 return (NULL);
311 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000312
Bill Wendling51b16f42009-05-30 01:09:53 +0000313 /* Third approach: $PATH */
314 if ((pv = getenv("PATH")) == NULL)
315 return (NULL);
316 s = pv = strdup(pv);
317 if (pv == NULL)
318 return (NULL);
319 while ((t = strsep(&s, ":")) != NULL) {
320 if (test_dir(buf, ret, t, bin) == 0) {
321 free(pv);
322 return (ret);
323 }
324 }
325 free(pv);
326 return (NULL);
Chris Lattner893a0f92009-03-02 22:17:15 +0000327}
Anton Korobeynikov1d76ab72010-08-31 22:38:00 +0000328#endif // __FreeBSD__ || __NetBSD__
Chris Lattner893a0f92009-03-02 22:17:15 +0000329
Chris Lattner1a091442008-03-03 02:55:43 +0000330/// GetMainExecutable - Return the path to the main executable, given the
331/// value of argv[0] from program startup.
332Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000333#if defined(__APPLE__)
334 // On OS X the executable path is saved to the stack by dyld. Reading it
335 // from there is much faster than calling dladdr, especially for large
336 // binaries with symbols.
337 char exe_path[MAXPATHLEN];
338 uint32_t size = sizeof(exe_path);
339 if (_NSGetExecutablePath(exe_path, &size) == 0) {
340 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000341 if (realpath(exe_path, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000342 return Path(link_path);
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000343 }
Dan Gohman86759ac2010-09-02 18:24:46 +0000344#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
Chris Lattner893a0f92009-03-02 22:17:15 +0000345 char exe_path[PATH_MAX];
346
347 if (getprogpath(exe_path, argv0) != NULL)
Dan Gohman8d4fd962010-11-02 22:07:47 +0000348 return Path(exe_path);
Chris Lattner893a0f92009-03-02 22:17:15 +0000349#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattner3bdfa042008-03-13 05:22:05 +0000350 char exe_path[MAXPATHLEN];
Seo Sanghyeonfd6437f2008-06-27 22:55:30 +0000351 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Dan Gohman7b3544b2009-08-05 20:16:55 +0000352 if (len >= 0)
Dan Gohman8d4fd962010-11-02 22:07:47 +0000353 return Path(StringRef(exe_path, len));
Chris Lattner3bdfa042008-03-13 05:22:05 +0000354#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000355 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000356 Dl_info DLInfo;
357 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000358 if (err == 0)
359 return Path();
Bill Wendling51b16f42009-05-30 01:09:53 +0000360
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000361 // If the filename is a symlink, we need to resolve and return the location of
362 // the actual executable.
363 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000364 if (realpath(DLInfo.dli_fname, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000365 return Path(link_path);
Dan Gohmanb52d44a2010-09-07 18:26:49 +0000366#else
367#error GetMainExecutable is not implemented on this host yet.
Chris Lattner1a091442008-03-03 02:55:43 +0000368#endif
369 return Path();
370}
371
372
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000373StringRef Path::getDirname() const {
374 return getDirnameCharSep(path, "/");
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000375}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000376
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000377StringRef
Reid Spencer07adb282004-11-05 22:15:36 +0000378Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000379 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000380 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000381 if (slash == std::string::npos)
382 slash = 0;
383 else
384 slash++;
385
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000386 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000387 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000388 return StringRef(path).substr(slash);
Jeff Cohen73f36672005-07-09 18:42:02 +0000389 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000390 return StringRef(path).substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000391}
392
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000393StringRef
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000394Path::getSuffix() const {
395 // Find the last slash
396 std::string::size_type slash = path.rfind('/');
397 if (slash == std::string::npos)
398 slash = 0;
399 else
400 slash++;
401
402 std::string::size_type dot = path.rfind('.');
403 if (dot == std::string::npos || dot < slash)
Dan Gohmand98af0a2010-08-04 01:39:08 +0000404 return StringRef();
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000405 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000406 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000407}
408
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000409bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000410 assert(len < 1024 && "Request for magic string too long");
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000411 char Buf[1025];
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000412 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000413 if (fd < 0)
414 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000415 ssize_t bytes_read = ::read(fd, Buf, len);
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000416 ::close(fd);
Dan Gohman02d58242010-05-27 17:14:10 +0000417 if (ssize_t(len) != bytes_read)
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000418 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000419 Magic.assign(Buf, len);
Reid Spencereaf18152004-11-14 22:08:36 +0000420 return true;
421}
422
Reid Spencer1b554b42004-09-11 04:55:08 +0000423bool
Reid Spencer8e665952004-08-29 05:24:01 +0000424Path::exists() const {
425 return 0 == access(path.c_str(), F_OK );
426}
427
428bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000429Path::isDirectory() const {
430 struct stat buf;
431 if (0 != stat(path.c_str(), &buf))
432 return false;
Evan Chenga98111c2010-10-07 22:05:57 +0000433 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
Ted Kremenekfd527112007-12-18 19:46:22 +0000434}
435
436bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000437Path::canRead() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000438 return 0 == access(path.c_str(), R_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000439}
440
441bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000442Path::canWrite() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000443 return 0 == access(path.c_str(), W_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000444}
445
446bool
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000447Path::isRegularFile() const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000448 // Get the status so we can determine if it's a file or directory
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000449 struct stat buf;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000450
Daniel Dunbar98e46d82009-11-24 19:03:33 +0000451 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000452 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000453
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000454 if (S_ISREG(buf.st_mode))
455 return true;
456
457 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000458}
459
460bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000461Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000462 if (0 != access(path.c_str(), R_OK | X_OK ))
463 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000464 struct stat buf;
465 if (0 != stat(path.c_str(), &buf))
466 return false;
467 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000468 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000469 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000470}
471
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000472StringRef
Reid Spencer8e665952004-08-29 05:24:01 +0000473Path::getLast() const {
474 // Find the last slash
475 size_t pos = path.rfind('/');
476
477 // Handle the corner cases
478 if (pos == std::string::npos)
479 return path;
480
481 // If the last character is a slash
482 if (pos == path.length()-1) {
483 // Find the second to last slash
484 size_t pos2 = path.rfind('/', pos-1);
485 if (pos2 == std::string::npos)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000486 return StringRef(path).substr(0,pos);
Reid Spencer8e665952004-08-29 05:24:01 +0000487 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000488 return StringRef(path).substr(pos2+1,pos-pos2-1);
Reid Spencer8e665952004-08-29 05:24:01 +0000489 }
490 // Return everything after the last slash
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000491 return StringRef(path).substr(pos+1);
Reid Spencer8e665952004-08-29 05:24:01 +0000492}
493
Reid Spencer2ae9d112007-04-07 18:52:17 +0000494const FileStatus *
495PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
496 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000497 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000498 if (0 != stat(path.c_str(), &buf)) {
499 MakeErrMsg(ErrStr, path + ": can't get status of file");
500 return 0;
501 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000502 status.fileSize = buf.st_size;
503 status.modTime.fromEpochTime(buf.st_mtime);
504 status.mode = buf.st_mode;
505 status.user = buf.st_uid;
506 status.group = buf.st_gid;
507 status.uniqueID = uint64_t(buf.st_ino);
508 status.isDir = S_ISDIR(buf.st_mode);
509 status.isFile = S_ISREG(buf.st_mode);
510 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000511 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000512 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000513}
514
Chris Lattner252ad032006-07-28 22:03:44 +0000515static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000516 // Get the umask value from the operating system. We want to use it
517 // when changing the file's permissions. Since calling umask() sets
518 // the umask and returns its old value, we must call it a second
519 // time to reset it to the user's preference.
520 int mask = umask(0777); // The arg. to umask is arbitrary.
521 umask(mask); // Restore the umask.
522
523 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000524 struct stat buf;
Chris Lattner74382b72009-08-23 22:45:37 +0000525 if (0 != stat(File.c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000526 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000527 // Change the file to have whichever permissions bits from 'bits'
528 // that the umask would not disable.
529 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
530 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000531 return true;
532}
533
Reid Spencere1647f42006-08-22 23:27:23 +0000534bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000535 if (!AddPermissionBits(*this, 0444))
Reid Spencer5a060772006-08-23 07:30:48 +0000536 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000537 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000538}
539
Reid Spencere1647f42006-08-22 23:27:23 +0000540bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000541 if (!AddPermissionBits(*this, 0222))
542 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000543 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000544}
545
Reid Spencere1647f42006-08-22 23:27:23 +0000546bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000547 if (!AddPermissionBits(*this, 0111))
548 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000549 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000550}
551
Reid Spencereaf18152004-11-14 22:08:36 +0000552bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000553Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000554 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000555 if (direntries == 0)
556 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000557
Reid Spencer3be872e2005-07-28 16:25:57 +0000558 std::string dirPath = path;
559 if (!lastIsSlash(dirPath))
560 dirPath += '/';
561
Reid Spencereaf18152004-11-14 22:08:36 +0000562 result.clear();
563 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000564 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000565 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000566 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000567 struct stat st;
568 if (0 != lstat(aPath.path.c_str(), &st)) {
569 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000570 continue; // dangling symlink -- ignore
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000571 return MakeErrMsg(ErrMsg,
Reid Spencer5a060772006-08-23 07:30:48 +0000572 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000573 }
Reid Spencerb608a812004-11-16 06:15:19 +0000574 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000575 }
Reid Spencereaf18152004-11-14 22:08:36 +0000576 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000577
Reid Spencereaf18152004-11-14 22:08:36 +0000578 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000579 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000580}
581
Reid Spencer8e665952004-08-29 05:24:01 +0000582bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000583Path::set(StringRef a_path) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000584 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000585 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000586 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000587 path = a_path;
Reid Spencer8e665952004-08-29 05:24:01 +0000588 return true;
589}
590
591bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000592Path::appendComponent(StringRef name) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000593 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000594 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000595 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000596 if (!lastIsSlash(path))
597 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000598 path += name;
Reid Spencer8e665952004-08-29 05:24:01 +0000599 return true;
600}
601
602bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000603Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000604 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000605 if (slashpos == 0 || slashpos == std::string::npos) {
606 path.erase();
607 return true;
608 }
Reid Spencer8e665952004-08-29 05:24:01 +0000609 if (slashpos == path.size() - 1)
610 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000611 if (slashpos == std::string::npos) {
612 path.erase();
613 return true;
614 }
Reid Spencer8e665952004-08-29 05:24:01 +0000615 path.erase(slashpos);
616 return true;
617}
618
619bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000620Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000621 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000622 size_t dotpos = path.rfind('.',path.size());
623 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000624 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000625 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000626 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000627 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000628 }
Reid Spencer8e665952004-08-29 05:24:01 +0000629 }
Jeff Cohen563a17f2005-07-08 04:49:16 +0000630 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000631}
632
Ted Kremenekc5412c52008-04-03 16:11:31 +0000633static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000634
Dan Gohman28daa102009-07-29 00:02:58 +0000635 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenekc5412c52008-04-03 16:11:31 +0000636 return false;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000637
Ted Kremenekc5412c52008-04-03 16:11:31 +0000638 if (create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000639
Ted Kremenekc5412c52008-04-03 16:11:31 +0000640 char* c = end;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000641
Ted Kremenekc5412c52008-04-03 16:11:31 +0000642 for (; c != beg; --c)
643 if (*c == '/') {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000644
Ted Kremenekc5412c52008-04-03 16:11:31 +0000645 // Recurse to handling the parent directory.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000646 *c = '\0';
Ted Kremenekc5412c52008-04-03 16:11:31 +0000647 bool x = createDirectoryHelper(beg, c, create_parents);
648 *c = '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000649
Ted Kremenekc5412c52008-04-03 16:11:31 +0000650 // Return if we encountered an error.
651 if (x)
652 return true;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000653
Ted Kremenekc5412c52008-04-03 16:11:31 +0000654 break;
655 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000656 }
657
Ted Kremenekc5412c52008-04-03 16:11:31 +0000658 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
659}
660
Reid Spencer8e665952004-08-29 05:24:01 +0000661bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000662Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000663 // Get a writeable copy of the path name
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000664 std::string pathname(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000665
666 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000667 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000668
Ted Kremenekc5412c52008-04-03 16:11:31 +0000669 if (pathname[lastchar] != '/')
670 ++lastchar;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000671
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000672 pathname[lastchar] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000673
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000674 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
Dan Gohman9e2e0c32010-11-02 23:16:26 +0000675 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000676
Reid Spencere5c9cb52006-08-23 00:39:35 +0000677 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000678}
679
680bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000681Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000682 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000683 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000684 if (fd < 0)
685 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000686 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000687 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000688}
689
Reid Spencer8e665952004-08-29 05:24:01 +0000690bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000691Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000692 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000693 if (makeUnique( reuse_current, ErrMsg ))
694 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000695
696 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000697 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000698 if (fd < 0)
Reid Spencer5a060772006-08-23 07:30:48 +0000699 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000700 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000701 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000702}
703
704bool
Chris Lattner0c332312006-07-28 22:29:50 +0000705Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000706 // Get the status so we can determine if it's a file or directory.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000707 struct stat buf;
708 if (0 != stat(path.c_str(), &buf)) {
709 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000710 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000711 }
712
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000713 // Note: this check catches strange situations. In all cases, LLVM should
714 // only be involved in the creation and deletion of regular files. This
715 // check ensures that what we're trying to erase is a regular file. It
716 // effectively prevents LLVM from erasing things like /dev/null, any block
717 // special file, or other things that aren't "regular" files.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000718 if (S_ISREG(buf.st_mode)) {
719 if (unlink(path.c_str()) != 0)
720 return MakeErrMsg(ErrStr, path + ": can't destroy file");
721 return false;
722 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000723
Reid Spencer2ae9d112007-04-07 18:52:17 +0000724 if (!S_ISDIR(buf.st_mode)) {
725 if (ErrStr) *ErrStr = "not a file or directory";
726 return true;
727 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000728
Chris Lattner0c332312006-07-28 22:29:50 +0000729 if (remove_contents) {
730 // Recursively descend the directory to remove its contents.
731 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov8eada622009-02-15 03:20:32 +0000732 if (system(cmd.c_str()) != 0) {
733 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
734 return true;
735 }
Chris Lattner0c332312006-07-28 22:29:50 +0000736 return false;
737 }
738
739 // Otherwise, try to just remove the one directory.
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000740 std::string pathname(path);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000741 size_t lastchar = path.length() - 1;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000742 if (pathname[lastchar] == '/')
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000743 pathname[lastchar] = '\0';
Chris Lattner0c332312006-07-28 22:29:50 +0000744 else
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000745 pathname[lastchar+1] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000746
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000747 if (rmdir(pathname.c_str()) != 0)
748 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000749 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000750}
751
752bool
Reid Spencer5a060772006-08-23 07:30:48 +0000753Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000754 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000755 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattner74382b72009-08-23 22:45:37 +0000756 newName.str() + "'");
Reid Spencer5a060772006-08-23 07:30:48 +0000757 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000758}
759
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000760bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000761Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000762 struct utimbuf utb;
763 utb.actime = si.modTime.toPosixTime();
764 utb.modtime = utb.actime;
765 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000766 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000767 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000768 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000769 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000770}
771
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000772bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000773sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000774 int inFile = -1;
775 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000776 inFile = ::open(Src.c_str(), O_RDONLY);
777 if (inFile == -1)
Chris Lattner74382b72009-08-23 22:45:37 +0000778 return MakeErrMsg(ErrMsg, Src.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000779 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000780
Reid Spencer51c5a282006-08-23 20:34:57 +0000781 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
782 if (outFile == -1) {
783 ::close(inFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000784 return MakeErrMsg(ErrMsg, Dest.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000785 ": can't create destination file for copy");
786 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000787
Reid Spencer51c5a282006-08-23 20:34:57 +0000788 char Buffer[16*1024];
789 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
790 if (Amt == -1) {
791 if (errno != EINTR && errno != EAGAIN) {
792 ::close(inFile);
793 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000794 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Reid Spencer51c5a282006-08-23 20:34:57 +0000795 }
796 } else {
797 char *BufPtr = Buffer;
798 while (Amt) {
799 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
800 if (AmtWritten == -1) {
801 if (errno != EINTR && errno != EAGAIN) {
802 ::close(inFile);
803 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000804 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000805 ": can't write destination file");
Reid Spencerc29befb2004-12-15 01:50:13 +0000806 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000807 } else {
808 Amt -= AmtWritten;
809 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000810 }
811 }
812 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000813 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000814 ::close(inFile);
815 ::close(outFile);
816 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000817}
818
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000819bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000820Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000821 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000822 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000823
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000824 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerc29befb2004-12-15 01:50:13 +0000825 // mktemp or our own implementation.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000826 // This uses std::vector instead of SmallVector to avoid a dependence on
827 // libSupport. And performance isn't critical here.
828 std::vector<char> Buf;
829 Buf.resize(path.size()+8);
Dan Gohman17192a12010-04-19 16:33:28 +0000830 char *FNBuffer = &Buf[0];
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000831 path.copy(FNBuffer,path.size());
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000832 if (isDirectory())
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000833 strcpy(FNBuffer+path.size(), "/XXXXXX");
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000834 else
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000835 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerc29befb2004-12-15 01:50:13 +0000836
837#if defined(HAVE_MKSTEMP)
838 int TempFD;
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000839 if ((TempFD = mkstemp(FNBuffer)) == -1)
Reid Spencer51c5a282006-08-23 20:34:57 +0000840 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000841
842 // We don't need to hold the temp file descriptor... we will trust that no one
843 // will overwrite/delete the file before we can open it again.
844 close(TempFD);
845
846 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000847 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000848#elif defined(HAVE_MKTEMP)
849 // If we don't have mkstemp, use the old and obsolete mktemp function.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000850 if (mktemp(FNBuffer) == 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000851 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000852
853 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000854 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000855#else
856 // Okay, looks like we have to do it all by our lonesome.
857 static unsigned FCounter = 0;
Chris Lattner1f011092010-07-12 00:09:55 +0000858 // Try to initialize with unique value.
859 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
860 char* pos = strstr(FNBuffer, "XXXXXX");
861 do {
862 if (++FCounter > 0xFFFFFF) {
863 return MakeErrMsg(ErrMsg,
864 path + ": can't make unique filename: too many files");
865 }
866 sprintf(pos, "%06X", FCounter);
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000867 path = FNBuffer;
Chris Lattner1f011092010-07-12 00:09:55 +0000868 } while (exists());
869 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
870 // LLVM.
Reid Spencerc29befb2004-12-15 01:50:13 +0000871#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000872 return false;
873}
Reid Spencerc29befb2004-12-15 01:50:13 +0000874
Chris Lattner799ed102008-04-01 06:00:12 +0000875const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000876 int Flags = MAP_PRIVATE;
877#ifdef MAP_FILE
878 Flags |= MAP_FILE;
879#endif
880 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
881 if (BasePtr == MAP_FAILED)
882 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000883 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000884}
885
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000886void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000887 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000888}
889
Reid Spencer51c5a282006-08-23 20:34:57 +0000890} // end llvm namespace