1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Unix specific implementation of the Path API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
28 #ifdef HAVE_SYS_MMAN_H
33 # define NAMLEN(dirent) strlen((dirent)->d_name)
35 # define dirent direct
36 # define NAMLEN(dirent) (dirent)->d_namlen
38 # include <sys/ndir.h>
49 #include <mach-o/dyld.h>
52 // Both stdio.h and cstdio are included via different pathes and
53 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
59 #if defined(__GNU__) && !defined(PATH_MAX)
60 # define PATH_MAX 4096
68 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
69 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
70 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
72 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
75 char fullpath[PATH_MAX];
77 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
78 if (realpath(fullpath, ret) == NULL)
80 if (stat(fullpath, &sb) != 0)
87 getprogpath(char ret[PATH_MAX], const char *bin)
91 /* First approach: absolute path. */
93 if (test_dir(ret, "/", bin) == 0)
98 /* Second approach: relative path. */
99 if (strchr(bin, '/') != NULL) {
101 if (getcwd(cwd, PATH_MAX) == NULL)
103 if (test_dir(ret, cwd, bin) == 0)
108 /* Third approach: $PATH */
109 if ((pv = getenv("PATH")) == NULL)
114 while ((t = strsep(&s, ":")) != NULL) {
115 if (test_dir(ret, t, bin) == 0) {
123 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
125 /// GetMainExecutable - Return the path to the main executable, given the
126 /// value of argv[0] from program startup.
127 std::string getMainExecutable(const char *argv0, void *MainAddr) {
128 #if defined(__APPLE__)
129 // On OS X the executable path is saved to the stack by dyld. Reading it
130 // from there is much faster than calling dladdr, especially for large
131 // binaries with symbols.
132 char exe_path[MAXPATHLEN];
133 uint32_t size = sizeof(exe_path);
134 if (_NSGetExecutablePath(exe_path, &size) == 0) {
135 char link_path[MAXPATHLEN];
136 if (realpath(exe_path, link_path))
139 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
140 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
141 defined(__FreeBSD_kernel__)
142 char exe_path[PATH_MAX];
144 if (getprogpath(exe_path, argv0) != NULL)
146 #elif defined(__linux__) || defined(__CYGWIN__)
147 char exe_path[MAXPATHLEN];
148 StringRef aPath("/proc/self/exe");
149 if (sys::fs::exists(aPath)) {
150 // /proc is not always mounted under Linux (chroot for example).
151 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
153 return std::string(exe_path, len);
155 // Fall back to the classical detection.
156 if (getprogpath(exe_path, argv0) != NULL)
159 #elif defined(HAVE_DLFCN_H)
160 // Use dladdr to get executable path if available.
162 int err = dladdr(MainAddr, &DLInfo);
166 // If the filename is a symlink, we need to resolve and return the location of
167 // the actual executable.
168 char link_path[MAXPATHLEN];
169 if (realpath(DLInfo.dli_fname, link_path))
172 #error GetMainExecutable is not implemented on this host yet.
177 TimeValue file_status::getLastModificationTime() const {
179 Ret.fromEpochTime(fs_st_mtime);
183 UniqueID file_status::getUniqueID() const {
184 return UniqueID(fs_st_dev, fs_st_ino);
187 std::error_code current_path(SmallVectorImpl<char> &result) {
190 const char *pwd = ::getenv("PWD");
191 llvm::sys::fs::file_status PWDStatus, DotStatus;
192 if (pwd && llvm::sys::path::is_absolute(pwd) &&
193 !llvm::sys::fs::status(pwd, PWDStatus) &&
194 !llvm::sys::fs::status(".", DotStatus) &&
195 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
196 result.append(pwd, pwd + strlen(pwd));
197 return std::error_code();
201 result.reserve(MAXPATHLEN);
204 result.reserve(1024);
208 if (::getcwd(result.data(), result.capacity()) == nullptr) {
209 // See if there was a real error.
211 return std::error_code(errno, std::generic_category());
212 // Otherwise there just wasn't enough space.
213 result.reserve(result.capacity() * 2);
218 result.set_size(strlen(result.data()));
219 return std::error_code();
222 std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
223 SmallString<128> path_storage;
224 StringRef p = path.toNullTerminatedStringRef(path_storage);
226 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
227 if (errno != EEXIST || !IgnoreExisting)
228 return std::error_code(errno, std::generic_category());
231 return std::error_code();
234 // Note that we are using symbolic link because hard links are not supported by
235 // all filesystems (SMB doesn't).
236 std::error_code create_link(const Twine &to, const Twine &from) {
238 SmallString<128> from_storage;
239 SmallString<128> to_storage;
240 StringRef f = from.toNullTerminatedStringRef(from_storage);
241 StringRef t = to.toNullTerminatedStringRef(to_storage);
243 if (::symlink(t.begin(), f.begin()) == -1)
244 return std::error_code(errno, std::generic_category());
246 return std::error_code();
249 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
250 SmallString<128> path_storage;
251 StringRef p = path.toNullTerminatedStringRef(path_storage);
254 if (lstat(p.begin(), &buf) != 0) {
255 if (errno != ENOENT || !IgnoreNonExisting)
256 return std::error_code(errno, std::generic_category());
257 return std::error_code();
260 // Note: this check catches strange situations. In all cases, LLVM should
261 // only be involved in the creation and deletion of regular files. This
262 // check ensures that what we're trying to erase is a regular file. It
263 // effectively prevents LLVM from erasing things like /dev/null, any block
264 // special file, or other things that aren't "regular" files.
265 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
266 return make_error_code(errc::operation_not_permitted);
268 if (::remove(p.begin()) == -1) {
269 if (errno != ENOENT || !IgnoreNonExisting)
270 return std::error_code(errno, std::generic_category());
273 return std::error_code();
276 std::error_code rename(const Twine &from, const Twine &to) {
278 SmallString<128> from_storage;
279 SmallString<128> to_storage;
280 StringRef f = from.toNullTerminatedStringRef(from_storage);
281 StringRef t = to.toNullTerminatedStringRef(to_storage);
283 if (::rename(f.begin(), t.begin()) == -1)
284 return std::error_code(errno, std::generic_category());
286 return std::error_code();
289 std::error_code resize_file(int FD, uint64_t Size) {
290 if (::ftruncate(FD, Size) == -1)
291 return std::error_code(errno, std::generic_category());
293 return std::error_code();
296 static int convertAccessMode(AccessMode Mode) {
298 case AccessMode::Exist:
300 case AccessMode::Write:
302 case AccessMode::Execute:
303 return R_OK | X_OK; // scripts also need R_OK.
305 llvm_unreachable("invalid enum");
308 std::error_code access(const Twine &Path, AccessMode Mode) {
309 SmallString<128> PathStorage;
310 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
312 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
313 return std::error_code(errno, std::generic_category());
315 if (Mode == AccessMode::Execute) {
316 // Don't say that directories are executable.
318 if (0 != stat(P.begin(), &buf))
319 return errc::permission_denied;
320 if (!S_ISREG(buf.st_mode))
321 return errc::permission_denied;
324 return std::error_code();
327 bool equivalent(file_status A, file_status B) {
328 assert(status_known(A) && status_known(B));
329 return A.fs_st_dev == B.fs_st_dev &&
330 A.fs_st_ino == B.fs_st_ino;
333 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
334 file_status fsA, fsB;
335 if (std::error_code ec = status(A, fsA))
337 if (std::error_code ec = status(B, fsB))
339 result = equivalent(fsA, fsB);
340 return std::error_code();
343 static std::error_code fillStatus(int StatRet, const struct stat &Status,
344 file_status &Result) {
346 std::error_code ec(errno, std::generic_category());
347 if (ec == errc::no_such_file_or_directory)
348 Result = file_status(file_type::file_not_found);
350 Result = file_status(file_type::status_error);
354 file_type Type = file_type::type_unknown;
356 if (S_ISDIR(Status.st_mode))
357 Type = file_type::directory_file;
358 else if (S_ISREG(Status.st_mode))
359 Type = file_type::regular_file;
360 else if (S_ISBLK(Status.st_mode))
361 Type = file_type::block_file;
362 else if (S_ISCHR(Status.st_mode))
363 Type = file_type::character_file;
364 else if (S_ISFIFO(Status.st_mode))
365 Type = file_type::fifo_file;
366 else if (S_ISSOCK(Status.st_mode))
367 Type = file_type::socket_file;
369 perms Perms = static_cast<perms>(Status.st_mode);
371 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
372 Status.st_uid, Status.st_gid, Status.st_size);
374 return std::error_code();
377 std::error_code status(const Twine &Path, file_status &Result) {
378 SmallString<128> PathStorage;
379 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
382 int StatRet = ::stat(P.begin(), &Status);
383 return fillStatus(StatRet, Status, Result);
386 std::error_code status(int FD, file_status &Result) {
388 int StatRet = ::fstat(FD, &Status);
389 return fillStatus(StatRet, Status, Result);
392 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
393 #if defined(HAVE_FUTIMENS)
395 Times[0].tv_sec = Time.toEpochTime();
396 Times[0].tv_nsec = 0;
398 if (::futimens(FD, Times))
399 return std::error_code(errno, std::generic_category());
400 return std::error_code();
401 #elif defined(HAVE_FUTIMES)
403 Times[0].tv_sec = Time.toEpochTime();
404 Times[0].tv_usec = 0;
406 if (::futimes(FD, Times))
407 return std::error_code(errno, std::generic_category());
408 return std::error_code();
410 #warning Missing futimes() and futimens()
411 return make_error_code(errc::function_not_supported);
415 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
419 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
420 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
421 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
422 if (Mapping == MAP_FAILED)
423 return std::error_code(errno, std::generic_category());
424 return std::error_code();
427 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
428 uint64_t offset, std::error_code &ec)
429 : Size(length), Mapping() {
430 // Make sure that the requested size fits within SIZE_T.
431 if (length > std::numeric_limits<size_t>::max()) {
432 ec = make_error_code(errc::invalid_argument);
436 ec = init(fd, offset, mode);
441 mapped_file_region::~mapped_file_region() {
443 ::munmap(Mapping, Size);
446 uint64_t mapped_file_region::size() const {
447 assert(Mapping && "Mapping failed but used anyway!");
451 char *mapped_file_region::data() const {
452 assert(Mapping && "Mapping failed but used anyway!");
453 return reinterpret_cast<char*>(Mapping);
456 const char *mapped_file_region::const_data() const {
457 assert(Mapping && "Mapping failed but used anyway!");
458 return reinterpret_cast<const char*>(Mapping);
461 int mapped_file_region::alignment() {
462 return Process::getPageSize();
465 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
467 SmallString<128> path_null(path);
468 DIR *directory = ::opendir(path_null.c_str());
470 return std::error_code(errno, std::generic_category());
472 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
473 // Add something for replace_filename to replace.
474 path::append(path_null, ".");
475 it.CurrentEntry = directory_entry(path_null.str());
476 return directory_iterator_increment(it);
479 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
480 if (it.IterationHandle)
481 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
482 it.IterationHandle = 0;
483 it.CurrentEntry = directory_entry();
484 return std::error_code();
487 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
489 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
490 if (cur_dir == nullptr && errno != 0) {
491 return std::error_code(errno, std::generic_category());
492 } else if (cur_dir != nullptr) {
493 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
494 if ((name.size() == 1 && name[0] == '.') ||
495 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
496 return directory_iterator_increment(it);
497 it.CurrentEntry.replace_filename(name);
499 return directory_iterator_destruct(it);
501 return std::error_code();
504 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
505 SmallString<128> Storage;
506 StringRef P = Name.toNullTerminatedStringRef(Storage);
507 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
509 return std::error_code(errno, std::generic_category());
511 return std::error_code();
514 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
515 sys::fs::OpenFlags Flags, unsigned Mode) {
516 // Verify that we don't have both "append" and "excl".
517 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
518 "Cannot specify both 'excl' and 'append' file creation flags!");
520 int OpenFlags = O_CREAT;
525 OpenFlags |= O_WRONLY;
527 if (Flags & F_Append)
528 OpenFlags |= O_APPEND;
530 OpenFlags |= O_TRUNC;
535 SmallString<128> Storage;
536 StringRef P = Name.toNullTerminatedStringRef(Storage);
537 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
539 return std::error_code(errno, std::generic_category());
541 return std::error_code();
544 } // end namespace fs
548 bool home_directory(SmallVectorImpl<char> &result) {
549 if (char *RequestedDir = getenv("HOME")) {
551 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
558 static const char *getEnvTempDir() {
559 // Check whether the temporary directory is specified by an environment
561 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
562 for (const char *Env : EnvironmentVariables) {
563 if (const char *Dir = std::getenv(Env))
570 static const char *getDefaultTempDir(bool ErasedOnReboot) {
581 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
584 if (ErasedOnReboot) {
585 // There is no env variable for the cache directory.
586 if (const char *RequestedDir = getEnvTempDir()) {
587 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
592 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
593 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
594 // macros defined in <unistd.h> on darwin >= 9
595 int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
596 : _CS_DARWIN_USER_CACHE_DIR;
597 size_t ConfLen = confstr(ConfName, nullptr, 0);
600 Result.resize(ConfLen);
601 ConfLen = confstr(ConfName, Result.data(), Result.size());
602 } while (ConfLen > 0 && ConfLen != Result.size());
605 assert(Result.back() == 0);
614 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
615 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
618 } // end namespace path
620 } // end namespace sys
621 } // end namespace llvm