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 InPCH;
71  bool IsValid; // Is this \c FileEntry initialized and valid?
72  bool DeferredOpen; // Created by getFile(OpenFile=0); may open later.
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  DeferredOpen(false) {}
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  // Only for use in tests to see if deferred opens are happening, rather than
108  // relying on RealPathName being empty.
109  bool isOpenForTests() const { return File != nullptr; }
110 };
111 
112 struct FileData;
113 
114 /// Implements support for file system lookup, file system caching,
115 /// and directory search management.
116 ///
117 /// This also handles more advanced properties, such as uniquing files based
118 /// on "inode", so that a file with two names (e.g. symlinked) will be treated
119 /// as a single file.
120 ///
121 class FileManager : public RefCountedBase<FileManager> {
123  FileSystemOptions FileSystemOpts;
124 
125  /// Cache for existing real directories.
126  std::map<llvm::sys::fs::UniqueID, DirectoryEntry> UniqueRealDirs;
127 
128  /// Cache for existing real files.
129  std::map<llvm::sys::fs::UniqueID, FileEntry> UniqueRealFiles;
130 
131  /// The virtual directories that we have allocated.
132  ///
133  /// For each virtual file (e.g. foo/bar/baz.cpp), we add all of its parent
134  /// directories (foo/ and foo/bar/) here.
135  SmallVector<std::unique_ptr<DirectoryEntry>, 4> VirtualDirectoryEntries;
136  /// The virtual files that we have allocated.
137  SmallVector<std::unique_ptr<FileEntry>, 4> VirtualFileEntries;
138 
139  /// A cache that maps paths to directory entries (either real or
140  /// virtual) we have looked up
141  ///
142  /// The actual Entries for real directories/files are
143  /// owned by UniqueRealDirs/UniqueRealFiles above, while the Entries
144  /// for virtual directories/files are owned by
145  /// VirtualDirectoryEntries/VirtualFileEntries above.
146  ///
147  llvm::StringMap<DirectoryEntry*, llvm::BumpPtrAllocator> SeenDirEntries;
148 
149  /// A cache that maps paths to file entries (either real or
150  /// virtual) we have looked up.
151  ///
152  /// \see SeenDirEntries
153  llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator> SeenFileEntries;
154 
155  /// The canonical names of directories.
156  llvm::DenseMap<const DirectoryEntry *, llvm::StringRef> CanonicalDirNames;
157 
158  /// Storage for canonical names that we have computed.
159  llvm::BumpPtrAllocator CanonicalNameStorage;
160 
161  /// Each FileEntry we create is assigned a unique ID #.
162  ///
163  unsigned NextFileUID;
164 
165  // Statistics.
166  unsigned NumDirLookups, NumFileLookups;
167  unsigned NumDirCacheMisses, NumFileCacheMisses;
168 
169  // Caching.
170  std::unique_ptr<FileSystemStatCache> StatCache;
171 
172  bool getStatValue(StringRef Path, FileData &Data, 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  FileManager(const FileSystemOptions &FileSystemOpts,
185  ~FileManager();
186 
187  /// Installs the provided FileSystemStatCache object within
188  /// the FileManager.
189  ///
190  /// Ownership of this object is transferred to the FileManager.
191  ///
192  /// \param statCache the new stat cache to install. Ownership of this
193  /// object is transferred to the FileManager.
194  void setStatCache(std::unique_ptr<FileSystemStatCache> statCache);
195 
196  /// Removes the FileSystemStatCache object from the manager.
197  void clearStatCache();
198 
199  /// Lookup, cache, and verify the specified directory (real or
200  /// virtual).
201  ///
202  /// This returns NULL if the directory doesn't exist.
203  ///
204  /// \param CacheFailure If true and the file does not exist, we'll cache
205  /// the failure to find this file.
206  const DirectoryEntry *getDirectory(StringRef DirName,
207  bool CacheFailure = true);
208 
209  /// Lookup, cache, and verify the specified file (real or
210  /// virtual).
211  ///
212  /// This returns NULL if the file doesn't exist.
213  ///
214  /// \param OpenFile if true and the file exists, it will be opened.
215  ///
216  /// \param CacheFailure If true and the file does not exist, we'll cache
217  /// the failure to find this file.
218  const FileEntry *getFile(StringRef Filename, bool OpenFile = false,
219  bool CacheFailure = true);
220 
221  /// Returns the current file system options
222  FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }
223  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
224 
226  return FS;
227  }
228 
229  /// Retrieve a file entry for a "virtual" file that acts as
230  /// if there were a file with the given name on disk.
231  ///
232  /// The file itself is not accessed.
233  const FileEntry *getVirtualFile(StringRef Filename, off_t Size,
234  time_t ModificationTime);
235 
236  /// Open the specified file as a MemoryBuffer, returning a new
237  /// MemoryBuffer if successful, otherwise returning null.
238  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
239  getBufferForFile(const FileEntry *Entry, bool isVolatile = false,
240  bool ShouldCloseOpenFile = true);
241  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
242  getBufferForFile(StringRef Filename, bool isVolatile = false);
243 
244  /// Get the 'stat' information for the given \p Path.
245  ///
246  /// If the path is relative, it will be resolved against the WorkingDir of the
247  /// FileManager's FileSystemOptions.
248  ///
249  /// \returns false on success, true on error.
250  bool getNoncachedStatValue(StringRef Path, llvm::vfs::Status &Result);
251 
252  /// Remove the real file \p Entry from the cache.
253  void invalidateCache(const FileEntry *Entry);
254 
255  /// If path is not absolute and FileSystemOptions set the working
256  /// directory, the path is modified to be relative to the given
257  /// working directory.
258  /// \returns true if \c path changed.
259  bool FixupRelativePath(SmallVectorImpl<char> &path) const;
260 
261  /// Makes \c Path absolute taking into account FileSystemOptions and the
262  /// working directory option.
263  /// \returns true if \c Path changed to absolute.
264  bool makeAbsolutePath(SmallVectorImpl<char> &Path) const;
265 
266  /// Produce an array mapping from the unique IDs assigned to each
267  /// file to the corresponding FileEntry pointer.
268  void GetUniqueIDMapping(
269  SmallVectorImpl<const FileEntry *> &UIDToFiles) const;
270 
271  /// Modifies the size and modification time of a previously created
272  /// FileEntry. Use with caution.
273  static void modifyFileEntry(FileEntry *File, off_t Size,
274  time_t ModificationTime);
275 
276  /// Retrieve the canonical name for a given directory.
277  ///
278  /// This is a very expensive operation, despite its results being cached,
279  /// and should only be used when the physical layout of the file system is
280  /// required, which is (almost) never.
281  StringRef getCanonicalName(const DirectoryEntry *Dir);
282 
283  void PrintStats() const;
284 };
285 
286 } // end namespace clang
287 
288 #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:121
time_t getModificationTime() const
Definition: FileManager.h:92
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:29
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
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
StringRef Filename
Definition: Format.cpp:1628
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:222
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:59
const FileSystemOptions & getFileSystemOpts() const
Definition: FileManager.h:223
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
bool isOpenForTests() const
Definition: FileManager.h:109
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:225
StringRef getName() const
Definition: FileManager.h:51