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"
22*075bf567SAdrian 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 
3920e62c1ccSChris Lattner void 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))
397f28df4cdSMichael J. Spencer     return;
39871731d6bSArgyrios Kyrtzidis 
3992c1dd271SDylan Noblesmith   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
400b5c356a4SAnders Carlsson   llvm::sys::path::append(NewPath, pathRef);
4016e640998SChris Lattner   path = NewPath;
4026e640998SChris Lattner }
4036e640998SChris Lattner 
404a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
405a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
406a885796dSBenjamin Kramer                               bool ShouldCloseOpenFile) {
4076d7833f1SArgyrios Kyrtzidis   uint64_t FileSize = Entry->getSize();
4086d7833f1SArgyrios Kyrtzidis   // If there's a high enough chance that the file have changed since we
4096d7833f1SArgyrios Kyrtzidis   // got its size, force a stat before opening it.
4106d7833f1SArgyrios Kyrtzidis   if (isVolatile)
4116d7833f1SArgyrios Kyrtzidis     FileSize = -1;
4126d7833f1SArgyrios Kyrtzidis 
4135ea7d07dSChris Lattner   const char *Filename = Entry->getName();
4145ea7d07dSChris Lattner   // If the file is already open, use the open file descriptor.
415c8130a74SBen Langmuir   if (Entry->File) {
416a885796dSBenjamin Kramer     auto Result =
417a885796dSBenjamin Kramer         Entry->File->getBuffer(Filename, FileSize,
41826d56393SArgyrios Kyrtzidis                                /*RequiresNullTerminator=*/true, isVolatile);
4199801b253SBen Langmuir     // FIXME: we need a set of APIs that can make guarantees about whether a
4209801b253SBen Langmuir     // FileEntry is open or not.
4219801b253SBen Langmuir     if (ShouldCloseOpenFile)
422c8130a74SBen Langmuir       Entry->closeFile();
4236406f7b8SRafael Espindola     return Result;
4245ea7d07dSChris Lattner   }
4256e640998SChris Lattner 
4265ea7d07dSChris Lattner   // Otherwise, open the file.
427669b0b15SArgyrios Kyrtzidis 
428a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
429a885796dSBenjamin Kramer     return FS->getBufferForFile(Filename, FileSize,
43026d56393SArgyrios Kyrtzidis                                 /*RequiresNullTerminator=*/true, isVolatile);
4315ea7d07dSChris Lattner 
4322c1dd271SDylan Noblesmith   SmallString<128> FilePath(Entry->getName());
433878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
43492e1b62dSYaron Keren   return FS->getBufferForFile(FilePath, FileSize,
43526d56393SArgyrios Kyrtzidis                               /*RequiresNullTerminator=*/true, isVolatile);
43626b5c190SChris Lattner }
43726b5c190SChris Lattner 
438a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
439a885796dSBenjamin Kramer FileManager::getBufferForFile(StringRef Filename) {
440a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
441a885796dSBenjamin Kramer     return FS->getBufferForFile(Filename);
44226b5c190SChris Lattner 
4432c1dd271SDylan Noblesmith   SmallString<128> FilePath(Filename);
444878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
445a885796dSBenjamin Kramer   return FS->getBufferForFile(FilePath.c_str());
44671731d6bSArgyrios Kyrtzidis }
44771731d6bSArgyrios Kyrtzidis 
448e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path,
449e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible.  This returns true
450e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns
451e1dd3e2cSZhanyong Wan /// false if it's an existent real file.  If FileDescriptor is NULL,
452e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up.
453f8f91b89SRafael Espindola bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
454326ffb36SDavid Blaikie                                std::unique_ptr<vfs::File> *F) {
455226efd35SChris Lattner   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
456226efd35SChris Lattner   // absolute!
4575769c3dfSChris Lattner   if (FileSystemOpts.WorkingDir.empty())
458c8130a74SBen Langmuir     return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
459226efd35SChris Lattner 
4602c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
461878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
46271731d6bSArgyrios Kyrtzidis 
463c8130a74SBen Langmuir   return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
464c8130a74SBen Langmuir                                   StatCache.get(), *FS);
46571731d6bSArgyrios Kyrtzidis }
46671731d6bSArgyrios Kyrtzidis 
4670e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path,
468c8130a74SBen Langmuir                                         vfs::Status &Result) {
4692c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
4705e368405SAnders Carlsson   FixupRelativePath(FilePath);
4715e368405SAnders Carlsson 
472c8130a74SBen Langmuir   llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
473c8130a74SBen Langmuir   if (!S)
474c8130a74SBen Langmuir     return true;
475c8130a74SBen Langmuir   Result = *S;
476c8130a74SBen Langmuir   return false;
4775e368405SAnders Carlsson }
4785e368405SAnders Carlsson 
479b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) {
480b3074003SAxel Naumann   assert(Entry && "Cannot invalidate a NULL FileEntry");
48138179d96SAxel Naumann 
48238179d96SAxel Naumann   SeenFileEntries.erase(Entry->getName());
483b3074003SAxel Naumann 
484b3074003SAxel Naumann   // FileEntry invalidation should not block future optimizations in the file
485b3074003SAxel Naumann   // caches. Possible alternatives are cache truncation (invalidate last N) or
486b3074003SAxel Naumann   // invalidation of the whole cache.
487c9b7234eSBen Langmuir   UniqueRealFiles.erase(Entry->getUniqueID());
48838179d96SAxel Naumann }
48938179d96SAxel Naumann 
49038179d96SAxel Naumann 
49109b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping(
4920e62c1ccSChris Lattner                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
49309b6989eSDouglas Gregor   UIDToFiles.clear();
49409b6989eSDouglas Gregor   UIDToFiles.resize(NextFileUID);
49509b6989eSDouglas Gregor 
49609b6989eSDouglas Gregor   // Map file entries
49709b6989eSDouglas Gregor   for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
498e1dd3e2cSZhanyong Wan          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
49909b6989eSDouglas Gregor        FE != FEEnd; ++FE)
50009b6989eSDouglas Gregor     if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
50109b6989eSDouglas Gregor       UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
50209b6989eSDouglas Gregor 
50309b6989eSDouglas Gregor   // Map virtual file entries
5042341c0d3SCraig Topper   for (SmallVectorImpl<FileEntry *>::const_iterator
50509b6989eSDouglas Gregor          VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
50609b6989eSDouglas Gregor        VFE != VFEEnd; ++VFE)
50709b6989eSDouglas Gregor     if (*VFE && *VFE != NON_EXISTENT_FILE)
50809b6989eSDouglas Gregor       UIDToFiles[(*VFE)->getUID()] = *VFE;
50909b6989eSDouglas Gregor }
510226efd35SChris Lattner 
5116eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File,
5126eec06d0SArgyrios Kyrtzidis                                   off_t Size, time_t ModificationTime) {
5136eec06d0SArgyrios Kyrtzidis   File->Size = Size;
5146eec06d0SArgyrios Kyrtzidis   File->ModTime = ModificationTime;
5156eec06d0SArgyrios Kyrtzidis }
5166eec06d0SArgyrios Kyrtzidis 
51754cc3c2fSRichard Smith /// Remove '.' path components from the given absolute path.
51854cc3c2fSRichard Smith /// \return \c true if any changes were made.
51954cc3c2fSRichard Smith // FIXME: Move this to llvm::sys::path.
52054cc3c2fSRichard Smith bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path) {
52154cc3c2fSRichard Smith   using namespace llvm::sys;
52254cc3c2fSRichard Smith 
52354cc3c2fSRichard Smith   SmallVector<StringRef, 16> ComponentStack;
52454cc3c2fSRichard Smith   StringRef P(Path.data(), Path.size());
52554cc3c2fSRichard Smith 
52654cc3c2fSRichard Smith   // Skip the root path, then look for traversal in the components.
52754cc3c2fSRichard Smith   StringRef Rel = path::relative_path(P);
52854cc3c2fSRichard Smith   bool AnyDots = false;
52954cc3c2fSRichard Smith   for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) {
53054cc3c2fSRichard Smith     if (C == ".") {
53154cc3c2fSRichard Smith       AnyDots = true;
53254cc3c2fSRichard Smith       continue;
53354cc3c2fSRichard Smith     }
53454cc3c2fSRichard Smith     ComponentStack.push_back(C);
53554cc3c2fSRichard Smith   }
53654cc3c2fSRichard Smith 
53754cc3c2fSRichard Smith   if (!AnyDots)
53854cc3c2fSRichard Smith     return false;
53954cc3c2fSRichard Smith 
54054cc3c2fSRichard Smith   SmallString<256> Buffer = path::root_path(P);
54154cc3c2fSRichard Smith   for (StringRef C : ComponentStack)
54254cc3c2fSRichard Smith     path::append(Buffer, C);
54354cc3c2fSRichard Smith 
54454cc3c2fSRichard Smith   Path.swap(Buffer);
54554cc3c2fSRichard Smith   return true;
54654cc3c2fSRichard Smith }
54754cc3c2fSRichard Smith 
548e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
549e00c8b20SDouglas Gregor   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
550e00c8b20SDouglas Gregor   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
551e00c8b20SDouglas Gregor     = CanonicalDirNames.find(Dir);
552e00c8b20SDouglas Gregor   if (Known != CanonicalDirNames.end())
553e00c8b20SDouglas Gregor     return Known->second;
554e00c8b20SDouglas Gregor 
555e00c8b20SDouglas Gregor   StringRef CanonicalName(Dir->getName());
55654cc3c2fSRichard Smith 
55754cc3c2fSRichard Smith #ifdef LLVM_ON_UNIX
558e00c8b20SDouglas Gregor   char CanonicalNameBuf[PATH_MAX];
559e00c8b20SDouglas Gregor   if (realpath(Dir->getName(), CanonicalNameBuf)) {
560e00c8b20SDouglas Gregor     unsigned Len = strlen(CanonicalNameBuf);
561e00c8b20SDouglas Gregor     char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
562e00c8b20SDouglas Gregor     memcpy(Mem, CanonicalNameBuf, Len);
563e00c8b20SDouglas Gregor     CanonicalName = StringRef(Mem, Len);
564e00c8b20SDouglas Gregor   }
56554cc3c2fSRichard Smith #else
56654cc3c2fSRichard Smith   SmallString<256> CanonicalNameBuf(CanonicalName);
56754cc3c2fSRichard Smith   llvm::sys::fs::make_absolute(CanonicalNameBuf);
56854cc3c2fSRichard Smith   llvm::sys::path::native(CanonicalNameBuf);
56954cc3c2fSRichard Smith   removeDotPaths(CanonicalNameBuf);
57054cc3c2fSRichard Smith #endif
571e00c8b20SDouglas Gregor 
572e00c8b20SDouglas Gregor   CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
573e00c8b20SDouglas Gregor   return CanonicalName;
574e00c8b20SDouglas Gregor }
575226efd35SChris Lattner 
5767a51313dSChris Lattner void FileManager::PrintStats() const {
57789b422c1SBenjamin Kramer   llvm::errs() << "\n*** File Manager Stats:\n";
578e1dd3e2cSZhanyong Wan   llvm::errs() << UniqueRealFiles.size() << " real files found, "
579e1dd3e2cSZhanyong Wan                << UniqueRealDirs.size() << " real dirs found.\n";
580e1dd3e2cSZhanyong Wan   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
581e1dd3e2cSZhanyong Wan                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
58289b422c1SBenjamin Kramer   llvm::errs() << NumDirLookups << " dir lookups, "
5837a51313dSChris Lattner                << NumDirCacheMisses << " dir cache misses.\n";
58489b422c1SBenjamin Kramer   llvm::errs() << NumFileLookups << " file lookups, "
5857a51313dSChris Lattner                << NumFileCacheMisses << " file cache misses.\n";
5867a51313dSChris Lattner 
58789b422c1SBenjamin Kramer   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
5887a51313dSChris Lattner }
589*075bf567SAdrian Prantl 
590*075bf567SAdrian Prantl PCHContainerOperations::~PCHContainerOperations() {}
591