blob: 908f43ed5a93f8186d53dcc883662775e9e7c524 [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>
Adrian Prantlfac78752019-04-18 21:22:50 +000040#include <copyfile.h>
David Carlierb79eee42018-11-10 01:01:03 +000041#elif defined(__DragonFly__)
42#include <sys/mount.h>
Rafael Espindola4601c462013-06-26 05:25:44 +000043#endif
44
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000045// Both stdio.h and cstdio are included via different paths and
Joerg Sonnenbergerc0697302012-08-10 10:56:09 +000046// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
47// either.
48#undef ferror
49#undef feof
50
Sylvestre Ledru14ada942012-04-11 15:35:36 +000051// For GNU Hurd
52#if defined(__GNU__) && !defined(PATH_MAX)
53# define PATH_MAX 4096
Sylvestre Ledruf4719c42018-10-23 07:13:47 +000054# define MAXPATHLEN 4096
Sylvestre Ledru14ada942012-04-11 15:35:36 +000055#endif
56
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000057#include <sys/types.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000058#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
Hubert Tong24168852019-03-29 23:32:47 +000059 !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000060#include <sys/statvfs.h>
61#define STATVFS statvfs
Zachary Turner392ed9d2017-02-21 20:55:47 +000062#define FSTATVFS fstatvfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000063#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
64#else
Zachary Turner392ed9d2017-02-21 20:55:47 +000065#if defined(__OpenBSD__) || defined(__FreeBSD__)
Mehdi Amini3ba84ca2016-04-08 16:45:05 +000066#include <sys/mount.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000067#include <sys/param.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000068#elif defined(__linux__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +000069#if defined(HAVE_LINUX_MAGIC_H)
Zachary Turner392ed9d2017-02-21 20:55:47 +000070#include <linux/magic.h>
Michal Gorny5ddd2a52017-02-22 18:09:15 +000071#else
72#if defined(HAVE_LINUX_NFS_FS_H)
73#include <linux/nfs_fs.h>
74#endif
75#if defined(HAVE_LINUX_SMB_H)
76#include <linux/smb.h>
77#endif
78#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000079#include <sys/vfs.h>
Hubert Tong24168852019-03-29 23:32:47 +000080#elif defined(_AIX)
81#include <sys/statfs.h>
82
83// <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
84// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
85// the typedef prior to including <sys/vmount.h> to work around this issue.
86typedef uint_t uint;
87#include <sys/vmount.h>
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000088#else
89#include <sys/mount.h>
90#endif
91#define STATVFS statfs
Zachary Turner392ed9d2017-02-21 20:55:47 +000092#define FSTATVFS fstatfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000093#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
94#endif
95
David Carlierb79eee42018-11-10 01:01:03 +000096#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
Zachary Turner392ed9d2017-02-21 20:55:47 +000097#define STATVFS_F_FLAG(vfs) (vfs).f_flag
98#else
99#define STATVFS_F_FLAG(vfs) (vfs).f_flags
100#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000101
Michael J. Spencer45710402010-12-03 01:21:28 +0000102using namespace llvm;
103
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000104namespace llvm {
105namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000106namespace fs {
Zachary Turner63db25b2018-06-04 19:38:11 +0000107
108const file_t kInvalidFile = -1;
109
Michal Gorny2d8be642019-03-04 04:53:50 +0000110#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000111 defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000112 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__)
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000113static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000114test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000115{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000116 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000117 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000118
Jonas Hahnfelde59746f2019-03-13 10:37:56 +0000119 int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
120 // We cannot write PATH_MAX characters because the string will be terminated
121 // with a null character. Fail if truncation happened.
122 if (chars >= PATH_MAX)
123 return 1;
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000124 if (!realpath(fullpath, ret))
125 return 1;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000126 if (stat(fullpath, &sb) != 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000127 return 1;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000128
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000129 return 0;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000130}
131
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000132static char *
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000133getprogpath(char ret[PATH_MAX], const char *bin)
134{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000135 /* First approach: absolute path. */
136 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000137 if (test_dir(ret, "/", bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000138 return ret;
139 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000140 }
141
142 /* Second approach: relative path. */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000143 if (strchr(bin, '/')) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000144 char cwd[PATH_MAX];
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000145 if (!getcwd(cwd, PATH_MAX))
146 return nullptr;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000147 if (test_dir(ret, cwd, bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000148 return ret;
149 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000150 }
151
152 /* Third approach: $PATH */
Xing Xue2dee0942019-05-16 14:02:13 +0000153 char *pv;
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000154 if ((pv = getenv("PATH")) == nullptr)
155 return nullptr;
Xing Xue2dee0942019-05-16 14:02:13 +0000156 char *s = strdup(pv);
157 if (!s)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000158 return nullptr;
Xing Xue2dee0942019-05-16 14:02:13 +0000159 char *state;
160 for (char *t = strtok_r(s, ":", &state); t != nullptr;
161 t = strtok_r(nullptr, ":", &state)) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000162 if (test_dir(ret, t, bin) == 0) {
Xing Xue2dee0942019-05-16 14:02:13 +0000163 free(s);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000164 return ret;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000165 }
166 }
Xing Xue2dee0942019-05-16 14:02:13 +0000167 free(s);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000168 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000169}
Dimitry Andricebc87792017-05-17 19:33:10 +0000170#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000171
172/// GetMainExecutable - Return the path to the main executable, given the
173/// value of argv[0] from program startup.
174std::string getMainExecutable(const char *argv0, void *MainAddr) {
175#if defined(__APPLE__)
176 // On OS X the executable path is saved to the stack by dyld. Reading it
177 // from there is much faster than calling dladdr, especially for large
178 // binaries with symbols.
179 char exe_path[MAXPATHLEN];
180 uint32_t size = sizeof(exe_path);
181 if (_NSGetExecutablePath(exe_path, &size) == 0) {
182 char link_path[MAXPATHLEN];
183 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000184 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000185 }
Michal Gorny2d8be642019-03-04 04:53:50 +0000186#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000187 defined(__minix) || defined(__DragonFly__) || \
188 defined(__FreeBSD_kernel__) || defined(_AIX)
David Chisnall714a4422019-04-29 09:24:51 +0000189 StringRef curproc("/proc/curproc/file");
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000190 char exe_path[PATH_MAX];
David Chisnall714a4422019-04-29 09:24:51 +0000191 // /proc is not mounted by default under FreeBSD, but gives more accurate
192 // information than argv[0] when it is.
193 if (sys::fs::exists(curproc)) {
194 ssize_t len = readlink(curproc.str().c_str(), exe_path, sizeof(exe_path));
195 if (len > 0) {
196 // Null terminate the string for realpath. readlink never null
197 // terminates its output.
198 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
199 exe_path[len] = '\0';
200 return exe_path;
201 }
202 }
203 // If we don't have procfs mounted, fall back to argv[0]
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000204 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000205 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000206#elif defined(__linux__) || defined(__CYGWIN__)
207 char exe_path[MAXPATHLEN];
208 StringRef aPath("/proc/self/exe");
209 if (sys::fs::exists(aPath)) {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000210 // /proc is not always mounted under Linux (chroot for example).
211 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
212 if (len < 0)
213 return "";
214
215 // Null terminate the string for realpath. readlink never null
216 // terminates its output.
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000217 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
Reid Kleckner1500eff2018-10-23 23:35:43 +0000218 exe_path[len] = '\0';
219
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000220 // On Linux, /proc/self/exe always looks through symlinks. However, on
221 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
222 // the program, and not the eventual binary file. Therefore, call realpath
223 // so this behaves the same on all platforms.
Reid Kleckner1500eff2018-10-23 23:35:43 +0000224#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
Sam McCalledf904e2019-07-02 15:42:37 +0000225 if (char *real_path = realpath(exe_path, NULL)) {
226 std::string ret = std::string(real_path);
227 free(real_path);
228 return ret;
229 }
Reid Kleckner1500eff2018-10-23 23:35:43 +0000230#else
231 char real_path[MAXPATHLEN];
Sam McCalledf904e2019-07-02 15:42:37 +0000232 if (realpath(exe_path, real_path))
233 return std::string(real_path);
Reid Kleckner1500eff2018-10-23 23:35:43 +0000234#endif
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000235 }
Sam McCalledf904e2019-07-02 15:42:37 +0000236 // Fall back to the classical detection.
237 if (getprogpath(exe_path, argv0))
238 return exe_path;
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000239#elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000240 // Use dladdr to get executable path if available.
241 Dl_info DLInfo;
242 int err = dladdr(MainAddr, &DLInfo);
243 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000244 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000245
246 // If the filename is a symlink, we need to resolve and return the location of
247 // the actual executable.
248 char link_path[MAXPATHLEN];
249 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000250 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000251#else
252#error GetMainExecutable is not implemented on this host yet.
253#endif
254 return "";
255}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000256
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000257TimePoint<> basic_file_status::getLastAccessedTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000258 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000259}
260
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000261TimePoint<> basic_file_status::getLastModificationTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000262 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000263}
264
Rafael Espindolad1230992013-07-29 21:55:38 +0000265UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000266 return UniqueID(fs_st_dev, fs_st_ino);
267}
268
Zachary Turner5821a3b2017-03-20 23:55:20 +0000269uint32_t file_status::getLinkCount() const {
270 return fs_st_nlinks;
271}
272
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000273ErrorOr<space_info> disk_space(const Twine &Path) {
274 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000275 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000276 return std::error_code(errno, std::generic_category());
277 auto FrSize = STATVFS_F_FRSIZE(Vfs);
278 space_info SpaceInfo;
279 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
280 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
281 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
282 return SpaceInfo;
283}
284
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000285std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000286 result.clear();
287
288 const char *pwd = ::getenv("PWD");
289 llvm::sys::fs::file_status PWDStatus, DotStatus;
290 if (pwd && llvm::sys::path::is_absolute(pwd) &&
291 !llvm::sys::fs::status(pwd, PWDStatus) &&
292 !llvm::sys::fs::status(".", DotStatus) &&
293 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
294 result.append(pwd, pwd + strlen(pwd));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000295 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000296 }
297
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000298#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000299 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000300#else
301// For GNU Hurd
302 result.reserve(1024);
303#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000304
Michael J. Spencer20daa282010-12-07 01:22:31 +0000305 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000306 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000307 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000308 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000309 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000310 // Otherwise there just wasn't enough space.
311 result.reserve(result.capacity() * 2);
312 } else
313 break;
314 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000315
316 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000317 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000318}
319
Pavel Labath2f096092017-01-24 10:32:03 +0000320std::error_code set_current_path(const Twine &path) {
321 SmallString<128> path_storage;
322 StringRef p = path.toNullTerminatedStringRef(path_storage);
323
324 if (::chdir(p.begin()) == -1)
325 return std::error_code(errno, std::generic_category());
326
327 return std::error_code();
328}
329
Frederic Riss6b9396c2015-08-06 21:04:55 +0000330std::error_code create_directory(const Twine &path, bool IgnoreExisting,
331 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000332 SmallString<128> path_storage;
333 StringRef p = path.toNullTerminatedStringRef(path_storage);
334
Frederic Riss6b9396c2015-08-06 21:04:55 +0000335 if (::mkdir(p.begin(), Perms) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000336 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000337 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000338 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000339
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000340 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000341}
342
Rafael Espindola83f858e2014-03-11 18:40:24 +0000343// Note that we are using symbolic link because hard links are not supported by
344// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000345std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000346 // Get arguments.
347 SmallString<128> from_storage;
348 SmallString<128> to_storage;
349 StringRef f = from.toNullTerminatedStringRef(from_storage);
350 StringRef t = to.toNullTerminatedStringRef(to_storage);
351
Rafael Espindola83f858e2014-03-11 18:40:24 +0000352 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000353 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000354
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000355 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000356}
357
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000358std::error_code create_hard_link(const Twine &to, const Twine &from) {
359 // Get arguments.
360 SmallString<128> from_storage;
361 SmallString<128> to_storage;
362 StringRef f = from.toNullTerminatedStringRef(from_storage);
363 StringRef t = to.toNullTerminatedStringRef(to_storage);
364
365 if (::link(t.begin(), f.begin()) == -1)
366 return std::error_code(errno, std::generic_category());
367
368 return std::error_code();
369}
370
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000371std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000372 SmallString<128> path_storage;
373 StringRef p = path.toNullTerminatedStringRef(path_storage);
374
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000375 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000376 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000377 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000378 return std::error_code(errno, std::generic_category());
379 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000380 }
381
382 // Note: this check catches strange situations. In all cases, LLVM should
383 // only be involved in the creation and deletion of regular files. This
384 // check ensures that what we're trying to erase is a regular file. It
385 // effectively prevents LLVM from erasing things like /dev/null, any block
386 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000387 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000388 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000389
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000390 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000391 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000392 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000393 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000394
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000395 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000396}
397
Zachary Turner392ed9d2017-02-21 20:55:47 +0000398static bool is_local_impl(struct STATVFS &Vfs) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000399#if defined(__linux__) || defined(__GNU__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +0000400#ifndef NFS_SUPER_MAGIC
401#define NFS_SUPER_MAGIC 0x6969
402#endif
403#ifndef SMB_SUPER_MAGIC
404#define SMB_SUPER_MAGIC 0x517B
405#endif
Zachary Turner6bc2dac2017-02-21 21:13:10 +0000406#ifndef CIFS_MAGIC_NUMBER
407#define CIFS_MAGIC_NUMBER 0xFF534D42
408#endif
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000409#ifdef __GNU__
410 switch ((uint32_t)Vfs.__f_type) {
411#else
Zachary Turner392ed9d2017-02-21 20:55:47 +0000412 switch ((uint32_t)Vfs.f_type) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000413#endif
Zachary Turner392ed9d2017-02-21 20:55:47 +0000414 case NFS_SUPER_MAGIC:
415 case SMB_SUPER_MAGIC:
416 case CIFS_MAGIC_NUMBER:
417 return false;
418 default:
419 return true;
420 }
Nuno Lopes7a1bbd42017-03-09 13:43:31 +0000421#elif defined(__CYGWIN__)
422 // Cygwin doesn't expose this information; would need to use Win32 API.
423 return false;
Petr Hosek87f13432018-05-03 01:38:49 +0000424#elif defined(__Fuchsia__)
425 // Fuchsia doesn't yet support remote filesystem mounts.
426 return true;
Keno Fischer5f4ae7c2019-06-23 00:29:59 +0000427#elif defined(__EMSCRIPTEN__)
428 // Emscripten doesn't currently support remote filesystem mounts.
429 return true;
Tim Northover43d64b02018-07-18 13:42:18 +0000430#elif defined(__HAIKU__)
431 // Haiku doesn't expose this information.
432 return false;
Kamil Rytarowski07c81b12017-06-01 12:57:00 +0000433#elif defined(__sun)
434 // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
435 StringRef fstype(Vfs.f_basetype);
436 // NFS is the only non-local fstype??
437 return !fstype.equals("nfs");
Hubert Tong24168852019-03-29 23:32:47 +0000438#elif defined(_AIX)
439 // Call mntctl; try more than twice in case of timing issues with a concurrent
440 // mount.
441 int Ret;
442 size_t BufSize = 2048u;
443 std::unique_ptr<char[]> Buf;
444 int Tries = 3;
445 while (Tries--) {
446 Buf = llvm::make_unique<char[]>(BufSize);
447 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
448 if (Ret != 0)
449 break;
450 BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
451 Buf.reset();
452 }
453
454 if (Ret == -1)
455 // There was an error; "remote" is the conservative answer.
456 return false;
457
458 // Look for the correct vmount entry.
459 char *CurObjPtr = Buf.get();
460 while (Ret--) {
461 struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
462 static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
463 "fsid length mismatch");
464 if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
465 return (Vp->vmt_flags & MNT_REMOTE) == 0;
466
467 CurObjPtr += Vp->vmt_length;
468 }
469
470 // vmount entry not found; "remote" is the conservative answer.
471 return false;
Zachary Turner392ed9d2017-02-21 20:55:47 +0000472#else
473 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
474#endif
475}
476
477std::error_code is_local(const Twine &Path, bool &Result) {
478 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000479 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Zachary Turner392ed9d2017-02-21 20:55:47 +0000480 return std::error_code(errno, std::generic_category());
481
482 Result = is_local_impl(Vfs);
483 return std::error_code();
484}
485
486std::error_code is_local(int FD, bool &Result) {
487 struct STATVFS Vfs;
488 if (::FSTATVFS(FD, &Vfs))
489 return std::error_code(errno, std::generic_category());
490
491 Result = is_local_impl(Vfs);
492 return std::error_code();
493}
494
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000495std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000496 // Get arguments.
497 SmallString<128> from_storage;
498 SmallString<128> to_storage;
499 StringRef f = from.toNullTerminatedStringRef(from_storage);
500 StringRef t = to.toNullTerminatedStringRef(to_storage);
501
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000502 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000503 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000504
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000505 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000506}
507
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000508std::error_code resize_file(int FD, uint64_t Size) {
Rafael Espindola3816c532016-07-19 20:19:56 +0000509#if defined(HAVE_POSIX_FALLOCATE)
510 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
511 // space, so we get an error if the disk is full.
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000512 if (int Err = ::posix_fallocate(FD, 0, Size)) {
Hubert Tong7f8b3bf2019-04-04 00:40:34 +0000513#ifdef _AIX
514 constexpr int NotSupportedError = ENOTSUP;
515#else
516 constexpr int NotSupportedError = EOPNOTSUPP;
517#endif
518 if (Err != EINVAL && Err != NotSupportedError)
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000519 return std::error_code(Err, std::generic_category());
520 }
521#endif
Rafael Espindola3816c532016-07-19 20:19:56 +0000522 // Use ftruncate as a fallback. It may or may not allocate space. At least on
523 // OS X with HFS+ it does.
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000524 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000525 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000526
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000527 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000528}
529
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000530static int convertAccessMode(AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000531 switch (Mode) {
532 case AccessMode::Exist:
533 return F_OK;
534 case AccessMode::Write:
535 return W_OK;
536 case AccessMode::Execute:
537 return R_OK | X_OK; // scripts also need R_OK.
538 }
539 llvm_unreachable("invalid enum");
540}
Michael J. Spencer45710402010-12-03 01:21:28 +0000541
Rafael Espindola281f23a2014-09-11 20:30:02 +0000542std::error_code access(const Twine &Path, AccessMode Mode) {
543 SmallString<128> PathStorage;
544 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
545
546 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
547 return std::error_code(errno, std::generic_category());
548
549 if (Mode == AccessMode::Execute) {
550 // Don't say that directories are executable.
551 struct stat buf;
552 if (0 != stat(P.begin(), &buf))
553 return errc::permission_denied;
554 if (!S_ISREG(buf.st_mode))
555 return errc::permission_denied;
556 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000557
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000558 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000559}
560
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000561bool can_execute(const Twine &Path) {
562 return !access(Path, AccessMode::Execute);
563}
564
Michael J. Spencer203d7802011-12-12 06:04:28 +0000565bool equivalent(file_status A, file_status B) {
566 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000567 return A.fs_st_dev == B.fs_st_dev &&
568 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000569}
570
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000571std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000572 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000573 if (std::error_code ec = status(A, fsA))
574 return ec;
575 if (std::error_code ec = status(B, fsB))
576 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000577 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000578 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000579}
580
Zachary Turnere48ace62017-03-10 17:39:21 +0000581static void expandTildeExpr(SmallVectorImpl<char> &Path) {
582 StringRef PathStr(Path.begin(), Path.size());
583 if (PathStr.empty() || !PathStr.startswith("~"))
584 return;
585
586 PathStr = PathStr.drop_front();
Zachary Turner18753342017-03-16 22:34:18 +0000587 StringRef Expr =
588 PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +0000589 StringRef Remainder = PathStr.substr(Expr.size() + 1);
590 SmallString<128> Storage;
591 if (Expr.empty()) {
592 // This is just ~/..., resolve it to the current user's home dir.
593 if (!path::home_directory(Storage)) {
594 // For some reason we couldn't get the home directory. Just exit.
595 return;
596 }
597
598 // Overwrite the first character and insert the rest.
599 Path[0] = Storage[0];
600 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
601 return;
602 }
603
604 // This is a string of the form ~username/, look up this user's entry in the
605 // password database.
606 struct passwd *Entry = nullptr;
607 std::string User = Expr.str();
608 Entry = ::getpwnam(User.c_str());
609
610 if (!Entry) {
611 // Unable to look up the entry, just return back the original path.
612 return;
613 }
614
615 Storage = Remainder;
616 Path.clear();
617 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
618 llvm::sys::path::append(Path, Storage);
619}
620
Jonas Devlieghereb23f4302018-11-13 18:23:32 +0000621
622void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
623 dest.clear();
624 if (path.isTriviallyEmpty())
625 return;
626
627 path.toVector(dest);
628 expandTildeExpr(dest);
629
630 return;
631}
632
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000633static file_type typeForMode(mode_t Mode) {
634 if (S_ISDIR(Mode))
635 return file_type::directory_file;
636 else if (S_ISREG(Mode))
637 return file_type::regular_file;
638 else if (S_ISBLK(Mode))
639 return file_type::block_file;
640 else if (S_ISCHR(Mode))
641 return file_type::character_file;
642 else if (S_ISFIFO(Mode))
643 return file_type::fifo_file;
644 else if (S_ISSOCK(Mode))
645 return file_type::socket_file;
646 else if (S_ISLNK(Mode))
647 return file_type::symlink_file;
648 return file_type::type_unknown;
649}
650
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000651static std::error_code fillStatus(int StatRet, const struct stat &Status,
Fangrui Song69d64182018-06-10 04:53:14 +0000652 file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000653 if (StatRet != 0) {
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000654 std::error_code EC(errno, std::generic_category());
655 if (EC == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000656 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000657 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000658 Result = file_status(file_type::status_error);
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000659 return EC;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000660 }
661
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000662 uint32_t atime_nsec, mtime_nsec;
663#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
664 atime_nsec = Status.st_atimespec.tv_nsec;
665 mtime_nsec = Status.st_mtimespec.tv_nsec;
666#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
667 atime_nsec = Status.st_atim.tv_nsec;
668 mtime_nsec = Status.st_mtim.tv_nsec;
669#else
670 atime_nsec = mtime_nsec = 0;
671#endif
672
James Henderson566fdf42017-03-16 11:22:09 +0000673 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000674 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000675 Status.st_nlink, Status.st_ino,
676 Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
677 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000678
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000679 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000680}
681
Zachary Turner82dd5422017-03-07 16:10:10 +0000682std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000683 SmallString<128> PathStorage;
684 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
685
686 struct stat Status;
Zachary Turner82dd5422017-03-07 16:10:10 +0000687 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
Rafael Espindola77021c92013-07-16 03:20:13 +0000688 return fillStatus(StatRet, Status, Result);
689}
690
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000691std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000692 struct stat Status;
693 int StatRet = ::fstat(FD, &Status);
Aaron Ballman345012d2017-03-13 12:24:51 +0000694 return fillStatus(StatRet, Status, Result);
695}
696
Alex Brachet3b715d62019-06-28 03:21:00 +0000697unsigned getUmask() {
698 // Chose arbitary new mask and reset the umask to the old mask.
699 // umask(2) never fails so ignore the return of the second call.
700 unsigned Mask = ::umask(0);
701 (void) ::umask(Mask);
702 return Mask;
703}
704
Fangrui Song6dc59622019-07-11 10:17:59 +0000705std::error_code setPermissions(const Twine &Path, perms Permissions) {
James Henderson566fdf42017-03-16 11:22:09 +0000706 SmallString<128> PathStorage;
707 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
708
709 if (::chmod(P.begin(), Permissions))
710 return std::error_code(errno, std::generic_category());
711 return std::error_code();
712}
713
Fangrui Song6dc59622019-07-11 10:17:59 +0000714std::error_code setPermissions(int FD, perms Permissions) {
715 if (::fchmod(FD, Permissions))
716 return std::error_code(errno, std::generic_category());
717 return std::error_code();
718}
719
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000720std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
721 TimePoint<> ModificationTime) {
Aaron Ballman345012d2017-03-13 12:24:51 +0000722#if defined(HAVE_FUTIMENS)
723 timespec Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000724 Times[0] = sys::toTimeSpec(AccessTime);
725 Times[1] = sys::toTimeSpec(ModificationTime);
Eric Christophera24dc7f2013-07-04 01:10:38 +0000726 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000727 return std::error_code(errno, std::generic_category());
728 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000729#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000730 timeval Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000731 Times[0] = sys::toTimeVal(
732 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
733 Times[1] =
734 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
735 ModificationTime));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000736 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000737 return std::error_code(errno, std::generic_category());
738 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000739#else
740#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000741 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000742#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000743}
744
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000745std::error_code mapped_file_region::init(int FD, uint64_t Offset,
746 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000747 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000748
749 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
750 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Zachary Turner842972b2017-02-22 21:24:06 +0000751#if defined(__APPLE__)
752 //----------------------------------------------------------------------
753 // Newer versions of MacOSX have a flag that will allow us to read from
754 // binaries whose code signature is invalid without crashing by using
755 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
756 // is mapped we can avoid crashing and return zeroes to any pages we try
757 // to read if the media becomes unavailable by using the
758 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
759 // with PROT_READ, so take care not to specify them otherwise.
760 //----------------------------------------------------------------------
761 if (Mode == readonly) {
762#if defined(MAP_RESILIENT_CODESIGN)
763 flags |= MAP_RESILIENT_CODESIGN;
764#endif
765#if defined(MAP_RESILIENT_MEDIA)
766 flags |= MAP_RESILIENT_MEDIA;
767#endif
768 }
769#endif // #if defined (__APPLE__)
Zachary Turner392ed9d2017-02-21 20:55:47 +0000770
Craig Toppere73658d2014-04-28 04:05:08 +0000771 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000772 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000773 return std::error_code(errno, std::generic_category());
774 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000775}
776
Roman Lebedev7c983672017-09-27 15:59:16 +0000777mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000778 uint64_t offset, std::error_code &ec)
Peter Collingbourne881ba102018-06-13 18:03:14 +0000779 : Size(length), Mapping(), Mode(mode) {
Zachary Turner2061ad22018-02-15 18:46:59 +0000780 (void)Mode;
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000781 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000782 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000783 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000784}
785
786mapped_file_region::~mapped_file_region() {
787 if (Mapping)
788 ::munmap(Mapping, Size);
789}
790
Roman Lebedev21b013e2017-09-27 16:08:33 +0000791size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000792 assert(Mapping && "Mapping failed but used anyway!");
793 return Size;
794}
795
796char *mapped_file_region::data() const {
797 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000798 return reinterpret_cast<char*>(Mapping);
799}
800
801const char *mapped_file_region::const_data() const {
802 assert(Mapping && "Mapping failed but used anyway!");
803 return reinterpret_cast<const char*>(Mapping);
804}
805
806int mapped_file_region::alignment() {
Lang Hamese4b4ab62019-05-08 02:11:07 +0000807 return Process::getPageSizeEstimate();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000808}
809
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000810std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000811 StringRef path,
812 bool follow_symlinks) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000813 SmallString<128> path_null(path);
814 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000815 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000816 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000817
818 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
819 // Add something for replace_filename to replace.
820 path::append(path_null, ".");
Zachary Turner260bda32017-03-08 22:49:32 +0000821 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
Michael J. Spencer52714862011-01-05 16:38:57 +0000822 return directory_iterator_increment(it);
823}
824
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000825std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000826 if (it.IterationHandle)
827 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
828 it.IterationHandle = 0;
829 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000830 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000831}
832
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000833static file_type direntType(dirent* Entry) {
834 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
835 // The DTTOIF macro lets us reuse our status -> type conversion.
Jordan Rose887d31c2019-07-18 20:05:11 +0000836 // Note that while glibc provides a macro to see if this is supported,
837 // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
838 // d_type-to-mode_t conversion macro instead.
839#if defined(DTTOIF)
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000840 return typeForMode(DTTOIF(Entry->d_type));
841#else
842 // Other platforms such as Solaris require a stat() to get the type.
843 return file_type::type_unknown;
844#endif
845}
846
847std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000848 errno = 0;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000849 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
850 if (CurDir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000851 return std::error_code(errno, std::generic_category());
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000852 } else if (CurDir != nullptr) {
853 StringRef Name(CurDir->d_name);
854 if ((Name.size() == 1 && Name[0] == '.') ||
855 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
856 return directory_iterator_increment(It);
857 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
Michael J. Spencer52714862011-01-05 16:38:57 +0000858 } else
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000859 return directory_iterator_destruct(It);
Michael J. Spencer52714862011-01-05 16:38:57 +0000860
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000861 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000862}
863
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000864ErrorOr<basic_file_status> directory_entry::status() const {
865 file_status s;
866 if (auto EC = fs::status(Path, s, FollowSymlinks))
867 return EC;
868 return s;
869}
870
Taewook Ohd9153272016-06-13 15:54:56 +0000871#if !defined(F_GETPATH)
872static bool hasProcSelfFD() {
873 // If we have a /proc filesystem mounted, we can quickly establish the
874 // real name of the file with readlink
875 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
876 return Result;
877}
878#endif
879
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000880static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
881 FileAccess Access) {
882 int Result = 0;
883 if (Access == FA_Read)
884 Result |= O_RDONLY;
885 else if (Access == FA_Write)
886 Result |= O_WRONLY;
887 else if (Access == (FA_Read | FA_Write))
888 Result |= O_RDWR;
889
890 // This is for compatibility with old code that assumed F_Append implied
891 // would open an existing file. See Windows/Path.inc for a longer comment.
892 if (Flags & F_Append)
893 Disp = CD_OpenAlways;
894
895 if (Disp == CD_CreateNew) {
896 Result |= O_CREAT; // Create if it doesn't exist.
897 Result |= O_EXCL; // Fail if it does.
898 } else if (Disp == CD_CreateAlways) {
899 Result |= O_CREAT; // Create if it doesn't exist.
900 Result |= O_TRUNC; // Truncate if it does.
901 } else if (Disp == CD_OpenAlways) {
902 Result |= O_CREAT; // Create if it doesn't exist.
903 } else if (Disp == CD_OpenExisting) {
904 // Nothing special, just don't add O_CREAT and we get these semantics.
905 }
906
907 if (Flags & F_Append)
908 Result |= O_APPEND;
909
910#ifdef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000911 if (!(Flags & OF_ChildInherit))
912 Result |= O_CLOEXEC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000913#endif
914
915 return Result;
916}
917
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000918std::error_code openFile(const Twine &Name, int &ResultFD,
919 CreationDisposition Disp, FileAccess Access,
920 OpenFlags Flags, unsigned Mode) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000921 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
922
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000923 SmallString<128> Storage;
924 StringRef P = Name.toNullTerminatedStringRef(Storage);
Hans Wennborg0a0e4112018-08-27 15:55:39 +0000925 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
926 // when open is overloaded, such as in Bionic.
927 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
928 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
Pavel Labathfe09f502017-06-29 13:15:31 +0000929 return std::error_code(errno, std::generic_category());
Pavel Labathf726dfa2017-01-24 10:57:01 +0000930#ifndef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000931 if (!(Flags & OF_ChildInherit)) {
932 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
933 (void)r;
934 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
935 }
Pavel Labathf726dfa2017-01-24 10:57:01 +0000936#endif
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000937 return std::error_code();
938}
939
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000940Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
941 FileAccess Access, OpenFlags Flags,
942 unsigned Mode) {
943
944 int FD;
945 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
946 if (EC)
947 return errorCodeToError(EC);
948 return FD;
949}
950
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000951std::error_code openFileForRead(const Twine &Name, int &ResultFD,
952 OpenFlags Flags,
953 SmallVectorImpl<char> *RealPath) {
954 std::error_code EC =
955 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
956 if (EC)
957 return EC;
958
Taewook Ohd9153272016-06-13 15:54:56 +0000959 // Attempt to get the real name of the file, if the user asked
960 if(!RealPath)
961 return std::error_code();
962 RealPath->clear();
963#if defined(F_GETPATH)
964 // When F_GETPATH is availble, it is the quickest way to get
965 // the real path name.
966 char Buffer[MAXPATHLEN];
967 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
968 RealPath->append(Buffer, Buffer + strlen(Buffer));
969#else
970 char Buffer[PATH_MAX];
971 if (hasProcSelfFD()) {
972 char ProcPath[64];
973 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
974 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
975 if (CharCount > 0)
976 RealPath->append(Buffer, Buffer + CharCount);
977 } else {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000978 SmallString<128> Storage;
979 StringRef P = Name.toNullTerminatedStringRef(Storage);
980
Taewook Ohd9153272016-06-13 15:54:56 +0000981 // Use ::realpath to get the real path name
982 if (::realpath(P.begin(), Buffer) != nullptr)
983 RealPath->append(Buffer, Buffer + strlen(Buffer));
984 }
985#endif
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000986 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000987}
Nick Kledzik18497e92012-06-20 00:28:54 +0000988
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000989Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
Zachary Turner63db25b2018-06-04 19:38:11 +0000990 SmallVectorImpl<char> *RealPath) {
991 file_t ResultFD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000992 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
Zachary Turner63db25b2018-06-04 19:38:11 +0000993 if (EC)
994 return errorCodeToError(EC);
995 return ResultFD;
996}
997
Reid Klecknercc418a32019-07-10 00:34:13 +0000998file_t getStdinHandle() { return 0; }
999file_t getStdoutHandle() { return 1; }
1000file_t getStderrHandle() { return 2; }
1001
1002std::error_code readNativeFile(file_t FD, MutableArrayRef<char> Buf,
1003 size_t *BytesRead) {
1004 *BytesRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Buf.size());
1005 if (ssize_t(*BytesRead) == -1)
1006 return std::error_code(errno, std::generic_category());
1007 return std::error_code();
1008}
1009
1010std::error_code readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1011 size_t Offset) {
1012 char *BufPtr = Buf.data();
1013 size_t BytesLeft = Buf.size();
1014
1015#ifndef HAVE_PREAD
1016 // If we don't have pread, seek to Offset.
1017 if (lseek(FD, Offset, SEEK_SET) == -1)
1018 return std::error_code(errno, std::generic_category());
1019#endif
1020
1021 while (BytesLeft) {
1022#ifdef HAVE_PREAD
1023 ssize_t NumRead = sys::RetryAfterSignal(-1, ::pread, FD, BufPtr, BytesLeft,
1024 Buf.size() - BytesLeft + Offset);
1025#else
1026 ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, BufPtr, BytesLeft);
1027#endif
1028 if (NumRead == -1) {
1029 // Error while reading.
1030 return std::error_code(errno, std::generic_category());
1031 }
1032 if (NumRead == 0) {
1033 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
1034 break;
1035 }
1036 BytesLeft -= NumRead;
1037 BufPtr += NumRead;
1038 }
1039 return std::error_code();
1040}
1041
1042std::error_code closeFile(file_t &F) {
1043 file_t TmpF = F;
Zachary Turner63db25b2018-06-04 19:38:11 +00001044 F = kInvalidFile;
Reid Klecknercc418a32019-07-10 00:34:13 +00001045 return Process::SafelyCloseFileDescriptor(TmpF);
Zachary Turner63db25b2018-06-04 19:38:11 +00001046}
1047
Zachary Turner260bda32017-03-08 22:49:32 +00001048template <typename T>
1049static std::error_code remove_directories_impl(const T &Entry,
1050 bool IgnoreErrors) {
1051 std::error_code EC;
1052 directory_iterator Begin(Entry, EC, false);
1053 directory_iterator End;
1054 while (Begin != End) {
1055 auto &Item = *Begin;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001056 ErrorOr<basic_file_status> st = Item.status();
1057 if (!st && !IgnoreErrors)
1058 return st.getError();
Zachary Turner260bda32017-03-08 22:49:32 +00001059
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001060 if (is_directory(*st)) {
Zachary Turner260bda32017-03-08 22:49:32 +00001061 EC = remove_directories_impl(Item, IgnoreErrors);
1062 if (EC && !IgnoreErrors)
1063 return EC;
1064 }
1065
1066 EC = fs::remove(Item.path(), true);
1067 if (EC && !IgnoreErrors)
1068 return EC;
1069
1070 Begin.increment(EC);
1071 if (EC && !IgnoreErrors)
1072 return EC;
1073 }
1074 return std::error_code();
1075}
1076
1077std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1078 auto EC = remove_directories_impl(path, IgnoreErrors);
1079 if (EC && !IgnoreErrors)
1080 return EC;
1081 EC = fs::remove(path, true);
1082 if (EC && !IgnoreErrors)
1083 return EC;
1084 return std::error_code();
1085}
1086
Zachary Turnere48ace62017-03-10 17:39:21 +00001087std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1088 bool expand_tilde) {
1089 dest.clear();
1090 if (path.isTriviallyEmpty())
1091 return std::error_code();
1092
1093 if (expand_tilde) {
1094 SmallString<128> Storage;
1095 path.toVector(Storage);
1096 expandTildeExpr(Storage);
1097 return real_path(Storage, dest, false);
1098 }
1099
Davide Italiano4762c062018-01-09 17:27:45 +00001100 SmallString<128> Storage;
1101 StringRef P = path.toNullTerminatedStringRef(Storage);
1102 char Buffer[PATH_MAX];
1103 if (::realpath(P.begin(), Buffer) == nullptr)
1104 return std::error_code(errno, std::generic_category());
1105 dest.append(Buffer, Buffer + strlen(Buffer));
Zachary Turnere48ace62017-03-10 17:39:21 +00001106 return std::error_code();
1107}
1108
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001109} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +00001110
1111namespace path {
1112
1113bool home_directory(SmallVectorImpl<char> &result) {
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001114 char *RequestedDir = getenv("HOME");
1115 if (!RequestedDir) {
1116 struct passwd *pw = getpwuid(getuid());
1117 if (pw && pw->pw_dir)
1118 RequestedDir = pw->pw_dir;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001119 }
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001120 if (!RequestedDir)
1121 return false;
1122
1123 result.clear();
1124 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1125 return true;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001126}
1127
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001128static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001129 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1130 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1131 // macros defined in <unistd.h> on darwin >= 9
1132 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1133 : _CS_DARWIN_USER_CACHE_DIR;
1134 size_t ConfLen = confstr(ConfName, nullptr, 0);
1135 if (ConfLen > 0) {
1136 do {
1137 Result.resize(ConfLen);
1138 ConfLen = confstr(ConfName, Result.data(), Result.size());
1139 } while (ConfLen > 0 && ConfLen != Result.size());
1140
1141 if (ConfLen > 0) {
1142 assert(Result.back() == 0);
1143 Result.pop_back();
1144 return true;
1145 }
1146
1147 Result.clear();
1148 }
1149 #endif
1150 return false;
1151}
1152
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001153static const char *getEnvTempDir() {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001154 // Check whether the temporary directory is specified by an environment
1155 // variable.
1156 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1157 for (const char *Env : EnvironmentVariables) {
1158 if (const char *Dir = std::getenv(Env))
1159 return Dir;
1160 }
1161
1162 return nullptr;
1163}
1164
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001165static const char *getDefaultTempDir(bool ErasedOnReboot) {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001166#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +00001167 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +00001168 return P_tmpdir;
1169#endif
1170
1171 if (ErasedOnReboot)
1172 return "/tmp";
1173 return "/var/tmp";
1174}
1175
1176void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1177 Result.clear();
1178
1179 if (ErasedOnReboot) {
1180 // There is no env variable for the cache directory.
1181 if (const char *RequestedDir = getEnvTempDir()) {
1182 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1183 return;
1184 }
1185 }
1186
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001187 if (getDarwinConfDir(ErasedOnReboot, Result))
1188 return;
Rafael Espindola016a6d52014-08-26 14:47:52 +00001189
1190 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1191 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1192}
1193
Peter Collingbournef7d41012014-01-31 23:46:06 +00001194} // end namespace path
1195
Adrian Prantlfac78752019-04-18 21:22:50 +00001196namespace fs {
1197
1198#ifdef __APPLE__
1199/// This implementation tries to perform an APFS CoW clone of the file,
1200/// which can be much faster and uses less space.
Adrian Prantlc90ff5e2019-04-24 19:08:43 +00001201/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1202/// file descriptor variant of this function still uses the default
1203/// implementation.
Adrian Prantlfac78752019-04-18 21:22:50 +00001204std::error_code copy_file(const Twine &From, const Twine &To) {
1205 uint32_t Flag = COPYFILE_DATA;
Adrian Prantlccdefb22019-05-07 17:10:27 +00001206#if __has_builtin(__builtin_available)
Adrian Prantlfac78752019-04-18 21:22:50 +00001207 if (__builtin_available(macos 10.12, *)) {
1208 bool IsSymlink;
1209 if (std::error_code Error = is_symlink_file(From, IsSymlink))
1210 return Error;
1211 // COPYFILE_CLONE clones the symlink instead of following it
1212 // and returns EEXISTS if the target file already exists.
1213 if (!IsSymlink && !exists(To))
1214 Flag = COPYFILE_CLONE;
1215 }
Adrian Prantlccdefb22019-05-07 17:10:27 +00001216#endif
Adrian Prantlfac78752019-04-18 21:22:50 +00001217 int Status =
1218 copyfile(From.str().c_str(), To.str().c_str(), /* State */ NULL, Flag);
1219
1220 if (Status == 0)
1221 return std::error_code();
1222 return std::error_code(errno, std::generic_category());
1223}
Adrian Prantlc90ff5e2019-04-24 19:08:43 +00001224#endif // __APPLE__
Adrian Prantlfac78752019-04-18 21:22:50 +00001225
1226} // end namespace fs
1227
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001228} // end namespace sys
1229} // end namespace llvm