clang  8.0.0svn
FileManager.h
Go to the documentation of this file.
1 //===--- FileManager.h - File System Probing and Caching --------*- 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 /// \file
11 /// Defines the clang::FileManager interface and associated types.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_BASIC_FILEMANAGER_H
16 #define LLVM_CLANG_BASIC_FILEMANAGER_H
17 
19 #include "clang/Basic/LLVM.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IntrusiveRefCntPtr.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/VirtualFileSystem.h"
29 #include <ctime>
30 #include <map>
31 #include <memory>
32 #include <string>
33 
34 namespace llvm {
35 
36 class MemoryBuffer;
37 
38 } // end namespace llvm
39 
40 namespace clang {
41 
42 class FileSystemStatCache;
43 
44 /// Cached information about one directory (either on disk or in
45 /// the virtual file system).
47  friend class FileManager;
48 
49  StringRef Name; // Name of the directory.
50 
51 public:
52  StringRef getName() const { return Name; }
53 };
54 
55 /// Cached information about one file (either on disk
56 /// or in the virtual file system).
57 ///
58 /// If the 'File' member is valid, then this FileEntry has an open file
59 /// descriptor for the file.
60 class FileEntry {
61  friend class FileManager;
62 
63  StringRef Name; // Name of the file.
64  std::string RealPathName; // Real path to the file; could be empty.
65  off_t Size; // File size in bytes.
66  time_t ModTime; // Modification time of file.
67  const DirectoryEntry *Dir; // Directory file lives in.
68  unsigned UID; // A unique (small) ID for the file.
69  llvm::sys::fs::UniqueID UniqueID;
70  bool IsNamedPipe;
71  bool InPCH;
72  bool IsValid; // Is this \c FileEntry initialized and valid?
73 
74  /// The open file, if it is owned by the \p FileEntry.
75  mutable std::unique_ptr<llvm::vfs::File> File;
76 
77 public:
79  : UniqueID(0, 0), IsNamedPipe(false), InPCH(false), IsValid(false)
80  {}
81 
82  FileEntry(const FileEntry &) = delete;
83  FileEntry &operator=(const FileEntry &) = delete;
84 
85  StringRef getName() const { return Name; }
86  StringRef tryGetRealPathName() const { return RealPathName; }
87  bool isValid() const { return IsValid; }
88  off_t getSize() const { return Size; }
89  unsigned getUID() const { return UID; }
90  const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
91  bool isInPCH() const { return InPCH; }
92  time_t getModificationTime() const { return ModTime; }
93 
94  /// Return the directory the file lives in.
95  const DirectoryEntry *getDir() const { return Dir; }
96 
97  bool operator<(const FileEntry &RHS) const { return UniqueID < RHS.UniqueID; }
98 
99  /// Check whether the file is a named pipe (and thus can't be opened by
100  /// the native FileManager methods).
101  bool isNamedPipe() const { return IsNamedPipe; }
102 
103  void closeFile() const {
104  File.reset(); // rely on destructor to close File
105  }
106 };
107 
108 struct FileData;
109 
110 /// Implements support for file system lookup, file system caching,
111 /// and directory search management.
112 ///
113 /// This also handles more advanced properties, such as uniquing files based
114 /// on "inode", so that a file with two names (e.g. symlinked) will be treated
115 /// as a single file.
116 ///
117 class FileManager : public RefCountedBase<FileManager> {
119  FileSystemOptions FileSystemOpts;
120 
121  /// Cache for existing real directories.
122  std::map<llvm::sys::fs::UniqueID, DirectoryEntry> UniqueRealDirs;
123 
124  /// Cache for existing real files.
125  std::map<llvm::sys::fs::UniqueID, FileEntry> UniqueRealFiles;
126 
127  /// The virtual directories that we have allocated.
128  ///
129  /// For each virtual file (e.g. foo/bar/baz.cpp), we add all of its parent
130  /// directories (foo/ and foo/bar/) here.
131  SmallVector<std::unique_ptr<DirectoryEntry>, 4> VirtualDirectoryEntries;
132  /// The virtual files that we have allocated.
133  SmallVector<std::unique_ptr<FileEntry>, 4> VirtualFileEntries;
134 
135  /// A cache that maps paths to directory entries (either real or
136  /// virtual) we have looked up
137  ///
138  /// The actual Entries for real directories/files are
139  /// owned by UniqueRealDirs/UniqueRealFiles above, while the Entries
140  /// for virtual directories/files are owned by
141  /// VirtualDirectoryEntries/VirtualFileEntries above.
142  ///
143  llvm::StringMap<DirectoryEntry*, llvm::BumpPtrAllocator> SeenDirEntries;
144 
145  /// A cache that maps paths to file entries (either real or
146  /// virtual) we have looked up.
147  ///
148  /// \see SeenDirEntries
149  llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator> SeenFileEntries;
150 
151  /// The canonical names of directories.
152  llvm::DenseMap<const DirectoryEntry *, llvm::StringRef> CanonicalDirNames;
153 
154  /// Storage for canonical names that we have computed.
155  llvm::BumpPtrAllocator CanonicalNameStorage;
156 
157  /// Each FileEntry we create is assigned a unique ID #.
158  ///
159  unsigned NextFileUID;
160 
161  // Statistics.
162  unsigned NumDirLookups, NumFileLookups;
163  unsigned NumDirCacheMisses, NumFileCacheMisses;
164 
165  // Caching.
166  std::unique_ptr<FileSystemStatCache> StatCache;
167 
168  bool getStatValue(StringRef Path, FileData &Data, bool isFile,
169  std::unique_ptr<llvm::vfs::File> *F);
170 
171  /// Add all ancestors of the given path (pointing to either a file
172  /// or a directory) as virtual directories.
173  void addAncestorsAsVirtualDirs(StringRef Path);
174 
175 public:
176  FileManager(const FileSystemOptions &FileSystemOpts,
178  ~FileManager();
179 
180  /// Installs the provided FileSystemStatCache object within
181  /// the FileManager.
182  ///
183  /// Ownership of this object is transferred to the FileManager.
184  ///
185  /// \param statCache the new stat cache to install. Ownership of this
186  /// object is transferred to the FileManager.
187  ///
188  /// \param AtBeginning whether this new stat cache must be installed at the
189  /// beginning of the chain of stat caches. Otherwise, it will be added to
190  /// the end of the chain.
191  void addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
192  bool AtBeginning = false);
193 
194  /// Removes the specified FileSystemStatCache object from the manager.
195  void removeStatCache(FileSystemStatCache *statCache);
196 
197  /// Removes all FileSystemStatCache objects from the manager.
198  void clearStatCaches();
199 
200  /// Lookup, cache, and verify the specified directory (real or
201  /// virtual).
202  ///
203  /// This returns NULL if the directory doesn't exist.
204  ///
205  /// \param CacheFailure If true and the file does not exist, we'll cache
206  /// the failure to find this file.
207  const DirectoryEntry *getDirectory(StringRef DirName,
208  bool CacheFailure = true);
209 
210  /// Lookup, cache, and verify the specified file (real or
211  /// virtual).
212  ///
213  /// This returns NULL if the file doesn't exist.
214  ///
215  /// \param OpenFile if true and the file exists, it will be opened.
216  ///
217  /// \param CacheFailure If true and the file does not exist, we'll cache
218  /// the failure to find this file.
219  const FileEntry *getFile(StringRef Filename, bool OpenFile = false,
220  bool CacheFailure = true);
221 
222  /// Returns the current file system options
223  FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }
224  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
225 
227  return FS;
228  }
229 
230  /// Retrieve a file entry for a "virtual" file that acts as
231  /// if there were a file with the given name on disk.
232  ///
233  /// The file itself is not accessed.
234  const FileEntry *getVirtualFile(StringRef Filename, off_t Size,
235  time_t ModificationTime);
236 
237  /// Open the specified file as a MemoryBuffer, returning a new
238  /// MemoryBuffer if successful, otherwise returning null.
239  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
240  getBufferForFile(const FileEntry *Entry, bool isVolatile = false,
241  bool ShouldCloseOpenFile = true);
242  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
243  getBufferForFile(StringRef Filename, bool isVolatile = false);
244 
245  /// Get the 'stat' information for the given \p Path.
246  ///
247  /// If the path is relative, it will be resolved against the WorkingDir of the
248  /// FileManager's FileSystemOptions.
249  ///
250  /// \returns false on success, true on error.
251  bool getNoncachedStatValue(StringRef Path, llvm::vfs::Status &Result);
252 
253  /// Remove the real file \p Entry from the cache.
254  void invalidateCache(const FileEntry *Entry);
255 
256  /// If path is not absolute and FileSystemOptions set the working
257  /// directory, the path is modified to be relative to the given
258  /// working directory.
259  /// \returns true if \c path changed.
260  bool FixupRelativePath(SmallVectorImpl<char> &path) const;
261 
262  /// Makes \c Path absolute taking into account FileSystemOptions and the
263  /// working directory option.
264  /// \returns true if \c Path changed to absolute.
265  bool makeAbsolutePath(SmallVectorImpl<char> &Path) const;
266 
267  /// Produce an array mapping from the unique IDs assigned to each
268  /// file to the corresponding FileEntry pointer.
269  void GetUniqueIDMapping(
270  SmallVectorImpl<const FileEntry *> &UIDToFiles) const;
271 
272  /// Modifies the size and modification time of a previously created
273  /// FileEntry. Use with caution.
274  static void modifyFileEntry(FileEntry *File, off_t Size,
275  time_t ModificationTime);
276 
277  /// Retrieve the canonical name for a given directory.
278  ///
279  /// This is a very expensive operation, despite its results being cached,
280  /// and should only be used when the physical layout of the file system is
281  /// required, which is (almost) never.
282  StringRef getCanonicalName(const DirectoryEntry *Dir);
283 
284  void PrintStats() const;
285 };
286 
287 } // end namespace clang
288 
289 #endif // LLVM_CLANG_BASIC_FILEMANAGER_H
StringRef tryGetRealPathName() const
Definition: FileManager.h:86
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:117
time_t getModificationTime() const
Definition: FileManager.h:92
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
void closeFile() const
Definition: FileManager.h:103
const llvm::sys::fs::UniqueID & getUniqueID() const
Definition: FileManager.h:90
unsigned getUID() const
Definition: FileManager.h:89
Abstract interface for introducing a FileManager cache for &#39;stat&#39; system calls, which is used by prec...
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
StringRef Filename
Definition: Format.cpp:1620
const DirectoryEntry * getDir() const
Return the directory the file lives in.
Definition: FileManager.h:95
#define false
Definition: stdbool.h:33
StringRef getName() const
Definition: FileManager.h:85
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
Definition: FileManager.h:223
bool isNamedPipe() const
Check whether the file is a named pipe (and thus can&#39;t be opened by the native FileManager methods)...
Definition: FileManager.h:101
bool operator<(const FileEntry &RHS) const
Definition: FileManager.h:97
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:60
const FileSystemOptions & getFileSystemOpts() const
Definition: FileManager.h:224
bool isValid() const
Definition: FileManager.h:87
Dataflow Directional Tag Classes.
bool isInPCH() const
Definition: FileManager.h:91
off_t getSize() const
Definition: FileManager.h:88
Defines the clang::FileSystemOptions interface.
Cached information about one directory (either on disk or in the virtual file system).
Definition: FileManager.h:46
Keeps track of options that affect how file operations are performed.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystem() const
Definition: FileManager.h:226
StringRef getName() const
Definition: FileManager.h:52