Clang Project

clang_source_code/include/clang/Basic/FileManager.h
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
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"
28#include <ctime>
29#include <map>
30#include <memory>
31#include <string>
32
33namespace llvm {
34
35class MemoryBuffer;
36
37// end namespace llvm
38
39namespace clang {
40
41class FileSystemStatCache;
42
43/// Cached information about one directory (either on disk or in
44/// the virtual file system).
45class DirectoryEntry {
46  friend class FileManager;
47
48  StringRef Name// Name of the directory.
49
50public:
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.
59class 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
75public:
76  FileEntry()
77      : UniqueID(00), 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 &RHSconst { 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///
116class FileManager : public RefCountedBase<FileManager> {
117  IntrusiveRefCntPtr<llvm::vfs::FileSystemFS;
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>, 4VirtualDirectoryEntries;
131  /// The virtual files that we have allocated.
132  SmallVector<std::unique_ptr<FileEntry>, 4VirtualFileEntries;
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 NumDirLookupsNumFileLookups;
162  unsigned NumDirCacheMissesNumFileCacheMisses;
163
164  // Caching.
165  std::unique_ptr<FileSystemStatCacheStatCache;
166
167  bool getStatValue(StringRef Path, llvm::vfs::Status &Statusbool 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 *UFEllvm::StringRef FileName);
176
177public:
178  /// Construct a file manager, optionally with a custom VFS.
179  ///
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::FileSystemFS = nullptr);
184  ~FileManager();
185
186  /// Installs the provided FileSystemStatCache object within
187  /// the FileManager.
188  ///
189  /// Ownership of this object is transferred to the FileManager.
190  ///
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<FileSystemStatCachestatCache);
194
195  /// Removes the FileSystemStatCache object from the manager.
196  void clearStatCache();
197
198  /// Lookup, cache, and verify the specified directory (real or
199  /// virtual).
200  ///
201  /// This returns NULL if the directory doesn't exist.
202  ///
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);
207
208  /// Lookup, cache, and verify the specified file (real or
209  /// virtual).
210  ///
211  /// This returns NULL if the file doesn't exist.
212  ///
213  /// \param OpenFile if true and the file exists, it will be opened.
214  ///
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 Filenamebool OpenFile = false,
218                           bool CacheFailure = true);
219
220  /// Returns the current file system options
221  FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }
222  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
223
224  llvm::vfs::FileSystem &getVirtualFileSystem() const { return *FS; }
225
226  /// Retrieve a file entry for a "virtual" file that acts as
227  /// if there were a file with the given name on disk.
228  ///
229  /// The file itself is not accessed.
230  const FileEntry *getVirtualFile(StringRef Filenameoff_t Size,
231                                  time_t ModificationTime);
232
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);
240
241  /// Get the 'stat' information for the given \p Path.
242  ///
243  /// If the path is relative, it will be resolved against the WorkingDir of the
244  /// FileManager's FileSystemOptions.
245  ///
246  /// \returns false on success, true on error.
247  bool getNoncachedStatValue(StringRef Path, llvm::vfs::Status &Result);
248
249  /// Remove the real file \p Entry from the cache.
250  void invalidateCache(const FileEntry *Entry);
251
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> &pathconst;
257
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> &Pathconst;
262
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 *> &UIDToFilesconst;
267
268  /// Modifies the size and modification time of a previously created
269  /// FileEntry. Use with caution.
270  static void modifyFileEntry(FileEntry *Fileoff_t Size,
271                              time_t ModificationTime);
272
273  /// Retrieve the canonical name for a given directory.
274  ///
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);
279
280  void PrintStats() const;
281};
282
283// end namespace clang
284
285#endif // LLVM_CLANG_BASIC_FILEMANAGER_H
286
clang::DirectoryEntry::Name
clang::DirectoryEntry::getName
clang::FileEntry::Name
clang::FileEntry::RealPathName
clang::FileEntry::Size
clang::FileEntry::ModTime
clang::FileEntry::Dir
clang::FileEntry::UID
clang::FileEntry::UniqueID
clang::FileEntry::IsNamedPipe
clang::FileEntry::IsValid
clang::FileEntry::File
clang::FileEntry::getName
clang::FileEntry::tryGetRealPathName
clang::FileEntry::isValid
clang::FileEntry::getSize
clang::FileEntry::getUID
clang::FileEntry::getUniqueID
clang::FileEntry::getModificationTime
clang::FileEntry::getDir
clang::FileEntry::isNamedPipe
clang::FileEntry::closeFile
clang::FileEntry::isOpenForTests
clang::FileManager::FS
clang::FileManager::FileSystemOpts
clang::FileManager::UniqueRealDirs
clang::FileManager::UniqueRealFiles
clang::FileManager::VirtualDirectoryEntries
clang::FileManager::VirtualFileEntries
clang::FileManager::SeenDirEntries
clang::FileManager::SeenFileEntries
clang::FileManager::CanonicalDirNames
clang::FileManager::CanonicalNameStorage
clang::FileManager::NextFileUID
clang::FileManager::NumDirLookups
clang::FileManager::NumFileLookups
clang::FileManager::NumDirCacheMisses
clang::FileManager::NumFileCacheMisses
clang::FileManager::StatCache
clang::FileManager::getStatValue
clang::FileManager::addAncestorsAsVirtualDirs
clang::FileManager::fillRealPathName
clang::FileManager::setStatCache
clang::FileManager::clearStatCache
clang::FileManager::getDirectory
clang::FileManager::getFile
clang::FileManager::getFileSystemOpts
clang::FileManager::getFileSystemOpts
clang::FileManager::getVirtualFileSystem
clang::FileManager::getVirtualFile
clang::FileManager::getBufferForFile
clang::FileManager::getBufferForFile
clang::FileManager::getNoncachedStatValue
clang::FileManager::invalidateCache
clang::FileManager::FixupRelativePath
clang::FileManager::makeAbsolutePath
clang::FileManager::GetUniqueIDMapping
clang::FileManager::modifyFileEntry
clang::FileManager::getCanonicalName
clang::FileManager::PrintStats