blob: 185f7fd66bf39443e5b6f153d5fe729bc7944d2e [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
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +000081Path::Path(StringRef p)
Nick Lewyckyfff116f2008-05-11 17:37:40 +000082 : path(p) {}
83
84Path::Path(const char *StrStart, unsigned StrLen)
85 : path(StrStart, StrLen) {}
86
Chris Lattner0eab5e22008-08-11 23:39:47 +000087Path&
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +000088Path::operator=(StringRef that) {
89 path.assign(that.data(), that.size());
Chris Lattner0eab5e22008-08-11 23:39:47 +000090 return *this;
91}
92
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +000093bool
Reid Spencer69a16162004-12-24 06:29:42 +000094Path::isValid() const {
Reid Spencer6371ccb2005-07-08 06:53:26 +000095 // Check some obvious things
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +000096 if (path.empty())
Reid Spencer69a16162004-12-24 06:29:42 +000097 return false;
Chris Lattner0f550142009-07-12 19:01:16 +000098 return path.length() < MAXPATHLEN;
Reid Spencer69a16162004-12-24 06:29:42 +000099}
100
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000101bool
Chris Lattner88d7e402009-06-15 04:17:07 +0000102Path::isAbsolute(const char *NameStart, unsigned NameLen) {
103 assert(NameStart);
104 if (NameLen == 0)
105 return false;
106 return NameStart[0] == '/';
107}
108
109bool
Reid Spencer69cce812007-03-29 16:43:20 +0000110Path::isAbsolute() const {
111 if (path.empty())
112 return false;
113 return path[0] == '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000114}
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000115
116void Path::makeAbsolute() {
117 if (isAbsolute())
118 return;
119
120 Path CWD = Path::GetCurrentDirectory();
121 assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
122
123 CWD.appendComponent(path);
124
Chris Lattner74382b72009-08-23 22:45:37 +0000125 path = CWD.str();
Daniel Dunbara00e85c2009-07-12 20:23:56 +0000126}
127
Reid Spencer8e665952004-08-29 05:24:01 +0000128Path
129Path::GetRootDirectory() {
130 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000131 result.set("/");
Reid Spencer8e665952004-08-29 05:24:01 +0000132 return result;
133}
134
Reid Spencer69a16162004-12-24 06:29:42 +0000135Path
Chris Lattnerd18a2c12009-02-19 05:34:35 +0000136Path::GetTemporaryDirectory(std::string *ErrMsg) {
Reid Spencer69a16162004-12-24 06:29:42 +0000137#if defined(HAVE_MKDTEMP)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000138 // The best way is with mkdtemp but that's not available on many systems,
Reid Spencer69a16162004-12-24 06:29:42 +0000139 // Linux and FreeBSD have it. Others probably won't.
140 char pathname[MAXPATHLEN];
141 strcpy(pathname,"/tmp/llvm_XXXXXX");
Reid Spencer48744762006-08-22 19:01:30 +0000142 if (0 == mkdtemp(pathname)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000143 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000144 std::string(pathname) + ": can't create temporary directory");
145 return Path();
146 }
Reid Spencer69a16162004-12-24 06:29:42 +0000147 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000148 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000149 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
150 return result;
151#elif defined(HAVE_MKSTEMP)
152 // If no mkdtemp is available, mkstemp can be used to create a temporary file
153 // which is then removed and created as a directory. We prefer this over
154 // mktemp because of mktemp's inherent security and threading risks. We still
155 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000156 // the time it is re-created as a directoy.
Reid Spencer69a16162004-12-24 06:29:42 +0000157 char pathname[MAXPATHLEN];
158 strcpy(pathname, "/tmp/llvm_XXXXXX");
159 int fd = 0;
Reid Spencer48744762006-08-22 19:01:30 +0000160 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000161 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000162 std::string(pathname) + ": can't create temporary directory");
163 return Path();
164 }
Reid Spencer69a16162004-12-24 06:29:42 +0000165 ::close(fd);
166 ::unlink(pathname); // start race condition, ignore errors
Reid Spencer48744762006-08-22 19:01:30 +0000167 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000168 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000169 std::string(pathname) + ": can't create temporary directory");
170 return Path();
171 }
Reid Spencer69a16162004-12-24 06:29:42 +0000172 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000173 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000174 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
175 return result;
176#elif defined(HAVE_MKTEMP)
177 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
178 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
179 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
180 // the XXXXXX with the pid of the process and a letter. That leads to only
181 // twenty six temporary files that can be generated.
182 char pathname[MAXPATHLEN];
183 strcpy(pathname, "/tmp/llvm_XXXXXX");
184 char *TmpName = ::mktemp(pathname);
Reid Spencer48744762006-08-22 19:01:30 +0000185 if (TmpName == 0) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000186 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000187 std::string(TmpName) + ": can't create unique directory name");
188 return Path();
189 }
190 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000191 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000192 std::string(TmpName) + ": can't create temporary directory");
193 return Path();
194 }
Reid Spencer69a16162004-12-24 06:29:42 +0000195 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000196 result.set(TmpName);
Reid Spencer69a16162004-12-24 06:29:42 +0000197 assert(result.isValid() && "mktemp didn't create a valid pathname!");
198 return result;
199#else
200 // This is the worst case implementation. tempnam(3) leaks memory unless its
201 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
202 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000203 // temporary name generated. So, we provide our own implementation that
Reid Spencer69a16162004-12-24 06:29:42 +0000204 // increments an integer from a random number seeded by the current time. This
205 // should be sufficiently unique that we don't have many collisions between
206 // processes. Generally LLVM processes don't run very long and don't use very
207 // many temporary files so this shouldn't be a big issue for LLVM.
208 static time_t num = ::time(0);
209 char pathname[MAXPATHLEN];
210 do {
211 num++;
212 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
213 } while ( 0 == access(pathname, F_OK ) );
Reid Spencer48744762006-08-22 19:01:30 +0000214 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000215 MakeErrMsg(ErrMsg,
Reid Spencer48744762006-08-22 19:01:30 +0000216 std::string(pathname) + ": can't create temporary directory");
217 return Path();
Reid Spencer51c5a282006-08-23 20:34:57 +0000218 }
Reid Spencer69a16162004-12-24 06:29:42 +0000219 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000220 result.set(pathname);
Reid Spencer69a16162004-12-24 06:29:42 +0000221 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
222 return result;
223#endif
224}
225
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000226void
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000227Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
228#ifdef LTDL_SHLIBPATH_VAR
229 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
230 if (env_var != 0) {
231 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000232 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000233#endif
234 // FIXME: Should this look at LD_LIBRARY_PATH too?
235 Paths.push_back(sys::Path("/usr/local/lib/"));
236 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
237 Paths.push_back(sys::Path("/usr/lib/"));
238 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000239}
240
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000241void
Gabor Greifa99be512007-07-05 17:07:56 +0000242Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000243 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
244 if (env_var != 0) {
245 getPathList(env_var,Paths);
246 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000247#ifdef LLVM_LIBDIR
248 {
249 Path tmpPath;
Reid Spencerdd04df02005-07-07 23:21:43 +0000250 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencerc7f08322005-07-07 18:21:42 +0000251 if (tmpPath.canRead())
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000252 Paths.push_back(tmpPath);
253 }
254#endif
255 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000256}
257
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000258Path
Reid Spencer8e665952004-08-29 05:24:01 +0000259Path::GetLLVMDefaultConfigDir() {
260 return Path("/etc/llvm/");
261}
262
Reid Spencer8e665952004-08-29 05:24:01 +0000263Path
264Path::GetUserHomeDirectory() {
265 const char* home = getenv("HOME");
266 if (home) {
267 Path result;
Reid Spencerdd04df02005-07-07 23:21:43 +0000268 if (result.set(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000269 return result;
270 }
271 return GetRootDirectory();
272}
273
Ted Kremenek79200782007-12-18 22:07:33 +0000274Path
275Path::GetCurrentDirectory() {
276 char pathname[MAXPATHLEN];
277 if (!getcwd(pathname,MAXPATHLEN)) {
278 assert (false && "Could not query current working directory.");
279 return Path("");
280 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000281
Ted Kremenek79200782007-12-18 22:07:33 +0000282 return Path(pathname);
283}
Reid Spencera229c5c2005-07-08 03:08:58 +0000284
Chris Lattner893a0f92009-03-02 22:17:15 +0000285#ifdef __FreeBSD__
286static int
287test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
288 const char *dir, const char *bin)
289{
Bill Wendling51b16f42009-05-30 01:09:53 +0000290 struct stat sb;
Chris Lattner893a0f92009-03-02 22:17:15 +0000291
Bill Wendling51b16f42009-05-30 01:09:53 +0000292 snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
293 if (realpath(buf, ret) == NULL)
294 return (1);
295 if (stat(buf, &sb) != 0)
296 return (1);
297
298 return (0);
Chris Lattner893a0f92009-03-02 22:17:15 +0000299}
300
301static char *
302getprogpath(char ret[PATH_MAX], const char *bin)
303{
Bill Wendling51b16f42009-05-30 01:09:53 +0000304 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner893a0f92009-03-02 22:17:15 +0000305
Bill Wendling51b16f42009-05-30 01:09:53 +0000306 /* First approach: absolute path. */
307 if (bin[0] == '/') {
308 if (test_dir(buf, ret, "/", bin) == 0)
309 return (ret);
310 return (NULL);
311 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000312
Bill Wendling51b16f42009-05-30 01:09:53 +0000313 /* Second approach: relative path. */
314 if (strchr(bin, '/') != NULL) {
315 if (getcwd(buf, PATH_MAX) == NULL)
316 return (NULL);
317 if (test_dir(buf, ret, buf, bin) == 0)
318 return (ret);
319 return (NULL);
320 }
Chris Lattner893a0f92009-03-02 22:17:15 +0000321
Bill Wendling51b16f42009-05-30 01:09:53 +0000322 /* Third approach: $PATH */
323 if ((pv = getenv("PATH")) == NULL)
324 return (NULL);
325 s = pv = strdup(pv);
326 if (pv == NULL)
327 return (NULL);
328 while ((t = strsep(&s, ":")) != NULL) {
329 if (test_dir(buf, ret, t, bin) == 0) {
330 free(pv);
331 return (ret);
332 }
333 }
334 free(pv);
335 return (NULL);
Chris Lattner893a0f92009-03-02 22:17:15 +0000336}
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000337#endif // __FreeBSD__
Chris Lattner893a0f92009-03-02 22:17:15 +0000338
Chris Lattner1a091442008-03-03 02:55:43 +0000339/// GetMainExecutable - Return the path to the main executable, given the
340/// value of argv[0] from program startup.
341Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000342#if defined(__APPLE__)
343 // On OS X the executable path is saved to the stack by dyld. Reading it
344 // from there is much faster than calling dladdr, especially for large
345 // binaries with symbols.
346 char exe_path[MAXPATHLEN];
347 uint32_t size = sizeof(exe_path);
348 if (_NSGetExecutablePath(exe_path, &size) == 0) {
349 char link_path[MAXPATHLEN];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000350 if (realpath(exe_path, link_path))
351 return Path(std::string(link_path));
Benjamin Kramerd8b06302009-09-09 12:09:08 +0000352 }
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];
Kovarththanan Rajaratnamd6146732009-11-29 17:19:48 +0000373 if (realpath(DLInfo.dli_fname, link_path))
374 return Path(std::string(link_path));
Chris Lattner1a091442008-03-03 02:55:43 +0000375#endif
376 return Path();
377}
378
379
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000380StringRef Path::getDirname() const {
381 return getDirnameCharSep(path, "/");
Ted Kremenek9b01cc02008-04-07 22:01:32 +0000382}
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000383
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000384StringRef
Reid Spencer07adb282004-11-05 22:15:36 +0000385Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000386 // Find the last slash
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000387 std::string::size_type slash = path.rfind('/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000388 if (slash == std::string::npos)
389 slash = 0;
390 else
391 slash++;
392
Ted Kremenekcf55c8e2008-04-07 21:53:57 +0000393 std::string::size_type dot = path.rfind('.');
Jeff Cohen73f36672005-07-09 18:42:02 +0000394 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000395 return StringRef(path).substr(slash);
Jeff Cohen73f36672005-07-09 18:42:02 +0000396 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000397 return StringRef(path).substr(slash, dot - slash);
Reid Spencer1b554b42004-09-11 04:55:08 +0000398}
399
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000400StringRef
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000401Path::getSuffix() const {
402 // Find the last slash
403 std::string::size_type slash = path.rfind('/');
404 if (slash == std::string::npos)
405 slash = 0;
406 else
407 slash++;
408
409 std::string::size_type dot = path.rfind('.');
410 if (dot == std::string::npos || dot < slash)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000411 return StringRef("");
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000412 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000413 return StringRef(path).substr(dot + 1);
Argyrios Kyrtzidisfc199882008-06-15 15:15:19 +0000414}
415
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000416bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000417 assert(len < 1024 && "Request for magic string too long");
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000418 char Buf[1025];
Chris Lattnerc7c453a2006-08-01 17:51:09 +0000419 int fd = ::open(path.c_str(), O_RDONLY);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000420 if (fd < 0)
421 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000422 ssize_t bytes_read = ::read(fd, Buf, len);
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000423 ::close(fd);
Dan Gohman02d58242010-05-27 17:14:10 +0000424 if (ssize_t(len) != bytes_read)
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000425 return false;
Chris Lattnere4b0cd22009-12-16 08:35:54 +0000426 Magic.assign(Buf, len);
Reid Spencereaf18152004-11-14 22:08:36 +0000427 return true;
428}
429
Reid Spencer1b554b42004-09-11 04:55:08 +0000430bool
Reid Spencer8e665952004-08-29 05:24:01 +0000431Path::exists() const {
432 return 0 == access(path.c_str(), F_OK );
433}
434
435bool
Ted Kremenekfd527112007-12-18 19:46:22 +0000436Path::isDirectory() const {
437 struct stat buf;
438 if (0 != stat(path.c_str(), &buf))
439 return false;
440 return buf.st_mode & S_IFDIR ? true : false;
441}
442
443bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000444Path::canRead() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000445 return 0 == access(path.c_str(), R_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000446}
447
448bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000449Path::canWrite() const {
Dan Gohman73c74ea2009-07-28 23:22:01 +0000450 return 0 == access(path.c_str(), W_OK);
Reid Spencer8e665952004-08-29 05:24:01 +0000451}
452
453bool
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000454Path::isRegularFile() const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000455 // Get the status so we can determine if it's a file or directory
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000456 struct stat buf;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000457
Daniel Dunbar98e46d82009-11-24 19:03:33 +0000458 if (0 != stat(path.c_str(), &buf))
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000459 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000460
Edward O'Callaghane49a8e42009-11-25 06:32:19 +0000461 if (S_ISREG(buf.st_mode))
462 return true;
463
464 return false;
Edward O'Callaghand41e9442009-11-24 15:19:10 +0000465}
466
467bool
Reid Spencerc7f08322005-07-07 18:21:42 +0000468Path::canExecute() const {
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000469 if (0 != access(path.c_str(), R_OK | X_OK ))
470 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000471 struct stat buf;
472 if (0 != stat(path.c_str(), &buf))
473 return false;
474 if (!S_ISREG(buf.st_mode))
Misha Brukman8177bf82005-04-20 15:33:22 +0000475 return false;
Reid Spencer8b2d1aa2005-07-08 17:46:10 +0000476 return true;
Reid Spencer8e665952004-08-29 05:24:01 +0000477}
478
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000479StringRef
Reid Spencer8e665952004-08-29 05:24:01 +0000480Path::getLast() const {
481 // Find the last slash
482 size_t pos = path.rfind('/');
483
484 // Handle the corner cases
485 if (pos == std::string::npos)
486 return path;
487
488 // If the last character is a slash
489 if (pos == path.length()-1) {
490 // Find the second to last slash
491 size_t pos2 = path.rfind('/', pos-1);
492 if (pos2 == std::string::npos)
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000493 return StringRef(path).substr(0,pos);
Reid Spencer8e665952004-08-29 05:24:01 +0000494 else
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000495 return StringRef(path).substr(pos2+1,pos-pos2-1);
Reid Spencer8e665952004-08-29 05:24:01 +0000496 }
497 // Return everything after the last slash
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000498 return StringRef(path).substr(pos+1);
Reid Spencer8e665952004-08-29 05:24:01 +0000499}
500
Reid Spencer2ae9d112007-04-07 18:52:17 +0000501const FileStatus *
502PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
503 if (!fsIsValid || update) {
Reid Spencer69cce812007-03-29 16:43:20 +0000504 struct stat buf;
Reid Spencer8475ec02007-03-29 19:05:44 +0000505 if (0 != stat(path.c_str(), &buf)) {
506 MakeErrMsg(ErrStr, path + ": can't get status of file");
507 return 0;
508 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000509 status.fileSize = buf.st_size;
510 status.modTime.fromEpochTime(buf.st_mtime);
511 status.mode = buf.st_mode;
512 status.user = buf.st_uid;
513 status.group = buf.st_gid;
514 status.uniqueID = uint64_t(buf.st_ino);
515 status.isDir = S_ISDIR(buf.st_mode);
516 status.isFile = S_ISREG(buf.st_mode);
517 fsIsValid = true;
Reid Spencer69cce812007-03-29 16:43:20 +0000518 }
Reid Spencer2ae9d112007-04-07 18:52:17 +0000519 return &status;
Reid Spencereaf18152004-11-14 22:08:36 +0000520}
521
Chris Lattner252ad032006-07-28 22:03:44 +0000522static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer77cc91d2004-12-13 19:59:50 +0000523 // Get the umask value from the operating system. We want to use it
524 // when changing the file's permissions. Since calling umask() sets
525 // the umask and returns its old value, we must call it a second
526 // time to reset it to the user's preference.
527 int mask = umask(0777); // The arg. to umask is arbitrary.
528 umask(mask); // Restore the umask.
529
530 // Get the file's current mode.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000531 struct stat buf;
Chris Lattner74382b72009-08-23 22:45:37 +0000532 if (0 != stat(File.c_str(), &buf))
Reid Spencer77cc91d2004-12-13 19:59:50 +0000533 return false;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000534 // Change the file to have whichever permissions bits from 'bits'
535 // that the umask would not disable.
536 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
537 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000538 return true;
539}
540
Reid Spencere1647f42006-08-22 23:27:23 +0000541bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000542 if (!AddPermissionBits(*this, 0444))
Reid Spencer5a060772006-08-23 07:30:48 +0000543 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
Reid Spencere1647f42006-08-22 23:27:23 +0000544 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000545}
546
Reid Spencere1647f42006-08-22 23:27:23 +0000547bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000548 if (!AddPermissionBits(*this, 0222))
549 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
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::makeExecutableOnDisk(std::string* ErrMsg) {
Reid Spencer5a060772006-08-23 07:30:48 +0000554 if (!AddPermissionBits(*this, 0111))
555 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
Reid Spencere1647f42006-08-22 23:27:23 +0000556 return false;
Reid Spencer77cc91d2004-12-13 19:59:50 +0000557}
558
Reid Spencereaf18152004-11-14 22:08:36 +0000559bool
Reid Spencer142ca8e2006-08-23 06:56:27 +0000560Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000561 DIR* direntries = ::opendir(path.c_str());
Reid Spencer5a060772006-08-23 07:30:48 +0000562 if (direntries == 0)
563 return MakeErrMsg(ErrMsg, path + ": can't open directory");
Reid Spencereaf18152004-11-14 22:08:36 +0000564
Reid Spencer3be872e2005-07-28 16:25:57 +0000565 std::string dirPath = path;
566 if (!lastIsSlash(dirPath))
567 dirPath += '/';
568
Reid Spencereaf18152004-11-14 22:08:36 +0000569 result.clear();
570 struct dirent* de = ::readdir(direntries);
Misha Brukman4619c752005-04-20 04:04:07 +0000571 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencereaf18152004-11-14 22:08:36 +0000572 if (de->d_name[0] != '.') {
Reid Spencer3be872e2005-07-28 16:25:57 +0000573 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattnerb14c3422006-07-07 21:21:06 +0000574 struct stat st;
575 if (0 != lstat(aPath.path.c_str(), &st)) {
576 if (S_ISLNK(st.st_mode))
Misha Brukman4619c752005-04-20 04:04:07 +0000577 continue; // dangling symlink -- ignore
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000578 return MakeErrMsg(ErrMsg,
Reid Spencer5a060772006-08-23 07:30:48 +0000579 aPath.path + ": can't determine file object type");
Misha Brukman4619c752005-04-20 04:04:07 +0000580 }
Reid Spencerb608a812004-11-16 06:15:19 +0000581 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000582 }
Reid Spencereaf18152004-11-14 22:08:36 +0000583 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000584
Reid Spencereaf18152004-11-14 22:08:36 +0000585 closedir(direntries);
Reid Spencer142ca8e2006-08-23 06:56:27 +0000586 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000587}
588
Reid Spencer8e665952004-08-29 05:24:01 +0000589bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000590Path::set(StringRef a_path) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000591 if (a_path.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000592 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000593 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000594 path = a_path;
Reid Spencer07adb282004-11-05 22:15:36 +0000595 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000596 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000597 return false;
598 }
599 return true;
600}
601
602bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000603Path::appendComponent(StringRef name) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000604 if (name.empty())
Reid Spencer8e665952004-08-29 05:24:01 +0000605 return false;
Reid Spencerdd04df02005-07-07 23:21:43 +0000606 std::string save(path);
Reid Spencer3be872e2005-07-28 16:25:57 +0000607 if (!lastIsSlash(path))
608 path += '/';
Reid Spencerdd04df02005-07-07 23:21:43 +0000609 path += name;
Reid Spencer07adb282004-11-05 22:15:36 +0000610 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000611 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000612 return false;
613 }
614 return true;
615}
616
617bool
Reid Spencerdd04df02005-07-07 23:21:43 +0000618Path::eraseComponent() {
Reid Spencer8e665952004-08-29 05:24:01 +0000619 size_t slashpos = path.rfind('/',path.size());
Reid Spencerdd04df02005-07-07 23:21:43 +0000620 if (slashpos == 0 || slashpos == std::string::npos) {
621 path.erase();
622 return true;
623 }
Reid Spencer8e665952004-08-29 05:24:01 +0000624 if (slashpos == path.size() - 1)
625 slashpos = path.rfind('/',slashpos-1);
Reid Spencerdd04df02005-07-07 23:21:43 +0000626 if (slashpos == std::string::npos) {
627 path.erase();
628 return true;
629 }
Reid Spencer8e665952004-08-29 05:24:01 +0000630 path.erase(slashpos);
631 return true;
632}
633
634bool
Jeffrey Yasskin88cd3582009-12-17 21:02:39 +0000635Path::appendSuffix(StringRef suffix) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000636 std::string save(path);
Reid Spencer8e665952004-08-29 05:24:01 +0000637 path.append(".");
638 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000639 if (!isValid()) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000640 path = save;
Reid Spencer8e665952004-08-29 05:24:01 +0000641 return false;
642 }
643 return true;
644}
645
Reid Spencerdd04df02005-07-07 23:21:43 +0000646bool
647Path::eraseSuffix() {
Reid Spencer6371ccb2005-07-08 06:53:26 +0000648 std::string save = path;
Reid Spencer8e665952004-08-29 05:24:01 +0000649 size_t dotpos = path.rfind('.',path.size());
650 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen563a17f2005-07-08 04:49:16 +0000651 if (dotpos != std::string::npos) {
Jeff Cohen73f36672005-07-09 18:42:02 +0000652 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen563a17f2005-07-08 04:49:16 +0000653 path.erase(dotpos, path.size()-dotpos);
Jeff Cohen85c716f2005-07-08 05:02:13 +0000654 return true;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000655 }
Reid Spencer8e665952004-08-29 05:24:01 +0000656 }
Reid Spencer6371ccb2005-07-08 06:53:26 +0000657 if (!isValid())
658 path = save;
Jeff Cohen563a17f2005-07-08 04:49:16 +0000659 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000660}
661
Ted Kremenekc5412c52008-04-03 16:11:31 +0000662static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000663
Dan Gohman28daa102009-07-29 00:02:58 +0000664 if (access(beg, R_OK | W_OK) == 0)
Ted Kremenekc5412c52008-04-03 16:11:31 +0000665 return false;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000666
Ted Kremenekc5412c52008-04-03 16:11:31 +0000667 if (create_parents) {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000668
Ted Kremenekc5412c52008-04-03 16:11:31 +0000669 char* c = end;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000670
Ted Kremenekc5412c52008-04-03 16:11:31 +0000671 for (; c != beg; --c)
672 if (*c == '/') {
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000673
Ted Kremenekc5412c52008-04-03 16:11:31 +0000674 // Recurse to handling the parent directory.
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000675 *c = '\0';
Ted Kremenekc5412c52008-04-03 16:11:31 +0000676 bool x = createDirectoryHelper(beg, c, create_parents);
677 *c = '/';
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000678
Ted Kremenekc5412c52008-04-03 16:11:31 +0000679 // Return if we encountered an error.
680 if (x)
681 return true;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000682
Ted Kremenekc5412c52008-04-03 16:11:31 +0000683 break;
684 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000685 }
686
Ted Kremenekc5412c52008-04-03 16:11:31 +0000687 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
688}
689
Reid Spencer8e665952004-08-29 05:24:01 +0000690bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000691Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
Reid Spencer8e665952004-08-29 05:24:01 +0000692 // Get a writeable copy of the path name
693 char pathname[MAXPATHLEN];
694 path.copy(pathname,MAXPATHLEN);
695
696 // Null-terminate the last component
Evan Cheng34cd4a42008-05-05 18:30:58 +0000697 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000698
Ted Kremenekc5412c52008-04-03 16:11:31 +0000699 if (pathname[lastchar] != '/')
700 ++lastchar;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000701
Ted Kremenekc5412c52008-04-03 16:11:31 +0000702 pathname[lastchar] = 0;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000703
Ted Kremenekc5412c52008-04-03 16:11:31 +0000704 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000705 return MakeErrMsg(ErrMsg,
Ted Kremenekc5412c52008-04-03 16:11:31 +0000706 std::string(pathname) + ": can't create directory");
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000707
Reid Spencere5c9cb52006-08-23 00:39:35 +0000708 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000709}
710
711bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000712Path::createFileOnDisk(std::string* ErrMsg) {
Reid Spencer8e665952004-08-29 05:24:01 +0000713 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000714 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
Reid Spencer5a060772006-08-23 07:30:48 +0000715 if (fd < 0)
716 return MakeErrMsg(ErrMsg, path + ": can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000717 ::close(fd);
Reid Spencere5c9cb52006-08-23 00:39:35 +0000718 return false;
Reid Spencerb89a2232004-08-25 06:20:07 +0000719}
720
Reid Spencer8e665952004-08-29 05:24:01 +0000721bool
Reid Spencere5c9cb52006-08-23 00:39:35 +0000722Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000723 // Make this into a unique file name
Reid Spencer51c5a282006-08-23 20:34:57 +0000724 if (makeUnique( reuse_current, ErrMsg ))
725 return true;
Reid Spencerc29befb2004-12-15 01:50:13 +0000726
727 // create the file
Reid Spencere5c9cb52006-08-23 00:39:35 +0000728 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000729 if (fd < 0)
Reid Spencer5a060772006-08-23 07:30:48 +0000730 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000731 ::close(fd);
Reid Spencerc29befb2004-12-15 01:50:13 +0000732 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000733}
734
735bool
Chris Lattner0c332312006-07-28 22:29:50 +0000736Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000737 // Get the status so we can determine if it's a file or directory.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000738 struct stat buf;
739 if (0 != stat(path.c_str(), &buf)) {
740 MakeErrMsg(ErrStr, path + ": can't get status of file");
Chris Lattner0c332312006-07-28 22:29:50 +0000741 return true;
Reid Spencer2ae9d112007-04-07 18:52:17 +0000742 }
743
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000744 // Note: this check catches strange situations. In all cases, LLVM should
745 // only be involved in the creation and deletion of regular files. This
746 // check ensures that what we're trying to erase is a regular file. It
747 // effectively prevents LLVM from erasing things like /dev/null, any block
748 // special file, or other things that aren't "regular" files.
Reid Spencer2ae9d112007-04-07 18:52:17 +0000749 if (S_ISREG(buf.st_mode)) {
750 if (unlink(path.c_str()) != 0)
751 return MakeErrMsg(ErrStr, path + ": can't destroy file");
752 return false;
753 }
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000754
Reid Spencer2ae9d112007-04-07 18:52:17 +0000755 if (!S_ISDIR(buf.st_mode)) {
756 if (ErrStr) *ErrStr = "not a file or directory";
757 return true;
758 }
Reid Spencer8475ec02007-03-29 19:05:44 +0000759
Chris Lattner0c332312006-07-28 22:29:50 +0000760 if (remove_contents) {
761 // Recursively descend the directory to remove its contents.
762 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov8eada622009-02-15 03:20:32 +0000763 if (system(cmd.c_str()) != 0) {
764 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
765 return true;
766 }
Chris Lattner0c332312006-07-28 22:29:50 +0000767 return false;
768 }
769
770 // Otherwise, try to just remove the one directory.
771 char pathname[MAXPATHLEN];
772 path.copy(pathname, MAXPATHLEN);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000773 size_t lastchar = path.length() - 1;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000774 if (pathname[lastchar] == '/')
Chris Lattner0c332312006-07-28 22:29:50 +0000775 pathname[lastchar] = 0;
776 else
777 pathname[lastchar+1] = 0;
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000778
Chris Lattner0c332312006-07-28 22:29:50 +0000779 if (rmdir(pathname) != 0)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000780 return MakeErrMsg(ErrStr,
Reid Spencer8475ec02007-03-29 19:05:44 +0000781 std::string(pathname) + ": can't erase directory");
Chris Lattner0c332312006-07-28 22:29:50 +0000782 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000783}
784
785bool
Reid Spencer5a060772006-08-23 07:30:48 +0000786Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
Reid Spencerdd04df02005-07-07 23:21:43 +0000787 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000788 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Chris Lattner74382b72009-08-23 22:45:37 +0000789 newName.str() + "'");
Reid Spencer5a060772006-08-23 07:30:48 +0000790 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000791}
792
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000793bool
Chris Lattner1bebfb52006-07-28 22:36:17 +0000794Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000795 struct utimbuf utb;
796 utb.actime = si.modTime.toPosixTime();
797 utb.modtime = utb.actime;
798 if (0 != ::utime(path.c_str(),&utb))
Reid Spencer51c5a282006-08-23 20:34:57 +0000799 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
Reid Spencereaf18152004-11-14 22:08:36 +0000800 if (0 != ::chmod(path.c_str(),si.mode))
Reid Spencer51c5a282006-08-23 20:34:57 +0000801 return MakeErrMsg(ErrStr, path + ": can't set mode");
Chris Lattner1bebfb52006-07-28 22:36:17 +0000802 return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000803}
804
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000805bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000806sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
Reid Spencerc29befb2004-12-15 01:50:13 +0000807 int inFile = -1;
808 int outFile = -1;
Reid Spencer51c5a282006-08-23 20:34:57 +0000809 inFile = ::open(Src.c_str(), O_RDONLY);
810 if (inFile == -1)
Chris Lattner74382b72009-08-23 22:45:37 +0000811 return MakeErrMsg(ErrMsg, Src.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000812 ": can't open source file to copy");
Reid Spencerc29befb2004-12-15 01:50:13 +0000813
Reid Spencer51c5a282006-08-23 20:34:57 +0000814 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
815 if (outFile == -1) {
816 ::close(inFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000817 return MakeErrMsg(ErrMsg, Dest.str() +
Reid Spencer51c5a282006-08-23 20:34:57 +0000818 ": can't create destination file for copy");
819 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000820
Reid Spencer51c5a282006-08-23 20:34:57 +0000821 char Buffer[16*1024];
822 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
823 if (Amt == -1) {
824 if (errno != EINTR && errno != EAGAIN) {
825 ::close(inFile);
826 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000827 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
Reid Spencer51c5a282006-08-23 20:34:57 +0000828 }
829 } else {
830 char *BufPtr = Buffer;
831 while (Amt) {
832 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
833 if (AmtWritten == -1) {
834 if (errno != EINTR && errno != EAGAIN) {
835 ::close(inFile);
836 ::close(outFile);
Chris Lattner74382b72009-08-23 22:45:37 +0000837 return MakeErrMsg(ErrMsg, Dest.str() +
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000838 ": can't write destination file");
Reid Spencerc29befb2004-12-15 01:50:13 +0000839 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000840 } else {
841 Amt -= AmtWritten;
842 BufPtr += AmtWritten;
Reid Spencerc29befb2004-12-15 01:50:13 +0000843 }
844 }
845 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000846 }
Reid Spencer51c5a282006-08-23 20:34:57 +0000847 ::close(inFile);
848 ::close(outFile);
849 return false;
Reid Spencerc29befb2004-12-15 01:50:13 +0000850}
851
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000852bool
Reid Spencer51c5a282006-08-23 20:34:57 +0000853Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000854 if (reuse_current && !exists())
Reid Spencer51c5a282006-08-23 20:34:57 +0000855 return false; // File doesn't exist already, just use it!
Reid Spencerc29befb2004-12-15 01:50:13 +0000856
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000857 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Reid Spencerc29befb2004-12-15 01:50:13 +0000858 // mktemp or our own implementation.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000859 // This uses std::vector instead of SmallVector to avoid a dependence on
860 // libSupport. And performance isn't critical here.
861 std::vector<char> Buf;
862 Buf.resize(path.size()+8);
Dan Gohman17192a12010-04-19 16:33:28 +0000863 char *FNBuffer = &Buf[0];
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000864 path.copy(FNBuffer,path.size());
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000865 if (isDirectory())
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000866 strcpy(FNBuffer+path.size(), "/XXXXXX");
Devang Patelbdfa9ac2008-07-24 00:35:38 +0000867 else
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000868 strcpy(FNBuffer+path.size(), "-XXXXXX");
Reid Spencerc29befb2004-12-15 01:50:13 +0000869
870#if defined(HAVE_MKSTEMP)
871 int TempFD;
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000872 if ((TempFD = mkstemp(FNBuffer)) == -1)
Reid Spencer51c5a282006-08-23 20:34:57 +0000873 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000874
875 // We don't need to hold the temp file descriptor... we will trust that no one
876 // will overwrite/delete the file before we can open it again.
877 close(TempFD);
878
879 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000880 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000881#elif defined(HAVE_MKTEMP)
882 // If we don't have mkstemp, use the old and obsolete mktemp function.
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000883 if (mktemp(FNBuffer) == 0)
Reid Spencer51c5a282006-08-23 20:34:57 +0000884 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
Reid Spencerc29befb2004-12-15 01:50:13 +0000885
886 // Save the name
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000887 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000888#else
889 // Okay, looks like we have to do it all by our lonesome.
890 static unsigned FCounter = 0;
891 unsigned offset = path.size() + 1;
Dan Gohman72bdd4c2010-04-19 15:54:44 +0000892 while ( FCounter < 999999 && exists()) {
893 sprintf(FNBuffer+offset,"%06u",++FCounter);
894 path = FNBuffer;
Reid Spencerc29befb2004-12-15 01:50:13 +0000895 }
896 if (FCounter > 999999)
Mikhail Glushenkovb8863a12009-02-15 03:20:03 +0000897 return MakeErrMsg(ErrMsg,
Reid Spencer51c5a282006-08-23 20:34:57 +0000898 path + ": can't make unique filename: too many files");
Reid Spencerc29befb2004-12-15 01:50:13 +0000899#endif
Reid Spencer51c5a282006-08-23 20:34:57 +0000900 return false;
901}
Reid Spencerc29befb2004-12-15 01:50:13 +0000902
Chris Lattner799ed102008-04-01 06:00:12 +0000903const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000904 int Flags = MAP_PRIVATE;
905#ifdef MAP_FILE
906 Flags |= MAP_FILE;
907#endif
908 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
909 if (BasePtr == MAP_FAILED)
910 return 0;
Chris Lattner14c762d2008-04-01 06:25:23 +0000911 return (const char*)BasePtr;
Chris Lattner799ed102008-04-01 06:00:12 +0000912}
913
Chris Lattner9ffd19a2008-04-01 06:16:24 +0000914void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner14c762d2008-04-01 06:25:23 +0000915 ::munmap((void*)BasePtr, FileSize);
Chris Lattner799ed102008-04-01 06:00:12 +0000916}
917
Reid Spencer51c5a282006-08-23 20:34:57 +0000918} // end llvm namespace