1//===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file declares the llvm::sys::fs namespace. It is designed after 11// TR2/boost filesystem (v3), but modified to remove exception handling and the 12// path class. 13// 14// All functions return an error_code and their actual work via the last out 15// argument. The out argument is defined if and only if errc::success is 16// returned. A function may return any error code in the generic or system 17// category. However, they shall be equivalent to any error conditions listed 18// in each functions respective documentation if the condition applies. [ note: 19// this does not guarantee that error_code will be in the set of explicitly 20// listed codes, but it does guarantee that if any of the explicitly listed 21// errors occur, the correct error_code will be used ]. All functions may 22// return errc::not_enough_memory if there is not enough memory to complete the 23// operation. 24// 25//===----------------------------------------------------------------------===// 26 27#ifndef LLVM_SUPPORT_FILESYSTEM_H 28#define LLVM_SUPPORT_FILESYSTEM_H 29 30#include "llvm/ADT/IntrusiveRefCntPtr.h" 31#include "llvm/ADT/SmallString.h" 32#include "llvm/ADT/StringRef.h" 33#include "llvm/ADT/Twine.h" 34#include "llvm/Support/Chrono.h" 35#include "llvm/Support/ErrorHandling.h" 36#include "llvm/Support/ErrorOr.h" 37#include <cassert> 38#include <cstdint> 39#include <ctime> 40#include <stack> 41#include <string> 42#include <system_error> 43#include <tuple> 44#include <vector> 45 46#ifdef HAVE_SYS_STAT_H 47#include <sys/stat.h> 48#endif 49 50namespace llvm { 51namespace sys { 52namespace fs { 53 54/// An enumeration for the file system's view of the type. 55enum class file_type { 56 status_error, 57 file_not_found, 58 regular_file, 59 directory_file, 60 symlink_file, 61 block_file, 62 character_file, 63 fifo_file, 64 socket_file, 65 type_unknown 66}; 67 68/// space_info - Self explanatory. 69struct space_info { 70 uint64_t capacity; 71 uint64_t free; 72 uint64_t available; 73}; 74 75enum perms { 76 no_perms = 0, 77 owner_read = 0400, 78 owner_write = 0200, 79 owner_exe = 0100, 80 owner_all = owner_read | owner_write | owner_exe, 81 group_read = 040, 82 group_write = 020, 83 group_exe = 010, 84 group_all = group_read | group_write | group_exe, 85 others_read = 04, 86 others_write = 02, 87 others_exe = 01, 88 others_all = others_read | others_write | others_exe, 89 all_read = owner_read | group_read | others_read, 90 all_write = owner_write | group_write | others_write, 91 all_exe = owner_exe | group_exe | others_exe, 92 all_all = owner_all | group_all | others_all, 93 set_uid_on_exe = 04000, 94 set_gid_on_exe = 02000, 95 sticky_bit = 01000, 96 perms_not_known = 0xFFFF 97}; 98 99// Helper functions so that you can use & and | to manipulate perms bits: 100inline perms operator|(perms l, perms r) { 101 return static_cast<perms>(static_cast<unsigned short>(l) | 102 static_cast<unsigned short>(r)); 103} 104inline perms operator&(perms l, perms r) { 105 return static_cast<perms>(static_cast<unsigned short>(l) & 106 static_cast<unsigned short>(r)); 107} 108inline perms &operator|=(perms &l, perms r) { 109 l = l | r; 110 return l; 111} 112inline perms &operator&=(perms &l, perms r) { 113 l = l & r; 114 return l; 115} 116inline perms operator~(perms x) { 117 return static_cast<perms>(~static_cast<unsigned short>(x)); 118} 119 120class UniqueID { 121 uint64_t Device; 122 uint64_t File; 123 124public: 125 UniqueID() = default; 126 UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {} 127 128 bool operator==(const UniqueID &Other) const { 129 return Device == Other.Device && File == Other.File; 130 } 131 bool operator!=(const UniqueID &Other) const { return !(*this == Other); } 132 bool operator<(const UniqueID &Other) const { 133 return std::tie(Device, File) < std::tie(Other.Device, Other.File); 134 } 135 136 uint64_t getDevice() const { return Device; } 137 uint64_t getFile() const { return File; } 138}; 139 140/// file_status - Represents the result of a call to stat and friends. It has 141/// a platform-specific member to store the result. 142class file_status 143{ 144 #if defined(LLVM_ON_UNIX) 145 dev_t fs_st_dev; 146 ino_t fs_st_ino; 147 time_t fs_st_atime; 148 time_t fs_st_mtime; 149 uid_t fs_st_uid; 150 gid_t fs_st_gid; 151 off_t fs_st_size; 152 #elif defined (LLVM_ON_WIN32) 153 uint32_t LastAccessedTimeHigh; 154 uint32_t LastAccessedTimeLow; 155 uint32_t LastWriteTimeHigh; 156 uint32_t LastWriteTimeLow; 157 uint32_t VolumeSerialNumber; 158 uint32_t FileSizeHigh; 159 uint32_t FileSizeLow; 160 uint32_t FileIndexHigh; 161 uint32_t FileIndexLow; 162 #endif 163 friend bool equivalent(file_status A, file_status B); 164 file_type Type; 165 perms Perms; 166 167public: 168 #if defined(LLVM_ON_UNIX) 169 file_status() 170 : fs_st_dev(0), fs_st_ino(0), fs_st_atime(0), fs_st_mtime(0), 171 fs_st_uid(0), fs_st_gid(0), fs_st_size(0), 172 Type(file_type::status_error), Perms(perms_not_known) {} 173 174 file_status(file_type Type) 175 : fs_st_dev(0), fs_st_ino(0), fs_st_atime(0), fs_st_mtime(0), 176 fs_st_uid(0), fs_st_gid(0), fs_st_size(0), Type(Type), 177 Perms(perms_not_known) {} 178 179 file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t ATime, 180 time_t MTime, uid_t UID, gid_t GID, off_t Size) 181 : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_atime(ATime), fs_st_mtime(MTime), 182 fs_st_uid(UID), fs_st_gid(GID), fs_st_size(Size), Type(Type), 183 Perms(Perms) {} 184 #elif defined(LLVM_ON_WIN32) 185 file_status() 186 : LastAccessedTimeHigh(0), LastAccessedTimeLow(0), LastWriteTimeHigh(0), 187 LastWriteTimeLow(0), VolumeSerialNumber(0), FileSizeHigh(0), 188 FileSizeLow(0), FileIndexHigh(0), FileIndexLow(0), 189 Type(file_type::status_error), Perms(perms_not_known) {} 190 191 file_status(file_type Type) 192 : LastAccessedTimeHigh(0), LastAccessedTimeLow(0), LastWriteTimeHigh(0), 193 LastWriteTimeLow(0), VolumeSerialNumber(0), FileSizeHigh(0), 194 FileSizeLow(0), FileIndexHigh(0), FileIndexLow(0), Type(Type), 195 Perms(perms_not_known) {} 196 197 file_status(file_type Type, uint32_t LastAccessTimeHigh, 198 uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh, 199 uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber, 200 uint32_t FileSizeHigh, uint32_t FileSizeLow, 201 uint32_t FileIndexHigh, uint32_t FileIndexLow) 202 : LastAccessedTimeHigh(LastAccessTimeHigh), LastAccessedTimeLow(LastAccessTimeLow), 203 LastWriteTimeHigh(LastWriteTimeHigh), 204 LastWriteTimeLow(LastWriteTimeLow), 205 VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh), 206 FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh), 207 FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {} 208 #endif 209 210 // getters 211 file_type type() const { return Type; } 212 perms permissions() const { return Perms; } 213 TimePoint<> getLastAccessedTime() const; 214 TimePoint<> getLastModificationTime() const; 215 UniqueID getUniqueID() const; 216 217 #if defined(LLVM_ON_UNIX) 218 uint32_t getUser() const { return fs_st_uid; } 219 uint32_t getGroup() const { return fs_st_gid; } 220 uint64_t getSize() const { return fs_st_size; } 221 #elif defined (LLVM_ON_WIN32) 222 uint32_t getUser() const { 223 return 9999; // Not applicable to Windows, so... 224 } 225 uint32_t getGroup() const { 226 return 9999; // Not applicable to Windows, so... 227 } 228 uint64_t getSize() const { 229 return (uint64_t(FileSizeHigh) << 32) + FileSizeLow; 230 } 231 #endif 232 233 // setters 234 void type(file_type v) { Type = v; } 235 void permissions(perms p) { Perms = p; } 236}; 237 238/// file_magic - An "enum class" enumeration of file types based on magic (the first 239/// N bytes of the file). 240struct file_magic { 241 enum Impl { 242 unknown = 0, ///< Unrecognized file 243 bitcode, ///< Bitcode file 244 archive, ///< ar style archive file 245 elf, ///< ELF Unknown type 246 elf_relocatable, ///< ELF Relocatable object file 247 elf_executable, ///< ELF Executable image 248 elf_shared_object, ///< ELF dynamically linked shared lib 249 elf_core, ///< ELF core image 250 macho_object, ///< Mach-O Object file 251 macho_executable, ///< Mach-O Executable 252 macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM 253 macho_core, ///< Mach-O Core File 254 macho_preload_executable, ///< Mach-O Preloaded Executable 255 macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib 256 macho_dynamic_linker, ///< The Mach-O dynamic linker 257 macho_bundle, ///< Mach-O Bundle file 258 macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub 259 macho_dsym_companion, ///< Mach-O dSYM companion file 260 macho_kext_bundle, ///< Mach-O kext bundle file 261 macho_universal_binary, ///< Mach-O universal binary 262 coff_cl_gl_object, ///< Microsoft cl.exe's intermediate code file 263 coff_object, ///< COFF object file 264 coff_import_library, ///< COFF import library 265 pecoff_executable, ///< PECOFF executable file 266 windows_resource, ///< Windows compiled resource file (.rc) 267 wasm_object ///< WebAssembly Object file 268 }; 269 270 bool is_object() const { 271 return V != unknown; 272 } 273 274 file_magic() : V(unknown) {} 275 file_magic(Impl V) : V(V) {} 276 operator Impl() const { return V; } 277 278private: 279 Impl V; 280}; 281 282/// @} 283/// @name Physical Operators 284/// @{ 285 286/// @brief Make \a path an absolute path. 287/// 288/// Makes \a path absolute using the \a current_directory if it is not already. 289/// An empty \a path will result in the \a current_directory. 290/// 291/// /absolute/path => /absolute/path 292/// relative/../path => <current-directory>/relative/../path 293/// 294/// @param path A path that is modified to be an absolute path. 295/// @returns errc::success if \a path has been made absolute, otherwise a 296/// platform-specific error_code. 297std::error_code make_absolute(const Twine ¤t_directory, 298 SmallVectorImpl<char> &path); 299 300/// @brief Make \a path an absolute path. 301/// 302/// Makes \a path absolute using the current directory if it is not already. An 303/// empty \a path will result in the current directory. 304/// 305/// /absolute/path => /absolute/path 306/// relative/../path => <current-directory>/relative/../path 307/// 308/// @param path A path that is modified to be an absolute path. 309/// @returns errc::success if \a path has been made absolute, otherwise a 310/// platform-specific error_code. 311std::error_code make_absolute(SmallVectorImpl<char> &path); 312 313/// @brief Create all the non-existent directories in path. 314/// 315/// @param path Directories to create. 316/// @returns errc::success if is_directory(path), otherwise a platform 317/// specific error_code. If IgnoreExisting is false, also returns 318/// error if the directory already existed. 319std::error_code create_directories(const Twine &path, 320 bool IgnoreExisting = true, 321 perms Perms = owner_all | group_all); 322 323/// @brief Create the directory in path. 324/// 325/// @param path Directory to create. 326/// @returns errc::success if is_directory(path), otherwise a platform 327/// specific error_code. If IgnoreExisting is false, also returns 328/// error if the directory already existed. 329std::error_code create_directory(const Twine &path, bool IgnoreExisting = true, 330 perms Perms = owner_all | group_all); 331 332/// @brief Create a link from \a from to \a to. 333/// 334/// The link may be a soft or a hard link, depending on the platform. The caller 335/// may not assume which one. Currently on windows it creates a hard link since 336/// soft links require extra privileges. On unix, it creates a soft link since 337/// hard links don't work on SMB file systems. 338/// 339/// @param to The path to hard link to. 340/// @param from The path to hard link from. This is created. 341/// @returns errc::success if the link was created, otherwise a platform 342/// specific error_code. 343std::error_code create_link(const Twine &to, const Twine &from); 344 345/// Create a hard link from \a from to \a to, or return an error. 346/// 347/// @param to The path to hard link to. 348/// @param from The path to hard link from. This is created. 349/// @returns errc::success if the link was created, otherwise a platform 350/// specific error_code. 351std::error_code create_hard_link(const Twine &to, const Twine &from); 352 353/// @brief Get the current path. 354/// 355/// @param result Holds the current path on return. 356/// @returns errc::success if the current path has been stored in result, 357/// otherwise a platform-specific error_code. 358std::error_code current_path(SmallVectorImpl<char> &result); 359 360/// @brief Remove path. Equivalent to POSIX remove(). 361/// 362/// @param path Input path. 363/// @returns errc::success if path has been removed or didn't exist, otherwise a 364/// platform-specific error code. If IgnoreNonExisting is false, also 365/// returns error if the file didn't exist. 366std::error_code remove(const Twine &path, bool IgnoreNonExisting = true); 367 368/// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename(). 369/// 370/// @param from The path to rename from. 371/// @param to The path to rename to. This is created. 372std::error_code rename(const Twine &from, const Twine &to); 373 374/// @brief Copy the contents of \a From to \a To. 375/// 376/// @param From The path to copy from. 377/// @param To The path to copy to. This is created. 378std::error_code copy_file(const Twine &From, const Twine &To); 379 380/// @brief Resize path to size. File is resized as if by POSIX truncate(). 381/// 382/// @param FD Input file descriptor. 383/// @param Size Size to resize to. 384/// @returns errc::success if \a path has been resized to \a size, otherwise a 385/// platform-specific error_code. 386std::error_code resize_file(int FD, uint64_t Size); 387 388/// @} 389/// @name Physical Observers 390/// @{ 391 392/// @brief Does file exist? 393/// 394/// @param status A file_status previously returned from stat. 395/// @returns True if the file represented by status exists, false if it does 396/// not. 397bool exists(file_status status); 398 399enum class AccessMode { Exist, Write, Execute }; 400 401/// @brief Can the file be accessed? 402/// 403/// @param Path Input path. 404/// @returns errc::success if the path can be accessed, otherwise a 405/// platform-specific error_code. 406std::error_code access(const Twine &Path, AccessMode Mode); 407 408/// @brief Does file exist? 409/// 410/// @param Path Input path. 411/// @returns True if it exists, false otherwise. 412inline bool exists(const Twine &Path) { 413 return !access(Path, AccessMode::Exist); 414} 415 416/// @brief Can we execute this file? 417/// 418/// @param Path Input path. 419/// @returns True if we can execute it, false otherwise. 420bool can_execute(const Twine &Path); 421 422/// @brief Can we write this file? 423/// 424/// @param Path Input path. 425/// @returns True if we can write to it, false otherwise. 426inline bool can_write(const Twine &Path) { 427 return !access(Path, AccessMode::Write); 428} 429 430/// @brief Do file_status's represent the same thing? 431/// 432/// @param A Input file_status. 433/// @param B Input file_status. 434/// 435/// assert(status_known(A) || status_known(B)); 436/// 437/// @returns True if A and B both represent the same file system entity, false 438/// otherwise. 439bool equivalent(file_status A, file_status B); 440 441/// @brief Do paths represent the same thing? 442/// 443/// assert(status_known(A) || status_known(B)); 444/// 445/// @param A Input path A. 446/// @param B Input path B. 447/// @param result Set to true if stat(A) and stat(B) have the same device and 448/// inode (or equivalent). 449/// @returns errc::success if result has been successfully set, otherwise a 450/// platform-specific error_code. 451std::error_code equivalent(const Twine &A, const Twine &B, bool &result); 452 453/// @brief Simpler version of equivalent for clients that don't need to 454/// differentiate between an error and false. 455inline bool equivalent(const Twine &A, const Twine &B) { 456 bool result; 457 return !equivalent(A, B, result) && result; 458} 459 460/// @brief Does status represent a directory? 461/// 462/// @param status A file_status previously returned from status. 463/// @returns status.type() == file_type::directory_file. 464bool is_directory(file_status status); 465 466/// @brief Is path a directory? 467/// 468/// @param path Input path. 469/// @param result Set to true if \a path is a directory, false if it is not. 470/// Undefined otherwise. 471/// @returns errc::success if result has been successfully set, otherwise a 472/// platform-specific error_code. 473std::error_code is_directory(const Twine &path, bool &result); 474 475/// @brief Simpler version of is_directory for clients that don't need to 476/// differentiate between an error and false. 477inline bool is_directory(const Twine &Path) { 478 bool Result; 479 return !is_directory(Path, Result) && Result; 480} 481 482/// @brief Does status represent a regular file? 483/// 484/// @param status A file_status previously returned from status. 485/// @returns status_known(status) && status.type() == file_type::regular_file. 486bool is_regular_file(file_status status); 487 488/// @brief Is path a regular file? 489/// 490/// @param path Input path. 491/// @param result Set to true if \a path is a regular file, false if it is not. 492/// Undefined otherwise. 493/// @returns errc::success if result has been successfully set, otherwise a 494/// platform-specific error_code. 495std::error_code is_regular_file(const Twine &path, bool &result); 496 497/// @brief Simpler version of is_regular_file for clients that don't need to 498/// differentiate between an error and false. 499inline bool is_regular_file(const Twine &Path) { 500 bool Result; 501 if (is_regular_file(Path, Result)) 502 return false; 503 return Result; 504} 505 506/// @brief Does this status represent something that exists but is not a 507/// directory, regular file, or symlink? 508/// 509/// @param status A file_status previously returned from status. 510/// @returns exists(s) && !is_regular_file(s) && !is_directory(s) 511bool is_other(file_status status); 512 513/// @brief Is path something that exists but is not a directory, 514/// regular file, or symlink? 515/// 516/// @param path Input path. 517/// @param result Set to true if \a path exists, but is not a directory, regular 518/// file, or a symlink, false if it does not. Undefined otherwise. 519/// @returns errc::success if result has been successfully set, otherwise a 520/// platform-specific error_code. 521std::error_code is_other(const Twine &path, bool &result); 522 523/// @brief Get file status as if by POSIX stat(). 524/// 525/// @param path Input path. 526/// @param result Set to the file status. 527/// @returns errc::success if result has been successfully set, otherwise a 528/// platform-specific error_code. 529std::error_code status(const Twine &path, file_status &result); 530 531/// @brief A version for when a file descriptor is already available. 532std::error_code status(int FD, file_status &Result); 533 534/// @brief Get file size. 535/// 536/// @param Path Input path. 537/// @param Result Set to the size of the file in \a Path. 538/// @returns errc::success if result has been successfully set, otherwise a 539/// platform-specific error_code. 540inline std::error_code file_size(const Twine &Path, uint64_t &Result) { 541 file_status Status; 542 std::error_code EC = status(Path, Status); 543 if (EC) 544 return EC; 545 Result = Status.getSize(); 546 return std::error_code(); 547} 548 549/// @brief Set the file modification and access time. 550/// 551/// @returns errc::success if the file times were successfully set, otherwise a 552/// platform-specific error_code or errc::function_not_supported on 553/// platforms where the functionality isn't available. 554std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time); 555 556/// @brief Is status available? 557/// 558/// @param s Input file status. 559/// @returns True if status() != status_error. 560bool status_known(file_status s); 561 562/// @brief Is status available? 563/// 564/// @param path Input path. 565/// @param result Set to true if status() != status_error. 566/// @returns errc::success if result has been successfully set, otherwise a 567/// platform-specific error_code. 568std::error_code status_known(const Twine &path, bool &result); 569 570/// @brief Create a uniquely named file. 571/// 572/// Generates a unique path suitable for a temporary file and then opens it as a 573/// file. The name is based on \a model with '%' replaced by a random char in 574/// [0-9a-f]. If \a model is not an absolute path, the temporary file will be 575/// created in the current directory. 576/// 577/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s 578/// 579/// This is an atomic operation. Either the file is created and opened, or the 580/// file system is left untouched. 581/// 582/// The intended use is for files that are to be kept, possibly after 583/// renaming them. For example, when running 'clang -c foo.o', the file can 584/// be first created as foo-abc123.o and then renamed. 585/// 586/// @param Model Name to base unique path off of. 587/// @param ResultFD Set to the opened file's file descriptor. 588/// @param ResultPath Set to the opened file's absolute path. 589/// @returns errc::success if Result{FD,Path} have been successfully set, 590/// otherwise a platform-specific error_code. 591std::error_code createUniqueFile(const Twine &Model, int &ResultFD, 592 SmallVectorImpl<char> &ResultPath, 593 unsigned Mode = all_read | all_write); 594 595/// @brief Simpler version for clients that don't want an open file. 596std::error_code createUniqueFile(const Twine &Model, 597 SmallVectorImpl<char> &ResultPath); 598 599/// @brief Create a file in the system temporary directory. 600/// 601/// The filename is of the form prefix-random_chars.suffix. Since the directory 602/// is not know to the caller, Prefix and Suffix cannot have path separators. 603/// The files are created with mode 0600. 604/// 605/// This should be used for things like a temporary .s that is removed after 606/// running the assembler. 607std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, 608 int &ResultFD, 609 SmallVectorImpl<char> &ResultPath); 610 611/// @brief Simpler version for clients that don't want an open file. 612std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, 613 SmallVectorImpl<char> &ResultPath); 614 615std::error_code createUniqueDirectory(const Twine &Prefix, 616 SmallVectorImpl<char> &ResultPath); 617 618/// @brief Fetch a path to an open file, as specified by a file descriptor 619/// 620/// @param FD File descriptor to a currently open file 621/// @param ResultPath The buffer into which to write the path 622std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath); 623 624enum OpenFlags : unsigned { 625 F_None = 0, 626 627 /// F_Excl - When opening a file, this flag makes raw_fd_ostream 628 /// report an error if the file already exists. 629 F_Excl = 1, 630 631 /// F_Append - When opening a file, if it already exists append to the 632 /// existing file instead of returning an error. This may not be specified 633 /// with F_Excl. 634 F_Append = 2, 635 636 /// The file should be opened in text mode on platforms that make this 637 /// distinction. 638 F_Text = 4, 639 640 /// Open the file for read and write. 641 F_RW = 8 642}; 643 644inline OpenFlags operator|(OpenFlags A, OpenFlags B) { 645 return OpenFlags(unsigned(A) | unsigned(B)); 646} 647 648inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) { 649 A = A | B; 650 return A; 651} 652 653std::error_code openFileForWrite(const Twine &Name, int &ResultFD, 654 OpenFlags Flags, unsigned Mode = 0666); 655 656std::error_code openFileForRead(const Twine &Name, int &ResultFD, 657 SmallVectorImpl<char> *RealPath = nullptr); 658 659/// @brief Identify the type of a binary file based on how magical it is. 660file_magic identify_magic(StringRef magic); 661 662/// @brief Get and identify \a path's type based on its content. 663/// 664/// @param path Input path. 665/// @param result Set to the type of file, or file_magic::unknown. 666/// @returns errc::success if result has been successfully set, otherwise a 667/// platform-specific error_code. 668std::error_code identify_magic(const Twine &path, file_magic &result); 669 670std::error_code getUniqueID(const Twine Path, UniqueID &Result); 671 672/// @brief Get disk space usage information. 673/// 674/// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug. 675/// Note: Windows reports results according to the quota allocated to the user. 676/// 677/// @param Path Input path. 678/// @returns a space_info structure filled with the capacity, free, and 679/// available space on the device \a Path is on. A platform specific error_code 680/// is returned on error. 681ErrorOr<space_info> disk_space(const Twine &Path); 682 683/// This class represents a memory mapped file. It is based on 684/// boost::iostreams::mapped_file. 685class mapped_file_region { 686public: 687 enum mapmode { 688 readonly, ///< May only access map via const_data as read only. 689 readwrite, ///< May access map via data and modify it. Written to path. 690 priv ///< May modify via data, but changes are lost on destruction. 691 }; 692 693private: 694 /// Platform-specific mapping state. 695 uint64_t Size; 696 void *Mapping; 697 698 std::error_code init(int FD, uint64_t Offset, mapmode Mode); 699 700public: 701 mapped_file_region() = delete; 702 mapped_file_region(mapped_file_region&) = delete; 703 mapped_file_region &operator =(mapped_file_region&) = delete; 704 705 /// \param fd An open file descriptor to map. mapped_file_region takes 706 /// ownership if closefd is true. It must have been opended in the correct 707 /// mode. 708 mapped_file_region(int fd, mapmode mode, uint64_t length, uint64_t offset, 709 std::error_code &ec); 710 711 ~mapped_file_region(); 712 713 uint64_t size() const; 714 char *data() const; 715 716 /// Get a const view of the data. Modifying this memory has undefined 717 /// behavior. 718 const char *const_data() const; 719 720 /// \returns The minimum alignment offset must be. 721 static int alignment(); 722}; 723 724/// Return the path to the main executable, given the value of argv[0] from 725/// program startup and the address of main itself. In extremis, this function 726/// may fail and return an empty path. 727std::string getMainExecutable(const char *argv0, void *MainExecAddr); 728 729/// @} 730/// @name Iterators 731/// @{ 732 733/// directory_entry - A single entry in a directory. Caches the status either 734/// from the result of the iteration syscall, or the first time status is 735/// called. 736class directory_entry { 737 std::string Path; 738 mutable file_status Status; 739 740public: 741 explicit directory_entry(const Twine &path, file_status st = file_status()) 742 : Path(path.str()) 743 , Status(st) {} 744 745 directory_entry() = default; 746 747 void assign(const Twine &path, file_status st = file_status()) { 748 Path = path.str(); 749 Status = st; 750 } 751 752 void replace_filename(const Twine &filename, file_status st = file_status()); 753 754 const std::string &path() const { return Path; } 755 std::error_code status(file_status &result) const; 756 757 bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; } 758 bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); } 759 bool operator< (const directory_entry& rhs) const; 760 bool operator<=(const directory_entry& rhs) const; 761 bool operator> (const directory_entry& rhs) const; 762 bool operator>=(const directory_entry& rhs) const; 763}; 764 765namespace detail { 766 struct DirIterState; 767 768 std::error_code directory_iterator_construct(DirIterState &, StringRef); 769 std::error_code directory_iterator_increment(DirIterState &); 770 std::error_code directory_iterator_destruct(DirIterState &); 771 772 /// DirIterState - Keeps state for the directory_iterator. It is reference 773 /// counted in order to preserve InputIterator semantics on copy. 774 struct DirIterState : public RefCountedBase<DirIterState> { 775 DirIterState() 776 : IterationHandle(0) {} 777 778 ~DirIterState() { 779 directory_iterator_destruct(*this); 780 } 781 782 intptr_t IterationHandle; 783 directory_entry CurrentEntry; 784 }; 785} // end namespace detail 786 787/// directory_iterator - Iterates through the entries in path. There is no 788/// operator++ because we need an error_code. If it's really needed we can make 789/// it call report_fatal_error on error. 790class directory_iterator { 791 IntrusiveRefCntPtr<detail::DirIterState> State; 792 793public: 794 explicit directory_iterator(const Twine &path, std::error_code &ec) { 795 State = new detail::DirIterState; 796 SmallString<128> path_storage; 797 ec = detail::directory_iterator_construct(*State, 798 path.toStringRef(path_storage)); 799 } 800 801 explicit directory_iterator(const directory_entry &de, std::error_code &ec) { 802 State = new detail::DirIterState; 803 ec = detail::directory_iterator_construct(*State, de.path()); 804 } 805 806 /// Construct end iterator. 807 directory_iterator() : State(nullptr) {} 808 809 // No operator++ because we need error_code. 810 directory_iterator &increment(std::error_code &ec) { 811 ec = directory_iterator_increment(*State); 812 return *this; 813 } 814 815 const directory_entry &operator*() const { return State->CurrentEntry; } 816 const directory_entry *operator->() const { return &State->CurrentEntry; } 817 818 bool operator==(const directory_iterator &RHS) const { 819 if (State == RHS.State) 820 return true; 821 if (!RHS.State) 822 return State->CurrentEntry == directory_entry(); 823 if (!State) 824 return RHS.State->CurrentEntry == directory_entry(); 825 return State->CurrentEntry == RHS.State->CurrentEntry; 826 } 827 828 bool operator!=(const directory_iterator &RHS) const { 829 return !(*this == RHS); 830 } 831 // Other members as required by 832 // C++ Std, 24.1.1 Input iterators [input.iterators] 833}; 834 835namespace detail { 836 /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is 837 /// reference counted in order to preserve InputIterator semantics on copy. 838 struct RecDirIterState : public RefCountedBase<RecDirIterState> { 839 RecDirIterState() 840 : Level(0) 841 , HasNoPushRequest(false) {} 842 843 std::stack<directory_iterator, std::vector<directory_iterator>> Stack; 844 uint16_t Level; 845 bool HasNoPushRequest; 846 }; 847} // end namespace detail 848 849/// recursive_directory_iterator - Same as directory_iterator except for it 850/// recurses down into child directories. 851class recursive_directory_iterator { 852 IntrusiveRefCntPtr<detail::RecDirIterState> State; 853 854public: 855 recursive_directory_iterator() = default; 856 explicit recursive_directory_iterator(const Twine &path, std::error_code &ec) 857 : State(new detail::RecDirIterState) { 858 State->Stack.push(directory_iterator(path, ec)); 859 if (State->Stack.top() == directory_iterator()) 860 State.reset(); 861 } 862 863 // No operator++ because we need error_code. 864 recursive_directory_iterator &increment(std::error_code &ec) { 865 const directory_iterator end_itr; 866 867 if (State->HasNoPushRequest) 868 State->HasNoPushRequest = false; 869 else { 870 file_status st; 871 if ((ec = State->Stack.top()->status(st))) return *this; 872 if (is_directory(st)) { 873 State->Stack.push(directory_iterator(*State->Stack.top(), ec)); 874 if (ec) return *this; 875 if (State->Stack.top() != end_itr) { 876 ++State->Level; 877 return *this; 878 } 879 State->Stack.pop(); 880 } 881 } 882 883 while (!State->Stack.empty() 884 && State->Stack.top().increment(ec) == end_itr) { 885 State->Stack.pop(); 886 --State->Level; 887 } 888 889 // Check if we are done. If so, create an end iterator. 890 if (State->Stack.empty()) 891 State.reset(); 892 893 return *this; 894 } 895 896 const directory_entry &operator*() const { return *State->Stack.top(); } 897 const directory_entry *operator->() const { return &*State->Stack.top(); } 898 899 // observers 900 /// Gets the current level. Starting path is at level 0. 901 int level() const { return State->Level; } 902 903 /// Returns true if no_push has been called for this directory_entry. 904 bool no_push_request() const { return State->HasNoPushRequest; } 905 906 // modifiers 907 /// Goes up one level if Level > 0. 908 void pop() { 909 assert(State && "Cannot pop an end iterator!"); 910 assert(State->Level > 0 && "Cannot pop an iterator with level < 1"); 911 912 const directory_iterator end_itr; 913 std::error_code ec; 914 do { 915 if (ec) 916 report_fatal_error("Error incrementing directory iterator."); 917 State->Stack.pop(); 918 --State->Level; 919 } while (!State->Stack.empty() 920 && State->Stack.top().increment(ec) == end_itr); 921 922 // Check if we are done. If so, create an end iterator. 923 if (State->Stack.empty()) 924 State.reset(); 925 } 926 927 /// Does not go down into the current directory_entry. 928 void no_push() { State->HasNoPushRequest = true; } 929 930 bool operator==(const recursive_directory_iterator &RHS) const { 931 return State == RHS.State; 932 } 933 934 bool operator!=(const recursive_directory_iterator &RHS) const { 935 return !(*this == RHS); 936 } 937 // Other members as required by 938 // C++ Std, 24.1.1 Input iterators [input.iterators] 939}; 940 941/// @} 942 943} // end namespace fs 944} // end namespace sys 945} // end namespace llvm 946 947#endif // LLVM_SUPPORT_FILESYSTEM_H 948