blob: e211ac99110aa67c0a68e411c4c1e35577b5ed05 [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
Rafael Espindolae79a8722013-06-28 03:48:47 +0000106static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
107 SmallVectorImpl<char> &ResultPath,
108 bool MakeAbsolute, unsigned Mode,
109 FSEntity Type) {
110 SmallString<128> ModelStorage;
111 Model.toVector(ModelStorage);
112
113 if (MakeAbsolute) {
114 // Make model absolute by prepending a temp directory if it's not already.
115 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
116 if (!absolute) {
117 SmallString<128> TDir;
118 if (error_code ec = TempDir(TDir)) return ec;
119 sys::path::append(TDir, Twine(ModelStorage));
120 ModelStorage.swap(TDir);
121 }
122 }
123
124 // From here on, DO NOT modify model. It may be needed if the randomly chosen
125 // path already exists.
126 ResultPath = ModelStorage;
127 // Null terminate.
128 ResultPath.push_back(0);
129 ResultPath.pop_back();
130
131retry_random_path:
132 // Replace '%' with random chars.
133 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
134 if (ModelStorage[i] == '%')
135 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
136 }
137
138 // Try to open + create the file.
139 switch (Type) {
140 case FS_File: {
141 int RandomFD = ::open(ResultPath.begin(), O_RDWR | O_CREAT | O_EXCL, Mode);
142 if (RandomFD == -1) {
143 int SavedErrno = errno;
144 // If the file existed, try again, otherwise, error.
145 if (SavedErrno == errc::file_exists)
146 goto retry_random_path;
147 return error_code(SavedErrno, system_category());
148 }
149
150 ResultFD = RandomFD;
151 return error_code::success();
152 }
153
154 case FS_Name: {
155 bool Exists;
156 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
157 if (EC)
158 return EC;
159 if (Exists)
160 goto retry_random_path;
161 return error_code::success();
162 }
163
164 case FS_Dir: {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000165 if (error_code EC = sys::fs::create_directory(ResultPath.begin(), false)) {
166 if (EC == errc::file_exists)
167 goto retry_random_path;
Rafael Espindolae79a8722013-06-28 03:48:47 +0000168 return EC;
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000169 }
Rafael Espindolae79a8722013-06-28 03:48:47 +0000170 return error_code::success();
171 }
172 }
Patrik Hagglunddcc336b2013-06-28 06:54:05 +0000173 llvm_unreachable("Invalid Type");
Rafael Espindolae79a8722013-06-28 03:48:47 +0000174}
175
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000176namespace llvm {
177namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000178namespace fs {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000179#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
180 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000181 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000182static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000183test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
184{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000185 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000186 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000187
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000188 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
189 if (realpath(fullpath, ret) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000190 return (1);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000191 if (stat(fullpath, &sb) != 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000192 return (1);
193
194 return (0);
195}
196
197static char *
198getprogpath(char ret[PATH_MAX], const char *bin)
199{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000200 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000201
202 /* First approach: absolute path. */
203 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000204 if (test_dir(ret, "/", bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000205 return (ret);
206 return (NULL);
207 }
208
209 /* Second approach: relative path. */
210 if (strchr(bin, '/') != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000211 char cwd[PATH_MAX];
212 if (getcwd(cwd, PATH_MAX) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000213 return (NULL);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000214 if (test_dir(ret, cwd, bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000215 return (ret);
216 return (NULL);
217 }
218
219 /* Third approach: $PATH */
220 if ((pv = getenv("PATH")) == NULL)
221 return (NULL);
222 s = pv = strdup(pv);
223 if (pv == NULL)
224 return (NULL);
225 while ((t = strsep(&s, ":")) != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000226 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000227 free(pv);
228 return (ret);
229 }
230 }
231 free(pv);
232 return (NULL);
233}
234#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
235
236/// GetMainExecutable - Return the path to the main executable, given the
237/// value of argv[0] from program startup.
238std::string getMainExecutable(const char *argv0, void *MainAddr) {
239#if defined(__APPLE__)
240 // On OS X the executable path is saved to the stack by dyld. Reading it
241 // from there is much faster than calling dladdr, especially for large
242 // binaries with symbols.
243 char exe_path[MAXPATHLEN];
244 uint32_t size = sizeof(exe_path);
245 if (_NSGetExecutablePath(exe_path, &size) == 0) {
246 char link_path[MAXPATHLEN];
247 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000248 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000249 }
250#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000251 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
252 defined(__FreeBSD_kernel__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000253 char exe_path[PATH_MAX];
254
255 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000256 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000257#elif defined(__linux__) || defined(__CYGWIN__)
258 char exe_path[MAXPATHLEN];
259 StringRef aPath("/proc/self/exe");
260 if (sys::fs::exists(aPath)) {
261 // /proc is not always mounted under Linux (chroot for example).
262 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
263 if (len >= 0)
264 return StringRef(exe_path, len);
265 } else {
266 // Fall back to the classical detection.
267 if (getprogpath(exe_path, argv0) != NULL)
268 return exe_path;
269 }
270#elif defined(HAVE_DLFCN_H)
271 // Use dladdr to get executable path if available.
272 Dl_info DLInfo;
273 int err = dladdr(MainAddr, &DLInfo);
274 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000275 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000276
277 // If the filename is a symlink, we need to resolve and return the location of
278 // the actual executable.
279 char link_path[MAXPATHLEN];
280 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000281 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000282#else
283#error GetMainExecutable is not implemented on this host yet.
284#endif
285 return "";
286}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000287
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000288TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000289 TimeValue Ret;
290 Ret.fromEpochTime(fs_st_mtime);
291 return Ret;
292}
293
Rafael Espindolad1230992013-07-29 21:55:38 +0000294UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000295 return UniqueID(fs_st_dev, fs_st_ino);
296}
297
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000298error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000299 result.clear();
300
301 const char *pwd = ::getenv("PWD");
302 llvm::sys::fs::file_status PWDStatus, DotStatus;
303 if (pwd && llvm::sys::path::is_absolute(pwd) &&
304 !llvm::sys::fs::status(pwd, PWDStatus) &&
305 !llvm::sys::fs::status(".", DotStatus) &&
306 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
307 result.append(pwd, pwd + strlen(pwd));
308 return error_code::success();
309 }
310
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000311#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000312 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000313#else
314// For GNU Hurd
315 result.reserve(1024);
316#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000317
Michael J. Spencer20daa282010-12-07 01:22:31 +0000318 while (true) {
319 if (::getcwd(result.data(), result.capacity()) == 0) {
320 // See if there was a real error.
321 if (errno != errc::not_enough_memory)
322 return error_code(errno, system_category());
323 // Otherwise there just wasn't enough space.
324 result.reserve(result.capacity() * 2);
325 } else
326 break;
327 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000328
329 result.set_size(strlen(result.data()));
David Blaikie18544b92012-02-09 19:24:12 +0000330 return error_code::success();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000331}
332
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000333error_code create_directory(const Twine &path, bool IgnoreExisting) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000334 SmallString<128> path_storage;
335 StringRef p = path.toNullTerminatedStringRef(path_storage);
336
Michael J. Spencere5755be2010-12-07 01:23:29 +0000337 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000338 if (errno != errc::file_exists || !IgnoreExisting)
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000339 return error_code(errno, system_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000340 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000341
David Blaikie18544b92012-02-09 19:24:12 +0000342 return error_code::success();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000343}
344
Michael J. Spencere0c45602010-12-03 05:58:41 +0000345error_code create_hard_link(const Twine &to, const Twine &from) {
346 // Get arguments.
347 SmallString<128> from_storage;
348 SmallString<128> to_storage;
349 StringRef f = from.toNullTerminatedStringRef(from_storage);
350 StringRef t = to.toNullTerminatedStringRef(to_storage);
351
352 if (::link(t.begin(), f.begin()) == -1)
353 return error_code(errno, system_category());
354
David Blaikie18544b92012-02-09 19:24:12 +0000355 return error_code::success();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000356}
357
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000358error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000359 SmallString<128> path_storage;
360 StringRef p = path.toNullTerminatedStringRef(path_storage);
361
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000362 struct stat buf;
363 if (stat(p.begin(), &buf) != 0) {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000364 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000365 return error_code(errno, system_category());
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000366 return error_code::success();
367 }
368
369 // Note: this check catches strange situations. In all cases, LLVM should
370 // only be involved in the creation and deletion of regular files. This
371 // check ensures that what we're trying to erase is a regular file. It
372 // effectively prevents LLVM from erasing things like /dev/null, any block
373 // special file, or other things that aren't "regular" files.
374 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
375 return make_error_code(errc::operation_not_permitted);
376
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000377 if (::remove(p.begin()) == -1) {
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000378 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000379 return error_code(errno, system_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000380 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000381
David Blaikie18544b92012-02-09 19:24:12 +0000382 return error_code::success();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000383}
384
Michael J. Spencer409f5562010-12-03 17:53:55 +0000385error_code rename(const Twine &from, const Twine &to) {
386 // Get arguments.
387 SmallString<128> from_storage;
388 SmallString<128> to_storage;
389 StringRef f = from.toNullTerminatedStringRef(from_storage);
390 StringRef t = to.toNullTerminatedStringRef(to_storage);
391
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000392 if (::rename(f.begin(), t.begin()) == -1)
393 return error_code(errno, system_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000394
David Blaikie18544b92012-02-09 19:24:12 +0000395 return error_code::success();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000396}
397
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000398error_code resize_file(const Twine &path, uint64_t size) {
399 SmallString<128> path_storage;
400 StringRef p = path.toNullTerminatedStringRef(path_storage);
401
402 if (::truncate(p.begin(), size) == -1)
403 return error_code(errno, system_category());
404
David Blaikie18544b92012-02-09 19:24:12 +0000405 return error_code::success();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000406}
407
Michael J. Spencer45710402010-12-03 01:21:28 +0000408error_code exists(const Twine &path, bool &result) {
409 SmallString<128> path_storage;
410 StringRef p = path.toNullTerminatedStringRef(path_storage);
411
Benjamin Kramer172f8082012-06-02 16:28:09 +0000412 if (::access(p.begin(), F_OK) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000413 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer45710402010-12-03 01:21:28 +0000414 return error_code(errno, system_category());
415 result = false;
416 } else
417 result = true;
418
David Blaikie18544b92012-02-09 19:24:12 +0000419 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000420}
421
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000422bool can_write(const Twine &Path) {
423 SmallString<128> PathStorage;
424 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
425 return 0 == access(P.begin(), W_OK);
426}
427
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000428bool can_execute(const Twine &Path) {
429 SmallString<128> PathStorage;
430 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
431
Manuel Klimek52772bf2013-06-17 10:48:34 +0000432 if (0 != access(P.begin(), R_OK | X_OK))
433 return false;
434 struct stat buf;
435 if (0 != stat(P.begin(), &buf))
436 return false;
437 if (!S_ISREG(buf.st_mode))
438 return false;
439 return true;
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000440}
441
Michael J. Spencer203d7802011-12-12 06:04:28 +0000442bool equivalent(file_status A, file_status B) {
443 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000444 return A.fs_st_dev == B.fs_st_dev &&
445 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000446}
447
Michael J. Spencer376d3872010-12-03 18:49:13 +0000448error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000449 file_status fsA, fsB;
450 if (error_code ec = status(A, fsA)) return ec;
451 if (error_code ec = status(B, fsB)) return ec;
452 result = equivalent(fsA, fsB);
David Blaikie18544b92012-02-09 19:24:12 +0000453 return error_code::success();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000454}
455
Rafael Espindola77021c92013-07-16 03:20:13 +0000456static error_code fillStatus(int StatRet, const struct stat &Status,
457 file_status &Result) {
458 if (StatRet != 0) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000459 error_code ec(errno, system_category());
460 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000461 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000462 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000463 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000464 return ec;
465 }
466
Rafael Espindola9da91a02013-07-16 02:55:33 +0000467 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000468
Rafael Espindola77021c92013-07-16 03:20:13 +0000469 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000470 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000471 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000472 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000473 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000474 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000475 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000476 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000477 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000478 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000479 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000480 Type = file_type::socket_file;
481
Rafael Espindola77021c92013-07-16 03:20:13 +0000482 perms Perms = static_cast<perms>(Status.st_mode);
483 Result =
484 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
485 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000486
David Blaikie18544b92012-02-09 19:24:12 +0000487 return error_code::success();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000488}
489
Rafael Espindola77021c92013-07-16 03:20:13 +0000490error_code status(const Twine &Path, file_status &Result) {
491 SmallString<128> PathStorage;
492 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
493
494 struct stat Status;
495 int StatRet = ::stat(P.begin(), &Status);
496 return fillStatus(StatRet, Status, Result);
497}
498
499error_code status(int FD, file_status &Result) {
500 struct stat Status;
501 int StatRet = ::fstat(FD, &Status);
502 return fillStatus(StatRet, Status, Result);
503}
504
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000505error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000506#if defined(HAVE_FUTIMENS)
507 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000508 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000509 Times[0].tv_nsec = 0;
510 Times[1] = Times[0];
511 if (::futimens(FD, Times))
Alp Tokerb30f01e2013-12-11 15:42:33 +0000512 return error_code(errno, system_category());
513 return error_code::success();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000514#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000515 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000516 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000517 Times[0].tv_usec = 0;
518 Times[1] = Times[0];
519 if (::futimes(FD, Times))
520 return error_code(errno, system_category());
521 return error_code::success();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000522#else
523#warning Missing futimes() and futimens()
524 return make_error_code(errc::not_supported);
525#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000526}
527
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000528error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
529 AutoFD ScopedFD(FD);
530 if (!CloseFD)
531 ScopedFD.take();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000532
533 // Figure out how large the file is.
534 struct stat FileInfo;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000535 if (fstat(FD, &FileInfo) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000536 return error_code(errno, system_category());
537 uint64_t FileSize = FileInfo.st_size;
538
539 if (Size == 0)
540 Size = FileSize;
541 else if (FileSize < Size) {
542 // We need to grow the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000543 if (ftruncate(FD, Size) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000544 return error_code(errno, system_category());
545 }
546
547 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
548 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
549#ifdef MAP_FILE
550 flags |= MAP_FILE;
551#endif
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000552 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000553 if (Mapping == MAP_FAILED)
554 return error_code(errno, system_category());
555 return error_code::success();
556}
557
558mapped_file_region::mapped_file_region(const Twine &path,
559 mapmode mode,
560 uint64_t length,
561 uint64_t offset,
562 error_code &ec)
563 : Mode(mode)
564 , Size(length)
565 , Mapping() {
566 // Make sure that the requested size fits within SIZE_T.
567 if (length > std::numeric_limits<size_t>::max()) {
568 ec = make_error_code(errc::invalid_argument);
569 return;
570 }
571
572 SmallString<128> path_storage;
573 StringRef name = path.toNullTerminatedStringRef(path_storage);
574 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
575 int ofd = ::open(name.begin(), oflags);
576 if (ofd == -1) {
577 ec = error_code(errno, system_category());
578 return;
579 }
580
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000581 ec = init(ofd, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000582 if (ec)
583 Mapping = 0;
584}
585
586mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000587 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000588 mapmode mode,
589 uint64_t length,
590 uint64_t offset,
591 error_code &ec)
592 : Mode(mode)
593 , Size(length)
594 , Mapping() {
595 // Make sure that the requested size fits within SIZE_T.
596 if (length > std::numeric_limits<size_t>::max()) {
597 ec = make_error_code(errc::invalid_argument);
598 return;
599 }
600
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000601 ec = init(fd, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000602 if (ec)
603 Mapping = 0;
604}
605
606mapped_file_region::~mapped_file_region() {
607 if (Mapping)
608 ::munmap(Mapping, Size);
609}
610
Chandler Carruthf12e3a62012-11-30 11:45:22 +0000611#if LLVM_HAS_RVALUE_REFERENCES
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000612mapped_file_region::mapped_file_region(mapped_file_region &&other)
613 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
614 other.Mapping = 0;
615}
616#endif
617
618mapped_file_region::mapmode mapped_file_region::flags() const {
619 assert(Mapping && "Mapping failed but used anyway!");
620 return Mode;
621}
622
623uint64_t mapped_file_region::size() const {
624 assert(Mapping && "Mapping failed but used anyway!");
625 return Size;
626}
627
628char *mapped_file_region::data() const {
629 assert(Mapping && "Mapping failed but used anyway!");
Alp Tokerf907b892013-12-05 05:44:44 +0000630 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000631 return reinterpret_cast<char*>(Mapping);
632}
633
634const char *mapped_file_region::const_data() const {
635 assert(Mapping && "Mapping failed but used anyway!");
636 return reinterpret_cast<const char*>(Mapping);
637}
638
639int mapped_file_region::alignment() {
Chandler Carruthacd64be2012-12-31 23:31:56 +0000640 return process::get_self()->page_size();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000641}
642
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000643error_code detail::directory_iterator_construct(detail::DirIterState &it,
644 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000645 SmallString<128> path_null(path);
646 DIR *directory = ::opendir(path_null.c_str());
647 if (directory == 0)
648 return error_code(errno, system_category());
649
650 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
651 // Add something for replace_filename to replace.
652 path::append(path_null, ".");
653 it.CurrentEntry = directory_entry(path_null.str());
654 return directory_iterator_increment(it);
655}
656
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000657error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000658 if (it.IterationHandle)
659 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
660 it.IterationHandle = 0;
661 it.CurrentEntry = directory_entry();
David Blaikie18544b92012-02-09 19:24:12 +0000662 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000663}
664
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000665error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000666 errno = 0;
667 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
668 if (cur_dir == 0 && errno != 0) {
669 return error_code(errno, system_category());
670 } else if (cur_dir != 0) {
671 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
672 if ((name.size() == 1 && name[0] == '.') ||
673 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
674 return directory_iterator_increment(it);
675 it.CurrentEntry.replace_filename(name);
676 } else
677 return directory_iterator_destruct(it);
678
David Blaikie18544b92012-02-09 19:24:12 +0000679 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000680}
681
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000682error_code get_magic(const Twine &path, uint32_t len,
683 SmallVectorImpl<char> &result) {
684 SmallString<128> PathStorage;
685 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
686 result.set_size(0);
687
688 // Open path.
689 std::FILE *file = std::fopen(Path.data(), "rb");
690 if (file == 0)
691 return error_code(errno, system_category());
692
693 // Reserve storage.
694 result.reserve(len);
695
696 // Read magic!
697 size_t size = std::fread(result.data(), 1, len, file);
698 if (std::ferror(file) != 0) {
699 std::fclose(file);
700 return error_code(errno, system_category());
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000701 } else if (size != len) {
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000702 if (std::feof(file) != 0) {
703 std::fclose(file);
704 result.set_size(size);
705 return make_error_code(errc::value_too_large);
706 }
707 }
708 std::fclose(file);
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000709 result.set_size(size);
David Blaikie18544b92012-02-09 19:24:12 +0000710 return error_code::success();
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000711}
712
Nick Kledzik18497e92012-06-20 00:28:54 +0000713error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
714 bool map_writable, void *&result) {
715 SmallString<128> path_storage;
716 StringRef name = path.toNullTerminatedStringRef(path_storage);
717 int oflags = map_writable ? O_RDWR : O_RDONLY;
718 int ofd = ::open(name.begin(), oflags);
719 if ( ofd == -1 )
720 return error_code(errno, system_category());
721 AutoFD fd(ofd);
722 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
723 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
724#ifdef MAP_FILE
725 flags |= MAP_FILE;
726#endif
727 result = ::mmap(0, size, prot, flags, fd, file_offset);
728 if (result == MAP_FAILED) {
729 return error_code(errno, system_category());
730 }
731
732 return error_code::success();
733}
734
735error_code unmap_file_pages(void *base, size_t size) {
736 if ( ::munmap(base, size) == -1 )
737 return error_code(errno, system_category());
738
739 return error_code::success();
740}
741
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000742error_code openFileForRead(const Twine &Name, int &ResultFD) {
743 SmallString<128> Storage;
744 StringRef P = Name.toNullTerminatedStringRef(Storage);
745 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
746 if (errno != EINTR)
747 return error_code(errno, system_category());
748 }
749 return error_code::success();
750}
Nick Kledzik18497e92012-06-20 00:28:54 +0000751
Rafael Espindola67080ce2013-07-19 15:02:03 +0000752error_code openFileForWrite(const Twine &Name, int &ResultFD,
753 sys::fs::OpenFlags Flags, unsigned Mode) {
754 // Verify that we don't have both "append" and "excl".
755 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
756 "Cannot specify both 'excl' and 'append' file creation flags!");
757
758 int OpenFlags = O_WRONLY | O_CREAT;
759
760 if (Flags & F_Append)
761 OpenFlags |= O_APPEND;
762 else
763 OpenFlags |= O_TRUNC;
764
765 if (Flags & F_Excl)
766 OpenFlags |= O_EXCL;
767
768 SmallString<128> Storage;
769 StringRef P = Name.toNullTerminatedStringRef(Storage);
770 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
771 if (errno != EINTR)
772 return error_code(errno, system_category());
773 }
774 return error_code::success();
775}
776
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000777} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000778
779namespace path {
780
781bool home_directory(SmallVectorImpl<char> &result) {
782 if (char *RequestedDir = getenv("HOME")) {
783 result.clear();
784 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
785 return true;
786 }
787
788 return false;
789}
790
791} // end namespace path
792
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000793} // end namespace sys
794} // end namespace llvm