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" 28f25faaafSMichael J. Spencer #include "llvm/Support/system_error.h" 2926db6481SBenjamin Kramer #include <map> 3026db6481SBenjamin Kramer #include <set> 3126db6481SBenjamin Kramer #include <string> 32278038b4SChris Lattner 337a51313dSChris Lattner using namespace clang; 347a51313dSChris Lattner 357a51313dSChris Lattner // FIXME: Enhance libsystem to support inode and other fields. 367a51313dSChris Lattner #include <sys/stat.h> 377a51313dSChris Lattner 387a51313dSChris Lattner /// NON_EXISTENT_DIR - A special value distinct from null that is used to 397a51313dSChris Lattner /// represent a dir name that doesn't exist on the disk. 407a51313dSChris Lattner #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) 417a51313dSChris Lattner 429624b695SChris Lattner /// NON_EXISTENT_FILE - A special value distinct from null that is used to 439624b695SChris Lattner /// represent a filename that doesn't exist on the disk. 449624b695SChris Lattner #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) 459624b695SChris Lattner 465c04bd81STed Kremenek //===----------------------------------------------------------------------===// 475c04bd81STed Kremenek // Common logic. 485c04bd81STed Kremenek //===----------------------------------------------------------------------===// 497a51313dSChris Lattner 50c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO, 51c8130a74SBen Langmuir IntrusiveRefCntPtr<vfs::FileSystem> FS) 52c8130a74SBen Langmuir : FS(FS), FileSystemOpts(FSO), 53e1dd3e2cSZhanyong Wan SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) { 547a51313dSChris Lattner NumDirLookups = NumFileLookups = 0; 557a51313dSChris Lattner NumDirCacheMisses = NumFileCacheMisses = 0; 56c8130a74SBen Langmuir 57c8130a74SBen Langmuir // If the caller doesn't provide a virtual file system, just grab the real 58c8130a74SBen Langmuir // file system. 59c8130a74SBen Langmuir if (!FS) 60c8130a74SBen Langmuir this->FS = vfs::getRealFileSystem(); 617a51313dSChris Lattner } 627a51313dSChris Lattner 637a51313dSChris Lattner FileManager::~FileManager() { 64966b25b9SChris Lattner for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i) 65966b25b9SChris Lattner delete VirtualFileEntries[i]; 66e1dd3e2cSZhanyong Wan for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i) 67e1dd3e2cSZhanyong Wan delete VirtualDirectoryEntries[i]; 687a51313dSChris Lattner } 697a51313dSChris Lattner 70226efd35SChris Lattner void FileManager::addStatCache(FileSystemStatCache *statCache, 71226efd35SChris Lattner bool AtBeginning) { 72d2eb58abSDouglas Gregor assert(statCache && "No stat cache provided?"); 73f1186c5aSCraig Topper if (AtBeginning || !StatCache.get()) { 749a16beb8SAhmed Charles statCache->setNextStatCache(StatCache.release()); 75d2eb58abSDouglas Gregor StatCache.reset(statCache); 76d2eb58abSDouglas Gregor return; 77d2eb58abSDouglas Gregor } 78d2eb58abSDouglas Gregor 79226efd35SChris Lattner FileSystemStatCache *LastCache = StatCache.get(); 80d2eb58abSDouglas Gregor while (LastCache->getNextStatCache()) 81d2eb58abSDouglas Gregor LastCache = LastCache->getNextStatCache(); 82d2eb58abSDouglas Gregor 83d2eb58abSDouglas Gregor LastCache->setNextStatCache(statCache); 84d2eb58abSDouglas Gregor } 85d2eb58abSDouglas Gregor 86226efd35SChris Lattner void FileManager::removeStatCache(FileSystemStatCache *statCache) { 87d2eb58abSDouglas Gregor if (!statCache) 88d2eb58abSDouglas Gregor return; 89d2eb58abSDouglas Gregor 90d2eb58abSDouglas Gregor if (StatCache.get() == statCache) { 91d2eb58abSDouglas Gregor // This is the first stat cache. 92d2eb58abSDouglas Gregor StatCache.reset(StatCache->takeNextStatCache()); 93d2eb58abSDouglas Gregor return; 94d2eb58abSDouglas Gregor } 95d2eb58abSDouglas Gregor 96d2eb58abSDouglas Gregor // Find the stat cache in the list. 97226efd35SChris Lattner FileSystemStatCache *PrevCache = StatCache.get(); 98d2eb58abSDouglas Gregor while (PrevCache && PrevCache->getNextStatCache() != statCache) 99d2eb58abSDouglas Gregor PrevCache = PrevCache->getNextStatCache(); 1009624b695SChris Lattner 1019624b695SChris Lattner assert(PrevCache && "Stat cache not found for removal"); 102d2eb58abSDouglas Gregor PrevCache->setNextStatCache(statCache->getNextStatCache()); 103d2eb58abSDouglas Gregor } 104d2eb58abSDouglas Gregor 1053aad855aSManuel Klimek void FileManager::clearStatCaches() { 106f1186c5aSCraig Topper StatCache.reset(nullptr); 1073aad855aSManuel Klimek } 1083aad855aSManuel Klimek 109407e2124SDouglas Gregor /// \brief Retrieve the directory that the given file name resides in. 110e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file. 111407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, 1121735f4e7SDouglas Gregor StringRef Filename, 1131735f4e7SDouglas Gregor bool CacheFailure) { 114f3c0ff73SZhanyong Wan if (Filename.empty()) 115f1186c5aSCraig Topper return nullptr; 116e1dd3e2cSZhanyong Wan 117f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 118f1186c5aSCraig Topper return nullptr; // If Filename is a directory. 1190c0e8040SChris Lattner 1200e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename); 1210c0e8040SChris Lattner // Use the current directory if file has no path component. 122f3c0ff73SZhanyong Wan if (DirName.empty()) 123f3c0ff73SZhanyong Wan DirName = "."; 1240c0e8040SChris Lattner 1251735f4e7SDouglas Gregor return FileMgr.getDirectory(DirName, CacheFailure); 126407e2124SDouglas Gregor } 127407e2124SDouglas Gregor 128e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or 129e1dd3e2cSZhanyong Wan /// a directory) as virtual directories. 1300e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 1310e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path); 132f3c0ff73SZhanyong Wan if (DirName.empty()) 133e1dd3e2cSZhanyong Wan return; 134e1dd3e2cSZhanyong Wan 135e1dd3e2cSZhanyong Wan llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt = 136e1dd3e2cSZhanyong Wan SeenDirEntries.GetOrCreateValue(DirName); 137e1dd3e2cSZhanyong Wan 138e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors 139e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache, 140e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in 141e1dd3e2cSZhanyong Wan // the cache. 142e1dd3e2cSZhanyong Wan if (NamedDirEnt.getValue()) 143e1dd3e2cSZhanyong Wan return; 144e1dd3e2cSZhanyong Wan 145e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache. 146e1dd3e2cSZhanyong Wan DirectoryEntry *UDE = new DirectoryEntry; 147e1dd3e2cSZhanyong Wan UDE->Name = NamedDirEnt.getKeyData(); 148e1dd3e2cSZhanyong Wan NamedDirEnt.setValue(UDE); 149e1dd3e2cSZhanyong Wan VirtualDirectoryEntries.push_back(UDE); 150e1dd3e2cSZhanyong Wan 151e1dd3e2cSZhanyong Wan // Recursively add the other ancestors. 152e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName); 153e1dd3e2cSZhanyong Wan } 154e1dd3e2cSZhanyong Wan 1551735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName, 1561735f4e7SDouglas Gregor bool CacheFailure) { 1578bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory. 15832f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 15932f1acf1SNAKAMURA Takumi // (though it can strip '\\') 1608bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 && 1618bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) && 1628bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back())) 16332f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1); 164ee30546cSRafael Espindola #ifdef LLVM_ON_WIN32 165ee30546cSRafael Espindola // Fixing a problem with "clang C:test.c" on Windows. 166ee30546cSRafael Espindola // Stat("C:") does not recognize "C:" as a valid directory 167ee30546cSRafael Espindola std::string DirNameStr; 168ee30546cSRafael Espindola if (DirName.size() > 1 && DirName.back() == ':' && 169ee30546cSRafael Espindola DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 170ee30546cSRafael Espindola DirNameStr = DirName.str() + '.'; 171ee30546cSRafael Espindola DirName = DirNameStr; 172ee30546cSRafael Espindola } 173ee30546cSRafael Espindola #endif 17432f1acf1SNAKAMURA Takumi 1757a51313dSChris Lattner ++NumDirLookups; 1767a51313dSChris Lattner llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt = 177e1dd3e2cSZhanyong Wan SeenDirEntries.GetOrCreateValue(DirName); 1787a51313dSChris Lattner 179e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map 180e1dd3e2cSZhanyong Wan // contains both virtual and real directories. 1817a51313dSChris Lattner if (NamedDirEnt.getValue()) 182f1186c5aSCraig Topper return NamedDirEnt.getValue() == NON_EXISTENT_DIR ? nullptr 183f1186c5aSCraig Topper : NamedDirEnt.getValue(); 1847a51313dSChris Lattner 1857a51313dSChris Lattner ++NumDirCacheMisses; 1867a51313dSChris Lattner 1877a51313dSChris Lattner // By default, initialize it to invalid. 1887a51313dSChris Lattner NamedDirEnt.setValue(NON_EXISTENT_DIR); 1897a51313dSChris Lattner 1907a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the 191e1dd3e2cSZhanyong Wan // SeenDirEntries map. 1927a51313dSChris Lattner const char *InterndDirName = NamedDirEnt.getKeyData(); 1937a51313dSChris Lattner 1947a51313dSChris Lattner // Check to see if the directory exists. 195f8f91b89SRafael Espindola FileData Data; 196f1186c5aSCraig Topper if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) { 197e1dd3e2cSZhanyong Wan // There's no real directory at the given path. 1981735f4e7SDouglas Gregor if (!CacheFailure) 1991735f4e7SDouglas Gregor SeenDirEntries.erase(DirName); 200f1186c5aSCraig Topper return nullptr; 201e1dd3e2cSZhanyong Wan } 2027a51313dSChris Lattner 203e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the 204e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is 205e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on 206e1dd3e2cSZhanyong Wan // Windows). 207c9b7234eSBen Langmuir DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID]; 2087a51313dSChris Lattner 2097a51313dSChris Lattner NamedDirEnt.setValue(&UDE); 210e1dd3e2cSZhanyong Wan if (!UDE.getName()) { 211e1dd3e2cSZhanyong Wan // We don't have this directory yet, add it. We use the string 212e1dd3e2cSZhanyong Wan // key from the SeenDirEntries map as the string. 2137a51313dSChris Lattner UDE.Name = InterndDirName; 214e1dd3e2cSZhanyong Wan } 215e1dd3e2cSZhanyong Wan 2167a51313dSChris Lattner return &UDE; 2177a51313dSChris Lattner } 2187a51313dSChris Lattner 2191735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, 2201735f4e7SDouglas Gregor bool CacheFailure) { 2217a51313dSChris Lattner ++NumFileLookups; 2227a51313dSChris Lattner 2237a51313dSChris Lattner // See if there is already an entry in the map. 2247a51313dSChris Lattner llvm::StringMapEntry<FileEntry *> &NamedFileEnt = 225e1dd3e2cSZhanyong Wan SeenFileEntries.GetOrCreateValue(Filename); 2267a51313dSChris Lattner 2277a51313dSChris Lattner // See if there is already an entry in the map. 2287a51313dSChris Lattner if (NamedFileEnt.getValue()) 2297a51313dSChris Lattner return NamedFileEnt.getValue() == NON_EXISTENT_FILE 230f1186c5aSCraig Topper ? nullptr : NamedFileEnt.getValue(); 2317a51313dSChris Lattner 2327a51313dSChris Lattner ++NumFileCacheMisses; 2337a51313dSChris Lattner 2347a51313dSChris Lattner // By default, initialize it to invalid. 2357a51313dSChris Lattner NamedFileEnt.setValue(NON_EXISTENT_FILE); 2367a51313dSChris Lattner 2377a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the 238e1dd3e2cSZhanyong Wan // SeenFileEntries map. 2397a51313dSChris Lattner const char *InterndFileName = NamedFileEnt.getKeyData(); 2407a51313dSChris Lattner 241966b25b9SChris Lattner // Look up the directory for the file. When looking up something like 242966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys' 243966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail 244966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories 245966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result. 2461735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 2471735f4e7SDouglas Gregor CacheFailure); 248f1186c5aSCraig Topper if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. 2491735f4e7SDouglas Gregor if (!CacheFailure) 2501735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2511735f4e7SDouglas Gregor 252f1186c5aSCraig Topper return nullptr; 2531735f4e7SDouglas Gregor } 254407e2124SDouglas Gregor 2557a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall. 2567a51313dSChris Lattner // FIXME: This will reduce the # syscalls. 2577a51313dSChris Lattner 2587a51313dSChris Lattner // Nope, there isn't. Check to see if the file exists. 259f1186c5aSCraig Topper vfs::File *F = nullptr; 260f8f91b89SRafael Espindola FileData Data; 261f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { 262e1dd3e2cSZhanyong Wan // There's no real file at the given path. 2631735f4e7SDouglas Gregor if (!CacheFailure) 2641735f4e7SDouglas Gregor SeenFileEntries.erase(Filename); 2651735f4e7SDouglas Gregor 266f1186c5aSCraig Topper return nullptr; 267e1dd3e2cSZhanyong Wan } 2687a51313dSChris Lattner 269ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file"); 270d6278e32SArgyrios Kyrtzidis 2717a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode. 2727a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example. 273c9b7234eSBen Langmuir FileEntry &UFE = UniqueRealFiles[Data.UniqueID]; 2747a51313dSChris Lattner 2757a51313dSChris Lattner NamedFileEnt.setValue(&UFE); 276c8a71468SBen Langmuir if (UFE.isValid()) { // Already have an entry with this inode, return it. 2775de00f3bSBen Langmuir 2785de00f3bSBen Langmuir // FIXME: this hack ensures that if we look up a file by a virtual path in 2795de00f3bSBen Langmuir // the VFS that the getDir() will have the virtual path, even if we found 2805de00f3bSBen Langmuir // the file by a 'real' path first. This is required in order to find a 2815de00f3bSBen Langmuir // module's structure when its headers/module map are mapped in the VFS. 2825de00f3bSBen Langmuir // We should remove this as soon as we can properly support a file having 2835de00f3bSBen Langmuir // multiple names. 2845de00f3bSBen Langmuir if (DirInfo != UFE.Dir && Data.IsVFSMapped) 2855de00f3bSBen Langmuir UFE.Dir = DirInfo; 2865de00f3bSBen Langmuir 287dd278430SChris Lattner // If the stat process opened the file, close it to avoid a FD leak. 288c8130a74SBen Langmuir if (F) 289c8130a74SBen Langmuir delete F; 290dd278430SChris Lattner 2917a51313dSChris Lattner return &UFE; 292dd278430SChris Lattner } 2937a51313dSChris Lattner 294c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it. 295d066d4c8SBen Langmuir UFE.Name = Data.Name; 296f8f91b89SRafael Espindola UFE.Size = Data.Size; 297f8f91b89SRafael Espindola UFE.ModTime = Data.ModTime; 2987a51313dSChris Lattner UFE.Dir = DirInfo; 2997a51313dSChris Lattner UFE.UID = NextFileUID++; 300c9b7234eSBen Langmuir UFE.UniqueID = Data.UniqueID; 301c9b7234eSBen Langmuir UFE.IsNamedPipe = Data.IsNamedPipe; 302c9b7234eSBen Langmuir UFE.InPCH = Data.InPCH; 303c8130a74SBen Langmuir UFE.File.reset(F); 304c8a71468SBen Langmuir UFE.IsValid = true; 3057a51313dSChris Lattner return &UFE; 3067a51313dSChris Lattner } 3077a51313dSChris Lattner 308407e2124SDouglas Gregor const FileEntry * 3090e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size, 3105159f616SChris Lattner time_t ModificationTime) { 311407e2124SDouglas Gregor ++NumFileLookups; 312407e2124SDouglas Gregor 313407e2124SDouglas Gregor // See if there is already an entry in the map. 314407e2124SDouglas Gregor llvm::StringMapEntry<FileEntry *> &NamedFileEnt = 315e1dd3e2cSZhanyong Wan SeenFileEntries.GetOrCreateValue(Filename); 316407e2124SDouglas Gregor 317407e2124SDouglas Gregor // See if there is already an entry in the map. 31863fbaedaSAxel Naumann if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE) 31963fbaedaSAxel Naumann return NamedFileEnt.getValue(); 320407e2124SDouglas Gregor 321407e2124SDouglas Gregor ++NumFileCacheMisses; 322407e2124SDouglas Gregor 323407e2124SDouglas Gregor // By default, initialize it to invalid. 324407e2124SDouglas Gregor NamedFileEnt.setValue(NON_EXISTENT_FILE); 325407e2124SDouglas Gregor 326e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename); 327f1186c5aSCraig Topper FileEntry *UFE = nullptr; 328e1dd3e2cSZhanyong Wan 329e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the 330e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the 331e1dd3e2cSZhanyong Wan // cache. 3321735f4e7SDouglas Gregor const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 3331735f4e7SDouglas Gregor /*CacheFailure=*/true); 334e1dd3e2cSZhanyong Wan assert(DirInfo && 335e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache."); 336e1dd3e2cSZhanyong Wan 337606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file 338f8f91b89SRafael Espindola FileData Data; 339606c4ac3SDouglas Gregor const char *InterndFileName = NamedFileEnt.getKeyData(); 340f1186c5aSCraig Topper if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { 341f8f91b89SRafael Espindola Data.Size = Size; 342f8f91b89SRafael Espindola Data.ModTime = ModificationTime; 343c9b7234eSBen Langmuir UFE = &UniqueRealFiles[Data.UniqueID]; 344606c4ac3SDouglas Gregor 345606c4ac3SDouglas Gregor NamedFileEnt.setValue(UFE); 346606c4ac3SDouglas Gregor 347606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't 348606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file 349606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file. 350c8130a74SBen Langmuir if (UFE->File) 351c8130a74SBen Langmuir UFE->closeFile(); 352606c4ac3SDouglas Gregor 353606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it. 354c8a71468SBen Langmuir if (UFE->isValid()) 355606c4ac3SDouglas Gregor return UFE; 356c9b7234eSBen Langmuir 357c9b7234eSBen Langmuir UFE->UniqueID = Data.UniqueID; 358c9b7234eSBen Langmuir UFE->IsNamedPipe = Data.IsNamedPipe; 359c9b7234eSBen Langmuir UFE->InPCH = Data.InPCH; 360606c4ac3SDouglas Gregor } 361606c4ac3SDouglas Gregor 362606c4ac3SDouglas Gregor if (!UFE) { 363606c4ac3SDouglas Gregor UFE = new FileEntry(); 364407e2124SDouglas Gregor VirtualFileEntries.push_back(UFE); 365407e2124SDouglas Gregor NamedFileEnt.setValue(UFE); 366606c4ac3SDouglas Gregor } 367407e2124SDouglas Gregor 3689624b695SChris Lattner UFE->Name = InterndFileName; 369407e2124SDouglas Gregor UFE->Size = Size; 370407e2124SDouglas Gregor UFE->ModTime = ModificationTime; 371407e2124SDouglas Gregor UFE->Dir = DirInfo; 372407e2124SDouglas Gregor UFE->UID = NextFileUID++; 373c8130a74SBen Langmuir UFE->File.reset(); 374407e2124SDouglas Gregor return UFE; 375407e2124SDouglas Gregor } 376407e2124SDouglas Gregor 3770e62c1ccSChris Lattner void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 3780e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size()); 379b5c356a4SAnders Carlsson 3809ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty() 3819ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef)) 382f28df4cdSMichael J. Spencer return; 38371731d6bSArgyrios Kyrtzidis 3842c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir); 385b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef); 3866e640998SChris Lattner path = NewPath; 3876e640998SChris Lattner } 3886e640998SChris Lattner 3896e640998SChris Lattner llvm::MemoryBuffer *FileManager:: 3906d7833f1SArgyrios Kyrtzidis getBufferForFile(const FileEntry *Entry, std::string *ErrorStr, 3916d7833f1SArgyrios Kyrtzidis bool isVolatile) { 392b8984329SAhmed Charles std::unique_ptr<llvm::MemoryBuffer> Result; 393*c080917eSRafael Espindola std::error_code ec; 394669b0b15SArgyrios Kyrtzidis 3956d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize(); 3966d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we 3976d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it. 3986d7833f1SArgyrios Kyrtzidis if (isVolatile) 3996d7833f1SArgyrios Kyrtzidis FileSize = -1; 4006d7833f1SArgyrios Kyrtzidis 4015ea7d07dSChris Lattner const char *Filename = Entry->getName(); 4025ea7d07dSChris Lattner // If the file is already open, use the open file descriptor. 403c8130a74SBen Langmuir if (Entry->File) { 40426d56393SArgyrios Kyrtzidis ec = Entry->File->getBuffer(Filename, Result, FileSize, 40526d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 406d9da7a1fSMichael J. Spencer if (ErrorStr) 407f25faaafSMichael J. Spencer *ErrorStr = ec.message(); 408c8130a74SBen Langmuir Entry->closeFile(); 4099a16beb8SAhmed Charles return Result.release(); 4105ea7d07dSChris Lattner } 4116e640998SChris Lattner 4125ea7d07dSChris Lattner // Otherwise, open the file. 413669b0b15SArgyrios Kyrtzidis 414669b0b15SArgyrios Kyrtzidis if (FileSystemOpts.WorkingDir.empty()) { 41526d56393SArgyrios Kyrtzidis ec = FS->getBufferForFile(Filename, Result, FileSize, 41626d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 417d9da7a1fSMichael J. Spencer if (ec && ErrorStr) 418f25faaafSMichael J. Spencer *ErrorStr = ec.message(); 4199a16beb8SAhmed Charles return Result.release(); 4205ea7d07dSChris Lattner } 4215ea7d07dSChris Lattner 4222c1dd271SDylan Noblesmith SmallString<128> FilePath(Entry->getName()); 423878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 42426d56393SArgyrios Kyrtzidis ec = FS->getBufferForFile(FilePath.str(), Result, FileSize, 42526d56393SArgyrios Kyrtzidis /*RequiresNullTerminator=*/true, isVolatile); 426d9da7a1fSMichael J. Spencer if (ec && ErrorStr) 427f25faaafSMichael J. Spencer *ErrorStr = ec.message(); 4289a16beb8SAhmed Charles return Result.release(); 42926b5c190SChris Lattner } 43026b5c190SChris Lattner 43126b5c190SChris Lattner llvm::MemoryBuffer *FileManager:: 4320e62c1ccSChris Lattner getBufferForFile(StringRef Filename, std::string *ErrorStr) { 433b8984329SAhmed Charles std::unique_ptr<llvm::MemoryBuffer> Result; 434*c080917eSRafael Espindola std::error_code ec; 435f25faaafSMichael J. Spencer if (FileSystemOpts.WorkingDir.empty()) { 436c8130a74SBen Langmuir ec = FS->getBufferForFile(Filename, Result); 437d9da7a1fSMichael J. Spencer if (ec && ErrorStr) 438f25faaafSMichael J. Spencer *ErrorStr = ec.message(); 4399a16beb8SAhmed Charles return Result.release(); 440f25faaafSMichael J. Spencer } 44126b5c190SChris Lattner 4422c1dd271SDylan Noblesmith SmallString<128> FilePath(Filename); 443878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 444c8130a74SBen Langmuir ec = FS->getBufferForFile(FilePath.c_str(), Result); 445d9da7a1fSMichael J. Spencer if (ec && ErrorStr) 446f25faaafSMichael J. Spencer *ErrorStr = ec.message(); 4479a16beb8SAhmed Charles return Result.release(); 44871731d6bSArgyrios Kyrtzidis } 44971731d6bSArgyrios Kyrtzidis 450e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path, 451e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true 452e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns 453e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL, 454e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up. 455f8f91b89SRafael Espindola bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile, 456c8130a74SBen Langmuir vfs::File **F) { 457226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 458226efd35SChris Lattner // absolute! 4595769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty()) 460c8130a74SBen Langmuir return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); 461226efd35SChris Lattner 4622c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 463878b3e2bSAnders Carlsson FixupRelativePath(FilePath); 46471731d6bSArgyrios Kyrtzidis 465c8130a74SBen Langmuir return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, 466c8130a74SBen Langmuir StatCache.get(), *FS); 46771731d6bSArgyrios Kyrtzidis } 46871731d6bSArgyrios Kyrtzidis 4690e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path, 470c8130a74SBen Langmuir vfs::Status &Result) { 4712c1dd271SDylan Noblesmith SmallString<128> FilePath(Path); 4725e368405SAnders Carlsson FixupRelativePath(FilePath); 4735e368405SAnders Carlsson 474c8130a74SBen Langmuir llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str()); 475c8130a74SBen Langmuir if (!S) 476c8130a74SBen Langmuir return true; 477c8130a74SBen Langmuir Result = *S; 478c8130a74SBen Langmuir return false; 4795e368405SAnders Carlsson } 4805e368405SAnders Carlsson 481b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) { 482b3074003SAxel Naumann assert(Entry && "Cannot invalidate a NULL FileEntry"); 48338179d96SAxel Naumann 48438179d96SAxel Naumann SeenFileEntries.erase(Entry->getName()); 485b3074003SAxel Naumann 486b3074003SAxel Naumann // FileEntry invalidation should not block future optimizations in the file 487b3074003SAxel Naumann // caches. Possible alternatives are cache truncation (invalidate last N) or 488b3074003SAxel Naumann // invalidation of the whole cache. 489c9b7234eSBen Langmuir UniqueRealFiles.erase(Entry->getUniqueID()); 49038179d96SAxel Naumann } 49138179d96SAxel Naumann 49238179d96SAxel Naumann 49309b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping( 4940e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 49509b6989eSDouglas Gregor UIDToFiles.clear(); 49609b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID); 49709b6989eSDouglas Gregor 49809b6989eSDouglas Gregor // Map file entries 49909b6989eSDouglas Gregor for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator 500e1dd3e2cSZhanyong Wan FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); 50109b6989eSDouglas Gregor FE != FEEnd; ++FE) 50209b6989eSDouglas Gregor if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) 50309b6989eSDouglas Gregor UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); 50409b6989eSDouglas Gregor 50509b6989eSDouglas Gregor // Map virtual file entries 5062341c0d3SCraig Topper for (SmallVectorImpl<FileEntry *>::const_iterator 50709b6989eSDouglas Gregor VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end(); 50809b6989eSDouglas Gregor VFE != VFEEnd; ++VFE) 50909b6989eSDouglas Gregor if (*VFE && *VFE != NON_EXISTENT_FILE) 51009b6989eSDouglas Gregor UIDToFiles[(*VFE)->getUID()] = *VFE; 51109b6989eSDouglas Gregor } 512226efd35SChris Lattner 5136eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File, 5146eec06d0SArgyrios Kyrtzidis off_t Size, time_t ModificationTime) { 5156eec06d0SArgyrios Kyrtzidis File->Size = Size; 5166eec06d0SArgyrios Kyrtzidis File->ModTime = ModificationTime; 5176eec06d0SArgyrios Kyrtzidis } 5186eec06d0SArgyrios Kyrtzidis 519e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 520e00c8b20SDouglas Gregor // FIXME: use llvm::sys::fs::canonical() when it gets implemented 521e00c8b20SDouglas Gregor #ifdef LLVM_ON_UNIX 522e00c8b20SDouglas Gregor llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 523e00c8b20SDouglas Gregor = CanonicalDirNames.find(Dir); 524e00c8b20SDouglas Gregor if (Known != CanonicalDirNames.end()) 525e00c8b20SDouglas Gregor return Known->second; 526e00c8b20SDouglas Gregor 527e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName()); 528e00c8b20SDouglas Gregor char CanonicalNameBuf[PATH_MAX]; 529e00c8b20SDouglas Gregor if (realpath(Dir->getName(), CanonicalNameBuf)) { 530e00c8b20SDouglas Gregor unsigned Len = strlen(CanonicalNameBuf); 531e00c8b20SDouglas Gregor char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1)); 532e00c8b20SDouglas Gregor memcpy(Mem, CanonicalNameBuf, Len); 533e00c8b20SDouglas Gregor CanonicalName = StringRef(Mem, Len); 534e00c8b20SDouglas Gregor } 535e00c8b20SDouglas Gregor 536e00c8b20SDouglas Gregor CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); 537e00c8b20SDouglas Gregor return CanonicalName; 538e00c8b20SDouglas Gregor #else 539e00c8b20SDouglas Gregor return StringRef(Dir->getName()); 540e00c8b20SDouglas Gregor #endif 541e00c8b20SDouglas Gregor } 542226efd35SChris Lattner 5437a51313dSChris Lattner void FileManager::PrintStats() const { 54489b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n"; 545e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, " 546e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n"; 547e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 548e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 54989b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, " 5507a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n"; 55189b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, " 5527a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n"; 5537a51313dSChris Lattner 55489b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 5557a51313dSChris Lattner } 556