blob: a02585c3bdc264a9d04d736267d37d646f2030a7 [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael J. Spencerebad2f92010-11-29 22:28:51 +00006//
7//===----------------------------------------------------------------------===//
8//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00009// This file implements the Unix specific implementation of the Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000010//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic UNIX code that
15//=== is guaranteed to work on *all* UNIX variants.
16//===----------------------------------------------------------------------===//
17
18#include "Unix.h"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000019#include <limits.h>
20#include <stdio.h>
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000021#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
Taewook Ohd9153272016-06-13 15:54:56 +000027#ifdef HAVE_UNISTD_H
28#include <unistd.h>
29#endif
Nick Kledzik18497e92012-06-20 00:28:54 +000030#ifdef HAVE_SYS_MMAN_H
31#include <sys/mman.h>
32#endif
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000033
Nico Weberf3db8e32018-04-02 17:17:29 +000034#include <dirent.h>
Zachary Turnere48ace62017-03-10 17:39:21 +000035#include <pwd.h>
36
Rafael Espindola4601c462013-06-26 05:25:44 +000037#ifdef __APPLE__
38#include <mach-o/dyld.h>
Taewook Ohd9153272016-06-13 15:54:56 +000039#include <sys/attr.h>
David Carlierb79eee42018-11-10 01:01:03 +000040#elif defined(__DragonFly__)
41#include <sys/mount.h>
Rafael Espindola4601c462013-06-26 05:25:44 +000042#endif
43
Simon Pilgrimf2fbf432016-11-20 13:47:59 +000044// Both stdio.h and cstdio are included via different paths and
Joerg Sonnenbergerc0697302012-08-10 10:56:09 +000045// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
46// either.
47#undef ferror
48#undef feof
49
Sylvestre Ledru14ada942012-04-11 15:35:36 +000050// For GNU Hurd
51#if defined(__GNU__) && !defined(PATH_MAX)
52# define PATH_MAX 4096
Sylvestre Ledruf4719c42018-10-23 07:13:47 +000053# define MAXPATHLEN 4096
Sylvestre Ledru14ada942012-04-11 15:35:36 +000054#endif
55
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000056#include <sys/types.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000057#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
Hubert Tong24168852019-03-29 23:32:47 +000058 !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000059#include <sys/statvfs.h>
60#define STATVFS statvfs
Zachary Turner392ed9d2017-02-21 20:55:47 +000061#define FSTATVFS fstatvfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000062#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
63#else
Zachary Turner392ed9d2017-02-21 20:55:47 +000064#if defined(__OpenBSD__) || defined(__FreeBSD__)
Mehdi Amini3ba84ca2016-04-08 16:45:05 +000065#include <sys/mount.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000066#include <sys/param.h>
Zachary Turner392ed9d2017-02-21 20:55:47 +000067#elif defined(__linux__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +000068#if defined(HAVE_LINUX_MAGIC_H)
Zachary Turner392ed9d2017-02-21 20:55:47 +000069#include <linux/magic.h>
Michal Gorny5ddd2a52017-02-22 18:09:15 +000070#else
71#if defined(HAVE_LINUX_NFS_FS_H)
72#include <linux/nfs_fs.h>
73#endif
74#if defined(HAVE_LINUX_SMB_H)
75#include <linux/smb.h>
76#endif
77#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000078#include <sys/vfs.h>
Hubert Tong24168852019-03-29 23:32:47 +000079#elif defined(_AIX)
80#include <sys/statfs.h>
81
82// <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
83// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
84// the typedef prior to including <sys/vmount.h> to work around this issue.
85typedef uint_t uint;
86#include <sys/vmount.h>
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000087#else
88#include <sys/mount.h>
89#endif
90#define STATVFS statfs
Zachary Turner392ed9d2017-02-21 20:55:47 +000091#define FSTATVFS fstatfs
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +000092#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
93#endif
94
David Carlierb79eee42018-11-10 01:01:03 +000095#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
Zachary Turner392ed9d2017-02-21 20:55:47 +000096#define STATVFS_F_FLAG(vfs) (vfs).f_flag
97#else
98#define STATVFS_F_FLAG(vfs) (vfs).f_flags
99#endif
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000100
Michael J. Spencer45710402010-12-03 01:21:28 +0000101using namespace llvm;
102
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000103namespace llvm {
104namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000105namespace fs {
Zachary Turner63db25b2018-06-04 19:38:11 +0000106
107const file_t kInvalidFile = -1;
108
Michal Gorny2d8be642019-03-04 04:53:50 +0000109#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000110 defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000111 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__)
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000112static int
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000113test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000114{
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000115 struct stat sb;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000116 char fullpath[PATH_MAX];
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000117
Jonas Hahnfelde59746f2019-03-13 10:37:56 +0000118 int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
119 // We cannot write PATH_MAX characters because the string will be terminated
120 // with a null character. Fail if truncation happened.
121 if (chars >= PATH_MAX)
122 return 1;
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000123 if (!realpath(fullpath, ret))
124 return 1;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000125 if (stat(fullpath, &sb) != 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000126 return 1;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000127
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000128 return 0;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000129}
130
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000131static char *
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000132getprogpath(char ret[PATH_MAX], const char *bin)
133{
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000134 char *pv, *s, *t;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000135
136 /* First approach: absolute path. */
137 if (bin[0] == '/') {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000138 if (test_dir(ret, "/", bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000139 return ret;
140 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000141 }
142
143 /* Second approach: relative path. */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000144 if (strchr(bin, '/')) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000145 char cwd[PATH_MAX];
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000146 if (!getcwd(cwd, PATH_MAX))
147 return nullptr;
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000148 if (test_dir(ret, cwd, bin) == 0)
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000149 return ret;
150 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000151 }
152
153 /* Third approach: $PATH */
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000154 if ((pv = getenv("PATH")) == nullptr)
155 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000156 s = pv = strdup(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000157 if (!pv)
158 return nullptr;
159 while ((t = strsep(&s, ":")) != nullptr) {
Sylvestre Ledru21e674722013-12-09 16:27:00 +0000160 if (test_dir(ret, t, bin) == 0) {
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000161 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000162 return ret;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000163 }
164 }
165 free(pv);
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000166 return nullptr;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000167}
Dimitry Andricebc87792017-05-17 19:33:10 +0000168#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000169
170/// GetMainExecutable - Return the path to the main executable, given the
171/// value of argv[0] from program startup.
172std::string getMainExecutable(const char *argv0, void *MainAddr) {
173#if defined(__APPLE__)
174 // On OS X the executable path is saved to the stack by dyld. Reading it
175 // from there is much faster than calling dladdr, especially for large
176 // binaries with symbols.
177 char exe_path[MAXPATHLEN];
178 uint32_t size = sizeof(exe_path);
179 if (_NSGetExecutablePath(exe_path, &size) == 0) {
180 char link_path[MAXPATHLEN];
181 if (realpath(exe_path, link_path))
Rafael Espindola4601c462013-06-26 05:25:44 +0000182 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000183 }
Michal Gorny2d8be642019-03-04 04:53:50 +0000184#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
Erich Keaned8f61f82017-07-21 22:48:47 +0000185 defined(__minix) || defined(__DragonFly__) || \
186 defined(__FreeBSD_kernel__) || defined(_AIX)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000187 char exe_path[PATH_MAX];
188
189 if (getprogpath(exe_path, argv0) != NULL)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000190 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000191#elif defined(__linux__) || defined(__CYGWIN__)
192 char exe_path[MAXPATHLEN];
193 StringRef aPath("/proc/self/exe");
194 if (sys::fs::exists(aPath)) {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000195 // /proc is not always mounted under Linux (chroot for example).
196 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
197 if (len < 0)
198 return "";
199
200 // Null terminate the string for realpath. readlink never null
201 // terminates its output.
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000202 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
Reid Kleckner1500eff2018-10-23 23:35:43 +0000203 exe_path[len] = '\0';
204
Reid Kleckner5fa1e352018-10-23 23:44:44 +0000205 // On Linux, /proc/self/exe always looks through symlinks. However, on
206 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
207 // the program, and not the eventual binary file. Therefore, call realpath
208 // so this behaves the same on all platforms.
Reid Kleckner1500eff2018-10-23 23:35:43 +0000209#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
210 char *real_path = realpath(exe_path, NULL);
211 std::string ret = std::string(real_path);
212 free(real_path);
213 return ret;
214#else
215 char real_path[MAXPATHLEN];
216 realpath(exe_path, real_path);
217 return std::string(real_path);
218#endif
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000219 } else {
Reid Kleckner1500eff2018-10-23 23:35:43 +0000220 // Fall back to the classical detection.
221 if (getprogpath(exe_path, argv0))
222 return exe_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000223 }
Omair Javaidf5d560bc842017-02-02 01:17:49 +0000224#elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000225 // Use dladdr to get executable path if available.
226 Dl_info DLInfo;
227 int err = dladdr(MainAddr, &DLInfo);
228 if (err == 0)
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000229 return "";
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000230
231 // If the filename is a symlink, we need to resolve and return the location of
232 // the actual executable.
233 char link_path[MAXPATHLEN];
234 if (realpath(DLInfo.dli_fname, link_path))
Rafael Espindola2c6f4fe2013-06-26 06:10:32 +0000235 return link_path;
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000236#else
237#error GetMainExecutable is not implemented on this host yet.
238#endif
239 return "";
240}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000241
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000242TimePoint<> basic_file_status::getLastAccessedTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000243 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000244}
245
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000246TimePoint<> basic_file_status::getLastModificationTime() const {
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000247 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000248}
249
Rafael Espindolad1230992013-07-29 21:55:38 +0000250UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000251 return UniqueID(fs_st_dev, fs_st_ino);
252}
253
Zachary Turner5821a3b2017-03-20 23:55:20 +0000254uint32_t file_status::getLinkCount() const {
255 return fs_st_nlinks;
256}
257
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000258ErrorOr<space_info> disk_space(const Twine &Path) {
259 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000260 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000261 return std::error_code(errno, std::generic_category());
262 auto FrSize = STATVFS_F_FRSIZE(Vfs);
263 space_info SpaceInfo;
264 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
265 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
266 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
267 return SpaceInfo;
268}
269
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000270std::error_code current_path(SmallVectorImpl<char> &result) {
Rafael Espindola6ee16382013-08-10 00:50:57 +0000271 result.clear();
272
273 const char *pwd = ::getenv("PWD");
274 llvm::sys::fs::file_status PWDStatus, DotStatus;
275 if (pwd && llvm::sys::path::is_absolute(pwd) &&
276 !llvm::sys::fs::status(pwd, PWDStatus) &&
277 !llvm::sys::fs::status(".", DotStatus) &&
278 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
279 result.append(pwd, pwd + strlen(pwd));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000280 return std::error_code();
Rafael Espindola6ee16382013-08-10 00:50:57 +0000281 }
282
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000283#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000284 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000285#else
286// For GNU Hurd
287 result.reserve(1024);
288#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000289
Michael J. Spencer20daa282010-12-07 01:22:31 +0000290 while (true) {
Craig Toppere73658d2014-04-28 04:05:08 +0000291 if (::getcwd(result.data(), result.capacity()) == nullptr) {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000292 // See if there was a real error.
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000293 if (errno != ENOMEM)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000294 return std::error_code(errno, std::generic_category());
Michael J. Spencer20daa282010-12-07 01:22:31 +0000295 // Otherwise there just wasn't enough space.
296 result.reserve(result.capacity() * 2);
297 } else
298 break;
299 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000300
301 result.set_size(strlen(result.data()));
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000302 return std::error_code();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000303}
304
Pavel Labath2f096092017-01-24 10:32:03 +0000305std::error_code set_current_path(const Twine &path) {
306 SmallString<128> path_storage;
307 StringRef p = path.toNullTerminatedStringRef(path_storage);
308
309 if (::chdir(p.begin()) == -1)
310 return std::error_code(errno, std::generic_category());
311
312 return std::error_code();
313}
314
Frederic Riss6b9396c2015-08-06 21:04:55 +0000315std::error_code create_directory(const Twine &path, bool IgnoreExisting,
316 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000317 SmallString<128> path_storage;
318 StringRef p = path.toNullTerminatedStringRef(path_storage);
319
Frederic Riss6b9396c2015-08-06 21:04:55 +0000320 if (::mkdir(p.begin(), Perms) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000321 if (errno != EEXIST || !IgnoreExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000322 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000323 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000324
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000325 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000326}
327
Rafael Espindola83f858e2014-03-11 18:40:24 +0000328// Note that we are using symbolic link because hard links are not supported by
329// all filesystems (SMB doesn't).
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000330std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000331 // Get arguments.
332 SmallString<128> from_storage;
333 SmallString<128> to_storage;
334 StringRef f = from.toNullTerminatedStringRef(from_storage);
335 StringRef t = to.toNullTerminatedStringRef(to_storage);
336
Rafael Espindola83f858e2014-03-11 18:40:24 +0000337 if (::symlink(t.begin(), f.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000338 return std::error_code(errno, std::generic_category());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000339
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000340 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000341}
342
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000343std::error_code create_hard_link(const Twine &to, const Twine &from) {
344 // Get arguments.
345 SmallString<128> from_storage;
346 SmallString<128> to_storage;
347 StringRef f = from.toNullTerminatedStringRef(from_storage);
348 StringRef t = to.toNullTerminatedStringRef(to_storage);
349
350 if (::link(t.begin(), f.begin()) == -1)
351 return std::error_code(errno, std::generic_category());
352
353 return std::error_code();
354}
355
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000356std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000357 SmallString<128> path_storage;
358 StringRef p = path.toNullTerminatedStringRef(path_storage);
359
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000360 struct stat buf;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000361 if (lstat(p.begin(), &buf) != 0) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000362 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000363 return std::error_code(errno, std::generic_category());
364 return std::error_code();
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000365 }
366
367 // Note: this check catches strange situations. In all cases, LLVM should
368 // only be involved in the creation and deletion of regular files. This
369 // check ensures that what we're trying to erase is a regular file. It
370 // effectively prevents LLVM from erasing things like /dev/null, any block
371 // special file, or other things that aren't "regular" files.
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +0000372 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000373 return make_error_code(errc::operation_not_permitted);
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000374
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000375 if (::remove(p.begin()) == -1) {
Rafael Espindola882ce87b2014-05-31 02:29:28 +0000376 if (errno != ENOENT || !IgnoreNonExisting)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000377 return std::error_code(errno, std::generic_category());
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000378 }
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000379
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000380 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000381}
382
Zachary Turner392ed9d2017-02-21 20:55:47 +0000383static bool is_local_impl(struct STATVFS &Vfs) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000384#if defined(__linux__) || defined(__GNU__)
Michal Gorny5ddd2a52017-02-22 18:09:15 +0000385#ifndef NFS_SUPER_MAGIC
386#define NFS_SUPER_MAGIC 0x6969
387#endif
388#ifndef SMB_SUPER_MAGIC
389#define SMB_SUPER_MAGIC 0x517B
390#endif
Zachary Turner6bc2dac2017-02-21 21:13:10 +0000391#ifndef CIFS_MAGIC_NUMBER
392#define CIFS_MAGIC_NUMBER 0xFF534D42
393#endif
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000394#ifdef __GNU__
395 switch ((uint32_t)Vfs.__f_type) {
396#else
Zachary Turner392ed9d2017-02-21 20:55:47 +0000397 switch ((uint32_t)Vfs.f_type) {
Sylvestre Ledruf4719c42018-10-23 07:13:47 +0000398#endif
Zachary Turner392ed9d2017-02-21 20:55:47 +0000399 case NFS_SUPER_MAGIC:
400 case SMB_SUPER_MAGIC:
401 case CIFS_MAGIC_NUMBER:
402 return false;
403 default:
404 return true;
405 }
Nuno Lopes7a1bbd42017-03-09 13:43:31 +0000406#elif defined(__CYGWIN__)
407 // Cygwin doesn't expose this information; would need to use Win32 API.
408 return false;
Petr Hosek87f13432018-05-03 01:38:49 +0000409#elif defined(__Fuchsia__)
410 // Fuchsia doesn't yet support remote filesystem mounts.
411 return true;
Tim Northover43d64b02018-07-18 13:42:18 +0000412#elif defined(__HAIKU__)
413 // Haiku doesn't expose this information.
414 return false;
Kamil Rytarowski07c81b12017-06-01 12:57:00 +0000415#elif defined(__sun)
416 // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
417 StringRef fstype(Vfs.f_basetype);
418 // NFS is the only non-local fstype??
419 return !fstype.equals("nfs");
Hubert Tong24168852019-03-29 23:32:47 +0000420#elif defined(_AIX)
421 // Call mntctl; try more than twice in case of timing issues with a concurrent
422 // mount.
423 int Ret;
424 size_t BufSize = 2048u;
425 std::unique_ptr<char[]> Buf;
426 int Tries = 3;
427 while (Tries--) {
428 Buf = llvm::make_unique<char[]>(BufSize);
429 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
430 if (Ret != 0)
431 break;
432 BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
433 Buf.reset();
434 }
435
436 if (Ret == -1)
437 // There was an error; "remote" is the conservative answer.
438 return false;
439
440 // Look for the correct vmount entry.
441 char *CurObjPtr = Buf.get();
442 while (Ret--) {
443 struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
444 static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
445 "fsid length mismatch");
446 if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
447 return (Vp->vmt_flags & MNT_REMOTE) == 0;
448
449 CurObjPtr += Vp->vmt_length;
450 }
451
452 // vmount entry not found; "remote" is the conservative answer.
453 return false;
Zachary Turner392ed9d2017-02-21 20:55:47 +0000454#else
455 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
456#endif
457}
458
459std::error_code is_local(const Twine &Path, bool &Result) {
460 struct STATVFS Vfs;
Hubert Tong24168852019-03-29 23:32:47 +0000461 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
Zachary Turner392ed9d2017-02-21 20:55:47 +0000462 return std::error_code(errno, std::generic_category());
463
464 Result = is_local_impl(Vfs);
465 return std::error_code();
466}
467
468std::error_code is_local(int FD, bool &Result) {
469 struct STATVFS Vfs;
470 if (::FSTATVFS(FD, &Vfs))
471 return std::error_code(errno, std::generic_category());
472
473 Result = is_local_impl(Vfs);
474 return std::error_code();
475}
476
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000477std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000478 // Get arguments.
479 SmallString<128> from_storage;
480 SmallString<128> to_storage;
481 StringRef f = from.toNullTerminatedStringRef(from_storage);
482 StringRef t = to.toNullTerminatedStringRef(to_storage);
483
Rafael Espindolab6fea4c2013-07-17 03:33:41 +0000484 if (::rename(f.begin(), t.begin()) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000485 return std::error_code(errno, std::generic_category());
Michael J. Spencer409f5562010-12-03 17:53:55 +0000486
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000487 return std::error_code();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000488}
489
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000490std::error_code resize_file(int FD, uint64_t Size) {
Rafael Espindola3816c532016-07-19 20:19:56 +0000491#if defined(HAVE_POSIX_FALLOCATE)
492 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
493 // space, so we get an error if the disk is full.
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000494 if (int Err = ::posix_fallocate(FD, 0, Size)) {
Davide Italiano1f465aa2017-11-07 00:47:04 +0000495 if (Err != EINVAL && Err != EOPNOTSUPP)
Joerg Sonnenbergerecfb8762017-05-05 17:55:58 +0000496 return std::error_code(Err, std::generic_category());
497 }
498#endif
Rafael Espindola3816c532016-07-19 20:19:56 +0000499 // Use ftruncate as a fallback. It may or may not allocate space. At least on
500 // OS X with HFS+ it does.
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000501 if (::ftruncate(FD, Size) == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000502 return std::error_code(errno, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000503
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000504 return std::error_code();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000505}
506
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000507static int convertAccessMode(AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000508 switch (Mode) {
509 case AccessMode::Exist:
510 return F_OK;
511 case AccessMode::Write:
512 return W_OK;
513 case AccessMode::Execute:
514 return R_OK | X_OK; // scripts also need R_OK.
515 }
516 llvm_unreachable("invalid enum");
517}
Michael J. Spencer45710402010-12-03 01:21:28 +0000518
Rafael Espindola281f23a2014-09-11 20:30:02 +0000519std::error_code access(const Twine &Path, AccessMode Mode) {
520 SmallString<128> PathStorage;
521 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
522
523 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
524 return std::error_code(errno, std::generic_category());
525
526 if (Mode == AccessMode::Execute) {
527 // Don't say that directories are executable.
528 struct stat buf;
529 if (0 != stat(P.begin(), &buf))
530 return errc::permission_denied;
531 if (!S_ISREG(buf.st_mode))
532 return errc::permission_denied;
533 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000534
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000535 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000536}
537
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000538bool can_execute(const Twine &Path) {
539 return !access(Path, AccessMode::Execute);
540}
541
Michael J. Spencer203d7802011-12-12 06:04:28 +0000542bool equivalent(file_status A, file_status B) {
543 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000544 return A.fs_st_dev == B.fs_st_dev &&
545 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000546}
547
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000548std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000549 file_status fsA, fsB;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000550 if (std::error_code ec = status(A, fsA))
551 return ec;
552 if (std::error_code ec = status(B, fsB))
553 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000554 result = equivalent(fsA, fsB);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000555 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000556}
557
Zachary Turnere48ace62017-03-10 17:39:21 +0000558static void expandTildeExpr(SmallVectorImpl<char> &Path) {
559 StringRef PathStr(Path.begin(), Path.size());
560 if (PathStr.empty() || !PathStr.startswith("~"))
561 return;
562
563 PathStr = PathStr.drop_front();
Zachary Turner18753342017-03-16 22:34:18 +0000564 StringRef Expr =
565 PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +0000566 StringRef Remainder = PathStr.substr(Expr.size() + 1);
567 SmallString<128> Storage;
568 if (Expr.empty()) {
569 // This is just ~/..., resolve it to the current user's home dir.
570 if (!path::home_directory(Storage)) {
571 // For some reason we couldn't get the home directory. Just exit.
572 return;
573 }
574
575 // Overwrite the first character and insert the rest.
576 Path[0] = Storage[0];
577 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
578 return;
579 }
580
581 // This is a string of the form ~username/, look up this user's entry in the
582 // password database.
583 struct passwd *Entry = nullptr;
584 std::string User = Expr.str();
585 Entry = ::getpwnam(User.c_str());
586
587 if (!Entry) {
588 // Unable to look up the entry, just return back the original path.
589 return;
590 }
591
592 Storage = Remainder;
593 Path.clear();
594 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
595 llvm::sys::path::append(Path, Storage);
596}
597
Jonas Devlieghereb23f4302018-11-13 18:23:32 +0000598
599void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
600 dest.clear();
601 if (path.isTriviallyEmpty())
602 return;
603
604 path.toVector(dest);
605 expandTildeExpr(dest);
606
607 return;
608}
609
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000610static file_type typeForMode(mode_t Mode) {
611 if (S_ISDIR(Mode))
612 return file_type::directory_file;
613 else if (S_ISREG(Mode))
614 return file_type::regular_file;
615 else if (S_ISBLK(Mode))
616 return file_type::block_file;
617 else if (S_ISCHR(Mode))
618 return file_type::character_file;
619 else if (S_ISFIFO(Mode))
620 return file_type::fifo_file;
621 else if (S_ISSOCK(Mode))
622 return file_type::socket_file;
623 else if (S_ISLNK(Mode))
624 return file_type::symlink_file;
625 return file_type::type_unknown;
626}
627
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000628static std::error_code fillStatus(int StatRet, const struct stat &Status,
Fangrui Song69d64182018-06-10 04:53:14 +0000629 file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000630 if (StatRet != 0) {
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000631 std::error_code EC(errno, std::generic_category());
632 if (EC == errc::no_such_file_or_directory)
Rafael Espindola77021c92013-07-16 03:20:13 +0000633 Result = file_status(file_type::file_not_found);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000634 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000635 Result = file_status(file_type::status_error);
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000636 return EC;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000637 }
638
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000639 uint32_t atime_nsec, mtime_nsec;
640#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
641 atime_nsec = Status.st_atimespec.tv_nsec;
642 mtime_nsec = Status.st_mtimespec.tv_nsec;
643#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
644 atime_nsec = Status.st_atim.tv_nsec;
645 mtime_nsec = Status.st_mtim.tv_nsec;
646#else
647 atime_nsec = mtime_nsec = 0;
648#endif
649
James Henderson566fdf42017-03-16 11:22:09 +0000650 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000651 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
Argyrios Kyrtzidis5167c132018-11-26 00:03:39 +0000652 Status.st_nlink, Status.st_ino,
653 Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
654 Status.st_uid, Status.st_gid, Status.st_size);
Michael J. Spencer203d7802011-12-12 06:04:28 +0000655
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000656 return std::error_code();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000657}
658
Zachary Turner82dd5422017-03-07 16:10:10 +0000659std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000660 SmallString<128> PathStorage;
661 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
662
663 struct stat Status;
Zachary Turner82dd5422017-03-07 16:10:10 +0000664 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
Rafael Espindola77021c92013-07-16 03:20:13 +0000665 return fillStatus(StatRet, Status, Result);
666}
667
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000668std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000669 struct stat Status;
670 int StatRet = ::fstat(FD, &Status);
Aaron Ballman345012d2017-03-13 12:24:51 +0000671 return fillStatus(StatRet, Status, Result);
672}
673
James Henderson566fdf42017-03-16 11:22:09 +0000674std::error_code setPermissions(const Twine &Path, perms Permissions) {
675 SmallString<128> PathStorage;
676 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
677
678 if (::chmod(P.begin(), Permissions))
679 return std::error_code(errno, std::generic_category());
680 return std::error_code();
681}
682
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000683std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
684 TimePoint<> ModificationTime) {
Aaron Ballman345012d2017-03-13 12:24:51 +0000685#if defined(HAVE_FUTIMENS)
686 timespec Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000687 Times[0] = sys::toTimeSpec(AccessTime);
688 Times[1] = sys::toTimeSpec(ModificationTime);
Eric Christophera24dc7f2013-07-04 01:10:38 +0000689 if (::futimens(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000690 return std::error_code(errno, std::generic_category());
691 return std::error_code();
Eric Christophera24dc7f2013-07-04 01:10:38 +0000692#elif defined(HAVE_FUTIMES)
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000693 timeval Times[2];
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000694 Times[0] = sys::toTimeVal(
695 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
696 Times[1] =
697 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
698 ModificationTime));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000699 if (::futimes(FD, Times))
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000700 return std::error_code(errno, std::generic_category());
701 return std::error_code();
Alp Tokerb30f01e2013-12-11 15:42:33 +0000702#else
703#warning Missing futimes() and futimens()
Alp Tokerb792a012014-06-30 18:57:04 +0000704 return make_error_code(errc::function_not_supported);
Alp Tokerb30f01e2013-12-11 15:42:33 +0000705#endif
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000706}
707
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000708std::error_code mapped_file_region::init(int FD, uint64_t Offset,
709 mapmode Mode) {
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000710 assert(Size != 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000711
712 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
713 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
Zachary Turner842972b2017-02-22 21:24:06 +0000714#if defined(__APPLE__)
715 //----------------------------------------------------------------------
716 // Newer versions of MacOSX have a flag that will allow us to read from
717 // binaries whose code signature is invalid without crashing by using
718 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
719 // is mapped we can avoid crashing and return zeroes to any pages we try
720 // to read if the media becomes unavailable by using the
721 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
722 // with PROT_READ, so take care not to specify them otherwise.
723 //----------------------------------------------------------------------
724 if (Mode == readonly) {
725#if defined(MAP_RESILIENT_CODESIGN)
726 flags |= MAP_RESILIENT_CODESIGN;
727#endif
728#if defined(MAP_RESILIENT_MEDIA)
729 flags |= MAP_RESILIENT_MEDIA;
730#endif
731 }
732#endif // #if defined (__APPLE__)
Zachary Turner392ed9d2017-02-21 20:55:47 +0000733
Craig Toppere73658d2014-04-28 04:05:08 +0000734 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000735 if (Mapping == MAP_FAILED)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000736 return std::error_code(errno, std::generic_category());
737 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000738}
739
Roman Lebedev7c983672017-09-27 15:59:16 +0000740mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000741 uint64_t offset, std::error_code &ec)
Peter Collingbourne881ba102018-06-13 18:03:14 +0000742 : Size(length), Mapping(), Mode(mode) {
Zachary Turner2061ad22018-02-15 18:46:59 +0000743 (void)Mode;
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000744 ec = init(fd, offset, mode);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000745 if (ec)
Craig Toppere73658d2014-04-28 04:05:08 +0000746 Mapping = nullptr;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000747}
748
749mapped_file_region::~mapped_file_region() {
750 if (Mapping)
751 ::munmap(Mapping, Size);
752}
753
Roman Lebedev21b013e2017-09-27 16:08:33 +0000754size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000755 assert(Mapping && "Mapping failed but used anyway!");
756 return Size;
757}
758
759char *mapped_file_region::data() const {
760 assert(Mapping && "Mapping failed but used anyway!");
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000761 return reinterpret_cast<char*>(Mapping);
762}
763
764const char *mapped_file_region::const_data() const {
765 assert(Mapping && "Mapping failed but used anyway!");
766 return reinterpret_cast<const char*>(Mapping);
767}
768
769int mapped_file_region::alignment() {
Rafael Espindolac0610bf2014-12-04 16:59:36 +0000770 return Process::getPageSize();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000771}
772
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000773std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000774 StringRef path,
775 bool follow_symlinks) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000776 SmallString<128> path_null(path);
777 DIR *directory = ::opendir(path_null.c_str());
Craig Toppere73658d2014-04-28 04:05:08 +0000778 if (!directory)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000779 return std::error_code(errno, std::generic_category());
Michael J. Spencer52714862011-01-05 16:38:57 +0000780
781 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
782 // Add something for replace_filename to replace.
783 path::append(path_null, ".");
Zachary Turner260bda32017-03-08 22:49:32 +0000784 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
Michael J. Spencer52714862011-01-05 16:38:57 +0000785 return directory_iterator_increment(it);
786}
787
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000788std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000789 if (it.IterationHandle)
790 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
791 it.IterationHandle = 0;
792 it.CurrentEntry = directory_entry();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000793 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000794}
795
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000796static file_type direntType(dirent* Entry) {
797 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
798 // The DTTOIF macro lets us reuse our status -> type conversion.
799#if defined(_DIRENT_HAVE_D_TYPE) && defined(DTTOIF)
800 return typeForMode(DTTOIF(Entry->d_type));
801#else
802 // Other platforms such as Solaris require a stat() to get the type.
803 return file_type::type_unknown;
804#endif
805}
806
807std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000808 errno = 0;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000809 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
810 if (CurDir == nullptr && errno != 0) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000811 return std::error_code(errno, std::generic_category());
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000812 } else if (CurDir != nullptr) {
813 StringRef Name(CurDir->d_name);
814 if ((Name.size() == 1 && Name[0] == '.') ||
815 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
816 return directory_iterator_increment(It);
817 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
Michael J. Spencer52714862011-01-05 16:38:57 +0000818 } else
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000819 return directory_iterator_destruct(It);
Michael J. Spencer52714862011-01-05 16:38:57 +0000820
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000821 return std::error_code();
Michael J. Spencer52714862011-01-05 16:38:57 +0000822}
823
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000824ErrorOr<basic_file_status> directory_entry::status() const {
825 file_status s;
826 if (auto EC = fs::status(Path, s, FollowSymlinks))
827 return EC;
828 return s;
829}
830
Taewook Ohd9153272016-06-13 15:54:56 +0000831#if !defined(F_GETPATH)
832static bool hasProcSelfFD() {
833 // If we have a /proc filesystem mounted, we can quickly establish the
834 // real name of the file with readlink
835 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
836 return Result;
837}
838#endif
839
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000840static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
841 FileAccess Access) {
842 int Result = 0;
843 if (Access == FA_Read)
844 Result |= O_RDONLY;
845 else if (Access == FA_Write)
846 Result |= O_WRONLY;
847 else if (Access == (FA_Read | FA_Write))
848 Result |= O_RDWR;
849
850 // This is for compatibility with old code that assumed F_Append implied
851 // would open an existing file. See Windows/Path.inc for a longer comment.
852 if (Flags & F_Append)
853 Disp = CD_OpenAlways;
854
855 if (Disp == CD_CreateNew) {
856 Result |= O_CREAT; // Create if it doesn't exist.
857 Result |= O_EXCL; // Fail if it does.
858 } else if (Disp == CD_CreateAlways) {
859 Result |= O_CREAT; // Create if it doesn't exist.
860 Result |= O_TRUNC; // Truncate if it does.
861 } else if (Disp == CD_OpenAlways) {
862 Result |= O_CREAT; // Create if it doesn't exist.
863 } else if (Disp == CD_OpenExisting) {
864 // Nothing special, just don't add O_CREAT and we get these semantics.
865 }
866
867 if (Flags & F_Append)
868 Result |= O_APPEND;
869
870#ifdef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000871 if (!(Flags & OF_ChildInherit))
872 Result |= O_CLOEXEC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000873#endif
874
875 return Result;
876}
877
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000878std::error_code openFile(const Twine &Name, int &ResultFD,
879 CreationDisposition Disp, FileAccess Access,
880 OpenFlags Flags, unsigned Mode) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000881 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
882
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000883 SmallString<128> Storage;
884 StringRef P = Name.toNullTerminatedStringRef(Storage);
Hans Wennborg0a0e4112018-08-27 15:55:39 +0000885 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
886 // when open is overloaded, such as in Bionic.
887 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
888 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
Pavel Labathfe09f502017-06-29 13:15:31 +0000889 return std::error_code(errno, std::generic_category());
Pavel Labathf726dfa2017-01-24 10:57:01 +0000890#ifndef O_CLOEXEC
Zachary Turner6edfecb2018-06-08 15:15:56 +0000891 if (!(Flags & OF_ChildInherit)) {
892 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
893 (void)r;
894 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
895 }
Pavel Labathf726dfa2017-01-24 10:57:01 +0000896#endif
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000897 return std::error_code();
898}
899
Zachary Turner9d2cfa62018-06-07 23:25:13 +0000900Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
901 FileAccess Access, OpenFlags Flags,
902 unsigned Mode) {
903
904 int FD;
905 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
906 if (EC)
907 return errorCodeToError(EC);
908 return FD;
909}
910
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000911std::error_code openFileForRead(const Twine &Name, int &ResultFD,
912 OpenFlags Flags,
913 SmallVectorImpl<char> *RealPath) {
914 std::error_code EC =
915 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
916 if (EC)
917 return EC;
918
Taewook Ohd9153272016-06-13 15:54:56 +0000919 // Attempt to get the real name of the file, if the user asked
920 if(!RealPath)
921 return std::error_code();
922 RealPath->clear();
923#if defined(F_GETPATH)
924 // When F_GETPATH is availble, it is the quickest way to get
925 // the real path name.
926 char Buffer[MAXPATHLEN];
927 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
928 RealPath->append(Buffer, Buffer + strlen(Buffer));
929#else
930 char Buffer[PATH_MAX];
931 if (hasProcSelfFD()) {
932 char ProcPath[64];
933 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
934 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
935 if (CharCount > 0)
936 RealPath->append(Buffer, Buffer + CharCount);
937 } else {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000938 SmallString<128> Storage;
939 StringRef P = Name.toNullTerminatedStringRef(Storage);
940
Taewook Ohd9153272016-06-13 15:54:56 +0000941 // Use ::realpath to get the real path name
942 if (::realpath(P.begin(), Buffer) != nullptr)
943 RealPath->append(Buffer, Buffer + strlen(Buffer));
944 }
945#endif
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000946 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000947}
Nick Kledzik18497e92012-06-20 00:28:54 +0000948
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000949Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
Zachary Turner63db25b2018-06-04 19:38:11 +0000950 SmallVectorImpl<char> *RealPath) {
951 file_t ResultFD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000952 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
Zachary Turner63db25b2018-06-04 19:38:11 +0000953 if (EC)
954 return errorCodeToError(EC);
955 return ResultFD;
956}
957
Zachary Turner63db25b2018-06-04 19:38:11 +0000958void closeFile(file_t &F) {
959 ::close(F);
960 F = kInvalidFile;
961}
962
Zachary Turner260bda32017-03-08 22:49:32 +0000963template <typename T>
964static std::error_code remove_directories_impl(const T &Entry,
965 bool IgnoreErrors) {
966 std::error_code EC;
967 directory_iterator Begin(Entry, EC, false);
968 directory_iterator End;
969 while (Begin != End) {
970 auto &Item = *Begin;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000971 ErrorOr<basic_file_status> st = Item.status();
972 if (!st && !IgnoreErrors)
973 return st.getError();
Zachary Turner260bda32017-03-08 22:49:32 +0000974
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000975 if (is_directory(*st)) {
Zachary Turner260bda32017-03-08 22:49:32 +0000976 EC = remove_directories_impl(Item, IgnoreErrors);
977 if (EC && !IgnoreErrors)
978 return EC;
979 }
980
981 EC = fs::remove(Item.path(), true);
982 if (EC && !IgnoreErrors)
983 return EC;
984
985 Begin.increment(EC);
986 if (EC && !IgnoreErrors)
987 return EC;
988 }
989 return std::error_code();
990}
991
992std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
993 auto EC = remove_directories_impl(path, IgnoreErrors);
994 if (EC && !IgnoreErrors)
995 return EC;
996 EC = fs::remove(path, true);
997 if (EC && !IgnoreErrors)
998 return EC;
999 return std::error_code();
1000}
1001
Zachary Turnere48ace62017-03-10 17:39:21 +00001002std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1003 bool expand_tilde) {
1004 dest.clear();
1005 if (path.isTriviallyEmpty())
1006 return std::error_code();
1007
1008 if (expand_tilde) {
1009 SmallString<128> Storage;
1010 path.toVector(Storage);
1011 expandTildeExpr(Storage);
1012 return real_path(Storage, dest, false);
1013 }
1014
Davide Italiano4762c062018-01-09 17:27:45 +00001015 SmallString<128> Storage;
1016 StringRef P = path.toNullTerminatedStringRef(Storage);
1017 char Buffer[PATH_MAX];
1018 if (::realpath(P.begin(), Buffer) == nullptr)
1019 return std::error_code(errno, std::generic_category());
1020 dest.append(Buffer, Buffer + strlen(Buffer));
Zachary Turnere48ace62017-03-10 17:39:21 +00001021 return std::error_code();
1022}
1023
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001024} // end namespace fs
Peter Collingbournef7d41012014-01-31 23:46:06 +00001025
1026namespace path {
1027
1028bool home_directory(SmallVectorImpl<char> &result) {
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001029 char *RequestedDir = getenv("HOME");
1030 if (!RequestedDir) {
1031 struct passwd *pw = getpwuid(getuid());
1032 if (pw && pw->pw_dir)
1033 RequestedDir = pw->pw_dir;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001034 }
Zachary Turnera3cf70b2017-03-22 15:24:59 +00001035 if (!RequestedDir)
1036 return false;
1037
1038 result.clear();
1039 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1040 return true;
Peter Collingbournef7d41012014-01-31 23:46:06 +00001041}
1042
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001043static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001044 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1045 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1046 // macros defined in <unistd.h> on darwin >= 9
1047 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1048 : _CS_DARWIN_USER_CACHE_DIR;
1049 size_t ConfLen = confstr(ConfName, nullptr, 0);
1050 if (ConfLen > 0) {
1051 do {
1052 Result.resize(ConfLen);
1053 ConfLen = confstr(ConfName, Result.data(), Result.size());
1054 } while (ConfLen > 0 && ConfLen != Result.size());
1055
1056 if (ConfLen > 0) {
1057 assert(Result.back() == 0);
1058 Result.pop_back();
1059 return true;
1060 }
1061
1062 Result.clear();
1063 }
1064 #endif
1065 return false;
1066}
1067
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001068static const char *getEnvTempDir() {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001069 // Check whether the temporary directory is specified by an environment
1070 // variable.
1071 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1072 for (const char *Env : EnvironmentVariables) {
1073 if (const char *Dir = std::getenv(Env))
1074 return Dir;
1075 }
1076
1077 return nullptr;
1078}
1079
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001080static const char *getDefaultTempDir(bool ErasedOnReboot) {
Rafael Espindola016a6d52014-08-26 14:47:52 +00001081#ifdef P_tmpdir
Benjamin Kramer870d9512014-08-27 11:47:52 +00001082 if ((bool)P_tmpdir)
Rafael Espindola016a6d52014-08-26 14:47:52 +00001083 return P_tmpdir;
1084#endif
1085
1086 if (ErasedOnReboot)
1087 return "/tmp";
1088 return "/var/tmp";
1089}
1090
1091void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1092 Result.clear();
1093
1094 if (ErasedOnReboot) {
1095 // There is no env variable for the cache directory.
1096 if (const char *RequestedDir = getEnvTempDir()) {
1097 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1098 return;
1099 }
1100 }
1101
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001102 if (getDarwinConfDir(ErasedOnReboot, Result))
1103 return;
Rafael Espindola016a6d52014-08-26 14:47:52 +00001104
1105 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1106 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1107}
1108
Peter Collingbournef7d41012014-01-31 23:46:06 +00001109} // end namespace path
1110
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001111} // end namespace sys
1112} // end namespace llvm