1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the FileManager interface.
12 //===----------------------------------------------------------------------===//
14 // TODO: This should index all interesting directories with dirent calls.
16 // opendir/readdir_r/closedir ?
18 //===----------------------------------------------------------------------===//
20 #include "clang/Basic/FileManager.h"
21 #include "clang/Basic/FileSystemStatCache.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Config/llvm-config.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/raw_ostream.h"
37 using namespace clang;
39 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
40 /// represent a dir name that doesn't exist on the disk.
41 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
43 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
44 /// represent a filename that doesn't exist on the disk.
45 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 FileManager::FileManager(const FileSystemOptions &FSO,
52 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
53 : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
54 SeenFileEntries(64), NextFileUID(0) {
55 NumDirLookups = NumFileLookups = 0;
56 NumDirCacheMisses = NumFileCacheMisses = 0;
58 // If the caller doesn't provide a virtual file system, just grab the real
61 this->FS = llvm::vfs::getRealFileSystem();
64 FileManager::~FileManager() = default;
66 void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
67 assert(statCache && "No stat cache provided?");
68 StatCache = std::move(statCache);
71 void FileManager::clearStatCache() { StatCache.reset(); }
73 /// Retrieve the directory that the given file name resides in.
74 /// Filename can point to either a real file or a virtual file.
75 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
81 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
82 return nullptr; // If Filename is a directory.
84 StringRef DirName = llvm::sys::path::parent_path(Filename);
85 // Use the current directory if file has no path component.
89 return FileMgr.getDirectory(DirName, CacheFailure);
92 /// Add all ancestors of the given path (pointing to either a file or
93 /// a directory) as virtual directories.
94 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
95 StringRef DirName = llvm::sys::path::parent_path(Path);
100 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
102 // When caching a virtual directory, we always cache its ancestors
103 // at the same time. Therefore, if DirName is already in the cache,
104 // we don't need to recurse as its ancestors must also already be in
106 if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR)
109 // Add the virtual directory to the cache.
110 auto UDE = llvm::make_unique<DirectoryEntry>();
111 UDE->Name = NamedDirEnt.first();
112 NamedDirEnt.second = UDE.get();
113 VirtualDirectoryEntries.push_back(std::move(UDE));
115 // Recursively add the other ancestors.
116 addAncestorsAsVirtualDirs(DirName);
119 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
121 // stat doesn't like trailing separators except for root directory.
122 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
123 // (though it can strip '\\')
124 if (DirName.size() > 1 &&
125 DirName != llvm::sys::path::root_path(DirName) &&
126 llvm::sys::path::is_separator(DirName.back()))
127 DirName = DirName.substr(0, DirName.size()-1);
129 // Fixing a problem with "clang C:test.c" on Windows.
130 // Stat("C:") does not recognize "C:" as a valid directory
131 std::string DirNameStr;
132 if (DirName.size() > 1 && DirName.back() == ':' &&
133 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
134 DirNameStr = DirName.str() + '.';
135 DirName = DirNameStr;
141 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
143 // See if there was already an entry in the map. Note that the map
144 // contains both virtual and real directories.
145 if (NamedDirEnt.second)
146 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
147 : NamedDirEnt.second;
151 // By default, initialize it to invalid.
152 NamedDirEnt.second = NON_EXISTENT_DIR;
154 // Get the null-terminated directory name as stored as the key of the
155 // SeenDirEntries map.
156 StringRef InterndDirName = NamedDirEnt.first();
158 // Check to see if the directory exists.
160 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
161 // There's no real directory at the given path.
163 SeenDirEntries.erase(DirName);
167 // It exists. See if we have already opened a directory with the
168 // same inode (this occurs on Unix-like systems when one dir is
169 // symlinked to another, for example) or the same path (on
171 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
173 NamedDirEnt.second = &UDE;
174 if (UDE.getName().empty()) {
175 // We don't have this directory yet, add it. We use the string
176 // key from the SeenDirEntries map as the string.
177 UDE.Name = InterndDirName;
183 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
187 // See if there is already an entry in the map.
189 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
191 // See if there is already an entry in the map.
192 if (NamedFileEnt.second)
193 return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr
194 : NamedFileEnt.second;
196 ++NumFileCacheMisses;
198 // By default, initialize it to invalid.
199 NamedFileEnt.second = NON_EXISTENT_FILE;
201 // Get the null-terminated file name as stored as the key of the
202 // SeenFileEntries map.
203 StringRef InterndFileName = NamedFileEnt.first();
205 // Look up the directory for the file. When looking up something like
206 // sys/foo.h we'll discover all of the search directories that have a 'sys'
207 // subdirectory. This will let us avoid having to waste time on known-to-fail
208 // searches when we go to find sys/bar.h, because all the search directories
209 // without a 'sys' subdir will get a cached failure result.
210 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
212 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
214 SeenFileEntries.erase(Filename);
219 // FIXME: Use the directory info to prune this, before doing the stat syscall.
220 // FIXME: This will reduce the # syscalls.
222 // Nope, there isn't. Check to see if the file exists.
223 std::unique_ptr<llvm::vfs::File> F;
225 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
226 // There's no real file at the given path.
228 SeenFileEntries.erase(Filename);
233 assert((openFile || !F) && "undesired open file");
235 // It exists. See if we have already opened a file with the same inode.
236 // This occurs when one dir is symlinked to another, for example.
237 FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
239 NamedFileEnt.second = &UFE;
241 // If the name returned by getStatValue is different than Filename, re-intern
243 if (Data.Name != Filename) {
245 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
246 if (!NamedFileEnt.second)
247 NamedFileEnt.second = &UFE;
249 assert(NamedFileEnt.second == &UFE &&
250 "filename from getStatValue() refers to wrong file");
251 InterndFileName = NamedFileEnt.first().data();
254 if (UFE.isValid()) { // Already have an entry with this inode, return it.
256 // FIXME: this hack ensures that if we look up a file by a virtual path in
257 // the VFS that the getDir() will have the virtual path, even if we found
258 // the file by a 'real' path first. This is required in order to find a
259 // module's structure when its headers/module map are mapped in the VFS.
260 // We should remove this as soon as we can properly support a file having
262 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
265 // Always update the name to use the last name by which a file was accessed.
266 // FIXME: Neither this nor always using the first name is correct; we want
267 // to switch towards a design where we return a FileName object that
268 // encapsulates both the name by which the file was accessed and the
269 // corresponding FileEntry.
270 UFE.Name = InterndFileName;
275 // Otherwise, we don't have this file yet, add it.
276 UFE.Name = InterndFileName;
277 UFE.Size = Data.Size;
278 UFE.ModTime = Data.ModTime;
280 UFE.UID = NextFileUID++;
281 UFE.UniqueID = Data.UniqueID;
282 UFE.IsNamedPipe = Data.IsNamedPipe;
283 UFE.InPCH = Data.InPCH;
284 UFE.File = std::move(F);
288 if (auto PathName = UFE.File->getName())
289 fillRealPathName(&UFE, *PathName);
295 FileManager::getVirtualFile(StringRef Filename, off_t Size,
296 time_t ModificationTime) {
299 // See if there is already an entry in the map.
301 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
303 // See if there is already an entry in the map.
304 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
305 return NamedFileEnt.second;
307 ++NumFileCacheMisses;
309 // By default, initialize it to invalid.
310 NamedFileEnt.second = NON_EXISTENT_FILE;
312 addAncestorsAsVirtualDirs(Filename);
313 FileEntry *UFE = nullptr;
315 // Now that all ancestors of Filename are in the cache, the
316 // following call is guaranteed to find the DirectoryEntry from the
318 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
319 /*CacheFailure=*/true);
321 "The directory of a virtual file should already be in the cache.");
323 // Check to see if the file exists. If so, drop the virtual file
325 const char *InterndFileName = NamedFileEnt.first().data();
326 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
328 Data.ModTime = ModificationTime;
329 UFE = &UniqueRealFiles[Data.UniqueID];
331 NamedFileEnt.second = UFE;
333 // If we had already opened this file, close it now so we don't
334 // leak the descriptor. We're not going to use the file
335 // descriptor anyway, since this is a virtual file.
339 // If we already have an entry with this inode, return it.
343 UFE->UniqueID = Data.UniqueID;
344 UFE->IsNamedPipe = Data.IsNamedPipe;
345 UFE->InPCH = Data.InPCH;
346 fillRealPathName(UFE, Data.Name);
350 VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
351 UFE = VirtualFileEntries.back().get();
352 NamedFileEnt.second = UFE;
355 UFE->Name = InterndFileName;
357 UFE->ModTime = ModificationTime;
359 UFE->UID = NextFileUID++;
365 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
366 StringRef pathRef(path.data(), path.size());
368 if (FileSystemOpts.WorkingDir.empty()
369 || llvm::sys::path::is_absolute(pathRef))
372 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
373 llvm::sys::path::append(NewPath, pathRef);
378 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
379 bool Changed = FixupRelativePath(Path);
381 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
382 FS->makeAbsolute(Path);
389 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
390 llvm::SmallString<128> AbsPath(FileName);
391 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
392 // but can be very expensive on real file systems.
393 // FIXME: the semantic of RealPathName is unclear, and the name might be
394 // misleading. We need to clean up the interface here.
395 makeAbsolutePath(AbsPath);
396 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
397 UFE->RealPathName = AbsPath.str();
400 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
401 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
402 bool ShouldCloseOpenFile) {
403 uint64_t FileSize = Entry->getSize();
404 // If there's a high enough chance that the file have changed since we
405 // got its size, force a stat before opening it.
409 StringRef Filename = Entry->getName();
410 // If the file is already open, use the open file descriptor.
413 Entry->File->getBuffer(Filename, FileSize,
414 /*RequiresNullTerminator=*/true, isVolatile);
415 // FIXME: we need a set of APIs that can make guarantees about whether a
416 // FileEntry is open or not.
417 if (ShouldCloseOpenFile)
422 // Otherwise, open the file.
424 if (FileSystemOpts.WorkingDir.empty())
425 return FS->getBufferForFile(Filename, FileSize,
426 /*RequiresNullTerminator=*/true, isVolatile);
428 SmallString<128> FilePath(Entry->getName());
429 FixupRelativePath(FilePath);
430 return FS->getBufferForFile(FilePath, FileSize,
431 /*RequiresNullTerminator=*/true, isVolatile);
434 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
435 FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
436 if (FileSystemOpts.WorkingDir.empty())
437 return FS->getBufferForFile(Filename, -1, true, isVolatile);
439 SmallString<128> FilePath(Filename);
440 FixupRelativePath(FilePath);
441 return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
444 /// getStatValue - Get the 'stat' information for the specified path,
445 /// using the cache to accelerate it if possible. This returns true
446 /// if the path points to a virtual file or does not exist, or returns
447 /// false if it's an existent real file. If FileDescriptor is NULL,
448 /// do directory look-up instead of file look-up.
449 bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile,
450 std::unique_ptr<llvm::vfs::File> *F) {
451 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
453 if (FileSystemOpts.WorkingDir.empty())
454 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
456 SmallString<128> FilePath(Path);
457 FixupRelativePath(FilePath);
459 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
460 StatCache.get(), *FS);
463 bool FileManager::getNoncachedStatValue(StringRef Path,
464 llvm::vfs::Status &Result) {
465 SmallString<128> FilePath(Path);
466 FixupRelativePath(FilePath);
468 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
475 void FileManager::invalidateCache(const FileEntry *Entry) {
476 assert(Entry && "Cannot invalidate a NULL FileEntry");
478 SeenFileEntries.erase(Entry->getName());
480 // FileEntry invalidation should not block future optimizations in the file
481 // caches. Possible alternatives are cache truncation (invalidate last N) or
482 // invalidation of the whole cache.
483 UniqueRealFiles.erase(Entry->getUniqueID());
486 void FileManager::GetUniqueIDMapping(
487 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
489 UIDToFiles.resize(NextFileUID);
492 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
493 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
495 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
496 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
498 // Map virtual file entries
499 for (const auto &VFE : VirtualFileEntries)
500 if (VFE && VFE.get() != NON_EXISTENT_FILE)
501 UIDToFiles[VFE->getUID()] = VFE.get();
504 void FileManager::modifyFileEntry(FileEntry *File,
505 off_t Size, time_t ModificationTime) {
507 File->ModTime = ModificationTime;
510 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
511 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
512 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
513 = CanonicalDirNames.find(Dir);
514 if (Known != CanonicalDirNames.end())
515 return Known->second;
517 StringRef CanonicalName(Dir->getName());
519 SmallString<4096> CanonicalNameBuf;
520 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
521 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
523 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
524 return CanonicalName;
527 void FileManager::PrintStats() const {
528 llvm::errs() << "\n*** File Manager Stats:\n";
529 llvm::errs() << UniqueRealFiles.size() << " real files found, "
530 << UniqueRealDirs.size() << " real dirs found.\n";
531 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
532 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
533 llvm::errs() << NumDirLookups << " dir lookups, "
534 << NumDirCacheMisses << " dir cache misses.\n";
535 llvm::errs() << NumFileLookups << " file lookups, "
536 << NumFileCacheMisses << " file cache misses.\n";
538 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;