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" 21d2725a31SDavid Blaikie #include "llvm/ADT/STLExtras.h" 22e8752a9dSVolodymyr Sapsai #include "llvm/ADT/SmallString.h" 23e8752a9dSVolodymyr Sapsai #include "llvm/ADT/Statistic.h" 24e8752a9dSVolodymyr Sapsai #include "llvm/Config/llvm-config.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 39e8752a9dSVolodymyr Sapsai #define DEBUG_TYPE "file-search" 40e8752a9dSVolodymyr Sapsai 41e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups."); 42e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups."); 43e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses, 44e8752a9dSVolodymyr Sapsai "Number of directory cache misses."); 45e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses."); 46e8752a9dSVolodymyr Sapsai 475c04bd81STed Kremenek //===----------------------------------------------------------------------===// 485c04bd81STed Kremenek // Common logic. 495c04bd81STed Kremenek //===----------------------------------------------------------------------===// 507a51313dSChris Lattner 51c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO, 52fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) 53f6021ecdSBenjamin Kramer : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64), 54f6021ecdSBenjamin Kramer SeenFileEntries(64), NextFileUID(0) { 55c8130a74SBen Langmuir // If the caller doesn't provide a virtual file system, just grab the real 56c8130a74SBen Langmuir // file system. 57f6021ecdSBenjamin Kramer if (!this->FS) 58fc51490bSJonas Devlieghere this->FS = llvm::vfs::getRealFileSystem(); 597a51313dSChris Lattner } 607a51313dSChris Lattner 61d2725a31SDavid Blaikie FileManager::~FileManager() = default; 627a51313dSChris Lattner 63d92b1ae1SAlex Lorenz void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) { 64d2eb58abSDouglas Gregor assert(statCache && "No stat cache provided?"); 6523430ccbSDavid Blaikie StatCache = std::move(statCache); 66d2eb58abSDouglas Gregor } 67d2eb58abSDouglas Gregor 68d92b1ae1SAlex Lorenz void FileManager::clearStatCache() { StatCache.reset(); } 693aad855aSManuel Klimek 709fc8faf9SAdrian Prantl /// Retrieve the directory that the given file name resides in. 71e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file. 721b042de5SDuncan P. N. Exon Smith static llvm::Expected<DirectoryEntryRef> 73461f0722SHarlan Haskins getDirectoryFromFile(FileManager &FileMgr, StringRef Filename, 741735f4e7SDouglas Gregor bool CacheFailure) { 75f3c0ff73SZhanyong Wan if (Filename.empty()) 761b042de5SDuncan P. N. Exon Smith return llvm::errorCodeToError( 771b042de5SDuncan P. N. Exon Smith make_error_code(std::errc::no_such_file_or_directory)); 78e1dd3e2cSZhanyong Wan 79f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 801b042de5SDuncan P. N. Exon Smith return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory)); 810c0e8040SChris Lattner 820e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename); 830c0e8040SChris Lattner // Use the current directory if file has no path component. 84f3c0ff73SZhanyong Wan if (DirName.empty()) 85f3c0ff73SZhanyong Wan DirName = "."; 860c0e8040SChris Lattner 871b042de5SDuncan P. N. Exon Smith return FileMgr.getDirectoryRef(DirName, CacheFailure); 88407e2124SDouglas Gregor } 89407e2124SDouglas Gregor 90e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or 91e1dd3e2cSZhanyong Wan /// a directory) as virtual directories. 920e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 930e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path); 94f3c0ff73SZhanyong Wan if (DirName.empty()) 951834dc75SDavid Majnemer DirName = "."; 96e1dd3e2cSZhanyong Wan 97461f0722SHarlan Haskins auto &NamedDirEnt = *SeenDirEntries.insert( 98461f0722SHarlan Haskins {DirName, std::errc::no_such_file_or_directory}).first; 99e1dd3e2cSZhanyong Wan 100e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors 101e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache, 102e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in 103018ab5faSRichard Smith // the cache (or it's a known non-virtual directory). 104018ab5faSRichard Smith if (NamedDirEnt.second) 105e1dd3e2cSZhanyong Wan return; 106e1dd3e2cSZhanyong Wan 107e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache. 1082b3d49b6SJonas Devlieghere auto UDE = std::make_unique<DirectoryEntry>(); 1090df59d8cSMehdi Amini UDE->Name = NamedDirEnt.first(); 110461f0722SHarlan Haskins NamedDirEnt.second = *UDE.get(); 111d2725a31SDavid Blaikie VirtualDirectoryEntries.push_back(std::move(UDE)); 112e1dd3e2cSZhanyong Wan 113e1dd3e2cSZhanyong Wan // Recursively add the other ancestors. 114e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName); 115e1dd3e2cSZhanyong Wan } 116e1dd3e2cSZhanyong Wan 1170377ca64SAlex Lorenz llvm::Expected<DirectoryEntryRef> 1180377ca64SAlex Lorenz FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) { 1198bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 12032f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 12132f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1228bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1238bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1248bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 12532f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 1261865df49SNico Weber #ifdef _WIN32 127ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 128ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 129ee30546cSRafael Espindola std::string DirNameStr; 130ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 131ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 132ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 133ee30546cSRafael Espindola DirName = DirNameStr; 134ee30546cSRafael Espindola } 135ee30546cSRafael Espindola #endif 13632f1acf1SNAKAMURA Takumi 1377a51313dSChris Lattner ++NumDirLookups; 1387a51313dSChris Lattner 139e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 140e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 141461f0722SHarlan Haskins auto SeenDirInsertResult = 142461f0722SHarlan Haskins SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory}); 1430377ca64SAlex Lorenz if (!SeenDirInsertResult.second) { 1440377ca64SAlex Lorenz if (SeenDirInsertResult.first->second) 1451b042de5SDuncan P. N. Exon Smith return DirectoryEntryRef(*SeenDirInsertResult.first); 1460377ca64SAlex Lorenz return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError()); 1470377ca64SAlex Lorenz } 1487a51313dSChris Lattner 149018ab5faSRichard Smith // We've not seen this before. Fill it in. 1507a51313dSChris Lattner ++NumDirCacheMisses; 151018ab5faSRichard Smith auto &NamedDirEnt = *SeenDirInsertResult.first; 152018ab5faSRichard Smith assert(!NamedDirEnt.second && "should be newly-created"); 1537a51313dSChris Lattner 1547a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 155e1dd3e2cSZhanyong Wan // SeenDirEntries map. 1560df59d8cSMehdi Amini StringRef InterndDirName = NamedDirEnt.first(); 1577a51313dSChris Lattner 1587a51313dSChris Lattner // Check to see if the directory exists. 15906f64d53SHarlan Haskins llvm::vfs::Status Status; 160461f0722SHarlan Haskins auto statError = getStatValue(InterndDirName, Status, false, 161461f0722SHarlan Haskins nullptr /*directory lookup*/); 162461f0722SHarlan Haskins if (statError) { 163e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 164461f0722SHarlan Haskins if (CacheFailure) 165461f0722SHarlan Haskins NamedDirEnt.second = statError; 166461f0722SHarlan Haskins else 1671735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 1680377ca64SAlex Lorenz return llvm::errorCodeToError(statError); 169e1dd3e2cSZhanyong Wan } 1707a51313dSChris Lattner 171e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 172e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 173e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 174e1dd3e2cSZhanyong Wan // Windows). 17506f64d53SHarlan Haskins DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()]; 1767a51313dSChris Lattner 177461f0722SHarlan Haskins NamedDirEnt.second = UDE; 1780df59d8cSMehdi Amini if (UDE.getName().empty()) { 179e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 180e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 1817a51313dSChris Lattner UDE.Name = InterndDirName; 182e1dd3e2cSZhanyong Wan } 183e1dd3e2cSZhanyong Wan 1841b042de5SDuncan P. N. Exon Smith return DirectoryEntryRef(NamedDirEnt); 1850377ca64SAlex Lorenz } 1860377ca64SAlex Lorenz 1870377ca64SAlex Lorenz llvm::ErrorOr<const DirectoryEntry *> 1880377ca64SAlex Lorenz FileManager::getDirectory(StringRef DirName, bool CacheFailure) { 1890377ca64SAlex Lorenz auto Result = getDirectoryRef(DirName, CacheFailure); 1900377ca64SAlex Lorenz if (Result) 1910377ca64SAlex Lorenz return &Result->getDirEntry(); 1920377ca64SAlex Lorenz return llvm::errorToErrorCode(Result.takeError()); 1937a51313dSChris Lattner } 1947a51313dSChris Lattner 195461f0722SHarlan Haskins llvm::ErrorOr<const FileEntry *> 196461f0722SHarlan Haskins FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) { 1974dc5573aSAlex Lorenz auto Result = getFileRef(Filename, openFile, CacheFailure); 1984dc5573aSAlex Lorenz if (Result) 1994dc5573aSAlex Lorenz return &Result->getFileEntry(); 2009ef6c49bSDuncan P. N. Exon Smith return llvm::errorToErrorCode(Result.takeError()); 2014dc5573aSAlex Lorenz } 2024dc5573aSAlex Lorenz 2039ef6c49bSDuncan P. N. Exon Smith llvm::Expected<FileEntryRef> 2044dc5573aSAlex Lorenz FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) { 2057a51313dSChris Lattner ++NumFileLookups; 2067a51313dSChris Lattner 2077a51313dSChris Lattner // See if there is already an entry in the map. 208461f0722SHarlan Haskins auto SeenFileInsertResult = 209461f0722SHarlan Haskins SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory}); 2104dc5573aSAlex Lorenz if (!SeenFileInsertResult.second) { 2114dc5573aSAlex Lorenz if (!SeenFileInsertResult.first->second) 2129ef6c49bSDuncan P. N. Exon Smith return llvm::errorCodeToError( 2139ef6c49bSDuncan P. N. Exon Smith SeenFileInsertResult.first->second.getError()); 2144dc5573aSAlex Lorenz // Construct and return and FileEntryRef, unless it's a redirect to another 2154dc5573aSAlex Lorenz // filename. 216917acac9SDuncan P. N. Exon Smith FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second; 217917acac9SDuncan P. N. Exon Smith if (LLVM_LIKELY(Value.V.is<FileEntry *>())) 218917acac9SDuncan P. N. Exon Smith return FileEntryRef(*SeenFileInsertResult.first); 219739d4bf8SNico Weber return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>( 220739d4bf8SNico Weber Value.V.get<const void *>())); 2214dc5573aSAlex Lorenz } 2227a51313dSChris Lattner 223018ab5faSRichard Smith // We've not seen this before. Fill it in. 224e84385feSSam McCall ++NumFileCacheMisses; 225b3144145SAlex Suhan auto *NamedFileEnt = &*SeenFileInsertResult.first; 226b3144145SAlex Suhan assert(!NamedFileEnt->second && "should be newly-created"); 227fa361206SSam McCall 2287a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 229e1dd3e2cSZhanyong Wan // SeenFileEntries map. 230b3144145SAlex Suhan StringRef InterndFileName = NamedFileEnt->first(); 2317a51313dSChris Lattner 232966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 233966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 234966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 235966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 236966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 237461f0722SHarlan Haskins auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure); 238461f0722SHarlan Haskins if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist. 2391b042de5SDuncan P. N. Exon Smith std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError()); 240461f0722SHarlan Haskins if (CacheFailure) 2411b042de5SDuncan P. N. Exon Smith NamedFileEnt->second = Err; 242461f0722SHarlan Haskins else 2431735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2441735f4e7SDouglas Gregor 2451b042de5SDuncan P. N. Exon Smith return llvm::errorCodeToError(Err); 2461735f4e7SDouglas Gregor } 2471b042de5SDuncan P. N. Exon Smith DirectoryEntryRef DirInfo = *DirInfoOrErr; 248407e2124SDouglas Gregor 2497a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2507a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2517a51313dSChris Lattner 252018ab5faSRichard Smith // Check to see if the file exists. 253fc51490bSJonas Devlieghere std::unique_ptr<llvm::vfs::File> F; 25406f64d53SHarlan Haskins llvm::vfs::Status Status; 255461f0722SHarlan Haskins auto statError = getStatValue(InterndFileName, Status, true, 256461f0722SHarlan Haskins openFile ? &F : nullptr); 257461f0722SHarlan Haskins if (statError) { 258e1dd3e2cSZhanyong Wan // There's no real file at the given path. 259461f0722SHarlan Haskins if (CacheFailure) 260b3144145SAlex Suhan NamedFileEnt->second = statError; 261461f0722SHarlan Haskins else 2621735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2631735f4e7SDouglas Gregor 2649ef6c49bSDuncan P. N. Exon Smith return llvm::errorCodeToError(statError); 265e1dd3e2cSZhanyong Wan } 2667a51313dSChris Lattner 267ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 268d6278e32SArgyrios Kyrtzidis 2697a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2707a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 27106f64d53SHarlan Haskins FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()]; 2727a51313dSChris Lattner 273917acac9SDuncan P. N. Exon Smith if (Status.getName() == Filename) { 274917acac9SDuncan P. N. Exon Smith // The name matches. Set the FileEntry. 2751b042de5SDuncan P. N. Exon Smith NamedFileEnt->second = FileEntryRef::MapValue(UFE, DirInfo); 276917acac9SDuncan P. N. Exon Smith } else { 277917acac9SDuncan P. N. Exon Smith // Name mismatch. We need a redirect. First grab the actual entry we want 278917acac9SDuncan P. N. Exon Smith // to return. 279917acac9SDuncan P. N. Exon Smith auto &Redirection = 2801b042de5SDuncan P. N. Exon Smith *SeenFileEntries 2811b042de5SDuncan P. N. Exon Smith .insert({Status.getName(), FileEntryRef::MapValue(UFE, DirInfo)}) 282917acac9SDuncan P. N. Exon Smith .first; 283917acac9SDuncan P. N. Exon Smith assert(Redirection.second->V.is<FileEntry *>() && 284917acac9SDuncan P. N. Exon Smith "filename redirected to a non-canonical filename?"); 285917acac9SDuncan P. N. Exon Smith assert(Redirection.second->V.get<FileEntry *>() == &UFE && 286ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file"); 287917acac9SDuncan P. N. Exon Smith 288917acac9SDuncan P. N. Exon Smith // Cache the redirection in the previously-inserted entry, still available 289917acac9SDuncan P. N. Exon Smith // in the tentative return value. 290917acac9SDuncan P. N. Exon Smith NamedFileEnt->second = FileEntryRef::MapValue(Redirection); 291917acac9SDuncan P. N. Exon Smith 292917acac9SDuncan P. N. Exon Smith // Fix the tentative return value. 293917acac9SDuncan P. N. Exon Smith NamedFileEnt = &Redirection; 294ab86fbe4SBen Langmuir } 295ab86fbe4SBen Langmuir 296917acac9SDuncan P. N. Exon Smith FileEntryRef ReturnedRef(*NamedFileEnt); 297c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2985de00f3bSBen Langmuir 2995de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 3005de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 3015de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 3025de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 3035de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 3045de00f3bSBen Langmuir // multiple names. 3051b042de5SDuncan P. N. Exon Smith if (&DirInfo.getDirEntry() != UFE.Dir && Status.IsVFSMapped) 3061b042de5SDuncan P. N. Exon Smith UFE.Dir = &DirInfo.getDirEntry(); 3075de00f3bSBen Langmuir 308917acac9SDuncan P. N. Exon Smith // Always update LastRef to the last name by which a file was accessed. 309917acac9SDuncan P. N. Exon Smith // FIXME: Neither this nor always using the first reference is correct; we 310917acac9SDuncan P. N. Exon Smith // want to switch towards a design where we return a FileName object that 311c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the 312c0ff9908SManuel Klimek // corresponding FileEntry. 313917acac9SDuncan P. N. Exon Smith // FIXME: LastRef should be removed from FileEntry once all clients adopt 314917acac9SDuncan P. N. Exon Smith // FileEntryRef. 315917acac9SDuncan P. N. Exon Smith UFE.LastRef = ReturnedRef; 316c0ff9908SManuel Klimek 317917acac9SDuncan P. N. Exon Smith return ReturnedRef; 318dd278430SChris Lattner } 3197a51313dSChris Lattner 320c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 321917acac9SDuncan P. N. Exon Smith UFE.LastRef = ReturnedRef; 32206f64d53SHarlan Haskins UFE.Size = Status.getSize(); 32306f64d53SHarlan Haskins UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 3241b042de5SDuncan P. N. Exon Smith UFE.Dir = &DirInfo.getDirEntry(); 3257a51313dSChris Lattner UFE.UID = NextFileUID++; 32606f64d53SHarlan Haskins UFE.UniqueID = Status.getUniqueID(); 32706f64d53SHarlan Haskins UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 328fa361206SSam McCall UFE.File = std::move(F); 329c8a71468SBen Langmuir UFE.IsValid = true; 330ddbabc6bSSimon Marchi 331fa361206SSam McCall if (UFE.File) { 332fa361206SSam McCall if (auto PathName = UFE.File->getName()) 333fa361206SSam McCall fillRealPathName(&UFE, *PathName); 334cd8607dbSJan Korous } else if (!openFile) { 335cd8607dbSJan Korous // We should still fill the path even if we aren't opening the file. 336cd8607dbSJan Korous fillRealPathName(&UFE, InterndFileName); 337fa361206SSam McCall } 338917acac9SDuncan P. N. Exon Smith return ReturnedRef; 3397a51313dSChris Lattner } 3407a51313dSChris Lattner 341ac40a2d8SDuncan P. N. Exon Smith const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size, 342ac40a2d8SDuncan P. N. Exon Smith time_t ModificationTime) { 343ac40a2d8SDuncan P. N. Exon Smith return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry(); 344ac40a2d8SDuncan P. N. Exon Smith } 345ac40a2d8SDuncan P. N. Exon Smith 346ac40a2d8SDuncan P. N. Exon Smith FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size, 3475159f616SChris Lattner time_t ModificationTime) { 348407e2124SDouglas Gregor ++NumFileLookups; 349407e2124SDouglas Gregor 350018ab5faSRichard Smith // See if there is already an entry in the map for an existing file. 351461f0722SHarlan Haskins auto &NamedFileEnt = *SeenFileEntries.insert( 352461f0722SHarlan Haskins {Filename, std::errc::no_such_file_or_directory}).first; 3534dc5573aSAlex Lorenz if (NamedFileEnt.second) { 354917acac9SDuncan P. N. Exon Smith FileEntryRef::MapValue Value = *NamedFileEnt.second; 355ac40a2d8SDuncan P. N. Exon Smith if (LLVM_LIKELY(Value.V.is<FileEntry *>())) 356ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(NamedFileEnt); 357ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>( 358ac40a2d8SDuncan P. N. Exon Smith Value.V.get<const void *>())); 3594dc5573aSAlex Lorenz } 360407e2124SDouglas Gregor 361018ab5faSRichard Smith // We've not seen this before, or the file is cached as non-existent. 362407e2124SDouglas Gregor ++NumFileCacheMisses; 363e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 364f1186c5aSCraig Topper FileEntry *UFE = nullptr; 365e1dd3e2cSZhanyong Wan 366e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 367e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 368e1dd3e2cSZhanyong Wan // cache. 3691b042de5SDuncan P. N. Exon Smith auto DirInfo = expectedToOptional( 3701b042de5SDuncan P. N. Exon Smith getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true)); 371e1dd3e2cSZhanyong Wan assert(DirInfo && 372e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 373e1dd3e2cSZhanyong Wan 374606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 37506f64d53SHarlan Haskins llvm::vfs::Status Status; 37613156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 377461f0722SHarlan Haskins if (!getStatValue(InterndFileName, Status, true, nullptr)) { 37806f64d53SHarlan Haskins UFE = &UniqueRealFiles[Status.getUniqueID()]; 37906f64d53SHarlan Haskins Status = llvm::vfs::Status( 38006f64d53SHarlan Haskins Status.getName(), Status.getUniqueID(), 38106f64d53SHarlan Haskins llvm::sys::toTimePoint(ModificationTime), 38206f64d53SHarlan Haskins Status.getUser(), Status.getGroup(), Size, 38306f64d53SHarlan Haskins Status.getType(), Status.getPermissions()); 384606c4ac3SDouglas Gregor 3851b042de5SDuncan P. N. Exon Smith NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo); 386606c4ac3SDouglas Gregor 387606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 388606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 389606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 390c8130a74SBen Langmuir if (UFE->File) 391c8130a74SBen Langmuir UFE->closeFile(); 392606c4ac3SDouglas Gregor 393606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 394917acac9SDuncan P. N. Exon Smith // 395917acac9SDuncan P. N. Exon Smith // FIXME: Surely this should add a reference by the new name, and return 396917acac9SDuncan P. N. Exon Smith // it instead... 397c8a71468SBen Langmuir if (UFE->isValid()) 398ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(NamedFileEnt); 399c9b7234eSBen Langmuir 40006f64d53SHarlan Haskins UFE->UniqueID = Status.getUniqueID(); 40106f64d53SHarlan Haskins UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 40206f64d53SHarlan Haskins fillRealPathName(UFE, Status.getName()); 403018ab5faSRichard Smith } else { 4042b3d49b6SJonas Devlieghere VirtualFileEntries.push_back(std::make_unique<FileEntry>()); 405d2725a31SDavid Blaikie UFE = VirtualFileEntries.back().get(); 4061b042de5SDuncan P. N. Exon Smith NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo); 407606c4ac3SDouglas Gregor } 408407e2124SDouglas Gregor 409917acac9SDuncan P. N. Exon Smith UFE->LastRef = FileEntryRef(NamedFileEnt); 410407e2124SDouglas Gregor UFE->Size = Size; 411407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 4121b042de5SDuncan P. N. Exon Smith UFE->Dir = &DirInfo->getDirEntry(); 413407e2124SDouglas Gregor UFE->UID = NextFileUID++; 414dfffaf57SErik Verbruggen UFE->IsValid = true; 415c8130a74SBen Langmuir UFE->File.reset(); 416ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(NamedFileEnt); 417407e2124SDouglas Gregor } 418407e2124SDouglas Gregor 419e1b7f22bSDuncan P. N. Exon Smith llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) { 420e1b7f22bSDuncan P. N. Exon Smith // Stat of the file and return nullptr if it doesn't exist. 421e1b7f22bSDuncan P. N. Exon Smith llvm::vfs::Status Status; 422e1b7f22bSDuncan P. N. Exon Smith if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr)) 423e1b7f22bSDuncan P. N. Exon Smith return None; 424e1b7f22bSDuncan P. N. Exon Smith 425917acac9SDuncan P. N. Exon Smith if (!SeenBypassFileEntries) 426917acac9SDuncan P. N. Exon Smith SeenBypassFileEntries = std::make_unique< 427917acac9SDuncan P. N. Exon Smith llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>(); 428917acac9SDuncan P. N. Exon Smith 429917acac9SDuncan P. N. Exon Smith // If we've already bypassed just use the existing one. 430917acac9SDuncan P. N. Exon Smith auto Insertion = SeenBypassFileEntries->insert( 431917acac9SDuncan P. N. Exon Smith {VF.getName(), std::errc::no_such_file_or_directory}); 432917acac9SDuncan P. N. Exon Smith if (!Insertion.second) 433917acac9SDuncan P. N. Exon Smith return FileEntryRef(*Insertion.first); 434917acac9SDuncan P. N. Exon Smith 435917acac9SDuncan P. N. Exon Smith // Fill in the new entry from the stat. 436e1b7f22bSDuncan P. N. Exon Smith BypassFileEntries.push_back(std::make_unique<FileEntry>()); 437e1b7f22bSDuncan P. N. Exon Smith const FileEntry &VFE = VF.getFileEntry(); 438e1b7f22bSDuncan P. N. Exon Smith FileEntry &BFE = *BypassFileEntries.back(); 4391b042de5SDuncan P. N. Exon Smith Insertion.first->second = FileEntryRef::MapValue(BFE, VF.getDir()); 440917acac9SDuncan P. N. Exon Smith BFE.LastRef = FileEntryRef(*Insertion.first); 441e1b7f22bSDuncan P. N. Exon Smith BFE.Size = Status.getSize(); 442e1b7f22bSDuncan P. N. Exon Smith BFE.Dir = VFE.Dir; 443e1b7f22bSDuncan P. N. Exon Smith BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 444e1b7f22bSDuncan P. N. Exon Smith BFE.UID = NextFileUID++; 445e1b7f22bSDuncan P. N. Exon Smith BFE.IsValid = true; 446917acac9SDuncan P. N. Exon Smith 447917acac9SDuncan P. N. Exon Smith // Save the entry in the bypass table and return. 448917acac9SDuncan P. N. Exon Smith return FileEntryRef(*Insertion.first); 449e1b7f22bSDuncan P. N. Exon Smith } 450e1b7f22bSDuncan P. N. Exon Smith 451c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 4520e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 453b5c356a4SAnders Carlsson 4549ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 4559ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 456c56419edSArgyrios Kyrtzidis return false; 45771731d6bSArgyrios Kyrtzidis 4582c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 459b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 4606e640998SChris Lattner path = NewPath; 461c56419edSArgyrios Kyrtzidis return true; 462c56419edSArgyrios Kyrtzidis } 463c56419edSArgyrios Kyrtzidis 464c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 465c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path); 466c56419edSArgyrios Kyrtzidis 467c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 46847035c02SIlya Biryukov FS->makeAbsolute(Path); 469c56419edSArgyrios Kyrtzidis Changed = true; 470c56419edSArgyrios Kyrtzidis } 471c56419edSArgyrios Kyrtzidis 472c56419edSArgyrios Kyrtzidis return Changed; 4736e640998SChris Lattner } 4746e640998SChris Lattner 475e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) { 476e9870c0cSKadir Cetinkaya llvm::SmallString<128> AbsPath(FileName); 477e9870c0cSKadir Cetinkaya // This is not the same as `VFS::getRealPath()`, which resolves symlinks 478e9870c0cSKadir Cetinkaya // but can be very expensive on real file systems. 479e9870c0cSKadir Cetinkaya // FIXME: the semantic of RealPathName is unclear, and the name might be 480e9870c0cSKadir Cetinkaya // misleading. We need to clean up the interface here. 481e9870c0cSKadir Cetinkaya makeAbsolutePath(AbsPath); 482e9870c0cSKadir Cetinkaya llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true); 483adcd0268SBenjamin Kramer UFE->RealPathName = std::string(AbsPath.str()); 484e9870c0cSKadir Cetinkaya } 485e9870c0cSKadir Cetinkaya 486a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 48792e8af0eSMichael Spencer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 48892e8af0eSMichael Spencer bool RequiresNullTerminator) { 4896d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4906d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4916d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 492*245218bbSDuncan P. N. Exon Smith if (isVolatile || Entry->isNamedPipe()) 4936d7833f1SArgyrios Kyrtzidis FileSize = -1; 4946d7833f1SArgyrios Kyrtzidis 495004b9c7aSMehdi Amini StringRef Filename = Entry->getName(); 4965ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 497c8130a74SBen Langmuir if (Entry->File) { 49892e8af0eSMichael Spencer auto Result = Entry->File->getBuffer(Filename, FileSize, 49992e8af0eSMichael Spencer RequiresNullTerminator, isVolatile); 500c8130a74SBen Langmuir Entry->closeFile(); 5016406f7b8SRafael Espindola return Result; 5025ea7d07dSChris Lattner } 5036e640998SChris Lattner 5045ea7d07dSChris Lattner // Otherwise, open the file. 50592e8af0eSMichael Spencer return getBufferForFileImpl(Filename, FileSize, isVolatile, 50692e8af0eSMichael Spencer RequiresNullTerminator); 507894b8d1dSDuncan P. N. Exon Smith } 508669b0b15SArgyrios Kyrtzidis 509894b8d1dSDuncan P. N. Exon Smith llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 510894b8d1dSDuncan P. N. Exon Smith FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, 51192e8af0eSMichael Spencer bool isVolatile, 51292e8af0eSMichael Spencer bool RequiresNullTerminator) { 513a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 51492e8af0eSMichael Spencer return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator, 51592e8af0eSMichael Spencer isVolatile); 5165ea7d07dSChris Lattner 517894b8d1dSDuncan P. N. Exon Smith SmallString<128> FilePath(Filename); 518878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 51992e8af0eSMichael Spencer return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator, 52092e8af0eSMichael Spencer isVolatile); 52126b5c190SChris Lattner } 52226b5c190SChris Lattner 523e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 524e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 525e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 526e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 527e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 528461f0722SHarlan Haskins std::error_code 529461f0722SHarlan Haskins FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status, 530461f0722SHarlan Haskins bool isFile, std::unique_ptr<llvm::vfs::File> *F) { 531226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 532226efd35SChris Lattner // absolute! 5335769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 534461f0722SHarlan Haskins return FileSystemStatCache::get(Path, Status, isFile, F, 535461f0722SHarlan Haskins StatCache.get(), *FS); 536226efd35SChris Lattner 5372c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 538878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 53971731d6bSArgyrios Kyrtzidis 540461f0722SHarlan Haskins return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F, 541461f0722SHarlan Haskins StatCache.get(), *FS); 54271731d6bSArgyrios Kyrtzidis } 54371731d6bSArgyrios Kyrtzidis 544461f0722SHarlan Haskins std::error_code 545461f0722SHarlan Haskins FileManager::getNoncachedStatValue(StringRef Path, 546fc51490bSJonas Devlieghere llvm::vfs::Status &Result) { 5472c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 5485e368405SAnders Carlsson FixupRelativePath(FilePath); 5495e368405SAnders Carlsson 550fc51490bSJonas Devlieghere llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str()); 551c8130a74SBen Langmuir if (!S) 552461f0722SHarlan Haskins return S.getError(); 553c8130a74SBen Langmuir Result = *S; 554461f0722SHarlan Haskins return std::error_code(); 5555e368405SAnders Carlsson } 5565e368405SAnders Carlsson 55709b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 5580e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 55909b6989eSDouglas Gregor UIDToFiles.clear(); 56009b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 56109b6989eSDouglas Gregor 56209b6989eSDouglas Gregor // Map file entries 563917acac9SDuncan P. N. Exon Smith for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>, 564461f0722SHarlan Haskins llvm::BumpPtrAllocator>::const_iterator 5654dc5573aSAlex Lorenz FE = SeenFileEntries.begin(), 5664dc5573aSAlex Lorenz FEEnd = SeenFileEntries.end(); 56709b6989eSDouglas Gregor FE != FEEnd; ++FE) 568917acac9SDuncan P. N. Exon Smith if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) { 569917acac9SDuncan P. N. Exon Smith if (const auto *FE = Entry->V.dyn_cast<FileEntry *>()) 5704dc5573aSAlex Lorenz UIDToFiles[FE->getUID()] = FE; 571461f0722SHarlan Haskins } 57209b6989eSDouglas Gregor 57309b6989eSDouglas Gregor // Map virtual file entries 574d2725a31SDavid Blaikie for (const auto &VFE : VirtualFileEntries) 575d2725a31SDavid Blaikie UIDToFiles[VFE->getUID()] = VFE.get(); 57609b6989eSDouglas Gregor } 577226efd35SChris Lattner 578e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 579e8efac4bSKarl-Johan Karlsson llvm::DenseMap<const void *, llvm::StringRef>::iterator Known 580e8efac4bSKarl-Johan Karlsson = CanonicalNames.find(Dir); 581e8efac4bSKarl-Johan Karlsson if (Known != CanonicalNames.end()) 582e00c8b20SDouglas Gregor return Known->second; 583e00c8b20SDouglas Gregor 584e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 58554cc3c2fSRichard Smith 5865fb18fecSEric Liu SmallString<4096> CanonicalNameBuf; 5875fb18fecSEric Liu if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf)) 588da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 589e00c8b20SDouglas Gregor 590e8efac4bSKarl-Johan Karlsson CanonicalNames.insert({Dir, CanonicalName}); 591e8efac4bSKarl-Johan Karlsson return CanonicalName; 592e8efac4bSKarl-Johan Karlsson } 593e8efac4bSKarl-Johan Karlsson 594e8efac4bSKarl-Johan Karlsson StringRef FileManager::getCanonicalName(const FileEntry *File) { 595e8efac4bSKarl-Johan Karlsson llvm::DenseMap<const void *, llvm::StringRef>::iterator Known 596e8efac4bSKarl-Johan Karlsson = CanonicalNames.find(File); 597e8efac4bSKarl-Johan Karlsson if (Known != CanonicalNames.end()) 598e8efac4bSKarl-Johan Karlsson return Known->second; 599e8efac4bSKarl-Johan Karlsson 600e8efac4bSKarl-Johan Karlsson StringRef CanonicalName(File->getName()); 601e8efac4bSKarl-Johan Karlsson 602e8efac4bSKarl-Johan Karlsson SmallString<4096> CanonicalNameBuf; 603e8efac4bSKarl-Johan Karlsson if (!FS->getRealPath(File->getName(), CanonicalNameBuf)) 604e8efac4bSKarl-Johan Karlsson CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 605e8efac4bSKarl-Johan Karlsson 606e8efac4bSKarl-Johan Karlsson CanonicalNames.insert({File, CanonicalName}); 607e00c8b20SDouglas Gregor return CanonicalName; 608e00c8b20SDouglas Gregor } 609226efd35SChris Lattner 6107a51313dSChris Lattner void FileManager::PrintStats() const { 61189b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 612e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 613e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 614e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 615e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 61689b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 6177a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 61889b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 6197a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 6207a51313dSChris Lattner 62189b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 6227a51313dSChris Lattner } 623