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