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, 52c8130a74SBen Langmuir IntrusiveRefCntPtr<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) 61c8130a74SBen Langmuir this->FS = 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 105407e2124SDouglas Gregor /// \brief 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); 160ee30546cSRafael Espindola #ifdef LLVM_ON_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. 255326ffb36SDavid Blaikie std::unique_ptr<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; 318f42103ceSTaewook Oh if (UFE.File) 319f42103ceSTaewook Oh if (auto RealPathName = UFE.File->getName()) 320f42103ceSTaewook Oh UFE.RealPathName = *RealPathName; 3217a51313dSChris Lattner return &UFE; 3227a51313dSChris Lattner } 3237a51313dSChris Lattner 324407e2124SDouglas Gregor const FileEntry * 3250e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3265159f616SChris Lattner time_t ModificationTime) { 327407e2124SDouglas Gregor ++NumFileLookups; 328407e2124SDouglas Gregor 329407e2124SDouglas Gregor // See if there is already an entry in the map. 33013156b68SDavid Blaikie auto &NamedFileEnt = 33113156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 332407e2124SDouglas Gregor 333407e2124SDouglas Gregor // See if there is already an entry in the map. 33413156b68SDavid Blaikie if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE) 33513156b68SDavid Blaikie return NamedFileEnt.second; 336407e2124SDouglas Gregor 337407e2124SDouglas Gregor ++NumFileCacheMisses; 338407e2124SDouglas Gregor 339407e2124SDouglas Gregor // By default, initialize it to invalid. 34013156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 341407e2124SDouglas Gregor 342e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 343f1186c5aSCraig Topper FileEntry *UFE = nullptr; 344e1dd3e2cSZhanyong Wan 345e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 346e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 347e1dd3e2cSZhanyong Wan // cache. 3481735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 3491735f4e7SDouglas Gregor /*CacheFailure=*/true); 350e1dd3e2cSZhanyong Wan assert(DirInfo && 351e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 352e1dd3e2cSZhanyong Wan 353606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 354f8f91b89SRafael Espindola FileData Data; 35513156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 356f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { 357f8f91b89SRafael Espindola Data.Size = Size; 358f8f91b89SRafael Espindola Data.ModTime = ModificationTime; 359c9b7234eSBen Langmuir UFE = &UniqueRealFiles[Data.UniqueID]; 360606c4ac3SDouglas Gregor 36113156b68SDavid Blaikie NamedFileEnt.second = UFE; 362606c4ac3SDouglas Gregor 363606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 364606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 365606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 366c8130a74SBen Langmuir if (UFE->File) 367c8130a74SBen Langmuir UFE->closeFile(); 368606c4ac3SDouglas Gregor 369606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 370c8a71468SBen Langmuir if (UFE->isValid()) 371606c4ac3SDouglas Gregor return UFE; 372c9b7234eSBen Langmuir 373c9b7234eSBen Langmuir UFE->UniqueID = Data.UniqueID; 374c9b7234eSBen Langmuir UFE->IsNamedPipe = Data.IsNamedPipe; 375c9b7234eSBen Langmuir UFE->InPCH = Data.InPCH; 376606c4ac3SDouglas Gregor } 377606c4ac3SDouglas Gregor 378606c4ac3SDouglas Gregor if (!UFE) { 379d2725a31SDavid Blaikie VirtualFileEntries.push_back(llvm::make_unique<FileEntry>()); 380d2725a31SDavid Blaikie UFE = VirtualFileEntries.back().get(); 38113156b68SDavid Blaikie NamedFileEnt.second = UFE; 382606c4ac3SDouglas Gregor } 383407e2124SDouglas Gregor 3849624b695SChris Lattner UFE->Name = InterndFileName; 385407e2124SDouglas Gregor UFE->Size = Size; 386407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 387407e2124SDouglas Gregor UFE->Dir = DirInfo; 388407e2124SDouglas Gregor UFE->UID = NextFileUID++; 389dfffaf57SErik Verbruggen UFE->IsValid = true; 390c8130a74SBen Langmuir UFE->File.reset(); 391407e2124SDouglas Gregor return UFE; 392407e2124SDouglas Gregor } 393407e2124SDouglas Gregor 394c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 3950e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 396b5c356a4SAnders Carlsson 3979ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 3989ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 399c56419edSArgyrios Kyrtzidis return false; 40071731d6bSArgyrios Kyrtzidis 4012c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 402b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 4036e640998SChris Lattner path = NewPath; 404c56419edSArgyrios Kyrtzidis return true; 405c56419edSArgyrios Kyrtzidis } 406c56419edSArgyrios Kyrtzidis 407c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 408c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path); 409c56419edSArgyrios Kyrtzidis 410c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 41147035c02SIlya Biryukov FS->makeAbsolute(Path); 412c56419edSArgyrios Kyrtzidis Changed = true; 413c56419edSArgyrios Kyrtzidis } 414c56419edSArgyrios Kyrtzidis 415c56419edSArgyrios Kyrtzidis return Changed; 4166e640998SChris Lattner } 4176e640998SChris Lattner 418a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 419a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 420a885796dSBenjamin Kramer bool ShouldCloseOpenFile) { 4216d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4226d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4236d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 4246d7833f1SArgyrios Kyrtzidis if (isVolatile) 4256d7833f1SArgyrios Kyrtzidis FileSize = -1; 4266d7833f1SArgyrios Kyrtzidis 427004b9c7aSMehdi Amini StringRef Filename = Entry->getName(); 4285ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 429c8130a74SBen Langmuir if (Entry->File) { 430a885796dSBenjamin Kramer auto Result = 431a885796dSBenjamin Kramer Entry->File->getBuffer(Filename, FileSize, 43226d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4339801b253SBen Langmuir // FIXME: we need a set of APIs that can make guarantees about whether a 4349801b253SBen Langmuir // FileEntry is open or not. 4359801b253SBen Langmuir if (ShouldCloseOpenFile) 436c8130a74SBen Langmuir Entry->closeFile(); 4376406f7b8SRafael Espindola return Result; 4385ea7d07dSChris Lattner } 4396e640998SChris Lattner 4405ea7d07dSChris Lattner // Otherwise, open the file. 441669b0b15SArgyrios Kyrtzidis 442a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 443a885796dSBenjamin Kramer return FS->getBufferForFile(Filename, FileSize, 44426d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4455ea7d07dSChris Lattner 4462c1dd271SDylan Noblesmith SmallString<128> FilePath(Entry->getName()); 447878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 44892e1b62dSYaron Keren return FS->getBufferForFile(FilePath, FileSize, 44926d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 45026b5c190SChris Lattner } 45126b5c190SChris Lattner 452a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 453a885796dSBenjamin Kramer FileManager::getBufferForFile(StringRef Filename) { 454a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 455a885796dSBenjamin Kramer return FS->getBufferForFile(Filename); 45626b5c190SChris Lattner 4572c1dd271SDylan Noblesmith SmallString<128> FilePath(Filename); 458878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 459a885796dSBenjamin Kramer return FS->getBufferForFile(FilePath.c_str()); 46071731d6bSArgyrios Kyrtzidis } 46171731d6bSArgyrios Kyrtzidis 462e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 463e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 464e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 465e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 466e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 4670df59d8cSMehdi Amini bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile, 468326ffb36SDavid Blaikie std::unique_ptr<vfs::File> *F) { 469226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 470226efd35SChris Lattner // absolute! 4715769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 472c8130a74SBen Langmuir return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); 473226efd35SChris Lattner 4742c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 475878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 47671731d6bSArgyrios Kyrtzidis 477c8130a74SBen Langmuir return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, 478c8130a74SBen Langmuir StatCache.get(), *FS); 47971731d6bSArgyrios Kyrtzidis } 48071731d6bSArgyrios Kyrtzidis 4810e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path, 482c8130a74SBen Langmuir vfs::Status &Result) { 4832c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 4845e368405SAnders Carlsson FixupRelativePath(FilePath); 4855e368405SAnders Carlsson 486c8130a74SBen Langmuir llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str()); 487c8130a74SBen Langmuir if (!S) 488c8130a74SBen Langmuir return true; 489c8130a74SBen Langmuir Result = *S; 490c8130a74SBen Langmuir return false; 4915e368405SAnders Carlsson } 4925e368405SAnders Carlsson 493b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) { 494b3074003SAxel Naumann assert(Entry && "Cannot invalidate a NULL FileEntry"); 49538179d96SAxel Naumann 49638179d96SAxel Naumann SeenFileEntries.erase(Entry->getName()); 497b3074003SAxel Naumann 498b3074003SAxel Naumann // FileEntry invalidation should not block future optimizations in the file 499b3074003SAxel Naumann // caches. Possible alternatives are cache truncation (invalidate last N) or 500b3074003SAxel Naumann // invalidation of the whole cache. 501c9b7234eSBen Langmuir UniqueRealFiles.erase(Entry->getUniqueID()); 50238179d96SAxel Naumann } 50338179d96SAxel Naumann 50409b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 5050e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 50609b6989eSDouglas Gregor UIDToFiles.clear(); 50709b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 50809b6989eSDouglas Gregor 50909b6989eSDouglas Gregor // Map file entries 51009b6989eSDouglas Gregor for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator 511e1dd3e2cSZhanyong Wan FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); 51209b6989eSDouglas Gregor FE != FEEnd; ++FE) 51309b6989eSDouglas Gregor if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) 51409b6989eSDouglas Gregor UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); 51509b6989eSDouglas Gregor 51609b6989eSDouglas Gregor // Map virtual file entries 517d2725a31SDavid Blaikie for (const auto &VFE : VirtualFileEntries) 518d2725a31SDavid Blaikie if (VFE && VFE.get() != NON_EXISTENT_FILE) 519d2725a31SDavid Blaikie UIDToFiles[VFE->getUID()] = VFE.get(); 52009b6989eSDouglas Gregor } 521226efd35SChris Lattner 5226eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File, 5236eec06d0SArgyrios Kyrtzidis off_t Size, time_t ModificationTime) { 5246eec06d0SArgyrios Kyrtzidis File->Size = Size; 5256eec06d0SArgyrios Kyrtzidis File->ModTime = ModificationTime; 5266eec06d0SArgyrios Kyrtzidis } 5276eec06d0SArgyrios Kyrtzidis 528e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 529e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 530e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 531e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 532e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 533e00c8b20SDouglas Gregor return Known->second; 534e00c8b20SDouglas Gregor 535e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 53654cc3c2fSRichard Smith 537*148c8cb4SNico Weber SmallString<PATH_MAX> CanonicalNameBuf; 538*148c8cb4SNico Weber if (!llvm::sys::fs::real_path(Dir->getName(), CanonicalNameBuf)) 539da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 540e00c8b20SDouglas Gregor 541e00c8b20SDouglas Gregor CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); 542e00c8b20SDouglas Gregor return CanonicalName; 543e00c8b20SDouglas Gregor } 544226efd35SChris Lattner 5457a51313dSChris Lattner void FileManager::PrintStats() const { 54689b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 547e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 548e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 549e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 550e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 55189b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 5527a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 55389b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 5547a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 5557a51313dSChris Lattner 55689b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 5577a51313dSChris Lattner } 558