blob: 0ccca597e1fa0945a1d934de7a92d8075344a546 [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"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +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
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000063#include <sys/types.h>
64#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__ANDROID__)
65#include <sys/statvfs.h>
66#define STATVFS statvfs
67#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
68#else
69#ifdef __OpenBSD__
70#include <sys/param.h>
Mehdi Amini3ba84ca2016-04-08 16:45:05 +000071#include <sys/mount.h>
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000072#elif defined(__ANDROID__)
73#include <sys/vfs.h>
74#else
75#include <sys/mount.h>
76#endif
77#define STATVFS statfs
78#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
79#endif
80
81
Michael J. Spencer45710402010-12-03 01:21:28 +000082using namespace llvm;
83
Michael J. Spencerebad2f92010-11-29 22:28:51 +000084namespace llvm {
85namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +000086namespace fs {
Rafael Espindolae03dfd92013-06-26 05:01:35 +000087#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
88 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +000089 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000090static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +000091test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000092{
Rafael Espindolae03dfd92013-06-26 05:01:35 +000093 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +000094 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +000095
Sylvestre Ledru21e674722013-12-09 16:27:00 +000096 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
Hans Wennborg083ca9b2015-10-06 23:24:35 +000097 if (!realpath(fullpath, ret))
98 return 1;
Sylvestre Ledru21e674722013-12-09 16:27:00 +000099 if (stat(fullpath, &sb) != 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000100 return 1;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000101
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000102 return 0;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000103}
104
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000105static char *
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000106getprogpath(char ret[PATH_MAX], const char *bin)
107{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000108 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000109
110 /* First approach: absolute path. */
111 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000112 if (test_dir(ret, "/", bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000113 return ret;
114 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000115 }
116
117 /* Second approach: relative path. */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000118 if (strchr(bin, '/')) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000119 char cwd[PATH_MAX];
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000120 if (!getcwd(cwd, PATH_MAX))
121 return nullptr;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000122 if (test_dir(ret, cwd, bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000123 return ret;
124 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000125 }
126
127 /* Third approach: $PATH */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000128 if ((pv = getenv("PATH")) == nullptr)
129 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000130 s = pv = strdup(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000131 if (!pv)
132 return nullptr;
133 while ((t = strsep(&s, ":")) != nullptr) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000134 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000135 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000136 return ret;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000137 }
138 }
139 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000140 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000141}
142#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
143
144/// GetMainExecutable - Return the path to the main executable, given the
145/// value of argv[0] from program startup.
146std::string getMainExecutable(const char *argv0, void *MainAddr) {
147#if defined(__APPLE__)
148 // On OS X the executable path is saved to the stack by dyld. Reading it
149 // from there is much faster than calling dladdr, especially for large
150 // binaries with symbols.
151 char exe_path[MAXPATHLEN];
152 uint32_t size = sizeof(exe_path);
153 if (_NSGetExecutablePath(exe_path, &size) == 0) {
154 char link_path[MAXPATHLEN];
155 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000156 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000157 }
158#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
Rafael Espindolaaca97392013-10-31 14:35:00 +0000159 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
160 defined(__FreeBSD_kernel__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000161 char exe_path[PATH_MAX];
162
163 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000164 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000165#elif defined(__linux__) || defined(__CYGWIN__)
166 char exe_path[MAXPATHLEN];
167 StringRef aPath("/proc/self/exe");
168 if (sys::fs::exists(aPath)) {
169 // /proc is not always mounted under Linux (chroot for example).
170 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
171 if (len >= 0)
Alexey Samsonov4c798452014-12-29 20:59:02 +0000172 return std::string(exe_path, len);
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000173 } else {
174 // Fall back to the classical detection.
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000175 if (getprogpath(exe_path, argv0))
176 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000177 }
178#elif defined(HAVE_DLFCN_H)
179 // Use dladdr to get executable path if available.
180 Dl_info DLInfo;
181 int err = dladdr(MainAddr, &DLInfo);
182 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000183 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000184
185 // If the filename is a symlink, we need to resolve and return the location of
186 // the actual executable.
187 char link_path[MAXPATHLEN];
188 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000189 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000190#else
191#error GetMainExecutable is not implemented on this host yet.
192#endif
193 return "";
194}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000195
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000196TimeValue file_status::getLastAccessedTime() const {
197 TimeValue Ret;
198 Ret.fromEpochTime(fs_st_atime);
199 return Ret;
200}
201
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000202TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000203 TimeValue Ret;
204 Ret.fromEpochTime(fs_st_mtime);
205 return Ret;
206}
207
Rafael Espindolad1230992013-07-29 21:55:38 +0000208UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000209 return UniqueID(fs_st_dev, fs_st_ino);
210}
211
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000212ErrorOr<space_info> disk_space(const Twine &Path) {
213 struct STATVFS Vfs;
214 if (::STATVFS(Path.str().c_str(), &Vfs))
215 return std::error_code(errno, std::generic_category());
216 auto FrSize = STATVFS_F_FRSIZE(Vfs);
217 space_info SpaceInfo;
218 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
219 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
220 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
221 return SpaceInfo;
222}
223
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000224std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000225 result.clear();
226
227 const char *pwd = ::getenv("PWD");
228 llvm::sys::fs::file_status PWDStatus, DotStatus;
229 if (pwd && llvm::sys::path::is_absolute(pwd) &&
230 !llvm::sys::fs::status(pwd, PWDStatus) &&
231 !llvm::sys::fs::status(".", DotStatus) &&
232 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
233 result.append(pwd, pwd + strlen(pwd));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000234 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000235 }
236
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000237#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000238 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000239#else
240// For GNU Hurd
241 result.reserve(1024);
242#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000243
Michael J. Spencer20daa282010-12-07 01:22:31 +0000244 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000245 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000246 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000247 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000248 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000249 // Otherwise there just wasn't enough space.
250 result.reserve(result.capacity() * 2);
251 } else
252 break;
253 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000254
255 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000256 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000257}
258
Frederic Riss6b9396c2015-08-06 21:04:55 +0000259std::error_code create_directory(const Twine &path, bool IgnoreExisting,
260 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000261 SmallString<128> path_storage;
262 StringRef p = path.toNullTerminatedStringRef(path_storage);
263
Frederic Riss6b9396c2015-08-06 21:04:55 +0000264 if (::mkdir(p.begin(), Perms) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000265 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000266 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000267 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000268
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000269 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000270}
271
Rafael Espindola83f858e2014-03-11 18:40:24 +0000272// Note that we are using symbolic link because hard links are not supported by
273// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000274std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000275 // Get arguments.
276 SmallString<128> from_storage;
277 SmallString<128> to_storage;
278 StringRef f = from.toNullTerminatedStringRef(from_storage);
279 StringRef t = to.toNullTerminatedStringRef(to_storage);
280
Rafael Espindola83f858e2014-03-11 18:40:24 +0000281 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000282 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000283
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000284 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000285}
286
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000287std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000288 SmallString<128> path_storage;
289 StringRef p = path.toNullTerminatedStringRef(path_storage);
290
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000291 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000292 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000293 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000294 return std::error_code(errno, std::generic_category());
295 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000296 }
297
298 // Note: this check catches strange situations. In all cases, LLVM should
299 // only be involved in the creation and deletion of regular files. This
300 // check ensures that what we're trying to erase is a regular file. It
301 // effectively prevents LLVM from erasing things like /dev/null, any block
302 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000303 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000304 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000305
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000306 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000307 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000308 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000309 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000310
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000311 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000312}
313
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000314std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000315 // Get arguments.
316 SmallString<128> from_storage;
317 SmallString<128> to_storage;
318 StringRef f = from.toNullTerminatedStringRef(from_storage);
319 StringRef t = to.toNullTerminatedStringRef(to_storage);
320
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000321 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000322 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000323
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000324 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000325}
326
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000327std::error_code resize_file(int FD, uint64_t Size) {
328 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000329 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000330
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000331 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000332}
333
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000334static int convertAccessMode(AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000335 switch (Mode) {
336 case AccessMode::Exist:
337 return F_OK;
338 case AccessMode::Write:
339 return W_OK;
340 case AccessMode::Execute:
341 return R_OK | X_OK; // scripts also need R_OK.
342 }
343 llvm_unreachable("invalid enum");
344}
Michael J. Spencer45710402010-12-03 01:21:28 +0000345
Rafael Espindola281f23a2014-09-11 20:30:02 +0000346std::error_code access(const Twine &Path, AccessMode Mode) {
347 SmallString<128> PathStorage;
348 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
349
350 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
351 return std::error_code(errno, std::generic_category());
352
353 if (Mode == AccessMode::Execute) {
354 // Don't say that directories are executable.
355 struct stat buf;
356 if (0 != stat(P.begin(), &buf))
357 return errc::permission_denied;
358 if (!S_ISREG(buf.st_mode))
359 return errc::permission_denied;
360 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000361
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000362 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000363}
364
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000365bool can_execute(const Twine &Path) {
366 return !access(Path, AccessMode::Execute);
367}
368
Michael J. Spencer203d7802011-12-12 06:04:28 +0000369bool equivalent(file_status A, file_status B) {
370 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000371 return A.fs_st_dev == B.fs_st_dev &&
372 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000373}
374
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000375std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000376 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000377 if (std::error_code ec = status(A, fsA))
378 return ec;
379 if (std::error_code ec = status(B, fsB))
380 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000381 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000382 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000383}
384
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000385static std::error_code fillStatus(int StatRet, const struct stat &Status,
386 file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000387 if (StatRet != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000388 std::error_code ec(errno, std::generic_category());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000389 if (ec == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000390 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000391 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000392 Result = file_status(file_type::status_error);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000393 return ec;
394 }
395
Rafael Espindola9da91a02013-07-16 02:55:33 +0000396 file_type Type = file_type::type_unknown;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000397
Rafael Espindola77021c92013-07-16 03:20:13 +0000398 if (S_ISDIR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000399 Type = file_type::directory_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000400 else if (S_ISREG(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000401 Type = file_type::regular_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000402 else if (S_ISBLK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000403 Type = file_type::block_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000404 else if (S_ISCHR(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000405 Type = file_type::character_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000406 else if (S_ISFIFO(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000407 Type = file_type::fifo_file;
Rafael Espindola77021c92013-07-16 03:20:13 +0000408 else if (S_ISSOCK(Status.st_mode))
Rafael Espindola9da91a02013-07-16 02:55:33 +0000409 Type = file_type::socket_file;
410
Rafael Espindola77021c92013-07-16 03:20:13 +0000411 perms Perms = static_cast<perms>(Status.st_mode);
412 Result =
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000413 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_atime,
414 Status.st_mtime, Status.st_uid, Status.st_gid,
415 Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000416
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000417 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000418}
419
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000420std::error_code status(const Twine &Path, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000421 SmallString<128> PathStorage;
422 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
423
424 struct stat Status;
425 int StatRet = ::stat(P.begin(), &Status);
426 return fillStatus(StatRet, Status, Result);
427}
428
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000429std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000430 struct stat Status;
431 int StatRet = ::fstat(FD, &Status);
432 return fillStatus(StatRet, Status, Result);
433}
434
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000435std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
Eric Christophera24dc7f2013-07-04 01:10:38 +0000436#if defined(HAVE_FUTIMENS)
437 timespec Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000438 Times[0].tv_sec = Time.toEpochTime();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000439 Times[0].tv_nsec = 0;
440 Times[1] = Times[0];
441 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000442 return std::error_code(errno, std::generic_category());
443 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000444#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000445 timeval Times[2];
Dmitri Gribenko70e65852014-02-11 09:11:18 +0000446 Times[0].tv_sec = Time.toEpochTime();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000447 Times[0].tv_usec = 0;
448 Times[1] = Times[0];
449 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000450 return std::error_code(errno, std::generic_category());
451 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000452#else
453#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000454 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000455#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000456}
457
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000458std::error_code mapped_file_region::init(int FD, uint64_t Offset,
459 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000460 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000461
462 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
463 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Craig Toppere73658d2014-04-28 04:05:08 +0000464 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000465 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000466 return std::error_code(errno, std::generic_category());
467 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000468}
469
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000470mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
471 uint64_t offset, std::error_code &ec)
472 : Size(length), Mapping() {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000473 // Make sure that the requested size fits within SIZE_T.
474 if (length > std::numeric_limits<size_t>::max()) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000475 ec = make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000476 return;
477 }
478
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000479 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000480 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000481 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000482}
483
484mapped_file_region::~mapped_file_region() {
485 if (Mapping)
486 ::munmap(Mapping, Size);
487}
488
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000489uint64_t mapped_file_region::size() const {
490 assert(Mapping && "Mapping failed but used anyway!");
491 return Size;
492}
493
494char *mapped_file_region::data() const {
495 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000496 return reinterpret_cast<char*>(Mapping);
497}
498
499const char *mapped_file_region::const_data() const {
500 assert(Mapping && "Mapping failed but used anyway!");
501 return reinterpret_cast<const char*>(Mapping);
502}
503
504int mapped_file_region::alignment() {
Rafael Espindolac0610bf2014-12-04 16:59:36 +0000505 return Process::getPageSize();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000506}
507
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000508std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000509 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000510 SmallString<128> path_null(path);
511 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000512 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000513 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000514
515 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
516 // Add something for replace_filename to replace.
517 path::append(path_null, ".");
518 it.CurrentEntry = directory_entry(path_null.str());
519 return directory_iterator_increment(it);
520}
521
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000522std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000523 if (it.IterationHandle)
524 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
525 it.IterationHandle = 0;
526 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000527 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000528}
529
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000530std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000531 errno = 0;
532 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
Craig Toppere73658d2014-04-28 04:05:08 +0000533 if (cur_dir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000534 return std::error_code(errno, std::generic_category());
Craig Toppere73658d2014-04-28 04:05:08 +0000535 } else if (cur_dir != nullptr) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000536 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
537 if ((name.size() == 1 && name[0] == '.') ||
538 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
539 return directory_iterator_increment(it);
540 it.CurrentEntry.replace_filename(name);
541 } else
542 return directory_iterator_destruct(it);
543
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000544 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000545}
546
Taewook Oh99497fd2016-06-04 03:36:12 +0000547std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000548 SmallString<128> Storage;
549 StringRef P = Name.toNullTerminatedStringRef(Storage);
550 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
551 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000552 return std::error_code(errno, std::generic_category());
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000553 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000554 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000555}
Nick Kledzik18497e92012-06-20 00:28:54 +0000556
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000557std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000558 sys::fs::OpenFlags Flags, unsigned Mode) {
559 // Verify that we don't have both "append" and "excl".
560 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
561 "Cannot specify both 'excl' and 'append' file creation flags!");
562
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000563 int OpenFlags = O_CREAT;
564
565 if (Flags & F_RW)
566 OpenFlags |= O_RDWR;
567 else
568 OpenFlags |= O_WRONLY;
Rafael Espindola67080ce2013-07-19 15:02:03 +0000569
570 if (Flags & F_Append)
571 OpenFlags |= O_APPEND;
572 else
573 OpenFlags |= O_TRUNC;
574
575 if (Flags & F_Excl)
576 OpenFlags |= O_EXCL;
577
578 SmallString<128> Storage;
579 StringRef P = Name.toNullTerminatedStringRef(Storage);
580 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
581 if (errno != EINTR)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000582 return std::error_code(errno, std::generic_category());
Rafael Espindola67080ce2013-07-19 15:02:03 +0000583 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000584 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000585}
586
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000587} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000588
589namespace path {
590
591bool home_directory(SmallVectorImpl<char> &result) {
592 if (char *RequestedDir = getenv("HOME")) {
593 result.clear();
594 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
595 return true;
596 }
597
598 return false;
599}
600
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000601static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000602 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
603 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
604 // macros defined in <unistd.h> on darwin >= 9
605 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
606 : _CS_DARWIN_USER_CACHE_DIR;
607 size_t ConfLen = confstr(ConfName, nullptr, 0);
608 if (ConfLen > 0) {
609 do {
610 Result.resize(ConfLen);
611 ConfLen = confstr(ConfName, Result.data(), Result.size());
612 } while (ConfLen > 0 && ConfLen != Result.size());
613
614 if (ConfLen > 0) {
615 assert(Result.back() == 0);
616 Result.pop_back();
617 return true;
618 }
619
620 Result.clear();
621 }
622 #endif
623 return false;
624}
625
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000626static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
Sean Silvaa915a162016-03-24 22:27:27 +0000627 // First try using XDG_CACHE_HOME env variable,
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000628 // as specified in XDG Base Directory Specification at
629 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
Sean Silvaa915a162016-03-24 22:27:27 +0000630 if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000631 Result.clear();
Sean Silvaa915a162016-03-24 22:27:27 +0000632 Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000633 return true;
634 }
635
636 // Try Darwin configuration query
637 if (getDarwinConfDir(false, Result))
638 return true;
639
640 // Use "$HOME/.cache" if $HOME is available
641 if (home_directory(Result)) {
642 append(Result, ".cache");
643 return true;
644 }
645
646 return false;
647}
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000648
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000649static const char *getEnvTempDir() {
Rafael Espindola016a6d52014-08-26 14:47:52 +0000650 // Check whether the temporary directory is specified by an environment
651 // variable.
652 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
653 for (const char *Env : EnvironmentVariables) {
654 if (const char *Dir = std::getenv(Env))
655 return Dir;
656 }
657
658 return nullptr;
659}
660
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000661static const char *getDefaultTempDir(bool ErasedOnReboot) {
Rafael Espindola016a6d52014-08-26 14:47:52 +0000662#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +0000663 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +0000664 return P_tmpdir;
665#endif
666
667 if (ErasedOnReboot)
668 return "/tmp";
669 return "/var/tmp";
670}
671
672void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
673 Result.clear();
674
675 if (ErasedOnReboot) {
676 // There is no env variable for the cache directory.
677 if (const char *RequestedDir = getEnvTempDir()) {
678 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
679 return;
680 }
681 }
682
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000683 if (getDarwinConfDir(ErasedOnReboot, Result))
684 return;
Rafael Espindola016a6d52014-08-26 14:47:52 +0000685
686 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
687 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
688}
689
Peter Collingbournef7d41012014-01-31 23:46:06 +0000690} // end namespace path
691
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000692} // end namespace sys
693} // end namespace llvm