blob: 418dc0733499d56fd0af10adc21c65b0a695378f [file] [log] [blame]
Charles Davis54c9eb62010-11-29 19:44:50 +00001//===- llvm/Support/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
Mikhail Glushenkova5398362009-02-15 03:20:03 +00002//
Reid Spencer814ba572004-08-25 06:20:07 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Glushenkova5398362009-02-15 03:20:03 +00007//
Reid Spencer814ba572004-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 Spencer6df221d2004-08-29 05:24:01 +000016//=== is guaranteed to work on *all* UNIX variants.
Reid Spencer814ba572004-08-25 06:20:07 +000017//===----------------------------------------------------------------------===//
18
19#include "Unix.h"
Reid Spencerd103e082004-12-27 06:17:15 +000020#if HAVE_SYS_STAT_H
Reid Spencer814ba572004-08-25 06:20:07 +000021#include <sys/stat.h>
Reid Spencerd103e082004-12-27 06:17:15 +000022#endif
23#if HAVE_FCNTL_H
Reid Spencer814ba572004-08-25 06:20:07 +000024#include <fcntl.h>
Reid Spencerd103e082004-12-27 06:17:15 +000025#endif
Chris Lattnerba98fca2008-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 Spencerd103e082004-12-27 06:17:15 +000032#if HAVE_UTIME_H
Reid Spencerc1d474f2004-11-14 22:08:36 +000033#include <utime.h>
Reid Spencerd103e082004-12-27 06:17:15 +000034#endif
35#if HAVE_TIME_H
Reid Spencer20540312004-12-24 06:29:42 +000036#include <time.h>
Reid Spencerd103e082004-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 Lattnere209be42008-03-03 02:55:43 +000055#if HAVE_DLFCN_H
56#include <dlfcn.h>
57#endif
58
Benjamin Kramer2a1131a2009-09-09 12:09:08 +000059#ifdef __APPLE__
60#include <mach-o/dyld.h>
61#endif
62
Reid Spencerd1ef1df2005-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 Spencer814ba572004-08-25 06:20:07 +000068
Reid Spencer29f83e02005-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 Spencer6df221d2004-08-29 05:24:01 +000076namespace llvm {
77using namespace sys;
Reid Spencer814ba572004-08-25 06:20:07 +000078
Daniel Dunbar5ea62002009-12-09 03:26:33 +000079const char sys::PathSeparator = ':';
Chris Lattner6fca9382008-02-27 06:17:10 +000080
Mikhail Glushenkovfcfaf512010-11-02 20:32:26 +000081StringRef Path::GetEXESuffix() {
Dan Gohmanbba85852010-11-02 20:52:47 +000082 return StringRef();
Mikhail Glushenkovfcfaf512010-11-02 20:32:26 +000083}
84
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +000085Path::Path(StringRef p)
Nick Lewyckyc38c1712008-05-11 17:37:40 +000086 : path(p) {}
87
88Path::Path(const char *StrStart, unsigned StrLen)
89 : path(StrStart, StrLen) {}
90
Chris Lattnerb56e07e2008-08-11 23:39:47 +000091Path&
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +000092Path::operator=(StringRef that) {
93 path.assign(that.data(), that.size());
Chris Lattnerb56e07e2008-08-11 23:39:47 +000094 return *this;
95}
96
Mikhail Glushenkova5398362009-02-15 03:20:03 +000097bool
Reid Spencer20540312004-12-24 06:29:42 +000098Path::isValid() const {
Dan Gohmanc0a8bee2010-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 Spencer20540312004-12-24 06:29:42 +0000105}
106
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000107bool
Chris Lattner3f556da2009-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 Spencer0f92f0e2007-03-29 16:43:20 +0000116Path::isAbsolute() const {
117 if (path.empty())
118 return false;
119 return path[0] == '/';
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000120}
Daniel Dunbardf555fd2009-07-12 20:23:56 +0000121
Reid Spencer6df221d2004-08-29 05:24:01 +0000122Path
123Path::GetRootDirectory() {
124 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000125 result.set("/");
Reid Spencer6df221d2004-08-29 05:24:01 +0000126 return result;
127}
128
Reid Spencer20540312004-12-24 06:29:42 +0000129Path
Chris Lattner3c50fdf2009-02-19 05:34:35 +0000130Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer20540312004-12-24 06:29:42 +0000131#if defined(HAVE_MKDTEMP)
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000132 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer20540312004-12-24 06:29:42 +0000133 // Linux and FreeBSD have it. Others probably won't.
Dan Gohman32d51fa2010-11-02 22:50:10 +0000134 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000135 if (0 == mkdtemp(pathname)) {
Dan Gohman6e05d6c2010-11-02 22:56:51 +0000136 MakeErrMsg(ErrMsg,
137 std::string(pathname) + ": can't create temporary directory");
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000138 return Path();
139 }
Dan Gohmanecc4d732010-11-03 00:01:23 +0000140 return Path(pathname);
Reid Spencer20540312004-12-24 06:29:42 +0000141#elif defined(HAVE_MKSTEMP)
142 // If no mkdtemp is available, mkstemp can be used to create a temporary file
143 // which is then removed and created as a directory. We prefer this over
144 // mktemp because of mktemp's inherent security and threading risks. We still
145 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000146 // the time it is re-created as a directoy.
Dan Gohman32d51fa2010-11-02 22:50:10 +0000147 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer20540312004-12-24 06:29:42 +0000148 int fd = 0;
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000149 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000150 MakeErrMsg(ErrMsg,
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000151 std::string(pathname) + ": can't create temporary directory");
152 return Path();
153 }
Reid Spencer20540312004-12-24 06:29:42 +0000154 ::close(fd);
155 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000156 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000157 MakeErrMsg(ErrMsg,
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000158 std::string(pathname) + ": can't create temporary directory");
159 return Path();
160 }
Dan Gohmanecc4d732010-11-03 00:01:23 +0000161 return Path(pathname);
Reid Spencer20540312004-12-24 06:29:42 +0000162#elif defined(HAVE_MKTEMP)
163 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
164 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
165 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
166 // the XXXXXX with the pid of the process and a letter. That leads to only
167 // twenty six temporary files that can be generated.
Dan Gohman32d51fa2010-11-02 22:50:10 +0000168 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer20540312004-12-24 06:29:42 +0000169 char *TmpName = ::mktemp(pathname);
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000170 if (TmpName == 0) {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000171 MakeErrMsg(ErrMsg,
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000172 std::string(TmpName) + ": can't create unique directory name");
173 return Path();
174 }
175 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000176 MakeErrMsg(ErrMsg,
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000177 std::string(TmpName) + ": can't create temporary directory");
178 return Path();
179 }
Dan Gohmanecc4d732010-11-03 00:01:23 +0000180 return Path(TmpName);
Reid Spencer20540312004-12-24 06:29:42 +0000181#else
182 // This is the worst case implementation. tempnam(3) leaks memory unless its
183 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
184 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000185 // temporary name generated. So, we provide our own implementation that
Reid Spencer20540312004-12-24 06:29:42 +0000186 // increments an integer from a random number seeded by the current time. This
187 // should be sufficiently unique that we don't have many collisions between
188 // processes. Generally LLVM processes don't run very long and don't use very
189 // many temporary files so this shouldn't be a big issue for LLVM.
190 static time_t num = ::time(0);
191 char pathname[MAXPATHLEN];
192 do {
193 num++;
194 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
195 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000196 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000197 MakeErrMsg(ErrMsg,
Reid Spencer6ba87bb2006-08-22 19:01:30 +0000198 std::string(pathname) + ": can't create temporary directory");
199 return Path();
Reid Spencere4ca7222006-08-23 20:34:57 +0000200 }
Dan Gohmanecc4d732010-11-03 00:01:23 +0000201 return Path(pathname);
Reid Spencer20540312004-12-24 06:29:42 +0000202#endif
203}
204
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000205void
Reid Spencer9b155dc2004-12-13 03:00:51 +0000206Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
207#ifdef LTDL_SHLIBPATH_VAR
208 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
209 if (env_var != 0) {
210 getPathList(env_var,Paths);
Reid Spencerdf05ec72004-09-14 00:16:39 +0000211 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000212#endif
213 // FIXME: Should this look at LD_LIBRARY_PATH too?
214 Paths.push_back(sys::Path("/usr/local/lib/"));
215 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
216 Paths.push_back(sys::Path("/usr/lib/"));
217 Paths.push_back(sys::Path("/lib/"));
Reid Spencerdf05ec72004-09-14 00:16:39 +0000218}
219
Reid Spencer9b155dc2004-12-13 03:00:51 +0000220void
Gabor Greife16561c2007-07-05 17:07:56 +0000221Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer9b155dc2004-12-13 03:00:51 +0000222 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
223 if (env_var != 0) {
224 getPathList(env_var,Paths);
225 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000226#ifdef LLVM_LIBDIR
227 {
228 Path tmpPath;
Reid Spencerc9c04732005-07-07 23:21:43 +0000229 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencer5b891e92005-07-07 18:21:42 +0000230 if (tmpPath.canRead())
Reid Spencer9b155dc2004-12-13 03:00:51 +0000231 Paths.push_back(tmpPath);
232 }
233#endif
234 GetSystemLibraryPaths(Paths);
Reid Spencer6df221d2004-08-29 05:24:01 +0000235}
236
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000237Path
Reid Spencer6df221d2004-08-29 05:24:01 +0000238Path::GetUserHomeDirectory() {
239 const char* home = getenv("HOME");
Michael J. Spencer9e590022010-12-27 03:21:41 +0000240 Path result;
241 if (home && result.set(home))
242 return result;
243 result.set("/");
244 return result;
Reid Spencer6df221d2004-08-29 05:24:01 +0000245}
246
Ted Kremenek14020702007-12-18 22:07:33 +0000247Path
248Path::GetCurrentDirectory() {
249 char pathname[MAXPATHLEN];
Nick Lewycky38b9b562011-07-29 04:42:39 +0000250 if (!getcwd(pathname, MAXPATHLEN)) {
251 assert(false && "Could not query current working directory.");
Dan Gohman5cae1032010-08-04 01:39:08 +0000252 return Path();
Ted Kremenek14020702007-12-18 22:07:33 +0000253 }
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000254
Ted Kremenek14020702007-12-18 22:07:33 +0000255 return Path(pathname);
256}
Reid Spenceraf48d862005-07-08 03:08:58 +0000257
Chris Lattnerc37910e2011-02-18 17:04:56 +0000258#if defined(__FreeBSD__) || defined (__NetBSD__) || \
259 defined(__OpenBSD__) || defined(__minix)
Chris Lattnerbab44172009-03-02 22:17:15 +0000260static int
261test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
262 const char *dir, const char *bin)
263{
Bill Wendling09f17a82009-05-30 01:09:53 +0000264 struct stat sb;
Chris Lattnerbab44172009-03-02 22:17:15 +0000265
Dan Gohman9e857442010-09-02 18:24:46 +0000266 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
Bill Wendling09f17a82009-05-30 01:09:53 +0000267 if (realpath(buf, ret) == NULL)
268 return (1);
269 if (stat(buf, &sb) != 0)
270 return (1);
271
272 return (0);
Chris Lattnerbab44172009-03-02 22:17:15 +0000273}
274
275static char *
276getprogpath(char ret[PATH_MAX], const char *bin)
277{
Bill Wendling09f17a82009-05-30 01:09:53 +0000278 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattnerbab44172009-03-02 22:17:15 +0000279
Bill Wendling09f17a82009-05-30 01:09:53 +0000280 /* First approach: absolute path. */
281 if (bin[0] == '/') {
282 if (test_dir(buf, ret, "/", bin) == 0)
283 return (ret);
284 return (NULL);
285 }
Chris Lattnerbab44172009-03-02 22:17:15 +0000286
Bill Wendling09f17a82009-05-30 01:09:53 +0000287 /* Second approach: relative path. */
288 if (strchr(bin, '/') != NULL) {
289 if (getcwd(buf, PATH_MAX) == NULL)
290 return (NULL);
291 if (test_dir(buf, ret, buf, bin) == 0)
292 return (ret);
293 return (NULL);
294 }
Chris Lattnerbab44172009-03-02 22:17:15 +0000295
Bill Wendling09f17a82009-05-30 01:09:53 +0000296 /* Third approach: $PATH */
297 if ((pv = getenv("PATH")) == NULL)
298 return (NULL);
299 s = pv = strdup(pv);
300 if (pv == NULL)
301 return (NULL);
302 while ((t = strsep(&s, ":")) != NULL) {
303 if (test_dir(buf, ret, t, bin) == 0) {
304 free(pv);
305 return (ret);
306 }
307 }
308 free(pv);
309 return (NULL);
Chris Lattnerbab44172009-03-02 22:17:15 +0000310}
Anton Korobeynikov4e7351d2010-08-31 22:38:00 +0000311#endif // __FreeBSD__ || __NetBSD__
Chris Lattnerbab44172009-03-02 22:17:15 +0000312
Chris Lattnere209be42008-03-03 02:55:43 +0000313/// GetMainExecutable - Return the path to the main executable, given the
314/// value of argv[0] from program startup.
315Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramer2a1131a2009-09-09 12:09:08 +0000316#if defined(__APPLE__)
317 // On OS X the executable path is saved to the stack by dyld. Reading it
318 // from there is much faster than calling dladdr, especially for large
319 // binaries with symbols.
320 char exe_path[MAXPATHLEN];
321 uint32_t size = sizeof(exe_path);
322 if (_NSGetExecutablePath(exe_path, &size) == 0) {
323 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnam4b9f0b62009-11-29 17:19:48 +0000324 if (realpath(exe_path, link_path))
Dan Gohman44e24e52010-11-02 22:07:47 +0000325 return Path(link_path);
Benjamin Kramer2a1131a2009-09-09 12:09:08 +0000326 }
Chris Lattnerc37910e2011-02-18 17:04:56 +0000327#elif defined(__FreeBSD__) || defined (__NetBSD__) || \
328 defined(__OpenBSD__) || defined(__minix)
Chris Lattnerbab44172009-03-02 22:17:15 +0000329 char exe_path[PATH_MAX];
330
331 if (getprogpath(exe_path, argv0) != NULL)
Dan Gohman44e24e52010-11-02 22:07:47 +0000332 return Path(exe_path);
Chris Lattnerbab44172009-03-02 22:17:15 +0000333#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattner02e727f2008-03-13 05:22:05 +0000334 char exe_path[MAXPATHLEN];
Seo Sanghyeon8f729132008-06-27 22:55:30 +0000335 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Dan Gohman798ae472009-08-05 20:16:55 +0000336 if (len >= 0)
Dan Gohman44e24e52010-11-02 22:07:47 +0000337 return Path(StringRef(exe_path, len));
Chris Lattner02e727f2008-03-13 05:22:05 +0000338#elif defined(HAVE_DLFCN_H)
Chris Lattnere209be42008-03-03 02:55:43 +0000339 // Use dladdr to get executable path if available.
Chris Lattnere209be42008-03-03 02:55:43 +0000340 Dl_info DLInfo;
341 int err = dladdr(MainAddr, &DLInfo);
Chris Lattner3c50fdf2009-02-19 05:34:35 +0000342 if (err == 0)
343 return Path();
Bill Wendling09f17a82009-05-30 01:09:53 +0000344
Chris Lattner3c50fdf2009-02-19 05:34:35 +0000345 // If the filename is a symlink, we need to resolve and return the location of
346 // the actual executable.
347 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnam4b9f0b62009-11-29 17:19:48 +0000348 if (realpath(DLInfo.dli_fname, link_path))
Dan Gohman44e24e52010-11-02 22:07:47 +0000349 return Path(link_path);
Dan Gohmand51b4312010-09-07 18:26:49 +0000350#else
351#error GetMainExecutable is not implemented on this host yet.
Chris Lattnere209be42008-03-03 02:55:43 +0000352#endif
353 return Path();
354}
355
356
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000357StringRef Path::getDirname() const {
358 return getDirnameCharSep(path, "/");
Ted Kremeneka518bb72008-04-07 22:01:32 +0000359}
Ted Kremenekc042bf12008-04-07 21:53:57 +0000360
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000361StringRef
Reid Spencer0c6a2832004-11-05 22:15:36 +0000362Path::getBasename() const {
Reid Spencerae9bbda2004-09-11 04:55:08 +0000363 // Find the last slash
Ted Kremenekc042bf12008-04-07 21:53:57 +0000364 std::string::size_type slash = path.rfind('/');
Reid Spencerae9bbda2004-09-11 04:55:08 +0000365 if (slash == std::string::npos)
366 slash = 0;
367 else
368 slash++;
369
Ted Kremenekc042bf12008-04-07 21:53:57 +0000370 std::string::size_type dot = path.rfind('.');
Jeff Cohen5b106d02005-07-09 18:42:02 +0000371 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000372 return StringRef(path).substr(slash);
Jeff Cohen5b106d02005-07-09 18:42:02 +0000373 else
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000374 return StringRef(path).substr(slash, dot - slash);
Reid Spencerae9bbda2004-09-11 04:55:08 +0000375}
376
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000377StringRef
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000378Path::getSuffix() const {
379 // Find the last slash
380 std::string::size_type slash = path.rfind('/');
381 if (slash == std::string::npos)
382 slash = 0;
383 else
384 slash++;
385
386 std::string::size_type dot = path.rfind('.');
387 if (dot == std::string::npos || dot < slash)
Dan Gohman5cae1032010-08-04 01:39:08 +0000388 return StringRef();
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000389 else
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000390 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidis2cc0abf2008-06-15 15:15:19 +0000391}
392
Chris Lattnere6be8562009-12-16 08:35:54 +0000393bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000394 assert(len < 1024 && "Request for magic string too long");
Chris Lattnere6be8562009-12-16 08:35:54 +0000395 char Buf[1025];
Chris Lattnerbe119d42006-08-01 17:51:09 +0000396 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000397 if (fd < 0)
398 return false;
Chris Lattnere6be8562009-12-16 08:35:54 +0000399 ssize_t bytes_read = ::read(fd, Buf, len);
Reid Spencerf4731852004-12-02 09:09:48 +0000400 ::close(fd);
Dan Gohman78d1e842010-05-27 17:14:10 +0000401 if (ssize_t(len) != bytes_read)
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000402 return false;
Chris Lattnere6be8562009-12-16 08:35:54 +0000403 Magic.assign(Buf, len);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000404 return true;
405}
406
Reid Spencerae9bbda2004-09-11 04:55:08 +0000407bool
Reid Spencer6df221d2004-08-29 05:24:01 +0000408Path::exists() const {
409 return 0 == access(path.c_str(), F_OK );
410}
411
412bool
Ted Kremenek74db0422007-12-18 19:46:22 +0000413Path::isDirectory() const {
414 struct stat buf;
415 if (0 != stat(path.c_str(), &buf))
416 return false;
Evan Cheng139edad2010-10-07 22:05:57 +0000417 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
Ted Kremenek74db0422007-12-18 19:46:22 +0000418}
419
420bool
Rafael Espindola559b8fb2010-11-07 04:36:50 +0000421Path::isSymLink() const {
422 struct stat buf;
423 if (0 != lstat(path.c_str(), &buf))
424 return false;
425 return S_ISLNK(buf.st_mode);
426}
427
428
429bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000430Path::canRead() const {
Dan Gohman36700652009-07-28 23:22:01 +0000431 return 0 == access(path.c_str(), R_OK);
Reid Spencer6df221d2004-08-29 05:24:01 +0000432}
433
434bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000435Path::canWrite() const {
Dan Gohman36700652009-07-28 23:22:01 +0000436 return 0 == access(path.c_str(), W_OK);
Reid Spencer6df221d2004-08-29 05:24:01 +0000437}
438
439bool
Edward O'Callaghan746782d2009-11-25 06:32:19 +0000440Path::isRegularFile() const {
Dan Gohman39027c42010-03-30 20:04:57 +0000441 // Get the status so we can determine if it's a file or directory
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000442 struct stat buf;
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000443
Daniel Dunbar7402c472009-11-24 19:03:33 +0000444 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000445 return false;
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000446
Edward O'Callaghan746782d2009-11-25 06:32:19 +0000447 if (S_ISREG(buf.st_mode))
448 return true;
449
450 return false;
Edward O'Callaghandddf1342009-11-24 15:19:10 +0000451}
452
453bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000454Path::canExecute() const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000455 if (0 != access(path.c_str(), R_OK | X_OK ))
456 return false;
Reid Spencerceeb9182007-04-07 18:52:17 +0000457 struct stat buf;
458 if (0 != stat(path.c_str(), &buf))
459 return false;
460 if (!S_ISREG(buf.st_mode))
Misha Brukmana9a8c1b2005-04-20 15:33:22 +0000461 return false;
Reid Spencer2d85f562005-07-08 17:46:10 +0000462 return true;
Reid Spencer6df221d2004-08-29 05:24:01 +0000463}
464
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000465StringRef
Reid Spencer6df221d2004-08-29 05:24:01 +0000466Path::getLast() const {
467 // Find the last slash
468 size_t pos = path.rfind('/');
469
470 // Handle the corner cases
471 if (pos == std::string::npos)
472 return path;
473
474 // If the last character is a slash
475 if (pos == path.length()-1) {
476 // Find the second to last slash
477 size_t pos2 = path.rfind('/', pos-1);
478 if (pos2 == std::string::npos)
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000479 return StringRef(path).substr(0,pos);
Reid Spencer6df221d2004-08-29 05:24:01 +0000480 else
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000481 return StringRef(path).substr(pos2+1,pos-pos2-1);
Reid Spencer6df221d2004-08-29 05:24:01 +0000482 }
483 // Return everything after the last slash
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000484 return StringRef(path).substr(pos+1);
Reid Spencer6df221d2004-08-29 05:24:01 +0000485}
486
Reid Spencerceeb9182007-04-07 18:52:17 +0000487const FileStatus *
488PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
489 if (!fsIsValid || update) {
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000490 struct stat buf;
Reid Spencer200c6f92007-03-29 19:05:44 +0000491 if (0 != stat(path.c_str(), &buf)) {
492 MakeErrMsg(ErrStr, path + ": can't get status of file");
493 return 0;
494 }
Reid Spencerceeb9182007-04-07 18:52:17 +0000495 status.fileSize = buf.st_size;
496 status.modTime.fromEpochTime(buf.st_mtime);
497 status.mode = buf.st_mode;
498 status.user = buf.st_uid;
499 status.group = buf.st_gid;
500 status.uniqueID = uint64_t(buf.st_ino);
501 status.isDir = S_ISDIR(buf.st_mode);
502 status.isFile = S_ISREG(buf.st_mode);
503 fsIsValid = true;
Reid Spencer0f92f0e2007-03-29 16:43:20 +0000504 }
Reid Spencerceeb9182007-04-07 18:52:17 +0000505 return &status;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000506}
507
Chris Lattner48572532006-07-28 22:03:44 +0000508static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer94bf2262004-12-13 19:59:50 +0000509 // Get the umask value from the operating system. We want to use it
510 // when changing the file's permissions. Since calling umask() sets
511 // the umask and returns its old value, we must call it a second
512 // time to reset it to the user's preference.
513 int mask = umask(0777); // The arg. to umask is arbitrary.
514 umask(mask); // Restore the umask.
515
516 // Get the file's current mode.
Reid Spencerceeb9182007-04-07 18:52:17 +0000517 struct stat buf;
Chris Lattnerc521f542009-08-23 22:45:37 +0000518 if (0 != stat(File.c_str(), &buf))
Reid Spencer94bf2262004-12-13 19:59:50 +0000519 return false;
Reid Spencerceeb9182007-04-07 18:52:17 +0000520 // Change the file to have whichever permissions bits from 'bits'
521 // that the umask would not disable.
522 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
523 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000524 return true;
525}
526
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000527bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000528 if (!AddPermissionBits(*this, 0444))
Reid Spencer879ed5a2006-08-23 07:30:48 +0000529 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000530 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000531}
532
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000533bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer879ed5a2006-08-23 07:30:48 +0000534 if (!AddPermissionBits(*this, 0222))
535 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000536 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000537}
538
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000539bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer879ed5a2006-08-23 07:30:48 +0000540 if (!AddPermissionBits(*this, 0111))
541 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencer9d2f19c2006-08-22 23:27:23 +0000542 return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000543}
544
Reid Spencerc1d474f2004-11-14 22:08:36 +0000545bool
Reid Spencer51edba12006-08-23 06:56:27 +0000546Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000547 DIR* direntries = ::opendir(path.c_str());
Reid Spencer879ed5a2006-08-23 07:30:48 +0000548 if (direntries == 0)
549 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencerc1d474f2004-11-14 22:08:36 +0000550
Reid Spencer29f83e02005-07-28 16:25:57 +0000551 std::string dirPath = path;
552 if (!lastIsSlash(dirPath))
553 dirPath += '/';
554
Reid Spencerc1d474f2004-11-14 22:08:36 +0000555 result.clear();
556 struct dirent* de = ::readdir(direntries);
Misha Brukman1001aea2005-04-20 04:04:07 +0000557 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000558 if (de->d_name[0] != '.') {
Reid Spencer29f83e02005-07-28 16:25:57 +0000559 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattner0b2890e2006-07-07 21:21:06 +0000560 struct stat st;
561 if (0 != lstat(aPath.path.c_str(), &st)) {
562 if (S_ISLNK(st.st_mode))
Misha Brukman1001aea2005-04-20 04:04:07 +0000563 continue; // dangling symlink -- ignore
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000564 return MakeErrMsg(ErrMsg,
Reid Spencer879ed5a2006-08-23 07:30:48 +0000565 aPath.path + ": can't determine file object type");
Misha Brukman1001aea2005-04-20 04:04:07 +0000566 }
Reid Spencer91f505e2004-11-16 06:15:19 +0000567 result.insert(aPath);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000568 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000569 }
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000570
Reid Spencerc1d474f2004-11-14 22:08:36 +0000571 closedir(direntries);
Reid Spencer51edba12006-08-23 06:56:27 +0000572 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000573}
574
Reid Spencer6df221d2004-08-29 05:24:01 +0000575bool
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000576Path::set(StringRef a_path) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000577 if (a_path.empty())
Reid Spencer6df221d2004-08-29 05:24:01 +0000578 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000579 path = a_path;
Reid Spencer6df221d2004-08-29 05:24:01 +0000580 return true;
581}
582
583bool
Jeffrey Yasskin5908f1e2009-12-17 21:02:39 +0000584Path::appendComponent(StringRef name) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000585 if (name.empty())
Reid Spencer6df221d2004-08-29 05:24:01 +0000586 return false;
Reid Spencer29f83e02005-07-28 16:25:57 +0000587 if (!lastIsSlash(path))
588 path += '/';
Reid Spencerc9c04732005-07-07 23:21:43 +0000589 path += name;
Reid Spencer6df221d2004-08-29 05:24:01 +0000590 return true;
591}
592
593bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000594Path::eraseComponent() {
Reid Spencer6df221d2004-08-29 05:24:01 +0000595 size_t slashpos = path.rfind('/',path.size());
Reid Spencerc9c04732005-07-07 23:21:43 +0000596 if (slashpos == 0 || slashpos == std::string::npos) {
597 path.erase();
598 return true;
599 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000600 if (slashpos == path.size() - 1)
601 slashpos = path.rfind('/',slashpos-1);
Reid Spencerc9c04732005-07-07 23:21:43 +0000602 if (slashpos == std::string::npos) {
603 path.erase();
604 return true;
605 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000606 path.erase(slashpos);
607 return true;
608}
609
610bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000611Path::eraseSuffix() {
Reid Spencer6df221d2004-08-29 05:24:01 +0000612 size_t dotpos = path.rfind('.',path.size());
613 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen4c241442005-07-08 04:49:16 +0000614 if (dotpos != std::string::npos) {
Jeff Cohen5b106d02005-07-09 18:42:02 +0000615 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen4c241442005-07-08 04:49:16 +0000616 path.erase(dotpos, path.size()-dotpos);
Jeff Cohenf5067762005-07-08 05:02:13 +0000617 return true;
Jeff Cohen4c241442005-07-08 04:49:16 +0000618 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000619 }
Jeff Cohen4c241442005-07-08 04:49:16 +0000620 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000621}
622
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000623static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000624
Dan Gohman4723c102009-07-29 00:02:58 +0000625 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000626 return false;
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000627
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000628 if (create_parents) {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000629
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000630 char* c = end;
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000631
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000632 for (; c != beg; --c)
633 if (*c == '/') {
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000634
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000635 // Recurse to handling the parent directory.
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000636 *c = '\0';
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000637 bool x = createDirectoryHelper(beg, c, create_parents);
638 *c = '/';
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000639
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000640 // Return if we encountered an error.
641 if (x)
642 return true;
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000643
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000644 break;
645 }
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000646 }
647
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000648 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
649}
650
Reid Spencer6df221d2004-08-29 05:24:01 +0000651bool
Reid Spencer8db84422006-08-23 00:39:35 +0000652Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000653 // Get a writeable copy of the path name
Dan Gohmana47bfef2010-11-02 22:55:34 +0000654 std::string pathname(path);
Reid Spencer6df221d2004-08-29 05:24:01 +0000655
656 // Null-terminate the last component
Evan Cheng86cb3182008-05-05 18:30:58 +0000657 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000658
Ted Kremenek1d0436c2008-04-03 16:11:31 +0000659 if (pathname[lastchar] != '/')
660 ++lastchar;
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000661
Dan Gohmanf6e13ce2010-11-02 22:41:19 +0000662 pathname[lastchar] = '\0';
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000663
Dan Gohmana47bfef2010-11-02 22:55:34 +0000664 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
Dan Gohmana8b63152010-11-02 23:16:26 +0000665 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000666
Reid Spencer8db84422006-08-23 00:39:35 +0000667 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000668}
669
670bool
Reid Spencer8db84422006-08-23 00:39:35 +0000671Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000672 // Create the file
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000673 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer879ed5a2006-08-23 07:30:48 +0000674 if (fd < 0)
675 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000676 ::close(fd);
Reid Spencer8db84422006-08-23 00:39:35 +0000677 return false;
Reid Spencer814ba572004-08-25 06:20:07 +0000678}
679
Reid Spencer6df221d2004-08-29 05:24:01 +0000680bool
Reid Spencer8db84422006-08-23 00:39:35 +0000681Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerf66d9322004-12-15 01:50:13 +0000682 // Make this into a unique file name
Reid Spencere4ca7222006-08-23 20:34:57 +0000683 if (makeUnique( reuse_current, ErrMsg ))
684 return true;
Reid Spencerf66d9322004-12-15 01:50:13 +0000685
686 // create the file
Reid Spencer8db84422006-08-23 00:39:35 +0000687 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000688 if (fd < 0)
Reid Spencer879ed5a2006-08-23 07:30:48 +0000689 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencer8db84422006-08-23 00:39:35 +0000690 ::close(fd);
Reid Spencerf66d9322004-12-15 01:50:13 +0000691 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000692}
693
694bool
Chris Lattner3cec1092006-07-28 22:29:50 +0000695Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Dan Gohman39027c42010-03-30 20:04:57 +0000696 // Get the status so we can determine if it's a file or directory.
Reid Spencerceeb9182007-04-07 18:52:17 +0000697 struct stat buf;
698 if (0 != stat(path.c_str(), &buf)) {
699 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner3cec1092006-07-28 22:29:50 +0000700 return true;
Reid Spencerceeb9182007-04-07 18:52:17 +0000701 }
702
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000703 // Note: this check catches strange situations. In all cases, LLVM should
704 // only be involved in the creation and deletion of regular files. This
705 // check ensures that what we're trying to erase is a regular file. It
706 // effectively prevents LLVM from erasing things like /dev/null, any block
707 // special file, or other things that aren't "regular" files.
Reid Spencerceeb9182007-04-07 18:52:17 +0000708 if (S_ISREG(buf.st_mode)) {
709 if (unlink(path.c_str()) != 0)
710 return MakeErrMsg(ErrStr, path + ": can't destroy file");
711 return false;
712 }
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000713
Reid Spencerceeb9182007-04-07 18:52:17 +0000714 if (!S_ISDIR(buf.st_mode)) {
715 if (ErrStr) *ErrStr = "not a file or directory";
716 return true;
717 }
Reid Spencer200c6f92007-03-29 19:05:44 +0000718
Chris Lattner3cec1092006-07-28 22:29:50 +0000719 if (remove_contents) {
720 // Recursively descend the directory to remove its contents.
721 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov58a1a8e2009-02-15 03:20:32 +0000722 if (system(cmd.c_str()) != 0) {
723 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
724 return true;
725 }
Chris Lattner3cec1092006-07-28 22:29:50 +0000726 return false;
727 }
728
729 // Otherwise, try to just remove the one directory.
Dan Gohmana47bfef2010-11-02 22:55:34 +0000730 std::string pathname(path);
Evan Cheng86cb3182008-05-05 18:30:58 +0000731 size_t lastchar = path.length() - 1;
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000732 if (pathname[lastchar] == '/')
Dan Gohmanf6e13ce2010-11-02 22:41:19 +0000733 pathname[lastchar] = '\0';
Chris Lattner3cec1092006-07-28 22:29:50 +0000734 else
Dan Gohmanf6e13ce2010-11-02 22:41:19 +0000735 pathname[lastchar+1] = '\0';
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000736
Dan Gohmana47bfef2010-11-02 22:55:34 +0000737 if (rmdir(pathname.c_str()) != 0)
738 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
Chris Lattner3cec1092006-07-28 22:29:50 +0000739 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000740}
741
742bool
Reid Spencer879ed5a2006-08-23 07:30:48 +0000743Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000744 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000745 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattnerc521f542009-08-23 22:45:37 +0000746 newName.str() + "'");
Reid Spencer879ed5a2006-08-23 07:30:48 +0000747 return false;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000748}
749
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000750bool
Chris Lattner60c50642006-07-28 22:36:17 +0000751Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000752 struct utimbuf utb;
753 utb.actime = si.modTime.toPosixTime();
754 utb.modtime = utb.actime;
755 if (0 != ::utime(path.c_str(),&utb))
Reid Spencere4ca7222006-08-23 20:34:57 +0000756 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencerc1d474f2004-11-14 22:08:36 +0000757 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencere4ca7222006-08-23 20:34:57 +0000758 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner60c50642006-07-28 22:36:17 +0000759 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000760}
761
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000762bool
Reid Spencere4ca7222006-08-23 20:34:57 +0000763sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerf66d9322004-12-15 01:50:13 +0000764 int inFile = -1;
765 int outFile = -1;
Reid Spencere4ca7222006-08-23 20:34:57 +0000766 inFile = ::open(Src.c_str(), O_RDONLY);
767 if (inFile == -1)
Chris Lattnerc521f542009-08-23 22:45:37 +0000768 return MakeErrMsg(ErrMsg, Src.str() +
Reid Spencere4ca7222006-08-23 20:34:57 +0000769 ": can't open source file to copy");
Reid Spencerf66d9322004-12-15 01:50:13 +0000770
Reid Spencere4ca7222006-08-23 20:34:57 +0000771 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
772 if (outFile == -1) {
773 ::close(inFile);
Chris Lattnerc521f542009-08-23 22:45:37 +0000774 return MakeErrMsg(ErrMsg, Dest.str() +
Reid Spencere4ca7222006-08-23 20:34:57 +0000775 ": can't create destination file for copy");
776 }
Reid Spencerf66d9322004-12-15 01:50:13 +0000777
Reid Spencere4ca7222006-08-23 20:34:57 +0000778 char Buffer[16*1024];
779 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
780 if (Amt == -1) {
781 if (errno != EINTR && errno != EAGAIN) {
782 ::close(inFile);
783 ::close(outFile);
Chris Lattnerc521f542009-08-23 22:45:37 +0000784 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Reid Spencere4ca7222006-08-23 20:34:57 +0000785 }
786 } else {
787 char *BufPtr = Buffer;
788 while (Amt) {
789 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
790 if (AmtWritten == -1) {
791 if (errno != EINTR && errno != EAGAIN) {
792 ::close(inFile);
793 ::close(outFile);
Chris Lattnerc521f542009-08-23 22:45:37 +0000794 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbar3222b9b2009-04-20 20:50:13 +0000795 ": can't write destination file");
Reid Spencerf66d9322004-12-15 01:50:13 +0000796 }
Reid Spencere4ca7222006-08-23 20:34:57 +0000797 } else {
798 Amt -= AmtWritten;
799 BufPtr += AmtWritten;
Reid Spencerf66d9322004-12-15 01:50:13 +0000800 }
801 }
802 }
Reid Spencerf66d9322004-12-15 01:50:13 +0000803 }
Reid Spencere4ca7222006-08-23 20:34:57 +0000804 ::close(inFile);
805 ::close(outFile);
806 return false;
Reid Spencerf66d9322004-12-15 01:50:13 +0000807}
808
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000809bool
Reid Spencere4ca7222006-08-23 20:34:57 +0000810Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Michael J. Spencer58df2e02011-01-10 02:34:23 +0000811 bool Exists;
812 if (reuse_current && (fs::exists(path, Exists) || !Exists))
Reid Spencere4ca7222006-08-23 20:34:57 +0000813 return false; // File doesn't exist already, just use it!
Reid Spencerf66d9322004-12-15 01:50:13 +0000814
Mikhail Glushenkova5398362009-02-15 03:20:03 +0000815 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerf66d9322004-12-15 01:50:13 +0000816 // mktemp or our own implementation.
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000817 // This uses std::vector instead of SmallVector to avoid a dependence on
818 // libSupport. And performance isn't critical here.
819 std::vector<char> Buf;
820 Buf.resize(path.size()+8);
Dan Gohman34570612010-04-19 16:33:28 +0000821 char *FNBuffer = &Buf[0];
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000822 path.copy(FNBuffer,path.size());
Michael J. Spencer0d771ed2011-01-11 01:21:55 +0000823 bool isdir;
824 if (!fs::is_directory(path, isdir) && isdir)
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000825 strcpy(FNBuffer+path.size(), "/XXXXXX");
Devang Patelcbfc1a42008-07-24 00:35:38 +0000826 else
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000827 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerf66d9322004-12-15 01:50:13 +0000828
829#if defined(HAVE_MKSTEMP)
830 int TempFD;
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000831 if ((TempFD = mkstemp(FNBuffer)) == -1)
Reid Spencere4ca7222006-08-23 20:34:57 +0000832 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000833
834 // We don't need to hold the temp file descriptor... we will trust that no one
835 // will overwrite/delete the file before we can open it again.
836 close(TempFD);
837
838 // Save the name
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000839 path = FNBuffer;
Chad Rosier30c34632011-07-05 18:55:31 +0000840
841 // By default mkstemp sets the mode to 0600, so update mode bits now.
842 AddPermissionBits (*this, 0666);
Reid Spencerf66d9322004-12-15 01:50:13 +0000843#elif defined(HAVE_MKTEMP)
844 // If we don't have mkstemp, use the old and obsolete mktemp function.
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000845 if (mktemp(FNBuffer) == 0)
Reid Spencere4ca7222006-08-23 20:34:57 +0000846 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000847
848 // Save the name
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000849 path = FNBuffer;
Reid Spencerf66d9322004-12-15 01:50:13 +0000850#else
851 // Okay, looks like we have to do it all by our lonesome.
852 static unsigned FCounter = 0;
Chris Lattnercda39c42010-07-12 00:09:55 +0000853 // Try to initialize with unique value.
854 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
855 char* pos = strstr(FNBuffer, "XXXXXX");
856 do {
857 if (++FCounter > 0xFFFFFF) {
858 return MakeErrMsg(ErrMsg,
859 path + ": can't make unique filename: too many files");
860 }
861 sprintf(pos, "%06X", FCounter);
Dan Gohmana84dc0c2010-04-19 15:54:44 +0000862 path = FNBuffer;
Chris Lattnercda39c42010-07-12 00:09:55 +0000863 } while (exists());
864 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
865 // LLVM.
Reid Spencerf66d9322004-12-15 01:50:13 +0000866#endif
Reid Spencere4ca7222006-08-23 20:34:57 +0000867 return false;
868}
Reid Spencerf66d9322004-12-15 01:50:13 +0000869
Rafael Espindola258a6052011-03-10 18:33:29 +0000870const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
Chris Lattner4c5e15f2008-04-01 06:16:24 +0000871 int Flags = MAP_PRIVATE;
872#ifdef MAP_FILE
873 Flags |= MAP_FILE;
874#endif
Rafael Espindola258a6052011-03-10 18:33:29 +0000875 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, Offset);
Chris Lattner4c5e15f2008-04-01 06:16:24 +0000876 if (BasePtr == MAP_FAILED)
877 return 0;
Chris Lattnerba98fca2008-04-01 06:25:23 +0000878 return (const char*)BasePtr;
Chris Lattner3089e1d2008-04-01 06:00:12 +0000879}
880
Rafael Espindola258a6052011-03-10 18:33:29 +0000881void Path::UnMapFilePages(const char *BasePtr, size_t FileSize) {
Chris Lattnerba98fca2008-04-01 06:25:23 +0000882 ::munmap((void*)BasePtr, FileSize);
Chris Lattner3089e1d2008-04-01 06:00:12 +0000883}
884
Reid Spencere4ca7222006-08-23 20:34:57 +0000885} // end llvm namespace