1 //===--- FileManager.h - File System Probing and Caching --------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// Defines the clang::FileManager interface and associated types.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_BASIC_FILEMANAGER_H
15 #define LLVM_CLANG_BASIC_FILEMANAGER_H
17 #include "clang/Basic/FileSystemOptions.h"
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"
37 } // end namespace llvm
41 class FileSystemStatCache;
43 /// Cached information about one directory (either on disk or in
44 /// the virtual file system).
45 class DirectoryEntry {
46 friend class FileManager;
48 StringRef Name; // Name of the directory.
51 StringRef getName() const { return Name; }
54 /// Cached information about one file (either on disk
55 /// or in the virtual file system).
57 /// If the 'File' member is valid, then this FileEntry has an open file
58 /// descriptor for the file.
60 friend class FileManager;
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;
70 bool IsValid; // Is this \c FileEntry initialized and valid?
72 /// The open file, if it is owned by the \p FileEntry.
73 mutable std::unique_ptr<llvm::vfs::File> File;
77 : UniqueID(0, 0), IsNamedPipe(false), IsValid(false)
80 FileEntry(const FileEntry &) = delete;
81 FileEntry &operator=(const FileEntry &) = delete;
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; }
91 /// Return the directory the file lives in.
92 const DirectoryEntry *getDir() const { return Dir; }
94 bool operator<(const FileEntry &RHS) const { return UniqueID < RHS.UniqueID; }
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; }
100 void closeFile() const {
101 File.reset(); // rely on destructor to close File
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; }
109 /// Implements support for file system lookup, file system caching,
110 /// and directory search management.
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.
116 class FileManager : public RefCountedBase<FileManager> {
117 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS;
118 FileSystemOptions FileSystemOpts;
120 /// Cache for existing real directories.
121 std::map<llvm::sys::fs::UniqueID, DirectoryEntry> UniqueRealDirs;
123 /// Cache for existing real files.
124 std::map<llvm::sys::fs::UniqueID, FileEntry> UniqueRealFiles;
126 /// The virtual directories that we have allocated.
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;
134 /// A cache that maps paths to directory entries (either real or
135 /// virtual) we have looked up
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.
142 llvm::StringMap<DirectoryEntry*, llvm::BumpPtrAllocator> SeenDirEntries;
144 /// A cache that maps paths to file entries (either real or
145 /// virtual) we have looked up.
147 /// \see SeenDirEntries
148 llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator> SeenFileEntries;
150 /// The canonical names of directories.
151 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef> CanonicalDirNames;
153 /// Storage for canonical names that we have computed.
154 llvm::BumpPtrAllocator CanonicalNameStorage;
156 /// Each FileEntry we create is assigned a unique ID #.
158 unsigned NextFileUID;
161 unsigned NumDirLookups, NumFileLookups;
162 unsigned NumDirCacheMisses, NumFileCacheMisses;
165 std::unique_ptr<FileSystemStatCache> StatCache;
167 bool getStatValue(StringRef Path, llvm::vfs::Status &Status, bool isFile,
168 std::unique_ptr<llvm::vfs::File> *F);
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);
174 /// Fills the RealPathName in file entry.
175 void fillRealPathName(FileEntry *UFE, llvm::StringRef FileName);
178 /// Construct a file manager, optionally with a custom VFS.
180 /// \param FS if non-null, the VFS to use. Otherwise uses
181 /// llvm::vfs::getRealFileSystem().
182 FileManager(const FileSystemOptions &FileSystemOpts,
183 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
186 /// Installs the provided FileSystemStatCache object within
189 /// Ownership of this object is transferred to the FileManager.
191 /// \param statCache the new stat cache to install. Ownership of this
192 /// object is transferred to the FileManager.
193 void setStatCache(std::unique_ptr<FileSystemStatCache> statCache);
195 /// Removes the FileSystemStatCache object from the manager.
196 void clearStatCache();
198 /// Lookup, cache, and verify the specified directory (real or
201 /// This returns NULL if the directory doesn't exist.
203 /// \param CacheFailure If true and the file does not exist, we'll cache
204 /// the failure to find this file.
205 const DirectoryEntry *getDirectory(StringRef DirName,
206 bool CacheFailure = true);
208 /// Lookup, cache, and verify the specified file (real or
211 /// This returns NULL if the file doesn't exist.
213 /// \param OpenFile if true and the file exists, it will be opened.
215 /// \param CacheFailure If true and the file does not exist, we'll cache
216 /// the failure to find this file.
217 const FileEntry *getFile(StringRef Filename, bool OpenFile = false,
218 bool CacheFailure = true);
220 /// Returns the current file system options
221 FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }
222 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
224 llvm::vfs::FileSystem &getVirtualFileSystem() const { return *FS; }
226 /// Retrieve a file entry for a "virtual" file that acts as
227 /// if there were a file with the given name on disk.
229 /// The file itself is not accessed.
230 const FileEntry *getVirtualFile(StringRef Filename, off_t Size,
231 time_t ModificationTime);
233 /// Open the specified file as a MemoryBuffer, returning a new
234 /// MemoryBuffer if successful, otherwise returning null.
235 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
236 getBufferForFile(const FileEntry *Entry, bool isVolatile = false,
237 bool ShouldCloseOpenFile = true);
238 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
239 getBufferForFile(StringRef Filename, bool isVolatile = false);
241 /// Get the 'stat' information for the given \p Path.
243 /// If the path is relative, it will be resolved against the WorkingDir of the
244 /// FileManager's FileSystemOptions.
246 /// \returns false on success, true on error.
247 bool getNoncachedStatValue(StringRef Path, llvm::vfs::Status &Result);
249 /// Remove the real file \p Entry from the cache.
250 void invalidateCache(const FileEntry *Entry);
252 /// If path is not absolute and FileSystemOptions set the working
253 /// directory, the path is modified to be relative to the given
254 /// working directory.
255 /// \returns true if \c path changed.
256 bool FixupRelativePath(SmallVectorImpl<char> &path) const;
258 /// Makes \c Path absolute taking into account FileSystemOptions and the
259 /// working directory option.
260 /// \returns true if \c Path changed to absolute.
261 bool makeAbsolutePath(SmallVectorImpl<char> &Path) const;
263 /// Produce an array mapping from the unique IDs assigned to each
264 /// file to the corresponding FileEntry pointer.
265 void GetUniqueIDMapping(
266 SmallVectorImpl<const FileEntry *> &UIDToFiles) const;
268 /// Modifies the size and modification time of a previously created
269 /// FileEntry. Use with caution.
270 static void modifyFileEntry(FileEntry *File, off_t Size,
271 time_t ModificationTime);
273 /// Retrieve the canonical name for a given directory.
275 /// This is a very expensive operation, despite its results being cached,
276 /// and should only be used when the physical layout of the file system is
277 /// required, which is (almost) never.
278 StringRef getCanonicalName(const DirectoryEntry *Dir);
280 void PrintStats() const;
283 } // end namespace clang
285 #endif // LLVM_CLANG_BASIC_FILEMANAGER_H