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