blob: a77efcca8f56aef1f62730717899a98630d9442a [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);
78 if (realpath(fullpath, ret) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +000079 return (1);
Sylvestre Ledru21e674722013-12-09 16:27:00 +000080 if (stat(fullpath, &sb) != 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +000081 return (1);
82
83 return (0);
84}
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)
Rafael Espindolae03dfd92013-06-26 05:01:35 +000094 return (ret);
95 return (NULL);
96 }
97
98 /* Second approach: relative path. */
99 if (strchr(bin, '/') != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000100 char cwd[PATH_MAX];
101 if (getcwd(cwd, PATH_MAX) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000102 return (NULL);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000103 if (test_dir(ret, cwd, bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000104 return (ret);
105 return (NULL);
106 }
107
108 /* Third approach: $PATH */
109 if ((pv = getenv("PATH")) == NULL)
110 return (NULL);
111 s = pv = strdup(pv);
112 if (pv == NULL)
113 return (NULL);
114 while ((t = strsep(&s, ":")) != NULL) {
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);
117 return (ret);
118 }
119 }
120 free(pv);
121 return (NULL);
122}
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.
156 if (getprogpath(exe_path, argv0) != NULL)
157 return exe_path;
158 }
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
Michael J. Spencer203d7802011-12-12 06:04:28 +0000328bool equivalent(file_status A, file_status B) {
329 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000330 return A.fs_st_dev == B.fs_st_dev &&
331 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000332}
333
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000334std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000335 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000336 if (std::error_code ec = status(A, fsA))
337 return ec;
338 if (std::error_code ec = status(B, fsB))
339 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000340 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000341 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000342}
343
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000344static std::error_code fillStatus(int StatRet, const struct stat &Status,
Rafael Espindola77021c92013-07-16 03:20:13 +0000345 file_status &Result) {
346 if (StatRet != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000347 std::error_code ec(errno, std::generic_category());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000348 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000349 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000350 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000351 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000352 return ec;
353 }
354
Rafael Espindola9da91a02013-07-16 02:55:33 +0000355 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000356
Rafael Espindola77021c92013-07-16 03:20:13 +0000357 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000358 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000359 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000360 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000361 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000362 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000363 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000364 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000365 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000366 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000367 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000368 Type = file_type::socket_file;
369
Rafael Espindola77021c92013-07-16 03:20:13 +0000370 perms Perms = static_cast<perms>(Status.st_mode);
371 Result =
372 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
373 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000374
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000375 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000376}
377
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000378std::error_code status(const Twine &Path, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000379 SmallString<128> PathStorage;
380 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
381
382 struct stat Status;
383 int StatRet = ::stat(P.begin(), &Status);
384 return fillStatus(StatRet, Status, Result);
385}
386
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000387std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000388 struct stat Status;
389 int StatRet = ::fstat(FD, &Status);
390 return fillStatus(StatRet, Status, Result);
391}
392
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000393std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000394#if defined(HAVE_FUTIMENS)
395 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000396 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000397 Times[0].tv_nsec = 0;
398 Times[1] = Times[0];
399 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000400 return std::error_code(errno, std::generic_category());
401 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000402#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000403 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000404 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000405 Times[0].tv_usec = 0;
406 Times[1] = Times[0];
407 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000408 return std::error_code(errno, std::generic_category());
409 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000410#else
411#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000412 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000413#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000414}
415
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000416std::error_code mapped_file_region::init(int FD, uint64_t Offset,
417 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000418 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000419
420 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
421 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Craig Toppere73658d2014-04-28 04:05:08 +0000422 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000423 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000424 return std::error_code(errno, std::generic_category());
425 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000426}
427
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000428mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
429 uint64_t offset, std::error_code &ec)
430 : Size(length), Mapping() {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000431 // Make sure that the requested size fits within SIZE_T.
432 if (length > std::numeric_limits<size_t>::max()) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000433 ec = make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000434 return;
435 }
436
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000437 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000438 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000439 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000440}
441
442mapped_file_region::~mapped_file_region() {
443 if (Mapping)
444 ::munmap(Mapping, Size);
445}
446
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000447uint64_t mapped_file_region::size() const {
448 assert(Mapping && "Mapping failed but used anyway!");
449 return Size;
450}
451
452char *mapped_file_region::data() const {
453 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000454 return reinterpret_cast<char*>(Mapping);
455}
456
457const char *mapped_file_region::const_data() const {
458 assert(Mapping && "Mapping failed but used anyway!");
459 return reinterpret_cast<const char*>(Mapping);
460}
461
462int mapped_file_region::alignment() {
Rafael Espindolac0610bf2014-12-04 16:59:36 +0000463 return Process::getPageSize();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000464}
465
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000466std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000467 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000468 SmallString<128> path_null(path);
469 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000470 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000471 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000472
473 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
474 // Add something for replace_filename to replace.
475 path::append(path_null, ".");
476 it.CurrentEntry = directory_entry(path_null.str());
477 return directory_iterator_increment(it);
478}
479
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000480std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000481 if (it.IterationHandle)
482 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
483 it.IterationHandle = 0;
484 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000485 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000486}
487
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000488std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000489 errno = 0;
490 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
Craig Toppere73658d2014-04-28 04:05:08 +0000491 if (cur_dir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000492 return std::error_code(errno, std::generic_category());
Craig Toppere73658d2014-04-28 04:05:08 +0000493 } else if (cur_dir != nullptr) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000494 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
495 if ((name.size() == 1 && name[0] == '.') ||
496 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
497 return directory_iterator_increment(it);
498 it.CurrentEntry.replace_filename(name);
499 } else
500 return directory_iterator_destruct(it);
501
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000502 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000503}
504
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000505std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000506 SmallString<128> Storage;
507 StringRef P = Name.toNullTerminatedStringRef(Storage);
508 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
509 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000510 return std::error_code(errno, std::generic_category());
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000511 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000512 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000513}
Nick Kledzik18497e92012-06-20 00:28:54 +0000514
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000515std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000516 sys::fs::OpenFlags Flags, unsigned Mode) {
517 // Verify that we don't have both "append" and "excl".
518 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
519 "Cannot specify both 'excl' and 'append' file creation flags!");
520
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000521 int OpenFlags = O_CREAT;
522
523 if (Flags & F_RW)
524 OpenFlags |= O_RDWR;
525 else
526 OpenFlags |= O_WRONLY;
Rafael Espindola67080ce2013-07-19 15:02:03 +0000527
528 if (Flags & F_Append)
529 OpenFlags |= O_APPEND;
530 else
531 OpenFlags |= O_TRUNC;
532
533 if (Flags & F_Excl)
534 OpenFlags |= O_EXCL;
535
536 SmallString<128> Storage;
537 StringRef P = Name.toNullTerminatedStringRef(Storage);
538 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
539 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000540 return std::error_code(errno, std::generic_category());
Rafael Espindola67080ce2013-07-19 15:02:03 +0000541 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000542 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000543}
544
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000545} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000546
547namespace path {
548
549bool home_directory(SmallVectorImpl<char> &result) {
550 if (char *RequestedDir = getenv("HOME")) {
551 result.clear();
552 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
553 return true;
554 }
555
556 return false;
557}
558
Rafael Espindola016a6d52014-08-26 14:47:52 +0000559static const char *getEnvTempDir() {
560 // Check whether the temporary directory is specified by an environment
561 // variable.
562 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
563 for (const char *Env : EnvironmentVariables) {
564 if (const char *Dir = std::getenv(Env))
565 return Dir;
566 }
567
568 return nullptr;
569}
570
571static const char *getDefaultTempDir(bool ErasedOnReboot) {
572#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +0000573 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +0000574 return P_tmpdir;
575#endif
576
577 if (ErasedOnReboot)
578 return "/tmp";
579 return "/var/tmp";
580}
581
582void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
583 Result.clear();
584
585 if (ErasedOnReboot) {
586 // There is no env variable for the cache directory.
587 if (const char *RequestedDir = getEnvTempDir()) {
588 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
589 return;
590 }
591 }
592
593#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
594 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
595 // macros defined in <unistd.h> on darwin >= 9
596 int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
597 : _CS_DARWIN_USER_CACHE_DIR;
598 size_t ConfLen = confstr(ConfName, nullptr, 0);
599 if (ConfLen > 0) {
600 do {
601 Result.resize(ConfLen);
602 ConfLen = confstr(ConfName, Result.data(), Result.size());
603 } while (ConfLen > 0 && ConfLen != Result.size());
604
605 if (ConfLen > 0) {
606 assert(Result.back() == 0);
607 Result.pop_back();
608 return;
609 }
610
611 Result.clear();
612 }
613#endif
614
615 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
616 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
617}
618
Peter Collingbournef7d41012014-01-31 23:46:06 +0000619} // end namespace path
620
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000621} // end namespace sys
622} // end namespace llvm