blob: 8a94b935993e62351b018d820d130b77d7b5dd47 [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"
Daniel Dunbar3f0fa192012-05-05 16:36:24 +000020#include "llvm/Support/Process.h"
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000021#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
Nick Kledzik18497e92012-06-20 00:28:54 +000027#ifdef HAVE_SYS_MMAN_H
28#include <sys/mman.h>
29#endif
Michael J. Spencer52714862011-01-05 16:38:57 +000030#if HAVE_DIRENT_H
31# include <dirent.h>
32# define NAMLEN(dirent) strlen((dirent)->d_name)
33#else
34# define dirent direct
35# define NAMLEN(dirent) (dirent)->d_namlen
36# if HAVE_SYS_NDIR_H
37# include <sys/ndir.h>
38# endif
39# if HAVE_SYS_DIR_H
40# include <sys/dir.h>
41# endif
42# if HAVE_NDIR_H
43# include <ndir.h>
44# endif
45#endif
Michael J. Spencer45710402010-12-03 01:21:28 +000046#if HAVE_STDIO_H
47#include <stdio.h>
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000048#endif
Bill Wendlingbdaa57f2011-09-14 21:49:42 +000049#if HAVE_LIMITS_H
50#include <limits.h>
51#endif
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000052
Rafael Espindola4601c462013-06-26 05:25:44 +000053#ifdef __APPLE__
54#include <mach-o/dyld.h>
55#endif
56
Joerg Sonnenbergerc0697302012-08-10 10:56:09 +000057// Both stdio.h and cstdio are included via different pathes and
58// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
59// either.
60#undef ferror
61#undef feof
62
Sylvestre Ledru14ada942012-04-11 15:35:36 +000063// For GNU Hurd
64#if defined(__GNU__) && !defined(PATH_MAX)
65# define PATH_MAX 4096
66#endif
67
Michael J. Spencer45710402010-12-03 01:21:28 +000068using namespace llvm;
69
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000070namespace {
Michael J. Spencer5529c572010-12-07 01:23:08 +000071 /// This class automatically closes the given file descriptor when it goes out
72 /// of scope. You can take back explicit ownership of the file descriptor by
73 /// calling take(). The destructor does not verify that close was successful.
74 /// Therefore, never allow this class to call close on a file descriptor that
75 /// has been read from or written to.
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000076 struct AutoFD {
77 int FileDescriptor;
78
79 AutoFD(int fd) : FileDescriptor(fd) {}
80 ~AutoFD() {
81 if (FileDescriptor >= 0)
82 ::close(FileDescriptor);
83 }
84
85 int take() {
86 int ret = FileDescriptor;
87 FileDescriptor = -1;
88 return ret;
89 }
90
91 operator int() const {return FileDescriptor;}
92 };
Michael J. Spencer45710402010-12-03 01:21:28 +000093
94 error_code TempDir(SmallVectorImpl<char> &result) {
95 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
96 const char *dir = 0;
97 (dir = std::getenv("TMPDIR" )) ||
98 (dir = std::getenv("TMP" )) ||
99 (dir = std::getenv("TEMP" )) ||
100 (dir = std::getenv("TEMPDIR")) ||
101#ifdef P_tmpdir
102 (dir = P_tmpdir) ||
103#endif
104 (dir = "/tmp");
105
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000106 result.clear();
Michael J. Spencer45710402010-12-03 01:21:28 +0000107 StringRef d(dir);
108 result.append(d.begin(), d.end());
David Blaikie18544b92012-02-09 19:24:12 +0000109 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000110 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000111}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000112
Rafael Espindolae79a8722013-06-28 03:48:47 +0000113static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
114 SmallVectorImpl<char> &ResultPath,
115 bool MakeAbsolute, unsigned Mode,
116 FSEntity Type) {
117 SmallString<128> ModelStorage;
118 Model.toVector(ModelStorage);
119
120 if (MakeAbsolute) {
121 // Make model absolute by prepending a temp directory if it's not already.
122 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
123 if (!absolute) {
124 SmallString<128> TDir;
125 if (error_code ec = TempDir(TDir)) return ec;
126 sys::path::append(TDir, Twine(ModelStorage));
127 ModelStorage.swap(TDir);
128 }
129 }
130
131 // From here on, DO NOT modify model. It may be needed if the randomly chosen
132 // path already exists.
133 ResultPath = ModelStorage;
134 // Null terminate.
135 ResultPath.push_back(0);
136 ResultPath.pop_back();
137
138retry_random_path:
139 // Replace '%' with random chars.
140 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
141 if (ModelStorage[i] == '%')
142 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
143 }
144
145 // Try to open + create the file.
146 switch (Type) {
147 case FS_File: {
148 int RandomFD = ::open(ResultPath.begin(), O_RDWR | O_CREAT | O_EXCL, Mode);
149 if (RandomFD == -1) {
150 int SavedErrno = errno;
151 // If the file existed, try again, otherwise, error.
152 if (SavedErrno == errc::file_exists)
153 goto retry_random_path;
154 return error_code(SavedErrno, system_category());
155 }
156
157 ResultFD = RandomFD;
158 return error_code::success();
159 }
160
161 case FS_Name: {
162 bool Exists;
163 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
164 if (EC)
165 return EC;
166 if (Exists)
167 goto retry_random_path;
168 return error_code::success();
169 }
170
171 case FS_Dir: {
172 bool Existed;
173 error_code EC = sys::fs::create_directory(ResultPath.begin(), Existed);
174 if (EC)
175 return EC;
176 if (Existed)
177 goto retry_random_path;
178 return error_code::success();
179 }
180 }
181}
182
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000183namespace llvm {
184namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000185namespace fs {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000186#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
187 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
188 defined(__linux__) || defined(__CYGWIN__)
189static int
190test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
191 const char *dir, const char *bin)
192{
193 struct stat sb;
194
195 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
196 if (realpath(buf, ret) == NULL)
197 return (1);
198 if (stat(buf, &sb) != 0)
199 return (1);
200
201 return (0);
202}
203
204static char *
205getprogpath(char ret[PATH_MAX], const char *bin)
206{
207 char *pv, *s, *t, buf[PATH_MAX];
208
209 /* First approach: absolute path. */
210 if (bin[0] == '/') {
211 if (test_dir(buf, ret, "/", bin) == 0)
212 return (ret);
213 return (NULL);
214 }
215
216 /* Second approach: relative path. */
217 if (strchr(bin, '/') != NULL) {
218 if (getcwd(buf, PATH_MAX) == NULL)
219 return (NULL);
220 if (test_dir(buf, ret, buf, bin) == 0)
221 return (ret);
222 return (NULL);
223 }
224
225 /* Third approach: $PATH */
226 if ((pv = getenv("PATH")) == NULL)
227 return (NULL);
228 s = pv = strdup(pv);
229 if (pv == NULL)
230 return (NULL);
231 while ((t = strsep(&s, ":")) != NULL) {
232 if (test_dir(buf, ret, t, bin) == 0) {
233 free(pv);
234 return (ret);
235 }
236 }
237 free(pv);
238 return (NULL);
239}
240#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
241
242/// GetMainExecutable - Return the path to the main executable, given the
243/// value of argv[0] from program startup.
244std::string getMainExecutable(const char *argv0, void *MainAddr) {
245#if defined(__APPLE__)
246 // On OS X the executable path is saved to the stack by dyld. Reading it
247 // from there is much faster than calling dladdr, especially for large
248 // binaries with symbols.
249 char exe_path[MAXPATHLEN];
250 uint32_t size = sizeof(exe_path);
251 if (_NSGetExecutablePath(exe_path, &size) == 0) {
252 char link_path[MAXPATHLEN];
253 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000254 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000255 }
256#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
257 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
258 char exe_path[PATH_MAX];
259
260 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000261 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000262#elif defined(__linux__) || defined(__CYGWIN__)
263 char exe_path[MAXPATHLEN];
264 StringRef aPath("/proc/self/exe");
265 if (sys::fs::exists(aPath)) {
266 // /proc is not always mounted under Linux (chroot for example).
267 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
268 if (len >= 0)
269 return StringRef(exe_path, len);
270 } else {
271 // Fall back to the classical detection.
272 if (getprogpath(exe_path, argv0) != NULL)
273 return exe_path;
274 }
275#elif defined(HAVE_DLFCN_H)
276 // Use dladdr to get executable path if available.
277 Dl_info DLInfo;
278 int err = dladdr(MainAddr, &DLInfo);
279 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000280 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000281
282 // If the filename is a symlink, we need to resolve and return the location of
283 // the actual executable.
284 char link_path[MAXPATHLEN];
285 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000286 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000287#else
288#error GetMainExecutable is not implemented on this host yet.
289#endif
290 return "";
291}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000292
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000293TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000294 TimeValue Ret;
295 Ret.fromEpochTime(fs_st_mtime);
296 return Ret;
297}
298
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000299error_code current_path(SmallVectorImpl<char> &result) {
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000300#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000301 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000302#else
303// For GNU Hurd
304 result.reserve(1024);
305#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000306
Michael J. Spencer20daa282010-12-07 01:22:31 +0000307 while (true) {
308 if (::getcwd(result.data(), result.capacity()) == 0) {
309 // See if there was a real error.
310 if (errno != errc::not_enough_memory)
311 return error_code(errno, system_category());
312 // Otherwise there just wasn't enough space.
313 result.reserve(result.capacity() * 2);
314 } else
315 break;
316 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000317
318 result.set_size(strlen(result.data()));
David Blaikie18544b92012-02-09 19:24:12 +0000319 return error_code::success();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000320}
321
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000322error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
323 // Get arguments.
324 SmallString<128> from_storage;
325 SmallString<128> to_storage;
Michael J. Spencer795adf52010-12-01 20:37:42 +0000326 StringRef f = from.toNullTerminatedStringRef(from_storage);
327 StringRef t = to.toNullTerminatedStringRef(to_storage);
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000328
329 const size_t buf_sz = 32768;
330 char buffer[buf_sz];
331 int from_file = -1, to_file = -1;
332
333 // Open from.
334 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
335 return error_code(errno, system_category());
336 AutoFD from_fd(from_file);
337
338 // Stat from.
339 struct stat from_stat;
340 if (::stat(f.begin(), &from_stat) != 0)
341 return error_code(errno, system_category());
342
343 // Setup to flags.
344 int to_flags = O_CREAT | O_WRONLY;
345 if (copt == copy_option::fail_if_exists)
346 to_flags |= O_EXCL;
347
348 // Open to.
349 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
350 return error_code(errno, system_category());
351 AutoFD to_fd(to_file);
352
353 // Copy!
354 ssize_t sz, sz_read = 1, sz_write;
355 while (sz_read > 0 &&
356 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
357 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
358 // Marc Rochkind, Addison-Wesley, 2004, page 94
359 sz_write = 0;
360 do {
361 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
362 sz_read = sz; // cause read loop termination.
363 break; // error.
364 }
365 sz_write += sz;
366 } while (sz_write < sz_read);
367 }
368
369 // After all the file operations above the return value of close actually
370 // matters.
371 if (::close(from_fd.take()) < 0) sz_read = -1;
372 if (::close(to_fd.take()) < 0) sz_read = -1;
373
374 // Check for errors.
375 if (sz_read < 0)
376 return error_code(errno, system_category());
377
David Blaikie18544b92012-02-09 19:24:12 +0000378 return error_code::success();
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000379}
380
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000381error_code create_directory(const Twine &path, bool &existed) {
382 SmallString<128> path_storage;
383 StringRef p = path.toNullTerminatedStringRef(path_storage);
384
Michael J. Spencere5755be2010-12-07 01:23:29 +0000385 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000386 if (errno != errc::file_exists)
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000387 return error_code(errno, system_category());
388 existed = true;
389 } else
390 existed = false;
391
David Blaikie18544b92012-02-09 19:24:12 +0000392 return error_code::success();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000393}
394
Michael J. Spencere0c45602010-12-03 05:58:41 +0000395error_code create_hard_link(const Twine &to, const Twine &from) {
396 // Get arguments.
397 SmallString<128> from_storage;
398 SmallString<128> to_storage;
399 StringRef f = from.toNullTerminatedStringRef(from_storage);
400 StringRef t = to.toNullTerminatedStringRef(to_storage);
401
402 if (::link(t.begin(), f.begin()) == -1)
403 return error_code(errno, system_category());
404
David Blaikie18544b92012-02-09 19:24:12 +0000405 return error_code::success();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000406}
407
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000408error_code create_symlink(const Twine &to, const Twine &from) {
409 // Get arguments.
410 SmallString<128> from_storage;
411 SmallString<128> to_storage;
412 StringRef f = from.toNullTerminatedStringRef(from_storage);
413 StringRef t = to.toNullTerminatedStringRef(to_storage);
414
415 if (::symlink(t.begin(), f.begin()) == -1)
416 return error_code(errno, system_category());
417
David Blaikie18544b92012-02-09 19:24:12 +0000418 return error_code::success();
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000419}
420
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000421error_code remove(const Twine &path, bool &existed) {
422 SmallString<128> path_storage;
423 StringRef p = path.toNullTerminatedStringRef(path_storage);
424
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000425 struct stat buf;
426 if (stat(p.begin(), &buf) != 0) {
427 if (errno != errc::no_such_file_or_directory)
428 return error_code(errno, system_category());
429 existed = false;
430 return error_code::success();
431 }
432
433 // Note: this check catches strange situations. In all cases, LLVM should
434 // only be involved in the creation and deletion of regular files. This
435 // check ensures that what we're trying to erase is a regular file. It
436 // effectively prevents LLVM from erasing things like /dev/null, any block
437 // special file, or other things that aren't "regular" files.
438 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
439 return make_error_code(errc::operation_not_permitted);
440
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000441 if (::remove(p.begin()) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000442 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000443 return error_code(errno, system_category());
444 existed = false;
445 } else
446 existed = true;
447
David Blaikie18544b92012-02-09 19:24:12 +0000448 return error_code::success();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000449}
450
Michael J. Spencer409f5562010-12-03 17:53:55 +0000451error_code rename(const Twine &from, const Twine &to) {
452 // Get arguments.
453 SmallString<128> from_storage;
454 SmallString<128> to_storage;
455 StringRef f = from.toNullTerminatedStringRef(from_storage);
456 StringRef t = to.toNullTerminatedStringRef(to_storage);
457
Michael J. Spencerec202ee2011-01-16 22:18:41 +0000458 if (::rename(f.begin(), t.begin()) == -1) {
459 // If it's a cross device link, copy then delete, otherwise return the error
460 if (errno == EXDEV) {
461 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
462 return ec;
463 bool Existed;
464 if (error_code ec = remove(from, Existed))
465 return ec;
466 } else
467 return error_code(errno, system_category());
468 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000469
David Blaikie18544b92012-02-09 19:24:12 +0000470 return error_code::success();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000471}
472
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000473error_code resize_file(const Twine &path, uint64_t size) {
474 SmallString<128> path_storage;
475 StringRef p = path.toNullTerminatedStringRef(path_storage);
476
477 if (::truncate(p.begin(), size) == -1)
478 return error_code(errno, system_category());
479
David Blaikie18544b92012-02-09 19:24:12 +0000480 return error_code::success();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000481}
482
Michael J. Spencer45710402010-12-03 01:21:28 +0000483error_code exists(const Twine &path, bool &result) {
484 SmallString<128> path_storage;
485 StringRef p = path.toNullTerminatedStringRef(path_storage);
486
Benjamin Kramer172f8082012-06-02 16:28:09 +0000487 if (::access(p.begin(), F_OK) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000488 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer45710402010-12-03 01:21:28 +0000489 return error_code(errno, system_category());
490 result = false;
491 } else
492 result = true;
493
David Blaikie18544b92012-02-09 19:24:12 +0000494 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000495}
496
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000497bool can_write(const Twine &Path) {
498 SmallString<128> PathStorage;
499 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
500 return 0 == access(P.begin(), W_OK);
501}
502
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000503bool can_execute(const Twine &Path) {
504 SmallString<128> PathStorage;
505 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
506
Manuel Klimek52772bf2013-06-17 10:48:34 +0000507 if (0 != access(P.begin(), R_OK | X_OK))
508 return false;
509 struct stat buf;
510 if (0 != stat(P.begin(), &buf))
511 return false;
512 if (!S_ISREG(buf.st_mode))
513 return false;
514 return true;
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000515}
516
Michael J. Spencer203d7802011-12-12 06:04:28 +0000517bool equivalent(file_status A, file_status B) {
518 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000519 return A.fs_st_dev == B.fs_st_dev &&
520 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000521}
522
Michael J. Spencer376d3872010-12-03 18:49:13 +0000523error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000524 file_status fsA, fsB;
525 if (error_code ec = status(A, fsA)) return ec;
526 if (error_code ec = status(B, fsB)) return ec;
527 result = equivalent(fsA, fsB);
David Blaikie18544b92012-02-09 19:24:12 +0000528 return error_code::success();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000529}
530
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000531error_code file_size(const Twine &path, uint64_t &result) {
532 SmallString<128> path_storage;
533 StringRef p = path.toNullTerminatedStringRef(path_storage);
534
535 struct stat status;
536 if (::stat(p.begin(), &status) == -1)
537 return error_code(errno, system_category());
538 if (!S_ISREG(status.st_mode))
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000539 return make_error_code(errc::operation_not_permitted);
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000540
541 result = status.st_size;
David Blaikie18544b92012-02-09 19:24:12 +0000542 return error_code::success();
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000543}
544
Rafael Espindola7cf7c512013-06-20 15:06:35 +0000545error_code getUniqueID(const Twine Path, uint64_t &Result) {
Rafael Espindola45e6c242013-06-18 19:34:49 +0000546 SmallString<128> Storage;
547 StringRef P = Path.toNullTerminatedStringRef(Storage);
548
549 struct stat Status;
550 if (::stat(P.begin(), &Status) != 0)
551 return error_code(errno, system_category());
552
553 Result = Status.st_ino;
554 return error_code::success();
555}
556
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000557error_code status(const Twine &path, file_status &result) {
558 SmallString<128> path_storage;
559 StringRef p = path.toNullTerminatedStringRef(path_storage);
560
561 struct stat status;
562 if (::stat(p.begin(), &status) != 0) {
563 error_code ec(errno, system_category());
564 if (ec == errc::no_such_file_or_directory)
565 result = file_status(file_type::file_not_found);
566 else
567 result = file_status(file_type::status_error);
568 return ec;
569 }
570
Nick Kledzik18497e92012-06-20 00:28:54 +0000571 perms prms = static_cast<perms>(status.st_mode & perms_mask);
572
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000573 if (S_ISDIR(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000574 result = file_status(file_type::directory_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000575 else if (S_ISREG(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000576 result = file_status(file_type::regular_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000577 else if (S_ISBLK(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000578 result = file_status(file_type::block_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000579 else if (S_ISCHR(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000580 result = file_status(file_type::character_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000581 else if (S_ISFIFO(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000582 result = file_status(file_type::fifo_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000583 else if (S_ISSOCK(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000584 result = file_status(file_type::socket_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000585 else
Nick Kledzik18497e92012-06-20 00:28:54 +0000586 result = file_status(file_type::type_unknown, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000587
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000588 result.fs_st_dev = status.st_dev;
589 result.fs_st_ino = status.st_ino;
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000590 result.fs_st_mtime = status.st_mtime;
Rafael Espindolae34d6a52013-06-20 22:02:10 +0000591 result.fs_st_uid = status.st_uid;
592 result.fs_st_gid = status.st_gid;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000593
David Blaikie18544b92012-02-09 19:24:12 +0000594 return error_code::success();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000595}
596
Nick Kledzik18497e92012-06-20 00:28:54 +0000597// Modifies permissions on a file.
598error_code permissions(const Twine &path, perms prms) {
599 if ((prms & add_perms) && (prms & remove_perms))
600 llvm_unreachable("add_perms and remove_perms are mutually exclusive");
601
602 // Get current permissions
Rafael Espindola1efb69c2013-06-20 22:07:53 +0000603 // FIXME: We only need this stat for add_perms and remove_perms.
Nick Kledzik18497e92012-06-20 00:28:54 +0000604 file_status info;
605 if (error_code ec = status(path, info)) {
606 return ec;
607 }
608
609 // Set updated permissions.
610 SmallString<128> path_storage;
611 StringRef p = path.toNullTerminatedStringRef(path_storage);
612 perms permsToSet;
613 if (prms & add_perms) {
614 permsToSet = (info.permissions() | prms) & perms_mask;
615 } else if (prms & remove_perms) {
616 permsToSet = (info.permissions() & ~prms) & perms_mask;
617 } else {
618 permsToSet = prms & perms_mask;
619 }
620 if (::chmod(p.begin(), static_cast<mode_t>(permsToSet))) {
621 return error_code(errno, system_category());
622 }
623
624 return error_code::success();
625}
626
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000627error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
628 timeval Times[2];
629 Times[0].tv_sec = Time.toPosixTime();
630 Times[0].tv_usec = 0;
631 Times[1] = Times[0];
632 if (::futimes(FD, Times))
633 return error_code(errno, system_category());
634 return error_code::success();
635}
636
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000637error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
638 AutoFD ScopedFD(FD);
639 if (!CloseFD)
640 ScopedFD.take();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000641
642 // Figure out how large the file is.
643 struct stat FileInfo;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000644 if (fstat(FD, &FileInfo) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000645 return error_code(errno, system_category());
646 uint64_t FileSize = FileInfo.st_size;
647
648 if (Size == 0)
649 Size = FileSize;
650 else if (FileSize < Size) {
651 // We need to grow the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000652 if (ftruncate(FD, Size) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000653 return error_code(errno, system_category());
654 }
655
656 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
657 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
658#ifdef MAP_FILE
659 flags |= MAP_FILE;
660#endif
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000661 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000662 if (Mapping == MAP_FAILED)
663 return error_code(errno, system_category());
664 return error_code::success();
665}
666
667mapped_file_region::mapped_file_region(const Twine &path,
668 mapmode mode,
669 uint64_t length,
670 uint64_t offset,
671 error_code &ec)
672 : Mode(mode)
673 , Size(length)
674 , Mapping() {
675 // Make sure that the requested size fits within SIZE_T.
676 if (length > std::numeric_limits<size_t>::max()) {
677 ec = make_error_code(errc::invalid_argument);
678 return;
679 }
680
681 SmallString<128> path_storage;
682 StringRef name = path.toNullTerminatedStringRef(path_storage);
683 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
684 int ofd = ::open(name.begin(), oflags);
685 if (ofd == -1) {
686 ec = error_code(errno, system_category());
687 return;
688 }
689
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000690 ec = init(ofd, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000691 if (ec)
692 Mapping = 0;
693}
694
695mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000696 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000697 mapmode mode,
698 uint64_t length,
699 uint64_t offset,
700 error_code &ec)
701 : Mode(mode)
702 , Size(length)
703 , Mapping() {
704 // Make sure that the requested size fits within SIZE_T.
705 if (length > std::numeric_limits<size_t>::max()) {
706 ec = make_error_code(errc::invalid_argument);
707 return;
708 }
709
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000710 ec = init(fd, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000711 if (ec)
712 Mapping = 0;
713}
714
715mapped_file_region::~mapped_file_region() {
716 if (Mapping)
717 ::munmap(Mapping, Size);
718}
719
Chandler Carruthf12e3a62012-11-30 11:45:22 +0000720#if LLVM_HAS_RVALUE_REFERENCES
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000721mapped_file_region::mapped_file_region(mapped_file_region &&other)
722 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
723 other.Mapping = 0;
724}
725#endif
726
727mapped_file_region::mapmode mapped_file_region::flags() const {
728 assert(Mapping && "Mapping failed but used anyway!");
729 return Mode;
730}
731
732uint64_t mapped_file_region::size() const {
733 assert(Mapping && "Mapping failed but used anyway!");
734 return Size;
735}
736
737char *mapped_file_region::data() const {
738 assert(Mapping && "Mapping failed but used anyway!");
739 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
740 return reinterpret_cast<char*>(Mapping);
741}
742
743const char *mapped_file_region::const_data() const {
744 assert(Mapping && "Mapping failed but used anyway!");
745 return reinterpret_cast<const char*>(Mapping);
746}
747
748int mapped_file_region::alignment() {
Chandler Carruthacd64be2012-12-31 23:31:56 +0000749 return process::get_self()->page_size();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000750}
751
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000752error_code detail::directory_iterator_construct(detail::DirIterState &it,
753 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000754 SmallString<128> path_null(path);
755 DIR *directory = ::opendir(path_null.c_str());
756 if (directory == 0)
757 return error_code(errno, system_category());
758
759 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
760 // Add something for replace_filename to replace.
761 path::append(path_null, ".");
762 it.CurrentEntry = directory_entry(path_null.str());
763 return directory_iterator_increment(it);
764}
765
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000766error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000767 if (it.IterationHandle)
768 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
769 it.IterationHandle = 0;
770 it.CurrentEntry = directory_entry();
David Blaikie18544b92012-02-09 19:24:12 +0000771 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000772}
773
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000774error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000775 errno = 0;
776 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
777 if (cur_dir == 0 && errno != 0) {
778 return error_code(errno, system_category());
779 } else if (cur_dir != 0) {
780 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
781 if ((name.size() == 1 && name[0] == '.') ||
782 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
783 return directory_iterator_increment(it);
784 it.CurrentEntry.replace_filename(name);
785 } else
786 return directory_iterator_destruct(it);
787
David Blaikie18544b92012-02-09 19:24:12 +0000788 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000789}
790
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000791error_code get_magic(const Twine &path, uint32_t len,
792 SmallVectorImpl<char> &result) {
793 SmallString<128> PathStorage;
794 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
795 result.set_size(0);
796
797 // Open path.
798 std::FILE *file = std::fopen(Path.data(), "rb");
799 if (file == 0)
800 return error_code(errno, system_category());
801
802 // Reserve storage.
803 result.reserve(len);
804
805 // Read magic!
806 size_t size = std::fread(result.data(), 1, len, file);
807 if (std::ferror(file) != 0) {
808 std::fclose(file);
809 return error_code(errno, system_category());
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000810 } else if (size != len) {
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000811 if (std::feof(file) != 0) {
812 std::fclose(file);
813 result.set_size(size);
814 return make_error_code(errc::value_too_large);
815 }
816 }
817 std::fclose(file);
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000818 result.set_size(size);
David Blaikie18544b92012-02-09 19:24:12 +0000819 return error_code::success();
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000820}
821
Nick Kledzik18497e92012-06-20 00:28:54 +0000822error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
823 bool map_writable, void *&result) {
824 SmallString<128> path_storage;
825 StringRef name = path.toNullTerminatedStringRef(path_storage);
826 int oflags = map_writable ? O_RDWR : O_RDONLY;
827 int ofd = ::open(name.begin(), oflags);
828 if ( ofd == -1 )
829 return error_code(errno, system_category());
830 AutoFD fd(ofd);
831 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
832 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
833#ifdef MAP_FILE
834 flags |= MAP_FILE;
835#endif
836 result = ::mmap(0, size, prot, flags, fd, file_offset);
837 if (result == MAP_FAILED) {
838 return error_code(errno, system_category());
839 }
840
841 return error_code::success();
842}
843
844error_code unmap_file_pages(void *base, size_t size) {
845 if ( ::munmap(base, size) == -1 )
846 return error_code(errno, system_category());
847
848 return error_code::success();
849}
850
851
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000852} // end namespace fs
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000853} // end namespace sys
854} // end namespace llvm