blob: 886ba6bf6d418e9374e29f244d2cffe4d77a2305 [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
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
Reid Spencer8e665952004-08-29 05:24:01 +0000122Path
123Path::GetRootDirectory() {
124 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000125 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000126 return result;
127}
128
Reid Spencer69a16162004-12-24 06:29:42 +0000129Path
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000130Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer69a16162004-12-24 06:29:42 +0000131#if defined(HAVE_MKDTEMP)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000132 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer69a16162004-12-24 06:29:42 +0000133 // Linux and FreeBSD have it. Others probably won't.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000134 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer48744762006-08-22 19:01:30 +0000135 if (0 == mkdtemp(pathname)) {
Dan Gohman6f6021e2010-11-02 22:56:51 +0000136 MakeErrMsg(ErrMsg,
137 std::string(pathname) + ": can't create temporary directory");
Reid Spencer48744762006-08-22 19:01:30 +0000138 return Path();
139 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000140 return Path(pathname);
Reid Spencer69a16162004-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 Glushenkovb8863a12009-02-15 03:20:03 +0000146 // the time it is re-created as a directoy.
Dan Gohman0803ebe2010-11-02 22:50:10 +0000147 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer69a16162004-12-24 06:29:42 +0000148 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000149 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000150 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000151 std::string(pathname) + ": can't create temporary directory");
152 return Path();
153 }
Reid Spencer69a16162004-12-24 06:29:42 +0000154 ::close(fd);
155 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000156 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000157 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000158 std::string(pathname) + ": can't create temporary directory");
159 return Path();
160 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000161 return Path(pathname);
Reid Spencer69a16162004-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 Gohman0803ebe2010-11-02 22:50:10 +0000168 char pathname[] = "/tmp/llvm_XXXXXX";
Reid Spencer69a16162004-12-24 06:29:42 +0000169 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000170 if (TmpName == 0) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000171 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-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 Glushenkovb8863a12009-02-15 03:20:03 +0000176 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000177 std::string(TmpName) + ": can't create temporary directory");
178 return Path();
179 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000180 return Path(TmpName);
Reid Spencer69a16162004-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 Glushenkovb8863a12009-02-15 03:20:03 +0000185 // temporary name generated. So, we provide our own implementation that
Reid Spencer69a16162004-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 Spencer48744762006-08-22 19:01:30 +0000196 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000197 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000198 std::string(pathname) + ": can't create temporary directory");
199 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000200 }
Dan Gohmanaabb9b62010-11-03 00:01:23 +0000201 return Path(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000202#endif
203}
204
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000205void
Reid Spencer1b6b99b2004-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 Spencer74e72612004-09-14 00:16:39 +0000211 }
Reid Spencer1b6b99b2004-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 Spencer74e72612004-09-14 00:16:39 +0000218}
219
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000220void
Gabor Greifa99be512007-07-05 17:07:56 +0000221Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-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 Spencer1b6b99b2004-12-13 03:00:51 +0000226#ifdef LLVM_LIBDIR
227 {
228 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000229 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000230 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000231 Paths.push_back(tmpPath);
232 }
233#endif
234 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000235}
236
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000237Path
Reid Spencer8e665952004-08-29 05:24:01 +0000238Path::GetLLVMDefaultConfigDir() {
239 return Path("/etc/llvm/");
240}
241
Reid Spencer8e665952004-08-29 05:24:01 +0000242Path
243Path::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];
255 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
Dan Gohman86759ac2010-09-02 18:24:46 +0000263#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
Chris Lattner893a0f92009-03-02 22:17:15 +0000264static int
265test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
266 const char *dir, const char *bin)
267{
Bill Wendling51b16f42009-05-30 01:09:53 +0000268 struct stat sb;
Chris Lattner893a0f92009-03-02 22:17:15 +0000269
Dan Gohman86759ac2010-09-02 18:24:46 +0000270 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
Bill Wendling51b16f42009-05-30 01:09:53 +0000271 if (realpath(buf, ret) == NULL)
272 return (1);
273 if (stat(buf, &sb) != 0)
274 return (1);
275
276 return (0);
Chris Lattner893a0f92009-03-02 22:17:15 +0000277}
278
279static char *
280getprogpath(char ret[PATH_MAX], const char *bin)
281{
Bill Wendling51b16f42009-05-30 01:09:53 +0000282 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner893a0f92009-03-02 22:17:15 +0000283
Bill Wendling51b16f42009-05-30 01:09:53 +0000284 /* First approach: absolute path. */
285 if (bin[0] == '/') {
286 if (test_dir(buf, ret, "/", bin) == 0)
287 return (ret);
288 return (NULL);
289 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000290
Bill Wendling51b16f42009-05-30 01:09:53 +0000291 /* Second approach: relative path. */
292 if (strchr(bin, '/') != NULL) {
293 if (getcwd(buf, PATH_MAX) == NULL)
294 return (NULL);
295 if (test_dir(buf, ret, buf, bin) == 0)
296 return (ret);
297 return (NULL);
298 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000299
Bill Wendling51b16f42009-05-30 01:09:53 +0000300 /* Third approach: $PATH */
301 if ((pv = getenv("PATH")) == NULL)
302 return (NULL);
303 s = pv = strdup(pv);
304 if (pv == NULL)
305 return (NULL);
306 while ((t = strsep(&s, ":")) != NULL) {
307 if (test_dir(buf, ret, t, bin) == 0) {
308 free(pv);
309 return (ret);
310 }
311 }
312 free(pv);
313 return (NULL);
Chris Lattner893a0f92009-03-02 22:17:15 +0000314}
Anton Korobeynikov1d76ab72010-08-31 22:38:00 +0000315#endif // __FreeBSD__ || __NetBSD__
Chris Lattner893a0f92009-03-02 22:17:15 +0000316
Chris Lattner1a091442008-03-03 02:55:43 +0000317/// GetMainExecutable - Return the path to the main executable, given the
318/// value of argv[0] from program startup.
319Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000320#if defined(__APPLE__)
321 // On OS X the executable path is saved to the stack by dyld. Reading it
322 // from there is much faster than calling dladdr, especially for large
323 // binaries with symbols.
324 char exe_path[MAXPATHLEN];
325 uint32_t size = sizeof(exe_path);
326 if (_NSGetExecutablePath(exe_path, &size) == 0) {
327 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000328 if (realpath(exe_path, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000329 return Path(link_path);
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000330 }
Dan Gohman86759ac2010-09-02 18:24:46 +0000331#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
Chris Lattner893a0f92009-03-02 22:17:15 +0000332 char exe_path[PATH_MAX];
333
334 if (getprogpath(exe_path, argv0) != NULL)
Dan Gohman8d4fd962010-11-02 22:07:47 +0000335 return Path(exe_path);
Chris Lattner893a0f92009-03-02 22:17:15 +0000336#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattner3bdfa042008-03-13 05:22:05 +0000337 char exe_path[MAXPATHLEN];
Seo Sanghyeonfd6437f2008-06-27 22:55:30 +0000338 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Dan Gohman7b3544b2009-08-05 20:16:55 +0000339 if (len >= 0)
Dan Gohman8d4fd962010-11-02 22:07:47 +0000340 return Path(StringRef(exe_path, len));
Chris Lattner3bdfa042008-03-13 05:22:05 +0000341#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000342 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000343 Dl_info DLInfo;
344 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000345 if (err == 0)
346 return Path();
Bill Wendling51b16f42009-05-30 01:09:53 +0000347
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000348 // If the filename is a symlink, we need to resolve and return the location of
349 // the actual executable.
350 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000351 if (realpath(DLInfo.dli_fname, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000352 return Path(link_path);
Dan Gohmanb52d44a2010-09-07 18:26:49 +0000353#else
354#error GetMainExecutable is not implemented on this host yet.
Chris Lattner1a091442008-03-03 02:55:43 +0000355#endif
356 return Path();
357}
358
359
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000360StringRef Path::getDirname() const {
361 return getDirnameCharSep(path, "/");
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000362}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000363
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000364StringRef
Reid Spencer07adb282004-11-05 22:15:36 +0000365Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000366 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000367 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000368 if (slash == std::string::npos)
369 slash = 0;
370 else
371 slash++;
372
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000373 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000374 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000375 return StringRef(path).substr(slash);
Jeff Cohen73f36672005-07-09 18:42:02 +0000376 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000377 return StringRef(path).substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000378}
379
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000380StringRef
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000381Path::getSuffix() const {
382 // Find the last slash
383 std::string::size_type slash = path.rfind('/');
384 if (slash == std::string::npos)
385 slash = 0;
386 else
387 slash++;
388
389 std::string::size_type dot = path.rfind('.');
390 if (dot == std::string::npos || dot < slash)
Dan Gohmand98af0a2010-08-04 01:39:08 +0000391 return StringRef();
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000392 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000393 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000394}
395
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000396bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000397 assert(len < 1024 && "Request for magic string too long");
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000398 char Buf[1025];
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000399 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000400 if (fd < 0)
401 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000402 ssize_t bytes_read = ::read(fd, Buf, len);
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000403 ::close(fd);
Dan Gohman02d58242010-05-27 17:14:10 +0000404 if (ssize_t(len) != bytes_read)
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000405 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000406 Magic.assign(Buf, len);
Reid Spencereaf18152004-11-14 22:08:36 +0000407 return true;
408}
409
Reid Spencer1b554b42004-09-11 04:55:08 +0000410bool
Reid Spencer8e665952004-08-29 05:24:01 +0000411Path::exists() const {
412 return 0 == access(path.c_str(), F_OK );
413}
414
415bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000416Path::isDirectory() const {
417 struct stat buf;
418 if (0 != stat(path.c_str(), &buf))
419 return false;
Evan Chenga98111c2010-10-07 22:05:57 +0000420 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
Ted Kremenekfd527112007-12-18 19:46:22 +0000421}
422
423bool
Rafael Espindola9e07a142010-11-07 04:36:50 +0000424Path::isSymLink() const {
425 struct stat buf;
426 if (0 != lstat(path.c_str(), &buf))
427 return false;
428 return S_ISLNK(buf.st_mode);
429}
430
431
432bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000433Path::canRead() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000434 return 0 == access(path.c_str(), R_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000435}
436
437bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000438Path::canWrite() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000439 return 0 == access(path.c_str(), W_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000440}
441
442bool
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000443Path::isRegularFile() const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000444 // Get the status so we can determine if it's a file or directory
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000445 struct stat buf;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000446
Daniel Dunbar98e46d82009-11-24 19:03:33 +0000447 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000448 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000449
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000450 if (S_ISREG(buf.st_mode))
451 return true;
452
453 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000454}
455
456bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000457Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000458 if (0 != access(path.c_str(), R_OK | X_OK ))
459 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000460 struct stat buf;
461 if (0 != stat(path.c_str(), &buf))
462 return false;
463 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000464 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000465 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000466}
467
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000468StringRef
Reid Spencer8e665952004-08-29 05:24:01 +0000469Path::getLast() const {
470 // Find the last slash
471 size_t pos = path.rfind('/');
472
473 // Handle the corner cases
474 if (pos == std::string::npos)
475 return path;
476
477 // If the last character is a slash
478 if (pos == path.length()-1) {
479 // Find the second to last slash
480 size_t pos2 = path.rfind('/', pos-1);
481 if (pos2 == std::string::npos)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000482 return StringRef(path).substr(0,pos);
Reid Spencer8e665952004-08-29 05:24:01 +0000483 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000484 return StringRef(path).substr(pos2+1,pos-pos2-1);
Reid Spencer8e665952004-08-29 05:24:01 +0000485 }
486 // Return everything after the last slash
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000487 return StringRef(path).substr(pos+1);
Reid Spencer8e665952004-08-29 05:24:01 +0000488}
489
Reid Spencer2ae9d112007-04-07 18:52:17 +0000490const FileStatus *
491PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
492 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000493 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000494 if (0 != stat(path.c_str(), &buf)) {
495 MakeErrMsg(ErrStr, path + ": can't get status of file");
496 return 0;
497 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000498 status.fileSize = buf.st_size;
499 status.modTime.fromEpochTime(buf.st_mtime);
500 status.mode = buf.st_mode;
501 status.user = buf.st_uid;
502 status.group = buf.st_gid;
503 status.uniqueID = uint64_t(buf.st_ino);
504 status.isDir = S_ISDIR(buf.st_mode);
505 status.isFile = S_ISREG(buf.st_mode);
506 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000507 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000508 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000509}
510
Chris Lattner252ad032006-07-28 22:03:44 +0000511static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000512 // Get the umask value from the operating system. We want to use it
513 // when changing the file's permissions. Since calling umask() sets
514 // the umask and returns its old value, we must call it a second
515 // time to reset it to the user's preference.
516 int mask = umask(0777); // The arg. to umask is arbitrary.
517 umask(mask); // Restore the umask.
518
519 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000520 struct stat buf;
Chris Lattner74382b72009-08-23 22:45:37 +0000521 if (0 != stat(File.c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000522 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000523 // Change the file to have whichever permissions bits from 'bits'
524 // that the umask would not disable.
525 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
526 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000527 return true;
528}
529
Reid Spencere1647f42006-08-22 23:27:23 +0000530bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000531 if (!AddPermissionBits(*this, 0444))
Reid Spencer5a060772006-08-23 07:30:48 +0000532 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000533 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000534}
535
Reid Spencere1647f42006-08-22 23:27:23 +0000536bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000537 if (!AddPermissionBits(*this, 0222))
538 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000539 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000540}
541
Reid Spencere1647f42006-08-22 23:27:23 +0000542bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000543 if (!AddPermissionBits(*this, 0111))
544 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000545 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000546}
547
Reid Spencereaf18152004-11-14 22:08:36 +0000548bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000549Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000550 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000551 if (direntries == 0)
552 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000553
Reid Spencer3be872e2005-07-28 16:25:57 +0000554 std::string dirPath = path;
555 if (!lastIsSlash(dirPath))
556 dirPath += '/';
557
Reid Spencereaf18152004-11-14 22:08:36 +0000558 result.clear();
559 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000560 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000561 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000562 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000563 struct stat st;
564 if (0 != lstat(aPath.path.c_str(), &st)) {
565 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000566 continue; // dangling symlink -- ignore
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000567 return MakeErrMsg(ErrMsg,
Reid Spencer5a060772006-08-23 07:30:48 +0000568 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000569 }
Reid Spencerb608a812004-11-16 06:15:19 +0000570 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000571 }
Reid Spencereaf18152004-11-14 22:08:36 +0000572 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000573
Reid Spencereaf18152004-11-14 22:08:36 +0000574 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000575 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000576}
577
Reid Spencer8e665952004-08-29 05:24:01 +0000578bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000579Path::set(StringRef a_path) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000580 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000581 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000582 path = a_path;
Reid Spencer8e665952004-08-29 05:24:01 +0000583 return true;
584}
585
586bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000587Path::appendComponent(StringRef name) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000588 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000589 return false;
Reid Spencer3be872e2005-07-28 16:25:57 +0000590 if (!lastIsSlash(path))
591 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000592 path += name;
Reid Spencer8e665952004-08-29 05:24:01 +0000593 return true;
594}
595
596bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000597Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000598 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000599 if (slashpos == 0 || slashpos == std::string::npos) {
600 path.erase();
601 return true;
602 }
Reid Spencer8e665952004-08-29 05:24:01 +0000603 if (slashpos == path.size() - 1)
604 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000605 if (slashpos == std::string::npos) {
606 path.erase();
607 return true;
608 }
Reid Spencer8e665952004-08-29 05:24:01 +0000609 path.erase(slashpos);
610 return true;
611}
612
613bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000614Path::eraseSuffix() {
Reid Spencer8e665952004-08-29 05:24:01 +0000615 size_t dotpos = path.rfind('.',path.size());
616 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000617 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000618 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000619 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000620 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000621 }
Reid Spencer8e665952004-08-29 05:24:01 +0000622 }
Jeff Cohen563a17f2005-07-08 04:49:16 +0000623 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000624}
625
Ted Kremenekc5412c52008-04-03 16:11:31 +0000626static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000627
Dan Gohman28daa102009-07-29 00:02:58 +0000628 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenekc5412c52008-04-03 16:11:31 +0000629 return false;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000630
Ted Kremenekc5412c52008-04-03 16:11:31 +0000631 if (create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000632
Ted Kremenekc5412c52008-04-03 16:11:31 +0000633 char* c = end;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000634
Ted Kremenekc5412c52008-04-03 16:11:31 +0000635 for (; c != beg; --c)
636 if (*c == '/') {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000637
Ted Kremenekc5412c52008-04-03 16:11:31 +0000638 // Recurse to handling the parent directory.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000639 *c = '\0';
Ted Kremenekc5412c52008-04-03 16:11:31 +0000640 bool x = createDirectoryHelper(beg, c, create_parents);
641 *c = '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000642
Ted Kremenekc5412c52008-04-03 16:11:31 +0000643 // Return if we encountered an error.
644 if (x)
645 return true;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000646
Ted Kremenekc5412c52008-04-03 16:11:31 +0000647 break;
648 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000649 }
650
Ted Kremenekc5412c52008-04-03 16:11:31 +0000651 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
652}
653
Reid Spencer8e665952004-08-29 05:24:01 +0000654bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000655Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000656 // Get a writeable copy of the path name
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000657 std::string pathname(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000658
659 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000660 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000661
Ted Kremenekc5412c52008-04-03 16:11:31 +0000662 if (pathname[lastchar] != '/')
663 ++lastchar;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000664
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000665 pathname[lastchar] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000666
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000667 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
Dan Gohman9e2e0c32010-11-02 23:16:26 +0000668 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000669
Reid Spencere5c9cb52006-08-23 00:39:35 +0000670 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000671}
672
673bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000674Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000675 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000676 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000677 if (fd < 0)
678 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000679 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000680 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000681}
682
Reid Spencer8e665952004-08-29 05:24:01 +0000683bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000684Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000685 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000686 if (makeUnique( reuse_current, ErrMsg ))
687 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000688
689 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000690 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000691 if (fd < 0)
Reid Spencer5a060772006-08-23 07:30:48 +0000692 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000693 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000694 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000695}
696
697bool
Chris Lattner0c332312006-07-28 22:29:50 +0000698Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000699 // Get the status so we can determine if it's a file or directory.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000700 struct stat buf;
701 if (0 != stat(path.c_str(), &buf)) {
702 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000703 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000704 }
705
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000706 // Note: this check catches strange situations. In all cases, LLVM should
707 // only be involved in the creation and deletion of regular files. This
708 // check ensures that what we're trying to erase is a regular file. It
709 // effectively prevents LLVM from erasing things like /dev/null, any block
710 // special file, or other things that aren't "regular" files.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000711 if (S_ISREG(buf.st_mode)) {
712 if (unlink(path.c_str()) != 0)
713 return MakeErrMsg(ErrStr, path + ": can't destroy file");
714 return false;
715 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000716
Reid Spencer2ae9d112007-04-07 18:52:17 +0000717 if (!S_ISDIR(buf.st_mode)) {
718 if (ErrStr) *ErrStr = "not a file or directory";
719 return true;
720 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000721
Chris Lattner0c332312006-07-28 22:29:50 +0000722 if (remove_contents) {
723 // Recursively descend the directory to remove its contents.
724 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov8eada622009-02-15 03:20:32 +0000725 if (system(cmd.c_str()) != 0) {
726 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
727 return true;
728 }
Chris Lattner0c332312006-07-28 22:29:50 +0000729 return false;
730 }
731
732 // Otherwise, try to just remove the one directory.
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000733 std::string pathname(path);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000734 size_t lastchar = path.length() - 1;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000735 if (pathname[lastchar] == '/')
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000736 pathname[lastchar] = '\0';
Chris Lattner0c332312006-07-28 22:29:50 +0000737 else
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000738 pathname[lastchar+1] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000739
Dan Gohmanb48a8fd2010-11-02 22:55:34 +0000740 if (rmdir(pathname.c_str()) != 0)
741 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000742 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000743}
744
745bool
Reid Spencer5a060772006-08-23 07:30:48 +0000746Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000747 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000748 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattner74382b72009-08-23 22:45:37 +0000749 newName.str() + "'");
Reid Spencer5a060772006-08-23 07:30:48 +0000750 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000751}
752
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000753bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000754Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000755 struct utimbuf utb;
756 utb.actime = si.modTime.toPosixTime();
757 utb.modtime = utb.actime;
758 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000759 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000760 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000761 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000762 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000763}
764
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000765bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000766sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000767 int inFile = -1;
768 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000769 inFile = ::open(Src.c_str(), O_RDONLY);
770 if (inFile == -1)
Chris Lattner74382b72009-08-23 22:45:37 +0000771 return MakeErrMsg(ErrMsg, Src.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000772 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000773
Reid Spencer51c5a282006-08-23 20:34:57 +0000774 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
775 if (outFile == -1) {
776 ::close(inFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000777 return MakeErrMsg(ErrMsg, Dest.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000778 ": can't create destination file for copy");
779 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000780
Reid Spencer51c5a282006-08-23 20:34:57 +0000781 char Buffer[16*1024];
782 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
783 if (Amt == -1) {
784 if (errno != EINTR && errno != EAGAIN) {
785 ::close(inFile);
786 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000787 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Reid Spencer51c5a282006-08-23 20:34:57 +0000788 }
789 } else {
790 char *BufPtr = Buffer;
791 while (Amt) {
792 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
793 if (AmtWritten == -1) {
794 if (errno != EINTR && errno != EAGAIN) {
795 ::close(inFile);
796 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000797 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000798 ": can't write destination file");
Reid Spencerc29befb2004-12-15 01:50:13 +0000799 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000800 } else {
801 Amt -= AmtWritten;
802 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000803 }
804 }
805 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000806 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000807 ::close(inFile);
808 ::close(outFile);
809 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000810}
811
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000812bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000813Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000814 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000815 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000816
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000817 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerc29befb2004-12-15 01:50:13 +0000818 // mktemp or our own implementation.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000819 // This uses std::vector instead of SmallVector to avoid a dependence on
820 // libSupport. And performance isn't critical here.
821 std::vector<char> Buf;
822 Buf.resize(path.size()+8);
Dan Gohman17192a12010-04-19 16:33:28 +0000823 char *FNBuffer = &Buf[0];
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000824 path.copy(FNBuffer,path.size());
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000825 if (isDirectory())
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000826 strcpy(FNBuffer+path.size(), "/XXXXXX");
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000827 else
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000828 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerc29befb2004-12-15 01:50:13 +0000829
830#if defined(HAVE_MKSTEMP)
831 int TempFD;
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000832 if ((TempFD = mkstemp(FNBuffer)) == -1)
Reid Spencer51c5a282006-08-23 20:34:57 +0000833 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000834
835 // We don't need to hold the temp file descriptor... we will trust that no one
836 // will overwrite/delete the file before we can open it again.
837 close(TempFD);
838
839 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000840 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000841#elif defined(HAVE_MKTEMP)
842 // If we don't have mkstemp, use the old and obsolete mktemp function.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000843 if (mktemp(FNBuffer) == 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000844 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000845
846 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000847 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000848#else
849 // Okay, looks like we have to do it all by our lonesome.
850 static unsigned FCounter = 0;
Chris Lattner1f011092010-07-12 00:09:55 +0000851 // Try to initialize with unique value.
852 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
853 char* pos = strstr(FNBuffer, "XXXXXX");
854 do {
855 if (++FCounter > 0xFFFFFF) {
856 return MakeErrMsg(ErrMsg,
857 path + ": can't make unique filename: too many files");
858 }
859 sprintf(pos, "%06X", FCounter);
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000860 path = FNBuffer;
Chris Lattner1f011092010-07-12 00:09:55 +0000861 } while (exists());
862 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
863 // LLVM.
Reid Spencerc29befb2004-12-15 01:50:13 +0000864#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000865 return false;
866}
Reid Spencerc29befb2004-12-15 01:50:13 +0000867
Chris Lattner799ed102008-04-01 06:00:12 +0000868const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000869 int Flags = MAP_PRIVATE;
870#ifdef MAP_FILE
871 Flags |= MAP_FILE;
872#endif
873 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
874 if (BasePtr == MAP_FAILED)
875 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000876 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000877}
878
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000879void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000880 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000881}
882
Reid Spencer51c5a282006-08-23 20:34:57 +0000883} // end llvm namespace