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