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