blob: 3a651f957cd0aa5f37ae3ac8f33e848a1cc6e4b4 [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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107Path::isAbsolute() const {
108 if (path.empty())
109 return false;
110 return path[0] == '/';
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000111}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000112Path
113Path::GetRootDirectory() {
114 Path result;
115 result.set("/");
116 return result;
117}
118
119Path
Chris Lattnera8164e42009-02-19 05:34:35 +0000120Path::GetTemporaryDirectory(std::string *ErrMsg) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121#if defined(HAVE_MKDTEMP)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000122 // The best way is with mkdtemp but that's not available on many systems,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 // Linux and FreeBSD have it. Others probably won't.
124 char pathname[MAXPATHLEN];
125 strcpy(pathname,"/tmp/llvm_XXXXXX");
126 if (0 == mkdtemp(pathname)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000127 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 std::string(pathname) + ": can't create temporary directory");
129 return Path();
130 }
131 Path result;
132 result.set(pathname);
133 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
134 return result;
135#elif defined(HAVE_MKSTEMP)
136 // If no mkdtemp is available, mkstemp can be used to create a temporary file
137 // which is then removed and created as a directory. We prefer this over
138 // mktemp because of mktemp's inherent security and threading risks. We still
139 // have a slight race condition from the time the temporary file is created to
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000140 // the time it is re-created as a directoy.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 char pathname[MAXPATHLEN];
142 strcpy(pathname, "/tmp/llvm_XXXXXX");
143 int fd = 0;
144 if (-1 == (fd = mkstemp(pathname))) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000145 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 std::string(pathname) + ": can't create temporary directory");
147 return Path();
148 }
149 ::close(fd);
150 ::unlink(pathname); // start race condition, ignore errors
151 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000152 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 std::string(pathname) + ": can't create temporary directory");
154 return Path();
155 }
156 Path result;
157 result.set(pathname);
158 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
159 return result;
160#elif defined(HAVE_MKTEMP)
161 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
162 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
163 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
164 // the XXXXXX with the pid of the process and a letter. That leads to only
165 // twenty six temporary files that can be generated.
166 char pathname[MAXPATHLEN];
167 strcpy(pathname, "/tmp/llvm_XXXXXX");
168 char *TmpName = ::mktemp(pathname);
169 if (TmpName == 0) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000170 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 std::string(TmpName) + ": can't create unique directory name");
172 return Path();
173 }
174 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000175 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 std::string(TmpName) + ": can't create temporary directory");
177 return Path();
178 }
179 Path result;
180 result.set(TmpName);
181 assert(result.isValid() && "mktemp didn't create a valid pathname!");
182 return result;
183#else
184 // This is the worst case implementation. tempnam(3) leaks memory unless its
185 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
186 // issues. The mktemp(3) function doesn't have enough variability in the
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000187 // temporary name generated. So, we provide our own implementation that
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 // increments an integer from a random number seeded by the current time. This
189 // should be sufficiently unique that we don't have many collisions between
190 // processes. Generally LLVM processes don't run very long and don't use very
191 // many temporary files so this shouldn't be a big issue for LLVM.
192 static time_t num = ::time(0);
193 char pathname[MAXPATHLEN];
194 do {
195 num++;
196 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
197 } while ( 0 == access(pathname, F_OK ) );
198 if (-1 == ::mkdir(pathname, S_IRWXU)) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000199 MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 std::string(pathname) + ": can't create temporary directory");
201 return Path();
202 }
203 Path result;
204 result.set(pathname);
205 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
206 return result;
207#endif
208}
209
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000210void
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
212#ifdef LTDL_SHLIBPATH_VAR
213 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
214 if (env_var != 0) {
215 getPathList(env_var,Paths);
216 }
217#endif
218 // FIXME: Should this look at LD_LIBRARY_PATH too?
219 Paths.push_back(sys::Path("/usr/local/lib/"));
220 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
221 Paths.push_back(sys::Path("/usr/lib/"));
222 Paths.push_back(sys::Path("/lib/"));
223}
224
225void
226Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
227 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
228 if (env_var != 0) {
229 getPathList(env_var,Paths);
230 }
231#ifdef LLVM_LIBDIR
232 {
233 Path tmpPath;
234 if (tmpPath.set(LLVM_LIBDIR))
235 if (tmpPath.canRead())
236 Paths.push_back(tmpPath);
237 }
238#endif
239 GetSystemLibraryPaths(Paths);
240}
241
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000242Path
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243Path::GetLLVMDefaultConfigDir() {
244 return Path("/etc/llvm/");
245}
246
247Path
248Path::GetUserHomeDirectory() {
249 const char* home = getenv("HOME");
250 if (home) {
251 Path result;
252 if (result.set(home))
253 return result;
254 }
255 return GetRootDirectory();
256}
257
Ted Kremenekb05c9352007-12-18 22:07:33 +0000258Path
259Path::GetCurrentDirectory() {
260 char pathname[MAXPATHLEN];
261 if (!getcwd(pathname,MAXPATHLEN)) {
262 assert (false && "Could not query current working directory.");
263 return Path("");
264 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000265
Ted Kremenekb05c9352007-12-18 22:07:33 +0000266 return Path(pathname);
267}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268
Chris Lattner365f2202008-03-03 02:55:43 +0000269/// GetMainExecutable - Return the path to the main executable, given the
270/// value of argv[0] from program startup.
271Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Seo Sanghyeon4d048212008-06-27 22:55:30 +0000272#if defined(__linux__) || defined(__CYGWIN__)
Chris Lattnerc9aca312008-03-13 05:22:05 +0000273 char exe_path[MAXPATHLEN];
Seo Sanghyeon4d048212008-06-27 22:55:30 +0000274 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
Chris Lattnerc9aca312008-03-13 05:22:05 +0000275 if (len > 0 && len < MAXPATHLEN - 1) {
276 exe_path[len] = '\0';
277 return Path(std::string(exe_path));
278 }
279#elif defined(HAVE_DLFCN_H)
Chris Lattner365f2202008-03-03 02:55:43 +0000280 // Use dladdr to get executable path if available.
Chris Lattner365f2202008-03-03 02:55:43 +0000281 Dl_info DLInfo;
282 int err = dladdr(MainAddr, &DLInfo);
Chris Lattnera8164e42009-02-19 05:34:35 +0000283 if (err == 0)
284 return Path();
285
286 // If the filename is a symlink, we need to resolve and return the location of
287 // the actual executable.
288 char link_path[MAXPATHLEN];
289 return Path(std::string(realpath(DLInfo.dli_fname, link_path)));
Chris Lattner365f2202008-03-03 02:55:43 +0000290#endif
291 return Path();
292}
293
294
Ted Kremenekb169dfa2008-04-07 22:01:32 +0000295std::string Path::getDirname() const {
296 return getDirnameCharSep(path, '/');
297}
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000298
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299std::string
300Path::getBasename() const {
301 // Find the last slash
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000302 std::string::size_type slash = path.rfind('/');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 if (slash == std::string::npos)
304 slash = 0;
305 else
306 slash++;
307
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000308 std::string::size_type dot = path.rfind('.');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 if (dot == std::string::npos || dot < slash)
310 return path.substr(slash);
311 else
312 return path.substr(slash, dot - slash);
313}
314
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000315std::string
316Path::getSuffix() const {
317 // Find the last slash
318 std::string::size_type slash = path.rfind('/');
319 if (slash == std::string::npos)
320 slash = 0;
321 else
322 slash++;
323
324 std::string::size_type dot = path.rfind('.');
325 if (dot == std::string::npos || dot < slash)
Wojciech Matyjewiczce6f1372008-06-15 18:02:47 +0000326 return std::string();
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000327 else
328 return path.substr(dot + 1);
329}
330
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
332 assert(len < 1024 && "Request for magic string too long");
333 char* buf = (char*) alloca(1 + len);
334 int fd = ::open(path.c_str(), O_RDONLY);
335 if (fd < 0)
336 return false;
337 ssize_t bytes_read = ::read(fd, buf, len);
338 ::close(fd);
339 if (ssize_t(len) != bytes_read) {
340 Magic.clear();
341 return false;
342 }
343 Magic.assign(buf,len);
344 return true;
345}
346
347bool
348Path::exists() const {
349 return 0 == access(path.c_str(), F_OK );
350}
351
352bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000353Path::isDirectory() const {
354 struct stat buf;
355 if (0 != stat(path.c_str(), &buf))
356 return false;
357 return buf.st_mode & S_IFDIR ? true : false;
358}
359
360bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361Path::canRead() const {
362 return 0 == access(path.c_str(), F_OK | R_OK );
363}
364
365bool
366Path::canWrite() const {
367 return 0 == access(path.c_str(), F_OK | W_OK );
368}
369
370bool
371Path::canExecute() const {
372 if (0 != access(path.c_str(), R_OK | X_OK ))
373 return false;
374 struct stat buf;
375 if (0 != stat(path.c_str(), &buf))
376 return false;
377 if (!S_ISREG(buf.st_mode))
378 return false;
379 return true;
380}
381
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000382std::string
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383Path::getLast() const {
384 // Find the last slash
385 size_t pos = path.rfind('/');
386
387 // Handle the corner cases
388 if (pos == std::string::npos)
389 return path;
390
391 // If the last character is a slash
392 if (pos == path.length()-1) {
393 // Find the second to last slash
394 size_t pos2 = path.rfind('/', pos-1);
395 if (pos2 == std::string::npos)
396 return path.substr(0,pos);
397 else
398 return path.substr(pos2+1,pos-pos2-1);
399 }
400 // Return everything after the last slash
401 return path.substr(pos+1);
402}
403
404const FileStatus *
405PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
406 if (!fsIsValid || update) {
407 struct stat buf;
408 if (0 != stat(path.c_str(), &buf)) {
409 MakeErrMsg(ErrStr, path + ": can't get status of file");
410 return 0;
411 }
412 status.fileSize = buf.st_size;
413 status.modTime.fromEpochTime(buf.st_mtime);
414 status.mode = buf.st_mode;
415 status.user = buf.st_uid;
416 status.group = buf.st_gid;
417 status.uniqueID = uint64_t(buf.st_ino);
418 status.isDir = S_ISDIR(buf.st_mode);
419 status.isFile = S_ISREG(buf.st_mode);
420 fsIsValid = true;
421 }
422 return &status;
423}
424
425static bool AddPermissionBits(const Path &File, int bits) {
426 // Get the umask value from the operating system. We want to use it
427 // when changing the file's permissions. Since calling umask() sets
428 // the umask and returns its old value, we must call it a second
429 // time to reset it to the user's preference.
430 int mask = umask(0777); // The arg. to umask is arbitrary.
431 umask(mask); // Restore the umask.
432
433 // Get the file's current mode.
434 struct stat buf;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000435 if (0 != stat(File.toString().c_str(), &buf))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 return false;
437 // Change the file to have whichever permissions bits from 'bits'
438 // that the umask would not disable.
439 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
440 return false;
441 return true;
442}
443
444bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000445 if (!AddPermissionBits(*this, 0444))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
447 return false;
448}
449
450bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
451 if (!AddPermissionBits(*this, 0222))
452 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
453 return false;
454}
455
456bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
457 if (!AddPermissionBits(*this, 0111))
458 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
459 return false;
460}
461
462bool
463Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
464 DIR* direntries = ::opendir(path.c_str());
465 if (direntries == 0)
466 return MakeErrMsg(ErrMsg, path + ": can't open directory");
467
468 std::string dirPath = path;
469 if (!lastIsSlash(dirPath))
470 dirPath += '/';
471
472 result.clear();
473 struct dirent* de = ::readdir(direntries);
474 for ( ; de != 0; de = ::readdir(direntries)) {
475 if (de->d_name[0] != '.') {
476 Path aPath(dirPath + (const char*)de->d_name);
477 struct stat st;
478 if (0 != lstat(aPath.path.c_str(), &st)) {
479 if (S_ISLNK(st.st_mode))
480 continue; // dangling symlink -- ignore
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000481 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 aPath.path + ": can't determine file object type");
483 }
484 result.insert(aPath);
485 }
486 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000487
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 closedir(direntries);
489 return false;
490}
491
492bool
493Path::set(const std::string& a_path) {
494 if (a_path.empty())
495 return false;
496 std::string save(path);
497 path = a_path;
498 if (!isValid()) {
499 path = save;
500 return false;
501 }
502 return true;
503}
504
505bool
506Path::appendComponent(const std::string& name) {
507 if (name.empty())
508 return false;
509 std::string save(path);
510 if (!lastIsSlash(path))
511 path += '/';
512 path += name;
513 if (!isValid()) {
514 path = save;
515 return false;
516 }
517 return true;
518}
519
520bool
521Path::eraseComponent() {
522 size_t slashpos = path.rfind('/',path.size());
523 if (slashpos == 0 || slashpos == std::string::npos) {
524 path.erase();
525 return true;
526 }
527 if (slashpos == path.size() - 1)
528 slashpos = path.rfind('/',slashpos-1);
529 if (slashpos == std::string::npos) {
530 path.erase();
531 return true;
532 }
533 path.erase(slashpos);
534 return true;
535}
536
537bool
538Path::appendSuffix(const std::string& suffix) {
539 std::string save(path);
540 path.append(".");
541 path.append(suffix);
542 if (!isValid()) {
543 path = save;
544 return false;
545 }
546 return true;
547}
548
549bool
550Path::eraseSuffix() {
551 std::string save = path;
552 size_t dotpos = path.rfind('.',path.size());
553 size_t slashpos = path.rfind('/',path.size());
554 if (dotpos != std::string::npos) {
555 if (slashpos == std::string::npos || dotpos > slashpos+1) {
556 path.erase(dotpos, path.size()-dotpos);
557 return true;
558 }
559 }
560 if (!isValid())
561 path = save;
562 return false;
563}
564
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000565static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000566
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000567 if (access(beg, F_OK | R_OK | W_OK) == 0)
568 return false;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000569
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000570 if (create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000571
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000572 char* c = end;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000573
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000574 for (; c != beg; --c)
575 if (*c == '/') {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000576
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000577 // Recurse to handling the parent directory.
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000578 *c = '\0';
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000579 bool x = createDirectoryHelper(beg, c, create_parents);
580 *c = '/';
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000581
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000582 // Return if we encountered an error.
583 if (x)
584 return true;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000585
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000586 break;
587 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000588 }
589
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000590 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
591}
592
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000593bool
594Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
595 // Get a writeable copy of the path name
596 char pathname[MAXPATHLEN];
597 path.copy(pathname,MAXPATHLEN);
598
599 // Null-terminate the last component
Evan Cheng591bfc82008-05-05 18:30:58 +0000600 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000601
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000602 if (pathname[lastchar] != '/')
603 ++lastchar;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000604
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000605 pathname[lastchar] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000606
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000607 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000608 return MakeErrMsg(ErrMsg,
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000609 std::string(pathname) + ": can't create directory");
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000610
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 return false;
612}
613
614bool
615Path::createFileOnDisk(std::string* ErrMsg) {
616 // Create the file
617 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
618 if (fd < 0)
619 return MakeErrMsg(ErrMsg, path + ": can't create file");
620 ::close(fd);
621 return false;
622}
623
624bool
625Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
626 // Make this into a unique file name
627 if (makeUnique( reuse_current, ErrMsg ))
628 return true;
629
630 // create the file
631 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000632 if (fd < 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
634 ::close(fd);
635 return false;
636}
637
638bool
639Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
640 // Get the status so we can determin if its a file or directory
641 struct stat buf;
642 if (0 != stat(path.c_str(), &buf)) {
643 MakeErrMsg(ErrStr, path + ": can't get status of file");
644 return true;
645 }
646
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000647 // Note: this check catches strange situations. In all cases, LLVM should
648 // only be involved in the creation and deletion of regular files. This
649 // check ensures that what we're trying to erase is a regular file. It
650 // effectively prevents LLVM from erasing things like /dev/null, any block
651 // special file, or other things that aren't "regular" files.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 if (S_ISREG(buf.st_mode)) {
653 if (unlink(path.c_str()) != 0)
654 return MakeErrMsg(ErrStr, path + ": can't destroy file");
655 return false;
656 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000657
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 if (!S_ISDIR(buf.st_mode)) {
659 if (ErrStr) *ErrStr = "not a file or directory";
660 return true;
661 }
662
663 if (remove_contents) {
664 // Recursively descend the directory to remove its contents.
665 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov61c9b982009-02-15 03:20:32 +0000666 if (system(cmd.c_str()) != 0) {
667 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
668 return true;
669 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 return false;
671 }
672
673 // Otherwise, try to just remove the one directory.
674 char pathname[MAXPATHLEN];
675 path.copy(pathname, MAXPATHLEN);
Evan Cheng591bfc82008-05-05 18:30:58 +0000676 size_t lastchar = path.length() - 1;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000677 if (pathname[lastchar] == '/')
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 pathname[lastchar] = 0;
679 else
680 pathname[lastchar+1] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000681
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 if (rmdir(pathname) != 0)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000683 return MakeErrMsg(ErrStr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 std::string(pathname) + ": can't erase directory");
685 return false;
686}
687
688bool
689Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
690 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000691 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 newName.toString() + "' ");
693 return false;
694}
695
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000696bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
698 struct utimbuf utb;
699 utb.actime = si.modTime.toPosixTime();
700 utb.modtime = utb.actime;
701 if (0 != ::utime(path.c_str(),&utb))
702 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
703 if (0 != ::chmod(path.c_str(),si.mode))
704 return MakeErrMsg(ErrStr, path + ": can't set mode");
705 return false;
706}
707
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000708bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
710 int inFile = -1;
711 int outFile = -1;
712 inFile = ::open(Src.c_str(), O_RDONLY);
713 if (inFile == -1)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000714 return MakeErrMsg(ErrMsg, Src.toString() +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 ": can't open source file to copy");
716
717 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
718 if (outFile == -1) {
719 ::close(inFile);
720 return MakeErrMsg(ErrMsg, Dest.toString() +
721 ": can't create destination file for copy");
722 }
723
724 char Buffer[16*1024];
725 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
726 if (Amt == -1) {
727 if (errno != EINTR && errno != EAGAIN) {
728 ::close(inFile);
729 ::close(outFile);
730 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
731 }
732 } else {
733 char *BufPtr = Buffer;
734 while (Amt) {
735 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
736 if (AmtWritten == -1) {
737 if (errno != EINTR && errno != EAGAIN) {
738 ::close(inFile);
739 ::close(outFile);
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000740 return MakeErrMsg(ErrMsg, Dest.toString() +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 ": can't write destination file: ");
742 }
743 } else {
744 Amt -= AmtWritten;
745 BufPtr += AmtWritten;
746 }
747 }
748 }
749 }
750 ::close(inFile);
751 ::close(outFile);
752 return false;
753}
754
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000755bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
757 if (reuse_current && !exists())
758 return false; // File doesn't exist already, just use it!
759
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000760 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 // mktemp or our own implementation.
762 char *FNBuffer = (char*) alloca(path.size()+8);
Devang Patel79612e12008-07-22 20:02:39 +0000763 path.copy(FNBuffer,path.size());
Devang Pateldb08c702008-07-24 00:35:38 +0000764 if (isDirectory())
765 strcpy(FNBuffer+path.size(), "/XXXXXX");
766 else
Devang Patel79612e12008-07-22 20:02:39 +0000767 strcpy(FNBuffer+path.size(), "-XXXXXX");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768
769#if defined(HAVE_MKSTEMP)
770 int TempFD;
771 if ((TempFD = mkstemp(FNBuffer)) == -1)
772 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
773
774 // We don't need to hold the temp file descriptor... we will trust that no one
775 // will overwrite/delete the file before we can open it again.
776 close(TempFD);
777
778 // Save the name
779 path = FNBuffer;
780#elif defined(HAVE_MKTEMP)
781 // If we don't have mkstemp, use the old and obsolete mktemp function.
782 if (mktemp(FNBuffer) == 0)
783 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
784
785 // Save the name
786 path = FNBuffer;
787#else
788 // Okay, looks like we have to do it all by our lonesome.
789 static unsigned FCounter = 0;
790 unsigned offset = path.size() + 1;
791 while ( FCounter < 999999 && exists()) {
792 sprintf(FNBuffer+offset,"%06u",++FCounter);
793 path = FNBuffer;
794 }
795 if (FCounter > 999999)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000796 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 path + ": can't make unique filename: too many files");
798#endif
799 return false;
800}
801
Chris Lattner157d70a2008-04-01 06:00:12 +0000802const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000803 int Flags = MAP_PRIVATE;
804#ifdef MAP_FILE
805 Flags |= MAP_FILE;
806#endif
807 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
808 if (BasePtr == MAP_FAILED)
809 return 0;
Chris Lattner116abbf2008-04-01 06:25:23 +0000810 return (const char*)BasePtr;
Chris Lattner157d70a2008-04-01 06:00:12 +0000811}
812
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000813void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner116abbf2008-04-01 06:25:23 +0000814 ::munmap((void*)BasePtr, FileSize);
Chris Lattner157d70a2008-04-01 06:00:12 +0000815}
816
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817} // end llvm namespace
818