1226efd35SChris Lattner //===--- FileManager.cpp - File System Probing and Caching ----------------===//
27a51313dSChris Lattner //
37a51313dSChris Lattner //                     The LLVM Compiler Infrastructure
47a51313dSChris Lattner //
57a51313dSChris Lattner // This file is distributed under the University of Illinois Open Source
67a51313dSChris Lattner // License. See LICENSE.TXT for details.
77a51313dSChris Lattner //
87a51313dSChris Lattner //===----------------------------------------------------------------------===//
97a51313dSChris Lattner //
107a51313dSChris Lattner //  This file implements the FileManager interface.
117a51313dSChris Lattner //
127a51313dSChris Lattner //===----------------------------------------------------------------------===//
137a51313dSChris Lattner //
147a51313dSChris Lattner // TODO: This should index all interesting directories with dirent calls.
157a51313dSChris Lattner //  getdirentries ?
167a51313dSChris Lattner //  opendir/readdir_r/closedir ?
177a51313dSChris Lattner //
187a51313dSChris Lattner //===----------------------------------------------------------------------===//
197a51313dSChris Lattner 
207a51313dSChris Lattner #include "clang/Basic/FileManager.h"
21226efd35SChris Lattner #include "clang/Basic/FileSystemStatCache.h"
227a51313dSChris Lattner #include "llvm/ADT/SmallString.h"
233a02247dSChandler Carruth #include "llvm/Config/llvm-config.h"
24740857faSMichael J. Spencer #include "llvm/Support/FileSystem.h"
2571731d6bSArgyrios Kyrtzidis #include "llvm/Support/MemoryBuffer.h"
268aaf4995SMichael J. Spencer #include "llvm/Support/Path.h"
273a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h"
2826db6481SBenjamin Kramer #include <map>
2926db6481SBenjamin Kramer #include <set>
3026db6481SBenjamin Kramer #include <string>
318a8e554aSRafael Espindola #include <system_error>
32278038b4SChris Lattner 
337a51313dSChris Lattner using namespace clang;
347a51313dSChris Lattner 
357a51313dSChris Lattner /// NON_EXISTENT_DIR - A special value distinct from null that is used to
367a51313dSChris Lattner /// represent a dir name that doesn't exist on the disk.
377a51313dSChris Lattner #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
387a51313dSChris Lattner 
399624b695SChris Lattner /// NON_EXISTENT_FILE - A special value distinct from null that is used to
409624b695SChris Lattner /// represent a filename that doesn't exist on the disk.
419624b695SChris Lattner #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
429624b695SChris Lattner 
435c04bd81STed Kremenek //===----------------------------------------------------------------------===//
445c04bd81STed Kremenek // Common logic.
455c04bd81STed Kremenek //===----------------------------------------------------------------------===//
467a51313dSChris Lattner 
47c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO,
48c8130a74SBen Langmuir                          IntrusiveRefCntPtr<vfs::FileSystem> FS)
49c8130a74SBen Langmuir   : FS(FS), FileSystemOpts(FSO),
50e1dd3e2cSZhanyong Wan     SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
517a51313dSChris Lattner   NumDirLookups = NumFileLookups = 0;
527a51313dSChris Lattner   NumDirCacheMisses = NumFileCacheMisses = 0;
53c8130a74SBen Langmuir 
54c8130a74SBen Langmuir   // If the caller doesn't provide a virtual file system, just grab the real
55c8130a74SBen Langmuir   // file system.
56c8130a74SBen Langmuir   if (!FS)
57c8130a74SBen Langmuir     this->FS = vfs::getRealFileSystem();
587a51313dSChris Lattner }
597a51313dSChris Lattner 
607a51313dSChris Lattner FileManager::~FileManager() {
61966b25b9SChris Lattner   for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
62966b25b9SChris Lattner     delete VirtualFileEntries[i];
63e1dd3e2cSZhanyong Wan   for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
64e1dd3e2cSZhanyong Wan     delete VirtualDirectoryEntries[i];
657a51313dSChris Lattner }
667a51313dSChris Lattner 
67226efd35SChris Lattner void FileManager::addStatCache(FileSystemStatCache *statCache,
68226efd35SChris Lattner                                bool AtBeginning) {
69d2eb58abSDouglas Gregor   assert(statCache && "No stat cache provided?");
70f1186c5aSCraig Topper   if (AtBeginning || !StatCache.get()) {
719a16beb8SAhmed Charles     statCache->setNextStatCache(StatCache.release());
72d2eb58abSDouglas Gregor     StatCache.reset(statCache);
73d2eb58abSDouglas Gregor     return;
74d2eb58abSDouglas Gregor   }
75d2eb58abSDouglas Gregor 
76226efd35SChris Lattner   FileSystemStatCache *LastCache = StatCache.get();
77d2eb58abSDouglas Gregor   while (LastCache->getNextStatCache())
78d2eb58abSDouglas Gregor     LastCache = LastCache->getNextStatCache();
79d2eb58abSDouglas Gregor 
80d2eb58abSDouglas Gregor   LastCache->setNextStatCache(statCache);
81d2eb58abSDouglas Gregor }
82d2eb58abSDouglas Gregor 
83226efd35SChris Lattner void FileManager::removeStatCache(FileSystemStatCache *statCache) {
84d2eb58abSDouglas Gregor   if (!statCache)
85d2eb58abSDouglas Gregor     return;
86d2eb58abSDouglas Gregor 
87d2eb58abSDouglas Gregor   if (StatCache.get() == statCache) {
88d2eb58abSDouglas Gregor     // This is the first stat cache.
89d2eb58abSDouglas Gregor     StatCache.reset(StatCache->takeNextStatCache());
90d2eb58abSDouglas Gregor     return;
91d2eb58abSDouglas Gregor   }
92d2eb58abSDouglas Gregor 
93d2eb58abSDouglas Gregor   // Find the stat cache in the list.
94226efd35SChris Lattner   FileSystemStatCache *PrevCache = StatCache.get();
95d2eb58abSDouglas Gregor   while (PrevCache && PrevCache->getNextStatCache() != statCache)
96d2eb58abSDouglas Gregor     PrevCache = PrevCache->getNextStatCache();
979624b695SChris Lattner 
989624b695SChris Lattner   assert(PrevCache && "Stat cache not found for removal");
99d2eb58abSDouglas Gregor   PrevCache->setNextStatCache(statCache->getNextStatCache());
100d2eb58abSDouglas Gregor }
101d2eb58abSDouglas Gregor 
1023aad855aSManuel Klimek void FileManager::clearStatCaches() {
103f1186c5aSCraig Topper   StatCache.reset(nullptr);
1043aad855aSManuel Klimek }
1053aad855aSManuel Klimek 
106407e2124SDouglas Gregor /// \brief Retrieve the directory that the given file name resides in.
107e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file.
108407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
1091735f4e7SDouglas Gregor                                                   StringRef Filename,
1101735f4e7SDouglas Gregor                                                   bool CacheFailure) {
111f3c0ff73SZhanyong Wan   if (Filename.empty())
112f1186c5aSCraig Topper     return nullptr;
113e1dd3e2cSZhanyong Wan 
114f3c0ff73SZhanyong Wan   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
115f1186c5aSCraig Topper     return nullptr; // If Filename is a directory.
1160c0e8040SChris Lattner 
1170e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Filename);
1180c0e8040SChris Lattner   // Use the current directory if file has no path component.
119f3c0ff73SZhanyong Wan   if (DirName.empty())
120f3c0ff73SZhanyong Wan     DirName = ".";
1210c0e8040SChris Lattner 
1221735f4e7SDouglas Gregor   return FileMgr.getDirectory(DirName, CacheFailure);
123407e2124SDouglas Gregor }
124407e2124SDouglas Gregor 
125e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or
126e1dd3e2cSZhanyong Wan /// a directory) as virtual directories.
1270e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
1280e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Path);
129f3c0ff73SZhanyong Wan   if (DirName.empty())
130e1dd3e2cSZhanyong Wan     return;
131e1dd3e2cSZhanyong Wan 
132e1dd3e2cSZhanyong Wan   llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
133e1dd3e2cSZhanyong Wan     SeenDirEntries.GetOrCreateValue(DirName);
134e1dd3e2cSZhanyong Wan 
135e1dd3e2cSZhanyong Wan   // When caching a virtual directory, we always cache its ancestors
136e1dd3e2cSZhanyong Wan   // at the same time.  Therefore, if DirName is already in the cache,
137e1dd3e2cSZhanyong Wan   // we don't need to recurse as its ancestors must also already be in
138e1dd3e2cSZhanyong Wan   // the cache.
139e1dd3e2cSZhanyong Wan   if (NamedDirEnt.getValue())
140e1dd3e2cSZhanyong Wan     return;
141e1dd3e2cSZhanyong Wan 
142e1dd3e2cSZhanyong Wan   // Add the virtual directory to the cache.
143e1dd3e2cSZhanyong Wan   DirectoryEntry *UDE = new DirectoryEntry;
144e1dd3e2cSZhanyong Wan   UDE->Name = NamedDirEnt.getKeyData();
145e1dd3e2cSZhanyong Wan   NamedDirEnt.setValue(UDE);
146e1dd3e2cSZhanyong Wan   VirtualDirectoryEntries.push_back(UDE);
147e1dd3e2cSZhanyong Wan 
148e1dd3e2cSZhanyong Wan   // Recursively add the other ancestors.
149e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(DirName);
150e1dd3e2cSZhanyong Wan }
151e1dd3e2cSZhanyong Wan 
1521735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
1531735f4e7SDouglas Gregor                                                 bool CacheFailure) {
1548bd8ee76SNAKAMURA Takumi   // stat doesn't like trailing separators except for root directory.
15532f1acf1SNAKAMURA Takumi   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
15632f1acf1SNAKAMURA Takumi   // (though it can strip '\\')
1578bd8ee76SNAKAMURA Takumi   if (DirName.size() > 1 &&
1588bd8ee76SNAKAMURA Takumi       DirName != llvm::sys::path::root_path(DirName) &&
1598bd8ee76SNAKAMURA Takumi       llvm::sys::path::is_separator(DirName.back()))
16032f1acf1SNAKAMURA Takumi     DirName = DirName.substr(0, DirName.size()-1);
161ee30546cSRafael Espindola #ifdef LLVM_ON_WIN32
162ee30546cSRafael Espindola   // Fixing a problem with "clang C:test.c" on Windows.
163ee30546cSRafael Espindola   // Stat("C:") does not recognize "C:" as a valid directory
164ee30546cSRafael Espindola   std::string DirNameStr;
165ee30546cSRafael Espindola   if (DirName.size() > 1 && DirName.back() == ':' &&
166ee30546cSRafael Espindola       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
167ee30546cSRafael Espindola     DirNameStr = DirName.str() + '.';
168ee30546cSRafael Espindola     DirName = DirNameStr;
169ee30546cSRafael Espindola   }
170ee30546cSRafael Espindola #endif
17132f1acf1SNAKAMURA Takumi 
1727a51313dSChris Lattner   ++NumDirLookups;
1737a51313dSChris Lattner   llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
174e1dd3e2cSZhanyong Wan     SeenDirEntries.GetOrCreateValue(DirName);
1757a51313dSChris Lattner 
176e1dd3e2cSZhanyong Wan   // See if there was already an entry in the map.  Note that the map
177e1dd3e2cSZhanyong Wan   // contains both virtual and real directories.
1787a51313dSChris Lattner   if (NamedDirEnt.getValue())
179f1186c5aSCraig Topper     return NamedDirEnt.getValue() == NON_EXISTENT_DIR ? nullptr
180f1186c5aSCraig Topper                                                       : NamedDirEnt.getValue();
1817a51313dSChris Lattner 
1827a51313dSChris Lattner   ++NumDirCacheMisses;
1837a51313dSChris Lattner 
1847a51313dSChris Lattner   // By default, initialize it to invalid.
1857a51313dSChris Lattner   NamedDirEnt.setValue(NON_EXISTENT_DIR);
1867a51313dSChris Lattner 
1877a51313dSChris Lattner   // Get the null-terminated directory name as stored as the key of the
188e1dd3e2cSZhanyong Wan   // SeenDirEntries map.
1897a51313dSChris Lattner   const char *InterndDirName = NamedDirEnt.getKeyData();
1907a51313dSChris Lattner 
1917a51313dSChris Lattner   // Check to see if the directory exists.
192f8f91b89SRafael Espindola   FileData Data;
193f1186c5aSCraig Topper   if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
194e1dd3e2cSZhanyong Wan     // There's no real directory at the given path.
1951735f4e7SDouglas Gregor     if (!CacheFailure)
1961735f4e7SDouglas Gregor       SeenDirEntries.erase(DirName);
197f1186c5aSCraig Topper     return nullptr;
198e1dd3e2cSZhanyong Wan   }
1997a51313dSChris Lattner 
200e1dd3e2cSZhanyong Wan   // It exists.  See if we have already opened a directory with the
201e1dd3e2cSZhanyong Wan   // same inode (this occurs on Unix-like systems when one dir is
202e1dd3e2cSZhanyong Wan   // symlinked to another, for example) or the same path (on
203e1dd3e2cSZhanyong Wan   // Windows).
204c9b7234eSBen Langmuir   DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
2057a51313dSChris Lattner 
2067a51313dSChris Lattner   NamedDirEnt.setValue(&UDE);
207e1dd3e2cSZhanyong Wan   if (!UDE.getName()) {
208e1dd3e2cSZhanyong Wan     // We don't have this directory yet, add it.  We use the string
209e1dd3e2cSZhanyong Wan     // key from the SeenDirEntries map as the string.
2107a51313dSChris Lattner     UDE.Name  = InterndDirName;
211e1dd3e2cSZhanyong Wan   }
212e1dd3e2cSZhanyong Wan 
2137a51313dSChris Lattner   return &UDE;
2147a51313dSChris Lattner }
2157a51313dSChris Lattner 
2161735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
2171735f4e7SDouglas Gregor                                       bool CacheFailure) {
2187a51313dSChris Lattner   ++NumFileLookups;
2197a51313dSChris Lattner 
2207a51313dSChris Lattner   // See if there is already an entry in the map.
2217a51313dSChris Lattner   llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
222e1dd3e2cSZhanyong Wan     SeenFileEntries.GetOrCreateValue(Filename);
2237a51313dSChris Lattner 
2247a51313dSChris Lattner   // See if there is already an entry in the map.
2257a51313dSChris Lattner   if (NamedFileEnt.getValue())
2267a51313dSChris Lattner     return NamedFileEnt.getValue() == NON_EXISTENT_FILE
227f1186c5aSCraig Topper                  ? nullptr : NamedFileEnt.getValue();
2287a51313dSChris Lattner 
2297a51313dSChris Lattner   ++NumFileCacheMisses;
2307a51313dSChris Lattner 
2317a51313dSChris Lattner   // By default, initialize it to invalid.
2327a51313dSChris Lattner   NamedFileEnt.setValue(NON_EXISTENT_FILE);
2337a51313dSChris Lattner 
2347a51313dSChris Lattner   // Get the null-terminated file name as stored as the key of the
235e1dd3e2cSZhanyong Wan   // SeenFileEntries map.
2367a51313dSChris Lattner   const char *InterndFileName = NamedFileEnt.getKeyData();
2377a51313dSChris Lattner 
238966b25b9SChris Lattner   // Look up the directory for the file.  When looking up something like
239966b25b9SChris Lattner   // sys/foo.h we'll discover all of the search directories that have a 'sys'
240966b25b9SChris Lattner   // subdirectory.  This will let us avoid having to waste time on known-to-fail
241966b25b9SChris Lattner   // searches when we go to find sys/bar.h, because all the search directories
242966b25b9SChris Lattner   // without a 'sys' subdir will get a cached failure result.
2431735f4e7SDouglas Gregor   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
2441735f4e7SDouglas Gregor                                                        CacheFailure);
245f1186c5aSCraig Topper   if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
2461735f4e7SDouglas Gregor     if (!CacheFailure)
2471735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2481735f4e7SDouglas Gregor 
249f1186c5aSCraig Topper     return nullptr;
2501735f4e7SDouglas Gregor   }
251407e2124SDouglas Gregor 
2527a51313dSChris Lattner   // FIXME: Use the directory info to prune this, before doing the stat syscall.
2537a51313dSChris Lattner   // FIXME: This will reduce the # syscalls.
2547a51313dSChris Lattner 
2557a51313dSChris Lattner   // Nope, there isn't.  Check to see if the file exists.
256*326ffb36SDavid Blaikie   std::unique_ptr<vfs::File> F;
257f8f91b89SRafael Espindola   FileData Data;
258f1186c5aSCraig Topper   if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
259e1dd3e2cSZhanyong Wan     // There's no real file at the given path.
2601735f4e7SDouglas Gregor     if (!CacheFailure)
2611735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2621735f4e7SDouglas Gregor 
263f1186c5aSCraig Topper     return nullptr;
264e1dd3e2cSZhanyong Wan   }
2657a51313dSChris Lattner 
266ab01d4bbSPatrik Hagglund   assert((openFile || !F) && "undesired open file");
267d6278e32SArgyrios Kyrtzidis 
2687a51313dSChris Lattner   // It exists.  See if we have already opened a file with the same inode.
2697a51313dSChris Lattner   // This occurs when one dir is symlinked to another, for example.
270c9b7234eSBen Langmuir   FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
2717a51313dSChris Lattner 
2727a51313dSChris Lattner   NamedFileEnt.setValue(&UFE);
273c8a71468SBen Langmuir   if (UFE.isValid()) { // Already have an entry with this inode, return it.
2745de00f3bSBen Langmuir 
2755de00f3bSBen Langmuir     // FIXME: this hack ensures that if we look up a file by a virtual path in
2765de00f3bSBen Langmuir     // the VFS that the getDir() will have the virtual path, even if we found
2775de00f3bSBen Langmuir     // the file by a 'real' path first. This is required in order to find a
2785de00f3bSBen Langmuir     // module's structure when its headers/module map are mapped in the VFS.
2795de00f3bSBen Langmuir     // We should remove this as soon as we can properly support a file having
2805de00f3bSBen Langmuir     // multiple names.
2815de00f3bSBen Langmuir     if (DirInfo != UFE.Dir && Data.IsVFSMapped)
2825de00f3bSBen Langmuir       UFE.Dir = DirInfo;
2835de00f3bSBen Langmuir 
2847a51313dSChris Lattner     return &UFE;
285dd278430SChris Lattner   }
2867a51313dSChris Lattner 
287c9b7234eSBen Langmuir   // Otherwise, we don't have this file yet, add it.
288d066d4c8SBen Langmuir   UFE.Name    = Data.Name;
289f8f91b89SRafael Espindola   UFE.Size = Data.Size;
290f8f91b89SRafael Espindola   UFE.ModTime = Data.ModTime;
2917a51313dSChris Lattner   UFE.Dir     = DirInfo;
2927a51313dSChris Lattner   UFE.UID     = NextFileUID++;
293c9b7234eSBen Langmuir   UFE.UniqueID = Data.UniqueID;
294c9b7234eSBen Langmuir   UFE.IsNamedPipe = Data.IsNamedPipe;
295c9b7234eSBen Langmuir   UFE.InPCH = Data.InPCH;
296*326ffb36SDavid Blaikie   UFE.File = std::move(F);
297c8a71468SBen Langmuir   UFE.IsValid = true;
2987a51313dSChris Lattner   return &UFE;
2997a51313dSChris Lattner }
3007a51313dSChris Lattner 
301407e2124SDouglas Gregor const FileEntry *
3020e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size,
3035159f616SChris Lattner                             time_t ModificationTime) {
304407e2124SDouglas Gregor   ++NumFileLookups;
305407e2124SDouglas Gregor 
306407e2124SDouglas Gregor   // See if there is already an entry in the map.
307407e2124SDouglas Gregor   llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
308e1dd3e2cSZhanyong Wan     SeenFileEntries.GetOrCreateValue(Filename);
309407e2124SDouglas Gregor 
310407e2124SDouglas Gregor   // See if there is already an entry in the map.
31163fbaedaSAxel Naumann   if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
31263fbaedaSAxel Naumann     return NamedFileEnt.getValue();
313407e2124SDouglas Gregor 
314407e2124SDouglas Gregor   ++NumFileCacheMisses;
315407e2124SDouglas Gregor 
316407e2124SDouglas Gregor   // By default, initialize it to invalid.
317407e2124SDouglas Gregor   NamedFileEnt.setValue(NON_EXISTENT_FILE);
318407e2124SDouglas Gregor 
319e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(Filename);
320f1186c5aSCraig Topper   FileEntry *UFE = nullptr;
321e1dd3e2cSZhanyong Wan 
322e1dd3e2cSZhanyong Wan   // Now that all ancestors of Filename are in the cache, the
323e1dd3e2cSZhanyong Wan   // following call is guaranteed to find the DirectoryEntry from the
324e1dd3e2cSZhanyong Wan   // cache.
3251735f4e7SDouglas Gregor   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
3261735f4e7SDouglas Gregor                                                        /*CacheFailure=*/true);
327e1dd3e2cSZhanyong Wan   assert(DirInfo &&
328e1dd3e2cSZhanyong Wan          "The directory of a virtual file should already be in the cache.");
329e1dd3e2cSZhanyong Wan 
330606c4ac3SDouglas Gregor   // Check to see if the file exists. If so, drop the virtual file
331f8f91b89SRafael Espindola   FileData Data;
332606c4ac3SDouglas Gregor   const char *InterndFileName = NamedFileEnt.getKeyData();
333f1186c5aSCraig Topper   if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
334f8f91b89SRafael Espindola     Data.Size = Size;
335f8f91b89SRafael Espindola     Data.ModTime = ModificationTime;
336c9b7234eSBen Langmuir     UFE = &UniqueRealFiles[Data.UniqueID];
337606c4ac3SDouglas Gregor 
338606c4ac3SDouglas Gregor     NamedFileEnt.setValue(UFE);
339606c4ac3SDouglas Gregor 
340606c4ac3SDouglas Gregor     // If we had already opened this file, close it now so we don't
341606c4ac3SDouglas Gregor     // leak the descriptor. We're not going to use the file
342606c4ac3SDouglas Gregor     // descriptor anyway, since this is a virtual file.
343c8130a74SBen Langmuir     if (UFE->File)
344c8130a74SBen Langmuir       UFE->closeFile();
345606c4ac3SDouglas Gregor 
346606c4ac3SDouglas Gregor     // If we already have an entry with this inode, return it.
347c8a71468SBen Langmuir     if (UFE->isValid())
348606c4ac3SDouglas Gregor       return UFE;
349c9b7234eSBen Langmuir 
350c9b7234eSBen Langmuir     UFE->UniqueID = Data.UniqueID;
351c9b7234eSBen Langmuir     UFE->IsNamedPipe = Data.IsNamedPipe;
352c9b7234eSBen Langmuir     UFE->InPCH = Data.InPCH;
353606c4ac3SDouglas Gregor   }
354606c4ac3SDouglas Gregor 
355606c4ac3SDouglas Gregor   if (!UFE) {
356606c4ac3SDouglas Gregor     UFE = new FileEntry();
357407e2124SDouglas Gregor     VirtualFileEntries.push_back(UFE);
358407e2124SDouglas Gregor     NamedFileEnt.setValue(UFE);
359606c4ac3SDouglas Gregor   }
360407e2124SDouglas Gregor 
3619624b695SChris Lattner   UFE->Name    = InterndFileName;
362407e2124SDouglas Gregor   UFE->Size    = Size;
363407e2124SDouglas Gregor   UFE->ModTime = ModificationTime;
364407e2124SDouglas Gregor   UFE->Dir     = DirInfo;
365407e2124SDouglas Gregor   UFE->UID     = NextFileUID++;
366c8130a74SBen Langmuir   UFE->File.reset();
367407e2124SDouglas Gregor   return UFE;
368407e2124SDouglas Gregor }
369407e2124SDouglas Gregor 
3700e62c1ccSChris Lattner void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
3710e62c1ccSChris Lattner   StringRef pathRef(path.data(), path.size());
372b5c356a4SAnders Carlsson 
3739ba8fb1eSAnders Carlsson   if (FileSystemOpts.WorkingDir.empty()
3749ba8fb1eSAnders Carlsson       || llvm::sys::path::is_absolute(pathRef))
375f28df4cdSMichael J. Spencer     return;
37671731d6bSArgyrios Kyrtzidis 
3772c1dd271SDylan Noblesmith   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
378b5c356a4SAnders Carlsson   llvm::sys::path::append(NewPath, pathRef);
3796e640998SChris Lattner   path = NewPath;
3806e640998SChris Lattner }
3816e640998SChris Lattner 
3826e640998SChris Lattner llvm::MemoryBuffer *FileManager::
3836d7833f1SArgyrios Kyrtzidis getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
3849801b253SBen Langmuir                  bool isVolatile, bool ShouldCloseOpenFile) {
385b8984329SAhmed Charles   std::unique_ptr<llvm::MemoryBuffer> Result;
386c080917eSRafael Espindola   std::error_code ec;
387669b0b15SArgyrios Kyrtzidis 
3886d7833f1SArgyrios Kyrtzidis   uint64_t FileSize = Entry->getSize();
3896d7833f1SArgyrios Kyrtzidis   // If there's a high enough chance that the file have changed since we
3906d7833f1SArgyrios Kyrtzidis   // got its size, force a stat before opening it.
3916d7833f1SArgyrios Kyrtzidis   if (isVolatile)
3926d7833f1SArgyrios Kyrtzidis     FileSize = -1;
3936d7833f1SArgyrios Kyrtzidis 
3945ea7d07dSChris Lattner   const char *Filename = Entry->getName();
3955ea7d07dSChris Lattner   // If the file is already open, use the open file descriptor.
396c8130a74SBen Langmuir   if (Entry->File) {
39726d56393SArgyrios Kyrtzidis     ec = Entry->File->getBuffer(Filename, Result, FileSize,
39826d56393SArgyrios Kyrtzidis                                 /*RequiresNullTerminator=*/true, isVolatile);
399d9da7a1fSMichael J. Spencer     if (ErrorStr)
400f25faaafSMichael J. Spencer       *ErrorStr = ec.message();
4019801b253SBen Langmuir     // FIXME: we need a set of APIs that can make guarantees about whether a
4029801b253SBen Langmuir     // FileEntry is open or not.
4039801b253SBen Langmuir     if (ShouldCloseOpenFile)
404c8130a74SBen Langmuir       Entry->closeFile();
4059a16beb8SAhmed Charles     return Result.release();
4065ea7d07dSChris Lattner   }
4076e640998SChris Lattner 
4085ea7d07dSChris Lattner   // Otherwise, open the file.
409669b0b15SArgyrios Kyrtzidis 
410669b0b15SArgyrios Kyrtzidis   if (FileSystemOpts.WorkingDir.empty()) {
41126d56393SArgyrios Kyrtzidis     ec = FS->getBufferForFile(Filename, Result, FileSize,
41226d56393SArgyrios Kyrtzidis                               /*RequiresNullTerminator=*/true, isVolatile);
413d9da7a1fSMichael J. Spencer     if (ec && ErrorStr)
414f25faaafSMichael J. Spencer       *ErrorStr = ec.message();
4159a16beb8SAhmed Charles     return Result.release();
4165ea7d07dSChris Lattner   }
4175ea7d07dSChris Lattner 
4182c1dd271SDylan Noblesmith   SmallString<128> FilePath(Entry->getName());
419878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
42026d56393SArgyrios Kyrtzidis   ec = FS->getBufferForFile(FilePath.str(), Result, FileSize,
42126d56393SArgyrios Kyrtzidis                             /*RequiresNullTerminator=*/true, isVolatile);
422d9da7a1fSMichael J. Spencer   if (ec && ErrorStr)
423f25faaafSMichael J. Spencer     *ErrorStr = ec.message();
4249a16beb8SAhmed Charles   return Result.release();
42526b5c190SChris Lattner }
42626b5c190SChris Lattner 
42726b5c190SChris Lattner llvm::MemoryBuffer *FileManager::
4280e62c1ccSChris Lattner getBufferForFile(StringRef Filename, std::string *ErrorStr) {
429b8984329SAhmed Charles   std::unique_ptr<llvm::MemoryBuffer> Result;
430c080917eSRafael Espindola   std::error_code ec;
431f25faaafSMichael J. Spencer   if (FileSystemOpts.WorkingDir.empty()) {
432c8130a74SBen Langmuir     ec = FS->getBufferForFile(Filename, Result);
433d9da7a1fSMichael J. Spencer     if (ec && ErrorStr)
434f25faaafSMichael J. Spencer       *ErrorStr = ec.message();
4359a16beb8SAhmed Charles     return Result.release();
436f25faaafSMichael J. Spencer   }
43726b5c190SChris Lattner 
4382c1dd271SDylan Noblesmith   SmallString<128> FilePath(Filename);
439878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
440c8130a74SBen Langmuir   ec = FS->getBufferForFile(FilePath.c_str(), Result);
441d9da7a1fSMichael J. Spencer   if (ec && ErrorStr)
442f25faaafSMichael J. Spencer     *ErrorStr = ec.message();
4439a16beb8SAhmed Charles   return Result.release();
44471731d6bSArgyrios Kyrtzidis }
44571731d6bSArgyrios Kyrtzidis 
446e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path,
447e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible.  This returns true
448e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns
449e1dd3e2cSZhanyong Wan /// false if it's an existent real file.  If FileDescriptor is NULL,
450e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up.
451f8f91b89SRafael Espindola bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
452*326ffb36SDavid Blaikie                                std::unique_ptr<vfs::File> *F) {
453226efd35SChris Lattner   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
454226efd35SChris Lattner   // absolute!
4555769c3dfSChris Lattner   if (FileSystemOpts.WorkingDir.empty())
456c8130a74SBen Langmuir     return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
457226efd35SChris Lattner 
4582c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
459878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
46071731d6bSArgyrios Kyrtzidis 
461c8130a74SBen Langmuir   return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
462c8130a74SBen Langmuir                                   StatCache.get(), *FS);
46371731d6bSArgyrios Kyrtzidis }
46471731d6bSArgyrios Kyrtzidis 
4650e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path,
466c8130a74SBen Langmuir                                         vfs::Status &Result) {
4672c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
4685e368405SAnders Carlsson   FixupRelativePath(FilePath);
4695e368405SAnders Carlsson 
470c8130a74SBen Langmuir   llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
471c8130a74SBen Langmuir   if (!S)
472c8130a74SBen Langmuir     return true;
473c8130a74SBen Langmuir   Result = *S;
474c8130a74SBen Langmuir   return false;
4755e368405SAnders Carlsson }
4765e368405SAnders Carlsson 
477b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) {
478b3074003SAxel Naumann   assert(Entry && "Cannot invalidate a NULL FileEntry");
47938179d96SAxel Naumann 
48038179d96SAxel Naumann   SeenFileEntries.erase(Entry->getName());
481b3074003SAxel Naumann 
482b3074003SAxel Naumann   // FileEntry invalidation should not block future optimizations in the file
483b3074003SAxel Naumann   // caches. Possible alternatives are cache truncation (invalidate last N) or
484b3074003SAxel Naumann   // invalidation of the whole cache.
485c9b7234eSBen Langmuir   UniqueRealFiles.erase(Entry->getUniqueID());
48638179d96SAxel Naumann }
48738179d96SAxel Naumann 
48838179d96SAxel Naumann 
48909b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping(
4900e62c1ccSChris Lattner                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
49109b6989eSDouglas Gregor   UIDToFiles.clear();
49209b6989eSDouglas Gregor   UIDToFiles.resize(NextFileUID);
49309b6989eSDouglas Gregor 
49409b6989eSDouglas Gregor   // Map file entries
49509b6989eSDouglas Gregor   for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
496e1dd3e2cSZhanyong Wan          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
49709b6989eSDouglas Gregor        FE != FEEnd; ++FE)
49809b6989eSDouglas Gregor     if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
49909b6989eSDouglas Gregor       UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
50009b6989eSDouglas Gregor 
50109b6989eSDouglas Gregor   // Map virtual file entries
5022341c0d3SCraig Topper   for (SmallVectorImpl<FileEntry *>::const_iterator
50309b6989eSDouglas Gregor          VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
50409b6989eSDouglas Gregor        VFE != VFEEnd; ++VFE)
50509b6989eSDouglas Gregor     if (*VFE && *VFE != NON_EXISTENT_FILE)
50609b6989eSDouglas Gregor       UIDToFiles[(*VFE)->getUID()] = *VFE;
50709b6989eSDouglas Gregor }
508226efd35SChris Lattner 
5096eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File,
5106eec06d0SArgyrios Kyrtzidis                                   off_t Size, time_t ModificationTime) {
5116eec06d0SArgyrios Kyrtzidis   File->Size = Size;
5126eec06d0SArgyrios Kyrtzidis   File->ModTime = ModificationTime;
5136eec06d0SArgyrios Kyrtzidis }
5146eec06d0SArgyrios Kyrtzidis 
515e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
516e00c8b20SDouglas Gregor   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
517e00c8b20SDouglas Gregor #ifdef LLVM_ON_UNIX
518e00c8b20SDouglas Gregor   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
519e00c8b20SDouglas Gregor     = CanonicalDirNames.find(Dir);
520e00c8b20SDouglas Gregor   if (Known != CanonicalDirNames.end())
521e00c8b20SDouglas Gregor     return Known->second;
522e00c8b20SDouglas Gregor 
523e00c8b20SDouglas Gregor   StringRef CanonicalName(Dir->getName());
524e00c8b20SDouglas Gregor   char CanonicalNameBuf[PATH_MAX];
525e00c8b20SDouglas Gregor   if (realpath(Dir->getName(), CanonicalNameBuf)) {
526e00c8b20SDouglas Gregor     unsigned Len = strlen(CanonicalNameBuf);
527e00c8b20SDouglas Gregor     char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
528e00c8b20SDouglas Gregor     memcpy(Mem, CanonicalNameBuf, Len);
529e00c8b20SDouglas Gregor     CanonicalName = StringRef(Mem, Len);
530e00c8b20SDouglas Gregor   }
531e00c8b20SDouglas Gregor 
532e00c8b20SDouglas Gregor   CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
533e00c8b20SDouglas Gregor   return CanonicalName;
534e00c8b20SDouglas Gregor #else
535e00c8b20SDouglas Gregor   return StringRef(Dir->getName());
536e00c8b20SDouglas Gregor #endif
537e00c8b20SDouglas Gregor }
538226efd35SChris Lattner 
5397a51313dSChris Lattner void FileManager::PrintStats() const {
54089b422c1SBenjamin Kramer   llvm::errs() << "\n*** File Manager Stats:\n";
541e1dd3e2cSZhanyong Wan   llvm::errs() << UniqueRealFiles.size() << " real files found, "
542e1dd3e2cSZhanyong Wan                << UniqueRealDirs.size() << " real dirs found.\n";
543e1dd3e2cSZhanyong Wan   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
544e1dd3e2cSZhanyong Wan                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
54589b422c1SBenjamin Kramer   llvm::errs() << NumDirLookups << " dir lookups, "
5467a51313dSChris Lattner                << NumDirCacheMisses << " dir cache misses.\n";
54789b422c1SBenjamin Kramer   llvm::errs() << NumFileLookups << " file lookups, "
5487a51313dSChris Lattner                << NumFileCacheMisses << " file cache misses.\n";
5497a51313dSChris Lattner 
55089b422c1SBenjamin Kramer   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
5517a51313dSChris Lattner }
552