FileSpec.h revision bf1fa97ab9a28890478daf70cdf6b8177ae3bbae
1//===-- FileSpec.h ----------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef liblldb_FileSpec_h_
11#define liblldb_FileSpec_h_
12#if defined(__cplusplus)
13
14#include "lldb/lldb-private.h"
15#include "lldb/Core/ConstString.h"
16#include "lldb/Core/STLUtils.h"
17#include "lldb/Host/TimeValue.h"
18
19namespace lldb_private {
20
21//----------------------------------------------------------------------
22/// @class FileSpec FileSpec.h "lldb/Host/FileSpec.h"
23/// @brief A file utility class.
24///
25/// A file specification class that divides paths up into a directory
26/// and basename. These string values of the paths are put into uniqued
27/// string pools for fast comparisons and efficient memory usage.
28///
29/// Another reason the paths are split into the directory and basename
30/// is to allow efficient debugger searching. Often in a debugger the
31/// user types in the basename of the file, for example setting a
32/// breakpoint by file and line, or specifying a module (shared library)
33/// to limit the scope in which to execute a command. The user rarely
34/// types in a full path. When the paths are already split up, it makes
35/// it easy for us to compare only the basenames of a lot of file
36/// specifications without having to split up the file path each time
37/// to get to the basename.
38//----------------------------------------------------------------------
39class FileSpec
40{
41public:
42    typedef enum FileType
43    {
44        eFileTypeInvalid = -1,
45        eFileTypeUnknown = 0,
46        eFileTypeDirectory,
47        eFileTypePipe,
48        eFileTypeRegular,
49        eFileTypeSocket,
50        eFileTypeSymbolicLink,
51        eFileTypeOther
52    } FileType;
53
54    FileSpec();
55
56    //------------------------------------------------------------------
57    /// Constructor with path.
58    ///
59    /// Takes a path to a file which can be just a filename, or a full
60    /// path. If \a path is not NULL or empty, this function will call
61    /// FileSpec::SetFile (const char *path, bool resolve).
62    ///
63    /// @param[in] path
64    ///     The full or partial path to a file.
65    ///
66    /// @param[in] resolve_path
67    ///     If \b true, then we resolve the path with realpath,
68    ///     if \b false we trust the path is in canonical form already.
69    ///
70    /// @see FileSpec::SetFile (const char *path, bool resolve)
71    //------------------------------------------------------------------
72    explicit FileSpec (const char *path, bool resolve_path);
73
74    //------------------------------------------------------------------
75    /// Copy constructor
76    ///
77    /// Makes a copy of the uniqued directory and filename strings from
78    /// \a rhs.
79    ///
80    /// @param[in] rhs
81    ///     A const FileSpec object reference to copy.
82    //------------------------------------------------------------------
83    FileSpec (const FileSpec& rhs);
84
85    //------------------------------------------------------------------
86    /// Copy constructor
87    ///
88    /// Makes a copy of the uniqued directory and filename strings from
89    /// \a rhs if it is not NULL.
90    ///
91    /// @param[in] rhs
92    ///     A const FileSpec object pointer to copy if non-NULL.
93    //------------------------------------------------------------------
94    FileSpec (const FileSpec* rhs);
95
96    //------------------------------------------------------------------
97    /// Destructor.
98    ///
99    /// The destructor is virtual in case this class is subclassed.
100    //------------------------------------------------------------------
101    virtual
102    ~FileSpec ();
103
104    //------------------------------------------------------------------
105    /// Assignment operator.
106    ///
107    /// Makes a copy of the uniqued directory and filename strings from
108    /// \a rhs.
109    ///
110    /// @param[in] rhs
111    ///     A const FileSpec object reference to assign to this object.
112    ///
113    /// @return
114    ///     A const reference to this object.
115    //------------------------------------------------------------------
116    const FileSpec&
117    operator= (const FileSpec& rhs);
118
119    //------------------------------------------------------------------
120    /// Equal to operator
121    ///
122    /// Tests if this object is equal to \a rhs.
123    ///
124    /// @param[in] rhs
125    ///     A const FileSpec object reference to compare this object
126    ///     to.
127    ///
128    /// @return
129    ///     \b true if this object is equal to \a rhs, \b false
130    ///     otherwise.
131    //------------------------------------------------------------------
132    bool
133    operator== (const FileSpec& rhs) const;
134
135    //------------------------------------------------------------------
136    /// Not equal to operator
137    ///
138    /// Tests if this object is not equal to \a rhs.
139    ///
140    /// @param[in] rhs
141    ///     A const FileSpec object reference to compare this object
142    ///     to.
143    ///
144    /// @return
145    ///     \b true if this object is equal to \a rhs, \b false
146    ///     otherwise.
147    //------------------------------------------------------------------
148    bool
149    operator!= (const FileSpec& rhs) const;
150
151    //------------------------------------------------------------------
152    /// Less than to operator
153    ///
154    /// Tests if this object is less than \a rhs.
155    ///
156    /// @param[in] rhs
157    ///     A const FileSpec object reference to compare this object
158    ///     to.
159    ///
160    /// @return
161    ///     \b true if this object is less than \a rhs, \b false
162    ///     otherwise.
163    //------------------------------------------------------------------
164    bool
165    operator< (const FileSpec& rhs) const;
166
167    //------------------------------------------------------------------
168    /// Convert to pointer operator.
169    ///
170    /// This allows code to check a FileSpec object to see if it
171    /// contains anything valid using code such as:
172    ///
173    /// @code
174    /// FileSpec file_spec(...);
175    /// if (file_spec)
176    /// { ...
177    /// @endcode
178    ///
179    /// @return
180    ///     A pointer to this object if either the directory or filename
181    ///     is valid, NULL otherwise.
182    //------------------------------------------------------------------
183    operator bool() const;
184
185    //------------------------------------------------------------------
186    /// Logical NOT operator.
187    ///
188    /// This allows code to check a FileSpec object to see if it is
189    /// invalid using code such as:
190    ///
191    /// @code
192    /// FileSpec file_spec(...);
193    /// if (!file_spec)
194    /// { ...
195    /// @endcode
196    ///
197    /// @return
198    ///     Returns \b true if the object has an empty directory and
199    ///     filename, \b false otherwise.
200    //------------------------------------------------------------------
201    bool
202    operator! () const;
203
204    //------------------------------------------------------------------
205    /// Clears the object state.
206    ///
207    /// Clear this object by releasing both the directory and filename
208    /// string values and reverting them to empty strings.
209    //------------------------------------------------------------------
210    void
211    Clear ();
212
213    //------------------------------------------------------------------
214    /// Compare two FileSpec objects.
215    ///
216    /// If \a full is true, then both the directory and the filename
217    /// must match. If \a full is false, then the directory names for
218    /// \a lhs and \a rhs are only compared if they are both not empty.
219    /// This allows a FileSpec object to only contain a filename
220    /// and it can match FileSpec objects that have matching
221    /// filenames with different paths.
222    ///
223    /// @param[in] lhs
224    ///     A const reference to the Left Hand Side object to compare.
225    ///
226    /// @param[in] rhs
227    ///     A const reference to the Right Hand Side object to compare.
228    ///
229    /// @param[in] full
230    ///     If true, then both the directory and filenames will have to
231    ///     match for a compare to return zero (equal to). If false
232    ///     and either directory from \a lhs or \a rhs is empty, then
233    ///     only the filename will be compared, else a full comparison
234    ///     is done.
235    ///
236    /// @return
237    ///     @li -1 if \a lhs is less than \a rhs
238    ///     @li 0 if \a lhs is equal to \a rhs
239    ///     @li 1 if \a lhs is greater than \a rhs
240    //------------------------------------------------------------------
241    static int
242    Compare (const FileSpec& lhs, const FileSpec& rhs, bool full);
243
244    static bool
245    Equal (const FileSpec& a, const FileSpec& b, bool full);
246
247    //------------------------------------------------------------------
248    /// Dump this object to a Stream.
249    ///
250    /// Dump the object to the supplied stream \a s. If the object
251    /// contains a valid directory name, it will be displayed followed
252    /// by a directory delimiter, and the filename.
253    ///
254    /// @param[in] s
255    ///     The stream to which to dump the object descripton.
256    //------------------------------------------------------------------
257    void
258    Dump (Stream *s) const;
259
260    //------------------------------------------------------------------
261    /// Existence test.
262    ///
263    /// @return
264    ///     \b true if the file exists on disk, \b false otherwise.
265    //------------------------------------------------------------------
266    bool
267    Exists () const;
268
269
270    //------------------------------------------------------------------
271    /// Expanded existence test.
272    ///
273    /// Call into the Host to see if it can help find the file (e.g. by
274    /// searching paths set in the environment, etc.).
275    ///
276    /// If found, sets the value of m_directory to the directory where
277    /// the file was found.
278    ///
279    /// @return
280    ///     \b true if was able to find the file using expanded search
281    ///     methods, \b false otherwise.
282    //------------------------------------------------------------------
283    bool
284    ResolveExecutableLocation ();
285
286    //------------------------------------------------------------------
287    /// Canonicalize this file path (basically running the static
288    /// FileSpec::Resolve method on it). Useful if you asked us not to
289    /// resolve the file path when you set the file.
290    //------------------------------------------------------------------
291    bool
292    ResolvePath ();
293
294    uint64_t
295    GetByteSize() const;
296
297    //------------------------------------------------------------------
298    /// Directory string get accessor.
299    ///
300    /// @return
301    ///     A reference to the directory string object.
302    //------------------------------------------------------------------
303    ConstString &
304    GetDirectory ();
305
306    //------------------------------------------------------------------
307    /// Directory string const get accessor.
308    ///
309    /// @return
310    ///     A const reference to the directory string object.
311    //------------------------------------------------------------------
312    const ConstString &
313    GetDirectory () const;
314
315    //------------------------------------------------------------------
316    /// Filename string get accessor.
317    ///
318    /// @return
319    ///     A reference to the filename string object.
320    //------------------------------------------------------------------
321    ConstString &
322    GetFilename ();
323
324    //------------------------------------------------------------------
325    /// Filename string const get accessor.
326    ///
327    /// @return
328    ///     A const reference to the filename string object.
329    //------------------------------------------------------------------
330    const ConstString &
331    GetFilename () const;
332
333    //------------------------------------------------------------------
334    /// Returns true if the filespec represents an implementation source
335    /// file (files with a ".c", ".cpp", ".m", ".mm" (many more)
336    /// extension).
337    ///
338    /// @return
339    ///     \b true if the filespec represents an implementation source
340    ///     file, \b false otherwise.
341    //------------------------------------------------------------------
342    bool
343    IsSourceImplementationFile () const;
344
345    //------------------------------------------------------------------
346    /// Returns true if the filespec represents path that is relative
347    /// path to the current working directory.
348    ///
349    /// @return
350    ///     \b true if the filespec represents a current working
351    ///     directory relative path, \b false otherwise.
352    //------------------------------------------------------------------
353    bool
354    IsRelativeToCurrentWorkingDirectory () const;
355
356    TimeValue
357    GetModificationTime () const;
358
359    //------------------------------------------------------------------
360    /// Extract the full path to the file.
361    ///
362    /// Extract the directory and path into a fixed buffer. This is
363    /// needed as the directory and path are stored in separate string
364    /// values.
365    ///
366    /// @param[out] path
367    ///     The buffer in which to place the extracted full path.
368    ///
369    /// @param[in] max_path_length
370    ///     The maximum length of \a path.
371    ///
372    /// @return
373    ///     Returns the number of characters that would be needed to
374    ///     properly copy the full path into \a path. If the returned
375    ///     number is less than \a max_path_length, then the path is
376    ///     properly copied and terminated. If the return value is
377    ///     >= \a max_path_length, then the path was truncated (but is
378    ///     still NULL terminated).
379    //------------------------------------------------------------------
380    size_t
381    GetPath (char *path, size_t max_path_length) const;
382
383    //------------------------------------------------------------------
384    /// Extract the full path to the file.
385    ///
386    /// Extract the directory and path into a std::string, which is returned.
387    ///
388    /// @param[out] path
389    ///     The directory + filename returned in this std::string reference.
390    //------------------------------------------------------------------
391    void
392    GetPath (std::string &path) const;
393
394    //------------------------------------------------------------------
395    /// Extract the full path to the file.
396    ///
397    /// Extract the directory and path into a std::string, which is returned.
398    ///
399    /// @return
400    ///     Returns a std::string with the directory and filename
401    ///     concatenated.
402    //------------------------------------------------------------------
403    std::string&
404    GetPath (void) const;
405
406    //------------------------------------------------------------------
407    /// Extract the extension of the file.
408    ///
409    /// Returns a ConstString that represents the extension of the filename
410    /// for this FileSpec object. If this object does not represent a file,
411    /// or the filename has no extension, ConstString(NULL) is returned.
412    /// The dot ('.') character is not returned as part of the extension
413    ///
414    /// @return
415    ///     Returns the extension of the file as a ConstString object.
416    //------------------------------------------------------------------
417    ConstString
418    GetFileNameExtension () const;
419
420    //------------------------------------------------------------------
421    /// Return the filename without the extension part
422    ///
423    /// Returns a ConstString that represents the filename of this object
424    /// without the extension part (e.g. for a file named "foo.bar", "foo"
425    /// is returned)
426    ///
427    /// @return
428    ///     Returns the filename without extension
429    ///     as a ConstString object.
430    //------------------------------------------------------------------
431    ConstString
432    GetFileNameStrippingExtension () const;
433
434    FileType
435    GetFileType () const;
436
437    bool
438    IsDirectory () const
439    {
440        return GetFileType() == FileSpec::eFileTypeDirectory;
441    }
442
443    bool
444    IsPipe () const
445    {
446        return GetFileType() == FileSpec::eFileTypePipe;
447    }
448
449    bool
450    IsRegularFile () const
451    {
452        return GetFileType() == FileSpec::eFileTypeRegular;
453    }
454
455    bool
456    IsSocket () const
457    {
458        return GetFileType() == FileSpec::eFileTypeSocket;
459    }
460
461    bool
462    IsSymbolicLink () const
463    {
464        return GetFileType() == FileSpec::eFileTypeSymbolicLink;
465    }
466
467    //------------------------------------------------------------------
468    /// Get the memory cost of this object.
469    ///
470    /// Return the size in bytes that this object takes in memory. This
471    /// returns the size in bytes of this object, not any shared string
472    /// values it may refer to.
473    ///
474    /// @return
475    ///     The number of bytes that this object occupies in memory.
476    ///
477    /// @see ConstString::StaticMemorySize ()
478    //------------------------------------------------------------------
479    size_t
480    MemorySize () const;
481
482    //------------------------------------------------------------------
483    /// Memory map part of, or the entire contents of, a file.
484    ///
485    /// Returns a shared pointer to a data buffer that contains all or
486    /// part of the contents of a file. The data is memory mapped and
487    /// will lazily page in data from the file as memory is accessed.
488    /// The data that is mappped will start \a offset bytes into the
489    /// file, and \a length bytes will be mapped. If \a length is
490    /// greater than the number of bytes available in the file starting
491    /// at \a offset, the number of bytes will be appropriately
492    /// truncated. The final number of bytes that get mapped can be
493    /// verified using the DataBuffer::GetByteSize() function on the return
494    /// shared data pointer object contents.
495    ///
496    /// @param[in] offset
497    ///     The offset in bytes from the beginning of the file where
498    ///     memory mapping should begin.
499    ///
500    /// @param[in] length
501    ///     The size in bytes that should be mapped starting \a offset
502    ///     bytes into the file. If \a length is \c SIZE_MAX, map
503    ///     as many bytes as possible.
504    ///
505    /// @return
506    ///     A shared pointer to the memeory mapped data. This shared
507    ///     pointer can contain a NULL DataBuffer pointer, so the contained
508    ///     pointer must be checked prior to using it.
509    //------------------------------------------------------------------
510    lldb::DataBufferSP
511    MemoryMapFileContents (off_t offset = 0, size_t length = SIZE_MAX) const;
512
513    //------------------------------------------------------------------
514    /// Read part of, or the entire contents of, a file into a heap based data buffer.
515    ///
516    /// Returns a shared pointer to a data buffer that contains all or
517    /// part of the contents of a file. The data copies into a heap based
518    /// buffer that lives in the DataBuffer shared pointer object returned.
519    /// The data that is cached will start \a offset bytes into the
520    /// file, and \a length bytes will be mapped. If \a length is
521    /// greater than the number of bytes available in the file starting
522    /// at \a offset, the number of bytes will be appropriately
523    /// truncated. The final number of bytes that get mapped can be
524    /// verified using the DataBuffer::GetByteSize() function.
525    ///
526    /// @param[in] offset
527    ///     The offset in bytes from the beginning of the file where
528    ///     memory mapping should begin.
529    ///
530    /// @param[in] length
531    ///     The size in bytes that should be mapped starting \a offset
532    ///     bytes into the file. If \a length is \c SIZE_MAX, map
533    ///     as many bytes as possible.
534    ///
535    /// @return
536    ///     A shared pointer to the memeory mapped data. This shared
537    ///     pointer can contain a NULL DataBuffer pointer, so the contained
538    ///     pointer must be checked prior to using it.
539    //------------------------------------------------------------------
540    lldb::DataBufferSP
541    ReadFileContents (off_t offset = 0, size_t length = SIZE_MAX, Error *error_ptr = NULL) const;
542
543    size_t
544    ReadFileContents (off_t file_offset, void *dst, size_t dst_len, Error *error_ptr) const;
545
546
547    //------------------------------------------------------------------
548    /// Read the entire contents of a file as data that can be used
549    /// as a C string.
550    ///
551    /// Read the entire contents of a file and ensure that the data
552    /// is NULL terminated so it can be used as a C string.
553    ///
554    /// @return
555    ///     A shared pointer to the data. This shared pointer can
556    ///     contain a NULL DataBuffer pointer, so the contained pointer
557    ///     must be checked prior to using it.
558    //------------------------------------------------------------------
559    lldb::DataBufferSP
560    ReadFileContentsAsCString(Error *error_ptr = NULL);
561    //------------------------------------------------------------------
562    /// Change the file specificed with a new path.
563    ///
564    /// Update the contents of this object with a new path. The path will
565    /// be split up into a directory and filename and stored as uniqued
566    /// string values for quick comparison and efficient memory usage.
567    ///
568    /// @param[in] path
569    ///     A full, partial, or relative path to a file.
570    ///
571    /// @param[in] resolve_path
572    ///     If \b true, then we will try to resolve links the path using
573    ///     the static FileSpec::Resolve.
574    //------------------------------------------------------------------
575    void
576    SetFile (const char *path, bool resolve_path);
577
578    bool
579    IsResolved () const
580    {
581        return m_is_resolved;
582    }
583
584    //------------------------------------------------------------------
585    /// Set if the file path has been resolved or not.
586    ///
587    /// If you know a file path is already resolved and avoided passing
588    /// a \b true parameter for any functions that take a "bool
589    /// resolve_path" parameter, you can set the value manually using
590    /// this call to make sure we don't try and resolve it later, or try
591    /// and resolve a path that has already been resolved.
592    ///
593    /// @param[in] is_resolved
594    ///     A boolean value that will replace the current value that
595    ///     indicates if the paths in this object have been resolved.
596    //------------------------------------------------------------------
597    void
598    SetIsResolved (bool is_resolved)
599    {
600        m_is_resolved = is_resolved;
601    }
602    //------------------------------------------------------------------
603    /// Read the file into an array of strings, one per line.
604    ///
605    /// Opens and reads the file in this object into an array of strings,
606    /// one string per line of the file. Returns a boolean indicating
607    /// success or failure.
608    ///
609    /// @param[out] lines
610    ///     The string array into which to read the file.
611    ///
612    /// @result
613    ///     Returns the number of lines that were read from the file.
614    //------------------------------------------------------------------
615    size_t
616    ReadFileLines (STLStringArray &lines);
617
618    //------------------------------------------------------------------
619    /// Resolves user name and links in \a src_path, and writes the output
620    /// to \a dst_path.  Note if the path pointed to by \a src_path does not
621    /// exist, the contents of \a src_path will be copied to \a dst_path
622    /// unchanged.
623    ///
624    /// @param[in] src_path
625    ///     Input path to be resolved.
626    ///
627    /// @param[in] dst_path
628    ///     Buffer to store the resolved path.
629    ///
630    /// @param[in] dst_len
631    ///     Size of the buffer pointed to by dst_path.
632    ///
633    /// @result
634    ///     The number of characters required to write the resolved path.  If the
635    ///     resolved path doesn't fit in dst_len, dst_len-1 characters will
636    ///     be written to \a dst_path, but the actual required length will still be returned.
637    //------------------------------------------------------------------
638    static size_t
639    Resolve (const char *src_path, char *dst_path, size_t dst_len);
640
641    //------------------------------------------------------------------
642    /// Resolves the user name at the beginning of \a src_path, and writes the output
643    /// to \a dst_path.  Note, \a src_path can contain other path components after the
644    /// user name, they will be copied over, and if the path doesn't start with "~" it
645    /// will also be copied over to \a dst_path.
646    ///
647    /// @param[in] src_path
648    ///     Input path to be resolved.
649    ///
650    /// @param[in] dst_path
651    ///     Buffer to store the resolved path.
652    ///
653    /// @param[in] dst_len
654    ///     Size of the buffer pointed to by dst_path.
655    ///
656    /// @result
657    ///     The number of characters required to write the resolved path, or 0 if
658    ///     the user name could not be found.  If the
659    ///     resolved path doesn't fit in dst_len, dst_len-1 characters will
660    ///     be written to \a dst_path, but the actual required length will still be returned.
661    //------------------------------------------------------------------
662    static size_t
663    ResolveUsername (const char *src_path, char *dst_path, size_t dst_len);
664
665    static size_t
666    ResolvePartialUsername (const char *partial_name, StringList &matches);
667
668    enum EnumerateDirectoryResult
669    {
670        eEnumerateDirectoryResultNext,  // Enumerate next entry in the current directory
671        eEnumerateDirectoryResultEnter, // Recurse into the current entry if it is a directory or symlink, or next if not
672        eEnumerateDirectoryResultExit,  // Exit from the current directory at the current level.
673        eEnumerateDirectoryResultQuit   // Stop directory enumerations at any level
674    };
675
676    typedef EnumerateDirectoryResult (*EnumerateDirectoryCallbackType) (void *baton,
677                                                                        FileType file_type,
678                                                                        const FileSpec &spec
679);
680
681    static EnumerateDirectoryResult
682    EnumerateDirectory (const char *dir_path,
683                        bool find_directories,
684                        bool find_files,
685                        bool find_other,
686                        EnumerateDirectoryCallbackType callback,
687                        void *callback_baton);
688
689protected:
690    //------------------------------------------------------------------
691    // Member variables
692    //------------------------------------------------------------------
693    ConstString m_directory;    ///< The uniqued directory path
694    ConstString m_filename;     ///< The uniqued filename path
695    mutable bool m_is_resolved; ///< True if this path has been resolved.
696};
697
698//----------------------------------------------------------------------
699/// Dump a FileSpec object to a stream
700//----------------------------------------------------------------------
701Stream& operator << (Stream& s, const FileSpec& f);
702
703} // namespace lldb_private
704
705#endif  // #if defined(__cplusplus)
706#endif  // liblldb_FileSpec_h_
707