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