blob: fe3f43a6fd80d247330a4d3e976b4d14f8245f09 [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
Rafael Espindola37b012d2014-02-23 15:16:03 +000090static error_code TempDir(SmallVectorImpl<char> &result) {
91 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
92 const char *dir = 0;
93 (dir = std::getenv("TMPDIR")) || (dir = std::getenv("TMP")) ||
94 (dir = std::getenv("TEMP")) || (dir = std::getenv("TEMPDIR")) ||
Michael J. Spencer45710402010-12-03 01:21:28 +000095#ifdef P_tmpdir
Rafael Espindola37b012d2014-02-23 15:16:03 +000096 (dir = P_tmpdir) ||
Michael J. Spencer45710402010-12-03 01:21:28 +000097#endif
Rafael Espindola37b012d2014-02-23 15:16:03 +000098 (dir = "/tmp");
Michael J. Spencer45710402010-12-03 01:21:28 +000099
Rafael Espindola37b012d2014-02-23 15:16:03 +0000100 result.clear();
101 StringRef d(dir);
102 result.append(d.begin(), d.end());
103 return error_code::success();
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000104}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000105
106namespace llvm {
107namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000108namespace fs {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000109#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
110 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000111 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000112static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000113test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
114{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000115 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000116 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000117
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000118 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
119 if (realpath(fullpath, ret) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000120 return (1);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000121 if (stat(fullpath, &sb) != 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000122 return (1);
123
124 return (0);
125}
126
127static char *
128getprogpath(char ret[PATH_MAX], const char *bin)
129{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000130 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000131
132 /* First approach: absolute path. */
133 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000134 if (test_dir(ret, "/", bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000135 return (ret);
136 return (NULL);
137 }
138
139 /* Second approach: relative path. */
140 if (strchr(bin, '/') != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000141 char cwd[PATH_MAX];
142 if (getcwd(cwd, PATH_MAX) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000143 return (NULL);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000144 if (test_dir(ret, cwd, bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000145 return (ret);
146 return (NULL);
147 }
148
149 /* Third approach: $PATH */
150 if ((pv = getenv("PATH")) == NULL)
151 return (NULL);
152 s = pv = strdup(pv);
153 if (pv == NULL)
154 return (NULL);
155 while ((t = strsep(&s, ":")) != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000156 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000157 free(pv);
158 return (ret);
159 }
160 }
161 free(pv);
162 return (NULL);
163}
164#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
165
166/// GetMainExecutable - Return the path to the main executable, given the
167/// value of argv[0] from program startup.
168std::string getMainExecutable(const char *argv0, void *MainAddr) {
169#if defined(__APPLE__)
170 // On OS X the executable path is saved to the stack by dyld. Reading it
171 // from there is much faster than calling dladdr, especially for large
172 // binaries with symbols.
173 char exe_path[MAXPATHLEN];
174 uint32_t size = sizeof(exe_path);
175 if (_NSGetExecutablePath(exe_path, &size) == 0) {
176 char link_path[MAXPATHLEN];
177 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000178 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000179 }
180#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000181 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
182 defined(__FreeBSD_kernel__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000183 char exe_path[PATH_MAX];
184
185 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000186 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000187#elif defined(__linux__) || defined(__CYGWIN__)
188 char exe_path[MAXPATHLEN];
189 StringRef aPath("/proc/self/exe");
190 if (sys::fs::exists(aPath)) {
191 // /proc is not always mounted under Linux (chroot for example).
192 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
193 if (len >= 0)
194 return StringRef(exe_path, len);
195 } else {
196 // Fall back to the classical detection.
197 if (getprogpath(exe_path, argv0) != NULL)
198 return exe_path;
199 }
200#elif defined(HAVE_DLFCN_H)
201 // Use dladdr to get executable path if available.
202 Dl_info DLInfo;
203 int err = dladdr(MainAddr, &DLInfo);
204 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000205 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000206
207 // If the filename is a symlink, we need to resolve and return the location of
208 // the actual executable.
209 char link_path[MAXPATHLEN];
210 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000211 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000212#else
213#error GetMainExecutable is not implemented on this host yet.
214#endif
215 return "";
216}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000217
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000218TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000219 TimeValue Ret;
220 Ret.fromEpochTime(fs_st_mtime);
221 return Ret;
222}
223
Rafael Espindolad1230992013-07-29 21:55:38 +0000224UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000225 return UniqueID(fs_st_dev, fs_st_ino);
226}
227
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000228error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000229 result.clear();
230
231 const char *pwd = ::getenv("PWD");
232 llvm::sys::fs::file_status PWDStatus, DotStatus;
233 if (pwd && llvm::sys::path::is_absolute(pwd) &&
234 !llvm::sys::fs::status(pwd, PWDStatus) &&
235 !llvm::sys::fs::status(".", DotStatus) &&
236 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
237 result.append(pwd, pwd + strlen(pwd));
238 return error_code::success();
239 }
240
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000241#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000242 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000243#else
244// For GNU Hurd
245 result.reserve(1024);
246#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000247
Michael J. Spencer20daa282010-12-07 01:22:31 +0000248 while (true) {
249 if (::getcwd(result.data(), result.capacity()) == 0) {
250 // See if there was a real error.
251 if (errno != errc::not_enough_memory)
252 return error_code(errno, system_category());
253 // Otherwise there just wasn't enough space.
254 result.reserve(result.capacity() * 2);
255 } else
256 break;
257 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000258
259 result.set_size(strlen(result.data()));
David Blaikie18544b92012-02-09 19:24:12 +0000260 return error_code::success();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000261}
262
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000263error_code create_directory(const Twine &path, bool IgnoreExisting) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000264 SmallString<128> path_storage;
265 StringRef p = path.toNullTerminatedStringRef(path_storage);
266
Michael J. Spencere5755be2010-12-07 01:23:29 +0000267 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000268 if (errno != errc::file_exists || !IgnoreExisting)
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000269 return error_code(errno, system_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000270 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000271
David Blaikie18544b92012-02-09 19:24:12 +0000272 return error_code::success();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000273}
274
Michael J. Spencere0c45602010-12-03 05:58:41 +0000275error_code create_hard_link(const Twine &to, const Twine &from) {
276 // Get arguments.
277 SmallString<128> from_storage;
278 SmallString<128> to_storage;
279 StringRef f = from.toNullTerminatedStringRef(from_storage);
280 StringRef t = to.toNullTerminatedStringRef(to_storage);
281
282 if (::link(t.begin(), f.begin()) == -1)
283 return error_code(errno, system_category());
284
David Blaikie18544b92012-02-09 19:24:12 +0000285 return error_code::success();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000286}
287
Argyrios Kyrtzidisec9dac22014-03-06 17:36:46 +0000288error_code create_symbolic_link(const Twine &to, const Twine &from) {
289 // Get arguments.
290 SmallString<128> from_storage;
291 SmallString<128> to_storage;
292 StringRef f = from.toNullTerminatedStringRef(from_storage);
293 StringRef t = to.toNullTerminatedStringRef(to_storage);
294
295 if (::symlink(t.begin(), f.begin()) == -1)
296 return error_code(errno, system_category());
297
298 return error_code::success();
299}
300
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000301error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000302 SmallString<128> path_storage;
303 StringRef p = path.toNullTerminatedStringRef(path_storage);
304
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000305 struct stat buf;
306 if (stat(p.begin(), &buf) != 0) {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000307 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000308 return error_code(errno, system_category());
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000309 return error_code::success();
310 }
311
312 // Note: this check catches strange situations. In all cases, LLVM should
313 // only be involved in the creation and deletion of regular files. This
314 // check ensures that what we're trying to erase is a regular file. It
315 // effectively prevents LLVM from erasing things like /dev/null, any block
316 // special file, or other things that aren't "regular" files.
317 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
318 return make_error_code(errc::operation_not_permitted);
319
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000320 if (::remove(p.begin()) == -1) {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000321 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000322 return error_code(errno, system_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000323 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000324
David Blaikie18544b92012-02-09 19:24:12 +0000325 return error_code::success();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000326}
327
Michael J. Spencer409f5562010-12-03 17:53:55 +0000328error_code rename(const Twine &from, const Twine &to) {
329 // Get arguments.
330 SmallString<128> from_storage;
331 SmallString<128> to_storage;
332 StringRef f = from.toNullTerminatedStringRef(from_storage);
333 StringRef t = to.toNullTerminatedStringRef(to_storage);
334
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000335 if (::rename(f.begin(), t.begin()) == -1)
336 return error_code(errno, system_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000337
David Blaikie18544b92012-02-09 19:24:12 +0000338 return error_code::success();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000339}
340
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000341error_code resize_file(const Twine &path, uint64_t size) {
342 SmallString<128> path_storage;
343 StringRef p = path.toNullTerminatedStringRef(path_storage);
344
345 if (::truncate(p.begin(), size) == -1)
346 return error_code(errno, system_category());
347
David Blaikie18544b92012-02-09 19:24:12 +0000348 return error_code::success();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000349}
350
Michael J. Spencer45710402010-12-03 01:21:28 +0000351error_code exists(const Twine &path, bool &result) {
352 SmallString<128> path_storage;
353 StringRef p = path.toNullTerminatedStringRef(path_storage);
354
Benjamin Kramer172f8082012-06-02 16:28:09 +0000355 if (::access(p.begin(), F_OK) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000356 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer45710402010-12-03 01:21:28 +0000357 return error_code(errno, system_category());
358 result = false;
359 } else
360 result = true;
361
David Blaikie18544b92012-02-09 19:24:12 +0000362 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000363}
364
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000365bool can_write(const Twine &Path) {
366 SmallString<128> PathStorage;
367 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
368 return 0 == access(P.begin(), W_OK);
369}
370
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000371bool can_execute(const Twine &Path) {
372 SmallString<128> PathStorage;
373 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
374
Manuel Klimek52772bf2013-06-17 10:48:34 +0000375 if (0 != access(P.begin(), R_OK | X_OK))
376 return false;
377 struct stat buf;
378 if (0 != stat(P.begin(), &buf))
379 return false;
380 if (!S_ISREG(buf.st_mode))
381 return false;
382 return true;
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000383}
384
Michael J. Spencer203d7802011-12-12 06:04:28 +0000385bool equivalent(file_status A, file_status B) {
386 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000387 return A.fs_st_dev == B.fs_st_dev &&
388 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000389}
390
Michael J. Spencer376d3872010-12-03 18:49:13 +0000391error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000392 file_status fsA, fsB;
393 if (error_code ec = status(A, fsA)) return ec;
394 if (error_code ec = status(B, fsB)) return ec;
395 result = equivalent(fsA, fsB);
David Blaikie18544b92012-02-09 19:24:12 +0000396 return error_code::success();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000397}
398
Rafael Espindola77021c92013-07-16 03:20:13 +0000399static error_code fillStatus(int StatRet, const struct stat &Status,
400 file_status &Result) {
401 if (StatRet != 0) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000402 error_code ec(errno, system_category());
403 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000404 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000405 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000406 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000407 return ec;
408 }
409
Rafael Espindola9da91a02013-07-16 02:55:33 +0000410 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000411
Rafael Espindola77021c92013-07-16 03:20:13 +0000412 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000413 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000414 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000415 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000416 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000417 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000418 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000419 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000420 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000421 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000422 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000423 Type = file_type::socket_file;
424
Rafael Espindola77021c92013-07-16 03:20:13 +0000425 perms Perms = static_cast<perms>(Status.st_mode);
426 Result =
427 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
428 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000429
David Blaikie18544b92012-02-09 19:24:12 +0000430 return error_code::success();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000431}
432
Rafael Espindola77021c92013-07-16 03:20:13 +0000433error_code status(const Twine &Path, file_status &Result) {
434 SmallString<128> PathStorage;
435 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
436
437 struct stat Status;
438 int StatRet = ::stat(P.begin(), &Status);
439 return fillStatus(StatRet, Status, Result);
440}
441
442error_code status(int FD, file_status &Result) {
443 struct stat Status;
444 int StatRet = ::fstat(FD, &Status);
445 return fillStatus(StatRet, Status, Result);
446}
447
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000448error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000449#if defined(HAVE_FUTIMENS)
450 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000451 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000452 Times[0].tv_nsec = 0;
453 Times[1] = Times[0];
454 if (::futimens(FD, Times))
Alp Tokerb30f01e2013-12-11 15:42:33 +0000455 return error_code(errno, system_category());
456 return error_code::success();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000457#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000458 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000459 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000460 Times[0].tv_usec = 0;
461 Times[1] = Times[0];
462 if (::futimes(FD, Times))
463 return error_code(errno, system_category());
464 return error_code::success();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000465#else
466#warning Missing futimes() and futimens()
467 return make_error_code(errc::not_supported);
468#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000469}
470
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000471error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
472 AutoFD ScopedFD(FD);
473 if (!CloseFD)
474 ScopedFD.take();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000475
476 // Figure out how large the file is.
477 struct stat FileInfo;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000478 if (fstat(FD, &FileInfo) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000479 return error_code(errno, system_category());
480 uint64_t FileSize = FileInfo.st_size;
481
482 if (Size == 0)
483 Size = FileSize;
484 else if (FileSize < Size) {
485 // We need to grow the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000486 if (ftruncate(FD, Size) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000487 return error_code(errno, system_category());
488 }
489
490 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
491 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
492#ifdef MAP_FILE
493 flags |= MAP_FILE;
494#endif
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000495 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000496 if (Mapping == MAP_FAILED)
497 return error_code(errno, system_category());
498 return error_code::success();
499}
500
501mapped_file_region::mapped_file_region(const Twine &path,
502 mapmode mode,
503 uint64_t length,
504 uint64_t offset,
505 error_code &ec)
506 : Mode(mode)
507 , Size(length)
508 , Mapping() {
509 // Make sure that the requested size fits within SIZE_T.
510 if (length > std::numeric_limits<size_t>::max()) {
511 ec = make_error_code(errc::invalid_argument);
512 return;
513 }
514
515 SmallString<128> path_storage;
516 StringRef name = path.toNullTerminatedStringRef(path_storage);
517 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
518 int ofd = ::open(name.begin(), oflags);
519 if (ofd == -1) {
520 ec = error_code(errno, system_category());
521 return;
522 }
523
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000524 ec = init(ofd, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000525 if (ec)
526 Mapping = 0;
527}
528
529mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000530 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000531 mapmode mode,
532 uint64_t length,
533 uint64_t offset,
534 error_code &ec)
535 : Mode(mode)
536 , Size(length)
537 , Mapping() {
538 // Make sure that the requested size fits within SIZE_T.
539 if (length > std::numeric_limits<size_t>::max()) {
540 ec = make_error_code(errc::invalid_argument);
541 return;
542 }
543
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000544 ec = init(fd, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000545 if (ec)
546 Mapping = 0;
547}
548
549mapped_file_region::~mapped_file_region() {
550 if (Mapping)
551 ::munmap(Mapping, Size);
552}
553
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000554mapped_file_region::mapped_file_region(mapped_file_region &&other)
555 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
556 other.Mapping = 0;
557}
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000558
559mapped_file_region::mapmode mapped_file_region::flags() const {
560 assert(Mapping && "Mapping failed but used anyway!");
561 return Mode;
562}
563
564uint64_t mapped_file_region::size() const {
565 assert(Mapping && "Mapping failed but used anyway!");
566 return Size;
567}
568
569char *mapped_file_region::data() const {
570 assert(Mapping && "Mapping failed but used anyway!");
Alp Tokerf907b892013-12-05 05:44:44 +0000571 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000572 return reinterpret_cast<char*>(Mapping);
573}
574
575const char *mapped_file_region::const_data() const {
576 assert(Mapping && "Mapping failed but used anyway!");
577 return reinterpret_cast<const char*>(Mapping);
578}
579
580int mapped_file_region::alignment() {
Chandler Carruthacd64be2012-12-31 23:31:56 +0000581 return process::get_self()->page_size();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000582}
583
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000584error_code detail::directory_iterator_construct(detail::DirIterState &it,
585 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000586 SmallString<128> path_null(path);
587 DIR *directory = ::opendir(path_null.c_str());
588 if (directory == 0)
589 return error_code(errno, system_category());
590
591 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
592 // Add something for replace_filename to replace.
593 path::append(path_null, ".");
594 it.CurrentEntry = directory_entry(path_null.str());
595 return directory_iterator_increment(it);
596}
597
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000598error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000599 if (it.IterationHandle)
600 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
601 it.IterationHandle = 0;
602 it.CurrentEntry = directory_entry();
David Blaikie18544b92012-02-09 19:24:12 +0000603 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000604}
605
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000606error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000607 errno = 0;
608 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
609 if (cur_dir == 0 && errno != 0) {
610 return error_code(errno, system_category());
611 } else if (cur_dir != 0) {
612 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
613 if ((name.size() == 1 && name[0] == '.') ||
614 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
615 return directory_iterator_increment(it);
616 it.CurrentEntry.replace_filename(name);
617 } else
618 return directory_iterator_destruct(it);
619
David Blaikie18544b92012-02-09 19:24:12 +0000620 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000621}
622
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000623error_code get_magic(const Twine &path, uint32_t len,
624 SmallVectorImpl<char> &result) {
625 SmallString<128> PathStorage;
626 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
627 result.set_size(0);
628
629 // Open path.
630 std::FILE *file = std::fopen(Path.data(), "rb");
631 if (file == 0)
632 return error_code(errno, system_category());
633
634 // Reserve storage.
635 result.reserve(len);
636
637 // Read magic!
638 size_t size = std::fread(result.data(), 1, len, file);
639 if (std::ferror(file) != 0) {
640 std::fclose(file);
641 return error_code(errno, system_category());
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000642 } else if (size != len) {
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000643 if (std::feof(file) != 0) {
644 std::fclose(file);
645 result.set_size(size);
646 return make_error_code(errc::value_too_large);
647 }
648 }
649 std::fclose(file);
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000650 result.set_size(size);
David Blaikie18544b92012-02-09 19:24:12 +0000651 return error_code::success();
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000652}
653
Nick Kledzik18497e92012-06-20 00:28:54 +0000654error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
655 bool map_writable, void *&result) {
656 SmallString<128> path_storage;
657 StringRef name = path.toNullTerminatedStringRef(path_storage);
658 int oflags = map_writable ? O_RDWR : O_RDONLY;
659 int ofd = ::open(name.begin(), oflags);
660 if ( ofd == -1 )
661 return error_code(errno, system_category());
662 AutoFD fd(ofd);
663 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
664 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
665#ifdef MAP_FILE
666 flags |= MAP_FILE;
667#endif
668 result = ::mmap(0, size, prot, flags, fd, file_offset);
669 if (result == MAP_FAILED) {
670 return error_code(errno, system_category());
671 }
672
673 return error_code::success();
674}
675
676error_code unmap_file_pages(void *base, size_t size) {
677 if ( ::munmap(base, size) == -1 )
678 return error_code(errno, system_category());
679
680 return error_code::success();
681}
682
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000683error_code openFileForRead(const Twine &Name, int &ResultFD) {
684 SmallString<128> Storage;
685 StringRef P = Name.toNullTerminatedStringRef(Storage);
686 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
687 if (errno != EINTR)
688 return error_code(errno, system_category());
689 }
690 return error_code::success();
691}
Nick Kledzik18497e92012-06-20 00:28:54 +0000692
Rafael Espindola67080ce2013-07-19 15:02:03 +0000693error_code openFileForWrite(const Twine &Name, int &ResultFD,
694 sys::fs::OpenFlags Flags, unsigned Mode) {
695 // Verify that we don't have both "append" and "excl".
696 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
697 "Cannot specify both 'excl' and 'append' file creation flags!");
698
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000699 int OpenFlags = O_CREAT;
700
701 if (Flags & F_RW)
702 OpenFlags |= O_RDWR;
703 else
704 OpenFlags |= O_WRONLY;
Rafael Espindola67080ce2013-07-19 15:02:03 +0000705
706 if (Flags & F_Append)
707 OpenFlags |= O_APPEND;
708 else
709 OpenFlags |= O_TRUNC;
710
711 if (Flags & F_Excl)
712 OpenFlags |= O_EXCL;
713
714 SmallString<128> Storage;
715 StringRef P = Name.toNullTerminatedStringRef(Storage);
716 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
717 if (errno != EINTR)
718 return error_code(errno, system_category());
719 }
720 return error_code::success();
721}
722
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000723} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000724
725namespace path {
726
727bool home_directory(SmallVectorImpl<char> &result) {
728 if (char *RequestedDir = getenv("HOME")) {
729 result.clear();
730 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
731 return true;
732 }
733
734 return false;
735}
736
737} // end namespace path
738
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000739} // end namespace sys
740} // end namespace llvm