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