blob: 5eba86d2077d9da6d50dad4ed516c2564f600efb [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael J. Spencerebad2f92010-11-29 22:28:51 +00006//
7//===----------------------------------------------------------------------===//
8//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00009// This file implements the Unix specific implementation of the Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000010//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic UNIX code that
15//=== is guaranteed to work on *all* UNIX variants.
16//===----------------------------------------------------------------------===//
17
18#include "Unix.h"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000019#include <limits.h>
20#include <stdio.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
Taewook Ohd9153272016-06-13 15:54:56 +000027#ifdef HAVE_UNISTD_H
28#include <unistd.h>
29#endif
Nick Kledzik18497e92012-06-20 00:28:54 +000030#ifdef HAVE_SYS_MMAN_H
31#include <sys/mman.h>
32#endif
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000033
Nico Weberf3db8e32018-04-02 17:17:29 +000034#include <dirent.h>
Zachary Turnere48ace62017-03-10 17:39:21 +000035#include <pwd.h>
36
Rafael Espindola4601c462013-06-26 05:25:44 +000037#ifdef __APPLE__
38#include <mach-o/dyld.h>
Taewook Ohd9153272016-06-13 15:54:56 +000039#include <sys/attr.h>
David Carlierb79eee42018-11-10 01:01:03 +000040#elif defined(__DragonFly__)
41#include <sys/mount.h>
Rafael Espindola4601c462013-06-26 05:25:44 +000042#endif
43
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000044// Both stdio.h and cstdio are included via different paths and
Joerg Sonnenbergerc0697302012-08-10 10:56:09 +000045// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
46// either.
47#undef ferror
48#undef feof
49
Sylvestre Ledru14ada942012-04-11 15:35:36 +000050// For GNU Hurd
51#if defined(__GNU__) && !defined(PATH_MAX)
52# define PATH_MAX 4096
Sylvestre Ledruf4719c42018-10-23 07:13:47 +000053# define MAXPATHLEN 4096
Sylvestre Ledru14ada942012-04-11 15:35:36 +000054#endif
55
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000056#include <sys/types.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000057#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
Eli Friedmanf4574702018-12-18 01:38:20 +000058 !defined(__linux__) && !defined(__FreeBSD_kernel__)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000059#include <sys/statvfs.h>
60#define STATVFS statvfs
Zachary Turner392ed9d2017-02-21 20:55:47 +000061#define FSTATVFS fstatvfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000062#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
63#else
Zachary Turner392ed9d2017-02-21 20:55:47 +000064#if defined(__OpenBSD__) || defined(__FreeBSD__)
Mehdi Amini3ba84ca2016-04-08 16:45:05 +000065#include <sys/mount.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000066#include <sys/param.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000067#elif defined(__linux__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +000068#if defined(HAVE_LINUX_MAGIC_H)
Zachary Turner392ed9d2017-02-21 20:55:47 +000069#include <linux/magic.h>
Michal Gorny5ddd2a52017-02-22 18:09:15 +000070#else
71#if defined(HAVE_LINUX_NFS_FS_H)
72#include <linux/nfs_fs.h>
73#endif
74#if defined(HAVE_LINUX_SMB_H)
75#include <linux/smb.h>
76#endif
77#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000078#include <sys/vfs.h>
79#else
80#include <sys/mount.h>
81#endif
82#define STATVFS statfs
Zachary Turner392ed9d2017-02-21 20:55:47 +000083#define FSTATVFS fstatfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000084#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
85#endif
86
David Carlierb79eee42018-11-10 01:01:03 +000087#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
Zachary Turner392ed9d2017-02-21 20:55:47 +000088#define STATVFS_F_FLAG(vfs) (vfs).f_flag
89#else
90#define STATVFS_F_FLAG(vfs) (vfs).f_flags
91#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000092
Michael J. Spencer45710402010-12-03 01:21:28 +000093using namespace llvm;
94
Michael J. Spencerebad2f92010-11-29 22:28:51 +000095namespace llvm {
96namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +000097namespace fs {
Zachary Turner63db25b2018-06-04 19:38:11 +000098
99const file_t kInvalidFile = -1;
100
Michal Gorny2d8be642019-03-04 04:53:50 +0000101#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000102 defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000103 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__)
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000104static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000105test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000106{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000107 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000108 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000109
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000110 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000111 if (!realpath(fullpath, ret))
112 return 1;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000113 if (stat(fullpath, &sb) != 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000114 return 1;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000115
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000116 return 0;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000117}
118
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000119static char *
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000120getprogpath(char ret[PATH_MAX], const char *bin)
121{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000122 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000123
124 /* First approach: absolute path. */
125 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000126 if (test_dir(ret, "/", bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000127 return ret;
128 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000129 }
130
131 /* Second approach: relative path. */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000132 if (strchr(bin, '/')) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000133 char cwd[PATH_MAX];
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000134 if (!getcwd(cwd, PATH_MAX))
135 return nullptr;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000136 if (test_dir(ret, cwd, bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000137 return ret;
138 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000139 }
140
141 /* Third approach: $PATH */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000142 if ((pv = getenv("PATH")) == nullptr)
143 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000144 s = pv = strdup(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000145 if (!pv)
146 return nullptr;
147 while ((t = strsep(&s, ":")) != nullptr) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000148 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000149 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000150 return ret;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000151 }
152 }
153 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000154 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000155}
Dimitry Andricebc87792017-05-17 19:33:10 +0000156#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000157
158/// GetMainExecutable - Return the path to the main executable, given the
159/// value of argv[0] from program startup.
160std::string getMainExecutable(const char *argv0, void *MainAddr) {
161#if defined(__APPLE__)
162 // On OS X the executable path is saved to the stack by dyld. Reading it
163 // from there is much faster than calling dladdr, especially for large
164 // binaries with symbols.
165 char exe_path[MAXPATHLEN];
166 uint32_t size = sizeof(exe_path);
167 if (_NSGetExecutablePath(exe_path, &size) == 0) {
168 char link_path[MAXPATHLEN];
169 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000170 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000171 }
Michal Gorny2d8be642019-03-04 04:53:50 +0000172#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000173 defined(__minix) || defined(__DragonFly__) || \
174 defined(__FreeBSD_kernel__) || defined(_AIX)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000175 char exe_path[PATH_MAX];
176
177 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000178 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000179#elif defined(__linux__) || defined(__CYGWIN__)
180 char exe_path[MAXPATHLEN];
181 StringRef aPath("/proc/self/exe");
182 if (sys::fs::exists(aPath)) {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000183 // /proc is not always mounted under Linux (chroot for example).
184 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
185 if (len < 0)
186 return "";
187
188 // Null terminate the string for realpath. readlink never null
189 // terminates its output.
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000190 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
Reid Kleckner1500eff2018-10-23 23:35:43 +0000191 exe_path[len] = '\0';
192
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000193 // On Linux, /proc/self/exe always looks through symlinks. However, on
194 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
195 // the program, and not the eventual binary file. Therefore, call realpath
196 // so this behaves the same on all platforms.
Reid Kleckner1500eff2018-10-23 23:35:43 +0000197#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
198 char *real_path = realpath(exe_path, NULL);
199 std::string ret = std::string(real_path);
200 free(real_path);
201 return ret;
202#else
203 char real_path[MAXPATHLEN];
204 realpath(exe_path, real_path);
205 return std::string(real_path);
206#endif
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000207 } else {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000208 // Fall back to the classical detection.
209 if (getprogpath(exe_path, argv0))
210 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000211 }
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000212#elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000213 // Use dladdr to get executable path if available.
214 Dl_info DLInfo;
215 int err = dladdr(MainAddr, &DLInfo);
216 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000217 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000218
219 // If the filename is a symlink, we need to resolve and return the location of
220 // the actual executable.
221 char link_path[MAXPATHLEN];
222 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000223 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000224#else
225#error GetMainExecutable is not implemented on this host yet.
226#endif
227 return "";
228}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000229
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000230TimePoint<> basic_file_status::getLastAccessedTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000231 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000232}
233
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000234TimePoint<> basic_file_status::getLastModificationTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000235 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000236}
237
Rafael Espindolad1230992013-07-29 21:55:38 +0000238UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000239 return UniqueID(fs_st_dev, fs_st_ino);
240}
241
Zachary Turner5821a3b2017-03-20 23:55:20 +0000242uint32_t file_status::getLinkCount() const {
243 return fs_st_nlinks;
244}
245
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000246ErrorOr<space_info> disk_space(const Twine &Path) {
247 struct STATVFS Vfs;
248 if (::STATVFS(Path.str().c_str(), &Vfs))
249 return std::error_code(errno, std::generic_category());
250 auto FrSize = STATVFS_F_FRSIZE(Vfs);
251 space_info SpaceInfo;
252 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
253 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
254 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
255 return SpaceInfo;
256}
257
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000258std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000259 result.clear();
260
261 const char *pwd = ::getenv("PWD");
262 llvm::sys::fs::file_status PWDStatus, DotStatus;
263 if (pwd && llvm::sys::path::is_absolute(pwd) &&
264 !llvm::sys::fs::status(pwd, PWDStatus) &&
265 !llvm::sys::fs::status(".", DotStatus) &&
266 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
267 result.append(pwd, pwd + strlen(pwd));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000268 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000269 }
270
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000271#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000272 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000273#else
274// For GNU Hurd
275 result.reserve(1024);
276#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000277
Michael J. Spencer20daa282010-12-07 01:22:31 +0000278 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000279 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000280 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000281 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000282 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000283 // Otherwise there just wasn't enough space.
284 result.reserve(result.capacity() * 2);
285 } else
286 break;
287 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000288
289 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000290 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000291}
292
Pavel Labath2f096092017-01-24 10:32:03 +0000293std::error_code set_current_path(const Twine &path) {
294 SmallString<128> path_storage;
295 StringRef p = path.toNullTerminatedStringRef(path_storage);
296
297 if (::chdir(p.begin()) == -1)
298 return std::error_code(errno, std::generic_category());
299
300 return std::error_code();
301}
302
Frederic Riss6b9396c2015-08-06 21:04:55 +0000303std::error_code create_directory(const Twine &path, bool IgnoreExisting,
304 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000305 SmallString<128> path_storage;
306 StringRef p = path.toNullTerminatedStringRef(path_storage);
307
Frederic Riss6b9396c2015-08-06 21:04:55 +0000308 if (::mkdir(p.begin(), Perms) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000309 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000310 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000311 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000312
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000313 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000314}
315
Rafael Espindola83f858e2014-03-11 18:40:24 +0000316// Note that we are using symbolic link because hard links are not supported by
317// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000318std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000319 // Get arguments.
320 SmallString<128> from_storage;
321 SmallString<128> to_storage;
322 StringRef f = from.toNullTerminatedStringRef(from_storage);
323 StringRef t = to.toNullTerminatedStringRef(to_storage);
324
Rafael Espindola83f858e2014-03-11 18:40:24 +0000325 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000326 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000327
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000328 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000329}
330
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000331std::error_code create_hard_link(const Twine &to, const Twine &from) {
332 // Get arguments.
333 SmallString<128> from_storage;
334 SmallString<128> to_storage;
335 StringRef f = from.toNullTerminatedStringRef(from_storage);
336 StringRef t = to.toNullTerminatedStringRef(to_storage);
337
338 if (::link(t.begin(), f.begin()) == -1)
339 return std::error_code(errno, std::generic_category());
340
341 return std::error_code();
342}
343
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000344std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000345 SmallString<128> path_storage;
346 StringRef p = path.toNullTerminatedStringRef(path_storage);
347
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000348 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000349 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000350 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000351 return std::error_code(errno, std::generic_category());
352 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000353 }
354
355 // Note: this check catches strange situations. In all cases, LLVM should
356 // only be involved in the creation and deletion of regular files. This
357 // check ensures that what we're trying to erase is a regular file. It
358 // effectively prevents LLVM from erasing things like /dev/null, any block
359 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000360 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000361 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000362
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000363 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000364 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000365 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000366 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000367
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000368 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000369}
370
Zachary Turner392ed9d2017-02-21 20:55:47 +0000371static bool is_local_impl(struct STATVFS &Vfs) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000372#if defined(__linux__) || defined(__GNU__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +0000373#ifndef NFS_SUPER_MAGIC
374#define NFS_SUPER_MAGIC 0x6969
375#endif
376#ifndef SMB_SUPER_MAGIC
377#define SMB_SUPER_MAGIC 0x517B
378#endif
Zachary Turner6bc2dac2017-02-21 21:13:10 +0000379#ifndef CIFS_MAGIC_NUMBER
380#define CIFS_MAGIC_NUMBER 0xFF534D42
381#endif
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000382#ifdef __GNU__
383 switch ((uint32_t)Vfs.__f_type) {
384#else
Zachary Turner392ed9d2017-02-21 20:55:47 +0000385 switch ((uint32_t)Vfs.f_type) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000386#endif
Zachary Turner392ed9d2017-02-21 20:55:47 +0000387 case NFS_SUPER_MAGIC:
388 case SMB_SUPER_MAGIC:
389 case CIFS_MAGIC_NUMBER:
390 return false;
391 default:
392 return true;
393 }
Nuno Lopes7a1bbd42017-03-09 13:43:31 +0000394#elif defined(__CYGWIN__)
395 // Cygwin doesn't expose this information; would need to use Win32 API.
396 return false;
Petr Hosek87f13432018-05-03 01:38:49 +0000397#elif defined(__Fuchsia__)
398 // Fuchsia doesn't yet support remote filesystem mounts.
399 return true;
Tim Northover43d64b02018-07-18 13:42:18 +0000400#elif defined(__HAIKU__)
401 // Haiku doesn't expose this information.
402 return false;
Kamil Rytarowski07c81b12017-06-01 12:57:00 +0000403#elif defined(__sun)
404 // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
405 StringRef fstype(Vfs.f_basetype);
406 // NFS is the only non-local fstype??
407 return !fstype.equals("nfs");
Zachary Turner392ed9d2017-02-21 20:55:47 +0000408#else
409 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
410#endif
411}
412
413std::error_code is_local(const Twine &Path, bool &Result) {
414 struct STATVFS Vfs;
415 if (::STATVFS(Path.str().c_str(), &Vfs))
416 return std::error_code(errno, std::generic_category());
417
418 Result = is_local_impl(Vfs);
419 return std::error_code();
420}
421
422std::error_code is_local(int FD, bool &Result) {
423 struct STATVFS Vfs;
424 if (::FSTATVFS(FD, &Vfs))
425 return std::error_code(errno, std::generic_category());
426
427 Result = is_local_impl(Vfs);
428 return std::error_code();
429}
430
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000431std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000432 // Get arguments.
433 SmallString<128> from_storage;
434 SmallString<128> to_storage;
435 StringRef f = from.toNullTerminatedStringRef(from_storage);
436 StringRef t = to.toNullTerminatedStringRef(to_storage);
437
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000438 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000439 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000440
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000441 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000442}
443
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000444std::error_code resize_file(int FD, uint64_t Size) {
Rafael Espindola3816c532016-07-19 20:19:56 +0000445#if defined(HAVE_POSIX_FALLOCATE)
446 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
447 // space, so we get an error if the disk is full.
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000448 if (int Err = ::posix_fallocate(FD, 0, Size)) {
Davide Italiano1f465aa2017-11-07 00:47:04 +0000449 if (Err != EINVAL && Err != EOPNOTSUPP)
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000450 return std::error_code(Err, std::generic_category());
451 }
452#endif
Rafael Espindola3816c532016-07-19 20:19:56 +0000453 // Use ftruncate as a fallback. It may or may not allocate space. At least on
454 // OS X with HFS+ it does.
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000455 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000456 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000457
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000458 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000459}
460
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000461static int convertAccessMode(AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000462 switch (Mode) {
463 case AccessMode::Exist:
464 return F_OK;
465 case AccessMode::Write:
466 return W_OK;
467 case AccessMode::Execute:
468 return R_OK | X_OK; // scripts also need R_OK.
469 }
470 llvm_unreachable("invalid enum");
471}
Michael J. Spencer45710402010-12-03 01:21:28 +0000472
Rafael Espindola281f23a2014-09-11 20:30:02 +0000473std::error_code access(const Twine &Path, AccessMode Mode) {
474 SmallString<128> PathStorage;
475 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
476
477 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
478 return std::error_code(errno, std::generic_category());
479
480 if (Mode == AccessMode::Execute) {
481 // Don't say that directories are executable.
482 struct stat buf;
483 if (0 != stat(P.begin(), &buf))
484 return errc::permission_denied;
485 if (!S_ISREG(buf.st_mode))
486 return errc::permission_denied;
487 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000488
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000489 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000490}
491
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000492bool can_execute(const Twine &Path) {
493 return !access(Path, AccessMode::Execute);
494}
495
Michael J. Spencer203d7802011-12-12 06:04:28 +0000496bool equivalent(file_status A, file_status B) {
497 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000498 return A.fs_st_dev == B.fs_st_dev &&
499 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000500}
501
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000502std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000503 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000504 if (std::error_code ec = status(A, fsA))
505 return ec;
506 if (std::error_code ec = status(B, fsB))
507 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000508 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000509 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000510}
511
Zachary Turnere48ace62017-03-10 17:39:21 +0000512static void expandTildeExpr(SmallVectorImpl<char> &Path) {
513 StringRef PathStr(Path.begin(), Path.size());
514 if (PathStr.empty() || !PathStr.startswith("~"))
515 return;
516
517 PathStr = PathStr.drop_front();
Zachary Turner18753342017-03-16 22:34:18 +0000518 StringRef Expr =
519 PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +0000520 StringRef Remainder = PathStr.substr(Expr.size() + 1);
521 SmallString<128> Storage;
522 if (Expr.empty()) {
523 // This is just ~/..., resolve it to the current user's home dir.
524 if (!path::home_directory(Storage)) {
525 // For some reason we couldn't get the home directory. Just exit.
526 return;
527 }
528
529 // Overwrite the first character and insert the rest.
530 Path[0] = Storage[0];
531 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
532 return;
533 }
534
535 // This is a string of the form ~username/, look up this user's entry in the
536 // password database.
537 struct passwd *Entry = nullptr;
538 std::string User = Expr.str();
539 Entry = ::getpwnam(User.c_str());
540
541 if (!Entry) {
542 // Unable to look up the entry, just return back the original path.
543 return;
544 }
545
546 Storage = Remainder;
547 Path.clear();
548 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
549 llvm::sys::path::append(Path, Storage);
550}
551
Jonas Devlieghereb23f4302018-11-13 18:23:32 +0000552
553void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
554 dest.clear();
555 if (path.isTriviallyEmpty())
556 return;
557
558 path.toVector(dest);
559 expandTildeExpr(dest);
560
561 return;
562}
563
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000564static file_type typeForMode(mode_t Mode) {
565 if (S_ISDIR(Mode))
566 return file_type::directory_file;
567 else if (S_ISREG(Mode))
568 return file_type::regular_file;
569 else if (S_ISBLK(Mode))
570 return file_type::block_file;
571 else if (S_ISCHR(Mode))
572 return file_type::character_file;
573 else if (S_ISFIFO(Mode))
574 return file_type::fifo_file;
575 else if (S_ISSOCK(Mode))
576 return file_type::socket_file;
577 else if (S_ISLNK(Mode))
578 return file_type::symlink_file;
579 return file_type::type_unknown;
580}
581
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000582static std::error_code fillStatus(int StatRet, const struct stat &Status,
Fangrui Song69d64182018-06-10 04:53:14 +0000583 file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000584 if (StatRet != 0) {
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000585 std::error_code EC(errno, std::generic_category());
586 if (EC == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000587 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000588 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000589 Result = file_status(file_type::status_error);
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000590 return EC;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000591 }
592
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000593 uint32_t atime_nsec, mtime_nsec;
594#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
595 atime_nsec = Status.st_atimespec.tv_nsec;
596 mtime_nsec = Status.st_mtimespec.tv_nsec;
597#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
598 atime_nsec = Status.st_atim.tv_nsec;
599 mtime_nsec = Status.st_mtim.tv_nsec;
600#else
601 atime_nsec = mtime_nsec = 0;
602#endif
603
James Henderson566fdf42017-03-16 11:22:09 +0000604 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000605 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000606 Status.st_nlink, Status.st_ino,
607 Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
608 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000609
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000610 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000611}
612
Zachary Turner82dd5422017-03-07 16:10:10 +0000613std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000614 SmallString<128> PathStorage;
615 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
616
617 struct stat Status;
Zachary Turner82dd5422017-03-07 16:10:10 +0000618 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
Rafael Espindola77021c92013-07-16 03:20:13 +0000619 return fillStatus(StatRet, Status, Result);
620}
621
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000622std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000623 struct stat Status;
624 int StatRet = ::fstat(FD, &Status);
Aaron Ballman345012d2017-03-13 12:24:51 +0000625 return fillStatus(StatRet, Status, Result);
626}
627
James Henderson566fdf42017-03-16 11:22:09 +0000628std::error_code setPermissions(const Twine &Path, perms Permissions) {
629 SmallString<128> PathStorage;
630 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
631
632 if (::chmod(P.begin(), Permissions))
633 return std::error_code(errno, std::generic_category());
634 return std::error_code();
635}
636
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000637std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
638 TimePoint<> ModificationTime) {
Aaron Ballman345012d2017-03-13 12:24:51 +0000639#if defined(HAVE_FUTIMENS)
640 timespec Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000641 Times[0] = sys::toTimeSpec(AccessTime);
642 Times[1] = sys::toTimeSpec(ModificationTime);
Eric Christophera24dc7f2013-07-04 01:10:38 +0000643 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000644 return std::error_code(errno, std::generic_category());
645 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000646#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000647 timeval Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000648 Times[0] = sys::toTimeVal(
649 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
650 Times[1] =
651 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
652 ModificationTime));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000653 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000654 return std::error_code(errno, std::generic_category());
655 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000656#else
657#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000658 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000659#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000660}
661
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000662std::error_code mapped_file_region::init(int FD, uint64_t Offset,
663 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000664 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000665
666 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
667 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Zachary Turner842972b2017-02-22 21:24:06 +0000668#if defined(__APPLE__)
669 //----------------------------------------------------------------------
670 // Newer versions of MacOSX have a flag that will allow us to read from
671 // binaries whose code signature is invalid without crashing by using
672 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
673 // is mapped we can avoid crashing and return zeroes to any pages we try
674 // to read if the media becomes unavailable by using the
675 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
676 // with PROT_READ, so take care not to specify them otherwise.
677 //----------------------------------------------------------------------
678 if (Mode == readonly) {
679#if defined(MAP_RESILIENT_CODESIGN)
680 flags |= MAP_RESILIENT_CODESIGN;
681#endif
682#if defined(MAP_RESILIENT_MEDIA)
683 flags |= MAP_RESILIENT_MEDIA;
684#endif
685 }
686#endif // #if defined (__APPLE__)
Zachary Turner392ed9d2017-02-21 20:55:47 +0000687
Craig Toppere73658d2014-04-28 04:05:08 +0000688 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000689 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000690 return std::error_code(errno, std::generic_category());
691 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000692}
693
Roman Lebedev7c983672017-09-27 15:59:16 +0000694mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000695 uint64_t offset, std::error_code &ec)
Peter Collingbourne881ba102018-06-13 18:03:14 +0000696 : Size(length), Mapping(), Mode(mode) {
Zachary Turner2061ad22018-02-15 18:46:59 +0000697 (void)Mode;
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000698 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000699 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000700 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000701}
702
703mapped_file_region::~mapped_file_region() {
704 if (Mapping)
705 ::munmap(Mapping, Size);
706}
707
Roman Lebedev21b013e2017-09-27 16:08:33 +0000708size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000709 assert(Mapping && "Mapping failed but used anyway!");
710 return Size;
711}
712
713char *mapped_file_region::data() const {
714 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000715 return reinterpret_cast<char*>(Mapping);
716}
717
718const char *mapped_file_region::const_data() const {
719 assert(Mapping && "Mapping failed but used anyway!");
720 return reinterpret_cast<const char*>(Mapping);
721}
722
723int mapped_file_region::alignment() {
Rafael Espindolac0610bf2014-12-04 16:59:36 +0000724 return Process::getPageSize();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000725}
726
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000727std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000728 StringRef path,
729 bool follow_symlinks) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000730 SmallString<128> path_null(path);
731 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000732 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000733 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000734
735 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
736 // Add something for replace_filename to replace.
737 path::append(path_null, ".");
Zachary Turner260bda32017-03-08 22:49:32 +0000738 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
Michael J. Spencer52714862011-01-05 16:38:57 +0000739 return directory_iterator_increment(it);
740}
741
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000742std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000743 if (it.IterationHandle)
744 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
745 it.IterationHandle = 0;
746 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000747 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000748}
749
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000750static file_type direntType(dirent* Entry) {
751 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
752 // The DTTOIF macro lets us reuse our status -> type conversion.
753#if defined(_DIRENT_HAVE_D_TYPE) && defined(DTTOIF)
754 return typeForMode(DTTOIF(Entry->d_type));
755#else
756 // Other platforms such as Solaris require a stat() to get the type.
757 return file_type::type_unknown;
758#endif
759}
760
761std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000762 errno = 0;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000763 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
764 if (CurDir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000765 return std::error_code(errno, std::generic_category());
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000766 } else if (CurDir != nullptr) {
767 StringRef Name(CurDir->d_name);
768 if ((Name.size() == 1 && Name[0] == '.') ||
769 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
770 return directory_iterator_increment(It);
771 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
Michael J. Spencer52714862011-01-05 16:38:57 +0000772 } else
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000773 return directory_iterator_destruct(It);
Michael J. Spencer52714862011-01-05 16:38:57 +0000774
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000775 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000776}
777
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000778ErrorOr<basic_file_status> directory_entry::status() const {
779 file_status s;
780 if (auto EC = fs::status(Path, s, FollowSymlinks))
781 return EC;
782 return s;
783}
784
Taewook Ohd9153272016-06-13 15:54:56 +0000785#if !defined(F_GETPATH)
786static bool hasProcSelfFD() {
787 // If we have a /proc filesystem mounted, we can quickly establish the
788 // real name of the file with readlink
789 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
790 return Result;
791}
792#endif
793
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000794static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
795 FileAccess Access) {
796 int Result = 0;
797 if (Access == FA_Read)
798 Result |= O_RDONLY;
799 else if (Access == FA_Write)
800 Result |= O_WRONLY;
801 else if (Access == (FA_Read | FA_Write))
802 Result |= O_RDWR;
803
804 // This is for compatibility with old code that assumed F_Append implied
805 // would open an existing file. See Windows/Path.inc for a longer comment.
806 if (Flags & F_Append)
807 Disp = CD_OpenAlways;
808
809 if (Disp == CD_CreateNew) {
810 Result |= O_CREAT; // Create if it doesn't exist.
811 Result |= O_EXCL; // Fail if it does.
812 } else if (Disp == CD_CreateAlways) {
813 Result |= O_CREAT; // Create if it doesn't exist.
814 Result |= O_TRUNC; // Truncate if it does.
815 } else if (Disp == CD_OpenAlways) {
816 Result |= O_CREAT; // Create if it doesn't exist.
817 } else if (Disp == CD_OpenExisting) {
818 // Nothing special, just don't add O_CREAT and we get these semantics.
819 }
820
821 if (Flags & F_Append)
822 Result |= O_APPEND;
823
824#ifdef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000825 if (!(Flags & OF_ChildInherit))
826 Result |= O_CLOEXEC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000827#endif
828
829 return Result;
830}
831
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000832std::error_code openFile(const Twine &Name, int &ResultFD,
833 CreationDisposition Disp, FileAccess Access,
834 OpenFlags Flags, unsigned Mode) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000835 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
836
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000837 SmallString<128> Storage;
838 StringRef P = Name.toNullTerminatedStringRef(Storage);
Hans Wennborg0a0e4112018-08-27 15:55:39 +0000839 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
840 // when open is overloaded, such as in Bionic.
841 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
842 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
Pavel Labathfe09f502017-06-29 13:15:31 +0000843 return std::error_code(errno, std::generic_category());
Pavel Labathf726dfa2017-01-24 10:57:01 +0000844#ifndef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000845 if (!(Flags & OF_ChildInherit)) {
846 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
847 (void)r;
848 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
849 }
Pavel Labathf726dfa2017-01-24 10:57:01 +0000850#endif
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000851 return std::error_code();
852}
853
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000854Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
855 FileAccess Access, OpenFlags Flags,
856 unsigned Mode) {
857
858 int FD;
859 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
860 if (EC)
861 return errorCodeToError(EC);
862 return FD;
863}
864
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000865std::error_code openFileForRead(const Twine &Name, int &ResultFD,
866 OpenFlags Flags,
867 SmallVectorImpl<char> *RealPath) {
868 std::error_code EC =
869 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
870 if (EC)
871 return EC;
872
Taewook Ohd9153272016-06-13 15:54:56 +0000873 // Attempt to get the real name of the file, if the user asked
874 if(!RealPath)
875 return std::error_code();
876 RealPath->clear();
877#if defined(F_GETPATH)
878 // When F_GETPATH is availble, it is the quickest way to get
879 // the real path name.
880 char Buffer[MAXPATHLEN];
881 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
882 RealPath->append(Buffer, Buffer + strlen(Buffer));
883#else
884 char Buffer[PATH_MAX];
885 if (hasProcSelfFD()) {
886 char ProcPath[64];
887 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
888 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
889 if (CharCount > 0)
890 RealPath->append(Buffer, Buffer + CharCount);
891 } else {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000892 SmallString<128> Storage;
893 StringRef P = Name.toNullTerminatedStringRef(Storage);
894
Taewook Ohd9153272016-06-13 15:54:56 +0000895 // Use ::realpath to get the real path name
896 if (::realpath(P.begin(), Buffer) != nullptr)
897 RealPath->append(Buffer, Buffer + strlen(Buffer));
898 }
899#endif
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000900 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000901}
Nick Kledzik18497e92012-06-20 00:28:54 +0000902
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000903Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
Zachary Turner63db25b2018-06-04 19:38:11 +0000904 SmallVectorImpl<char> *RealPath) {
905 file_t ResultFD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000906 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
Zachary Turner63db25b2018-06-04 19:38:11 +0000907 if (EC)
908 return errorCodeToError(EC);
909 return ResultFD;
910}
911
Zachary Turner63db25b2018-06-04 19:38:11 +0000912void closeFile(file_t &F) {
913 ::close(F);
914 F = kInvalidFile;
915}
916
Zachary Turner260bda32017-03-08 22:49:32 +0000917template <typename T>
918static std::error_code remove_directories_impl(const T &Entry,
919 bool IgnoreErrors) {
920 std::error_code EC;
921 directory_iterator Begin(Entry, EC, false);
922 directory_iterator End;
923 while (Begin != End) {
924 auto &Item = *Begin;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000925 ErrorOr<basic_file_status> st = Item.status();
926 if (!st && !IgnoreErrors)
927 return st.getError();
Zachary Turner260bda32017-03-08 22:49:32 +0000928
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000929 if (is_directory(*st)) {
Zachary Turner260bda32017-03-08 22:49:32 +0000930 EC = remove_directories_impl(Item, IgnoreErrors);
931 if (EC && !IgnoreErrors)
932 return EC;
933 }
934
935 EC = fs::remove(Item.path(), true);
936 if (EC && !IgnoreErrors)
937 return EC;
938
939 Begin.increment(EC);
940 if (EC && !IgnoreErrors)
941 return EC;
942 }
943 return std::error_code();
944}
945
946std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
947 auto EC = remove_directories_impl(path, IgnoreErrors);
948 if (EC && !IgnoreErrors)
949 return EC;
950 EC = fs::remove(path, true);
951 if (EC && !IgnoreErrors)
952 return EC;
953 return std::error_code();
954}
955
Zachary Turnere48ace62017-03-10 17:39:21 +0000956std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
957 bool expand_tilde) {
958 dest.clear();
959 if (path.isTriviallyEmpty())
960 return std::error_code();
961
962 if (expand_tilde) {
963 SmallString<128> Storage;
964 path.toVector(Storage);
965 expandTildeExpr(Storage);
966 return real_path(Storage, dest, false);
967 }
968
Davide Italiano4762c062018-01-09 17:27:45 +0000969 SmallString<128> Storage;
970 StringRef P = path.toNullTerminatedStringRef(Storage);
971 char Buffer[PATH_MAX];
972 if (::realpath(P.begin(), Buffer) == nullptr)
973 return std::error_code(errno, std::generic_category());
974 dest.append(Buffer, Buffer + strlen(Buffer));
Zachary Turnere48ace62017-03-10 17:39:21 +0000975 return std::error_code();
976}
977
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000978} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +0000979
980namespace path {
981
982bool home_directory(SmallVectorImpl<char> &result) {
Zachary Turnera3cf70b2017-03-22 15:24:59 +0000983 char *RequestedDir = getenv("HOME");
984 if (!RequestedDir) {
985 struct passwd *pw = getpwuid(getuid());
986 if (pw && pw->pw_dir)
987 RequestedDir = pw->pw_dir;
Peter Collingbournef7d41012014-01-31 23:46:06 +0000988 }
Zachary Turnera3cf70b2017-03-22 15:24:59 +0000989 if (!RequestedDir)
990 return false;
991
992 result.clear();
993 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
994 return true;
Peter Collingbournef7d41012014-01-31 23:46:06 +0000995}
996
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000997static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
Pawel Bylica0e97e5c2015-11-02 09:49:17 +0000998 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
999 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1000 // macros defined in <unistd.h> on darwin >= 9
1001 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1002 : _CS_DARWIN_USER_CACHE_DIR;
1003 size_t ConfLen = confstr(ConfName, nullptr, 0);
1004 if (ConfLen > 0) {
1005 do {
1006 Result.resize(ConfLen);
1007 ConfLen = confstr(ConfName, Result.data(), Result.size());
1008 } while (ConfLen > 0 && ConfLen != Result.size());
1009
1010 if (ConfLen > 0) {
1011 assert(Result.back() == 0);
1012 Result.pop_back();
1013 return true;
1014 }
1015
1016 Result.clear();
1017 }
1018 #endif
1019 return false;
1020}
1021
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001022static const char *getEnvTempDir() {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001023 // Check whether the temporary directory is specified by an environment
1024 // variable.
1025 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1026 for (const char *Env : EnvironmentVariables) {
1027 if (const char *Dir = std::getenv(Env))
1028 return Dir;
1029 }
1030
1031 return nullptr;
1032}
1033
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001034static const char *getDefaultTempDir(bool ErasedOnReboot) {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001035#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +00001036 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +00001037 return P_tmpdir;
1038#endif
1039
1040 if (ErasedOnReboot)
1041 return "/tmp";
1042 return "/var/tmp";
1043}
1044
1045void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1046 Result.clear();
1047
1048 if (ErasedOnReboot) {
1049 // There is no env variable for the cache directory.
1050 if (const char *RequestedDir = getEnvTempDir()) {
1051 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1052 return;
1053 }
1054 }
1055
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001056 if (getDarwinConfDir(ErasedOnReboot, Result))
1057 return;
Rafael Espindola016a6d52014-08-26 14:47:52 +00001058
1059 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1060 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1061}
1062
Peter Collingbournef7d41012014-01-31 23:46:06 +00001063} // end namespace path
1064
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001065} // end namespace sys
1066} // end namespace llvm