blob: e79abcb0fcbfec2de09f3e0cb39b3a4fb588210a [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +000010// This file implements the Unix specific implementation of the Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000011//
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 "Unix.h"
Reid Kleckner37f69de2013-07-26 16:54:23 +000020#include <limits.h>
21#include <stdio.h>
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000022#if HAVE_SYS_STAT_H
23#include <sys/stat.h>
24#endif
25#if HAVE_FCNTL_H
26#include <fcntl.h>
27#endif
Nick Kledzik18497e92012-06-20 00:28:54 +000028#ifdef HAVE_SYS_MMAN_H
29#include <sys/mman.h>
30#endif
Michael J. Spencer52714862011-01-05 16:38:57 +000031#if HAVE_DIRENT_H
32# include <dirent.h>
33# define NAMLEN(dirent) strlen((dirent)->d_name)
34#else
35# define dirent direct
36# define NAMLEN(dirent) (dirent)->d_namlen
37# if HAVE_SYS_NDIR_H
38# include <sys/ndir.h>
39# endif
40# if HAVE_SYS_DIR_H
41# include <sys/dir.h>
42# endif
43# if HAVE_NDIR_H
44# include <ndir.h>
45# endif
46#endif
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000047
Rafael Espindola4601c462013-06-26 05:25:44 +000048#ifdef __APPLE__
49#include <mach-o/dyld.h>
50#endif
51
Joerg Sonnenbergerc0697302012-08-10 10:56:09 +000052// 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
54// either.
55#undef ferror
56#undef feof
57
Sylvestre Ledru14ada942012-04-11 15:35:36 +000058// For GNU Hurd
59#if defined(__GNU__) && !defined(PATH_MAX)
60# define PATH_MAX 4096
61#endif
62
Michael J. Spencer45710402010-12-03 01:21:28 +000063using namespace llvm;
64
Michael J. Spencerebad2f92010-11-29 22:28:51 +000065namespace llvm {
66namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +000067namespace fs {
Rafael Espindolae03dfd92013-06-26 05:01:35 +000068#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
69 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +000070 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +000071static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +000072test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
73{
Rafael Espindolae03dfd92013-06-26 05:01:35 +000074 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +000075 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +000076
Sylvestre Ledru21e674722013-12-09 16:27:00 +000077 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
Hans Wennborg083ca9b2015-10-06 23:24:35 +000078 if (!realpath(fullpath, ret))
79 return 1;
Sylvestre Ledru21e674722013-12-09 16:27:00 +000080 if (stat(fullpath, &sb) != 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +000081 return 1;
Rafael Espindolae03dfd92013-06-26 05:01:35 +000082
Hans Wennborg083ca9b2015-10-06 23:24:35 +000083 return 0;
Rafael Espindolae03dfd92013-06-26 05:01:35 +000084}
85
86static char *
87getprogpath(char ret[PATH_MAX], const char *bin)
88{
Sylvestre Ledru21e674722013-12-09 16:27:00 +000089 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +000090
91 /* First approach: absolute path. */
92 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +000093 if (test_dir(ret, "/", bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +000094 return ret;
95 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +000096 }
97
98 /* Second approach: relative path. */
Hans Wennborg083ca9b2015-10-06 23:24:35 +000099 if (strchr(bin, '/')) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000100 char cwd[PATH_MAX];
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000101 if (!getcwd(cwd, PATH_MAX))
102 return nullptr;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000103 if (test_dir(ret, cwd, bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000104 return ret;
105 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000106 }
107
108 /* Third approach: $PATH */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000109 if ((pv = getenv("PATH")) == nullptr)
110 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000111 s = pv = strdup(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000112 if (!pv)
113 return nullptr;
114 while ((t = strsep(&s, ":")) != nullptr) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000115 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000116 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000117 return ret;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000118 }
119 }
120 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000121 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000122}
123#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
124
125/// GetMainExecutable - Return the path to the main executable, given the
126/// value of argv[0] from program startup.
127std::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))
Rafael Espindola4601c462013-06-26 05:25:44 +0000137 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000138 }
139#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000140 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
141 defined(__FreeBSD_kernel__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000142 char exe_path[PATH_MAX];
143
144 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000145 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000146#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));
152 if (len >= 0)
Alexey Samsonov4c798452014-12-29 20:59:02 +0000153 return std::string(exe_path, len);
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000154 } else {
155 // Fall back to the classical detection.
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000156 if (getprogpath(exe_path, argv0))
157 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000158 }
159#elif defined(HAVE_DLFCN_H)
160 // Use dladdr to get executable path if available.
161 Dl_info DLInfo;
162 int err = dladdr(MainAddr, &DLInfo);
163 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000164 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000165
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))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000170 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000171#else
172#error GetMainExecutable is not implemented on this host yet.
173#endif
174 return "";
175}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000176
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000177TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000178 TimeValue Ret;
179 Ret.fromEpochTime(fs_st_mtime);
180 return Ret;
181}
182
Rafael Espindolad1230992013-07-29 21:55:38 +0000183UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000184 return UniqueID(fs_st_dev, fs_st_ino);
185}
186
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000187std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000188 result.clear();
189
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));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000197 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000198 }
199
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000200#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000201 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000202#else
203// For GNU Hurd
204 result.reserve(1024);
205#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000206
Michael J. Spencer20daa282010-12-07 01:22:31 +0000207 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000208 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000209 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000210 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000211 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000212 // Otherwise there just wasn't enough space.
213 result.reserve(result.capacity() * 2);
214 } else
215 break;
216 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000217
218 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000219 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000220}
221
Frederic Riss6b9396c2015-08-06 21:04:55 +0000222std::error_code create_directory(const Twine &path, bool IgnoreExisting,
223 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000224 SmallString<128> path_storage;
225 StringRef p = path.toNullTerminatedStringRef(path_storage);
226
Frederic Riss6b9396c2015-08-06 21:04:55 +0000227 if (::mkdir(p.begin(), Perms) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000228 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000229 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000230 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000231
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000232 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000233}
234
Rafael Espindola83f858e2014-03-11 18:40:24 +0000235// Note that we are using symbolic link because hard links are not supported by
236// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000237std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000238 // Get arguments.
239 SmallString<128> from_storage;
240 SmallString<128> to_storage;
241 StringRef f = from.toNullTerminatedStringRef(from_storage);
242 StringRef t = to.toNullTerminatedStringRef(to_storage);
243
Rafael Espindola83f858e2014-03-11 18:40:24 +0000244 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000245 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000246
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000247 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000248}
249
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000250std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000251 SmallString<128> path_storage;
252 StringRef p = path.toNullTerminatedStringRef(path_storage);
253
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000254 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000255 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000256 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000257 return std::error_code(errno, std::generic_category());
258 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000259 }
260
261 // Note: this check catches strange situations. In all cases, LLVM should
262 // only be involved in the creation and deletion of regular files. This
263 // check ensures that what we're trying to erase is a regular file. It
264 // effectively prevents LLVM from erasing things like /dev/null, any block
265 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000266 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000267 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000268
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000269 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000270 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000271 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000272 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000273
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000274 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000275}
276
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000277std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000278 // Get arguments.
279 SmallString<128> from_storage;
280 SmallString<128> to_storage;
281 StringRef f = from.toNullTerminatedStringRef(from_storage);
282 StringRef t = to.toNullTerminatedStringRef(to_storage);
283
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000284 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000285 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000286
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000287 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000288}
289
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000290std::error_code resize_file(int FD, uint64_t Size) {
291 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000292 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000293
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000294 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000295}
296
Rafael Espindola281f23a2014-09-11 20:30:02 +0000297static int convertAccessMode(AccessMode Mode) {
298 switch (Mode) {
299 case AccessMode::Exist:
300 return F_OK;
301 case AccessMode::Write:
302 return W_OK;
303 case AccessMode::Execute:
304 return R_OK | X_OK; // scripts also need R_OK.
305 }
306 llvm_unreachable("invalid enum");
307}
Michael J. Spencer45710402010-12-03 01:21:28 +0000308
Rafael Espindola281f23a2014-09-11 20:30:02 +0000309std::error_code access(const Twine &Path, AccessMode Mode) {
310 SmallString<128> PathStorage;
311 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
312
313 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
314 return std::error_code(errno, std::generic_category());
315
316 if (Mode == AccessMode::Execute) {
317 // Don't say that directories are executable.
318 struct stat buf;
319 if (0 != stat(P.begin(), &buf))
320 return errc::permission_denied;
321 if (!S_ISREG(buf.st_mode))
322 return errc::permission_denied;
323 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000324
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000325 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000326}
327
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000328bool can_execute(const Twine &Path) {
329 return !access(Path, AccessMode::Execute);
330}
331
Michael J. Spencer203d7802011-12-12 06:04:28 +0000332bool equivalent(file_status A, file_status B) {
333 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000334 return A.fs_st_dev == B.fs_st_dev &&
335 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000336}
337
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000338std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000339 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000340 if (std::error_code ec = status(A, fsA))
341 return ec;
342 if (std::error_code ec = status(B, fsB))
343 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000344 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000345 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000346}
347
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000348static std::error_code fillStatus(int StatRet, const struct stat &Status,
Rafael Espindola77021c92013-07-16 03:20:13 +0000349 file_status &Result) {
350 if (StatRet != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000351 std::error_code ec(errno, std::generic_category());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000352 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000353 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000354 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000355 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000356 return ec;
357 }
358
Rafael Espindola9da91a02013-07-16 02:55:33 +0000359 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000360
Rafael Espindola77021c92013-07-16 03:20:13 +0000361 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000362 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000363 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000364 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000365 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000366 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000367 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000368 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000369 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000370 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000371 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000372 Type = file_type::socket_file;
373
Rafael Espindola77021c92013-07-16 03:20:13 +0000374 perms Perms = static_cast<perms>(Status.st_mode);
375 Result =
376 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
377 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000378
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000379 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000380}
381
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000382std::error_code status(const Twine &Path, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000383 SmallString<128> PathStorage;
384 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
385
386 struct stat Status;
387 int StatRet = ::stat(P.begin(), &Status);
388 return fillStatus(StatRet, Status, Result);
389}
390
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000391std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000392 struct stat Status;
393 int StatRet = ::fstat(FD, &Status);
394 return fillStatus(StatRet, Status, Result);
395}
396
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000397std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000398#if defined(HAVE_FUTIMENS)
399 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000400 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000401 Times[0].tv_nsec = 0;
402 Times[1] = Times[0];
403 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000404 return std::error_code(errno, std::generic_category());
405 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000406#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000407 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000408 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000409 Times[0].tv_usec = 0;
410 Times[1] = Times[0];
411 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000412 return std::error_code(errno, std::generic_category());
413 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000414#else
415#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000416 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000417#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000418}
419
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000420std::error_code mapped_file_region::init(int FD, uint64_t Offset,
421 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000422 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000423
424 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
425 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Craig Toppere73658d2014-04-28 04:05:08 +0000426 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000427 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000428 return std::error_code(errno, std::generic_category());
429 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000430}
431
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000432mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
433 uint64_t offset, std::error_code &ec)
434 : Size(length), Mapping() {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000435 // Make sure that the requested size fits within SIZE_T.
436 if (length > std::numeric_limits<size_t>::max()) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000437 ec = make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000438 return;
439 }
440
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000441 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000442 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000443 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000444}
445
446mapped_file_region::~mapped_file_region() {
447 if (Mapping)
448 ::munmap(Mapping, Size);
449}
450
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000451uint64_t mapped_file_region::size() const {
452 assert(Mapping && "Mapping failed but used anyway!");
453 return Size;
454}
455
456char *mapped_file_region::data() const {
457 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000458 return reinterpret_cast<char*>(Mapping);
459}
460
461const char *mapped_file_region::const_data() const {
462 assert(Mapping && "Mapping failed but used anyway!");
463 return reinterpret_cast<const char*>(Mapping);
464}
465
466int mapped_file_region::alignment() {
Rafael Espindolac0610bf2014-12-04 16:59:36 +0000467 return Process::getPageSize();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000468}
469
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000470std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000471 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000472 SmallString<128> path_null(path);
473 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000474 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000475 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000476
477 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
478 // Add something for replace_filename to replace.
479 path::append(path_null, ".");
480 it.CurrentEntry = directory_entry(path_null.str());
481 return directory_iterator_increment(it);
482}
483
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000484std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000485 if (it.IterationHandle)
486 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
487 it.IterationHandle = 0;
488 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000489 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000490}
491
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000492std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000493 errno = 0;
494 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
Craig Toppere73658d2014-04-28 04:05:08 +0000495 if (cur_dir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000496 return std::error_code(errno, std::generic_category());
Craig Toppere73658d2014-04-28 04:05:08 +0000497 } else if (cur_dir != nullptr) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000498 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
499 if ((name.size() == 1 && name[0] == '.') ||
500 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
501 return directory_iterator_increment(it);
502 it.CurrentEntry.replace_filename(name);
503 } else
504 return directory_iterator_destruct(it);
505
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000506 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000507}
508
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000509std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000510 SmallString<128> Storage;
511 StringRef P = Name.toNullTerminatedStringRef(Storage);
512 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
513 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000514 return std::error_code(errno, std::generic_category());
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000515 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000516 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000517}
Nick Kledzik18497e92012-06-20 00:28:54 +0000518
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000519std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000520 sys::fs::OpenFlags Flags, unsigned Mode) {
521 // Verify that we don't have both "append" and "excl".
522 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
523 "Cannot specify both 'excl' and 'append' file creation flags!");
524
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000525 int OpenFlags = O_CREAT;
526
527 if (Flags & F_RW)
528 OpenFlags |= O_RDWR;
529 else
530 OpenFlags |= O_WRONLY;
Rafael Espindola67080ce2013-07-19 15:02:03 +0000531
532 if (Flags & F_Append)
533 OpenFlags |= O_APPEND;
534 else
535 OpenFlags |= O_TRUNC;
536
537 if (Flags & F_Excl)
538 OpenFlags |= O_EXCL;
539
540 SmallString<128> Storage;
541 StringRef P = Name.toNullTerminatedStringRef(Storage);
542 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
543 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000544 return std::error_code(errno, std::generic_category());
Rafael Espindola67080ce2013-07-19 15:02:03 +0000545 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000546 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000547}
548
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000549} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000550
551namespace path {
552
553bool home_directory(SmallVectorImpl<char> &result) {
554 if (char *RequestedDir = getenv("HOME")) {
555 result.clear();
556 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
557 return true;
558 }
559
560 return false;
561}
562
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000563namespace {
564bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
565 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
566 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
567 // macros defined in <unistd.h> on darwin >= 9
568 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
569 : _CS_DARWIN_USER_CACHE_DIR;
570 size_t ConfLen = confstr(ConfName, nullptr, 0);
571 if (ConfLen > 0) {
572 do {
573 Result.resize(ConfLen);
574 ConfLen = confstr(ConfName, Result.data(), Result.size());
575 } while (ConfLen > 0 && ConfLen != Result.size());
576
577 if (ConfLen > 0) {
578 assert(Result.back() == 0);
579 Result.pop_back();
580 return true;
581 }
582
583 Result.clear();
584 }
585 #endif
586 return false;
587}
588
589bool getUserCacheDir(SmallVectorImpl<char> &Result) {
590 // First try using XDS_CACHE_HOME env variable,
591 // as specified in XDG Base Directory Specification at
592 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
593 if (const char *XdsCacheDir = std::getenv("XDS_CACHE_HOME")) {
594 Result.clear();
595 Result.append(XdsCacheDir, XdsCacheDir + strlen(XdsCacheDir));
596 return true;
597 }
598
599 // Try Darwin configuration query
600 if (getDarwinConfDir(false, Result))
601 return true;
602
603 // Use "$HOME/.cache" if $HOME is available
604 if (home_directory(Result)) {
605 append(Result, ".cache");
606 return true;
607 }
608
609 return false;
610}
611}
612
613
Rafael Espindola016a6d52014-08-26 14:47:52 +0000614static const char *getEnvTempDir() {
615 // Check whether the temporary directory is specified by an environment
616 // variable.
617 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
618 for (const char *Env : EnvironmentVariables) {
619 if (const char *Dir = std::getenv(Env))
620 return Dir;
621 }
622
623 return nullptr;
624}
625
626static const char *getDefaultTempDir(bool ErasedOnReboot) {
627#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +0000628 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +0000629 return P_tmpdir;
630#endif
631
632 if (ErasedOnReboot)
633 return "/tmp";
634 return "/var/tmp";
635}
636
637void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
638 Result.clear();
639
640 if (ErasedOnReboot) {
641 // There is no env variable for the cache directory.
642 if (const char *RequestedDir = getEnvTempDir()) {
643 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
644 return;
645 }
646 }
647
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000648 if (getDarwinConfDir(ErasedOnReboot, Result))
649 return;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000650
651 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
652 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
653}
654
Peter Collingbournef7d41012014-01-31 23:46:06 +0000655} // end namespace path
656
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000657} // end namespace sys
658} // end namespace llvm