blob: 8de94c11dcecb71db94101c02804e916db20bcba [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)
153 return StringRef(exe_path, len);
154 } 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
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000222std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000223 SmallString<128> path_storage;
224 StringRef p = path.toNullTerminatedStringRef(path_storage);
225
Michael J. Spencere5755be2010-12-07 01:23:29 +0000226 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000227 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000228 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000229 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000230
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000231 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000232}
233
Rafael Espindola83f858e2014-03-11 18:40:24 +0000234// Note that we are using symbolic link because hard links are not supported by
235// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000236std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000237 // Get arguments.
238 SmallString<128> from_storage;
239 SmallString<128> to_storage;
240 StringRef f = from.toNullTerminatedStringRef(from_storage);
241 StringRef t = to.toNullTerminatedStringRef(to_storage);
242
Rafael Espindola83f858e2014-03-11 18:40:24 +0000243 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000244 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000245
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000246 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000247}
248
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000249std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000250 SmallString<128> path_storage;
251 StringRef p = path.toNullTerminatedStringRef(path_storage);
252
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000253 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000254 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000255 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000256 return std::error_code(errno, std::generic_category());
257 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000258 }
259
260 // Note: this check catches strange situations. In all cases, LLVM should
261 // only be involved in the creation and deletion of regular files. This
262 // check ensures that what we're trying to erase is a regular file. It
263 // effectively prevents LLVM from erasing things like /dev/null, any block
264 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000265 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000266 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000267
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000268 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000269 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000270 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000271 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000272
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000273 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000274}
275
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000276std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000277 // Get arguments.
278 SmallString<128> from_storage;
279 SmallString<128> to_storage;
280 StringRef f = from.toNullTerminatedStringRef(from_storage);
281 StringRef t = to.toNullTerminatedStringRef(to_storage);
282
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000283 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000284 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000285
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000286 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000287}
288
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000289std::error_code resize_file(int FD, uint64_t Size) {
290 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000291 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000292
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000293 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000294}
295
Rafael Espindola281f23a2014-09-11 20:30:02 +0000296static int convertAccessMode(AccessMode Mode) {
297 switch (Mode) {
298 case AccessMode::Exist:
299 return F_OK;
300 case AccessMode::Write:
301 return W_OK;
302 case AccessMode::Execute:
303 return R_OK | X_OK; // scripts also need R_OK.
304 }
305 llvm_unreachable("invalid enum");
306}
Michael J. Spencer45710402010-12-03 01:21:28 +0000307
Rafael Espindola281f23a2014-09-11 20:30:02 +0000308std::error_code access(const Twine &Path, AccessMode Mode) {
309 SmallString<128> PathStorage;
310 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
311
312 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
313 return std::error_code(errno, std::generic_category());
314
315 if (Mode == AccessMode::Execute) {
316 // Don't say that directories are executable.
317 struct stat buf;
318 if (0 != stat(P.begin(), &buf))
319 return errc::permission_denied;
320 if (!S_ISREG(buf.st_mode))
321 return errc::permission_denied;
322 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000323
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000324 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000325}
326
Michael J. Spencer203d7802011-12-12 06:04:28 +0000327bool equivalent(file_status A, file_status B) {
328 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000329 return A.fs_st_dev == B.fs_st_dev &&
330 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000331}
332
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000333std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000334 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000335 if (std::error_code ec = status(A, fsA))
336 return ec;
337 if (std::error_code ec = status(B, fsB))
338 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000339 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000340 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000341}
342
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000343static std::error_code fillStatus(int StatRet, const struct stat &Status,
Rafael Espindola77021c92013-07-16 03:20:13 +0000344 file_status &Result) {
345 if (StatRet != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000346 std::error_code ec(errno, std::generic_category());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000347 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000348 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000349 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000350 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000351 return ec;
352 }
353
Rafael Espindola9da91a02013-07-16 02:55:33 +0000354 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000355
Rafael Espindola77021c92013-07-16 03:20:13 +0000356 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000357 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000358 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000359 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000360 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000361 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000362 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000363 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000364 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000365 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000366 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000367 Type = file_type::socket_file;
368
Rafael Espindola77021c92013-07-16 03:20:13 +0000369 perms Perms = static_cast<perms>(Status.st_mode);
370 Result =
371 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
372 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000373
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000374 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000375}
376
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000377std::error_code status(const Twine &Path, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000378 SmallString<128> PathStorage;
379 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
380
381 struct stat Status;
382 int StatRet = ::stat(P.begin(), &Status);
383 return fillStatus(StatRet, Status, Result);
384}
385
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000386std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000387 struct stat Status;
388 int StatRet = ::fstat(FD, &Status);
389 return fillStatus(StatRet, Status, Result);
390}
391
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000392std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000393#if defined(HAVE_FUTIMENS)
394 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000395 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000396 Times[0].tv_nsec = 0;
397 Times[1] = Times[0];
398 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000399 return std::error_code(errno, std::generic_category());
400 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000401#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000402 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000403 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000404 Times[0].tv_usec = 0;
405 Times[1] = Times[0];
406 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000407 return std::error_code(errno, std::generic_category());
408 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000409#else
410#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000411 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000412#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000413}
414
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000415std::error_code mapped_file_region::init(int FD, uint64_t Offset,
416 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000417 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000418
419 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
420 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Craig Toppere73658d2014-04-28 04:05:08 +0000421 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000422 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000423 return std::error_code(errno, std::generic_category());
424 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000425}
426
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000427mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
428 uint64_t offset, std::error_code &ec)
429 : Size(length), Mapping() {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000430 // Make sure that the requested size fits within SIZE_T.
431 if (length > std::numeric_limits<size_t>::max()) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000432 ec = make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000433 return;
434 }
435
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000436 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000437 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000438 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000439}
440
441mapped_file_region::~mapped_file_region() {
442 if (Mapping)
443 ::munmap(Mapping, Size);
444}
445
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000446uint64_t mapped_file_region::size() const {
447 assert(Mapping && "Mapping failed but used anyway!");
448 return Size;
449}
450
451char *mapped_file_region::data() const {
452 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000453 return reinterpret_cast<char*>(Mapping);
454}
455
456const char *mapped_file_region::const_data() const {
457 assert(Mapping && "Mapping failed but used anyway!");
458 return reinterpret_cast<const char*>(Mapping);
459}
460
461int mapped_file_region::alignment() {
Rafael Espindolac0610bf2014-12-04 16:59:36 +0000462 return Process::getPageSize();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000463}
464
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000465std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000466 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000467 SmallString<128> path_null(path);
468 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000469 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000470 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000471
472 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
473 // Add something for replace_filename to replace.
474 path::append(path_null, ".");
475 it.CurrentEntry = directory_entry(path_null.str());
476 return directory_iterator_increment(it);
477}
478
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000479std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000480 if (it.IterationHandle)
481 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
482 it.IterationHandle = 0;
483 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000484 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000485}
486
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000487std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000488 errno = 0;
489 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
Craig Toppere73658d2014-04-28 04:05:08 +0000490 if (cur_dir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000491 return std::error_code(errno, std::generic_category());
Craig Toppere73658d2014-04-28 04:05:08 +0000492 } else if (cur_dir != nullptr) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000493 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
494 if ((name.size() == 1 && name[0] == '.') ||
495 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
496 return directory_iterator_increment(it);
497 it.CurrentEntry.replace_filename(name);
498 } else
499 return directory_iterator_destruct(it);
500
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000501 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000502}
503
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000504std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000505 SmallString<128> Storage;
506 StringRef P = Name.toNullTerminatedStringRef(Storage);
507 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
508 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000509 return std::error_code(errno, std::generic_category());
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000510 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000511 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000512}
Nick Kledzik18497e92012-06-20 00:28:54 +0000513
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000514std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000515 sys::fs::OpenFlags Flags, unsigned Mode) {
516 // Verify that we don't have both "append" and "excl".
517 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
518 "Cannot specify both 'excl' and 'append' file creation flags!");
519
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000520 int OpenFlags = O_CREAT;
521
522 if (Flags & F_RW)
523 OpenFlags |= O_RDWR;
524 else
525 OpenFlags |= O_WRONLY;
Rafael Espindola67080ce2013-07-19 15:02:03 +0000526
527 if (Flags & F_Append)
528 OpenFlags |= O_APPEND;
529 else
530 OpenFlags |= O_TRUNC;
531
532 if (Flags & F_Excl)
533 OpenFlags |= O_EXCL;
534
535 SmallString<128> Storage;
536 StringRef P = Name.toNullTerminatedStringRef(Storage);
537 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
538 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000539 return std::error_code(errno, std::generic_category());
Rafael Espindola67080ce2013-07-19 15:02:03 +0000540 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000541 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000542}
543
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000544} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000545
546namespace path {
547
548bool home_directory(SmallVectorImpl<char> &result) {
549 if (char *RequestedDir = getenv("HOME")) {
550 result.clear();
551 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
552 return true;
553 }
554
555 return false;
556}
557
Rafael Espindola016a6d52014-08-26 14:47:52 +0000558static const char *getEnvTempDir() {
559 // Check whether the temporary directory is specified by an environment
560 // variable.
561 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
562 for (const char *Env : EnvironmentVariables) {
563 if (const char *Dir = std::getenv(Env))
564 return Dir;
565 }
566
567 return nullptr;
568}
569
570static const char *getDefaultTempDir(bool ErasedOnReboot) {
571#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +0000572 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +0000573 return P_tmpdir;
574#endif
575
576 if (ErasedOnReboot)
577 return "/tmp";
578 return "/var/tmp";
579}
580
581void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
582 Result.clear();
583
584 if (ErasedOnReboot) {
585 // There is no env variable for the cache directory.
586 if (const char *RequestedDir = getEnvTempDir()) {
587 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
588 return;
589 }
590 }
591
592#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
593 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
594 // macros defined in <unistd.h> on darwin >= 9
595 int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
596 : _CS_DARWIN_USER_CACHE_DIR;
597 size_t ConfLen = confstr(ConfName, nullptr, 0);
598 if (ConfLen > 0) {
599 do {
600 Result.resize(ConfLen);
601 ConfLen = confstr(ConfName, Result.data(), Result.size());
602 } while (ConfLen > 0 && ConfLen != Result.size());
603
604 if (ConfLen > 0) {
605 assert(Result.back() == 0);
606 Result.pop_back();
607 return;
608 }
609
610 Result.clear();
611 }
612#endif
613
614 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
615 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
616}
617
Peter Collingbournef7d41012014-01-31 23:46:06 +0000618} // end namespace path
619
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000620} // end namespace sys
621} // end namespace llvm