Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:30

0001 //===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file declares the llvm::sys::fs namespace. It is designed after
0010 // TR2/boost filesystem (v3), but modified to remove exception handling and the
0011 // path class.
0012 //
0013 // All functions return an error_code and their actual work via the last out
0014 // argument. The out argument is defined if and only if errc::success is
0015 // returned. A function may return any error code in the generic or system
0016 // category. However, they shall be equivalent to any error conditions listed
0017 // in each functions respective documentation if the condition applies. [ note:
0018 // this does not guarantee that error_code will be in the set of explicitly
0019 // listed codes, but it does guarantee that if any of the explicitly listed
0020 // errors occur, the correct error_code will be used ]. All functions may
0021 // return errc::not_enough_memory if there is not enough memory to complete the
0022 // operation.
0023 //
0024 //===----------------------------------------------------------------------===//
0025 
0026 #ifndef LLVM_SUPPORT_FILESYSTEM_H
0027 #define LLVM_SUPPORT_FILESYSTEM_H
0028 
0029 #include "llvm/ADT/SmallString.h"
0030 #include "llvm/ADT/StringRef.h"
0031 #include "llvm/ADT/Twine.h"
0032 #include "llvm/Config/llvm-config.h"
0033 #include "llvm/Support/Chrono.h"
0034 #include "llvm/Support/Error.h"
0035 #include "llvm/Support/ErrorHandling.h"
0036 #include "llvm/Support/ErrorOr.h"
0037 #include "llvm/Support/FileSystem/UniqueID.h"
0038 #include "llvm/Support/MD5.h"
0039 #include <cassert>
0040 #include <cstdint>
0041 #include <ctime>
0042 #include <memory>
0043 #include <string>
0044 #include <system_error>
0045 #include <vector>
0046 
0047 namespace llvm {
0048 namespace sys {
0049 namespace fs {
0050 
0051 #if defined(_WIN32)
0052 // A Win32 HANDLE is a typedef of void*
0053 using file_t = void *;
0054 #else
0055 using file_t = int;
0056 #endif
0057 
0058 extern const file_t kInvalidFile;
0059 
0060 /// An enumeration for the file system's view of the type.
0061 enum class file_type {
0062   status_error,
0063   file_not_found,
0064   regular_file,
0065   directory_file,
0066   symlink_file,
0067   block_file,
0068   character_file,
0069   fifo_file,
0070   socket_file,
0071   type_unknown
0072 };
0073 
0074 /// space_info - Self explanatory.
0075 struct space_info {
0076   uint64_t capacity;
0077   uint64_t free;
0078   uint64_t available;
0079 };
0080 
0081 enum perms {
0082   no_perms = 0,
0083   owner_read = 0400,
0084   owner_write = 0200,
0085   owner_exe = 0100,
0086   owner_all = owner_read | owner_write | owner_exe,
0087   group_read = 040,
0088   group_write = 020,
0089   group_exe = 010,
0090   group_all = group_read | group_write | group_exe,
0091   others_read = 04,
0092   others_write = 02,
0093   others_exe = 01,
0094   others_all = others_read | others_write | others_exe,
0095   all_read = owner_read | group_read | others_read,
0096   all_write = owner_write | group_write | others_write,
0097   all_exe = owner_exe | group_exe | others_exe,
0098   all_all = owner_all | group_all | others_all,
0099   set_uid_on_exe = 04000,
0100   set_gid_on_exe = 02000,
0101   sticky_bit = 01000,
0102   all_perms = all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit,
0103   perms_not_known = 0xFFFF
0104 };
0105 
0106 // Helper functions so that you can use & and | to manipulate perms bits:
0107 inline perms operator|(perms l, perms r) {
0108   return static_cast<perms>(static_cast<unsigned short>(l) |
0109                             static_cast<unsigned short>(r));
0110 }
0111 inline perms operator&(perms l, perms r) {
0112   return static_cast<perms>(static_cast<unsigned short>(l) &
0113                             static_cast<unsigned short>(r));
0114 }
0115 inline perms &operator|=(perms &l, perms r) {
0116   l = l | r;
0117   return l;
0118 }
0119 inline perms &operator&=(perms &l, perms r) {
0120   l = l & r;
0121   return l;
0122 }
0123 inline perms operator~(perms x) {
0124   // Avoid UB by explicitly truncating the (unsigned) ~ result.
0125   return static_cast<perms>(
0126       static_cast<unsigned short>(~static_cast<unsigned short>(x)));
0127 }
0128 
0129 /// Represents the result of a call to directory_iterator::status(). This is a
0130 /// subset of the information returned by a regular sys::fs::status() call, and
0131 /// represents the information provided by Windows FileFirstFile/FindNextFile.
0132 class basic_file_status {
0133 protected:
0134   #if defined(LLVM_ON_UNIX)
0135   time_t fs_st_atime = 0;
0136   time_t fs_st_mtime = 0;
0137   uint32_t fs_st_atime_nsec = 0;
0138   uint32_t fs_st_mtime_nsec = 0;
0139   uid_t fs_st_uid = 0;
0140   gid_t fs_st_gid = 0;
0141   off_t fs_st_size = 0;
0142   #elif defined (_WIN32)
0143   uint32_t LastAccessedTimeHigh = 0;
0144   uint32_t LastAccessedTimeLow = 0;
0145   uint32_t LastWriteTimeHigh = 0;
0146   uint32_t LastWriteTimeLow = 0;
0147   uint32_t FileSizeHigh = 0;
0148   uint32_t FileSizeLow = 0;
0149   #endif
0150   file_type Type = file_type::status_error;
0151   perms Perms = perms_not_known;
0152 
0153 public:
0154   basic_file_status() = default;
0155 
0156   explicit basic_file_status(file_type Type) : Type(Type) {}
0157 
0158   #if defined(LLVM_ON_UNIX)
0159   basic_file_status(file_type Type, perms Perms, time_t ATime,
0160                     uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec,
0161                     uid_t UID, gid_t GID, off_t Size)
0162       : fs_st_atime(ATime), fs_st_mtime(MTime),
0163         fs_st_atime_nsec(ATimeNSec), fs_st_mtime_nsec(MTimeNSec),
0164         fs_st_uid(UID), fs_st_gid(GID),
0165         fs_st_size(Size), Type(Type), Perms(Perms) {}
0166 #elif defined(_WIN32)
0167   basic_file_status(file_type Type, perms Perms, uint32_t LastAccessTimeHigh,
0168                     uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh,
0169                     uint32_t LastWriteTimeLow, uint32_t FileSizeHigh,
0170                     uint32_t FileSizeLow)
0171       : LastAccessedTimeHigh(LastAccessTimeHigh),
0172         LastAccessedTimeLow(LastAccessTimeLow),
0173         LastWriteTimeHigh(LastWriteTimeHigh),
0174         LastWriteTimeLow(LastWriteTimeLow), FileSizeHigh(FileSizeHigh),
0175         FileSizeLow(FileSizeLow), Type(Type), Perms(Perms) {}
0176   #endif
0177 
0178   // getters
0179   file_type type() const { return Type; }
0180   perms permissions() const { return Perms; }
0181 
0182   /// The file access time as reported from the underlying file system.
0183   ///
0184   /// Also see comments on \c getLastModificationTime() related to the precision
0185   /// of the returned value.
0186   TimePoint<> getLastAccessedTime() const;
0187 
0188   /// The file modification time as reported from the underlying file system.
0189   ///
0190   /// The returned value allows for nanosecond precision but the actual
0191   /// resolution is an implementation detail of the underlying file system.
0192   /// There is no guarantee for what kind of resolution you can expect, the
0193   /// resolution can differ across platforms and even across mountpoints on the
0194   /// same machine.
0195   TimePoint<> getLastModificationTime() const;
0196 
0197   #if defined(LLVM_ON_UNIX)
0198   uint32_t getUser() const { return fs_st_uid; }
0199   uint32_t getGroup() const { return fs_st_gid; }
0200   uint64_t getSize() const { return fs_st_size; }
0201   #elif defined (_WIN32)
0202   uint32_t getUser() const {
0203     return 9999; // Not applicable to Windows, so...
0204   }
0205 
0206   uint32_t getGroup() const {
0207     return 9999; // Not applicable to Windows, so...
0208   }
0209 
0210   uint64_t getSize() const {
0211     return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
0212   }
0213   #endif
0214 
0215   // setters
0216   void type(file_type v) { Type = v; }
0217   void permissions(perms p) { Perms = p; }
0218 };
0219 
0220 /// Represents the result of a call to sys::fs::status().
0221 class file_status : public basic_file_status {
0222   friend bool equivalent(file_status A, file_status B);
0223 
0224   #if defined(LLVM_ON_UNIX)
0225   dev_t fs_st_dev = 0;
0226   nlink_t fs_st_nlinks = 0;
0227   ino_t fs_st_ino = 0;
0228   #elif defined (_WIN32)
0229   uint32_t NumLinks = 0;
0230   uint32_t VolumeSerialNumber = 0;
0231   uint64_t PathHash = 0;
0232   #endif
0233 
0234 public:
0235   file_status() = default;
0236 
0237   explicit file_status(file_type Type) : basic_file_status(Type) {}
0238 
0239   #if defined(LLVM_ON_UNIX)
0240   file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino,
0241               time_t ATime, uint32_t ATimeNSec,
0242               time_t MTime, uint32_t MTimeNSec,
0243               uid_t UID, gid_t GID, off_t Size)
0244       : basic_file_status(Type, Perms, ATime, ATimeNSec, MTime, MTimeNSec,
0245                           UID, GID, Size),
0246         fs_st_dev(Dev), fs_st_nlinks(Links), fs_st_ino(Ino) {}
0247   #elif defined(_WIN32)
0248   file_status(file_type Type, perms Perms, uint32_t LinkCount,
0249               uint32_t LastAccessTimeHigh, uint32_t LastAccessTimeLow,
0250               uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow,
0251               uint32_t VolumeSerialNumber, uint32_t FileSizeHigh,
0252               uint32_t FileSizeLow, uint64_t PathHash)
0253       : basic_file_status(Type, Perms, LastAccessTimeHigh, LastAccessTimeLow,
0254                           LastWriteTimeHigh, LastWriteTimeLow, FileSizeHigh,
0255                           FileSizeLow),
0256         NumLinks(LinkCount), VolumeSerialNumber(VolumeSerialNumber),
0257         PathHash(PathHash) {}
0258   #endif
0259 
0260   UniqueID getUniqueID() const;
0261   uint32_t getLinkCount() const;
0262 };
0263 
0264 /// @}
0265 /// @name Physical Operators
0266 /// @{
0267 
0268 /// Make \a path an absolute path.
0269 ///
0270 /// Makes \a path absolute using the \a current_directory if it is not already.
0271 /// An empty \a path will result in the \a current_directory.
0272 ///
0273 /// /absolute/path   => /absolute/path
0274 /// relative/../path => <current-directory>/relative/../path
0275 ///
0276 /// @param path A path that is modified to be an absolute path.
0277 void make_absolute(const Twine &current_directory, SmallVectorImpl<char> &path);
0278 
0279 /// Make \a path an absolute path.
0280 ///
0281 /// Makes \a path absolute using the current directory if it is not already. An
0282 /// empty \a path will result in the current directory.
0283 ///
0284 /// /absolute/path   => /absolute/path
0285 /// relative/../path => <current-directory>/relative/../path
0286 ///
0287 /// @param path A path that is modified to be an absolute path.
0288 /// @returns errc::success if \a path has been made absolute, otherwise a
0289 ///          platform-specific error_code.
0290 std::error_code make_absolute(SmallVectorImpl<char> &path);
0291 
0292 /// Create all the non-existent directories in path.
0293 ///
0294 /// @param path Directories to create.
0295 /// @returns errc::success if is_directory(path), otherwise a platform
0296 ///          specific error_code. If IgnoreExisting is false, also returns
0297 ///          error if the directory already existed.
0298 std::error_code create_directories(const Twine &path,
0299                                    bool IgnoreExisting = true,
0300                                    perms Perms = owner_all | group_all);
0301 
0302 /// Create the directory in path.
0303 ///
0304 /// @param path Directory to create.
0305 /// @returns errc::success if is_directory(path), otherwise a platform
0306 ///          specific error_code. If IgnoreExisting is false, also returns
0307 ///          error if the directory already existed.
0308 std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
0309                                  perms Perms = owner_all | group_all);
0310 
0311 /// Create a link from \a from to \a to.
0312 ///
0313 /// The link may be a soft or a hard link, depending on the platform. The caller
0314 /// may not assume which one. Currently on windows it creates a hard link since
0315 /// soft links require extra privileges. On unix, it creates a soft link since
0316 /// hard links don't work on SMB file systems.
0317 ///
0318 /// @param to The path to hard link to.
0319 /// @param from The path to hard link from. This is created.
0320 /// @returns errc::success if the link was created, otherwise a platform
0321 /// specific error_code.
0322 std::error_code create_link(const Twine &to, const Twine &from);
0323 
0324 /// Create a hard link from \a from to \a to, or return an error.
0325 ///
0326 /// @param to The path to hard link to.
0327 /// @param from The path to hard link from. This is created.
0328 /// @returns errc::success if the link was created, otherwise a platform
0329 /// specific error_code.
0330 std::error_code create_hard_link(const Twine &to, const Twine &from);
0331 
0332 /// Collapse all . and .. patterns, resolve all symlinks, and optionally
0333 ///        expand ~ expressions to the user's home directory.
0334 ///
0335 /// @param path The path to resolve.
0336 /// @param output The location to store the resolved path.
0337 /// @param expand_tilde If true, resolves ~ expressions to the user's home
0338 ///                     directory.
0339 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
0340                           bool expand_tilde = false);
0341 
0342 /// Expands ~ expressions to the user's home directory. On Unix ~user
0343 /// directories are resolved as well.
0344 ///
0345 /// @param path The path to resolve.
0346 void expand_tilde(const Twine &path, SmallVectorImpl<char> &output);
0347 
0348 /// Get the current path.
0349 ///
0350 /// @param result Holds the current path on return.
0351 /// @returns errc::success if the current path has been stored in result,
0352 ///          otherwise a platform-specific error_code.
0353 std::error_code current_path(SmallVectorImpl<char> &result);
0354 
0355 /// Set the current path.
0356 ///
0357 /// @param path The path to set.
0358 /// @returns errc::success if the current path was successfully set,
0359 ///          otherwise a platform-specific error_code.
0360 std::error_code set_current_path(const Twine &path);
0361 
0362 /// Remove path. Equivalent to POSIX remove().
0363 ///
0364 /// @param path Input path.
0365 /// @returns errc::success if path has been removed or didn't exist, otherwise a
0366 ///          platform-specific error code. If IgnoreNonExisting is false, also
0367 ///          returns error if the file didn't exist.
0368 std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
0369 
0370 /// Recursively delete a directory.
0371 ///
0372 /// @param path Input path.
0373 /// @returns errc::success if path has been removed or didn't exist, otherwise a
0374 ///          platform-specific error code.
0375 std::error_code remove_directories(const Twine &path, bool IgnoreErrors = true);
0376 
0377 /// Rename \a from to \a to.
0378 ///
0379 /// Files are renamed as if by POSIX rename(), except that on Windows there may
0380 /// be a short interval of time during which the destination file does not
0381 /// exist.
0382 ///
0383 /// @param from The path to rename from.
0384 /// @param to The path to rename to. This is created.
0385 std::error_code rename(const Twine &from, const Twine &to);
0386 
0387 /// Copy the contents of \a From to \a To.
0388 ///
0389 /// @param From The path to copy from.
0390 /// @param To The path to copy to. This is created.
0391 std::error_code copy_file(const Twine &From, const Twine &To);
0392 
0393 /// Copy the contents of \a From to \a To.
0394 ///
0395 /// @param From The path to copy from.
0396 /// @param ToFD The open file descriptor of the destination file.
0397 std::error_code copy_file(const Twine &From, int ToFD);
0398 
0399 /// Resize path to size. File is resized as if by POSIX truncate().
0400 ///
0401 /// @param FD Input file descriptor.
0402 /// @param Size Size to resize to.
0403 /// @returns errc::success if \a path has been resized to \a size, otherwise a
0404 ///          platform-specific error_code.
0405 std::error_code resize_file(int FD, uint64_t Size);
0406 
0407 /// Resize \p FD to \p Size before mapping \a mapped_file_region::readwrite. On
0408 /// non-Windows, this calls \a resize_file(). On Windows, this is a no-op,
0409 /// since the subsequent mapping (via \c CreateFileMapping) automatically
0410 /// extends the file.
0411 inline std::error_code resize_file_before_mapping_readwrite(int FD,
0412                                                             uint64_t Size) {
0413 #ifdef _WIN32
0414   (void)FD;
0415   (void)Size;
0416   return std::error_code();
0417 #else
0418   return resize_file(FD, Size);
0419 #endif
0420 }
0421 
0422 /// Compute an MD5 hash of a file's contents.
0423 ///
0424 /// @param FD Input file descriptor.
0425 /// @returns An MD5Result with the hash computed, if successful, otherwise a
0426 ///          std::error_code.
0427 ErrorOr<MD5::MD5Result> md5_contents(int FD);
0428 
0429 /// Version of compute_md5 that doesn't require an open file descriptor.
0430 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path);
0431 
0432 /// @}
0433 /// @name Physical Observers
0434 /// @{
0435 
0436 /// Does file exist?
0437 ///
0438 /// @param status A basic_file_status previously returned from stat.
0439 /// @returns True if the file represented by status exists, false if it does
0440 ///          not.
0441 bool exists(const basic_file_status &status);
0442 
0443 enum class AccessMode { Exist, Write, Execute };
0444 
0445 /// Can the file be accessed?
0446 ///
0447 /// @param Path Input path.
0448 /// @returns errc::success if the path can be accessed, otherwise a
0449 ///          platform-specific error_code.
0450 std::error_code access(const Twine &Path, AccessMode Mode);
0451 
0452 /// Does file exist?
0453 ///
0454 /// @param Path Input path.
0455 /// @returns True if it exists, false otherwise.
0456 inline bool exists(const Twine &Path) {
0457   return !access(Path, AccessMode::Exist);
0458 }
0459 
0460 /// Can we execute this file?
0461 ///
0462 /// @param Path Input path.
0463 /// @returns True if we can execute it, false otherwise.
0464 bool can_execute(const Twine &Path);
0465 
0466 /// Can we write this file?
0467 ///
0468 /// @param Path Input path.
0469 /// @returns True if we can write to it, false otherwise.
0470 inline bool can_write(const Twine &Path) {
0471   return !access(Path, AccessMode::Write);
0472 }
0473 
0474 /// Do file_status's represent the same thing?
0475 ///
0476 /// @param A Input file_status.
0477 /// @param B Input file_status.
0478 ///
0479 /// assert(status_known(A) || status_known(B));
0480 ///
0481 /// @returns True if A and B both represent the same file system entity, false
0482 ///          otherwise.
0483 bool equivalent(file_status A, file_status B);
0484 
0485 /// Do paths represent the same thing?
0486 ///
0487 /// assert(status_known(A) || status_known(B));
0488 ///
0489 /// @param A Input path A.
0490 /// @param B Input path B.
0491 /// @param result Set to true if stat(A) and stat(B) have the same device and
0492 ///               inode (or equivalent).
0493 /// @returns errc::success if result has been successfully set, otherwise a
0494 ///          platform-specific error_code.
0495 std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
0496 
0497 /// Simpler version of equivalent for clients that don't need to
0498 ///        differentiate between an error and false.
0499 inline bool equivalent(const Twine &A, const Twine &B) {
0500   bool result;
0501   return !equivalent(A, B, result) && result;
0502 }
0503 
0504 /// Is the file mounted on a local filesystem?
0505 ///
0506 /// @param path Input path.
0507 /// @param result Set to true if \a path is on fixed media such as a hard disk,
0508 ///               false if it is not.
0509 /// @returns errc::success if result has been successfully set, otherwise a
0510 ///          platform specific error_code.
0511 std::error_code is_local(const Twine &path, bool &result);
0512 
0513 /// Version of is_local accepting an open file descriptor.
0514 std::error_code is_local(int FD, bool &result);
0515 
0516 /// Simpler version of is_local for clients that don't need to
0517 ///        differentiate between an error and false.
0518 inline bool is_local(const Twine &Path) {
0519   bool Result;
0520   return !is_local(Path, Result) && Result;
0521 }
0522 
0523 /// Simpler version of is_local accepting an open file descriptor for
0524 ///        clients that don't need to differentiate between an error and false.
0525 inline bool is_local(int FD) {
0526   bool Result;
0527   return !is_local(FD, Result) && Result;
0528 }
0529 
0530 /// Does status represent a directory?
0531 ///
0532 /// @param Path The path to get the type of.
0533 /// @param Follow For symbolic links, indicates whether to return the file type
0534 ///               of the link itself, or of the target.
0535 /// @returns A value from the file_type enumeration indicating the type of file.
0536 file_type get_file_type(const Twine &Path, bool Follow = true);
0537 
0538 /// Does status represent a directory?
0539 ///
0540 /// @param status A basic_file_status previously returned from status.
0541 /// @returns status.type() == file_type::directory_file.
0542 bool is_directory(const basic_file_status &status);
0543 
0544 /// Is path a directory?
0545 ///
0546 /// @param path Input path.
0547 /// @param result Set to true if \a path is a directory (after following
0548 ///               symlinks, false if it is not. Undefined otherwise.
0549 /// @returns errc::success if result has been successfully set, otherwise a
0550 ///          platform-specific error_code.
0551 std::error_code is_directory(const Twine &path, bool &result);
0552 
0553 /// Simpler version of is_directory for clients that don't need to
0554 ///        differentiate between an error and false.
0555 inline bool is_directory(const Twine &Path) {
0556   bool Result;
0557   return !is_directory(Path, Result) && Result;
0558 }
0559 
0560 /// Does status represent a regular file?
0561 ///
0562 /// @param status A basic_file_status previously returned from status.
0563 /// @returns status_known(status) && status.type() == file_type::regular_file.
0564 bool is_regular_file(const basic_file_status &status);
0565 
0566 /// Is path a regular file?
0567 ///
0568 /// @param path Input path.
0569 /// @param result Set to true if \a path is a regular file (after following
0570 ///               symlinks), false if it is not. Undefined otherwise.
0571 /// @returns errc::success if result has been successfully set, otherwise a
0572 ///          platform-specific error_code.
0573 std::error_code is_regular_file(const Twine &path, bool &result);
0574 
0575 /// Simpler version of is_regular_file for clients that don't need to
0576 ///        differentiate between an error and false.
0577 inline bool is_regular_file(const Twine &Path) {
0578   bool Result;
0579   if (is_regular_file(Path, Result))
0580     return false;
0581   return Result;
0582 }
0583 
0584 /// Does status represent a symlink file?
0585 ///
0586 /// @param status A basic_file_status previously returned from status.
0587 /// @returns status_known(status) && status.type() == file_type::symlink_file.
0588 bool is_symlink_file(const basic_file_status &status);
0589 
0590 /// Is path a symlink file?
0591 ///
0592 /// @param path Input path.
0593 /// @param result Set to true if \a path is a symlink file, false if it is not.
0594 ///               Undefined otherwise.
0595 /// @returns errc::success if result has been successfully set, otherwise a
0596 ///          platform-specific error_code.
0597 std::error_code is_symlink_file(const Twine &path, bool &result);
0598 
0599 /// Simpler version of is_symlink_file for clients that don't need to
0600 ///        differentiate between an error and false.
0601 inline bool is_symlink_file(const Twine &Path) {
0602   bool Result;
0603   if (is_symlink_file(Path, Result))
0604     return false;
0605   return Result;
0606 }
0607 
0608 /// Does this status represent something that exists but is not a
0609 ///        directory or regular file?
0610 ///
0611 /// @param status A basic_file_status previously returned from status.
0612 /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
0613 bool is_other(const basic_file_status &status);
0614 
0615 /// Is path something that exists but is not a directory,
0616 ///        regular file, or symlink?
0617 ///
0618 /// @param path Input path.
0619 /// @param result Set to true if \a path exists, but is not a directory, regular
0620 ///               file, or a symlink, false if it does not. Undefined otherwise.
0621 /// @returns errc::success if result has been successfully set, otherwise a
0622 ///          platform-specific error_code.
0623 std::error_code is_other(const Twine &path, bool &result);
0624 
0625 /// Get file status as if by POSIX stat().
0626 ///
0627 /// @param path Input path.
0628 /// @param result Set to the file status.
0629 /// @param follow When true, follows symlinks.  Otherwise, the symlink itself is
0630 ///               statted.
0631 /// @returns errc::success if result has been successfully set, otherwise a
0632 ///          platform-specific error_code.
0633 std::error_code status(const Twine &path, file_status &result,
0634                        bool follow = true);
0635 
0636 /// A version for when a file descriptor is already available.
0637 std::error_code status(int FD, file_status &Result);
0638 
0639 #ifdef _WIN32
0640 /// A version for when a file descriptor is already available.
0641 std::error_code status(file_t FD, file_status &Result);
0642 #endif
0643 
0644 /// Get file creation mode mask of the process.
0645 ///
0646 /// @returns Mask reported by umask(2)
0647 /// @note There is no umask on Windows. This function returns 0 always
0648 ///       on Windows. This function does not return an error_code because
0649 ///       umask(2) never fails. It is not thread safe.
0650 unsigned getUmask();
0651 
0652 /// Set file permissions.
0653 ///
0654 /// @param Path File to set permissions on.
0655 /// @param Permissions New file permissions.
0656 /// @returns errc::success if the permissions were successfully set, otherwise
0657 ///          a platform-specific error_code.
0658 /// @note On Windows, all permissions except *_write are ignored. Using any of
0659 ///       owner_write, group_write, or all_write will make the file writable.
0660 ///       Otherwise, the file will be marked as read-only.
0661 std::error_code setPermissions(const Twine &Path, perms Permissions);
0662 
0663 /// Vesion of setPermissions accepting a file descriptor.
0664 /// TODO Delete the path based overload once we implement the FD based overload
0665 /// on Windows.
0666 std::error_code setPermissions(int FD, perms Permissions);
0667 
0668 /// Get file permissions.
0669 ///
0670 /// @param Path File to get permissions from.
0671 /// @returns the permissions if they were successfully retrieved, otherwise a
0672 ///          platform-specific error_code.
0673 /// @note On Windows, if the file does not have the FILE_ATTRIBUTE_READONLY
0674 ///       attribute, all_all will be returned. Otherwise, all_read | all_exe
0675 ///       will be returned.
0676 ErrorOr<perms> getPermissions(const Twine &Path);
0677 
0678 /// Get file size.
0679 ///
0680 /// @param Path Input path.
0681 /// @param Result Set to the size of the file in \a Path.
0682 /// @returns errc::success if result has been successfully set, otherwise a
0683 ///          platform-specific error_code.
0684 inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
0685   file_status Status;
0686   std::error_code EC = status(Path, Status);
0687   if (EC)
0688     return EC;
0689   Result = Status.getSize();
0690   return std::error_code();
0691 }
0692 
0693 /// Set the file modification and access time.
0694 ///
0695 /// @returns errc::success if the file times were successfully set, otherwise a
0696 ///          platform-specific error_code or errc::function_not_supported on
0697 ///          platforms where the functionality isn't available.
0698 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
0699                                                  TimePoint<> ModificationTime);
0700 
0701 /// Simpler version that sets both file modification and access time to the same
0702 /// time.
0703 inline std::error_code setLastAccessAndModificationTime(int FD,
0704                                                         TimePoint<> Time) {
0705   return setLastAccessAndModificationTime(FD, Time, Time);
0706 }
0707 
0708 /// Is status available?
0709 ///
0710 /// @param s Input file status.
0711 /// @returns True if status() != status_error.
0712 bool status_known(const basic_file_status &s);
0713 
0714 /// Is status available?
0715 ///
0716 /// @param path Input path.
0717 /// @param result Set to true if status() != status_error.
0718 /// @returns errc::success if result has been successfully set, otherwise a
0719 ///          platform-specific error_code.
0720 std::error_code status_known(const Twine &path, bool &result);
0721 
0722 enum CreationDisposition : unsigned {
0723   /// CD_CreateAlways - When opening a file:
0724   ///   * If it already exists, truncate it.
0725   ///   * If it does not already exist, create a new file.
0726   CD_CreateAlways = 0,
0727 
0728   /// CD_CreateNew - When opening a file:
0729   ///   * If it already exists, fail.
0730   ///   * If it does not already exist, create a new file.
0731   CD_CreateNew = 1,
0732 
0733   /// CD_OpenExisting - When opening a file:
0734   ///   * If it already exists, open the file with the offset set to 0.
0735   ///   * If it does not already exist, fail.
0736   CD_OpenExisting = 2,
0737 
0738   /// CD_OpenAlways - When opening a file:
0739   ///   * If it already exists, open the file with the offset set to 0.
0740   ///   * If it does not already exist, create a new file.
0741   CD_OpenAlways = 3,
0742 };
0743 
0744 enum FileAccess : unsigned {
0745   FA_Read = 1,
0746   FA_Write = 2,
0747 };
0748 
0749 enum OpenFlags : unsigned {
0750   OF_None = 0,
0751 
0752   /// The file should be opened in text mode on platforms like z/OS that make
0753   /// this distinction.
0754   OF_Text = 1,
0755 
0756   /// The file should use a carriage linefeed '\r\n'. This flag should only be
0757   /// used with OF_Text. Only makes a difference on Windows.
0758   OF_CRLF = 2,
0759 
0760   /// The file should be opened in text mode and use a carriage linefeed '\r\n'.
0761   /// This flag has the same functionality as OF_Text on z/OS but adds a
0762   /// carriage linefeed on Windows.
0763   OF_TextWithCRLF = OF_Text | OF_CRLF,
0764 
0765   /// The file should be opened in append mode.
0766   OF_Append = 4,
0767 
0768   /// The returned handle can be used for deleting the file. Only makes a
0769   /// difference on windows.
0770   OF_Delete = 8,
0771 
0772   /// When a child process is launched, this file should remain open in the
0773   /// child process.
0774   OF_ChildInherit = 16,
0775 
0776   /// Force files Atime to be updated on access. Only makes a difference on
0777   /// Windows.
0778   OF_UpdateAtime = 32,
0779 };
0780 
0781 /// Create a potentially unique file name but does not create it.
0782 ///
0783 /// Generates a unique path suitable for a temporary file but does not
0784 /// open or create the file. The name is based on \a Model with '%'
0785 /// replaced by a random char in [0-9a-f]. If \a MakeAbsolute is true
0786 /// then the system's temp directory is prepended first. If \a MakeAbsolute
0787 /// is false the current directory will be used instead.
0788 ///
0789 /// This function does not check if the file exists. If you want to be sure
0790 /// that the file does not yet exist, you should use enough '%' characters
0791 /// in your model to ensure this. Each '%' gives 4-bits of entropy so you can
0792 /// use 32 of them to get 128 bits of entropy.
0793 ///
0794 /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
0795 ///
0796 /// @param Model Name to base unique path off of.
0797 /// @param ResultPath Set to the file's path.
0798 /// @param MakeAbsolute Whether to use the system temp directory.
0799 void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
0800                       bool MakeAbsolute);
0801 
0802 /// Create a uniquely named file.
0803 ///
0804 /// Generates a unique path suitable for a temporary file and then opens it as a
0805 /// file. The name is based on \a Model with '%' replaced by a random char in
0806 /// [0-9a-f]. If \a Model is not an absolute path, the temporary file will be
0807 /// created in the current directory.
0808 ///
0809 /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
0810 ///
0811 /// This is an atomic operation. Either the file is created and opened, or the
0812 /// file system is left untouched.
0813 ///
0814 /// The intended use is for files that are to be kept, possibly after
0815 /// renaming them. For example, when running 'clang -c foo.o', the file can
0816 /// be first created as foo-abc123.o and then renamed.
0817 ///
0818 /// @param Model Name to base unique path off of.
0819 /// @param ResultFD Set to the opened file's file descriptor.
0820 /// @param ResultPath Set to the opened file's absolute path.
0821 /// @param Flags Set to the opened file's flags.
0822 /// @param Mode Set to the opened file's permissions.
0823 /// @returns errc::success if Result{FD,Path} have been successfully set,
0824 ///          otherwise a platform-specific error_code.
0825 std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
0826                                  SmallVectorImpl<char> &ResultPath,
0827                                  OpenFlags Flags = OF_None,
0828                                  unsigned Mode = all_read | all_write);
0829 
0830 /// Simpler version for clients that don't want an open file. An empty
0831 /// file will still be created.
0832 std::error_code createUniqueFile(const Twine &Model,
0833                                  SmallVectorImpl<char> &ResultPath,
0834                                  unsigned Mode = all_read | all_write);
0835 
0836 /// Represents a temporary file.
0837 ///
0838 /// The temporary file must be eventually discarded or given a final name and
0839 /// kept.
0840 ///
0841 /// The destructor doesn't implicitly discard because there is no way to
0842 /// properly handle errors in a destructor.
0843 class TempFile {
0844   bool Done = false;
0845   TempFile(StringRef Name, int FD);
0846 
0847 public:
0848   /// This creates a temporary file with createUniqueFile and schedules it for
0849   /// deletion with sys::RemoveFileOnSignal.
0850   static Expected<TempFile> create(const Twine &Model,
0851                                    unsigned Mode = all_read | all_write,
0852                                    OpenFlags ExtraFlags = OF_None);
0853   TempFile(TempFile &&Other);
0854   TempFile &operator=(TempFile &&Other);
0855 
0856   // Name of the temporary file.
0857   std::string TmpName;
0858 
0859   // The open file descriptor.
0860   int FD = -1;
0861 
0862 #ifdef _WIN32
0863   // Whether we need to manually remove the file on close.
0864   bool RemoveOnClose = false;
0865 #endif
0866 
0867   // Keep this with the given name.
0868   Error keep(const Twine &Name);
0869 
0870   // Keep this with the temporary name.
0871   Error keep();
0872 
0873   // Delete the file.
0874   Error discard();
0875 
0876   // This checks that keep or delete was called.
0877   ~TempFile();
0878 };
0879 
0880 /// Create a file in the system temporary directory.
0881 ///
0882 /// The filename is of the form prefix-random_chars.suffix. Since the directory
0883 /// is not know to the caller, Prefix and Suffix cannot have path separators.
0884 /// The files are created with mode 0600.
0885 ///
0886 /// This should be used for things like a temporary .s that is removed after
0887 /// running the assembler.
0888 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
0889                                     int &ResultFD,
0890                                     SmallVectorImpl<char> &ResultPath,
0891                                     OpenFlags Flags = OF_None);
0892 
0893 /// Simpler version for clients that don't want an open file. An empty
0894 /// file will still be created.
0895 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
0896                                     SmallVectorImpl<char> &ResultPath,
0897                                     OpenFlags Flags = OF_None);
0898 
0899 std::error_code createUniqueDirectory(const Twine &Prefix,
0900                                       SmallVectorImpl<char> &ResultPath);
0901 
0902 /// Get a unique name, not currently exisiting in the filesystem. Subject
0903 /// to race conditions, prefer to use createUniqueFile instead.
0904 ///
0905 /// Similar to createUniqueFile, but instead of creating a file only
0906 /// checks if it exists. This function is subject to race conditions, if you
0907 /// want to use the returned name to actually create a file, use
0908 /// createUniqueFile instead.
0909 std::error_code getPotentiallyUniqueFileName(const Twine &Model,
0910                                              SmallVectorImpl<char> &ResultPath);
0911 
0912 /// Get a unique temporary file name, not currently exisiting in the
0913 /// filesystem. Subject to race conditions, prefer to use createTemporaryFile
0914 /// instead.
0915 ///
0916 /// Similar to createTemporaryFile, but instead of creating a file only
0917 /// checks if it exists. This function is subject to race conditions, if you
0918 /// want to use the returned name to actually create a file, use
0919 /// createTemporaryFile instead.
0920 std::error_code
0921 getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
0922                                  SmallVectorImpl<char> &ResultPath);
0923 
0924 inline OpenFlags operator|(OpenFlags A, OpenFlags B) {
0925   return OpenFlags(unsigned(A) | unsigned(B));
0926 }
0927 
0928 inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) {
0929   A = A | B;
0930   return A;
0931 }
0932 
0933 inline FileAccess operator|(FileAccess A, FileAccess B) {
0934   return FileAccess(unsigned(A) | unsigned(B));
0935 }
0936 
0937 inline FileAccess &operator|=(FileAccess &A, FileAccess B) {
0938   A = A | B;
0939   return A;
0940 }
0941 
0942 /// @brief Opens a file with the specified creation disposition, access mode,
0943 /// and flags and returns a file descriptor.
0944 ///
0945 /// The caller is responsible for closing the file descriptor once they are
0946 /// finished with it.
0947 ///
0948 /// @param Name The path of the file to open, relative or absolute.
0949 /// @param ResultFD If the file could be opened successfully, its descriptor
0950 ///                 is stored in this location. Otherwise, this is set to -1.
0951 /// @param Disp Value specifying the existing-file behavior.
0952 /// @param Access Value specifying whether to open the file in read, write, or
0953 ///               read-write mode.
0954 /// @param Flags Additional flags.
0955 /// @param Mode The access permissions of the file, represented in octal.
0956 /// @returns errc::success if \a Name has been opened, otherwise a
0957 ///          platform-specific error_code.
0958 std::error_code openFile(const Twine &Name, int &ResultFD,
0959                          CreationDisposition Disp, FileAccess Access,
0960                          OpenFlags Flags, unsigned Mode = 0666);
0961 
0962 /// @brief Opens a file with the specified creation disposition, access mode,
0963 /// and flags and returns a platform-specific file object.
0964 ///
0965 /// The caller is responsible for closing the file object once they are
0966 /// finished with it.
0967 ///
0968 /// @param Name The path of the file to open, relative or absolute.
0969 /// @param Disp Value specifying the existing-file behavior.
0970 /// @param Access Value specifying whether to open the file in read, write, or
0971 ///               read-write mode.
0972 /// @param Flags Additional flags.
0973 /// @param Mode The access permissions of the file, represented in octal.
0974 /// @returns errc::success if \a Name has been opened, otherwise a
0975 ///          platform-specific error_code.
0976 Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
0977                                 FileAccess Access, OpenFlags Flags,
0978                                 unsigned Mode = 0666);
0979 
0980 /// Converts from a Posix file descriptor number to a native file handle.
0981 /// On Windows, this retreives the underlying handle. On non-Windows, this is a
0982 /// no-op.
0983 file_t convertFDToNativeFile(int FD);
0984 
0985 #ifndef _WIN32
0986 inline file_t convertFDToNativeFile(int FD) { return FD; }
0987 #endif
0988 
0989 /// Return an open handle to standard in. On Unix, this is typically FD 0.
0990 /// Returns kInvalidFile when the stream is closed.
0991 file_t getStdinHandle();
0992 
0993 /// Return an open handle to standard out. On Unix, this is typically FD 1.
0994 /// Returns kInvalidFile when the stream is closed.
0995 file_t getStdoutHandle();
0996 
0997 /// Return an open handle to standard error. On Unix, this is typically FD 2.
0998 /// Returns kInvalidFile when the stream is closed.
0999 file_t getStderrHandle();
1000 
1001 /// Reads \p Buf.size() bytes from \p FileHandle into \p Buf. Returns the number
1002 /// of bytes actually read. On Unix, this is equivalent to `return ::read(FD,
1003 /// Buf.data(), Buf.size())`, with error reporting. Returns 0 when reaching EOF.
1004 ///
1005 /// @param FileHandle File to read from.
1006 /// @param Buf Buffer to read into.
1007 /// @returns The number of bytes read, or error.
1008 Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf);
1009 
1010 /// Default chunk size for \a readNativeFileToEOF().
1011 enum : size_t { DefaultReadChunkSize = 4 * 4096 };
1012 
1013 /// Reads from \p FileHandle until EOF, appending to \p Buffer in chunks of
1014 /// size \p ChunkSize.
1015 ///
1016 /// This calls \a readNativeFile() in a loop. On Error, previous chunks that
1017 /// were read successfully are left in \p Buffer and returned.
1018 ///
1019 /// Note: For reading the final chunk at EOF, \p Buffer's capacity needs extra
1020 /// storage of \p ChunkSize.
1021 ///
1022 /// \param FileHandle File to read from.
1023 /// \param Buffer Where to put the file content.
1024 /// \param ChunkSize Size of chunks.
1025 /// \returns The error if EOF was not found.
1026 Error readNativeFileToEOF(file_t FileHandle, SmallVectorImpl<char> &Buffer,
1027                           ssize_t ChunkSize = DefaultReadChunkSize);
1028 
1029 /// Reads \p Buf.size() bytes from \p FileHandle at offset \p Offset into \p
1030 /// Buf. If 'pread' is available, this will use that, otherwise it will use
1031 /// 'lseek'. Returns the number of bytes actually read. Returns 0 when reaching
1032 /// EOF.
1033 ///
1034 /// @param FileHandle File to read from.
1035 /// @param Buf Buffer to read into.
1036 /// @param Offset Offset into the file at which the read should occur.
1037 /// @returns The number of bytes read, or error.
1038 Expected<size_t> readNativeFileSlice(file_t FileHandle,
1039                                      MutableArrayRef<char> Buf,
1040                                      uint64_t Offset);
1041 
1042 /// @brief Opens the file with the given name in a write-only or read-write
1043 /// mode, returning its open file descriptor. If the file does not exist, it
1044 /// is created.
1045 ///
1046 /// The caller is responsible for closing the file descriptor once they are
1047 /// finished with it.
1048 ///
1049 /// @param Name The path of the file to open, relative or absolute.
1050 /// @param ResultFD If the file could be opened successfully, its descriptor
1051 ///                 is stored in this location. Otherwise, this is set to -1.
1052 /// @param Flags Additional flags used to determine whether the file should be
1053 ///              opened in, for example, read-write or in write-only mode.
1054 /// @param Mode The access permissions of the file, represented in octal.
1055 /// @returns errc::success if \a Name has been opened, otherwise a
1056 ///          platform-specific error_code.
1057 inline std::error_code
1058 openFileForWrite(const Twine &Name, int &ResultFD,
1059                  CreationDisposition Disp = CD_CreateAlways,
1060                  OpenFlags Flags = OF_None, unsigned Mode = 0666) {
1061   return openFile(Name, ResultFD, Disp, FA_Write, Flags, Mode);
1062 }
1063 
1064 /// @brief Opens the file with the given name in a write-only or read-write
1065 /// mode, returning its open file descriptor. If the file does not exist, it
1066 /// is created.
1067 ///
1068 /// The caller is responsible for closing the freeing the file once they are
1069 /// finished with it.
1070 ///
1071 /// @param Name The path of the file to open, relative or absolute.
1072 /// @param Flags Additional flags used to determine whether the file should be
1073 ///              opened in, for example, read-write or in write-only mode.
1074 /// @param Mode The access permissions of the file, represented in octal.
1075 /// @returns a platform-specific file descriptor if \a Name has been opened,
1076 ///          otherwise an error object.
1077 inline Expected<file_t> openNativeFileForWrite(const Twine &Name,
1078                                                CreationDisposition Disp,
1079                                                OpenFlags Flags,
1080                                                unsigned Mode = 0666) {
1081   return openNativeFile(Name, Disp, FA_Write, Flags, Mode);
1082 }
1083 
1084 /// @brief Opens the file with the given name in a write-only or read-write
1085 /// mode, returning its open file descriptor. If the file does not exist, it
1086 /// is created.
1087 ///
1088 /// The caller is responsible for closing the file descriptor once they are
1089 /// finished with it.
1090 ///
1091 /// @param Name The path of the file to open, relative or absolute.
1092 /// @param ResultFD If the file could be opened successfully, its descriptor
1093 ///                 is stored in this location. Otherwise, this is set to -1.
1094 /// @param Flags Additional flags used to determine whether the file should be
1095 ///              opened in, for example, read-write or in write-only mode.
1096 /// @param Mode The access permissions of the file, represented in octal.
1097 /// @returns errc::success if \a Name has been opened, otherwise a
1098 ///          platform-specific error_code.
1099 inline std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD,
1100                                             CreationDisposition Disp,
1101                                             OpenFlags Flags,
1102                                             unsigned Mode = 0666) {
1103   return openFile(Name, ResultFD, Disp, FA_Write | FA_Read, Flags, Mode);
1104 }
1105 
1106 /// @brief Opens the file with the given name in a write-only or read-write
1107 /// mode, returning its open file descriptor. If the file does not exist, it
1108 /// is created.
1109 ///
1110 /// The caller is responsible for closing the freeing the file once they are
1111 /// finished with it.
1112 ///
1113 /// @param Name The path of the file to open, relative or absolute.
1114 /// @param Flags Additional flags used to determine whether the file should be
1115 ///              opened in, for example, read-write or in write-only mode.
1116 /// @param Mode The access permissions of the file, represented in octal.
1117 /// @returns a platform-specific file descriptor if \a Name has been opened,
1118 ///          otherwise an error object.
1119 inline Expected<file_t> openNativeFileForReadWrite(const Twine &Name,
1120                                                    CreationDisposition Disp,
1121                                                    OpenFlags Flags,
1122                                                    unsigned Mode = 0666) {
1123   return openNativeFile(Name, Disp, FA_Write | FA_Read, Flags, Mode);
1124 }
1125 
1126 /// @brief Opens the file with the given name in a read-only mode, returning
1127 /// its open file descriptor.
1128 ///
1129 /// The caller is responsible for closing the file descriptor once they are
1130 /// finished with it.
1131 ///
1132 /// @param Name The path of the file to open, relative or absolute.
1133 /// @param ResultFD If the file could be opened successfully, its descriptor
1134 ///                 is stored in this location. Otherwise, this is set to -1.
1135 /// @param RealPath If nonnull, extra work is done to determine the real path
1136 ///                 of the opened file, and that path is stored in this
1137 ///                 location.
1138 /// @returns errc::success if \a Name has been opened, otherwise a
1139 ///          platform-specific error_code.
1140 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1141                                 OpenFlags Flags = OF_None,
1142                                 SmallVectorImpl<char> *RealPath = nullptr);
1143 
1144 /// @brief Opens the file with the given name in a read-only mode, returning
1145 /// its open file descriptor.
1146 ///
1147 /// The caller is responsible for closing the freeing the file once they are
1148 /// finished with it.
1149 ///
1150 /// @param Name The path of the file to open, relative or absolute.
1151 /// @param RealPath If nonnull, extra work is done to determine the real path
1152 ///                 of the opened file, and that path is stored in this
1153 ///                 location.
1154 /// @returns a platform-specific file descriptor if \a Name has been opened,
1155 ///          otherwise an error object.
1156 Expected<file_t>
1157 openNativeFileForRead(const Twine &Name, OpenFlags Flags = OF_None,
1158                       SmallVectorImpl<char> *RealPath = nullptr);
1159 
1160 /// Try to locks the file during the specified time.
1161 ///
1162 /// This function implements advisory locking on entire file. If it returns
1163 /// <em>errc::success</em>, the file is locked by the calling process. Until the
1164 /// process unlocks the file by calling \a unlockFile, all attempts to lock the
1165 /// same file will fail/block. The process that locked the file may assume that
1166 /// none of other processes read or write this file, provided that all processes
1167 /// lock the file prior to accessing its content.
1168 ///
1169 /// @param FD      The descriptor representing the file to lock.
1170 /// @param Timeout Time in milliseconds that the process should wait before
1171 ///                reporting lock failure. Zero value means try to get lock only
1172 ///                once.
1173 /// @returns errc::success if lock is successfully obtained,
1174 /// errc::no_lock_available if the file cannot be locked, or platform-specific
1175 /// error_code otherwise.
1176 ///
1177 /// @note Care should be taken when using this function in a multithreaded
1178 /// context, as it may not prevent other threads in the same process from
1179 /// obtaining a lock on the same file, even if they are using a different file
1180 /// descriptor.
1181 std::error_code
1182 tryLockFile(int FD,
1183             std::chrono::milliseconds Timeout = std::chrono::milliseconds(0));
1184 
1185 /// Lock the file.
1186 ///
1187 /// This function acts as @ref tryLockFile but it waits infinitely.
1188 std::error_code lockFile(int FD);
1189 
1190 /// Unlock the file.
1191 ///
1192 /// @param FD The descriptor representing the file to unlock.
1193 /// @returns errc::success if lock is successfully released or platform-specific
1194 /// error_code otherwise.
1195 std::error_code unlockFile(int FD);
1196 
1197 /// @brief Close the file object.  This should be used instead of ::close for
1198 /// portability. On error, the caller should assume the file is closed, as is
1199 /// the case for Process::SafelyCloseFileDescriptor
1200 ///
1201 /// @param F On input, this is the file to close.  On output, the file is
1202 /// set to kInvalidFile.
1203 ///
1204 /// @returns An error code if closing the file failed. Typically, an error here
1205 /// means that the filesystem may have failed to perform some buffered writes.
1206 std::error_code closeFile(file_t &F);
1207 
1208 #ifdef LLVM_ON_UNIX
1209 /// @brief Change ownership of a file.
1210 ///
1211 /// @param Owner The owner of the file to change to.
1212 /// @param Group The group of the file to change to.
1213 /// @returns errc::success if successfully updated file ownership, otherwise an
1214 ///          error code is returned.
1215 std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group);
1216 #endif
1217 
1218 /// RAII class that facilitates file locking.
1219 class FileLocker {
1220   int FD; ///< Locked file handle.
1221   FileLocker(int FD) : FD(FD) {}
1222   friend class llvm::raw_fd_ostream;
1223 
1224 public:
1225   FileLocker(const FileLocker &L) = delete;
1226   FileLocker(FileLocker &&L) : FD(L.FD) { L.FD = -1; }
1227   ~FileLocker() {
1228     if (FD != -1)
1229       unlockFile(FD);
1230   }
1231   FileLocker &operator=(FileLocker &&L) {
1232     FD = L.FD;
1233     L.FD = -1;
1234     return *this;
1235   }
1236   FileLocker &operator=(const FileLocker &L) = delete;
1237   std::error_code unlock() {
1238     if (FD != -1) {
1239       std::error_code Result = unlockFile(FD);
1240       FD = -1;
1241       return Result;
1242     }
1243     return std::error_code();
1244   }
1245 };
1246 
1247 std::error_code getUniqueID(const Twine Path, UniqueID &Result);
1248 
1249 /// Get disk space usage information.
1250 ///
1251 /// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug.
1252 /// Note: Windows reports results according to the quota allocated to the user.
1253 ///
1254 /// @param Path Input path.
1255 /// @returns a space_info structure filled with the capacity, free, and
1256 /// available space on the device \a Path is on. A platform specific error_code
1257 /// is returned on error.
1258 ErrorOr<space_info> disk_space(const Twine &Path);
1259 
1260 /// This class represents a memory mapped file. It is based on
1261 /// boost::iostreams::mapped_file.
1262 class mapped_file_region {
1263 public:
1264   enum mapmode {
1265     readonly, ///< May only access map via const_data as read only.
1266     readwrite, ///< May access map via data and modify it. Written to path.
1267     priv ///< May modify via data, but changes are lost on destruction.
1268   };
1269 
1270 private:
1271   /// Platform-specific mapping state.
1272   size_t Size = 0;
1273   void *Mapping = nullptr;
1274 #ifdef _WIN32
1275   sys::fs::file_t FileHandle = nullptr;
1276 #endif
1277   mapmode Mode = readonly;
1278 
1279   void copyFrom(const mapped_file_region &Copied) {
1280     Size = Copied.Size;
1281     Mapping = Copied.Mapping;
1282 #ifdef _WIN32
1283     FileHandle = Copied.FileHandle;
1284 #endif
1285     Mode = Copied.Mode;
1286   }
1287 
1288   void moveFromImpl(mapped_file_region &Moved) {
1289     copyFrom(Moved);
1290     Moved.copyFrom(mapped_file_region());
1291   }
1292 
1293   void unmapImpl();
1294   void dontNeedImpl();
1295 
1296   std::error_code init(sys::fs::file_t FD, uint64_t Offset, mapmode Mode);
1297 
1298 public:
1299   mapped_file_region() = default;
1300   mapped_file_region(mapped_file_region &&Moved) { moveFromImpl(Moved); }
1301   mapped_file_region &operator=(mapped_file_region &&Moved) {
1302     unmap();
1303     moveFromImpl(Moved);
1304     return *this;
1305   }
1306 
1307   mapped_file_region(const mapped_file_region &) = delete;
1308   mapped_file_region &operator=(const mapped_file_region &) = delete;
1309 
1310   /// \param fd An open file descriptor to map. Does not take ownership of fd.
1311   mapped_file_region(sys::fs::file_t fd, mapmode mode, size_t length, uint64_t offset,
1312                      std::error_code &ec);
1313 
1314   ~mapped_file_region() { unmapImpl(); }
1315 
1316   /// Check if this is a valid mapping.
1317   explicit operator bool() const { return Mapping; }
1318 
1319   /// Unmap.
1320   void unmap() {
1321     unmapImpl();
1322     copyFrom(mapped_file_region());
1323   }
1324   void dontNeed() { dontNeedImpl(); }
1325 
1326   size_t size() const;
1327   char *data() const;
1328 
1329   /// Get a const view of the data. Modifying this memory has undefined
1330   /// behavior.
1331   const char *const_data() const;
1332 
1333   /// \returns The minimum alignment offset must be.
1334   static int alignment();
1335 };
1336 
1337 /// Return the path to the main executable, given the value of argv[0] from
1338 /// program startup and the address of main itself. In extremis, this function
1339 /// may fail and return an empty path.
1340 std::string getMainExecutable(const char *argv0, void *MainExecAddr);
1341 
1342 /// @}
1343 /// @name Iterators
1344 /// @{
1345 
1346 /// directory_entry - A single entry in a directory.
1347 class directory_entry {
1348   // FIXME: different platforms make different information available "for free"
1349   // when traversing a directory. The design of this class wraps most of the
1350   // information in basic_file_status, so on platforms where we can't populate
1351   // that whole structure, callers end up paying for a stat().
1352   // std::filesystem::directory_entry may be a better model.
1353   std::string Path;
1354   file_type Type = file_type::type_unknown; // Most platforms can provide this.
1355   bool FollowSymlinks = true;               // Affects the behavior of status().
1356   basic_file_status Status;                 // If available.
1357 
1358 public:
1359   explicit directory_entry(const Twine &Path, bool FollowSymlinks = true,
1360                            file_type Type = file_type::type_unknown,
1361                            basic_file_status Status = basic_file_status())
1362       : Path(Path.str()), Type(Type), FollowSymlinks(FollowSymlinks),
1363         Status(Status) {}
1364 
1365   directory_entry() = default;
1366 
1367   void replace_filename(const Twine &Filename, file_type Type,
1368                         basic_file_status Status = basic_file_status());
1369 
1370   const std::string &path() const { return Path; }
1371   // Get basic information about entry file (a subset of fs::status()).
1372   // On most platforms this is a stat() call.
1373   // On windows the information was already retrieved from the directory.
1374   ErrorOr<basic_file_status> status() const;
1375   // Get the type of this file.
1376   // On most platforms (Linux/Mac/Windows/BSD), this was already retrieved.
1377   // On some platforms (e.g. Solaris) this is a stat() call.
1378   file_type type() const {
1379     if (Type != file_type::type_unknown)
1380       return Type;
1381     auto S = status();
1382     return S ? S->type() : file_type::type_unknown;
1383   }
1384 
1385   bool operator==(const directory_entry& RHS) const { return Path == RHS.Path; }
1386   bool operator!=(const directory_entry& RHS) const { return !(*this == RHS); }
1387   bool operator< (const directory_entry& RHS) const;
1388   bool operator<=(const directory_entry& RHS) const;
1389   bool operator> (const directory_entry& RHS) const;
1390   bool operator>=(const directory_entry& RHS) const;
1391 };
1392 
1393 namespace detail {
1394 
1395   struct DirIterState;
1396 
1397   std::error_code directory_iterator_construct(DirIterState &, StringRef, bool);
1398   std::error_code directory_iterator_increment(DirIterState &);
1399   std::error_code directory_iterator_destruct(DirIterState &);
1400 
1401   /// Keeps state for the directory_iterator.
1402   struct DirIterState {
1403     ~DirIterState() {
1404       directory_iterator_destruct(*this);
1405     }
1406 
1407     intptr_t IterationHandle = 0;
1408     directory_entry CurrentEntry;
1409   };
1410 
1411 } // end namespace detail
1412 
1413 /// directory_iterator - Iterates through the entries in path. There is no
1414 /// operator++ because we need an error_code. If it's really needed we can make
1415 /// it call report_fatal_error on error.
1416 class directory_iterator {
1417   std::shared_ptr<detail::DirIterState> State;
1418   bool FollowSymlinks = true;
1419 
1420 public:
1421   explicit directory_iterator(const Twine &path, std::error_code &ec,
1422                               bool follow_symlinks = true)
1423       : FollowSymlinks(follow_symlinks) {
1424     State = std::make_shared<detail::DirIterState>();
1425     SmallString<128> path_storage;
1426     ec = detail::directory_iterator_construct(
1427         *State, path.toStringRef(path_storage), FollowSymlinks);
1428   }
1429 
1430   explicit directory_iterator(const directory_entry &de, std::error_code &ec,
1431                               bool follow_symlinks = true)
1432       : FollowSymlinks(follow_symlinks) {
1433     State = std::make_shared<detail::DirIterState>();
1434     ec = detail::directory_iterator_construct(
1435         *State, de.path(), FollowSymlinks);
1436   }
1437 
1438   /// Construct end iterator.
1439   directory_iterator() = default;
1440 
1441   // No operator++ because we need error_code.
1442   directory_iterator &increment(std::error_code &ec) {
1443     ec = directory_iterator_increment(*State);
1444     return *this;
1445   }
1446 
1447   const directory_entry &operator*() const { return State->CurrentEntry; }
1448   const directory_entry *operator->() const { return &State->CurrentEntry; }
1449 
1450   bool operator==(const directory_iterator &RHS) const {
1451     if (State == RHS.State)
1452       return true;
1453     if (!RHS.State)
1454       return State->CurrentEntry == directory_entry();
1455     if (!State)
1456       return RHS.State->CurrentEntry == directory_entry();
1457     return State->CurrentEntry == RHS.State->CurrentEntry;
1458   }
1459 
1460   bool operator!=(const directory_iterator &RHS) const {
1461     return !(*this == RHS);
1462   }
1463 };
1464 
1465 namespace detail {
1466 
1467   /// Keeps state for the recursive_directory_iterator.
1468   struct RecDirIterState {
1469     std::vector<directory_iterator> Stack;
1470     uint16_t Level = 0;
1471     bool HasNoPushRequest = false;
1472   };
1473 
1474 } // end namespace detail
1475 
1476 /// recursive_directory_iterator - Same as directory_iterator except for it
1477 /// recurses down into child directories.
1478 class recursive_directory_iterator {
1479   std::shared_ptr<detail::RecDirIterState> State;
1480   bool Follow;
1481 
1482 public:
1483   recursive_directory_iterator() = default;
1484   explicit recursive_directory_iterator(const Twine &path, std::error_code &ec,
1485                                         bool follow_symlinks = true)
1486       : State(std::make_shared<detail::RecDirIterState>()),
1487         Follow(follow_symlinks) {
1488     State->Stack.push_back(directory_iterator(path, ec, Follow));
1489     if (State->Stack.back() == directory_iterator())
1490       State.reset();
1491   }
1492 
1493   // No operator++ because we need error_code.
1494   recursive_directory_iterator &increment(std::error_code &ec) {
1495     const directory_iterator end_itr = {};
1496 
1497     if (State->HasNoPushRequest)
1498       State->HasNoPushRequest = false;
1499     else {
1500       file_type type = State->Stack.back()->type();
1501       if (type == file_type::symlink_file && Follow) {
1502         // Resolve the symlink: is it a directory to recurse into?
1503         ErrorOr<basic_file_status> status = State->Stack.back()->status();
1504         if (status)
1505           type = status->type();
1506         // Otherwise broken symlink, and we'll continue.
1507       }
1508       if (type == file_type::directory_file) {
1509         State->Stack.push_back(
1510             directory_iterator(*State->Stack.back(), ec, Follow));
1511         if (State->Stack.back() != end_itr) {
1512           ++State->Level;
1513           return *this;
1514         }
1515         State->Stack.pop_back();
1516       }
1517     }
1518 
1519     while (!State->Stack.empty()
1520            && State->Stack.back().increment(ec) == end_itr) {
1521       State->Stack.pop_back();
1522       --State->Level;
1523     }
1524 
1525     // Check if we are done. If so, create an end iterator.
1526     if (State->Stack.empty())
1527       State.reset();
1528 
1529     return *this;
1530   }
1531 
1532   const directory_entry &operator*() const { return *State->Stack.back(); }
1533   const directory_entry *operator->() const { return &*State->Stack.back(); }
1534 
1535   // observers
1536   /// Gets the current level. Starting path is at level 0.
1537   int level() const { return State->Level; }
1538 
1539   /// Returns true if no_push has been called for this directory_entry.
1540   bool no_push_request() const { return State->HasNoPushRequest; }
1541 
1542   // modifiers
1543   /// Goes up one level if Level > 0.
1544   void pop() {
1545     assert(State && "Cannot pop an end iterator!");
1546     assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
1547 
1548     const directory_iterator end_itr = {};
1549     std::error_code ec;
1550     do {
1551       if (ec)
1552         report_fatal_error("Error incrementing directory iterator.");
1553       State->Stack.pop_back();
1554       --State->Level;
1555     } while (!State->Stack.empty()
1556              && State->Stack.back().increment(ec) == end_itr);
1557 
1558     // Check if we are done. If so, create an end iterator.
1559     if (State->Stack.empty())
1560       State.reset();
1561   }
1562 
1563   /// Does not go down into the current directory_entry.
1564   void no_push() { State->HasNoPushRequest = true; }
1565 
1566   bool operator==(const recursive_directory_iterator &RHS) const {
1567     return State == RHS.State;
1568   }
1569 
1570   bool operator!=(const recursive_directory_iterator &RHS) const {
1571     return !(*this == RHS);
1572   }
1573 };
1574 
1575 /// @}
1576 
1577 } // end namespace fs
1578 } // end namespace sys
1579 } // end namespace llvm
1580 
1581 #endif // LLVM_SUPPORT_FILESYSTEM_H