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
350UniqueID file_status::getUniqueID() const {
351 return UniqueID(fs_st_dev, fs_st_ino);
352}
353
354uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }
355
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
603static int convertAccessMode(AccessMode Mode) {
604 switch (Mode) {
606 return F_OK;
608 return W_OK;
610 return R_OK | X_OK; // scripts also need R_OK.
611 }
612 llvm_unreachable("invalid enum");
613}
614
615std::error_code access(const Twine &Path, AccessMode Mode) {
616 SmallString<128> PathStorage;
617 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
618
619 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
620 return errnoAsErrorCode();
621
622 if (Mode == AccessMode::Execute) {
623 // Don't say that directories are executable.
624 struct stat buf;
625 if (0 != stat(P.begin(), &buf))
627 if (!S_ISREG(buf.st_mode))
629 }
630
631 return std::error_code();
632}
633
634bool can_execute(const Twine &Path) {
635 return !access(Path, AccessMode::Execute);
636}
637
638bool equivalent(file_status A, file_status B) {
640 return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino;
641}
642
643std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
644 file_status fsA, fsB;
645 if (std::error_code ec = status(A, fsA))
646 return ec;
647 if (std::error_code ec = status(B, fsB))
648 return ec;
649 result = equivalent(fsA, fsB);
650 return std::error_code();
651}
652
653static void expandTildeExpr(SmallVectorImpl<char> &Path) {
654 StringRef PathStr(Path.begin(), Path.size());
655 if (PathStr.empty() || !PathStr.starts_with("~"))
656 return;
657
658 PathStr = PathStr.drop_front();
659 StringRef Expr =
660 PathStr.take_until([](char c) { return path::is_separator(c); });
661 StringRef Remainder = PathStr.substr(Expr.size() + 1);
662 SmallString<128> Storage;
663 if (Expr.empty()) {
664 // This is just ~/..., resolve it to the current user's home dir.
665 if (!path::home_directory(Storage)) {
666 // For some reason we couldn't get the home directory. Just exit.
667 return;
668 }
669
670 // Overwrite the first character and insert the rest.
671 Path[0] = Storage[0];
672 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
673 return;
674 }
675
676 // This is a string of the form ~username/, look up this user's entry in the
677 // password database.
678 std::unique_ptr<char[]> Buf;
679 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
680 if (BufSize <= 0)
681 BufSize = 16384;
682 Buf = std::make_unique<char[]>(BufSize);
683 struct passwd Pwd;
684 std::string User = Expr.str();
685 struct passwd *Entry = nullptr;
686 getpwnam_r(User.c_str(), &Pwd, Buf.get(), BufSize, &Entry);
687
688 if (!Entry || !Entry->pw_dir) {
689 // Unable to look up the entry, just return back the original path.
690 return;
691 }
692
693 Storage = Remainder;
694 Path.clear();
695 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
696 llvm::sys::path::append(Path, Storage);
697}
698
699void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
700 dest.clear();
701 if (path.isTriviallyEmpty())
702 return;
703
704 path.toVector(dest);
705 expandTildeExpr(dest);
706}
707
708static file_type typeForMode(mode_t Mode) {
709 if (S_ISDIR(Mode))
711 else if (S_ISREG(Mode))
713 else if (S_ISBLK(Mode))
715 else if (S_ISCHR(Mode))
717 else if (S_ISFIFO(Mode))
719 else if (S_ISSOCK(Mode))
721 else if (S_ISLNK(Mode))
724}
725
726static std::error_code fillStatus(int StatRet, const struct stat &Status,
727 file_status &Result) {
728 if (StatRet != 0) {
729 std::error_code EC = errnoAsErrorCode();
731 Result = file_status(file_type::file_not_found);
732 else
733 Result = file_status(file_type::status_error);
734 return EC;
735 }
736
737 uint32_t atime_nsec, mtime_nsec;
738#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
739 atime_nsec = Status.st_atimespec.tv_nsec;
740 mtime_nsec = Status.st_mtimespec.tv_nsec;
741#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
742 atime_nsec = Status.st_atim.tv_nsec;
743 mtime_nsec = Status.st_mtim.tv_nsec;
744#else
745 atime_nsec = mtime_nsec = 0;
746#endif
747
748 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
749 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
750 Status.st_nlink, Status.st_ino, Status.st_atime,
751 atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,
752 Status.st_gid, Status.st_size);
753
754 return std::error_code();
755}
756
757std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
758 SmallString<128> PathStorage;
759 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
760
761 struct stat Status;
762 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
763 return fillStatus(StatRet, Status, Result);
764}
765
766std::error_code status(int FD, file_status &Result) {
767 struct stat Status;
768 int StatRet = ::fstat(FD, &Status);
769 return fillStatus(StatRet, Status, Result);
770}
771
772unsigned getUmask() {
773 // Chose arbitary new mask and reset the umask to the old mask.
774 // umask(2) never fails so ignore the return of the second call.
775 unsigned Mask = ::umask(0);
776 (void)::umask(Mask);
777 return Mask;
778}
779
780std::error_code setPermissions(const Twine &Path, perms Permissions) {
781 SmallString<128> PathStorage;
782 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
783
784 if (::chmod(P.begin(), Permissions))
785 return errnoAsErrorCode();
786 return std::error_code();
787}
788
789std::error_code setPermissions(int FD, perms Permissions) {
790 if (::fchmod(FD, Permissions))
791 return errnoAsErrorCode();
792 return std::error_code();
793}
794
795std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
796 TimePoint<> ModificationTime) {
797#if defined(HAVE_FUTIMENS)
798 timespec Times[2];
799 Times[0] = sys::toTimeSpec(AccessTime);
800 Times[1] = sys::toTimeSpec(ModificationTime);
801 if (::futimens(FD, Times))
802 return errnoAsErrorCode();
803 return std::error_code();
804#elif defined(HAVE_FUTIMES)
805 timeval Times[2];
806 Times[0] = sys::toTimeVal(
807 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
808 Times[1] =
809 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
810 ModificationTime));
811 if (::futimes(FD, Times))
812 return errnoAsErrorCode();
813 return std::error_code();
814#elif defined(__MVS__)
815 attrib_t Attr;
816 memset(&Attr, 0, sizeof(Attr));
817 Attr.att_atimechg = 1;
818 Attr.att_atime = sys::toTimeT(AccessTime);
819 Attr.att_mtimechg = 1;
820 Attr.att_mtime = sys::toTimeT(ModificationTime);
821 if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
822 return errnoAsErrorCode();
823 return std::error_code();
824#else
825#warning Missing futimes() and futimens()
827#endif
828}
829
830std::error_code mapped_file_region::init(int FD, uint64_t Offset,
831 mapmode Mode) {
832 assert(Size != 0);
833
834 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
835 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
836#if defined(MAP_NORESERVE)
837 flags |= MAP_NORESERVE;
838#endif
839#if defined(__APPLE__)
840 //----------------------------------------------------------------------
841 // Newer versions of MacOSX have a flag that will allow us to read from
842 // binaries whose code signature is invalid without crashing by using
843 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
844 // is mapped we can avoid crashing and return zeroes to any pages we try
845 // to read if the media becomes unavailable by using the
846 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
847 // with PROT_READ, so take care not to specify them otherwise.
848 //----------------------------------------------------------------------
849 if (Mode == readonly) {
850#if defined(MAP_RESILIENT_CODESIGN)
851 flags |= MAP_RESILIENT_CODESIGN;
852#endif
853#if defined(MAP_RESILIENT_MEDIA)
854 flags |= MAP_RESILIENT_MEDIA;
855#endif
856 }
857#endif // #if defined (__APPLE__)
858
859 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
860 if (Mapping == MAP_FAILED)
861 return errnoAsErrorCode();
862 return std::error_code();
863}
864
865mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
866 uint64_t offset, std::error_code &ec)
867 : Size(length), Mode(mode) {
868 (void)Mode;
869 ec = init(fd, offset, mode);
870 if (ec)
871 copyFrom(mapped_file_region());
872}
873
874void mapped_file_region::unmapImpl() {
875 if (Mapping)
876 ::munmap(Mapping, Size);
877}
878
879std::error_code mapped_file_region::sync() const {
880 if (int Res = ::msync(Mapping, Size, MS_SYNC))
881 return std::error_code(Res, std::generic_category());
882 return std::error_code();
883}
884
885void mapped_file_region::dontNeedImpl() {
886 assert(Mode == mapped_file_region::readonly);
887 if (!Mapping)
888 return;
889#if defined(__MVS__) || defined(_AIX)
890 // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
891#elif defined(POSIX_MADV_DONTNEED)
892 ::posix_madvise(Mapping, Size, POSIX_MADV_DONTNEED);
893#else
894 ::madvise(Mapping, Size, MADV_DONTNEED);
895#endif
896}
897
898int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }
899
900std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
901 StringRef path,
902 bool follow_symlinks) {
903 SmallString<128> path_null(path);
904 DIR *directory = ::opendir(path_null.c_str());
905 if (!directory)
906 return errnoAsErrorCode();
907
908 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
909 // Add something for replace_filename to replace.
910 path::append(path_null, ".");
911 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
913}
914
915std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
916 if (it.IterationHandle)
917 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
918 it.IterationHandle = 0;
919 it.CurrentEntry = directory_entry();
920 return std::error_code();
921}
922
923static file_type direntType(dirent *Entry) {
924 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
925 // The DTTOIF macro lets us reuse our status -> type conversion.
926 // Note that while glibc provides a macro to see if this is supported,
927 // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
928 // d_type-to-mode_t conversion macro instead.
929#if defined(DTTOIF)
930 return typeForMode(DTTOIF(Entry->d_type));
931#else
932 // Other platforms such as Solaris require a stat() to get the type.
933 return file_type::type_unknown;
934#endif
935}
936
937std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
938 errno = 0;
939 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
940 if (CurDir == nullptr && errno != 0) {
941 return errnoAsErrorCode();
942 } else if (CurDir != nullptr) {
943 StringRef Name(CurDir->d_name);
944 if ((Name.size() == 1 && Name[0] == '.') ||
945 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
947 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
948 } else {
950 }
951
952 return std::error_code();
953}
954
955ErrorOr<basic_file_status> directory_entry::status() const {
956 file_status s;
957 if (auto EC = fs::status(Path, s, FollowSymlinks))
958 return EC;
959 return s;
960}
961
962//
963// FreeBSD optionally provides /proc/self/fd, but it is incompatible with
964// Linux. The thing to use is realpath.
965//
966#if !defined(__FreeBSD__) && !defined(__OpenBSD__)
967#define TRY_PROC_SELF_FD
968#endif
969
970#if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
971static bool hasProcSelfFD() {
972 // If we have a /proc filesystem mounted, we can quickly establish the
973 // real name of the file with readlink
974 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
975 return Result;
976}
977#endif
978
979static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
980 FileAccess Access) {
981 int Result = 0;
982 if (Access == FA_Read)
983 Result |= O_RDONLY;
984 else if (Access == FA_Write)
985 Result |= O_WRONLY;
986 else if (Access == (FA_Read | FA_Write))
987 Result |= O_RDWR;
988
989 // This is for compatibility with old code that assumed OF_Append implied
990 // would open an existing file. See Windows/Path.inc for a longer comment.
991 if (Flags & OF_Append)
992 Disp = CD_OpenAlways;
993
994 if (Disp == CD_CreateNew) {
995 Result |= O_CREAT; // Create if it doesn't exist.
996 Result |= O_EXCL; // Fail if it does.
997 } else if (Disp == CD_CreateAlways) {
998 Result |= O_CREAT; // Create if it doesn't exist.
999 Result |= O_TRUNC; // Truncate if it does.
1000 } else if (Disp == CD_OpenAlways) {
1001 Result |= O_CREAT; // Create if it doesn't exist.
1002 } else if (Disp == CD_OpenExisting) {
1003 // Nothing special, just don't add O_CREAT and we get these semantics.
1004 }
1005
1006// Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1007// calling write(). Instead we need to use lseek() to set offset to EOF after
1008// open().
1009#ifndef __MVS__
1010 if (Flags & OF_Append)
1011 Result |= O_APPEND;
1012#endif
1013
1014#ifdef O_CLOEXEC
1015 if (!(Flags & OF_ChildInherit))
1016 Result |= O_CLOEXEC;
1017#endif
1018
1019 return Result;
1020}
1021
1022std::error_code openFile(const Twine &Name, int &ResultFD,
1023 CreationDisposition Disp, FileAccess Access,
1024 OpenFlags Flags, unsigned Mode) {
1025 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
1026
1027 SmallString<128> Storage;
1028 StringRef P = Name.toNullTerminatedStringRef(Storage);
1029 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
1030 // when open is overloaded, such as in Bionic.
1031 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
1032 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
1033 return errnoAsErrorCode();
1034#ifndef O_CLOEXEC
1035 if (!(Flags & OF_ChildInherit)) {
1036 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1037 (void)r;
1038 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
1039 }
1040#endif
1041
1042#ifdef __MVS__
1043 /* Reason about auto-conversion and file tags. Setting the file tag only
1044 * applies if file is opened in write mode:
1045 *
1046 * Text file:
1047 * File exists File created
1048 * CD_CreateNew n/a conv: on
1049 * tag: set 1047
1050 * CD_CreateAlways conv: auto conv: on
1051 * tag: auto 1047 tag: set 1047
1052 * CD_OpenAlways conv: auto conv: on
1053 * tag: auto 1047 tag: set 1047
1054 * CD_OpenExisting conv: auto n/a
1055 * tag: unchanged
1056 *
1057 * Binary file:
1058 * File exists File created
1059 * CD_CreateNew n/a conv: off
1060 * tag: set binary
1061 * CD_CreateAlways conv: off conv: off
1062 * tag: auto binary tag: set binary
1063 * CD_OpenAlways conv: off conv: off
1064 * tag: auto binary tag: set binary
1065 * CD_OpenExisting conv: off n/a
1066 * tag: unchanged
1067 *
1068 * Actions:
1069 * conv: off -> auto-conversion is turned off
1070 * conv: on -> auto-conversion is turned on
1071 * conv: auto -> auto-conversion is turned on if the file is untagged
1072 * tag: set 1047 -> set the file tag to text encoded in 1047
1073 * tag: set binary -> set the file tag to binary
1074 * tag: auto 1047 -> set file tag to 1047 if not set
1075 * tag: auto binary -> set file tag to binary if not set
1076 * tag: unchanged -> do not care about the file tag
1077 *
1078 * It is not possible to distinguish between the cases "file exists" and
1079 * "file created". In the latter case, the file tag is not set and the file
1080 * size is zero. The decision table boils down to:
1081 *
1082 * the file tag is set if
1083 * - the file is opened for writing
1084 * - the create disposition is not equal to CD_OpenExisting
1085 * - the file tag is not set
1086 * - the file size is zero
1087 *
1088 * This only applies if the file is a regular file. E.g. enabling
1089 * auto-conversion for reading from /dev/null results in error EINVAL when
1090 * calling read().
1091 *
1092 * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1093 * calling write(). Instead we need to use lseek() to set offset to EOF after
1094 * open().
1095 */
1096 if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1097 return errnoAsErrorCode();
1098 struct stat Stat;
1099 if (fstat(ResultFD, &Stat) == -1)
1100 return errnoAsErrorCode();
1101 if (S_ISREG(Stat.st_mode)) {
1102 bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
1103 !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1104 Stat.st_size == 0;
1105 if (Flags & OF_Text) {
1106 if (auto EC = llvm::enableAutoConversion(ResultFD))
1107 return EC;
1108 if (DoSetTag) {
1109 if (auto EC = llvm::setzOSFileTag(ResultFD, CCSID_IBM_1047, true))
1110 return EC;
1111 }
1112 } else {
1113 if (auto EC = llvm::disableAutoConversion(ResultFD))
1114 return EC;
1115 if (DoSetTag) {
1116 if (auto EC = llvm::setzOSFileTag(ResultFD, FT_BINARY, false))
1117 return EC;
1118 }
1119 }
1120 }
1121#endif
1122
1123 return std::error_code();
1124}
1125
1126Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
1127 FileAccess Access, OpenFlags Flags,
1128 unsigned Mode) {
1129
1130 int FD;
1131 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
1132 if (EC)
1133 return errorCodeToError(EC);
1134 return FD;
1135}
1136
1137std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1138 OpenFlags Flags,
1139 SmallVectorImpl<char> *RealPath) {
1140 std::error_code EC =
1141 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
1142 if (EC)
1143 return EC;
1144
1145 // Attempt to get the real name of the file, if the user asked
1146 if (!RealPath)
1147 return std::error_code();
1148 RealPath->clear();
1149#if defined(F_GETPATH)
1150 // When F_GETPATH is availble, it is the quickest way to get
1151 // the real path name.
1152 char Buffer[PATH_MAX];
1153 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1154 RealPath->append(Buffer, Buffer + strlen(Buffer));
1155#else
1156 char Buffer[PATH_MAX];
1157#if defined(TRY_PROC_SELF_FD)
1158 if (hasProcSelfFD()) {
1159 char ProcPath[64];
1160 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
1161 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
1162 if (CharCount > 0)
1163 RealPath->append(Buffer, Buffer + CharCount);
1164 } else {
1165#endif
1166 SmallString<128> Storage;
1167 StringRef P = Name.toNullTerminatedStringRef(Storage);
1168
1169 // Use ::realpath to get the real path name
1170 if (::realpath(P.begin(), Buffer) != nullptr)
1171 RealPath->append(Buffer, Buffer + strlen(Buffer));
1172#if defined(TRY_PROC_SELF_FD)
1173 }
1174#endif
1175#endif
1176 return std::error_code();
1177}
1178
1179Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1180 SmallVectorImpl<char> *RealPath) {
1181 file_t ResultFD;
1182 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
1183 if (EC)
1184 return errorCodeToError(EC);
1185 return ResultFD;
1186}
1187
1188file_t getStdinHandle() { return 0; }
1189file_t getStdoutHandle() { return 1; }
1190file_t getStderrHandle() { return 2; }
1191
1193#if defined(__APPLE__)
1194 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1195#else
1196 size_t Size = Buf.size();
1197#endif
1198 ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1199 if (NumRead == -1)
1201// The underlying operation on these platforms allow opening directories
1202// for reading in more cases than other platforms.
1203#if defined(__MVS__) || defined(_AIX)
1204 struct stat Status;
1205 if (fstat(FD, &Status) == -1)
1207 if (S_ISDIR(Status.st_mode))
1208 return errorCodeToError(make_error_code(errc::is_a_directory));
1209#endif
1210 return NumRead;
1211}
1212
1214 uint64_t Offset) {
1215#if defined(__APPLE__)
1216 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1217#else
1218 size_t Size = Buf.size();
1219#endif
1220#ifdef HAVE_PREAD
1221 ssize_t NumRead =
1222 sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
1223#else
1224 if (lseek(FD, Offset, SEEK_SET) == -1)
1226 ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1227#endif
1228 if (NumRead == -1)
1230 return NumRead;
1231}
1232
1233std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,
1234 LockKind Kind) {
1235 auto Start = std::chrono::steady_clock::now();
1236 auto End = Start + Timeout;
1237 do {
1238 struct flock Lock;
1239 memset(&Lock, 0, sizeof(Lock));
1240 switch (Kind) {
1241 case LockKind::Exclusive:
1242 Lock.l_type = F_WRLCK;
1243 break;
1244 case LockKind::Shared:
1245 Lock.l_type = F_RDLCK;
1246 break;
1247 }
1248 Lock.l_whence = SEEK_SET;
1249 Lock.l_start = 0;
1250 Lock.l_len = 0;
1251 if (::fcntl(FD, F_SETLK, &Lock) != -1)
1252 return std::error_code();
1253 int Error = errno;
1254 if (Error != EACCES && Error != EAGAIN)
1255 return std::error_code(Error, std::generic_category());
1256 if (Timeout.count() == 0)
1257 break;
1258 usleep(1000);
1259 } while (std::chrono::steady_clock::now() < End);
1260 return make_error_code(errc::no_lock_available);
1261}
1262
1263std::error_code lockFile(int FD, LockKind Kind) {
1264 struct flock Lock;
1265 memset(&Lock, 0, sizeof(Lock));
1266 switch (Kind) {
1267 case LockKind::Exclusive:
1268 Lock.l_type = F_WRLCK;
1269 break;
1270 case LockKind::Shared:
1271 Lock.l_type = F_RDLCK;
1272 break;
1273 }
1274 Lock.l_whence = SEEK_SET;
1275 Lock.l_start = 0;
1276 Lock.l_len = 0;
1277 if (::fcntl(FD, F_SETLKW, &Lock) != -1)
1278 return std::error_code();
1279 return errnoAsErrorCode();
1280}
1281
1282std::error_code unlockFile(int FD) {
1283 struct flock Lock;
1284 Lock.l_type = F_UNLCK;
1285 Lock.l_whence = SEEK_SET;
1286 Lock.l_start = 0;
1287 Lock.l_len = 0;
1288 if (::fcntl(FD, F_SETLK, &Lock) != -1)
1289 return std::error_code();
1290 return errnoAsErrorCode();
1291}
1292
1293std::error_code closeFile(file_t &F) {
1294 file_t TmpF = F;
1295 F = kInvalidFile;
1296 return Process::SafelyCloseFileDescriptor(TmpF);
1297}
1298
1299template <typename T>
1300static std::error_code remove_directories_impl(const T &Entry,
1301 bool IgnoreErrors) {
1302 std::error_code EC;
1303 directory_iterator Begin(Entry, EC, false);
1304 directory_iterator End;
1305 while (Begin != End) {
1306 auto &Item = *Begin;
1307 ErrorOr<basic_file_status> st = Item.status();
1308 if (st) {
1309 if (is_directory(*st)) {
1310 EC = remove_directories_impl(Item, IgnoreErrors);
1311 if (EC && !IgnoreErrors)
1312 return EC;
1313 }
1314
1315 EC = fs::remove(Item.path(), true);
1316 if (EC && !IgnoreErrors)
1317 return EC;
1318 } else if (!IgnoreErrors) {
1319 return st.getError();
1320 }
1321
1322 Begin.increment(EC);
1323 if (EC && !IgnoreErrors)
1324 return EC;
1325 }
1326 return std::error_code();
1327}
1328
1329std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1330 auto EC = remove_directories_impl(path, IgnoreErrors);
1331 if (EC && !IgnoreErrors)
1332 return EC;
1333 EC = fs::remove(path, true);
1334 if (EC && !IgnoreErrors)
1335 return EC;
1336 return std::error_code();
1337}
1338
1339std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1340 bool expand_tilde) {
1341 dest.clear();
1342 if (path.isTriviallyEmpty())
1343 return std::error_code();
1344
1345 if (expand_tilde) {
1346 SmallString<128> Storage;
1347 path.toVector(Storage);
1348 expandTildeExpr(Storage);
1349 return real_path(Storage, dest, false);
1350 }
1351
1352 SmallString<128> Storage;
1353 StringRef P = path.toNullTerminatedStringRef(Storage);
1354 char Buffer[PATH_MAX];
1355 if (::realpath(P.begin(), Buffer) == nullptr)
1356 return errnoAsErrorCode();
1357 dest.append(Buffer, Buffer + strlen(Buffer));
1358 return std::error_code();
1359}
1360
1361std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
1362 auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
1363 // Retry if fchown call fails due to interruption.
1364 if ((sys::RetryAfterSignal(-1, FChown)) < 0)
1365 return errnoAsErrorCode();
1366 return std::error_code();
1367}
1368
1369} // end namespace fs
1370
1371namespace path {
1372
1374 std::unique_ptr<char[]> Buf;
1375 char *RequestedDir = getenv("HOME");
1376 if (!RequestedDir) {
1377 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
1378 if (BufSize <= 0)
1379 BufSize = 16384;
1380 Buf = std::make_unique<char[]>(BufSize);
1381 struct passwd Pwd;
1382 struct passwd *pw = nullptr;
1383 getpwuid_r(getuid(), &Pwd, Buf.get(), BufSize, &pw);
1384 if (pw && pw->pw_dir)
1385 RequestedDir = pw->pw_dir;
1386 }
1387 if (!RequestedDir)
1388 return false;
1389
1390 result.clear();
1391 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1392 return true;
1393}
1394
1395static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1396#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1397 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1398 // macros defined in <unistd.h> on darwin >= 9
1399 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;
1400 size_t ConfLen = confstr(ConfName, nullptr, 0);
1401 if (ConfLen > 0) {
1402 do {
1403 Result.resize(ConfLen);
1404 ConfLen = confstr(ConfName, Result.data(), Result.size());
1405 } while (ConfLen > 0 && ConfLen != Result.size());
1406
1407 if (ConfLen > 0) {
1408 assert(Result.back() == 0);
1409 Result.pop_back();
1410 return true;
1411 }
1412
1413 Result.clear();
1414 }
1415#endif
1416 return false;
1417}
1418
1420#ifdef __APPLE__
1421 // Mac: ~/Library/Preferences/
1422 if (home_directory(result)) {
1423 append(result, "Library", "Preferences");
1424 return true;
1425 }
1426#else
1427 // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
1428 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1429 if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
1430 result.clear();
1431 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1432 return true;
1433 }
1434#endif
1435 // Fallback: ~/.config
1436 if (!home_directory(result)) {
1437 return false;
1438 }
1439 append(result, ".config");
1440 return true;
1441}
1442
1444#ifdef __APPLE__
1445 if (getDarwinConfDir(false /*tempDir*/, result)) {
1446 return true;
1447 }
1448#else
1449 // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
1450 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1451 if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
1452 result.clear();
1453 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1454 return true;
1455 }
1456#endif
1457 if (!home_directory(result)) {
1458 return false;
1459 }
1460 append(result, ".cache");
1461 return true;
1462}
1463
1464static const char *getEnvTempDir() {
1465 // Check whether the temporary directory is specified by an environment
1466 // variable.
1467 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1468 for (const char *Env : EnvironmentVariables) {
1469 if (const char *Dir = std::getenv(Env))
1470 return Dir;
1471 }
1472
1473 return nullptr;
1474}
1475
1476static const char *getDefaultTempDir(bool ErasedOnReboot) {
1477#ifdef P_tmpdir
1478 if ((bool)P_tmpdir)
1479 return P_tmpdir;
1480#endif
1481
1482 if (ErasedOnReboot)
1483 return "/tmp";
1484 return "/var/tmp";
1485}
1486
1487void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1488 Result.clear();
1489
1490 if (ErasedOnReboot) {
1491 // There is no env variable for the cache directory.
1492 if (const char *RequestedDir = getEnvTempDir()) {
1493 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1494 return;
1495 }
1496 }
1497
1498 if (getDarwinConfDir(ErasedOnReboot, Result))
1499 return;
1500
1501 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1502 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1503}
1504
1505} // end namespace path
1506
1507namespace fs {
1508
1509#ifdef __APPLE__
1510/// This implementation tries to perform an APFS CoW clone of the file,
1511/// which can be much faster and uses less space.
1512/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1513/// file descriptor variant of this function still uses the default
1514/// implementation.
1515std::error_code copy_file(const Twine &From, const Twine &To) {
1516 std::string FromS = From.str();
1517 std::string ToS = To.str();
1518#if __has_builtin(__builtin_available)
1519 if (__builtin_available(macos 10.12, *)) {
1520 // Optimistically try to use clonefile() and handle errors, rather than
1521 // calling stat() to see if it'll work.
1522 //
1523 // Note: It's okay if From is a symlink. In contrast to the behaviour of
1524 // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
1525 // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
1526 if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
1527 return std::error_code();
1528
1529 auto Errno = errno;
1530 switch (Errno) {
1531 case EEXIST: // To already exists.
1532 case ENOTSUP: // Device does not support cloning.
1533 case EXDEV: // From and To are on different devices.
1534 break;
1535 default:
1536 // Anything else will also break copyfile().
1537 return std::error_code(Errno, std::generic_category());
1538 }
1539
1540 // TODO: For EEXIST, profile calling fs::generateUniqueName() and
1541 // clonefile() in a retry loop (then rename() on success) before falling
1542 // back to copyfile(). Depending on the size of the file this could be
1543 // cheaper.
1544 }
1545#endif
1546 if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
1547 return std::error_code();
1548 return errnoAsErrorCode();
1549}
1550#endif // __APPLE__
1551
1552} // end namespace fs
1553
1554} // end namespace sys
1555} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define CCSID_IBM_1047
Definition: AutoConvert.h:25
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
DXIL Resource Access
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
uint64_t Offset
Definition: ELF_riscv.cpp:478
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Definition: LibDriver.cpp:100
#define F(x, y, z)
Definition: MD5.cpp:55
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:915
#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
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
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
Tagged union holding either a T or a Error.
Definition: Error.h:485
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:303
T * data() const
Definition: ArrayRef.h:345
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
size_t capacity() const
Definition: SmallVector.h:80
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
Definition: SmallVector.h:642
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:684
void truncate(size_type N)
Like resize, but requires that N is less than size().
Definition: SmallVector.h:645
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:287
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:233
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:581
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
iterator begin() const
Definition: StringRef.h:120
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
StringRef take_until(function_ref< bool(char)> F) const
Return the longest prefix of 'this' such that no character in the prefix satisfies the given predicat...
Definition: StringRef.h:613
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:431
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition: Twine.cpp:32
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.
Definition: FileSystem.h:1290
@ readwrite
May access map via data and modify it. Written to path.
Definition: FileSystem.h:1291
#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.
Definition: BitmaskEnum.h:126
@ Entry
Definition: COFF.h:862
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
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:749
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 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
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.
Definition: AddressRanges.h:18
@ 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:1702
std::error_code make_error_code(BitcodeError E)
@ no_such_file_or_directory
@ operation_not_permitted
@ function_not_supported
@ 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