blob: 84a5751203e00d353fe256537f65e452f534bfa2 [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 };
Michael J. Spencer45710402010-12-03 01:21:28 +000088
89 error_code TempDir(SmallVectorImpl<char> &result) {
90 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
91 const char *dir = 0;
92 (dir = std::getenv("TMPDIR" )) ||
93 (dir = std::getenv("TMP" )) ||
94 (dir = std::getenv("TEMP" )) ||
95 (dir = std::getenv("TEMPDIR")) ||
96#ifdef P_tmpdir
97 (dir = P_tmpdir) ||
98#endif
99 (dir = "/tmp");
100
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000101 result.clear();
Michael J. Spencer45710402010-12-03 01:21:28 +0000102 StringRef d(dir);
103 result.append(d.begin(), d.end());
David Blaikie18544b92012-02-09 19:24:12 +0000104 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000105 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000106}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000107
Rafael Espindolae79a8722013-06-28 03:48:47 +0000108static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
109 SmallVectorImpl<char> &ResultPath,
110 bool MakeAbsolute, unsigned Mode,
111 FSEntity Type) {
112 SmallString<128> ModelStorage;
113 Model.toVector(ModelStorage);
114
115 if (MakeAbsolute) {
116 // Make model absolute by prepending a temp directory if it's not already.
117 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
118 if (!absolute) {
119 SmallString<128> TDir;
120 if (error_code ec = TempDir(TDir)) return ec;
121 sys::path::append(TDir, Twine(ModelStorage));
122 ModelStorage.swap(TDir);
123 }
124 }
125
126 // From here on, DO NOT modify model. It may be needed if the randomly chosen
127 // path already exists.
128 ResultPath = ModelStorage;
129 // Null terminate.
130 ResultPath.push_back(0);
131 ResultPath.pop_back();
132
133retry_random_path:
134 // Replace '%' with random chars.
135 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
136 if (ModelStorage[i] == '%')
137 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
138 }
139
140 // Try to open + create the file.
141 switch (Type) {
142 case FS_File: {
143 int RandomFD = ::open(ResultPath.begin(), O_RDWR | O_CREAT | O_EXCL, Mode);
144 if (RandomFD == -1) {
145 int SavedErrno = errno;
146 // If the file existed, try again, otherwise, error.
147 if (SavedErrno == errc::file_exists)
148 goto retry_random_path;
149 return error_code(SavedErrno, system_category());
150 }
151
152 ResultFD = RandomFD;
153 return error_code::success();
154 }
155
156 case FS_Name: {
157 bool Exists;
158 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
159 if (EC)
160 return EC;
161 if (Exists)
162 goto retry_random_path;
163 return error_code::success();
164 }
165
166 case FS_Dir: {
167 bool Existed;
168 error_code EC = sys::fs::create_directory(ResultPath.begin(), Existed);
169 if (EC)
170 return EC;
171 if (Existed)
172 goto retry_random_path;
173 return error_code::success();
174 }
175 }
Patrik Hagglunddcc336b2013-06-28 06:54:05 +0000176 llvm_unreachable("Invalid Type");
Rafael Espindolae79a8722013-06-28 03:48:47 +0000177}
178
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000179namespace llvm {
180namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000181namespace fs {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000182#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
183 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000184 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000185static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000186test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
187{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000188 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000189 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000190
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000191 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
192 if (realpath(fullpath, ret) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000193 return (1);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000194 if (stat(fullpath, &sb) != 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000195 return (1);
196
197 return (0);
198}
199
200static char *
201getprogpath(char ret[PATH_MAX], const char *bin)
202{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000203 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000204
205 /* First approach: absolute path. */
206 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000207 if (test_dir(ret, "/", bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000208 return (ret);
209 return (NULL);
210 }
211
212 /* Second approach: relative path. */
213 if (strchr(bin, '/') != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000214 char cwd[PATH_MAX];
215 if (getcwd(cwd, PATH_MAX) == NULL)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000216 return (NULL);
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000217 if (test_dir(ret, cwd, bin) == 0)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000218 return (ret);
219 return (NULL);
220 }
221
222 /* Third approach: $PATH */
223 if ((pv = getenv("PATH")) == NULL)
224 return (NULL);
225 s = pv = strdup(pv);
226 if (pv == NULL)
227 return (NULL);
228 while ((t = strsep(&s, ":")) != NULL) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000229 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000230 free(pv);
231 return (ret);
232 }
233 }
234 free(pv);
235 return (NULL);
236}
237#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
238
239/// GetMainExecutable - Return the path to the main executable, given the
240/// value of argv[0] from program startup.
241std::string getMainExecutable(const char *argv0, void *MainAddr) {
242#if defined(__APPLE__)
243 // On OS X the executable path is saved to the stack by dyld. Reading it
244 // from there is much faster than calling dladdr, especially for large
245 // binaries with symbols.
246 char exe_path[MAXPATHLEN];
247 uint32_t size = sizeof(exe_path);
248 if (_NSGetExecutablePath(exe_path, &size) == 0) {
249 char link_path[MAXPATHLEN];
250 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000251 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000252 }
253#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000254 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
255 defined(__FreeBSD_kernel__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000256 char exe_path[PATH_MAX];
257
258 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000259 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000260#elif defined(__linux__) || defined(__CYGWIN__)
261 char exe_path[MAXPATHLEN];
262 StringRef aPath("/proc/self/exe");
263 if (sys::fs::exists(aPath)) {
264 // /proc is not always mounted under Linux (chroot for example).
265 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
266 if (len >= 0)
267 return StringRef(exe_path, len);
268 } else {
269 // Fall back to the classical detection.
270 if (getprogpath(exe_path, argv0) != NULL)
271 return exe_path;
272 }
273#elif defined(HAVE_DLFCN_H)
274 // Use dladdr to get executable path if available.
275 Dl_info DLInfo;
276 int err = dladdr(MainAddr, &DLInfo);
277 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000278 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000279
280 // If the filename is a symlink, we need to resolve and return the location of
281 // the actual executable.
282 char link_path[MAXPATHLEN];
283 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000284 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000285#else
286#error GetMainExecutable is not implemented on this host yet.
287#endif
288 return "";
289}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000290
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000291TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000292 TimeValue Ret;
293 Ret.fromEpochTime(fs_st_mtime);
294 return Ret;
295}
296
Rafael Espindolad1230992013-07-29 21:55:38 +0000297UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000298 return UniqueID(fs_st_dev, fs_st_ino);
299}
300
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000301error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000302 result.clear();
303
304 const char *pwd = ::getenv("PWD");
305 llvm::sys::fs::file_status PWDStatus, DotStatus;
306 if (pwd && llvm::sys::path::is_absolute(pwd) &&
307 !llvm::sys::fs::status(pwd, PWDStatus) &&
308 !llvm::sys::fs::status(".", DotStatus) &&
309 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
310 result.append(pwd, pwd + strlen(pwd));
311 return error_code::success();
312 }
313
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000314#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000315 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000316#else
317// For GNU Hurd
318 result.reserve(1024);
319#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000320
Michael J. Spencer20daa282010-12-07 01:22:31 +0000321 while (true) {
322 if (::getcwd(result.data(), result.capacity()) == 0) {
323 // See if there was a real error.
324 if (errno != errc::not_enough_memory)
325 return error_code(errno, system_category());
326 // Otherwise there just wasn't enough space.
327 result.reserve(result.capacity() * 2);
328 } else
329 break;
330 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000331
332 result.set_size(strlen(result.data()));
David Blaikie18544b92012-02-09 19:24:12 +0000333 return error_code::success();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000334}
335
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000336error_code create_directory(const Twine &path, bool &existed) {
337 SmallString<128> path_storage;
338 StringRef p = path.toNullTerminatedStringRef(path_storage);
339
Michael J. Spencere5755be2010-12-07 01:23:29 +0000340 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000341 if (errno != errc::file_exists)
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000342 return error_code(errno, system_category());
343 existed = true;
344 } else
345 existed = false;
346
David Blaikie18544b92012-02-09 19:24:12 +0000347 return error_code::success();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000348}
349
Michael J. Spencere0c45602010-12-03 05:58:41 +0000350error_code create_hard_link(const Twine &to, const Twine &from) {
351 // Get arguments.
352 SmallString<128> from_storage;
353 SmallString<128> to_storage;
354 StringRef f = from.toNullTerminatedStringRef(from_storage);
355 StringRef t = to.toNullTerminatedStringRef(to_storage);
356
357 if (::link(t.begin(), f.begin()) == -1)
358 return error_code(errno, system_category());
359
David Blaikie18544b92012-02-09 19:24:12 +0000360 return error_code::success();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000361}
362
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000363error_code create_symlink(const Twine &to, const Twine &from) {
364 // Get arguments.
365 SmallString<128> from_storage;
366 SmallString<128> to_storage;
367 StringRef f = from.toNullTerminatedStringRef(from_storage);
368 StringRef t = to.toNullTerminatedStringRef(to_storage);
369
370 if (::symlink(t.begin(), f.begin()) == -1)
371 return error_code(errno, system_category());
372
David Blaikie18544b92012-02-09 19:24:12 +0000373 return error_code::success();
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000374}
375
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000376error_code remove(const Twine &path, bool &existed) {
377 SmallString<128> path_storage;
378 StringRef p = path.toNullTerminatedStringRef(path_storage);
379
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000380 struct stat buf;
381 if (stat(p.begin(), &buf) != 0) {
382 if (errno != errc::no_such_file_or_directory)
383 return error_code(errno, system_category());
384 existed = false;
385 return error_code::success();
386 }
387
388 // Note: this check catches strange situations. In all cases, LLVM should
389 // only be involved in the creation and deletion of regular files. This
390 // check ensures that what we're trying to erase is a regular file. It
391 // effectively prevents LLVM from erasing things like /dev/null, any block
392 // special file, or other things that aren't "regular" files.
393 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
394 return make_error_code(errc::operation_not_permitted);
395
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000396 if (::remove(p.begin()) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000397 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000398 return error_code(errno, system_category());
399 existed = false;
400 } else
401 existed = true;
402
David Blaikie18544b92012-02-09 19:24:12 +0000403 return error_code::success();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000404}
405
Michael J. Spencer409f5562010-12-03 17:53:55 +0000406error_code rename(const Twine &from, const Twine &to) {
407 // Get arguments.
408 SmallString<128> from_storage;
409 SmallString<128> to_storage;
410 StringRef f = from.toNullTerminatedStringRef(from_storage);
411 StringRef t = to.toNullTerminatedStringRef(to_storage);
412
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000413 if (::rename(f.begin(), t.begin()) == -1)
414 return error_code(errno, system_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000415
David Blaikie18544b92012-02-09 19:24:12 +0000416 return error_code::success();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000417}
418
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000419error_code resize_file(const Twine &path, uint64_t size) {
420 SmallString<128> path_storage;
421 StringRef p = path.toNullTerminatedStringRef(path_storage);
422
423 if (::truncate(p.begin(), size) == -1)
424 return error_code(errno, system_category());
425
David Blaikie18544b92012-02-09 19:24:12 +0000426 return error_code::success();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000427}
428
Michael J. Spencer45710402010-12-03 01:21:28 +0000429error_code exists(const Twine &path, bool &result) {
430 SmallString<128> path_storage;
431 StringRef p = path.toNullTerminatedStringRef(path_storage);
432
Benjamin Kramer172f8082012-06-02 16:28:09 +0000433 if (::access(p.begin(), F_OK) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000434 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer45710402010-12-03 01:21:28 +0000435 return error_code(errno, system_category());
436 result = false;
437 } else
438 result = true;
439
David Blaikie18544b92012-02-09 19:24:12 +0000440 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000441}
442
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000443bool can_write(const Twine &Path) {
444 SmallString<128> PathStorage;
445 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
446 return 0 == access(P.begin(), W_OK);
447}
448
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000449bool can_execute(const Twine &Path) {
450 SmallString<128> PathStorage;
451 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
452
Manuel Klimek52772bf2013-06-17 10:48:34 +0000453 if (0 != access(P.begin(), R_OK | X_OK))
454 return false;
455 struct stat buf;
456 if (0 != stat(P.begin(), &buf))
457 return false;
458 if (!S_ISREG(buf.st_mode))
459 return false;
460 return true;
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000461}
462
Michael J. Spencer203d7802011-12-12 06:04:28 +0000463bool equivalent(file_status A, file_status B) {
464 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000465 return A.fs_st_dev == B.fs_st_dev &&
466 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000467}
468
Michael J. Spencer376d3872010-12-03 18:49:13 +0000469error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000470 file_status fsA, fsB;
471 if (error_code ec = status(A, fsA)) return ec;
472 if (error_code ec = status(B, fsB)) return ec;
473 result = equivalent(fsA, fsB);
David Blaikie18544b92012-02-09 19:24:12 +0000474 return error_code::success();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000475}
476
Rafael Espindola77021c92013-07-16 03:20:13 +0000477static error_code fillStatus(int StatRet, const struct stat &Status,
478 file_status &Result) {
479 if (StatRet != 0) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000480 error_code ec(errno, system_category());
481 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000482 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000483 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000484 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000485 return ec;
486 }
487
Rafael Espindola9da91a02013-07-16 02:55:33 +0000488 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000489
Rafael Espindola77021c92013-07-16 03:20:13 +0000490 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000491 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000492 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000493 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000494 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000495 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000496 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000497 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000498 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000499 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000500 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000501 Type = file_type::socket_file;
502
Rafael Espindola77021c92013-07-16 03:20:13 +0000503 perms Perms = static_cast<perms>(Status.st_mode);
504 Result =
505 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
506 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000507
David Blaikie18544b92012-02-09 19:24:12 +0000508 return error_code::success();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000509}
510
Rafael Espindola77021c92013-07-16 03:20:13 +0000511error_code status(const Twine &Path, file_status &Result) {
512 SmallString<128> PathStorage;
513 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
514
515 struct stat Status;
516 int StatRet = ::stat(P.begin(), &Status);
517 return fillStatus(StatRet, Status, Result);
518}
519
520error_code status(int FD, file_status &Result) {
521 struct stat Status;
522 int StatRet = ::fstat(FD, &Status);
523 return fillStatus(StatRet, Status, Result);
524}
525
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000526error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000527#if defined(HAVE_FUTIMENS)
528 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000529 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000530 Times[0].tv_nsec = 0;
531 Times[1] = Times[0];
532 if (::futimens(FD, Times))
Alp Tokerb30f01e2013-12-11 15:42:33 +0000533 return error_code(errno, system_category());
534 return error_code::success();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000535#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000536 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000537 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000538 Times[0].tv_usec = 0;
539 Times[1] = Times[0];
540 if (::futimes(FD, Times))
541 return error_code(errno, system_category());
542 return error_code::success();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000543#else
544#warning Missing futimes() and futimens()
545 return make_error_code(errc::not_supported);
546#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000547}
548
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000549error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
550 AutoFD ScopedFD(FD);
551 if (!CloseFD)
552 ScopedFD.take();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000553
554 // Figure out how large the file is.
555 struct stat FileInfo;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000556 if (fstat(FD, &FileInfo) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000557 return error_code(errno, system_category());
558 uint64_t FileSize = FileInfo.st_size;
559
560 if (Size == 0)
561 Size = FileSize;
562 else if (FileSize < Size) {
563 // We need to grow the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000564 if (ftruncate(FD, Size) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000565 return error_code(errno, system_category());
566 }
567
568 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
569 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
570#ifdef MAP_FILE
571 flags |= MAP_FILE;
572#endif
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000573 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000574 if (Mapping == MAP_FAILED)
575 return error_code(errno, system_category());
576 return error_code::success();
577}
578
579mapped_file_region::mapped_file_region(const Twine &path,
580 mapmode mode,
581 uint64_t length,
582 uint64_t offset,
583 error_code &ec)
584 : Mode(mode)
585 , Size(length)
586 , Mapping() {
587 // Make sure that the requested size fits within SIZE_T.
588 if (length > std::numeric_limits<size_t>::max()) {
589 ec = make_error_code(errc::invalid_argument);
590 return;
591 }
592
593 SmallString<128> path_storage;
594 StringRef name = path.toNullTerminatedStringRef(path_storage);
595 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
596 int ofd = ::open(name.begin(), oflags);
597 if (ofd == -1) {
598 ec = error_code(errno, system_category());
599 return;
600 }
601
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000602 ec = init(ofd, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000603 if (ec)
604 Mapping = 0;
605}
606
607mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000608 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000609 mapmode mode,
610 uint64_t length,
611 uint64_t offset,
612 error_code &ec)
613 : Mode(mode)
614 , Size(length)
615 , Mapping() {
616 // Make sure that the requested size fits within SIZE_T.
617 if (length > std::numeric_limits<size_t>::max()) {
618 ec = make_error_code(errc::invalid_argument);
619 return;
620 }
621
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000622 ec = init(fd, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000623 if (ec)
624 Mapping = 0;
625}
626
627mapped_file_region::~mapped_file_region() {
628 if (Mapping)
629 ::munmap(Mapping, Size);
630}
631
Chandler Carruthf12e3a62012-11-30 11:45:22 +0000632#if LLVM_HAS_RVALUE_REFERENCES
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000633mapped_file_region::mapped_file_region(mapped_file_region &&other)
634 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
635 other.Mapping = 0;
636}
637#endif
638
639mapped_file_region::mapmode mapped_file_region::flags() const {
640 assert(Mapping && "Mapping failed but used anyway!");
641 return Mode;
642}
643
644uint64_t mapped_file_region::size() const {
645 assert(Mapping && "Mapping failed but used anyway!");
646 return Size;
647}
648
649char *mapped_file_region::data() const {
650 assert(Mapping && "Mapping failed but used anyway!");
Alp Tokerf907b892013-12-05 05:44:44 +0000651 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000652 return reinterpret_cast<char*>(Mapping);
653}
654
655const char *mapped_file_region::const_data() const {
656 assert(Mapping && "Mapping failed but used anyway!");
657 return reinterpret_cast<const char*>(Mapping);
658}
659
660int mapped_file_region::alignment() {
Chandler Carruthacd64be2012-12-31 23:31:56 +0000661 return process::get_self()->page_size();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000662}
663
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000664error_code detail::directory_iterator_construct(detail::DirIterState &it,
665 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000666 SmallString<128> path_null(path);
667 DIR *directory = ::opendir(path_null.c_str());
668 if (directory == 0)
669 return error_code(errno, system_category());
670
671 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
672 // Add something for replace_filename to replace.
673 path::append(path_null, ".");
674 it.CurrentEntry = directory_entry(path_null.str());
675 return directory_iterator_increment(it);
676}
677
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000678error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000679 if (it.IterationHandle)
680 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
681 it.IterationHandle = 0;
682 it.CurrentEntry = directory_entry();
David Blaikie18544b92012-02-09 19:24:12 +0000683 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000684}
685
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000686error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000687 errno = 0;
688 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
689 if (cur_dir == 0 && errno != 0) {
690 return error_code(errno, system_category());
691 } else if (cur_dir != 0) {
692 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
693 if ((name.size() == 1 && name[0] == '.') ||
694 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
695 return directory_iterator_increment(it);
696 it.CurrentEntry.replace_filename(name);
697 } else
698 return directory_iterator_destruct(it);
699
David Blaikie18544b92012-02-09 19:24:12 +0000700 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000701}
702
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000703error_code get_magic(const Twine &path, uint32_t len,
704 SmallVectorImpl<char> &result) {
705 SmallString<128> PathStorage;
706 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
707 result.set_size(0);
708
709 // Open path.
710 std::FILE *file = std::fopen(Path.data(), "rb");
711 if (file == 0)
712 return error_code(errno, system_category());
713
714 // Reserve storage.
715 result.reserve(len);
716
717 // Read magic!
718 size_t size = std::fread(result.data(), 1, len, file);
719 if (std::ferror(file) != 0) {
720 std::fclose(file);
721 return error_code(errno, system_category());
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000722 } else if (size != len) {
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000723 if (std::feof(file) != 0) {
724 std::fclose(file);
725 result.set_size(size);
726 return make_error_code(errc::value_too_large);
727 }
728 }
729 std::fclose(file);
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000730 result.set_size(size);
David Blaikie18544b92012-02-09 19:24:12 +0000731 return error_code::success();
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000732}
733
Nick Kledzik18497e92012-06-20 00:28:54 +0000734error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
735 bool map_writable, void *&result) {
736 SmallString<128> path_storage;
737 StringRef name = path.toNullTerminatedStringRef(path_storage);
738 int oflags = map_writable ? O_RDWR : O_RDONLY;
739 int ofd = ::open(name.begin(), oflags);
740 if ( ofd == -1 )
741 return error_code(errno, system_category());
742 AutoFD fd(ofd);
743 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
744 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
745#ifdef MAP_FILE
746 flags |= MAP_FILE;
747#endif
748 result = ::mmap(0, size, prot, flags, fd, file_offset);
749 if (result == MAP_FAILED) {
750 return error_code(errno, system_category());
751 }
752
753 return error_code::success();
754}
755
756error_code unmap_file_pages(void *base, size_t size) {
757 if ( ::munmap(base, size) == -1 )
758 return error_code(errno, system_category());
759
760 return error_code::success();
761}
762
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000763error_code openFileForRead(const Twine &Name, int &ResultFD) {
764 SmallString<128> Storage;
765 StringRef P = Name.toNullTerminatedStringRef(Storage);
766 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
767 if (errno != EINTR)
768 return error_code(errno, system_category());
769 }
770 return error_code::success();
771}
Nick Kledzik18497e92012-06-20 00:28:54 +0000772
Rafael Espindola67080ce2013-07-19 15:02:03 +0000773error_code openFileForWrite(const Twine &Name, int &ResultFD,
774 sys::fs::OpenFlags Flags, unsigned Mode) {
775 // Verify that we don't have both "append" and "excl".
776 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
777 "Cannot specify both 'excl' and 'append' file creation flags!");
778
779 int OpenFlags = O_WRONLY | O_CREAT;
780
781 if (Flags & F_Append)
782 OpenFlags |= O_APPEND;
783 else
784 OpenFlags |= O_TRUNC;
785
786 if (Flags & F_Excl)
787 OpenFlags |= O_EXCL;
788
789 SmallString<128> Storage;
790 StringRef P = Name.toNullTerminatedStringRef(Storage);
791 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
792 if (errno != EINTR)
793 return error_code(errno, system_category());
794 }
795 return error_code::success();
796}
797
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000798} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000799
800namespace path {
801
802bool home_directory(SmallVectorImpl<char> &result) {
803 if (char *RequestedDir = getenv("HOME")) {
804 result.clear();
805 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
806 return true;
807 }
808
809 return false;
810}
811
812} // end namespace path
813
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000814} // end namespace sys
815} // end namespace llvm