Home | History | Annotate | Download | only in Support
      1 //===- llvm/Support/PathV1.h - Path Operating System 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::Path class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_SYSTEM_PATH_H
     15 #define LLVM_SYSTEM_PATH_H
     16 
     17 #include "llvm/ADT/StringRef.h"
     18 #include "llvm/Support/Compiler.h"
     19 #include "llvm/Support/TimeValue.h"
     20 #include <set>
     21 #include <string>
     22 #include <vector>
     23 
     24 #define LLVM_PATH_DEPRECATED_MSG(replacement) \
     25   "PathV1 has been deprecated and will be removed as soon as all LLVM and" \
     26   " Clang clients have been moved over to PathV2. Please use `" #replacement \
     27   "` from PathV2 instead."
     28 
     29 namespace llvm {
     30 namespace sys {
     31 
     32   /// This structure provides basic file system information about a file. It
     33   /// is patterned after the stat(2) Unix operating system call but made
     34   /// platform independent and eliminates many of the unix-specific fields.
     35   /// However, to support llvm-ar, the mode, user, and group fields are
     36   /// retained. These pertain to unix security and may not have a meaningful
     37   /// value on non-Unix platforms. However, the other fields should
     38   /// always be applicable on all platforms.  The structure is filled in by
     39   /// the PathWithStatus class.
     40   /// @brief File status structure
     41   class FileStatus {
     42   public:
     43     uint64_t    fileSize;   ///< Size of the file in bytes
     44     TimeValue   modTime;    ///< Time of file's modification
     45     uint32_t    mode;       ///< Mode of the file, if applicable
     46     uint32_t    user;       ///< User ID of owner, if applicable
     47     uint32_t    group;      ///< Group ID of owner, if applicable
     48     uint64_t    uniqueID;   ///< A number to uniquely ID this file
     49     bool        isDir  : 1; ///< True if this is a directory.
     50     bool        isFile : 1; ///< True if this is a file.
     51 
     52     FileStatus() : fileSize(0), modTime(0,0), mode(0777), user(999),
     53                    group(999), uniqueID(0), isDir(false), isFile(false) { }
     54 
     55     TimeValue getTimestamp() const { return modTime; }
     56     uint64_t getSize() const { return fileSize; }
     57     uint32_t getMode() const { return mode; }
     58     uint32_t getUser() const { return user; }
     59     uint32_t getGroup() const { return group; }
     60     uint64_t getUniqueID() const { return uniqueID; }
     61   };
     62 
     63   /// This class provides an abstraction for the path to a file or directory
     64   /// in the operating system's filesystem and provides various basic operations
     65   /// on it.  Note that this class only represents the name of a path to a file
     66   /// or directory which may or may not be valid for a given machine's file
     67   /// system. The class is patterned after the java.io.File class with various
     68   /// extensions and several omissions (not relevant to LLVM).  A Path object
     69   /// ensures that the path it encapsulates is syntactically valid for the
     70   /// operating system it is running on but does not ensure correctness for
     71   /// any particular file system. That is, a syntactically valid path might
     72   /// specify path components that do not exist in the file system and using
     73   /// such a Path to act on the file system could produce errors. There is one
     74   /// invalid Path value which is permitted: the empty path.  The class should
     75   /// never allow a syntactically invalid non-empty path name to be assigned.
     76   /// Empty paths are required in order to indicate an error result in some
     77   /// situations. If the path is empty, the isValid operation will return
     78   /// false. All operations will fail if isValid is false. Operations that
     79   /// change the path will either return false if it would cause a syntactically
     80   /// invalid path name (in which case the Path object is left unchanged) or
     81   /// throw an std::string exception indicating the error. The methods are
     82   /// grouped into four basic categories: Path Accessors (provide information
     83   /// about the path without accessing disk), Disk Accessors (provide
     84   /// information about the underlying file or directory), Path Mutators
     85   /// (change the path information, not the disk), and Disk Mutators (change
     86   /// the disk file/directory referenced by the path). The Disk Mutator methods
     87   /// all have the word "disk" embedded in their method name to reinforce the
     88   /// notion that the operation modifies the file system.
     89   /// @since 1.4
     90   /// @brief An abstraction for operating system paths.
     91   class Path {
     92     /// @name Constructors
     93     /// @{
     94     public:
     95       /// Construct a path to the root directory of the file system. The root
     96       /// directory is a top level directory above which there are no more
     97       /// directories. For example, on UNIX, the root directory is /. On Windows
     98       /// it is file:///. Other operating systems may have different notions of
     99       /// what the root directory is or none at all. In that case, a consistent
    100       /// default root directory will be used.
    101       LLVM_ATTRIBUTE_DEPRECATED(static Path GetRootDirectory(),
    102         LLVM_PATH_DEPRECATED_MSG(NOTHING));
    103 
    104       /// Construct a path to a unique temporary directory that is created in
    105       /// a "standard" place for the operating system. The directory is
    106       /// guaranteed to be created on exit from this function. If the directory
    107       /// cannot be created, the function will throw an exception.
    108       /// @returns an invalid path (empty) on error
    109       /// @param ErrMsg Optional place for an error message if an error occurs
    110       /// @brief Construct a path to an new, unique, existing temporary
    111       /// directory.
    112       static Path GetTemporaryDirectory(std::string* ErrMsg = 0);
    113 
    114       /// Construct a vector of sys::Path that contains the "standard" system
    115       /// library paths suitable for linking into programs.
    116       /// @brief Construct a path to the system library directory
    117       static void GetSystemLibraryPaths(std::vector<sys::Path>& Paths);
    118 
    119       /// Construct a vector of sys::Path that contains the "standard" bitcode
    120       /// library paths suitable for linking into an llvm program. This function
    121       /// *must* return the value of LLVM_LIB_SEARCH_PATH as well as the value
    122       /// of LLVM_LIBDIR. It also must provide the System library paths as
    123       /// returned by GetSystemLibraryPaths.
    124       /// @see GetSystemLibraryPaths
    125       /// @brief Construct a list of directories in which bitcode could be
    126       /// found.
    127       static void GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths);
    128 
    129       /// Find the path to a library using its short name. Use the system
    130       /// dependent library paths to locate the library.
    131       /// @brief Find a library.
    132       static Path FindLibrary(std::string& short_name);
    133 
    134       /// Construct a path to the current user's home directory. The
    135       /// implementation must use an operating system specific mechanism for
    136       /// determining the user's home directory. For example, the environment
    137       /// variable "HOME" could be used on Unix. If a given operating system
    138       /// does not have the concept of a user's home directory, this static
    139       /// constructor must provide the same result as GetRootDirectory.
    140       /// @brief Construct a path to the current user's "home" directory
    141       static Path GetUserHomeDirectory();
    142 
    143       /// Construct a path to the current directory for the current process.
    144       /// @returns The current working directory.
    145       /// @brief Returns the current working directory.
    146       static Path GetCurrentDirectory();
    147 
    148       /// Return the suffix commonly used on file names that contain an
    149       /// executable.
    150       /// @returns The executable file suffix for the current platform.
    151       /// @brief Return the executable file suffix.
    152       static StringRef GetEXESuffix();
    153 
    154       /// Return the suffix commonly used on file names that contain a shared
    155       /// object, shared archive, or dynamic link library. Such files are
    156       /// linked at runtime into a process and their code images are shared
    157       /// between processes.
    158       /// @returns The dynamic link library suffix for the current platform.
    159       /// @brief Return the dynamic link library suffix.
    160       static StringRef GetDLLSuffix();
    161 
    162       /// GetMainExecutable - Return the path to the main executable, given the
    163       /// value of argv[0] from program startup and the address of main itself.
    164       /// In extremis, this function may fail and return an empty path.
    165       static Path GetMainExecutable(const char *argv0, void *MainAddr);
    166 
    167       /// This is one of the very few ways in which a path can be constructed
    168       /// with a syntactically invalid name. The only *legal* invalid name is an
    169       /// empty one. Other invalid names are not permitted. Empty paths are
    170       /// provided so that they can be used to indicate null or error results in
    171       /// other lib/System functionality.
    172       /// @brief Construct an empty (and invalid) path.
    173       Path() : path() {}
    174       Path(const Path &that) : path(that.path) {}
    175 
    176       /// This constructor will accept a char* or std::string as a path. No
    177       /// checking is done on this path to determine if it is valid. To
    178       /// determine validity of the path, use the isValid method.
    179       /// @param p The path to assign.
    180       /// @brief Construct a Path from a string.
    181       explicit Path(StringRef p);
    182 
    183       /// This constructor will accept a character range as a path.  No checking
    184       /// is done on this path to determine if it is valid.  To determine
    185       /// validity of the path, use the isValid method.
    186       /// @param StrStart A pointer to the first character of the path name
    187       /// @param StrLen The length of the path name at StrStart
    188       /// @brief Construct a Path from a string.
    189       Path(const char *StrStart, unsigned StrLen);
    190 
    191     /// @}
    192     /// @name Operators
    193     /// @{
    194     public:
    195       /// Makes a copy of \p that to \p this.
    196       /// @returns \p this
    197       /// @brief Assignment Operator
    198       Path &operator=(const Path &that) {
    199         path = that.path;
    200         return *this;
    201       }
    202 
    203       /// Makes a copy of \p that to \p this.
    204       /// @param that A StringRef denoting the path
    205       /// @returns \p this
    206       /// @brief Assignment Operator
    207       Path &operator=(StringRef that);
    208 
    209       /// Compares \p this Path with \p that Path for equality.
    210       /// @returns true if \p this and \p that refer to the same thing.
    211       /// @brief Equality Operator
    212       bool operator==(const Path &that) const;
    213 
    214       /// Compares \p this Path with \p that Path for inequality.
    215       /// @returns true if \p this and \p that refer to different things.
    216       /// @brief Inequality Operator
    217       bool operator!=(const Path &that) const { return !(*this == that); }
    218 
    219       /// Determines if \p this Path is less than \p that Path. This is required
    220       /// so that Path objects can be placed into ordered collections (e.g.
    221       /// std::map). The comparison is done lexicographically as defined by
    222       /// the std::string::compare method.
    223       /// @returns true if \p this path is lexicographically less than \p that.
    224       /// @brief Less Than Operator
    225       bool operator<(const Path& that) const;
    226 
    227     /// @}
    228     /// @name Path Accessors
    229     /// @{
    230     public:
    231       /// This function will use an operating system specific algorithm to
    232       /// determine if the current value of \p this is a syntactically valid
    233       /// path name for the operating system. The path name does not need to
    234       /// exist, validity is simply syntactical. Empty paths are always invalid.
    235       /// @returns true iff the path name is syntactically legal for the
    236       /// host operating system.
    237       /// @brief Determine if a path is syntactically valid or not.
    238       bool isValid() const;
    239 
    240       /// This function determines if the contents of the path name are empty.
    241       /// That is, the path name has a zero length. This does NOT determine if
    242       /// if the file is empty. To get the length of the file itself, Use the
    243       /// PathWithStatus::getFileStatus() method and then the getSize() method
    244       /// on the returned FileStatus object.
    245       /// @returns true iff the path is empty.
    246       /// @brief Determines if the path name is empty (invalid).
    247       bool isEmpty() const { return path.empty(); }
    248 
    249        /// This function returns the last component of the path name. The last
    250       /// component is the file or directory name occurring after the last
    251       /// directory separator. If no directory separator is present, the entire
    252       /// path name is returned (i.e. same as toString).
    253       /// @returns StringRef containing the last component of the path name.
    254       /// @brief Returns the last component of the path name.
    255       LLVM_ATTRIBUTE_DEPRECATED(
    256         StringRef getLast() const,
    257         LLVM_PATH_DEPRECATED_MSG(path::filename));
    258 
    259       /// This function strips off the path and suffix of the file or directory
    260       /// name and returns just the basename. For example /a/foo.bar would cause
    261       /// this function to return "foo".
    262       /// @returns StringRef containing the basename of the path
    263       /// @brief Get the base name of the path
    264       LLVM_ATTRIBUTE_DEPRECATED(StringRef getBasename() const,
    265         LLVM_PATH_DEPRECATED_MSG(path::stem));
    266 
    267       /// This function strips off the suffix of the path beginning with the
    268       /// path separator ('/' on Unix, '\' on Windows) and returns the result.
    269       LLVM_ATTRIBUTE_DEPRECATED(StringRef getDirname() const,
    270         LLVM_PATH_DEPRECATED_MSG(path::parent_path));
    271 
    272       /// This function strips off the path and basename(up to and
    273       /// including the last dot) of the file or directory name and
    274       /// returns just the suffix. For example /a/foo.bar would cause
    275       /// this function to return "bar".
    276       /// @returns StringRef containing the suffix of the path
    277       /// @brief Get the suffix of the path
    278       LLVM_ATTRIBUTE_DEPRECATED(StringRef getSuffix() const,
    279         LLVM_PATH_DEPRECATED_MSG(path::extension));
    280 
    281       /// Obtain a 'C' string for the path name.
    282       /// @returns a 'C' string containing the path name.
    283       /// @brief Returns the path as a C string.
    284       const char *c_str() const { return path.c_str(); }
    285       const std::string &str() const { return path; }
    286 
    287 
    288       /// size - Return the length in bytes of this path name.
    289       size_t size() const { return path.size(); }
    290 
    291       /// empty - Returns true if the path is empty.
    292       unsigned empty() const { return path.empty(); }
    293 
    294     /// @}
    295     /// @name Disk Accessors
    296     /// @{
    297     public:
    298       /// This function determines if the path name is absolute, as opposed to
    299       /// relative.
    300       /// @brief Determine if the path is absolute.
    301       LLVM_ATTRIBUTE_DEPRECATED(
    302         bool isAbsolute() const,
    303         LLVM_PATH_DEPRECATED_MSG(path::is_absolute));
    304 
    305       /// This function determines if the path name is absolute, as opposed to
    306       /// relative.
    307       /// @brief Determine if the path is absolute.
    308       LLVM_ATTRIBUTE_DEPRECATED(
    309         static bool isAbsolute(const char *NameStart, unsigned NameLen),
    310         LLVM_PATH_DEPRECATED_MSG(path::is_absolute));
    311 
    312       /// This function opens the file associated with the path name provided by
    313       /// the Path object and reads its magic number. If the magic number at the
    314       /// start of the file matches \p magic, true is returned. In all other
    315       /// cases (file not found, file not accessible, etc.) it returns false.
    316       /// @returns true if the magic number of the file matches \p magic.
    317       /// @brief Determine if file has a specific magic number
    318       LLVM_ATTRIBUTE_DEPRECATED(bool hasMagicNumber(StringRef magic) const,
    319         LLVM_PATH_DEPRECATED_MSG(fs::has_magic));
    320 
    321       /// This function retrieves the first \p len bytes of the file associated
    322       /// with \p this. These bytes are returned as the "magic number" in the
    323       /// \p Magic parameter.
    324       /// @returns true if the Path is a file and the magic number is retrieved,
    325       /// false otherwise.
    326       /// @brief Get the file's magic number.
    327       bool getMagicNumber(std::string& Magic, unsigned len) const;
    328 
    329       /// This function determines if the path name in the object references an
    330       /// archive file by looking at its magic number.
    331       /// @returns true if the file starts with the magic number for an archive
    332       /// file.
    333       /// @brief Determine if the path references an archive file.
    334       bool isArchive() const;
    335 
    336       /// This function determines if the path name in the object references an
    337       /// LLVM Bitcode file by looking at its magic number.
    338       /// @returns true if the file starts with the magic number for LLVM
    339       /// bitcode files.
    340       /// @brief Determine if the path references a bitcode file.
    341       bool isBitcodeFile() const;
    342 
    343       /// This function determines if the path name in the object references a
    344       /// native Dynamic Library (shared library, shared object) by looking at
    345       /// the file's magic number. The Path object must reference a file, not a
    346       /// directory.
    347       /// @returns true if the file starts with the magic number for a native
    348       /// shared library.
    349       /// @brief Determine if the path references a dynamic library.
    350       bool isDynamicLibrary() const;
    351 
    352       /// This function determines if the path name in the object references a
    353       /// native object file by looking at it's magic number. The term object
    354       /// file is defined as "an organized collection of separate, named
    355       /// sequences of binary data." This covers the obvious file formats such
    356       /// as COFF and ELF, but it also includes llvm ir bitcode, archives,
    357       /// libraries, etc...
    358       /// @returns true if the file starts with the magic number for an object
    359       /// file.
    360       /// @brief Determine if the path references an object file.
    361       bool isObjectFile() const;
    362 
    363       /// This function determines if the path name references an existing file
    364       /// or directory in the file system.
    365       /// @returns true if the pathname references an existing file or
    366       /// directory.
    367       /// @brief Determines if the path is a file or directory in
    368       /// the file system.
    369       LLVM_ATTRIBUTE_DEPRECATED(bool exists() const,
    370         LLVM_PATH_DEPRECATED_MSG(fs::exists));
    371 
    372       /// This function determines if the path name references an
    373       /// existing directory.
    374       /// @returns true if the pathname references an existing directory.
    375       /// @brief Determines if the path is a directory in the file system.
    376       LLVM_ATTRIBUTE_DEPRECATED(bool isDirectory() const,
    377         LLVM_PATH_DEPRECATED_MSG(fs::is_directory));
    378 
    379       /// This function determines if the path name references an
    380       /// existing symbolic link.
    381       /// @returns true if the pathname references an existing symlink.
    382       /// @brief Determines if the path is a symlink in the file system.
    383       LLVM_ATTRIBUTE_DEPRECATED(bool isSymLink() const,
    384         LLVM_PATH_DEPRECATED_MSG(fs::is_symlink));
    385 
    386       /// This function determines if the path name references a readable file
    387       /// or directory in the file system. This function checks for
    388       /// the existence and readability (by the current program) of the file
    389       /// or directory.
    390       /// @returns true if the pathname references a readable file.
    391       /// @brief Determines if the path is a readable file or directory
    392       /// in the file system.
    393       bool canRead() const;
    394 
    395       /// This function determines if the path name references a writable file
    396       /// or directory in the file system. This function checks for the
    397       /// existence and writability (by the current program) of the file or
    398       /// directory.
    399       /// @returns true if the pathname references a writable file.
    400       /// @brief Determines if the path is a writable file or directory
    401       /// in the file system.
    402       bool canWrite() const;
    403 
    404       /// This function checks that what we're trying to work only on a regular
    405       /// file. Check for things like /dev/null, any block special file, or
    406       /// other things that aren't "regular" regular files.
    407       /// @returns true if the file is S_ISREG.
    408       /// @brief Determines if the file is a regular file
    409       bool isRegularFile() const;
    410 
    411       /// This function determines if the path name references an executable
    412       /// file in the file system. This function checks for the existence and
    413       /// executability (by the current program) of the file.
    414       /// @returns true if the pathname references an executable file.
    415       /// @brief Determines if the path is an executable file in the file
    416       /// system.
    417       bool canExecute() const;
    418 
    419       /// This function builds a list of paths that are the names of the
    420       /// files and directories in a directory.
    421       /// @returns true if an error occurs, true otherwise
    422       /// @brief Build a list of directory's contents.
    423       bool getDirectoryContents(
    424         std::set<Path> &paths, ///< The resulting list of file & directory names
    425         std::string* ErrMsg    ///< Optional place to return an error message.
    426       ) const;
    427 
    428     /// @}
    429     /// @name Path Mutators
    430     /// @{
    431     public:
    432       /// The path name is cleared and becomes empty. This is an invalid
    433       /// path name but is the *only* invalid path name. This is provided
    434       /// so that path objects can be used to indicate the lack of a
    435       /// valid path being found.
    436       /// @brief Make the path empty.
    437       void clear() { path.clear(); }
    438 
    439       /// This method sets the Path object to \p unverified_path. This can fail
    440       /// if the \p unverified_path does not pass the syntactic checks of the
    441       /// isValid() method. If verification fails, the Path object remains
    442       /// unchanged and false is returned. Otherwise true is returned and the
    443       /// Path object takes on the path value of \p unverified_path
    444       /// @returns true if the path was set, false otherwise.
    445       /// @param unverified_path The path to be set in Path object.
    446       /// @brief Set a full path from a StringRef
    447       bool set(StringRef unverified_path);
    448 
    449       /// One path component is removed from the Path. If only one component is
    450       /// present in the path, the Path object becomes empty. If the Path object
    451       /// is empty, no change is made.
    452       /// @returns false if the path component could not be removed.
    453       /// @brief Removes the last directory component of the Path.
    454       bool eraseComponent();
    455 
    456       /// The \p component is added to the end of the Path if it is a legal
    457       /// name for the operating system. A directory separator will be added if
    458       /// needed.
    459       /// @returns false if the path component could not be added.
    460       /// @brief Appends one path component to the Path.
    461       bool appendComponent(StringRef component);
    462 
    463       /// A period and the \p suffix are appended to the end of the pathname.
    464       /// When the \p suffix is empty, no action is performed.
    465       /// @brief Adds a period and the \p suffix to the end of the pathname.
    466       void appendSuffix(StringRef suffix);
    467 
    468       /// The suffix of the filename is erased. The suffix begins with and
    469       /// includes the last . character in the filename after the last directory
    470       /// separator and extends until the end of the name. If no . character is
    471       /// after the last directory separator, then the file name is left
    472       /// unchanged (i.e. it was already without a suffix) but the function
    473       /// returns false.
    474       /// @returns false if there was no suffix to remove, true otherwise.
    475       /// @brief Remove the suffix from a path name.
    476       bool eraseSuffix();
    477 
    478       /// The current Path name is made unique in the file system. Upon return,
    479       /// the Path will have been changed to make a unique file in the file
    480       /// system or it will not have been changed if the current path name is
    481       /// already unique.
    482       /// @throws std::string if an unrecoverable error occurs.
    483       /// @brief Make the current path name unique in the file system.
    484       bool makeUnique( bool reuse_current /*= true*/, std::string* ErrMsg );
    485 
    486       /// The current Path name is made absolute by prepending the
    487       /// current working directory if necessary.
    488       LLVM_ATTRIBUTE_DEPRECATED(
    489         void makeAbsolute(),
    490         LLVM_PATH_DEPRECATED_MSG(fs::make_absolute));
    491 
    492     /// @}
    493     /// @name Disk Mutators
    494     /// @{
    495     public:
    496       /// This method attempts to make the file referenced by the Path object
    497       /// available for reading so that the canRead() method will return true.
    498       /// @brief Make the file readable;
    499       bool makeReadableOnDisk(std::string* ErrMsg = 0);
    500 
    501       /// This method attempts to make the file referenced by the Path object
    502       /// available for writing so that the canWrite() method will return true.
    503       /// @brief Make the file writable;
    504       bool makeWriteableOnDisk(std::string* ErrMsg = 0);
    505 
    506       /// This method attempts to make the file referenced by the Path object
    507       /// available for execution so that the canExecute() method will return
    508       /// true.
    509       /// @brief Make the file readable;
    510       bool makeExecutableOnDisk(std::string* ErrMsg = 0);
    511 
    512       /// This method allows the last modified time stamp and permission bits
    513       /// to be set on the disk object referenced by the Path.
    514       /// @throws std::string if an error occurs.
    515       /// @returns true on error.
    516       /// @brief Set the status information.
    517       bool setStatusInfoOnDisk(const FileStatus &SI,
    518                                std::string *ErrStr = 0) const;
    519 
    520       /// This method attempts to create a directory in the file system with the
    521       /// same name as the Path object. The \p create_parents parameter controls
    522       /// whether intermediate directories are created or not. if \p
    523       /// create_parents is true, then an attempt will be made to create all
    524       /// intermediate directories, as needed. If \p create_parents is false,
    525       /// then only the final directory component of the Path name will be
    526       /// created. The created directory will have no entries.
    527       /// @returns true if the directory could not be created, false otherwise
    528       /// @brief Create the directory this Path refers to.
    529       bool createDirectoryOnDisk(
    530         bool create_parents = false, ///<  Determines whether non-existent
    531            ///< directory components other than the last one (the "parents")
    532            ///< are created or not.
    533         std::string* ErrMsg = 0 ///< Optional place to put error messages.
    534       );
    535 
    536       /// This method attempts to create a file in the file system with the same
    537       /// name as the Path object. The intermediate directories must all exist
    538       /// at the time this method is called. Use createDirectoriesOnDisk to
    539       /// accomplish that. The created file will be empty upon return from this
    540       /// function.
    541       /// @returns true if the file could not be created, false otherwise.
    542       /// @brief Create the file this Path refers to.
    543       bool createFileOnDisk(
    544         std::string* ErrMsg = 0 ///< Optional place to put error messages.
    545       );
    546 
    547       /// This is like createFile except that it creates a temporary file. A
    548       /// unique temporary file name is generated based on the contents of
    549       /// \p this before the call. The new name is assigned to \p this and the
    550       /// file is created.  Note that this will both change the Path object
    551       /// *and* create the corresponding file. This function will ensure that
    552       /// the newly generated temporary file name is unique in the file system.
    553       /// @returns true if the file couldn't be created, false otherwise.
    554       /// @brief Create a unique temporary file
    555       bool createTemporaryFileOnDisk(
    556         bool reuse_current = false, ///< When set to true, this parameter
    557           ///< indicates that if the current file name does not exist then
    558           ///< it will be used without modification.
    559         std::string* ErrMsg = 0 ///< Optional place to put error messages
    560       );
    561 
    562       /// This method renames the file referenced by \p this as \p newName. The
    563       /// file referenced by \p this must exist. The file referenced by
    564       /// \p newName does not need to exist.
    565       /// @returns true on error, false otherwise
    566       /// @brief Rename one file as another.
    567       bool renamePathOnDisk(const Path& newName, std::string* ErrMsg);
    568 
    569       /// This method attempts to destroy the file or directory named by the
    570       /// last component of the Path. If the Path refers to a directory and the
    571       /// \p destroy_contents is false, an attempt will be made to remove just
    572       /// the directory (the final Path component). If \p destroy_contents is
    573       /// true, an attempt will be made to remove the entire contents of the
    574       /// directory, recursively. If the Path refers to a file, the
    575       /// \p destroy_contents parameter is ignored.
    576       /// @param destroy_contents Indicates whether the contents of a destroyed
    577       /// @param Err An optional string to receive an error message.
    578       /// directory should also be destroyed (recursively).
    579       /// @returns false if the file/directory was destroyed, true on error.
    580       /// @brief Removes the file or directory from the filesystem.
    581       bool eraseFromDisk(bool destroy_contents = false,
    582                          std::string *Err = 0) const;
    583 
    584 
    585       /// MapInFilePages - This is a low level system API to map in the file
    586       /// that is currently opened as FD into the current processes' address
    587       /// space for read only access.  This function may return null on failure
    588       /// or if the system cannot provide the following constraints:
    589       ///  1) The pages must be valid after the FD is closed, until
    590       ///     UnMapFilePages is called.
    591       ///  2) Any padding after the end of the file must be zero filled, if
    592       ///     present.
    593       ///  3) The pages must be contiguous.
    594       ///
    595       /// This API is not intended for general use, clients should use
    596       /// MemoryBuffer::getFile instead.
    597       static const char *MapInFilePages(int FD, size_t FileSize,
    598                                         off_t Offset);
    599 
    600       /// UnMapFilePages - Free pages mapped into the current process by
    601       /// MapInFilePages.
    602       ///
    603       /// This API is not intended for general use, clients should use
    604       /// MemoryBuffer::getFile instead.
    605       static void UnMapFilePages(const char *Base, size_t FileSize);
    606 
    607     /// @}
    608     /// @name Data
    609     /// @{
    610     protected:
    611       // Our win32 implementation relies on this string being mutable.
    612       mutable std::string path;   ///< Storage for the path name.
    613 
    614 
    615     /// @}
    616   };
    617 
    618   /// This class is identical to Path class except it allows you to obtain the
    619   /// file status of the Path as well. The reason for the distinction is one of
    620   /// efficiency. First, the file status requires additional space and the space
    621   /// is incorporated directly into PathWithStatus without an additional malloc.
    622   /// Second, obtaining status information is an expensive operation on most
    623   /// operating systems so we want to be careful and explicit about where we
    624   /// allow this operation in LLVM.
    625   /// @brief Path with file status class.
    626   class PathWithStatus : public Path {
    627     /// @name Constructors
    628     /// @{
    629     public:
    630       /// @brief Default constructor
    631       PathWithStatus() : Path(), status(), fsIsValid(false) {}
    632 
    633       /// @brief Copy constructor
    634       PathWithStatus(const PathWithStatus &that)
    635         : Path(static_cast<const Path&>(that)), status(that.status),
    636            fsIsValid(that.fsIsValid) {}
    637 
    638       /// This constructor allows construction from a Path object
    639       /// @brief Path constructor
    640       PathWithStatus(const Path &other)
    641         : Path(other), status(), fsIsValid(false) {}
    642 
    643       /// This constructor will accept a char* or std::string as a path. No
    644       /// checking is done on this path to determine if it is valid. To
    645       /// determine validity of the path, use the isValid method.
    646       /// @brief Construct a Path from a string.
    647       explicit PathWithStatus(
    648         StringRef p ///< The path to assign.
    649       ) : Path(p), status(), fsIsValid(false) {}
    650 
    651       /// This constructor will accept a character range as a path.  No checking
    652       /// is done on this path to determine if it is valid.  To determine
    653       /// validity of the path, use the isValid method.
    654       /// @brief Construct a Path from a string.
    655       explicit PathWithStatus(
    656         const char *StrStart,  ///< Pointer to the first character of the path
    657         unsigned StrLen        ///< Length of the path.
    658       ) : Path(StrStart, StrLen), status(), fsIsValid(false) {}
    659 
    660       /// Makes a copy of \p that to \p this.
    661       /// @returns \p this
    662       /// @brief Assignment Operator
    663       PathWithStatus &operator=(const PathWithStatus &that) {
    664         static_cast<Path&>(*this) = static_cast<const Path&>(that);
    665         status = that.status;
    666         fsIsValid = that.fsIsValid;
    667         return *this;
    668       }
    669 
    670       /// Makes a copy of \p that to \p this.
    671       /// @returns \p this
    672       /// @brief Assignment Operator
    673       PathWithStatus &operator=(const Path &that) {
    674         static_cast<Path&>(*this) = static_cast<const Path&>(that);
    675         fsIsValid = false;
    676         return *this;
    677       }
    678 
    679     /// @}
    680     /// @name Methods
    681     /// @{
    682     public:
    683       /// This function returns status information about the file. The type of
    684       /// path (file or directory) is updated to reflect the actual contents
    685       /// of the file system.
    686       /// @returns 0 on failure, with Error explaining why (if non-zero)
    687       /// @returns a pointer to a FileStatus structure on success.
    688       /// @brief Get file status.
    689       const FileStatus *getFileStatus(
    690         bool forceUpdate = false, ///< Force an update from the file system
    691         std::string *Error = 0    ///< Optional place to return an error msg.
    692       ) const;
    693 
    694     /// @}
    695     /// @name Data
    696     /// @{
    697     private:
    698       mutable FileStatus status; ///< Status information.
    699       mutable bool fsIsValid;    ///< Whether we've obtained it or not
    700 
    701     /// @}
    702   };
    703 
    704   /// This enumeration delineates the kinds of files that LLVM knows about.
    705   enum LLVMFileType {
    706     Unknown_FileType = 0,              ///< Unrecognized file
    707     Bitcode_FileType,                  ///< Bitcode file
    708     Archive_FileType,                  ///< ar style archive file
    709     ELF_Relocatable_FileType,          ///< ELF Relocatable object file
    710     ELF_Executable_FileType,           ///< ELF Executable image
    711     ELF_SharedObject_FileType,         ///< ELF dynamically linked shared lib
    712     ELF_Core_FileType,                 ///< ELF core image
    713     Mach_O_Object_FileType,            ///< Mach-O Object file
    714     Mach_O_Executable_FileType,        ///< Mach-O Executable
    715     Mach_O_FixedVirtualMemorySharedLib_FileType, ///< Mach-O Shared Lib, FVM
    716     Mach_O_Core_FileType,              ///< Mach-O Core File
    717     Mach_O_PreloadExecutable_FileType, ///< Mach-O Preloaded Executable
    718     Mach_O_DynamicallyLinkedSharedLib_FileType, ///< Mach-O dynlinked shared lib
    719     Mach_O_DynamicLinker_FileType,     ///< The Mach-O dynamic linker
    720     Mach_O_Bundle_FileType,            ///< Mach-O Bundle file
    721     Mach_O_DynamicallyLinkedSharedLibStub_FileType, ///< Mach-O Shared lib stub
    722     Mach_O_DSYMCompanion_FileType,     ///< Mach-O dSYM companion file
    723     COFF_FileType                      ///< COFF object file or lib
    724   };
    725 
    726   /// This utility function allows any memory block to be examined in order
    727   /// to determine its file type.
    728   LLVMFileType IdentifyFileType(const char*magic, unsigned length);
    729 
    730   /// This function can be used to copy the file specified by Src to the
    731   /// file specified by Dest. If an error occurs, Dest is removed.
    732   /// @returns true if an error occurs, false otherwise
    733   /// @brief Copy one file to another.
    734   bool CopyFile(const Path& Dest, const Path& Src, std::string* ErrMsg);
    735 
    736   /// This is the OS-specific path separator: a colon on Unix or a semicolon
    737   /// on Windows.
    738   extern const char PathSeparator;
    739 }
    740 
    741 }
    742 
    743 #endif
    744