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" 22075bf567SAdrian Prantl #include "clang/Frontend/PCHContainerOperations.h" 237a51313dSChris Lattner #include "llvm/ADT/SmallString.h" 243a02247dSChandler Carruth #include "llvm/Config/llvm-config.h" 25740857faSMichael J. Spencer #include "llvm/Support/FileSystem.h" 2671731d6bSArgyrios Kyrtzidis #include "llvm/Support/MemoryBuffer.h" 278aaf4995SMichael J. Spencer #include "llvm/Support/Path.h" 283a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h" 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 617a51313dSChris Lattner FileManager::~FileManager() { 62966b25b9SChris Lattner for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i) 63966b25b9SChris Lattner delete VirtualFileEntries[i]; 64e1dd3e2cSZhanyong Wan for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i) 65e1dd3e2cSZhanyong Wan delete VirtualDirectoryEntries[i]; 667a51313dSChris Lattner } 677a51313dSChris Lattner 6823430ccbSDavid Blaikie void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, 69226efd35SChris Lattner bool AtBeginning) { 70d2eb58abSDouglas Gregor assert(statCache && "No stat cache provided?"); 71f1186c5aSCraig Topper if (AtBeginning || !StatCache.get()) { 7223430ccbSDavid Blaikie statCache->setNextStatCache(std::move(StatCache)); 7323430ccbSDavid Blaikie StatCache = std::move(statCache); 74d2eb58abSDouglas Gregor return; 75d2eb58abSDouglas Gregor } 76d2eb58abSDouglas Gregor 77226efd35SChris Lattner FileSystemStatCache *LastCache = StatCache.get(); 78d2eb58abSDouglas Gregor while (LastCache->getNextStatCache()) 79d2eb58abSDouglas Gregor LastCache = LastCache->getNextStatCache(); 80d2eb58abSDouglas Gregor 8123430ccbSDavid Blaikie LastCache->setNextStatCache(std::move(statCache)); 82d2eb58abSDouglas Gregor } 83d2eb58abSDouglas Gregor 84226efd35SChris Lattner void FileManager::removeStatCache(FileSystemStatCache *statCache) { 85d2eb58abSDouglas Gregor if (!statCache) 86d2eb58abSDouglas Gregor return; 87d2eb58abSDouglas Gregor 88d2eb58abSDouglas Gregor if (StatCache.get() == statCache) { 89d2eb58abSDouglas Gregor // This is the first stat cache. 90dd0e1e8dSDavid Blaikie StatCache = StatCache->takeNextStatCache(); 91d2eb58abSDouglas Gregor return; 92d2eb58abSDouglas Gregor } 93d2eb58abSDouglas Gregor 94d2eb58abSDouglas Gregor // Find the stat cache in the list. 95226efd35SChris Lattner FileSystemStatCache *PrevCache = StatCache.get(); 96d2eb58abSDouglas Gregor while (PrevCache && PrevCache->getNextStatCache() != statCache) 97d2eb58abSDouglas Gregor PrevCache = PrevCache->getNextStatCache(); 989624b695SChris Lattner 999624b695SChris Lattner assert(PrevCache && "Stat cache not found for removal"); 10023430ccbSDavid Blaikie PrevCache->setNextStatCache(statCache->takeNextStatCache()); 101d2eb58abSDouglas Gregor } 102d2eb58abSDouglas Gregor 1033aad855aSManuel Klimek void FileManager::clearStatCaches() { 1043875a82dSDavid Blaikie StatCache.reset(); 1053aad855aSManuel Klimek } 1063aad855aSManuel Klimek 107407e2124SDouglas Gregor /// \brief Retrieve the directory that the given file name resides in. 108e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file. 109407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, 1101735f4e7SDouglas Gregor StringRef Filename, 1111735f4e7SDouglas Gregor bool CacheFailure) { 112f3c0ff73SZhanyong Wan if (Filename.empty()) 113f1186c5aSCraig Topper return nullptr; 114e1dd3e2cSZhanyong Wan 115f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 116f1186c5aSCraig Topper return nullptr; // If Filename is a directory. 1170c0e8040SChris Lattner 1180e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename); 1190c0e8040SChris Lattner // Use the current directory if file has no path component. 120f3c0ff73SZhanyong Wan if (DirName.empty()) 121f3c0ff73SZhanyong Wan DirName = "."; 1220c0e8040SChris Lattner 1231735f4e7SDouglas Gregor return FileMgr.getDirectory(DirName, CacheFailure); 124407e2124SDouglas Gregor } 125407e2124SDouglas Gregor 126e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or 127e1dd3e2cSZhanyong Wan /// a directory) as virtual directories. 1280e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 1290e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path); 130f3c0ff73SZhanyong Wan if (DirName.empty()) 131e1dd3e2cSZhanyong Wan return; 132e1dd3e2cSZhanyong Wan 13313156b68SDavid Blaikie auto &NamedDirEnt = 13413156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 135e1dd3e2cSZhanyong Wan 136e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors 137e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache, 138e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in 139e1dd3e2cSZhanyong Wan // the cache. 14013156b68SDavid Blaikie if (NamedDirEnt.second) 141e1dd3e2cSZhanyong Wan return; 142e1dd3e2cSZhanyong Wan 143e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache. 144e1dd3e2cSZhanyong Wan DirectoryEntry *UDE = new DirectoryEntry; 14513156b68SDavid Blaikie UDE->Name = NamedDirEnt.first().data(); 14613156b68SDavid Blaikie NamedDirEnt.second = UDE; 147e1dd3e2cSZhanyong Wan VirtualDirectoryEntries.push_back(UDE); 148e1dd3e2cSZhanyong Wan 149e1dd3e2cSZhanyong Wan // Recursively add the other ancestors. 150e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName); 151e1dd3e2cSZhanyong Wan } 152e1dd3e2cSZhanyong Wan 1531735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName, 1541735f4e7SDouglas Gregor bool CacheFailure) { 1558bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 15632f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 15732f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1588bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1598bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1608bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 16132f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 162ee30546cSRafael Espindola #ifdef LLVM_ON_WIN32 163ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 164ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 165ee30546cSRafael Espindola std::string DirNameStr; 166ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 167ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 168ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 169ee30546cSRafael Espindola DirName = DirNameStr; 170ee30546cSRafael Espindola } 171ee30546cSRafael Espindola #endif 17232f1acf1SNAKAMURA Takumi 1737a51313dSChris Lattner ++NumDirLookups; 17413156b68SDavid Blaikie auto &NamedDirEnt = 17513156b68SDavid Blaikie *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 1767a51313dSChris Lattner 177e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 178e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 17913156b68SDavid Blaikie if (NamedDirEnt.second) 18013156b68SDavid Blaikie return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr 18113156b68SDavid Blaikie : NamedDirEnt.second; 1827a51313dSChris Lattner 1837a51313dSChris Lattner ++NumDirCacheMisses; 1847a51313dSChris Lattner 1857a51313dSChris Lattner // By default, initialize it to invalid. 18613156b68SDavid Blaikie NamedDirEnt.second = NON_EXISTENT_DIR; 1877a51313dSChris Lattner 1887a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 189e1dd3e2cSZhanyong Wan // SeenDirEntries map. 19013156b68SDavid Blaikie const char *InterndDirName = NamedDirEnt.first().data(); 1917a51313dSChris Lattner 1927a51313dSChris Lattner // Check to see if the directory exists. 193f8f91b89SRafael Espindola FileData Data; 194f1186c5aSCraig Topper if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) { 195e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 1961735f4e7SDouglas Gregor if (!CacheFailure) 1971735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 198f1186c5aSCraig Topper return nullptr; 199e1dd3e2cSZhanyong Wan } 2007a51313dSChris Lattner 201e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 202e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 203e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 204e1dd3e2cSZhanyong Wan // Windows). 205c9b7234eSBen Langmuir DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID]; 2067a51313dSChris Lattner 20713156b68SDavid Blaikie NamedDirEnt.second = &UDE; 208e1dd3e2cSZhanyong Wan if (!UDE.getName()) { 209e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 210e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 2117a51313dSChris Lattner UDE.Name = InterndDirName; 212e1dd3e2cSZhanyong Wan } 213e1dd3e2cSZhanyong Wan 2147a51313dSChris Lattner return &UDE; 2157a51313dSChris Lattner } 2167a51313dSChris Lattner 2171735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, 2181735f4e7SDouglas Gregor bool CacheFailure) { 2197a51313dSChris Lattner ++NumFileLookups; 2207a51313dSChris Lattner 2217a51313dSChris Lattner // See if there is already an entry in the map. 22213156b68SDavid Blaikie auto &NamedFileEnt = 22313156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 2247a51313dSChris Lattner 2257a51313dSChris Lattner // See if there is already an entry in the map. 22613156b68SDavid Blaikie if (NamedFileEnt.second) 22713156b68SDavid Blaikie return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr 22813156b68SDavid Blaikie : NamedFileEnt.second; 2297a51313dSChris Lattner 2307a51313dSChris Lattner ++NumFileCacheMisses; 2317a51313dSChris Lattner 2327a51313dSChris Lattner // By default, initialize it to invalid. 23313156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 2347a51313dSChris Lattner 2357a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 236e1dd3e2cSZhanyong Wan // SeenFileEntries map. 23713156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 2387a51313dSChris Lattner 239966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 240966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 241966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 242966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 243966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 2441735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 2451735f4e7SDouglas Gregor CacheFailure); 246f1186c5aSCraig Topper if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. 2471735f4e7SDouglas Gregor if (!CacheFailure) 2481735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2491735f4e7SDouglas Gregor 250f1186c5aSCraig Topper return nullptr; 2511735f4e7SDouglas Gregor } 252407e2124SDouglas Gregor 2537a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2547a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2557a51313dSChris Lattner 2567a51313dSChris Lattner // Nope, there isn't. Check to see if the file exists. 257326ffb36SDavid Blaikie std::unique_ptr<vfs::File> F; 258f8f91b89SRafael Espindola FileData Data; 259f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { 260e1dd3e2cSZhanyong Wan // There's no real file at the given path. 2611735f4e7SDouglas Gregor if (!CacheFailure) 2621735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2631735f4e7SDouglas Gregor 264f1186c5aSCraig Topper return nullptr; 265e1dd3e2cSZhanyong Wan } 2667a51313dSChris Lattner 267ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 268d6278e32SArgyrios Kyrtzidis 2697a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2707a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 271c9b7234eSBen Langmuir FileEntry &UFE = UniqueRealFiles[Data.UniqueID]; 2727a51313dSChris Lattner 27313156b68SDavid Blaikie NamedFileEnt.second = &UFE; 274ab86fbe4SBen Langmuir 275ab86fbe4SBen Langmuir // If the name returned by getStatValue is different than Filename, re-intern 276ab86fbe4SBen Langmuir // the name. 277ab86fbe4SBen Langmuir if (Data.Name != Filename) { 27813156b68SDavid Blaikie auto &NamedFileEnt = 27913156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first; 28013156b68SDavid Blaikie if (!NamedFileEnt.second) 28113156b68SDavid Blaikie NamedFileEnt.second = &UFE; 282ab86fbe4SBen Langmuir else 28313156b68SDavid Blaikie assert(NamedFileEnt.second == &UFE && 284ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file"); 28513156b68SDavid Blaikie InterndFileName = NamedFileEnt.first().data(); 286ab86fbe4SBen Langmuir } 287ab86fbe4SBen Langmuir 288c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2895de00f3bSBen Langmuir 2905de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 2915de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 2925de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 2935de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 2945de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 2955de00f3bSBen Langmuir // multiple names. 2965de00f3bSBen Langmuir if (DirInfo != UFE.Dir && Data.IsVFSMapped) 2975de00f3bSBen Langmuir UFE.Dir = DirInfo; 2985de00f3bSBen Langmuir 299c0ff9908SManuel Klimek // Always update the name to use the last name by which a file was accessed. 300c0ff9908SManuel Klimek // FIXME: Neither this nor always using the first name is correct; we want 301c0ff9908SManuel Klimek // to switch towards a design where we return a FileName object that 302c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the 303c0ff9908SManuel Klimek // corresponding FileEntry. 304ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 305c0ff9908SManuel Klimek 3067a51313dSChris Lattner return &UFE; 307dd278430SChris Lattner } 3087a51313dSChris Lattner 309c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 310ab86fbe4SBen Langmuir UFE.Name = InterndFileName; 311f8f91b89SRafael Espindola UFE.Size = Data.Size; 312f8f91b89SRafael Espindola UFE.ModTime = Data.ModTime; 3137a51313dSChris Lattner UFE.Dir = DirInfo; 3147a51313dSChris Lattner UFE.UID = NextFileUID++; 315c9b7234eSBen Langmuir UFE.UniqueID = Data.UniqueID; 316c9b7234eSBen Langmuir UFE.IsNamedPipe = Data.IsNamedPipe; 317c9b7234eSBen Langmuir UFE.InPCH = Data.InPCH; 318326ffb36SDavid Blaikie UFE.File = std::move(F); 319c8a71468SBen Langmuir UFE.IsValid = true; 3207a51313dSChris Lattner return &UFE; 3217a51313dSChris Lattner } 3227a51313dSChris Lattner 323407e2124SDouglas Gregor const FileEntry * 3240e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3255159f616SChris Lattner time_t ModificationTime) { 326407e2124SDouglas Gregor ++NumFileLookups; 327407e2124SDouglas Gregor 328407e2124SDouglas Gregor // See if there is already an entry in the map. 32913156b68SDavid Blaikie auto &NamedFileEnt = 33013156b68SDavid Blaikie *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 331407e2124SDouglas Gregor 332407e2124SDouglas Gregor // See if there is already an entry in the map. 33313156b68SDavid Blaikie if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE) 33413156b68SDavid Blaikie return NamedFileEnt.second; 335407e2124SDouglas Gregor 336407e2124SDouglas Gregor ++NumFileCacheMisses; 337407e2124SDouglas Gregor 338407e2124SDouglas Gregor // By default, initialize it to invalid. 33913156b68SDavid Blaikie NamedFileEnt.second = NON_EXISTENT_FILE; 340407e2124SDouglas Gregor 341e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 342f1186c5aSCraig Topper FileEntry *UFE = nullptr; 343e1dd3e2cSZhanyong Wan 344e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 345e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 346e1dd3e2cSZhanyong Wan // cache. 3471735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 3481735f4e7SDouglas Gregor /*CacheFailure=*/true); 349e1dd3e2cSZhanyong Wan assert(DirInfo && 350e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 351e1dd3e2cSZhanyong Wan 352606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 353f8f91b89SRafael Espindola FileData Data; 35413156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data(); 355f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { 356f8f91b89SRafael Espindola Data.Size = Size; 357f8f91b89SRafael Espindola Data.ModTime = ModificationTime; 358c9b7234eSBen Langmuir UFE = &UniqueRealFiles[Data.UniqueID]; 359606c4ac3SDouglas Gregor 36013156b68SDavid Blaikie NamedFileEnt.second = UFE; 361606c4ac3SDouglas Gregor 362606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 363606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 364606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 365c8130a74SBen Langmuir if (UFE->File) 366c8130a74SBen Langmuir UFE->closeFile(); 367606c4ac3SDouglas Gregor 368606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 369c8a71468SBen Langmuir if (UFE->isValid()) 370606c4ac3SDouglas Gregor return UFE; 371c9b7234eSBen Langmuir 372c9b7234eSBen Langmuir UFE->UniqueID = Data.UniqueID; 373c9b7234eSBen Langmuir UFE->IsNamedPipe = Data.IsNamedPipe; 374c9b7234eSBen Langmuir UFE->InPCH = Data.InPCH; 375606c4ac3SDouglas Gregor } 376606c4ac3SDouglas Gregor 377606c4ac3SDouglas Gregor if (!UFE) { 378606c4ac3SDouglas Gregor UFE = new FileEntry(); 379407e2124SDouglas Gregor VirtualFileEntries.push_back(UFE); 38013156b68SDavid Blaikie NamedFileEnt.second = UFE; 381606c4ac3SDouglas Gregor } 382407e2124SDouglas Gregor 3839624b695SChris Lattner UFE->Name = InterndFileName; 384407e2124SDouglas Gregor UFE->Size = Size; 385407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 386407e2124SDouglas Gregor UFE->Dir = DirInfo; 387407e2124SDouglas Gregor UFE->UID = NextFileUID++; 388c8130a74SBen Langmuir UFE->File.reset(); 389407e2124SDouglas Gregor return UFE; 390407e2124SDouglas Gregor } 391407e2124SDouglas Gregor 392c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 3930e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 394b5c356a4SAnders Carlsson 3959ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 3969ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 397c56419edSArgyrios Kyrtzidis return false; 39871731d6bSArgyrios Kyrtzidis 3992c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 400b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 4016e640998SChris Lattner path = NewPath; 402c56419edSArgyrios Kyrtzidis return true; 403c56419edSArgyrios Kyrtzidis } 404c56419edSArgyrios Kyrtzidis 405c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 406c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path); 407c56419edSArgyrios Kyrtzidis 408c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 409c56419edSArgyrios Kyrtzidis llvm::sys::fs::make_absolute(Path); 410c56419edSArgyrios Kyrtzidis Changed = true; 411c56419edSArgyrios Kyrtzidis } 412c56419edSArgyrios Kyrtzidis 413c56419edSArgyrios Kyrtzidis return Changed; 4146e640998SChris Lattner } 4156e640998SChris Lattner 416a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 417a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 418a885796dSBenjamin Kramer bool ShouldCloseOpenFile) { 4196d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 4206d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 4216d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 4226d7833f1SArgyrios Kyrtzidis if (isVolatile) 4236d7833f1SArgyrios Kyrtzidis FileSize = -1; 4246d7833f1SArgyrios Kyrtzidis 4255ea7d07dSChris Lattner const char *Filename = Entry->getName(); 4265ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 427c8130a74SBen Langmuir if (Entry->File) { 428a885796dSBenjamin Kramer auto Result = 429a885796dSBenjamin Kramer Entry->File->getBuffer(Filename, FileSize, 43026d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4319801b253SBen Langmuir // FIXME: we need a set of APIs that can make guarantees about whether a 4329801b253SBen Langmuir // FileEntry is open or not. 4339801b253SBen Langmuir if (ShouldCloseOpenFile) 434c8130a74SBen Langmuir Entry->closeFile(); 4356406f7b8SRafael Espindola return Result; 4365ea7d07dSChris Lattner } 4376e640998SChris Lattner 4385ea7d07dSChris Lattner // Otherwise, open the file. 439669b0b15SArgyrios Kyrtzidis 440a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 441a885796dSBenjamin Kramer return FS->getBufferForFile(Filename, FileSize, 44226d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 4435ea7d07dSChris Lattner 4442c1dd271SDylan Noblesmith SmallString<128> FilePath(Entry->getName()); 445878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 44692e1b62dSYaron Keren return FS->getBufferForFile(FilePath, FileSize, 44726d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 44826b5c190SChris Lattner } 44926b5c190SChris Lattner 450a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 451a885796dSBenjamin Kramer FileManager::getBufferForFile(StringRef Filename) { 452a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty()) 453a885796dSBenjamin Kramer return FS->getBufferForFile(Filename); 45426b5c190SChris Lattner 4552c1dd271SDylan Noblesmith SmallString<128> FilePath(Filename); 456878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 457a885796dSBenjamin Kramer return FS->getBufferForFile(FilePath.c_str()); 45871731d6bSArgyrios Kyrtzidis } 45971731d6bSArgyrios Kyrtzidis 460e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 461e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 462e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 463e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 464e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 465f8f91b89SRafael Espindola bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile, 466326ffb36SDavid Blaikie std::unique_ptr<vfs::File> *F) { 467226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 468226efd35SChris Lattner // absolute! 4695769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 470c8130a74SBen Langmuir return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); 471226efd35SChris Lattner 4722c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 473878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 47471731d6bSArgyrios Kyrtzidis 475c8130a74SBen Langmuir return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, 476c8130a74SBen Langmuir StatCache.get(), *FS); 47771731d6bSArgyrios Kyrtzidis } 47871731d6bSArgyrios Kyrtzidis 4790e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path, 480c8130a74SBen Langmuir vfs::Status &Result) { 4812c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 4825e368405SAnders Carlsson FixupRelativePath(FilePath); 4835e368405SAnders Carlsson 484c8130a74SBen Langmuir llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str()); 485c8130a74SBen Langmuir if (!S) 486c8130a74SBen Langmuir return true; 487c8130a74SBen Langmuir Result = *S; 488c8130a74SBen Langmuir return false; 4895e368405SAnders Carlsson } 4905e368405SAnders Carlsson 491b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) { 492b3074003SAxel Naumann assert(Entry && "Cannot invalidate a NULL FileEntry"); 49338179d96SAxel Naumann 49438179d96SAxel Naumann SeenFileEntries.erase(Entry->getName()); 495b3074003SAxel Naumann 496b3074003SAxel Naumann // FileEntry invalidation should not block future optimizations in the file 497b3074003SAxel Naumann // caches. Possible alternatives are cache truncation (invalidate last N) or 498b3074003SAxel Naumann // invalidation of the whole cache. 499c9b7234eSBen Langmuir UniqueRealFiles.erase(Entry->getUniqueID()); 50038179d96SAxel Naumann } 50138179d96SAxel Naumann 50238179d96SAxel Naumann 50309b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 5040e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 50509b6989eSDouglas Gregor UIDToFiles.clear(); 50609b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 50709b6989eSDouglas Gregor 50809b6989eSDouglas Gregor // Map file entries 50909b6989eSDouglas Gregor for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator 510e1dd3e2cSZhanyong Wan FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); 51109b6989eSDouglas Gregor FE != FEEnd; ++FE) 51209b6989eSDouglas Gregor if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) 51309b6989eSDouglas Gregor UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); 51409b6989eSDouglas Gregor 51509b6989eSDouglas Gregor // Map virtual file entries 5162341c0d3SCraig Topper for (SmallVectorImpl<FileEntry *>::const_iterator 51709b6989eSDouglas Gregor VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end(); 51809b6989eSDouglas Gregor VFE != VFEEnd; ++VFE) 51909b6989eSDouglas Gregor if (*VFE && *VFE != NON_EXISTENT_FILE) 52009b6989eSDouglas Gregor UIDToFiles[(*VFE)->getUID()] = *VFE; 52109b6989eSDouglas Gregor } 522226efd35SChris Lattner 5236eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File, 5246eec06d0SArgyrios Kyrtzidis off_t Size, time_t ModificationTime) { 5256eec06d0SArgyrios Kyrtzidis File->Size = Size; 5266eec06d0SArgyrios Kyrtzidis File->ModTime = ModificationTime; 5276eec06d0SArgyrios Kyrtzidis } 5286eec06d0SArgyrios Kyrtzidis 529b963dedbSSean Silva /// Remove '.' and '..' path components from the given absolute path. 53054cc3c2fSRichard Smith /// \return \c true if any changes were made. 53154cc3c2fSRichard Smith // FIXME: Move this to llvm::sys::path. 5323e36e507SSean Silva bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path, bool RemoveDotDot) { 53354cc3c2fSRichard Smith using namespace llvm::sys; 53454cc3c2fSRichard Smith 53554cc3c2fSRichard Smith SmallVector<StringRef, 16> ComponentStack; 53654cc3c2fSRichard Smith StringRef P(Path.data(), Path.size()); 53754cc3c2fSRichard Smith 53854cc3c2fSRichard Smith // Skip the root path, then look for traversal in the components. 53954cc3c2fSRichard Smith StringRef Rel = path::relative_path(P); 54054cc3c2fSRichard Smith for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) { 541b963dedbSSean Silva if (C == ".") 542b963dedbSSean Silva continue; 5433e36e507SSean Silva if (RemoveDotDot) { 544b963dedbSSean Silva if (C == "..") { 545b963dedbSSean Silva if (!ComponentStack.empty()) 546b963dedbSSean Silva ComponentStack.pop_back(); 54754cc3c2fSRichard Smith continue; 54854cc3c2fSRichard Smith } 5493e36e507SSean Silva } 55054cc3c2fSRichard Smith ComponentStack.push_back(C); 55154cc3c2fSRichard Smith } 55254cc3c2fSRichard Smith 55354cc3c2fSRichard Smith SmallString<256> Buffer = path::root_path(P); 55454cc3c2fSRichard Smith for (StringRef C : ComponentStack) 55554cc3c2fSRichard Smith path::append(Buffer, C); 55654cc3c2fSRichard Smith 557b963dedbSSean Silva bool Changed = (Path != Buffer); 55854cc3c2fSRichard Smith Path.swap(Buffer); 559b963dedbSSean Silva return Changed; 56054cc3c2fSRichard Smith } 56154cc3c2fSRichard Smith 562e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 563e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 564e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 565e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 566e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 567e00c8b20SDouglas Gregor return Known->second; 568e00c8b20SDouglas Gregor 569e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 57054cc3c2fSRichard Smith 57154cc3c2fSRichard Smith #ifdef LLVM_ON_UNIX 572e00c8b20SDouglas Gregor char CanonicalNameBuf[PATH_MAX]; 573*da4690aeSBenjamin Kramer if (realpath(Dir->getName(), CanonicalNameBuf)) 574*da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 57554cc3c2fSRichard Smith #else 57654cc3c2fSRichard Smith SmallString<256> CanonicalNameBuf(CanonicalName); 57754cc3c2fSRichard Smith llvm::sys::fs::make_absolute(CanonicalNameBuf); 57854cc3c2fSRichard Smith llvm::sys::path::native(CanonicalNameBuf); 579de381665SSean Silva // We've run into needing to remove '..' here in the wild though, so 580de381665SSean Silva // remove it. 581de381665SSean Silva // On Windows, symlinks are significantly less prevalent, so removing 582de381665SSean Silva // '..' is pretty safe. 583de381665SSean Silva // Ideally we'd have an equivalent of `realpath` and could implement 584de381665SSean Silva // sys::fs::canonical across all the platforms. 585de381665SSean Silva removeDotPaths(CanonicalNameBuf, /*RemoveDotDot*/true); 586*da4690aeSBenjamin Kramer CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 58754cc3c2fSRichard Smith #endif 588e00c8b20SDouglas Gregor 589e00c8b20SDouglas Gregor CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); 590e00c8b20SDouglas Gregor return CanonicalName; 591e00c8b20SDouglas Gregor } 592226efd35SChris Lattner 5937a51313dSChris Lattner void FileManager::PrintStats() const { 59489b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 595e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 596e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 597e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 598e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 59989b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 6007a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 60189b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 6027a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 6037a51313dSChris Lattner 60489b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 6057a51313dSChris Lattner } 606075bf567SAdrian Prantl 607fb2398d0SAdrian Prantl // Virtual destructors for abstract base classes that need live in Basic. 608fb2398d0SAdrian Prantl PCHContainerWriter::~PCHContainerWriter() {} 609fb2398d0SAdrian Prantl PCHContainerReader::~PCHContainerReader() {} 610