#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemStatCache.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <utility>
using namespace clang;
#define DEBUG_TYPE "file-search"
ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
"Number of directory cache misses.");
ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
FileManager::FileManager(const FileSystemOptions &FSO,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
: FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
SeenFileEntries(64), NextFileUID(0) {
if (!this->FS)
this->FS = llvm::vfs::getRealFileSystem();
}
FileManager::~FileManager() = default;
void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
assert(statCache && "No stat cache provided?");
StatCache = std::move(statCache);
}
void FileManager::clearStatCache() { StatCache.reset(); }
static llvm::Expected<DirectoryEntryRef>
getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
bool CacheFailure) {
if (Filename.empty())
return llvm::errorCodeToError(
make_error_code(std::errc::no_such_file_or_directory));
if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory));
StringRef DirName = llvm::sys::path::parent_path(Filename);
if (DirName.empty())
DirName = ".";
return FileMgr.getDirectoryRef(DirName, CacheFailure);
}
void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
StringRef DirName = llvm::sys::path::parent_path(Path);
if (DirName.empty())
DirName = ".";
auto &NamedDirEnt = *SeenDirEntries.insert(
{DirName, std::errc::no_such_file_or_directory}).first;
if (NamedDirEnt.second)
return;
auto *UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
UDE->Name = NamedDirEnt.first();
NamedDirEnt.second = *UDE;
VirtualDirectoryEntries.push_back(UDE);
addAncestorsAsVirtualDirs(DirName);
}
llvm::Expected<DirectoryEntryRef>
FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
if (DirName.size() > 1 &&
DirName != llvm::sys::path::root_path(DirName) &&
llvm::sys::path::is_separator(DirName.back()))
DirName = DirName.substr(0, DirName.size()-1);
Optional<std::string> DirNameStr;
if (is_style_windows(llvm::sys::path::Style::native)) {
if (DirName.size() > 1 && DirName.back() == ':' &&
DirName.equals_insensitive(llvm::sys::path::root_name(DirName))) {
DirNameStr = DirName.str() + '.';
DirName = *DirNameStr;
}
}
++NumDirLookups;
auto SeenDirInsertResult =
SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
if (!SeenDirInsertResult.second) {
if (SeenDirInsertResult.first->second)
return DirectoryEntryRef(*SeenDirInsertResult.first);
return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
}
++NumDirCacheMisses;
auto &NamedDirEnt = *SeenDirInsertResult.first;
assert(!NamedDirEnt.second && "should be newly-created");
StringRef InterndDirName = NamedDirEnt.first();
llvm::vfs::Status Status;
auto statError = getStatValue(InterndDirName, Status, false,
nullptr );
if (statError) {
if (CacheFailure)
NamedDirEnt.second = statError;
else
SeenDirEntries.erase(DirName);
return llvm::errorCodeToError(statError);
}
DirectoryEntry *&UDE = UniqueRealDirs[Status.getUniqueID()];
if (!UDE) {
UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
UDE->Name = InterndDirName;
}
NamedDirEnt.second = *UDE;
return DirectoryEntryRef(NamedDirEnt);
}
llvm::ErrorOr<const DirectoryEntry *>
FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
auto Result = getDirectoryRef(DirName, CacheFailure);
if (Result)
return &Result->getDirEntry();
return llvm::errorToErrorCode(Result.takeError());
}
llvm::ErrorOr<const FileEntry *>
FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
auto Result = getFileRef(Filename, openFile, CacheFailure);
if (Result)
return &Result->getFileEntry();
return llvm::errorToErrorCode(Result.takeError());
}
llvm::Expected<FileEntryRef>
FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
++NumFileLookups;
auto SeenFileInsertResult =
SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
if (!SeenFileInsertResult.second) {
if (!SeenFileInsertResult.first->second)
return llvm::errorCodeToError(
SeenFileInsertResult.first->second.getError());
FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
return FileEntryRef(*SeenFileInsertResult.first);
return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
Value.V.get<const void *>()));
}
++NumFileCacheMisses;
auto *NamedFileEnt = &*SeenFileInsertResult.first;
assert(!NamedFileEnt->second && "should be newly-created");
StringRef InterndFileName = NamedFileEnt->first();
auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
if (!DirInfoOrErr) { std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
if (CacheFailure)
NamedFileEnt->second = Err;
else
SeenFileEntries.erase(Filename);
return llvm::errorCodeToError(Err);
}
DirectoryEntryRef DirInfo = *DirInfoOrErr;
std::unique_ptr<llvm::vfs::File> F;
llvm::vfs::Status Status;
auto statError = getStatValue(InterndFileName, Status, true,
openFile ? &F : nullptr);
if (statError) {
if (CacheFailure)
NamedFileEnt->second = statError;
else
SeenFileEntries.erase(Filename);
return llvm::errorCodeToError(statError);
}
assert((openFile || !F) && "undesired open file");
FileEntry *&UFE = UniqueRealFiles[Status.getUniqueID()];
bool ReusingEntry = UFE != nullptr;
if (!UFE)
UFE = new (FilesAlloc.Allocate()) FileEntry();
if (Status.getName() == Filename) {
NamedFileEnt->second = FileEntryRef::MapValue(*UFE, DirInfo);
} else {
auto &Redirection =
*SeenFileEntries
.insert({Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)})
.first;
assert(Redirection.second->V.is<FileEntry *>() &&
"filename redirected to a non-canonical filename?");
assert(Redirection.second->V.get<FileEntry *>() == UFE &&
"filename from getStatValue() refers to wrong file");
NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
NamedFileEnt = &Redirection;
}
FileEntryRef ReturnedRef(*NamedFileEnt);
if (ReusingEntry) {
if (&DirInfo.getDirEntry() != UFE->Dir && Status.IsVFSMapped)
UFE->Dir = &DirInfo.getDirEntry();
UFE->LastRef = ReturnedRef;
return ReturnedRef;
}
UFE->LastRef = ReturnedRef;
UFE->Size = Status.getSize();
UFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
UFE->Dir = &DirInfo.getDirEntry();
UFE->UID = NextFileUID++;
UFE->UniqueID = Status.getUniqueID();
UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
UFE->File = std::move(F);
if (UFE->File) {
if (auto PathName = UFE->File->getName())
fillRealPathName(UFE, *PathName);
} else if (!openFile) {
fillRealPathName(UFE, InterndFileName);
}
return ReturnedRef;
}
llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
if (STDIN)
return *STDIN;
std::unique_ptr<llvm::MemoryBuffer> Content;
if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
Content = std::move(*ContentOrError);
else
return llvm::errorCodeToError(ContentOrError.getError());
STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
Content->getBufferSize(), 0);
FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
FE.Content = std::move(Content);
FE.IsNamedPipe = true;
return *STDIN;
}
const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
time_t ModificationTime) {
return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
}
FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
time_t ModificationTime) {
++NumFileLookups;
auto &NamedFileEnt = *SeenFileEntries.insert(
{Filename, std::errc::no_such_file_or_directory}).first;
if (NamedFileEnt.second) {
FileEntryRef::MapValue Value = *NamedFileEnt.second;
if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
return FileEntryRef(NamedFileEnt);
return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
Value.V.get<const void *>()));
}
++NumFileCacheMisses;
addAncestorsAsVirtualDirs(Filename);
FileEntry *UFE = nullptr;
auto DirInfo = expectedToOptional(getDirectoryFromFile(
*this, Filename.empty() ? "." : Filename, true));
assert(DirInfo &&
"The directory of a virtual file should already be in the cache.");
llvm::vfs::Status Status;
const char *InterndFileName = NamedFileEnt.first().data();
if (!getStatValue(InterndFileName, Status, true, nullptr)) {
Status = llvm::vfs::Status(
Status.getName(), Status.getUniqueID(),
llvm::sys::toTimePoint(ModificationTime),
Status.getUser(), Status.getGroup(), Size,
Status.getType(), Status.getPermissions());
auto &RealFE = UniqueRealFiles[Status.getUniqueID()];
if (RealFE) {
if (RealFE->File)
RealFE->closeFile();
NamedFileEnt.second = FileEntryRef::MapValue(*RealFE, *DirInfo);
return FileEntryRef(NamedFileEnt);
}
RealFE = new (FilesAlloc.Allocate()) FileEntry();
RealFE->UniqueID = Status.getUniqueID();
RealFE->IsNamedPipe =
Status.getType() == llvm::sys::fs::file_type::fifo_file;
fillRealPathName(RealFE, Status.getName());
UFE = RealFE;
} else {
UFE = new (FilesAlloc.Allocate()) FileEntry();
VirtualFileEntries.push_back(UFE);
}
NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
UFE->LastRef = FileEntryRef(NamedFileEnt);
UFE->Size = Size;
UFE->ModTime = ModificationTime;
UFE->Dir = &DirInfo->getDirEntry();
UFE->UID = NextFileUID++;
UFE->File.reset();
return FileEntryRef(NamedFileEnt);
}
llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
llvm::vfs::Status Status;
if (getStatValue(VF.getName(), Status, true, nullptr))
return None;
if (!SeenBypassFileEntries)
SeenBypassFileEntries = std::make_unique<
llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
auto Insertion = SeenBypassFileEntries->insert(
{VF.getName(), std::errc::no_such_file_or_directory});
if (!Insertion.second)
return FileEntryRef(*Insertion.first);
FileEntry *BFE = new (FilesAlloc.Allocate()) FileEntry();
BypassFileEntries.push_back(BFE);
Insertion.first->second = FileEntryRef::MapValue(*BFE, VF.getDir());
BFE->LastRef = FileEntryRef(*Insertion.first);
BFE->Size = Status.getSize();
BFE->Dir = VF.getFileEntry().Dir;
BFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
BFE->UID = NextFileUID++;
return FileEntryRef(*Insertion.first);
}
bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
StringRef pathRef(path.data(), path.size());
if (FileSystemOpts.WorkingDir.empty()
|| llvm::sys::path::is_absolute(pathRef))
return false;
SmallString<128> NewPath(FileSystemOpts.WorkingDir);
llvm::sys::path::append(NewPath, pathRef);
path = NewPath;
return true;
}
bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
bool Changed = FixupRelativePath(Path);
if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
FS->makeAbsolute(Path);
Changed = true;
}
return Changed;
}
void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
llvm::SmallString<128> AbsPath(FileName);
makeAbsolutePath(AbsPath);
llvm::sys::path::remove_dots(AbsPath, true);
UFE->RealPathName = std::string(AbsPath.str());
}
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
bool RequiresNullTerminator) {
if (Entry->Content)
return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
uint64_t FileSize = Entry->getSize();
if (isVolatile || Entry->isNamedPipe())
FileSize = -1;
StringRef Filename = Entry->getName();
if (Entry->File) {
auto Result = Entry->File->getBuffer(Filename, FileSize,
RequiresNullTerminator, isVolatile);
Entry->closeFile();
return Result;
}
return getBufferForFileImpl(Filename, FileSize, isVolatile,
RequiresNullTerminator);
}
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
bool isVolatile,
bool RequiresNullTerminator) {
if (FileSystemOpts.WorkingDir.empty())
return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
isVolatile);
SmallString<128> FilePath(Filename);
FixupRelativePath(FilePath);
return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
isVolatile);
}
std::error_code
FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
if (FileSystemOpts.WorkingDir.empty())
return FileSystemStatCache::get(Path, Status, isFile, F,
StatCache.get(), *FS);
SmallString<128> FilePath(Path);
FixupRelativePath(FilePath);
return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
StatCache.get(), *FS);
}
std::error_code
FileManager::getNoncachedStatValue(StringRef Path,
llvm::vfs::Status &Result) {
SmallString<128> FilePath(Path);
FixupRelativePath(FilePath);
llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
if (!S)
return S.getError();
Result = *S;
return std::error_code();
}
void FileManager::GetUniqueIDMapping(
SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
UIDToFiles.clear();
UIDToFiles.resize(NextFileUID);
for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
llvm::BumpPtrAllocator>::const_iterator
FE = SeenFileEntries.begin(),
FEEnd = SeenFileEntries.end();
FE != FEEnd; ++FE)
if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
UIDToFiles[FE->getUID()] = FE;
}
for (const auto &VFE : VirtualFileEntries)
UIDToFiles[VFE->getUID()] = VFE;
}
StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
= CanonicalNames.find(Dir);
if (Known != CanonicalNames.end())
return Known->second;
StringRef CanonicalName(Dir->getName());
SmallString<4096> CanonicalNameBuf;
if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
CanonicalNames.insert({Dir, CanonicalName});
return CanonicalName;
}
StringRef FileManager::getCanonicalName(const FileEntry *File) {
llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
= CanonicalNames.find(File);
if (Known != CanonicalNames.end())
return Known->second;
StringRef CanonicalName(File->getName());
SmallString<4096> CanonicalNameBuf;
if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
CanonicalNames.insert({File, CanonicalName});
return CanonicalName;
}
void FileManager::PrintStats() const {
llvm::errs() << "\n*** File Manager Stats:\n";
llvm::errs() << UniqueRealFiles.size() << " real files found, "
<< UniqueRealDirs.size() << " real dirs found.\n";
llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
<< VirtualDirectoryEntries.size() << " virtual dirs found.\n";
llvm::errs() << NumDirLookups << " dir lookups, "
<< NumDirCacheMisses << " dir cache misses.\n";
llvm::errs() << NumFileLookups << " file lookups, "
<< NumFileCacheMisses << " file cache misses.\n";
}