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 110*0377ca64SAlex Lorenz llvm::Expected<DirectoryEntryRef> 111*0377ca64SAlex Lorenz FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) { 1128bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 11332f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 11432f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1158bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1168bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1178bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 11832f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 1191865df49SNico Weber #ifdef _WIN32 120ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 121ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 122ee30546cSRafael Espindola std::string DirNameStr; 123ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 124ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 125ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 126ee30546cSRafael Espindola DirName = DirNameStr; 127ee30546cSRafael Espindola } 128ee30546cSRafael Espindola #endif 12932f1acf1SNAKAMURA Takumi 1307a51313dSChris Lattner ++NumDirLookups; 1317a51313dSChris Lattner 132e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 133e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 134461f0722SHarlan Haskins auto SeenDirInsertResult = 135461f0722SHarlan Haskins SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory}); 136*0377ca64SAlex Lorenz if (!SeenDirInsertResult.second) { 137*0377ca64SAlex Lorenz if (SeenDirInsertResult.first->second) 138*0377ca64SAlex Lorenz return DirectoryEntryRef(&*SeenDirInsertResult.first); 139*0377ca64SAlex Lorenz return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError()); 140*0377ca64SAlex Lorenz } 1417a51313dSChris Lattner 142018ab5faSRichard Smith // We've not seen this before. Fill it in. 1437a51313dSChris Lattner ++NumDirCacheMisses; 144018ab5faSRichard Smith auto &NamedDirEnt = *SeenDirInsertResult.first; 145018ab5faSRichard Smith assert(!NamedDirEnt.second && "should be newly-created"); 1467a51313dSChris Lattner 1477a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 148e1dd3e2cSZhanyong Wan // SeenDirEntries map. 1490df59d8cSMehdi Amini StringRef InterndDirName = NamedDirEnt.first(); 1507a51313dSChris Lattner 1517a51313dSChris Lattner // Check to see if the directory exists. 15206f64d53SHarlan Haskins llvm::vfs::Status Status; 153461f0722SHarlan Haskins auto statError = getStatValue(InterndDirName, Status, false, 154461f0722SHarlan Haskins nullptr /*directory lookup*/); 155461f0722SHarlan Haskins if (statError) { 156e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 157461f0722SHarlan Haskins if (CacheFailure) 158461f0722SHarlan Haskins NamedDirEnt.second = statError; 159461f0722SHarlan Haskins else 1601735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 161*0377ca64SAlex Lorenz return llvm::errorCodeToError(statError); 162e1dd3e2cSZhanyong Wan } 1637a51313dSChris Lattner 164e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 165e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 166e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 167e1dd3e2cSZhanyong Wan // Windows). 16806f64d53SHarlan Haskins DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()]; 1697a51313dSChris Lattner 170461f0722SHarlan Haskins NamedDirEnt.second = UDE; 1710df59d8cSMehdi Amini if (UDE.getName().empty()) { 172e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 173e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 1747a51313dSChris Lattner UDE.Name = InterndDirName; 175e1dd3e2cSZhanyong Wan } 176e1dd3e2cSZhanyong Wan 177*0377ca64SAlex Lorenz return DirectoryEntryRef(&NamedDirEnt); 178*0377ca64SAlex Lorenz } 179*0377ca64SAlex Lorenz 180*0377ca64SAlex Lorenz llvm::ErrorOr<const DirectoryEntry *> 181*0377ca64SAlex Lorenz FileManager::getDirectory(StringRef DirName, bool CacheFailure) { 182*0377ca64SAlex Lorenz auto Result = getDirectoryRef(DirName, CacheFailure); 183*0377ca64SAlex Lorenz if (Result) 184*0377ca64SAlex Lorenz return &Result->getDirEntry(); 185*0377ca64SAlex Lorenz return llvm::errorToErrorCode(Result.takeError()); 1867a51313dSChris Lattner } 1877a51313dSChris Lattner 188461f0722SHarlan Haskins llvm::ErrorOr<const FileEntry *> 189461f0722SHarlan Haskins FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) { 1904dc5573aSAlex Lorenz auto Result = getFileRef(Filename, openFile, CacheFailure); 1914dc5573aSAlex Lorenz if (Result) 1924dc5573aSAlex Lorenz return &Result->getFileEntry(); 1939ef6c49bSDuncan P. N. Exon Smith return llvm::errorToErrorCode(Result.takeError()); 1944dc5573aSAlex Lorenz } 1954dc5573aSAlex Lorenz 1969ef6c49bSDuncan P. N. Exon Smith llvm::Expected<FileEntryRef> 1974dc5573aSAlex Lorenz FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) { 1987a51313dSChris Lattner ++NumFileLookups; 1997a51313dSChris Lattner 2007a51313dSChris Lattner // See if there is already an entry in the map. 201461f0722SHarlan Haskins auto SeenFileInsertResult = 202461f0722SHarlan Haskins SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory}); 2034dc5573aSAlex Lorenz if (!SeenFileInsertResult.second) { 2044dc5573aSAlex Lorenz if (!SeenFileInsertResult.first->second) 2059ef6c49bSDuncan P. N. Exon Smith return llvm::errorCodeToError( 2069ef6c49bSDuncan P. N. Exon Smith SeenFileInsertResult.first->second.getError()); 2074dc5573aSAlex Lorenz // Construct and return and FileEntryRef, unless it's a redirect to another 2084dc5573aSAlex Lorenz // filename. 2094dc5573aSAlex Lorenz SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second; 2104dc5573aSAlex Lorenz FileEntry *FE; 2114dc5573aSAlex Lorenz if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>())) 2124dc5573aSAlex Lorenz return FileEntryRef(SeenFileInsertResult.first->first(), *FE); 2134dc5573aSAlex Lorenz return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure); 2144dc5573aSAlex Lorenz } 2157a51313dSChris Lattner 216018ab5faSRichard Smith // We've not seen this before. Fill it in. 217e84385feSSam McCall ++NumFileCacheMisses; 218018ab5faSRichard Smith auto &NamedFileEnt = *SeenFileInsertResult.first; 219018ab5faSRichard Smith assert(!NamedFileEnt.second && "should be newly-created"); 220fa361206SSam McCall 2217a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 222e1dd3e2cSZhanyong Wan // SeenFileEntries map. 2230df59d8cSMehdi Amini StringRef InterndFileName = NamedFileEnt.first(); 2247a51313dSChris Lattner 225966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 226966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 227966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 228966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 229966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 230461f0722SHarlan Haskins auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure); 231461f0722SHarlan Haskins if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist. 232461f0722SHarlan Haskins if (CacheFailure) 233461f0722SHarlan Haskins NamedFileEnt.second = DirInfoOrErr.getError(); 234461f0722SHarlan Haskins else 2351735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2361735f4e7SDouglas Gregor 2379ef6c49bSDuncan P. N. Exon Smith return llvm::errorCodeToError(DirInfoOrErr.getError()); 2381735f4e7SDouglas Gregor } 239461f0722SHarlan Haskins const DirectoryEntry *DirInfo = *DirInfoOrErr; 240407e2124SDouglas Gregor 2417a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2427a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2437a51313dSChris Lattner 244018ab5faSRichard Smith // Check to see if the file exists. 245fc51490bSJonas Devlieghere std::unique_ptr<llvm::vfs::File> F; 24606f64d53SHarlan Haskins llvm::vfs::Status Status; 247461f0722SHarlan Haskins auto statError = getStatValue(InterndFileName, Status, true, 248461f0722SHarlan Haskins openFile ? &F : nullptr); 249461f0722SHarlan Haskins if (statError) { 250e1dd3e2cSZhanyong Wan // There's no real file at the given path. 251461f0722SHarlan Haskins if (CacheFailure) 252461f0722SHarlan Haskins NamedFileEnt.second = statError; 253461f0722SHarlan Haskins else 2541735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2551735f4e7SDouglas Gregor 2569ef6c49bSDuncan P. N. Exon Smith return llvm::errorCodeToError(statError); 257e1dd3e2cSZhanyong Wan } 2587a51313dSChris Lattner 259ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 260d6278e32SArgyrios Kyrtzidis 2617a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2627a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 26306f64d53SHarlan Haskins FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()]; 2647a51313dSChris Lattner 2654dc5573aSAlex Lorenz NamedFileEnt.second = &UFE; 266ab86fbe4SBen Langmuir 267ab86fbe4SBen Langmuir // If the name returned by getStatValue is different than Filename, re-intern 268ab86fbe4SBen Langmuir // the name. 26906f64d53SHarlan Haskins if (Status.getName() != Filename) { 27098f9e94eSRichard Smith auto &NewNamedFileEnt = 2714dc5573aSAlex Lorenz *SeenFileEntries.insert({Status.getName(), &UFE}).first; 27298f9e94eSRichard Smith assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE && 273ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file"); 27498f9e94eSRichard Smith InterndFileName = NewNamedFileEnt.first().data(); 2754dc5573aSAlex Lorenz // In addition to re-interning the name, construct a redirecting seen file 2764dc5573aSAlex Lorenz // entry, that will point to the name the filesystem actually wants to use. 2774dc5573aSAlex Lorenz StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName); 27898f9e94eSRichard Smith NamedFileEnt.second = Redirect; 279ab86fbe4SBen Langmuir } 280ab86fbe4SBen Langmuir 281c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2825de00f3bSBen Langmuir 2835de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 2845de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 2855de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 2865de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 2875de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 2885de00f3bSBen Langmuir // multiple names. 28906f64d53SHarlan Haskins if (DirInfo != UFE.Dir && Status.IsVFSMapped) 2905de00f3bSBen Langmuir UFE.Dir = DirInfo; 2915de00f3bSBen Langmuir 292c0ff9908SManuel Klimek // Always update the name to use the last name by which a file was accessed. 293c0ff9908SManuel Klimek // FIXME: Neither this nor always using the first name is correct; we want 294c0ff9908SManuel Klimek // to switch towards a design where we return a FileName object that 295c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the 296c0ff9908SManuel Klimek // corresponding FileEntry. 2974dc5573aSAlex Lorenz // FIXME: The Name should be removed from FileEntry once all clients 2984dc5573aSAlex Lorenz // adopt FileEntryRef. 299ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 300c0ff9908SManuel Klimek 3014dc5573aSAlex Lorenz return FileEntryRef(InterndFileName, UFE); 302dd278430SChris Lattner } 3037a51313dSChris Lattner 304c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 305ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 30606f64d53SHarlan Haskins UFE.Size = Status.getSize(); 30706f64d53SHarlan Haskins UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 3087a51313dSChris Lattner UFE.Dir = DirInfo; 3097a51313dSChris Lattner UFE.UID = NextFileUID++; 31006f64d53SHarlan Haskins UFE.UniqueID = Status.getUniqueID(); 31106f64d53SHarlan Haskins UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 312fa361206SSam McCall UFE.File = std::move(F); 313c8a71468SBen Langmuir UFE.IsValid = true; 314ddbabc6bSSimon Marchi 315fa361206SSam McCall if (UFE.File) { 316fa361206SSam McCall if (auto PathName = UFE.File->getName()) 317fa361206SSam McCall fillRealPathName(&UFE, *PathName); 318cd8607dbSJan Korous } else if (!openFile) { 319cd8607dbSJan Korous // We should still fill the path even if we aren't opening the file. 320cd8607dbSJan Korous fillRealPathName(&UFE, InterndFileName); 321fa361206SSam McCall } 3224dc5573aSAlex Lorenz return FileEntryRef(InterndFileName, UFE); 3237a51313dSChris Lattner } 3247a51313dSChris Lattner 325407e2124SDouglas Gregor const FileEntry * 3260e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3275159f616SChris Lattner time_t ModificationTime) { 328407e2124SDouglas Gregor ++NumFileLookups; 329407e2124SDouglas Gregor 330018ab5faSRichard Smith // See if there is already an entry in the map for an existing file. 331461f0722SHarlan Haskins auto &NamedFileEnt = *SeenFileEntries.insert( 332461f0722SHarlan Haskins {Filename, std::errc::no_such_file_or_directory}).first; 3334dc5573aSAlex Lorenz if (NamedFileEnt.second) { 3344dc5573aSAlex Lorenz SeenFileEntryOrRedirect Value = *NamedFileEnt.second; 3354dc5573aSAlex Lorenz FileEntry *FE; 3364dc5573aSAlex Lorenz if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>())) 3374dc5573aSAlex Lorenz return FE; 3384dc5573aSAlex Lorenz return getVirtualFile(*Value.get<const StringRef *>(), Size, 3394dc5573aSAlex Lorenz ModificationTime); 3404dc5573aSAlex Lorenz } 341407e2124SDouglas Gregor 342018ab5faSRichard Smith // We've not seen this before, or the file is cached as non-existent. 343407e2124SDouglas Gregor ++NumFileCacheMisses; 344e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 345f1186c5aSCraig Topper FileEntry *UFE = nullptr; 346e1dd3e2cSZhanyong Wan 347e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 348e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 349e1dd3e2cSZhanyong Wan // cache. 350461f0722SHarlan Haskins auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true); 351e1dd3e2cSZhanyong Wan assert(DirInfo && 352e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 353e1dd3e2cSZhanyong Wan 354606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 35506f64d53SHarlan Haskins llvm::vfs::Status Status; 35613156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 357461f0722SHarlan Haskins if (!getStatValue(InterndFileName, Status, true, nullptr)) { 35806f64d53SHarlan Haskins UFE = &UniqueRealFiles[Status.getUniqueID()]; 35906f64d53SHarlan Haskins Status = llvm::vfs::Status( 36006f64d53SHarlan Haskins Status.getName(), Status.getUniqueID(), 36106f64d53SHarlan Haskins llvm::sys::toTimePoint(ModificationTime), 36206f64d53SHarlan Haskins Status.getUser(), Status.getGroup(), Size, 36306f64d53SHarlan Haskins Status.getType(), Status.getPermissions()); 364606c4ac3SDouglas Gregor 3654dc5573aSAlex Lorenz NamedFileEnt.second = UFE; 366606c4ac3SDouglas Gregor 367606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 368606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 369606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 370c8130a74SBen Langmuir if (UFE->File) 371c8130a74SBen Langmuir UFE->closeFile(); 372606c4ac3SDouglas Gregor 373606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 374c8a71468SBen Langmuir if (UFE->isValid()) 375606c4ac3SDouglas Gregor return UFE; 376c9b7234eSBen Langmuir 37706f64d53SHarlan Haskins UFE->UniqueID = Status.getUniqueID(); 37806f64d53SHarlan Haskins UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 37906f64d53SHarlan Haskins fillRealPathName(UFE, Status.getName()); 380018ab5faSRichard Smith } else { 3812b3d49b6SJonas Devlieghere VirtualFileEntries.push_back(std::make_unique<FileEntry>()); 382d2725a31SDavid Blaikie UFE = VirtualFileEntries.back().get(); 3834dc5573aSAlex Lorenz NamedFileEnt.second = UFE; 384606c4ac3SDouglas Gregor } 385407e2124SDouglas Gregor 3869624b695SChris Lattner UFE->Name = InterndFileName; 387407e2124SDouglas Gregor UFE->Size = Size; 388407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 389461f0722SHarlan Haskins UFE->Dir = *DirInfo; 390407e2124SDouglas Gregor UFE->UID = NextFileUID++; 391dfffaf57SErik Verbruggen UFE->IsValid = true; 392c8130a74SBen Langmuir UFE->File.reset(); 393407e2124SDouglas Gregor return UFE; 394407e2124SDouglas Gregor } 395407e2124SDouglas Gregor 396e1b7f22bSDuncan P. N. Exon Smith llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) { 397e1b7f22bSDuncan P. N. Exon Smith // Stat of the file and return nullptr if it doesn't exist. 398e1b7f22bSDuncan P. N. Exon Smith llvm::vfs::Status Status; 399e1b7f22bSDuncan P. N. Exon Smith if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr)) 400e1b7f22bSDuncan P. N. Exon Smith return None; 401e1b7f22bSDuncan P. N. Exon Smith 402e1b7f22bSDuncan P. N. Exon Smith // Fill it in from the stat. 403e1b7f22bSDuncan P. N. Exon Smith BypassFileEntries.push_back(std::make_unique<FileEntry>()); 404e1b7f22bSDuncan P. N. Exon Smith const FileEntry &VFE = VF.getFileEntry(); 405e1b7f22bSDuncan P. N. Exon Smith FileEntry &BFE = *BypassFileEntries.back(); 406e1b7f22bSDuncan P. N. Exon Smith BFE.Name = VFE.getName(); 407e1b7f22bSDuncan P. N. Exon Smith BFE.Size = Status.getSize(); 408e1b7f22bSDuncan P. N. Exon Smith BFE.Dir = VFE.Dir; 409e1b7f22bSDuncan P. N. Exon Smith BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 410e1b7f22bSDuncan P. N. Exon Smith BFE.UID = NextFileUID++; 411e1b7f22bSDuncan P. N. Exon Smith BFE.IsValid = true; 412e1b7f22bSDuncan P. N. Exon Smith return FileEntryRef(VF.getName(), BFE); 413e1b7f22bSDuncan P. N. Exon Smith } 414e1b7f22bSDuncan P. N. Exon Smith 415c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 4160e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 417b5c356a4SAnders Carlsson 4189ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 4199ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 420c56419edSArgyrios Kyrtzidis return false; 42171731d6bSArgyrios Kyrtzidis 4222c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 423b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 4246e640998SChris Lattner path = NewPath; 425c56419edSArgyrios Kyrtzidis return true; 426c56419edSArgyrios Kyrtzidis } 427c56419edSArgyrios Kyrtzidis 428c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 429c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path); 430c56419edSArgyrios Kyrtzidis 431c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 43247035c02SIlya Biryukov FS->makeAbsolute(Path); 433c56419edSArgyrios Kyrtzidis Changed = true; 434c56419edSArgyrios Kyrtzidis } 435c56419edSArgyrios Kyrtzidis 436c56419edSArgyrios Kyrtzidis return Changed; 4376e640998SChris Lattner } 4386e640998SChris Lattner 439e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) { 440e9870c0cSKadir Cetinkaya llvm::SmallString<128> AbsPath(FileName); 441e9870c0cSKadir Cetinkaya // This is not the same as `VFS::getRealPath()`, which resolves symlinks 442e9870c0cSKadir Cetinkaya // but can be very expensive on real file systems. 443e9870c0cSKadir Cetinkaya // FIXME: the semantic of RealPathName is unclear, and the name might be 444e9870c0cSKadir Cetinkaya // misleading. We need to clean up the interface here. 445e9870c0cSKadir Cetinkaya makeAbsolutePath(AbsPath); 446e9870c0cSKadir Cetinkaya llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true); 447e9870c0cSKadir Cetinkaya UFE->RealPathName = AbsPath.str(); 448e9870c0cSKadir Cetinkaya } 449e9870c0cSKadir Cetinkaya 450a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 451122705b9SDuncan P. N. Exon Smith FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile) { 4526d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4536d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4546d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 4556d7833f1SArgyrios Kyrtzidis if (isVolatile) 4566d7833f1SArgyrios Kyrtzidis FileSize = -1; 4576d7833f1SArgyrios Kyrtzidis 458004b9c7aSMehdi Amini StringRef Filename = Entry->getName(); 4595ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 460c8130a74SBen Langmuir if (Entry->File) { 461a885796dSBenjamin Kramer auto Result = 462a885796dSBenjamin Kramer Entry->File->getBuffer(Filename, FileSize, 46326d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 464c8130a74SBen Langmuir Entry->closeFile(); 4656406f7b8SRafael Espindola return Result; 4665ea7d07dSChris Lattner } 4676e640998SChris Lattner 4685ea7d07dSChris Lattner // Otherwise, open the file. 469894b8d1dSDuncan P. N. Exon Smith return getBufferForFileImpl(Filename, FileSize, isVolatile); 470894b8d1dSDuncan P. N. Exon Smith } 471669b0b15SArgyrios Kyrtzidis 472894b8d1dSDuncan P. N. Exon Smith llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 473894b8d1dSDuncan P. N. Exon Smith FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, 474894b8d1dSDuncan P. N. Exon Smith bool isVolatile) { 475a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 476a885796dSBenjamin Kramer return FS->getBufferForFile(Filename, FileSize, 47726d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4785ea7d07dSChris Lattner 479894b8d1dSDuncan P. N. Exon Smith SmallString<128> FilePath(Filename); 480878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 48192e1b62dSYaron Keren return FS->getBufferForFile(FilePath, FileSize, 48226d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 48326b5c190SChris Lattner } 48426b5c190SChris Lattner 485e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 486e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 487e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 488e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 489e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 490461f0722SHarlan Haskins std::error_code 491461f0722SHarlan Haskins FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status, 492461f0722SHarlan Haskins bool isFile, std::unique_ptr<llvm::vfs::File> *F) { 493226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 494226efd35SChris Lattner // absolute! 4955769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 496461f0722SHarlan Haskins return FileSystemStatCache::get(Path, Status, isFile, F, 497461f0722SHarlan Haskins StatCache.get(), *FS); 498226efd35SChris Lattner 4992c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 500878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 50171731d6bSArgyrios Kyrtzidis 502461f0722SHarlan Haskins return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F, 503461f0722SHarlan Haskins StatCache.get(), *FS); 50471731d6bSArgyrios Kyrtzidis } 50571731d6bSArgyrios Kyrtzidis 506461f0722SHarlan Haskins std::error_code 507461f0722SHarlan Haskins FileManager::getNoncachedStatValue(StringRef Path, 508fc51490bSJonas Devlieghere llvm::vfs::Status &Result) { 5092c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 5105e368405SAnders Carlsson FixupRelativePath(FilePath); 5115e368405SAnders Carlsson 512fc51490bSJonas Devlieghere llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str()); 513c8130a74SBen Langmuir if (!S) 514461f0722SHarlan Haskins return S.getError(); 515c8130a74SBen Langmuir Result = *S; 516461f0722SHarlan Haskins return std::error_code(); 5175e368405SAnders Carlsson } 5185e368405SAnders Carlsson 51909b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 5200e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 52109b6989eSDouglas Gregor UIDToFiles.clear(); 52209b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 52309b6989eSDouglas Gregor 52409b6989eSDouglas Gregor // Map file entries 5254dc5573aSAlex Lorenz for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>, 526461f0722SHarlan Haskins llvm::BumpPtrAllocator>::const_iterator 5274dc5573aSAlex Lorenz FE = SeenFileEntries.begin(), 5284dc5573aSAlex Lorenz FEEnd = SeenFileEntries.end(); 52909b6989eSDouglas Gregor FE != FEEnd; ++FE) 5304dc5573aSAlex Lorenz if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) { 5314dc5573aSAlex Lorenz if (const auto *FE = (*Entry).dyn_cast<FileEntry *>()) 5324dc5573aSAlex Lorenz UIDToFiles[FE->getUID()] = FE; 533461f0722SHarlan Haskins } 53409b6989eSDouglas Gregor 53509b6989eSDouglas Gregor // Map virtual file entries 536d2725a31SDavid Blaikie for (const auto &VFE : VirtualFileEntries) 537d2725a31SDavid Blaikie UIDToFiles[VFE->getUID()] = VFE.get(); 53809b6989eSDouglas Gregor } 539226efd35SChris Lattner 540e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 541e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 542e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 543e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 544e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 545e00c8b20SDouglas Gregor return Known->second; 546e00c8b20SDouglas Gregor 547e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 54854cc3c2fSRichard Smith 5495fb18fecSEric Liu SmallString<4096> CanonicalNameBuf; 5505fb18fecSEric Liu if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf)) 551da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 552e00c8b20SDouglas Gregor 553018ab5faSRichard Smith CanonicalDirNames.insert({Dir, CanonicalName}); 554e00c8b20SDouglas Gregor return CanonicalName; 555e00c8b20SDouglas Gregor } 556226efd35SChris Lattner 5577a51313dSChris Lattner void FileManager::PrintStats() const { 55889b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 559e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 560e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 561e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 562e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 56389b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 5647a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 56589b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 5667a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 5677a51313dSChris Lattner 56889b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 5697a51313dSChris Lattner } 570