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.
66461f0722SHarlan Haskins static llvm::ErrorOr<const DirectoryEntry *>
67461f0722SHarlan Haskins getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
681735f4e7SDouglas Gregor                      bool CacheFailure) {
69f3c0ff73SZhanyong Wan   if (Filename.empty())
70461f0722SHarlan Haskins     return std::errc::no_such_file_or_directory;
71e1dd3e2cSZhanyong Wan 
72f3c0ff73SZhanyong Wan   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
73461f0722SHarlan Haskins     return std::errc::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 
90461f0722SHarlan Haskins   auto &NamedDirEnt = *SeenDirEntries.insert(
91461f0722SHarlan Haskins         {DirName, std::errc::no_such_file_or_directory}).first;
92e1dd3e2cSZhanyong Wan 
93e1dd3e2cSZhanyong Wan   // When caching a virtual directory, we always cache its ancestors
94e1dd3e2cSZhanyong Wan   // at the same time.  Therefore, if DirName is already in the cache,
95e1dd3e2cSZhanyong Wan   // we don't need to recurse as its ancestors must also already be in
96018ab5faSRichard Smith   // the cache (or it's a known non-virtual directory).
97018ab5faSRichard Smith   if (NamedDirEnt.second)
98e1dd3e2cSZhanyong Wan     return;
99e1dd3e2cSZhanyong Wan 
100e1dd3e2cSZhanyong Wan   // Add the virtual directory to the cache.
1012b3d49b6SJonas Devlieghere   auto UDE = std::make_unique<DirectoryEntry>();
1020df59d8cSMehdi Amini   UDE->Name = NamedDirEnt.first();
103461f0722SHarlan Haskins   NamedDirEnt.second = *UDE.get();
104d2725a31SDavid Blaikie   VirtualDirectoryEntries.push_back(std::move(UDE));
105e1dd3e2cSZhanyong Wan 
106e1dd3e2cSZhanyong Wan   // Recursively add the other ancestors.
107e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(DirName);
108e1dd3e2cSZhanyong Wan }
109e1dd3e2cSZhanyong Wan 
110461f0722SHarlan Haskins /// Converts a llvm::ErrorOr<T &> to an llvm::ErrorOr<T *> by promoting
111461f0722SHarlan Haskins /// the address of the inner reference to a pointer or by propagating the error.
112461f0722SHarlan Haskins template <typename T>
113461f0722SHarlan Haskins static llvm::ErrorOr<T *> promoteInnerReference(llvm::ErrorOr<T &> value) {
114461f0722SHarlan Haskins   if (value) return &*value;
115461f0722SHarlan Haskins   return value.getError();
116461f0722SHarlan Haskins }
117461f0722SHarlan Haskins 
118461f0722SHarlan Haskins llvm::ErrorOr<const DirectoryEntry *>
119461f0722SHarlan Haskins FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
1208bd8ee76SNAKAMURA Takumi   // stat doesn't like trailing separators except for root directory.
12132f1acf1SNAKAMURA Takumi   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
12232f1acf1SNAKAMURA Takumi   // (though it can strip '\\')
1238bd8ee76SNAKAMURA Takumi   if (DirName.size() > 1 &&
1248bd8ee76SNAKAMURA Takumi       DirName != llvm::sys::path::root_path(DirName) &&
1258bd8ee76SNAKAMURA Takumi       llvm::sys::path::is_separator(DirName.back()))
12632f1acf1SNAKAMURA Takumi     DirName = DirName.substr(0, DirName.size()-1);
1271865df49SNico Weber #ifdef _WIN32
128ee30546cSRafael Espindola   // Fixing a problem with "clang C:test.c" on Windows.
129ee30546cSRafael Espindola   // Stat("C:") does not recognize "C:" as a valid directory
130ee30546cSRafael Espindola   std::string DirNameStr;
131ee30546cSRafael Espindola   if (DirName.size() > 1 && DirName.back() == ':' &&
132ee30546cSRafael Espindola       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
133ee30546cSRafael Espindola     DirNameStr = DirName.str() + '.';
134ee30546cSRafael Espindola     DirName = DirNameStr;
135ee30546cSRafael Espindola   }
136ee30546cSRafael Espindola #endif
13732f1acf1SNAKAMURA Takumi 
1387a51313dSChris Lattner   ++NumDirLookups;
1397a51313dSChris Lattner 
140e1dd3e2cSZhanyong Wan   // See if there was already an entry in the map.  Note that the map
141e1dd3e2cSZhanyong Wan   // contains both virtual and real directories.
142461f0722SHarlan Haskins   auto SeenDirInsertResult =
143461f0722SHarlan Haskins       SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
144018ab5faSRichard Smith   if (!SeenDirInsertResult.second)
145461f0722SHarlan Haskins     return promoteInnerReference(SeenDirInsertResult.first->second);
1467a51313dSChris Lattner 
147018ab5faSRichard Smith   // We've not seen this before. Fill it in.
1487a51313dSChris Lattner   ++NumDirCacheMisses;
149018ab5faSRichard Smith   auto &NamedDirEnt = *SeenDirInsertResult.first;
150018ab5faSRichard Smith   assert(!NamedDirEnt.second && "should be newly-created");
1517a51313dSChris Lattner 
1527a51313dSChris Lattner   // Get the null-terminated directory name as stored as the key of the
153e1dd3e2cSZhanyong Wan   // SeenDirEntries map.
1540df59d8cSMehdi Amini   StringRef InterndDirName = NamedDirEnt.first();
1557a51313dSChris Lattner 
1567a51313dSChris Lattner   // Check to see if the directory exists.
15706f64d53SHarlan Haskins   llvm::vfs::Status Status;
158461f0722SHarlan Haskins   auto statError = getStatValue(InterndDirName, Status, false,
159461f0722SHarlan Haskins                                 nullptr /*directory lookup*/);
160461f0722SHarlan Haskins   if (statError) {
161e1dd3e2cSZhanyong Wan     // There's no real directory at the given path.
162461f0722SHarlan Haskins     if (CacheFailure)
163461f0722SHarlan Haskins       NamedDirEnt.second = statError;
164461f0722SHarlan Haskins     else
1651735f4e7SDouglas Gregor       SeenDirEntries.erase(DirName);
166461f0722SHarlan Haskins     return statError;
167e1dd3e2cSZhanyong Wan   }
1687a51313dSChris Lattner 
169e1dd3e2cSZhanyong Wan   // It exists.  See if we have already opened a directory with the
170e1dd3e2cSZhanyong Wan   // same inode (this occurs on Unix-like systems when one dir is
171e1dd3e2cSZhanyong Wan   // symlinked to another, for example) or the same path (on
172e1dd3e2cSZhanyong Wan   // Windows).
17306f64d53SHarlan Haskins   DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
1747a51313dSChris Lattner 
175461f0722SHarlan Haskins   NamedDirEnt.second = UDE;
1760df59d8cSMehdi Amini   if (UDE.getName().empty()) {
177e1dd3e2cSZhanyong Wan     // We don't have this directory yet, add it.  We use the string
178e1dd3e2cSZhanyong Wan     // key from the SeenDirEntries map as the string.
1797a51313dSChris Lattner     UDE.Name  = InterndDirName;
180e1dd3e2cSZhanyong Wan   }
181e1dd3e2cSZhanyong Wan 
1827a51313dSChris Lattner   return &UDE;
1837a51313dSChris Lattner }
1847a51313dSChris Lattner 
185461f0722SHarlan Haskins llvm::ErrorOr<const FileEntry *>
186461f0722SHarlan Haskins FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
1874dc5573aSAlex Lorenz   auto Result = getFileRef(Filename, openFile, CacheFailure);
1884dc5573aSAlex Lorenz   if (Result)
1894dc5573aSAlex Lorenz     return &Result->getFileEntry();
1909ef6c49bSDuncan P. N. Exon Smith   return llvm::errorToErrorCode(Result.takeError());
1914dc5573aSAlex Lorenz }
1924dc5573aSAlex Lorenz 
1939ef6c49bSDuncan P. N. Exon Smith llvm::Expected<FileEntryRef>
1944dc5573aSAlex Lorenz FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
1957a51313dSChris Lattner   ++NumFileLookups;
1967a51313dSChris Lattner 
1977a51313dSChris Lattner   // See if there is already an entry in the map.
198461f0722SHarlan Haskins   auto SeenFileInsertResult =
199461f0722SHarlan Haskins       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
2004dc5573aSAlex Lorenz   if (!SeenFileInsertResult.second) {
2014dc5573aSAlex Lorenz     if (!SeenFileInsertResult.first->second)
2029ef6c49bSDuncan P. N. Exon Smith       return llvm::errorCodeToError(
2039ef6c49bSDuncan P. N. Exon Smith           SeenFileInsertResult.first->second.getError());
2044dc5573aSAlex Lorenz     // Construct and return and FileEntryRef, unless it's a redirect to another
2054dc5573aSAlex Lorenz     // filename.
2064dc5573aSAlex Lorenz     SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second;
2074dc5573aSAlex Lorenz     FileEntry *FE;
2084dc5573aSAlex Lorenz     if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
2094dc5573aSAlex Lorenz       return FileEntryRef(SeenFileInsertResult.first->first(), *FE);
2104dc5573aSAlex Lorenz     return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure);
2114dc5573aSAlex Lorenz   }
2127a51313dSChris Lattner 
213018ab5faSRichard Smith   // We've not seen this before. Fill it in.
214e84385feSSam McCall   ++NumFileCacheMisses;
215018ab5faSRichard Smith   auto &NamedFileEnt = *SeenFileInsertResult.first;
216018ab5faSRichard Smith   assert(!NamedFileEnt.second && "should be newly-created");
217fa361206SSam McCall 
2187a51313dSChris Lattner   // Get the null-terminated file name as stored as the key of the
219e1dd3e2cSZhanyong Wan   // SeenFileEntries map.
2200df59d8cSMehdi Amini   StringRef InterndFileName = NamedFileEnt.first();
2217a51313dSChris Lattner 
222966b25b9SChris Lattner   // Look up the directory for the file.  When looking up something like
223966b25b9SChris Lattner   // sys/foo.h we'll discover all of the search directories that have a 'sys'
224966b25b9SChris Lattner   // subdirectory.  This will let us avoid having to waste time on known-to-fail
225966b25b9SChris Lattner   // searches when we go to find sys/bar.h, because all the search directories
226966b25b9SChris Lattner   // without a 'sys' subdir will get a cached failure result.
227461f0722SHarlan Haskins   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
228461f0722SHarlan Haskins   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
229461f0722SHarlan Haskins     if (CacheFailure)
230461f0722SHarlan Haskins       NamedFileEnt.second = DirInfoOrErr.getError();
231461f0722SHarlan Haskins     else
2321735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2331735f4e7SDouglas Gregor 
2349ef6c49bSDuncan P. N. Exon Smith     return llvm::errorCodeToError(DirInfoOrErr.getError());
2351735f4e7SDouglas Gregor   }
236461f0722SHarlan Haskins   const DirectoryEntry *DirInfo = *DirInfoOrErr;
237407e2124SDouglas Gregor 
2387a51313dSChris Lattner   // FIXME: Use the directory info to prune this, before doing the stat syscall.
2397a51313dSChris Lattner   // FIXME: This will reduce the # syscalls.
2407a51313dSChris Lattner 
241018ab5faSRichard Smith   // Check to see if the file exists.
242fc51490bSJonas Devlieghere   std::unique_ptr<llvm::vfs::File> F;
24306f64d53SHarlan Haskins   llvm::vfs::Status Status;
244461f0722SHarlan Haskins   auto statError = getStatValue(InterndFileName, Status, true,
245461f0722SHarlan Haskins                                 openFile ? &F : nullptr);
246461f0722SHarlan Haskins   if (statError) {
247e1dd3e2cSZhanyong Wan     // There's no real file at the given path.
248461f0722SHarlan Haskins     if (CacheFailure)
249461f0722SHarlan Haskins       NamedFileEnt.second = statError;
250461f0722SHarlan Haskins     else
2511735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2521735f4e7SDouglas Gregor 
2539ef6c49bSDuncan P. N. Exon Smith     return llvm::errorCodeToError(statError);
254e1dd3e2cSZhanyong Wan   }
2557a51313dSChris Lattner 
256ab01d4bbSPatrik Hagglund   assert((openFile || !F) && "undesired open file");
257d6278e32SArgyrios Kyrtzidis 
2587a51313dSChris Lattner   // It exists.  See if we have already opened a file with the same inode.
2597a51313dSChris Lattner   // This occurs when one dir is symlinked to another, for example.
26006f64d53SHarlan Haskins   FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
2617a51313dSChris Lattner 
2624dc5573aSAlex Lorenz   NamedFileEnt.second = &UFE;
263ab86fbe4SBen Langmuir 
264ab86fbe4SBen Langmuir   // If the name returned by getStatValue is different than Filename, re-intern
265ab86fbe4SBen Langmuir   // the name.
26606f64d53SHarlan Haskins   if (Status.getName() != Filename) {
26798f9e94eSRichard Smith     auto &NewNamedFileEnt =
2684dc5573aSAlex Lorenz         *SeenFileEntries.insert({Status.getName(), &UFE}).first;
26998f9e94eSRichard Smith     assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE &&
270ab86fbe4SBen Langmuir            "filename from getStatValue() refers to wrong file");
27198f9e94eSRichard Smith     InterndFileName = NewNamedFileEnt.first().data();
2724dc5573aSAlex Lorenz     // In addition to re-interning the name, construct a redirecting seen file
2734dc5573aSAlex Lorenz     // entry, that will point to the name the filesystem actually wants to use.
2744dc5573aSAlex Lorenz     StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName);
27598f9e94eSRichard Smith     NamedFileEnt.second = Redirect;
276ab86fbe4SBen Langmuir   }
277ab86fbe4SBen Langmuir 
278c8a71468SBen Langmuir   if (UFE.isValid()) { // Already have an entry with this inode, return it.
2795de00f3bSBen Langmuir 
2805de00f3bSBen Langmuir     // FIXME: this hack ensures that if we look up a file by a virtual path in
2815de00f3bSBen Langmuir     // the VFS that the getDir() will have the virtual path, even if we found
2825de00f3bSBen Langmuir     // the file by a 'real' path first. This is required in order to find a
2835de00f3bSBen Langmuir     // module's structure when its headers/module map are mapped in the VFS.
2845de00f3bSBen Langmuir     // We should remove this as soon as we can properly support a file having
2855de00f3bSBen Langmuir     // multiple names.
28606f64d53SHarlan Haskins     if (DirInfo != UFE.Dir && Status.IsVFSMapped)
2875de00f3bSBen Langmuir       UFE.Dir = DirInfo;
2885de00f3bSBen Langmuir 
289c0ff9908SManuel Klimek     // Always update the name to use the last name by which a file was accessed.
290c0ff9908SManuel Klimek     // FIXME: Neither this nor always using the first name is correct; we want
291c0ff9908SManuel Klimek     // to switch towards a design where we return a FileName object that
292c0ff9908SManuel Klimek     // encapsulates both the name by which the file was accessed and the
293c0ff9908SManuel Klimek     // corresponding FileEntry.
2944dc5573aSAlex Lorenz     // FIXME: The Name should be removed from FileEntry once all clients
2954dc5573aSAlex Lorenz     // adopt FileEntryRef.
296ab86fbe4SBen Langmuir     UFE.Name = InterndFileName;
297c0ff9908SManuel Klimek 
2984dc5573aSAlex Lorenz     return FileEntryRef(InterndFileName, UFE);
299dd278430SChris Lattner   }
3007a51313dSChris Lattner 
301c9b7234eSBen Langmuir   // Otherwise, we don't have this file yet, add it.
302ab86fbe4SBen Langmuir   UFE.Name    = InterndFileName;
30306f64d53SHarlan Haskins   UFE.Size    = Status.getSize();
30406f64d53SHarlan Haskins   UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
3057a51313dSChris Lattner   UFE.Dir     = DirInfo;
3067a51313dSChris Lattner   UFE.UID     = NextFileUID++;
30706f64d53SHarlan Haskins   UFE.UniqueID = Status.getUniqueID();
30806f64d53SHarlan Haskins   UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
309fa361206SSam McCall   UFE.File = std::move(F);
310c8a71468SBen Langmuir   UFE.IsValid = true;
311ddbabc6bSSimon Marchi 
312fa361206SSam McCall   if (UFE.File) {
313fa361206SSam McCall     if (auto PathName = UFE.File->getName())
314fa361206SSam McCall       fillRealPathName(&UFE, *PathName);
315cd8607dbSJan Korous   } else if (!openFile) {
316cd8607dbSJan Korous     // We should still fill the path even if we aren't opening the file.
317cd8607dbSJan Korous     fillRealPathName(&UFE, InterndFileName);
318fa361206SSam McCall   }
3194dc5573aSAlex Lorenz   return FileEntryRef(InterndFileName, UFE);
3207a51313dSChris Lattner }
3217a51313dSChris Lattner 
322407e2124SDouglas Gregor const FileEntry *
3230e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size,
3245159f616SChris Lattner                             time_t ModificationTime) {
325407e2124SDouglas Gregor   ++NumFileLookups;
326407e2124SDouglas Gregor 
327018ab5faSRichard Smith   // See if there is already an entry in the map for an existing file.
328461f0722SHarlan Haskins   auto &NamedFileEnt = *SeenFileEntries.insert(
329461f0722SHarlan Haskins       {Filename, std::errc::no_such_file_or_directory}).first;
3304dc5573aSAlex Lorenz   if (NamedFileEnt.second) {
3314dc5573aSAlex Lorenz     SeenFileEntryOrRedirect Value = *NamedFileEnt.second;
3324dc5573aSAlex Lorenz     FileEntry *FE;
3334dc5573aSAlex Lorenz     if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
3344dc5573aSAlex Lorenz       return FE;
3354dc5573aSAlex Lorenz     return getVirtualFile(*Value.get<const StringRef *>(), Size,
3364dc5573aSAlex Lorenz                           ModificationTime);
3374dc5573aSAlex Lorenz   }
338407e2124SDouglas Gregor 
339018ab5faSRichard Smith   // We've not seen this before, or the file is cached as non-existent.
340407e2124SDouglas Gregor   ++NumFileCacheMisses;
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.
347461f0722SHarlan Haskins   auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
348e1dd3e2cSZhanyong Wan   assert(DirInfo &&
349e1dd3e2cSZhanyong Wan          "The directory of a virtual file should already be in the cache.");
350e1dd3e2cSZhanyong Wan 
351606c4ac3SDouglas Gregor   // Check to see if the file exists. If so, drop the virtual file
35206f64d53SHarlan Haskins   llvm::vfs::Status Status;
35313156b68SDavid Blaikie   const char *InterndFileName = NamedFileEnt.first().data();
354461f0722SHarlan Haskins   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
35506f64d53SHarlan Haskins     UFE = &UniqueRealFiles[Status.getUniqueID()];
35606f64d53SHarlan Haskins     Status = llvm::vfs::Status(
35706f64d53SHarlan Haskins       Status.getName(), Status.getUniqueID(),
35806f64d53SHarlan Haskins       llvm::sys::toTimePoint(ModificationTime),
35906f64d53SHarlan Haskins       Status.getUser(), Status.getGroup(), Size,
36006f64d53SHarlan Haskins       Status.getType(), Status.getPermissions());
361606c4ac3SDouglas Gregor 
3624dc5573aSAlex Lorenz     NamedFileEnt.second = UFE;
363606c4ac3SDouglas Gregor 
364606c4ac3SDouglas Gregor     // If we had already opened this file, close it now so we don't
365606c4ac3SDouglas Gregor     // leak the descriptor. We're not going to use the file
366606c4ac3SDouglas Gregor     // descriptor anyway, since this is a virtual file.
367c8130a74SBen Langmuir     if (UFE->File)
368c8130a74SBen Langmuir       UFE->closeFile();
369606c4ac3SDouglas Gregor 
370606c4ac3SDouglas Gregor     // If we already have an entry with this inode, return it.
371c8a71468SBen Langmuir     if (UFE->isValid())
372606c4ac3SDouglas Gregor       return UFE;
373c9b7234eSBen Langmuir 
37406f64d53SHarlan Haskins     UFE->UniqueID = Status.getUniqueID();
37506f64d53SHarlan Haskins     UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
37606f64d53SHarlan Haskins     fillRealPathName(UFE, Status.getName());
377018ab5faSRichard Smith   } else {
3782b3d49b6SJonas Devlieghere     VirtualFileEntries.push_back(std::make_unique<FileEntry>());
379d2725a31SDavid Blaikie     UFE = VirtualFileEntries.back().get();
3804dc5573aSAlex Lorenz     NamedFileEnt.second = UFE;
381606c4ac3SDouglas Gregor   }
382407e2124SDouglas Gregor 
3839624b695SChris Lattner   UFE->Name    = InterndFileName;
384407e2124SDouglas Gregor   UFE->Size    = Size;
385407e2124SDouglas Gregor   UFE->ModTime = ModificationTime;
386461f0722SHarlan Haskins   UFE->Dir     = *DirInfo;
387407e2124SDouglas Gregor   UFE->UID     = NextFileUID++;
388dfffaf57SErik Verbruggen   UFE->IsValid = true;
389c8130a74SBen Langmuir   UFE->File.reset();
390407e2124SDouglas Gregor   return UFE;
391407e2124SDouglas Gregor }
392407e2124SDouglas Gregor 
393c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
3940e62c1ccSChris Lattner   StringRef pathRef(path.data(), path.size());
395b5c356a4SAnders Carlsson 
3969ba8fb1eSAnders Carlsson   if (FileSystemOpts.WorkingDir.empty()
3979ba8fb1eSAnders Carlsson       || llvm::sys::path::is_absolute(pathRef))
398c56419edSArgyrios Kyrtzidis     return false;
39971731d6bSArgyrios Kyrtzidis 
4002c1dd271SDylan Noblesmith   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
401b5c356a4SAnders Carlsson   llvm::sys::path::append(NewPath, pathRef);
4026e640998SChris Lattner   path = NewPath;
403c56419edSArgyrios Kyrtzidis   return true;
404c56419edSArgyrios Kyrtzidis }
405c56419edSArgyrios Kyrtzidis 
406c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
407c56419edSArgyrios Kyrtzidis   bool Changed = FixupRelativePath(Path);
408c56419edSArgyrios Kyrtzidis 
409c56419edSArgyrios Kyrtzidis   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
41047035c02SIlya Biryukov     FS->makeAbsolute(Path);
411c56419edSArgyrios Kyrtzidis     Changed = true;
412c56419edSArgyrios Kyrtzidis   }
413c56419edSArgyrios Kyrtzidis 
414c56419edSArgyrios Kyrtzidis   return Changed;
4156e640998SChris Lattner }
4166e640998SChris Lattner 
417e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
418e9870c0cSKadir Cetinkaya   llvm::SmallString<128> AbsPath(FileName);
419e9870c0cSKadir Cetinkaya   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
420e9870c0cSKadir Cetinkaya   // but can be very expensive on real file systems.
421e9870c0cSKadir Cetinkaya   // FIXME: the semantic of RealPathName is unclear, and the name might be
422e9870c0cSKadir Cetinkaya   // misleading. We need to clean up the interface here.
423e9870c0cSKadir Cetinkaya   makeAbsolutePath(AbsPath);
424e9870c0cSKadir Cetinkaya   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
425e9870c0cSKadir Cetinkaya   UFE->RealPathName = AbsPath.str();
426e9870c0cSKadir Cetinkaya }
427e9870c0cSKadir Cetinkaya 
428a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
429*122705b9SDuncan P. N. Exon Smith FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile) {
4306d7833f1SArgyrios Kyrtzidis   uint64_t FileSize = Entry->getSize();
4316d7833f1SArgyrios Kyrtzidis   // If there's a high enough chance that the file have changed since we
4326d7833f1SArgyrios Kyrtzidis   // got its size, force a stat before opening it.
4336d7833f1SArgyrios Kyrtzidis   if (isVolatile)
4346d7833f1SArgyrios Kyrtzidis     FileSize = -1;
4356d7833f1SArgyrios Kyrtzidis 
436004b9c7aSMehdi Amini   StringRef Filename = Entry->getName();
4375ea7d07dSChris Lattner   // If the file is already open, use the open file descriptor.
438c8130a74SBen Langmuir   if (Entry->File) {
439a885796dSBenjamin Kramer     auto Result =
440a885796dSBenjamin Kramer         Entry->File->getBuffer(Filename, FileSize,
44126d56393SArgyrios Kyrtzidis                                /*RequiresNullTerminator=*/true, isVolatile);
442c8130a74SBen Langmuir     Entry->closeFile();
4436406f7b8SRafael Espindola     return Result;
4445ea7d07dSChris Lattner   }
4456e640998SChris Lattner 
4465ea7d07dSChris Lattner   // Otherwise, open the file.
447894b8d1dSDuncan P. N. Exon Smith   return getBufferForFileImpl(Filename, FileSize, isVolatile);
448894b8d1dSDuncan P. N. Exon Smith }
449669b0b15SArgyrios Kyrtzidis 
450894b8d1dSDuncan P. N. Exon Smith llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
451894b8d1dSDuncan P. N. Exon Smith FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
452894b8d1dSDuncan P. N. Exon Smith                                   bool isVolatile) {
453a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
454a885796dSBenjamin Kramer     return FS->getBufferForFile(Filename, FileSize,
45526d56393SArgyrios Kyrtzidis                                 /*RequiresNullTerminator=*/true, isVolatile);
4565ea7d07dSChris Lattner 
457894b8d1dSDuncan P. N. Exon Smith   SmallString<128> FilePath(Filename);
458878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
45992e1b62dSYaron Keren   return FS->getBufferForFile(FilePath, FileSize,
46026d56393SArgyrios Kyrtzidis                               /*RequiresNullTerminator=*/true, isVolatile);
46126b5c190SChris Lattner }
46226b5c190SChris Lattner 
463e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path,
464e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible.  This returns true
465e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns
466e1dd3e2cSZhanyong Wan /// false if it's an existent real file.  If FileDescriptor is NULL,
467e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up.
468461f0722SHarlan Haskins std::error_code
469461f0722SHarlan Haskins FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
470461f0722SHarlan Haskins                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
471226efd35SChris Lattner   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
472226efd35SChris Lattner   // absolute!
4735769c3dfSChris Lattner   if (FileSystemOpts.WorkingDir.empty())
474461f0722SHarlan Haskins     return FileSystemStatCache::get(Path, Status, isFile, F,
475461f0722SHarlan Haskins                                     StatCache.get(), *FS);
476226efd35SChris Lattner 
4772c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
478878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
47971731d6bSArgyrios Kyrtzidis 
480461f0722SHarlan Haskins   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
481461f0722SHarlan Haskins                                   StatCache.get(), *FS);
48271731d6bSArgyrios Kyrtzidis }
48371731d6bSArgyrios Kyrtzidis 
484461f0722SHarlan Haskins std::error_code
485461f0722SHarlan Haskins FileManager::getNoncachedStatValue(StringRef Path,
486fc51490bSJonas Devlieghere                                    llvm::vfs::Status &Result) {
4872c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
4885e368405SAnders Carlsson   FixupRelativePath(FilePath);
4895e368405SAnders Carlsson 
490fc51490bSJonas Devlieghere   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
491c8130a74SBen Langmuir   if (!S)
492461f0722SHarlan Haskins     return S.getError();
493c8130a74SBen Langmuir   Result = *S;
494461f0722SHarlan Haskins   return std::error_code();
4955e368405SAnders Carlsson }
4965e368405SAnders Carlsson 
49709b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping(
4980e62c1ccSChris Lattner                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
49909b6989eSDouglas Gregor   UIDToFiles.clear();
50009b6989eSDouglas Gregor   UIDToFiles.resize(NextFileUID);
50109b6989eSDouglas Gregor 
50209b6989eSDouglas Gregor   // Map file entries
5034dc5573aSAlex Lorenz   for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>,
504461f0722SHarlan Haskins                        llvm::BumpPtrAllocator>::const_iterator
5054dc5573aSAlex Lorenz            FE = SeenFileEntries.begin(),
5064dc5573aSAlex Lorenz            FEEnd = SeenFileEntries.end();
50709b6989eSDouglas Gregor        FE != FEEnd; ++FE)
5084dc5573aSAlex Lorenz     if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) {
5094dc5573aSAlex Lorenz       if (const auto *FE = (*Entry).dyn_cast<FileEntry *>())
5104dc5573aSAlex Lorenz         UIDToFiles[FE->getUID()] = FE;
511461f0722SHarlan Haskins     }
51209b6989eSDouglas Gregor 
51309b6989eSDouglas Gregor   // Map virtual file entries
514d2725a31SDavid Blaikie   for (const auto &VFE : VirtualFileEntries)
515d2725a31SDavid Blaikie     UIDToFiles[VFE->getUID()] = VFE.get();
51609b6989eSDouglas Gregor }
517226efd35SChris Lattner 
5186eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File,
5196eec06d0SArgyrios Kyrtzidis                                   off_t Size, time_t ModificationTime) {
5206eec06d0SArgyrios Kyrtzidis   File->Size = Size;
5216eec06d0SArgyrios Kyrtzidis   File->ModTime = ModificationTime;
5226eec06d0SArgyrios Kyrtzidis }
5236eec06d0SArgyrios Kyrtzidis 
524e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
525e00c8b20SDouglas Gregor   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
526e00c8b20SDouglas Gregor   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
527e00c8b20SDouglas Gregor     = CanonicalDirNames.find(Dir);
528e00c8b20SDouglas Gregor   if (Known != CanonicalDirNames.end())
529e00c8b20SDouglas Gregor     return Known->second;
530e00c8b20SDouglas Gregor 
531e00c8b20SDouglas Gregor   StringRef CanonicalName(Dir->getName());
53254cc3c2fSRichard Smith 
5335fb18fecSEric Liu   SmallString<4096> CanonicalNameBuf;
5345fb18fecSEric Liu   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
535da4690aeSBenjamin Kramer     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
536e00c8b20SDouglas Gregor 
537018ab5faSRichard Smith   CanonicalDirNames.insert({Dir, CanonicalName});
538e00c8b20SDouglas Gregor   return CanonicalName;
539e00c8b20SDouglas Gregor }
540226efd35SChris Lattner 
5417a51313dSChris Lattner void FileManager::PrintStats() const {
54289b422c1SBenjamin Kramer   llvm::errs() << "\n*** File Manager Stats:\n";
543e1dd3e2cSZhanyong Wan   llvm::errs() << UniqueRealFiles.size() << " real files found, "
544e1dd3e2cSZhanyong Wan                << UniqueRealDirs.size() << " real dirs found.\n";
545e1dd3e2cSZhanyong Wan   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
546e1dd3e2cSZhanyong Wan                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
54789b422c1SBenjamin Kramer   llvm::errs() << NumDirLookups << " dir lookups, "
5487a51313dSChris Lattner                << NumDirCacheMisses << " dir cache misses.\n";
54989b422c1SBenjamin Kramer   llvm::errs() << NumFileLookups << " file lookups, "
5507a51313dSChris Lattner                << NumFileCacheMisses << " file cache misses.\n";
5517a51313dSChris Lattner 
55289b422c1SBenjamin Kramer   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
5537a51313dSChris Lattner }
554