blob: a8dcedb7417947e34e45df5290ca529a5b56eebf [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
120Path::GetTemporaryDirectory(std::string* ErrMsg ) {
121#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);
283 if (err != 0)
284 return Path(std::string(DLInfo.dli_fname));
285#endif
286 return Path();
287}
288
289
Ted Kremenekb169dfa2008-04-07 22:01:32 +0000290std::string Path::getDirname() const {
291 return getDirnameCharSep(path, '/');
292}
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000293
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294std::string
295Path::getBasename() const {
296 // Find the last slash
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000297 std::string::size_type slash = path.rfind('/');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 if (slash == std::string::npos)
299 slash = 0;
300 else
301 slash++;
302
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000303 std::string::size_type dot = path.rfind('.');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 if (dot == std::string::npos || dot < slash)
305 return path.substr(slash);
306 else
307 return path.substr(slash, dot - slash);
308}
309
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000310std::string
311Path::getSuffix() const {
312 // Find the last slash
313 std::string::size_type slash = path.rfind('/');
314 if (slash == std::string::npos)
315 slash = 0;
316 else
317 slash++;
318
319 std::string::size_type dot = path.rfind('.');
320 if (dot == std::string::npos || dot < slash)
Wojciech Matyjewiczce6f1372008-06-15 18:02:47 +0000321 return std::string();
Argiris Kirtzidisc8f4a3a2008-06-15 15:15:19 +0000322 else
323 return path.substr(dot + 1);
324}
325
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
327 assert(len < 1024 && "Request for magic string too long");
328 char* buf = (char*) alloca(1 + len);
329 int fd = ::open(path.c_str(), O_RDONLY);
330 if (fd < 0)
331 return false;
332 ssize_t bytes_read = ::read(fd, buf, len);
333 ::close(fd);
334 if (ssize_t(len) != bytes_read) {
335 Magic.clear();
336 return false;
337 }
338 Magic.assign(buf,len);
339 return true;
340}
341
342bool
343Path::exists() const {
344 return 0 == access(path.c_str(), F_OK );
345}
346
347bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000348Path::isDirectory() const {
349 struct stat buf;
350 if (0 != stat(path.c_str(), &buf))
351 return false;
352 return buf.st_mode & S_IFDIR ? true : false;
353}
354
355bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356Path::canRead() const {
357 return 0 == access(path.c_str(), F_OK | R_OK );
358}
359
360bool
361Path::canWrite() const {
362 return 0 == access(path.c_str(), F_OK | W_OK );
363}
364
365bool
366Path::canExecute() const {
367 if (0 != access(path.c_str(), R_OK | X_OK ))
368 return false;
369 struct stat buf;
370 if (0 != stat(path.c_str(), &buf))
371 return false;
372 if (!S_ISREG(buf.st_mode))
373 return false;
374 return true;
375}
376
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000377std::string
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378Path::getLast() const {
379 // Find the last slash
380 size_t pos = path.rfind('/');
381
382 // Handle the corner cases
383 if (pos == std::string::npos)
384 return path;
385
386 // If the last character is a slash
387 if (pos == path.length()-1) {
388 // Find the second to last slash
389 size_t pos2 = path.rfind('/', pos-1);
390 if (pos2 == std::string::npos)
391 return path.substr(0,pos);
392 else
393 return path.substr(pos2+1,pos-pos2-1);
394 }
395 // Return everything after the last slash
396 return path.substr(pos+1);
397}
398
399const FileStatus *
400PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
401 if (!fsIsValid || update) {
402 struct stat buf;
403 if (0 != stat(path.c_str(), &buf)) {
404 MakeErrMsg(ErrStr, path + ": can't get status of file");
405 return 0;
406 }
407 status.fileSize = buf.st_size;
408 status.modTime.fromEpochTime(buf.st_mtime);
409 status.mode = buf.st_mode;
410 status.user = buf.st_uid;
411 status.group = buf.st_gid;
412 status.uniqueID = uint64_t(buf.st_ino);
413 status.isDir = S_ISDIR(buf.st_mode);
414 status.isFile = S_ISREG(buf.st_mode);
415 fsIsValid = true;
416 }
417 return &status;
418}
419
420static bool AddPermissionBits(const Path &File, int bits) {
421 // Get the umask value from the operating system. We want to use it
422 // when changing the file's permissions. Since calling umask() sets
423 // the umask and returns its old value, we must call it a second
424 // time to reset it to the user's preference.
425 int mask = umask(0777); // The arg. to umask is arbitrary.
426 umask(mask); // Restore the umask.
427
428 // Get the file's current mode.
429 struct stat buf;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000430 if (0 != stat(File.toString().c_str(), &buf))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 return false;
432 // Change the file to have whichever permissions bits from 'bits'
433 // that the umask would not disable.
434 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
435 return false;
436 return true;
437}
438
439bool Path::makeReadableOnDisk(std::string* ErrMsg) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000440 if (!AddPermissionBits(*this, 0444))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
442 return false;
443}
444
445bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
446 if (!AddPermissionBits(*this, 0222))
447 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
448 return false;
449}
450
451bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
452 if (!AddPermissionBits(*this, 0111))
453 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
454 return false;
455}
456
457bool
458Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
459 DIR* direntries = ::opendir(path.c_str());
460 if (direntries == 0)
461 return MakeErrMsg(ErrMsg, path + ": can't open directory");
462
463 std::string dirPath = path;
464 if (!lastIsSlash(dirPath))
465 dirPath += '/';
466
467 result.clear();
468 struct dirent* de = ::readdir(direntries);
469 for ( ; de != 0; de = ::readdir(direntries)) {
470 if (de->d_name[0] != '.') {
471 Path aPath(dirPath + (const char*)de->d_name);
472 struct stat st;
473 if (0 != lstat(aPath.path.c_str(), &st)) {
474 if (S_ISLNK(st.st_mode))
475 continue; // dangling symlink -- ignore
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000476 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 aPath.path + ": can't determine file object type");
478 }
479 result.insert(aPath);
480 }
481 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000482
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 closedir(direntries);
484 return false;
485}
486
487bool
488Path::set(const std::string& a_path) {
489 if (a_path.empty())
490 return false;
491 std::string save(path);
492 path = a_path;
493 if (!isValid()) {
494 path = save;
495 return false;
496 }
497 return true;
498}
499
500bool
501Path::appendComponent(const std::string& name) {
502 if (name.empty())
503 return false;
504 std::string save(path);
505 if (!lastIsSlash(path))
506 path += '/';
507 path += name;
508 if (!isValid()) {
509 path = save;
510 return false;
511 }
512 return true;
513}
514
515bool
516Path::eraseComponent() {
517 size_t slashpos = path.rfind('/',path.size());
518 if (slashpos == 0 || slashpos == std::string::npos) {
519 path.erase();
520 return true;
521 }
522 if (slashpos == path.size() - 1)
523 slashpos = path.rfind('/',slashpos-1);
524 if (slashpos == std::string::npos) {
525 path.erase();
526 return true;
527 }
528 path.erase(slashpos);
529 return true;
530}
531
532bool
533Path::appendSuffix(const std::string& suffix) {
534 std::string save(path);
535 path.append(".");
536 path.append(suffix);
537 if (!isValid()) {
538 path = save;
539 return false;
540 }
541 return true;
542}
543
544bool
545Path::eraseSuffix() {
546 std::string save = path;
547 size_t dotpos = path.rfind('.',path.size());
548 size_t slashpos = path.rfind('/',path.size());
549 if (dotpos != std::string::npos) {
550 if (slashpos == std::string::npos || dotpos > slashpos+1) {
551 path.erase(dotpos, path.size()-dotpos);
552 return true;
553 }
554 }
555 if (!isValid())
556 path = save;
557 return false;
558}
559
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000560static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000561
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000562 if (access(beg, F_OK | R_OK | W_OK) == 0)
563 return false;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000564
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000565 if (create_parents) {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000566
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000567 char* c = end;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000568
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000569 for (; c != beg; --c)
570 if (*c == '/') {
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000571
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000572 // Recurse to handling the parent directory.
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000573 *c = '\0';
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000574 bool x = createDirectoryHelper(beg, c, create_parents);
575 *c = '/';
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000576
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000577 // Return if we encountered an error.
578 if (x)
579 return true;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000580
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000581 break;
582 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000583 }
584
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000585 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
586}
587
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588bool
589Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
590 // Get a writeable copy of the path name
591 char pathname[MAXPATHLEN];
592 path.copy(pathname,MAXPATHLEN);
593
594 // Null-terminate the last component
Evan Cheng591bfc82008-05-05 18:30:58 +0000595 size_t lastchar = path.length() - 1 ;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000596
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000597 if (pathname[lastchar] != '/')
598 ++lastchar;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000599
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000600 pathname[lastchar] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000601
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000602 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000603 return MakeErrMsg(ErrMsg,
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000604 std::string(pathname) + ": can't create directory");
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000605
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 return false;
607}
608
609bool
610Path::createFileOnDisk(std::string* ErrMsg) {
611 // Create the file
612 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
613 if (fd < 0)
614 return MakeErrMsg(ErrMsg, path + ": can't create file");
615 ::close(fd);
616 return false;
617}
618
619bool
620Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
621 // Make this into a unique file name
622 if (makeUnique( reuse_current, ErrMsg ))
623 return true;
624
625 // create the file
626 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000627 if (fd < 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
629 ::close(fd);
630 return false;
631}
632
633bool
634Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
635 // Get the status so we can determin if its a file or directory
636 struct stat buf;
637 if (0 != stat(path.c_str(), &buf)) {
638 MakeErrMsg(ErrStr, path + ": can't get status of file");
639 return true;
640 }
641
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000642 // Note: this check catches strange situations. In all cases, LLVM should
643 // only be involved in the creation and deletion of regular files. This
644 // check ensures that what we're trying to erase is a regular file. It
645 // effectively prevents LLVM from erasing things like /dev/null, any block
646 // special file, or other things that aren't "regular" files.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 if (S_ISREG(buf.st_mode)) {
648 if (unlink(path.c_str()) != 0)
649 return MakeErrMsg(ErrStr, path + ": can't destroy file");
650 return false;
651 }
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000652
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 if (!S_ISDIR(buf.st_mode)) {
654 if (ErrStr) *ErrStr = "not a file or directory";
655 return true;
656 }
657
658 if (remove_contents) {
659 // Recursively descend the directory to remove its contents.
660 std::string cmd = "/bin/rm -rf " + path;
Mikhail Glushenkov61c9b982009-02-15 03:20:32 +0000661 if (system(cmd.c_str()) != 0) {
662 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
663 return true;
664 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 return false;
666 }
667
668 // Otherwise, try to just remove the one directory.
669 char pathname[MAXPATHLEN];
670 path.copy(pathname, MAXPATHLEN);
Evan Cheng591bfc82008-05-05 18:30:58 +0000671 size_t lastchar = path.length() - 1;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000672 if (pathname[lastchar] == '/')
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 pathname[lastchar] = 0;
674 else
675 pathname[lastchar+1] = 0;
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000676
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 if (rmdir(pathname) != 0)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000678 return MakeErrMsg(ErrStr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 std::string(pathname) + ": can't erase directory");
680 return false;
681}
682
683bool
684Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
685 if (0 != ::rename(path.c_str(), newName.c_str()))
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000686 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 newName.toString() + "' ");
688 return false;
689}
690
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000691bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
693 struct utimbuf utb;
694 utb.actime = si.modTime.toPosixTime();
695 utb.modtime = utb.actime;
696 if (0 != ::utime(path.c_str(),&utb))
697 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
698 if (0 != ::chmod(path.c_str(),si.mode))
699 return MakeErrMsg(ErrStr, path + ": can't set mode");
700 return false;
701}
702
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000703bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
705 int inFile = -1;
706 int outFile = -1;
707 inFile = ::open(Src.c_str(), O_RDONLY);
708 if (inFile == -1)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000709 return MakeErrMsg(ErrMsg, Src.toString() +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 ": can't open source file to copy");
711
712 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
713 if (outFile == -1) {
714 ::close(inFile);
715 return MakeErrMsg(ErrMsg, Dest.toString() +
716 ": can't create destination file for copy");
717 }
718
719 char Buffer[16*1024];
720 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
721 if (Amt == -1) {
722 if (errno != EINTR && errno != EAGAIN) {
723 ::close(inFile);
724 ::close(outFile);
725 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
726 }
727 } else {
728 char *BufPtr = Buffer;
729 while (Amt) {
730 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
731 if (AmtWritten == -1) {
732 if (errno != EINTR && errno != EAGAIN) {
733 ::close(inFile);
734 ::close(outFile);
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000735 return MakeErrMsg(ErrMsg, Dest.toString() +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 ": can't write destination file: ");
737 }
738 } else {
739 Amt -= AmtWritten;
740 BufPtr += AmtWritten;
741 }
742 }
743 }
744 }
745 ::close(inFile);
746 ::close(outFile);
747 return false;
748}
749
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000750bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
752 if (reuse_current && !exists())
753 return false; // File doesn't exist already, just use it!
754
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000755 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 // mktemp or our own implementation.
757 char *FNBuffer = (char*) alloca(path.size()+8);
Devang Patel79612e12008-07-22 20:02:39 +0000758 path.copy(FNBuffer,path.size());
Devang Pateldb08c702008-07-24 00:35:38 +0000759 if (isDirectory())
760 strcpy(FNBuffer+path.size(), "/XXXXXX");
761 else
Devang Patel79612e12008-07-22 20:02:39 +0000762 strcpy(FNBuffer+path.size(), "-XXXXXX");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763
764#if defined(HAVE_MKSTEMP)
765 int TempFD;
766 if ((TempFD = mkstemp(FNBuffer)) == -1)
767 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
768
769 // We don't need to hold the temp file descriptor... we will trust that no one
770 // will overwrite/delete the file before we can open it again.
771 close(TempFD);
772
773 // Save the name
774 path = FNBuffer;
775#elif defined(HAVE_MKTEMP)
776 // If we don't have mkstemp, use the old and obsolete mktemp function.
777 if (mktemp(FNBuffer) == 0)
778 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
779
780 // Save the name
781 path = FNBuffer;
782#else
783 // Okay, looks like we have to do it all by our lonesome.
784 static unsigned FCounter = 0;
785 unsigned offset = path.size() + 1;
786 while ( FCounter < 999999 && exists()) {
787 sprintf(FNBuffer+offset,"%06u",++FCounter);
788 path = FNBuffer;
789 }
790 if (FCounter > 999999)
Mikhail Glushenkov9c369df2009-02-15 03:20:03 +0000791 return MakeErrMsg(ErrMsg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 path + ": can't make unique filename: too many files");
793#endif
794 return false;
795}
796
Chris Lattner157d70a2008-04-01 06:00:12 +0000797const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000798 int Flags = MAP_PRIVATE;
799#ifdef MAP_FILE
800 Flags |= MAP_FILE;
801#endif
802 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
803 if (BasePtr == MAP_FAILED)
804 return 0;
Chris Lattner116abbf2008-04-01 06:25:23 +0000805 return (const char*)BasePtr;
Chris Lattner157d70a2008-04-01 06:00:12 +0000806}
807
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000808void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner116abbf2008-04-01 06:25:23 +0000809 ::munmap((void*)BasePtr, FileSize);
Chris Lattner157d70a2008-04-01 06:00:12 +0000810}
811
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812} // end llvm namespace
813