blob: 2a03dc682bced7127dfbc9ee7fdd8c47e84e0aeb [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>
Ed Mastea0a38b82019-11-13 13:24:23 -050041#elif defined(__FreeBSD__)
42#include <osreldate.h>
43#if __FreeBSD_version >= 1300057
44#include <sys/auxv.h>
45#else
46#include <machine/elf.h>
47extern char **environ;
48#endif
David Carlierb79eee42018-11-10 01:01:03 +000049#elif defined(__DragonFly__)
50#include <sys/mount.h>
Rafael Espindola4601c462013-06-26 05:25:44 +000051#endif
52
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000053// Both stdio.h and cstdio are included via different paths and
Joerg Sonnenbergerc0697302012-08-10 10:56:09 +000054// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
55// either.
56#undef ferror
57#undef feof
58
Sylvestre Ledru14ada942012-04-11 15:35:36 +000059// For GNU Hurd
60#if defined(__GNU__) && !defined(PATH_MAX)
61# define PATH_MAX 4096
Sylvestre Ledruf4719c42018-10-23 07:13:47 +000062# define MAXPATHLEN 4096
Sylvestre Ledru14ada942012-04-11 15:35:36 +000063#endif
64
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000065#include <sys/types.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000066#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
Hubert Tong24168852019-03-29 23:32:47 +000067 !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000068#include <sys/statvfs.h>
69#define STATVFS statvfs
Zachary Turner392ed9d2017-02-21 20:55:47 +000070#define FSTATVFS fstatvfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000071#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
72#else
Zachary Turner392ed9d2017-02-21 20:55:47 +000073#if defined(__OpenBSD__) || defined(__FreeBSD__)
Mehdi Amini3ba84ca2016-04-08 16:45:05 +000074#include <sys/mount.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000075#include <sys/param.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000076#elif defined(__linux__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +000077#if defined(HAVE_LINUX_MAGIC_H)
Zachary Turner392ed9d2017-02-21 20:55:47 +000078#include <linux/magic.h>
Michal Gorny5ddd2a52017-02-22 18:09:15 +000079#else
80#if defined(HAVE_LINUX_NFS_FS_H)
81#include <linux/nfs_fs.h>
82#endif
83#if defined(HAVE_LINUX_SMB_H)
84#include <linux/smb.h>
85#endif
86#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000087#include <sys/vfs.h>
Hubert Tong24168852019-03-29 23:32:47 +000088#elif defined(_AIX)
89#include <sys/statfs.h>
90
91// <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
92// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
93// the typedef prior to including <sys/vmount.h> to work around this issue.
94typedef uint_t uint;
95#include <sys/vmount.h>
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000096#else
97#include <sys/mount.h>
98#endif
99#define STATVFS statfs
Zachary Turner392ed9d2017-02-21 20:55:47 +0000100#define FSTATVFS fstatfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000101#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
102#endif
103
David Carlierb79eee42018-11-10 01:01:03 +0000104#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
Zachary Turner392ed9d2017-02-21 20:55:47 +0000105#define STATVFS_F_FLAG(vfs) (vfs).f_flag
106#else
107#define STATVFS_F_FLAG(vfs) (vfs).f_flags
108#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000109
Michael J. Spencer45710402010-12-03 01:21:28 +0000110using namespace llvm;
111
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000112namespace llvm {
113namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000114namespace fs {
Zachary Turner63db25b2018-06-04 19:38:11 +0000115
116const file_t kInvalidFile = -1;
117
Michal Gorny2d8be642019-03-04 04:53:50 +0000118#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000119 defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000120 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__)
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000121static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000122test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000123{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000124 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000125 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000126
Jonas Hahnfelde59746f2019-03-13 10:37:56 +0000127 int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
128 // We cannot write PATH_MAX characters because the string will be terminated
129 // with a null character. Fail if truncation happened.
130 if (chars >= PATH_MAX)
131 return 1;
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000132 if (!realpath(fullpath, ret))
133 return 1;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000134 if (stat(fullpath, &sb) != 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000135 return 1;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000136
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000137 return 0;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000138}
139
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000140static char *
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000141getprogpath(char ret[PATH_MAX], const char *bin)
142{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000143 /* First approach: absolute path. */
144 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000145 if (test_dir(ret, "/", bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000146 return ret;
147 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000148 }
149
150 /* Second approach: relative path. */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000151 if (strchr(bin, '/')) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000152 char cwd[PATH_MAX];
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000153 if (!getcwd(cwd, PATH_MAX))
154 return nullptr;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000155 if (test_dir(ret, cwd, bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000156 return ret;
157 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000158 }
159
160 /* Third approach: $PATH */
Xing Xue2dee0942019-05-16 14:02:13 +0000161 char *pv;
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000162 if ((pv = getenv("PATH")) == nullptr)
163 return nullptr;
Xing Xue2dee0942019-05-16 14:02:13 +0000164 char *s = strdup(pv);
165 if (!s)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000166 return nullptr;
Xing Xue2dee0942019-05-16 14:02:13 +0000167 char *state;
168 for (char *t = strtok_r(s, ":", &state); t != nullptr;
169 t = strtok_r(nullptr, ":", &state)) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000170 if (test_dir(ret, t, bin) == 0) {
Xing Xue2dee0942019-05-16 14:02:13 +0000171 free(s);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000172 return ret;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000173 }
174 }
Xing Xue2dee0942019-05-16 14:02:13 +0000175 free(s);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000176 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000177}
Dimitry Andricebc87792017-05-17 19:33:10 +0000178#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000179
180/// GetMainExecutable - Return the path to the main executable, given the
181/// value of argv[0] from program startup.
182std::string getMainExecutable(const char *argv0, void *MainAddr) {
183#if defined(__APPLE__)
184 // On OS X the executable path is saved to the stack by dyld. Reading it
185 // from there is much faster than calling dladdr, especially for large
186 // binaries with symbols.
187 char exe_path[MAXPATHLEN];
188 uint32_t size = sizeof(exe_path);
189 if (_NSGetExecutablePath(exe_path, &size) == 0) {
190 char link_path[MAXPATHLEN];
191 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000192 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000193 }
Ed Mastea0a38b82019-11-13 13:24:23 -0500194#elif defined(__FreeBSD__)
195 // On FreeBSD if the exec path specified in ELF auxiliary vectors is
196 // preferred, if available. /proc/curproc/file and the KERN_PROC_PATHNAME
197 // sysctl may not return the desired path if there are multiple hardlinks
198 // to the file.
199 char exe_path[PATH_MAX];
200#if __FreeBSD_version >= 1300057
Ed Mastea0a38b82019-11-13 13:24:23 -0500201 if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0)
202 return exe_path;
203#else
204 // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
205 // fall back to finding the ELF auxiliary vectors after the process's
206 // environment.
207 char **p = ::environ;
208 while (*p++ != 0)
209 ;
210 // Iterate through auxiliary vectors for AT_EXECPATH.
211 for (;;) {
212 switch (*(uintptr_t *)p++) {
213 case AT_EXECPATH:
214 return *p;
215 case AT_NULL:
216 break;
217 }
218 p++;
219 }
220#endif
221 // Fall back to argv[0] if auxiliary vectors are not available.
222 if (getprogpath(exe_path, argv0) != NULL)
223 return exe_path;
224#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__minix) || \
225 defined(__DragonFly__) || defined(__FreeBSD_kernel__) || defined(_AIX)
Nico Weber19193172019-08-07 17:00:19 +0000226 const char *curproc = "/proc/curproc/file";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000227 char exe_path[PATH_MAX];
David Chisnall714a4422019-04-29 09:24:51 +0000228 if (sys::fs::exists(curproc)) {
Nico Weber19193172019-08-07 17:00:19 +0000229 ssize_t len = readlink(curproc, exe_path, sizeof(exe_path));
David Chisnall714a4422019-04-29 09:24:51 +0000230 if (len > 0) {
231 // Null terminate the string for realpath. readlink never null
232 // terminates its output.
233 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
234 exe_path[len] = '\0';
235 return exe_path;
236 }
237 }
238 // If we don't have procfs mounted, fall back to argv[0]
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000239 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000240 return exe_path;
kristinaf4267122019-11-01 17:27:24 +0000241#elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000242 char exe_path[MAXPATHLEN];
Nico Weber19193172019-08-07 17:00:19 +0000243 const char *aPath = "/proc/self/exe";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000244 if (sys::fs::exists(aPath)) {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000245 // /proc is not always mounted under Linux (chroot for example).
Nico Weber19193172019-08-07 17:00:19 +0000246 ssize_t len = readlink(aPath, exe_path, sizeof(exe_path));
Reid Kleckner1500eff2018-10-23 23:35:43 +0000247 if (len < 0)
248 return "";
249
250 // Null terminate the string for realpath. readlink never null
251 // terminates its output.
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000252 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
Reid Kleckner1500eff2018-10-23 23:35:43 +0000253 exe_path[len] = '\0';
254
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000255 // On Linux, /proc/self/exe always looks through symlinks. However, on
256 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
257 // the program, and not the eventual binary file. Therefore, call realpath
258 // so this behaves the same on all platforms.
Reid Kleckner1500eff2018-10-23 23:35:43 +0000259#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
Sam McCalledf904e2019-07-02 15:42:37 +0000260 if (char *real_path = realpath(exe_path, NULL)) {
261 std::string ret = std::string(real_path);
262 free(real_path);
263 return ret;
264 }
Reid Kleckner1500eff2018-10-23 23:35:43 +0000265#else
266 char real_path[MAXPATHLEN];
Sam McCalledf904e2019-07-02 15:42:37 +0000267 if (realpath(exe_path, real_path))
268 return std::string(real_path);
Reid Kleckner1500eff2018-10-23 23:35:43 +0000269#endif
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000270 }
Sam McCalledf904e2019-07-02 15:42:37 +0000271 // Fall back to the classical detection.
272 if (getprogpath(exe_path, argv0))
273 return exe_path;
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000274#elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000275 // Use dladdr to get executable path if available.
276 Dl_info DLInfo;
277 int err = dladdr(MainAddr, &DLInfo);
278 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000279 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000280
281 // If the filename is a symlink, we need to resolve and return the location of
282 // the actual executable.
283 char link_path[MAXPATHLEN];
284 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000285 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000286#else
287#error GetMainExecutable is not implemented on this host yet.
288#endif
289 return "";
290}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000291
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000292TimePoint<> basic_file_status::getLastAccessedTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000293 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000294}
295
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000296TimePoint<> basic_file_status::getLastModificationTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000297 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000298}
299
Rafael Espindolad1230992013-07-29 21:55:38 +0000300UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000301 return UniqueID(fs_st_dev, fs_st_ino);
302}
303
Zachary Turner5821a3b2017-03-20 23:55:20 +0000304uint32_t file_status::getLinkCount() const {
305 return fs_st_nlinks;
306}
307
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000308ErrorOr<space_info> disk_space(const Twine &Path) {
309 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000310 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000311 return std::error_code(errno, std::generic_category());
312 auto FrSize = STATVFS_F_FRSIZE(Vfs);
313 space_info SpaceInfo;
314 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
315 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
316 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
317 return SpaceInfo;
318}
319
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000320std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000321 result.clear();
322
323 const char *pwd = ::getenv("PWD");
324 llvm::sys::fs::file_status PWDStatus, DotStatus;
325 if (pwd && llvm::sys::path::is_absolute(pwd) &&
326 !llvm::sys::fs::status(pwd, PWDStatus) &&
327 !llvm::sys::fs::status(".", DotStatus) &&
328 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
329 result.append(pwd, pwd + strlen(pwd));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000330 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000331 }
332
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000333#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000334 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000335#else
336// For GNU Hurd
337 result.reserve(1024);
338#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000339
Michael J. Spencer20daa282010-12-07 01:22:31 +0000340 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000341 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000342 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000343 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000344 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000345 // Otherwise there just wasn't enough space.
346 result.reserve(result.capacity() * 2);
347 } else
348 break;
349 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000350
351 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000352 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000353}
354
Pavel Labath2f096092017-01-24 10:32:03 +0000355std::error_code set_current_path(const Twine &path) {
356 SmallString<128> path_storage;
357 StringRef p = path.toNullTerminatedStringRef(path_storage);
358
359 if (::chdir(p.begin()) == -1)
360 return std::error_code(errno, std::generic_category());
361
362 return std::error_code();
363}
364
Frederic Riss6b9396c2015-08-06 21:04:55 +0000365std::error_code create_directory(const Twine &path, bool IgnoreExisting,
366 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000367 SmallString<128> path_storage;
368 StringRef p = path.toNullTerminatedStringRef(path_storage);
369
Frederic Riss6b9396c2015-08-06 21:04:55 +0000370 if (::mkdir(p.begin(), Perms) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000371 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000372 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000373 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000374
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000375 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000376}
377
Rafael Espindola83f858e2014-03-11 18:40:24 +0000378// Note that we are using symbolic link because hard links are not supported by
379// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000380std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000381 // Get arguments.
382 SmallString<128> from_storage;
383 SmallString<128> to_storage;
384 StringRef f = from.toNullTerminatedStringRef(from_storage);
385 StringRef t = to.toNullTerminatedStringRef(to_storage);
386
Rafael Espindola83f858e2014-03-11 18:40:24 +0000387 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000388 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000389
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000390 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000391}
392
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000393std::error_code create_hard_link(const Twine &to, const Twine &from) {
394 // Get arguments.
395 SmallString<128> from_storage;
396 SmallString<128> to_storage;
397 StringRef f = from.toNullTerminatedStringRef(from_storage);
398 StringRef t = to.toNullTerminatedStringRef(to_storage);
399
400 if (::link(t.begin(), f.begin()) == -1)
401 return std::error_code(errno, std::generic_category());
402
403 return std::error_code();
404}
405
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000406std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000407 SmallString<128> path_storage;
408 StringRef p = path.toNullTerminatedStringRef(path_storage);
409
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000410 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000411 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000412 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000413 return std::error_code(errno, std::generic_category());
414 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000415 }
416
417 // Note: this check catches strange situations. In all cases, LLVM should
418 // only be involved in the creation and deletion of regular files. This
419 // check ensures that what we're trying to erase is a regular file. It
420 // effectively prevents LLVM from erasing things like /dev/null, any block
421 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000422 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000423 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000424
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000425 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000426 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000427 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000428 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000429
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000430 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000431}
432
Zachary Turner392ed9d2017-02-21 20:55:47 +0000433static bool is_local_impl(struct STATVFS &Vfs) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000434#if defined(__linux__) || defined(__GNU__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +0000435#ifndef NFS_SUPER_MAGIC
436#define NFS_SUPER_MAGIC 0x6969
437#endif
438#ifndef SMB_SUPER_MAGIC
439#define SMB_SUPER_MAGIC 0x517B
440#endif
Zachary Turner6bc2dac2017-02-21 21:13:10 +0000441#ifndef CIFS_MAGIC_NUMBER
442#define CIFS_MAGIC_NUMBER 0xFF534D42
443#endif
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000444#ifdef __GNU__
445 switch ((uint32_t)Vfs.__f_type) {
446#else
Zachary Turner392ed9d2017-02-21 20:55:47 +0000447 switch ((uint32_t)Vfs.f_type) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000448#endif
Zachary Turner392ed9d2017-02-21 20:55:47 +0000449 case NFS_SUPER_MAGIC:
450 case SMB_SUPER_MAGIC:
451 case CIFS_MAGIC_NUMBER:
452 return false;
453 default:
454 return true;
455 }
Nuno Lopes7a1bbd42017-03-09 13:43:31 +0000456#elif defined(__CYGWIN__)
457 // Cygwin doesn't expose this information; would need to use Win32 API.
458 return false;
Petr Hosek87f13432018-05-03 01:38:49 +0000459#elif defined(__Fuchsia__)
460 // Fuchsia doesn't yet support remote filesystem mounts.
461 return true;
Keno Fischer5f4ae7c2019-06-23 00:29:59 +0000462#elif defined(__EMSCRIPTEN__)
463 // Emscripten doesn't currently support remote filesystem mounts.
464 return true;
Tim Northover43d64b02018-07-18 13:42:18 +0000465#elif defined(__HAIKU__)
466 // Haiku doesn't expose this information.
467 return false;
Kamil Rytarowski07c81b12017-06-01 12:57:00 +0000468#elif defined(__sun)
469 // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
470 StringRef fstype(Vfs.f_basetype);
471 // NFS is the only non-local fstype??
472 return !fstype.equals("nfs");
Hubert Tong24168852019-03-29 23:32:47 +0000473#elif defined(_AIX)
474 // Call mntctl; try more than twice in case of timing issues with a concurrent
475 // mount.
476 int Ret;
477 size_t BufSize = 2048u;
478 std::unique_ptr<char[]> Buf;
479 int Tries = 3;
480 while (Tries--) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000481 Buf = std::make_unique<char[]>(BufSize);
Hubert Tong24168852019-03-29 23:32:47 +0000482 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
483 if (Ret != 0)
484 break;
485 BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
486 Buf.reset();
487 }
488
489 if (Ret == -1)
490 // There was an error; "remote" is the conservative answer.
491 return false;
492
493 // Look for the correct vmount entry.
494 char *CurObjPtr = Buf.get();
495 while (Ret--) {
496 struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
497 static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
498 "fsid length mismatch");
499 if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
500 return (Vp->vmt_flags & MNT_REMOTE) == 0;
501
502 CurObjPtr += Vp->vmt_length;
503 }
504
505 // vmount entry not found; "remote" is the conservative answer.
506 return false;
Zachary Turner392ed9d2017-02-21 20:55:47 +0000507#else
508 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
509#endif
510}
511
512std::error_code is_local(const Twine &Path, bool &Result) {
513 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000514 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Zachary Turner392ed9d2017-02-21 20:55:47 +0000515 return std::error_code(errno, std::generic_category());
516
517 Result = is_local_impl(Vfs);
518 return std::error_code();
519}
520
521std::error_code is_local(int FD, bool &Result) {
522 struct STATVFS Vfs;
523 if (::FSTATVFS(FD, &Vfs))
524 return std::error_code(errno, std::generic_category());
525
526 Result = is_local_impl(Vfs);
527 return std::error_code();
528}
529
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000530std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000531 // Get arguments.
532 SmallString<128> from_storage;
533 SmallString<128> to_storage;
534 StringRef f = from.toNullTerminatedStringRef(from_storage);
535 StringRef t = to.toNullTerminatedStringRef(to_storage);
536
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000537 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000538 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000539
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000540 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000541}
542
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000543std::error_code resize_file(int FD, uint64_t Size) {
Rafael Espindola3816c532016-07-19 20:19:56 +0000544#if defined(HAVE_POSIX_FALLOCATE)
545 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
546 // space, so we get an error if the disk is full.
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000547 if (int Err = ::posix_fallocate(FD, 0, Size)) {
Hubert Tong7f8b3bf2019-04-04 00:40:34 +0000548#ifdef _AIX
549 constexpr int NotSupportedError = ENOTSUP;
550#else
551 constexpr int NotSupportedError = EOPNOTSUPP;
552#endif
553 if (Err != EINVAL && Err != NotSupportedError)
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000554 return std::error_code(Err, std::generic_category());
555 }
556#endif
Rafael Espindola3816c532016-07-19 20:19:56 +0000557 // Use ftruncate as a fallback. It may or may not allocate space. At least on
558 // OS X with HFS+ it does.
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000559 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000560 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000561
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000562 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000563}
564
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000565static int convertAccessMode(AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000566 switch (Mode) {
567 case AccessMode::Exist:
568 return F_OK;
569 case AccessMode::Write:
570 return W_OK;
571 case AccessMode::Execute:
572 return R_OK | X_OK; // scripts also need R_OK.
573 }
574 llvm_unreachable("invalid enum");
575}
Michael J. Spencer45710402010-12-03 01:21:28 +0000576
Rafael Espindola281f23a2014-09-11 20:30:02 +0000577std::error_code access(const Twine &Path, AccessMode Mode) {
578 SmallString<128> PathStorage;
579 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
580
581 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
582 return std::error_code(errno, std::generic_category());
583
584 if (Mode == AccessMode::Execute) {
585 // Don't say that directories are executable.
586 struct stat buf;
587 if (0 != stat(P.begin(), &buf))
588 return errc::permission_denied;
589 if (!S_ISREG(buf.st_mode))
590 return errc::permission_denied;
591 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000592
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000593 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000594}
595
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000596bool can_execute(const Twine &Path) {
597 return !access(Path, AccessMode::Execute);
598}
599
Michael J. Spencer203d7802011-12-12 06:04:28 +0000600bool equivalent(file_status A, file_status B) {
601 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000602 return A.fs_st_dev == B.fs_st_dev &&
603 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000604}
605
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000606std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000607 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000608 if (std::error_code ec = status(A, fsA))
609 return ec;
610 if (std::error_code ec = status(B, fsB))
611 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000612 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000613 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000614}
615
Zachary Turnere48ace62017-03-10 17:39:21 +0000616static void expandTildeExpr(SmallVectorImpl<char> &Path) {
617 StringRef PathStr(Path.begin(), Path.size());
618 if (PathStr.empty() || !PathStr.startswith("~"))
619 return;
620
621 PathStr = PathStr.drop_front();
Zachary Turner18753342017-03-16 22:34:18 +0000622 StringRef Expr =
623 PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +0000624 StringRef Remainder = PathStr.substr(Expr.size() + 1);
625 SmallString<128> Storage;
626 if (Expr.empty()) {
627 // This is just ~/..., resolve it to the current user's home dir.
628 if (!path::home_directory(Storage)) {
629 // For some reason we couldn't get the home directory. Just exit.
630 return;
631 }
632
633 // Overwrite the first character and insert the rest.
634 Path[0] = Storage[0];
635 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
636 return;
637 }
638
639 // This is a string of the form ~username/, look up this user's entry in the
640 // password database.
641 struct passwd *Entry = nullptr;
642 std::string User = Expr.str();
643 Entry = ::getpwnam(User.c_str());
644
645 if (!Entry) {
646 // Unable to look up the entry, just return back the original path.
647 return;
648 }
649
650 Storage = Remainder;
651 Path.clear();
652 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
653 llvm::sys::path::append(Path, Storage);
654}
655
Jonas Devlieghereb23f4302018-11-13 18:23:32 +0000656
657void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
658 dest.clear();
659 if (path.isTriviallyEmpty())
660 return;
661
662 path.toVector(dest);
663 expandTildeExpr(dest);
664
665 return;
666}
667
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000668static file_type typeForMode(mode_t Mode) {
669 if (S_ISDIR(Mode))
670 return file_type::directory_file;
671 else if (S_ISREG(Mode))
672 return file_type::regular_file;
673 else if (S_ISBLK(Mode))
674 return file_type::block_file;
675 else if (S_ISCHR(Mode))
676 return file_type::character_file;
677 else if (S_ISFIFO(Mode))
678 return file_type::fifo_file;
679 else if (S_ISSOCK(Mode))
680 return file_type::socket_file;
681 else if (S_ISLNK(Mode))
682 return file_type::symlink_file;
683 return file_type::type_unknown;
684}
685
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000686static std::error_code fillStatus(int StatRet, const struct stat &Status,
Fangrui Song69d64182018-06-10 04:53:14 +0000687 file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000688 if (StatRet != 0) {
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000689 std::error_code EC(errno, std::generic_category());
690 if (EC == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000691 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000692 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000693 Result = file_status(file_type::status_error);
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000694 return EC;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000695 }
696
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000697 uint32_t atime_nsec, mtime_nsec;
698#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
699 atime_nsec = Status.st_atimespec.tv_nsec;
700 mtime_nsec = Status.st_mtimespec.tv_nsec;
701#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
702 atime_nsec = Status.st_atim.tv_nsec;
703 mtime_nsec = Status.st_mtim.tv_nsec;
704#else
705 atime_nsec = mtime_nsec = 0;
706#endif
707
James Henderson566fdf42017-03-16 11:22:09 +0000708 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000709 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000710 Status.st_nlink, Status.st_ino,
711 Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
712 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000713
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000714 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000715}
716
Zachary Turner82dd5422017-03-07 16:10:10 +0000717std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000718 SmallString<128> PathStorage;
719 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
720
721 struct stat Status;
Zachary Turner82dd5422017-03-07 16:10:10 +0000722 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
Rafael Espindola77021c92013-07-16 03:20:13 +0000723 return fillStatus(StatRet, Status, Result);
724}
725
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000726std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000727 struct stat Status;
728 int StatRet = ::fstat(FD, &Status);
Aaron Ballman345012d2017-03-13 12:24:51 +0000729 return fillStatus(StatRet, Status, Result);
730}
731
Alex Brachet3b715d62019-06-28 03:21:00 +0000732unsigned getUmask() {
733 // Chose arbitary new mask and reset the umask to the old mask.
734 // umask(2) never fails so ignore the return of the second call.
735 unsigned Mask = ::umask(0);
736 (void) ::umask(Mask);
737 return Mask;
738}
739
Fangrui Song6dc59622019-07-11 10:17:59 +0000740std::error_code setPermissions(const Twine &Path, perms Permissions) {
James Henderson566fdf42017-03-16 11:22:09 +0000741 SmallString<128> PathStorage;
742 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
743
744 if (::chmod(P.begin(), Permissions))
745 return std::error_code(errno, std::generic_category());
746 return std::error_code();
747}
748
Fangrui Song6dc59622019-07-11 10:17:59 +0000749std::error_code setPermissions(int FD, perms Permissions) {
750 if (::fchmod(FD, Permissions))
751 return std::error_code(errno, std::generic_category());
752 return std::error_code();
753}
754
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000755std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
756 TimePoint<> ModificationTime) {
Aaron Ballman345012d2017-03-13 12:24:51 +0000757#if defined(HAVE_FUTIMENS)
758 timespec Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000759 Times[0] = sys::toTimeSpec(AccessTime);
760 Times[1] = sys::toTimeSpec(ModificationTime);
Eric Christophera24dc7f2013-07-04 01:10:38 +0000761 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000762 return std::error_code(errno, std::generic_category());
763 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000764#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000765 timeval Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000766 Times[0] = sys::toTimeVal(
767 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
768 Times[1] =
769 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
770 ModificationTime));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000771 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000772 return std::error_code(errno, std::generic_category());
773 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000774#else
775#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000776 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000777#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000778}
779
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000780std::error_code mapped_file_region::init(int FD, uint64_t Offset,
781 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000782 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000783
784 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
785 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Zachary Turner842972b2017-02-22 21:24:06 +0000786#if defined(__APPLE__)
787 //----------------------------------------------------------------------
788 // Newer versions of MacOSX have a flag that will allow us to read from
789 // binaries whose code signature is invalid without crashing by using
790 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
791 // is mapped we can avoid crashing and return zeroes to any pages we try
792 // to read if the media becomes unavailable by using the
793 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
794 // with PROT_READ, so take care not to specify them otherwise.
795 //----------------------------------------------------------------------
796 if (Mode == readonly) {
797#if defined(MAP_RESILIENT_CODESIGN)
798 flags |= MAP_RESILIENT_CODESIGN;
799#endif
800#if defined(MAP_RESILIENT_MEDIA)
801 flags |= MAP_RESILIENT_MEDIA;
802#endif
803 }
804#endif // #if defined (__APPLE__)
Zachary Turner392ed9d2017-02-21 20:55:47 +0000805
Craig Toppere73658d2014-04-28 04:05:08 +0000806 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000807 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000808 return std::error_code(errno, std::generic_category());
809 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000810}
811
Roman Lebedev7c983672017-09-27 15:59:16 +0000812mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000813 uint64_t offset, std::error_code &ec)
Peter Collingbourne881ba102018-06-13 18:03:14 +0000814 : Size(length), Mapping(), Mode(mode) {
Zachary Turner2061ad22018-02-15 18:46:59 +0000815 (void)Mode;
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000816 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000817 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000818 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000819}
820
821mapped_file_region::~mapped_file_region() {
822 if (Mapping)
823 ::munmap(Mapping, Size);
824}
825
Roman Lebedev21b013e2017-09-27 16:08:33 +0000826size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000827 assert(Mapping && "Mapping failed but used anyway!");
828 return Size;
829}
830
831char *mapped_file_region::data() const {
832 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000833 return reinterpret_cast<char*>(Mapping);
834}
835
836const char *mapped_file_region::const_data() const {
837 assert(Mapping && "Mapping failed but used anyway!");
838 return reinterpret_cast<const char*>(Mapping);
839}
840
841int mapped_file_region::alignment() {
Lang Hamese4b4ab62019-05-08 02:11:07 +0000842 return Process::getPageSizeEstimate();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000843}
844
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000845std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000846 StringRef path,
847 bool follow_symlinks) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000848 SmallString<128> path_null(path);
849 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000850 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000851 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000852
853 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
854 // Add something for replace_filename to replace.
855 path::append(path_null, ".");
Zachary Turner260bda32017-03-08 22:49:32 +0000856 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
Michael J. Spencer52714862011-01-05 16:38:57 +0000857 return directory_iterator_increment(it);
858}
859
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000860std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000861 if (it.IterationHandle)
862 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
863 it.IterationHandle = 0;
864 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000865 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000866}
867
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000868static file_type direntType(dirent* Entry) {
869 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
870 // The DTTOIF macro lets us reuse our status -> type conversion.
Jordan Rose887d31c2019-07-18 20:05:11 +0000871 // Note that while glibc provides a macro to see if this is supported,
872 // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
873 // d_type-to-mode_t conversion macro instead.
874#if defined(DTTOIF)
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000875 return typeForMode(DTTOIF(Entry->d_type));
876#else
877 // Other platforms such as Solaris require a stat() to get the type.
878 return file_type::type_unknown;
879#endif
880}
881
882std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000883 errno = 0;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000884 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
885 if (CurDir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000886 return std::error_code(errno, std::generic_category());
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000887 } else if (CurDir != nullptr) {
888 StringRef Name(CurDir->d_name);
889 if ((Name.size() == 1 && Name[0] == '.') ||
890 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
891 return directory_iterator_increment(It);
892 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
Michael J. Spencer52714862011-01-05 16:38:57 +0000893 } else
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000894 return directory_iterator_destruct(It);
Michael J. Spencer52714862011-01-05 16:38:57 +0000895
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000896 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000897}
898
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000899ErrorOr<basic_file_status> directory_entry::status() const {
900 file_status s;
901 if (auto EC = fs::status(Path, s, FollowSymlinks))
902 return EC;
903 return s;
904}
905
Taewook Ohd9153272016-06-13 15:54:56 +0000906#if !defined(F_GETPATH)
907static bool hasProcSelfFD() {
908 // If we have a /proc filesystem mounted, we can quickly establish the
909 // real name of the file with readlink
910 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
911 return Result;
912}
913#endif
914
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000915static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
916 FileAccess Access) {
917 int Result = 0;
918 if (Access == FA_Read)
919 Result |= O_RDONLY;
920 else if (Access == FA_Write)
921 Result |= O_WRONLY;
922 else if (Access == (FA_Read | FA_Write))
923 Result |= O_RDWR;
924
Fangrui Songd9b948b2019-08-05 05:43:48 +0000925 // This is for compatibility with old code that assumed OF_Append implied
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000926 // would open an existing file. See Windows/Path.inc for a longer comment.
Fangrui Songd9b948b2019-08-05 05:43:48 +0000927 if (Flags & OF_Append)
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000928 Disp = CD_OpenAlways;
929
930 if (Disp == CD_CreateNew) {
931 Result |= O_CREAT; // Create if it doesn't exist.
932 Result |= O_EXCL; // Fail if it does.
933 } else if (Disp == CD_CreateAlways) {
934 Result |= O_CREAT; // Create if it doesn't exist.
935 Result |= O_TRUNC; // Truncate if it does.
936 } else if (Disp == CD_OpenAlways) {
937 Result |= O_CREAT; // Create if it doesn't exist.
938 } else if (Disp == CD_OpenExisting) {
939 // Nothing special, just don't add O_CREAT and we get these semantics.
940 }
941
Fangrui Songd9b948b2019-08-05 05:43:48 +0000942 if (Flags & OF_Append)
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000943 Result |= O_APPEND;
944
945#ifdef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000946 if (!(Flags & OF_ChildInherit))
947 Result |= O_CLOEXEC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000948#endif
949
950 return Result;
951}
952
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000953std::error_code openFile(const Twine &Name, int &ResultFD,
954 CreationDisposition Disp, FileAccess Access,
955 OpenFlags Flags, unsigned Mode) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000956 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
957
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000958 SmallString<128> Storage;
959 StringRef P = Name.toNullTerminatedStringRef(Storage);
Hans Wennborg0a0e4112018-08-27 15:55:39 +0000960 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
961 // when open is overloaded, such as in Bionic.
962 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
963 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
Pavel Labathfe09f502017-06-29 13:15:31 +0000964 return std::error_code(errno, std::generic_category());
Pavel Labathf726dfa2017-01-24 10:57:01 +0000965#ifndef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000966 if (!(Flags & OF_ChildInherit)) {
967 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
968 (void)r;
969 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
970 }
Pavel Labathf726dfa2017-01-24 10:57:01 +0000971#endif
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000972 return std::error_code();
973}
974
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000975Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
976 FileAccess Access, OpenFlags Flags,
977 unsigned Mode) {
978
979 int FD;
980 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
981 if (EC)
982 return errorCodeToError(EC);
983 return FD;
984}
985
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000986std::error_code openFileForRead(const Twine &Name, int &ResultFD,
987 OpenFlags Flags,
988 SmallVectorImpl<char> *RealPath) {
989 std::error_code EC =
990 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
991 if (EC)
992 return EC;
993
Taewook Ohd9153272016-06-13 15:54:56 +0000994 // Attempt to get the real name of the file, if the user asked
995 if(!RealPath)
996 return std::error_code();
997 RealPath->clear();
998#if defined(F_GETPATH)
999 // When F_GETPATH is availble, it is the quickest way to get
1000 // the real path name.
1001 char Buffer[MAXPATHLEN];
1002 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1003 RealPath->append(Buffer, Buffer + strlen(Buffer));
1004#else
1005 char Buffer[PATH_MAX];
1006 if (hasProcSelfFD()) {
1007 char ProcPath[64];
1008 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
1009 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
1010 if (CharCount > 0)
1011 RealPath->append(Buffer, Buffer + CharCount);
1012 } else {
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001013 SmallString<128> Storage;
1014 StringRef P = Name.toNullTerminatedStringRef(Storage);
1015
Taewook Ohd9153272016-06-13 15:54:56 +00001016 // Use ::realpath to get the real path name
1017 if (::realpath(P.begin(), Buffer) != nullptr)
1018 RealPath->append(Buffer, Buffer + strlen(Buffer));
1019 }
1020#endif
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001021 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001022}
Nick Kledzik18497e92012-06-20 00:28:54 +00001023
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001024Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
Zachary Turner63db25b2018-06-04 19:38:11 +00001025 SmallVectorImpl<char> *RealPath) {
1026 file_t ResultFD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001027 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
Zachary Turner63db25b2018-06-04 19:38:11 +00001028 if (EC)
1029 return errorCodeToError(EC);
1030 return ResultFD;
1031}
1032
Reid Klecknercc418a32019-07-10 00:34:13 +00001033file_t getStdinHandle() { return 0; }
1034file_t getStdoutHandle() { return 1; }
1035file_t getStderrHandle() { return 2; }
1036
Pavel Labath1b30ea22019-08-22 08:13:30 +00001037Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
1038 ssize_t NumRead =
1039 sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Buf.size());
1040 if (ssize_t(NumRead) == -1)
1041 return errorCodeToError(std::error_code(errno, std::generic_category()));
1042 return NumRead;
Reid Klecknercc418a32019-07-10 00:34:13 +00001043}
1044
Pavel Labath1b30ea22019-08-22 08:13:30 +00001045Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1046 uint64_t Offset) {
Reid Klecknercc418a32019-07-10 00:34:13 +00001047#ifdef HAVE_PREAD
Pavel Labath1b30ea22019-08-22 08:13:30 +00001048 ssize_t NumRead =
1049 sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Buf.size(), Offset);
Reid Klecknercc418a32019-07-10 00:34:13 +00001050#else
Pavel Labath1b30ea22019-08-22 08:13:30 +00001051 if (lseek(FD, Offset, SEEK_SET) == -1)
1052 return errorCodeToError(std::error_code(errno, std::generic_category()));
1053 ssize_t NumRead =
1054 sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Buf.size());
Reid Klecknercc418a32019-07-10 00:34:13 +00001055#endif
Pavel Labath1b30ea22019-08-22 08:13:30 +00001056 if (NumRead == -1)
1057 return errorCodeToError(std::error_code(errno, std::generic_category()));
1058 return NumRead;
Reid Klecknercc418a32019-07-10 00:34:13 +00001059}
1060
1061std::error_code closeFile(file_t &F) {
1062 file_t TmpF = F;
Zachary Turner63db25b2018-06-04 19:38:11 +00001063 F = kInvalidFile;
Reid Klecknercc418a32019-07-10 00:34:13 +00001064 return Process::SafelyCloseFileDescriptor(TmpF);
Zachary Turner63db25b2018-06-04 19:38:11 +00001065}
1066
Zachary Turner260bda32017-03-08 22:49:32 +00001067template <typename T>
1068static std::error_code remove_directories_impl(const T &Entry,
1069 bool IgnoreErrors) {
1070 std::error_code EC;
1071 directory_iterator Begin(Entry, EC, false);
1072 directory_iterator End;
1073 while (Begin != End) {
1074 auto &Item = *Begin;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001075 ErrorOr<basic_file_status> st = Item.status();
1076 if (!st && !IgnoreErrors)
1077 return st.getError();
Zachary Turner260bda32017-03-08 22:49:32 +00001078
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001079 if (is_directory(*st)) {
Zachary Turner260bda32017-03-08 22:49:32 +00001080 EC = remove_directories_impl(Item, IgnoreErrors);
1081 if (EC && !IgnoreErrors)
1082 return EC;
1083 }
1084
1085 EC = fs::remove(Item.path(), true);
1086 if (EC && !IgnoreErrors)
1087 return EC;
1088
1089 Begin.increment(EC);
1090 if (EC && !IgnoreErrors)
1091 return EC;
1092 }
1093 return std::error_code();
1094}
1095
1096std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1097 auto EC = remove_directories_impl(path, IgnoreErrors);
1098 if (EC && !IgnoreErrors)
1099 return EC;
1100 EC = fs::remove(path, true);
1101 if (EC && !IgnoreErrors)
1102 return EC;
1103 return std::error_code();
1104}
1105
Zachary Turnere48ace62017-03-10 17:39:21 +00001106std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1107 bool expand_tilde) {
1108 dest.clear();
1109 if (path.isTriviallyEmpty())
1110 return std::error_code();
1111
1112 if (expand_tilde) {
1113 SmallString<128> Storage;
1114 path.toVector(Storage);
1115 expandTildeExpr(Storage);
1116 return real_path(Storage, dest, false);
1117 }
1118
Davide Italiano4762c062018-01-09 17:27:45 +00001119 SmallString<128> Storage;
1120 StringRef P = path.toNullTerminatedStringRef(Storage);
1121 char Buffer[PATH_MAX];
1122 if (::realpath(P.begin(), Buffer) == nullptr)
1123 return std::error_code(errno, std::generic_category());
1124 dest.append(Buffer, Buffer + strlen(Buffer));
Zachary Turnere48ace62017-03-10 17:39:21 +00001125 return std::error_code();
1126}
1127
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001128} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +00001129
1130namespace path {
1131
1132bool home_directory(SmallVectorImpl<char> &result) {
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001133 char *RequestedDir = getenv("HOME");
1134 if (!RequestedDir) {
1135 struct passwd *pw = getpwuid(getuid());
1136 if (pw && pw->pw_dir)
1137 RequestedDir = pw->pw_dir;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001138 }
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001139 if (!RequestedDir)
1140 return false;
1141
1142 result.clear();
1143 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1144 return true;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001145}
1146
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001147static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001148 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1149 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1150 // macros defined in <unistd.h> on darwin >= 9
1151 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1152 : _CS_DARWIN_USER_CACHE_DIR;
1153 size_t ConfLen = confstr(ConfName, nullptr, 0);
1154 if (ConfLen > 0) {
1155 do {
1156 Result.resize(ConfLen);
1157 ConfLen = confstr(ConfName, Result.data(), Result.size());
1158 } while (ConfLen > 0 && ConfLen != Result.size());
1159
1160 if (ConfLen > 0) {
1161 assert(Result.back() == 0);
1162 Result.pop_back();
1163 return true;
1164 }
1165
1166 Result.clear();
1167 }
1168 #endif
1169 return false;
1170}
1171
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001172static const char *getEnvTempDir() {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001173 // Check whether the temporary directory is specified by an environment
1174 // variable.
1175 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1176 for (const char *Env : EnvironmentVariables) {
1177 if (const char *Dir = std::getenv(Env))
1178 return Dir;
1179 }
1180
1181 return nullptr;
1182}
1183
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001184static const char *getDefaultTempDir(bool ErasedOnReboot) {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001185#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +00001186 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +00001187 return P_tmpdir;
1188#endif
1189
1190 if (ErasedOnReboot)
1191 return "/tmp";
1192 return "/var/tmp";
1193}
1194
1195void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1196 Result.clear();
1197
1198 if (ErasedOnReboot) {
1199 // There is no env variable for the cache directory.
1200 if (const char *RequestedDir = getEnvTempDir()) {
1201 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1202 return;
1203 }
1204 }
1205
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001206 if (getDarwinConfDir(ErasedOnReboot, Result))
1207 return;
Rafael Espindola016a6d52014-08-26 14:47:52 +00001208
1209 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1210 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1211}
1212
Peter Collingbournef7d41012014-01-31 23:46:06 +00001213} // end namespace path
1214
Adrian Prantlfac78752019-04-18 21:22:50 +00001215namespace fs {
1216
1217#ifdef __APPLE__
1218/// This implementation tries to perform an APFS CoW clone of the file,
1219/// which can be much faster and uses less space.
Adrian Prantlc90ff5e2019-04-24 19:08:43 +00001220/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1221/// file descriptor variant of this function still uses the default
1222/// implementation.
Adrian Prantlfac78752019-04-18 21:22:50 +00001223std::error_code copy_file(const Twine &From, const Twine &To) {
1224 uint32_t Flag = COPYFILE_DATA;
Yi Kong1755abe2019-07-26 05:17:14 +00001225#if __has_builtin(__builtin_available) && defined(COPYFILE_CLONE)
Adrian Prantlfac78752019-04-18 21:22:50 +00001226 if (__builtin_available(macos 10.12, *)) {
1227 bool IsSymlink;
1228 if (std::error_code Error = is_symlink_file(From, IsSymlink))
1229 return Error;
1230 // COPYFILE_CLONE clones the symlink instead of following it
1231 // and returns EEXISTS if the target file already exists.
1232 if (!IsSymlink && !exists(To))
1233 Flag = COPYFILE_CLONE;
1234 }
Adrian Prantlccdefb22019-05-07 17:10:27 +00001235#endif
Adrian Prantlfac78752019-04-18 21:22:50 +00001236 int Status =
1237 copyfile(From.str().c_str(), To.str().c_str(), /* State */ NULL, Flag);
1238
1239 if (Status == 0)
1240 return std::error_code();
1241 return std::error_code(errno, std::generic_category());
1242}
Adrian Prantlc90ff5e2019-04-24 19:08:43 +00001243#endif // __APPLE__
Adrian Prantlfac78752019-04-18 21:22:50 +00001244
1245} // end namespace fs
1246
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001247} // end namespace sys
1248} // end namespace llvm