blob: 24b0e21ce0ad4f0ffd16203db048b0c3cc06dfde [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. Spencer9fc1d9d2010-12-01 19:32:01 +000065namespace {
Michael J. Spencer5529c572010-12-07 01:23:08 +000066 /// This class automatically closes the given file descriptor when it goes out
67 /// of scope. You can take back explicit ownership of the file descriptor by
68 /// calling take(). The destructor does not verify that close was successful.
69 /// Therefore, never allow this class to call close on a file descriptor that
70 /// has been read from or written to.
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000071 struct AutoFD {
72 int FileDescriptor;
73
74 AutoFD(int fd) : FileDescriptor(fd) {}
75 ~AutoFD() {
76 if (FileDescriptor >= 0)
77 ::close(FileDescriptor);
78 }
79
80 int take() {
81 int ret = FileDescriptor;
82 FileDescriptor = -1;
83 return ret;
84 }
85
86 operator int() const {return FileDescriptor;}
87 };
Rafael Espindola37b012d2014-02-23 15:16:03 +000088}
Michael J. Spencer45710402010-12-03 01:21:28 +000089
Michael J. Spencerebad2f92010-11-29 22:28:51 +000090namespace llvm {
91namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +000092namespace fs {
Rafael Espindolae03dfd92013-06-26 05:01:35 +000093#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
94 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +000095 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +000096static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +000097test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
98{
Rafael Espindolae03dfd92013-06-26 05:01:35 +000099 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000100 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000101
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000102 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
103 if (realpath(fullpath, ret) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000104 return (1);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000105 if (stat(fullpath, &sb) != 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000106 return (1);
107
108 return (0);
109}
110
111static char *
112getprogpath(char ret[PATH_MAX], const char *bin)
113{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000114 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000115
116 /* First approach: absolute path. */
117 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000118 if (test_dir(ret, "/", bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000119 return (ret);
120 return (NULL);
121 }
122
123 /* Second approach: relative path. */
124 if (strchr(bin, '/') != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000125 char cwd[PATH_MAX];
126 if (getcwd(cwd, PATH_MAX) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000127 return (NULL);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000128 if (test_dir(ret, cwd, bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000129 return (ret);
130 return (NULL);
131 }
132
133 /* Third approach: $PATH */
134 if ((pv = getenv("PATH")) == NULL)
135 return (NULL);
136 s = pv = strdup(pv);
137 if (pv == NULL)
138 return (NULL);
139 while ((t = strsep(&s, ":")) != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000140 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000141 free(pv);
142 return (ret);
143 }
144 }
145 free(pv);
146 return (NULL);
147}
148#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
149
150/// GetMainExecutable - Return the path to the main executable, given the
151/// value of argv[0] from program startup.
152std::string getMainExecutable(const char *argv0, void *MainAddr) {
153#if defined(__APPLE__)
154 // On OS X the executable path is saved to the stack by dyld. Reading it
155 // from there is much faster than calling dladdr, especially for large
156 // binaries with symbols.
157 char exe_path[MAXPATHLEN];
158 uint32_t size = sizeof(exe_path);
159 if (_NSGetExecutablePath(exe_path, &size) == 0) {
160 char link_path[MAXPATHLEN];
161 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000162 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000163 }
164#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000165 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
166 defined(__FreeBSD_kernel__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000167 char exe_path[PATH_MAX];
168
169 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000170 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000171#elif defined(__linux__) || defined(__CYGWIN__)
172 char exe_path[MAXPATHLEN];
173 StringRef aPath("/proc/self/exe");
174 if (sys::fs::exists(aPath)) {
175 // /proc is not always mounted under Linux (chroot for example).
176 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
177 if (len >= 0)
178 return StringRef(exe_path, len);
179 } else {
180 // Fall back to the classical detection.
181 if (getprogpath(exe_path, argv0) != NULL)
182 return exe_path;
183 }
184#elif defined(HAVE_DLFCN_H)
185 // Use dladdr to get executable path if available.
186 Dl_info DLInfo;
187 int err = dladdr(MainAddr, &DLInfo);
188 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000189 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000190
191 // If the filename is a symlink, we need to resolve and return the location of
192 // the actual executable.
193 char link_path[MAXPATHLEN];
194 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000195 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000196#else
197#error GetMainExecutable is not implemented on this host yet.
198#endif
199 return "";
200}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000201
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000202TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000203 TimeValue Ret;
204 Ret.fromEpochTime(fs_st_mtime);
205 return Ret;
206}
207
Rafael Espindolad1230992013-07-29 21:55:38 +0000208UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000209 return UniqueID(fs_st_dev, fs_st_ino);
210}
211
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000212std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000213 result.clear();
214
215 const char *pwd = ::getenv("PWD");
216 llvm::sys::fs::file_status PWDStatus, DotStatus;
217 if (pwd && llvm::sys::path::is_absolute(pwd) &&
218 !llvm::sys::fs::status(pwd, PWDStatus) &&
219 !llvm::sys::fs::status(".", DotStatus) &&
220 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
221 result.append(pwd, pwd + strlen(pwd));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000222 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000223 }
224
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000225#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000226 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000227#else
228// For GNU Hurd
229 result.reserve(1024);
230#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000231
Michael J. Spencer20daa282010-12-07 01:22:31 +0000232 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000233 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000234 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000235 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000236 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000237 // Otherwise there just wasn't enough space.
238 result.reserve(result.capacity() * 2);
239 } else
240 break;
241 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000242
243 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000244 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000245}
246
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000247std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000248 SmallString<128> path_storage;
249 StringRef p = path.toNullTerminatedStringRef(path_storage);
250
Michael J. Spencere5755be2010-12-07 01:23:29 +0000251 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000252 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000253 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000254 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000255
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000256 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000257}
258
Rafael Espindola83f858e2014-03-11 18:40:24 +0000259// Note that we are using symbolic link because hard links are not supported by
260// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000261std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000262 // Get arguments.
263 SmallString<128> from_storage;
264 SmallString<128> to_storage;
265 StringRef f = from.toNullTerminatedStringRef(from_storage);
266 StringRef t = to.toNullTerminatedStringRef(to_storage);
267
Rafael Espindola83f858e2014-03-11 18:40:24 +0000268 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000269 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000270
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000271 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000272}
273
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000274std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000275 SmallString<128> path_storage;
276 StringRef p = path.toNullTerminatedStringRef(path_storage);
277
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000278 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000279 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000280 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000281 return std::error_code(errno, std::generic_category());
282 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000283 }
284
285 // Note: this check catches strange situations. In all cases, LLVM should
286 // only be involved in the creation and deletion of regular files. This
287 // check ensures that what we're trying to erase is a regular file. It
288 // effectively prevents LLVM from erasing things like /dev/null, any block
289 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000290 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000291 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000292
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000293 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000294 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000295 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000296 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000297
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000298 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000299}
300
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000301std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000302 // Get arguments.
303 SmallString<128> from_storage;
304 SmallString<128> to_storage;
305 StringRef f = from.toNullTerminatedStringRef(from_storage);
306 StringRef t = to.toNullTerminatedStringRef(to_storage);
307
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000308 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000309 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000310
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000311 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000312}
313
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000314std::error_code resize_file(const Twine &path, uint64_t size) {
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000315 SmallString<128> path_storage;
316 StringRef p = path.toNullTerminatedStringRef(path_storage);
317
318 if (::truncate(p.begin(), size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000319 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000320
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000321 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000322}
323
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000324std::error_code exists(const Twine &path, bool &result) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000325 SmallString<128> path_storage;
326 StringRef p = path.toNullTerminatedStringRef(path_storage);
327
Benjamin Kramer172f8082012-06-02 16:28:09 +0000328 if (::access(p.begin(), F_OK) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000329 if (errno != ENOENT)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000330 return std::error_code(errno, std::generic_category());
Michael J. Spencer45710402010-12-03 01:21:28 +0000331 result = false;
332 } else
333 result = true;
334
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000335 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000336}
337
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000338bool can_write(const Twine &Path) {
339 SmallString<128> PathStorage;
340 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
341 return 0 == access(P.begin(), W_OK);
342}
343
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000344bool can_execute(const Twine &Path) {
345 SmallString<128> PathStorage;
346 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
347
Manuel Klimek52772bf2013-06-17 10:48:34 +0000348 if (0 != access(P.begin(), R_OK | X_OK))
349 return false;
350 struct stat buf;
351 if (0 != stat(P.begin(), &buf))
352 return false;
353 if (!S_ISREG(buf.st_mode))
354 return false;
355 return true;
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000356}
357
Michael J. Spencer203d7802011-12-12 06:04:28 +0000358bool equivalent(file_status A, file_status B) {
359 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000360 return A.fs_st_dev == B.fs_st_dev &&
361 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000362}
363
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000364std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000365 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000366 if (std::error_code ec = status(A, fsA))
367 return ec;
368 if (std::error_code ec = status(B, fsB))
369 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000370 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000371 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000372}
373
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000374static std::error_code fillStatus(int StatRet, const struct stat &Status,
Rafael Espindola77021c92013-07-16 03:20:13 +0000375 file_status &Result) {
376 if (StatRet != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000377 std::error_code ec(errno, std::generic_category());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000378 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000379 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000380 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000381 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000382 return ec;
383 }
384
Rafael Espindola9da91a02013-07-16 02:55:33 +0000385 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000386
Rafael Espindola77021c92013-07-16 03:20:13 +0000387 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000388 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000389 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000390 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000391 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000392 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000393 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000394 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000395 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000396 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000397 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000398 Type = file_type::socket_file;
399
Rafael Espindola77021c92013-07-16 03:20:13 +0000400 perms Perms = static_cast<perms>(Status.st_mode);
401 Result =
402 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
403 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000404
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000405 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000406}
407
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000408std::error_code status(const Twine &Path, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000409 SmallString<128> PathStorage;
410 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
411
412 struct stat Status;
413 int StatRet = ::stat(P.begin(), &Status);
414 return fillStatus(StatRet, Status, Result);
415}
416
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000417std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000418 struct stat Status;
419 int StatRet = ::fstat(FD, &Status);
420 return fillStatus(StatRet, Status, Result);
421}
422
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000423std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000424#if defined(HAVE_FUTIMENS)
425 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000426 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000427 Times[0].tv_nsec = 0;
428 Times[1] = Times[0];
429 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000430 return std::error_code(errno, std::generic_category());
431 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000432#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000433 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000434 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000435 Times[0].tv_usec = 0;
436 Times[1] = Times[0];
437 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000438 return std::error_code(errno, std::generic_category());
439 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000440#else
441#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000442 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000443#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000444}
445
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000446std::error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000447 AutoFD ScopedFD(FD);
448 if (!CloseFD)
449 ScopedFD.take();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000450
451 // Figure out how large the file is.
452 struct stat FileInfo;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000453 if (fstat(FD, &FileInfo) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000454 return std::error_code(errno, std::generic_category());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000455 uint64_t FileSize = FileInfo.st_size;
456
457 if (Size == 0)
458 Size = FileSize;
459 else if (FileSize < Size) {
460 // We need to grow the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000461 if (ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000462 return std::error_code(errno, std::generic_category());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000463 }
464
465 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
466 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
467#ifdef MAP_FILE
468 flags |= MAP_FILE;
469#endif
Craig Toppere73658d2014-04-28 04:05:08 +0000470 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000471 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000472 return std::error_code(errno, std::generic_category());
473 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000474}
475
476mapped_file_region::mapped_file_region(const Twine &path,
477 mapmode mode,
478 uint64_t length,
479 uint64_t offset,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000480 std::error_code &ec)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000481 : Mode(mode)
482 , Size(length)
483 , Mapping() {
484 // Make sure that the requested size fits within SIZE_T.
485 if (length > std::numeric_limits<size_t>::max()) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000486 ec = make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000487 return;
488 }
489
490 SmallString<128> path_storage;
491 StringRef name = path.toNullTerminatedStringRef(path_storage);
492 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
493 int ofd = ::open(name.begin(), oflags);
494 if (ofd == -1) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000495 ec = std::error_code(errno, std::generic_category());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000496 return;
497 }
498
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000499 ec = init(ofd, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000500 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000501 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000502}
503
504mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000505 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000506 mapmode mode,
507 uint64_t length,
508 uint64_t offset,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000509 std::error_code &ec)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000510 : Mode(mode)
511 , Size(length)
512 , Mapping() {
513 // Make sure that the requested size fits within SIZE_T.
514 if (length > std::numeric_limits<size_t>::max()) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000515 ec = make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000516 return;
517 }
518
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000519 ec = init(fd, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000520 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000521 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000522}
523
524mapped_file_region::~mapped_file_region() {
525 if (Mapping)
526 ::munmap(Mapping, Size);
527}
528
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000529mapped_file_region::mapped_file_region(mapped_file_region &&other)
530 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
Craig Toppere73658d2014-04-28 04:05:08 +0000531 other.Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000532}
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000533
534mapped_file_region::mapmode mapped_file_region::flags() const {
535 assert(Mapping && "Mapping failed but used anyway!");
536 return Mode;
537}
538
539uint64_t mapped_file_region::size() const {
540 assert(Mapping && "Mapping failed but used anyway!");
541 return Size;
542}
543
544char *mapped_file_region::data() const {
545 assert(Mapping && "Mapping failed but used anyway!");
Alp Tokerf907b892013-12-05 05:44:44 +0000546 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000547 return reinterpret_cast<char*>(Mapping);
548}
549
550const char *mapped_file_region::const_data() const {
551 assert(Mapping && "Mapping failed but used anyway!");
552 return reinterpret_cast<const char*>(Mapping);
553}
554
555int mapped_file_region::alignment() {
Chandler Carruthacd64be2012-12-31 23:31:56 +0000556 return process::get_self()->page_size();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000557}
558
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000559std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000560 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000561 SmallString<128> path_null(path);
562 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000563 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000564 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000565
566 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
567 // Add something for replace_filename to replace.
568 path::append(path_null, ".");
569 it.CurrentEntry = directory_entry(path_null.str());
570 return directory_iterator_increment(it);
571}
572
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000573std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000574 if (it.IterationHandle)
575 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
576 it.IterationHandle = 0;
577 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000578 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000579}
580
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000581std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000582 errno = 0;
583 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
Craig Toppere73658d2014-04-28 04:05:08 +0000584 if (cur_dir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000585 return std::error_code(errno, std::generic_category());
Craig Toppere73658d2014-04-28 04:05:08 +0000586 } else if (cur_dir != nullptr) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000587 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
588 if ((name.size() == 1 && name[0] == '.') ||
589 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
590 return directory_iterator_increment(it);
591 it.CurrentEntry.replace_filename(name);
592 } else
593 return directory_iterator_destruct(it);
594
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000595 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000596}
597
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000598std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000599 SmallString<128> Storage;
600 StringRef P = Name.toNullTerminatedStringRef(Storage);
601 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
602 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000603 return std::error_code(errno, std::generic_category());
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000604 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000605 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000606}
Nick Kledzik18497e92012-06-20 00:28:54 +0000607
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000608std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000609 sys::fs::OpenFlags Flags, unsigned Mode) {
610 // Verify that we don't have both "append" and "excl".
611 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
612 "Cannot specify both 'excl' and 'append' file creation flags!");
613
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000614 int OpenFlags = O_CREAT;
615
616 if (Flags & F_RW)
617 OpenFlags |= O_RDWR;
618 else
619 OpenFlags |= O_WRONLY;
Rafael Espindola67080ce2013-07-19 15:02:03 +0000620
621 if (Flags & F_Append)
622 OpenFlags |= O_APPEND;
623 else
624 OpenFlags |= O_TRUNC;
625
626 if (Flags & F_Excl)
627 OpenFlags |= O_EXCL;
628
629 SmallString<128> Storage;
630 StringRef P = Name.toNullTerminatedStringRef(Storage);
631 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
632 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000633 return std::error_code(errno, std::generic_category());
Rafael Espindola67080ce2013-07-19 15:02:03 +0000634 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000635 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000636}
637
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000638} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000639
640namespace path {
641
642bool home_directory(SmallVectorImpl<char> &result) {
643 if (char *RequestedDir = getenv("HOME")) {
644 result.clear();
645 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
646 return true;
647 }
648
649 return false;
650}
651
Rafael Espindola016a6d52014-08-26 14:47:52 +0000652static const char *getEnvTempDir() {
653 // Check whether the temporary directory is specified by an environment
654 // variable.
655 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
656 for (const char *Env : EnvironmentVariables) {
657 if (const char *Dir = std::getenv(Env))
658 return Dir;
659 }
660
661 return nullptr;
662}
663
664static const char *getDefaultTempDir(bool ErasedOnReboot) {
665#ifdef P_tmpdir
666 if (P_tmpdir)
667 return P_tmpdir;
668#endif
669
670 if (ErasedOnReboot)
671 return "/tmp";
672 return "/var/tmp";
673}
674
675void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
676 Result.clear();
677
678 if (ErasedOnReboot) {
679 // There is no env variable for the cache directory.
680 if (const char *RequestedDir = getEnvTempDir()) {
681 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
682 return;
683 }
684 }
685
686#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
687 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
688 // macros defined in <unistd.h> on darwin >= 9
689 int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
690 : _CS_DARWIN_USER_CACHE_DIR;
691 size_t ConfLen = confstr(ConfName, nullptr, 0);
692 if (ConfLen > 0) {
693 do {
694 Result.resize(ConfLen);
695 ConfLen = confstr(ConfName, Result.data(), Result.size());
696 } while (ConfLen > 0 && ConfLen != Result.size());
697
698 if (ConfLen > 0) {
699 assert(Result.back() == 0);
700 Result.pop_back();
701 return;
702 }
703
704 Result.clear();
705 }
706#endif
707
708 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
709 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
710}
711
Peter Collingbournef7d41012014-01-31 23:46:06 +0000712} // end namespace path
713
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000714} // end namespace sys
715} // end namespace llvm