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