blob: 571ecbd401a2518df06af3353101d224bdc23c28 [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 {
Reid Spencer6371ccb2005-07-08 06:53:26 +000099 // Check some obvious things
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000100 if (path.empty())
Reid Spencer69a16162004-12-24 06:29:42 +0000101 return false;
Chris Lattner0f550142009-07-12 19:01:16 +0000102 return path.length() < MAXPATHLEN;
Reid Spencer69a16162004-12-24 06:29:42 +0000103}
104
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000105bool
Chris Lattner88d7e402009-06-15 04:17:07 +0000106Path::isAbsolute(const char *NameStart, unsigned NameLen) {
107 assert(NameStart);
108 if (NameLen == 0)
109 return false;
110 return NameStart[0] == '/';
111}
112
113bool
Reid Spencer69cce812007-03-29 16:43:20 +0000114Path::isAbsolute() const {
115 if (path.empty())
116 return false;
117 return path[0] == '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000118}
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000119
120void Path::makeAbsolute() {
121 if (isAbsolute())
122 return;
123
124 Path CWD = Path::GetCurrentDirectory();
125 assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
126
127 CWD.appendComponent(path);
128
Chris Lattner74382b72009-08-23 22:45:37 +0000129 path = CWD.str();
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000130}
131
Reid Spencer8e665952004-08-29 05:24:01 +0000132Path
133Path::GetRootDirectory() {
134 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000135 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000136 return result;
137}
138
Reid Spencer69a16162004-12-24 06:29:42 +0000139Path
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000140Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer69a16162004-12-24 06:29:42 +0000141#if defined(HAVE_MKDTEMP)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000142 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer69a16162004-12-24 06:29:42 +0000143 // Linux and FreeBSD have it. Others probably won't.
144 char pathname[MAXPATHLEN];
145 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000146 if (0 == mkdtemp(pathname)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000147 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000148 std::string(pathname) + ": can't create temporary directory");
149 return Path();
150 }
Reid Spencer69a16162004-12-24 06:29:42 +0000151 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000152 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000153 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
154 return result;
155#elif defined(HAVE_MKSTEMP)
156 // If no mkdtemp is available, mkstemp can be used to create a temporary file
157 // which is then removed and created as a directory. We prefer this over
158 // mktemp because of mktemp's inherent security and threading risks. We still
159 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000160 // the time it is re-created as a directoy.
Reid Spencer69a16162004-12-24 06:29:42 +0000161 char pathname[MAXPATHLEN];
162 strcpy(pathname, "/tmp/llvm_XXXXXX");
163 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000164 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000165 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000166 std::string(pathname) + ": can't create temporary directory");
167 return Path();
168 }
Reid Spencer69a16162004-12-24 06:29:42 +0000169 ::close(fd);
170 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000171 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000172 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000173 std::string(pathname) + ": can't create temporary directory");
174 return Path();
175 }
Reid Spencer69a16162004-12-24 06:29:42 +0000176 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000177 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000178 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
179 return result;
180#elif defined(HAVE_MKTEMP)
181 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
182 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
183 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
184 // the XXXXXX with the pid of the process and a letter. That leads to only
185 // twenty six temporary files that can be generated.
186 char pathname[MAXPATHLEN];
187 strcpy(pathname, "/tmp/llvm_XXXXXX");
188 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000189 if (TmpName == 0) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000190 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000191 std::string(TmpName) + ": can't create unique directory name");
192 return Path();
193 }
194 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000195 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000196 std::string(TmpName) + ": can't create temporary directory");
197 return Path();
198 }
Reid Spencer69a16162004-12-24 06:29:42 +0000199 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000200 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000201 assert(result.isValid() && "mktemp didn't create a valid pathname!");
202 return result;
203#else
204 // This is the worst case implementation. tempnam(3) leaks memory unless its
205 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
206 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000207 // temporary name generated. So, we provide our own implementation that
Reid Spencer69a16162004-12-24 06:29:42 +0000208 // increments an integer from a random number seeded by the current time. This
209 // should be sufficiently unique that we don't have many collisions between
210 // processes. Generally LLVM processes don't run very long and don't use very
211 // many temporary files so this shouldn't be a big issue for LLVM.
212 static time_t num = ::time(0);
213 char pathname[MAXPATHLEN];
214 do {
215 num++;
216 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
217 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000218 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000219 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000220 std::string(pathname) + ": can't create temporary directory");
221 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000222 }
Reid Spencer69a16162004-12-24 06:29:42 +0000223 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000224 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000225 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
226 return result;
227#endif
228}
229
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000230void
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000231Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
232#ifdef LTDL_SHLIBPATH_VAR
233 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
234 if (env_var != 0) {
235 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000236 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000237#endif
238 // FIXME: Should this look at LD_LIBRARY_PATH too?
239 Paths.push_back(sys::Path("/usr/local/lib/"));
240 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
241 Paths.push_back(sys::Path("/usr/lib/"));
242 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000243}
244
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000245void
Gabor Greifa99be512007-07-05 17:07:56 +0000246Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000247 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
248 if (env_var != 0) {
249 getPathList(env_var,Paths);
250 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000251#ifdef LLVM_LIBDIR
252 {
253 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000254 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000255 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000256 Paths.push_back(tmpPath);
257 }
258#endif
259 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000260}
261
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000262Path
Reid Spencer8e665952004-08-29 05:24:01 +0000263Path::GetLLVMDefaultConfigDir() {
264 return Path("/etc/llvm/");
265}
266
Reid Spencer8e665952004-08-29 05:24:01 +0000267Path
268Path::GetUserHomeDirectory() {
269 const char* home = getenv("HOME");
270 if (home) {
271 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000272 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000273 return result;
274 }
275 return GetRootDirectory();
276}
277
Ted Kremenek79200782007-12-18 22:07:33 +0000278Path
279Path::GetCurrentDirectory() {
280 char pathname[MAXPATHLEN];
281 if (!getcwd(pathname,MAXPATHLEN)) {
282 assert (false && "Could not query current working directory.");
Dan Gohmand98af0a2010-08-04 01:39:08 +0000283 return Path();
Ted Kremenek79200782007-12-18 22:07:33 +0000284 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000285
Ted Kremenek79200782007-12-18 22:07:33 +0000286 return Path(pathname);
287}
Reid Spencera229c5c2005-07-08 03:08:58 +0000288
Dan Gohman86759ac2010-09-02 18:24:46 +0000289#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
Chris Lattner893a0f92009-03-02 22:17:15 +0000290static int
291test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
292 const char *dir, const char *bin)
293{
Bill Wendling51b16f42009-05-30 01:09:53 +0000294 struct stat sb;
Chris Lattner893a0f92009-03-02 22:17:15 +0000295
Dan Gohman86759ac2010-09-02 18:24:46 +0000296 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
Bill Wendling51b16f42009-05-30 01:09:53 +0000297 if (realpath(buf, ret) == NULL)
298 return (1);
299 if (stat(buf, &sb) != 0)
300 return (1);
301
302 return (0);
Chris Lattner893a0f92009-03-02 22:17:15 +0000303}
304
305static char *
306getprogpath(char ret[PATH_MAX], const char *bin)
307{
Bill Wendling51b16f42009-05-30 01:09:53 +0000308 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner893a0f92009-03-02 22:17:15 +0000309
Bill Wendling51b16f42009-05-30 01:09:53 +0000310 /* First approach: absolute path. */
311 if (bin[0] == '/') {
312 if (test_dir(buf, ret, "/", bin) == 0)
313 return (ret);
314 return (NULL);
315 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000316
Bill Wendling51b16f42009-05-30 01:09:53 +0000317 /* Second approach: relative path. */
318 if (strchr(bin, '/') != NULL) {
319 if (getcwd(buf, PATH_MAX) == NULL)
320 return (NULL);
321 if (test_dir(buf, ret, buf, bin) == 0)
322 return (ret);
323 return (NULL);
324 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000325
Bill Wendling51b16f42009-05-30 01:09:53 +0000326 /* Third approach: $PATH */
327 if ((pv = getenv("PATH")) == NULL)
328 return (NULL);
329 s = pv = strdup(pv);
330 if (pv == NULL)
331 return (NULL);
332 while ((t = strsep(&s, ":")) != NULL) {
333 if (test_dir(buf, ret, t, bin) == 0) {
334 free(pv);
335 return (ret);
336 }
337 }
338 free(pv);
339 return (NULL);
Chris Lattner893a0f92009-03-02 22:17:15 +0000340}
Anton Korobeynikov1d76ab72010-08-31 22:38:00 +0000341#endif // __FreeBSD__ || __NetBSD__
Chris Lattner893a0f92009-03-02 22:17:15 +0000342
Chris Lattner1a091442008-03-03 02:55:43 +0000343/// GetMainExecutable - Return the path to the main executable, given the
344/// value of argv[0] from program startup.
345Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000346#if defined(__APPLE__)
347 // On OS X the executable path is saved to the stack by dyld. Reading it
348 // from there is much faster than calling dladdr, especially for large
349 // binaries with symbols.
350 char exe_path[MAXPATHLEN];
351 uint32_t size = sizeof(exe_path);
352 if (_NSGetExecutablePath(exe_path, &size) == 0) {
353 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000354 if (realpath(exe_path, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000355 return Path(link_path);
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000356 }
Dan Gohman86759ac2010-09-02 18:24:46 +0000357#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
Chris Lattner893a0f92009-03-02 22:17:15 +0000358 char exe_path[PATH_MAX];
359
360 if (getprogpath(exe_path, argv0) != NULL)
Dan Gohman8d4fd962010-11-02 22:07:47 +0000361 return Path(exe_path);
Chris Lattner893a0f92009-03-02 22:17:15 +0000362#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattner3bdfa042008-03-13 05:22:05 +0000363 char exe_path[MAXPATHLEN];
Seo Sanghyeonfd6437f2008-06-27 22:55:30 +0000364 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Dan Gohman7b3544b2009-08-05 20:16:55 +0000365 if (len >= 0)
Dan Gohman8d4fd962010-11-02 22:07:47 +0000366 return Path(StringRef(exe_path, len));
Chris Lattner3bdfa042008-03-13 05:22:05 +0000367#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000368 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000369 Dl_info DLInfo;
370 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000371 if (err == 0)
372 return Path();
Bill Wendling51b16f42009-05-30 01:09:53 +0000373
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000374 // If the filename is a symlink, we need to resolve and return the location of
375 // the actual executable.
376 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000377 if (realpath(DLInfo.dli_fname, link_path))
Dan Gohman8d4fd962010-11-02 22:07:47 +0000378 return Path(link_path);
Dan Gohmanb52d44a2010-09-07 18:26:49 +0000379#else
380#error GetMainExecutable is not implemented on this host yet.
Chris Lattner1a091442008-03-03 02:55:43 +0000381#endif
382 return Path();
383}
384
385
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000386StringRef Path::getDirname() const {
387 return getDirnameCharSep(path, "/");
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000388}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000389
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000390StringRef
Reid Spencer07adb282004-11-05 22:15:36 +0000391Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000392 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000393 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000394 if (slash == std::string::npos)
395 slash = 0;
396 else
397 slash++;
398
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000399 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000400 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000401 return StringRef(path).substr(slash);
Jeff Cohen73f36672005-07-09 18:42:02 +0000402 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000403 return StringRef(path).substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000404}
405
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000406StringRef
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000407Path::getSuffix() const {
408 // Find the last slash
409 std::string::size_type slash = path.rfind('/');
410 if (slash == std::string::npos)
411 slash = 0;
412 else
413 slash++;
414
415 std::string::size_type dot = path.rfind('.');
416 if (dot == std::string::npos || dot < slash)
Dan Gohmand98af0a2010-08-04 01:39:08 +0000417 return StringRef();
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000418 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000419 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000420}
421
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000422bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000423 assert(len < 1024 && "Request for magic string too long");
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000424 char Buf[1025];
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000425 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000426 if (fd < 0)
427 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000428 ssize_t bytes_read = ::read(fd, Buf, len);
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000429 ::close(fd);
Dan Gohman02d58242010-05-27 17:14:10 +0000430 if (ssize_t(len) != bytes_read)
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000431 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000432 Magic.assign(Buf, len);
Reid Spencereaf18152004-11-14 22:08:36 +0000433 return true;
434}
435
Reid Spencer1b554b42004-09-11 04:55:08 +0000436bool
Reid Spencer8e665952004-08-29 05:24:01 +0000437Path::exists() const {
438 return 0 == access(path.c_str(), F_OK );
439}
440
441bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000442Path::isDirectory() const {
443 struct stat buf;
444 if (0 != stat(path.c_str(), &buf))
445 return false;
Evan Chenga98111c2010-10-07 22:05:57 +0000446 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
Ted Kremenekfd527112007-12-18 19:46:22 +0000447}
448
449bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000450Path::canRead() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000451 return 0 == access(path.c_str(), R_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000452}
453
454bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000455Path::canWrite() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000456 return 0 == access(path.c_str(), W_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000457}
458
459bool
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000460Path::isRegularFile() const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000461 // Get the status so we can determine if it's a file or directory
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000462 struct stat buf;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000463
Daniel Dunbar98e46d82009-11-24 19:03:33 +0000464 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000465 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000466
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000467 if (S_ISREG(buf.st_mode))
468 return true;
469
470 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000471}
472
473bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000474Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000475 if (0 != access(path.c_str(), R_OK | X_OK ))
476 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000477 struct stat buf;
478 if (0 != stat(path.c_str(), &buf))
479 return false;
480 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000481 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000482 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000483}
484
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000485StringRef
Reid Spencer8e665952004-08-29 05:24:01 +0000486Path::getLast() const {
487 // Find the last slash
488 size_t pos = path.rfind('/');
489
490 // Handle the corner cases
491 if (pos == std::string::npos)
492 return path;
493
494 // If the last character is a slash
495 if (pos == path.length()-1) {
496 // Find the second to last slash
497 size_t pos2 = path.rfind('/', pos-1);
498 if (pos2 == std::string::npos)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000499 return StringRef(path).substr(0,pos);
Reid Spencer8e665952004-08-29 05:24:01 +0000500 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000501 return StringRef(path).substr(pos2+1,pos-pos2-1);
Reid Spencer8e665952004-08-29 05:24:01 +0000502 }
503 // Return everything after the last slash
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000504 return StringRef(path).substr(pos+1);
Reid Spencer8e665952004-08-29 05:24:01 +0000505}
506
Reid Spencer2ae9d112007-04-07 18:52:17 +0000507const FileStatus *
508PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
509 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000510 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000511 if (0 != stat(path.c_str(), &buf)) {
512 MakeErrMsg(ErrStr, path + ": can't get status of file");
513 return 0;
514 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000515 status.fileSize = buf.st_size;
516 status.modTime.fromEpochTime(buf.st_mtime);
517 status.mode = buf.st_mode;
518 status.user = buf.st_uid;
519 status.group = buf.st_gid;
520 status.uniqueID = uint64_t(buf.st_ino);
521 status.isDir = S_ISDIR(buf.st_mode);
522 status.isFile = S_ISREG(buf.st_mode);
523 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000524 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000525 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000526}
527
Chris Lattner252ad032006-07-28 22:03:44 +0000528static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000529 // Get the umask value from the operating system. We want to use it
530 // when changing the file's permissions. Since calling umask() sets
531 // the umask and returns its old value, we must call it a second
532 // time to reset it to the user's preference.
533 int mask = umask(0777); // The arg. to umask is arbitrary.
534 umask(mask); // Restore the umask.
535
536 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000537 struct stat buf;
Chris Lattner74382b72009-08-23 22:45:37 +0000538 if (0 != stat(File.c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000539 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000540 // Change the file to have whichever permissions bits from 'bits'
541 // that the umask would not disable.
542 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
543 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000544 return true;
545}
546
Reid Spencere1647f42006-08-22 23:27:23 +0000547bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000548 if (!AddPermissionBits(*this, 0444))
Reid Spencer5a060772006-08-23 07:30:48 +0000549 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000550 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000551}
552
Reid Spencere1647f42006-08-22 23:27:23 +0000553bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000554 if (!AddPermissionBits(*this, 0222))
555 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000556 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000557}
558
Reid Spencere1647f42006-08-22 23:27:23 +0000559bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000560 if (!AddPermissionBits(*this, 0111))
561 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000562 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000563}
564
Reid Spencereaf18152004-11-14 22:08:36 +0000565bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000566Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000567 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000568 if (direntries == 0)
569 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000570
Reid Spencer3be872e2005-07-28 16:25:57 +0000571 std::string dirPath = path;
572 if (!lastIsSlash(dirPath))
573 dirPath += '/';
574
Reid Spencereaf18152004-11-14 22:08:36 +0000575 result.clear();
576 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000577 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000578 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000579 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000580 struct stat st;
581 if (0 != lstat(aPath.path.c_str(), &st)) {
582 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000583 continue; // dangling symlink -- ignore
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000584 return MakeErrMsg(ErrMsg,
Reid Spencer5a060772006-08-23 07:30:48 +0000585 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000586 }
Reid Spencerb608a812004-11-16 06:15:19 +0000587 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000588 }
Reid Spencereaf18152004-11-14 22:08:36 +0000589 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000590
Reid Spencereaf18152004-11-14 22:08:36 +0000591 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000592 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000593}
594
Reid Spencer8e665952004-08-29 05:24:01 +0000595bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000596Path::set(StringRef a_path) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000597 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000598 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000599 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000600 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000601 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000602 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000603 return false;
604 }
605 return true;
606}
607
608bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000609Path::appendComponent(StringRef name) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000610 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000611 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000612 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000613 if (!lastIsSlash(path))
614 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000615 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000616 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000617 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000618 return false;
619 }
620 return true;
621}
622
623bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000624Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000625 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000626 if (slashpos == 0 || slashpos == std::string::npos) {
627 path.erase();
628 return true;
629 }
Reid Spencer8e665952004-08-29 05:24:01 +0000630 if (slashpos == path.size() - 1)
631 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000632 if (slashpos == std::string::npos) {
633 path.erase();
634 return true;
635 }
Reid Spencer8e665952004-08-29 05:24:01 +0000636 path.erase(slashpos);
637 return true;
638}
639
640bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000641Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000642 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000643 size_t dotpos = path.rfind('.',path.size());
644 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000645 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000646 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000647 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000648 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000649 }
Reid Spencer8e665952004-08-29 05:24:01 +0000650 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000651 if (!isValid())
652 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000653 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000654}
655
Ted Kremenekc5412c52008-04-03 16:11:31 +0000656static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000657
Dan Gohman28daa102009-07-29 00:02:58 +0000658 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenekc5412c52008-04-03 16:11:31 +0000659 return false;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000660
Ted Kremenekc5412c52008-04-03 16:11:31 +0000661 if (create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000662
Ted Kremenekc5412c52008-04-03 16:11:31 +0000663 char* c = end;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000664
Ted Kremenekc5412c52008-04-03 16:11:31 +0000665 for (; c != beg; --c)
666 if (*c == '/') {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000667
Ted Kremenekc5412c52008-04-03 16:11:31 +0000668 // Recurse to handling the parent directory.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000669 *c = '\0';
Ted Kremenekc5412c52008-04-03 16:11:31 +0000670 bool x = createDirectoryHelper(beg, c, create_parents);
671 *c = '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000672
Ted Kremenekc5412c52008-04-03 16:11:31 +0000673 // Return if we encountered an error.
674 if (x)
675 return true;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000676
Ted Kremenekc5412c52008-04-03 16:11:31 +0000677 break;
678 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000679 }
680
Ted Kremenekc5412c52008-04-03 16:11:31 +0000681 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
682}
683
Reid Spencer8e665952004-08-29 05:24:01 +0000684bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000685Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000686 // Get a writeable copy of the path name
687 char pathname[MAXPATHLEN];
688 path.copy(pathname,MAXPATHLEN);
689
690 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000691 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000692
Ted Kremenekc5412c52008-04-03 16:11:31 +0000693 if (pathname[lastchar] != '/')
694 ++lastchar;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000695
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000696 pathname[lastchar] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000697
Ted Kremenekc5412c52008-04-03 16:11:31 +0000698 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000699 return MakeErrMsg(ErrMsg,
Ted Kremenekc5412c52008-04-03 16:11:31 +0000700 std::string(pathname) + ": can't create directory");
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000701
Reid Spencere5c9cb52006-08-23 00:39:35 +0000702 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000703}
704
705bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000706Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000707 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000708 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000709 if (fd < 0)
710 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000711 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000712 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000713}
714
Reid Spencer8e665952004-08-29 05:24:01 +0000715bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000716Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000717 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000718 if (makeUnique( reuse_current, ErrMsg ))
719 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000720
721 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000722 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000723 if (fd < 0)
Reid Spencer5a060772006-08-23 07:30:48 +0000724 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000725 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000726 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000727}
728
729bool
Chris Lattner0c332312006-07-28 22:29:50 +0000730Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000731 // Get the status so we can determine if it's a file or directory.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000732 struct stat buf;
733 if (0 != stat(path.c_str(), &buf)) {
734 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000735 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000736 }
737
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000738 // Note: this check catches strange situations. In all cases, LLVM should
739 // only be involved in the creation and deletion of regular files. This
740 // check ensures that what we're trying to erase is a regular file. It
741 // effectively prevents LLVM from erasing things like /dev/null, any block
742 // special file, or other things that aren't "regular" files.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000743 if (S_ISREG(buf.st_mode)) {
744 if (unlink(path.c_str()) != 0)
745 return MakeErrMsg(ErrStr, path + ": can't destroy file");
746 return false;
747 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000748
Reid Spencer2ae9d112007-04-07 18:52:17 +0000749 if (!S_ISDIR(buf.st_mode)) {
750 if (ErrStr) *ErrStr = "not a file or directory";
751 return true;
752 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000753
Chris Lattner0c332312006-07-28 22:29:50 +0000754 if (remove_contents) {
755 // Recursively descend the directory to remove its contents.
756 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov8eada622009-02-15 03:20:32 +0000757 if (system(cmd.c_str()) != 0) {
758 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
759 return true;
760 }
Chris Lattner0c332312006-07-28 22:29:50 +0000761 return false;
762 }
763
764 // Otherwise, try to just remove the one directory.
765 char pathname[MAXPATHLEN];
766 path.copy(pathname, MAXPATHLEN);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000767 size_t lastchar = path.length() - 1;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000768 if (pathname[lastchar] == '/')
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000769 pathname[lastchar] = '\0';
Chris Lattner0c332312006-07-28 22:29:50 +0000770 else
Dan Gohmana0f1a2b2010-11-02 22:41:19 +0000771 pathname[lastchar+1] = '\0';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000772
Chris Lattner0c332312006-07-28 22:29:50 +0000773 if (rmdir(pathname) != 0)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000774 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000775 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000776 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000777}
778
779bool
Reid Spencer5a060772006-08-23 07:30:48 +0000780Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000781 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000782 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattner74382b72009-08-23 22:45:37 +0000783 newName.str() + "'");
Reid Spencer5a060772006-08-23 07:30:48 +0000784 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000785}
786
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000787bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000788Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000789 struct utimbuf utb;
790 utb.actime = si.modTime.toPosixTime();
791 utb.modtime = utb.actime;
792 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000793 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000794 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000795 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000796 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000797}
798
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000799bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000800sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000801 int inFile = -1;
802 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000803 inFile = ::open(Src.c_str(), O_RDONLY);
804 if (inFile == -1)
Chris Lattner74382b72009-08-23 22:45:37 +0000805 return MakeErrMsg(ErrMsg, Src.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000806 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000807
Reid Spencer51c5a282006-08-23 20:34:57 +0000808 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
809 if (outFile == -1) {
810 ::close(inFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000811 return MakeErrMsg(ErrMsg, Dest.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000812 ": can't create destination file for copy");
813 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000814
Reid Spencer51c5a282006-08-23 20:34:57 +0000815 char Buffer[16*1024];
816 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
817 if (Amt == -1) {
818 if (errno != EINTR && errno != EAGAIN) {
819 ::close(inFile);
820 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000821 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Reid Spencer51c5a282006-08-23 20:34:57 +0000822 }
823 } else {
824 char *BufPtr = Buffer;
825 while (Amt) {
826 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
827 if (AmtWritten == -1) {
828 if (errno != EINTR && errno != EAGAIN) {
829 ::close(inFile);
830 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000831 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000832 ": can't write destination file");
Reid Spencerc29befb2004-12-15 01:50:13 +0000833 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000834 } else {
835 Amt -= AmtWritten;
836 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000837 }
838 }
839 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000840 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000841 ::close(inFile);
842 ::close(outFile);
843 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000844}
845
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000846bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000847Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000848 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000849 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000850
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000851 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerc29befb2004-12-15 01:50:13 +0000852 // mktemp or our own implementation.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000853 // This uses std::vector instead of SmallVector to avoid a dependence on
854 // libSupport. And performance isn't critical here.
855 std::vector<char> Buf;
856 Buf.resize(path.size()+8);
Dan Gohman17192a12010-04-19 16:33:28 +0000857 char *FNBuffer = &Buf[0];
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000858 path.copy(FNBuffer,path.size());
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000859 if (isDirectory())
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000860 strcpy(FNBuffer+path.size(), "/XXXXXX");
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000861 else
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000862 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerc29befb2004-12-15 01:50:13 +0000863
864#if defined(HAVE_MKSTEMP)
865 int TempFD;
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000866 if ((TempFD = mkstemp(FNBuffer)) == -1)
Reid Spencer51c5a282006-08-23 20:34:57 +0000867 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000868
869 // We don't need to hold the temp file descriptor... we will trust that no one
870 // will overwrite/delete the file before we can open it again.
871 close(TempFD);
872
873 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000874 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000875#elif defined(HAVE_MKTEMP)
876 // If we don't have mkstemp, use the old and obsolete mktemp function.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000877 if (mktemp(FNBuffer) == 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000878 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000879
880 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000881 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000882#else
883 // Okay, looks like we have to do it all by our lonesome.
884 static unsigned FCounter = 0;
Chris Lattner1f011092010-07-12 00:09:55 +0000885 // Try to initialize with unique value.
886 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
887 char* pos = strstr(FNBuffer, "XXXXXX");
888 do {
889 if (++FCounter > 0xFFFFFF) {
890 return MakeErrMsg(ErrMsg,
891 path + ": can't make unique filename: too many files");
892 }
893 sprintf(pos, "%06X", FCounter);
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000894 path = FNBuffer;
Chris Lattner1f011092010-07-12 00:09:55 +0000895 } while (exists());
896 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
897 // LLVM.
Reid Spencerc29befb2004-12-15 01:50:13 +0000898#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000899 return false;
900}
Reid Spencerc29befb2004-12-15 01:50:13 +0000901
Chris Lattner799ed102008-04-01 06:00:12 +0000902const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000903 int Flags = MAP_PRIVATE;
904#ifdef MAP_FILE
905 Flags |= MAP_FILE;
906#endif
907 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
908 if (BasePtr == MAP_FAILED)
909 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000910 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000911}
912
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000913void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000914 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000915}
916
Reid Spencer51c5a282006-08-23 20:34:57 +0000917} // end llvm namespace