20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Config/llvm-config.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/IOSandbox.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/VirtualFileSystem.h"
29#include "llvm/Support/raw_ostream.h"
38#define DEBUG_TYPE "file-search"
41 std::optional<std::string> &Storage) {
42 using namespace llvm::sys::path;
46 if (Path.size() > 1 && root_path(Path) != Path && is_separator(Path.back()))
47 Path = Path.drop_back();
52 if (is_style_windows(Style::native)) {
53 if (Path.size() > 1 && Path.back() ==
':' &&
54 Path.equals_insensitive(root_name(Path))) {
55 Storage = Path.str() +
".";
70 : FS(
std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
71 SeenFileEntries(64), NextFileUID(0) {
75 this->FS = llvm::vfs::getRealFileSystem();
80 this->FS = std::move(FS);
90llvm::ErrorOr<DirectoryEntryRef>
91FileManager::getDirectoryFromFile(StringRef Filename,
bool CacheFailure) {
95 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
98 StringRef DirName = llvm::sys::path::parent_path(Filename);
103 return getDirectoryRefImpl(DirName, CacheFailure);
106DirectoryEntry *&FileManager::getRealDirEntry(
const llvm::vfs::Status &Status) {
107 assert(Status.isDirectory() &&
"The directory should exist!");
124void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
125 StringRef DirName = llvm::sys::path::parent_path(Path);
132 std::optional<std::string>
Storage;
133 StringRef OriginalDirName = DirName;
136 auto &NamedDirEnt = *SeenDirEntries.insert(
137 {DirName, std::errc::no_such_file_or_directory}).first;
143 if (NamedDirEnt.second)
147 llvm::vfs::Status Status;
149 getStatValue(DirName, Status,
false,
nullptr );
153 auto *UDE =
new (DirsAlloc.Allocate()) DirectoryEntry();
154 NamedDirEnt.second = *UDE;
155 VirtualDirectoryEntries.push_back(UDE);
158 DirectoryEntry *&UDE = getRealDirEntry(Status);
159 NamedDirEnt.second = *UDE;
163 addAncestorsAsVirtualDirs(OriginalDirName);
166llvm::ErrorOr<DirectoryEntryRef>
167FileManager::getDirectoryRefImpl(StringRef DirName,
bool CacheFailure) {
168 std::optional<std::string> DirNameStr;
175 auto SeenDirInsertResult =
176 SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
177 if (!SeenDirInsertResult.second) {
178 if (SeenDirInsertResult.first->second)
179 return DirectoryEntryRef(*SeenDirInsertResult.first);
180 return SeenDirInsertResult.first->second.getError();
185 auto &NamedDirEnt = *SeenDirInsertResult.first;
186 assert(!NamedDirEnt.second &&
"should be newly-created");
190 StringRef InterndDirName = NamedDirEnt.first();
193 llvm::vfs::Status Status;
194 auto statError = getStatValue(InterndDirName, Status,
false,
199 NamedDirEnt.second = statError;
201 SeenDirEntries.erase(DirName);
206 DirectoryEntry *&UDE = getRealDirEntry(Status);
207 NamedDirEnt.second = *UDE;
209 return DirectoryEntryRef(NamedDirEnt);
212llvm::ErrorOr<FileEntryRef> FileManager::getFileRefImpl(StringRef Filename,
219 auto SeenFileInsertResult =
220 SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
221 if (!SeenFileInsertResult.second) {
222 if (!SeenFileInsertResult.first->second)
223 return SeenFileInsertResult.first->second.getError();
224 return FileEntryRef(*SeenFileInsertResult.first);
228 ++NumFileCacheMisses;
229 auto *NamedFileEnt = &*SeenFileInsertResult.first;
230 assert(!NamedFileEnt->second &&
"should be newly-created");
234 StringRef InterndFileName = NamedFileEnt->first();
241 auto DirInfoOrErr = getDirectoryFromFile(Filename, CacheFailure);
243 std::error_code Err = DirInfoOrErr.getError();
245 NamedFileEnt->second = Err;
247 SeenFileEntries.erase(Filename);
251 DirectoryEntryRef DirInfo = *DirInfoOrErr;
257 std::unique_ptr<llvm::vfs::File> F;
258 llvm::vfs::Status Status;
259 auto statError = getStatValue(InterndFileName, Status,
true,
260 openFile ? &F :
nullptr, IsText);
264 NamedFileEnt->second = statError;
266 SeenFileEntries.erase(Filename);
271 assert((openFile || !F) &&
"undesired open file");
275 FileEntry *&UFE = UniqueRealFiles[Status.getUniqueID()];
276 bool ReusingEntry = UFE !=
nullptr;
278 UFE =
new (FilesAlloc.Allocate()) FileEntry();
280 if (!Status.ExposesExternalVFSPath || Status.getName() == Filename) {
282 NamedFileEnt->second = FileEntryRef::MapValue(*UFE, DirInfo);
321 .insert({Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)})
324 "filename redirected to a non-canonical filename?");
326 "filename from getStatValue() refers to wrong file");
330 NamedFileEnt->second = FileEntryRef::MapValue(Redirection, DirInfo);
333 FileEntryRef ReturnedRef(*NamedFileEnt);
339 UFE->Size = Status.getSize();
340 UFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
342 UFE->UID = NextFileUID++;
343 UFE->UniqueID = Status.getUniqueID();
344 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
346 Status.getType() == llvm::sys::fs::file_type::character_file;
347 UFE->File = std::move(F);
350 if (
auto PathName = UFE->File->getName())
351 fillRealPathName(UFE, *PathName);
352 }
else if (!openFile) {
354 fillRealPathName(UFE, InterndFileName);
364 auto ContentOrError = [] {
365 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
366 return llvm::MemoryBuffer::getSTDIN();
370 return llvm::createFileError(
"-", ContentOrError.getError());
372 auto Content = std::move(*ContentOrError);
374 Content->getBufferSize(), 0);
376 FE.Content = std::move(Content);
377 FE.IsNamedPipe =
true;
382 FS->visit([Active](llvm::vfs::FileSystem &FileSys) {
383 if (
auto *RFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&FileSys))
384 RFS->setUsageTrackingActive(Active);
389 time_t ModificationTime) {
393 auto &NamedFileEnt = *SeenFileEntries.insert(
394 {Filename, std::errc::no_such_file_or_directory}).first;
395 if (NamedFileEnt.second) {
403 ++NumFileCacheMisses;
404 addAncestorsAsVirtualDirs(Filename);
413 auto DirInfo = getDirectoryFromFile(Filename.empty() ?
"." : Filename,
416 "The directory of a virtual file should already be in the cache.");
419 llvm::vfs::Status Status;
420 const char *InterndFileName = NamedFileEnt.first().data();
421 if (!getStatValue(InterndFileName, Status,
true,
nullptr)) {
422 Status = llvm::vfs::Status(
423 Status.getName(), Status.getUniqueID(),
424 llvm::sys::toTimePoint(ModificationTime),
425 Status.getUser(), Status.getGroup(), Size,
426 Status.getType(), Status.getPermissions());
428 auto &RealFE = UniqueRealFiles[Status.getUniqueID()];
443 RealFE =
new (FilesAlloc.Allocate())
FileEntry();
444 RealFE->UniqueID = Status.getUniqueID();
445 RealFE->IsNamedPipe =
446 Status.getType() == llvm::sys::fs::file_type::fifo_file;
447 fillRealPathName(RealFE, Status.getName());
452 UFE =
new (FilesAlloc.Allocate())
FileEntry();
453 VirtualFileEntries.push_back(UFE);
458 UFE->ModTime = ModificationTime;
460 UFE->UID = NextFileUID++;
467 llvm::vfs::Status Status;
468 if (getStatValue(VF.
getName(), Status,
true,
nullptr))
471 if (!SeenBypassFileEntries)
472 SeenBypassFileEntries = std::make_unique<
473 llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
476 auto Insertion = SeenBypassFileEntries->insert(
477 {VF.
getName(), std::errc::no_such_file_or_directory});
478 if (!Insertion.second)
483 BypassFileEntries.push_back(BFE);
485 BFE->Size = Status.getSize();
487 BFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
488 BFE->UID = NextFileUID++;
496 StringRef pathRef(Path.data(), Path.size());
498 if (FileSystemOpts.WorkingDir.empty()
499 || llvm::sys::path::is_absolute(pathRef))
503 llvm::sys::path::append(NewPath, pathRef);
504 Path = std::move(NewPath);
509 bool Canonicalize)
const {
512 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
513 FS->makeAbsolute(Path);
518 Changed |= llvm::sys::path::remove_dots(Path);
530 llvm::sys::path::remove_dots(AbsPath,
true);
531 UFE->RealPathName = std::string(AbsPath);
534llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
536 bool RequiresNullTerminator,
537 std::optional<int64_t> MaybeLimit,
bool IsText) {
541 return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
543 uint64_t FileSize = Entry->
getSize();
546 FileSize = *MaybeLimit;
553 StringRef Filename = FE.
getName();
556 auto Result = Entry->File->getBuffer(Filename, FileSize,
557 RequiresNullTerminator, isVolatile);
563 return getBufferForFileImpl(Filename, FileSize, isVolatile,
564 RequiresNullTerminator, IsText);
567llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
568FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
569 bool isVolatile,
bool RequiresNullTerminator,
572 return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
577 return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
581std::error_code FileManager::getStatValue(StringRef Path,
582 llvm::vfs::Status &Status,
584 std::unique_ptr<llvm::vfs::File> *F,
596 bool isForDir = !isFile;
597 std::error_code RetCode;
599 if (isForDir || !F) {
602 llvm::ErrorOr<llvm::vfs::Status> StatusOrErr = FS->status(Path);
604 RetCode = StatusOrErr.getError();
606 Status = *StatusOrErr;
617 IsText ? FS->openFileForRead(Path) : FS->openFileForReadBinary(Path);
621 RetCode = OwnedFile.getError();
626 llvm::ErrorOr<llvm::vfs::Status> StatusOrErr = (*OwnedFile)->status();
628 Status = *StatusOrErr;
629 *F = std::move(*OwnedFile);
634 RetCode = StatusOrErr.getError();
645 if (Status.isDirectory() != isForDir) {
649 return std::make_error_code(Status.isDirectory()
650 ? std::errc::is_a_directory
651 : std::errc::not_a_directory);
654 return std::error_code();
666 llvm::DenseMap<const void *, llvm::StringRef>::iterator
Known =
667 CanonicalNames.find(Entry);
668 if (
Known != CanonicalNames.end())
669 return Known->second;
673 StringRef CanonicalName(Name);
677 if (!FS->getRealPath(Name, RealPathBuf)) {
678 if (is_style_windows(llvm::sys::path::Style::native)) {
682 if (!FS->makeAbsolute(AbsPathBuf)) {
683 if (llvm::sys::path::root_name(RealPathBuf) ==
684 llvm::sys::path::root_name(AbsPathBuf)) {
685 CanonicalName = RealPathBuf.str().copy(CanonicalNameStorage);
690 llvm::sys::path::remove_dots(AbsPathBuf,
true);
691 CanonicalName = AbsPathBuf.str().copy(CanonicalNameStorage);
695 CanonicalName = RealPathBuf.str().copy(CanonicalNameStorage);
699 CanonicalNames.insert({Entry, CanonicalName});
700 return CanonicalName;
704 assert(&
Other !=
this &&
"Collecting stats into the same FileManager");
705 NumDirLookups +=
Other.NumDirLookups;
706 NumFileLookups +=
Other.NumFileLookups;
707 NumDirCacheMisses +=
Other.NumDirCacheMisses;
708 NumFileCacheMisses +=
Other.NumFileCacheMisses;
712 llvm::errs() <<
"\n*** File Manager Stats:\n";
713 llvm::errs() << UniqueRealFiles.size() <<
" real files found, "
714 << UniqueRealDirs.size() <<
" real dirs found.\n";
715 llvm::errs() << VirtualFileEntries.size() <<
" virtual files found, "
716 << VirtualDirectoryEntries.size() <<
" virtual dirs found.\n";
717 llvm::errs() << NumDirLookups <<
" dir lookups, "
718 << NumDirCacheMisses <<
" dir cache misses.\n";
719 llvm::errs() << NumFileLookups <<
" file lookups, "
720 << NumFileCacheMisses <<
" file cache misses.\n";
723 if (
auto *T = dyn_cast_or_null<llvm::vfs::TracingFileSystem>(&VFS))
724 llvm::errs() <<
"\n*** Virtual File System Stats:\n"
725 << T->NumStatusCalls <<
" status() calls\n"
726 << T->NumOpenFileForReadCalls <<
" openFileForRead() calls\n"
727 << T->NumDirBeginCalls <<
" dir_begin() calls\n"
728 << T->NumGetRealPathCalls <<
" getRealPath() calls\n"
729 << T->NumExistsCalls <<
" exists() calls\n"
730 << T->NumIsLocalCalls <<
" isLocal() calls\n";
static void normalizeCacheKey(StringRef &Path, std::optional< std::string > &Storage)
Defines the clang::FileManager interface and associated types.
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
StringRef getName() const
const DirectoryEntry & getDirEntry() const
Cached information about one directory (either on disk or in the virtual file system).
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
const FileEntry & getFileEntry() const
StringRef getName() const
The name of this FileEntry.
DirectoryEntryRef getDir() const
Cached information about one file (either on disk or in the virtual file system).
bool isNamedPipe() const
Check whether the file is a named pipe (and thus can't be opened by the native FileManager methods).
void AddStats(const FileManager &Other)
Import statistics from a child FileManager and add them to this current FileManager.
void trackVFSUsage(bool Active)
Enable or disable tracking of VFS usage.
llvm::vfs::FileSystem & getVirtualFileSystem() const
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::Expected< FileEntryRef > getSTDIN()
Get the FileEntryRef for stdin, returning an error if stdin cannot be read.
StringRef getCanonicalName(DirectoryEntryRef Dir)
Retrieve the canonical name for a given directory.
FileManager(const FileSystemOptions &FileSystemOpts, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Construct a file manager, optionally with a custom VFS.
void setVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
bool FixupRelativePath(SmallVectorImpl< char > &Path) const
If path is not absolute and FileSystemOptions set the working directory, the path is modified to be r...
bool makeAbsolutePath(SmallVectorImpl< char > &Path, bool Canonicalize=false) const
Makes Path absolute taking into account FileSystemOptions and the working directory option,...
OptionalFileEntryRef getBypassFile(FileEntryRef VFE)
Retrieve a FileEntry that bypasses VFE, which is expected to be a virtual file entry,...
static bool fixupRelativePath(const FileSystemOptions &FileSystemOpts, SmallVectorImpl< char > &Path)
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::error_code make_error_code(BuildPreambleError Error)
@ Result
The result type of a method or function.
U cast(CodeGen::Address addr)
Type stored in the StringMap.