clang  10.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  llvm::sys::fs::UniqueID UniqueID;
68  unsigned UID; // A unique (small) ID for the file.
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, or an error that occurred when we looked up
136  /// the directory.
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<llvm::ErrorOr<DirectoryEntry &>, llvm::BumpPtrAllocator>
144  SeenDirEntries;
145 
146  /// A cache that maps paths to file entries (either real or
147  /// virtual) we have looked up, or an error that occurred when we looked up
148  /// the file.
149  ///
150  /// \see SeenDirEntries
151  llvm::StringMap<llvm::ErrorOr<FileEntry &>, llvm::BumpPtrAllocator>
152  SeenFileEntries;
153 
154  /// The canonical names of directories.
155  llvm::DenseMap<const DirectoryEntry *, llvm::StringRef> CanonicalDirNames;
156 
157  /// Storage for canonical names that we have computed.
158  llvm::BumpPtrAllocator CanonicalNameStorage;
159 
160  /// Each FileEntry we create is assigned a unique ID #.
161  ///
162  unsigned NextFileUID;
163 
164  // Statistics.
165  unsigned NumDirLookups, NumFileLookups;
166  unsigned NumDirCacheMisses, NumFileCacheMisses;
167 
168  // Caching.
169  std::unique_ptr<FileSystemStatCache> StatCache;
170 
171  std::error_code getStatValue(StringRef Path, llvm::vfs::Status &Status,
172  bool isFile,
173  std::unique_ptr<llvm::vfs::File> *F);
174 
175  /// Add all ancestors of the given path (pointing to either a file
176  /// or a directory) as virtual directories.
177  void addAncestorsAsVirtualDirs(StringRef Path);
178 
179  /// Fills the RealPathName in file entry.
180  void fillRealPathName(FileEntry *UFE, llvm::StringRef FileName);
181 
182 public:
183  /// Construct a file manager, optionally with a custom VFS.
184  ///
185  /// \param FS if non-null, the VFS to use. Otherwise uses
186  /// llvm::vfs::getRealFileSystem().
187  FileManager(const FileSystemOptions &FileSystemOpts,
189  ~FileManager();
190 
191  /// Installs the provided FileSystemStatCache object within
192  /// the FileManager.
193  ///
194  /// Ownership of this object is transferred to the FileManager.
195  ///
196  /// \param statCache the new stat cache to install. Ownership of this
197  /// object is transferred to the FileManager.
198  void setStatCache(std::unique_ptr<FileSystemStatCache> statCache);
199 
200  /// Removes the FileSystemStatCache object from the manager.
201  void clearStatCache();
202 
203  /// Lookup, cache, and verify the specified directory (real or
204  /// virtual).
205  ///
206  /// This returns a \c std::error_code if there was an error reading the
207  /// directory. If there is no error, the DirectoryEntry is guaranteed to be
208  /// non-NULL.
209  ///
210  /// \param CacheFailure If true and the file does not exist, we'll cache
211  /// the failure to find this file.
212  llvm::ErrorOr<const DirectoryEntry *>
213  getDirectory(StringRef DirName, bool CacheFailure = true);
214 
215  /// Lookup, cache, and verify the specified file (real or
216  /// virtual).
217  ///
218  /// This returns a \c std::error_code if there was an error loading the file.
219  /// If there is no error, the FileEntry is guaranteed to be non-NULL.
220  ///
221  /// \param OpenFile if true and the file exists, it will be opened.
222  ///
223  /// \param CacheFailure If true and the file does not exist, we'll cache
224  /// the failure to find this file.
225  llvm::ErrorOr<const FileEntry *>
226  getFile(StringRef Filename, bool OpenFile = false, bool CacheFailure = true);
227 
228  /// Returns the current file system options
229  FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }
230  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
231 
232  llvm::vfs::FileSystem &getVirtualFileSystem() const { return *FS; }
233 
235  this->FS = std::move(FS);
236  }
237 
238  /// Retrieve a file entry for a "virtual" file that acts as
239  /// if there were a file with the given name on disk.
240  ///
241  /// The file itself is not accessed.
242  const FileEntry *getVirtualFile(StringRef Filename, off_t Size,
243  time_t ModificationTime);
244 
245  /// Open the specified file as a MemoryBuffer, returning a new
246  /// MemoryBuffer if successful, otherwise returning null.
247  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
248  getBufferForFile(const FileEntry *Entry, bool isVolatile = false,
249  bool ShouldCloseOpenFile = true);
250  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
251  getBufferForFile(StringRef Filename, bool isVolatile = false);
252 
253  /// Get the 'stat' information for the given \p Path.
254  ///
255  /// If the path is relative, it will be resolved against the WorkingDir of the
256  /// FileManager's FileSystemOptions.
257  ///
258  /// \returns a \c std::error_code describing an error, if there was one
259  std::error_code getNoncachedStatValue(StringRef Path,
260  llvm::vfs::Status &Result);
261 
262  /// Remove the real file \p Entry from the cache.
263  void invalidateCache(const FileEntry *Entry);
264 
265  /// If path is not absolute and FileSystemOptions set the working
266  /// directory, the path is modified to be relative to the given
267  /// working directory.
268  /// \returns true if \c path changed.
269  bool FixupRelativePath(SmallVectorImpl<char> &path) const;
270 
271  /// Makes \c Path absolute taking into account FileSystemOptions and the
272  /// working directory option.
273  /// \returns true if \c Path changed to absolute.
274  bool makeAbsolutePath(SmallVectorImpl<char> &Path) const;
275 
276  /// Produce an array mapping from the unique IDs assigned to each
277  /// file to the corresponding FileEntry pointer.
278  void GetUniqueIDMapping(
279  SmallVectorImpl<const FileEntry *> &UIDToFiles) const;
280 
281  /// Modifies the size and modification time of a previously created
282  /// FileEntry. Use with caution.
283  static void modifyFileEntry(FileEntry *File, off_t Size,
284  time_t ModificationTime);
285 
286  /// Retrieve the canonical name for a given directory.
287  ///
288  /// This is a very expensive operation, despite its results being cached,
289  /// and should only be used when the physical layout of the file system is
290  /// required, which is (almost) never.
291  StringRef getCanonicalName(const DirectoryEntry *Dir);
292 
293  void PrintStats() const;
294 };
295 
296 } // end namespace clang
297 
298 #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
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Definition: Dominators.h:30
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:1726
const DirectoryEntry * getDir() const
Return the directory the file lives in.
Definition: FileManager.h:92
#define false
Definition: stdbool.h:17
StringRef getName() const
Definition: FileManager.h:83
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
Definition: FileManager.h:229
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:230
void setVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Definition: FileManager.h:234
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.
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:232
StringRef getName() const
Definition: FileManager.h:51