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