Home | History | Annotate | Download | only in Basic
      1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements the FileManager interface.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 //
     14 // TODO: This should index all interesting directories with dirent calls.
     15 //  getdirentries ?
     16 //  opendir/readdir_r/closedir ?
     17 //
     18 //===----------------------------------------------------------------------===//
     19 
     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"
     29 #include <map>
     30 #include <set>
     31 #include <string>
     32 #include <system_error>
     33 
     34 using namespace clang;
     35 
     36 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
     37 /// represent a dir name that doesn't exist on the disk.
     38 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
     39 
     40 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
     41 /// represent a filename that doesn't exist on the disk.
     42 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
     43 
     44 //===----------------------------------------------------------------------===//
     45 // Common logic.
     46 //===----------------------------------------------------------------------===//
     47 
     48 FileManager::FileManager(const FileSystemOptions &FSO,
     49                          IntrusiveRefCntPtr<vfs::FileSystem> FS)
     50   : FS(FS), FileSystemOpts(FSO),
     51     SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
     52   NumDirLookups = NumFileLookups = 0;
     53   NumDirCacheMisses = NumFileCacheMisses = 0;
     54 
     55   // If the caller doesn't provide a virtual file system, just grab the real
     56   // file system.
     57   if (!FS)
     58     this->FS = vfs::getRealFileSystem();
     59 }
     60 
     61 FileManager::~FileManager() = default;
     62 
     63 void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
     64                                bool AtBeginning) {
     65   assert(statCache && "No stat cache provided?");
     66   if (AtBeginning || !StatCache.get()) {
     67     statCache->setNextStatCache(std::move(StatCache));
     68     StatCache = std::move(statCache);
     69     return;
     70   }
     71 
     72   FileSystemStatCache *LastCache = StatCache.get();
     73   while (LastCache->getNextStatCache())
     74     LastCache = LastCache->getNextStatCache();
     75 
     76   LastCache->setNextStatCache(std::move(statCache));
     77 }
     78 
     79 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
     80   if (!statCache)
     81     return;
     82 
     83   if (StatCache.get() == statCache) {
     84     // This is the first stat cache.
     85     StatCache = StatCache->takeNextStatCache();
     86     return;
     87   }
     88 
     89   // Find the stat cache in the list.
     90   FileSystemStatCache *PrevCache = StatCache.get();
     91   while (PrevCache && PrevCache->getNextStatCache() != statCache)
     92     PrevCache = PrevCache->getNextStatCache();
     93 
     94   assert(PrevCache && "Stat cache not found for removal");
     95   PrevCache->setNextStatCache(statCache->takeNextStatCache());
     96 }
     97 
     98 void FileManager::clearStatCaches() {
     99   StatCache.reset();
    100 }
    101 
    102 /// \brief Retrieve the directory that the given file name resides in.
    103 /// Filename can point to either a real file or a virtual file.
    104 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
    105                                                   StringRef Filename,
    106                                                   bool CacheFailure) {
    107   if (Filename.empty())
    108     return nullptr;
    109 
    110   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
    111     return nullptr; // If Filename is a directory.
    112 
    113   StringRef DirName = llvm::sys::path::parent_path(Filename);
    114   // Use the current directory if file has no path component.
    115   if (DirName.empty())
    116     DirName = ".";
    117 
    118   return FileMgr.getDirectory(DirName, CacheFailure);
    119 }
    120 
    121 /// Add all ancestors of the given path (pointing to either a file or
    122 /// a directory) as virtual directories.
    123 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
    124   StringRef DirName = llvm::sys::path::parent_path(Path);
    125   if (DirName.empty())
    126     DirName = ".";
    127 
    128   auto &NamedDirEnt =
    129       *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
    130 
    131   // When caching a virtual directory, we always cache its ancestors
    132   // at the same time.  Therefore, if DirName is already in the cache,
    133   // we don't need to recurse as its ancestors must also already be in
    134   // the cache.
    135   if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR)
    136     return;
    137 
    138   // Add the virtual directory to the cache.
    139   auto UDE = llvm::make_unique<DirectoryEntry>();
    140   UDE->Name = NamedDirEnt.first().data();
    141   NamedDirEnt.second = UDE.get();
    142   VirtualDirectoryEntries.push_back(std::move(UDE));
    143 
    144   // Recursively add the other ancestors.
    145   addAncestorsAsVirtualDirs(DirName);
    146 }
    147 
    148 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
    149                                                 bool CacheFailure) {
    150   // stat doesn't like trailing separators except for root directory.
    151   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
    152   // (though it can strip '\\')
    153   if (DirName.size() > 1 &&
    154       DirName != llvm::sys::path::root_path(DirName) &&
    155       llvm::sys::path::is_separator(DirName.back()))
    156     DirName = DirName.substr(0, DirName.size()-1);
    157 #ifdef LLVM_ON_WIN32
    158   // Fixing a problem with "clang C:test.c" on Windows.
    159   // Stat("C:") does not recognize "C:" as a valid directory
    160   std::string DirNameStr;
    161   if (DirName.size() > 1 && DirName.back() == ':' &&
    162       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
    163     DirNameStr = DirName.str() + '.';
    164     DirName = DirNameStr;
    165   }
    166 #endif
    167 
    168   ++NumDirLookups;
    169   auto &NamedDirEnt =
    170       *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
    171 
    172   // See if there was already an entry in the map.  Note that the map
    173   // contains both virtual and real directories.
    174   if (NamedDirEnt.second)
    175     return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
    176                                                   : NamedDirEnt.second;
    177 
    178   ++NumDirCacheMisses;
    179 
    180   // By default, initialize it to invalid.
    181   NamedDirEnt.second = NON_EXISTENT_DIR;
    182 
    183   // Get the null-terminated directory name as stored as the key of the
    184   // SeenDirEntries map.
    185   const char *InterndDirName = NamedDirEnt.first().data();
    186 
    187   // Check to see if the directory exists.
    188   FileData Data;
    189   if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
    190     // There's no real directory at the given path.
    191     if (!CacheFailure)
    192       SeenDirEntries.erase(DirName);
    193     return nullptr;
    194   }
    195 
    196   // It exists.  See if we have already opened a directory with the
    197   // same inode (this occurs on Unix-like systems when one dir is
    198   // symlinked to another, for example) or the same path (on
    199   // Windows).
    200   DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
    201 
    202   NamedDirEnt.second = &UDE;
    203   if (!UDE.getName()) {
    204     // We don't have this directory yet, add it.  We use the string
    205     // key from the SeenDirEntries map as the string.
    206     UDE.Name  = InterndDirName;
    207   }
    208 
    209   return &UDE;
    210 }
    211 
    212 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
    213                                       bool CacheFailure) {
    214   ++NumFileLookups;
    215 
    216   // See if there is already an entry in the map.
    217   auto &NamedFileEnt =
    218       *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
    219 
    220   // See if there is already an entry in the map.
    221   if (NamedFileEnt.second)
    222     return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr
    223                                                     : NamedFileEnt.second;
    224 
    225   ++NumFileCacheMisses;
    226 
    227   // By default, initialize it to invalid.
    228   NamedFileEnt.second = NON_EXISTENT_FILE;
    229 
    230   // Get the null-terminated file name as stored as the key of the
    231   // SeenFileEntries map.
    232   const char *InterndFileName = NamedFileEnt.first().data();
    233 
    234   // Look up the directory for the file.  When looking up something like
    235   // sys/foo.h we'll discover all of the search directories that have a 'sys'
    236   // subdirectory.  This will let us avoid having to waste time on known-to-fail
    237   // searches when we go to find sys/bar.h, because all the search directories
    238   // without a 'sys' subdir will get a cached failure result.
    239   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
    240                                                        CacheFailure);
    241   if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
    242     if (!CacheFailure)
    243       SeenFileEntries.erase(Filename);
    244 
    245     return nullptr;
    246   }
    247 
    248   // FIXME: Use the directory info to prune this, before doing the stat syscall.
    249   // FIXME: This will reduce the # syscalls.
    250 
    251   // Nope, there isn't.  Check to see if the file exists.
    252   std::unique_ptr<vfs::File> F;
    253   FileData Data;
    254   if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
    255     // There's no real file at the given path.
    256     if (!CacheFailure)
    257       SeenFileEntries.erase(Filename);
    258 
    259     return nullptr;
    260   }
    261 
    262   assert((openFile || !F) && "undesired open file");
    263 
    264   // It exists.  See if we have already opened a file with the same inode.
    265   // This occurs when one dir is symlinked to another, for example.
    266   FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
    267 
    268   NamedFileEnt.second = &UFE;
    269 
    270   // If the name returned by getStatValue is different than Filename, re-intern
    271   // the name.
    272   if (Data.Name != Filename) {
    273     auto &NamedFileEnt =
    274         *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
    275     if (!NamedFileEnt.second)
    276       NamedFileEnt.second = &UFE;
    277     else
    278       assert(NamedFileEnt.second == &UFE &&
    279              "filename from getStatValue() refers to wrong file");
    280     InterndFileName = NamedFileEnt.first().data();
    281   }
    282 
    283   if (UFE.isValid()) { // Already have an entry with this inode, return it.
    284 
    285     // FIXME: this hack ensures that if we look up a file by a virtual path in
    286     // the VFS that the getDir() will have the virtual path, even if we found
    287     // the file by a 'real' path first. This is required in order to find a
    288     // module's structure when its headers/module map are mapped in the VFS.
    289     // We should remove this as soon as we can properly support a file having
    290     // multiple names.
    291     if (DirInfo != UFE.Dir && Data.IsVFSMapped)
    292       UFE.Dir = DirInfo;
    293 
    294     // Always update the name to use the last name by which a file was accessed.
    295     // FIXME: Neither this nor always using the first name is correct; we want
    296     // to switch towards a design where we return a FileName object that
    297     // encapsulates both the name by which the file was accessed and the
    298     // corresponding FileEntry.
    299     UFE.Name = InterndFileName;
    300 
    301     return &UFE;
    302   }
    303 
    304   // Otherwise, we don't have this file yet, add it.
    305   UFE.Name    = InterndFileName;
    306   UFE.Size = Data.Size;
    307   UFE.ModTime = Data.ModTime;
    308   UFE.Dir     = DirInfo;
    309   UFE.UID     = NextFileUID++;
    310   UFE.UniqueID = Data.UniqueID;
    311   UFE.IsNamedPipe = Data.IsNamedPipe;
    312   UFE.InPCH = Data.InPCH;
    313   UFE.File = std::move(F);
    314   UFE.IsValid = true;
    315   if (UFE.File)
    316     if (auto RealPathName = UFE.File->getName())
    317       UFE.RealPathName = *RealPathName;
    318   return &UFE;
    319 }
    320 
    321 const FileEntry *
    322 FileManager::getVirtualFile(StringRef Filename, off_t Size,
    323                             time_t ModificationTime) {
    324   ++NumFileLookups;
    325 
    326   // See if there is already an entry in the map.
    327   auto &NamedFileEnt =
    328       *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
    329 
    330   // See if there is already an entry in the map.
    331   if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
    332     return NamedFileEnt.second;
    333 
    334   ++NumFileCacheMisses;
    335 
    336   // By default, initialize it to invalid.
    337   NamedFileEnt.second = NON_EXISTENT_FILE;
    338 
    339   addAncestorsAsVirtualDirs(Filename);
    340   FileEntry *UFE = nullptr;
    341 
    342   // Now that all ancestors of Filename are in the cache, the
    343   // following call is guaranteed to find the DirectoryEntry from the
    344   // cache.
    345   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
    346                                                        /*CacheFailure=*/true);
    347   assert(DirInfo &&
    348          "The directory of a virtual file should already be in the cache.");
    349 
    350   // Check to see if the file exists. If so, drop the virtual file
    351   FileData Data;
    352   const char *InterndFileName = NamedFileEnt.first().data();
    353   if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
    354     Data.Size = Size;
    355     Data.ModTime = ModificationTime;
    356     UFE = &UniqueRealFiles[Data.UniqueID];
    357 
    358     NamedFileEnt.second = UFE;
    359 
    360     // If we had already opened this file, close it now so we don't
    361     // leak the descriptor. We're not going to use the file
    362     // descriptor anyway, since this is a virtual file.
    363     if (UFE->File)
    364       UFE->closeFile();
    365 
    366     // If we already have an entry with this inode, return it.
    367     if (UFE->isValid())
    368       return UFE;
    369 
    370     UFE->UniqueID = Data.UniqueID;
    371     UFE->IsNamedPipe = Data.IsNamedPipe;
    372     UFE->InPCH = Data.InPCH;
    373   }
    374 
    375   if (!UFE) {
    376     VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
    377     UFE = VirtualFileEntries.back().get();
    378     NamedFileEnt.second = UFE;
    379   }
    380 
    381   UFE->Name    = InterndFileName;
    382   UFE->Size    = Size;
    383   UFE->ModTime = ModificationTime;
    384   UFE->Dir     = DirInfo;
    385   UFE->UID     = NextFileUID++;
    386   UFE->File.reset();
    387   return UFE;
    388 }
    389 
    390 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
    391   StringRef pathRef(path.data(), path.size());
    392 
    393   if (FileSystemOpts.WorkingDir.empty()
    394       || llvm::sys::path::is_absolute(pathRef))
    395     return false;
    396 
    397   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
    398   llvm::sys::path::append(NewPath, pathRef);
    399   path = NewPath;
    400   return true;
    401 }
    402 
    403 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
    404   bool Changed = FixupRelativePath(Path);
    405 
    406   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
    407     llvm::sys::fs::make_absolute(Path);
    408     Changed = true;
    409   }
    410 
    411   return Changed;
    412 }
    413 
    414 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
    415 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
    416                               bool ShouldCloseOpenFile) {
    417   uint64_t FileSize = Entry->getSize();
    418   // If there's a high enough chance that the file have changed since we
    419   // got its size, force a stat before opening it.
    420   if (isVolatile)
    421     FileSize = -1;
    422 
    423   const char *Filename = Entry->getName();
    424   // If the file is already open, use the open file descriptor.
    425   if (Entry->File) {
    426     auto Result =
    427         Entry->File->getBuffer(Filename, FileSize,
    428                                /*RequiresNullTerminator=*/true, isVolatile);
    429     // FIXME: we need a set of APIs that can make guarantees about whether a
    430     // FileEntry is open or not.
    431     if (ShouldCloseOpenFile)
    432       Entry->closeFile();
    433     return Result;
    434   }
    435 
    436   // Otherwise, open the file.
    437 
    438   if (FileSystemOpts.WorkingDir.empty())
    439     return FS->getBufferForFile(Filename, FileSize,
    440                                 /*RequiresNullTerminator=*/true, isVolatile);
    441 
    442   SmallString<128> FilePath(Entry->getName());
    443   FixupRelativePath(FilePath);
    444   return FS->getBufferForFile(FilePath, FileSize,
    445                               /*RequiresNullTerminator=*/true, isVolatile);
    446 }
    447 
    448 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
    449 FileManager::getBufferForFile(StringRef Filename) {
    450   if (FileSystemOpts.WorkingDir.empty())
    451     return FS->getBufferForFile(Filename);
    452 
    453   SmallString<128> FilePath(Filename);
    454   FixupRelativePath(FilePath);
    455   return FS->getBufferForFile(FilePath.c_str());
    456 }
    457 
    458 /// getStatValue - Get the 'stat' information for the specified path,
    459 /// using the cache to accelerate it if possible.  This returns true
    460 /// if the path points to a virtual file or does not exist, or returns
    461 /// false if it's an existent real file.  If FileDescriptor is NULL,
    462 /// do directory look-up instead of file look-up.
    463 bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
    464                                std::unique_ptr<vfs::File> *F) {
    465   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
    466   // absolute!
    467   if (FileSystemOpts.WorkingDir.empty())
    468     return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
    469 
    470   SmallString<128> FilePath(Path);
    471   FixupRelativePath(FilePath);
    472 
    473   return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
    474                                   StatCache.get(), *FS);
    475 }
    476 
    477 bool FileManager::getNoncachedStatValue(StringRef Path,
    478                                         vfs::Status &Result) {
    479   SmallString<128> FilePath(Path);
    480   FixupRelativePath(FilePath);
    481 
    482   llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
    483   if (!S)
    484     return true;
    485   Result = *S;
    486   return false;
    487 }
    488 
    489 void FileManager::invalidateCache(const FileEntry *Entry) {
    490   assert(Entry && "Cannot invalidate a NULL FileEntry");
    491 
    492   SeenFileEntries.erase(Entry->getName());
    493 
    494   // FileEntry invalidation should not block future optimizations in the file
    495   // caches. Possible alternatives are cache truncation (invalidate last N) or
    496   // invalidation of the whole cache.
    497   UniqueRealFiles.erase(Entry->getUniqueID());
    498 }
    499 
    500 
    501 void FileManager::GetUniqueIDMapping(
    502                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
    503   UIDToFiles.clear();
    504   UIDToFiles.resize(NextFileUID);
    505 
    506   // Map file entries
    507   for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
    508          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
    509        FE != FEEnd; ++FE)
    510     if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
    511       UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
    512 
    513   // Map virtual file entries
    514   for (const auto &VFE : VirtualFileEntries)
    515     if (VFE && VFE.get() != NON_EXISTENT_FILE)
    516       UIDToFiles[VFE->getUID()] = VFE.get();
    517 }
    518 
    519 void FileManager::modifyFileEntry(FileEntry *File,
    520                                   off_t Size, time_t ModificationTime) {
    521   File->Size = Size;
    522   File->ModTime = ModificationTime;
    523 }
    524 
    525 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
    526   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
    527   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
    528     = CanonicalDirNames.find(Dir);
    529   if (Known != CanonicalDirNames.end())
    530     return Known->second;
    531 
    532   StringRef CanonicalName(Dir->getName());
    533 
    534 #ifdef LLVM_ON_UNIX
    535   char CanonicalNameBuf[PATH_MAX];
    536   if (realpath(Dir->getName(), CanonicalNameBuf))
    537     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
    538 #else
    539   SmallString<256> CanonicalNameBuf(CanonicalName);
    540   llvm::sys::fs::make_absolute(CanonicalNameBuf);
    541   llvm::sys::path::native(CanonicalNameBuf);
    542   // We've run into needing to remove '..' here in the wild though, so
    543   // remove it.
    544   // On Windows, symlinks are significantly less prevalent, so removing
    545   // '..' is pretty safe.
    546   // Ideally we'd have an equivalent of `realpath` and could implement
    547   // sys::fs::canonical across all the platforms.
    548   llvm::sys::path::remove_dots(CanonicalNameBuf, /* remove_dot_dot */ true);
    549   CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
    550 #endif
    551 
    552   CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
    553   return CanonicalName;
    554 }
    555 
    556 void FileManager::PrintStats() const {
    557   llvm::errs() << "\n*** File Manager Stats:\n";
    558   llvm::errs() << UniqueRealFiles.size() << " real files found, "
    559                << UniqueRealDirs.size() << " real dirs found.\n";
    560   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
    561                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
    562   llvm::errs() << NumDirLookups << " dir lookups, "
    563                << NumDirCacheMisses << " dir cache misses.\n";
    564   llvm::errs() << NumFileLookups << " file lookups, "
    565                << NumFileCacheMisses << " file cache misses.\n";
    566 
    567   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
    568 }
    569