1//===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===// 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 7//===----------------------------------------------------------------------===// 9// This file declares the llvm::sys::fs namespace. It is designed after 10// TR2/boost filesystem (v3), but modified to remove exception handling and the 13// All functions return an error_code and their actual work via the last out 14// argument. The out argument is defined if and only if errc::success is 15// returned. A function may return any error code in the generic or system 16// category. However, they shall be equivalent to any error conditions listed 17// in each functions respective documentation if the condition applies. [ note: 18// this does not guarantee that error_code will be in the set of explicitly 19// listed codes, but it does guarantee that if any of the explicitly listed 20// errors occur, the correct error_code will be used ]. All functions may 21// return errc::not_enough_memory if there is not enough memory to complete the 24//===----------------------------------------------------------------------===// 26#ifndef LLVM_SUPPORT_FILESYSTEM_H 27#define LLVM_SUPPORT_FILESYSTEM_H 32#include "llvm/Config/llvm-config.h" 44#include <system_error> 52// A Win32 HANDLE is a typedef of void* 60/// An enumeration for the file system's view of the type. 74/// space_info - Self explanatory. 106// Helper functions so that you can use & and | to manipulate perms bits: 108returnstatic_cast<perms>(
static_cast<unsignedshort>(l) |
109static_cast<unsignedshort>(r));
112returnstatic_cast<perms>(
static_cast<unsignedshort>(l) &
113static_cast<unsignedshort>(r));
124// Avoid UB by explicitly truncating the (unsigned) ~ result. 125returnstatic_cast<perms>(
126static_cast<unsignedshort>(~static_cast<unsigned short>(x)));
129/// Represents the result of a call to directory_iterator::status(). This is a 130/// subset of the information returned by a regular sys::fs::status() call, and 131/// represents the information provided by Windows FileFirstFile/FindNextFile. 134 #if defined(LLVM_ON_UNIX) 142 #elif defined (_WIN32) 158 #if defined(LLVM_ON_UNIX) 161 uid_t UID, gid_t GID, off_t
Size)
171 : LastAccessedTimeHigh(LastAccessTimeHigh),
172 LastAccessedTimeLow(LastAccessTimeLow),
173 LastWriteTimeHigh(LastWriteTimeHigh),
174 LastWriteTimeLow(LastWriteTimeLow), FileSizeHigh(FileSizeHigh),
182 /// The file access time as reported from the underlying file system. 184 /// Also see comments on \c getLastModificationTime() related to the precision 185 /// of the returned value. 188 /// The file modification time as reported from the underlying file system. 190 /// The returned value allows for nanosecond precision but the actual 191 /// resolution is an implementation detail of the underlying file system. 192 /// There is no guarantee for what kind of resolution you can expect, the 193 /// resolution can differ across platforms and even across mountpoints on the 197 #if defined(LLVM_ON_UNIX) 201 #elif defined (_WIN32) 203return 9999;
// Not applicable to Windows, so... 207return 9999;
// Not applicable to Windows, so... 211return (
uint64_t(FileSizeHigh) << 32) + FileSizeLow;
220/// Represents the result of a call to sys::fs::status(). 224 #if defined(LLVM_ON_UNIX) 226 nlink_t fs_st_nlinks = 0;
228 #elif defined (_WIN32) 239 #if defined(LLVM_ON_UNIX) 243 uid_t UID, gid_t GID, off_t
Size)
246 fs_st_dev(Dev), fs_st_nlinks(Links), fs_st_ino(Ino) {}
247 #elif defined(_WIN32) 254 LastWriteTimeHigh, LastWriteTimeLow, FileSizeHigh,
256 NumLinks(LinkCount), VolumeSerialNumber(VolumeSerialNumber),
257 PathHash(PathHash) {}
265/// @name Physical Operators 268/// Make \a path an absolute path. 270/// Makes \a path absolute using the \a current_directory if it is not already. 271/// An empty \a path will result in the \a current_directory. 273/// /absolute/path => /absolute/path 274/// relative/../path => <current-directory>/relative/../path 276/// @param path A path that is modified to be an absolute path. 279/// Make \a path an absolute path. 281/// Makes \a path absolute using the current directory if it is not already. An 282/// empty \a path will result in the current directory. 284/// /absolute/path => /absolute/path 285/// relative/../path => <current-directory>/relative/../path 287/// @param path A path that is modified to be an absolute path. 288/// @returns errc::success if \a path has been made absolute, otherwise a 289/// platform-specific error_code. 292/// Create all the non-existent directories in path. 294/// @param path Directories to create. 295/// @returns errc::success if is_directory(path), otherwise a platform 296/// specific error_code. If IgnoreExisting is false, also returns 297/// error if the directory already existed. 299bool IgnoreExisting =
true,
302/// Create the directory in path. 304/// @param path Directory to create. 305/// @returns errc::success if is_directory(path), otherwise a platform 306/// specific error_code. If IgnoreExisting is false, also returns 307/// error if the directory already existed. 311/// Create a link from \a from to \a to. 313/// The link may be a soft or a hard link, depending on the platform. The caller 314/// may not assume which one. Currently on windows it creates a hard link since 315/// soft links require extra privileges. On unix, it creates a soft link since 316/// hard links don't work on SMB file systems. 318/// @param to The path to hard link to. 319/// @param from The path to hard link from. This is created. 320/// @returns errc::success if the link was created, otherwise a platform 321/// specific error_code. 324/// Create a hard link from \a from to \a to, or return an error. 326/// @param to The path to hard link to. 327/// @param from The path to hard link from. This is created. 328/// @returns errc::success if the link was created, otherwise a platform 329/// specific error_code. 332/// Collapse all . and .. patterns, resolve all symlinks, and optionally 333/// expand ~ expressions to the user's home directory. 335/// @param path The path to resolve. 336/// @param output The location to store the resolved path. 337/// @param expand_tilde If true, resolves ~ expressions to the user's home 342/// Expands ~ expressions to the user's home directory. On Unix ~user 343/// directories are resolved as well. 345/// @param path The path to resolve. 348/// Get the current path. 350/// @param result Holds the current path on return. 351/// @returns errc::success if the current path has been stored in result, 352/// otherwise a platform-specific error_code. 355/// Set the current path. 357/// @param path The path to set. 358/// @returns errc::success if the current path was successfully set, 359/// otherwise a platform-specific error_code. 362/// Remove path. Equivalent to POSIX remove(). 364/// @param path Input path. 365/// @returns errc::success if path has been removed or didn't exist, otherwise a 366/// platform-specific error code. If IgnoreNonExisting is false, also 367/// returns error if the file didn't exist. 368std::error_code
remove(
constTwine &path,
bool IgnoreNonExisting =
true);
370/// Recursively delete a directory. 372/// @param path Input path. 373/// @returns errc::success if path has been removed or didn't exist, otherwise a 374/// platform-specific error code. 377/// Rename \a from to \a to. 379/// Files are renamed as if by POSIX rename(), except that on Windows there may 380/// be a short interval of time during which the destination file does not 383/// @param from The path to rename from. 384/// @param to The path to rename to. This is created. 387/// Copy the contents of \a From to \a To. 389/// @param From The path to copy from. 390/// @param To The path to copy to. This is created. 393/// Copy the contents of \a From to \a To. 395/// @param From The path to copy from. 396/// @param ToFD The open file descriptor of the destination file. 399/// Resize path to size. File is resized as if by POSIX truncate(). 401/// @param FD Input file descriptor. 402/// @param Size Size to resize to. 403/// @returns errc::success if \a path has been resized to \a size, otherwise a 404/// platform-specific error_code. 407/// Resize \p FD to \p Size before mapping \a mapped_file_region::readwrite. On 408/// non-Windows, this calls \a resize_file(). On Windows, this is a no-op, 409/// since the subsequent mapping (via \c CreateFileMapping) automatically 416return std::error_code();
422/// Compute an MD5 hash of a file's contents. 424/// @param FD Input file descriptor. 425/// @returns An MD5Result with the hash computed, if successful, otherwise a 429/// Version of compute_md5 that doesn't require an open file descriptor. 433/// @name Physical Observers 438/// @param status A basic_file_status previously returned from stat. 439/// @returns True if the file represented by status exists, false if it does 445/// Can the file be accessed? 447/// @param Path Input path. 448/// @returns errc::success if the path can be accessed, otherwise a 449/// platform-specific error_code. 454/// @param Path Input path. 455/// @returns True if it exists, false otherwise. 460/// Can we execute this file? 462/// @param Path Input path. 463/// @returns True if we can execute it, false otherwise. 466/// Can we write this file? 468/// @param Path Input path. 469/// @returns True if we can write to it, false otherwise. 474/// Do file_status's represent the same thing? 476/// @param A Input file_status. 477/// @param B Input file_status. 479/// assert(status_known(A) || status_known(B)); 481/// @returns True if A and B both represent the same file system entity, false 485/// Do paths represent the same thing? 487/// assert(status_known(A) || status_known(B)); 489/// @param A Input path A. 490/// @param B Input path B. 491/// @param result Set to true if stat(A) and stat(B) have the same device and 492/// inode (or equivalent). 493/// @returns errc::success if result has been successfully set, otherwise a 494/// platform-specific error_code. 497/// Simpler version of equivalent for clients that don't need to 498/// differentiate between an error and false. 504/// Is the file mounted on a local filesystem? 506/// @param path Input path. 507/// @param result Set to true if \a path is on fixed media such as a hard disk, 508/// false if it is not. 509/// @returns errc::success if result has been successfully set, otherwise a 510/// platform specific error_code. 513/// Version of is_local accepting an open file descriptor. 516/// Simpler version of is_local for clients that don't need to 517/// differentiate between an error and false. 520return !
is_local(Path, Result) && Result;
523/// Simpler version of is_local accepting an open file descriptor for 524/// clients that don't need to differentiate between an error and false. 527return !
is_local(FD, Result) && Result;
530/// Does status represent a directory? 532/// @param Path The path to get the type of. 533/// @param Follow For symbolic links, indicates whether to return the file type 534/// of the link itself, or of the target. 535/// @returns A value from the file_type enumeration indicating the type of file. 538/// Does status represent a directory? 540/// @param status A basic_file_status previously returned from status. 541/// @returns status.type() == file_type::directory_file. 544/// Is path a directory? 546/// @param path Input path. 547/// @param result Set to true if \a path is a directory (after following 548/// symlinks, false if it is not. Undefined otherwise. 549/// @returns errc::success if result has been successfully set, otherwise a 550/// platform-specific error_code. 553/// Simpler version of is_directory for clients that don't need to 554/// differentiate between an error and false. 560/// Does status represent a regular file? 562/// @param status A basic_file_status previously returned from status. 563/// @returns status_known(status) && status.type() == file_type::regular_file. 566/// Is path a regular file? 568/// @param path Input path. 569/// @param result Set to true if \a path is a regular file (after following 570/// symlinks), false if it is not. Undefined otherwise. 571/// @returns errc::success if result has been successfully set, otherwise a 572/// platform-specific error_code. 575/// Simpler version of is_regular_file for clients that don't need to 576/// differentiate between an error and false. 584/// Does status represent a symlink file? 586/// @param status A basic_file_status previously returned from status. 587/// @returns status_known(status) && status.type() == file_type::symlink_file. 590/// Is path a symlink file? 592/// @param path Input path. 593/// @param result Set to true if \a path is a symlink file, false if it is not. 594/// Undefined otherwise. 595/// @returns errc::success if result has been successfully set, otherwise a 596/// platform-specific error_code. 599/// Simpler version of is_symlink_file for clients that don't need to 600/// differentiate between an error and false. 608/// Does this status represent something that exists but is not a 609/// directory or regular file? 611/// @param status A basic_file_status previously returned from status. 612/// @returns exists(s) && !is_regular_file(s) && !is_directory(s) 615/// Is path something that exists but is not a directory, 616/// regular file, or symlink? 618/// @param path Input path. 619/// @param result Set to true if \a path exists, but is not a directory, regular 620/// file, or a symlink, false if it does not. Undefined otherwise. 621/// @returns errc::success if result has been successfully set, otherwise a 622/// platform-specific error_code. 625/// Get file status as if by POSIX stat(). 627/// @param path Input path. 628/// @param result Set to the file status. 629/// @param follow When true, follows symlinks. Otherwise, the symlink itself is 631/// @returns errc::success if result has been successfully set, otherwise a 632/// platform-specific error_code. 636/// A version for when a file descriptor is already available. 640/// A version for when a file descriptor is already available. 644/// Get file creation mode mask of the process. 646/// @returns Mask reported by umask(2) 647/// @note There is no umask on Windows. This function returns 0 always 648/// on Windows. This function does not return an error_code because 649/// umask(2) never fails. It is not thread safe. 652/// Set file permissions. 654/// @param Path File to set permissions on. 655/// @param Permissions New file permissions. 656/// @returns errc::success if the permissions were successfully set, otherwise 657/// a platform-specific error_code. 658/// @note On Windows, all permissions except *_write are ignored. Using any of 659/// owner_write, group_write, or all_write will make the file writable. 660/// Otherwise, the file will be marked as read-only. 663/// Vesion of setPermissions accepting a file descriptor. 664/// TODO Delete the path based overload once we implement the FD based overload 668/// Get file permissions. 670/// @param Path File to get permissions from. 671/// @returns the permissions if they were successfully retrieved, otherwise a 672/// platform-specific error_code. 673/// @note On Windows, if the file does not have the FILE_ATTRIBUTE_READONLY 674/// attribute, all_all will be returned. Otherwise, all_read | all_exe 680/// @param Path Input path. 681/// @param Result Set to the size of the file in \a Path. 682/// @returns errc::success if result has been successfully set, otherwise a 683/// platform-specific error_code. 690return std::error_code();
693/// Set the file modification and access time. 695/// @returns errc::success if the file times were successfully set, otherwise a 696/// platform-specific error_code or errc::function_not_supported on 697/// platforms where the functionality isn't available. 701/// Simpler version that sets both file modification and access time to the same 708/// Is status available? 710/// @param s Input file status. 711/// @returns True if status() != status_error. 714/// Is status available? 716/// @param path Input path. 717/// @param result Set to true if status() != status_error. 718/// @returns errc::success if result has been successfully set, otherwise a 719/// platform-specific error_code. 723 /// CD_CreateAlways - When opening a file: 724 /// * If it already exists, truncate it. 725 /// * If it does not already exist, create a new file. 728 /// CD_CreateNew - When opening a file: 729 /// * If it already exists, fail. 730 /// * If it does not already exist, create a new file. 733 /// CD_OpenExisting - When opening a file: 734 /// * If it already exists, open the file with the offset set to 0. 735 /// * If it does not already exist, fail. 738 /// CD_OpenAlways - When opening a file: 739 /// * If it already exists, open the file with the offset set to 0. 740 /// * If it does not already exist, create a new file. 752 /// The file should be opened in text mode on platforms like z/OS that make 753 /// this distinction. 756 /// The file should use a carriage linefeed '\r\n'. This flag should only be 757 /// used with OF_Text. Only makes a difference on Windows. 760 /// The file should be opened in text mode and use a carriage linefeed '\r\n'. 761 /// This flag has the same functionality as OF_Text on z/OS but adds a 762 /// carriage linefeed on Windows. 765 /// The file should be opened in append mode. 768 /// The returned handle can be used for deleting the file. Only makes a 769 /// difference on windows. 772 /// When a child process is launched, this file should remain open in the 776 /// Force files Atime to be updated on access. Only makes a difference on 781/// Create a potentially unique file name but does not create it. 783/// Generates a unique path suitable for a temporary file but does not 784/// open or create the file. The name is based on \a Model with '%' 785/// replaced by a random char in [0-9a-f]. If \a MakeAbsolute is true 786/// then the system's temp directory is prepended first. If \a MakeAbsolute 787/// is false the current directory will be used instead. 789/// This function does not check if the file exists. If you want to be sure 790/// that the file does not yet exist, you should use enough '%' characters 791/// in your model to ensure this. Each '%' gives 4-bits of entropy so you can 792/// use 32 of them to get 128 bits of entropy. 794/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s 796/// @param Model Name to base unique path off of. 797/// @param ResultPath Set to the file's path. 798/// @param MakeAbsolute Whether to use the system temp directory. 802/// Create a uniquely named file. 804/// Generates a unique path suitable for a temporary file and then opens it as a 805/// file. The name is based on \a Model with '%' replaced by a random char in 806/// [0-9a-f]. If \a Model is not an absolute path, the temporary file will be 807/// created in the current directory. 809/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s 811/// This is an atomic operation. Either the file is created and opened, or the 812/// file system is left untouched. 814/// The intended use is for files that are to be kept, possibly after 815/// renaming them. For example, when running 'clang -c foo.o', the file can 816/// be first created as foo-abc123.o and then renamed. 818/// @param Model Name to base unique path off of. 819/// @param ResultFD Set to the opened file's file descriptor. 820/// @param ResultPath Set to the opened file's absolute path. 821/// @param Flags Set to the opened file's flags. 822/// @param Mode Set to the opened file's permissions. 823/// @returns errc::success if Result{FD,Path} have been successfully set, 824/// otherwise a platform-specific error_code. 830/// Simpler version for clients that don't want an open file. An empty 831/// file will still be created. 836/// Represents a temporary file. 838/// The temporary file must be eventually discarded or given a final name and 841/// The destructor doesn't implicitly discard because there is no way to 842/// properly handle errors in a destructor. 848 /// This creates a temporary file with createUniqueFile and schedules it for 849 /// deletion with sys::RemoveFileOnSignal. 856// Name of the temporary file. 859// The open file descriptor. 863// Whether we need to manually remove the file on close. 864bool RemoveOnClose =
false;
867// Keep this with the given name. 870// Keep this with the temporary name. 876// This checks that keep or delete was called. 880/// Create a file in the system temporary directory. 882/// The filename is of the form prefix-random_chars.suffix. Since the directory 883/// is not know to the caller, Prefix and Suffix cannot have path separators. 884/// The files are created with mode 0600. 886/// This should be used for things like a temporary .s that is removed after 887/// running the assembler. 893/// Simpler version for clients that don't want an open file. An empty 894/// file will still be created. 902/// Get a unique name, not currently exisiting in the filesystem. Subject 903/// to race conditions, prefer to use createUniqueFile instead. 905/// Similar to createUniqueFile, but instead of creating a file only 906/// checks if it exists. This function is subject to race conditions, if you 907/// want to use the returned name to actually create a file, use 908/// createUniqueFile instead. 912/// Get a unique temporary file name, not currently exisiting in the 913/// filesystem. Subject to race conditions, prefer to use createTemporaryFile 916/// Similar to createTemporaryFile, but instead of creating a file only 917/// checks if it exists. This function is subject to race conditions, if you 918/// want to use the returned name to actually create a file, use 919/// createTemporaryFile instead. 942/// @brief Opens a file with the specified creation disposition, access mode, 943/// and flags and returns a file descriptor. 945/// The caller is responsible for closing the file descriptor once they are 948/// @param Name The path of the file to open, relative or absolute. 949/// @param ResultFD If the file could be opened successfully, its descriptor 950/// is stored in this location. Otherwise, this is set to -1. 951/// @param Disp Value specifying the existing-file behavior. 952/// @param Access Value specifying whether to open the file in read, write, or 954/// @param Flags Additional flags. 955/// @param Mode The access permissions of the file, represented in octal. 956/// @returns errc::success if \a Name has been opened, otherwise a 957/// platform-specific error_code. 962/// @brief Opens a file with the specified creation disposition, access mode, 963/// and flags and returns a platform-specific file object. 965/// The caller is responsible for closing the file object once they are 968/// @param Name The path of the file to open, relative or absolute. 969/// @param Disp Value specifying the existing-file behavior. 970/// @param Access Value specifying whether to open the file in read, write, or 972/// @param Flags Additional flags. 973/// @param Mode The access permissions of the file, represented in octal. 974/// @returns errc::success if \a Name has been opened, otherwise a 975/// platform-specific error_code. 980/// Converts from a Posix file descriptor number to a native file handle. 981/// On Windows, this retreives the underlying handle. On non-Windows, this is a 989/// Return an open handle to standard in. On Unix, this is typically FD 0. 990/// Returns kInvalidFile when the stream is closed. 993/// Return an open handle to standard out. On Unix, this is typically FD 1. 994/// Returns kInvalidFile when the stream is closed. 997/// Return an open handle to standard error. On Unix, this is typically FD 2. 998/// Returns kInvalidFile when the stream is closed. 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. 1005/// @param FileHandle File to read from. 1006/// @param Buf Buffer to read into. 1007/// @returns The number of bytes read, or error. 1010/// Default chunk size for \a readNativeFileToEOF(). 1013/// Reads from \p FileHandle until EOF, appending to \p Buffer in chunks of 1014/// size \p ChunkSize. 1016/// This calls \a readNativeFile() in a loop. On Error, previous chunks that 1017/// were read successfully are left in \p Buffer and returned. 1019/// Note: For reading the final chunk at EOF, \p Buffer's capacity needs extra 1020/// storage of \p ChunkSize. 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. 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 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. 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 1046/// The caller is responsible for closing the file descriptor once they are 1047/// finished with it. 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. 1057inline std::error_code
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 1068/// The caller is responsible for closing the freeing the file once they are 1069/// finished with it. 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. 1080unsignedMode = 0666) {
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 1088/// The caller is responsible for closing the file descriptor once they are 1089/// finished with it. 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. 1102unsignedMode = 0666) {
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 1110/// The caller is responsible for closing the freeing the file once they are 1111/// finished with it. 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. 1122unsignedMode = 0666) {
1126/// @brief Opens the file with the given name in a read-only mode, returning 1127/// its open file descriptor. 1129/// The caller is responsible for closing the file descriptor once they are 1130/// finished with it. 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 1138/// @returns errc::success if \a Name has been opened, otherwise a 1139/// platform-specific error_code. 1144/// @brief Opens the file with the given name in a read-only mode, returning 1145/// its open file descriptor. 1147/// The caller is responsible for closing the freeing the file once they are 1148/// finished with it. 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 1154/// @returns a platform-specific file descriptor if \a Name has been opened, 1155/// otherwise an error object. 1160/// Try to locks the file during the specified time. 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. 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 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. 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 1183 std::chrono::milliseconds Timeout = std::chrono::milliseconds(0));
1187/// This function acts as @ref tryLockFile but it waits infinitely. 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. 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 1201/// @param F On input, this is the file to close. On output, the file is 1202/// set to kInvalidFile. 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. 1209/// @brief Change ownership of a file. 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. 1218/// RAII class that facilitates file locking. 1220int FD;
///< Locked file handle. 1243return std::error_code();
1249/// Get disk space usage information. 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. 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. 1260/// This class represents a memory mapped file. It is based on 1261/// boost::iostreams::mapped_file. 1265readonly,
///< May only access map via const_data as read only. 1266readwrite,
///< May access map via data and modify it. Written to path. 1267priv///< May modify via data, but changes are lost on destruction. 1271 /// Platform-specific mapping state. 1273void *Mapping =
nullptr;
1281 Mapping = Copied.Mapping;
1283 FileHandle = Copied.FileHandle;
1303 moveFromImpl(Moved);
1310 /// \param fd An open file descriptor to map. Does not take ownership of fd. 1312 std::error_code &ec);
1316 /// Check if this is a valid mapping. 1317explicitoperatorbool()
const{
return Mapping; }
1329 /// Get a const view of the data. Modifying this memory has undefined 1333 /// \returns The minimum alignment offset must be. 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. 1346/// directory_entry - A single entry in a directory. 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. 1355bool FollowSymlinks =
true;
// Affects the behavior of status(). 1362 : Path(Path.str()),
Type(
Type), FollowSymlinks(FollowSymlinks),
1370const 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. 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. 1401 /// Keeps state for the directory_iterator. 1411}
// end namespace detail 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. 1417 std::shared_ptr<detail::DirIterState> State;
1418bool FollowSymlinks =
true;
1422bool follow_symlinks =
true)
1423 : FollowSymlinks(follow_symlinks) {
1424 State = std::make_shared<detail::DirIterState>();
1427 *State, path.
toStringRef(path_storage), FollowSymlinks);
1431bool follow_symlinks =
true)
1432 : FollowSymlinks(follow_symlinks) {
1433 State = std::make_shared<detail::DirIterState>();
1435 *State, de.
path(), FollowSymlinks);
1438 /// Construct end iterator. 1441// No operator++ because we need error_code. 1443 ec = directory_iterator_increment(*State);
1451if (State ==
RHS.State)
1457return State->CurrentEntry ==
RHS.State->CurrentEntry;
1461return !(*
this ==
RHS);
1467 /// Keeps state for the recursive_directory_iterator. 1474}
// end namespace detail 1476/// recursive_directory_iterator - Same as directory_iterator except for it 1477/// recurses down into child directories. 1479 std::shared_ptr<detail::RecDirIterState> State;
1485bool follow_symlinks =
true)
1486 : State(
std::make_shared<
detail::RecDirIterState>()),
1487 Follow(follow_symlinks) {
1493// No operator++ because we need error_code. 1497if (State->HasNoPushRequest)
1498 State->HasNoPushRequest =
false;
1502// Resolve the symlink: is it a directory to recurse into? 1506// Otherwise broken symlink, and we'll continue. 1509 State->Stack.push_back(
1511if (State->Stack.back() != end_itr) {
1515 State->Stack.pop_back();
1519while (!State->Stack.empty()
1520 && State->Stack.back().increment(ec) == end_itr) {
1521 State->Stack.pop_back();
1525// Check if we are done. If so, create an end iterator. 1526if (State->Stack.empty())
1536 /// Gets the current level. Starting path is at level 0. 1539 /// Returns true if no_push has been called for this directory_entry. 1543 /// Goes up one level if Level > 0. 1545assert(State &&
"Cannot pop an end iterator!");
1546assert(State->Level > 0 &&
"Cannot pop an iterator with level < 1");
1553 State->Stack.pop_back();
1555 }
while (!State->Stack.empty()
1556 && State->Stack.back().increment(ec) == end_itr);
1558// Check if we are done. If so, create an end iterator. 1559if (State->Stack.empty())
1563 /// Does not go down into the current directory_entry. 1567return State ==
RHS.State;
1571return !(*
this ==
RHS);
1578}
// end namespace sys 1579}
// end namespace llvm 1581#endif// LLVM_SUPPORT_FILESYSTEM_H BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Provides ErrorOr<T> smart pointer.
amode Optimize addressing mode
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
Represents either an error or a value T.
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
The instances of the Type class are immutable: once they are created, they are never changed.
A raw_ostream that writes to a file descriptor.
RAII class that facilitates file locking.
FileLocker & operator=(FileLocker &&L)
FileLocker(const FileLocker &L)=delete
FileLocker & operator=(const FileLocker &L)=delete
FileLocker(FileLocker &&L)
Represents a temporary file.
TempFile & operator=(TempFile &&Other)
static Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write, OpenFlags ExtraFlags=OF_None)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Represents the result of a call to directory_iterator::status().
basic_file_status(file_type Type, perms Perms, time_t ATime, uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec, uid_t UID, gid_t GID, off_t Size)
void permissions(perms p)
uint32_t fs_st_mtime_nsec
basic_file_status()=default
uint32_t fs_st_atime_nsec
uint32_t getGroup() const
perms permissions() const
TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
basic_file_status(file_type Type)
TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
directory_entry - A single entry in a directory.
directory_entry(const Twine &Path, bool FollowSymlinks=true, file_type Type=file_type::type_unknown, basic_file_status Status=basic_file_status())
ErrorOr< basic_file_status > status() const
bool operator>=(const directory_entry &RHS) const
bool operator<(const directory_entry &RHS) const
bool operator<=(const directory_entry &RHS) const
bool operator==(const directory_entry &RHS) const
bool operator!=(const directory_entry &RHS) const
bool operator>(const directory_entry &RHS) const
const std::string & path() const
directory_entry()=default
void replace_filename(const Twine &Filename, file_type Type, basic_file_status Status=basic_file_status())
directory_iterator - Iterates through the entries in path.
bool operator!=(const directory_iterator &RHS) const
directory_iterator(const directory_entry &de, std::error_code &ec, bool follow_symlinks=true)
directory_iterator(const Twine &path, std::error_code &ec, bool follow_symlinks=true)
directory_iterator()=default
Construct end iterator.
const directory_entry & operator*() const
directory_iterator & increment(std::error_code &ec)
bool operator==(const directory_iterator &RHS) const
const directory_entry * operator->() const
Represents the result of a call to sys::fs::status().
uint32_t getLinkCount() const
UniqueID getUniqueID() const
file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino, time_t ATime, uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec, uid_t UID, gid_t GID, off_t Size)
friend bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
file_status(file_type Type)
This class represents a memory mapped file.
mapped_file_region(mapped_file_region &&Moved)
mapped_file_region()=default
@ priv
May modify via data, but changes are lost on destruction.
@ readonly
May only access map via const_data as read only.
@ readwrite
May access map via data and modify it. Written to path.
mapped_file_region & operator=(mapped_file_region &&Moved)
mapped_file_region(sys::fs::file_t fd, mapmode mode, size_t length, uint64_t offset, std::error_code &ec)
const char * const_data() const
Get a const view of the data.
mapped_file_region(const mapped_file_region &)=delete
mapped_file_region & operator=(const mapped_file_region &)=delete
recursive_directory_iterator - Same as directory_iterator except for it recurses down into child dire...
void pop()
Goes up one level if Level > 0.
bool operator==(const recursive_directory_iterator &RHS) const
void no_push()
Does not go down into the current directory_entry.
int level() const
Gets the current level. Starting path is at level 0.
const directory_entry * operator->() const
recursive_directory_iterator()=default
recursive_directory_iterator & increment(std::error_code &ec)
recursive_directory_iterator(const Twine &path, std::error_code &ec, bool follow_symlinks=true)
const directory_entry & operator*() const
bool no_push_request() const
Returns true if no_push has been called for this directory_entry.
bool operator!=(const recursive_directory_iterator &RHS) const
std::error_code directory_iterator_construct(DirIterState &, StringRef, bool)
std::error_code directory_iterator_destruct(DirIterState &)
std::error_code directory_iterator_increment(DirIterState &)
std::error_code unlockFile(int FD)
Unlock the file.
std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
bool is_regular_file(const basic_file_status &status)
Does status represent a regular file?
bool is_symlink_file(const basic_file_status &status)
Does status represent a symlink file?
perms operator&(perms l, perms r)
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
void make_absolute(const Twine ¤t_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
perms operator|(perms l, perms r)
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
const file_t kInvalidFile
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
Error readNativeFileToEOF(file_t FileHandle, SmallVectorImpl< char > &Buffer, ssize_t ChunkSize=DefaultReadChunkSize)
Reads from FileHandle until EOF, appending to Buffer in chunks of size ChunkSize.
std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0))
Try to locks the file during the specified time.
perms & operator&=(perms &l, perms r)
Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
ErrorOr< perms > getPermissions(const Twine &Path)
Get file permissions.
bool can_write(const Twine &Path)
Can we write this file?
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
std::error_code openFile(const Twine &Name, int &ResultFD, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a file descr...
std::error_code resize_file_before_mapping_readwrite(int FD, uint64_t Size)
Resize FD to Size before mapping mapped_file_region::readwrite.
std::error_code closeFile(file_t &F)
Close the file object.
std::error_code getPotentiallyUniqueFileName(const Twine &Model, SmallVectorImpl< char > &ResultPath)
Get a unique name, not currently exisiting in the filesystem.
file_t getStdoutHandle()
Return an open handle to standard out.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
bool is_other(const basic_file_status &status)
Does this status represent something that exists but is not a directory or regular file?
std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
std::error_code getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix, SmallVectorImpl< char > &ResultPath)
Get a unique temporary file name, not currently exisiting in the filesystem.
perms & operator|=(perms &l, perms r)
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
bool exists(const basic_file_status &status)
Does file exist?
@ OF_Delete
The returned handle can be used for deleting the file.
@ OF_ChildInherit
When a child process is launched, this file should remain open in the child process.
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
@ OF_CRLF
The file should use a carriage linefeed '\r '.
@ OF_UpdateAtime
Force files Atime to be updated on access.
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
@ OF_Append
The file should be opened in append mode.
file_type
An enumeration for the file system's view of the type.
std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group)
Change ownership of a file.
Expected< file_t > openNativeFileForWrite(const Twine &Name, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
std::error_code getUniqueID(const Twine Path, UniqueID &Result)
std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None, unsigned Mode=all_read|all_write)
Create a uniquely named file.
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
std::error_code lockFile(int FD)
Lock the file.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
@ CD_OpenExisting
CD_OpenExisting - When opening a file:
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
@ CD_CreateNew
CD_CreateNew - When opening a file:
std::error_code set_current_path(const Twine &path)
Set the current path.
Expected< file_t > openNativeFileForReadWrite(const Twine &Name, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
Expected< file_t > openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a platform-s...
void createUniquePath(const Twine &Model, SmallVectorImpl< char > &ResultPath, bool MakeAbsolute)
Create a potentially unique file name but does not create it.
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
file_t getStderrHandle()
Return an open handle to standard error.
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
bool status_known(const basic_file_status &s)
Is status available?
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
file_type get_file_type(const Twine &Path, bool Follow=true)
Does status represent a directory?
std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl< char > &ResultPath)
file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
bool can_execute(const Twine &Path)
Can we execute this file?
unsigned getUmask()
Get file creation mode mask of the process.
ErrorOr< MD5::MD5Result > md5_contents(int FD)
Compute an MD5 hash of a file's contents.
Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
file_t getStdinHandle()
Return an open handle to standard in.
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
This is an optimization pass for GlobalISel generic memory operations.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Implement std::hash so that hash_code can be used in STL containers.
Keeps state for the directory_iterator.
directory_entry CurrentEntry
Keeps state for the recursive_directory_iterator.
std::vector< directory_iterator > Stack
space_info - Self explanatory.