blob: 1f73571cf140ba350d6efd80735d6169f774b6eb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +00002//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-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 Glushenkov9c369df2009-02-15 03:20:03 +00007//
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
16//=== is guaranteed to work on *all* UNIX variants.
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Config/alloca.h"
20#include "Unix.h"
21#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
Chris Lattner116abbf2008-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#if HAVE_UTIME_H
34#include <utime.h>
35#endif
36#if HAVE_TIME_H
37#include <time.h>
38#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 Lattner365f2202008-03-03 02:55:43 +000056#if HAVE_DLFCN_H
57#include <dlfcn.h>
58#endif
59
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
65
66namespace {
67inline bool lastIsSlash(const std::string& path) {
68 return !path.empty() && path[path.length() - 1] == '/';
69}
70
71}
72
73namespace llvm {
74using namespace sys;
75
Chris Lattner4b8f1c62008-02-27 06:17:10 +000076extern const char sys::PathSeparator = ':';
77
Nick Lewycky4fd4b462008-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 Lattner43ac42b2008-08-11 23:39:47 +000084Path&
85Path::operator=(const std::string &that) {
86 path = that;
87 return *this;
88}
89
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +000090bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091Path::isValid() const {
92 // Check some obvious things
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +000093 if (path.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 return false;
95 else if (path.length() >= MAXPATHLEN)
96 return false;
97
98 // Check that the characters are ascii chars
99 size_t len = path.length();
100 unsigned i = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000101 while (i < len && isascii(path[i]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102 ++i;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000103 return i >= len;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104}
105
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000106bool
Chris Lattnerd024d8d2009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115Path::isAbsolute() const {
116 if (path.empty())
117 return false;
118 return path[0] == '/';
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000119}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120Path
121Path::GetRootDirectory() {
122 Path result;
123 result.set("/");
124 return result;
125}
126
127Path
Chris Lattnera8164e42009-02-19 05:34:35 +0000128Path::GetTemporaryDirectory(std::string *ErrMsg) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129#if defined(HAVE_MKDTEMP)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000130 // The best way is with mkdtemp but that's not available on many systems,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 // Linux and FreeBSD have it. Others probably won't.
132 char pathname[MAXPATHLEN];
133 strcpy(pathname,"/tmp/llvm_XXXXXX");
134 if (0 == mkdtemp(pathname)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000135 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 std::string(pathname) + ": can't create temporary directory");
137 return Path();
138 }
139 Path result;
140 result.set(pathname);
141 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 Glushenkov9c369df2009-02-15 03:20:03 +0000148 // the time it is re-created as a directoy.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149 char pathname[MAXPATHLEN];
150 strcpy(pathname, "/tmp/llvm_XXXXXX");
151 int fd = 0;
152 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000153 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 std::string(pathname) + ": can't create temporary directory");
155 return Path();
156 }
157 ::close(fd);
158 ::unlink(pathname); // start race condition, ignore errors
159 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000160 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 std::string(pathname) + ": can't create temporary directory");
162 return Path();
163 }
164 Path result;
165 result.set(pathname);
166 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);
177 if (TmpName == 0) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000178 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 std::string(TmpName) + ": can't create unique directory name");
180 return Path();
181 }
182 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000183 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 std::string(TmpName) + ": can't create temporary directory");
185 return Path();
186 }
187 Path result;
188 result.set(TmpName);
189 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 Glushenkov9c369df2009-02-15 03:20:03 +0000195 // temporary name generated. So, we provide our own implementation that
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 ) );
206 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000207 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 std::string(pathname) + ": can't create temporary directory");
209 return Path();
210 }
211 Path result;
212 result.set(pathname);
213 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
214 return result;
215#endif
216}
217
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000218void
Dan Gohmanf17a25c2007-07-18 16:29:46 +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);
224 }
225#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/"));
231}
232
233void
234Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
235 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
236 if (env_var != 0) {
237 getPathList(env_var,Paths);
238 }
239#ifdef LLVM_LIBDIR
240 {
241 Path tmpPath;
242 if (tmpPath.set(LLVM_LIBDIR))
243 if (tmpPath.canRead())
244 Paths.push_back(tmpPath);
245 }
246#endif
247 GetSystemLibraryPaths(Paths);
248}
249
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000250Path
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251Path::GetLLVMDefaultConfigDir() {
252 return Path("/etc/llvm/");
253}
254
255Path
256Path::GetUserHomeDirectory() {
257 const char* home = getenv("HOME");
258 if (home) {
259 Path result;
260 if (result.set(home))
261 return result;
262 }
263 return GetRootDirectory();
264}
265
Ted Kremenekb05c9352007-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 Glushenkov9c369df2009-02-15 03:20:03 +0000273
Ted Kremenekb05c9352007-12-18 22:07:33 +0000274 return Path(pathname);
275}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276
Chris Lattner085fe052009-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 Wendlingc1946742009-05-30 01:09:53 +0000282 struct stat sb;
Chris Lattner085fe052009-03-02 22:17:15 +0000283
Bill Wendlingc1946742009-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 Lattner085fe052009-03-02 22:17:15 +0000291}
292
293static char *
294getprogpath(char ret[PATH_MAX], const char *bin)
295{
Bill Wendlingc1946742009-05-30 01:09:53 +0000296 char *pv, *s, *t, buf[PATH_MAX];
Chris Lattner085fe052009-03-02 22:17:15 +0000297
Bill Wendlingc1946742009-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 Lattner085fe052009-03-02 22:17:15 +0000304
Bill Wendlingc1946742009-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 Lattner085fe052009-03-02 22:17:15 +0000313
Bill Wendlingc1946742009-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 Lattner085fe052009-03-02 22:17:15 +0000328}
329#endif
330
Chris Lattner365f2202008-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 Lattner085fe052009-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 Lattnerc9aca312008-03-13 05:22:05 +0000340 char exe_path[MAXPATHLEN];
Seo Sanghyeon4d048212008-06-27 22:55:30 +0000341 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Chris Lattnerc9aca312008-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 Lattner365f2202008-03-03 02:55:43 +0000347 // Use dladdr to get executable path if available.
Chris Lattner365f2202008-03-03 02:55:43 +0000348 Dl_info DLInfo;
349 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnera8164e42009-02-19 05:34:35 +0000350 if (err == 0)
351 return Path();
Bill Wendlingc1946742009-05-30 01:09:53 +0000352
Chris Lattnera8164e42009-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 Lattner365f2202008-03-03 02:55:43 +0000357#endif
358 return Path();
359}
360
361
Ted Kremenekb169dfa2008-04-07 22:01:32 +0000362std::string Path::getDirname() const {
363 return getDirnameCharSep(path, '/');
364}
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000365
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366std::string
367Path::getBasename() const {
368 // Find the last slash
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000369 std::string::size_type slash = path.rfind('/');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 if (slash == std::string::npos)
371 slash = 0;
372 else
373 slash++;
374
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000375 std::string::size_type dot = path.rfind('.');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 if (dot == std::string::npos || dot < slash)
377 return path.substr(slash);
378 else
379 return path.substr(slash, dot - slash);
380}
381
Argiris Kirtzidisc8f4a3a2008-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 Matyjewiczce6f1372008-06-15 18:02:47 +0000393 return std::string();
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000394 else
395 return path.substr(dot + 1);
396}
397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
399 assert(len < 1024 && "Request for magic string too long");
400 char* buf = (char*) alloca(1 + len);
401 int fd = ::open(path.c_str(), O_RDONLY);
402 if (fd < 0)
403 return false;
404 ssize_t bytes_read = ::read(fd, buf, len);
405 ::close(fd);
406 if (ssize_t(len) != bytes_read) {
407 Magic.clear();
408 return false;
409 }
410 Magic.assign(buf,len);
411 return true;
412}
413
414bool
415Path::exists() const {
416 return 0 == access(path.c_str(), F_OK );
417}
418
419bool
Ted Kremenek65149be2007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428Path::canRead() const {
429 return 0 == access(path.c_str(), F_OK | R_OK );
430}
431
432bool
433Path::canWrite() const {
434 return 0 == access(path.c_str(), F_OK | W_OK );
435}
436
437bool
438Path::canExecute() const {
439 if (0 != access(path.c_str(), R_OK | X_OK ))
440 return false;
441 struct stat buf;
442 if (0 != stat(path.c_str(), &buf))
443 return false;
444 if (!S_ISREG(buf.st_mode))
445 return false;
446 return true;
447}
448
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000449std::string
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
471const FileStatus *
472PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
473 if (!fsIsValid || update) {
474 struct stat buf;
475 if (0 != stat(path.c_str(), &buf)) {
476 MakeErrMsg(ErrStr, path + ": can't get status of file");
477 return 0;
478 }
479 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;
488 }
489 return &status;
490}
491
492static bool AddPermissionBits(const Path &File, int bits) {
493 // 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.
501 struct stat buf;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000502 if (0 != stat(File.toString().c_str(), &buf))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 return false;
504 // 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;
508 return true;
509}
510
511bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000512 if (!AddPermissionBits(*this, 0444))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
514 return false;
515}
516
517bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
518 if (!AddPermissionBits(*this, 0222))
519 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
520 return false;
521}
522
523bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
524 if (!AddPermissionBits(*this, 0111))
525 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
526 return false;
527}
528
529bool
530Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
531 DIR* direntries = ::opendir(path.c_str());
532 if (direntries == 0)
533 return MakeErrMsg(ErrMsg, path + ": can't open directory");
534
535 std::string dirPath = path;
536 if (!lastIsSlash(dirPath))
537 dirPath += '/';
538
539 result.clear();
540 struct dirent* de = ::readdir(direntries);
541 for ( ; de != 0; de = ::readdir(direntries)) {
542 if (de->d_name[0] != '.') {
543 Path aPath(dirPath + (const char*)de->d_name);
544 struct stat st;
545 if (0 != lstat(aPath.path.c_str(), &st)) {
546 if (S_ISLNK(st.st_mode))
547 continue; // dangling symlink -- ignore
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000548 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 aPath.path + ": can't determine file object type");
550 }
551 result.insert(aPath);
552 }
553 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000554
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 closedir(direntries);
556 return false;
557}
558
559bool
560Path::set(const std::string& a_path) {
561 if (a_path.empty())
562 return false;
563 std::string save(path);
564 path = a_path;
565 if (!isValid()) {
566 path = save;
567 return false;
568 }
569 return true;
570}
571
572bool
573Path::appendComponent(const std::string& name) {
574 if (name.empty())
575 return false;
576 std::string save(path);
577 if (!lastIsSlash(path))
578 path += '/';
579 path += name;
580 if (!isValid()) {
581 path = save;
582 return false;
583 }
584 return true;
585}
586
587bool
588Path::eraseComponent() {
589 size_t slashpos = path.rfind('/',path.size());
590 if (slashpos == 0 || slashpos == std::string::npos) {
591 path.erase();
592 return true;
593 }
594 if (slashpos == path.size() - 1)
595 slashpos = path.rfind('/',slashpos-1);
596 if (slashpos == std::string::npos) {
597 path.erase();
598 return true;
599 }
600 path.erase(slashpos);
601 return true;
602}
603
604bool
605Path::appendSuffix(const std::string& suffix) {
606 std::string save(path);
607 path.append(".");
608 path.append(suffix);
609 if (!isValid()) {
610 path = save;
611 return false;
612 }
613 return true;
614}
615
616bool
617Path::eraseSuffix() {
618 std::string save = path;
619 size_t dotpos = path.rfind('.',path.size());
620 size_t slashpos = path.rfind('/',path.size());
621 if (dotpos != std::string::npos) {
622 if (slashpos == std::string::npos || dotpos > slashpos+1) {
623 path.erase(dotpos, path.size()-dotpos);
624 return true;
625 }
626 }
627 if (!isValid())
628 path = save;
629 return false;
630}
631
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000632static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000633
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000634 if (access(beg, F_OK | R_OK | W_OK) == 0)
635 return false;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000636
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000637 if (create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000638
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000639 char* c = end;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000640
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000641 for (; c != beg; --c)
642 if (*c == '/') {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000643
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000644 // Recurse to handling the parent directory.
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000645 *c = '\0';
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000646 bool x = createDirectoryHelper(beg, c, create_parents);
647 *c = '/';
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000648
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000649 // Return if we encountered an error.
650 if (x)
651 return true;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000652
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000653 break;
654 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000655 }
656
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000657 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
658}
659
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660bool
661Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
662 // 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 Cheng591bfc82008-05-05 18:30:58 +0000667 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000668
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000669 if (pathname[lastchar] != '/')
670 ++lastchar;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000671
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000672 pathname[lastchar] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000673
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000674 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000675 return MakeErrMsg(ErrMsg,
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000676 std::string(pathname) + ": can't create directory");
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000677
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 return false;
679}
680
681bool
682Path::createFileOnDisk(std::string* ErrMsg) {
683 // Create the file
684 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
685 if (fd < 0)
686 return MakeErrMsg(ErrMsg, path + ": can't create file");
687 ::close(fd);
688 return false;
689}
690
691bool
692Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
693 // Make this into a unique file name
694 if (makeUnique( reuse_current, ErrMsg ))
695 return true;
696
697 // create the file
698 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000699 if (fd < 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
701 ::close(fd);
702 return false;
703}
704
705bool
706Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
707 // 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");
711 return true;
712 }
713
Mikhail Glushenkov9c369df2009-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Glushenkov9c369df2009-02-15 03:20:03 +0000724
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 if (!S_ISDIR(buf.st_mode)) {
726 if (ErrStr) *ErrStr = "not a file or directory";
727 return true;
728 }
729
730 if (remove_contents) {
731 // Recursively descend the directory to remove its contents.
732 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov61c9b982009-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 return false;
738 }
739
740 // Otherwise, try to just remove the one directory.
741 char pathname[MAXPATHLEN];
742 path.copy(pathname, MAXPATHLEN);
Evan Cheng591bfc82008-05-05 18:30:58 +0000743 size_t lastchar = path.length() - 1;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000744 if (pathname[lastchar] == '/')
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 pathname[lastchar] = 0;
746 else
747 pathname[lastchar+1] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000748
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 if (rmdir(pathname) != 0)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000750 return MakeErrMsg(ErrStr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 std::string(pathname) + ": can't erase directory");
752 return false;
753}
754
755bool
756Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
757 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000758 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000759 newName.toString() + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 return false;
761}
762
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000763bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
765 struct utimbuf utb;
766 utb.actime = si.modTime.toPosixTime();
767 utb.modtime = utb.actime;
768 if (0 != ::utime(path.c_str(),&utb))
769 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
770 if (0 != ::chmod(path.c_str(),si.mode))
771 return MakeErrMsg(ErrStr, path + ": can't set mode");
772 return false;
773}
774
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000775bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
777 int inFile = -1;
778 int outFile = -1;
779 inFile = ::open(Src.c_str(), O_RDONLY);
780 if (inFile == -1)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000781 return MakeErrMsg(ErrMsg, Src.toString() +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 ": can't open source file to copy");
783
784 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 }
790
791 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 Dunbarf7ea85d2009-04-20 20:50:13 +0000797 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file");
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Glushenkov9c369df2009-02-15 03:20:03 +0000807 return MakeErrMsg(ErrMsg, Dest.toString() +
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000808 ": can't write destination file");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 }
810 } else {
811 Amt -= AmtWritten;
812 BufPtr += AmtWritten;
813 }
814 }
815 }
816 }
817 ::close(inFile);
818 ::close(outFile);
819 return false;
820}
821
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000822bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
824 if (reuse_current && !exists())
825 return false; // File doesn't exist already, just use it!
826
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000827 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 // mktemp or our own implementation.
829 char *FNBuffer = (char*) alloca(path.size()+8);
Devang Patel79612e12008-07-22 20:02:39 +0000830 path.copy(FNBuffer,path.size());
Devang Pateldb08c702008-07-24 00:35:38 +0000831 if (isDirectory())
832 strcpy(FNBuffer+path.size(), "/XXXXXX");
833 else
Devang Patel79612e12008-07-22 20:02:39 +0000834 strcpy(FNBuffer+path.size(), "-XXXXXX");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835
836#if defined(HAVE_MKSTEMP)
837 int TempFD;
838 if ((TempFD = mkstemp(FNBuffer)) == -1)
839 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
840
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.
849 if (mktemp(FNBuffer) == 0)
850 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
851
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 Glushenkov9c369df2009-02-15 03:20:03 +0000863 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 path + ": can't make unique filename: too many files");
865#endif
866 return false;
867}
868
Chris Lattner157d70a2008-04-01 06:00:12 +0000869const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner7bbb6d62008-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 Lattner116abbf2008-04-01 06:25:23 +0000877 return (const char*)BasePtr;
Chris Lattner157d70a2008-04-01 06:00:12 +0000878}
879
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000880void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner116abbf2008-04-01 06:25:23 +0000881 ::munmap((void*)BasePtr, FileSize);
Chris Lattner157d70a2008-04-01 06:00:12 +0000882}
883
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884} // end llvm namespace