blob: 1f73571cf140ba350d6efd80735d6169f774b6eb [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
Misha Brukman210b32b2004-12-20 00:16:38 +000019#include "llvm/Config/alloca.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
Reid Spencer932e2e32005-06-02 05:38:20 +000060// Put in a hack for Cygwin which falsely reports that the mkdtemp function
61// is available when it is not.
62#ifdef __CYGWIN__
63# undef HAVE_MKDTEMP
64#endif
Reid Spencerb89a2232004-08-25 06:20:07 +000065
Reid Spencer3be872e2005-07-28 16:25:57 +000066namespace {
67inline bool lastIsSlash(const std::string& path) {
68 return !path.empty() && path[path.length() - 1] == '/';
69}
70
71}
72
Reid Spencer8e665952004-08-29 05:24:01 +000073namespace llvm {
74using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000075
Chris Lattnere1b332a2008-02-27 06:17:10 +000076extern const char sys::PathSeparator = ':';
77
Nick Lewyckyfff116f2008-05-11 17:37:40 +000078Path::Path(const std::string& p)
79 : path(p) {}
80
81Path::Path(const char *StrStart, unsigned StrLen)
82 : path(StrStart, StrLen) {}
83
Chris Lattner0eab5e22008-08-11 23:39:47 +000084Path&
85Path::operator=(const std::string &that) {
86 path = that;
87 return *this;
88}
89
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +000090bool
Reid Spencer69a16162004-12-24 06:29:42 +000091Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000092 // Check some obvious things
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +000093 if (path.empty())
Reid Spencer69a16162004-12-24 06:29:42 +000094 return false;
95 else if (path.length() >= MAXPATHLEN)
96 return false;
Reid Spencer6371ccb2005-07-08 06:53:26 +000097
98 // Check that the characters are ascii chars
99 size_t len = path.length();
100 unsigned i = 0;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000101 while (i < len && isascii(path[i]))
Reid Spencer6371ccb2005-07-08 06:53:26 +0000102 ++i;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000103 return i >= len;
Reid Spencer69a16162004-12-24 06:29:42 +0000104}
105
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000106bool
Chris Lattner88d7e402009-06-15 04:17:07 +0000107Path::isAbsolute(const char *NameStart, unsigned NameLen) {
108 assert(NameStart);
109 if (NameLen == 0)
110 return false;
111 return NameStart[0] == '/';
112}
113
114bool
Reid Spencer69cce812007-03-29 16:43:20 +0000115Path::isAbsolute() const {
116 if (path.empty())
117 return false;
118 return path[0] == '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000119}
Reid Spencer8e665952004-08-29 05:24:01 +0000120Path
121Path::GetRootDirectory() {
122 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000123 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000124 return result;
125}
126
Reid Spencer69a16162004-12-24 06:29:42 +0000127Path
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000128Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer69a16162004-12-24 06:29:42 +0000129#if defined(HAVE_MKDTEMP)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000130 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer69a16162004-12-24 06:29:42 +0000131 // Linux and FreeBSD have it. Others probably won't.
132 char pathname[MAXPATHLEN];
133 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000134 if (0 == mkdtemp(pathname)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000135 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000136 std::string(pathname) + ": can't create temporary directory");
137 return Path();
138 }
Reid Spencer69a16162004-12-24 06:29:42 +0000139 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000140 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000141 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
142 return result;
143#elif defined(HAVE_MKSTEMP)
144 // If no mkdtemp is available, mkstemp can be used to create a temporary file
145 // which is then removed and created as a directory. We prefer this over
146 // mktemp because of mktemp's inherent security and threading risks. We still
147 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000148 // the time it is re-created as a directoy.
Reid Spencer69a16162004-12-24 06:29:42 +0000149 char pathname[MAXPATHLEN];
150 strcpy(pathname, "/tmp/llvm_XXXXXX");
151 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000152 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000153 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000154 std::string(pathname) + ": can't create temporary directory");
155 return Path();
156 }
Reid Spencer69a16162004-12-24 06:29:42 +0000157 ::close(fd);
158 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000159 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000160 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000161 std::string(pathname) + ": can't create temporary directory");
162 return Path();
163 }
Reid Spencer69a16162004-12-24 06:29:42 +0000164 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000165 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000166 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
167 return result;
168#elif defined(HAVE_MKTEMP)
169 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
170 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
171 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
172 // the XXXXXX with the pid of the process and a letter. That leads to only
173 // twenty six temporary files that can be generated.
174 char pathname[MAXPATHLEN];
175 strcpy(pathname, "/tmp/llvm_XXXXXX");
176 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000177 if (TmpName == 0) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000178 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000179 std::string(TmpName) + ": can't create unique directory name");
180 return Path();
181 }
182 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000183 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000184 std::string(TmpName) + ": can't create temporary directory");
185 return Path();
186 }
Reid Spencer69a16162004-12-24 06:29:42 +0000187 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000188 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000189 assert(result.isValid() && "mktemp didn't create a valid pathname!");
190 return result;
191#else
192 // This is the worst case implementation. tempnam(3) leaks memory unless its
193 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
194 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000195 // temporary name generated. So, we provide our own implementation that
Reid Spencer69a16162004-12-24 06:29:42 +0000196 // increments an integer from a random number seeded by the current time. This
197 // should be sufficiently unique that we don't have many collisions between
198 // processes. Generally LLVM processes don't run very long and don't use very
199 // many temporary files so this shouldn't be a big issue for LLVM.
200 static time_t num = ::time(0);
201 char pathname[MAXPATHLEN];
202 do {
203 num++;
204 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
205 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000206 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000207 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000208 std::string(pathname) + ": can't create temporary directory");
209 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000210 }
Reid Spencer69a16162004-12-24 06:29:42 +0000211 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000212 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000213 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
214 return result;
215#endif
216}
217
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000218void
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000219Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
220#ifdef LTDL_SHLIBPATH_VAR
221 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
222 if (env_var != 0) {
223 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000224 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000225#endif
226 // FIXME: Should this look at LD_LIBRARY_PATH too?
227 Paths.push_back(sys::Path("/usr/local/lib/"));
228 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
229 Paths.push_back(sys::Path("/usr/lib/"));
230 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000231}
232
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000233void
Gabor Greifa99be512007-07-05 17:07:56 +0000234Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000235 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
236 if (env_var != 0) {
237 getPathList(env_var,Paths);
238 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000239#ifdef LLVM_LIBDIR
240 {
241 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000242 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000243 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000244 Paths.push_back(tmpPath);
245 }
246#endif
247 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000248}
249
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000250Path
Reid Spencer8e665952004-08-29 05:24:01 +0000251Path::GetLLVMDefaultConfigDir() {
252 return Path("/etc/llvm/");
253}
254
Reid Spencer8e665952004-08-29 05:24:01 +0000255Path
256Path::GetUserHomeDirectory() {
257 const char* home = getenv("HOME");
258 if (home) {
259 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000260 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000261 return result;
262 }
263 return GetRootDirectory();
264}
265
Ted Kremenek79200782007-12-18 22:07:33 +0000266Path
267Path::GetCurrentDirectory() {
268 char pathname[MAXPATHLEN];
269 if (!getcwd(pathname,MAXPATHLEN)) {
270 assert (false && "Could not query current working directory.");
271 return Path("");
272 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000273
Ted Kremenek79200782007-12-18 22:07:33 +0000274 return Path(pathname);
275}
Reid Spencera229c5c2005-07-08 03:08:58 +0000276
Chris Lattner893a0f92009-03-02 22:17:15 +0000277#ifdef __FreeBSD__
278static int
279test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
280 const char *dir, const char *bin)
281{
Bill Wendling51b16f42009-05-30 01:09:53 +0000282 struct stat sb;
Chris Lattner893a0f92009-03-02 22:17:15 +0000283
Bill Wendling51b16f42009-05-30 01:09:53 +0000284 snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
285 if (realpath(buf, ret) == NULL)
286 return (1);
287 if (stat(buf, &sb) != 0)
288 return (1);
289
290 return (0);
Chris Lattner893a0f92009-03-02 22:17:15 +0000291}
292
293static char *
294getprogpath(char ret[PATH_MAX], const char *bin)
295{
Bill Wendling51b16f42009-05-30 01:09:53 +0000296 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner893a0f92009-03-02 22:17:15 +0000297
Bill Wendling51b16f42009-05-30 01:09:53 +0000298 /* First approach: absolute path. */
299 if (bin[0] == '/') {
300 if (test_dir(buf, ret, "/", bin) == 0)
301 return (ret);
302 return (NULL);
303 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000304
Bill Wendling51b16f42009-05-30 01:09:53 +0000305 /* Second approach: relative path. */
306 if (strchr(bin, '/') != NULL) {
307 if (getcwd(buf, PATH_MAX) == NULL)
308 return (NULL);
309 if (test_dir(buf, ret, buf, 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 /* Third approach: $PATH */
315 if ((pv = getenv("PATH")) == NULL)
316 return (NULL);
317 s = pv = strdup(pv);
318 if (pv == NULL)
319 return (NULL);
320 while ((t = strsep(&s, ":")) != NULL) {
321 if (test_dir(buf, ret, t, bin) == 0) {
322 free(pv);
323 return (ret);
324 }
325 }
326 free(pv);
327 return (NULL);
Chris Lattner893a0f92009-03-02 22:17:15 +0000328}
329#endif
330
Chris Lattner1a091442008-03-03 02:55:43 +0000331/// GetMainExecutable - Return the path to the main executable, given the
332/// value of argv[0] from program startup.
333Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Chris Lattner893a0f92009-03-02 22:17:15 +0000334#if defined(__FreeBSD__)
335 char exe_path[PATH_MAX];
336
337 if (getprogpath(exe_path, argv0) != NULL)
338 return Path(std::string(exe_path));
339#elif defined(__linux__) || defined(__CYGWIN__)
Chris Lattner3bdfa042008-03-13 05:22:05 +0000340 char exe_path[MAXPATHLEN];
Seo Sanghyeonfd6437f2008-06-27 22:55:30 +0000341 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Chris Lattner3bdfa042008-03-13 05:22:05 +0000342 if (len > 0 && len < MAXPATHLEN - 1) {
343 exe_path[len] = '\0';
344 return Path(std::string(exe_path));
345 }
346#elif defined(HAVE_DLFCN_H)
Chris Lattner1a091442008-03-03 02:55:43 +0000347 // Use dladdr to get executable path if available.
Chris Lattner1a091442008-03-03 02:55:43 +0000348 Dl_info DLInfo;
349 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000350 if (err == 0)
351 return Path();
Bill Wendling51b16f42009-05-30 01:09:53 +0000352
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000353 // If the filename is a symlink, we need to resolve and return the location of
354 // the actual executable.
355 char link_path[MAXPATHLEN];
356 return Path(std::string(realpath(DLInfo.dli_fname, link_path)));
Chris Lattner1a091442008-03-03 02:55:43 +0000357#endif
358 return Path();
359}
360
361
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000362std::string Path::getDirname() const {
363 return getDirnameCharSep(path, '/');
364}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000365
Reid Spencer1b554b42004-09-11 04:55:08 +0000366std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000367Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000368 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000369 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000370 if (slash == std::string::npos)
371 slash = 0;
372 else
373 slash++;
374
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000375 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000376 if (dot == std::string::npos || dot < slash)
377 return path.substr(slash);
378 else
379 return path.substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000380}
381
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000382std::string
383Path::getSuffix() const {
384 // Find the last slash
385 std::string::size_type slash = path.rfind('/');
386 if (slash == std::string::npos)
387 slash = 0;
388 else
389 slash++;
390
391 std::string::size_type dot = path.rfind('.');
392 if (dot == std::string::npos || dot < slash)
Wojciech Matyjewicz93c53462008-06-15 18:02:47 +0000393 return std::string();
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000394 else
395 return path.substr(dot + 1);
396}
397
Reid Spencereaf18152004-11-14 22:08:36 +0000398bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000399 assert(len < 1024 && "Request for magic string too long");
400 char* buf = (char*) alloca(1 + len);
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000401 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000402 if (fd < 0)
403 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000404 ssize_t bytes_read = ::read(fd, buf, len);
405 ::close(fd);
406 if (ssize_t(len) != bytes_read) {
407 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000408 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000409 }
410 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000411 return true;
412}
413
Reid Spencer1b554b42004-09-11 04:55:08 +0000414bool
Reid Spencer8e665952004-08-29 05:24:01 +0000415Path::exists() const {
416 return 0 == access(path.c_str(), F_OK );
417}
418
419bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000420Path::isDirectory() const {
421 struct stat buf;
422 if (0 != stat(path.c_str(), &buf))
423 return false;
424 return buf.st_mode & S_IFDIR ? true : false;
425}
426
427bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000428Path::canRead() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000429 return 0 == access(path.c_str(), F_OK | R_OK );
430}
431
432bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000433Path::canWrite() const {
Reid Spencer8e665952004-08-29 05:24:01 +0000434 return 0 == access(path.c_str(), F_OK | W_OK );
435}
436
437bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000438Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000439 if (0 != access(path.c_str(), R_OK | X_OK ))
440 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000441 struct stat buf;
442 if (0 != stat(path.c_str(), &buf))
443 return false;
444 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000445 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000446 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000447}
448
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000449std::string
Reid Spencer8e665952004-08-29 05:24:01 +0000450Path::getLast() const {
451 // Find the last slash
452 size_t pos = path.rfind('/');
453
454 // Handle the corner cases
455 if (pos == std::string::npos)
456 return path;
457
458 // If the last character is a slash
459 if (pos == path.length()-1) {
460 // Find the second to last slash
461 size_t pos2 = path.rfind('/', pos-1);
462 if (pos2 == std::string::npos)
463 return path.substr(0,pos);
464 else
465 return path.substr(pos2+1,pos-pos2-1);
466 }
467 // Return everything after the last slash
468 return path.substr(pos+1);
469}
470
Reid Spencer2ae9d112007-04-07 18:52:17 +0000471const FileStatus *
472PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
473 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000474 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000475 if (0 != stat(path.c_str(), &buf)) {
476 MakeErrMsg(ErrStr, path + ": can't get status of file");
477 return 0;
478 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000479 status.fileSize = buf.st_size;
480 status.modTime.fromEpochTime(buf.st_mtime);
481 status.mode = buf.st_mode;
482 status.user = buf.st_uid;
483 status.group = buf.st_gid;
484 status.uniqueID = uint64_t(buf.st_ino);
485 status.isDir = S_ISDIR(buf.st_mode);
486 status.isFile = S_ISREG(buf.st_mode);
487 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000488 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000489 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000490}
491
Chris Lattner252ad032006-07-28 22:03:44 +0000492static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000493 // Get the umask value from the operating system. We want to use it
494 // when changing the file's permissions. Since calling umask() sets
495 // the umask and returns its old value, we must call it a second
496 // time to reset it to the user's preference.
497 int mask = umask(0777); // The arg. to umask is arbitrary.
498 umask(mask); // Restore the umask.
499
500 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000501 struct stat buf;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000502 if (0 != stat(File.toString().c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000503 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000504 // Change the file to have whichever permissions bits from 'bits'
505 // that the umask would not disable.
506 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
507 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000508 return true;
509}
510
Reid Spencere1647f42006-08-22 23:27:23 +0000511bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000512 if (!AddPermissionBits(*this, 0444))
Reid Spencer5a060772006-08-23 07:30:48 +0000513 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000514 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000515}
516
Reid Spencere1647f42006-08-22 23:27:23 +0000517bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000518 if (!AddPermissionBits(*this, 0222))
519 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
Reid Spencere1647f42006-08-22 23:27:23 +0000520 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000521}
522
Reid Spencere1647f42006-08-22 23:27:23 +0000523bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000524 if (!AddPermissionBits(*this, 0111))
525 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000526 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000527}
528
Reid Spencereaf18152004-11-14 22:08:36 +0000529bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000530Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000531 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000532 if (direntries == 0)
533 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000534
Reid Spencer3be872e2005-07-28 16:25:57 +0000535 std::string dirPath = path;
536 if (!lastIsSlash(dirPath))
537 dirPath += '/';
538
Reid Spencereaf18152004-11-14 22:08:36 +0000539 result.clear();
540 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000541 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000542 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000543 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000544 struct stat st;
545 if (0 != lstat(aPath.path.c_str(), &st)) {
546 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000547 continue; // dangling symlink -- ignore
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000548 return MakeErrMsg(ErrMsg,
Reid Spencer5a060772006-08-23 07:30:48 +0000549 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000550 }
Reid Spencerb608a812004-11-16 06:15:19 +0000551 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000552 }
Reid Spencereaf18152004-11-14 22:08:36 +0000553 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000554
Reid Spencereaf18152004-11-14 22:08:36 +0000555 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000556 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000557}
558
Reid Spencer8e665952004-08-29 05:24:01 +0000559bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000560Path::set(const std::string& a_path) {
561 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000562 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000563 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000564 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000565 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000566 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000567 return false;
568 }
569 return true;
570}
571
572bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000573Path::appendComponent(const std::string& name) {
574 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000575 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000576 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000577 if (!lastIsSlash(path))
578 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000579 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000580 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000581 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000582 return false;
583 }
584 return true;
585}
586
587bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000588Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000589 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000590 if (slashpos == 0 || slashpos == std::string::npos) {
591 path.erase();
592 return true;
593 }
Reid Spencer8e665952004-08-29 05:24:01 +0000594 if (slashpos == path.size() - 1)
595 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000596 if (slashpos == std::string::npos) {
597 path.erase();
598 return true;
599 }
Reid Spencer8e665952004-08-29 05:24:01 +0000600 path.erase(slashpos);
601 return true;
602}
603
604bool
Reid Spencer07adb282004-11-05 22:15:36 +0000605Path::appendSuffix(const std::string& suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000606 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000607 path.append(".");
608 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000609 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000610 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000611 return false;
612 }
613 return true;
614}
615
Reid Spencerdd04df02005-07-07 23:21:43 +0000616bool
617Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000618 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000619 size_t dotpos = path.rfind('.',path.size());
620 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000621 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000622 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000623 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000624 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000625 }
Reid Spencer8e665952004-08-29 05:24:01 +0000626 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000627 if (!isValid())
628 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000629 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000630}
631
Ted Kremenekc5412c52008-04-03 16:11:31 +0000632static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000633
Ted Kremenekc5412c52008-04-03 16:11:31 +0000634 if (access(beg, F_OK | R_OK | W_OK) == 0)
635 return false;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000636
Ted Kremenekc5412c52008-04-03 16:11:31 +0000637 if (create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000638
Ted Kremenekc5412c52008-04-03 16:11:31 +0000639 char* c = end;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000640
Ted Kremenekc5412c52008-04-03 16:11:31 +0000641 for (; c != beg; --c)
642 if (*c == '/') {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000643
Ted Kremenekc5412c52008-04-03 16:11:31 +0000644 // Recurse to handling the parent directory.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000645 *c = '\0';
Ted Kremenekc5412c52008-04-03 16:11:31 +0000646 bool x = createDirectoryHelper(beg, c, create_parents);
647 *c = '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000648
Ted Kremenekc5412c52008-04-03 16:11:31 +0000649 // Return if we encountered an error.
650 if (x)
651 return true;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000652
Ted Kremenekc5412c52008-04-03 16:11:31 +0000653 break;
654 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000655 }
656
Ted Kremenekc5412c52008-04-03 16:11:31 +0000657 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
658}
659
Reid Spencer8e665952004-08-29 05:24:01 +0000660bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000661Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000662 // Get a writeable copy of the path name
663 char pathname[MAXPATHLEN];
664 path.copy(pathname,MAXPATHLEN);
665
666 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000667 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000668
Ted Kremenekc5412c52008-04-03 16:11:31 +0000669 if (pathname[lastchar] != '/')
670 ++lastchar;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000671
Ted Kremenekc5412c52008-04-03 16:11:31 +0000672 pathname[lastchar] = 0;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000673
Ted Kremenekc5412c52008-04-03 16:11:31 +0000674 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000675 return MakeErrMsg(ErrMsg,
Ted Kremenekc5412c52008-04-03 16:11:31 +0000676 std::string(pathname) + ": can't create directory");
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000677
Reid Spencere5c9cb52006-08-23 00:39:35 +0000678 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000679}
680
681bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000682Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000683 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000684 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000685 if (fd < 0)
686 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000687 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000688 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000689}
690
Reid Spencer8e665952004-08-29 05:24:01 +0000691bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000692Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000693 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000694 if (makeUnique( reuse_current, ErrMsg ))
695 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000696
697 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000698 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000699 if (fd < 0)
Reid Spencer5a060772006-08-23 07:30:48 +0000700 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000701 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000702 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000703}
704
705bool
Chris Lattner0c332312006-07-28 22:29:50 +0000706Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Reid Spencer2ae9d112007-04-07 18:52:17 +0000707 // Get the status so we can determin if its a file or directory
708 struct stat buf;
709 if (0 != stat(path.c_str(), &buf)) {
710 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000711 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000712 }
713
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000714 // Note: this check catches strange situations. In all cases, LLVM should
715 // only be involved in the creation and deletion of regular files. This
716 // check ensures that what we're trying to erase is a regular file. It
717 // effectively prevents LLVM from erasing things like /dev/null, any block
718 // special file, or other things that aren't "regular" files.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000719 if (S_ISREG(buf.st_mode)) {
720 if (unlink(path.c_str()) != 0)
721 return MakeErrMsg(ErrStr, path + ": can't destroy file");
722 return false;
723 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000724
Reid Spencer2ae9d112007-04-07 18:52:17 +0000725 if (!S_ISDIR(buf.st_mode)) {
726 if (ErrStr) *ErrStr = "not a file or directory";
727 return true;
728 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000729
Chris Lattner0c332312006-07-28 22:29:50 +0000730 if (remove_contents) {
731 // Recursively descend the directory to remove its contents.
732 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov8eada622009-02-15 03:20:32 +0000733 if (system(cmd.c_str()) != 0) {
734 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
735 return true;
736 }
Chris Lattner0c332312006-07-28 22:29:50 +0000737 return false;
738 }
739
740 // Otherwise, try to just remove the one directory.
741 char pathname[MAXPATHLEN];
742 path.copy(pathname, MAXPATHLEN);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000743 size_t lastchar = path.length() - 1;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000744 if (pathname[lastchar] == '/')
Chris Lattner0c332312006-07-28 22:29:50 +0000745 pathname[lastchar] = 0;
746 else
747 pathname[lastchar+1] = 0;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000748
Chris Lattner0c332312006-07-28 22:29:50 +0000749 if (rmdir(pathname) != 0)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000750 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000751 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000752 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000753}
754
755bool
Reid Spencer5a060772006-08-23 07:30:48 +0000756Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000757 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000758 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000759 newName.toString() + "'");
Reid Spencer5a060772006-08-23 07:30:48 +0000760 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000761}
762
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000763bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000764Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000765 struct utimbuf utb;
766 utb.actime = si.modTime.toPosixTime();
767 utb.modtime = utb.actime;
768 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000769 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000770 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000771 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000772 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000773}
774
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000775bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000776sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000777 int inFile = -1;
778 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000779 inFile = ::open(Src.c_str(), O_RDONLY);
780 if (inFile == -1)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000781 return MakeErrMsg(ErrMsg, Src.toString() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000782 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000783
Reid Spencer51c5a282006-08-23 20:34:57 +0000784 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
785 if (outFile == -1) {
786 ::close(inFile);
787 return MakeErrMsg(ErrMsg, Dest.toString() +
788 ": can't create destination file for copy");
789 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000790
Reid Spencer51c5a282006-08-23 20:34:57 +0000791 char Buffer[16*1024];
792 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
793 if (Amt == -1) {
794 if (errno != EINTR && errno != EAGAIN) {
795 ::close(inFile);
796 ::close(outFile);
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000797 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file");
Reid Spencer51c5a282006-08-23 20:34:57 +0000798 }
799 } else {
800 char *BufPtr = Buffer;
801 while (Amt) {
802 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
803 if (AmtWritten == -1) {
804 if (errno != EINTR && errno != EAGAIN) {
805 ::close(inFile);
806 ::close(outFile);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000807 return MakeErrMsg(ErrMsg, Dest.toString() +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000808 ": can't write destination file");
Reid Spencerc29befb2004-12-15 01:50:13 +0000809 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000810 } else {
811 Amt -= AmtWritten;
812 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000813 }
814 }
815 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000816 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000817 ::close(inFile);
818 ::close(outFile);
819 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000820}
821
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000822bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000823Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000824 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000825 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000826
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000827 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerc29befb2004-12-15 01:50:13 +0000828 // mktemp or our own implementation.
829 char *FNBuffer = (char*) alloca(path.size()+8);
Devang Patelce8fdf12008-07-22 20:02:39 +0000830 path.copy(FNBuffer,path.size());
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000831 if (isDirectory())
832 strcpy(FNBuffer+path.size(), "/XXXXXX");
833 else
Devang Patelce8fdf12008-07-22 20:02:39 +0000834 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerc29befb2004-12-15 01:50:13 +0000835
836#if defined(HAVE_MKSTEMP)
837 int TempFD;
Reid Spencer51c5a282006-08-23 20:34:57 +0000838 if ((TempFD = mkstemp(FNBuffer)) == -1)
839 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000840
841 // We don't need to hold the temp file descriptor... we will trust that no one
842 // will overwrite/delete the file before we can open it again.
843 close(TempFD);
844
845 // Save the name
846 path = FNBuffer;
847#elif defined(HAVE_MKTEMP)
848 // If we don't have mkstemp, use the old and obsolete mktemp function.
Reid Spencer51c5a282006-08-23 20:34:57 +0000849 if (mktemp(FNBuffer) == 0)
850 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000851
852 // Save the name
853 path = FNBuffer;
854#else
855 // Okay, looks like we have to do it all by our lonesome.
856 static unsigned FCounter = 0;
857 unsigned offset = path.size() + 1;
858 while ( FCounter < 999999 && exists()) {
859 sprintf(FNBuffer+offset,"%06u",++FCounter);
860 path = FNBuffer;
861 }
862 if (FCounter > 999999)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000863 return MakeErrMsg(ErrMsg,
Reid Spencer51c5a282006-08-23 20:34:57 +0000864 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000865#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000866 return false;
867}
Reid Spencerc29befb2004-12-15 01:50:13 +0000868
Chris Lattner799ed102008-04-01 06:00:12 +0000869const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000870 int Flags = MAP_PRIVATE;
871#ifdef MAP_FILE
872 Flags |= MAP_FILE;
873#endif
874 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
875 if (BasePtr == MAP_FAILED)
876 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000877 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000878}
879
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000880void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000881 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000882}
883
Reid Spencer51c5a282006-08-23 20:34:57 +0000884} // end llvm namespace