1226efd35SChris Lattner //===--- FileManager.cpp - File System Probing and Caching ----------------===// 27a51313dSChris Lattner // 37a51313dSChris Lattner // The LLVM Compiler Infrastructure 47a51313dSChris Lattner // 57a51313dSChris Lattner // This file is distributed under the University of Illinois Open Source 67a51313dSChris Lattner // License. See LICENSE.TXT for details. 77a51313dSChris Lattner // 87a51313dSChris Lattner //===----------------------------------------------------------------------===// 97a51313dSChris Lattner // 107a51313dSChris Lattner // This file implements the FileManager interface. 117a51313dSChris Lattner // 127a51313dSChris Lattner //===----------------------------------------------------------------------===// 137a51313dSChris Lattner // 147a51313dSChris Lattner // TODO: This should index all interesting directories with dirent calls. 157a51313dSChris Lattner // getdirentries ? 167a51313dSChris Lattner // opendir/readdir_r/closedir ? 177a51313dSChris Lattner // 187a51313dSChris Lattner //===----------------------------------------------------------------------===// 197a51313dSChris Lattner 207a51313dSChris Lattner #include "clang/Basic/FileManager.h" 21226efd35SChris Lattner #include "clang/Basic/FileSystemStatCache.h" 227a51313dSChris Lattner #include "llvm/ADT/SmallString.h" 233a02247dSChandler Carruth #include "llvm/Config/llvm-config.h" 24d2725a31SDavid Blaikie #include "llvm/ADT/STLExtras.h" 25740857faSMichael J. Spencer #include "llvm/Support/FileSystem.h" 2671731d6bSArgyrios Kyrtzidis #include "llvm/Support/MemoryBuffer.h" 278aaf4995SMichael J. Spencer #include "llvm/Support/Path.h" 283a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h" 2926db6481SBenjamin Kramer #include <map> 3026db6481SBenjamin Kramer #include <set> 3126db6481SBenjamin Kramer #include <string> 328a8e554aSRafael Espindola #include <system_error> 33278038b4SChris Lattner 347a51313dSChris Lattner using namespace clang; 357a51313dSChris Lattner 367a51313dSChris Lattner /// NON_EXISTENT_DIR - A special value distinct from null that is used to 377a51313dSChris Lattner /// represent a dir name that doesn't exist on the disk. 387a51313dSChris Lattner #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) 397a51313dSChris Lattner 409624b695SChris Lattner /// NON_EXISTENT_FILE - A special value distinct from null that is used to 419624b695SChris Lattner /// represent a filename that doesn't exist on the disk. 429624b695SChris Lattner #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) 439624b695SChris Lattner 445c04bd81STed Kremenek //===----------------------------------------------------------------------===// 455c04bd81STed Kremenek // Common logic. 465c04bd81STed Kremenek //===----------------------------------------------------------------------===// 477a51313dSChris Lattner 48c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO, 49c8130a74SBen Langmuir IntrusiveRefCntPtr<vfs::FileSystem> FS) 50c8130a74SBen Langmuir : FS(FS), FileSystemOpts(FSO), 51e1dd3e2cSZhanyong Wan SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) { 527a51313dSChris Lattner NumDirLookups = NumFileLookups = 0; 537a51313dSChris Lattner NumDirCacheMisses = NumFileCacheMisses = 0; 54c8130a74SBen Langmuir 55c8130a74SBen Langmuir // If the caller doesn't provide a virtual file system, just grab the real 56c8130a74SBen Langmuir // file system. 57c8130a74SBen Langmuir if (!FS) 58c8130a74SBen Langmuir this->FS = vfs::getRealFileSystem(); 597a51313dSChris Lattner } 607a51313dSChris Lattner 61d2725a31SDavid Blaikie FileManager::~FileManager() = default; 627a51313dSChris Lattner 6323430ccbSDavid Blaikie void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, 64226efd35SChris Lattner bool AtBeginning) { 65d2eb58abSDouglas Gregor assert(statCache && "No stat cache provided?"); 66f1186c5aSCraig Topper if (AtBeginning || !StatCache.get()) { 6723430ccbSDavid Blaikie statCache->setNextStatCache(std::move(StatCache)); 6823430ccbSDavid Blaikie StatCache = std::move(statCache); 69d2eb58abSDouglas Gregor return; 70d2eb58abSDouglas Gregor } 71d2eb58abSDouglas Gregor 72226efd35SChris Lattner FileSystemStatCache *LastCache = StatCache.get(); 73d2eb58abSDouglas Gregor while (LastCache->getNextStatCache()) 74d2eb58abSDouglas Gregor LastCache = LastCache->getNextStatCache(); 75d2eb58abSDouglas Gregor 7623430ccbSDavid Blaikie LastCache->setNextStatCache(std::move(statCache)); 77d2eb58abSDouglas Gregor } 78d2eb58abSDouglas Gregor 79226efd35SChris Lattner void FileManager::removeStatCache(FileSystemStatCache *statCache) { 80d2eb58abSDouglas Gregor if (!statCache) 81d2eb58abSDouglas Gregor return; 82d2eb58abSDouglas Gregor 83d2eb58abSDouglas Gregor if (StatCache.get() == statCache) { 84d2eb58abSDouglas Gregor // This is the first stat cache. 85dd0e1e8dSDavid Blaikie StatCache = StatCache->takeNextStatCache(); 86d2eb58abSDouglas Gregor return; 87d2eb58abSDouglas Gregor } 88d2eb58abSDouglas Gregor 89d2eb58abSDouglas Gregor // Find the stat cache in the list. 90226efd35SChris Lattner FileSystemStatCache *PrevCache = StatCache.get(); 91d2eb58abSDouglas Gregor while (PrevCache && PrevCache->getNextStatCache() != statCache) 92d2eb58abSDouglas Gregor PrevCache = PrevCache->getNextStatCache(); 939624b695SChris Lattner 949624b695SChris Lattner assert(PrevCache && "Stat cache not found for removal"); 9523430ccbSDavid Blaikie PrevCache->setNextStatCache(statCache->takeNextStatCache()); 96d2eb58abSDouglas Gregor } 97d2eb58abSDouglas Gregor 983aad855aSManuel Klimek void FileManager::clearStatCaches() { 993875a82dSDavid Blaikie StatCache.reset(); 1003aad855aSManuel Klimek } 1013aad855aSManuel Klimek 102407e2124SDouglas Gregor /// \brief Retrieve the directory that the given file name resides in. 103e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file. 104407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, 1051735f4e7SDouglas Gregor StringRef Filename, 1061735f4e7SDouglas Gregor bool CacheFailure) { 107f3c0ff73SZhanyong Wan if (Filename.empty()) 108f1186c5aSCraig Topper return nullptr; 109e1dd3e2cSZhanyong Wan 110f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 111f1186c5aSCraig Topper return nullptr; // If Filename is a directory. 1120c0e8040SChris Lattner 1130e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename); 1140c0e8040SChris Lattner // Use the current directory if file has no path component. 115f3c0ff73SZhanyong Wan if (DirName.empty()) 116f3c0ff73SZhanyong Wan DirName = "."; 1170c0e8040SChris Lattner 1181735f4e7SDouglas Gregor return FileMgr.getDirectory(DirName, CacheFailure); 119407e2124SDouglas Gregor } 120407e2124SDouglas Gregor 121e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or 122e1dd3e2cSZhanyong Wan /// a directory) as virtual directories. 1230e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 1240e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path); 125f3c0ff73SZhanyong Wan if (DirName.empty()) 1261834dc75SDavid Majnemer DirName = "."; 127e1dd3e2cSZhanyong Wan 12813156b68SDavid Blaikie auto &NamedDirEnt = 12913156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 130e1dd3e2cSZhanyong Wan 131e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors 132e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache, 133e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in 134e1dd3e2cSZhanyong Wan // the cache. 135a8cfffa3SRichard Smith if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR) 136e1dd3e2cSZhanyong Wan return; 137e1dd3e2cSZhanyong Wan 138e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache. 139d2725a31SDavid Blaikie auto UDE = llvm::make_unique<DirectoryEntry>(); 14013156b68SDavid Blaikie UDE->Name = NamedDirEnt.first().data(); 141d2725a31SDavid Blaikie NamedDirEnt.second = UDE.get(); 142d2725a31SDavid Blaikie VirtualDirectoryEntries.push_back(std::move(UDE)); 143e1dd3e2cSZhanyong Wan 144e1dd3e2cSZhanyong Wan // Recursively add the other ancestors. 145e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName); 146e1dd3e2cSZhanyong Wan } 147e1dd3e2cSZhanyong Wan 1481735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName, 1491735f4e7SDouglas Gregor bool CacheFailure) { 1508bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 15132f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 15232f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1538bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1548bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1558bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 15632f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 157ee30546cSRafael Espindola #ifdef LLVM_ON_WIN32 158ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 159ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 160ee30546cSRafael Espindola std::string DirNameStr; 161ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 162ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 163ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 164ee30546cSRafael Espindola DirName = DirNameStr; 165ee30546cSRafael Espindola } 166ee30546cSRafael Espindola #endif 16732f1acf1SNAKAMURA Takumi 1687a51313dSChris Lattner ++NumDirLookups; 16913156b68SDavid Blaikie auto &NamedDirEnt = 17013156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 1717a51313dSChris Lattner 172e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 173e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 17413156b68SDavid Blaikie if (NamedDirEnt.second) 17513156b68SDavid Blaikie return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr 17613156b68SDavid Blaikie : NamedDirEnt.second; 1777a51313dSChris Lattner 1787a51313dSChris Lattner ++NumDirCacheMisses; 1797a51313dSChris Lattner 1807a51313dSChris Lattner // By default, initialize it to invalid. 18113156b68SDavid Blaikie NamedDirEnt.second = NON_EXISTENT_DIR; 1827a51313dSChris Lattner 1837a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 184e1dd3e2cSZhanyong Wan // SeenDirEntries map. 18513156b68SDavid Blaikie const char *InterndDirName = NamedDirEnt.first().data(); 1867a51313dSChris Lattner 1877a51313dSChris Lattner // Check to see if the directory exists. 188f8f91b89SRafael Espindola FileData Data; 189f1186c5aSCraig Topper if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) { 190e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 1911735f4e7SDouglas Gregor if (!CacheFailure) 1921735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 193f1186c5aSCraig Topper return nullptr; 194e1dd3e2cSZhanyong Wan } 1957a51313dSChris Lattner 196e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 197e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 198e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 199e1dd3e2cSZhanyong Wan // Windows). 200c9b7234eSBen Langmuir DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID]; 2017a51313dSChris Lattner 20213156b68SDavid Blaikie NamedDirEnt.second = &UDE; 203e1dd3e2cSZhanyong Wan if (!UDE.getName()) { 204e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 205e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 2067a51313dSChris Lattner UDE.Name = InterndDirName; 207e1dd3e2cSZhanyong Wan } 208e1dd3e2cSZhanyong Wan 2097a51313dSChris Lattner return &UDE; 2107a51313dSChris Lattner } 2117a51313dSChris Lattner 2121735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, 2131735f4e7SDouglas Gregor bool CacheFailure) { 2147a51313dSChris Lattner ++NumFileLookups; 2157a51313dSChris Lattner 2167a51313dSChris Lattner // See if there is already an entry in the map. 21713156b68SDavid Blaikie auto &NamedFileEnt = 21813156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 2197a51313dSChris Lattner 2207a51313dSChris Lattner // See if there is already an entry in the map. 22113156b68SDavid Blaikie if (NamedFileEnt.second) 22213156b68SDavid Blaikie return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr 22313156b68SDavid Blaikie : NamedFileEnt.second; 2247a51313dSChris Lattner 2257a51313dSChris Lattner ++NumFileCacheMisses; 2267a51313dSChris Lattner 2277a51313dSChris Lattner // By default, initialize it to invalid. 22813156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 2297a51313dSChris Lattner 2307a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 231e1dd3e2cSZhanyong Wan // SeenFileEntries map. 23213156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 2337a51313dSChris Lattner 234966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 235966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 236966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 237966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 238966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 2391735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 2401735f4e7SDouglas Gregor CacheFailure); 241f1186c5aSCraig Topper if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. 2421735f4e7SDouglas Gregor if (!CacheFailure) 2431735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2441735f4e7SDouglas Gregor 245f1186c5aSCraig Topper return nullptr; 2461735f4e7SDouglas Gregor } 247407e2124SDouglas Gregor 2487a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2497a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2507a51313dSChris Lattner 2517a51313dSChris Lattner // Nope, there isn't. Check to see if the file exists. 252326ffb36SDavid Blaikie std::unique_ptr<vfs::File> F; 253f8f91b89SRafael Espindola FileData Data; 254f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { 255e1dd3e2cSZhanyong Wan // There's no real file at the given path. 2561735f4e7SDouglas Gregor if (!CacheFailure) 2571735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2581735f4e7SDouglas Gregor 259f1186c5aSCraig Topper return nullptr; 260e1dd3e2cSZhanyong Wan } 2617a51313dSChris Lattner 262ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 263d6278e32SArgyrios Kyrtzidis 2647a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2657a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 266c9b7234eSBen Langmuir FileEntry &UFE = UniqueRealFiles[Data.UniqueID]; 2677a51313dSChris Lattner 26813156b68SDavid Blaikie NamedFileEnt.second = &UFE; 269ab86fbe4SBen Langmuir 270ab86fbe4SBen Langmuir // If the name returned by getStatValue is different than Filename, re-intern 271ab86fbe4SBen Langmuir // the name. 272ab86fbe4SBen Langmuir if (Data.Name != Filename) { 27313156b68SDavid Blaikie auto &NamedFileEnt = 27413156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first; 27513156b68SDavid Blaikie if (!NamedFileEnt.second) 27613156b68SDavid Blaikie NamedFileEnt.second = &UFE; 277ab86fbe4SBen Langmuir else 27813156b68SDavid Blaikie assert(NamedFileEnt.second == &UFE && 279ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file"); 28013156b68SDavid Blaikie InterndFileName = NamedFileEnt.first().data(); 281ab86fbe4SBen Langmuir } 282ab86fbe4SBen Langmuir 283c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2845de00f3bSBen Langmuir 2855de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 2865de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 2875de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 2885de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 2895de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 2905de00f3bSBen Langmuir // multiple names. 2915de00f3bSBen Langmuir if (DirInfo != UFE.Dir && Data.IsVFSMapped) 2925de00f3bSBen Langmuir UFE.Dir = DirInfo; 2935de00f3bSBen Langmuir 294c0ff9908SManuel Klimek // Always update the name to use the last name by which a file was accessed. 295c0ff9908SManuel Klimek // FIXME: Neither this nor always using the first name is correct; we want 296c0ff9908SManuel Klimek // to switch towards a design where we return a FileName object that 297c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the 298c0ff9908SManuel Klimek // corresponding FileEntry. 299ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 300c0ff9908SManuel Klimek 3017a51313dSChris Lattner return &UFE; 302dd278430SChris Lattner } 3037a51313dSChris Lattner 304c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 305ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 306f8f91b89SRafael Espindola UFE.Size = Data.Size; 307f8f91b89SRafael Espindola UFE.ModTime = Data.ModTime; 3087a51313dSChris Lattner UFE.Dir = DirInfo; 3097a51313dSChris Lattner UFE.UID = NextFileUID++; 310c9b7234eSBen Langmuir UFE.UniqueID = Data.UniqueID; 311c9b7234eSBen Langmuir UFE.IsNamedPipe = Data.IsNamedPipe; 312c9b7234eSBen Langmuir UFE.InPCH = Data.InPCH; 313326ffb36SDavid Blaikie UFE.File = std::move(F); 314c8a71468SBen Langmuir UFE.IsValid = true; 315*f42103ceSTaewook Oh if (UFE.File) 316*f42103ceSTaewook Oh if (auto RealPathName = UFE.File->getName()) 317*f42103ceSTaewook Oh UFE.RealPathName = *RealPathName; 3187a51313dSChris Lattner return &UFE; 3197a51313dSChris Lattner } 3207a51313dSChris Lattner 321407e2124SDouglas Gregor const FileEntry * 3220e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3235159f616SChris Lattner time_t ModificationTime) { 324407e2124SDouglas Gregor ++NumFileLookups; 325407e2124SDouglas Gregor 326407e2124SDouglas Gregor // See if there is already an entry in the map. 32713156b68SDavid Blaikie auto &NamedFileEnt = 32813156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 329407e2124SDouglas Gregor 330407e2124SDouglas Gregor // See if there is already an entry in the map. 33113156b68SDavid Blaikie if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE) 33213156b68SDavid Blaikie return NamedFileEnt.second; 333407e2124SDouglas Gregor 334407e2124SDouglas Gregor ++NumFileCacheMisses; 335407e2124SDouglas Gregor 336407e2124SDouglas Gregor // By default, initialize it to invalid. 33713156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 338407e2124SDouglas Gregor 339e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 340f1186c5aSCraig Topper FileEntry *UFE = nullptr; 341e1dd3e2cSZhanyong Wan 342e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 343e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 344e1dd3e2cSZhanyong Wan // cache. 3451735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 3461735f4e7SDouglas Gregor /*CacheFailure=*/true); 347e1dd3e2cSZhanyong Wan assert(DirInfo && 348e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 349e1dd3e2cSZhanyong Wan 350606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 351f8f91b89SRafael Espindola FileData Data; 35213156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 353f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { 354f8f91b89SRafael Espindola Data.Size = Size; 355f8f91b89SRafael Espindola Data.ModTime = ModificationTime; 356c9b7234eSBen Langmuir UFE = &UniqueRealFiles[Data.UniqueID]; 357606c4ac3SDouglas Gregor 35813156b68SDavid Blaikie NamedFileEnt.second = UFE; 359606c4ac3SDouglas Gregor 360606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 361606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 362606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 363c8130a74SBen Langmuir if (UFE->File) 364c8130a74SBen Langmuir UFE->closeFile(); 365606c4ac3SDouglas Gregor 366606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 367c8a71468SBen Langmuir if (UFE->isValid()) 368606c4ac3SDouglas Gregor return UFE; 369c9b7234eSBen Langmuir 370c9b7234eSBen Langmuir UFE->UniqueID = Data.UniqueID; 371c9b7234eSBen Langmuir UFE->IsNamedPipe = Data.IsNamedPipe; 372c9b7234eSBen Langmuir UFE->InPCH = Data.InPCH; 373606c4ac3SDouglas Gregor } 374606c4ac3SDouglas Gregor 375606c4ac3SDouglas Gregor if (!UFE) { 376d2725a31SDavid Blaikie VirtualFileEntries.push_back(llvm::make_unique<FileEntry>()); 377d2725a31SDavid Blaikie UFE = VirtualFileEntries.back().get(); 37813156b68SDavid Blaikie NamedFileEnt.second = UFE; 379606c4ac3SDouglas Gregor } 380407e2124SDouglas Gregor 3819624b695SChris Lattner UFE->Name = InterndFileName; 382407e2124SDouglas Gregor UFE->Size = Size; 383407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 384407e2124SDouglas Gregor UFE->Dir = DirInfo; 385407e2124SDouglas Gregor UFE->UID = NextFileUID++; 386c8130a74SBen Langmuir UFE->File.reset(); 387407e2124SDouglas Gregor return UFE; 388407e2124SDouglas Gregor } 389407e2124SDouglas Gregor 390c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 3910e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 392b5c356a4SAnders Carlsson 3939ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 3949ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 395c56419edSArgyrios Kyrtzidis return false; 39671731d6bSArgyrios Kyrtzidis 3972c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 398b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 3996e640998SChris Lattner path = NewPath; 400c56419edSArgyrios Kyrtzidis return true; 401c56419edSArgyrios Kyrtzidis } 402c56419edSArgyrios Kyrtzidis 403c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 404c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path); 405c56419edSArgyrios Kyrtzidis 406c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 407c56419edSArgyrios Kyrtzidis llvm::sys::fs::make_absolute(Path); 408c56419edSArgyrios Kyrtzidis Changed = true; 409c56419edSArgyrios Kyrtzidis } 410c56419edSArgyrios Kyrtzidis 411c56419edSArgyrios Kyrtzidis return Changed; 4126e640998SChris Lattner } 4136e640998SChris Lattner 414a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 415a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 416a885796dSBenjamin Kramer bool ShouldCloseOpenFile) { 4176d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4186d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4196d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 4206d7833f1SArgyrios Kyrtzidis if (isVolatile) 4216d7833f1SArgyrios Kyrtzidis FileSize = -1; 4226d7833f1SArgyrios Kyrtzidis 4235ea7d07dSChris Lattner const char *Filename = Entry->getName(); 4245ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 425c8130a74SBen Langmuir if (Entry->File) { 426a885796dSBenjamin Kramer auto Result = 427a885796dSBenjamin Kramer Entry->File->getBuffer(Filename, FileSize, 42826d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4299801b253SBen Langmuir // FIXME: we need a set of APIs that can make guarantees about whether a 4309801b253SBen Langmuir // FileEntry is open or not. 4319801b253SBen Langmuir if (ShouldCloseOpenFile) 432c8130a74SBen Langmuir Entry->closeFile(); 4336406f7b8SRafael Espindola return Result; 4345ea7d07dSChris Lattner } 4356e640998SChris Lattner 4365ea7d07dSChris Lattner // Otherwise, open the file. 437669b0b15SArgyrios Kyrtzidis 438a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 439a885796dSBenjamin Kramer return FS->getBufferForFile(Filename, FileSize, 44026d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4415ea7d07dSChris Lattner 4422c1dd271SDylan Noblesmith SmallString<128> FilePath(Entry->getName()); 443878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 44492e1b62dSYaron Keren return FS->getBufferForFile(FilePath, FileSize, 44526d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 44626b5c190SChris Lattner } 44726b5c190SChris Lattner 448a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 449a885796dSBenjamin Kramer FileManager::getBufferForFile(StringRef Filename) { 450a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 451a885796dSBenjamin Kramer return FS->getBufferForFile(Filename); 45226b5c190SChris Lattner 4532c1dd271SDylan Noblesmith SmallString<128> FilePath(Filename); 454878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 455a885796dSBenjamin Kramer return FS->getBufferForFile(FilePath.c_str()); 45671731d6bSArgyrios Kyrtzidis } 45771731d6bSArgyrios Kyrtzidis 458e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 459e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 460e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 461e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 462e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 463f8f91b89SRafael Espindola bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile, 464326ffb36SDavid Blaikie std::unique_ptr<vfs::File> *F) { 465226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 466226efd35SChris Lattner // absolute! 4675769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 468c8130a74SBen Langmuir return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); 469226efd35SChris Lattner 4702c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 471878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 47271731d6bSArgyrios Kyrtzidis 473c8130a74SBen Langmuir return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, 474c8130a74SBen Langmuir StatCache.get(), *FS); 47571731d6bSArgyrios Kyrtzidis } 47671731d6bSArgyrios Kyrtzidis 4770e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path, 478c8130a74SBen Langmuir vfs::Status &Result) { 4792c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 4805e368405SAnders Carlsson FixupRelativePath(FilePath); 4815e368405SAnders Carlsson 482c8130a74SBen Langmuir llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str()); 483c8130a74SBen Langmuir if (!S) 484c8130a74SBen Langmuir return true; 485c8130a74SBen Langmuir Result = *S; 486c8130a74SBen Langmuir return false; 4875e368405SAnders Carlsson } 4885e368405SAnders Carlsson 489b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) { 490b3074003SAxel Naumann assert(Entry && "Cannot invalidate a NULL FileEntry"); 49138179d96SAxel Naumann 49238179d96SAxel Naumann SeenFileEntries.erase(Entry->getName()); 493b3074003SAxel Naumann 494b3074003SAxel Naumann // FileEntry invalidation should not block future optimizations in the file 495b3074003SAxel Naumann // caches. Possible alternatives are cache truncation (invalidate last N) or 496b3074003SAxel Naumann // invalidation of the whole cache. 497c9b7234eSBen Langmuir UniqueRealFiles.erase(Entry->getUniqueID()); 49838179d96SAxel Naumann } 49938179d96SAxel Naumann 50038179d96SAxel Naumann 50109b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 5020e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 50309b6989eSDouglas Gregor UIDToFiles.clear(); 50409b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 50509b6989eSDouglas Gregor 50609b6989eSDouglas Gregor // Map file entries 50709b6989eSDouglas Gregor for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator 508e1dd3e2cSZhanyong Wan FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); 50909b6989eSDouglas Gregor FE != FEEnd; ++FE) 51009b6989eSDouglas Gregor if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) 51109b6989eSDouglas Gregor UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); 51209b6989eSDouglas Gregor 51309b6989eSDouglas Gregor // Map virtual file entries 514d2725a31SDavid Blaikie for (const auto &VFE : VirtualFileEntries) 515d2725a31SDavid Blaikie if (VFE && VFE.get() != NON_EXISTENT_FILE) 516d2725a31SDavid Blaikie UIDToFiles[VFE->getUID()] = VFE.get(); 51709b6989eSDouglas Gregor } 518226efd35SChris Lattner 5196eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File, 5206eec06d0SArgyrios Kyrtzidis off_t Size, time_t ModificationTime) { 5216eec06d0SArgyrios Kyrtzidis File->Size = Size; 5226eec06d0SArgyrios Kyrtzidis File->ModTime = ModificationTime; 5236eec06d0SArgyrios Kyrtzidis } 5246eec06d0SArgyrios Kyrtzidis 525e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 526e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 527e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 528e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 529e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 530e00c8b20SDouglas Gregor return Known->second; 531e00c8b20SDouglas Gregor 532e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 53354cc3c2fSRichard Smith 53454cc3c2fSRichard Smith #ifdef LLVM_ON_UNIX 535e00c8b20SDouglas Gregor char CanonicalNameBuf[PATH_MAX]; 536da4690aeSBenjamin Kramer if (realpath(Dir->getName(), CanonicalNameBuf)) 537da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 53854cc3c2fSRichard Smith #else 53954cc3c2fSRichard Smith SmallString<256> CanonicalNameBuf(CanonicalName); 54054cc3c2fSRichard Smith llvm::sys::fs::make_absolute(CanonicalNameBuf); 54154cc3c2fSRichard Smith llvm::sys::path::native(CanonicalNameBuf); 542de381665SSean Silva // We've run into needing to remove '..' here in the wild though, so 543de381665SSean Silva // remove it. 544de381665SSean Silva // On Windows, symlinks are significantly less prevalent, so removing 545de381665SSean Silva // '..' is pretty safe. 546de381665SSean Silva // Ideally we'd have an equivalent of `realpath` and could implement 547de381665SSean Silva // sys::fs::canonical across all the platforms. 548aeb9dd92SMike Aizatsky llvm::sys::path::remove_dots(CanonicalNameBuf, /* remove_dot_dot */ true); 549da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 55054cc3c2fSRichard Smith #endif 551e00c8b20SDouglas Gregor 552e00c8b20SDouglas Gregor CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); 553e00c8b20SDouglas Gregor return CanonicalName; 554e00c8b20SDouglas Gregor } 555226efd35SChris Lattner 5567a51313dSChris Lattner void FileManager::PrintStats() const { 55789b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 558e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 559e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 560e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 561e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 56289b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 5637a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 56489b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 5657a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 5667a51313dSChris Lattner 56789b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 5687a51313dSChris Lattner } 569