1//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Unix specific implementation of the Path API.
10//
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"
19
20#include "llvm/Support/IOSandbox.h"
21
22#include <limits.h>
23#include <stdio.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#ifdef HAVE_UNISTD_H
27#include <unistd.h>
28#endif
29#ifdef HAVE_SYS_MMAN_H
30#include <sys/mman.h>
31#endif
32
33#include <dirent.h>
34#include <pwd.h>
35
36#ifdef __APPLE__
37#include <copyfile.h>
38#include <mach-o/dyld.h>
39#include <sys/attr.h>
40#if __has_include(<sys/clonefile.h>)
41#include <sys/clonefile.h>
42#endif
43#elif defined(__FreeBSD__)
44#include <osreldate.h>
45#if __FreeBSD_version >= 1300057
46#include <sys/auxv.h>
47#else
48#include <machine/elf.h>
49extern char **environ;
50#endif
51#elif defined(__DragonFly__)
52#include <sys/mount.h>
53#elif defined(__MVS__)
54#include "llvm/Support/AutoConvert.h"
55#include <sys/ps.h>
56#endif
57
58// Both stdio.h and cstdio are included via different paths and
59// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
60// either.
61#undef ferror
62#undef feof
63
64#if !defined(PATH_MAX)
65// For GNU Hurd
66#if defined(__GNU__)
67#define PATH_MAX 4096
68#elif defined(__MVS__)
69#define PATH_MAX _XOPEN_PATH_MAX
70#endif
71#endif
72
73#include <sys/types.h>
74#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
75 !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX) && \
76 !defined(__managarm__)
77#include <sys/statvfs.h>
78#define STATVFS statvfs
79#define FSTATVFS fstatvfs
80#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
81#else
82#if defined(__OpenBSD__) || defined(__FreeBSD__)
83#include <sys/mount.h>
84#include <sys/param.h>
85#elif defined(__linux__) || defined(__managarm__)
86#include <sys/vfs.h>
87#elif defined(_AIX)
88#include <sys/statfs.h>
89
90// <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
91// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
92// the typedef prior to including <sys/vmount.h> to work around this issue.
93typedef uint_t uint;
94#include <sys/vmount.h>
95#else
96#include <sys/mount.h>
97#endif
98#define STATVFS statfs
99#define FSTATVFS fstatfs
100#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
101#endif
102
103#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) || \
104 defined(__MVS__)
105#define STATVFS_F_FLAG(vfs) (vfs).f_flag
106#else
107#define STATVFS_F_FLAG(vfs) (vfs).f_flags
108#endif
109
110using namespace llvm;
111
112namespace llvm {
113namespace sys {
114namespace fs {
115
116#if defined(__FreeBSD__) || defined(__NetBSD__) || \
117 (defined(__OpenBSD__) && !defined(HAVE_GETEXECPATH)) || \
118 defined(__FreeBSD_kernel__) || defined(__linux__) || \
119 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || \
120 defined(__GNU__) || \
121 (defined(__sun__) && defined(__svr4__) || defined(__HAIKU__)) || \
122 defined(__managarm__)
123static int test_dir(char ret[PATH_MAX], const char *dir, const char *bin) {
124 struct stat sb;
125 char fullpath[PATH_MAX];
126
127 int chars = snprintf(s: fullpath, PATH_MAX, format: "%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;
132 if (!realpath(name: fullpath, resolved: ret))
133 return 1;
134 if (stat(file: fullpath, buf: &sb) != 0)
135 return 1;
136
137 return 0;
138}
139
140static char *getprogpath(char ret[PATH_MAX], const char *bin) {
141 if (bin == nullptr)
142 return nullptr;
143
144 /* First approach: absolute path. */
145 if (bin[0] == '/') {
146 if (test_dir(ret, dir: "/", bin) == 0)
147 return ret;
148 return nullptr;
149 }
150
151 /* Second approach: relative path. */
152 if (strchr(s: bin, c: '/')) {
153 char cwd[PATH_MAX];
154 if (!getcwd(buf: cwd, PATH_MAX))
155 return nullptr;
156 if (test_dir(ret, dir: cwd, bin) == 0)
157 return ret;
158 return nullptr;
159 }
160
161 /* Third approach: $PATH */
162 char *pv;
163 if ((pv = getenv(name: "PATH")) == nullptr)
164 return nullptr;
165 char *s = strdup(s: pv);
166 if (!s)
167 return nullptr;
168 char *state;
169 for (char *t = strtok_r(s: s, delim: ":", save_ptr: &state); t != nullptr;
170 t = strtok_r(s: nullptr, delim: ":", save_ptr: &state)) {
171 if (test_dir(ret, dir: t, bin) == 0) {
172 free(ptr: s);
173 return ret;
174 }
175 }
176 free(ptr: s);
177 return nullptr;
178}
179#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
180
181/// GetMainExecutable - Return the path to the main executable, given the
182/// value of argv[0] from program startup.
183std::string getMainExecutable(const char *argv0, void *MainAddr) {
184 auto BypassSandbox = sandbox::scopedDisable();
185
186#if defined(__APPLE__)
187 // On OS X the executable path is saved to the stack by dyld. Reading it
188 // from there is much faster than calling dladdr, especially for large
189 // binaries with symbols.
190 char exe_path[PATH_MAX];
191 uint32_t size = sizeof(exe_path);
192 if (_NSGetExecutablePath(exe_path, &size) == 0) {
193 char link_path[PATH_MAX];
194 if (realpath(exe_path, link_path))
195 return link_path;
196 }
197#elif defined(__FreeBSD__)
198 // On FreeBSD if the exec path specified in ELF auxiliary vectors is
199 // preferred, if available. /proc/curproc/file and the KERN_PROC_PATHNAME
200 // sysctl may not return the desired path if there are multiple hardlinks
201 // to the file.
202 char exe_path[PATH_MAX];
203#if __FreeBSD_version >= 1300057
204 if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0) {
205 char link_path[PATH_MAX];
206 if (realpath(exe_path, link_path))
207 return link_path;
208 }
209#else
210 // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
211 // fall back to finding the ELF auxiliary vectors after the process's
212 // environment.
213 char **p = ::environ;
214 while (*p++ != 0)
215 ;
216 // Iterate through auxiliary vectors for AT_EXECPATH.
217 for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {
218 if (aux->a_type == AT_EXECPATH) {
219 char link_path[PATH_MAX];
220 if (realpath((char *)aux->a_un.a_ptr, link_path))
221 return link_path;
222 }
223 }
224#endif
225 // Fall back to argv[0] if auxiliary vectors are not available.
226 if (getprogpath(exe_path, argv0) != NULL)
227 return exe_path;
228#elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) || \
229 defined(__NetBSD__)
230 const char *curproc = "/proc/curproc/file";
231 char exe_path[PATH_MAX];
232 if (sys::fs::exists(curproc)) {
233 ssize_t len = ::readlink(curproc, exe_path, sizeof(exe_path));
234 if (len > 0) {
235 // Null terminate the string for realpath. readlink never null
236 // terminates its output.
237 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
238 exe_path[len] = '\0';
239 return exe_path;
240 }
241 }
242 // If we don't have procfs mounted, fall back to argv[0]
243 if (getprogpath(exe_path, argv0) != NULL)
244 return exe_path;
245#elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__) || \
246 defined(__managarm__)
247 char exe_path[PATH_MAX];
248 const char *aPath = "/proc/self/exe";
249 if (sys::fs::exists(Path: aPath)) {
250 // /proc is not always mounted under Linux (chroot for example).
251 ssize_t len = ::readlink(path: aPath, buf: exe_path, len: sizeof(exe_path));
252 if (len < 0)
253 return "";
254
255 // Null terminate the string for realpath. readlink never null
256 // terminates its output.
257 len = std::min(a: len, b: ssize_t(sizeof(exe_path) - 1));
258 exe_path[len] = '\0';
259
260 // On Linux, /proc/self/exe always looks through symlinks. However, on
261 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
262 // the program, and not the eventual binary file. Therefore, call realpath
263 // so this behaves the same on all platforms.
264#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
265 if (char *real_path = realpath(name: exe_path, resolved: nullptr)) {
266 std::string ret = std::string(real_path);
267 free(ptr: real_path);
268 return ret;
269 }
270#else
271 char real_path[PATH_MAX];
272 if (realpath(exe_path, real_path))
273 return std::string(real_path);
274#endif
275 }
276 // Fall back to the classical detection.
277 if (getprogpath(ret: exe_path, bin: argv0))
278 return exe_path;
279#elif defined(__OpenBSD__)
280 char exe_path[PATH_MAX];
281#ifdef HAVE_GETEXECPATH
282 if (getexecpath(exe_path, sizeof(exe_path)) == 0)
283 return exe_path;
284#else
285 if (getprogpath(exe_path, argv0) != NULL)
286 return exe_path;
287#endif
288#elif defined(__HAIKU__)
289 char exe_path[PATH_MAX];
290 // argv[0] only
291 if (getprogpath(exe_path, argv0) != NULL)
292 return exe_path;
293#elif defined(__sun__) && defined(__svr4__)
294 char exe_path[PATH_MAX];
295 const char *aPath = "/proc/self/execname";
296 if (sys::fs::exists(aPath)) {
297 int fd = open(aPath, O_RDONLY);
298 if (fd == -1)
299 return "";
300 if (read(fd, exe_path, sizeof(exe_path)) < 0)
301 return "";
302 return exe_path;
303 }
304 // Fall back to the classical detection.
305 if (getprogpath(exe_path, argv0) != NULL)
306 return exe_path;
307#elif defined(__MVS__)
308 int token = 0;
309 W_PSPROC buf;
310 char exe_path[PS_PATHBLEN];
311 pid_t pid = getpid();
312
313 memset(&buf, 0, sizeof(buf));
314 buf.ps_pathptr = exe_path;
315 buf.ps_pathlen = sizeof(exe_path);
316
317 while (true) {
318 if ((token = w_getpsent(token, &buf, sizeof(buf))) <= 0)
319 break;
320 if (buf.ps_pid != pid)
321 continue;
322 char real_path[PATH_MAX];
323 if (realpath(exe_path, real_path))
324 return std::string(real_path);
325 break; // Found entry, but realpath failed.
326 }
327#elif defined(HAVE_DLOPEN)
328 // Use dladdr to get executable path if available.
329 Dl_info DLInfo;
330 int err = dladdr(MainAddr, &DLInfo);
331 if (err == 0)
332 return "";
333
334 // If the filename is a symlink, we need to resolve and return the location of
335 // the actual executable.
336 char link_path[PATH_MAX];
337 if (realpath(DLInfo.dli_fname, link_path))
338 return link_path;
339#else
340#error GetMainExecutable is not implemented on this host yet.
341#endif
342 return "";
343}
344
345TimePoint<> basic_file_status::getLastAccessedTime() const {
346 return toTimePoint(T: fs_st_atime, nsec: fs_st_atime_nsec);
347}
348
349TimePoint<> basic_file_status::getLastModificationTime() const {
350 return toTimePoint(T: fs_st_mtime, nsec: fs_st_mtime_nsec);
351}
352
353UniqueID file_status::getUniqueID() const {
354 return UniqueID(fs_st_dev, fs_st_ino);
355}
356
357uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }
358
359ErrorOr<space_info> disk_space(const Twine &Path) {
360 struct STATVFS Vfs;
361 if (::STATVFS(file: const_cast<char *>(Path.str().c_str()), buf: &Vfs))
362 return errnoAsErrorCode();
363 auto FrSize = STATVFS_F_FRSIZE(Vfs);
364 space_info SpaceInfo;
365 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
366 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
367 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
368 return SpaceInfo;
369}
370
371std::error_code current_path(SmallVectorImpl<char> &result) {
372 sandbox::violationIfEnabled();
373
374 result.clear();
375
376 const char *pwd = ::getenv(name: "PWD");
377 llvm::sys::fs::file_status PWDStatus, DotStatus;
378 if (pwd && llvm::sys::path::is_absolute(path: pwd) &&
379 !llvm::sys::fs::status(path: pwd, result&: PWDStatus) &&
380 !llvm::sys::fs::status(path: ".", result&: DotStatus) &&
381 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
382 result.append(in_start: pwd, in_end: pwd + strlen(s: pwd));
383 return std::error_code();
384 }
385
386 result.resize_for_overwrite(PATH_MAX);
387
388 while (true) {
389 if (::getcwd(buf: result.data(), size: result.size()) == nullptr) {
390 // See if there was a real error.
391 if (errno != ENOMEM) {
392 result.clear();
393 return errnoAsErrorCode();
394 }
395 // Otherwise there just wasn't enough space.
396 result.resize_for_overwrite(N: result.capacity() * 2);
397 } else {
398 break;
399 }
400 }
401
402 result.truncate(N: strlen(s: result.data()));
403 return std::error_code();
404}
405
406std::error_code set_current_path(const Twine &path) {
407 sandbox::violationIfEnabled();
408
409 SmallString<128> path_storage;
410 StringRef p = path.toNullTerminatedStringRef(Out&: path_storage);
411
412 if (::chdir(path: p.begin()) == -1)
413 return errnoAsErrorCode();
414
415 return std::error_code();
416}
417
418std::error_code create_directory(const Twine &path, bool IgnoreExisting,
419 perms Perms) {
420 SmallString<128> path_storage;
421 StringRef p = path.toNullTerminatedStringRef(Out&: path_storage);
422
423 if (::mkdir(path: p.begin(), mode: Perms) == -1) {
424 if (errno != EEXIST || !IgnoreExisting)
425 return errnoAsErrorCode();
426 }
427
428 return std::error_code();
429}
430
431std::error_code create_symlink(const Twine &to, const Twine &from) {
432 // Get arguments.
433 SmallString<128> from_storage;
434 SmallString<128> to_storage;
435 StringRef f = from.toNullTerminatedStringRef(Out&: from_storage);
436 StringRef t = to.toNullTerminatedStringRef(Out&: to_storage);
437
438 if (::symlink(from: t.begin(), to: f.begin()) == -1)
439 return errnoAsErrorCode();
440
441 return std::error_code();
442}
443
444std::error_code create_link(const Twine &to, const Twine &from) {
445 std::error_code EC = create_symlink(to, from);
446 if (EC)
447 EC = create_hard_link(to, from);
448 return EC;
449}
450
451std::error_code create_hard_link(const Twine &to, const Twine &from) {
452 // Get arguments.
453 SmallString<128> from_storage;
454 SmallString<128> to_storage;
455 StringRef f = from.toNullTerminatedStringRef(Out&: from_storage);
456 StringRef t = to.toNullTerminatedStringRef(Out&: to_storage);
457
458 if (::link(from: t.begin(), to: f.begin()) == -1)
459 return errnoAsErrorCode();
460
461 return std::error_code();
462}
463
464std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
465 SmallString<128> path_storage;
466 StringRef p = path.toNullTerminatedStringRef(Out&: path_storage);
467
468 struct stat buf;
469 if (lstat(file: p.begin(), buf: &buf) != 0) {
470 if (errno != ENOENT || !IgnoreNonExisting)
471 return errnoAsErrorCode();
472 return std::error_code();
473 }
474
475 // Note: this check catches strange situations. In all cases, LLVM should
476 // only be involved in the creation and deletion of regular files. This
477 // check ensures that what we're trying to erase is a regular file. It
478 // effectively prevents LLVM from erasing things like /dev/null, any block
479 // special file, or other things that aren't "regular" files.
480 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
481 return make_error_code(E: errc::operation_not_permitted);
482
483 if (::remove(filename: p.begin()) == -1) {
484 if (errno != ENOENT || !IgnoreNonExisting)
485 return errnoAsErrorCode();
486 }
487
488 return std::error_code();
489}
490
491static bool is_local_impl(struct STATVFS &Vfs) {
492#if defined(__linux__) || defined(__GNU__) || defined(__managarm__)
493#ifndef NFS_SUPER_MAGIC
494#define NFS_SUPER_MAGIC 0x6969
495#endif
496#ifndef SMB_SUPER_MAGIC
497#define SMB_SUPER_MAGIC 0x517B
498#endif
499#ifndef CIFS_MAGIC_NUMBER
500#define CIFS_MAGIC_NUMBER 0xFF534D42
501#endif
502#ifndef DVS_FTYPE_MAGIC
503#define DVS_FTYPE_MAGIC 0x3E3F
504#endif
505#ifndef LUSTRE_SUPER_MAGIC
506#define LUSTRE_SUPER_MAGIC 0x0BD00BD0
507#endif
508#ifndef GPFS_SUPER_MAGIC
509#define GPFS_SUPER_MAGIC 0x47504653
510#endif
511#ifndef CEPH_SUPER_MAGIC
512#define CEPH_SUPER_MAGIC 0x00C36400
513#endif
514#ifndef AFS_SUPER_MAGIC
515#define AFS_SUPER_MAGIC 0x5346414F
516#endif
517#ifndef AFS_FS_MAGIC
518#define AFS_FS_MAGIC 0x6B414653
519#endif
520#ifndef BEEGFS_MAGIC
521#define BEEGFS_MAGIC 0x19830326
522#endif
523#if defined(__GNU__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 39)))
524 switch ((uint32_t)Vfs.__f_type) {
525#else
526 switch ((uint32_t)Vfs.f_type) {
527#endif
528 case NFS_SUPER_MAGIC:
529 case SMB_SUPER_MAGIC:
530 case CIFS_MAGIC_NUMBER:
531 case DVS_FTYPE_MAGIC:
532 case LUSTRE_SUPER_MAGIC:
533 case GPFS_SUPER_MAGIC:
534 case CEPH_SUPER_MAGIC:
535 case AFS_SUPER_MAGIC:
536 case AFS_FS_MAGIC:
537 case BEEGFS_MAGIC:
538 return false;
539 default:
540 return true;
541 }
542#elif defined(__CYGWIN__)
543 // Cygwin doesn't expose this information; would need to use Win32 API.
544 return false;
545#elif defined(__Fuchsia__)
546 // Fuchsia doesn't yet support remote filesystem mounts.
547 return true;
548#elif defined(__EMSCRIPTEN__)
549 // Emscripten doesn't currently support remote filesystem mounts.
550 return true;
551#elif defined(__HAIKU__)
552 // Haiku doesn't expose this information.
553 return false;
554#elif defined(__sun)
555 // statvfs::f_basetype contains a null-terminated FSType name of the mounted
556 // target
557 StringRef fstype(Vfs.f_basetype);
558 // NFS is the only non-local fstype??
559 return fstype != "nfs";
560#elif defined(_AIX)
561 // Call mntctl; try more than twice in case of timing issues with a concurrent
562 // mount.
563 int Ret;
564 size_t BufSize = 2048u;
565 std::unique_ptr<char[]> Buf;
566 int Tries = 3;
567 while (Tries--) {
568 Buf = std::make_unique<char[]>(BufSize);
569 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
570 if (Ret != 0)
571 break;
572 BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
573 Buf.reset();
574 }
575
576 if (Ret == -1)
577 // There was an error; "remote" is the conservative answer.
578 return false;
579
580 // Look for the correct vmount entry.
581 char *CurObjPtr = Buf.get();
582 while (Ret--) {
583 struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
584 static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
585 "fsid length mismatch");
586 if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
587 return (Vp->vmt_flags & MNT_REMOTE) == 0;
588
589 CurObjPtr += Vp->vmt_length;
590 }
591
592 // vmount entry not found; "remote" is the conservative answer.
593 return false;
594#elif defined(__MVS__)
595 // The file system can have an arbitrary structure on z/OS; must go with the
596 // conservative answer.
597 return false;
598#else
599 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
600#endif
601}
602
603std::error_code is_local(const Twine &Path, bool &Result) {
604 sandbox::violationIfEnabled();
605
606 struct STATVFS Vfs;
607 if (::STATVFS(file: const_cast<char *>(Path.str().c_str()), buf: &Vfs))
608 return errnoAsErrorCode();
609
610 Result = is_local_impl(Vfs);
611 return std::error_code();
612}
613
614std::error_code is_local(int FD, bool &Result) {
615 sandbox::violationIfEnabled();
616
617 struct STATVFS Vfs;
618 if (::FSTATVFS(fildes: FD, buf: &Vfs))
619 return errnoAsErrorCode();
620
621 Result = is_local_impl(Vfs);
622 return std::error_code();
623}
624
625std::error_code rename(const Twine &from, const Twine &to) {
626 // Get arguments.
627 SmallString<128> from_storage;
628 SmallString<128> to_storage;
629 StringRef f = from.toNullTerminatedStringRef(Out&: from_storage);
630 StringRef t = to.toNullTerminatedStringRef(Out&: to_storage);
631
632 if (::rename(old: f.begin(), new: t.begin()) == -1)
633 return errnoAsErrorCode();
634
635 return std::error_code();
636}
637
638std::error_code resize_file(int FD, uint64_t Size) {
639 // Use ftruncate as a fallback. It may or may not allocate space. At least on
640 // OS X with HFS+ it does.
641 if (sys::RetryAfterSignal(Fail: -1, F&: ::ftruncate, As: FD, As: Size) == -1)
642 return errnoAsErrorCode();
643
644 return std::error_code();
645}
646
647std::error_code resize_file_sparse(int FD, uint64_t Size) {
648 // On Unix, this is the same as `resize_file`.
649 return resize_file(FD, Size);
650}
651
652static int convertAccessMode(AccessMode Mode) {
653 switch (Mode) {
654 case AccessMode::Exist:
655 return F_OK;
656 case AccessMode::Write:
657 return W_OK;
658 case AccessMode::Execute:
659 return R_OK | X_OK; // scripts also need R_OK.
660 }
661 llvm_unreachable("invalid enum");
662}
663
664std::error_code access(const Twine &Path, AccessMode Mode) {
665 sandbox::violationIfEnabled();
666
667 SmallString<128> PathStorage;
668 StringRef P = Path.toNullTerminatedStringRef(Out&: PathStorage);
669
670 if (::access(name: P.begin(), type: convertAccessMode(Mode)) == -1)
671 return errnoAsErrorCode();
672
673 if (Mode == AccessMode::Execute) {
674 // Don't say that directories are executable.
675 struct stat buf;
676 if (0 != stat(file: P.begin(), buf: &buf))
677 return errc::permission_denied;
678 if (!S_ISREG(buf.st_mode))
679 return errc::permission_denied;
680 }
681
682 return std::error_code();
683}
684
685bool can_execute(const Twine &Path) {
686 sandbox::violationIfEnabled();
687
688 return !access(Path, Mode: AccessMode::Execute);
689}
690
691bool equivalent(file_status A, file_status B) {
692 assert(status_known(A) && status_known(B));
693 return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino;
694}
695
696std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
697 sandbox::violationIfEnabled();
698
699 file_status fsA, fsB;
700 if (std::error_code ec = status(path: A, result&: fsA))
701 return ec;
702 if (std::error_code ec = status(path: B, result&: fsB))
703 return ec;
704 result = equivalent(A: fsA, B: fsB);
705 return std::error_code();
706}
707
708static void expandTildeExpr(SmallVectorImpl<char> &Path) {
709 StringRef PathStr(Path.begin(), Path.size());
710 if (PathStr.empty() || !PathStr.starts_with(Prefix: "~"))
711 return;
712
713 PathStr = PathStr.drop_front();
714 StringRef Expr =
715 PathStr.take_until(F: [](char c) { return path::is_separator(value: c); });
716 StringRef Remainder = PathStr.substr(Start: Expr.size() + 1);
717 SmallString<128> Storage;
718 if (Expr.empty()) {
719 // This is just ~/..., resolve it to the current user's home dir.
720 if (!path::home_directory(result&: Storage)) {
721 // For some reason we couldn't get the home directory. Just exit.
722 return;
723 }
724
725 // Overwrite the first character and insert the rest.
726 Path[0] = Storage[0];
727 Path.insert(I: Path.begin() + 1, From: Storage.begin() + 1, To: Storage.end());
728 return;
729 }
730
731 // This is a string of the form ~username/, look up this user's entry in the
732 // password database.
733 std::unique_ptr<char[]> Buf;
734 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
735 if (BufSize <= 0)
736 BufSize = 16384;
737 Buf = std::make_unique<char[]>(num: BufSize);
738 struct passwd Pwd;
739 std::string User = Expr.str();
740 struct passwd *Entry = nullptr;
741 getpwnam_r(name: User.c_str(), resultbuf: &Pwd, buffer: Buf.get(), buflen: BufSize, result: &Entry);
742
743 if (!Entry || !Entry->pw_dir) {
744 // Unable to look up the entry, just return back the original path.
745 return;
746 }
747
748 Storage = Remainder;
749 Path.clear();
750 Path.append(in_start: Entry->pw_dir, in_end: Entry->pw_dir + strlen(s: Entry->pw_dir));
751 llvm::sys::path::append(path&: Path, a: Storage);
752}
753
754void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
755 dest.clear();
756 if (path.isTriviallyEmpty())
757 return;
758
759 path.toVector(Out&: dest);
760 expandTildeExpr(Path&: dest);
761}
762
763static file_type typeForMode(mode_t Mode) {
764 if (S_ISDIR(Mode))
765 return file_type::directory_file;
766 else if (S_ISREG(Mode))
767 return file_type::regular_file;
768 else if (S_ISBLK(Mode))
769 return file_type::block_file;
770 else if (S_ISCHR(Mode))
771 return file_type::character_file;
772 else if (S_ISFIFO(Mode))
773 return file_type::fifo_file;
774 else if (S_ISSOCK(Mode))
775 return file_type::socket_file;
776 else if (S_ISLNK(Mode))
777 return file_type::symlink_file;
778 return file_type::type_unknown;
779}
780
781static std::error_code fillStatus(int StatRet, const struct stat &Status,
782 file_status &Result) {
783 if (StatRet != 0) {
784 std::error_code EC = errnoAsErrorCode();
785 if (EC == errc::no_such_file_or_directory)
786 Result = file_status(file_type::file_not_found);
787 else
788 Result = file_status(file_type::status_error);
789 return EC;
790 }
791
792 uint32_t atime_nsec, mtime_nsec;
793#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
794 atime_nsec = Status.st_atimespec.tv_nsec;
795 mtime_nsec = Status.st_mtimespec.tv_nsec;
796#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
797 atime_nsec = Status.st_atim.tv_nsec;
798 mtime_nsec = Status.st_mtim.tv_nsec;
799#else
800 atime_nsec = mtime_nsec = 0;
801#endif
802
803 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
804 Result = file_status(typeForMode(Mode: Status.st_mode), Perms, Status.st_dev,
805 Status.st_nlink, Status.st_ino, Status.st_atime,
806 atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,
807 Status.st_gid, Status.st_size);
808
809 return std::error_code();
810}
811
812std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
813 sandbox::violationIfEnabled();
814
815 SmallString<128> PathStorage;
816 StringRef P = Path.toNullTerminatedStringRef(Out&: PathStorage);
817
818 struct stat Status;
819 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
820 return fillStatus(StatRet, Status, Result);
821}
822
823std::error_code status(file_t F, file_status &Result) {
824 return status(FD: F.get(), Result);
825}
826
827std::error_code status(int FD, file_status &Result) {
828 sandbox::violationIfEnabled();
829
830 struct stat Status;
831 int StatRet = ::fstat(fd: FD, buf: &Status);
832 return fillStatus(StatRet, Status, Result);
833}
834
835unsigned getUmask() {
836 // Chose arbitary new mask and reset the umask to the old mask.
837 // umask(2) never fails so ignore the return of the second call.
838 unsigned Mask = ::umask(mask: 0);
839 (void)::umask(mask: Mask);
840 return Mask;
841}
842
843std::error_code setPermissions(const Twine &Path, perms Permissions) {
844 SmallString<128> PathStorage;
845 StringRef P = Path.toNullTerminatedStringRef(Out&: PathStorage);
846
847 if (::chmod(file: P.begin(), mode: Permissions))
848 return errnoAsErrorCode();
849 return std::error_code();
850}
851
852std::error_code setPermissions(int FD, perms Permissions) {
853 if (::fchmod(fd: FD, mode: Permissions))
854 return errnoAsErrorCode();
855 return std::error_code();
856}
857
858std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
859 TimePoint<> ModificationTime) {
860#if defined(HAVE_FUTIMENS)
861 timespec Times[2];
862 Times[0] = sys::toTimeSpec(TP: AccessTime);
863 Times[1] = sys::toTimeSpec(TP: ModificationTime);
864 if (::futimens(fd: FD, times: Times))
865 return errnoAsErrorCode();
866 return std::error_code();
867#elif defined(HAVE_FUTIMES)
868 timeval Times[2];
869 Times[0] = sys::toTimeVal(
870 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
871 Times[1] =
872 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
873 ModificationTime));
874 if (::futimes(FD, Times))
875 return errnoAsErrorCode();
876 return std::error_code();
877#elif defined(__MVS__)
878 attrib_t Attr;
879 memset(&Attr, 0, sizeof(Attr));
880 Attr.att_atimechg = 1;
881 Attr.att_atime = sys::toTimeT(AccessTime);
882 Attr.att_mtimechg = 1;
883 Attr.att_mtime = sys::toTimeT(ModificationTime);
884 if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
885 return errnoAsErrorCode();
886 return std::error_code();
887#else
888#warning Missing futimes() and futimens()
889 return make_error_code(errc::function_not_supported);
890#endif
891}
892
893std::error_code mapped_file_region::init(file_t FD, uint64_t Offset,
894 mapmode Mode, const char *Name) {
895 assert(Size != 0);
896
897 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
898 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
899#if defined(MAP_NORESERVE)
900 flags |= MAP_NORESERVE;
901#endif
902#if defined(__APPLE__)
903 //----------------------------------------------------------------------
904 // Newer versions of MacOSX have a flag that will allow us to read from
905 // binaries whose code signature is invalid without crashing by using
906 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
907 // is mapped we can avoid crashing and return zeroes to any pages we try
908 // to read if the media becomes unavailable by using the
909 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
910 // with PROT_READ, so take care not to specify them otherwise.
911 //----------------------------------------------------------------------
912 if (Mode == readonly) {
913#if defined(MAP_RESILIENT_CODESIGN)
914 flags |= MAP_RESILIENT_CODESIGN;
915#endif
916#if defined(MAP_RESILIENT_MEDIA)
917 flags |= MAP_RESILIENT_MEDIA;
918#endif
919 }
920#endif // #if defined (__APPLE__)
921
922 Mapping = ::mmap(addr: nullptr, len: Size, prot: prot, flags: flags, fd: FD.get(), offset: Offset);
923 if (Mapping == MAP_FAILED)
924 return errnoAsErrorCode();
925 return std::error_code();
926}
927
928mapped_file_region::mapped_file_region(file_t fd, mapmode mode, size_t length,
929 uint64_t offset, std::error_code &ec,
930 const char *name)
931 : Size(length), Mode(mode) {
932 sandbox::violationIfEnabled();
933
934 (void)Mode;
935 ec = init(FD: fd, Offset: offset, Mode: mode, Name: name);
936 if (ec)
937 copyFrom(Copied: mapped_file_region());
938}
939
940void mapped_file_region::unmapImpl() {
941 if (Mapping)
942 ::munmap(addr: Mapping, len: Size);
943}
944
945std::error_code mapped_file_region::sync() const {
946 if (int Res = sys::RetryAfterSignal(Fail: -1, F&: ::msync, As: Mapping, As: Size, MS_SYNC))
947 return std::error_code(Res, std::generic_category());
948 return std::error_code();
949}
950
951void mapped_file_region::dontNeedImpl() {
952 assert(Mode == mapped_file_region::readonly);
953 if (!Mapping)
954 return;
955#ifdef __linux__
956 // Linux's MADV_DONTNEED unmaps the pages and reduces RSS. Other systems
957 // treat it as a hint (macOS keeps the pages resident), and glibc and musl's
958 // posix_madvise ignore POSIX_MADV_DONTNEED.
959 ::madvise(addr: Mapping, len: Size, MADV_DONTNEED);
960#endif
961}
962
963void mapped_file_region::willNeedImpl() {
964 assert(Mode == mapped_file_region::readonly);
965 if (!Mapping)
966 return;
967#if defined(__MVS__) || defined(_AIX)
968 // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
969#elif defined(POSIX_MADV_WILLNEED)
970 ::posix_madvise(addr: Mapping, len: Size, POSIX_MADV_WILLNEED);
971#else
972 ::madvise(Mapping, Size, MADV_WILLNEED);
973#endif
974}
975
976void mapped_file_region::randomAccessImpl() {
977 assert(Mode == mapped_file_region::readonly);
978 if (!Mapping)
979 return;
980#if defined(__MVS__) || defined(_AIX)
981 // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
982#elif defined(POSIX_MADV_RANDOM)
983 ::posix_madvise(addr: Mapping, len: Size, POSIX_MADV_RANDOM);
984#else
985 ::madvise(Mapping, Size, MADV_RANDOM);
986#endif
987}
988
989int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }
990
991std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
992 StringRef path,
993 bool follow_symlinks) {
994 sandbox::violationIfEnabled();
995
996 SmallString<128> path_null(path);
997 DIR *directory = ::opendir(name: path_null.c_str());
998 if (!directory)
999 return errnoAsErrorCode();
1000
1001 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
1002 // Add something for replace_filename to replace.
1003 path::append(path&: path_null, a: ".");
1004 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
1005 return directory_iterator_increment(it);
1006}
1007
1008std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
1009 if (it.IterationHandle)
1010 ::closedir(dirp: reinterpret_cast<DIR *>(it.IterationHandle));
1011 it.IterationHandle = 0;
1012 it.CurrentEntry = directory_entry();
1013 return std::error_code();
1014}
1015
1016static file_type direntType(dirent *Entry) {
1017 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
1018 // The DTTOIF macro lets us reuse our status -> type conversion.
1019 // Note that while glibc provides a macro to see if this is supported,
1020 // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
1021 // d_type-to-mode_t conversion macro instead.
1022#if defined(DTTOIF)
1023 return typeForMode(DTTOIF(Entry->d_type));
1024#else
1025 // Other platforms such as Solaris require a stat() to get the type.
1026 return file_type::type_unknown;
1027#endif
1028}
1029
1030std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
1031 sandbox::violationIfEnabled();
1032
1033 errno = 0;
1034 dirent *CurDir = ::readdir(dirp: reinterpret_cast<DIR *>(It.IterationHandle));
1035 if (CurDir == nullptr && errno != 0) {
1036 return errnoAsErrorCode();
1037 } else if (CurDir != nullptr) {
1038 StringRef Name(CurDir->d_name);
1039 if ((Name.size() == 1 && Name[0] == '.') ||
1040 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
1041 return directory_iterator_increment(It);
1042 It.CurrentEntry.replace_filename(Filename: Name, Type: direntType(Entry: CurDir));
1043 } else {
1044 return directory_iterator_destruct(it&: It);
1045 }
1046
1047 return std::error_code();
1048}
1049
1050ErrorOr<basic_file_status> directory_entry::status() const {
1051 sandbox::violationIfEnabled();
1052
1053 file_status s;
1054 if (auto EC = fs::status(Path, Result&: s, Follow: FollowSymlinks))
1055 return EC;
1056 return s;
1057}
1058
1059// Only enable on OSes that have the /proc filesystem, /proc/self/fd,
1060// and semantics compatible with Linux.
1061#if defined(__linux__)
1062#define TRY_PROC_SELF_FD
1063#endif
1064
1065#if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
1066static bool hasProcSelfFD() {
1067 // If we have a /proc filesystem mounted, we can quickly establish the
1068 // real name of the file with readlink
1069 static const bool Result = (::access(name: "/proc/self/fd", R_OK) == 0);
1070 return Result;
1071}
1072#endif
1073
1074static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
1075 FileAccess Access) {
1076 int Result = 0;
1077 if (Access == FA_Read)
1078 Result |= O_RDONLY;
1079 else if (Access == FA_Write)
1080 Result |= O_WRONLY;
1081 else if (Access == (FA_Read | FA_Write))
1082 Result |= O_RDWR;
1083
1084 // This is for compatibility with old code that assumed OF_Append implied
1085 // would open an existing file. See Windows/Path.inc for a longer comment.
1086 if (Flags & OF_Append)
1087 Disp = CD_OpenAlways;
1088
1089 if (Disp == CD_CreateNew) {
1090 Result |= O_CREAT; // Create if it doesn't exist.
1091 Result |= O_EXCL; // Fail if it does.
1092 } else if (Disp == CD_CreateAlways) {
1093 Result |= O_CREAT; // Create if it doesn't exist.
1094 Result |= O_TRUNC; // Truncate if it does.
1095 } else if (Disp == CD_OpenAlways) {
1096 Result |= O_CREAT; // Create if it doesn't exist.
1097 } else if (Disp == CD_OpenExisting) {
1098 // Nothing special, just don't add O_CREAT and we get these semantics.
1099 }
1100
1101// Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1102// calling write(). Instead we need to use lseek() to set offset to EOF after
1103// open().
1104#ifndef __MVS__
1105 if (Flags & OF_Append)
1106 Result |= O_APPEND;
1107#endif
1108
1109#ifdef O_CLOEXEC
1110 if (!(Flags & OF_ChildInherit))
1111 Result |= O_CLOEXEC;
1112#endif
1113
1114 return Result;
1115}
1116
1117std::error_code openFile(const Twine &Name, int &ResultFD,
1118 CreationDisposition Disp, FileAccess Access,
1119 OpenFlags Flags, unsigned Mode) {
1120 sandbox::violationIfEnabled();
1121
1122 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
1123
1124 SmallString<128> Storage;
1125 StringRef P = Name.toNullTerminatedStringRef(Out&: Storage);
1126 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
1127 // when open is overloaded, such as in Bionic.
1128 auto Open = [&]() { return ::open(file: P.begin(), oflag: OpenFlags, Mode); };
1129 if ((ResultFD = sys::RetryAfterSignal(Fail: -1, F: Open)) < 0)
1130 return errnoAsErrorCode();
1131#ifndef O_CLOEXEC
1132 if (!(Flags & OF_ChildInherit)) {
1133 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1134 (void)r;
1135 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
1136 }
1137#endif
1138
1139#ifdef __MVS__
1140 /* Reason about auto-conversion and file tags. Setting the file tag only
1141 * applies if file is opened in write mode:
1142 *
1143 * Text file:
1144 * File exists File created
1145 * CD_CreateNew n/a conv: on
1146 * tag: set 1047
1147 * CD_CreateAlways conv: auto conv: on
1148 * tag: auto 1047 tag: set 1047
1149 * CD_OpenAlways conv: auto conv: on
1150 * tag: auto 1047 tag: set 1047
1151 * CD_OpenExisting conv: auto n/a
1152 * tag: unchanged
1153 *
1154 * Binary file:
1155 * File exists File created
1156 * CD_CreateNew n/a conv: off
1157 * tag: set binary
1158 * CD_CreateAlways conv: off conv: off
1159 * tag: auto binary tag: set binary
1160 * CD_OpenAlways conv: off conv: off
1161 * tag: auto binary tag: set binary
1162 * CD_OpenExisting conv: off n/a
1163 * tag: unchanged
1164 *
1165 * Actions:
1166 * conv: off -> auto-conversion is turned off
1167 * conv: on -> auto-conversion is turned on
1168 * conv: auto -> auto-conversion is turned on if the file is untagged
1169 * tag: set 1047 -> set the file tag to text encoded in 1047
1170 * tag: set binary -> set the file tag to binary
1171 * tag: auto 1047 -> set file tag to 1047 if not set
1172 * tag: auto binary -> set file tag to binary if not set
1173 * tag: unchanged -> do not care about the file tag
1174 *
1175 * It is not possible to distinguish between the cases "file exists" and
1176 * "file created". In the latter case, the file tag is not set and the file
1177 * size is zero. The decision table boils down to:
1178 *
1179 * the file tag is set if
1180 * - the file is opened for writing
1181 * - the create disposition is not equal to CD_OpenExisting
1182 * - the file tag is not set
1183 * - the file size is zero
1184 *
1185 * This only applies if the file is a regular file. E.g. enabling
1186 * auto-conversion for reading from /dev/null results in error EINVAL when
1187 * calling read().
1188 *
1189 * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1190 * calling write(). Instead we need to use lseek() to set offset to EOF after
1191 * open().
1192 */
1193 if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1194 return errnoAsErrorCode();
1195 struct stat Stat;
1196 if (fstat(ResultFD, &Stat) == -1)
1197 return errnoAsErrorCode();
1198 if (S_ISREG(Stat.st_mode)) {
1199 bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
1200 !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1201 Stat.st_size == 0;
1202 if (Flags & OF_Text) {
1203 if ((Access & FA_Write) && (Disp != CD_OpenExisting)) {
1204 int ccsid = (Flags & OF_ForceUTF8) ? CCSID_UTF_8 : CCSID_IBM_1047;
1205 if (Stat.st_tag.ft_txtflag && Stat.st_tag.ft_ccsid != FT_UNTAGGED)
1206 ccsid = Stat.st_tag.ft_ccsid;
1207 if (auto EC = llvm::enableAutoConversion(ResultFD, ccsid))
1208 return EC;
1209 if (DoSetTag) {
1210 if (auto EC = llvm::setzOSFileTag(ResultFD, ccsid, /*IsText=*/true))
1211 return EC;
1212 }
1213 } else if (auto EC = llvm::enableAutoConversion(ResultFD))
1214 return EC;
1215 } else {
1216 if (auto EC = llvm::disableAutoConversion(ResultFD))
1217 return EC;
1218 if (DoSetTag) {
1219 if (auto EC =
1220 llvm::setzOSFileTag(ResultFD, FT_BINARY, /*IsText=*/false))
1221 return EC;
1222 }
1223 }
1224 }
1225#endif
1226
1227 return std::error_code();
1228}
1229
1230Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1231 FileAccess Access, OpenFlags Flags,
1232 unsigned Mode) {
1233 sandbox::violationIfEnabled();
1234
1235 int FD;
1236 std::error_code EC = openFile(Name, ResultFD&: FD, Disp, Access, Flags, Mode);
1237 if (EC)
1238 return errorCodeToError(EC);
1239 return FD;
1240}
1241
1242std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1243 OpenFlags Flags,
1244 SmallVectorImpl<char> *RealPath) {
1245 sandbox::violationIfEnabled();
1246
1247 std::error_code EC =
1248 openFile(Name, ResultFD, Disp: CD_OpenExisting, Access: FA_Read, Flags, Mode: 0666);
1249 if (EC)
1250 return EC;
1251
1252 // Attempt to get the real name of the file, if the user asked
1253 if (!RealPath)
1254 return std::error_code();
1255 RealPath->clear();
1256 // Fast path: ask for the real file path via handle.
1257 if (getRealPathFromHandle(Handle: ResultFD, RealPath&: *RealPath) == errc::not_supported) {
1258 // Slow path: ask for the real file path via name.
1259 SmallString<128> Storage;
1260 StringRef P = Name.toNullTerminatedStringRef(Out&: Storage);
1261 char Buffer[PATH_MAX];
1262 if (::realpath(name: P.begin(), resolved: Buffer) != nullptr)
1263 RealPath->append(in_start: Buffer, in_end: Buffer + strlen(s: Buffer));
1264 }
1265 return std::error_code();
1266}
1267
1268std::error_code getRealPathFromHandle(file_t Handle,
1269 SmallVectorImpl<char> &RealPath) {
1270#if defined(F_GETPATH)
1271 char Buffer[PATH_MAX];
1272 // When F_GETPATH is available, it is the quickest way to get
1273 // the real path name.
1274 if (::fcntl(Handle.get(), F_GETPATH, Buffer) != -1) {
1275 RealPath.append(Buffer, Buffer + strlen(Buffer));
1276 return std::error_code();
1277 }
1278 return std::error_code(errno, std::generic_category());
1279#elif defined(TRY_PROC_SELF_FD)
1280 char Buffer[PATH_MAX];
1281 if (hasProcSelfFD()) {
1282 char ProcPath[64];
1283 snprintf(s: ProcPath, maxlen: sizeof(ProcPath), format: "/proc/self/fd/%d", Handle.get());
1284 ssize_t CharCount = ::readlink(path: ProcPath, buf: Buffer, len: sizeof(Buffer));
1285 if (CharCount > 0) {
1286 RealPath.append(in_start: Buffer, in_end: Buffer + CharCount);
1287 return std::error_code();
1288 }
1289 return std::error_code(errno, std::generic_category());
1290 }
1291 return make_error_code(E: errc::not_supported);
1292#else
1293 return make_error_code(errc::not_supported);
1294#endif
1295}
1296
1297Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1298 SmallVectorImpl<char> *RealPath) {
1299 sandbox::violationIfEnabled();
1300
1301 int ResultFD;
1302 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
1303 if (EC)
1304 return errorCodeToError(EC);
1305// The underlying operation on these platforms allow opening directories
1306// for reading in more cases than other platforms.
1307#if defined(__MVS__) || defined(_AIX)
1308 struct stat Status;
1309 if (fstat(ResultFD, &Status) == -1)
1310 return errorCodeToError(errnoAsErrorCode());
1311 if (S_ISDIR(Status.st_mode))
1312 return errorCodeToError(make_error_code(errc::is_a_directory));
1313#endif
1314 return ResultFD;
1315}
1316
1317file_t getStdinHandle() { return 0; }
1318file_t getStdoutHandle() { return 1; }
1319file_t getStderrHandle() { return 2; }
1320
1321Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
1322 sandbox::violationIfEnabled();
1323
1324#if defined(__APPLE__)
1325 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1326#else
1327 size_t Size = Buf.size();
1328#endif
1329 ssize_t NumRead =
1330 sys::RetryAfterSignal(Fail: -1, F&: ::read, As: FD.get(), As: Buf.data(), As: Size);
1331 if (NumRead == -1)
1332 return errorCodeToError(EC: errnoAsErrorCode());
1333 return NumRead;
1334}
1335
1336Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1337 uint64_t Offset) {
1338 sandbox::violationIfEnabled();
1339
1340#if defined(__APPLE__)
1341 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1342#else
1343 size_t Size = Buf.size();
1344#endif
1345#ifdef HAVE_PREAD
1346 ssize_t NumRead =
1347 sys::RetryAfterSignal(Fail: -1, F&: ::pread, As: FD.get(), As: Buf.data(), As: Size, As: Offset);
1348#else
1349 if (lseek(FD.get(), Offset, SEEK_SET) == -1)
1350 return errorCodeToError(errnoAsErrorCode());
1351 ssize_t NumRead =
1352 sys::RetryAfterSignal(-1, ::read, FD.get(), Buf.data(), Size);
1353#endif
1354 if (NumRead == -1)
1355 return errorCodeToError(EC: errnoAsErrorCode());
1356 return NumRead;
1357}
1358
1359std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,
1360 LockKind Kind) {
1361 auto Start = std::chrono::steady_clock::now();
1362 auto End = Start + Timeout;
1363 do {
1364 struct flock Lock;
1365 memset(s: &Lock, c: 0, n: sizeof(Lock));
1366 switch (Kind) {
1367 case LockKind::Exclusive:
1368 Lock.l_type = F_WRLCK;
1369 break;
1370 case LockKind::Shared:
1371 Lock.l_type = F_RDLCK;
1372 break;
1373 }
1374 Lock.l_whence = SEEK_SET;
1375 Lock.l_start = 0;
1376 Lock.l_len = 0;
1377 if (::fcntl(fd: FD, F_SETLK, &Lock) != -1)
1378 return std::error_code();
1379 int Error = errno;
1380 if (Error != EACCES && Error != EAGAIN)
1381 return std::error_code(Error, std::generic_category());
1382 if (Timeout.count() == 0)
1383 break;
1384 usleep(useconds: 1000);
1385 } while (std::chrono::steady_clock::now() < End);
1386 return make_error_code(E: errc::no_lock_available);
1387}
1388
1389std::error_code lockFile(int FD, LockKind Kind) {
1390 struct flock Lock;
1391 memset(s: &Lock, c: 0, n: sizeof(Lock));
1392 switch (Kind) {
1393 case LockKind::Exclusive:
1394 Lock.l_type = F_WRLCK;
1395 break;
1396 case LockKind::Shared:
1397 Lock.l_type = F_RDLCK;
1398 break;
1399 }
1400 Lock.l_whence = SEEK_SET;
1401 Lock.l_start = 0;
1402 Lock.l_len = 0;
1403 if (sys::RetryAfterSignal(Fail: -1, F&: ::fcntl, As: FD, F_SETLKW, As: &Lock) != -1)
1404 return std::error_code();
1405 return errnoAsErrorCode();
1406}
1407
1408std::error_code unlockFile(int FD) {
1409 struct flock Lock;
1410 Lock.l_type = F_UNLCK;
1411 Lock.l_whence = SEEK_SET;
1412 Lock.l_start = 0;
1413 Lock.l_len = 0;
1414 if (sys::RetryAfterSignal(Fail: -1, F&: ::fcntl, As: FD, F_SETLK, As: &Lock) != -1)
1415 return std::error_code();
1416 return errnoAsErrorCode();
1417}
1418
1419std::error_code closeFile(file_t &F) {
1420 sandbox::violationIfEnabled();
1421
1422 file_t TmpF = F;
1423 F = file_t::Invalid;
1424 return Process::SafelyCloseFileDescriptor(FD: TmpF.get());
1425}
1426
1427template <typename T>
1428static std::error_code remove_directories_impl(const T &Entry,
1429 bool IgnoreErrors) {
1430 std::error_code EC;
1431 directory_iterator Begin(Entry, EC, false);
1432 directory_iterator End;
1433 while (Begin != End) {
1434 auto &Item = *Begin;
1435 ErrorOr<basic_file_status> st = Item.status();
1436 if (st) {
1437 if (is_directory(status: *st)) {
1438 EC = remove_directories_impl(Entry: Item, IgnoreErrors);
1439 if (EC && !IgnoreErrors)
1440 return EC;
1441 }
1442
1443 EC = fs::remove(path: Item.path(), IgnoreNonExisting: true);
1444 if (EC && !IgnoreErrors)
1445 return EC;
1446 } else if (!IgnoreErrors) {
1447 return st.getError();
1448 }
1449
1450 Begin.increment(ec&: EC);
1451 if (EC && !IgnoreErrors)
1452 return EC;
1453 }
1454 return std::error_code();
1455}
1456
1457std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1458 auto EC = remove_directories_impl(Entry: path, IgnoreErrors);
1459 if (EC && !IgnoreErrors)
1460 return EC;
1461 EC = fs::remove(path, IgnoreNonExisting: true);
1462 if (EC && !IgnoreErrors)
1463 return EC;
1464 return std::error_code();
1465}
1466
1467std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1468 bool expand_tilde) {
1469 sandbox::violationIfEnabled();
1470
1471 dest.clear();
1472 if (path.isTriviallyEmpty())
1473 return std::error_code();
1474
1475 if (expand_tilde) {
1476 SmallString<128> Storage;
1477 path.toVector(Out&: Storage);
1478 expandTildeExpr(Path&: Storage);
1479 return real_path(path: Storage, dest, expand_tilde: false);
1480 }
1481
1482 SmallString<128> Storage;
1483 StringRef P = path.toNullTerminatedStringRef(Out&: Storage);
1484 char Buffer[PATH_MAX];
1485 if (::realpath(name: P.begin(), resolved: Buffer) == nullptr)
1486 return errnoAsErrorCode();
1487 dest.append(in_start: Buffer, in_end: Buffer + strlen(s: Buffer));
1488 return std::error_code();
1489}
1490
1491std::error_code readlink(const Twine &path, SmallVectorImpl<char> &dest) {
1492 dest.clear();
1493
1494 SmallString<128> Storage;
1495 StringRef P = path.toNullTerminatedStringRef(Out&: Storage);
1496
1497 // Call ::readlink in a loop, growing the buffer until the result fits. We
1498 // can't use lstat to get the size ahead of time because it's racy (the
1499 // symlink can be replaced between lstat and readlink), and some filesystems
1500 // (e.g. /proc on Linux) report st_size == 0 for symlinks.
1501 //
1502 // Default buffer starts at destination's current capacity unless that's too
1503 // small. 32 is the somewhat arbitrary lower bound, but if we're going to have
1504 // to allocate anyway it should have a reasonable chance of holding the
1505 // result. This is to handle cases of `SmallString<0>` as buffers.
1506 size_t BufSize = std::max(a: std::size_t{32}, b: dest.capacity());
1507 for (;;) {
1508 dest.resize_for_overwrite(N: BufSize);
1509 ssize_t Len = ::readlink(path: P.begin(), buf: dest.data(), len: dest.size());
1510 if (Len < 0)
1511 return errnoAsErrorCode();
1512 if (static_cast<size_t>(Len) < BufSize) {
1513 dest.truncate(N: Len);
1514 return std::error_code();
1515 }
1516 // Result may have been truncated. Grow and retry.
1517 BufSize *= 2;
1518 }
1519}
1520
1521std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
1522 auto FChown = [&]() { return ::fchown(fd: FD, owner: Owner, group: Group); };
1523 // Retry if fchown call fails due to interruption.
1524 if ((sys::RetryAfterSignal(Fail: -1, F: FChown)) < 0)
1525 return errnoAsErrorCode();
1526 return std::error_code();
1527}
1528
1529} // end namespace fs
1530
1531namespace path {
1532
1533bool home_directory(SmallVectorImpl<char> &result) {
1534 std::unique_ptr<char[]> Buf;
1535 char *RequestedDir = getenv(name: "HOME");
1536 if (!RequestedDir) {
1537 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
1538 if (BufSize <= 0)
1539 BufSize = 16384;
1540 Buf = std::make_unique<char[]>(num: BufSize);
1541 struct passwd Pwd;
1542 struct passwd *pw = nullptr;
1543 getpwuid_r(uid: getuid(), resultbuf: &Pwd, buffer: Buf.get(), buflen: BufSize, result: &pw);
1544 if (pw && pw->pw_dir)
1545 RequestedDir = pw->pw_dir;
1546 }
1547 if (!RequestedDir)
1548 return false;
1549
1550 result.clear();
1551 result.append(in_start: RequestedDir, in_end: RequestedDir + strlen(s: RequestedDir));
1552 return true;
1553}
1554
1555static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1556#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1557 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1558 // macros defined in <unistd.h> on darwin >= 9
1559 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;
1560 size_t ConfLen = confstr(ConfName, nullptr, 0);
1561 if (ConfLen > 0) {
1562 do {
1563 Result.resize(ConfLen);
1564 ConfLen = confstr(ConfName, Result.data(), Result.size());
1565 } while (ConfLen > 0 && ConfLen != Result.size());
1566
1567 if (ConfLen > 0) {
1568 assert(Result.back() == 0);
1569 Result.pop_back();
1570 return true;
1571 }
1572
1573 Result.clear();
1574 }
1575#endif
1576 return false;
1577}
1578
1579bool user_config_directory(SmallVectorImpl<char> &result) {
1580#ifdef __APPLE__
1581 // Mac: ~/Library/Preferences/
1582 if (home_directory(result)) {
1583 append(result, "Library", "Preferences");
1584 return true;
1585 }
1586#else
1587 // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
1588 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1589 if (const char *RequestedDir = getenv(name: "XDG_CONFIG_HOME")) {
1590 result.clear();
1591 result.append(in_start: RequestedDir, in_end: RequestedDir + strlen(s: RequestedDir));
1592 return true;
1593 }
1594#endif
1595 // Fallback: ~/.config
1596 if (!home_directory(result)) {
1597 return false;
1598 }
1599 append(path&: result, a: ".config");
1600 return true;
1601}
1602
1603bool cache_directory(SmallVectorImpl<char> &result) {
1604#ifdef __APPLE__
1605 if (getDarwinConfDir(false /*tempDir*/, result)) {
1606 return true;
1607 }
1608#else
1609 // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
1610 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1611 if (const char *RequestedDir = getenv(name: "XDG_CACHE_HOME")) {
1612 result.clear();
1613 result.append(in_start: RequestedDir, in_end: RequestedDir + strlen(s: RequestedDir));
1614 return true;
1615 }
1616#endif
1617 if (!home_directory(result)) {
1618 return false;
1619 }
1620 append(path&: result, a: ".cache");
1621 return true;
1622}
1623
1624static const char *getEnvTempDir() {
1625 // Check whether the temporary directory is specified by an environment
1626 // variable.
1627 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1628 for (const char *Env : EnvironmentVariables) {
1629 if (const char *Dir = std::getenv(name: Env))
1630 return Dir;
1631 }
1632
1633 return nullptr;
1634}
1635
1636static const char *getDefaultTempDir(bool ErasedOnReboot) {
1637#ifdef P_tmpdir
1638 if ((bool)P_tmpdir)
1639 return P_tmpdir;
1640#endif
1641
1642 if (ErasedOnReboot)
1643 return "/tmp";
1644 return "/var/tmp";
1645}
1646
1647void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1648 Result.clear();
1649
1650 if (ErasedOnReboot) {
1651 // There is no env variable for the cache directory.
1652 if (const char *RequestedDir = getEnvTempDir()) {
1653 Result.append(in_start: RequestedDir, in_end: RequestedDir + strlen(s: RequestedDir));
1654 return;
1655 }
1656 }
1657
1658 if (getDarwinConfDir(TempDir: ErasedOnReboot, Result))
1659 return;
1660
1661 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1662 Result.append(in_start: RequestedDir, in_end: RequestedDir + strlen(s: RequestedDir));
1663}
1664
1665} // end namespace path
1666
1667namespace fs {
1668
1669#ifdef __APPLE__
1670/// This implementation tries to perform an APFS CoW clone of the file,
1671/// which can be much faster and uses less space.
1672/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1673/// file descriptor variant of this function still uses the default
1674/// implementation.
1675std::error_code copy_file(const Twine &From, const Twine &To) {
1676 std::string FromS = From.str();
1677 std::string ToS = To.str();
1678#if __has_builtin(__builtin_available)
1679 if (__builtin_available(macos 10.12, *)) {
1680 // Optimistically try to use clonefile() and handle errors, rather than
1681 // calling stat() to see if it'll work.
1682 //
1683 // Note: It's okay if From is a symlink. In contrast to the behaviour of
1684 // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
1685 // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
1686 if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
1687 return std::error_code();
1688
1689 auto Errno = errno;
1690 switch (Errno) {
1691 case EEXIST: // To already exists.
1692 case ENOTSUP: // Device does not support cloning.
1693 case EXDEV: // From and To are on different devices.
1694 break;
1695 default:
1696 // Anything else will also break copyfile().
1697 return std::error_code(Errno, std::generic_category());
1698 }
1699
1700 // TODO: For EEXIST, profile calling fs::generateUniqueName() and
1701 // clonefile() in a retry loop (then rename() on success) before falling
1702 // back to copyfile(). Depending on the size of the file this could be
1703 // cheaper.
1704 }
1705#endif
1706 if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
1707 return std::error_code();
1708 return errnoAsErrorCode();
1709}
1710#endif // __APPLE__
1711
1712} // end namespace fs
1713
1714} // end namespace sys
1715} // end namespace llvm
1716