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