LLVM API Documentation

FileSystem.h
Go to the documentation of this file.
00001 //===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file declares the llvm::sys::fs namespace. It is designed after
00011 // TR2/boost filesystem (v3), but modified to remove exception handling and the
00012 // path class.
00013 //
00014 // All functions return an error_code and their actual work via the last out
00015 // argument. The out argument is defined if and only if errc::success is
00016 // returned. A function may return any error code in the generic or system
00017 // category. However, they shall be equivalent to any error conditions listed
00018 // in each functions respective documentation if the condition applies. [ note:
00019 // this does not guarantee that error_code will be in the set of explicitly
00020 // listed codes, but it does guarantee that if any of the explicitly listed
00021 // errors occur, the correct error_code will be used ]. All functions may
00022 // return errc::not_enough_memory if there is not enough memory to complete the
00023 // operation.
00024 //
00025 //===----------------------------------------------------------------------===//
00026 
00027 #ifndef LLVM_SUPPORT_FILESYSTEM_H
00028 #define LLVM_SUPPORT_FILESYSTEM_H
00029 
00030 #include "llvm/ADT/IntrusiveRefCntPtr.h"
00031 #include "llvm/ADT/SmallString.h"
00032 #include "llvm/ADT/Twine.h"
00033 #include "llvm/Support/DataTypes.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 #include "llvm/Support/TimeValue.h"
00036 #include <ctime>
00037 #include <iterator>
00038 #include <stack>
00039 #include <string>
00040 #include <system_error>
00041 #include <tuple>
00042 #include <vector>
00043 
00044 #ifdef HAVE_SYS_STAT_H
00045 #include <sys/stat.h>
00046 #endif
00047 
00048 namespace llvm {
00049 namespace sys {
00050 namespace fs {
00051 
00052 /// An enumeration for the file system's view of the type.
00053 enum class file_type {
00054   status_error,
00055   file_not_found,
00056   regular_file,
00057   directory_file,
00058   symlink_file,
00059   block_file,
00060   character_file,
00061   fifo_file,
00062   socket_file,
00063   type_unknown
00064 };
00065 
00066 /// space_info - Self explanatory.
00067 struct space_info {
00068   uint64_t capacity;
00069   uint64_t free;
00070   uint64_t available;
00071 };
00072 
00073 enum perms {
00074   no_perms = 0,
00075   owner_read = 0400,
00076   owner_write = 0200,
00077   owner_exe = 0100,
00078   owner_all = owner_read | owner_write | owner_exe,
00079   group_read = 040,
00080   group_write = 020,
00081   group_exe = 010,
00082   group_all = group_read | group_write | group_exe,
00083   others_read = 04,
00084   others_write = 02,
00085   others_exe = 01,
00086   others_all = others_read | others_write | others_exe,
00087   all_read = owner_read | group_read | others_read,
00088   all_write = owner_write | group_write | others_write,
00089   all_exe = owner_exe | group_exe | others_exe,
00090   all_all = owner_all | group_all | others_all,
00091   set_uid_on_exe = 04000,
00092   set_gid_on_exe = 02000,
00093   sticky_bit = 01000,
00094   perms_not_known = 0xFFFF
00095 };
00096 
00097 // Helper functions so that you can use & and | to manipulate perms bits:
00098 inline perms operator|(perms l , perms r) {
00099   return static_cast<perms>(
00100              static_cast<unsigned short>(l) | static_cast<unsigned short>(r)); 
00101 }
00102 inline perms operator&(perms l , perms r) {
00103   return static_cast<perms>(
00104              static_cast<unsigned short>(l) & static_cast<unsigned short>(r)); 
00105 }
00106 inline perms &operator|=(perms &l, perms r) {
00107   l = l | r; 
00108   return l; 
00109 }
00110 inline perms &operator&=(perms &l, perms r) {
00111   l = l & r; 
00112   return l; 
00113 }
00114 inline perms operator~(perms x) {
00115   return static_cast<perms>(~static_cast<unsigned short>(x));
00116 }
00117 
00118 class UniqueID {
00119   uint64_t Device;
00120   uint64_t File;
00121 
00122 public:
00123   UniqueID() {}
00124   UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
00125   bool operator==(const UniqueID &Other) const {
00126     return Device == Other.Device && File == Other.File;
00127   }
00128   bool operator!=(const UniqueID &Other) const { return !(*this == Other); }
00129   bool operator<(const UniqueID &Other) const {
00130     return std::tie(Device, File) < std::tie(Other.Device, Other.File);
00131   }
00132   uint64_t getDevice() const { return Device; }
00133   uint64_t getFile() const { return File; }
00134 };
00135 
00136 /// file_status - Represents the result of a call to stat and friends. It has
00137 ///               a platform-specific member to store the result.
00138 class file_status
00139 {
00140   #if defined(LLVM_ON_UNIX)
00141   dev_t fs_st_dev;
00142   ino_t fs_st_ino;
00143   time_t fs_st_mtime;
00144   uid_t fs_st_uid;
00145   gid_t fs_st_gid;
00146   off_t fs_st_size;
00147   #elif defined (LLVM_ON_WIN32)
00148   uint32_t LastWriteTimeHigh;
00149   uint32_t LastWriteTimeLow;
00150   uint32_t VolumeSerialNumber;
00151   uint32_t FileSizeHigh;
00152   uint32_t FileSizeLow;
00153   uint32_t FileIndexHigh;
00154   uint32_t FileIndexLow;
00155   #endif
00156   friend bool equivalent(file_status A, file_status B);
00157   file_type Type;
00158   perms Perms;
00159 public:
00160   #if defined(LLVM_ON_UNIX)
00161     file_status() : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0),
00162         fs_st_uid(0), fs_st_gid(0), fs_st_size(0),
00163         Type(file_type::status_error), Perms(perms_not_known) {}
00164 
00165     file_status(file_type Type) : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0),
00166         fs_st_uid(0), fs_st_gid(0), fs_st_size(0), Type(Type),
00167         Perms(perms_not_known) {}
00168 
00169     file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t MTime,
00170                 uid_t UID, gid_t GID, off_t Size)
00171         : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_mtime(MTime), fs_st_uid(UID),
00172           fs_st_gid(GID), fs_st_size(Size), Type(Type), Perms(Perms) {}
00173   #elif defined(LLVM_ON_WIN32)
00174     file_status() : LastWriteTimeHigh(0), LastWriteTimeLow(0),
00175         VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0),
00176         FileIndexHigh(0), FileIndexLow(0), Type(file_type::status_error),
00177         Perms(perms_not_known) {}
00178 
00179     file_status(file_type Type) : LastWriteTimeHigh(0), LastWriteTimeLow(0),
00180         VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0),
00181         FileIndexHigh(0), FileIndexLow(0), Type(Type),
00182         Perms(perms_not_known) {}
00183 
00184     file_status(file_type Type, uint32_t LastWriteTimeHigh,
00185                 uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber,
00186                 uint32_t FileSizeHigh, uint32_t FileSizeLow,
00187                 uint32_t FileIndexHigh, uint32_t FileIndexLow)
00188         : LastWriteTimeHigh(LastWriteTimeHigh),
00189           LastWriteTimeLow(LastWriteTimeLow),
00190           VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh),
00191           FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh),
00192           FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {}
00193   #endif
00194 
00195   // getters
00196   file_type type() const { return Type; }
00197   perms permissions() const { return Perms; }
00198   TimeValue getLastModificationTime() const;
00199   UniqueID getUniqueID() const;
00200 
00201   #if defined(LLVM_ON_UNIX)
00202   uint32_t getUser() const { return fs_st_uid; }
00203   uint32_t getGroup() const { return fs_st_gid; }
00204   uint64_t getSize() const { return fs_st_size; }
00205   #elif defined (LLVM_ON_WIN32)
00206   uint32_t getUser() const {
00207     return 9999; // Not applicable to Windows, so...
00208   }
00209   uint32_t getGroup() const {
00210     return 9999; // Not applicable to Windows, so...
00211   }
00212   uint64_t getSize() const {
00213     return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
00214   }
00215   #endif
00216 
00217   // setters
00218   void type(file_type v) { Type = v; }
00219   void permissions(perms p) { Perms = p; }
00220 };
00221 
00222 /// file_magic - An "enum class" enumeration of file types based on magic (the first
00223 ///         N bytes of the file).
00224 struct file_magic {
00225   enum Impl {
00226     unknown = 0,              ///< Unrecognized file
00227     bitcode,                  ///< Bitcode file
00228     archive,                  ///< ar style archive file
00229     elf_relocatable,          ///< ELF Relocatable object file
00230     elf_executable,           ///< ELF Executable image
00231     elf_shared_object,        ///< ELF dynamically linked shared lib
00232     elf_core,                 ///< ELF core image
00233     macho_object,             ///< Mach-O Object file
00234     macho_executable,         ///< Mach-O Executable
00235     macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM
00236     macho_core,               ///< Mach-O Core File
00237     macho_preload_executable, ///< Mach-O Preloaded Executable
00238     macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib
00239     macho_dynamic_linker,     ///< The Mach-O dynamic linker
00240     macho_bundle,             ///< Mach-O Bundle file
00241     macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub
00242     macho_dsym_companion,     ///< Mach-O dSYM companion file
00243     macho_universal_binary,   ///< Mach-O universal binary
00244     coff_object,              ///< COFF object file
00245     coff_import_library,      ///< COFF import library
00246     pecoff_executable,        ///< PECOFF executable file
00247     windows_resource          ///< Windows compiled resource file (.rc)
00248   };
00249 
00250   bool is_object() const {
00251     return V == unknown ? false : true;
00252   }
00253 
00254   file_magic() : V(unknown) {}
00255   file_magic(Impl V) : V(V) {}
00256   operator Impl() const { return V; }
00257 
00258 private:
00259   Impl V;
00260 };
00261 
00262 /// @}
00263 /// @name Physical Operators
00264 /// @{
00265 
00266 /// @brief Make \a path an absolute path.
00267 ///
00268 /// Makes \a path absolute using the current directory if it is not already. An
00269 /// empty \a path will result in the current directory.
00270 ///
00271 /// /absolute/path   => /absolute/path
00272 /// relative/../path => <current-directory>/relative/../path
00273 ///
00274 /// @param path A path that is modified to be an absolute path.
00275 /// @returns errc::success if \a path has been made absolute, otherwise a
00276 ///          platform-specific error_code.
00277 std::error_code make_absolute(SmallVectorImpl<char> &path);
00278 
00279 /// @brief Create all the non-existent directories in path.
00280 ///
00281 /// @param path Directories to create.
00282 /// @returns errc::success if is_directory(path), otherwise a platform
00283 ///          specific error_code. If IgnoreExisting is false, also returns
00284 ///          error if the directory already existed.
00285 std::error_code create_directories(const Twine &path,
00286                                    bool IgnoreExisting = true);
00287 
00288 /// @brief Create the directory in path.
00289 ///
00290 /// @param path Directory to create.
00291 /// @returns errc::success if is_directory(path), otherwise a platform
00292 ///          specific error_code. If IgnoreExisting is false, also returns
00293 ///          error if the directory already existed.
00294 std::error_code create_directory(const Twine &path, bool IgnoreExisting = true);
00295 
00296 /// @brief Create a link from \a from to \a to.
00297 ///
00298 /// The link may be a soft or a hard link, depending on the platform. The caller
00299 /// may not assume which one. Currently on windows it creates a hard link since
00300 /// soft links require extra privileges. On unix, it creates a soft link since
00301 /// hard links don't work on SMB file systems.
00302 ///
00303 /// @param to The path to hard link to.
00304 /// @param from The path to hard link from. This is created.
00305 /// @returns errc::success if the link was created, otherwise a platform
00306 /// specific error_code.
00307 std::error_code create_link(const Twine &to, const Twine &from);
00308 
00309 /// @brief Get the current path.
00310 ///
00311 /// @param result Holds the current path on return.
00312 /// @returns errc::success if the current path has been stored in result,
00313 ///          otherwise a platform-specific error_code.
00314 std::error_code current_path(SmallVectorImpl<char> &result);
00315 
00316 /// @brief Remove path. Equivalent to POSIX remove().
00317 ///
00318 /// @param path Input path.
00319 /// @returns errc::success if path has been removed or didn't exist, otherwise a
00320 ///          platform-specific error code. If IgnoreNonExisting is false, also
00321 ///          returns error if the file didn't exist.
00322 std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
00323 
00324 /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename().
00325 ///
00326 /// @param from The path to rename from.
00327 /// @param to The path to rename to. This is created.
00328 std::error_code rename(const Twine &from, const Twine &to);
00329 
00330 /// @brief Copy the contents of \a From to \a To.
00331 ///
00332 /// @param From The path to copy from.
00333 /// @param To The path to copy to. This is created.
00334 std::error_code copy_file(const Twine &From, const Twine &To);
00335 
00336 /// @brief Resize path to size. File is resized as if by POSIX truncate().
00337 ///
00338 /// @param path Input path.
00339 /// @param size Size to resize to.
00340 /// @returns errc::success if \a path has been resized to \a size, otherwise a
00341 ///          platform-specific error_code.
00342 std::error_code resize_file(const Twine &path, uint64_t size);
00343 
00344 /// @}
00345 /// @name Physical Observers
00346 /// @{
00347 
00348 /// @brief Does file exist?
00349 ///
00350 /// @param status A file_status previously returned from stat.
00351 /// @returns True if the file represented by status exists, false if it does
00352 ///          not.
00353 bool exists(file_status status);
00354 
00355 enum class AccessMode { Exist, Write, Execute };
00356 
00357 /// @brief Can the file be accessed?
00358 ///
00359 /// @param Path Input path.
00360 /// @returns errc::success if the path can be accessed, otherwise a
00361 ///          platform-specific error_code.
00362 std::error_code access(const Twine &Path, AccessMode Mode);
00363 
00364 /// @brief Does file exist?
00365 ///
00366 /// @param Path Input path.
00367 /// @returns True if it exists, false otherwise.
00368 inline bool exists(const Twine &Path) {
00369   return !access(Path, AccessMode::Exist);
00370 }
00371 
00372 /// @brief Can we execute this file?
00373 ///
00374 /// @param Path Input path.
00375 /// @returns True if we can execute it, false otherwise.
00376 inline bool can_execute(const Twine &Path) {
00377   return !access(Path, AccessMode::Execute);
00378 }
00379 
00380 /// @brief Can we write this file?
00381 ///
00382 /// @param Path Input path.
00383 /// @returns True if we can write to it, false otherwise.
00384 inline bool can_write(const Twine &Path) {
00385   return !access(Path, AccessMode::Write);
00386 }
00387 
00388 /// @brief Do file_status's represent the same thing?
00389 ///
00390 /// @param A Input file_status.
00391 /// @param B Input file_status.
00392 ///
00393 /// assert(status_known(A) || status_known(B));
00394 ///
00395 /// @returns True if A and B both represent the same file system entity, false
00396 ///          otherwise.
00397 bool equivalent(file_status A, file_status B);
00398 
00399 /// @brief Do paths represent the same thing?
00400 ///
00401 /// assert(status_known(A) || status_known(B));
00402 ///
00403 /// @param A Input path A.
00404 /// @param B Input path B.
00405 /// @param result Set to true if stat(A) and stat(B) have the same device and
00406 ///               inode (or equivalent).
00407 /// @returns errc::success if result has been successfully set, otherwise a
00408 ///          platform-specific error_code.
00409 std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
00410 
00411 /// @brief Simpler version of equivalent for clients that don't need to
00412 ///        differentiate between an error and false.
00413 inline bool equivalent(const Twine &A, const Twine &B) {
00414   bool result;
00415   return !equivalent(A, B, result) && result;
00416 }
00417 
00418 /// @brief Does status represent a directory?
00419 ///
00420 /// @param status A file_status previously returned from status.
00421 /// @returns status.type() == file_type::directory_file.
00422 bool is_directory(file_status status);
00423 
00424 /// @brief Is path a directory?
00425 ///
00426 /// @param path Input path.
00427 /// @param result Set to true if \a path is a directory, false if it is not.
00428 ///               Undefined otherwise.
00429 /// @returns errc::success if result has been successfully set, otherwise a
00430 ///          platform-specific error_code.
00431 std::error_code is_directory(const Twine &path, bool &result);
00432 
00433 /// @brief Simpler version of is_directory for clients that don't need to
00434 ///        differentiate between an error and false.
00435 inline bool is_directory(const Twine &Path) {
00436   bool Result;
00437   return !is_directory(Path, Result) && Result;
00438 }
00439 
00440 /// @brief Does status represent a regular file?
00441 ///
00442 /// @param status A file_status previously returned from status.
00443 /// @returns status_known(status) && status.type() == file_type::regular_file.
00444 bool is_regular_file(file_status status);
00445 
00446 /// @brief Is path a regular file?
00447 ///
00448 /// @param path Input path.
00449 /// @param result Set to true if \a path is a regular file, false if it is not.
00450 ///               Undefined otherwise.
00451 /// @returns errc::success if result has been successfully set, otherwise a
00452 ///          platform-specific error_code.
00453 std::error_code is_regular_file(const Twine &path, bool &result);
00454 
00455 /// @brief Simpler version of is_regular_file for clients that don't need to
00456 ///        differentiate between an error and false.
00457 inline bool is_regular_file(const Twine &Path) {
00458   bool Result;
00459   if (is_regular_file(Path, Result))
00460     return false;
00461   return Result;
00462 }
00463 
00464 /// @brief Does this status represent something that exists but is not a
00465 ///        directory, regular file, or symlink?
00466 ///
00467 /// @param status A file_status previously returned from status.
00468 /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
00469 bool is_other(file_status status);
00470 
00471 /// @brief Is path something that exists but is not a directory,
00472 ///        regular file, or symlink?
00473 ///
00474 /// @param path Input path.
00475 /// @param result Set to true if \a path exists, but is not a directory, regular
00476 ///               file, or a symlink, false if it does not. Undefined otherwise.
00477 /// @returns errc::success if result has been successfully set, otherwise a
00478 ///          platform-specific error_code.
00479 std::error_code is_other(const Twine &path, bool &result);
00480 
00481 /// @brief Get file status as if by POSIX stat().
00482 ///
00483 /// @param path Input path.
00484 /// @param result Set to the file status.
00485 /// @returns errc::success if result has been successfully set, otherwise a
00486 ///          platform-specific error_code.
00487 std::error_code status(const Twine &path, file_status &result);
00488 
00489 /// @brief A version for when a file descriptor is already available.
00490 std::error_code status(int FD, file_status &Result);
00491 
00492 /// @brief Get file size.
00493 ///
00494 /// @param Path Input path.
00495 /// @param Result Set to the size of the file in \a Path.
00496 /// @returns errc::success if result has been successfully set, otherwise a
00497 ///          platform-specific error_code.
00498 inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
00499   file_status Status;
00500   std::error_code EC = status(Path, Status);
00501   if (EC)
00502     return EC;
00503   Result = Status.getSize();
00504   return std::error_code();
00505 }
00506 
00507 /// @brief Set the file modification and access time.
00508 ///
00509 /// @returns errc::success if the file times were successfully set, otherwise a
00510 ///          platform-specific error_code or errc::function_not_supported on
00511 ///          platforms where the functionality isn't available.
00512 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time);
00513 
00514 /// @brief Is status available?
00515 ///
00516 /// @param s Input file status.
00517 /// @returns True if status() != status_error.
00518 bool status_known(file_status s);
00519 
00520 /// @brief Is status available?
00521 ///
00522 /// @param path Input path.
00523 /// @param result Set to true if status() != status_error.
00524 /// @returns errc::success if result has been successfully set, otherwise a
00525 ///          platform-specific error_code.
00526 std::error_code status_known(const Twine &path, bool &result);
00527 
00528 /// @brief Create a uniquely named file.
00529 ///
00530 /// Generates a unique path suitable for a temporary file and then opens it as a
00531 /// file. The name is based on \a model with '%' replaced by a random char in
00532 /// [0-9a-f]. If \a model is not an absolute path, a suitable temporary
00533 /// directory will be prepended.
00534 ///
00535 /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
00536 ///
00537 /// This is an atomic operation. Either the file is created and opened, or the
00538 /// file system is left untouched.
00539 ///
00540 /// The intendend use is for files that are to be kept, possibly after
00541 /// renaming them. For example, when running 'clang -c foo.o', the file can
00542 /// be first created as foo-abc123.o and then renamed.
00543 ///
00544 /// @param Model Name to base unique path off of.
00545 /// @param ResultFD Set to the opened file's file descriptor.
00546 /// @param ResultPath Set to the opened file's absolute path.
00547 /// @returns errc::success if Result{FD,Path} have been successfully set,
00548 ///          otherwise a platform-specific error_code.
00549 std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
00550                                  SmallVectorImpl<char> &ResultPath,
00551                                  unsigned Mode = all_read | all_write);
00552 
00553 /// @brief Simpler version for clients that don't want an open file.
00554 std::error_code createUniqueFile(const Twine &Model,
00555                                  SmallVectorImpl<char> &ResultPath);
00556 
00557 /// @brief Create a file in the system temporary directory.
00558 ///
00559 /// The filename is of the form prefix-random_chars.suffix. Since the directory
00560 /// is not know to the caller, Prefix and Suffix cannot have path separators.
00561 /// The files are created with mode 0600.
00562 ///
00563 /// This should be used for things like a temporary .s that is removed after
00564 /// running the assembler.
00565 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
00566                                     int &ResultFD,
00567                                     SmallVectorImpl<char> &ResultPath);
00568 
00569 /// @brief Simpler version for clients that don't want an open file.
00570 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
00571                                     SmallVectorImpl<char> &ResultPath);
00572 
00573 std::error_code createUniqueDirectory(const Twine &Prefix,
00574                                       SmallVectorImpl<char> &ResultPath);
00575 
00576 enum OpenFlags : unsigned {
00577   F_None = 0,
00578 
00579   /// F_Excl - When opening a file, this flag makes raw_fd_ostream
00580   /// report an error if the file already exists.
00581   F_Excl = 1,
00582 
00583   /// F_Append - When opening a file, if it already exists append to the
00584   /// existing file instead of returning an error.  This may not be specified
00585   /// with F_Excl.
00586   F_Append = 2,
00587 
00588   /// The file should be opened in text mode on platforms that make this
00589   /// distinction.
00590   F_Text = 4,
00591 
00592   /// Open the file for read and write.
00593   F_RW = 8
00594 };
00595 
00596 inline OpenFlags operator|(OpenFlags A, OpenFlags B) {
00597   return OpenFlags(unsigned(A) | unsigned(B));
00598 }
00599 
00600 inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) {
00601   A = A | B;
00602   return A;
00603 }
00604 
00605 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
00606                                  OpenFlags Flags, unsigned Mode = 0666);
00607 
00608 std::error_code openFileForRead(const Twine &Name, int &ResultFD);
00609 
00610 /// @brief Identify the type of a binary file based on how magical it is.
00611 file_magic identify_magic(StringRef magic);
00612 
00613 /// @brief Get and identify \a path's type based on its content.
00614 ///
00615 /// @param path Input path.
00616 /// @param result Set to the type of file, or file_magic::unknown.
00617 /// @returns errc::success if result has been successfully set, otherwise a
00618 ///          platform-specific error_code.
00619 std::error_code identify_magic(const Twine &path, file_magic &result);
00620 
00621 std::error_code getUniqueID(const Twine Path, UniqueID &Result);
00622 
00623 /// This class represents a memory mapped file. It is based on
00624 /// boost::iostreams::mapped_file.
00625 class mapped_file_region {
00626   mapped_file_region() LLVM_DELETED_FUNCTION;
00627   mapped_file_region(mapped_file_region&) LLVM_DELETED_FUNCTION;
00628   mapped_file_region &operator =(mapped_file_region&) LLVM_DELETED_FUNCTION;
00629 
00630 public:
00631   enum mapmode {
00632     readonly, ///< May only access map via const_data as read only.
00633     readwrite, ///< May access map via data and modify it. Written to path.
00634     priv ///< May modify via data, but changes are lost on destruction.
00635   };
00636 
00637 private:
00638   /// Platform-specific mapping state.
00639   mapmode Mode;
00640   uint64_t Size;
00641   void *Mapping;
00642 #ifdef LLVM_ON_WIN32
00643   int FileDescriptor;
00644   void *FileHandle;
00645   void *FileMappingHandle;
00646 #endif
00647 
00648   std::error_code init(int FD, bool CloseFD, uint64_t Offset);
00649 
00650 public:
00651   typedef char char_type;
00652 
00653   mapped_file_region(mapped_file_region&&);
00654   mapped_file_region &operator =(mapped_file_region&&);
00655 
00656   /// Construct a mapped_file_region at \a path starting at \a offset of length
00657   /// \a length and with access \a mode.
00658   ///
00659   /// \param path Path to the file to map. If it does not exist it will be
00660   ///             created.
00661   /// \param mode How to map the memory.
00662   /// \param length Number of bytes to map in starting at \a offset. If the file
00663   ///               is shorter than this, it will be extended. If \a length is
00664   ///               0, the entire file will be mapped.
00665   /// \param offset Byte offset from the beginning of the file where the map
00666   ///               should begin. Must be a multiple of
00667   ///               mapped_file_region::alignment().
00668   /// \param ec This is set to errc::success if the map was constructed
00669   ///           successfully. Otherwise it is set to a platform dependent error.
00670   mapped_file_region(const Twine &path, mapmode mode, uint64_t length,
00671                      uint64_t offset, std::error_code &ec);
00672 
00673   /// \param fd An open file descriptor to map. mapped_file_region takes
00674   ///   ownership if closefd is true. It must have been opended in the correct
00675   ///   mode.
00676   mapped_file_region(int fd, bool closefd, mapmode mode, uint64_t length,
00677                      uint64_t offset, std::error_code &ec);
00678 
00679   ~mapped_file_region();
00680 
00681   mapmode flags() const;
00682   uint64_t size() const;
00683   char *data() const;
00684 
00685   /// Get a const view of the data. Modifying this memory has undefined
00686   /// behavior.
00687   const char *const_data() const;
00688 
00689   /// \returns The minimum alignment offset must be.
00690   static int alignment();
00691 };
00692 
00693 /// Return the path to the main executable, given the value of argv[0] from
00694 /// program startup and the address of main itself. In extremis, this function
00695 /// may fail and return an empty path.
00696 std::string getMainExecutable(const char *argv0, void *MainExecAddr);
00697 
00698 /// @}
00699 /// @name Iterators
00700 /// @{
00701 
00702 /// directory_entry - A single entry in a directory. Caches the status either
00703 /// from the result of the iteration syscall, or the first time status is
00704 /// called.
00705 class directory_entry {
00706   std::string Path;
00707   mutable file_status Status;
00708 
00709 public:
00710   explicit directory_entry(const Twine &path, file_status st = file_status())
00711     : Path(path.str())
00712     , Status(st) {}
00713 
00714   directory_entry() {}
00715 
00716   void assign(const Twine &path, file_status st = file_status()) {
00717     Path = path.str();
00718     Status = st;
00719   }
00720 
00721   void replace_filename(const Twine &filename, file_status st = file_status());
00722 
00723   const std::string &path() const { return Path; }
00724   std::error_code status(file_status &result) const;
00725 
00726   bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; }
00727   bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); }
00728   bool operator< (const directory_entry& rhs) const;
00729   bool operator<=(const directory_entry& rhs) const;
00730   bool operator> (const directory_entry& rhs) const;
00731   bool operator>=(const directory_entry& rhs) const;
00732 };
00733 
00734 namespace detail {
00735   struct DirIterState;
00736 
00737   std::error_code directory_iterator_construct(DirIterState &, StringRef);
00738   std::error_code directory_iterator_increment(DirIterState &);
00739   std::error_code directory_iterator_destruct(DirIterState &);
00740 
00741   /// DirIterState - Keeps state for the directory_iterator. It is reference
00742   /// counted in order to preserve InputIterator semantics on copy.
00743   struct DirIterState : public RefCountedBase<DirIterState> {
00744     DirIterState()
00745       : IterationHandle(0) {}
00746 
00747     ~DirIterState() {
00748       directory_iterator_destruct(*this);
00749     }
00750 
00751     intptr_t IterationHandle;
00752     directory_entry CurrentEntry;
00753   };
00754 }
00755 
00756 /// directory_iterator - Iterates through the entries in path. There is no
00757 /// operator++ because we need an error_code. If it's really needed we can make
00758 /// it call report_fatal_error on error.
00759 class directory_iterator {
00760   IntrusiveRefCntPtr<detail::DirIterState> State;
00761 
00762 public:
00763   explicit directory_iterator(const Twine &path, std::error_code &ec) {
00764     State = new detail::DirIterState;
00765     SmallString<128> path_storage;
00766     ec = detail::directory_iterator_construct(*State,
00767             path.toStringRef(path_storage));
00768   }
00769 
00770   explicit directory_iterator(const directory_entry &de, std::error_code &ec) {
00771     State = new detail::DirIterState;
00772     ec = detail::directory_iterator_construct(*State, de.path());
00773   }
00774 
00775   /// Construct end iterator.
00776   directory_iterator() : State(nullptr) {}
00777 
00778   // No operator++ because we need error_code.
00779   directory_iterator &increment(std::error_code &ec) {
00780     ec = directory_iterator_increment(*State);
00781     return *this;
00782   }
00783 
00784   const directory_entry &operator*() const { return State->CurrentEntry; }
00785   const directory_entry *operator->() const { return &State->CurrentEntry; }
00786 
00787   bool operator==(const directory_iterator &RHS) const {
00788     if (State == RHS.State)
00789       return true;
00790     if (!RHS.State)
00791       return State->CurrentEntry == directory_entry();
00792     if (!State)
00793       return RHS.State->CurrentEntry == directory_entry();
00794     return State->CurrentEntry == RHS.State->CurrentEntry;
00795   }
00796 
00797   bool operator!=(const directory_iterator &RHS) const {
00798     return !(*this == RHS);
00799   }
00800   // Other members as required by
00801   // C++ Std, 24.1.1 Input iterators [input.iterators]
00802 };
00803 
00804 namespace detail {
00805   /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is
00806   /// reference counted in order to preserve InputIterator semantics on copy.
00807   struct RecDirIterState : public RefCountedBase<RecDirIterState> {
00808     RecDirIterState()
00809       : Level(0)
00810       , HasNoPushRequest(false) {}
00811 
00812     std::stack<directory_iterator, std::vector<directory_iterator> > Stack;
00813     uint16_t Level;
00814     bool HasNoPushRequest;
00815   };
00816 }
00817 
00818 /// recursive_directory_iterator - Same as directory_iterator except for it
00819 /// recurses down into child directories.
00820 class recursive_directory_iterator {
00821   IntrusiveRefCntPtr<detail::RecDirIterState> State;
00822 
00823 public:
00824   recursive_directory_iterator() {}
00825   explicit recursive_directory_iterator(const Twine &path, std::error_code &ec)
00826       : State(new detail::RecDirIterState) {
00827     State->Stack.push(directory_iterator(path, ec));
00828     if (State->Stack.top() == directory_iterator())
00829       State.reset();
00830   }
00831   // No operator++ because we need error_code.
00832   recursive_directory_iterator &increment(std::error_code &ec) {
00833     const directory_iterator end_itr;
00834 
00835     if (State->HasNoPushRequest)
00836       State->HasNoPushRequest = false;
00837     else {
00838       file_status st;
00839       if ((ec = State->Stack.top()->status(st))) return *this;
00840       if (is_directory(st)) {
00841         State->Stack.push(directory_iterator(*State->Stack.top(), ec));
00842         if (ec) return *this;
00843         if (State->Stack.top() != end_itr) {
00844           ++State->Level;
00845           return *this;
00846         }
00847         State->Stack.pop();
00848       }
00849     }
00850 
00851     while (!State->Stack.empty()
00852            && State->Stack.top().increment(ec) == end_itr) {
00853       State->Stack.pop();
00854       --State->Level;
00855     }
00856 
00857     // Check if we are done. If so, create an end iterator.
00858     if (State->Stack.empty())
00859       State.reset();
00860 
00861     return *this;
00862   }
00863 
00864   const directory_entry &operator*() const { return *State->Stack.top(); }
00865   const directory_entry *operator->() const { return &*State->Stack.top(); }
00866 
00867   // observers
00868   /// Gets the current level. Starting path is at level 0.
00869   int level() const { return State->Level; }
00870 
00871   /// Returns true if no_push has been called for this directory_entry.
00872   bool no_push_request() const { return State->HasNoPushRequest; }
00873 
00874   // modifiers
00875   /// Goes up one level if Level > 0.
00876   void pop() {
00877     assert(State && "Cannot pop an end iterator!");
00878     assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
00879 
00880     const directory_iterator end_itr;
00881     std::error_code ec;
00882     do {
00883       if (ec)
00884         report_fatal_error("Error incrementing directory iterator.");
00885       State->Stack.pop();
00886       --State->Level;
00887     } while (!State->Stack.empty()
00888              && State->Stack.top().increment(ec) == end_itr);
00889 
00890     // Check if we are done. If so, create an end iterator.
00891     if (State->Stack.empty())
00892       State.reset();
00893   }
00894 
00895   /// Does not go down into the current directory_entry.
00896   void no_push() { State->HasNoPushRequest = true; }
00897 
00898   bool operator==(const recursive_directory_iterator &RHS) const {
00899     return State == RHS.State;
00900   }
00901 
00902   bool operator!=(const recursive_directory_iterator &RHS) const {
00903     return !(*this == RHS);
00904   }
00905   // Other members as required by
00906   // C++ Std, 24.1.1 Input iterators [input.iterators]
00907 };
00908 
00909 /// @}
00910 
00911 } // end namespace fs
00912 } // end namespace sys
00913 } // end namespace llvm
00914 
00915 #endif