1 //===- llvm/Support/PathV1.h - Path Operating System Concept ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the llvm::sys::Path class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_PATHV1_H
15 #define LLVM_SUPPORT_PATHV1_H
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/TimeValue.h"
24 #define LLVM_PATH_DEPRECATED_MSG(replacement) \
25 "PathV1 has been deprecated and will be removed as soon as all LLVM and" \
26 " Clang clients have been moved over to PathV2. Please use `" #replacement \
27 "` from PathV2 instead."
32 /// This structure provides basic file system information about a file. It
33 /// is patterned after the stat(2) Unix operating system call but made
34 /// platform independent and eliminates many of the unix-specific fields.
35 /// However, to support llvm-ar, the mode, user, and group fields are
36 /// retained. These pertain to unix security and may not have a meaningful
37 /// value on non-Unix platforms. However, the other fields should
38 /// always be applicable on all platforms. The structure is filled in by
39 /// the PathWithStatus class.
40 /// @brief File status structure
43 uint64_t fileSize; ///< Size of the file in bytes
44 TimeValue modTime; ///< Time of file's modification
45 uint32_t mode; ///< Mode of the file, if applicable
46 uint32_t user; ///< User ID of owner, if applicable
47 uint32_t group; ///< Group ID of owner, if applicable
48 uint64_t uniqueID; ///< A number to uniquely ID this file
49 bool isDir : 1; ///< True if this is a directory.
50 bool isFile : 1; ///< True if this is a file.
52 FileStatus() : fileSize(0), modTime(0,0), mode(0777), user(999),
53 group(999), uniqueID(0), isDir(false), isFile(false) { }
55 TimeValue getTimestamp() const { return modTime; }
56 uint64_t getSize() const { return fileSize; }
57 uint32_t getMode() const { return mode; }
58 uint32_t getUser() const { return user; }
59 uint32_t getGroup() const { return group; }
60 uint64_t getUniqueID() const { return uniqueID; }
63 /// This class provides an abstraction for the path to a file or directory
64 /// in the operating system's filesystem and provides various basic operations
65 /// on it. Note that this class only represents the name of a path to a file
66 /// or directory which may or may not be valid for a given machine's file
67 /// system. The class is patterned after the java.io.File class with various
68 /// extensions and several omissions (not relevant to LLVM). A Path object
69 /// ensures that the path it encapsulates is syntactically valid for the
70 /// operating system it is running on but does not ensure correctness for
71 /// any particular file system. That is, a syntactically valid path might
72 /// specify path components that do not exist in the file system and using
73 /// such a Path to act on the file system could produce errors. There is one
74 /// invalid Path value which is permitted: the empty path. The class should
75 /// never allow a syntactically invalid non-empty path name to be assigned.
76 /// Empty paths are required in order to indicate an error result in some
77 /// situations. If the path is empty, the isValid operation will return
78 /// false. All operations will fail if isValid is false. Operations that
79 /// change the path will either return false if it would cause a syntactically
80 /// invalid path name (in which case the Path object is left unchanged) or
81 /// throw an std::string exception indicating the error. The methods are
82 /// grouped into four basic categories: Path Accessors (provide information
83 /// about the path without accessing disk), Disk Accessors (provide
84 /// information about the underlying file or directory), Path Mutators
85 /// (change the path information, not the disk), and Disk Mutators (change
86 /// the disk file/directory referenced by the path). The Disk Mutator methods
87 /// all have the word "disk" embedded in their method name to reinforce the
88 /// notion that the operation modifies the file system.
90 /// @brief An abstraction for operating system paths.
92 /// @name Constructors
95 /// Construct a path to a unique temporary directory that is created in
96 /// a "standard" place for the operating system. The directory is
97 /// guaranteed to be created on exit from this function. If the directory
98 /// cannot be created, the function will throw an exception.
99 /// @returns an invalid path (empty) on error
100 /// @param ErrMsg Optional place for an error message if an error occurs
101 /// @brief Construct a path to an new, unique, existing temporary
103 static Path GetTemporaryDirectory(std::string* ErrMsg = 0);
105 /// Construct a path to the current directory for the current process.
106 /// @returns The current working directory.
107 /// @brief Returns the current working directory.
108 static Path GetCurrentDirectory();
110 /// Return the suffix commonly used on file names that contain an
112 /// @returns The executable file suffix for the current platform.
113 /// @brief Return the executable file suffix.
114 static StringRef GetEXESuffix();
116 /// GetMainExecutable - Return the path to the main executable, given the
117 /// value of argv[0] from program startup and the address of main itself.
118 /// In extremis, this function may fail and return an empty path.
119 static Path GetMainExecutable(const char *argv0, void *MainAddr);
121 /// This is one of the very few ways in which a path can be constructed
122 /// with a syntactically invalid name. The only *legal* invalid name is an
123 /// empty one. Other invalid names are not permitted. Empty paths are
124 /// provided so that they can be used to indicate null or error results in
125 /// other lib/System functionality.
126 /// @brief Construct an empty (and invalid) path.
128 Path(const Path &that) : path(that.path) {}
130 /// This constructor will accept a char* or std::string as a path. No
131 /// checking is done on this path to determine if it is valid. To
132 /// determine validity of the path, use the isValid method.
133 /// @param p The path to assign.
134 /// @brief Construct a Path from a string.
135 explicit Path(StringRef p);
137 /// This constructor will accept a character range as a path. No checking
138 /// is done on this path to determine if it is valid. To determine
139 /// validity of the path, use the isValid method.
140 /// @param StrStart A pointer to the first character of the path name
141 /// @param StrLen The length of the path name at StrStart
142 /// @brief Construct a Path from a string.
143 Path(const char *StrStart, unsigned StrLen);
149 /// Makes a copy of \p that to \p this.
151 /// @brief Assignment Operator
152 Path &operator=(const Path &that) {
157 /// Makes a copy of \p that to \p this.
158 /// @param that A StringRef denoting the path
160 /// @brief Assignment Operator
161 Path &operator=(StringRef that);
163 /// Compares \p this Path with \p that Path for equality.
164 /// @returns true if \p this and \p that refer to the same thing.
165 /// @brief Equality Operator
166 bool operator==(const Path &that) const;
168 /// Compares \p this Path with \p that Path for inequality.
169 /// @returns true if \p this and \p that refer to different things.
170 /// @brief Inequality Operator
171 bool operator!=(const Path &that) const { return !(*this == that); }
173 /// Determines if \p this Path is less than \p that Path. This is required
174 /// so that Path objects can be placed into ordered collections (e.g.
175 /// std::map). The comparison is done lexicographically as defined by
176 /// the std::string::compare method.
177 /// @returns true if \p this path is lexicographically less than \p that.
178 /// @brief Less Than Operator
179 bool operator<(const Path& that) const;
182 /// @name Path Accessors
185 /// This function will use an operating system specific algorithm to
186 /// determine if the current value of \p this is a syntactically valid
187 /// path name for the operating system. The path name does not need to
188 /// exist, validity is simply syntactical. Empty paths are always invalid.
189 /// @returns true iff the path name is syntactically legal for the
190 /// host operating system.
191 /// @brief Determine if a path is syntactically valid or not.
192 bool isValid() const;
194 /// This function determines if the contents of the path name are empty.
195 /// That is, the path name has a zero length. This does NOT determine if
196 /// if the file is empty. To get the length of the file itself, Use the
197 /// PathWithStatus::getFileStatus() method and then the getSize() method
198 /// on the returned FileStatus object.
199 /// @returns true iff the path is empty.
200 /// @brief Determines if the path name is empty (invalid).
201 bool isEmpty() const { return path.empty(); }
203 /// This function strips off the path and basename(up to and
204 /// including the last dot) of the file or directory name and
205 /// returns just the suffix. For example /a/foo.bar would cause
206 /// this function to return "bar".
207 /// @returns StringRef containing the suffix of the path
208 /// @brief Get the suffix of the path
209 LLVM_ATTRIBUTE_DEPRECATED(StringRef getSuffix() const,
210 LLVM_PATH_DEPRECATED_MSG(path::extension));
212 /// Obtain a 'C' string for the path name.
213 /// @returns a 'C' string containing the path name.
214 /// @brief Returns the path as a C string.
215 const char *c_str() const { return path.c_str(); }
216 const std::string &str() const { return path; }
219 /// size - Return the length in bytes of this path name.
220 size_t size() const { return path.size(); }
222 /// empty - Returns true if the path is empty.
223 unsigned empty() const { return path.empty(); }
226 /// @name Disk Accessors
229 /// This function determines if the path name is absolute, as opposed to
231 /// @brief Determine if the path is absolute.
232 LLVM_ATTRIBUTE_DEPRECATED(
233 bool isAbsolute() const,
234 LLVM_PATH_DEPRECATED_MSG(path::is_absolute));
236 /// This function determines if the path name is absolute, as opposed to
238 /// @brief Determine if the path is absolute.
239 LLVM_ATTRIBUTE_DEPRECATED(
240 static bool isAbsolute(const char *NameStart, unsigned NameLen),
241 LLVM_PATH_DEPRECATED_MSG(path::is_absolute));
243 /// This function opens the file associated with the path name provided by
244 /// the Path object and reads its magic number. If the magic number at the
245 /// start of the file matches \p magic, true is returned. In all other
246 /// cases (file not found, file not accessible, etc.) it returns false.
247 /// @returns true if the magic number of the file matches \p magic.
248 /// @brief Determine if file has a specific magic number
249 LLVM_ATTRIBUTE_DEPRECATED(bool hasMagicNumber(StringRef magic) const,
250 LLVM_PATH_DEPRECATED_MSG(fs::has_magic));
252 /// This function retrieves the first \p len bytes of the file associated
253 /// with \p this. These bytes are returned as the "magic number" in the
254 /// \p Magic parameter.
255 /// @returns true if the Path is a file and the magic number is retrieved,
257 /// @brief Get the file's magic number.
258 bool getMagicNumber(std::string& Magic, unsigned len) const;
260 /// This function determines if the path name in the object references an
261 /// archive file by looking at its magic number.
262 /// @returns true if the file starts with the magic number for an archive
264 /// @brief Determine if the path references an archive file.
265 bool isArchive() const;
267 /// This function determines if the path name in the object references an
268 /// LLVM Bitcode file by looking at its magic number.
269 /// @returns true if the file starts with the magic number for LLVM
271 /// @brief Determine if the path references a bitcode file.
272 bool isBitcodeFile() const;
274 /// This function determines if the path name in the object references a
275 /// native Dynamic Library (shared library, shared object) by looking at
276 /// the file's magic number. The Path object must reference a file, not a
278 /// @returns true if the file starts with the magic number for a native
280 /// @brief Determine if the path references a dynamic library.
281 bool isDynamicLibrary() const;
283 /// This function determines if the path name in the object references a
284 /// native object file by looking at it's magic number. The term object
285 /// file is defined as "an organized collection of separate, named
286 /// sequences of binary data." This covers the obvious file formats such
287 /// as COFF and ELF, but it also includes llvm ir bitcode, archives,
288 /// libraries, etc...
289 /// @returns true if the file starts with the magic number for an object
291 /// @brief Determine if the path references an object file.
292 bool isObjectFile() const;
294 /// This function determines if the path name references an existing file
295 /// or directory in the file system.
296 /// @returns true if the pathname references an existing file or
298 /// @brief Determines if the path is a file or directory in
300 LLVM_ATTRIBUTE_DEPRECATED(bool exists() const,
301 LLVM_PATH_DEPRECATED_MSG(fs::exists));
303 /// This function determines if the path name references an
304 /// existing directory.
305 /// @returns true if the pathname references an existing directory.
306 /// @brief Determines if the path is a directory in the file system.
307 LLVM_ATTRIBUTE_DEPRECATED(bool isDirectory() const,
308 LLVM_PATH_DEPRECATED_MSG(fs::is_directory));
310 /// This function determines if the path name references an
311 /// existing symbolic link.
312 /// @returns true if the pathname references an existing symlink.
313 /// @brief Determines if the path is a symlink in the file system.
314 LLVM_ATTRIBUTE_DEPRECATED(bool isSymLink() const,
315 LLVM_PATH_DEPRECATED_MSG(fs::is_symlink));
317 /// This function determines if the path name references a readable file
318 /// or directory in the file system. This function checks for
319 /// the existence and readability (by the current program) of the file
321 /// @returns true if the pathname references a readable file.
322 /// @brief Determines if the path is a readable file or directory
323 /// in the file system.
324 bool canRead() const;
326 /// This function determines if the path name references a writable file
327 /// or directory in the file system. This function checks for the
328 /// existence and writability (by the current program) of the file or
330 /// @returns true if the pathname references a writable file.
331 /// @brief Determines if the path is a writable file or directory
332 /// in the file system.
333 bool canWrite() const;
335 /// This function checks that what we're trying to work only on a regular
336 /// file. Check for things like /dev/null, any block special file, or
337 /// other things that aren't "regular" regular files.
338 /// @returns true if the file is S_ISREG.
339 /// @brief Determines if the file is a regular file
340 bool isRegularFile() const;
342 /// This function determines if the path name references an executable
343 /// file in the file system. This function checks for the existence and
344 /// executability (by the current program) of the file.
345 /// @returns true if the pathname references an executable file.
346 /// @brief Determines if the path is an executable file in the file
348 bool canExecute() const;
350 /// This function builds a list of paths that are the names of the
351 /// files and directories in a directory.
352 /// @returns true if an error occurs, true otherwise
353 /// @brief Build a list of directory's contents.
354 bool getDirectoryContents(
355 std::set<Path> &paths, ///< The resulting list of file & directory names
356 std::string* ErrMsg ///< Optional place to return an error message.
360 /// @name Path Mutators
363 /// The path name is cleared and becomes empty. This is an invalid
364 /// path name but is the *only* invalid path name. This is provided
365 /// so that path objects can be used to indicate the lack of a
366 /// valid path being found.
367 /// @brief Make the path empty.
368 void clear() { path.clear(); }
370 /// This method sets the Path object to \p unverified_path. This can fail
371 /// if the \p unverified_path does not pass the syntactic checks of the
372 /// isValid() method. If verification fails, the Path object remains
373 /// unchanged and false is returned. Otherwise true is returned and the
374 /// Path object takes on the path value of \p unverified_path
375 /// @returns true if the path was set, false otherwise.
376 /// @param unverified_path The path to be set in Path object.
377 /// @brief Set a full path from a StringRef
378 bool set(StringRef unverified_path);
380 /// One path component is removed from the Path. If only one component is
381 /// present in the path, the Path object becomes empty. If the Path object
382 /// is empty, no change is made.
383 /// @returns false if the path component could not be removed.
384 /// @brief Removes the last directory component of the Path.
385 bool eraseComponent();
387 /// The \p component is added to the end of the Path if it is a legal
388 /// name for the operating system. A directory separator will be added if
390 /// @returns false if the path component could not be added.
391 /// @brief Appends one path component to the Path.
392 bool appendComponent(StringRef component);
394 /// A period and the \p suffix are appended to the end of the pathname.
395 /// When the \p suffix is empty, no action is performed.
396 /// @brief Adds a period and the \p suffix to the end of the pathname.
397 void appendSuffix(StringRef suffix);
399 /// The suffix of the filename is erased. The suffix begins with and
400 /// includes the last . character in the filename after the last directory
401 /// separator and extends until the end of the name. If no . character is
402 /// after the last directory separator, then the file name is left
403 /// unchanged (i.e. it was already without a suffix) but the function
405 /// @returns false if there was no suffix to remove, true otherwise.
406 /// @brief Remove the suffix from a path name.
409 /// The current Path name is made unique in the file system. Upon return,
410 /// the Path will have been changed to make a unique file in the file
411 /// system or it will not have been changed if the current path name is
413 /// @throws std::string if an unrecoverable error occurs.
414 /// @brief Make the current path name unique in the file system.
415 bool makeUnique( bool reuse_current /*= true*/, std::string* ErrMsg );
417 /// The current Path name is made absolute by prepending the
418 /// current working directory if necessary.
419 LLVM_ATTRIBUTE_DEPRECATED(
421 LLVM_PATH_DEPRECATED_MSG(fs::make_absolute));
424 /// @name Disk Mutators
427 /// This method attempts to make the file referenced by the Path object
428 /// available for reading so that the canRead() method will return true.
429 /// @brief Make the file readable;
430 bool makeReadableOnDisk(std::string* ErrMsg = 0);
432 /// This method attempts to make the file referenced by the Path object
433 /// available for writing so that the canWrite() method will return true.
434 /// @brief Make the file writable;
435 bool makeWriteableOnDisk(std::string* ErrMsg = 0);
437 /// This method allows the last modified time stamp and permission bits
438 /// to be set on the disk object referenced by the Path.
439 /// @throws std::string if an error occurs.
440 /// @returns true on error.
441 /// @brief Set the status information.
442 bool setStatusInfoOnDisk(const FileStatus &SI,
443 std::string *ErrStr = 0) const;
445 /// This method attempts to create a directory in the file system with the
446 /// same name as the Path object. The \p create_parents parameter controls
447 /// whether intermediate directories are created or not. if \p
448 /// create_parents is true, then an attempt will be made to create all
449 /// intermediate directories, as needed. If \p create_parents is false,
450 /// then only the final directory component of the Path name will be
451 /// created. The created directory will have no entries.
452 /// @returns true if the directory could not be created, false otherwise
453 /// @brief Create the directory this Path refers to.
454 bool createDirectoryOnDisk(
455 bool create_parents = false, ///< Determines whether non-existent
456 ///< directory components other than the last one (the "parents")
457 ///< are created or not.
458 std::string* ErrMsg = 0 ///< Optional place to put error messages.
461 /// This is like createFile except that it creates a temporary file. A
462 /// unique temporary file name is generated based on the contents of
463 /// \p this before the call. The new name is assigned to \p this and the
464 /// file is created. Note that this will both change the Path object
465 /// *and* create the corresponding file. This function will ensure that
466 /// the newly generated temporary file name is unique in the file system.
467 /// @returns true if the file couldn't be created, false otherwise.
468 /// @brief Create a unique temporary file
469 bool createTemporaryFileOnDisk(
470 bool reuse_current = false, ///< When set to true, this parameter
471 ///< indicates that if the current file name does not exist then
472 ///< it will be used without modification.
473 std::string* ErrMsg = 0 ///< Optional place to put error messages
476 /// This method renames the file referenced by \p this as \p newName. The
477 /// file referenced by \p this must exist. The file referenced by
478 /// \p newName does not need to exist.
479 /// @returns true on error, false otherwise
480 /// @brief Rename one file as another.
481 bool renamePathOnDisk(const Path& newName, std::string* ErrMsg);
483 /// This method attempts to destroy the file or directory named by the
484 /// last component of the Path. If the Path refers to a directory and the
485 /// \p destroy_contents is false, an attempt will be made to remove just
486 /// the directory (the final Path component). If \p destroy_contents is
487 /// true, an attempt will be made to remove the entire contents of the
488 /// directory, recursively. If the Path refers to a file, the
489 /// \p destroy_contents parameter is ignored.
490 /// @param destroy_contents Indicates whether the contents of a destroyed
491 /// @param Err An optional string to receive an error message.
492 /// directory should also be destroyed (recursively).
493 /// @returns false if the file/directory was destroyed, true on error.
494 /// @brief Removes the file or directory from the filesystem.
495 bool eraseFromDisk(bool destroy_contents = false,
496 std::string *Err = 0) const;
502 // Our win32 implementation relies on this string being mutable.
503 mutable std::string path; ///< Storage for the path name.
509 /// This class is identical to Path class except it allows you to obtain the
510 /// file status of the Path as well. The reason for the distinction is one of
511 /// efficiency. First, the file status requires additional space and the space
512 /// is incorporated directly into PathWithStatus without an additional malloc.
513 /// Second, obtaining status information is an expensive operation on most
514 /// operating systems so we want to be careful and explicit about where we
515 /// allow this operation in LLVM.
516 /// @brief Path with file status class.
517 class PathWithStatus : public Path {
518 /// @name Constructors
521 /// @brief Default constructor
522 PathWithStatus() : Path(), status(), fsIsValid(false) {}
524 /// @brief Copy constructor
525 PathWithStatus(const PathWithStatus &that)
526 : Path(static_cast<const Path&>(that)), status(that.status),
527 fsIsValid(that.fsIsValid) {}
529 /// This constructor allows construction from a Path object
530 /// @brief Path constructor
531 PathWithStatus(const Path &other)
532 : Path(other), status(), fsIsValid(false) {}
534 /// This constructor will accept a char* or std::string as a path. No
535 /// checking is done on this path to determine if it is valid. To
536 /// determine validity of the path, use the isValid method.
537 /// @brief Construct a Path from a string.
538 explicit PathWithStatus(
539 StringRef p ///< The path to assign.
540 ) : Path(p), status(), fsIsValid(false) {}
542 /// This constructor will accept a character range as a path. No checking
543 /// is done on this path to determine if it is valid. To determine
544 /// validity of the path, use the isValid method.
545 /// @brief Construct a Path from a string.
546 explicit PathWithStatus(
547 const char *StrStart, ///< Pointer to the first character of the path
548 unsigned StrLen ///< Length of the path.
549 ) : Path(StrStart, StrLen), status(), fsIsValid(false) {}
551 /// Makes a copy of \p that to \p this.
553 /// @brief Assignment Operator
554 PathWithStatus &operator=(const PathWithStatus &that) {
555 static_cast<Path&>(*this) = static_cast<const Path&>(that);
556 status = that.status;
557 fsIsValid = that.fsIsValid;
561 /// Makes a copy of \p that to \p this.
563 /// @brief Assignment Operator
564 PathWithStatus &operator=(const Path &that) {
565 static_cast<Path&>(*this) = static_cast<const Path&>(that);
574 /// This function returns status information about the file. The type of
575 /// path (file or directory) is updated to reflect the actual contents
576 /// of the file system.
577 /// @returns 0 on failure, with Error explaining why (if non-zero),
578 /// otherwise returns a pointer to a FileStatus structure on success.
579 /// @brief Get file status.
580 const FileStatus *getFileStatus(
581 bool forceUpdate = false, ///< Force an update from the file system
582 std::string *Error = 0 ///< Optional place to return an error msg.
589 mutable FileStatus status; ///< Status information.
590 mutable bool fsIsValid; ///< Whether we've obtained it or not
595 /// This is the OS-specific path separator: a colon on Unix or a semicolon
597 extern const char PathSeparator;