1 //===-- FileSpec.h ----------------------------------------------*- 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 #ifndef liblldb_FileSpec_h_
11 #define liblldb_FileSpec_h_
18 // Other libraries and framework includes
20 #include "lldb/Core/ConstString.h"
21 #include "lldb/Core/STLUtils.h"
22 #include "lldb/Host/PosixApi.h"
23 #include "lldb/lldb-private.h"
25 #include "llvm/Support/FormatVariadic.h"
27 namespace lldb_private {
29 //----------------------------------------------------------------------
30 /// @class FileSpec FileSpec.h "lldb/Host/FileSpec.h"
31 /// @brief A file utility class.
33 /// A file specification class that divides paths up into a directory
34 /// and basename. These string values of the paths are put into uniqued
35 /// string pools for fast comparisons and efficient memory usage.
37 /// Another reason the paths are split into the directory and basename
38 /// is to allow efficient debugger searching. Often in a debugger the
39 /// user types in the basename of the file, for example setting a
40 /// breakpoint by file and line, or specifying a module (shared library)
41 /// to limit the scope in which to execute a command. The user rarely
42 /// types in a full path. When the paths are already split up, it makes
43 /// it easy for us to compare only the basenames of a lot of file
44 /// specifications without having to split up the file path each time
45 /// to get to the basename.
46 //----------------------------------------------------------------------
49 typedef enum FileType {
50 eFileTypeInvalid = -1,
56 eFileTypeSymbolicLink,
68 //------------------------------------------------------------------
69 /// Constructor with path.
71 /// Takes a path to a file which can be just a filename, or a full
72 /// path. If \a path is not nullptr or empty, this function will call
73 /// FileSpec::SetFile (const char *path, bool resolve).
76 /// The full or partial path to a file.
78 /// @param[in] resolve_path
79 /// If \b true, then we resolve the path, removing stray ../.. and so
81 /// if \b false we trust the path is in canonical form already.
83 /// @see FileSpec::SetFile (const char *path, bool resolve)
84 //------------------------------------------------------------------
85 explicit FileSpec(llvm::StringRef path, bool resolve_path,
86 PathSyntax syntax = ePathSyntaxHostNative);
88 explicit FileSpec(llvm::StringRef path, bool resolve_path, ArchSpec arch);
90 //------------------------------------------------------------------
93 /// Makes a copy of the uniqued directory and filename strings from
97 /// A const FileSpec object reference to copy.
98 //------------------------------------------------------------------
99 FileSpec(const FileSpec &rhs);
101 //------------------------------------------------------------------
104 /// Makes a copy of the uniqued directory and filename strings from
105 /// \a rhs if it is not nullptr.
108 /// A const FileSpec object pointer to copy if non-nullptr.
109 //------------------------------------------------------------------
110 FileSpec(const FileSpec *rhs);
112 //------------------------------------------------------------------
114 //------------------------------------------------------------------
117 bool DirectoryEquals(const FileSpec &other) const;
119 bool FileEquals(const FileSpec &other) const;
121 //------------------------------------------------------------------
122 /// Assignment operator.
124 /// Makes a copy of the uniqued directory and filename strings from
128 /// A const FileSpec object reference to assign to this object.
131 /// A const reference to this object.
132 //------------------------------------------------------------------
133 const FileSpec &operator=(const FileSpec &rhs);
135 //------------------------------------------------------------------
136 /// Equal to operator
138 /// Tests if this object is equal to \a rhs.
141 /// A const FileSpec object reference to compare this object
145 /// \b true if this object is equal to \a rhs, \b false
147 //------------------------------------------------------------------
148 bool operator==(const FileSpec &rhs) const;
150 //------------------------------------------------------------------
151 /// Not equal to operator
153 /// Tests if this object is not equal to \a rhs.
156 /// A const FileSpec object reference to compare this object
160 /// \b true if this object is equal to \a rhs, \b false
162 //------------------------------------------------------------------
163 bool operator!=(const FileSpec &rhs) const;
165 //------------------------------------------------------------------
166 /// Less than to operator
168 /// Tests if this object is less than \a rhs.
171 /// A const FileSpec object reference to compare this object
175 /// \b true if this object is less than \a rhs, \b false
177 //------------------------------------------------------------------
178 bool operator<(const FileSpec &rhs) const;
180 //------------------------------------------------------------------
181 /// Convert to pointer operator.
183 /// This allows code to check a FileSpec object to see if it
184 /// contains anything valid using code such as:
187 /// FileSpec file_spec(...);
193 /// A pointer to this object if either the directory or filename
194 /// is valid, nullptr otherwise.
195 //------------------------------------------------------------------
196 explicit operator bool() const;
198 //------------------------------------------------------------------
199 /// Logical NOT operator.
201 /// This allows code to check a FileSpec object to see if it is
202 /// invalid using code such as:
205 /// FileSpec file_spec(...);
211 /// Returns \b true if the object has an empty directory and
212 /// filename, \b false otherwise.
213 //------------------------------------------------------------------
214 bool operator!() const;
216 //------------------------------------------------------------------
217 /// Clears the object state.
219 /// Clear this object by releasing both the directory and filename
220 /// string values and reverting them to empty strings.
221 //------------------------------------------------------------------
224 //------------------------------------------------------------------
225 /// Compare two FileSpec objects.
227 /// If \a full is true, then both the directory and the filename
228 /// must match. If \a full is false, then the directory names for
229 /// \a lhs and \a rhs are only compared if they are both not empty.
230 /// This allows a FileSpec object to only contain a filename
231 /// and it can match FileSpec objects that have matching
232 /// filenames with different paths.
235 /// A const reference to the Left Hand Side object to compare.
238 /// A const reference to the Right Hand Side object to compare.
241 /// If true, then both the directory and filenames will have to
242 /// match for a compare to return zero (equal to). If false
243 /// and either directory from \a lhs or \a rhs is empty, then
244 /// only the filename will be compared, else a full comparison
248 /// @li -1 if \a lhs is less than \a rhs
249 /// @li 0 if \a lhs is equal to \a rhs
250 /// @li 1 if \a lhs is greater than \a rhs
251 //------------------------------------------------------------------
252 static int Compare(const FileSpec &lhs, const FileSpec &rhs, bool full);
254 static bool Equal(const FileSpec &a, const FileSpec &b, bool full,
255 bool remove_backups = false);
257 //------------------------------------------------------------------
258 /// Case sensitivity of path.
261 /// \b true if the file path is case sensitive (POSIX), false
262 /// if case insensitive (Windows).
263 //------------------------------------------------------------------
264 bool IsCaseSensitive() const { return m_syntax != ePathSyntaxWindows; }
266 //------------------------------------------------------------------
267 /// Dump this object to a Stream.
269 /// Dump the object to the supplied stream \a s. If the object
270 /// contains a valid directory name, it will be displayed followed
271 /// by a directory delimiter, and the filename.
274 /// The stream to which to dump the object description.
275 //------------------------------------------------------------------
276 void Dump(Stream *s) const;
278 //------------------------------------------------------------------
282 /// \b true if the file exists on disk, \b false otherwise.
283 //------------------------------------------------------------------
286 //------------------------------------------------------------------
287 /// Check if a file is readable by the current user
290 /// \b true if the file exists on disk and is readable, \b false
292 //------------------------------------------------------------------
293 bool Readable() const;
295 //------------------------------------------------------------------
296 /// Expanded existence test.
298 /// Call into the Host to see if it can help find the file (e.g. by
299 /// searching paths set in the environment, etc.).
301 /// If found, sets the value of m_directory to the directory where
302 /// the file was found.
305 /// \b true if was able to find the file using expanded search
306 /// methods, \b false otherwise.
307 //------------------------------------------------------------------
308 bool ResolveExecutableLocation();
310 //------------------------------------------------------------------
311 /// Canonicalize this file path (basically running the static
312 /// FileSpec::Resolve method on it). Useful if you asked us not to
313 /// resolve the file path when you set the file.
314 //------------------------------------------------------------------
317 uint64_t GetByteSize() const;
319 PathSyntax GetPathSyntax() const;
321 //------------------------------------------------------------------
322 /// Directory string get accessor.
325 /// A reference to the directory string object.
326 //------------------------------------------------------------------
327 ConstString &GetDirectory();
329 //------------------------------------------------------------------
330 /// Directory string const get accessor.
333 /// A const reference to the directory string object.
334 //------------------------------------------------------------------
335 const ConstString &GetDirectory() const;
337 //------------------------------------------------------------------
338 /// Filename string get accessor.
341 /// A reference to the filename string object.
342 //------------------------------------------------------------------
343 ConstString &GetFilename();
345 //------------------------------------------------------------------
346 /// Filename string const get accessor.
349 /// A const reference to the filename string object.
350 //------------------------------------------------------------------
351 const ConstString &GetFilename() const;
353 //------------------------------------------------------------------
354 /// Returns true if the filespec represents an implementation source
355 /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
359 /// \b true if the filespec represents an implementation source
360 /// file, \b false otherwise.
361 //------------------------------------------------------------------
362 bool IsSourceImplementationFile() const;
364 //------------------------------------------------------------------
365 /// Returns true if the filespec represents a relative path.
368 /// \b true if the filespec represents a relative path,
369 /// \b false otherwise.
370 //------------------------------------------------------------------
371 bool IsRelative() const;
373 //------------------------------------------------------------------
374 /// Returns true if the filespec represents an absolute path.
377 /// \b true if the filespec represents an absolute path,
378 /// \b false otherwise.
379 //------------------------------------------------------------------
380 bool IsAbsolute() const;
382 //------------------------------------------------------------------
383 /// Extract the full path to the file.
385 /// Extract the directory and path into a fixed buffer. This is
386 /// needed as the directory and path are stored in separate string
390 /// The buffer in which to place the extracted full path.
392 /// @param[in] max_path_length
393 /// The maximum length of \a path.
396 /// Returns the number of characters that would be needed to
397 /// properly copy the full path into \a path. If the returned
398 /// number is less than \a max_path_length, then the path is
399 /// properly copied and terminated. If the return value is
400 /// >= \a max_path_length, then the path was truncated (but is
401 /// still NULL terminated).
402 //------------------------------------------------------------------
403 size_t GetPath(char *path, size_t max_path_length,
404 bool denormalize = true) const;
406 //------------------------------------------------------------------
407 /// Extract the full path to the file.
409 /// Extract the directory and path into a std::string, which is returned.
412 /// Returns a std::string with the directory and filename
414 //------------------------------------------------------------------
415 std::string GetPath(bool denormalize = true) const;
417 const char *GetCString(bool denormalize = true) const;
419 //------------------------------------------------------------------
420 /// Extract the full path to the file.
422 /// Extract the directory and path into an llvm::SmallVectorImpl<>
425 /// Returns a std::string with the directory and filename
427 //------------------------------------------------------------------
428 void GetPath(llvm::SmallVectorImpl<char> &path,
429 bool denormalize = true) const;
431 //------------------------------------------------------------------
432 /// Extract the extension of the file.
434 /// Returns a ConstString that represents the extension of the filename
435 /// for this FileSpec object. If this object does not represent a file,
436 /// or the filename has no extension, ConstString(nullptr) is returned.
437 /// The dot ('.') character is not returned as part of the extension
440 /// Returns the extension of the file as a ConstString object.
441 //------------------------------------------------------------------
442 ConstString GetFileNameExtension() const;
444 //------------------------------------------------------------------
445 /// Return the filename without the extension part
447 /// Returns a ConstString that represents the filename of this object
448 /// without the extension part (e.g. for a file named "foo.bar", "foo"
452 /// Returns the filename without extension
453 /// as a ConstString object.
454 //------------------------------------------------------------------
455 ConstString GetFileNameStrippingExtension() const;
457 FileType GetFileType() const;
459 //------------------------------------------------------------------
460 /// Return the current permissions of the path.
462 /// Returns a bitmask for the current permissions of the file
463 /// ( zero or more of the permission bits defined in
464 /// File::Permissions).
467 /// Zero if the file doesn't exist or we are unable to get
468 /// information for the file, otherwise one or more permission
469 /// bits from the File::Permissions enumeration.
470 //------------------------------------------------------------------
471 uint32_t GetPermissions() const;
473 bool IsDirectory() const {
474 return GetFileType() == FileSpec::eFileTypeDirectory;
477 bool IsPipe() const { return GetFileType() == FileSpec::eFileTypePipe; }
479 bool IsRegularFile() const {
480 return GetFileType() == FileSpec::eFileTypeRegular;
483 bool IsSocket() const { return GetFileType() == FileSpec::eFileTypeSocket; }
485 bool IsSymbolicLink() const;
487 //------------------------------------------------------------------
488 /// Get the memory cost of this object.
490 /// Return the size in bytes that this object takes in memory. This
491 /// returns the size in bytes of this object, not any shared string
492 /// values it may refer to.
495 /// The number of bytes that this object occupies in memory.
497 /// @see ConstString::StaticMemorySize ()
498 //------------------------------------------------------------------
499 size_t MemorySize() const;
501 //------------------------------------------------------------------
502 /// Memory map part of, or the entire contents of, a file.
504 /// Returns a shared pointer to a data buffer that contains all or
505 /// part of the contents of a file. The data is memory mapped and
506 /// will lazily page in data from the file as memory is accessed.
507 /// The data that is mapped will start \a offset bytes into the
508 /// file, and \a length bytes will be mapped. If \a length is
509 /// greater than the number of bytes available in the file starting
510 /// at \a offset, the number of bytes will be appropriately
511 /// truncated. The final number of bytes that get mapped can be
512 /// verified using the DataBuffer::GetByteSize() function on the return
513 /// shared data pointer object contents.
515 /// @param[in] offset
516 /// The offset in bytes from the beginning of the file where
517 /// memory mapping should begin.
519 /// @param[in] length
520 /// The size in bytes that should be mapped starting \a offset
521 /// bytes into the file. If \a length is \c SIZE_MAX, map
522 /// as many bytes as possible.
525 /// A shared pointer to the memory mapped data. This shared
526 /// pointer can contain a nullptr DataBuffer pointer, so the contained
527 /// pointer must be checked prior to using it.
528 //------------------------------------------------------------------
529 lldb::DataBufferSP MemoryMapFileContents(off_t offset = 0,
530 size_t length = SIZE_MAX) const;
532 //------------------------------------------------------------------
533 /// Memory map part of, or the entire contents of, a file only if
534 /// the file is local (not on a network mount).
536 /// Returns a shared pointer to a data buffer that contains all or
537 /// part of the contents of a file. The data will be memory mapped
538 /// if the file is local and will lazily page in data from the file
539 /// as memory is accessed. If the data is memory mapped, the data
540 /// that is mapped will start \a offset bytes into the file, and
541 /// \a length bytes will be mapped. If \a length is
542 /// greater than the number of bytes available in the file starting
543 /// at \a offset, the number of bytes will be appropriately
544 /// truncated. The final number of bytes that get mapped can be
545 /// verified using the DataBuffer::GetByteSize() function on the return
546 /// shared data pointer object contents.
548 /// If the file is on a network mount the data will be read into a
549 /// heap buffer immediately so that accesses to the data won't later
550 /// cause a crash if we touch a page that isn't paged in and the
551 /// network mount has been disconnected or gone away.
553 /// @param[in] offset
554 /// The offset in bytes from the beginning of the file where
555 /// memory mapping should begin.
557 /// @param[in] length
558 /// The size in bytes that should be mapped starting \a offset
559 /// bytes into the file. If \a length is \c SIZE_MAX, map
560 /// as many bytes as possible.
563 /// A shared pointer to the memory mapped data. This shared
564 /// pointer can contain a nullptr DataBuffer pointer, so the contained
565 /// pointer must be checked prior to using it.
566 //------------------------------------------------------------------
567 lldb::DataBufferSP MemoryMapFileContentsIfLocal(off_t file_offset,
568 size_t file_size) const;
570 //------------------------------------------------------------------
571 /// Read part of, or the entire contents of, a file into a heap based data
574 /// Returns a shared pointer to a data buffer that contains all or
575 /// part of the contents of a file. The data copies into a heap based
576 /// buffer that lives in the DataBuffer shared pointer object returned.
577 /// The data that is cached will start \a offset bytes into the
578 /// file, and \a length bytes will be mapped. If \a length is
579 /// greater than the number of bytes available in the file starting
580 /// at \a offset, the number of bytes will be appropriately
581 /// truncated. The final number of bytes that get mapped can be
582 /// verified using the DataBuffer::GetByteSize() function.
584 /// @param[in] offset
585 /// The offset in bytes from the beginning of the file where
586 /// memory mapping should begin.
588 /// @param[in] length
589 /// The size in bytes that should be mapped starting \a offset
590 /// bytes into the file. If \a length is \c SIZE_MAX, map
591 /// as many bytes as possible.
594 /// A shared pointer to the memory mapped data. This shared
595 /// pointer can contain a nullptr DataBuffer pointer, so the contained
596 /// pointer must be checked prior to using it.
597 //------------------------------------------------------------------
598 lldb::DataBufferSP ReadFileContents(off_t offset = 0,
599 size_t length = SIZE_MAX,
600 Error *error_ptr = nullptr) const;
602 size_t ReadFileContents(off_t file_offset, void *dst, size_t dst_len,
603 Error *error_ptr) const;
605 //------------------------------------------------------------------
606 /// Read the entire contents of a file as data that can be used
609 /// Read the entire contents of a file and ensure that the data
610 /// is NULL terminated so it can be used as a C string.
613 /// A shared pointer to the data. This shared pointer can
614 /// contain a nullptr DataBuffer pointer, so the contained pointer
615 /// must be checked prior to using it.
616 //------------------------------------------------------------------
617 lldb::DataBufferSP ReadFileContentsAsCString(Error *error_ptr = nullptr);
619 //------------------------------------------------------------------
620 /// Normalize a pathname by collapsing redundant separators and
621 /// up-level references.
622 //------------------------------------------------------------------
623 FileSpec GetNormalizedPath() const;
625 //------------------------------------------------------------------
626 /// Change the file specified with a new path.
628 /// Update the contents of this object with a new path. The path will
629 /// be split up into a directory and filename and stored as uniqued
630 /// string values for quick comparison and efficient memory usage.
633 /// A full, partial, or relative path to a file.
635 /// @param[in] resolve_path
636 /// If \b true, then we will try to resolve links the path using
637 /// the static FileSpec::Resolve.
638 //------------------------------------------------------------------
639 void SetFile(llvm::StringRef path, bool resolve_path,
640 PathSyntax syntax = ePathSyntaxHostNative);
642 void SetFile(llvm::StringRef path, bool resolve_path, ArchSpec arch);
644 bool IsResolved() const { return m_is_resolved; }
646 //------------------------------------------------------------------
647 /// Set if the file path has been resolved or not.
649 /// If you know a file path is already resolved and avoided passing
650 /// a \b true parameter for any functions that take a "bool
651 /// resolve_path" parameter, you can set the value manually using
652 /// this call to make sure we don't try and resolve it later, or try
653 /// and resolve a path that has already been resolved.
655 /// @param[in] is_resolved
656 /// A boolean value that will replace the current value that
657 /// indicates if the paths in this object have been resolved.
658 //------------------------------------------------------------------
659 void SetIsResolved(bool is_resolved) { m_is_resolved = is_resolved; }
661 //------------------------------------------------------------------
662 /// Read the file into an array of strings, one per line.
664 /// Opens and reads the file in this object into an array of strings,
665 /// one string per line of the file. Returns a boolean indicating
666 /// success or failure.
668 /// @param[out] lines
669 /// The string array into which to read the file.
672 /// Returns the number of lines that were read from the file.
673 //------------------------------------------------------------------
674 size_t ReadFileLines(STLStringArray &lines);
676 //------------------------------------------------------------------
677 /// Resolves user name and links in \a path, and overwrites the input
678 /// argument with the resolved path.
681 /// Input path to be resolved, in the form of a llvm::SmallString or
683 //------------------------------------------------------------------
684 static void Resolve(llvm::SmallVectorImpl<char> &path);
686 FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const;
687 FileSpec CopyByRemovingLastPathComponent() const;
689 void PrependPathComponent(llvm::StringRef component);
690 void PrependPathComponent(const FileSpec &new_path);
692 void AppendPathComponent(llvm::StringRef component);
693 void AppendPathComponent(const FileSpec &new_path);
695 void RemoveLastPathComponent();
697 ConstString GetLastPathComponent() const;
699 //------------------------------------------------------------------
700 /// Resolves the user name at the beginning of \a src_path, and writes the
702 /// to \a dst_path. Note, \a src_path can contain other path components after
704 /// user name, they will be copied over, and if the path doesn't start with
706 /// will also be copied over to \a dst_path.
708 /// @param[in] src_path
709 /// Input path to be resolved.
711 /// @param[in] dst_path
712 /// Buffer to store the resolved path.
713 //------------------------------------------------------------------
714 static void ResolveUsername(llvm::SmallVectorImpl<char> &path);
716 static size_t ResolvePartialUsername(llvm::StringRef partial_name,
717 StringList &matches);
719 enum EnumerateDirectoryResult {
720 eEnumerateDirectoryResultNext, // Enumerate next entry in the current
722 eEnumerateDirectoryResultEnter, // Recurse into the current entry if it is a
723 // directory or symlink, or next if not
724 eEnumerateDirectoryResultExit, // Exit from the current directory at the
726 eEnumerateDirectoryResultQuit // Stop directory enumerations at any level
729 typedef EnumerateDirectoryResult (*EnumerateDirectoryCallbackType)(
730 void *baton, FileType file_type, const FileSpec &spec);
732 static EnumerateDirectoryResult
733 EnumerateDirectory(llvm::StringRef dir_path, bool find_directories,
734 bool find_files, bool find_other,
735 EnumerateDirectoryCallbackType callback,
736 void *callback_baton);
738 typedef std::function<EnumerateDirectoryResult(FileType file_type,
739 const FileSpec &spec)>
742 static EnumerateDirectoryResult
743 ForEachItemInDirectory(llvm::StringRef dir_path,
744 DirectoryCallback const &callback);
747 //------------------------------------------------------------------
749 //------------------------------------------------------------------
750 ConstString m_directory; ///< The uniqued directory path
751 ConstString m_filename; ///< The uniqued filename path
752 mutable bool m_is_resolved = false; ///< True if this path has been resolved.
754 m_syntax; ///< The syntax that this path uses (e.g. Windows / Posix)
757 //----------------------------------------------------------------------
758 /// Dump a FileSpec object to a stream
759 //----------------------------------------------------------------------
760 Stream &operator<<(Stream &s, const FileSpec &f);
762 } // namespace lldb_private
766 /// Implementation of format_provider<T> for FileSpec.
768 /// The options string of a FileSpec has the grammar:
770 /// file_spec_options :: (empty) | F | D
772 /// =======================================================
773 /// | style | Meaning | Example |
774 /// -------------------------------------------------------
775 /// | | | Input | Output |
776 /// =======================================================
777 /// | F | Only print filename | /foo/bar | bar |
778 /// | D | Only print directory | /foo/bar | /foo/ |
779 /// | (empty) | Print file and dir | | |
780 /// =======================================================
782 /// Any other value is considered an invalid format string.
784 template <> struct format_provider<lldb_private::FileSpec> {
785 static void format(const lldb_private::FileSpec &F, llvm::raw_ostream &Stream,
790 #endif // liblldb_FileSpec_h_