1226efd35SChris Lattner //===--- FileManager.cpp - File System Probing and Caching ----------------===// 27a51313dSChris Lattner // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 67a51313dSChris Lattner // 77a51313dSChris Lattner //===----------------------------------------------------------------------===// 87a51313dSChris Lattner // 97a51313dSChris Lattner // This file implements the FileManager interface. 107a51313dSChris Lattner // 117a51313dSChris Lattner //===----------------------------------------------------------------------===// 127a51313dSChris Lattner // 137a51313dSChris Lattner // TODO: This should index all interesting directories with dirent calls. 147a51313dSChris Lattner // getdirentries ? 157a51313dSChris Lattner // opendir/readdir_r/closedir ? 167a51313dSChris Lattner // 177a51313dSChris Lattner //===----------------------------------------------------------------------===// 187a51313dSChris Lattner 197a51313dSChris Lattner #include "clang/Basic/FileManager.h" 20226efd35SChris Lattner #include "clang/Basic/FileSystemStatCache.h" 217a51313dSChris Lattner #include "llvm/ADT/SmallString.h" 223a02247dSChandler Carruth #include "llvm/Config/llvm-config.h" 23d2725a31SDavid Blaikie #include "llvm/ADT/STLExtras.h" 24740857faSMichael J. Spencer #include "llvm/Support/FileSystem.h" 2571731d6bSArgyrios Kyrtzidis #include "llvm/Support/MemoryBuffer.h" 268aaf4995SMichael J. Spencer #include "llvm/Support/Path.h" 273a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h" 2835b79c24SEugene Zelenko #include <algorithm> 2935b79c24SEugene Zelenko #include <cassert> 3035b79c24SEugene Zelenko #include <climits> 3135b79c24SEugene Zelenko #include <cstdint> 3235b79c24SEugene Zelenko #include <cstdlib> 3326db6481SBenjamin Kramer #include <string> 3435b79c24SEugene Zelenko #include <utility> 35278038b4SChris Lattner 367a51313dSChris Lattner using namespace clang; 377a51313dSChris Lattner 385c04bd81STed Kremenek //===----------------------------------------------------------------------===// 395c04bd81STed Kremenek // Common logic. 405c04bd81STed Kremenek //===----------------------------------------------------------------------===// 417a51313dSChris Lattner 42c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO, 43fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) 44f6021ecdSBenjamin Kramer : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64), 45f6021ecdSBenjamin Kramer SeenFileEntries(64), NextFileUID(0) { 467a51313dSChris Lattner NumDirLookups = NumFileLookups = 0; 477a51313dSChris Lattner NumDirCacheMisses = NumFileCacheMisses = 0; 48c8130a74SBen Langmuir 49c8130a74SBen Langmuir // If the caller doesn't provide a virtual file system, just grab the real 50c8130a74SBen Langmuir // file system. 51f6021ecdSBenjamin Kramer if (!this->FS) 52fc51490bSJonas Devlieghere this->FS = llvm::vfs::getRealFileSystem(); 537a51313dSChris Lattner } 547a51313dSChris Lattner 55d2725a31SDavid Blaikie FileManager::~FileManager() = default; 567a51313dSChris Lattner 57d92b1ae1SAlex Lorenz void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) { 58d2eb58abSDouglas Gregor assert(statCache && "No stat cache provided?"); 5923430ccbSDavid Blaikie StatCache = std::move(statCache); 60d2eb58abSDouglas Gregor } 61d2eb58abSDouglas Gregor 62d92b1ae1SAlex Lorenz void FileManager::clearStatCache() { StatCache.reset(); } 633aad855aSManuel Klimek 649fc8faf9SAdrian Prantl /// Retrieve the directory that the given file name resides in. 65e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file. 66461f0722SHarlan Haskins static llvm::ErrorOr<const DirectoryEntry *> 67461f0722SHarlan Haskins getDirectoryFromFile(FileManager &FileMgr, StringRef Filename, 681735f4e7SDouglas Gregor bool CacheFailure) { 69f3c0ff73SZhanyong Wan if (Filename.empty()) 70461f0722SHarlan Haskins return std::errc::no_such_file_or_directory; 71e1dd3e2cSZhanyong Wan 72f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 73461f0722SHarlan Haskins return std::errc::is_a_directory; 740c0e8040SChris Lattner 750e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename); 760c0e8040SChris Lattner // Use the current directory if file has no path component. 77f3c0ff73SZhanyong Wan if (DirName.empty()) 78f3c0ff73SZhanyong Wan DirName = "."; 790c0e8040SChris Lattner 801735f4e7SDouglas Gregor return FileMgr.getDirectory(DirName, CacheFailure); 81407e2124SDouglas Gregor } 82407e2124SDouglas Gregor 83e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or 84e1dd3e2cSZhanyong Wan /// a directory) as virtual directories. 850e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 860e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path); 87f3c0ff73SZhanyong Wan if (DirName.empty()) 881834dc75SDavid Majnemer DirName = "."; 89e1dd3e2cSZhanyong Wan 90461f0722SHarlan Haskins auto &NamedDirEnt = *SeenDirEntries.insert( 91461f0722SHarlan Haskins {DirName, std::errc::no_such_file_or_directory}).first; 92e1dd3e2cSZhanyong Wan 93e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors 94e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache, 95e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in 96018ab5faSRichard Smith // the cache (or it's a known non-virtual directory). 97018ab5faSRichard Smith if (NamedDirEnt.second) 98e1dd3e2cSZhanyong Wan return; 99e1dd3e2cSZhanyong Wan 100e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache. 1012b3d49b6SJonas Devlieghere auto UDE = std::make_unique<DirectoryEntry>(); 1020df59d8cSMehdi Amini UDE->Name = NamedDirEnt.first(); 103461f0722SHarlan Haskins NamedDirEnt.second = *UDE.get(); 104d2725a31SDavid Blaikie VirtualDirectoryEntries.push_back(std::move(UDE)); 105e1dd3e2cSZhanyong Wan 106e1dd3e2cSZhanyong Wan // Recursively add the other ancestors. 107e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName); 108e1dd3e2cSZhanyong Wan } 109e1dd3e2cSZhanyong Wan 110461f0722SHarlan Haskins /// Converts a llvm::ErrorOr<T &> to an llvm::ErrorOr<T *> by promoting 111461f0722SHarlan Haskins /// the address of the inner reference to a pointer or by propagating the error. 112461f0722SHarlan Haskins template <typename T> 113461f0722SHarlan Haskins static llvm::ErrorOr<T *> promoteInnerReference(llvm::ErrorOr<T &> value) { 114461f0722SHarlan Haskins if (value) return &*value; 115461f0722SHarlan Haskins return value.getError(); 116461f0722SHarlan Haskins } 117461f0722SHarlan Haskins 118461f0722SHarlan Haskins llvm::ErrorOr<const DirectoryEntry *> 119461f0722SHarlan Haskins FileManager::getDirectory(StringRef DirName, bool CacheFailure) { 1208bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 12132f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 12232f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1238bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1248bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1258bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 12632f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 1271865df49SNico Weber #ifdef _WIN32 128ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 129ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 130ee30546cSRafael Espindola std::string DirNameStr; 131ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 132ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 133ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 134ee30546cSRafael Espindola DirName = DirNameStr; 135ee30546cSRafael Espindola } 136ee30546cSRafael Espindola #endif 13732f1acf1SNAKAMURA Takumi 1387a51313dSChris Lattner ++NumDirLookups; 1397a51313dSChris Lattner 140e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 141e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 142461f0722SHarlan Haskins auto SeenDirInsertResult = 143461f0722SHarlan Haskins SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory}); 144018ab5faSRichard Smith if (!SeenDirInsertResult.second) 145461f0722SHarlan Haskins return promoteInnerReference(SeenDirInsertResult.first->second); 1467a51313dSChris Lattner 147018ab5faSRichard Smith // We've not seen this before. Fill it in. 1487a51313dSChris Lattner ++NumDirCacheMisses; 149018ab5faSRichard Smith auto &NamedDirEnt = *SeenDirInsertResult.first; 150018ab5faSRichard Smith assert(!NamedDirEnt.second && "should be newly-created"); 1517a51313dSChris Lattner 1527a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 153e1dd3e2cSZhanyong Wan // SeenDirEntries map. 1540df59d8cSMehdi Amini StringRef InterndDirName = NamedDirEnt.first(); 1557a51313dSChris Lattner 1567a51313dSChris Lattner // Check to see if the directory exists. 15706f64d53SHarlan Haskins llvm::vfs::Status Status; 158461f0722SHarlan Haskins auto statError = getStatValue(InterndDirName, Status, false, 159461f0722SHarlan Haskins nullptr /*directory lookup*/); 160461f0722SHarlan Haskins if (statError) { 161e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 162461f0722SHarlan Haskins if (CacheFailure) 163461f0722SHarlan Haskins NamedDirEnt.second = statError; 164461f0722SHarlan Haskins else 1651735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 166461f0722SHarlan Haskins return statError; 167e1dd3e2cSZhanyong Wan } 1687a51313dSChris Lattner 169e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 170e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 171e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 172e1dd3e2cSZhanyong Wan // Windows). 17306f64d53SHarlan Haskins DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()]; 1747a51313dSChris Lattner 175461f0722SHarlan Haskins NamedDirEnt.second = UDE; 1760df59d8cSMehdi Amini if (UDE.getName().empty()) { 177e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 178e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 1797a51313dSChris Lattner UDE.Name = InterndDirName; 180e1dd3e2cSZhanyong Wan } 181e1dd3e2cSZhanyong Wan 1827a51313dSChris Lattner return &UDE; 1837a51313dSChris Lattner } 1847a51313dSChris Lattner 185461f0722SHarlan Haskins llvm::ErrorOr<const FileEntry *> 186461f0722SHarlan Haskins FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) { 1874dc5573aSAlex Lorenz auto Result = getFileRef(Filename, openFile, CacheFailure); 1884dc5573aSAlex Lorenz if (Result) 1894dc5573aSAlex Lorenz return &Result->getFileEntry(); 1904dc5573aSAlex Lorenz return Result.getError(); 1914dc5573aSAlex Lorenz } 1924dc5573aSAlex Lorenz 1934dc5573aSAlex Lorenz llvm::ErrorOr<FileEntryRef> 1944dc5573aSAlex Lorenz FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) { 1957a51313dSChris Lattner ++NumFileLookups; 1967a51313dSChris Lattner 1977a51313dSChris Lattner // See if there is already an entry in the map. 198461f0722SHarlan Haskins auto SeenFileInsertResult = 199461f0722SHarlan Haskins SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory}); 2004dc5573aSAlex Lorenz if (!SeenFileInsertResult.second) { 2014dc5573aSAlex Lorenz if (!SeenFileInsertResult.first->second) 2024dc5573aSAlex Lorenz return SeenFileInsertResult.first->second.getError(); 2034dc5573aSAlex Lorenz // Construct and return and FileEntryRef, unless it's a redirect to another 2044dc5573aSAlex Lorenz // filename. 2054dc5573aSAlex Lorenz SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second; 2064dc5573aSAlex Lorenz FileEntry *FE; 2074dc5573aSAlex Lorenz if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>())) 2084dc5573aSAlex Lorenz return FileEntryRef(SeenFileInsertResult.first->first(), *FE); 2094dc5573aSAlex Lorenz return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure); 2104dc5573aSAlex Lorenz } 2117a51313dSChris Lattner 212018ab5faSRichard Smith // We've not seen this before. Fill it in. 213e84385feSSam McCall ++NumFileCacheMisses; 214018ab5faSRichard Smith auto &NamedFileEnt = *SeenFileInsertResult.first; 215018ab5faSRichard Smith assert(!NamedFileEnt.second && "should be newly-created"); 216fa361206SSam McCall 2177a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 218e1dd3e2cSZhanyong Wan // SeenFileEntries map. 2190df59d8cSMehdi Amini StringRef InterndFileName = NamedFileEnt.first(); 2207a51313dSChris Lattner 221966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 222966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 223966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 224966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 225966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 226461f0722SHarlan Haskins auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure); 227461f0722SHarlan Haskins if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist. 228461f0722SHarlan Haskins if (CacheFailure) 229461f0722SHarlan Haskins NamedFileEnt.second = DirInfoOrErr.getError(); 230461f0722SHarlan Haskins else 2311735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2321735f4e7SDouglas Gregor 233461f0722SHarlan Haskins return DirInfoOrErr.getError(); 2341735f4e7SDouglas Gregor } 235461f0722SHarlan Haskins const DirectoryEntry *DirInfo = *DirInfoOrErr; 236407e2124SDouglas Gregor 2377a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2387a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2397a51313dSChris Lattner 240018ab5faSRichard Smith // Check to see if the file exists. 241fc51490bSJonas Devlieghere std::unique_ptr<llvm::vfs::File> F; 24206f64d53SHarlan Haskins llvm::vfs::Status Status; 243461f0722SHarlan Haskins auto statError = getStatValue(InterndFileName, Status, true, 244461f0722SHarlan Haskins openFile ? &F : nullptr); 245461f0722SHarlan Haskins if (statError) { 246e1dd3e2cSZhanyong Wan // There's no real file at the given path. 247461f0722SHarlan Haskins if (CacheFailure) 248461f0722SHarlan Haskins NamedFileEnt.second = statError; 249461f0722SHarlan Haskins else 2501735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2511735f4e7SDouglas Gregor 252461f0722SHarlan Haskins return statError; 253e1dd3e2cSZhanyong Wan } 2547a51313dSChris Lattner 255ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 256d6278e32SArgyrios Kyrtzidis 2577a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2587a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 25906f64d53SHarlan Haskins FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()]; 2607a51313dSChris Lattner 2614dc5573aSAlex Lorenz NamedFileEnt.second = &UFE; 262ab86fbe4SBen Langmuir 263ab86fbe4SBen Langmuir // If the name returned by getStatValue is different than Filename, re-intern 264ab86fbe4SBen Langmuir // the name. 26506f64d53SHarlan Haskins if (Status.getName() != Filename) { 266*98f9e94eSRichard Smith auto &NewNamedFileEnt = 2674dc5573aSAlex Lorenz *SeenFileEntries.insert({Status.getName(), &UFE}).first; 268*98f9e94eSRichard Smith assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE && 269ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file"); 270*98f9e94eSRichard Smith InterndFileName = NewNamedFileEnt.first().data(); 2714dc5573aSAlex Lorenz // In addition to re-interning the name, construct a redirecting seen file 2724dc5573aSAlex Lorenz // entry, that will point to the name the filesystem actually wants to use. 2734dc5573aSAlex Lorenz StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName); 274*98f9e94eSRichard Smith NamedFileEnt.second = Redirect; 275ab86fbe4SBen Langmuir } 276ab86fbe4SBen Langmuir 277c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2785de00f3bSBen Langmuir 2795de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 2805de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 2815de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 2825de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 2835de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 2845de00f3bSBen Langmuir // multiple names. 28506f64d53SHarlan Haskins if (DirInfo != UFE.Dir && Status.IsVFSMapped) 2865de00f3bSBen Langmuir UFE.Dir = DirInfo; 2875de00f3bSBen Langmuir 288c0ff9908SManuel Klimek // Always update the name to use the last name by which a file was accessed. 289c0ff9908SManuel Klimek // FIXME: Neither this nor always using the first name is correct; we want 290c0ff9908SManuel Klimek // to switch towards a design where we return a FileName object that 291c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the 292c0ff9908SManuel Klimek // corresponding FileEntry. 2934dc5573aSAlex Lorenz // FIXME: The Name should be removed from FileEntry once all clients 2944dc5573aSAlex Lorenz // adopt FileEntryRef. 295ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 296c0ff9908SManuel Klimek 2974dc5573aSAlex Lorenz return FileEntryRef(InterndFileName, UFE); 298dd278430SChris Lattner } 2997a51313dSChris Lattner 300c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 301ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 30206f64d53SHarlan Haskins UFE.Size = Status.getSize(); 30306f64d53SHarlan Haskins UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 3047a51313dSChris Lattner UFE.Dir = DirInfo; 3057a51313dSChris Lattner UFE.UID = NextFileUID++; 30606f64d53SHarlan Haskins UFE.UniqueID = Status.getUniqueID(); 30706f64d53SHarlan Haskins UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 308fa361206SSam McCall UFE.File = std::move(F); 309c8a71468SBen Langmuir UFE.IsValid = true; 310ddbabc6bSSimon Marchi 311fa361206SSam McCall if (UFE.File) { 312fa361206SSam McCall if (auto PathName = UFE.File->getName()) 313fa361206SSam McCall fillRealPathName(&UFE, *PathName); 314cd8607dbSJan Korous } else if (!openFile) { 315cd8607dbSJan Korous // We should still fill the path even if we aren't opening the file. 316cd8607dbSJan Korous fillRealPathName(&UFE, InterndFileName); 317fa361206SSam McCall } 3184dc5573aSAlex Lorenz return FileEntryRef(InterndFileName, UFE); 3197a51313dSChris Lattner } 3207a51313dSChris Lattner 321407e2124SDouglas Gregor const FileEntry * 3220e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3235159f616SChris Lattner time_t ModificationTime) { 324407e2124SDouglas Gregor ++NumFileLookups; 325407e2124SDouglas Gregor 326018ab5faSRichard Smith // See if there is already an entry in the map for an existing file. 327461f0722SHarlan Haskins auto &NamedFileEnt = *SeenFileEntries.insert( 328461f0722SHarlan Haskins {Filename, std::errc::no_such_file_or_directory}).first; 3294dc5573aSAlex Lorenz if (NamedFileEnt.second) { 3304dc5573aSAlex Lorenz SeenFileEntryOrRedirect Value = *NamedFileEnt.second; 3314dc5573aSAlex Lorenz FileEntry *FE; 3324dc5573aSAlex Lorenz if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>())) 3334dc5573aSAlex Lorenz return FE; 3344dc5573aSAlex Lorenz return getVirtualFile(*Value.get<const StringRef *>(), Size, 3354dc5573aSAlex Lorenz ModificationTime); 3364dc5573aSAlex Lorenz } 337407e2124SDouglas Gregor 338018ab5faSRichard Smith // We've not seen this before, or the file is cached as non-existent. 339407e2124SDouglas Gregor ++NumFileCacheMisses; 340e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 341f1186c5aSCraig Topper FileEntry *UFE = nullptr; 342e1dd3e2cSZhanyong Wan 343e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 344e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 345e1dd3e2cSZhanyong Wan // cache. 346461f0722SHarlan Haskins auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true); 347e1dd3e2cSZhanyong Wan assert(DirInfo && 348e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 349e1dd3e2cSZhanyong Wan 350606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 35106f64d53SHarlan Haskins llvm::vfs::Status Status; 35213156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 353461f0722SHarlan Haskins if (!getStatValue(InterndFileName, Status, true, nullptr)) { 35406f64d53SHarlan Haskins UFE = &UniqueRealFiles[Status.getUniqueID()]; 35506f64d53SHarlan Haskins Status = llvm::vfs::Status( 35606f64d53SHarlan Haskins Status.getName(), Status.getUniqueID(), 35706f64d53SHarlan Haskins llvm::sys::toTimePoint(ModificationTime), 35806f64d53SHarlan Haskins Status.getUser(), Status.getGroup(), Size, 35906f64d53SHarlan Haskins Status.getType(), Status.getPermissions()); 360606c4ac3SDouglas Gregor 3614dc5573aSAlex Lorenz 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 37306f64d53SHarlan Haskins UFE->UniqueID = Status.getUniqueID(); 37406f64d53SHarlan Haskins UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 37506f64d53SHarlan Haskins fillRealPathName(UFE, Status.getName()); 376018ab5faSRichard Smith } else { 3772b3d49b6SJonas Devlieghere VirtualFileEntries.push_back(std::make_unique<FileEntry>()); 378d2725a31SDavid Blaikie UFE = VirtualFileEntries.back().get(); 3794dc5573aSAlex Lorenz NamedFileEnt.second = UFE; 380606c4ac3SDouglas Gregor } 381407e2124SDouglas Gregor 3829624b695SChris Lattner UFE->Name = InterndFileName; 383407e2124SDouglas Gregor UFE->Size = Size; 384407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 385461f0722SHarlan Haskins UFE->Dir = *DirInfo; 386407e2124SDouglas Gregor UFE->UID = NextFileUID++; 387dfffaf57SErik Verbruggen UFE->IsValid = true; 388c8130a74SBen Langmuir UFE->File.reset(); 389407e2124SDouglas Gregor return UFE; 390407e2124SDouglas Gregor } 391407e2124SDouglas Gregor 392c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 3930e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 394b5c356a4SAnders Carlsson 3959ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 3969ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 397c56419edSArgyrios Kyrtzidis return false; 39871731d6bSArgyrios Kyrtzidis 3992c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 400b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 4016e640998SChris Lattner path = NewPath; 402c56419edSArgyrios Kyrtzidis return true; 403c56419edSArgyrios Kyrtzidis } 404c56419edSArgyrios Kyrtzidis 405c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 406c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path); 407c56419edSArgyrios Kyrtzidis 408c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 40947035c02SIlya Biryukov FS->makeAbsolute(Path); 410c56419edSArgyrios Kyrtzidis Changed = true; 411c56419edSArgyrios Kyrtzidis } 412c56419edSArgyrios Kyrtzidis 413c56419edSArgyrios Kyrtzidis return Changed; 4146e640998SChris Lattner } 4156e640998SChris Lattner 416e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) { 417e9870c0cSKadir Cetinkaya llvm::SmallString<128> AbsPath(FileName); 418e9870c0cSKadir Cetinkaya // This is not the same as `VFS::getRealPath()`, which resolves symlinks 419e9870c0cSKadir Cetinkaya // but can be very expensive on real file systems. 420e9870c0cSKadir Cetinkaya // FIXME: the semantic of RealPathName is unclear, and the name might be 421e9870c0cSKadir Cetinkaya // misleading. We need to clean up the interface here. 422e9870c0cSKadir Cetinkaya makeAbsolutePath(AbsPath); 423e9870c0cSKadir Cetinkaya llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true); 424e9870c0cSKadir Cetinkaya UFE->RealPathName = AbsPath.str(); 425e9870c0cSKadir Cetinkaya } 426e9870c0cSKadir Cetinkaya 427a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 428a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 429a885796dSBenjamin Kramer bool ShouldCloseOpenFile) { 4306d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4316d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4326d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 4336d7833f1SArgyrios Kyrtzidis if (isVolatile) 4346d7833f1SArgyrios Kyrtzidis FileSize = -1; 4356d7833f1SArgyrios Kyrtzidis 436004b9c7aSMehdi Amini StringRef Filename = Entry->getName(); 4375ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 438c8130a74SBen Langmuir if (Entry->File) { 439a885796dSBenjamin Kramer auto Result = 440a885796dSBenjamin Kramer Entry->File->getBuffer(Filename, FileSize, 44126d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4429801b253SBen Langmuir // FIXME: we need a set of APIs that can make guarantees about whether a 4439801b253SBen Langmuir // FileEntry is open or not. 4449801b253SBen Langmuir if (ShouldCloseOpenFile) 445c8130a74SBen Langmuir Entry->closeFile(); 4466406f7b8SRafael Espindola return Result; 4475ea7d07dSChris Lattner } 4486e640998SChris Lattner 4495ea7d07dSChris Lattner // Otherwise, open the file. 450894b8d1dSDuncan P. N. Exon Smith return getBufferForFileImpl(Filename, FileSize, isVolatile); 451894b8d1dSDuncan P. N. Exon Smith } 452669b0b15SArgyrios Kyrtzidis 453894b8d1dSDuncan P. N. Exon Smith llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 454894b8d1dSDuncan P. N. Exon Smith FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, 455894b8d1dSDuncan P. N. Exon Smith bool isVolatile) { 456a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 457a885796dSBenjamin Kramer return FS->getBufferForFile(Filename, FileSize, 45826d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4595ea7d07dSChris Lattner 460894b8d1dSDuncan P. N. Exon Smith SmallString<128> FilePath(Filename); 461878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 46292e1b62dSYaron Keren return FS->getBufferForFile(FilePath, FileSize, 46326d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 46426b5c190SChris Lattner } 46526b5c190SChris Lattner 466e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 467e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 468e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 469e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 470e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 471461f0722SHarlan Haskins std::error_code 472461f0722SHarlan Haskins FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status, 473461f0722SHarlan Haskins bool isFile, std::unique_ptr<llvm::vfs::File> *F) { 474226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 475226efd35SChris Lattner // absolute! 4765769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 477461f0722SHarlan Haskins return FileSystemStatCache::get(Path, Status, isFile, F, 478461f0722SHarlan Haskins StatCache.get(), *FS); 479226efd35SChris Lattner 4802c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 481878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 48271731d6bSArgyrios Kyrtzidis 483461f0722SHarlan Haskins return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F, 484461f0722SHarlan Haskins StatCache.get(), *FS); 48571731d6bSArgyrios Kyrtzidis } 48671731d6bSArgyrios Kyrtzidis 487461f0722SHarlan Haskins std::error_code 488461f0722SHarlan Haskins FileManager::getNoncachedStatValue(StringRef Path, 489fc51490bSJonas Devlieghere llvm::vfs::Status &Result) { 4902c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 4915e368405SAnders Carlsson FixupRelativePath(FilePath); 4925e368405SAnders Carlsson 493fc51490bSJonas Devlieghere llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str()); 494c8130a74SBen Langmuir if (!S) 495461f0722SHarlan Haskins return S.getError(); 496c8130a74SBen Langmuir Result = *S; 497461f0722SHarlan Haskins return std::error_code(); 4985e368405SAnders Carlsson } 4995e368405SAnders Carlsson 500b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) { 501b3074003SAxel Naumann assert(Entry && "Cannot invalidate a NULL FileEntry"); 50238179d96SAxel Naumann 50338179d96SAxel Naumann SeenFileEntries.erase(Entry->getName()); 504b3074003SAxel Naumann 505b3074003SAxel Naumann // FileEntry invalidation should not block future optimizations in the file 506b3074003SAxel Naumann // caches. Possible alternatives are cache truncation (invalidate last N) or 507b3074003SAxel Naumann // invalidation of the whole cache. 508018ab5faSRichard Smith // 509018ab5faSRichard Smith // FIXME: This is broken. We sometimes have the same FileEntry* shared 510f56e8991SNico Weber // between multiple SeenFileEntries, so this can leave dangling pointers. 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 5204dc5573aSAlex Lorenz for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>, 521461f0722SHarlan Haskins llvm::BumpPtrAllocator>::const_iterator 5224dc5573aSAlex Lorenz FE = SeenFileEntries.begin(), 5234dc5573aSAlex Lorenz FEEnd = SeenFileEntries.end(); 52409b6989eSDouglas Gregor FE != FEEnd; ++FE) 5254dc5573aSAlex Lorenz if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) { 5264dc5573aSAlex Lorenz if (const auto *FE = (*Entry).dyn_cast<FileEntry *>()) 5274dc5573aSAlex Lorenz UIDToFiles[FE->getUID()] = FE; 528461f0722SHarlan Haskins } 52909b6989eSDouglas Gregor 53009b6989eSDouglas Gregor // Map virtual file entries 531d2725a31SDavid Blaikie for (const auto &VFE : VirtualFileEntries) 532d2725a31SDavid Blaikie UIDToFiles[VFE->getUID()] = VFE.get(); 53309b6989eSDouglas Gregor } 534226efd35SChris Lattner 5356eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File, 5366eec06d0SArgyrios Kyrtzidis off_t Size, time_t ModificationTime) { 5376eec06d0SArgyrios Kyrtzidis File->Size = Size; 5386eec06d0SArgyrios Kyrtzidis File->ModTime = ModificationTime; 5396eec06d0SArgyrios Kyrtzidis } 5406eec06d0SArgyrios Kyrtzidis 541e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 542e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 543e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 544e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 545e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 546e00c8b20SDouglas Gregor return Known->second; 547e00c8b20SDouglas Gregor 548e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 54954cc3c2fSRichard Smith 5505fb18fecSEric Liu SmallString<4096> CanonicalNameBuf; 5515fb18fecSEric Liu if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf)) 552da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 553e00c8b20SDouglas Gregor 554018ab5faSRichard Smith CanonicalDirNames.insert({Dir, CanonicalName}); 555e00c8b20SDouglas Gregor return CanonicalName; 556e00c8b20SDouglas Gregor } 557226efd35SChris Lattner 5587a51313dSChris Lattner void FileManager::PrintStats() const { 55989b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 560e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 561e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 562e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 563e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 56489b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 5657a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 56689b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 5677a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 5687a51313dSChris Lattner 56989b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 5707a51313dSChris Lattner } 571