Change Path::getStatusInfo to return a boolean and error string on an error
[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 was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source 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 "llvm/System/IncludeFile.h"
19 #include <set>
20 #include <string>
21 #include <vector>
22 #include <iosfwd>
23
24 namespace llvm {
25 namespace sys {
26
27   /// This structure provides basic file system information about a file. It
28   /// is patterned after the stat(2) Unix operating system call but made
29   /// platform independent and eliminates many of the unix-specific fields.
30   /// However, to support llvm-ar, the mode, user, and group fields are
31   /// retained. These pertain to unix security and may not have a meaningful
32   /// value on non-Unix platforms. However, the fileSize and modTime fields
33   /// should always be applicable on all platforms.  The structure is
34   /// filled in by the Path::getFileStatus method.
35   /// @brief File status structure
36   class FileStatus {
37   public:
38     uint64_t    fileSize;   ///< Size of the file in bytes
39     TimeValue   modTime;    ///< Time of file's modification
40     uint32_t    mode;       ///< Mode of the file, if applicable
41     uint32_t    user;       ///< User ID of owner, if applicable
42     uint32_t    group;      ///< Group ID of owner, if applicable
43     bool        isDir  : 1; ///< True if this is a directory.
44     bool        isFile : 1; ///< True if this is a file.
45
46     FileStatus() : fileSize(0), modTime(0,0), mode(0777), user(999),
47                    group(999), isDir(false) { }
48     
49     TimeValue getTimestamp() const { return modTime; }
50     size_t getSize() const { return fileSize; }
51     uint32_t getMode() const { return mode; }
52     uint32_t getUser() const { return user; }
53     uint32_t getGroup() const { return group; }
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       /// @throws std::string indicating why the directory could not be created.
101       /// @brief Constrct a path to an new, unique, existing temporary
102       /// directory.
103       static Path GetTemporaryDirectory();
104
105       /// Construct a vector of sys::Path that contains the "standard" system
106       /// library paths suitable for linking into programs. This function *must*
107       /// return the value of LLVM_LIB_SEARCH_PATH as the first item in \p Paths
108       /// if that environment variable is set and it references a directory.
109       /// @brief Construct a path to the system library directory
110       static void GetSystemLibraryPaths(std::vector<sys::Path>& Paths);
111
112       /// Construct a vector of sys::Path that contains the "standard" bytecode
113       /// library paths suitable for linking into an llvm program. This function
114       /// *must* return the value of LLVM_LIB_SEARCH_PATH as well as the value
115       /// of LLVM_LIBDIR. It also must provide the System library paths as
116       /// returned by GetSystemLibraryPaths.
117       /// @see GetSystemLibraryPaths
118       /// @brief Construct a list of directories in which bytecode could be
119       /// found.
120       static void GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths);
121
122       /// Find the path to a library using its short name. Use the system
123       /// dependent library paths to locate the library.
124       /// @brief Find a library.
125       static Path  FindLibrary(std::string& short_name);
126
127       /// Construct a path to the default LLVM configuration directory. The
128       /// implementation must ensure that this is a well-known (same on many
129       /// systems) directory in which llvm configuration files exist. For
130       /// example, on Unix, the /etc/llvm directory has been selected.
131       /// @brief Construct a path to the default LLVM configuration directory
132       static Path GetLLVMDefaultConfigDir();
133
134       /// Construct a path to the LLVM installed configuration directory. The
135       /// implementation must ensure that this refers to the "etc" directory of
136       /// the LLVM installation. This is the location where configuration files
137       /// will be located for a particular installation of LLVM on a machine.
138       /// @brief Construct a path to the LLVM installed configuration directory
139       static Path GetLLVMConfigDir();
140
141       /// Construct a path to the current user's home directory. The
142       /// implementation must use an operating system specific mechanism for
143       /// determining the user's home directory. For example, the environment
144       /// variable "HOME" could be used on Unix. If a given operating system
145       /// does not have the concept of a user's home directory, this static
146       /// constructor must provide the same result as GetRootDirectory.
147       /// @brief Construct a path to the current user's "home" directory
148       static Path GetUserHomeDirectory();
149
150       /// Return the suffix commonly used on file names that contain a shared
151       /// object, shared archive, or dynamic link library. Such files are
152       /// linked at runtime into a process and their code images are shared
153       /// between processes.
154       /// @returns The dynamic link library suffix for the current platform.
155       /// @brief Return the dynamic link library suffix.
156       static std::string GetDLLSuffix();
157
158       /// This is one of the very few ways in which a path can be constructed
159       /// with a syntactically invalid name. The only *legal* invalid name is an
160       /// empty one. Other invalid names are not permitted. Empty paths are
161       /// provided so that they can be used to indicate null or error results in
162       /// other lib/System functionality.
163       /// @brief Construct an empty (and invalid) path.
164       Path() : path() {}
165
166       /// This constructor will accept a std::string as a path but it verifies
167       /// that the path string has a legal syntax for the operating system on
168       /// which it is running. This allows a path to be taken in from outside
169       /// the program. However, if the path is not valid, the Path object will
170       /// be set to an empty string and an exception will be thrown.
171       /// @throws std::string if \p unverified_path is not legal.
172       /// @param unverified_path The path to verify and assign.
173       /// @brief Construct a Path from a string.
174       explicit Path(const std::string& unverified_path);
175
176     /// @}
177     /// @name Operators
178     /// @{
179     public:
180       /// Makes a copy of \p that to \p this.
181       /// @returns \p this
182       /// @brief Assignment Operator
183       Path &operator=(const Path &that) {
184         path = that.path;
185         return *this;
186       }
187
188       /// Compares \p this Path with \p that Path for equality.
189       /// @returns true if \p this and \p that refer to the same thing.
190       /// @brief Equality Operator
191       bool operator==(const Path &that) const {
192         return 0 == path.compare(that.path);
193       }
194
195       /// Compares \p this Path with \p that Path for inequality.
196       /// @returns true if \p this and \p that refer to different things.
197       /// @brief Inequality Operator
198       bool operator!=(const Path &that) const {
199         return 0 != path.compare(that.path);
200       }
201
202       /// Determines if \p this Path is less than \p that Path. This is required
203       /// so that Path objects can be placed into ordered collections (e.g.
204       /// std::map). The comparison is done lexicographically as defined by
205       /// the std::string::compare method.
206       /// @returns true if \p this path is lexicographically less than \p that.
207       /// @brief Less Than Operator
208       bool operator<(const Path& that) const {
209         return 0 > path.compare(that.path);
210       }
211
212     /// @}
213     /// @name Path Accessors
214     /// @{
215     public:
216       /// This function will use an operating system specific algorithm to
217       /// determine if the current value of \p this is a syntactically valid
218       /// path name for the operating system. The path name does not need to
219       /// exist, validity is simply syntactical. Empty paths are always invalid.
220       /// @returns true iff the path name is syntactically legal for the
221       /// host operating system.
222       /// @brief Determine if a path is syntactically valid or not.
223       bool isValid() const;
224
225       /// This function determines if the contents of the path name are
226       /// empty. That is, the path has a zero length. This does NOT determine if
227       /// if the file is empty. Use the getSize method for that.
228       /// @returns true iff the path is empty.
229       /// @brief Determines if the path name is empty (invalid).
230       bool isEmpty() const { return path.empty(); }
231
232       /// This function returns the current contents of the path as a
233       /// std::string. This allows the underlying path string to be manipulated.
234       /// @returns std::string containing the path name.
235       /// @brief Returns the path as a std::string.
236       const std::string &toString() const { return path; }
237
238       /// This function returns the last component of the path name. The last
239       /// component is the file or directory name occuring after the last
240       /// directory separator. If no directory separator is present, the entire
241       /// path name is returned (i.e. same as toString).
242       /// @returns std::string containing the last component of the path name.
243       /// @brief Returns the last component of the path name.
244       std::string getLast() const;
245
246       /// This function strips off the path and suffix of the file or directory
247       /// name and returns just the basename. For example /a/foo.bar would cause
248       /// this function to return "foo".
249       /// @returns std::string containing the basename of the path
250       /// @brief Get the base name of the path
251       std::string getBasename() const;
252
253       /// Obtain a 'C' string for the path name.
254       /// @returns a 'C' string containing the path name.
255       /// @brief Returns the path as a C string.
256       const char *const c_str() const { return path.c_str(); }
257
258     /// @}
259     /// @name Disk Accessors
260     /// @{
261     public:
262       /// This function determines if the object referenced by this path is
263       /// a file or not. This function accesses the underlying file system to
264       /// determine the type of entity referenced by the path.
265       /// @returns true if this path name references a file.
266       /// @brief Determines if the path name references a file.
267       bool isFile() const;
268
269       /// This function determines if the object referenced by this path is a
270       /// directory or not. This function accesses the underlying file system to
271       /// determine the type of entity referenced by the path.
272       /// @returns true if the path name references a directory
273       /// @brief Determines if the path name references a directory.
274       bool isDirectory() const;
275
276       /// This function determines if the path refers to a hidden file. The
277       /// notion of hidden files is defined by  the underlying system. The
278       /// system may not support hidden files in which case this function always
279       /// returns false on such systems. Hidden files have the "hidden"
280       /// attribute set on Win32. On Unix, hidden files start with a period.
281       /// @brief Determines if the path name references a hidden file.
282       bool isHidden() const;
283
284       /// This function determines if the path name in this object references
285       /// the root (top level directory) of the file system. The details of what
286       /// is considered the "root" may vary from system to system so this method
287       /// will do the necessary checking.
288       /// @returns true iff the path name references the root directory.
289       /// @brief Determines if the path references the root directory.
290       bool isRootDirectory() const;
291
292       /// This function opens the file associated with the path name provided by
293       /// the Path object and reads its magic number. If the magic number at the
294       /// start of the file matches \p magic, true is returned. In all other
295       /// cases (file not found, file not accessible, etc.) it returns false.
296       /// @returns true if the magic number of the file matches \p magic.
297       /// @brief Determine if file has a specific magic number
298       bool hasMagicNumber(const std::string& magic) const;
299
300       /// This function retrieves the first \p len bytes of the file associated
301       /// with \p this. These bytes are returned as the "magic number" in the
302       /// \p Magic parameter.
303       /// @returns true if the Path is a file and the magic number is retrieved,
304       /// false otherwise.
305       /// @brief Get the file's magic number.
306       bool getMagicNumber(std::string& Magic, unsigned len) const;
307
308       /// This function determines if the path name in the object references an
309       /// archive file by looking at its magic number.
310       /// @returns true if the file starts with the magic number for an archive
311       /// file.
312       /// @brief Determine if the path references an archive file.
313       bool isArchive() const;
314
315       /// This function determines if the path name in the object references an
316       /// LLVM Bytecode file by looking at its magic number.
317       /// @returns true if the file starts with the magic number for LLVM
318       /// bytecode files.
319       /// @brief Determine if the path references a bytecode file.
320       bool isBytecodeFile() const;
321
322       /// This function determines if the path name in the object references a
323       /// native Dynamic Library (shared library, shared object) by looking at
324       /// the file's magic number. The Path object must reference a file, not a
325       /// directory.
326       /// @return strue if the file starts with the magid number for a native
327       /// shared library.
328       /// @brief Determine if the path reference a dynamic library.
329       bool isDynamicLibrary() const;
330
331       /// This function determines if the path name references an existing file
332       /// or directory in the file system.
333       /// @returns true if the pathname references an existing file or
334       /// directory.
335       /// @brief Determines if the path is a file or directory in
336       /// the file system.
337       bool exists() const;
338
339       /// This function determines if the path name references a readable file
340       /// or directory in the file system. This function checks for
341       /// the existence and readability (by the current program) of the file
342       /// or directory.
343       /// @returns true if the pathname references a readable file.
344       /// @brief Determines if the path is a readable file or directory
345       /// in the file system.
346       bool canRead() const;
347
348       /// This function determines if the path name references a writable file
349       /// or directory in the file system. This function checks for the
350       /// existence and writability (by the current program) of the file or
351       /// directory.
352       /// @returns true if the pathname references a writable file.
353       /// @brief Determines if the path is a writable file or directory
354       /// in the file system.
355       bool canWrite() const;
356
357       /// This function determines if the path name references an executable
358       /// file in the file system. This function checks for the existence and
359       /// executability (by the current program) of the file.
360       /// @returns true if the pathname references an executable file.
361       /// @brief Determines if the path is an executable file in the file
362       /// system.
363       bool canExecute() const;
364
365       /// This function builds a list of paths that are the names of the
366       /// files and directories in a directory.
367       /// @returns false if \p this is not a directory, true otherwise
368       /// @throws std::string if the directory cannot be searched
369       /// @brief Build a list of directory's contents.
370       bool getDirectoryContents(std::set<Path> &paths) const;
371
372       /// This function returns status information about the file. The type of
373       /// path (file or directory) is updated to reflect the actual contents
374       /// of the file system.  This returns false on success, or true on error
375       /// and fills in the specified error string if specified.
376       /// @brief Get file status.
377       bool getFileStatus(FileStatus &Status, std::string *Error = 0) const;
378
379     /// @}
380     /// @name Path Mutators
381     /// @{
382     public:
383       /// The path name is cleared and becomes empty. This is an invalid
384       /// path name but is the *only* invalid path name. This is provided
385       /// so that path objects can be used to indicate the lack of a
386       /// valid path being found.
387       /// @brief Make the path empty.
388       void clear() { path.clear(); }
389
390       /// This method sets the Path object to \p unverified_path. This can fail
391       /// if the \p unverified_path does not pass the syntactic checks of the
392       /// isValid() method. If verification fails, the Path object remains
393       /// unchanged and false is returned. Otherwise true is returned and the
394       /// Path object takes on the path value of \p unverified_path
395       /// @returns true if the path was set, false otherwise.
396       /// @param unverified_path The path to be set in Path object.
397       /// @brief Set a full path from a std::string
398       bool set(const std::string& unverified_path);
399
400       /// One path component is removed from the Path. If only one component is
401       /// present in the path, the Path object becomes empty. If the Path object
402       /// is empty, no change is made.
403       /// @returns false if the path component could not be removed.
404       /// @brief Removes the last directory component of the Path.
405       bool eraseComponent();
406
407       /// The \p component is added to the end of the Path if it is a legal
408       /// name for the operating system. A directory separator will be added if
409       /// needed.
410       /// @returns false if the path component could not be added.
411       /// @brief Appends one path component to the Path.
412       bool appendComponent( const std::string& component );
413
414       /// A period and the \p suffix are appended to the end of the pathname.
415       /// The precondition for this function is that the Path reference a file
416       /// name (i.e. isFile() returns true). If the Path is not a file, no
417       /// action is taken and the function returns false. If the path would
418       /// become invalid for the host operating system, false is returned.
419       /// @returns false if the suffix could not be added, true if it was.
420       /// @brief Adds a period and the \p suffix to the end of the pathname.
421       bool appendSuffix(const std::string& suffix);
422
423       /// The suffix of the filename is erased. The suffix begins with and
424       /// includes the last . character in the filename after the last directory
425       /// separator and extends until the end of the name. If no . character is
426       /// after the last directory separator, then the file name is left
427       /// unchanged (i.e. it was already without a suffix) but the function
428       /// returns false.
429       /// @returns false if there was no suffix to remove, true otherwise.
430       /// @brief Remove the suffix from a path name.
431       bool eraseSuffix();
432
433       /// The current Path name is made unique in the file system. Upon return,
434       /// the Path will have been changed to make a unique file in the file
435       /// system or it will not have been changed if the current path name is
436       /// already unique.
437       /// @throws std::string if an unrecoverable error occurs.
438       /// @brief Make the current path name unique in the file system.
439       void makeUnique( bool reuse_current = true );
440
441     /// @}
442     /// @name Disk Mutators
443     /// @{
444     public:
445       /// This method attempts to make the file referenced by the Path object
446       /// available for reading so that the canRead() method will return true.
447       /// @brief Make the file readable;
448       void makeReadableOnDisk();
449
450       /// This method attempts to make the file referenced by the Path object
451       /// available for writing so that the canWrite() method will return true.
452       /// @brief Make the file writable;
453       void makeWriteableOnDisk();
454
455       /// This method attempts to make the file referenced by the Path object
456       /// available for execution so that the canExecute() method will return
457       /// true.
458       /// @brief Make the file readable;
459       void makeExecutableOnDisk();
460
461       /// This method allows the last modified time stamp and permission bits
462       /// to be set on the disk object referenced by the Path.
463       /// @throws std::string if an error occurs.
464       /// @returns true
465       /// @brief Set the status information.
466       bool setStatusInfoOnDisk(const FileStatus &SI) const;
467
468       /// This method attempts to create a directory in the file system with the
469       /// same name as the Path object. The \p create_parents parameter controls
470       /// whether intermediate directories are created or not. if \p
471       /// create_parents is true, then an attempt will be made to create all
472       /// intermediate directories, as needed. If \p create_parents is false,
473       /// then only the final directory component of the Path name will be
474       /// created. The created directory will have no entries.
475       /// @returns false if the Path does not reference a directory, true
476       /// otherwise.
477       /// @param create_parents Determines whether non-existent directory
478       /// components other than the last one (the "parents") are created or not.
479       /// @throws std::string if an error occurs.
480       /// @brief Create the directory this Path refers to.
481       bool createDirectoryOnDisk( bool create_parents = false );
482
483       /// This method attempts to create a file in the file system with the same
484       /// name as the Path object. The intermediate directories must all exist
485       /// at the time this method is called. Use createDirectoriesOnDisk to
486       /// accomplish that. The created file will be empty upon return from this
487       /// function.
488       /// @returns false if the Path does not reference a file, true otherwise.
489       /// @throws std::string if an error occurs.
490       /// @brief Create the file this Path refers to.
491       bool createFileOnDisk();
492
493       /// This is like createFile except that it creates a temporary file. A
494       /// unique temporary file name is generated based on the contents of
495       /// \p this before the call. The new name is assigned to \p this and the
496       /// file is created.  Note that this will both change the Path object
497       /// *and* create the corresponding file. This function will ensure that
498       /// the newly generated temporary file name is unique in the file system.
499       /// @param reuse_current When set to true, this parameter indicates that
500       /// if the current file name does not exist then it will be used without
501       /// modification.
502       /// @returns true if successful, false if the file couldn't be created.
503       /// @throws std::string if there is a hard error creating the temp file
504       /// name.
505       /// @brief Create a unique temporary file
506       bool createTemporaryFileOnDisk(bool reuse_current = false);
507
508       /// This method renames the file referenced by \p this as \p newName. The
509       /// file referenced by \p this must exist. The file referenced by
510       /// \p newName does not need to exist.
511       /// @returns true
512       /// @throws std::string if there is an file system error.
513       /// @brief Rename one file as another.
514       bool renamePathOnDisk(const Path& newName);
515
516       /// This method attempts to destroy the file or directory named by the
517       /// last component of the Path. If the Path refers to a directory and the
518       /// \p destroy_contents is false, an attempt will be made to remove just
519       /// the directory (the final Path component). If \p destroy_contents is
520       /// true, an attempt will be made to remove the entire contents of the
521       /// directory, recursively. If the Path refers to a file, the
522       /// \p destroy_contents parameter is ignored.
523       /// @param destroy_contents Indicates whether the contents of a destroyed
524       /// directory should also be destroyed (recursively).
525       /// @returns true if the file/directory was destroyed, false if the path
526       /// refers to something that is neither a file nor a directory.
527       /// @throws std::string if there is an error.
528       /// @brief Removes the file or directory from the filesystem.
529       bool eraseFromDisk(bool destroy_contents = false) const;
530
531     /// @}
532     /// @name Data
533     /// @{
534     private:
535         mutable std::string path;   ///< Storage for the path name.
536
537     /// @}
538   };
539
540   /// This enumeration delineates the kinds of files that LLVM knows about.
541   enum LLVMFileType {
542     UnknownFileType = 0,            ///< Unrecognized file
543     BytecodeFileType = 1,           ///< Uncompressed bytecode file
544     CompressedBytecodeFileType = 2, ///< Compressed bytecode file
545     ArchiveFileType = 3             ///< ar style archive file
546   };
547
548   /// This utility function allows any memory block to be examined in order
549   /// to determine its file type.
550   LLVMFileType IdentifyFileType(const char*magic, unsigned length);
551
552   /// This function can be used to copy the file specified by Src to the
553   /// file specified by Dest. If an error occurs, Dest is removed.
554   /// @throws std::string if an error opening or writing the files occurs.
555   /// @brief Copy one file to another.
556   void CopyFile(const Path& Dest, const Path& Src);
557 }
558
559 std::ostream& operator<<(std::ostream& strm, const sys::Path& aPath);
560
561 }
562
563 FORCE_DEFINING_FILE_TO_BE_LINKED(SystemPath)
564 #endif