#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemStatCache.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/system_error.h"
#include "llvm/Config/llvm-config.h"
#include <map>
#include <set>
#include <string>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#include <sys/uio.h>
#else
#include <io.h>
#endif
using namespace clang;
#include <sys/stat.h>
#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
FileEntry::~FileEntry() {
if (FD != -1) ::close(FD);
}
#ifdef LLVM_ON_WIN32
namespace {
static std::string GetFullPath(const char *relPath) {
char *absPathStrPtr = _fullpath(NULL, relPath, 0);
assert(absPathStrPtr && "_fullpath() returned NULL!");
std::string absPath(absPathStrPtr);
free(absPathStrPtr);
return absPath;
}
}
class FileManager::UniqueDirContainer {
llvm::StringMap<DirectoryEntry> UniqueDirs;
public:
DirectoryEntry &getDirectory(const char *Name,
const struct stat & ) {
std::string FullPath(GetFullPath(Name));
return UniqueDirs.GetOrCreateValue(FullPath).getValue();
}
size_t size() const { return UniqueDirs.size(); }
};
class FileManager::UniqueFileContainer {
llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
public:
FileEntry &getFile(const char *Name, const struct stat & ) {
std::string FullPath(GetFullPath(Name));
FullPath = StringRef(FullPath).lower();
return UniqueFiles.GetOrCreateValue(FullPath).getValue();
}
size_t size() const { return UniqueFiles.size(); }
};
#else
class FileManager::UniqueDirContainer {
std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
public:
DirectoryEntry &getDirectory(const char * ,
const struct stat &StatBuf) {
return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
}
size_t size() const { return UniqueDirs.size(); }
};
class FileManager::UniqueFileContainer {
std::set<FileEntry> UniqueFiles;
public:
FileEntry &getFile(const char * , const struct stat &StatBuf) {
return
const_cast<FileEntry&>(
*UniqueFiles.insert(FileEntry(StatBuf.st_dev,
StatBuf.st_ino,
StatBuf.st_mode)).first);
}
size_t size() const { return UniqueFiles.size(); }
};
#endif
FileManager::FileManager(const FileSystemOptions &FSO)
: FileSystemOpts(FSO),
UniqueRealDirs(*new UniqueDirContainer()),
UniqueRealFiles(*new UniqueFileContainer()),
SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
NumDirLookups = NumFileLookups = 0;
NumDirCacheMisses = NumFileCacheMisses = 0;
}
FileManager::~FileManager() {
delete &UniqueRealDirs;
delete &UniqueRealFiles;
for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
delete VirtualFileEntries[i];
for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
delete VirtualDirectoryEntries[i];
}
void FileManager::addStatCache(FileSystemStatCache *statCache,
bool AtBeginning) {
assert(statCache && "No stat cache provided?");
if (AtBeginning || StatCache.get() == 0) {
statCache->setNextStatCache(StatCache.take());
StatCache.reset(statCache);
return;
}
FileSystemStatCache *LastCache = StatCache.get();
while (LastCache->getNextStatCache())
LastCache = LastCache->getNextStatCache();
LastCache->setNextStatCache(statCache);
}
void FileManager::removeStatCache(FileSystemStatCache *statCache) {
if (!statCache)
return;
if (StatCache.get() == statCache) {
StatCache.reset(StatCache->takeNextStatCache());
return;
}
FileSystemStatCache *PrevCache = StatCache.get();
while (PrevCache && PrevCache->getNextStatCache() != statCache)
PrevCache = PrevCache->getNextStatCache();
assert(PrevCache && "Stat cache not found for removal");
PrevCache->setNextStatCache(statCache->getNextStatCache());
}
static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
StringRef Filename,
bool CacheFailure) {
if (Filename.empty())
return NULL;
if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
return NULL;
StringRef DirName = llvm::sys::path::parent_path(Filename);
if (DirName.empty())
DirName = ".";
return FileMgr.getDirectory(DirName, CacheFailure);
}
void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
StringRef DirName = llvm::sys::path::parent_path(Path);
if (DirName.empty())
return;
llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
SeenDirEntries.GetOrCreateValue(DirName);
if (NamedDirEnt.getValue())
return;
DirectoryEntry *UDE = new DirectoryEntry;
UDE->Name = NamedDirEnt.getKeyData();
NamedDirEnt.setValue(UDE);
VirtualDirectoryEntries.push_back(UDE);
addAncestorsAsVirtualDirs(DirName);
}
const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
bool CacheFailure) {
if (DirName.size() > 1 && llvm::sys::path::is_separator(DirName.back()))
DirName = DirName.substr(0, DirName.size()-1);
++NumDirLookups;
llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
SeenDirEntries.GetOrCreateValue(DirName);
if (NamedDirEnt.getValue())
return NamedDirEnt.getValue() == NON_EXISTENT_DIR
? 0 : NamedDirEnt.getValue();
++NumDirCacheMisses;
NamedDirEnt.setValue(NON_EXISTENT_DIR);
const char *InterndDirName = NamedDirEnt.getKeyData();
struct stat StatBuf;
if (getStatValue(InterndDirName, StatBuf, 0)) {
if (!CacheFailure)
SeenDirEntries.erase(DirName);
return 0;
}
DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
NamedDirEnt.setValue(&UDE);
if (!UDE.getName()) {
UDE.Name = InterndDirName;
}
return &UDE;
}
const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
bool CacheFailure) {
++NumFileLookups;
llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
SeenFileEntries.GetOrCreateValue(Filename);
if (NamedFileEnt.getValue())
return NamedFileEnt.getValue() == NON_EXISTENT_FILE
? 0 : NamedFileEnt.getValue();
++NumFileCacheMisses;
NamedFileEnt.setValue(NON_EXISTENT_FILE);
const char *InterndFileName = NamedFileEnt.getKeyData();
const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
CacheFailure);
if (DirInfo == 0) { if (!CacheFailure)
SeenFileEntries.erase(Filename);
return 0;
}
int FileDescriptor = -1;
struct stat StatBuf;
if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
if (!CacheFailure)
SeenFileEntries.erase(Filename);
return 0;
}
if (FileDescriptor != -1 && !openFile) {
close(FileDescriptor);
FileDescriptor = -1;
}
FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
NamedFileEnt.setValue(&UFE);
if (UFE.getName()) { if (FileDescriptor != -1)
close(FileDescriptor);
return &UFE;
}
UFE.Name = InterndFileName;
UFE.Size = StatBuf.st_size;
UFE.ModTime = StatBuf.st_mtime;
UFE.Dir = DirInfo;
UFE.UID = NextFileUID++;
UFE.FD = FileDescriptor;
return &UFE;
}
const FileEntry *
FileManager::getVirtualFile(StringRef Filename, off_t Size,
time_t ModificationTime) {
++NumFileLookups;
llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
SeenFileEntries.GetOrCreateValue(Filename);
if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
return NamedFileEnt.getValue();
++NumFileCacheMisses;
NamedFileEnt.setValue(NON_EXISTENT_FILE);
addAncestorsAsVirtualDirs(Filename);
FileEntry *UFE = 0;
const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
true);
assert(DirInfo &&
"The directory of a virtual file should already be in the cache.");
int FileDescriptor = -1;
struct stat StatBuf;
const char *InterndFileName = NamedFileEnt.getKeyData();
if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
if (FileDescriptor != -1)
close(FileDescriptor);
StatBuf.st_size = Size;
StatBuf.st_mtime = ModificationTime;
UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
NamedFileEnt.setValue(UFE);
if (UFE->FD != -1) {
close(UFE->FD);
UFE->FD = -1;
}
if (UFE->getName())
return UFE;
}
if (!UFE) {
UFE = new FileEntry();
VirtualFileEntries.push_back(UFE);
NamedFileEnt.setValue(UFE);
}
UFE->Name = InterndFileName;
UFE->Size = Size;
UFE->ModTime = ModificationTime;
UFE->Dir = DirInfo;
UFE->UID = NextFileUID++;
UFE->FD = -1;
return UFE;
}
void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
StringRef pathRef(path.data(), path.size());
if (FileSystemOpts.WorkingDir.empty()
|| llvm::sys::path::is_absolute(pathRef))
return;
SmallString<128> NewPath(FileSystemOpts.WorkingDir);
llvm::sys::path::append(NewPath, pathRef);
path = NewPath;
}
llvm::MemoryBuffer *FileManager::
getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
OwningPtr<llvm::MemoryBuffer> Result;
llvm::error_code ec;
const char *Filename = Entry->getName();
if (Entry->FD != -1) {
ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result,
Entry->getSize());
if (ErrorStr)
*ErrorStr = ec.message();
close(Entry->FD);
Entry->FD = -1;
return Result.take();
}
if (FileSystemOpts.WorkingDir.empty()) {
ec = llvm::MemoryBuffer::getFile(Filename, Result, Entry->getSize());
if (ec && ErrorStr)
*ErrorStr = ec.message();
return Result.take();
}
SmallString<128> FilePath(Entry->getName());
FixupRelativePath(FilePath);
ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, Entry->getSize());
if (ec && ErrorStr)
*ErrorStr = ec.message();
return Result.take();
}
llvm::MemoryBuffer *FileManager::
getBufferForFile(StringRef Filename, std::string *ErrorStr) {
OwningPtr<llvm::MemoryBuffer> Result;
llvm::error_code ec;
if (FileSystemOpts.WorkingDir.empty()) {
ec = llvm::MemoryBuffer::getFile(Filename, Result);
if (ec && ErrorStr)
*ErrorStr = ec.message();
return Result.take();
}
SmallString<128> FilePath(Filename);
FixupRelativePath(FilePath);
ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
if (ec && ErrorStr)
*ErrorStr = ec.message();
return Result.take();
}
bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
int *FileDescriptor) {
if (FileSystemOpts.WorkingDir.empty())
return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
StatCache.get());
SmallString<128> FilePath(Path);
FixupRelativePath(FilePath);
return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
StatCache.get());
}
bool FileManager::getNoncachedStatValue(StringRef Path,
struct stat &StatBuf) {
SmallString<128> FilePath(Path);
FixupRelativePath(FilePath);
return ::stat(FilePath.c_str(), &StatBuf) != 0;
}
void FileManager::GetUniqueIDMapping(
SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
UIDToFiles.clear();
UIDToFiles.resize(NextFileUID);
for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
FE != FEEnd; ++FE)
if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
for (SmallVector<FileEntry*, 4>::const_iterator
VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
VFE != VFEEnd; ++VFE)
if (*VFE && *VFE != NON_EXISTENT_FILE)
UIDToFiles[(*VFE)->getUID()] = *VFE;
}
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";
}