blob: 4300d6719b3393e26f7174f6babf4f5ae10ebb24 [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
Chris Lattnerdbe89cd2009-08-23 22:57:38 +000019#include "llvm/ADT/SmallVector.h"
Reid Spencerb89a2232004-08-25 06:20:07 +000020#include "Unix.h"
Reid Spenceraf2f2082004-12-27 06:17:15 +000021#if HAVE_SYS_STAT_H
Reid Spencerb89a2232004-08-25 06:20:07 +000022#include <sys/stat.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000023#endif
24#if HAVE_FCNTL_H
Reid Spencerb89a2232004-08-25 06:20:07 +000025#include <fcntl.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000026#endif
Chris Lattner14c762d2008-04-01 06:25:23 +000027#ifdef HAVE_SYS_MMAN_H
28#include <sys/mman.h>
29#endif
30#ifdef HAVE_SYS_STAT_H
31#include <sys/stat.h>
32#endif
Reid Spenceraf2f2082004-12-27 06:17:15 +000033#if HAVE_UTIME_H
Reid Spencereaf18152004-11-14 22:08:36 +000034#include <utime.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000035#endif
36#if HAVE_TIME_H
Reid Spencer69a16162004-12-24 06:29:42 +000037#include <time.h>
Reid Spenceraf2f2082004-12-27 06:17:15 +000038#endif
39#if HAVE_DIRENT_H
40# include <dirent.h>
41# define NAMLEN(dirent) strlen((dirent)->d_name)
42#else
43# define dirent direct
44# define NAMLEN(dirent) (dirent)->d_namlen
45# if HAVE_SYS_NDIR_H
46# include <sys/ndir.h>
47# endif
48# if HAVE_SYS_DIR_H
49# include <sys/dir.h>
50# endif
51# if HAVE_NDIR_H
52# include <ndir.h>
53# endif
54#endif
55
Chris Lattner1a091442008-03-03 02:55:43 +000056#if HAVE_DLFCN_H
57#include <dlfcn.h>
58#endif
59
Benjamin Kramerd8b06302009-09-09 12:09:08 +000060#ifdef __APPLE__
61#include <mach-o/dyld.h>
62#endif
63
Reid Spencer932e2e32005-06-02 05:38:20 +000064// Put in a hack for Cygwin which falsely reports that the mkdtemp function
65// is available when it is not.
66#ifdef __CYGWIN__
67# undef HAVE_MKDTEMP
68#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000069
Reid Spencer3be872e2005-07-28 16:25:57 +000070namespace {
71inline bool lastIsSlash(const std::string& path) {
72 return !path.empty() && path[path.length() - 1] == '/';
73}
74
75}
76
Reid Spencer8e665952004-08-29 05:24:01 +000077namespace llvm {
78using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000079
Chris Lattnere1b332a2008-02-27 06:17:10 +000080extern const char sys::PathSeparator = ':';
81
Nick Lewyckyfff116f2008-05-11 17:37:40 +000082Path::Path(const std::string& p)
83 : path(p) {}
84
85Path::Path(const char *StrStart, unsigned StrLen)
86 : path(StrStart, StrLen) {}
87
Chris Lattner0eab5e22008-08-11 23:39:47 +000088Path&
89Path::operator=(const std::string &that) {
90 path = that;
91 return *this;
92}
93
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +000094bool
Reid Spencer69a16162004-12-24 06:29:42 +000095Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000096 // Check some obvious things
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +000097 if (path.empty())
Reid Spencer69a16162004-12-24 06:29:42 +000098 return false;
Chris Lattner0f550142009-07-12 19:01:16 +000099 return path.length() < MAXPATHLEN;
Reid Spencer69a16162004-12-24 06:29:42 +0000100}
101
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000102bool
Chris Lattner88d7e402009-06-15 04:17:07 +0000103Path::isAbsolute(const char *NameStart, unsigned NameLen) {
104 assert(NameStart);
105 if (NameLen == 0)
106 return false;
107 return NameStart[0] == '/';
108}
109
110bool
Reid Spencer69cce812007-03-29 16:43:20 +0000111Path::isAbsolute() const {
112 if (path.empty())
113 return false;
114 return path[0] == '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000115}
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000116
117void Path::makeAbsolute() {
118 if (isAbsolute())
119 return;
120
121 Path CWD = Path::GetCurrentDirectory();
122 assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
123
124 CWD.appendComponent(path);
125
Chris Lattner74382b72009-08-23 22:45:37 +0000126 path = CWD.str();
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000127}
128
Reid Spencer8e665952004-08-29 05:24:01 +0000129Path
130Path::GetRootDirectory() {
131 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000132 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000133 return result;
134}
135
Reid Spencer69a16162004-12-24 06:29:42 +0000136Path
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000137Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer69a16162004-12-24 06:29:42 +0000138#if defined(HAVE_MKDTEMP)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000139 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer69a16162004-12-24 06:29:42 +0000140 // Linux and FreeBSD have it. Others probably won't.
141 char pathname[MAXPATHLEN];
142 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000143 if (0 == mkdtemp(pathname)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000144 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000145 std::string(pathname) + ": can't create temporary directory");
146 return Path();
147 }
Reid Spencer69a16162004-12-24 06:29:42 +0000148 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000149 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000150 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
151 return result;
152#elif defined(HAVE_MKSTEMP)
153 // If no mkdtemp is available, mkstemp can be used to create a temporary file
154 // which is then removed and created as a directory. We prefer this over
155 // mktemp because of mktemp's inherent security and threading risks. We still
156 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000157 // the time it is re-created as a directoy.
Reid Spencer69a16162004-12-24 06:29:42 +0000158 char pathname[MAXPATHLEN];
159 strcpy(pathname, "/tmp/llvm_XXXXXX");
160 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000161 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000162 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000163 std::string(pathname) + ": can't create temporary directory");
164 return Path();
165 }
Reid Spencer69a16162004-12-24 06:29:42 +0000166 ::close(fd);
167 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000168 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000169 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000170 std::string(pathname) + ": can't create temporary directory");
171 return Path();
172 }
Reid Spencer69a16162004-12-24 06:29:42 +0000173 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000174 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000175 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
176 return result;
177#elif defined(HAVE_MKTEMP)
178 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
179 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
180 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
181 // the XXXXXX with the pid of the process and a letter. That leads to only
182 // twenty six temporary files that can be generated.
183 char pathname[MAXPATHLEN];
184 strcpy(pathname, "/tmp/llvm_XXXXXX");
185 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000186 if (TmpName == 0) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000187 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000188 std::string(TmpName) + ": can't create unique directory name");
189 return Path();
190 }
191 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000192 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000193 std::string(TmpName) + ": can't create temporary directory");
194 return Path();
195 }
Reid Spencer69a16162004-12-24 06:29:42 +0000196 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000197 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000198 assert(result.isValid() && "mktemp didn't create a valid pathname!");
199 return result;
200#else
201 // This is the worst case implementation. tempnam(3) leaks memory unless its
202 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
203 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000204 // temporary name generated. So, we provide our own implementation that
Reid Spencer69a16162004-12-24 06:29:42 +0000205 // increments an integer from a random number seeded by the current time. This
206 // should be sufficiently unique that we don't have many collisions between
207 // processes. Generally LLVM processes don't run very long and don't use very
208 // many temporary files so this shouldn't be a big issue for LLVM.
209 static time_t num = ::time(0);
210 char pathname[MAXPATHLEN];
211 do {
212 num++;
213 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
214 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000215 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000216 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000217 std::string(pathname) + ": can't create temporary directory");
218 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000219 }
Reid Spencer69a16162004-12-24 06:29:42 +0000220 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000221 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000222 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
223 return result;
224#endif
225}
226
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000227void
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000228Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
229#ifdef LTDL_SHLIBPATH_VAR
230 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
231 if (env_var != 0) {
232 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000233 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000234#endif
235 // FIXME: Should this look at LD_LIBRARY_PATH too?
236 Paths.push_back(sys::Path("/usr/local/lib/"));
237 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
238 Paths.push_back(sys::Path("/usr/lib/"));
239 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000240}
241
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000242void
Gabor Greifa99be512007-07-05 17:07:56 +0000243Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000244 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
245 if (env_var != 0) {
246 getPathList(env_var,Paths);
247 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000248#ifdef LLVM_LIBDIR
249 {
250 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000251 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000252 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000253 Paths.push_back(tmpPath);
254 }
255#endif
256 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000257}
258
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000259Path
Reid Spencer8e665952004-08-29 05:24:01 +0000260Path::GetLLVMDefaultConfigDir() {
261 return Path("/etc/llvm/");
262}
263
Reid Spencer8e665952004-08-29 05:24:01 +0000264Path
265Path::GetUserHomeDirectory() {
266 const char* home = getenv("HOME");
267 if (home) {
268 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000269 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000270 return result;
271 }
272 return GetRootDirectory();
273}
274
Ted Kremenek79200782007-12-18 22:07:33 +0000275Path
276Path::GetCurrentDirectory() {
277 char pathname[MAXPATHLEN];
278 if (!getcwd(pathname,MAXPATHLEN)) {
279 assert (false && "Could not query current working directory.");
280 return Path("");
281 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000282
Ted Kremenek79200782007-12-18 22:07:33 +0000283 return Path(pathname);
284}
Reid Spencera229c5c2005-07-08 03:08:58 +0000285
Chris Lattner893a0f92009-03-02 22:17:15 +0000286#ifdef __FreeBSD__
287static int
288test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
289 const char *dir, const char *bin)
290{
Bill Wendling51b16f42009-05-30 01:09:53 +0000291 struct stat sb;
Chris Lattner893a0f92009-03-02 22:17:15 +0000292
Bill Wendling51b16f42009-05-30 01:09:53 +0000293 snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
294 if (realpath(buf, ret) == NULL)
295 return (1);
296 if (stat(buf, &sb) != 0)
297 return (1);
298
299 return (0);
Chris Lattner893a0f92009-03-02 22:17:15 +0000300}
301
302static char *
303getprogpath(char ret[PATH_MAX], const char *bin)
304{
Bill Wendling51b16f42009-05-30 01:09:53 +0000305 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner893a0f92009-03-02 22:17:15 +0000306
Bill Wendling51b16f42009-05-30 01:09:53 +0000307 /* First approach: absolute path. */
308 if (bin[0] == '/') {
309 if (test_dir(buf, ret, "/", bin) == 0)
310 return (ret);
311 return (NULL);
312 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000313
Bill Wendling51b16f42009-05-30 01:09:53 +0000314 /* Second approach: relative path. */
315 if (strchr(bin, '/') != NULL) {
316 if (getcwd(buf, PATH_MAX) == NULL)
317 return (NULL);
318 if (test_dir(buf, ret, buf, bin) == 0)
319 return (ret);
320 return (NULL);
321 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000322
Bill Wendling51b16f42009-05-30 01:09:53 +0000323 /* Third approach: $PATH */
324 if ((pv = getenv("PATH")) == NULL)
325 return (NULL);
326 s = pv = strdup(pv);
327 if (pv == NULL)
328 return (NULL);
329 while ((t = strsep(&s, ":")) != NULL) {
330 if (test_dir(buf, ret, t, bin) == 0) {
331 free(pv);
332 return (ret);
333 }
334 }
335 free(pv);
336 return (NULL);
Chris Lattner893a0f92009-03-02 22:17:15 +0000337}
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000338#endif // __FreeBSD__
Chris Lattner893a0f92009-03-02 22:17:15 +0000339
Chris Lattner1a091442008-03-03 02:55:43 +0000340/// GetMainExecutable - Return the path to the main executable, given the
341/// value of argv[0] from program startup.
342Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000343#if defined(__APPLE__)
344 // On OS X the executable path is saved to the stack by dyld. Reading it
345 // from there is much faster than calling dladdr, especially for large
346 // binaries with symbols.
347 char exe_path[MAXPATHLEN];
348 uint32_t size = sizeof(exe_path);
349 if (_NSGetExecutablePath(exe_path, &size) == 0) {
350 char link_path[MAXPATHLEN];
351 return Path(std::string(realpath(exe_path, link_path)));
352 }
353#elif defined(__FreeBSD__)
Chris Lattner893a0f92009-03-02 22:17:15 +0000354 char exe_path[PATH_MAX];
355
356 if (getprogpath(exe_path, argv0) != NULL)
357 return Path(std::string(exe_path));
358#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattner3bdfa042008-03-13 05:22:05 +0000359 char exe_path[MAXPATHLEN];
Seo Sanghyeonfd6437f2008-06-27 22:55:30 +0000360 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Dan Gohman7b3544b2009-08-05 20:16:55 +0000361 if (len >= 0)
362 return Path(std::string(exe_path, len));
Chris Lattner3bdfa042008-03-13 05:22:05 +0000363#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000364 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000365 Dl_info DLInfo;
366 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000367 if (err == 0)
368 return Path();
Bill Wendling51b16f42009-05-30 01:09:53 +0000369
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000370 // If the filename is a symlink, we need to resolve and return the location of
371 // the actual executable.
372 char link_path[MAXPATHLEN];
373 return Path(std::string(realpath(DLInfo.dli_fname, link_path)));
Chris Lattner1a091442008-03-03 02:55:43 +0000374#endif
375 return Path();
376}
377
378
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000379std::string Path::getDirname() const {
380 return getDirnameCharSep(path, '/');
381}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000382
Reid Spencer1b554b42004-09-11 04:55:08 +0000383std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000384Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000385 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000386 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000387 if (slash == std::string::npos)
388 slash = 0;
389 else
390 slash++;
391
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000392 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000393 if (dot == std::string::npos || dot < slash)
394 return path.substr(slash);
395 else
396 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000397}
398
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000399std::string
400Path::getSuffix() const {
401 // Find the last slash
402 std::string::size_type slash = path.rfind('/');
403 if (slash == std::string::npos)
404 slash = 0;
405 else
406 slash++;
407
408 std::string::size_type dot = path.rfind('.');
409 if (dot == std::string::npos || dot < slash)
Wojciech Matyjewicz93c53462008-06-15 18:02:47 +0000410 return std::string();
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000411 else
412 return path.substr(dot + 1);
413}
414
Reid Spencereaf18152004-11-14 22:08:36 +0000415bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000416 assert(len < 1024 && "Request for magic string too long");
Chris Lattnerdbe89cd2009-08-23 22:57:38 +0000417 SmallVector<char, 128> Buf;
418 Buf.resize(1 + len);
419 char* buf = Buf.data();
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000420 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000421 if (fd < 0)
422 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000423 ssize_t bytes_read = ::read(fd, buf, len);
424 ::close(fd);
425 if (ssize_t(len) != bytes_read) {
426 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000427 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000428 }
429 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000430 return true;
431}
432
Reid Spencer1b554b42004-09-11 04:55:08 +0000433bool
Reid Spencer8e665952004-08-29 05:24:01 +0000434Path::exists() const {
435 return 0 == access(path.c_str(), F_OK );
436}
437
438bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000439Path::isDirectory() const {
440 struct stat buf;
441 if (0 != stat(path.c_str(), &buf))
442 return false;
443 return buf.st_mode & S_IFDIR ? true : false;
444}
445
446bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000447Path::canRead() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000448 return 0 == access(path.c_str(), R_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000449}
450
451bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000452Path::canWrite() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000453 return 0 == access(path.c_str(), W_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000454}
455
456bool
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000457Path::isRegularFile() const {
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000458 // Get the status so we can determine if its a file or directory
459 struct stat buf;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000460
Daniel Dunbar98e46d82009-11-24 19:03:33 +0000461 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000462 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000463
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000464 if (S_ISREG(buf.st_mode))
465 return true;
466
467 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000468}
469
470bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000471Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000472 if (0 != access(path.c_str(), R_OK | X_OK ))
473 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000474 struct stat buf;
475 if (0 != stat(path.c_str(), &buf))
476 return false;
477 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000478 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000479 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000480}
481
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000482std::string
Reid Spencer8e665952004-08-29 05:24:01 +0000483Path::getLast() const {
484 // Find the last slash
485 size_t pos = path.rfind('/');
486
487 // Handle the corner cases
488 if (pos == std::string::npos)
489 return path;
490
491 // If the last character is a slash
492 if (pos == path.length()-1) {
493 // Find the second to last slash
494 size_t pos2 = path.rfind('/', pos-1);
495 if (pos2 == std::string::npos)
496 return path.substr(0,pos);
497 else
498 return path.substr(pos2+1,pos-pos2-1);
499 }
500 // Return everything after the last slash
501 return path.substr(pos+1);
502}
503
Reid Spencer2ae9d112007-04-07 18:52:17 +0000504const FileStatus *
505PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
506 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000507 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000508 if (0 != stat(path.c_str(), &buf)) {
509 MakeErrMsg(ErrStr, path + ": can't get status of file");
510 return 0;
511 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000512 status.fileSize = buf.st_size;
513 status.modTime.fromEpochTime(buf.st_mtime);
514 status.mode = buf.st_mode;
515 status.user = buf.st_uid;
516 status.group = buf.st_gid;
517 status.uniqueID = uint64_t(buf.st_ino);
518 status.isDir = S_ISDIR(buf.st_mode);
519 status.isFile = S_ISREG(buf.st_mode);
520 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000521 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000522 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000523}
524
Chris Lattner252ad032006-07-28 22:03:44 +0000525static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000526 // Get the umask value from the operating system. We want to use it
527 // when changing the file's permissions. Since calling umask() sets
528 // the umask and returns its old value, we must call it a second
529 // time to reset it to the user's preference.
530 int mask = umask(0777); // The arg. to umask is arbitrary.
531 umask(mask); // Restore the umask.
532
533 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000534 struct stat buf;
Chris Lattner74382b72009-08-23 22:45:37 +0000535 if (0 != stat(File.c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000536 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000537 // Change the file to have whichever permissions bits from 'bits'
538 // that the umask would not disable.
539 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
540 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000541 return true;
542}
543
Reid Spencere1647f42006-08-22 23:27:23 +0000544bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000545 if (!AddPermissionBits(*this, 0444))
Reid Spencer5a060772006-08-23 07:30:48 +0000546 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000547 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000548}
549
Reid Spencere1647f42006-08-22 23:27:23 +0000550bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000551 if (!AddPermissionBits(*this, 0222))
552 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000553 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000554}
555
Reid Spencere1647f42006-08-22 23:27:23 +0000556bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000557 if (!AddPermissionBits(*this, 0111))
558 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000559 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000560}
561
Reid Spencereaf18152004-11-14 22:08:36 +0000562bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000563Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000564 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000565 if (direntries == 0)
566 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000567
Reid Spencer3be872e2005-07-28 16:25:57 +0000568 std::string dirPath = path;
569 if (!lastIsSlash(dirPath))
570 dirPath += '/';
571
Reid Spencereaf18152004-11-14 22:08:36 +0000572 result.clear();
573 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000574 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000575 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000576 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000577 struct stat st;
578 if (0 != lstat(aPath.path.c_str(), &st)) {
579 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000580 continue; // dangling symlink -- ignore
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000581 return MakeErrMsg(ErrMsg,
Reid Spencer5a060772006-08-23 07:30:48 +0000582 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000583 }
Reid Spencerb608a812004-11-16 06:15:19 +0000584 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000585 }
Reid Spencereaf18152004-11-14 22:08:36 +0000586 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000587
Reid Spencereaf18152004-11-14 22:08:36 +0000588 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000589 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000590}
591
Reid Spencer8e665952004-08-29 05:24:01 +0000592bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000593Path::set(const std::string& a_path) {
594 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000595 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000596 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000597 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000598 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000599 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000600 return false;
601 }
602 return true;
603}
604
605bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000606Path::appendComponent(const std::string& name) {
607 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000608 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000609 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000610 if (!lastIsSlash(path))
611 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000612 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000613 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000614 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000615 return false;
616 }
617 return true;
618}
619
620bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000621Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000622 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000623 if (slashpos == 0 || slashpos == std::string::npos) {
624 path.erase();
625 return true;
626 }
Reid Spencer8e665952004-08-29 05:24:01 +0000627 if (slashpos == path.size() - 1)
628 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000629 if (slashpos == std::string::npos) {
630 path.erase();
631 return true;
632 }
Reid Spencer8e665952004-08-29 05:24:01 +0000633 path.erase(slashpos);
634 return true;
635}
636
637bool
Reid Spencer07adb282004-11-05 22:15:36 +0000638Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000639 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000640 path.append(".");
641 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000642 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000643 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000644 return false;
645 }
646 return true;
647}
648
Reid Spencerdd04df02005-07-07 23:21:43 +0000649bool
650Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000651 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000652 size_t dotpos = path.rfind('.',path.size());
653 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000654 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000655 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000656 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000657 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000658 }
Reid Spencer8e665952004-08-29 05:24:01 +0000659 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000660 if (!isValid())
661 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000662 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000663}
664
Ted Kremenekc5412c52008-04-03 16:11:31 +0000665static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000666
Dan Gohman28daa102009-07-29 00:02:58 +0000667 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenekc5412c52008-04-03 16:11:31 +0000668 return false;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000669
Ted Kremenekc5412c52008-04-03 16:11:31 +0000670 if (create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000671
Ted Kremenekc5412c52008-04-03 16:11:31 +0000672 char* c = end;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000673
Ted Kremenekc5412c52008-04-03 16:11:31 +0000674 for (; c != beg; --c)
675 if (*c == '/') {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000676
Ted Kremenekc5412c52008-04-03 16:11:31 +0000677 // Recurse to handling the parent directory.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000678 *c = '\0';
Ted Kremenekc5412c52008-04-03 16:11:31 +0000679 bool x = createDirectoryHelper(beg, c, create_parents);
680 *c = '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000681
Ted Kremenekc5412c52008-04-03 16:11:31 +0000682 // Return if we encountered an error.
683 if (x)
684 return true;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000685
Ted Kremenekc5412c52008-04-03 16:11:31 +0000686 break;
687 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000688 }
689
Ted Kremenekc5412c52008-04-03 16:11:31 +0000690 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
691}
692
Reid Spencer8e665952004-08-29 05:24:01 +0000693bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000694Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000695 // Get a writeable copy of the path name
696 char pathname[MAXPATHLEN];
697 path.copy(pathname,MAXPATHLEN);
698
699 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000700 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000701
Ted Kremenekc5412c52008-04-03 16:11:31 +0000702 if (pathname[lastchar] != '/')
703 ++lastchar;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000704
Ted Kremenekc5412c52008-04-03 16:11:31 +0000705 pathname[lastchar] = 0;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000706
Ted Kremenekc5412c52008-04-03 16:11:31 +0000707 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000708 return MakeErrMsg(ErrMsg,
Ted Kremenekc5412c52008-04-03 16:11:31 +0000709 std::string(pathname) + ": can't create directory");
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000710
Reid Spencere5c9cb52006-08-23 00:39:35 +0000711 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000712}
713
714bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000715Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000716 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000717 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000718 if (fd < 0)
719 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000720 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000721 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000722}
723
Reid Spencer8e665952004-08-29 05:24:01 +0000724bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000725Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000726 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000727 if (makeUnique( reuse_current, ErrMsg ))
728 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000729
730 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000731 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000732 if (fd < 0)
Reid Spencer5a060772006-08-23 07:30:48 +0000733 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000734 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000735 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000736}
737
738bool
Chris Lattner0c332312006-07-28 22:29:50 +0000739Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000740 // Get the status so we can determine if its a file or directory
Reid Spencer2ae9d112007-04-07 18:52:17 +0000741 struct stat buf;
742 if (0 != stat(path.c_str(), &buf)) {
743 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000744 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000745 }
746
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000747 // Note: this check catches strange situations. In all cases, LLVM should
748 // only be involved in the creation and deletion of regular files. This
749 // check ensures that what we're trying to erase is a regular file. It
750 // effectively prevents LLVM from erasing things like /dev/null, any block
751 // special file, or other things that aren't "regular" files.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000752 if (S_ISREG(buf.st_mode)) {
753 if (unlink(path.c_str()) != 0)
754 return MakeErrMsg(ErrStr, path + ": can't destroy file");
755 return false;
756 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000757
Reid Spencer2ae9d112007-04-07 18:52:17 +0000758 if (!S_ISDIR(buf.st_mode)) {
759 if (ErrStr) *ErrStr = "not a file or directory";
760 return true;
761 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000762
Chris Lattner0c332312006-07-28 22:29:50 +0000763 if (remove_contents) {
764 // Recursively descend the directory to remove its contents.
765 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov8eada622009-02-15 03:20:32 +0000766 if (system(cmd.c_str()) != 0) {
767 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
768 return true;
769 }
Chris Lattner0c332312006-07-28 22:29:50 +0000770 return false;
771 }
772
773 // Otherwise, try to just remove the one directory.
774 char pathname[MAXPATHLEN];
775 path.copy(pathname, MAXPATHLEN);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000776 size_t lastchar = path.length() - 1;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000777 if (pathname[lastchar] == '/')
Chris Lattner0c332312006-07-28 22:29:50 +0000778 pathname[lastchar] = 0;
779 else
780 pathname[lastchar+1] = 0;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000781
Chris Lattner0c332312006-07-28 22:29:50 +0000782 if (rmdir(pathname) != 0)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000783 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000784 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000785 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000786}
787
788bool
Reid Spencer5a060772006-08-23 07:30:48 +0000789Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000790 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000791 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattner74382b72009-08-23 22:45:37 +0000792 newName.str() + "'");
Reid Spencer5a060772006-08-23 07:30:48 +0000793 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000794}
795
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000796bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000797Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000798 struct utimbuf utb;
799 utb.actime = si.modTime.toPosixTime();
800 utb.modtime = utb.actime;
801 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000802 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000803 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000804 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000805 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000806}
807
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000808bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000809sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000810 int inFile = -1;
811 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000812 inFile = ::open(Src.c_str(), O_RDONLY);
813 if (inFile == -1)
Chris Lattner74382b72009-08-23 22:45:37 +0000814 return MakeErrMsg(ErrMsg, Src.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000815 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000816
Reid Spencer51c5a282006-08-23 20:34:57 +0000817 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
818 if (outFile == -1) {
819 ::close(inFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000820 return MakeErrMsg(ErrMsg, Dest.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000821 ": can't create destination file for copy");
822 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000823
Reid Spencer51c5a282006-08-23 20:34:57 +0000824 char Buffer[16*1024];
825 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
826 if (Amt == -1) {
827 if (errno != EINTR && errno != EAGAIN) {
828 ::close(inFile);
829 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000830 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Reid Spencer51c5a282006-08-23 20:34:57 +0000831 }
832 } else {
833 char *BufPtr = Buffer;
834 while (Amt) {
835 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
836 if (AmtWritten == -1) {
837 if (errno != EINTR && errno != EAGAIN) {
838 ::close(inFile);
839 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000840 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000841 ": can't write destination file");
Reid Spencerc29befb2004-12-15 01:50:13 +0000842 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000843 } else {
844 Amt -= AmtWritten;
845 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000846 }
847 }
848 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000849 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000850 ::close(inFile);
851 ::close(outFile);
852 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000853}
854
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000855bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000856Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000857 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000858 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000859
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000860 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerc29befb2004-12-15 01:50:13 +0000861 // mktemp or our own implementation.
Chris Lattnerdbe89cd2009-08-23 22:57:38 +0000862 SmallVector<char, 128> Buf;
863 Buf.resize(path.size()+8);
864 char *FNBuffer = Buf.data();
Devang Patelce8fdf12008-07-22 20:02:39 +0000865 path.copy(FNBuffer,path.size());
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000866 if (isDirectory())
867 strcpy(FNBuffer+path.size(), "/XXXXXX");
868 else
Devang Patelce8fdf12008-07-22 20:02:39 +0000869 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerc29befb2004-12-15 01:50:13 +0000870
871#if defined(HAVE_MKSTEMP)
872 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000873 if ((TempFD = mkstemp(FNBuffer)) == -1)
874 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000875
876 // We don't need to hold the temp file descriptor... we will trust that no one
877 // will overwrite/delete the file before we can open it again.
878 close(TempFD);
879
880 // Save the name
881 path = FNBuffer;
882#elif defined(HAVE_MKTEMP)
883 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000884 if (mktemp(FNBuffer) == 0)
885 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000886
887 // Save the name
888 path = FNBuffer;
889#else
890 // Okay, looks like we have to do it all by our lonesome.
891 static unsigned FCounter = 0;
892 unsigned offset = path.size() + 1;
893 while ( FCounter < 999999 && exists()) {
894 sprintf(FNBuffer+offset,"%06u",++FCounter);
895 path = FNBuffer;
896 }
897 if (FCounter > 999999)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000898 return MakeErrMsg(ErrMsg,
Reid Spencer51c5a282006-08-23 20:34:57 +0000899 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000900#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000901 return false;
902}
Reid Spencerc29befb2004-12-15 01:50:13 +0000903
Chris Lattner799ed102008-04-01 06:00:12 +0000904const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000905 int Flags = MAP_PRIVATE;
906#ifdef MAP_FILE
907 Flags |= MAP_FILE;
908#endif
909 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
910 if (BasePtr == MAP_FAILED)
911 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000912 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000913}
914
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000915void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000916 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000917}
918
Reid Spencer51c5a282006-08-23 20:34:57 +0000919} // end llvm namespace