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