1226efd35SChris Lattner //===--- FileManager.cpp - File System Probing and Caching ----------------===//
27a51313dSChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67a51313dSChris Lattner //
77a51313dSChris Lattner //===----------------------------------------------------------------------===//
87a51313dSChris Lattner //
97a51313dSChris Lattner //  This file implements the FileManager interface.
107a51313dSChris Lattner //
117a51313dSChris Lattner //===----------------------------------------------------------------------===//
127a51313dSChris Lattner //
137a51313dSChris Lattner // TODO: This should index all interesting directories with dirent calls.
147a51313dSChris Lattner //  getdirentries ?
157a51313dSChris Lattner //  opendir/readdir_r/closedir ?
167a51313dSChris Lattner //
177a51313dSChris Lattner //===----------------------------------------------------------------------===//
187a51313dSChris Lattner 
197a51313dSChris Lattner #include "clang/Basic/FileManager.h"
20226efd35SChris Lattner #include "clang/Basic/FileSystemStatCache.h"
217a51313dSChris Lattner #include "llvm/ADT/SmallString.h"
223a02247dSChandler Carruth #include "llvm/Config/llvm-config.h"
23d2725a31SDavid Blaikie #include "llvm/ADT/STLExtras.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"
2835b79c24SEugene Zelenko #include <algorithm>
2935b79c24SEugene Zelenko #include <cassert>
3035b79c24SEugene Zelenko #include <climits>
3135b79c24SEugene Zelenko #include <cstdint>
3235b79c24SEugene Zelenko #include <cstdlib>
3326db6481SBenjamin Kramer #include <string>
3435b79c24SEugene Zelenko #include <utility>
35278038b4SChris Lattner 
367a51313dSChris Lattner using namespace clang;
377a51313dSChris Lattner 
385c04bd81STed Kremenek //===----------------------------------------------------------------------===//
395c04bd81STed Kremenek // Common logic.
405c04bd81STed Kremenek //===----------------------------------------------------------------------===//
417a51313dSChris Lattner 
42c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO,
43fc51490bSJonas Devlieghere                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
44f6021ecdSBenjamin Kramer     : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
45f6021ecdSBenjamin Kramer       SeenFileEntries(64), NextFileUID(0) {
467a51313dSChris Lattner   NumDirLookups = NumFileLookups = 0;
477a51313dSChris Lattner   NumDirCacheMisses = NumFileCacheMisses = 0;
48c8130a74SBen Langmuir 
49c8130a74SBen Langmuir   // If the caller doesn't provide a virtual file system, just grab the real
50c8130a74SBen Langmuir   // file system.
51f6021ecdSBenjamin Kramer   if (!this->FS)
52fc51490bSJonas Devlieghere     this->FS = llvm::vfs::getRealFileSystem();
537a51313dSChris Lattner }
547a51313dSChris Lattner 
55d2725a31SDavid Blaikie FileManager::~FileManager() = default;
567a51313dSChris Lattner 
57d92b1ae1SAlex Lorenz void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
58d2eb58abSDouglas Gregor   assert(statCache && "No stat cache provided?");
5923430ccbSDavid Blaikie   StatCache = std::move(statCache);
60d2eb58abSDouglas Gregor }
61d2eb58abSDouglas Gregor 
62d92b1ae1SAlex Lorenz void FileManager::clearStatCache() { StatCache.reset(); }
633aad855aSManuel Klimek 
649fc8faf9SAdrian Prantl /// Retrieve the directory that the given file name resides in.
65e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file.
66407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
671735f4e7SDouglas Gregor                                                   StringRef Filename,
681735f4e7SDouglas Gregor                                                   bool CacheFailure) {
69f3c0ff73SZhanyong Wan   if (Filename.empty())
70f1186c5aSCraig Topper     return nullptr;
71e1dd3e2cSZhanyong Wan 
72f3c0ff73SZhanyong Wan   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
73f1186c5aSCraig Topper     return nullptr; // If Filename is a directory.
740c0e8040SChris Lattner 
750e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Filename);
760c0e8040SChris Lattner   // Use the current directory if file has no path component.
77f3c0ff73SZhanyong Wan   if (DirName.empty())
78f3c0ff73SZhanyong Wan     DirName = ".";
790c0e8040SChris Lattner 
801735f4e7SDouglas Gregor   return FileMgr.getDirectory(DirName, CacheFailure);
81407e2124SDouglas Gregor }
82407e2124SDouglas Gregor 
83e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or
84e1dd3e2cSZhanyong Wan /// a directory) as virtual directories.
850e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
860e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Path);
87f3c0ff73SZhanyong Wan   if (DirName.empty())
881834dc75SDavid Majnemer     DirName = ".";
89e1dd3e2cSZhanyong Wan 
90018ab5faSRichard Smith   auto &NamedDirEnt = *SeenDirEntries.insert({DirName, nullptr}).first;
91e1dd3e2cSZhanyong Wan 
92e1dd3e2cSZhanyong Wan   // When caching a virtual directory, we always cache its ancestors
93e1dd3e2cSZhanyong Wan   // at the same time.  Therefore, if DirName is already in the cache,
94e1dd3e2cSZhanyong Wan   // we don't need to recurse as its ancestors must also already be in
95018ab5faSRichard Smith   // the cache (or it's a known non-virtual directory).
96018ab5faSRichard Smith   if (NamedDirEnt.second)
97e1dd3e2cSZhanyong Wan     return;
98e1dd3e2cSZhanyong Wan 
99e1dd3e2cSZhanyong Wan   // Add the virtual directory to the cache.
100d2725a31SDavid Blaikie   auto UDE = llvm::make_unique<DirectoryEntry>();
1010df59d8cSMehdi Amini   UDE->Name = NamedDirEnt.first();
102d2725a31SDavid Blaikie   NamedDirEnt.second = UDE.get();
103d2725a31SDavid Blaikie   VirtualDirectoryEntries.push_back(std::move(UDE));
104e1dd3e2cSZhanyong Wan 
105e1dd3e2cSZhanyong Wan   // Recursively add the other ancestors.
106e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(DirName);
107e1dd3e2cSZhanyong Wan }
108e1dd3e2cSZhanyong Wan 
1091735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
1101735f4e7SDouglas Gregor                                                 bool CacheFailure) {
1118bd8ee76SNAKAMURA Takumi   // stat doesn't like trailing separators except for root directory.
11232f1acf1SNAKAMURA Takumi   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
11332f1acf1SNAKAMURA Takumi   // (though it can strip '\\')
1148bd8ee76SNAKAMURA Takumi   if (DirName.size() > 1 &&
1158bd8ee76SNAKAMURA Takumi       DirName != llvm::sys::path::root_path(DirName) &&
1168bd8ee76SNAKAMURA Takumi       llvm::sys::path::is_separator(DirName.back()))
11732f1acf1SNAKAMURA Takumi     DirName = DirName.substr(0, DirName.size()-1);
1181865df49SNico Weber #ifdef _WIN32
119ee30546cSRafael Espindola   // Fixing a problem with "clang C:test.c" on Windows.
120ee30546cSRafael Espindola   // Stat("C:") does not recognize "C:" as a valid directory
121ee30546cSRafael Espindola   std::string DirNameStr;
122ee30546cSRafael Espindola   if (DirName.size() > 1 && DirName.back() == ':' &&
123ee30546cSRafael Espindola       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
124ee30546cSRafael Espindola     DirNameStr = DirName.str() + '.';
125ee30546cSRafael Espindola     DirName = DirNameStr;
126ee30546cSRafael Espindola   }
127ee30546cSRafael Espindola #endif
12832f1acf1SNAKAMURA Takumi 
1297a51313dSChris Lattner   ++NumDirLookups;
1307a51313dSChris Lattner 
131e1dd3e2cSZhanyong Wan   // See if there was already an entry in the map.  Note that the map
132e1dd3e2cSZhanyong Wan   // contains both virtual and real directories.
133018ab5faSRichard Smith   auto SeenDirInsertResult = SeenDirEntries.insert({DirName, nullptr});
134018ab5faSRichard Smith   if (!SeenDirInsertResult.second)
135018ab5faSRichard Smith     return SeenDirInsertResult.first->second;
1367a51313dSChris Lattner 
137018ab5faSRichard Smith   // We've not seen this before. Fill it in.
1387a51313dSChris Lattner   ++NumDirCacheMisses;
139018ab5faSRichard Smith   auto &NamedDirEnt = *SeenDirInsertResult.first;
140018ab5faSRichard Smith   assert(!NamedDirEnt.second && "should be newly-created");
1417a51313dSChris Lattner 
1427a51313dSChris Lattner   // Get the null-terminated directory name as stored as the key of the
143e1dd3e2cSZhanyong Wan   // SeenDirEntries map.
1440df59d8cSMehdi Amini   StringRef InterndDirName = NamedDirEnt.first();
1457a51313dSChris Lattner 
1467a51313dSChris Lattner   // Check to see if the directory exists.
147f8f91b89SRafael Espindola   FileData Data;
148f1186c5aSCraig Topper   if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
149e1dd3e2cSZhanyong Wan     // There's no real directory at the given path.
1501735f4e7SDouglas Gregor     if (!CacheFailure)
1511735f4e7SDouglas Gregor       SeenDirEntries.erase(DirName);
152f1186c5aSCraig Topper     return nullptr;
153e1dd3e2cSZhanyong Wan   }
1547a51313dSChris Lattner 
155e1dd3e2cSZhanyong Wan   // It exists.  See if we have already opened a directory with the
156e1dd3e2cSZhanyong Wan   // same inode (this occurs on Unix-like systems when one dir is
157e1dd3e2cSZhanyong Wan   // symlinked to another, for example) or the same path (on
158e1dd3e2cSZhanyong Wan   // Windows).
159c9b7234eSBen Langmuir   DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
1607a51313dSChris Lattner 
16113156b68SDavid Blaikie   NamedDirEnt.second = &UDE;
1620df59d8cSMehdi Amini   if (UDE.getName().empty()) {
163e1dd3e2cSZhanyong Wan     // We don't have this directory yet, add it.  We use the string
164e1dd3e2cSZhanyong Wan     // key from the SeenDirEntries map as the string.
1657a51313dSChris Lattner     UDE.Name  = InterndDirName;
166e1dd3e2cSZhanyong Wan   }
167e1dd3e2cSZhanyong Wan 
1687a51313dSChris Lattner   return &UDE;
1697a51313dSChris Lattner }
1707a51313dSChris Lattner 
1711735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
1721735f4e7SDouglas Gregor                                       bool CacheFailure) {
1737a51313dSChris Lattner   ++NumFileLookups;
1747a51313dSChris Lattner 
1757a51313dSChris Lattner   // See if there is already an entry in the map.
176018ab5faSRichard Smith   auto SeenFileInsertResult = SeenFileEntries.insert({Filename, nullptr});
177018ab5faSRichard Smith   if (!SeenFileInsertResult.second)
178018ab5faSRichard Smith     return SeenFileInsertResult.first->second;
1797a51313dSChris Lattner 
180018ab5faSRichard Smith   // We've not seen this before. Fill it in.
181e84385feSSam McCall   ++NumFileCacheMisses;
182018ab5faSRichard Smith   auto &NamedFileEnt = *SeenFileInsertResult.first;
183018ab5faSRichard Smith   assert(!NamedFileEnt.second && "should be newly-created");
184fa361206SSam McCall 
1857a51313dSChris Lattner   // Get the null-terminated file name as stored as the key of the
186e1dd3e2cSZhanyong Wan   // SeenFileEntries map.
1870df59d8cSMehdi Amini   StringRef InterndFileName = NamedFileEnt.first();
1887a51313dSChris Lattner 
189966b25b9SChris Lattner   // Look up the directory for the file.  When looking up something like
190966b25b9SChris Lattner   // sys/foo.h we'll discover all of the search directories that have a 'sys'
191966b25b9SChris Lattner   // subdirectory.  This will let us avoid having to waste time on known-to-fail
192966b25b9SChris Lattner   // searches when we go to find sys/bar.h, because all the search directories
193966b25b9SChris Lattner   // without a 'sys' subdir will get a cached failure result.
1941735f4e7SDouglas Gregor   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
1951735f4e7SDouglas Gregor                                                        CacheFailure);
196f1186c5aSCraig Topper   if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
1971735f4e7SDouglas Gregor     if (!CacheFailure)
1981735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
1991735f4e7SDouglas Gregor 
200f1186c5aSCraig Topper     return nullptr;
2011735f4e7SDouglas Gregor   }
202407e2124SDouglas Gregor 
2037a51313dSChris Lattner   // FIXME: Use the directory info to prune this, before doing the stat syscall.
2047a51313dSChris Lattner   // FIXME: This will reduce the # syscalls.
2057a51313dSChris Lattner 
206018ab5faSRichard Smith   // Check to see if the file exists.
207fc51490bSJonas Devlieghere   std::unique_ptr<llvm::vfs::File> F;
208f8f91b89SRafael Espindola   FileData Data;
209f1186c5aSCraig Topper   if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
210e1dd3e2cSZhanyong Wan     // There's no real file at the given path.
2111735f4e7SDouglas Gregor     if (!CacheFailure)
2121735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2131735f4e7SDouglas Gregor 
214f1186c5aSCraig Topper     return nullptr;
215e1dd3e2cSZhanyong Wan   }
2167a51313dSChris Lattner 
217ab01d4bbSPatrik Hagglund   assert((openFile || !F) && "undesired open file");
218d6278e32SArgyrios Kyrtzidis 
2197a51313dSChris Lattner   // It exists.  See if we have already opened a file with the same inode.
2207a51313dSChris Lattner   // This occurs when one dir is symlinked to another, for example.
221c9b7234eSBen Langmuir   FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
2227a51313dSChris Lattner 
22313156b68SDavid Blaikie   NamedFileEnt.second = &UFE;
224ab86fbe4SBen Langmuir 
225ab86fbe4SBen Langmuir   // If the name returned by getStatValue is different than Filename, re-intern
226ab86fbe4SBen Langmuir   // the name.
227ab86fbe4SBen Langmuir   if (Data.Name != Filename) {
228018ab5faSRichard Smith     auto &NamedFileEnt = *SeenFileEntries.insert({Data.Name, &UFE}).first;
22913156b68SDavid Blaikie     assert(NamedFileEnt.second == &UFE &&
230ab86fbe4SBen Langmuir            "filename from getStatValue() refers to wrong file");
23113156b68SDavid Blaikie     InterndFileName = NamedFileEnt.first().data();
232ab86fbe4SBen Langmuir   }
233ab86fbe4SBen Langmuir 
234c8a71468SBen Langmuir   if (UFE.isValid()) { // Already have an entry with this inode, return it.
2355de00f3bSBen Langmuir 
2365de00f3bSBen Langmuir     // FIXME: this hack ensures that if we look up a file by a virtual path in
2375de00f3bSBen Langmuir     // the VFS that the getDir() will have the virtual path, even if we found
2385de00f3bSBen Langmuir     // the file by a 'real' path first. This is required in order to find a
2395de00f3bSBen Langmuir     // module's structure when its headers/module map are mapped in the VFS.
2405de00f3bSBen Langmuir     // We should remove this as soon as we can properly support a file having
2415de00f3bSBen Langmuir     // multiple names.
2425de00f3bSBen Langmuir     if (DirInfo != UFE.Dir && Data.IsVFSMapped)
2435de00f3bSBen Langmuir       UFE.Dir = DirInfo;
2445de00f3bSBen Langmuir 
245c0ff9908SManuel Klimek     // Always update the name to use the last name by which a file was accessed.
246c0ff9908SManuel Klimek     // FIXME: Neither this nor always using the first name is correct; we want
247c0ff9908SManuel Klimek     // to switch towards a design where we return a FileName object that
248c0ff9908SManuel Klimek     // encapsulates both the name by which the file was accessed and the
249c0ff9908SManuel Klimek     // corresponding FileEntry.
250ab86fbe4SBen Langmuir     UFE.Name = InterndFileName;
251c0ff9908SManuel Klimek 
2527a51313dSChris Lattner     return &UFE;
253dd278430SChris Lattner   }
2547a51313dSChris Lattner 
255c9b7234eSBen Langmuir   // Otherwise, we don't have this file yet, add it.
256ab86fbe4SBen Langmuir   UFE.Name    = InterndFileName;
257f8f91b89SRafael Espindola   UFE.Size = Data.Size;
258f8f91b89SRafael Espindola   UFE.ModTime = Data.ModTime;
2597a51313dSChris Lattner   UFE.Dir     = DirInfo;
2607a51313dSChris Lattner   UFE.UID     = NextFileUID++;
261c9b7234eSBen Langmuir   UFE.UniqueID = Data.UniqueID;
262c9b7234eSBen Langmuir   UFE.IsNamedPipe = Data.IsNamedPipe;
263c9b7234eSBen Langmuir   UFE.InPCH = Data.InPCH;
264fa361206SSam McCall   UFE.File = std::move(F);
265c8a71468SBen Langmuir   UFE.IsValid = true;
266ddbabc6bSSimon Marchi 
267fa361206SSam McCall   if (UFE.File) {
268fa361206SSam McCall     if (auto PathName = UFE.File->getName())
269fa361206SSam McCall       fillRealPathName(&UFE, *PathName);
270*cd8607dbSJan Korous   } else if (!openFile) {
271*cd8607dbSJan Korous     // We should still fill the path even if we aren't opening the file.
272*cd8607dbSJan Korous     fillRealPathName(&UFE, InterndFileName);
273fa361206SSam McCall   }
2747a51313dSChris Lattner   return &UFE;
2757a51313dSChris Lattner }
2767a51313dSChris Lattner 
277407e2124SDouglas Gregor const FileEntry *
2780e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size,
2795159f616SChris Lattner                             time_t ModificationTime) {
280407e2124SDouglas Gregor   ++NumFileLookups;
281407e2124SDouglas Gregor 
282018ab5faSRichard Smith   // See if there is already an entry in the map for an existing file.
283018ab5faSRichard Smith   auto &NamedFileEnt = *SeenFileEntries.insert({Filename, nullptr}).first;
284018ab5faSRichard Smith   if (NamedFileEnt.second)
28513156b68SDavid Blaikie     return NamedFileEnt.second;
286407e2124SDouglas Gregor 
287018ab5faSRichard Smith   // We've not seen this before, or the file is cached as non-existent.
288407e2124SDouglas Gregor   ++NumFileCacheMisses;
289e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(Filename);
290f1186c5aSCraig Topper   FileEntry *UFE = nullptr;
291e1dd3e2cSZhanyong Wan 
292e1dd3e2cSZhanyong Wan   // Now that all ancestors of Filename are in the cache, the
293e1dd3e2cSZhanyong Wan   // following call is guaranteed to find the DirectoryEntry from the
294e1dd3e2cSZhanyong Wan   // cache.
2951735f4e7SDouglas Gregor   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
2961735f4e7SDouglas Gregor                                                        /*CacheFailure=*/true);
297e1dd3e2cSZhanyong Wan   assert(DirInfo &&
298e1dd3e2cSZhanyong Wan          "The directory of a virtual file should already be in the cache.");
299e1dd3e2cSZhanyong Wan 
300606c4ac3SDouglas Gregor   // Check to see if the file exists. If so, drop the virtual file
301f8f91b89SRafael Espindola   FileData Data;
30213156b68SDavid Blaikie   const char *InterndFileName = NamedFileEnt.first().data();
303f1186c5aSCraig Topper   if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
304f8f91b89SRafael Espindola     Data.Size = Size;
305f8f91b89SRafael Espindola     Data.ModTime = ModificationTime;
306c9b7234eSBen Langmuir     UFE = &UniqueRealFiles[Data.UniqueID];
307606c4ac3SDouglas Gregor 
30813156b68SDavid Blaikie     NamedFileEnt.second = UFE;
309606c4ac3SDouglas Gregor 
310606c4ac3SDouglas Gregor     // If we had already opened this file, close it now so we don't
311606c4ac3SDouglas Gregor     // leak the descriptor. We're not going to use the file
312606c4ac3SDouglas Gregor     // descriptor anyway, since this is a virtual file.
313c8130a74SBen Langmuir     if (UFE->File)
314c8130a74SBen Langmuir       UFE->closeFile();
315606c4ac3SDouglas Gregor 
316606c4ac3SDouglas Gregor     // If we already have an entry with this inode, return it.
317c8a71468SBen Langmuir     if (UFE->isValid())
318606c4ac3SDouglas Gregor       return UFE;
319c9b7234eSBen Langmuir 
320c9b7234eSBen Langmuir     UFE->UniqueID = Data.UniqueID;
321c9b7234eSBen Langmuir     UFE->IsNamedPipe = Data.IsNamedPipe;
322c9b7234eSBen Langmuir     UFE->InPCH = Data.InPCH;
323e9870c0cSKadir Cetinkaya     fillRealPathName(UFE, Data.Name);
324018ab5faSRichard Smith   } else {
325d2725a31SDavid Blaikie     VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
326d2725a31SDavid Blaikie     UFE = VirtualFileEntries.back().get();
32713156b68SDavid Blaikie     NamedFileEnt.second = UFE;
328606c4ac3SDouglas Gregor   }
329407e2124SDouglas Gregor 
3309624b695SChris Lattner   UFE->Name    = InterndFileName;
331407e2124SDouglas Gregor   UFE->Size    = Size;
332407e2124SDouglas Gregor   UFE->ModTime = ModificationTime;
333407e2124SDouglas Gregor   UFE->Dir     = DirInfo;
334407e2124SDouglas Gregor   UFE->UID     = NextFileUID++;
335dfffaf57SErik Verbruggen   UFE->IsValid = true;
336c8130a74SBen Langmuir   UFE->File.reset();
337407e2124SDouglas Gregor   return UFE;
338407e2124SDouglas Gregor }
339407e2124SDouglas Gregor 
340c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
3410e62c1ccSChris Lattner   StringRef pathRef(path.data(), path.size());
342b5c356a4SAnders Carlsson 
3439ba8fb1eSAnders Carlsson   if (FileSystemOpts.WorkingDir.empty()
3449ba8fb1eSAnders Carlsson       || llvm::sys::path::is_absolute(pathRef))
345c56419edSArgyrios Kyrtzidis     return false;
34671731d6bSArgyrios Kyrtzidis 
3472c1dd271SDylan Noblesmith   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
348b5c356a4SAnders Carlsson   llvm::sys::path::append(NewPath, pathRef);
3496e640998SChris Lattner   path = NewPath;
350c56419edSArgyrios Kyrtzidis   return true;
351c56419edSArgyrios Kyrtzidis }
352c56419edSArgyrios Kyrtzidis 
353c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
354c56419edSArgyrios Kyrtzidis   bool Changed = FixupRelativePath(Path);
355c56419edSArgyrios Kyrtzidis 
356c56419edSArgyrios Kyrtzidis   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
35747035c02SIlya Biryukov     FS->makeAbsolute(Path);
358c56419edSArgyrios Kyrtzidis     Changed = true;
359c56419edSArgyrios Kyrtzidis   }
360c56419edSArgyrios Kyrtzidis 
361c56419edSArgyrios Kyrtzidis   return Changed;
3626e640998SChris Lattner }
3636e640998SChris Lattner 
364e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
365e9870c0cSKadir Cetinkaya   llvm::SmallString<128> AbsPath(FileName);
366e9870c0cSKadir Cetinkaya   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
367e9870c0cSKadir Cetinkaya   // but can be very expensive on real file systems.
368e9870c0cSKadir Cetinkaya   // FIXME: the semantic of RealPathName is unclear, and the name might be
369e9870c0cSKadir Cetinkaya   // misleading. We need to clean up the interface here.
370e9870c0cSKadir Cetinkaya   makeAbsolutePath(AbsPath);
371e9870c0cSKadir Cetinkaya   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
372e9870c0cSKadir Cetinkaya   UFE->RealPathName = AbsPath.str();
373e9870c0cSKadir Cetinkaya }
374e9870c0cSKadir Cetinkaya 
375a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
376a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
377a885796dSBenjamin Kramer                               bool ShouldCloseOpenFile) {
3786d7833f1SArgyrios Kyrtzidis   uint64_t FileSize = Entry->getSize();
3796d7833f1SArgyrios Kyrtzidis   // If there's a high enough chance that the file have changed since we
3806d7833f1SArgyrios Kyrtzidis   // got its size, force a stat before opening it.
3816d7833f1SArgyrios Kyrtzidis   if (isVolatile)
3826d7833f1SArgyrios Kyrtzidis     FileSize = -1;
3836d7833f1SArgyrios Kyrtzidis 
384004b9c7aSMehdi Amini   StringRef Filename = Entry->getName();
3855ea7d07dSChris Lattner   // If the file is already open, use the open file descriptor.
386c8130a74SBen Langmuir   if (Entry->File) {
387a885796dSBenjamin Kramer     auto Result =
388a885796dSBenjamin Kramer         Entry->File->getBuffer(Filename, FileSize,
38926d56393SArgyrios Kyrtzidis                                /*RequiresNullTerminator=*/true, isVolatile);
3909801b253SBen Langmuir     // FIXME: we need a set of APIs that can make guarantees about whether a
3919801b253SBen Langmuir     // FileEntry is open or not.
3929801b253SBen Langmuir     if (ShouldCloseOpenFile)
393c8130a74SBen Langmuir       Entry->closeFile();
3946406f7b8SRafael Espindola     return Result;
3955ea7d07dSChris Lattner   }
3966e640998SChris Lattner 
3975ea7d07dSChris Lattner   // Otherwise, open the file.
398669b0b15SArgyrios Kyrtzidis 
399a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
400a885796dSBenjamin Kramer     return FS->getBufferForFile(Filename, FileSize,
40126d56393SArgyrios Kyrtzidis                                 /*RequiresNullTerminator=*/true, isVolatile);
4025ea7d07dSChris Lattner 
4032c1dd271SDylan Noblesmith   SmallString<128> FilePath(Entry->getName());
404878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
40592e1b62dSYaron Keren   return FS->getBufferForFile(FilePath, FileSize,
40626d56393SArgyrios Kyrtzidis                               /*RequiresNullTerminator=*/true, isVolatile);
40726b5c190SChris Lattner }
40826b5c190SChris Lattner 
409a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4102ebe3a02SIvan Donchevskii FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
411a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
4122ebe3a02SIvan Donchevskii     return FS->getBufferForFile(Filename, -1, true, isVolatile);
41326b5c190SChris Lattner 
4142c1dd271SDylan Noblesmith   SmallString<128> FilePath(Filename);
415878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
4162ebe3a02SIvan Donchevskii   return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
41771731d6bSArgyrios Kyrtzidis }
41871731d6bSArgyrios Kyrtzidis 
419e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path,
420e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible.  This returns true
421e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns
422e1dd3e2cSZhanyong Wan /// false if it's an existent real file.  If FileDescriptor is NULL,
423e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up.
4240df59d8cSMehdi Amini bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile,
425fc51490bSJonas Devlieghere                                std::unique_ptr<llvm::vfs::File> *F) {
426226efd35SChris Lattner   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
427226efd35SChris Lattner   // absolute!
4285769c3dfSChris Lattner   if (FileSystemOpts.WorkingDir.empty())
429c8130a74SBen Langmuir     return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
430226efd35SChris Lattner 
4312c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
432878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
43371731d6bSArgyrios Kyrtzidis 
434c8130a74SBen Langmuir   return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
435c8130a74SBen Langmuir                                   StatCache.get(), *FS);
43671731d6bSArgyrios Kyrtzidis }
43771731d6bSArgyrios Kyrtzidis 
4380e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path,
439fc51490bSJonas Devlieghere                                         llvm::vfs::Status &Result) {
4402c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
4415e368405SAnders Carlsson   FixupRelativePath(FilePath);
4425e368405SAnders Carlsson 
443fc51490bSJonas Devlieghere   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
444c8130a74SBen Langmuir   if (!S)
445c8130a74SBen Langmuir     return true;
446c8130a74SBen Langmuir   Result = *S;
447c8130a74SBen Langmuir   return false;
4485e368405SAnders Carlsson }
4495e368405SAnders Carlsson 
450b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) {
451b3074003SAxel Naumann   assert(Entry && "Cannot invalidate a NULL FileEntry");
45238179d96SAxel Naumann 
45338179d96SAxel Naumann   SeenFileEntries.erase(Entry->getName());
454b3074003SAxel Naumann 
455b3074003SAxel Naumann   // FileEntry invalidation should not block future optimizations in the file
456b3074003SAxel Naumann   // caches. Possible alternatives are cache truncation (invalidate last N) or
457b3074003SAxel Naumann   // invalidation of the whole cache.
458018ab5faSRichard Smith   //
459018ab5faSRichard Smith   // FIXME: This is broken. We sometimes have the same FileEntry* shared
460018ab5faSRichard Smith   // betweeen multiple SeenFileEntries, so this can leave dangling pointers.
461c9b7234eSBen Langmuir   UniqueRealFiles.erase(Entry->getUniqueID());
46238179d96SAxel Naumann }
46338179d96SAxel Naumann 
46409b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping(
4650e62c1ccSChris Lattner                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
46609b6989eSDouglas Gregor   UIDToFiles.clear();
46709b6989eSDouglas Gregor   UIDToFiles.resize(NextFileUID);
46809b6989eSDouglas Gregor 
46909b6989eSDouglas Gregor   // Map file entries
47009b6989eSDouglas Gregor   for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
471e1dd3e2cSZhanyong Wan          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
47209b6989eSDouglas Gregor        FE != FEEnd; ++FE)
473018ab5faSRichard Smith     if (FE->getValue())
47409b6989eSDouglas Gregor       UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
47509b6989eSDouglas Gregor 
47609b6989eSDouglas Gregor   // Map virtual file entries
477d2725a31SDavid Blaikie   for (const auto &VFE : VirtualFileEntries)
478d2725a31SDavid Blaikie     UIDToFiles[VFE->getUID()] = VFE.get();
47909b6989eSDouglas Gregor }
480226efd35SChris Lattner 
4816eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File,
4826eec06d0SArgyrios Kyrtzidis                                   off_t Size, time_t ModificationTime) {
4836eec06d0SArgyrios Kyrtzidis   File->Size = Size;
4846eec06d0SArgyrios Kyrtzidis   File->ModTime = ModificationTime;
4856eec06d0SArgyrios Kyrtzidis }
4866eec06d0SArgyrios Kyrtzidis 
487e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
488e00c8b20SDouglas Gregor   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
489e00c8b20SDouglas Gregor   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
490e00c8b20SDouglas Gregor     = CanonicalDirNames.find(Dir);
491e00c8b20SDouglas Gregor   if (Known != CanonicalDirNames.end())
492e00c8b20SDouglas Gregor     return Known->second;
493e00c8b20SDouglas Gregor 
494e00c8b20SDouglas Gregor   StringRef CanonicalName(Dir->getName());
49554cc3c2fSRichard Smith 
4965fb18fecSEric Liu   SmallString<4096> CanonicalNameBuf;
4975fb18fecSEric Liu   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
498da4690aeSBenjamin Kramer     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
499e00c8b20SDouglas Gregor 
500018ab5faSRichard Smith   CanonicalDirNames.insert({Dir, CanonicalName});
501e00c8b20SDouglas Gregor   return CanonicalName;
502e00c8b20SDouglas Gregor }
503226efd35SChris Lattner 
5047a51313dSChris Lattner void FileManager::PrintStats() const {
50589b422c1SBenjamin Kramer   llvm::errs() << "\n*** File Manager Stats:\n";
506e1dd3e2cSZhanyong Wan   llvm::errs() << UniqueRealFiles.size() << " real files found, "
507e1dd3e2cSZhanyong Wan                << UniqueRealDirs.size() << " real dirs found.\n";
508e1dd3e2cSZhanyong Wan   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
509e1dd3e2cSZhanyong Wan                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
51089b422c1SBenjamin Kramer   llvm::errs() << NumDirLookups << " dir lookups, "
5117a51313dSChris Lattner                << NumDirCacheMisses << " dir cache misses.\n";
51289b422c1SBenjamin Kramer   llvm::errs() << NumFileLookups << " file lookups, "
5137a51313dSChris Lattner                << NumFileCacheMisses << " file cache misses.\n";
5147a51313dSChris Lattner 
51589b422c1SBenjamin Kramer   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
5167a51313dSChris Lattner }
517