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"
21d2725a31SDavid Blaikie #include "llvm/ADT/STLExtras.h"
22e8752a9dSVolodymyr Sapsai #include "llvm/ADT/SmallString.h"
23e8752a9dSVolodymyr Sapsai #include "llvm/ADT/Statistic.h"
24e8752a9dSVolodymyr Sapsai #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"
2935b79c24SEugene Zelenko #include <algorithm>
3035b79c24SEugene Zelenko #include <cassert>
3135b79c24SEugene Zelenko #include <climits>
3235b79c24SEugene Zelenko #include <cstdint>
3335b79c24SEugene Zelenko #include <cstdlib>
3426db6481SBenjamin Kramer #include <string>
3535b79c24SEugene Zelenko #include <utility>
36278038b4SChris Lattner 
377a51313dSChris Lattner using namespace clang;
387a51313dSChris Lattner 
39e8752a9dSVolodymyr Sapsai #define DEBUG_TYPE "file-search"
40e8752a9dSVolodymyr Sapsai 
41e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
42e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
43e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
44e8752a9dSVolodymyr Sapsai                          "Number of directory cache misses.");
45e8752a9dSVolodymyr Sapsai ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
46e8752a9dSVolodymyr Sapsai 
475c04bd81STed Kremenek //===----------------------------------------------------------------------===//
485c04bd81STed Kremenek // Common logic.
495c04bd81STed Kremenek //===----------------------------------------------------------------------===//
507a51313dSChris Lattner 
51c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO,
52fc51490bSJonas Devlieghere                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
53f6021ecdSBenjamin Kramer     : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
54f6021ecdSBenjamin Kramer       SeenFileEntries(64), NextFileUID(0) {
55c8130a74SBen Langmuir   // If the caller doesn't provide a virtual file system, just grab the real
56c8130a74SBen Langmuir   // file system.
57f6021ecdSBenjamin Kramer   if (!this->FS)
58fc51490bSJonas Devlieghere     this->FS = llvm::vfs::getRealFileSystem();
597a51313dSChris Lattner }
607a51313dSChris Lattner 
61d2725a31SDavid Blaikie FileManager::~FileManager() = default;
627a51313dSChris Lattner 
63d92b1ae1SAlex Lorenz void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64d2eb58abSDouglas Gregor   assert(statCache && "No stat cache provided?");
6523430ccbSDavid Blaikie   StatCache = std::move(statCache);
66d2eb58abSDouglas Gregor }
67d2eb58abSDouglas Gregor 
68d92b1ae1SAlex Lorenz void FileManager::clearStatCache() { StatCache.reset(); }
693aad855aSManuel Klimek 
709fc8faf9SAdrian Prantl /// Retrieve the directory that the given file name resides in.
71e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file.
72461f0722SHarlan Haskins static llvm::ErrorOr<const DirectoryEntry *>
73461f0722SHarlan Haskins getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
741735f4e7SDouglas Gregor                      bool CacheFailure) {
75f3c0ff73SZhanyong Wan   if (Filename.empty())
76461f0722SHarlan Haskins     return std::errc::no_such_file_or_directory;
77e1dd3e2cSZhanyong Wan 
78f3c0ff73SZhanyong Wan   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
79461f0722SHarlan Haskins     return std::errc::is_a_directory;
800c0e8040SChris Lattner 
810e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Filename);
820c0e8040SChris Lattner   // Use the current directory if file has no path component.
83f3c0ff73SZhanyong Wan   if (DirName.empty())
84f3c0ff73SZhanyong Wan     DirName = ".";
850c0e8040SChris Lattner 
861735f4e7SDouglas Gregor   return FileMgr.getDirectory(DirName, CacheFailure);
87407e2124SDouglas Gregor }
88407e2124SDouglas Gregor 
89e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or
90e1dd3e2cSZhanyong Wan /// a directory) as virtual directories.
910e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
920e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Path);
93f3c0ff73SZhanyong Wan   if (DirName.empty())
941834dc75SDavid Majnemer     DirName = ".";
95e1dd3e2cSZhanyong Wan 
96461f0722SHarlan Haskins   auto &NamedDirEnt = *SeenDirEntries.insert(
97461f0722SHarlan Haskins         {DirName, std::errc::no_such_file_or_directory}).first;
98e1dd3e2cSZhanyong Wan 
99e1dd3e2cSZhanyong Wan   // When caching a virtual directory, we always cache its ancestors
100e1dd3e2cSZhanyong Wan   // at the same time.  Therefore, if DirName is already in the cache,
101e1dd3e2cSZhanyong Wan   // we don't need to recurse as its ancestors must also already be in
102018ab5faSRichard Smith   // the cache (or it's a known non-virtual directory).
103018ab5faSRichard Smith   if (NamedDirEnt.second)
104e1dd3e2cSZhanyong Wan     return;
105e1dd3e2cSZhanyong Wan 
106e1dd3e2cSZhanyong Wan   // Add the virtual directory to the cache.
1072b3d49b6SJonas Devlieghere   auto UDE = std::make_unique<DirectoryEntry>();
1080df59d8cSMehdi Amini   UDE->Name = NamedDirEnt.first();
109461f0722SHarlan Haskins   NamedDirEnt.second = *UDE.get();
110d2725a31SDavid Blaikie   VirtualDirectoryEntries.push_back(std::move(UDE));
111e1dd3e2cSZhanyong Wan 
112e1dd3e2cSZhanyong Wan   // Recursively add the other ancestors.
113e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(DirName);
114e1dd3e2cSZhanyong Wan }
115e1dd3e2cSZhanyong Wan 
1160377ca64SAlex Lorenz llvm::Expected<DirectoryEntryRef>
1170377ca64SAlex Lorenz FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
1188bd8ee76SNAKAMURA Takumi   // stat doesn't like trailing separators except for root directory.
11932f1acf1SNAKAMURA Takumi   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
12032f1acf1SNAKAMURA Takumi   // (though it can strip '\\')
1218bd8ee76SNAKAMURA Takumi   if (DirName.size() > 1 &&
1228bd8ee76SNAKAMURA Takumi       DirName != llvm::sys::path::root_path(DirName) &&
1238bd8ee76SNAKAMURA Takumi       llvm::sys::path::is_separator(DirName.back()))
12432f1acf1SNAKAMURA Takumi     DirName = DirName.substr(0, DirName.size()-1);
1251865df49SNico Weber #ifdef _WIN32
126ee30546cSRafael Espindola   // Fixing a problem with "clang C:test.c" on Windows.
127ee30546cSRafael Espindola   // Stat("C:") does not recognize "C:" as a valid directory
128ee30546cSRafael Espindola   std::string DirNameStr;
129ee30546cSRafael Espindola   if (DirName.size() > 1 && DirName.back() == ':' &&
130ee30546cSRafael Espindola       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
131ee30546cSRafael Espindola     DirNameStr = DirName.str() + '.';
132ee30546cSRafael Espindola     DirName = DirNameStr;
133ee30546cSRafael Espindola   }
134ee30546cSRafael Espindola #endif
13532f1acf1SNAKAMURA Takumi 
1367a51313dSChris Lattner   ++NumDirLookups;
1377a51313dSChris Lattner 
138e1dd3e2cSZhanyong Wan   // See if there was already an entry in the map.  Note that the map
139e1dd3e2cSZhanyong Wan   // contains both virtual and real directories.
140461f0722SHarlan Haskins   auto SeenDirInsertResult =
141461f0722SHarlan Haskins       SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
1420377ca64SAlex Lorenz   if (!SeenDirInsertResult.second) {
1430377ca64SAlex Lorenz     if (SeenDirInsertResult.first->second)
1440377ca64SAlex Lorenz       return DirectoryEntryRef(&*SeenDirInsertResult.first);
1450377ca64SAlex Lorenz     return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
1460377ca64SAlex Lorenz   }
1477a51313dSChris Lattner 
148018ab5faSRichard Smith   // We've not seen this before. Fill it in.
1497a51313dSChris Lattner   ++NumDirCacheMisses;
150018ab5faSRichard Smith   auto &NamedDirEnt = *SeenDirInsertResult.first;
151018ab5faSRichard Smith   assert(!NamedDirEnt.second && "should be newly-created");
1527a51313dSChris Lattner 
1537a51313dSChris Lattner   // Get the null-terminated directory name as stored as the key of the
154e1dd3e2cSZhanyong Wan   // SeenDirEntries map.
1550df59d8cSMehdi Amini   StringRef InterndDirName = NamedDirEnt.first();
1567a51313dSChris Lattner 
1577a51313dSChris Lattner   // Check to see if the directory exists.
15806f64d53SHarlan Haskins   llvm::vfs::Status Status;
159461f0722SHarlan Haskins   auto statError = getStatValue(InterndDirName, Status, false,
160461f0722SHarlan Haskins                                 nullptr /*directory lookup*/);
161461f0722SHarlan Haskins   if (statError) {
162e1dd3e2cSZhanyong Wan     // There's no real directory at the given path.
163461f0722SHarlan Haskins     if (CacheFailure)
164461f0722SHarlan Haskins       NamedDirEnt.second = statError;
165461f0722SHarlan Haskins     else
1661735f4e7SDouglas Gregor       SeenDirEntries.erase(DirName);
1670377ca64SAlex Lorenz     return llvm::errorCodeToError(statError);
168e1dd3e2cSZhanyong Wan   }
1697a51313dSChris Lattner 
170e1dd3e2cSZhanyong Wan   // It exists.  See if we have already opened a directory with the
171e1dd3e2cSZhanyong Wan   // same inode (this occurs on Unix-like systems when one dir is
172e1dd3e2cSZhanyong Wan   // symlinked to another, for example) or the same path (on
173e1dd3e2cSZhanyong Wan   // Windows).
17406f64d53SHarlan Haskins   DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
1757a51313dSChris Lattner 
176461f0722SHarlan Haskins   NamedDirEnt.second = UDE;
1770df59d8cSMehdi Amini   if (UDE.getName().empty()) {
178e1dd3e2cSZhanyong Wan     // We don't have this directory yet, add it.  We use the string
179e1dd3e2cSZhanyong Wan     // key from the SeenDirEntries map as the string.
1807a51313dSChris Lattner     UDE.Name  = InterndDirName;
181e1dd3e2cSZhanyong Wan   }
182e1dd3e2cSZhanyong Wan 
1830377ca64SAlex Lorenz   return DirectoryEntryRef(&NamedDirEnt);
1840377ca64SAlex Lorenz }
1850377ca64SAlex Lorenz 
1860377ca64SAlex Lorenz llvm::ErrorOr<const DirectoryEntry *>
1870377ca64SAlex Lorenz FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
1880377ca64SAlex Lorenz   auto Result = getDirectoryRef(DirName, CacheFailure);
1890377ca64SAlex Lorenz   if (Result)
1900377ca64SAlex Lorenz     return &Result->getDirEntry();
1910377ca64SAlex Lorenz   return llvm::errorToErrorCode(Result.takeError());
1927a51313dSChris Lattner }
1937a51313dSChris Lattner 
194461f0722SHarlan Haskins llvm::ErrorOr<const FileEntry *>
195461f0722SHarlan Haskins FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
1964dc5573aSAlex Lorenz   auto Result = getFileRef(Filename, openFile, CacheFailure);
1974dc5573aSAlex Lorenz   if (Result)
1984dc5573aSAlex Lorenz     return &Result->getFileEntry();
1999ef6c49bSDuncan P. N. Exon Smith   return llvm::errorToErrorCode(Result.takeError());
2004dc5573aSAlex Lorenz }
2014dc5573aSAlex Lorenz 
2029ef6c49bSDuncan P. N. Exon Smith llvm::Expected<FileEntryRef>
2034dc5573aSAlex Lorenz FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
2047a51313dSChris Lattner   ++NumFileLookups;
2057a51313dSChris Lattner 
2067a51313dSChris Lattner   // See if there is already an entry in the map.
207461f0722SHarlan Haskins   auto SeenFileInsertResult =
208461f0722SHarlan Haskins       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
2094dc5573aSAlex Lorenz   if (!SeenFileInsertResult.second) {
2104dc5573aSAlex Lorenz     if (!SeenFileInsertResult.first->second)
2119ef6c49bSDuncan P. N. Exon Smith       return llvm::errorCodeToError(
2129ef6c49bSDuncan P. N. Exon Smith           SeenFileInsertResult.first->second.getError());
2134dc5573aSAlex Lorenz     // Construct and return and FileEntryRef, unless it's a redirect to another
2144dc5573aSAlex Lorenz     // filename.
2154dc5573aSAlex Lorenz     SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second;
2164dc5573aSAlex Lorenz     FileEntry *FE;
2174dc5573aSAlex Lorenz     if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
2184dc5573aSAlex Lorenz       return FileEntryRef(SeenFileInsertResult.first->first(), *FE);
2194dc5573aSAlex Lorenz     return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure);
2204dc5573aSAlex Lorenz   }
2217a51313dSChris Lattner 
222018ab5faSRichard Smith   // We've not seen this before. Fill it in.
223e84385feSSam McCall   ++NumFileCacheMisses;
224b3144145SAlex Suhan   auto *NamedFileEnt = &*SeenFileInsertResult.first;
225b3144145SAlex Suhan   assert(!NamedFileEnt->second && "should be newly-created");
226fa361206SSam McCall 
2277a51313dSChris Lattner   // Get the null-terminated file name as stored as the key of the
228e1dd3e2cSZhanyong Wan   // SeenFileEntries map.
229b3144145SAlex Suhan   StringRef InterndFileName = NamedFileEnt->first();
2307a51313dSChris Lattner 
231966b25b9SChris Lattner   // Look up the directory for the file.  When looking up something like
232966b25b9SChris Lattner   // sys/foo.h we'll discover all of the search directories that have a 'sys'
233966b25b9SChris Lattner   // subdirectory.  This will let us avoid having to waste time on known-to-fail
234966b25b9SChris Lattner   // searches when we go to find sys/bar.h, because all the search directories
235966b25b9SChris Lattner   // without a 'sys' subdir will get a cached failure result.
236461f0722SHarlan Haskins   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
237461f0722SHarlan Haskins   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
238461f0722SHarlan Haskins     if (CacheFailure)
239b3144145SAlex Suhan       NamedFileEnt->second = DirInfoOrErr.getError();
240461f0722SHarlan Haskins     else
2411735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2421735f4e7SDouglas Gregor 
2439ef6c49bSDuncan P. N. Exon Smith     return llvm::errorCodeToError(DirInfoOrErr.getError());
2441735f4e7SDouglas Gregor   }
245461f0722SHarlan Haskins   const DirectoryEntry *DirInfo = *DirInfoOrErr;
246407e2124SDouglas Gregor 
2477a51313dSChris Lattner   // FIXME: Use the directory info to prune this, before doing the stat syscall.
2487a51313dSChris Lattner   // FIXME: This will reduce the # syscalls.
2497a51313dSChris Lattner 
250018ab5faSRichard Smith   // Check to see if the file exists.
251fc51490bSJonas Devlieghere   std::unique_ptr<llvm::vfs::File> F;
25206f64d53SHarlan Haskins   llvm::vfs::Status Status;
253461f0722SHarlan Haskins   auto statError = getStatValue(InterndFileName, Status, true,
254461f0722SHarlan Haskins                                 openFile ? &F : nullptr);
255461f0722SHarlan Haskins   if (statError) {
256e1dd3e2cSZhanyong Wan     // There's no real file at the given path.
257461f0722SHarlan Haskins     if (CacheFailure)
258b3144145SAlex Suhan       NamedFileEnt->second = statError;
259461f0722SHarlan Haskins     else
2601735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2611735f4e7SDouglas Gregor 
2629ef6c49bSDuncan P. N. Exon Smith     return llvm::errorCodeToError(statError);
263e1dd3e2cSZhanyong Wan   }
2647a51313dSChris Lattner 
265ab01d4bbSPatrik Hagglund   assert((openFile || !F) && "undesired open file");
266d6278e32SArgyrios Kyrtzidis 
2677a51313dSChris Lattner   // It exists.  See if we have already opened a file with the same inode.
2687a51313dSChris Lattner   // This occurs when one dir is symlinked to another, for example.
26906f64d53SHarlan Haskins   FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
2707a51313dSChris Lattner 
271b3144145SAlex Suhan   NamedFileEnt->second = &UFE;
272ab86fbe4SBen Langmuir 
273ab86fbe4SBen Langmuir   // If the name returned by getStatValue is different than Filename, re-intern
274ab86fbe4SBen Langmuir   // the name.
27506f64d53SHarlan Haskins   if (Status.getName() != Filename) {
27698f9e94eSRichard Smith     auto &NewNamedFileEnt =
2774dc5573aSAlex Lorenz         *SeenFileEntries.insert({Status.getName(), &UFE}).first;
27898f9e94eSRichard Smith     assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE &&
279ab86fbe4SBen Langmuir            "filename from getStatValue() refers to wrong file");
28098f9e94eSRichard Smith     InterndFileName = NewNamedFileEnt.first().data();
2814dc5573aSAlex Lorenz     // In addition to re-interning the name, construct a redirecting seen file
2824dc5573aSAlex Lorenz     // entry, that will point to the name the filesystem actually wants to use.
2834dc5573aSAlex Lorenz     StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName);
284b3144145SAlex Suhan     auto SeenFileInsertResultIt = SeenFileEntries.find(Filename);
285b3144145SAlex Suhan     assert(SeenFileInsertResultIt != SeenFileEntries.end() &&
286b3144145SAlex Suhan            "unexpected SeenFileEntries cache miss");
287b3144145SAlex Suhan     SeenFileInsertResultIt->second = Redirect;
288b3144145SAlex Suhan     NamedFileEnt = &*SeenFileInsertResultIt;
289ab86fbe4SBen Langmuir   }
290ab86fbe4SBen Langmuir 
291c8a71468SBen Langmuir   if (UFE.isValid()) { // Already have an entry with this inode, return it.
2925de00f3bSBen Langmuir 
2935de00f3bSBen Langmuir     // FIXME: this hack ensures that if we look up a file by a virtual path in
2945de00f3bSBen Langmuir     // the VFS that the getDir() will have the virtual path, even if we found
2955de00f3bSBen Langmuir     // the file by a 'real' path first. This is required in order to find a
2965de00f3bSBen Langmuir     // module's structure when its headers/module map are mapped in the VFS.
2975de00f3bSBen Langmuir     // We should remove this as soon as we can properly support a file having
2985de00f3bSBen Langmuir     // multiple names.
29906f64d53SHarlan Haskins     if (DirInfo != UFE.Dir && Status.IsVFSMapped)
3005de00f3bSBen Langmuir       UFE.Dir = DirInfo;
3015de00f3bSBen Langmuir 
302c0ff9908SManuel Klimek     // Always update the name to use the last name by which a file was accessed.
303c0ff9908SManuel Klimek     // FIXME: Neither this nor always using the first name is correct; we want
304c0ff9908SManuel Klimek     // to switch towards a design where we return a FileName object that
305c0ff9908SManuel Klimek     // encapsulates both the name by which the file was accessed and the
306c0ff9908SManuel Klimek     // corresponding FileEntry.
3074dc5573aSAlex Lorenz     // FIXME: The Name should be removed from FileEntry once all clients
3084dc5573aSAlex Lorenz     // adopt FileEntryRef.
309ab86fbe4SBen Langmuir     UFE.Name = InterndFileName;
310c0ff9908SManuel Klimek 
3114dc5573aSAlex Lorenz     return FileEntryRef(InterndFileName, UFE);
312dd278430SChris Lattner   }
3137a51313dSChris Lattner 
314c9b7234eSBen Langmuir   // Otherwise, we don't have this file yet, add it.
315ab86fbe4SBen Langmuir   UFE.Name    = InterndFileName;
31606f64d53SHarlan Haskins   UFE.Size    = Status.getSize();
31706f64d53SHarlan Haskins   UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
3187a51313dSChris Lattner   UFE.Dir     = DirInfo;
3197a51313dSChris Lattner   UFE.UID     = NextFileUID++;
32006f64d53SHarlan Haskins   UFE.UniqueID = Status.getUniqueID();
32106f64d53SHarlan Haskins   UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
322fa361206SSam McCall   UFE.File = std::move(F);
323c8a71468SBen Langmuir   UFE.IsValid = true;
324ddbabc6bSSimon Marchi 
325fa361206SSam McCall   if (UFE.File) {
326fa361206SSam McCall     if (auto PathName = UFE.File->getName())
327fa361206SSam McCall       fillRealPathName(&UFE, *PathName);
328cd8607dbSJan Korous   } else if (!openFile) {
329cd8607dbSJan Korous     // We should still fill the path even if we aren't opening the file.
330cd8607dbSJan Korous     fillRealPathName(&UFE, InterndFileName);
331fa361206SSam McCall   }
3324dc5573aSAlex Lorenz   return FileEntryRef(InterndFileName, UFE);
3337a51313dSChris Lattner }
3347a51313dSChris Lattner 
335407e2124SDouglas Gregor const FileEntry *
3360e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size,
3375159f616SChris Lattner                             time_t ModificationTime) {
338407e2124SDouglas Gregor   ++NumFileLookups;
339407e2124SDouglas Gregor 
340018ab5faSRichard Smith   // See if there is already an entry in the map for an existing file.
341461f0722SHarlan Haskins   auto &NamedFileEnt = *SeenFileEntries.insert(
342461f0722SHarlan Haskins       {Filename, std::errc::no_such_file_or_directory}).first;
3434dc5573aSAlex Lorenz   if (NamedFileEnt.second) {
3444dc5573aSAlex Lorenz     SeenFileEntryOrRedirect Value = *NamedFileEnt.second;
3454dc5573aSAlex Lorenz     FileEntry *FE;
3464dc5573aSAlex Lorenz     if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
3474dc5573aSAlex Lorenz       return FE;
3484dc5573aSAlex Lorenz     return getVirtualFile(*Value.get<const StringRef *>(), Size,
3494dc5573aSAlex Lorenz                           ModificationTime);
3504dc5573aSAlex Lorenz   }
351407e2124SDouglas Gregor 
352018ab5faSRichard Smith   // We've not seen this before, or the file is cached as non-existent.
353407e2124SDouglas Gregor   ++NumFileCacheMisses;
354e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(Filename);
355f1186c5aSCraig Topper   FileEntry *UFE = nullptr;
356e1dd3e2cSZhanyong Wan 
357e1dd3e2cSZhanyong Wan   // Now that all ancestors of Filename are in the cache, the
358e1dd3e2cSZhanyong Wan   // following call is guaranteed to find the DirectoryEntry from the
359e1dd3e2cSZhanyong Wan   // cache.
360461f0722SHarlan Haskins   auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
361e1dd3e2cSZhanyong Wan   assert(DirInfo &&
362e1dd3e2cSZhanyong Wan          "The directory of a virtual file should already be in the cache.");
363e1dd3e2cSZhanyong Wan 
364606c4ac3SDouglas Gregor   // Check to see if the file exists. If so, drop the virtual file
36506f64d53SHarlan Haskins   llvm::vfs::Status Status;
36613156b68SDavid Blaikie   const char *InterndFileName = NamedFileEnt.first().data();
367461f0722SHarlan Haskins   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
36806f64d53SHarlan Haskins     UFE = &UniqueRealFiles[Status.getUniqueID()];
36906f64d53SHarlan Haskins     Status = llvm::vfs::Status(
37006f64d53SHarlan Haskins       Status.getName(), Status.getUniqueID(),
37106f64d53SHarlan Haskins       llvm::sys::toTimePoint(ModificationTime),
37206f64d53SHarlan Haskins       Status.getUser(), Status.getGroup(), Size,
37306f64d53SHarlan Haskins       Status.getType(), Status.getPermissions());
374606c4ac3SDouglas Gregor 
3754dc5573aSAlex Lorenz     NamedFileEnt.second = UFE;
376606c4ac3SDouglas Gregor 
377606c4ac3SDouglas Gregor     // If we had already opened this file, close it now so we don't
378606c4ac3SDouglas Gregor     // leak the descriptor. We're not going to use the file
379606c4ac3SDouglas Gregor     // descriptor anyway, since this is a virtual file.
380c8130a74SBen Langmuir     if (UFE->File)
381c8130a74SBen Langmuir       UFE->closeFile();
382606c4ac3SDouglas Gregor 
383606c4ac3SDouglas Gregor     // If we already have an entry with this inode, return it.
384c8a71468SBen Langmuir     if (UFE->isValid())
385606c4ac3SDouglas Gregor       return UFE;
386c9b7234eSBen Langmuir 
38706f64d53SHarlan Haskins     UFE->UniqueID = Status.getUniqueID();
38806f64d53SHarlan Haskins     UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
38906f64d53SHarlan Haskins     fillRealPathName(UFE, Status.getName());
390018ab5faSRichard Smith   } else {
3912b3d49b6SJonas Devlieghere     VirtualFileEntries.push_back(std::make_unique<FileEntry>());
392d2725a31SDavid Blaikie     UFE = VirtualFileEntries.back().get();
3934dc5573aSAlex Lorenz     NamedFileEnt.second = UFE;
394606c4ac3SDouglas Gregor   }
395407e2124SDouglas Gregor 
3969624b695SChris Lattner   UFE->Name    = InterndFileName;
397407e2124SDouglas Gregor   UFE->Size    = Size;
398407e2124SDouglas Gregor   UFE->ModTime = ModificationTime;
399461f0722SHarlan Haskins   UFE->Dir     = *DirInfo;
400407e2124SDouglas Gregor   UFE->UID     = NextFileUID++;
401dfffaf57SErik Verbruggen   UFE->IsValid = true;
402c8130a74SBen Langmuir   UFE->File.reset();
403407e2124SDouglas Gregor   return UFE;
404407e2124SDouglas Gregor }
405407e2124SDouglas Gregor 
406e1b7f22bSDuncan P. N. Exon Smith llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
407e1b7f22bSDuncan P. N. Exon Smith   // Stat of the file and return nullptr if it doesn't exist.
408e1b7f22bSDuncan P. N. Exon Smith   llvm::vfs::Status Status;
409e1b7f22bSDuncan P. N. Exon Smith   if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
410e1b7f22bSDuncan P. N. Exon Smith     return None;
411e1b7f22bSDuncan P. N. Exon Smith 
412e1b7f22bSDuncan P. N. Exon Smith   // Fill it in from the stat.
413e1b7f22bSDuncan P. N. Exon Smith   BypassFileEntries.push_back(std::make_unique<FileEntry>());
414e1b7f22bSDuncan P. N. Exon Smith   const FileEntry &VFE = VF.getFileEntry();
415e1b7f22bSDuncan P. N. Exon Smith   FileEntry &BFE = *BypassFileEntries.back();
416e1b7f22bSDuncan P. N. Exon Smith   BFE.Name = VFE.getName();
417e1b7f22bSDuncan P. N. Exon Smith   BFE.Size = Status.getSize();
418e1b7f22bSDuncan P. N. Exon Smith   BFE.Dir = VFE.Dir;
419e1b7f22bSDuncan P. N. Exon Smith   BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
420e1b7f22bSDuncan P. N. Exon Smith   BFE.UID = NextFileUID++;
421e1b7f22bSDuncan P. N. Exon Smith   BFE.IsValid = true;
422e1b7f22bSDuncan P. N. Exon Smith   return FileEntryRef(VF.getName(), BFE);
423e1b7f22bSDuncan P. N. Exon Smith }
424e1b7f22bSDuncan P. N. Exon Smith 
425c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
4260e62c1ccSChris Lattner   StringRef pathRef(path.data(), path.size());
427b5c356a4SAnders Carlsson 
4289ba8fb1eSAnders Carlsson   if (FileSystemOpts.WorkingDir.empty()
4299ba8fb1eSAnders Carlsson       || llvm::sys::path::is_absolute(pathRef))
430c56419edSArgyrios Kyrtzidis     return false;
43171731d6bSArgyrios Kyrtzidis 
4322c1dd271SDylan Noblesmith   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
433b5c356a4SAnders Carlsson   llvm::sys::path::append(NewPath, pathRef);
4346e640998SChris Lattner   path = NewPath;
435c56419edSArgyrios Kyrtzidis   return true;
436c56419edSArgyrios Kyrtzidis }
437c56419edSArgyrios Kyrtzidis 
438c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
439c56419edSArgyrios Kyrtzidis   bool Changed = FixupRelativePath(Path);
440c56419edSArgyrios Kyrtzidis 
441c56419edSArgyrios Kyrtzidis   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
44247035c02SIlya Biryukov     FS->makeAbsolute(Path);
443c56419edSArgyrios Kyrtzidis     Changed = true;
444c56419edSArgyrios Kyrtzidis   }
445c56419edSArgyrios Kyrtzidis 
446c56419edSArgyrios Kyrtzidis   return Changed;
4476e640998SChris Lattner }
4486e640998SChris Lattner 
449e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
450e9870c0cSKadir Cetinkaya   llvm::SmallString<128> AbsPath(FileName);
451e9870c0cSKadir Cetinkaya   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
452e9870c0cSKadir Cetinkaya   // but can be very expensive on real file systems.
453e9870c0cSKadir Cetinkaya   // FIXME: the semantic of RealPathName is unclear, and the name might be
454e9870c0cSKadir Cetinkaya   // misleading. We need to clean up the interface here.
455e9870c0cSKadir Cetinkaya   makeAbsolutePath(AbsPath);
456e9870c0cSKadir Cetinkaya   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
457e9870c0cSKadir Cetinkaya   UFE->RealPathName = AbsPath.str();
458e9870c0cSKadir Cetinkaya }
459e9870c0cSKadir Cetinkaya 
460a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
461122705b9SDuncan P. N. Exon Smith FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile) {
4626d7833f1SArgyrios Kyrtzidis   uint64_t FileSize = Entry->getSize();
4636d7833f1SArgyrios Kyrtzidis   // If there's a high enough chance that the file have changed since we
4646d7833f1SArgyrios Kyrtzidis   // got its size, force a stat before opening it.
4656d7833f1SArgyrios Kyrtzidis   if (isVolatile)
4666d7833f1SArgyrios Kyrtzidis     FileSize = -1;
4676d7833f1SArgyrios Kyrtzidis 
468004b9c7aSMehdi Amini   StringRef Filename = Entry->getName();
4695ea7d07dSChris Lattner   // If the file is already open, use the open file descriptor.
470c8130a74SBen Langmuir   if (Entry->File) {
471a885796dSBenjamin Kramer     auto Result =
472a885796dSBenjamin Kramer         Entry->File->getBuffer(Filename, FileSize,
47326d56393SArgyrios Kyrtzidis                                /*RequiresNullTerminator=*/true, isVolatile);
474c8130a74SBen Langmuir     Entry->closeFile();
4756406f7b8SRafael Espindola     return Result;
4765ea7d07dSChris Lattner   }
4776e640998SChris Lattner 
4785ea7d07dSChris Lattner   // Otherwise, open the file.
479894b8d1dSDuncan P. N. Exon Smith   return getBufferForFileImpl(Filename, FileSize, isVolatile);
480894b8d1dSDuncan P. N. Exon Smith }
481669b0b15SArgyrios Kyrtzidis 
482894b8d1dSDuncan P. N. Exon Smith llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
483894b8d1dSDuncan P. N. Exon Smith FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
484894b8d1dSDuncan P. N. Exon Smith                                   bool isVolatile) {
485a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
486a885796dSBenjamin Kramer     return FS->getBufferForFile(Filename, FileSize,
48726d56393SArgyrios Kyrtzidis                                 /*RequiresNullTerminator=*/true, isVolatile);
4885ea7d07dSChris Lattner 
489894b8d1dSDuncan P. N. Exon Smith   SmallString<128> FilePath(Filename);
490878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
49192e1b62dSYaron Keren   return FS->getBufferForFile(FilePath, FileSize,
49226d56393SArgyrios Kyrtzidis                               /*RequiresNullTerminator=*/true, isVolatile);
49326b5c190SChris Lattner }
49426b5c190SChris Lattner 
495e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path,
496e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible.  This returns true
497e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns
498e1dd3e2cSZhanyong Wan /// false if it's an existent real file.  If FileDescriptor is NULL,
499e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up.
500461f0722SHarlan Haskins std::error_code
501461f0722SHarlan Haskins FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
502461f0722SHarlan Haskins                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
503226efd35SChris Lattner   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
504226efd35SChris Lattner   // absolute!
5055769c3dfSChris Lattner   if (FileSystemOpts.WorkingDir.empty())
506461f0722SHarlan Haskins     return FileSystemStatCache::get(Path, Status, isFile, F,
507461f0722SHarlan Haskins                                     StatCache.get(), *FS);
508226efd35SChris Lattner 
5092c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
510878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
51171731d6bSArgyrios Kyrtzidis 
512461f0722SHarlan Haskins   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
513461f0722SHarlan Haskins                                   StatCache.get(), *FS);
51471731d6bSArgyrios Kyrtzidis }
51571731d6bSArgyrios Kyrtzidis 
516461f0722SHarlan Haskins std::error_code
517461f0722SHarlan Haskins FileManager::getNoncachedStatValue(StringRef Path,
518fc51490bSJonas Devlieghere                                    llvm::vfs::Status &Result) {
5192c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
5205e368405SAnders Carlsson   FixupRelativePath(FilePath);
5215e368405SAnders Carlsson 
522fc51490bSJonas Devlieghere   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
523c8130a74SBen Langmuir   if (!S)
524461f0722SHarlan Haskins     return S.getError();
525c8130a74SBen Langmuir   Result = *S;
526461f0722SHarlan Haskins   return std::error_code();
5275e368405SAnders Carlsson }
5285e368405SAnders Carlsson 
52909b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping(
5300e62c1ccSChris Lattner                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
53109b6989eSDouglas Gregor   UIDToFiles.clear();
53209b6989eSDouglas Gregor   UIDToFiles.resize(NextFileUID);
53309b6989eSDouglas Gregor 
53409b6989eSDouglas Gregor   // Map file entries
5354dc5573aSAlex Lorenz   for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>,
536461f0722SHarlan Haskins                        llvm::BumpPtrAllocator>::const_iterator
5374dc5573aSAlex Lorenz            FE = SeenFileEntries.begin(),
5384dc5573aSAlex Lorenz            FEEnd = SeenFileEntries.end();
53909b6989eSDouglas Gregor        FE != FEEnd; ++FE)
5404dc5573aSAlex Lorenz     if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) {
5414dc5573aSAlex Lorenz       if (const auto *FE = (*Entry).dyn_cast<FileEntry *>())
5424dc5573aSAlex Lorenz         UIDToFiles[FE->getUID()] = FE;
543461f0722SHarlan Haskins     }
54409b6989eSDouglas Gregor 
54509b6989eSDouglas Gregor   // Map virtual file entries
546d2725a31SDavid Blaikie   for (const auto &VFE : VirtualFileEntries)
547d2725a31SDavid Blaikie     UIDToFiles[VFE->getUID()] = VFE.get();
54809b6989eSDouglas Gregor }
549226efd35SChris Lattner 
550e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
551*e8efac4bSKarl-Johan Karlsson   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
552*e8efac4bSKarl-Johan Karlsson     = CanonicalNames.find(Dir);
553*e8efac4bSKarl-Johan Karlsson   if (Known != CanonicalNames.end())
554e00c8b20SDouglas Gregor     return Known->second;
555e00c8b20SDouglas Gregor 
556e00c8b20SDouglas Gregor   StringRef CanonicalName(Dir->getName());
55754cc3c2fSRichard Smith 
5585fb18fecSEric Liu   SmallString<4096> CanonicalNameBuf;
5595fb18fecSEric Liu   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
560da4690aeSBenjamin Kramer     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
561e00c8b20SDouglas Gregor 
562*e8efac4bSKarl-Johan Karlsson   CanonicalNames.insert({Dir, CanonicalName});
563*e8efac4bSKarl-Johan Karlsson   return CanonicalName;
564*e8efac4bSKarl-Johan Karlsson }
565*e8efac4bSKarl-Johan Karlsson 
566*e8efac4bSKarl-Johan Karlsson StringRef FileManager::getCanonicalName(const FileEntry *File) {
567*e8efac4bSKarl-Johan Karlsson   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
568*e8efac4bSKarl-Johan Karlsson     = CanonicalNames.find(File);
569*e8efac4bSKarl-Johan Karlsson   if (Known != CanonicalNames.end())
570*e8efac4bSKarl-Johan Karlsson     return Known->second;
571*e8efac4bSKarl-Johan Karlsson 
572*e8efac4bSKarl-Johan Karlsson   StringRef CanonicalName(File->getName());
573*e8efac4bSKarl-Johan Karlsson 
574*e8efac4bSKarl-Johan Karlsson   SmallString<4096> CanonicalNameBuf;
575*e8efac4bSKarl-Johan Karlsson   if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
576*e8efac4bSKarl-Johan Karlsson     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
577*e8efac4bSKarl-Johan Karlsson 
578*e8efac4bSKarl-Johan Karlsson   CanonicalNames.insert({File, CanonicalName});
579e00c8b20SDouglas Gregor   return CanonicalName;
580e00c8b20SDouglas Gregor }
581226efd35SChris Lattner 
5827a51313dSChris Lattner void FileManager::PrintStats() const {
58389b422c1SBenjamin Kramer   llvm::errs() << "\n*** File Manager Stats:\n";
584e1dd3e2cSZhanyong Wan   llvm::errs() << UniqueRealFiles.size() << " real files found, "
585e1dd3e2cSZhanyong Wan                << UniqueRealDirs.size() << " real dirs found.\n";
586e1dd3e2cSZhanyong Wan   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
587e1dd3e2cSZhanyong Wan                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
58889b422c1SBenjamin Kramer   llvm::errs() << NumDirLookups << " dir lookups, "
5897a51313dSChris Lattner                << NumDirCacheMisses << " dir cache misses.\n";
59089b422c1SBenjamin Kramer   llvm::errs() << NumFileLookups << " file lookups, "
5917a51313dSChris Lattner                << NumFileCacheMisses << " file cache misses.\n";
5927a51313dSChris Lattner 
59389b422c1SBenjamin Kramer   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
5947a51313dSChris Lattner }
595