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