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