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
FileManager(const FileSystemOptions & FSO,IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)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
setStatCache(std::unique_ptr<FileSystemStatCache> statCache)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
clearStatCache()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.
721b042de5SDuncan P. N. Exon Smith static llvm::Expected<DirectoryEntryRef>
getDirectoryFromFile(FileManager & FileMgr,StringRef Filename,bool CacheFailure)73461f0722SHarlan Haskins getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
741735f4e7SDouglas Gregor bool CacheFailure) {
75f3c0ff73SZhanyong Wan if (Filename.empty())
761b042de5SDuncan P. N. Exon Smith return llvm::errorCodeToError(
771b042de5SDuncan P. N. Exon Smith make_error_code(std::errc::no_such_file_or_directory));
78e1dd3e2cSZhanyong Wan
79f3c0ff73SZhanyong Wan if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
801b042de5SDuncan P. N. Exon Smith return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory));
810c0e8040SChris Lattner
820e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Filename);
830c0e8040SChris Lattner // Use the current directory if file has no path component.
84f3c0ff73SZhanyong Wan if (DirName.empty())
85f3c0ff73SZhanyong Wan DirName = ".";
860c0e8040SChris Lattner
871b042de5SDuncan P. N. Exon Smith return FileMgr.getDirectoryRef(DirName, CacheFailure);
88407e2124SDouglas Gregor }
89407e2124SDouglas Gregor
90e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or
91e1dd3e2cSZhanyong Wan /// a directory) as virtual directories.
addAncestorsAsVirtualDirs(StringRef Path)920e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
930e62c1ccSChris Lattner StringRef DirName = llvm::sys::path::parent_path(Path);
94f3c0ff73SZhanyong Wan if (DirName.empty())
951834dc75SDavid Majnemer DirName = ".";
96e1dd3e2cSZhanyong Wan
97461f0722SHarlan Haskins auto &NamedDirEnt = *SeenDirEntries.insert(
98461f0722SHarlan Haskins {DirName, std::errc::no_such_file_or_directory}).first;
99e1dd3e2cSZhanyong Wan
100e1dd3e2cSZhanyong Wan // When caching a virtual directory, we always cache its ancestors
101e1dd3e2cSZhanyong Wan // at the same time. Therefore, if DirName is already in the cache,
102e1dd3e2cSZhanyong Wan // we don't need to recurse as its ancestors must also already be in
103018ab5faSRichard Smith // the cache (or it's a known non-virtual directory).
104018ab5faSRichard Smith if (NamedDirEnt.second)
105e1dd3e2cSZhanyong Wan return;
106e1dd3e2cSZhanyong Wan
107e1dd3e2cSZhanyong Wan // Add the virtual directory to the cache.
108cf1c5507SSam McCall auto *UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
1090df59d8cSMehdi Amini UDE->Name = NamedDirEnt.first();
110cf1c5507SSam McCall NamedDirEnt.second = *UDE;
111cf1c5507SSam McCall VirtualDirectoryEntries.push_back(UDE);
112e1dd3e2cSZhanyong Wan
113e1dd3e2cSZhanyong Wan // Recursively add the other ancestors.
114e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(DirName);
115e1dd3e2cSZhanyong Wan }
116e1dd3e2cSZhanyong Wan
1170377ca64SAlex Lorenz llvm::Expected<DirectoryEntryRef>
getDirectoryRef(StringRef DirName,bool CacheFailure)1180377ca64SAlex Lorenz FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
1198bd8ee76SNAKAMURA Takumi // stat doesn't like trailing separators except for root directory.
12032f1acf1SNAKAMURA Takumi // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
12132f1acf1SNAKAMURA Takumi // (though it can strip '\\')
1228bd8ee76SNAKAMURA Takumi if (DirName.size() > 1 &&
1238bd8ee76SNAKAMURA Takumi DirName != llvm::sys::path::root_path(DirName) &&
1248bd8ee76SNAKAMURA Takumi llvm::sys::path::is_separator(DirName.back()))
12532f1acf1SNAKAMURA Takumi DirName = DirName.substr(0, DirName.size()-1);
1269091df5fSDuncan P. N. Exon Smith Optional<std::string> DirNameStr;
12799023627SDuncan P. N. Exon Smith if (is_style_windows(llvm::sys::path::Style::native)) {
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 if (DirName.size() > 1 && DirName.back() == ':' &&
131e5c7c171SMartin Storsjö DirName.equals_insensitive(llvm::sys::path::root_name(DirName))) {
132ee30546cSRafael Espindola DirNameStr = DirName.str() + '.';
1339091df5fSDuncan P. N. Exon Smith DirName = *DirNameStr;
134ee30546cSRafael Espindola }
13599023627SDuncan P. N. Exon Smith }
13632f1acf1SNAKAMURA Takumi
1377a51313dSChris Lattner ++NumDirLookups;
1387a51313dSChris Lattner
139e1dd3e2cSZhanyong Wan // See if there was already an entry in the map. Note that the map
140e1dd3e2cSZhanyong Wan // contains both virtual and real directories.
141461f0722SHarlan Haskins auto SeenDirInsertResult =
142461f0722SHarlan Haskins SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
1430377ca64SAlex Lorenz if (!SeenDirInsertResult.second) {
1440377ca64SAlex Lorenz if (SeenDirInsertResult.first->second)
1451b042de5SDuncan P. N. Exon Smith return DirectoryEntryRef(*SeenDirInsertResult.first);
1460377ca64SAlex Lorenz return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
1470377ca64SAlex Lorenz }
1487a51313dSChris Lattner
149018ab5faSRichard Smith // We've not seen this before. Fill it in.
1507a51313dSChris Lattner ++NumDirCacheMisses;
151018ab5faSRichard Smith auto &NamedDirEnt = *SeenDirInsertResult.first;
152018ab5faSRichard Smith assert(!NamedDirEnt.second && "should be newly-created");
1537a51313dSChris Lattner
1547a51313dSChris Lattner // Get the null-terminated directory name as stored as the key of the
155e1dd3e2cSZhanyong Wan // SeenDirEntries map.
1560df59d8cSMehdi Amini StringRef InterndDirName = NamedDirEnt.first();
1577a51313dSChris Lattner
1587a51313dSChris Lattner // Check to see if the directory exists.
15906f64d53SHarlan Haskins llvm::vfs::Status Status;
160461f0722SHarlan Haskins auto statError = getStatValue(InterndDirName, Status, false,
161461f0722SHarlan Haskins nullptr /*directory lookup*/);
162461f0722SHarlan Haskins if (statError) {
163e1dd3e2cSZhanyong Wan // There's no real directory at the given path.
164461f0722SHarlan Haskins if (CacheFailure)
165461f0722SHarlan Haskins NamedDirEnt.second = statError;
166461f0722SHarlan Haskins else
1671735f4e7SDouglas Gregor SeenDirEntries.erase(DirName);
1680377ca64SAlex Lorenz return llvm::errorCodeToError(statError);
169e1dd3e2cSZhanyong Wan }
1707a51313dSChris Lattner
171e1dd3e2cSZhanyong Wan // It exists. See if we have already opened a directory with the
172e1dd3e2cSZhanyong Wan // same inode (this occurs on Unix-like systems when one dir is
173e1dd3e2cSZhanyong Wan // symlinked to another, for example) or the same path (on
174e1dd3e2cSZhanyong Wan // Windows).
175cf1c5507SSam McCall DirectoryEntry *&UDE = UniqueRealDirs[Status.getUniqueID()];
1767a51313dSChris Lattner
177cf1c5507SSam McCall if (!UDE) {
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.
180cf1c5507SSam McCall UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
181cf1c5507SSam McCall UDE->Name = InterndDirName;
182e1dd3e2cSZhanyong Wan }
183cf1c5507SSam McCall NamedDirEnt.second = *UDE;
184e1dd3e2cSZhanyong Wan
1851b042de5SDuncan P. N. Exon Smith return DirectoryEntryRef(NamedDirEnt);
1860377ca64SAlex Lorenz }
1870377ca64SAlex Lorenz
1880377ca64SAlex Lorenz llvm::ErrorOr<const DirectoryEntry *>
getDirectory(StringRef DirName,bool CacheFailure)1890377ca64SAlex Lorenz FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
1900377ca64SAlex Lorenz auto Result = getDirectoryRef(DirName, CacheFailure);
1910377ca64SAlex Lorenz if (Result)
1920377ca64SAlex Lorenz return &Result->getDirEntry();
1930377ca64SAlex Lorenz return llvm::errorToErrorCode(Result.takeError());
1947a51313dSChris Lattner }
1957a51313dSChris Lattner
196461f0722SHarlan Haskins llvm::ErrorOr<const FileEntry *>
getFile(StringRef Filename,bool openFile,bool CacheFailure)197461f0722SHarlan Haskins FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
1984dc5573aSAlex Lorenz auto Result = getFileRef(Filename, openFile, CacheFailure);
1994dc5573aSAlex Lorenz if (Result)
2004dc5573aSAlex Lorenz return &Result->getFileEntry();
2019ef6c49bSDuncan P. N. Exon Smith return llvm::errorToErrorCode(Result.takeError());
2024dc5573aSAlex Lorenz }
2034dc5573aSAlex Lorenz
2049ef6c49bSDuncan P. N. Exon Smith llvm::Expected<FileEntryRef>
getFileRef(StringRef Filename,bool openFile,bool CacheFailure)2054dc5573aSAlex Lorenz FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
2067a51313dSChris Lattner ++NumFileLookups;
2077a51313dSChris Lattner
2087a51313dSChris Lattner // See if there is already an entry in the map.
209461f0722SHarlan Haskins auto SeenFileInsertResult =
210461f0722SHarlan Haskins SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
2114dc5573aSAlex Lorenz if (!SeenFileInsertResult.second) {
2124dc5573aSAlex Lorenz if (!SeenFileInsertResult.first->second)
2139ef6c49bSDuncan P. N. Exon Smith return llvm::errorCodeToError(
2149ef6c49bSDuncan P. N. Exon Smith SeenFileInsertResult.first->second.getError());
2154dc5573aSAlex Lorenz // Construct and return and FileEntryRef, unless it's a redirect to another
2164dc5573aSAlex Lorenz // filename.
217917acac9SDuncan P. N. Exon Smith FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
218917acac9SDuncan P. N. Exon Smith if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
219917acac9SDuncan P. N. Exon Smith return FileEntryRef(*SeenFileInsertResult.first);
220739d4bf8SNico Weber return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
221739d4bf8SNico Weber Value.V.get<const void *>()));
2224dc5573aSAlex Lorenz }
2237a51313dSChris Lattner
224018ab5faSRichard Smith // We've not seen this before. Fill it in.
225e84385feSSam McCall ++NumFileCacheMisses;
226b3144145SAlex Suhan auto *NamedFileEnt = &*SeenFileInsertResult.first;
227b3144145SAlex Suhan assert(!NamedFileEnt->second && "should be newly-created");
228fa361206SSam McCall
2297a51313dSChris Lattner // Get the null-terminated file name as stored as the key of the
230e1dd3e2cSZhanyong Wan // SeenFileEntries map.
231b3144145SAlex Suhan StringRef InterndFileName = NamedFileEnt->first();
2327a51313dSChris Lattner
233966b25b9SChris Lattner // Look up the directory for the file. When looking up something like
234966b25b9SChris Lattner // sys/foo.h we'll discover all of the search directories that have a 'sys'
235966b25b9SChris Lattner // subdirectory. This will let us avoid having to waste time on known-to-fail
236966b25b9SChris Lattner // searches when we go to find sys/bar.h, because all the search directories
237966b25b9SChris Lattner // without a 'sys' subdir will get a cached failure result.
238461f0722SHarlan Haskins auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
239461f0722SHarlan Haskins if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
2401b042de5SDuncan P. N. Exon Smith std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
241461f0722SHarlan Haskins if (CacheFailure)
2421b042de5SDuncan P. N. Exon Smith NamedFileEnt->second = Err;
243461f0722SHarlan Haskins else
2441735f4e7SDouglas Gregor SeenFileEntries.erase(Filename);
2451735f4e7SDouglas Gregor
2461b042de5SDuncan P. N. Exon Smith return llvm::errorCodeToError(Err);
2471735f4e7SDouglas Gregor }
2481b042de5SDuncan P. N. Exon Smith DirectoryEntryRef DirInfo = *DirInfoOrErr;
249407e2124SDouglas Gregor
2507a51313dSChris Lattner // FIXME: Use the directory info to prune this, before doing the stat syscall.
2517a51313dSChris Lattner // FIXME: This will reduce the # syscalls.
2527a51313dSChris Lattner
253018ab5faSRichard Smith // Check to see if the file exists.
254fc51490bSJonas Devlieghere std::unique_ptr<llvm::vfs::File> F;
25506f64d53SHarlan Haskins llvm::vfs::Status Status;
256461f0722SHarlan Haskins auto statError = getStatValue(InterndFileName, Status, true,
257461f0722SHarlan Haskins openFile ? &F : nullptr);
258461f0722SHarlan Haskins if (statError) {
259e1dd3e2cSZhanyong Wan // There's no real file at the given path.
260461f0722SHarlan Haskins if (CacheFailure)
261b3144145SAlex Suhan NamedFileEnt->second = statError;
262461f0722SHarlan Haskins else
2631735f4e7SDouglas Gregor SeenFileEntries.erase(Filename);
2641735f4e7SDouglas Gregor
2659ef6c49bSDuncan P. N. Exon Smith return llvm::errorCodeToError(statError);
266e1dd3e2cSZhanyong Wan }
2677a51313dSChris Lattner
268ab01d4bbSPatrik Hagglund assert((openFile || !F) && "undesired open file");
269d6278e32SArgyrios Kyrtzidis
2707a51313dSChris Lattner // It exists. See if we have already opened a file with the same inode.
2717a51313dSChris Lattner // This occurs when one dir is symlinked to another, for example.
272cf1c5507SSam McCall FileEntry *&UFE = UniqueRealFiles[Status.getUniqueID()];
273cf1c5507SSam McCall bool ReusingEntry = UFE != nullptr;
274cf1c5507SSam McCall if (!UFE)
275cf1c5507SSam McCall UFE = new (FilesAlloc.Allocate()) FileEntry();
2767a51313dSChris Lattner
277917acac9SDuncan P. N. Exon Smith if (Status.getName() == Filename) {
278917acac9SDuncan P. N. Exon Smith // The name matches. Set the FileEntry.
279cf1c5507SSam McCall NamedFileEnt->second = FileEntryRef::MapValue(*UFE, DirInfo);
280917acac9SDuncan P. N. Exon Smith } else {
281f65b0b5dSBen Barham // Name mismatch. We need a redirect. First grab the actual entry we want
282f65b0b5dSBen Barham // to return.
2838976a1e1SDuncan P. N. Exon Smith //
2848976a1e1SDuncan P. N. Exon Smith // This redirection logic intentionally leaks the external name of a
2858976a1e1SDuncan P. N. Exon Smith // redirected file that uses 'use-external-name' in \a
2868976a1e1SDuncan P. N. Exon Smith // vfs::RedirectionFileSystem. This allows clang to report the external
2878976a1e1SDuncan P. N. Exon Smith // name to users (in diagnostics) and to tools that don't have access to
2888976a1e1SDuncan P. N. Exon Smith // the VFS (in debug info and dependency '.d' files).
2898976a1e1SDuncan P. N. Exon Smith //
290*fe2478d4SBen Barham // FIXME: This is pretty complex and has some very complicated interactions
291*fe2478d4SBen Barham // with the rest of clang. It's also inconsistent with how "real"
292*fe2478d4SBen Barham // filesystems behave and confuses parts of clang expect to see the
293*fe2478d4SBen Barham // name-as-accessed on the \a FileEntryRef.
294*fe2478d4SBen Barham //
295*fe2478d4SBen Barham // Further, it isn't *just* external names, but will also give back absolute
296*fe2478d4SBen Barham // paths when a relative path was requested - the check is comparing the
297*fe2478d4SBen Barham // name from the status, which is passed an absolute path resolved from the
298*fe2478d4SBen Barham // current working directory. `clang-apply-replacements` appears to depend
299*fe2478d4SBen Barham // on this behaviour, though it's adjusting the working directory, which is
300*fe2478d4SBen Barham // definitely not supported. Once that's fixed this hack should be able to
301*fe2478d4SBen Barham // be narrowed to only when there's an externally mapped name given back.
302*fe2478d4SBen Barham //
303*fe2478d4SBen Barham // A potential plan to remove this is as follows -
304*fe2478d4SBen Barham // - Add API to determine if the name has been rewritten by the VFS.
305*fe2478d4SBen Barham // - Fix `clang-apply-replacements` to pass down the absolute path rather
306*fe2478d4SBen Barham // than changing the CWD. Narrow this hack down to just externally
307*fe2478d4SBen Barham // mapped paths.
308*fe2478d4SBen Barham // - Expose the requested filename. One possibility would be to allow
309*fe2478d4SBen Barham // redirection-FileEntryRefs to be returned, rather than returning
310*fe2478d4SBen Barham // the pointed-at-FileEntryRef, and customizing `getName()` to look
311*fe2478d4SBen Barham // through the indirection.
312*fe2478d4SBen Barham // - Update callers such as `HeaderSearch::findUsableModuleForHeader()`
313*fe2478d4SBen Barham // to explicitly use the requested filename rather than just using
314*fe2478d4SBen Barham // `getName()`.
315*fe2478d4SBen Barham // - Add a `FileManager::getExternalPath` API for explicitly getting the
316*fe2478d4SBen Barham // remapped external filename when there is one available. Adopt it in
317*fe2478d4SBen Barham // callers like diagnostics/deps reporting instead of calling
318*fe2478d4SBen Barham // `getName()` directly.
319*fe2478d4SBen Barham // - Switch the meaning of `FileEntryRef::getName()` to get the requested
320*fe2478d4SBen Barham // name, not the external name. Once that sticks, revert callers that
321*fe2478d4SBen Barham // want the requested name back to calling `getName()`.
322*fe2478d4SBen Barham // - Update the VFS to always return the requested name. This could also
323*fe2478d4SBen Barham // return the external name, or just have an API to request it
324*fe2478d4SBen Barham // lazily. The latter has the benefit of making accesses of the
325*fe2478d4SBen Barham // external path easily tracked, but may also require extra work than
326*fe2478d4SBen Barham // just returning up front.
327*fe2478d4SBen Barham // - (Optionally) Add an API to VFS to get the external filename lazily
328*fe2478d4SBen Barham // and update `FileManager::getExternalPath()` to use it instead. This
329*fe2478d4SBen Barham // has the benefit of making such accesses easily tracked, though isn't
330*fe2478d4SBen Barham // necessarily required (and could cause extra work than just adding to
331*fe2478d4SBen Barham // eg. `vfs::Status` up front).
332917acac9SDuncan P. N. Exon Smith auto &Redirection =
3331b042de5SDuncan P. N. Exon Smith *SeenFileEntries
334cf1c5507SSam McCall .insert({Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)})
335917acac9SDuncan P. N. Exon Smith .first;
336917acac9SDuncan P. N. Exon Smith assert(Redirection.second->V.is<FileEntry *>() &&
337917acac9SDuncan P. N. Exon Smith "filename redirected to a non-canonical filename?");
338cf1c5507SSam McCall assert(Redirection.second->V.get<FileEntry *>() == UFE &&
339ab86fbe4SBen Langmuir "filename from getStatValue() refers to wrong file");
340917acac9SDuncan P. N. Exon Smith
341917acac9SDuncan P. N. Exon Smith // Cache the redirection in the previously-inserted entry, still available
342917acac9SDuncan P. N. Exon Smith // in the tentative return value.
343917acac9SDuncan P. N. Exon Smith NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
344917acac9SDuncan P. N. Exon Smith
345917acac9SDuncan P. N. Exon Smith // Fix the tentative return value.
346917acac9SDuncan P. N. Exon Smith NamedFileEnt = &Redirection;
347ab86fbe4SBen Langmuir }
348ab86fbe4SBen Langmuir
349917acac9SDuncan P. N. Exon Smith FileEntryRef ReturnedRef(*NamedFileEnt);
350cf1c5507SSam McCall if (ReusingEntry) { // Already have an entry with this inode, return it.
3515de00f3bSBen Langmuir
352*fe2478d4SBen Barham // FIXME: This hack ensures that `getDir()` will use the path that was
353*fe2478d4SBen Barham // used to lookup this file, even if we found a file by different path
354*fe2478d4SBen Barham // first. This is required in order to find a module's structure when its
355*fe2478d4SBen Barham // headers/module map are mapped in the VFS.
356*fe2478d4SBen Barham //
357*fe2478d4SBen Barham // See above for how this will eventually be removed. `IsVFSMapped`
358*fe2478d4SBen Barham // *cannot* be narrowed to `ExposesExternalVFSPath` as crash reproducers
359*fe2478d4SBen Barham // also depend on this logic and they have `use-external-paths: false`.
360f65b0b5dSBen Barham if (&DirInfo.getDirEntry() != UFE->Dir && Status.IsVFSMapped)
361cf1c5507SSam McCall UFE->Dir = &DirInfo.getDirEntry();
3625de00f3bSBen Langmuir
363917acac9SDuncan P. N. Exon Smith // Always update LastRef to the last name by which a file was accessed.
364917acac9SDuncan P. N. Exon Smith // FIXME: Neither this nor always using the first reference is correct; we
365917acac9SDuncan P. N. Exon Smith // want to switch towards a design where we return a FileName object that
366c0ff9908SManuel Klimek // encapsulates both the name by which the file was accessed and the
367c0ff9908SManuel Klimek // corresponding FileEntry.
368917acac9SDuncan P. N. Exon Smith // FIXME: LastRef should be removed from FileEntry once all clients adopt
369917acac9SDuncan P. N. Exon Smith // FileEntryRef.
370cf1c5507SSam McCall UFE->LastRef = ReturnedRef;
371c0ff9908SManuel Klimek
372917acac9SDuncan P. N. Exon Smith return ReturnedRef;
373dd278430SChris Lattner }
3747a51313dSChris Lattner
375c9b7234eSBen Langmuir // Otherwise, we don't have this file yet, add it.
376cf1c5507SSam McCall UFE->LastRef = ReturnedRef;
377cf1c5507SSam McCall UFE->Size = Status.getSize();
378cf1c5507SSam McCall UFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
379cf1c5507SSam McCall UFE->Dir = &DirInfo.getDirEntry();
380cf1c5507SSam McCall UFE->UID = NextFileUID++;
381cf1c5507SSam McCall UFE->UniqueID = Status.getUniqueID();
382cf1c5507SSam McCall UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
383cf1c5507SSam McCall UFE->File = std::move(F);
384ddbabc6bSSimon Marchi
385cf1c5507SSam McCall if (UFE->File) {
386cf1c5507SSam McCall if (auto PathName = UFE->File->getName())
387cf1c5507SSam McCall fillRealPathName(UFE, *PathName);
388cd8607dbSJan Korous } else if (!openFile) {
389cd8607dbSJan Korous // We should still fill the path even if we aren't opening the file.
390cf1c5507SSam McCall fillRealPathName(UFE, InterndFileName);
391fa361206SSam McCall }
392917acac9SDuncan P. N. Exon Smith return ReturnedRef;
3937a51313dSChris Lattner }
3947a51313dSChris Lattner
getSTDIN()3953ee43adfSDuncan P. N. Exon Smith llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
3963ee43adfSDuncan P. N. Exon Smith // Only read stdin once.
3973ee43adfSDuncan P. N. Exon Smith if (STDIN)
3983ee43adfSDuncan P. N. Exon Smith return *STDIN;
3993ee43adfSDuncan P. N. Exon Smith
4003ee43adfSDuncan P. N. Exon Smith std::unique_ptr<llvm::MemoryBuffer> Content;
4013ee43adfSDuncan P. N. Exon Smith if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
4023ee43adfSDuncan P. N. Exon Smith Content = std::move(*ContentOrError);
4033ee43adfSDuncan P. N. Exon Smith else
4043ee43adfSDuncan P. N. Exon Smith return llvm::errorCodeToError(ContentOrError.getError());
4053ee43adfSDuncan P. N. Exon Smith
4063ee43adfSDuncan P. N. Exon Smith STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
4073ee43adfSDuncan P. N. Exon Smith Content->getBufferSize(), 0);
4083ee43adfSDuncan P. N. Exon Smith FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
4093ee43adfSDuncan P. N. Exon Smith FE.Content = std::move(Content);
4103ee43adfSDuncan P. N. Exon Smith FE.IsNamedPipe = true;
4113ee43adfSDuncan P. N. Exon Smith return *STDIN;
4123ee43adfSDuncan P. N. Exon Smith }
4133ee43adfSDuncan P. N. Exon Smith
getVirtualFile(StringRef Filename,off_t Size,time_t ModificationTime)414ac40a2d8SDuncan P. N. Exon Smith const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
415ac40a2d8SDuncan P. N. Exon Smith time_t ModificationTime) {
416ac40a2d8SDuncan P. N. Exon Smith return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
417ac40a2d8SDuncan P. N. Exon Smith }
418ac40a2d8SDuncan P. N. Exon Smith
getVirtualFileRef(StringRef Filename,off_t Size,time_t ModificationTime)419ac40a2d8SDuncan P. N. Exon Smith FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
4205159f616SChris Lattner time_t ModificationTime) {
421407e2124SDouglas Gregor ++NumFileLookups;
422407e2124SDouglas Gregor
423018ab5faSRichard Smith // See if there is already an entry in the map for an existing file.
424461f0722SHarlan Haskins auto &NamedFileEnt = *SeenFileEntries.insert(
425461f0722SHarlan Haskins {Filename, std::errc::no_such_file_or_directory}).first;
4264dc5573aSAlex Lorenz if (NamedFileEnt.second) {
427917acac9SDuncan P. N. Exon Smith FileEntryRef::MapValue Value = *NamedFileEnt.second;
428ac40a2d8SDuncan P. N. Exon Smith if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
429ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(NamedFileEnt);
430ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
431ac40a2d8SDuncan P. N. Exon Smith Value.V.get<const void *>()));
4324dc5573aSAlex Lorenz }
433407e2124SDouglas Gregor
434018ab5faSRichard Smith // We've not seen this before, or the file is cached as non-existent.
435407e2124SDouglas Gregor ++NumFileCacheMisses;
436e1dd3e2cSZhanyong Wan addAncestorsAsVirtualDirs(Filename);
437f1186c5aSCraig Topper FileEntry *UFE = nullptr;
438e1dd3e2cSZhanyong Wan
439e1dd3e2cSZhanyong Wan // Now that all ancestors of Filename are in the cache, the
440e1dd3e2cSZhanyong Wan // following call is guaranteed to find the DirectoryEntry from the
441c1554f32SAlex Lorenz // cache. A virtual file can also have an empty filename, that could come
442c1554f32SAlex Lorenz // from a source location preprocessor directive with an empty filename as
443c1554f32SAlex Lorenz // an example, so we need to pretend it has a name to ensure a valid directory
444c1554f32SAlex Lorenz // entry can be returned.
445c1554f32SAlex Lorenz auto DirInfo = expectedToOptional(getDirectoryFromFile(
446c1554f32SAlex Lorenz *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true));
447e1dd3e2cSZhanyong Wan assert(DirInfo &&
448e1dd3e2cSZhanyong Wan "The directory of a virtual file should already be in the cache.");
449e1dd3e2cSZhanyong Wan
450606c4ac3SDouglas Gregor // Check to see if the file exists. If so, drop the virtual file
45106f64d53SHarlan Haskins llvm::vfs::Status Status;
45213156b68SDavid Blaikie const char *InterndFileName = NamedFileEnt.first().data();
453461f0722SHarlan Haskins if (!getStatValue(InterndFileName, Status, true, nullptr)) {
45406f64d53SHarlan Haskins Status = llvm::vfs::Status(
45506f64d53SHarlan Haskins Status.getName(), Status.getUniqueID(),
45606f64d53SHarlan Haskins llvm::sys::toTimePoint(ModificationTime),
45706f64d53SHarlan Haskins Status.getUser(), Status.getGroup(), Size,
45806f64d53SHarlan Haskins Status.getType(), Status.getPermissions());
459606c4ac3SDouglas Gregor
460cf1c5507SSam McCall auto &RealFE = UniqueRealFiles[Status.getUniqueID()];
461cf1c5507SSam McCall if (RealFE) {
462606c4ac3SDouglas Gregor // If we had already opened this file, close it now so we don't
463606c4ac3SDouglas Gregor // leak the descriptor. We're not going to use the file
464606c4ac3SDouglas Gregor // descriptor anyway, since this is a virtual file.
465cf1c5507SSam McCall if (RealFE->File)
466cf1c5507SSam McCall RealFE->closeFile();
467606c4ac3SDouglas Gregor // If we already have an entry with this inode, return it.
468917acac9SDuncan P. N. Exon Smith //
469917acac9SDuncan P. N. Exon Smith // FIXME: Surely this should add a reference by the new name, and return
470917acac9SDuncan P. N. Exon Smith // it instead...
471cf1c5507SSam McCall NamedFileEnt.second = FileEntryRef::MapValue(*RealFE, *DirInfo);
472ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(NamedFileEnt);
473cf1c5507SSam McCall }
474cf1c5507SSam McCall // File exists, but no entry - create it.
475cf1c5507SSam McCall RealFE = new (FilesAlloc.Allocate()) FileEntry();
476cf1c5507SSam McCall RealFE->UniqueID = Status.getUniqueID();
477cf1c5507SSam McCall RealFE->IsNamedPipe =
478cf1c5507SSam McCall Status.getType() == llvm::sys::fs::file_type::fifo_file;
479cf1c5507SSam McCall fillRealPathName(RealFE, Status.getName());
480c9b7234eSBen Langmuir
481cf1c5507SSam McCall UFE = RealFE;
482018ab5faSRichard Smith } else {
483cf1c5507SSam McCall // File does not exist, create a virtual entry.
484cf1c5507SSam McCall UFE = new (FilesAlloc.Allocate()) FileEntry();
485cf1c5507SSam McCall VirtualFileEntries.push_back(UFE);
486606c4ac3SDouglas Gregor }
487407e2124SDouglas Gregor
488cf1c5507SSam McCall NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
489917acac9SDuncan P. N. Exon Smith UFE->LastRef = FileEntryRef(NamedFileEnt);
490407e2124SDouglas Gregor UFE->Size = Size;
491407e2124SDouglas Gregor UFE->ModTime = ModificationTime;
4921b042de5SDuncan P. N. Exon Smith UFE->Dir = &DirInfo->getDirEntry();
493407e2124SDouglas Gregor UFE->UID = NextFileUID++;
494c8130a74SBen Langmuir UFE->File.reset();
495ac40a2d8SDuncan P. N. Exon Smith return FileEntryRef(NamedFileEnt);
496407e2124SDouglas Gregor }
497407e2124SDouglas Gregor
getBypassFile(FileEntryRef VF)498e1b7f22bSDuncan P. N. Exon Smith llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
499e1b7f22bSDuncan P. N. Exon Smith // Stat of the file and return nullptr if it doesn't exist.
500e1b7f22bSDuncan P. N. Exon Smith llvm::vfs::Status Status;
501e1b7f22bSDuncan P. N. Exon Smith if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
502e1b7f22bSDuncan P. N. Exon Smith return None;
503e1b7f22bSDuncan P. N. Exon Smith
504917acac9SDuncan P. N. Exon Smith if (!SeenBypassFileEntries)
505917acac9SDuncan P. N. Exon Smith SeenBypassFileEntries = std::make_unique<
506917acac9SDuncan P. N. Exon Smith llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
507917acac9SDuncan P. N. Exon Smith
508917acac9SDuncan P. N. Exon Smith // If we've already bypassed just use the existing one.
509917acac9SDuncan P. N. Exon Smith auto Insertion = SeenBypassFileEntries->insert(
510917acac9SDuncan P. N. Exon Smith {VF.getName(), std::errc::no_such_file_or_directory});
511917acac9SDuncan P. N. Exon Smith if (!Insertion.second)
512917acac9SDuncan P. N. Exon Smith return FileEntryRef(*Insertion.first);
513917acac9SDuncan P. N. Exon Smith
514917acac9SDuncan P. N. Exon Smith // Fill in the new entry from the stat.
515cf1c5507SSam McCall FileEntry *BFE = new (FilesAlloc.Allocate()) FileEntry();
516cf1c5507SSam McCall BypassFileEntries.push_back(BFE);
517cf1c5507SSam McCall Insertion.first->second = FileEntryRef::MapValue(*BFE, VF.getDir());
518cf1c5507SSam McCall BFE->LastRef = FileEntryRef(*Insertion.first);
519cf1c5507SSam McCall BFE->Size = Status.getSize();
520cf1c5507SSam McCall BFE->Dir = VF.getFileEntry().Dir;
521cf1c5507SSam McCall BFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
522cf1c5507SSam McCall BFE->UID = NextFileUID++;
523917acac9SDuncan P. N. Exon Smith
524917acac9SDuncan P. N. Exon Smith // Save the entry in the bypass table and return.
525917acac9SDuncan P. N. Exon Smith return FileEntryRef(*Insertion.first);
526e1b7f22bSDuncan P. N. Exon Smith }
527e1b7f22bSDuncan P. N. Exon Smith
FixupRelativePath(SmallVectorImpl<char> & path) const528c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
5290e62c1ccSChris Lattner StringRef pathRef(path.data(), path.size());
530b5c356a4SAnders Carlsson
5319ba8fb1eSAnders Carlsson if (FileSystemOpts.WorkingDir.empty()
5329ba8fb1eSAnders Carlsson || llvm::sys::path::is_absolute(pathRef))
533c56419edSArgyrios Kyrtzidis return false;
53471731d6bSArgyrios Kyrtzidis
5352c1dd271SDylan Noblesmith SmallString<128> NewPath(FileSystemOpts.WorkingDir);
536b5c356a4SAnders Carlsson llvm::sys::path::append(NewPath, pathRef);
5376e640998SChris Lattner path = NewPath;
538c56419edSArgyrios Kyrtzidis return true;
539c56419edSArgyrios Kyrtzidis }
540c56419edSArgyrios Kyrtzidis
makeAbsolutePath(SmallVectorImpl<char> & Path) const541c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
542c56419edSArgyrios Kyrtzidis bool Changed = FixupRelativePath(Path);
543c56419edSArgyrios Kyrtzidis
544c56419edSArgyrios Kyrtzidis if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
54547035c02SIlya Biryukov FS->makeAbsolute(Path);
546c56419edSArgyrios Kyrtzidis Changed = true;
547c56419edSArgyrios Kyrtzidis }
548c56419edSArgyrios Kyrtzidis
549c56419edSArgyrios Kyrtzidis return Changed;
5506e640998SChris Lattner }
5516e640998SChris Lattner
fillRealPathName(FileEntry * UFE,llvm::StringRef FileName)552e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
553e9870c0cSKadir Cetinkaya llvm::SmallString<128> AbsPath(FileName);
554e9870c0cSKadir Cetinkaya // This is not the same as `VFS::getRealPath()`, which resolves symlinks
555e9870c0cSKadir Cetinkaya // but can be very expensive on real file systems.
556e9870c0cSKadir Cetinkaya // FIXME: the semantic of RealPathName is unclear, and the name might be
557e9870c0cSKadir Cetinkaya // misleading. We need to clean up the interface here.
558e9870c0cSKadir Cetinkaya makeAbsolutePath(AbsPath);
559e9870c0cSKadir Cetinkaya llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
560adcd0268SBenjamin Kramer UFE->RealPathName = std::string(AbsPath.str());
561e9870c0cSKadir Cetinkaya }
562e9870c0cSKadir Cetinkaya
563a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBufferForFile(const FileEntry * Entry,bool isVolatile,bool RequiresNullTerminator)56492e8af0eSMichael Spencer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
56592e8af0eSMichael Spencer bool RequiresNullTerminator) {
5663ee43adfSDuncan P. N. Exon Smith // If the content is living on the file entry, return a reference to it.
5673ee43adfSDuncan P. N. Exon Smith if (Entry->Content)
5683ee43adfSDuncan P. N. Exon Smith return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
5693ee43adfSDuncan P. N. Exon Smith
5706d7833f1SArgyrios Kyrtzidis uint64_t FileSize = Entry->getSize();
5716d7833f1SArgyrios Kyrtzidis // If there's a high enough chance that the file have changed since we
5726d7833f1SArgyrios Kyrtzidis // got its size, force a stat before opening it.
573245218bbSDuncan P. N. Exon Smith if (isVolatile || Entry->isNamedPipe())
5746d7833f1SArgyrios Kyrtzidis FileSize = -1;
5756d7833f1SArgyrios Kyrtzidis
576004b9c7aSMehdi Amini StringRef Filename = Entry->getName();
5775ea7d07dSChris Lattner // If the file is already open, use the open file descriptor.
578c8130a74SBen Langmuir if (Entry->File) {
57992e8af0eSMichael Spencer auto Result = Entry->File->getBuffer(Filename, FileSize,
58092e8af0eSMichael Spencer RequiresNullTerminator, isVolatile);
581c8130a74SBen Langmuir Entry->closeFile();
5826406f7b8SRafael Espindola return Result;
5835ea7d07dSChris Lattner }
5846e640998SChris Lattner
5855ea7d07dSChris Lattner // Otherwise, open the file.
58692e8af0eSMichael Spencer return getBufferForFileImpl(Filename, FileSize, isVolatile,
58792e8af0eSMichael Spencer RequiresNullTerminator);
588894b8d1dSDuncan P. N. Exon Smith }
589669b0b15SArgyrios Kyrtzidis
590894b8d1dSDuncan P. N. Exon Smith llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBufferForFileImpl(StringRef Filename,int64_t FileSize,bool isVolatile,bool RequiresNullTerminator)591894b8d1dSDuncan P. N. Exon Smith FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
59292e8af0eSMichael Spencer bool isVolatile,
59392e8af0eSMichael Spencer bool RequiresNullTerminator) {
594a885796dSBenjamin Kramer if (FileSystemOpts.WorkingDir.empty())
59592e8af0eSMichael Spencer return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
59692e8af0eSMichael Spencer isVolatile);
5975ea7d07dSChris Lattner
598894b8d1dSDuncan P. N. Exon Smith SmallString<128> FilePath(Filename);
599878b3e2bSAnders Carlsson FixupRelativePath(FilePath);
60092e8af0eSMichael Spencer return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
60192e8af0eSMichael Spencer isVolatile);
60226b5c190SChris Lattner }
60326b5c190SChris Lattner
604e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path,
605e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible. This returns true
606e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns
607e1dd3e2cSZhanyong Wan /// false if it's an existent real file. If FileDescriptor is NULL,
608e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up.
609461f0722SHarlan Haskins std::error_code
getStatValue(StringRef Path,llvm::vfs::Status & Status,bool isFile,std::unique_ptr<llvm::vfs::File> * F)610461f0722SHarlan Haskins FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
611461f0722SHarlan Haskins bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
612226efd35SChris Lattner // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
613226efd35SChris Lattner // absolute!
6145769c3dfSChris Lattner if (FileSystemOpts.WorkingDir.empty())
615461f0722SHarlan Haskins return FileSystemStatCache::get(Path, Status, isFile, F,
616461f0722SHarlan Haskins StatCache.get(), *FS);
617226efd35SChris Lattner
6182c1dd271SDylan Noblesmith SmallString<128> FilePath(Path);
619878b3e2bSAnders Carlsson FixupRelativePath(FilePath);
62071731d6bSArgyrios Kyrtzidis
621461f0722SHarlan Haskins return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
622461f0722SHarlan Haskins StatCache.get(), *FS);
62371731d6bSArgyrios Kyrtzidis }
62471731d6bSArgyrios Kyrtzidis
625461f0722SHarlan Haskins std::error_code
getNoncachedStatValue(StringRef Path,llvm::vfs::Status & Result)626461f0722SHarlan Haskins FileManager::getNoncachedStatValue(StringRef Path,
627fc51490bSJonas Devlieghere llvm::vfs::Status &Result) {
6282c1dd271SDylan Noblesmith SmallString<128> FilePath(Path);
6295e368405SAnders Carlsson FixupRelativePath(FilePath);
6305e368405SAnders Carlsson
631fc51490bSJonas Devlieghere llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
632c8130a74SBen Langmuir if (!S)
633461f0722SHarlan Haskins return S.getError();
634c8130a74SBen Langmuir Result = *S;
635461f0722SHarlan Haskins return std::error_code();
6365e368405SAnders Carlsson }
6375e368405SAnders Carlsson
GetUniqueIDMapping(SmallVectorImpl<const FileEntry * > & UIDToFiles) const63809b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping(
6390e62c1ccSChris Lattner SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
64009b6989eSDouglas Gregor UIDToFiles.clear();
64109b6989eSDouglas Gregor UIDToFiles.resize(NextFileUID);
64209b6989eSDouglas Gregor
64309b6989eSDouglas Gregor // Map file entries
644917acac9SDuncan P. N. Exon Smith for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
645461f0722SHarlan Haskins llvm::BumpPtrAllocator>::const_iterator
6464dc5573aSAlex Lorenz FE = SeenFileEntries.begin(),
6474dc5573aSAlex Lorenz FEEnd = SeenFileEntries.end();
64809b6989eSDouglas Gregor FE != FEEnd; ++FE)
649917acac9SDuncan P. N. Exon Smith if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
650917acac9SDuncan P. N. Exon Smith if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
6514dc5573aSAlex Lorenz UIDToFiles[FE->getUID()] = FE;
652461f0722SHarlan Haskins }
65309b6989eSDouglas Gregor
65409b6989eSDouglas Gregor // Map virtual file entries
655d2725a31SDavid Blaikie for (const auto &VFE : VirtualFileEntries)
656cf1c5507SSam McCall UIDToFiles[VFE->getUID()] = VFE;
65709b6989eSDouglas Gregor }
658226efd35SChris Lattner
getCanonicalName(const DirectoryEntry * Dir)659e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
660e8efac4bSKarl-Johan Karlsson llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
661e8efac4bSKarl-Johan Karlsson = CanonicalNames.find(Dir);
662e8efac4bSKarl-Johan Karlsson if (Known != CanonicalNames.end())
663e00c8b20SDouglas Gregor return Known->second;
664e00c8b20SDouglas Gregor
665e00c8b20SDouglas Gregor StringRef CanonicalName(Dir->getName());
66654cc3c2fSRichard Smith
6675fb18fecSEric Liu SmallString<4096> CanonicalNameBuf;
6685fb18fecSEric Liu if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
6691def2579SDavid Blaikie CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
670e00c8b20SDouglas Gregor
671e8efac4bSKarl-Johan Karlsson CanonicalNames.insert({Dir, CanonicalName});
672e8efac4bSKarl-Johan Karlsson return CanonicalName;
673e8efac4bSKarl-Johan Karlsson }
674e8efac4bSKarl-Johan Karlsson
getCanonicalName(const FileEntry * File)675e8efac4bSKarl-Johan Karlsson StringRef FileManager::getCanonicalName(const FileEntry *File) {
676e8efac4bSKarl-Johan Karlsson llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
677e8efac4bSKarl-Johan Karlsson = CanonicalNames.find(File);
678e8efac4bSKarl-Johan Karlsson if (Known != CanonicalNames.end())
679e8efac4bSKarl-Johan Karlsson return Known->second;
680e8efac4bSKarl-Johan Karlsson
681e8efac4bSKarl-Johan Karlsson StringRef CanonicalName(File->getName());
682e8efac4bSKarl-Johan Karlsson
683e8efac4bSKarl-Johan Karlsson SmallString<4096> CanonicalNameBuf;
684e8efac4bSKarl-Johan Karlsson if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
6851def2579SDavid Blaikie CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
686e8efac4bSKarl-Johan Karlsson
687e8efac4bSKarl-Johan Karlsson CanonicalNames.insert({File, CanonicalName});
688e00c8b20SDouglas Gregor return CanonicalName;
689e00c8b20SDouglas Gregor }
690226efd35SChris Lattner
PrintStats() const6917a51313dSChris Lattner void FileManager::PrintStats() const {
69289b422c1SBenjamin Kramer llvm::errs() << "\n*** File Manager Stats:\n";
693e1dd3e2cSZhanyong Wan llvm::errs() << UniqueRealFiles.size() << " real files found, "
694e1dd3e2cSZhanyong Wan << UniqueRealDirs.size() << " real dirs found.\n";
695e1dd3e2cSZhanyong Wan llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
696e1dd3e2cSZhanyong Wan << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
69789b422c1SBenjamin Kramer llvm::errs() << NumDirLookups << " dir lookups, "
6987a51313dSChris Lattner << NumDirCacheMisses << " dir cache misses.\n";
69989b422c1SBenjamin Kramer llvm::errs() << NumFileLookups << " file lookups, "
7007a51313dSChris Lattner << NumFileCacheMisses << " file cache misses.\n";
7017a51313dSChris Lattner
70289b422c1SBenjamin Kramer //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
7037a51313dSChris Lattner }
704