1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
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 //===----------------------------------------------------------------------===//
9 // This file implements the FileManager interface.
11 //===----------------------------------------------------------------------===//
13 // TODO: This should index all interesting directories with dirent calls.
15 // opendir/readdir_r/closedir ?
17 //===----------------------------------------------------------------------===//
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemStatCache.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Config/llvm-config.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 #define DEBUG_TYPE "file-search"
41 ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
42 ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
43 ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
44 "Number of directory cache misses.");
45 ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
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 // If the caller doesn't provide a virtual file system, just grab the real
58 this->FS = llvm::vfs::getRealFileSystem();
61 FileManager::~FileManager() = default;
63 void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64 assert(statCache && "No stat cache provided?");
65 StatCache = std::move(statCache);
68 void FileManager::clearStatCache() { StatCache.reset(); }
70 /// Retrieve the directory that the given file name resides in.
71 /// Filename can point to either a real file or a virtual file.
72 static llvm::ErrorOr<const DirectoryEntry *>
73 getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
76 return std::errc::no_such_file_or_directory;
78 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
79 return std::errc::is_a_directory;
81 StringRef DirName = llvm::sys::path::parent_path(Filename);
82 // Use the current directory if file has no path component.
86 return FileMgr.getDirectory(DirName, CacheFailure);
89 /// Add all ancestors of the given path (pointing to either a file or
90 /// a directory) as virtual directories.
91 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
92 StringRef DirName = llvm::sys::path::parent_path(Path);
96 auto &NamedDirEnt = *SeenDirEntries.insert(
97 {DirName, std::errc::no_such_file_or_directory}).first;
99 // When caching a virtual directory, we always cache its ancestors
100 // at the same time. Therefore, if DirName is already in the cache,
101 // we don't need to recurse as its ancestors must also already be in
102 // the cache (or it's a known non-virtual directory).
103 if (NamedDirEnt.second)
106 // Add the virtual directory to the cache.
107 auto UDE = std::make_unique<DirectoryEntry>();
108 UDE->Name = NamedDirEnt.first();
109 NamedDirEnt.second = *UDE.get();
110 VirtualDirectoryEntries.push_back(std::move(UDE));
112 // Recursively add the other ancestors.
113 addAncestorsAsVirtualDirs(DirName);
116 llvm::Expected<DirectoryEntryRef>
117 FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
118 // stat doesn't like trailing separators except for root directory.
119 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
120 // (though it can strip '\\')
121 if (DirName.size() > 1 &&
122 DirName != llvm::sys::path::root_path(DirName) &&
123 llvm::sys::path::is_separator(DirName.back()))
124 DirName = DirName.substr(0, DirName.size()-1);
126 // Fixing a problem with "clang C:test.c" on Windows.
127 // Stat("C:") does not recognize "C:" as a valid directory
128 std::string DirNameStr;
129 if (DirName.size() > 1 && DirName.back() == ':' &&
130 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
131 DirNameStr = DirName.str() + '.';
132 DirName = DirNameStr;
138 // See if there was already an entry in the map. Note that the map
139 // contains both virtual and real directories.
140 auto SeenDirInsertResult =
141 SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
142 if (!SeenDirInsertResult.second) {
143 if (SeenDirInsertResult.first->second)
144 return DirectoryEntryRef(&*SeenDirInsertResult.first);
145 return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
148 // We've not seen this before. Fill it in.
150 auto &NamedDirEnt = *SeenDirInsertResult.first;
151 assert(!NamedDirEnt.second && "should be newly-created");
153 // Get the null-terminated directory name as stored as the key of the
154 // SeenDirEntries map.
155 StringRef InterndDirName = NamedDirEnt.first();
157 // Check to see if the directory exists.
158 llvm::vfs::Status Status;
159 auto statError = getStatValue(InterndDirName, Status, false,
160 nullptr /*directory lookup*/);
162 // There's no real directory at the given path.
164 NamedDirEnt.second = statError;
166 SeenDirEntries.erase(DirName);
167 return llvm::errorCodeToError(statError);
170 // It exists. See if we have already opened a directory with the
171 // same inode (this occurs on Unix-like systems when one dir is
172 // symlinked to another, for example) or the same path (on
174 DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
176 NamedDirEnt.second = UDE;
177 if (UDE.getName().empty()) {
178 // We don't have this directory yet, add it. We use the string
179 // key from the SeenDirEntries map as the string.
180 UDE.Name = InterndDirName;
183 return DirectoryEntryRef(&NamedDirEnt);
186 llvm::ErrorOr<const DirectoryEntry *>
187 FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
188 auto Result = getDirectoryRef(DirName, CacheFailure);
190 return &Result->getDirEntry();
191 return llvm::errorToErrorCode(Result.takeError());
194 llvm::ErrorOr<const FileEntry *>
195 FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
196 auto Result = getFileRef(Filename, openFile, CacheFailure);
198 return &Result->getFileEntry();
199 return llvm::errorToErrorCode(Result.takeError());
202 llvm::Expected<FileEntryRef>
203 FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
206 // See if there is already an entry in the map.
207 auto SeenFileInsertResult =
208 SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
209 if (!SeenFileInsertResult.second) {
210 if (!SeenFileInsertResult.first->second)
211 return llvm::errorCodeToError(
212 SeenFileInsertResult.first->second.getError());
213 // Construct and return and FileEntryRef, unless it's a redirect to another
215 SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second;
217 if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
218 return FileEntryRef(SeenFileInsertResult.first->first(), *FE);
219 return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure);
222 // We've not seen this before. Fill it in.
223 ++NumFileCacheMisses;
224 auto &NamedFileEnt = *SeenFileInsertResult.first;
225 assert(!NamedFileEnt.second && "should be newly-created");
227 // Get the null-terminated file name as stored as the key of the
228 // SeenFileEntries map.
229 StringRef InterndFileName = NamedFileEnt.first();
231 // Look up the directory for the file. When looking up something like
232 // sys/foo.h we'll discover all of the search directories that have a 'sys'
233 // subdirectory. This will let us avoid having to waste time on known-to-fail
234 // searches when we go to find sys/bar.h, because all the search directories
235 // without a 'sys' subdir will get a cached failure result.
236 auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
237 if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
239 NamedFileEnt.second = DirInfoOrErr.getError();
241 SeenFileEntries.erase(Filename);
243 return llvm::errorCodeToError(DirInfoOrErr.getError());
245 const DirectoryEntry *DirInfo = *DirInfoOrErr;
247 // FIXME: Use the directory info to prune this, before doing the stat syscall.
248 // FIXME: This will reduce the # syscalls.
250 // Check to see if the file exists.
251 std::unique_ptr<llvm::vfs::File> F;
252 llvm::vfs::Status Status;
253 auto statError = getStatValue(InterndFileName, Status, true,
254 openFile ? &F : nullptr);
256 // There's no real file at the given path.
258 NamedFileEnt.second = statError;
260 SeenFileEntries.erase(Filename);
262 return llvm::errorCodeToError(statError);
265 assert((openFile || !F) && "undesired open file");
267 // It exists. See if we have already opened a file with the same inode.
268 // This occurs when one dir is symlinked to another, for example.
269 FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
271 NamedFileEnt.second = &UFE;
273 // If the name returned by getStatValue is different than Filename, re-intern
275 if (Status.getName() != Filename) {
276 auto &NewNamedFileEnt =
277 *SeenFileEntries.insert({Status.getName(), &UFE}).first;
278 assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE &&
279 "filename from getStatValue() refers to wrong file");
280 InterndFileName = NewNamedFileEnt.first().data();
281 // In addition to re-interning the name, construct a redirecting seen file
282 // entry, that will point to the name the filesystem actually wants to use.
283 StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName);
284 NamedFileEnt.second = Redirect;
287 if (UFE.isValid()) { // Already have an entry with this inode, return it.
289 // FIXME: this hack ensures that if we look up a file by a virtual path in
290 // the VFS that the getDir() will have the virtual path, even if we found
291 // the file by a 'real' path first. This is required in order to find a
292 // module's structure when its headers/module map are mapped in the VFS.
293 // We should remove this as soon as we can properly support a file having
295 if (DirInfo != UFE.Dir && Status.IsVFSMapped)
298 // Always update the name to use the last name by which a file was accessed.
299 // FIXME: Neither this nor always using the first name is correct; we want
300 // to switch towards a design where we return a FileName object that
301 // encapsulates both the name by which the file was accessed and the
302 // corresponding FileEntry.
303 // FIXME: The Name should be removed from FileEntry once all clients
304 // adopt FileEntryRef.
305 UFE.Name = InterndFileName;
307 return FileEntryRef(InterndFileName, UFE);
310 // Otherwise, we don't have this file yet, add it.
311 UFE.Name = InterndFileName;
312 UFE.Size = Status.getSize();
313 UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
315 UFE.UID = NextFileUID++;
316 UFE.UniqueID = Status.getUniqueID();
317 UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
318 UFE.File = std::move(F);
322 if (auto PathName = UFE.File->getName())
323 fillRealPathName(&UFE, *PathName);
324 } else if (!openFile) {
325 // We should still fill the path even if we aren't opening the file.
326 fillRealPathName(&UFE, InterndFileName);
328 return FileEntryRef(InterndFileName, UFE);
332 FileManager::getVirtualFile(StringRef Filename, off_t Size,
333 time_t ModificationTime) {
336 // See if there is already an entry in the map for an existing file.
337 auto &NamedFileEnt = *SeenFileEntries.insert(
338 {Filename, std::errc::no_such_file_or_directory}).first;
339 if (NamedFileEnt.second) {
340 SeenFileEntryOrRedirect Value = *NamedFileEnt.second;
342 if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
344 return getVirtualFile(*Value.get<const StringRef *>(), Size,
348 // We've not seen this before, or the file is cached as non-existent.
349 ++NumFileCacheMisses;
350 addAncestorsAsVirtualDirs(Filename);
351 FileEntry *UFE = nullptr;
353 // Now that all ancestors of Filename are in the cache, the
354 // following call is guaranteed to find the DirectoryEntry from the
356 auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
358 "The directory of a virtual file should already be in the cache.");
360 // Check to see if the file exists. If so, drop the virtual file
361 llvm::vfs::Status Status;
362 const char *InterndFileName = NamedFileEnt.first().data();
363 if (!getStatValue(InterndFileName, Status, true, nullptr)) {
364 UFE = &UniqueRealFiles[Status.getUniqueID()];
365 Status = llvm::vfs::Status(
366 Status.getName(), Status.getUniqueID(),
367 llvm::sys::toTimePoint(ModificationTime),
368 Status.getUser(), Status.getGroup(), Size,
369 Status.getType(), Status.getPermissions());
371 NamedFileEnt.second = UFE;
373 // If we had already opened this file, close it now so we don't
374 // leak the descriptor. We're not going to use the file
375 // descriptor anyway, since this is a virtual file.
379 // If we already have an entry with this inode, return it.
383 UFE->UniqueID = Status.getUniqueID();
384 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
385 fillRealPathName(UFE, Status.getName());
387 VirtualFileEntries.push_back(std::make_unique<FileEntry>());
388 UFE = VirtualFileEntries.back().get();
389 NamedFileEnt.second = UFE;
392 UFE->Name = InterndFileName;
394 UFE->ModTime = ModificationTime;
396 UFE->UID = NextFileUID++;
402 llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
403 // Stat of the file and return nullptr if it doesn't exist.
404 llvm::vfs::Status Status;
405 if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
408 // Fill it in from the stat.
409 BypassFileEntries.push_back(std::make_unique<FileEntry>());
410 const FileEntry &VFE = VF.getFileEntry();
411 FileEntry &BFE = *BypassFileEntries.back();
412 BFE.Name = VFE.getName();
413 BFE.Size = Status.getSize();
415 BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
416 BFE.UID = NextFileUID++;
418 return FileEntryRef(VF.getName(), BFE);
421 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
422 StringRef pathRef(path.data(), path.size());
424 if (FileSystemOpts.WorkingDir.empty()
425 || llvm::sys::path::is_absolute(pathRef))
428 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
429 llvm::sys::path::append(NewPath, pathRef);
434 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
435 bool Changed = FixupRelativePath(Path);
437 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
438 FS->makeAbsolute(Path);
445 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
446 llvm::SmallString<128> AbsPath(FileName);
447 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
448 // but can be very expensive on real file systems.
449 // FIXME: the semantic of RealPathName is unclear, and the name might be
450 // misleading. We need to clean up the interface here.
451 makeAbsolutePath(AbsPath);
452 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
453 UFE->RealPathName = AbsPath.str();
456 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
457 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile) {
458 uint64_t FileSize = Entry->getSize();
459 // If there's a high enough chance that the file have changed since we
460 // got its size, force a stat before opening it.
464 StringRef Filename = Entry->getName();
465 // If the file is already open, use the open file descriptor.
468 Entry->File->getBuffer(Filename, FileSize,
469 /*RequiresNullTerminator=*/true, isVolatile);
474 // Otherwise, open the file.
475 return getBufferForFileImpl(Filename, FileSize, isVolatile);
478 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
479 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
481 if (FileSystemOpts.WorkingDir.empty())
482 return FS->getBufferForFile(Filename, FileSize,
483 /*RequiresNullTerminator=*/true, isVolatile);
485 SmallString<128> FilePath(Filename);
486 FixupRelativePath(FilePath);
487 return FS->getBufferForFile(FilePath, FileSize,
488 /*RequiresNullTerminator=*/true, isVolatile);
491 /// getStatValue - Get the 'stat' information for the specified path,
492 /// using the cache to accelerate it if possible. This returns true
493 /// if the path points to a virtual file or does not exist, or returns
494 /// false if it's an existent real file. If FileDescriptor is NULL,
495 /// do directory look-up instead of file look-up.
497 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
498 bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
499 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
501 if (FileSystemOpts.WorkingDir.empty())
502 return FileSystemStatCache::get(Path, Status, isFile, F,
503 StatCache.get(), *FS);
505 SmallString<128> FilePath(Path);
506 FixupRelativePath(FilePath);
508 return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
509 StatCache.get(), *FS);
513 FileManager::getNoncachedStatValue(StringRef Path,
514 llvm::vfs::Status &Result) {
515 SmallString<128> FilePath(Path);
516 FixupRelativePath(FilePath);
518 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
522 return std::error_code();
525 void FileManager::GetUniqueIDMapping(
526 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
528 UIDToFiles.resize(NextFileUID);
531 for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>,
532 llvm::BumpPtrAllocator>::const_iterator
533 FE = SeenFileEntries.begin(),
534 FEEnd = SeenFileEntries.end();
536 if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) {
537 if (const auto *FE = (*Entry).dyn_cast<FileEntry *>())
538 UIDToFiles[FE->getUID()] = FE;
541 // Map virtual file entries
542 for (const auto &VFE : VirtualFileEntries)
543 UIDToFiles[VFE->getUID()] = VFE.get();
546 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
547 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
548 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
549 = CanonicalDirNames.find(Dir);
550 if (Known != CanonicalDirNames.end())
551 return Known->second;
553 StringRef CanonicalName(Dir->getName());
555 SmallString<4096> CanonicalNameBuf;
556 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
557 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
559 CanonicalDirNames.insert({Dir, CanonicalName});
560 return CanonicalName;
563 void FileManager::PrintStats() const {
564 llvm::errs() << "\n*** File Manager Stats:\n";
565 llvm::errs() << UniqueRealFiles.size() << " real files found, "
566 << UniqueRealDirs.size() << " real dirs found.\n";
567 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
568 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
569 llvm::errs() << NumDirLookups << " dir lookups, "
570 << NumDirCacheMisses << " dir cache misses.\n";
571 llvm::errs() << NumFileLookups << " file lookups, "
572 << NumFileCacheMisses << " file cache misses.\n";
574 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;