blob: fbe3ed11c59b8bc6fe530a2f60bacb3b78c4f307 [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{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000135 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000136
137 /* First approach: absolute path. */
138 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000139 if (test_dir(ret, "/", bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000140 return ret;
141 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000142 }
143
144 /* Second approach: relative path. */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000145 if (strchr(bin, '/')) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000146 char cwd[PATH_MAX];
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000147 if (!getcwd(cwd, PATH_MAX))
148 return nullptr;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000149 if (test_dir(ret, cwd, bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000150 return ret;
151 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000152 }
153
154 /* Third approach: $PATH */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000155 if ((pv = getenv("PATH")) == nullptr)
156 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000157 s = pv = strdup(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000158 if (!pv)
159 return nullptr;
160 while ((t = strsep(&s, ":")) != nullptr) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000161 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000162 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000163 return ret;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000164 }
165 }
166 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000167 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000168}
Dimitry Andricebc87792017-05-17 19:33:10 +0000169#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000170
171/// GetMainExecutable - Return the path to the main executable, given the
172/// value of argv[0] from program startup.
173std::string getMainExecutable(const char *argv0, void *MainAddr) {
174#if defined(__APPLE__)
175 // On OS X the executable path is saved to the stack by dyld. Reading it
176 // from there is much faster than calling dladdr, especially for large
177 // binaries with symbols.
178 char exe_path[MAXPATHLEN];
179 uint32_t size = sizeof(exe_path);
180 if (_NSGetExecutablePath(exe_path, &size) == 0) {
181 char link_path[MAXPATHLEN];
182 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000183 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000184 }
Michal Gorny2d8be642019-03-04 04:53:50 +0000185#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000186 defined(__minix) || defined(__DragonFly__) || \
187 defined(__FreeBSD_kernel__) || defined(_AIX)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000188 char exe_path[PATH_MAX];
189
190 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000191 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000192#elif defined(__linux__) || defined(__CYGWIN__)
193 char exe_path[MAXPATHLEN];
194 StringRef aPath("/proc/self/exe");
195 if (sys::fs::exists(aPath)) {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000196 // /proc is not always mounted under Linux (chroot for example).
197 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
198 if (len < 0)
199 return "";
200
201 // Null terminate the string for realpath. readlink never null
202 // terminates its output.
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000203 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
Reid Kleckner1500eff2018-10-23 23:35:43 +0000204 exe_path[len] = '\0';
205
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000206 // On Linux, /proc/self/exe always looks through symlinks. However, on
207 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
208 // the program, and not the eventual binary file. Therefore, call realpath
209 // so this behaves the same on all platforms.
Reid Kleckner1500eff2018-10-23 23:35:43 +0000210#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
211 char *real_path = realpath(exe_path, NULL);
212 std::string ret = std::string(real_path);
213 free(real_path);
214 return ret;
215#else
216 char real_path[MAXPATHLEN];
217 realpath(exe_path, real_path);
218 return std::string(real_path);
219#endif
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000220 } else {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000221 // Fall back to the classical detection.
222 if (getprogpath(exe_path, argv0))
223 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000224 }
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000225#elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000226 // Use dladdr to get executable path if available.
227 Dl_info DLInfo;
228 int err = dladdr(MainAddr, &DLInfo);
229 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000230 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000231
232 // If the filename is a symlink, we need to resolve and return the location of
233 // the actual executable.
234 char link_path[MAXPATHLEN];
235 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000236 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000237#else
238#error GetMainExecutable is not implemented on this host yet.
239#endif
240 return "";
241}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000242
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000243TimePoint<> basic_file_status::getLastAccessedTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000244 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000245}
246
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000247TimePoint<> basic_file_status::getLastModificationTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000248 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000249}
250
Rafael Espindolad1230992013-07-29 21:55:38 +0000251UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000252 return UniqueID(fs_st_dev, fs_st_ino);
253}
254
Zachary Turner5821a3b2017-03-20 23:55:20 +0000255uint32_t file_status::getLinkCount() const {
256 return fs_st_nlinks;
257}
258
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000259ErrorOr<space_info> disk_space(const Twine &Path) {
260 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000261 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000262 return std::error_code(errno, std::generic_category());
263 auto FrSize = STATVFS_F_FRSIZE(Vfs);
264 space_info SpaceInfo;
265 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
266 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
267 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
268 return SpaceInfo;
269}
270
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000271std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000272 result.clear();
273
274 const char *pwd = ::getenv("PWD");
275 llvm::sys::fs::file_status PWDStatus, DotStatus;
276 if (pwd && llvm::sys::path::is_absolute(pwd) &&
277 !llvm::sys::fs::status(pwd, PWDStatus) &&
278 !llvm::sys::fs::status(".", DotStatus) &&
279 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
280 result.append(pwd, pwd + strlen(pwd));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000281 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000282 }
283
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000284#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000285 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000286#else
287// For GNU Hurd
288 result.reserve(1024);
289#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000290
Michael J. Spencer20daa282010-12-07 01:22:31 +0000291 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000292 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000293 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000294 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000295 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000296 // Otherwise there just wasn't enough space.
297 result.reserve(result.capacity() * 2);
298 } else
299 break;
300 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000301
302 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000303 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000304}
305
Pavel Labath2f096092017-01-24 10:32:03 +0000306std::error_code set_current_path(const Twine &path) {
307 SmallString<128> path_storage;
308 StringRef p = path.toNullTerminatedStringRef(path_storage);
309
310 if (::chdir(p.begin()) == -1)
311 return std::error_code(errno, std::generic_category());
312
313 return std::error_code();
314}
315
Frederic Riss6b9396c2015-08-06 21:04:55 +0000316std::error_code create_directory(const Twine &path, bool IgnoreExisting,
317 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000318 SmallString<128> path_storage;
319 StringRef p = path.toNullTerminatedStringRef(path_storage);
320
Frederic Riss6b9396c2015-08-06 21:04:55 +0000321 if (::mkdir(p.begin(), Perms) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000322 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000323 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000324 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000325
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000326 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000327}
328
Rafael Espindola83f858e2014-03-11 18:40:24 +0000329// Note that we are using symbolic link because hard links are not supported by
330// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000331std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000332 // 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
Rafael Espindola83f858e2014-03-11 18:40:24 +0000338 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000339 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000340
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000341 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000342}
343
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000344std::error_code create_hard_link(const Twine &to, const Twine &from) {
345 // Get arguments.
346 SmallString<128> from_storage;
347 SmallString<128> to_storage;
348 StringRef f = from.toNullTerminatedStringRef(from_storage);
349 StringRef t = to.toNullTerminatedStringRef(to_storage);
350
351 if (::link(t.begin(), f.begin()) == -1)
352 return std::error_code(errno, std::generic_category());
353
354 return std::error_code();
355}
356
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000357std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000358 SmallString<128> path_storage;
359 StringRef p = path.toNullTerminatedStringRef(path_storage);
360
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000361 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000362 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000363 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000364 return std::error_code(errno, std::generic_category());
365 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000366 }
367
368 // Note: this check catches strange situations. In all cases, LLVM should
369 // only be involved in the creation and deletion of regular files. This
370 // check ensures that what we're trying to erase is a regular file. It
371 // effectively prevents LLVM from erasing things like /dev/null, any block
372 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000373 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000374 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000375
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000376 if (::remove(p.begin()) == -1) {
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());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000379 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000380
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000381 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000382}
383
Zachary Turner392ed9d2017-02-21 20:55:47 +0000384static bool is_local_impl(struct STATVFS &Vfs) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000385#if defined(__linux__) || defined(__GNU__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +0000386#ifndef NFS_SUPER_MAGIC
387#define NFS_SUPER_MAGIC 0x6969
388#endif
389#ifndef SMB_SUPER_MAGIC
390#define SMB_SUPER_MAGIC 0x517B
391#endif
Zachary Turner6bc2dac2017-02-21 21:13:10 +0000392#ifndef CIFS_MAGIC_NUMBER
393#define CIFS_MAGIC_NUMBER 0xFF534D42
394#endif
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000395#ifdef __GNU__
396 switch ((uint32_t)Vfs.__f_type) {
397#else
Zachary Turner392ed9d2017-02-21 20:55:47 +0000398 switch ((uint32_t)Vfs.f_type) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000399#endif
Zachary Turner392ed9d2017-02-21 20:55:47 +0000400 case NFS_SUPER_MAGIC:
401 case SMB_SUPER_MAGIC:
402 case CIFS_MAGIC_NUMBER:
403 return false;
404 default:
405 return true;
406 }
Nuno Lopes7a1bbd42017-03-09 13:43:31 +0000407#elif defined(__CYGWIN__)
408 // Cygwin doesn't expose this information; would need to use Win32 API.
409 return false;
Petr Hosek87f13432018-05-03 01:38:49 +0000410#elif defined(__Fuchsia__)
411 // Fuchsia doesn't yet support remote filesystem mounts.
412 return true;
Tim Northover43d64b02018-07-18 13:42:18 +0000413#elif defined(__HAIKU__)
414 // Haiku doesn't expose this information.
415 return false;
Kamil Rytarowski07c81b12017-06-01 12:57:00 +0000416#elif defined(__sun)
417 // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
418 StringRef fstype(Vfs.f_basetype);
419 // NFS is the only non-local fstype??
420 return !fstype.equals("nfs");
Hubert Tong24168852019-03-29 23:32:47 +0000421#elif defined(_AIX)
422 // Call mntctl; try more than twice in case of timing issues with a concurrent
423 // mount.
424 int Ret;
425 size_t BufSize = 2048u;
426 std::unique_ptr<char[]> Buf;
427 int Tries = 3;
428 while (Tries--) {
429 Buf = llvm::make_unique<char[]>(BufSize);
430 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
431 if (Ret != 0)
432 break;
433 BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
434 Buf.reset();
435 }
436
437 if (Ret == -1)
438 // There was an error; "remote" is the conservative answer.
439 return false;
440
441 // Look for the correct vmount entry.
442 char *CurObjPtr = Buf.get();
443 while (Ret--) {
444 struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
445 static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
446 "fsid length mismatch");
447 if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
448 return (Vp->vmt_flags & MNT_REMOTE) == 0;
449
450 CurObjPtr += Vp->vmt_length;
451 }
452
453 // vmount entry not found; "remote" is the conservative answer.
454 return false;
Zachary Turner392ed9d2017-02-21 20:55:47 +0000455#else
456 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
457#endif
458}
459
460std::error_code is_local(const Twine &Path, bool &Result) {
461 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000462 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Zachary Turner392ed9d2017-02-21 20:55:47 +0000463 return std::error_code(errno, std::generic_category());
464
465 Result = is_local_impl(Vfs);
466 return std::error_code();
467}
468
469std::error_code is_local(int FD, bool &Result) {
470 struct STATVFS Vfs;
471 if (::FSTATVFS(FD, &Vfs))
472 return std::error_code(errno, std::generic_category());
473
474 Result = is_local_impl(Vfs);
475 return std::error_code();
476}
477
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000478std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000479 // Get arguments.
480 SmallString<128> from_storage;
481 SmallString<128> to_storage;
482 StringRef f = from.toNullTerminatedStringRef(from_storage);
483 StringRef t = to.toNullTerminatedStringRef(to_storage);
484
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000485 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000486 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000487
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000488 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000489}
490
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000491std::error_code resize_file(int FD, uint64_t Size) {
Rafael Espindola3816c532016-07-19 20:19:56 +0000492#if defined(HAVE_POSIX_FALLOCATE)
493 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
494 // space, so we get an error if the disk is full.
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000495 if (int Err = ::posix_fallocate(FD, 0, Size)) {
Hubert Tong7f8b3bf2019-04-04 00:40:34 +0000496#ifdef _AIX
497 constexpr int NotSupportedError = ENOTSUP;
498#else
499 constexpr int NotSupportedError = EOPNOTSUPP;
500#endif
501 if (Err != EINVAL && Err != NotSupportedError)
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000502 return std::error_code(Err, std::generic_category());
503 }
504#endif
Rafael Espindola3816c532016-07-19 20:19:56 +0000505 // Use ftruncate as a fallback. It may or may not allocate space. At least on
506 // OS X with HFS+ it does.
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000507 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000508 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000509
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000510 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000511}
512
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000513static int convertAccessMode(AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000514 switch (Mode) {
515 case AccessMode::Exist:
516 return F_OK;
517 case AccessMode::Write:
518 return W_OK;
519 case AccessMode::Execute:
520 return R_OK | X_OK; // scripts also need R_OK.
521 }
522 llvm_unreachable("invalid enum");
523}
Michael J. Spencer45710402010-12-03 01:21:28 +0000524
Rafael Espindola281f23a2014-09-11 20:30:02 +0000525std::error_code access(const Twine &Path, AccessMode Mode) {
526 SmallString<128> PathStorage;
527 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
528
529 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
530 return std::error_code(errno, std::generic_category());
531
532 if (Mode == AccessMode::Execute) {
533 // Don't say that directories are executable.
534 struct stat buf;
535 if (0 != stat(P.begin(), &buf))
536 return errc::permission_denied;
537 if (!S_ISREG(buf.st_mode))
538 return errc::permission_denied;
539 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000540
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000541 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000542}
543
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000544bool can_execute(const Twine &Path) {
545 return !access(Path, AccessMode::Execute);
546}
547
Michael J. Spencer203d7802011-12-12 06:04:28 +0000548bool equivalent(file_status A, file_status B) {
549 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000550 return A.fs_st_dev == B.fs_st_dev &&
551 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000552}
553
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000554std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000555 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000556 if (std::error_code ec = status(A, fsA))
557 return ec;
558 if (std::error_code ec = status(B, fsB))
559 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000560 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000561 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000562}
563
Zachary Turnere48ace62017-03-10 17:39:21 +0000564static void expandTildeExpr(SmallVectorImpl<char> &Path) {
565 StringRef PathStr(Path.begin(), Path.size());
566 if (PathStr.empty() || !PathStr.startswith("~"))
567 return;
568
569 PathStr = PathStr.drop_front();
Zachary Turner18753342017-03-16 22:34:18 +0000570 StringRef Expr =
571 PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +0000572 StringRef Remainder = PathStr.substr(Expr.size() + 1);
573 SmallString<128> Storage;
574 if (Expr.empty()) {
575 // This is just ~/..., resolve it to the current user's home dir.
576 if (!path::home_directory(Storage)) {
577 // For some reason we couldn't get the home directory. Just exit.
578 return;
579 }
580
581 // Overwrite the first character and insert the rest.
582 Path[0] = Storage[0];
583 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
584 return;
585 }
586
587 // This is a string of the form ~username/, look up this user's entry in the
588 // password database.
589 struct passwd *Entry = nullptr;
590 std::string User = Expr.str();
591 Entry = ::getpwnam(User.c_str());
592
593 if (!Entry) {
594 // Unable to look up the entry, just return back the original path.
595 return;
596 }
597
598 Storage = Remainder;
599 Path.clear();
600 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
601 llvm::sys::path::append(Path, Storage);
602}
603
Jonas Devlieghereb23f4302018-11-13 18:23:32 +0000604
605void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
606 dest.clear();
607 if (path.isTriviallyEmpty())
608 return;
609
610 path.toVector(dest);
611 expandTildeExpr(dest);
612
613 return;
614}
615
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000616static file_type typeForMode(mode_t Mode) {
617 if (S_ISDIR(Mode))
618 return file_type::directory_file;
619 else if (S_ISREG(Mode))
620 return file_type::regular_file;
621 else if (S_ISBLK(Mode))
622 return file_type::block_file;
623 else if (S_ISCHR(Mode))
624 return file_type::character_file;
625 else if (S_ISFIFO(Mode))
626 return file_type::fifo_file;
627 else if (S_ISSOCK(Mode))
628 return file_type::socket_file;
629 else if (S_ISLNK(Mode))
630 return file_type::symlink_file;
631 return file_type::type_unknown;
632}
633
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000634static std::error_code fillStatus(int StatRet, const struct stat &Status,
Fangrui Song69d64182018-06-10 04:53:14 +0000635 file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000636 if (StatRet != 0) {
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000637 std::error_code EC(errno, std::generic_category());
638 if (EC == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000639 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000640 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000641 Result = file_status(file_type::status_error);
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000642 return EC;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000643 }
644
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000645 uint32_t atime_nsec, mtime_nsec;
646#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
647 atime_nsec = Status.st_atimespec.tv_nsec;
648 mtime_nsec = Status.st_mtimespec.tv_nsec;
649#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
650 atime_nsec = Status.st_atim.tv_nsec;
651 mtime_nsec = Status.st_mtim.tv_nsec;
652#else
653 atime_nsec = mtime_nsec = 0;
654#endif
655
James Henderson566fdf42017-03-16 11:22:09 +0000656 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000657 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000658 Status.st_nlink, Status.st_ino,
659 Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
660 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000661
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000662 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000663}
664
Zachary Turner82dd5422017-03-07 16:10:10 +0000665std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000666 SmallString<128> PathStorage;
667 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
668
669 struct stat Status;
Zachary Turner82dd5422017-03-07 16:10:10 +0000670 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
Rafael Espindola77021c92013-07-16 03:20:13 +0000671 return fillStatus(StatRet, Status, Result);
672}
673
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000674std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000675 struct stat Status;
676 int StatRet = ::fstat(FD, &Status);
Aaron Ballman345012d2017-03-13 12:24:51 +0000677 return fillStatus(StatRet, Status, Result);
678}
679
James Henderson566fdf42017-03-16 11:22:09 +0000680std::error_code setPermissions(const Twine &Path, perms Permissions) {
681 SmallString<128> PathStorage;
682 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
683
684 if (::chmod(P.begin(), Permissions))
685 return std::error_code(errno, std::generic_category());
686 return std::error_code();
687}
688
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000689std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
690 TimePoint<> ModificationTime) {
Aaron Ballman345012d2017-03-13 12:24:51 +0000691#if defined(HAVE_FUTIMENS)
692 timespec Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000693 Times[0] = sys::toTimeSpec(AccessTime);
694 Times[1] = sys::toTimeSpec(ModificationTime);
Eric Christophera24dc7f2013-07-04 01:10:38 +0000695 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000696 return std::error_code(errno, std::generic_category());
697 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000698#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000699 timeval Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000700 Times[0] = sys::toTimeVal(
701 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
702 Times[1] =
703 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
704 ModificationTime));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000705 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000706 return std::error_code(errno, std::generic_category());
707 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000708#else
709#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000710 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000711#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000712}
713
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000714std::error_code mapped_file_region::init(int FD, uint64_t Offset,
715 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000716 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000717
718 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
719 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Zachary Turner842972b2017-02-22 21:24:06 +0000720#if defined(__APPLE__)
721 //----------------------------------------------------------------------
722 // Newer versions of MacOSX have a flag that will allow us to read from
723 // binaries whose code signature is invalid without crashing by using
724 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
725 // is mapped we can avoid crashing and return zeroes to any pages we try
726 // to read if the media becomes unavailable by using the
727 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
728 // with PROT_READ, so take care not to specify them otherwise.
729 //----------------------------------------------------------------------
730 if (Mode == readonly) {
731#if defined(MAP_RESILIENT_CODESIGN)
732 flags |= MAP_RESILIENT_CODESIGN;
733#endif
734#if defined(MAP_RESILIENT_MEDIA)
735 flags |= MAP_RESILIENT_MEDIA;
736#endif
737 }
738#endif // #if defined (__APPLE__)
Zachary Turner392ed9d2017-02-21 20:55:47 +0000739
Craig Toppere73658d2014-04-28 04:05:08 +0000740 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000741 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000742 return std::error_code(errno, std::generic_category());
743 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000744}
745
Roman Lebedev7c983672017-09-27 15:59:16 +0000746mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000747 uint64_t offset, std::error_code &ec)
Peter Collingbourne881ba102018-06-13 18:03:14 +0000748 : Size(length), Mapping(), Mode(mode) {
Zachary Turner2061ad22018-02-15 18:46:59 +0000749 (void)Mode;
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000750 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000751 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000752 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000753}
754
755mapped_file_region::~mapped_file_region() {
756 if (Mapping)
757 ::munmap(Mapping, Size);
758}
759
Roman Lebedev21b013e2017-09-27 16:08:33 +0000760size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000761 assert(Mapping && "Mapping failed but used anyway!");
762 return Size;
763}
764
765char *mapped_file_region::data() const {
766 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000767 return reinterpret_cast<char*>(Mapping);
768}
769
770const char *mapped_file_region::const_data() const {
771 assert(Mapping && "Mapping failed but used anyway!");
772 return reinterpret_cast<const char*>(Mapping);
773}
774
775int mapped_file_region::alignment() {
Rafael Espindolac0610bf2014-12-04 16:59:36 +0000776 return Process::getPageSize();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000777}
778
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000779std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000780 StringRef path,
781 bool follow_symlinks) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000782 SmallString<128> path_null(path);
783 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000784 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000785 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000786
787 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
788 // Add something for replace_filename to replace.
789 path::append(path_null, ".");
Zachary Turner260bda32017-03-08 22:49:32 +0000790 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
Michael J. Spencer52714862011-01-05 16:38:57 +0000791 return directory_iterator_increment(it);
792}
793
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000794std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000795 if (it.IterationHandle)
796 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
797 it.IterationHandle = 0;
798 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000799 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000800}
801
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000802static file_type direntType(dirent* Entry) {
803 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
804 // The DTTOIF macro lets us reuse our status -> type conversion.
805#if defined(_DIRENT_HAVE_D_TYPE) && defined(DTTOIF)
806 return typeForMode(DTTOIF(Entry->d_type));
807#else
808 // Other platforms such as Solaris require a stat() to get the type.
809 return file_type::type_unknown;
810#endif
811}
812
813std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000814 errno = 0;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000815 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
816 if (CurDir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000817 return std::error_code(errno, std::generic_category());
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000818 } else if (CurDir != nullptr) {
819 StringRef Name(CurDir->d_name);
820 if ((Name.size() == 1 && Name[0] == '.') ||
821 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
822 return directory_iterator_increment(It);
823 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
Michael J. Spencer52714862011-01-05 16:38:57 +0000824 } else
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000825 return directory_iterator_destruct(It);
Michael J. Spencer52714862011-01-05 16:38:57 +0000826
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000827 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000828}
829
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000830ErrorOr<basic_file_status> directory_entry::status() const {
831 file_status s;
832 if (auto EC = fs::status(Path, s, FollowSymlinks))
833 return EC;
834 return s;
835}
836
Taewook Ohd9153272016-06-13 15:54:56 +0000837#if !defined(F_GETPATH)
838static bool hasProcSelfFD() {
839 // If we have a /proc filesystem mounted, we can quickly establish the
840 // real name of the file with readlink
841 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
842 return Result;
843}
844#endif
845
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000846static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
847 FileAccess Access) {
848 int Result = 0;
849 if (Access == FA_Read)
850 Result |= O_RDONLY;
851 else if (Access == FA_Write)
852 Result |= O_WRONLY;
853 else if (Access == (FA_Read | FA_Write))
854 Result |= O_RDWR;
855
856 // This is for compatibility with old code that assumed F_Append implied
857 // would open an existing file. See Windows/Path.inc for a longer comment.
858 if (Flags & F_Append)
859 Disp = CD_OpenAlways;
860
861 if (Disp == CD_CreateNew) {
862 Result |= O_CREAT; // Create if it doesn't exist.
863 Result |= O_EXCL; // Fail if it does.
864 } else if (Disp == CD_CreateAlways) {
865 Result |= O_CREAT; // Create if it doesn't exist.
866 Result |= O_TRUNC; // Truncate if it does.
867 } else if (Disp == CD_OpenAlways) {
868 Result |= O_CREAT; // Create if it doesn't exist.
869 } else if (Disp == CD_OpenExisting) {
870 // Nothing special, just don't add O_CREAT and we get these semantics.
871 }
872
873 if (Flags & F_Append)
874 Result |= O_APPEND;
875
876#ifdef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000877 if (!(Flags & OF_ChildInherit))
878 Result |= O_CLOEXEC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000879#endif
880
881 return Result;
882}
883
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000884std::error_code openFile(const Twine &Name, int &ResultFD,
885 CreationDisposition Disp, FileAccess Access,
886 OpenFlags Flags, unsigned Mode) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000887 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
888
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000889 SmallString<128> Storage;
890 StringRef P = Name.toNullTerminatedStringRef(Storage);
Hans Wennborg0a0e4112018-08-27 15:55:39 +0000891 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
892 // when open is overloaded, such as in Bionic.
893 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
894 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
Pavel Labathfe09f502017-06-29 13:15:31 +0000895 return std::error_code(errno, std::generic_category());
Pavel Labathf726dfa2017-01-24 10:57:01 +0000896#ifndef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000897 if (!(Flags & OF_ChildInherit)) {
898 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
899 (void)r;
900 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
901 }
Pavel Labathf726dfa2017-01-24 10:57:01 +0000902#endif
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000903 return std::error_code();
904}
905
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000906Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
907 FileAccess Access, OpenFlags Flags,
908 unsigned Mode) {
909
910 int FD;
911 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
912 if (EC)
913 return errorCodeToError(EC);
914 return FD;
915}
916
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000917std::error_code openFileForRead(const Twine &Name, int &ResultFD,
918 OpenFlags Flags,
919 SmallVectorImpl<char> *RealPath) {
920 std::error_code EC =
921 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
922 if (EC)
923 return EC;
924
Taewook Ohd9153272016-06-13 15:54:56 +0000925 // Attempt to get the real name of the file, if the user asked
926 if(!RealPath)
927 return std::error_code();
928 RealPath->clear();
929#if defined(F_GETPATH)
930 // When F_GETPATH is availble, it is the quickest way to get
931 // the real path name.
932 char Buffer[MAXPATHLEN];
933 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
934 RealPath->append(Buffer, Buffer + strlen(Buffer));
935#else
936 char Buffer[PATH_MAX];
937 if (hasProcSelfFD()) {
938 char ProcPath[64];
939 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
940 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
941 if (CharCount > 0)
942 RealPath->append(Buffer, Buffer + CharCount);
943 } else {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000944 SmallString<128> Storage;
945 StringRef P = Name.toNullTerminatedStringRef(Storage);
946
Taewook Ohd9153272016-06-13 15:54:56 +0000947 // Use ::realpath to get the real path name
948 if (::realpath(P.begin(), Buffer) != nullptr)
949 RealPath->append(Buffer, Buffer + strlen(Buffer));
950 }
951#endif
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000952 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000953}
Nick Kledzik18497e92012-06-20 00:28:54 +0000954
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000955Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
Zachary Turner63db25b2018-06-04 19:38:11 +0000956 SmallVectorImpl<char> *RealPath) {
957 file_t ResultFD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000958 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
Zachary Turner63db25b2018-06-04 19:38:11 +0000959 if (EC)
960 return errorCodeToError(EC);
961 return ResultFD;
962}
963
Zachary Turner63db25b2018-06-04 19:38:11 +0000964void closeFile(file_t &F) {
965 ::close(F);
966 F = kInvalidFile;
967}
968
Zachary Turner260bda32017-03-08 22:49:32 +0000969template <typename T>
970static std::error_code remove_directories_impl(const T &Entry,
971 bool IgnoreErrors) {
972 std::error_code EC;
973 directory_iterator Begin(Entry, EC, false);
974 directory_iterator End;
975 while (Begin != End) {
976 auto &Item = *Begin;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000977 ErrorOr<basic_file_status> st = Item.status();
978 if (!st && !IgnoreErrors)
979 return st.getError();
Zachary Turner260bda32017-03-08 22:49:32 +0000980
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000981 if (is_directory(*st)) {
Zachary Turner260bda32017-03-08 22:49:32 +0000982 EC = remove_directories_impl(Item, IgnoreErrors);
983 if (EC && !IgnoreErrors)
984 return EC;
985 }
986
987 EC = fs::remove(Item.path(), true);
988 if (EC && !IgnoreErrors)
989 return EC;
990
991 Begin.increment(EC);
992 if (EC && !IgnoreErrors)
993 return EC;
994 }
995 return std::error_code();
996}
997
998std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
999 auto EC = remove_directories_impl(path, IgnoreErrors);
1000 if (EC && !IgnoreErrors)
1001 return EC;
1002 EC = fs::remove(path, true);
1003 if (EC && !IgnoreErrors)
1004 return EC;
1005 return std::error_code();
1006}
1007
Zachary Turnere48ace62017-03-10 17:39:21 +00001008std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1009 bool expand_tilde) {
1010 dest.clear();
1011 if (path.isTriviallyEmpty())
1012 return std::error_code();
1013
1014 if (expand_tilde) {
1015 SmallString<128> Storage;
1016 path.toVector(Storage);
1017 expandTildeExpr(Storage);
1018 return real_path(Storage, dest, false);
1019 }
1020
Davide Italiano4762c062018-01-09 17:27:45 +00001021 SmallString<128> Storage;
1022 StringRef P = path.toNullTerminatedStringRef(Storage);
1023 char Buffer[PATH_MAX];
1024 if (::realpath(P.begin(), Buffer) == nullptr)
1025 return std::error_code(errno, std::generic_category());
1026 dest.append(Buffer, Buffer + strlen(Buffer));
Zachary Turnere48ace62017-03-10 17:39:21 +00001027 return std::error_code();
1028}
1029
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001030} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +00001031
1032namespace path {
1033
1034bool home_directory(SmallVectorImpl<char> &result) {
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001035 char *RequestedDir = getenv("HOME");
1036 if (!RequestedDir) {
1037 struct passwd *pw = getpwuid(getuid());
1038 if (pw && pw->pw_dir)
1039 RequestedDir = pw->pw_dir;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001040 }
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001041 if (!RequestedDir)
1042 return false;
1043
1044 result.clear();
1045 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1046 return true;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001047}
1048
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001049static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001050 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1051 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1052 // macros defined in <unistd.h> on darwin >= 9
1053 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1054 : _CS_DARWIN_USER_CACHE_DIR;
1055 size_t ConfLen = confstr(ConfName, nullptr, 0);
1056 if (ConfLen > 0) {
1057 do {
1058 Result.resize(ConfLen);
1059 ConfLen = confstr(ConfName, Result.data(), Result.size());
1060 } while (ConfLen > 0 && ConfLen != Result.size());
1061
1062 if (ConfLen > 0) {
1063 assert(Result.back() == 0);
1064 Result.pop_back();
1065 return true;
1066 }
1067
1068 Result.clear();
1069 }
1070 #endif
1071 return false;
1072}
1073
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001074static const char *getEnvTempDir() {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001075 // Check whether the temporary directory is specified by an environment
1076 // variable.
1077 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1078 for (const char *Env : EnvironmentVariables) {
1079 if (const char *Dir = std::getenv(Env))
1080 return Dir;
1081 }
1082
1083 return nullptr;
1084}
1085
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001086static const char *getDefaultTempDir(bool ErasedOnReboot) {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001087#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +00001088 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +00001089 return P_tmpdir;
1090#endif
1091
1092 if (ErasedOnReboot)
1093 return "/tmp";
1094 return "/var/tmp";
1095}
1096
1097void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1098 Result.clear();
1099
1100 if (ErasedOnReboot) {
1101 // There is no env variable for the cache directory.
1102 if (const char *RequestedDir = getEnvTempDir()) {
1103 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1104 return;
1105 }
1106 }
1107
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001108 if (getDarwinConfDir(ErasedOnReboot, Result))
1109 return;
Rafael Espindola016a6d52014-08-26 14:47:52 +00001110
1111 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1112 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1113}
1114
Peter Collingbournef7d41012014-01-31 23:46:06 +00001115} // end namespace path
1116
Adrian Prantlfac78752019-04-18 21:22:50 +00001117namespace fs {
1118
1119#ifdef __APPLE__
1120/// This implementation tries to perform an APFS CoW clone of the file,
1121/// which can be much faster and uses less space.
1122std::error_code copy_file(const Twine &From, const Twine &To) {
1123 uint32_t Flag = COPYFILE_DATA;
1124 if (__builtin_available(macos 10.12, *)) {
1125 bool IsSymlink;
1126 if (std::error_code Error = is_symlink_file(From, IsSymlink))
1127 return Error;
1128 // COPYFILE_CLONE clones the symlink instead of following it
1129 // and returns EEXISTS if the target file already exists.
1130 if (!IsSymlink && !exists(To))
1131 Flag = COPYFILE_CLONE;
1132 }
1133
1134 int Status =
1135 copyfile(From.str().c_str(), To.str().c_str(), /* State */ NULL, Flag);
1136
1137 if (Status == 0)
1138 return std::error_code();
1139 return std::error_code(errno, std::generic_category());
1140}
1141
1142/// This implementation tries to perform an APFS CoW clone of the file,
1143/// which can be much faster and uses less space.
1144std::error_code copy_file(const Twine &From, int ToFD) {
1145 int ReadFD;
1146 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
1147 return EC;
1148
1149 uint32_t Flag = COPYFILE_DATA;
1150 if (__builtin_available(macos 10.12, *))
1151 Flag = COPYFILE_CLONE;
1152
1153 int Status = fcopyfile(ReadFD, ToFD, /*State*/ NULL, Flag);
1154
1155 close(ReadFD);
1156 if (Status == 0)
1157 return std::error_code();
1158 return std::error_code(errno, std::generic_category());
1159}
1160#endif
1161
1162} // end namespace fs
1163
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001164} // end namespace sys
1165} // end namespace llvm