1226efd35SChris Lattner //===--- FileManager.cpp - File System Probing and Caching ----------------===// 27a51313dSChris Lattner // 37a51313dSChris Lattner // The LLVM Compiler Infrastructure 47a51313dSChris Lattner // 57a51313dSChris Lattner // This file is distributed under the University of Illinois Open Source 67a51313dSChris Lattner // License. See LICENSE.TXT for details. 77a51313dSChris Lattner // 87a51313dSChris Lattner //===----------------------------------------------------------------------===// 97a51313dSChris Lattner // 107a51313dSChris Lattner // This file implements the FileManager interface. 117a51313dSChris Lattner // 127a51313dSChris Lattner //===----------------------------------------------------------------------===// 137a51313dSChris Lattner // 147a51313dSChris Lattner // TODO: This should index all interesting directories with dirent calls. 157a51313dSChris Lattner // getdirentries ? 167a51313dSChris Lattner // opendir/readdir_r/closedir ? 177a51313dSChris Lattner // 187a51313dSChris Lattner //===----------------------------------------------------------------------===// 197a51313dSChris Lattner 207a51313dSChris Lattner #include "clang/Basic/FileManager.h" 21226efd35SChris Lattner #include "clang/Basic/FileSystemStatCache.h" 227a51313dSChris Lattner #include "llvm/ADT/SmallString.h" 233a02247dSChandler Carruth #include "llvm/Config/llvm-config.h" 24d2725a31SDavid Blaikie #include "llvm/ADT/STLExtras.h" 25740857faSMichael J. Spencer #include "llvm/Support/FileSystem.h" 2671731d6bSArgyrios Kyrtzidis #include "llvm/Support/MemoryBuffer.h" 278aaf4995SMichael J. Spencer #include "llvm/Support/Path.h" 283a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h" 2935b79c24SEugene Zelenko #include <algorithm> 3035b79c24SEugene Zelenko #include <cassert> 3135b79c24SEugene Zelenko #include <climits> 3235b79c24SEugene Zelenko #include <cstdint> 3335b79c24SEugene Zelenko #include <cstdlib> 3426db6481SBenjamin Kramer #include <string> 3535b79c24SEugene Zelenko #include <utility> 36278038b4SChris Lattner 377a51313dSChris Lattner using namespace clang; 387a51313dSChris Lattner 397a51313dSChris Lattner /// NON_EXISTENT_DIR - A special value distinct from null that is used to 407a51313dSChris Lattner /// represent a dir name that doesn't exist on the disk. 417a51313dSChris Lattner #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) 427a51313dSChris Lattner 439624b695SChris Lattner /// NON_EXISTENT_FILE - A special value distinct from null that is used to 449624b695SChris Lattner /// represent a filename that doesn't exist on the disk. 459624b695SChris Lattner #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) 469624b695SChris Lattner 475c04bd81STed Kremenek //===----------------------------------------------------------------------===// 485c04bd81STed Kremenek // Common logic. 495c04bd81STed Kremenek //===----------------------------------------------------------------------===// 507a51313dSChris Lattner 51c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO, 52*fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) 53f6021ecdSBenjamin Kramer : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64), 54f6021ecdSBenjamin Kramer SeenFileEntries(64), NextFileUID(0) { 557a51313dSChris Lattner NumDirLookups = NumFileLookups = 0; 567a51313dSChris Lattner NumDirCacheMisses = NumFileCacheMisses = 0; 57c8130a74SBen Langmuir 58c8130a74SBen Langmuir // If the caller doesn't provide a virtual file system, just grab the real 59c8130a74SBen Langmuir // file system. 60f6021ecdSBenjamin Kramer if (!this->FS) 61*fc51490bSJonas Devlieghere this->FS = llvm::vfs::getRealFileSystem(); 627a51313dSChris Lattner } 637a51313dSChris Lattner 64d2725a31SDavid Blaikie FileManager::~FileManager() = default; 657a51313dSChris Lattner 6623430ccbSDavid Blaikie void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, 67226efd35SChris Lattner bool AtBeginning) { 68d2eb58abSDouglas Gregor assert(statCache && "No stat cache provided?"); 69f1186c5aSCraig Topper if (AtBeginning || !StatCache.get()) { 7023430ccbSDavid Blaikie statCache->setNextStatCache(std::move(StatCache)); 7123430ccbSDavid Blaikie StatCache = std::move(statCache); 72d2eb58abSDouglas Gregor return; 73d2eb58abSDouglas Gregor } 74d2eb58abSDouglas Gregor 75226efd35SChris Lattner FileSystemStatCache *LastCache = StatCache.get(); 76d2eb58abSDouglas Gregor while (LastCache->getNextStatCache()) 77d2eb58abSDouglas Gregor LastCache = LastCache->getNextStatCache(); 78d2eb58abSDouglas Gregor 7923430ccbSDavid Blaikie LastCache->setNextStatCache(std::move(statCache)); 80d2eb58abSDouglas Gregor } 81d2eb58abSDouglas Gregor 82226efd35SChris Lattner void FileManager::removeStatCache(FileSystemStatCache *statCache) { 83d2eb58abSDouglas Gregor if (!statCache) 84d2eb58abSDouglas Gregor return; 85d2eb58abSDouglas Gregor 86d2eb58abSDouglas Gregor if (StatCache.get() == statCache) { 87d2eb58abSDouglas Gregor // This is the first stat cache. 88dd0e1e8dSDavid Blaikie StatCache = StatCache->takeNextStatCache(); 89d2eb58abSDouglas Gregor return; 90d2eb58abSDouglas Gregor } 91d2eb58abSDouglas Gregor 92d2eb58abSDouglas Gregor // Find the stat cache in the list. 93226efd35SChris Lattner FileSystemStatCache *PrevCache = StatCache.get(); 94d2eb58abSDouglas Gregor while (PrevCache && PrevCache->getNextStatCache() != statCache) 95d2eb58abSDouglas Gregor PrevCache = PrevCache->getNextStatCache(); 969624b695SChris Lattner 979624b695SChris Lattner assert(PrevCache && "Stat cache not found for removal"); 9823430ccbSDavid Blaikie PrevCache->setNextStatCache(statCache->takeNextStatCache()); 99d2eb58abSDouglas Gregor } 100d2eb58abSDouglas Gregor 1013aad855aSManuel Klimek void FileManager::clearStatCaches() { 1023875a82dSDavid Blaikie StatCache.reset(); 1033aad855aSManuel Klimek } 1043aad855aSManuel Klimek 1059fc8faf9SAdrian Prantl /// Retrieve the directory that the given file name resides in. 106e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file. 107407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, 1081735f4e7SDouglas Gregor StringRef Filename, 1091735f4e7SDouglas Gregor bool CacheFailure) { 110f3c0ff73SZhanyong Wan if (Filename.empty()) 111f1186c5aSCraig Topper return nullptr; 112e1dd3e2cSZhanyong Wan 113f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 114f1186c5aSCraig Topper return nullptr; // If Filename is a directory. 1150c0e8040SChris Lattner 1160e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename); 1170c0e8040SChris Lattner // Use the current directory if file has no path component. 118f3c0ff73SZhanyong Wan if (DirName.empty()) 119f3c0ff73SZhanyong Wan DirName = "."; 1200c0e8040SChris Lattner 1211735f4e7SDouglas Gregor return FileMgr.getDirectory(DirName, CacheFailure); 122407e2124SDouglas Gregor } 123407e2124SDouglas Gregor 124e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or 125e1dd3e2cSZhanyong Wan /// a directory) as virtual directories. 1260e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 1270e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path); 128f3c0ff73SZhanyong Wan if (DirName.empty()) 1291834dc75SDavid Majnemer DirName = "."; 130e1dd3e2cSZhanyong Wan 13113156b68SDavid Blaikie auto &NamedDirEnt = 13213156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 133e1dd3e2cSZhanyong Wan 134e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors 135e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache, 136e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in 137e1dd3e2cSZhanyong Wan // the cache. 138a8cfffa3SRichard Smith if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR) 139e1dd3e2cSZhanyong Wan return; 140e1dd3e2cSZhanyong Wan 141e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache. 142d2725a31SDavid Blaikie auto UDE = llvm::make_unique<DirectoryEntry>(); 1430df59d8cSMehdi Amini UDE->Name = NamedDirEnt.first(); 144d2725a31SDavid Blaikie NamedDirEnt.second = UDE.get(); 145d2725a31SDavid Blaikie VirtualDirectoryEntries.push_back(std::move(UDE)); 146e1dd3e2cSZhanyong Wan 147e1dd3e2cSZhanyong Wan // Recursively add the other ancestors. 148e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName); 149e1dd3e2cSZhanyong Wan } 150e1dd3e2cSZhanyong Wan 1511735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName, 1521735f4e7SDouglas Gregor bool CacheFailure) { 1538bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 15432f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 15532f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1568bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1578bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1588bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 15932f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 1601865df49SNico Weber #ifdef _WIN32 161ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 162ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 163ee30546cSRafael Espindola std::string DirNameStr; 164ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 165ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 166ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 167ee30546cSRafael Espindola DirName = DirNameStr; 168ee30546cSRafael Espindola } 169ee30546cSRafael Espindola #endif 17032f1acf1SNAKAMURA Takumi 1717a51313dSChris Lattner ++NumDirLookups; 17213156b68SDavid Blaikie auto &NamedDirEnt = 17313156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 1747a51313dSChris Lattner 175e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 176e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 17713156b68SDavid Blaikie if (NamedDirEnt.second) 17813156b68SDavid Blaikie return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr 17913156b68SDavid Blaikie : NamedDirEnt.second; 1807a51313dSChris Lattner 1817a51313dSChris Lattner ++NumDirCacheMisses; 1827a51313dSChris Lattner 1837a51313dSChris Lattner // By default, initialize it to invalid. 18413156b68SDavid Blaikie NamedDirEnt.second = NON_EXISTENT_DIR; 1857a51313dSChris Lattner 1867a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 187e1dd3e2cSZhanyong Wan // SeenDirEntries map. 1880df59d8cSMehdi Amini StringRef InterndDirName = NamedDirEnt.first(); 1897a51313dSChris Lattner 1907a51313dSChris Lattner // Check to see if the directory exists. 191f8f91b89SRafael Espindola FileData Data; 192f1186c5aSCraig Topper if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) { 193e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 1941735f4e7SDouglas Gregor if (!CacheFailure) 1951735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 196f1186c5aSCraig Topper return nullptr; 197e1dd3e2cSZhanyong Wan } 1987a51313dSChris Lattner 199e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 200e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 201e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 202e1dd3e2cSZhanyong Wan // Windows). 203c9b7234eSBen Langmuir DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID]; 2047a51313dSChris Lattner 20513156b68SDavid Blaikie NamedDirEnt.second = &UDE; 2060df59d8cSMehdi Amini if (UDE.getName().empty()) { 207e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 208e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 2097a51313dSChris Lattner UDE.Name = InterndDirName; 210e1dd3e2cSZhanyong Wan } 211e1dd3e2cSZhanyong Wan 2127a51313dSChris Lattner return &UDE; 2137a51313dSChris Lattner } 2147a51313dSChris Lattner 2151735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, 2161735f4e7SDouglas Gregor bool CacheFailure) { 2177a51313dSChris Lattner ++NumFileLookups; 2187a51313dSChris Lattner 2197a51313dSChris Lattner // See if there is already an entry in the map. 22013156b68SDavid Blaikie auto &NamedFileEnt = 22113156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 2227a51313dSChris Lattner 2237a51313dSChris Lattner // See if there is already an entry in the map. 22413156b68SDavid Blaikie if (NamedFileEnt.second) 22513156b68SDavid Blaikie return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr 22613156b68SDavid Blaikie : NamedFileEnt.second; 2277a51313dSChris Lattner 2287a51313dSChris Lattner ++NumFileCacheMisses; 2297a51313dSChris Lattner 2307a51313dSChris Lattner // By default, initialize it to invalid. 23113156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 2327a51313dSChris Lattner 2337a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 234e1dd3e2cSZhanyong Wan // SeenFileEntries map. 2350df59d8cSMehdi Amini StringRef InterndFileName = NamedFileEnt.first(); 2367a51313dSChris Lattner 237966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 238966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 239966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 240966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 241966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 2421735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 2431735f4e7SDouglas Gregor CacheFailure); 244f1186c5aSCraig Topper if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. 2451735f4e7SDouglas Gregor if (!CacheFailure) 2461735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2471735f4e7SDouglas Gregor 248f1186c5aSCraig Topper return nullptr; 2491735f4e7SDouglas Gregor } 250407e2124SDouglas Gregor 2517a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2527a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2537a51313dSChris Lattner 2547a51313dSChris Lattner // Nope, there isn't. Check to see if the file exists. 255*fc51490bSJonas Devlieghere std::unique_ptr<llvm::vfs::File> F; 256f8f91b89SRafael Espindola FileData Data; 257f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { 258e1dd3e2cSZhanyong Wan // There's no real file at the given path. 2591735f4e7SDouglas Gregor if (!CacheFailure) 2601735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2611735f4e7SDouglas Gregor 262f1186c5aSCraig Topper return nullptr; 263e1dd3e2cSZhanyong Wan } 2647a51313dSChris Lattner 265ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 266d6278e32SArgyrios Kyrtzidis 2677a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2687a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 269c9b7234eSBen Langmuir FileEntry &UFE = UniqueRealFiles[Data.UniqueID]; 2707a51313dSChris Lattner 27113156b68SDavid Blaikie NamedFileEnt.second = &UFE; 272ab86fbe4SBen Langmuir 273ab86fbe4SBen Langmuir // If the name returned by getStatValue is different than Filename, re-intern 274ab86fbe4SBen Langmuir // the name. 275ab86fbe4SBen Langmuir if (Data.Name != Filename) { 27613156b68SDavid Blaikie auto &NamedFileEnt = 27713156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first; 27813156b68SDavid Blaikie if (!NamedFileEnt.second) 27913156b68SDavid Blaikie NamedFileEnt.second = &UFE; 280ab86fbe4SBen Langmuir else 28113156b68SDavid Blaikie assert(NamedFileEnt.second == &UFE && 282ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file"); 28313156b68SDavid Blaikie InterndFileName = NamedFileEnt.first().data(); 284ab86fbe4SBen Langmuir } 285ab86fbe4SBen Langmuir 286c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2875de00f3bSBen Langmuir 2885de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 2895de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 2905de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 2915de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 2925de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 2935de00f3bSBen Langmuir // multiple names. 2945de00f3bSBen Langmuir if (DirInfo != UFE.Dir && Data.IsVFSMapped) 2955de00f3bSBen Langmuir UFE.Dir = DirInfo; 2965de00f3bSBen Langmuir 297c0ff9908SManuel Klimek // Always update the name to use the last name by which a file was accessed. 298c0ff9908SManuel Klimek // FIXME: Neither this nor always using the first name is correct; we want 299c0ff9908SManuel Klimek // to switch towards a design where we return a FileName object that 300c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the 301c0ff9908SManuel Klimek // corresponding FileEntry. 302ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 303c0ff9908SManuel Klimek 3047a51313dSChris Lattner return &UFE; 305dd278430SChris Lattner } 3067a51313dSChris Lattner 307c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 308ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 309f8f91b89SRafael Espindola UFE.Size = Data.Size; 310f8f91b89SRafael Espindola UFE.ModTime = Data.ModTime; 3117a51313dSChris Lattner UFE.Dir = DirInfo; 3127a51313dSChris Lattner UFE.UID = NextFileUID++; 313c9b7234eSBen Langmuir UFE.UniqueID = Data.UniqueID; 314c9b7234eSBen Langmuir UFE.IsNamedPipe = Data.IsNamedPipe; 315c9b7234eSBen Langmuir UFE.InPCH = Data.InPCH; 316326ffb36SDavid Blaikie UFE.File = std::move(F); 317c8a71468SBen Langmuir UFE.IsValid = true; 318ddbabc6bSSimon Marchi 3198e44a8e7SEric Liu if (UFE.File) { 3208e44a8e7SEric Liu if (auto PathName = UFE.File->getName()) { 3218e44a8e7SEric Liu llvm::SmallString<128> AbsPath(*PathName); 3228e44a8e7SEric Liu // This is not the same as `VFS::getRealPath()`, which resolves symlinks 3238e44a8e7SEric Liu // but can be very expensive on real file systems. 324411e7100SEric Liu // FIXME: the semantic of RealPathName is unclear, and the name might be 325411e7100SEric Liu // misleading. We need to clean up the interface here. 326411e7100SEric Liu makeAbsolutePath(AbsPath); 327411e7100SEric Liu llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true); 328411e7100SEric Liu UFE.RealPathName = AbsPath.str(); 3298e44a8e7SEric Liu } 3308e44a8e7SEric Liu } 3317a51313dSChris Lattner return &UFE; 3327a51313dSChris Lattner } 3337a51313dSChris Lattner 334407e2124SDouglas Gregor const FileEntry * 3350e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3365159f616SChris Lattner time_t ModificationTime) { 337407e2124SDouglas Gregor ++NumFileLookups; 338407e2124SDouglas Gregor 339407e2124SDouglas Gregor // See if there is already an entry in the map. 34013156b68SDavid Blaikie auto &NamedFileEnt = 34113156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 342407e2124SDouglas Gregor 343407e2124SDouglas Gregor // See if there is already an entry in the map. 34413156b68SDavid Blaikie if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE) 34513156b68SDavid Blaikie return NamedFileEnt.second; 346407e2124SDouglas Gregor 347407e2124SDouglas Gregor ++NumFileCacheMisses; 348407e2124SDouglas Gregor 349407e2124SDouglas Gregor // By default, initialize it to invalid. 35013156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 351407e2124SDouglas Gregor 352e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 353f1186c5aSCraig Topper FileEntry *UFE = nullptr; 354e1dd3e2cSZhanyong Wan 355e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 356e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 357e1dd3e2cSZhanyong Wan // cache. 3581735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 3591735f4e7SDouglas Gregor /*CacheFailure=*/true); 360e1dd3e2cSZhanyong Wan assert(DirInfo && 361e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 362e1dd3e2cSZhanyong Wan 363606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 364f8f91b89SRafael Espindola FileData Data; 36513156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 366f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { 367f8f91b89SRafael Espindola Data.Size = Size; 368f8f91b89SRafael Espindola Data.ModTime = ModificationTime; 369c9b7234eSBen Langmuir UFE = &UniqueRealFiles[Data.UniqueID]; 370606c4ac3SDouglas Gregor 37113156b68SDavid Blaikie NamedFileEnt.second = UFE; 372606c4ac3SDouglas Gregor 373606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 374606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 375606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 376c8130a74SBen Langmuir if (UFE->File) 377c8130a74SBen Langmuir UFE->closeFile(); 378606c4ac3SDouglas Gregor 379606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 380c8a71468SBen Langmuir if (UFE->isValid()) 381606c4ac3SDouglas Gregor return UFE; 382c9b7234eSBen Langmuir 383c9b7234eSBen Langmuir UFE->UniqueID = Data.UniqueID; 384c9b7234eSBen Langmuir UFE->IsNamedPipe = Data.IsNamedPipe; 385c9b7234eSBen Langmuir UFE->InPCH = Data.InPCH; 386606c4ac3SDouglas Gregor } 387606c4ac3SDouglas Gregor 388606c4ac3SDouglas Gregor if (!UFE) { 389d2725a31SDavid Blaikie VirtualFileEntries.push_back(llvm::make_unique<FileEntry>()); 390d2725a31SDavid Blaikie UFE = VirtualFileEntries.back().get(); 39113156b68SDavid Blaikie NamedFileEnt.second = UFE; 392606c4ac3SDouglas Gregor } 393407e2124SDouglas Gregor 3949624b695SChris Lattner UFE->Name = InterndFileName; 395407e2124SDouglas Gregor UFE->Size = Size; 396407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 397407e2124SDouglas Gregor UFE->Dir = DirInfo; 398407e2124SDouglas Gregor UFE->UID = NextFileUID++; 399dfffaf57SErik Verbruggen UFE->IsValid = true; 400c8130a74SBen Langmuir UFE->File.reset(); 401407e2124SDouglas Gregor return UFE; 402407e2124SDouglas Gregor } 403407e2124SDouglas Gregor 404c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 4050e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 406b5c356a4SAnders Carlsson 4079ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 4089ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 409c56419edSArgyrios Kyrtzidis return false; 41071731d6bSArgyrios Kyrtzidis 4112c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 412b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 4136e640998SChris Lattner path = NewPath; 414c56419edSArgyrios Kyrtzidis return true; 415c56419edSArgyrios Kyrtzidis } 416c56419edSArgyrios Kyrtzidis 417c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 418c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path); 419c56419edSArgyrios Kyrtzidis 420c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 42147035c02SIlya Biryukov FS->makeAbsolute(Path); 422c56419edSArgyrios Kyrtzidis Changed = true; 423c56419edSArgyrios Kyrtzidis } 424c56419edSArgyrios Kyrtzidis 425c56419edSArgyrios Kyrtzidis return Changed; 4266e640998SChris Lattner } 4276e640998SChris Lattner 428a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 429a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 430a885796dSBenjamin Kramer bool ShouldCloseOpenFile) { 4316d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4326d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4336d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 4346d7833f1SArgyrios Kyrtzidis if (isVolatile) 4356d7833f1SArgyrios Kyrtzidis FileSize = -1; 4366d7833f1SArgyrios Kyrtzidis 437004b9c7aSMehdi Amini StringRef Filename = Entry->getName(); 4385ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 439c8130a74SBen Langmuir if (Entry->File) { 440a885796dSBenjamin Kramer auto Result = 441a885796dSBenjamin Kramer Entry->File->getBuffer(Filename, FileSize, 44226d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4439801b253SBen Langmuir // FIXME: we need a set of APIs that can make guarantees about whether a 4449801b253SBen Langmuir // FileEntry is open or not. 4459801b253SBen Langmuir if (ShouldCloseOpenFile) 446c8130a74SBen Langmuir Entry->closeFile(); 4476406f7b8SRafael Espindola return Result; 4485ea7d07dSChris Lattner } 4496e640998SChris Lattner 4505ea7d07dSChris Lattner // Otherwise, open the file. 451669b0b15SArgyrios Kyrtzidis 452a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 453a885796dSBenjamin Kramer return FS->getBufferForFile(Filename, FileSize, 45426d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4555ea7d07dSChris Lattner 4562c1dd271SDylan Noblesmith SmallString<128> FilePath(Entry->getName()); 457878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 45892e1b62dSYaron Keren return FS->getBufferForFile(FilePath, FileSize, 45926d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 46026b5c190SChris Lattner } 46126b5c190SChris Lattner 462a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 4632ebe3a02SIvan Donchevskii FileManager::getBufferForFile(StringRef Filename, bool isVolatile) { 464a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 4652ebe3a02SIvan Donchevskii return FS->getBufferForFile(Filename, -1, true, isVolatile); 46626b5c190SChris Lattner 4672c1dd271SDylan Noblesmith SmallString<128> FilePath(Filename); 468878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 4692ebe3a02SIvan Donchevskii return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile); 47071731d6bSArgyrios Kyrtzidis } 47171731d6bSArgyrios Kyrtzidis 472e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 473e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 474e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 475e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 476e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 4770df59d8cSMehdi Amini bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile, 478*fc51490bSJonas Devlieghere std::unique_ptr<llvm::vfs::File> *F) { 479226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 480226efd35SChris Lattner // absolute! 4815769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 482c8130a74SBen Langmuir return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); 483226efd35SChris Lattner 4842c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 485878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 48671731d6bSArgyrios Kyrtzidis 487c8130a74SBen Langmuir return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, 488c8130a74SBen Langmuir StatCache.get(), *FS); 48971731d6bSArgyrios Kyrtzidis } 49071731d6bSArgyrios Kyrtzidis 4910e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path, 492*fc51490bSJonas Devlieghere llvm::vfs::Status &Result) { 4932c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 4945e368405SAnders Carlsson FixupRelativePath(FilePath); 4955e368405SAnders Carlsson 496*fc51490bSJonas Devlieghere llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str()); 497c8130a74SBen Langmuir if (!S) 498c8130a74SBen Langmuir return true; 499c8130a74SBen Langmuir Result = *S; 500c8130a74SBen Langmuir return false; 5015e368405SAnders Carlsson } 5025e368405SAnders Carlsson 503b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) { 504b3074003SAxel Naumann assert(Entry && "Cannot invalidate a NULL FileEntry"); 50538179d96SAxel Naumann 50638179d96SAxel Naumann SeenFileEntries.erase(Entry->getName()); 507b3074003SAxel Naumann 508b3074003SAxel Naumann // FileEntry invalidation should not block future optimizations in the file 509b3074003SAxel Naumann // caches. Possible alternatives are cache truncation (invalidate last N) or 510b3074003SAxel Naumann // invalidation of the whole cache. 511c9b7234eSBen Langmuir UniqueRealFiles.erase(Entry->getUniqueID()); 51238179d96SAxel Naumann } 51338179d96SAxel Naumann 51409b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 5150e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 51609b6989eSDouglas Gregor UIDToFiles.clear(); 51709b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 51809b6989eSDouglas Gregor 51909b6989eSDouglas Gregor // Map file entries 52009b6989eSDouglas Gregor for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator 521e1dd3e2cSZhanyong Wan FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); 52209b6989eSDouglas Gregor FE != FEEnd; ++FE) 52309b6989eSDouglas Gregor if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) 52409b6989eSDouglas Gregor UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); 52509b6989eSDouglas Gregor 52609b6989eSDouglas Gregor // Map virtual file entries 527d2725a31SDavid Blaikie for (const auto &VFE : VirtualFileEntries) 528d2725a31SDavid Blaikie if (VFE && VFE.get() != NON_EXISTENT_FILE) 529d2725a31SDavid Blaikie UIDToFiles[VFE->getUID()] = VFE.get(); 53009b6989eSDouglas Gregor } 531226efd35SChris Lattner 5326eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File, 5336eec06d0SArgyrios Kyrtzidis off_t Size, time_t ModificationTime) { 5346eec06d0SArgyrios Kyrtzidis File->Size = Size; 5356eec06d0SArgyrios Kyrtzidis File->ModTime = ModificationTime; 5366eec06d0SArgyrios Kyrtzidis } 5376eec06d0SArgyrios Kyrtzidis 538e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 539e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 540e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 541e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 542e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 543e00c8b20SDouglas Gregor return Known->second; 544e00c8b20SDouglas Gregor 545e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 54654cc3c2fSRichard Smith 5475fb18fecSEric Liu SmallString<4096> CanonicalNameBuf; 5485fb18fecSEric Liu if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf)) 549da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 550e00c8b20SDouglas Gregor 551e00c8b20SDouglas Gregor CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); 552e00c8b20SDouglas Gregor return CanonicalName; 553e00c8b20SDouglas Gregor } 554226efd35SChris Lattner 5557a51313dSChris Lattner void FileManager::PrintStats() const { 55689b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 557e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 558e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 559e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 560e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 56189b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 5627a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 56389b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 5647a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 5657a51313dSChris Lattner 56689b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 5677a51313dSChris Lattner } 568