1226efd35SChris Lattner //===--- FileManager.cpp - File System Probing and Caching ----------------===// 27a51313dSChris Lattner // 37a51313dSChris Lattner // The LLVM Compiler Infrastructure 47a51313dSChris Lattner // 57a51313dSChris Lattner // This file is distributed under the University of Illinois Open Source 67a51313dSChris Lattner // License. See LICENSE.TXT for details. 77a51313dSChris Lattner // 87a51313dSChris Lattner //===----------------------------------------------------------------------===// 97a51313dSChris Lattner // 107a51313dSChris Lattner // This file implements the FileManager interface. 117a51313dSChris Lattner // 127a51313dSChris Lattner //===----------------------------------------------------------------------===// 137a51313dSChris Lattner // 147a51313dSChris Lattner // TODO: This should index all interesting directories with dirent calls. 157a51313dSChris Lattner // getdirentries ? 167a51313dSChris Lattner // opendir/readdir_r/closedir ? 177a51313dSChris Lattner // 187a51313dSChris Lattner //===----------------------------------------------------------------------===// 197a51313dSChris Lattner 207a51313dSChris Lattner #include "clang/Basic/FileManager.h" 21226efd35SChris Lattner #include "clang/Basic/FileSystemStatCache.h" 227a51313dSChris Lattner #include "llvm/ADT/SmallString.h" 233a02247dSChandler Carruth #include "llvm/Config/llvm-config.h" 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" 2826db6481SBenjamin Kramer #include <map> 2926db6481SBenjamin Kramer #include <set> 3026db6481SBenjamin Kramer #include <string> 318a8e554aSRafael Espindola #include <system_error> 32278038b4SChris Lattner 337a51313dSChris Lattner using namespace clang; 347a51313dSChris Lattner 357a51313dSChris Lattner /// NON_EXISTENT_DIR - A special value distinct from null that is used to 367a51313dSChris Lattner /// represent a dir name that doesn't exist on the disk. 377a51313dSChris Lattner #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) 387a51313dSChris Lattner 399624b695SChris Lattner /// NON_EXISTENT_FILE - A special value distinct from null that is used to 409624b695SChris Lattner /// represent a filename that doesn't exist on the disk. 419624b695SChris Lattner #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) 429624b695SChris Lattner 435c04bd81STed Kremenek //===----------------------------------------------------------------------===// 445c04bd81STed Kremenek // Common logic. 455c04bd81STed Kremenek //===----------------------------------------------------------------------===// 467a51313dSChris Lattner 47c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO, 48c8130a74SBen Langmuir IntrusiveRefCntPtr<vfs::FileSystem> FS) 49c8130a74SBen Langmuir : FS(FS), FileSystemOpts(FSO), 50e1dd3e2cSZhanyong Wan SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) { 517a51313dSChris Lattner NumDirLookups = NumFileLookups = 0; 527a51313dSChris Lattner NumDirCacheMisses = NumFileCacheMisses = 0; 53c8130a74SBen Langmuir 54c8130a74SBen Langmuir // If the caller doesn't provide a virtual file system, just grab the real 55c8130a74SBen Langmuir // file system. 56c8130a74SBen Langmuir if (!FS) 57c8130a74SBen Langmuir this->FS = vfs::getRealFileSystem(); 587a51313dSChris Lattner } 597a51313dSChris Lattner 607a51313dSChris Lattner FileManager::~FileManager() { 61966b25b9SChris Lattner for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i) 62966b25b9SChris Lattner delete VirtualFileEntries[i]; 63e1dd3e2cSZhanyong Wan for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i) 64e1dd3e2cSZhanyong Wan delete VirtualDirectoryEntries[i]; 657a51313dSChris Lattner } 667a51313dSChris Lattner 6723430ccbSDavid Blaikie void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, 68226efd35SChris Lattner bool AtBeginning) { 69d2eb58abSDouglas Gregor assert(statCache && "No stat cache provided?"); 70f1186c5aSCraig Topper if (AtBeginning || !StatCache.get()) { 7123430ccbSDavid Blaikie statCache->setNextStatCache(std::move(StatCache)); 7223430ccbSDavid Blaikie StatCache = std::move(statCache); 73d2eb58abSDouglas Gregor return; 74d2eb58abSDouglas Gregor } 75d2eb58abSDouglas Gregor 76226efd35SChris Lattner FileSystemStatCache *LastCache = StatCache.get(); 77d2eb58abSDouglas Gregor while (LastCache->getNextStatCache()) 78d2eb58abSDouglas Gregor LastCache = LastCache->getNextStatCache(); 79d2eb58abSDouglas Gregor 8023430ccbSDavid Blaikie LastCache->setNextStatCache(std::move(statCache)); 81d2eb58abSDouglas Gregor } 82d2eb58abSDouglas Gregor 83226efd35SChris Lattner void FileManager::removeStatCache(FileSystemStatCache *statCache) { 84d2eb58abSDouglas Gregor if (!statCache) 85d2eb58abSDouglas Gregor return; 86d2eb58abSDouglas Gregor 87d2eb58abSDouglas Gregor if (StatCache.get() == statCache) { 88d2eb58abSDouglas Gregor // This is the first stat cache. 89dd0e1e8dSDavid Blaikie StatCache = StatCache->takeNextStatCache(); 90d2eb58abSDouglas Gregor return; 91d2eb58abSDouglas Gregor } 92d2eb58abSDouglas Gregor 93d2eb58abSDouglas Gregor // Find the stat cache in the list. 94226efd35SChris Lattner FileSystemStatCache *PrevCache = StatCache.get(); 95d2eb58abSDouglas Gregor while (PrevCache && PrevCache->getNextStatCache() != statCache) 96d2eb58abSDouglas Gregor PrevCache = PrevCache->getNextStatCache(); 979624b695SChris Lattner 989624b695SChris Lattner assert(PrevCache && "Stat cache not found for removal"); 9923430ccbSDavid Blaikie PrevCache->setNextStatCache(statCache->takeNextStatCache()); 100d2eb58abSDouglas Gregor } 101d2eb58abSDouglas Gregor 1023aad855aSManuel Klimek void FileManager::clearStatCaches() { 1033875a82dSDavid Blaikie StatCache.reset(); 1043aad855aSManuel Klimek } 1053aad855aSManuel Klimek 106407e2124SDouglas Gregor /// \brief Retrieve the directory that the given file name resides in. 107e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file. 108407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, 1091735f4e7SDouglas Gregor StringRef Filename, 1101735f4e7SDouglas Gregor bool CacheFailure) { 111f3c0ff73SZhanyong Wan if (Filename.empty()) 112f1186c5aSCraig Topper return nullptr; 113e1dd3e2cSZhanyong Wan 114f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 115f1186c5aSCraig Topper return nullptr; // If Filename is a directory. 1160c0e8040SChris Lattner 1170e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename); 1180c0e8040SChris Lattner // Use the current directory if file has no path component. 119f3c0ff73SZhanyong Wan if (DirName.empty()) 120f3c0ff73SZhanyong Wan DirName = "."; 1210c0e8040SChris Lattner 1221735f4e7SDouglas Gregor return FileMgr.getDirectory(DirName, CacheFailure); 123407e2124SDouglas Gregor } 124407e2124SDouglas Gregor 125e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or 126e1dd3e2cSZhanyong Wan /// a directory) as virtual directories. 1270e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 1280e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path); 129f3c0ff73SZhanyong Wan if (DirName.empty()) 130e1dd3e2cSZhanyong Wan return; 131e1dd3e2cSZhanyong Wan 13213156b68SDavid Blaikie auto &NamedDirEnt = 13313156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 134e1dd3e2cSZhanyong Wan 135e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors 136e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache, 137e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in 138e1dd3e2cSZhanyong Wan // the cache. 13913156b68SDavid Blaikie if (NamedDirEnt.second) 140e1dd3e2cSZhanyong Wan return; 141e1dd3e2cSZhanyong Wan 142e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache. 143e1dd3e2cSZhanyong Wan DirectoryEntry *UDE = new DirectoryEntry; 14413156b68SDavid Blaikie UDE->Name = NamedDirEnt.first().data(); 14513156b68SDavid Blaikie NamedDirEnt.second = UDE; 146e1dd3e2cSZhanyong Wan VirtualDirectoryEntries.push_back(UDE); 147e1dd3e2cSZhanyong Wan 148e1dd3e2cSZhanyong Wan // Recursively add the other ancestors. 149e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName); 150e1dd3e2cSZhanyong Wan } 151e1dd3e2cSZhanyong Wan 1521735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName, 1531735f4e7SDouglas Gregor bool CacheFailure) { 1548bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 15532f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 15632f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1578bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1588bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1598bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 16032f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 161ee30546cSRafael Espindola #ifdef LLVM_ON_WIN32 162ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 163ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 164ee30546cSRafael Espindola std::string DirNameStr; 165ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 166ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 167ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 168ee30546cSRafael Espindola DirName = DirNameStr; 169ee30546cSRafael Espindola } 170ee30546cSRafael Espindola #endif 17132f1acf1SNAKAMURA Takumi 1727a51313dSChris Lattner ++NumDirLookups; 17313156b68SDavid Blaikie auto &NamedDirEnt = 17413156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 1757a51313dSChris Lattner 176e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 177e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 17813156b68SDavid Blaikie if (NamedDirEnt.second) 17913156b68SDavid Blaikie return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr 18013156b68SDavid Blaikie : NamedDirEnt.second; 1817a51313dSChris Lattner 1827a51313dSChris Lattner ++NumDirCacheMisses; 1837a51313dSChris Lattner 1847a51313dSChris Lattner // By default, initialize it to invalid. 18513156b68SDavid Blaikie NamedDirEnt.second = NON_EXISTENT_DIR; 1867a51313dSChris Lattner 1877a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 188e1dd3e2cSZhanyong Wan // SeenDirEntries map. 18913156b68SDavid Blaikie const char *InterndDirName = NamedDirEnt.first().data(); 1907a51313dSChris Lattner 1917a51313dSChris Lattner // Check to see if the directory exists. 192f8f91b89SRafael Espindola FileData Data; 193f1186c5aSCraig Topper if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) { 194e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 1951735f4e7SDouglas Gregor if (!CacheFailure) 1961735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 197f1186c5aSCraig Topper return nullptr; 198e1dd3e2cSZhanyong Wan } 1997a51313dSChris Lattner 200e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 201e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 202e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 203e1dd3e2cSZhanyong Wan // Windows). 204c9b7234eSBen Langmuir DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID]; 2057a51313dSChris Lattner 20613156b68SDavid Blaikie NamedDirEnt.second = &UDE; 207e1dd3e2cSZhanyong Wan if (!UDE.getName()) { 208e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 209e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 2107a51313dSChris Lattner UDE.Name = InterndDirName; 211e1dd3e2cSZhanyong Wan } 212e1dd3e2cSZhanyong Wan 2137a51313dSChris Lattner return &UDE; 2147a51313dSChris Lattner } 2157a51313dSChris Lattner 2161735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, 2171735f4e7SDouglas Gregor bool CacheFailure) { 2187a51313dSChris Lattner ++NumFileLookups; 2197a51313dSChris Lattner 2207a51313dSChris Lattner // See if there is already an entry in the map. 22113156b68SDavid Blaikie auto &NamedFileEnt = 22213156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 2237a51313dSChris Lattner 2247a51313dSChris Lattner // See if there is already an entry in the map. 22513156b68SDavid Blaikie if (NamedFileEnt.second) 22613156b68SDavid Blaikie return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr 22713156b68SDavid Blaikie : NamedFileEnt.second; 2287a51313dSChris Lattner 2297a51313dSChris Lattner ++NumFileCacheMisses; 2307a51313dSChris Lattner 2317a51313dSChris Lattner // By default, initialize it to invalid. 23213156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 2337a51313dSChris Lattner 2347a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 235e1dd3e2cSZhanyong Wan // SeenFileEntries map. 23613156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 2377a51313dSChris Lattner 238966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 239966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 240966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 241966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 242966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 2431735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 2441735f4e7SDouglas Gregor CacheFailure); 245f1186c5aSCraig Topper if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. 2461735f4e7SDouglas Gregor if (!CacheFailure) 2471735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2481735f4e7SDouglas Gregor 249f1186c5aSCraig Topper return nullptr; 2501735f4e7SDouglas Gregor } 251407e2124SDouglas Gregor 2527a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2537a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2547a51313dSChris Lattner 2557a51313dSChris Lattner // Nope, there isn't. Check to see if the file exists. 256326ffb36SDavid Blaikie std::unique_ptr<vfs::File> F; 257f8f91b89SRafael Espindola FileData Data; 258f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { 259e1dd3e2cSZhanyong Wan // There's no real file at the given path. 2601735f4e7SDouglas Gregor if (!CacheFailure) 2611735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2621735f4e7SDouglas Gregor 263f1186c5aSCraig Topper return nullptr; 264e1dd3e2cSZhanyong Wan } 2657a51313dSChris Lattner 266ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 267d6278e32SArgyrios Kyrtzidis 2687a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2697a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 270c9b7234eSBen Langmuir FileEntry &UFE = UniqueRealFiles[Data.UniqueID]; 2717a51313dSChris Lattner 27213156b68SDavid Blaikie NamedFileEnt.second = &UFE; 273ab86fbe4SBen Langmuir 274ab86fbe4SBen Langmuir // If the name returned by getStatValue is different than Filename, re-intern 275ab86fbe4SBen Langmuir // the name. 276ab86fbe4SBen Langmuir if (Data.Name != Filename) { 27713156b68SDavid Blaikie auto &NamedFileEnt = 27813156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first; 27913156b68SDavid Blaikie if (!NamedFileEnt.second) 28013156b68SDavid Blaikie NamedFileEnt.second = &UFE; 281ab86fbe4SBen Langmuir else 28213156b68SDavid Blaikie assert(NamedFileEnt.second == &UFE && 283ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file"); 28413156b68SDavid Blaikie InterndFileName = NamedFileEnt.first().data(); 285ab86fbe4SBen Langmuir } 286ab86fbe4SBen Langmuir 287c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2885de00f3bSBen Langmuir 2895de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 2905de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 2915de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 2925de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 2935de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 2945de00f3bSBen Langmuir // multiple names. 2955de00f3bSBen Langmuir if (DirInfo != UFE.Dir && Data.IsVFSMapped) 2965de00f3bSBen Langmuir UFE.Dir = DirInfo; 2975de00f3bSBen Langmuir 298c0ff9908SManuel Klimek // Always update the name to use the last name by which a file was accessed. 299c0ff9908SManuel Klimek // FIXME: Neither this nor always using the first name is correct; we want 300c0ff9908SManuel Klimek // to switch towards a design where we return a FileName object that 301c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the 302c0ff9908SManuel Klimek // corresponding FileEntry. 303ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 304c0ff9908SManuel Klimek 3057a51313dSChris Lattner return &UFE; 306dd278430SChris Lattner } 3077a51313dSChris Lattner 308c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 309ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 310f8f91b89SRafael Espindola UFE.Size = Data.Size; 311f8f91b89SRafael Espindola UFE.ModTime = Data.ModTime; 3127a51313dSChris Lattner UFE.Dir = DirInfo; 3137a51313dSChris Lattner UFE.UID = NextFileUID++; 314c9b7234eSBen Langmuir UFE.UniqueID = Data.UniqueID; 315c9b7234eSBen Langmuir UFE.IsNamedPipe = Data.IsNamedPipe; 316c9b7234eSBen Langmuir UFE.InPCH = Data.InPCH; 317326ffb36SDavid Blaikie UFE.File = std::move(F); 318c8a71468SBen Langmuir UFE.IsValid = true; 3197a51313dSChris Lattner return &UFE; 3207a51313dSChris Lattner } 3217a51313dSChris Lattner 322407e2124SDouglas Gregor const FileEntry * 3230e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3245159f616SChris Lattner time_t ModificationTime) { 325407e2124SDouglas Gregor ++NumFileLookups; 326407e2124SDouglas Gregor 327407e2124SDouglas Gregor // See if there is already an entry in the map. 32813156b68SDavid Blaikie auto &NamedFileEnt = 32913156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 330407e2124SDouglas Gregor 331407e2124SDouglas Gregor // See if there is already an entry in the map. 33213156b68SDavid Blaikie if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE) 33313156b68SDavid Blaikie return NamedFileEnt.second; 334407e2124SDouglas Gregor 335407e2124SDouglas Gregor ++NumFileCacheMisses; 336407e2124SDouglas Gregor 337407e2124SDouglas Gregor // By default, initialize it to invalid. 33813156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 339407e2124SDouglas Gregor 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. 3461735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 3471735f4e7SDouglas Gregor /*CacheFailure=*/true); 348e1dd3e2cSZhanyong Wan assert(DirInfo && 349e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 350e1dd3e2cSZhanyong Wan 351606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 352f8f91b89SRafael Espindola FileData Data; 35313156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 354f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { 355f8f91b89SRafael Espindola Data.Size = Size; 356f8f91b89SRafael Espindola Data.ModTime = ModificationTime; 357c9b7234eSBen Langmuir UFE = &UniqueRealFiles[Data.UniqueID]; 358606c4ac3SDouglas Gregor 35913156b68SDavid Blaikie NamedFileEnt.second = UFE; 360606c4ac3SDouglas Gregor 361606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 362606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 363606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 364c8130a74SBen Langmuir if (UFE->File) 365c8130a74SBen Langmuir UFE->closeFile(); 366606c4ac3SDouglas Gregor 367606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 368c8a71468SBen Langmuir if (UFE->isValid()) 369606c4ac3SDouglas Gregor return UFE; 370c9b7234eSBen Langmuir 371c9b7234eSBen Langmuir UFE->UniqueID = Data.UniqueID; 372c9b7234eSBen Langmuir UFE->IsNamedPipe = Data.IsNamedPipe; 373c9b7234eSBen Langmuir UFE->InPCH = Data.InPCH; 374606c4ac3SDouglas Gregor } 375606c4ac3SDouglas Gregor 376606c4ac3SDouglas Gregor if (!UFE) { 377606c4ac3SDouglas Gregor UFE = new FileEntry(); 378407e2124SDouglas Gregor VirtualFileEntries.push_back(UFE); 37913156b68SDavid Blaikie NamedFileEnt.second = UFE; 380606c4ac3SDouglas Gregor } 381407e2124SDouglas Gregor 3829624b695SChris Lattner UFE->Name = InterndFileName; 383407e2124SDouglas Gregor UFE->Size = Size; 384407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 385407e2124SDouglas Gregor UFE->Dir = DirInfo; 386407e2124SDouglas Gregor UFE->UID = NextFileUID++; 387c8130a74SBen Langmuir UFE->File.reset(); 388407e2124SDouglas Gregor return UFE; 389407e2124SDouglas Gregor } 390407e2124SDouglas Gregor 3910e62c1ccSChris Lattner void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 3920e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 393b5c356a4SAnders Carlsson 3949ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 3959ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 396f28df4cdSMichael J. Spencer return; 39771731d6bSArgyrios Kyrtzidis 3982c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 399b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 4006e640998SChris Lattner path = NewPath; 4016e640998SChris Lattner } 4026e640998SChris Lattner 403a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 404a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 405a885796dSBenjamin Kramer bool ShouldCloseOpenFile) { 4066d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4076d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4086d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 4096d7833f1SArgyrios Kyrtzidis if (isVolatile) 4106d7833f1SArgyrios Kyrtzidis FileSize = -1; 4116d7833f1SArgyrios Kyrtzidis 4125ea7d07dSChris Lattner const char *Filename = Entry->getName(); 4135ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 414c8130a74SBen Langmuir if (Entry->File) { 415a885796dSBenjamin Kramer auto Result = 416a885796dSBenjamin Kramer Entry->File->getBuffer(Filename, FileSize, 41726d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4189801b253SBen Langmuir // FIXME: we need a set of APIs that can make guarantees about whether a 4199801b253SBen Langmuir // FileEntry is open or not. 4209801b253SBen Langmuir if (ShouldCloseOpenFile) 421c8130a74SBen Langmuir Entry->closeFile(); 4226406f7b8SRafael Espindola return Result; 4235ea7d07dSChris Lattner } 4246e640998SChris Lattner 4255ea7d07dSChris Lattner // Otherwise, open the file. 426669b0b15SArgyrios Kyrtzidis 427a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 428a885796dSBenjamin Kramer return FS->getBufferForFile(Filename, FileSize, 42926d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4305ea7d07dSChris Lattner 4312c1dd271SDylan Noblesmith SmallString<128> FilePath(Entry->getName()); 432878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 433*92e1b62dSYaron Keren return FS->getBufferForFile(FilePath, FileSize, 43426d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 43526b5c190SChris Lattner } 43626b5c190SChris Lattner 437a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 438a885796dSBenjamin Kramer FileManager::getBufferForFile(StringRef Filename) { 439a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 440a885796dSBenjamin Kramer return FS->getBufferForFile(Filename); 44126b5c190SChris Lattner 4422c1dd271SDylan Noblesmith SmallString<128> FilePath(Filename); 443878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 444a885796dSBenjamin Kramer return FS->getBufferForFile(FilePath.c_str()); 44571731d6bSArgyrios Kyrtzidis } 44671731d6bSArgyrios Kyrtzidis 447e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 448e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 449e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 450e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 451e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 452f8f91b89SRafael Espindola bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile, 453326ffb36SDavid Blaikie std::unique_ptr<vfs::File> *F) { 454226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 455226efd35SChris Lattner // absolute! 4565769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 457c8130a74SBen Langmuir return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); 458226efd35SChris Lattner 4592c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 460878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 46171731d6bSArgyrios Kyrtzidis 462c8130a74SBen Langmuir return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, 463c8130a74SBen Langmuir StatCache.get(), *FS); 46471731d6bSArgyrios Kyrtzidis } 46571731d6bSArgyrios Kyrtzidis 4660e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path, 467c8130a74SBen Langmuir vfs::Status &Result) { 4682c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 4695e368405SAnders Carlsson FixupRelativePath(FilePath); 4705e368405SAnders Carlsson 471c8130a74SBen Langmuir llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str()); 472c8130a74SBen Langmuir if (!S) 473c8130a74SBen Langmuir return true; 474c8130a74SBen Langmuir Result = *S; 475c8130a74SBen Langmuir return false; 4765e368405SAnders Carlsson } 4775e368405SAnders Carlsson 478b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) { 479b3074003SAxel Naumann assert(Entry && "Cannot invalidate a NULL FileEntry"); 48038179d96SAxel Naumann 48138179d96SAxel Naumann SeenFileEntries.erase(Entry->getName()); 482b3074003SAxel Naumann 483b3074003SAxel Naumann // FileEntry invalidation should not block future optimizations in the file 484b3074003SAxel Naumann // caches. Possible alternatives are cache truncation (invalidate last N) or 485b3074003SAxel Naumann // invalidation of the whole cache. 486c9b7234eSBen Langmuir UniqueRealFiles.erase(Entry->getUniqueID()); 48738179d96SAxel Naumann } 48838179d96SAxel Naumann 48938179d96SAxel Naumann 49009b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 4910e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 49209b6989eSDouglas Gregor UIDToFiles.clear(); 49309b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 49409b6989eSDouglas Gregor 49509b6989eSDouglas Gregor // Map file entries 49609b6989eSDouglas Gregor for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator 497e1dd3e2cSZhanyong Wan FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); 49809b6989eSDouglas Gregor FE != FEEnd; ++FE) 49909b6989eSDouglas Gregor if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) 50009b6989eSDouglas Gregor UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); 50109b6989eSDouglas Gregor 50209b6989eSDouglas Gregor // Map virtual file entries 5032341c0d3SCraig Topper for (SmallVectorImpl<FileEntry *>::const_iterator 50409b6989eSDouglas Gregor VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end(); 50509b6989eSDouglas Gregor VFE != VFEEnd; ++VFE) 50609b6989eSDouglas Gregor if (*VFE && *VFE != NON_EXISTENT_FILE) 50709b6989eSDouglas Gregor UIDToFiles[(*VFE)->getUID()] = *VFE; 50809b6989eSDouglas Gregor } 509226efd35SChris Lattner 5106eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File, 5116eec06d0SArgyrios Kyrtzidis off_t Size, time_t ModificationTime) { 5126eec06d0SArgyrios Kyrtzidis File->Size = Size; 5136eec06d0SArgyrios Kyrtzidis File->ModTime = ModificationTime; 5146eec06d0SArgyrios Kyrtzidis } 5156eec06d0SArgyrios Kyrtzidis 51654cc3c2fSRichard Smith /// Remove '.' path components from the given absolute path. 51754cc3c2fSRichard Smith /// \return \c true if any changes were made. 51854cc3c2fSRichard Smith // FIXME: Move this to llvm::sys::path. 51954cc3c2fSRichard Smith bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path) { 52054cc3c2fSRichard Smith using namespace llvm::sys; 52154cc3c2fSRichard Smith 52254cc3c2fSRichard Smith SmallVector<StringRef, 16> ComponentStack; 52354cc3c2fSRichard Smith StringRef P(Path.data(), Path.size()); 52454cc3c2fSRichard Smith 52554cc3c2fSRichard Smith // Skip the root path, then look for traversal in the components. 52654cc3c2fSRichard Smith StringRef Rel = path::relative_path(P); 52754cc3c2fSRichard Smith bool AnyDots = false; 52854cc3c2fSRichard Smith for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) { 52954cc3c2fSRichard Smith if (C == ".") { 53054cc3c2fSRichard Smith AnyDots = true; 53154cc3c2fSRichard Smith continue; 53254cc3c2fSRichard Smith } 53354cc3c2fSRichard Smith ComponentStack.push_back(C); 53454cc3c2fSRichard Smith } 53554cc3c2fSRichard Smith 53654cc3c2fSRichard Smith if (!AnyDots) 53754cc3c2fSRichard Smith return false; 53854cc3c2fSRichard Smith 53954cc3c2fSRichard Smith SmallString<256> Buffer = path::root_path(P); 54054cc3c2fSRichard Smith for (StringRef C : ComponentStack) 54154cc3c2fSRichard Smith path::append(Buffer, C); 54254cc3c2fSRichard Smith 54354cc3c2fSRichard Smith Path.swap(Buffer); 54454cc3c2fSRichard Smith return true; 54554cc3c2fSRichard Smith } 54654cc3c2fSRichard Smith 547e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 548e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 549e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 550e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 551e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 552e00c8b20SDouglas Gregor return Known->second; 553e00c8b20SDouglas Gregor 554e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 55554cc3c2fSRichard Smith 55654cc3c2fSRichard Smith #ifdef LLVM_ON_UNIX 557e00c8b20SDouglas Gregor char CanonicalNameBuf[PATH_MAX]; 558e00c8b20SDouglas Gregor if (realpath(Dir->getName(), CanonicalNameBuf)) { 559e00c8b20SDouglas Gregor unsigned Len = strlen(CanonicalNameBuf); 560e00c8b20SDouglas Gregor char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1)); 561e00c8b20SDouglas Gregor memcpy(Mem, CanonicalNameBuf, Len); 562e00c8b20SDouglas Gregor CanonicalName = StringRef(Mem, Len); 563e00c8b20SDouglas Gregor } 56454cc3c2fSRichard Smith #else 56554cc3c2fSRichard Smith SmallString<256> CanonicalNameBuf(CanonicalName); 56654cc3c2fSRichard Smith llvm::sys::fs::make_absolute(CanonicalNameBuf); 56754cc3c2fSRichard Smith llvm::sys::path::native(CanonicalNameBuf); 56854cc3c2fSRichard Smith removeDotPaths(CanonicalNameBuf); 56954cc3c2fSRichard Smith #endif 570e00c8b20SDouglas Gregor 571e00c8b20SDouglas Gregor CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); 572e00c8b20SDouglas Gregor return CanonicalName; 573e00c8b20SDouglas Gregor } 574226efd35SChris Lattner 5757a51313dSChris Lattner void FileManager::PrintStats() const { 57689b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 577e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 578e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 579e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 580e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 58189b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 5827a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 58389b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 5847a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 5857a51313dSChris Lattner 58689b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 5877a51313dSChris Lattner } 588