xref: /src/contrib/llvm-project/clang/lib/Basic/FileManager.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1bca07a45SDimitry Andric //===--- FileManager.cpp - File System Probing and Caching ----------------===//
2ec2b103cSEd Schouten //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ec2b103cSEd Schouten //
7ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
8ec2b103cSEd Schouten //
9ec2b103cSEd Schouten //  This file implements the FileManager interface.
10ec2b103cSEd Schouten //
11ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
12ec2b103cSEd Schouten //
13ec2b103cSEd Schouten // TODO: This should index all interesting directories with dirent calls.
14ec2b103cSEd Schouten //  getdirentries ?
15ec2b103cSEd Schouten //  opendir/readdir_r/closedir ?
16ec2b103cSEd Schouten //
17ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
18ec2b103cSEd Schouten 
19ec2b103cSEd Schouten #include "clang/Basic/FileManager.h"
20bca07a45SDimitry Andric #include "clang/Basic/FileSystemStatCache.h"
2145b53394SDimitry Andric #include "llvm/ADT/STLExtras.h"
22519fc96cSDimitry Andric #include "llvm/ADT/SmallString.h"
23519fc96cSDimitry Andric #include "llvm/ADT/Statistic.h"
24519fc96cSDimitry Andric #include "llvm/Config/llvm-config.h"
25bca07a45SDimitry Andric #include "llvm/Support/FileSystem.h"
26bca07a45SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
27bca07a45SDimitry Andric #include "llvm/Support/Path.h"
28809500fcSDimitry Andric #include "llvm/Support/raw_ostream.h"
29bab175ecSDimitry Andric #include <algorithm>
30bab175ecSDimitry Andric #include <cassert>
31bab175ecSDimitry Andric #include <climits>
32bab175ecSDimitry Andric #include <cstdint>
33bab175ecSDimitry Andric #include <cstdlib>
34e3b55780SDimitry Andric #include <optional>
354c8b2481SRoman Divacky #include <string>
36bab175ecSDimitry Andric #include <utility>
37bca07a45SDimitry Andric 
38ec2b103cSEd Schouten using namespace clang;
39ec2b103cSEd Schouten 
40519fc96cSDimitry Andric #define DEBUG_TYPE "file-search"
41519fc96cSDimitry Andric 
42ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
43ec2b103cSEd Schouten // Common logic.
44ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
45ec2b103cSEd Schouten 
FileManager(const FileSystemOptions & FSO,IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)469f4dbff6SDimitry Andric FileManager::FileManager(const FileSystemOptions &FSO,
47676fbe81SDimitry Andric                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
487442d6faSDimitry Andric     : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
497442d6faSDimitry Andric       SeenFileEntries(64), NextFileUID(0) {
509f4dbff6SDimitry Andric   // If the caller doesn't provide a virtual file system, just grab the real
519f4dbff6SDimitry Andric   // file system.
527442d6faSDimitry Andric   if (!this->FS)
53676fbe81SDimitry Andric     this->FS = llvm::vfs::getRealFileSystem();
54ec2b103cSEd Schouten }
55ec2b103cSEd Schouten 
5645b53394SDimitry Andric FileManager::~FileManager() = default;
57ec2b103cSEd Schouten 
setStatCache(std::unique_ptr<FileSystemStatCache> statCache)58676fbe81SDimitry Andric void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
5973490b89SRoman Divacky   assert(statCache && "No stat cache provided?");
6006d4ba38SDimitry Andric   StatCache = std::move(statCache);
6173490b89SRoman Divacky }
6273490b89SRoman Divacky 
clearStatCache()63676fbe81SDimitry Andric void FileManager::clearStatCache() { StatCache.reset(); }
6456d91b49SDimitry Andric 
6548675466SDimitry Andric /// Retrieve the directory that the given file name resides in.
66bca07a45SDimitry Andric /// Filename can point to either a real file or a virtual file.
67b60736ecSDimitry Andric static llvm::Expected<DirectoryEntryRef>
getDirectoryFromFile(FileManager & FileMgr,StringRef Filename,bool CacheFailure)68519fc96cSDimitry Andric getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
6936981b17SDimitry Andric                      bool CacheFailure) {
70bca07a45SDimitry Andric   if (Filename.empty())
71b60736ecSDimitry Andric     return llvm::errorCodeToError(
72b60736ecSDimitry Andric         make_error_code(std::errc::no_such_file_or_directory));
7334d02d0bSRoman Divacky 
74bca07a45SDimitry Andric   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
75b60736ecSDimitry Andric     return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory));
76bca07a45SDimitry Andric 
7736981b17SDimitry Andric   StringRef DirName = llvm::sys::path::parent_path(Filename);
7834d02d0bSRoman Divacky   // Use the current directory if file has no path component.
79bca07a45SDimitry Andric   if (DirName.empty())
80bca07a45SDimitry Andric     DirName = ".";
81bca07a45SDimitry Andric 
82b60736ecSDimitry Andric   return FileMgr.getDirectoryRef(DirName, CacheFailure);
8334d02d0bSRoman Divacky }
8434d02d0bSRoman Divacky 
getRealDirEntry(const llvm::vfs::Status & Status)85ac9a064cSDimitry Andric DirectoryEntry *&FileManager::getRealDirEntry(const llvm::vfs::Status &Status) {
86ac9a064cSDimitry Andric   assert(Status.isDirectory() && "The directory should exist!");
87ac9a064cSDimitry Andric   // See if we have already opened a directory with the
88ac9a064cSDimitry Andric   // same inode (this occurs on Unix-like systems when one dir is
89ac9a064cSDimitry Andric   // symlinked to another, for example) or the same path (on
90ac9a064cSDimitry Andric   // Windows).
91ac9a064cSDimitry Andric   DirectoryEntry *&UDE = UniqueRealDirs[Status.getUniqueID()];
92ac9a064cSDimitry Andric 
93ac9a064cSDimitry Andric   if (!UDE) {
94ac9a064cSDimitry Andric     // We don't have this directory yet, add it.  We use the string
95ac9a064cSDimitry Andric     // key from the SeenDirEntries map as the string.
96ac9a064cSDimitry Andric     UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
97ac9a064cSDimitry Andric   }
98ac9a064cSDimitry Andric   return UDE;
99ac9a064cSDimitry Andric }
100ac9a064cSDimitry Andric 
101bca07a45SDimitry Andric /// Add all ancestors of the given path (pointing to either a file or
102bca07a45SDimitry Andric /// a directory) as virtual directories.
addAncestorsAsVirtualDirs(StringRef Path)10336981b17SDimitry Andric void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
10436981b17SDimitry Andric   StringRef DirName = llvm::sys::path::parent_path(Path);
105bca07a45SDimitry Andric   if (DirName.empty())
1062b6b257fSDimitry Andric     DirName = ".";
107bca07a45SDimitry Andric 
108519fc96cSDimitry Andric   auto &NamedDirEnt = *SeenDirEntries.insert(
109519fc96cSDimitry Andric         {DirName, std::errc::no_such_file_or_directory}).first;
110bca07a45SDimitry Andric 
111bca07a45SDimitry Andric   // When caching a virtual directory, we always cache its ancestors
112bca07a45SDimitry Andric   // at the same time.  Therefore, if DirName is already in the cache,
113bca07a45SDimitry Andric   // we don't need to recurse as its ancestors must also already be in
11422989816SDimitry Andric   // the cache (or it's a known non-virtual directory).
11522989816SDimitry Andric   if (NamedDirEnt.second)
116bca07a45SDimitry Andric     return;
117bca07a45SDimitry Andric 
118ac9a064cSDimitry Andric   // Check to see if the directory exists.
119ac9a064cSDimitry Andric   llvm::vfs::Status Status;
120ac9a064cSDimitry Andric   auto statError =
121ac9a064cSDimitry Andric       getStatValue(DirName, Status, false, nullptr /*directory lookup*/);
122ac9a064cSDimitry Andric   if (statError) {
123ac9a064cSDimitry Andric     // There's no real directory at the given path.
124bca07a45SDimitry Andric     // Add the virtual directory to the cache.
125145449b1SDimitry Andric     auto *UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
126145449b1SDimitry Andric     NamedDirEnt.second = *UDE;
127145449b1SDimitry Andric     VirtualDirectoryEntries.push_back(UDE);
128ac9a064cSDimitry Andric   } else {
129ac9a064cSDimitry Andric     // There is the real directory
130ac9a064cSDimitry Andric     DirectoryEntry *&UDE = getRealDirEntry(Status);
131ac9a064cSDimitry Andric     NamedDirEnt.second = *UDE;
132ac9a064cSDimitry Andric   }
133bca07a45SDimitry Andric 
134bca07a45SDimitry Andric   // Recursively add the other ancestors.
135bca07a45SDimitry Andric   addAncestorsAsVirtualDirs(DirName);
136bca07a45SDimitry Andric }
137bca07a45SDimitry Andric 
138519fc96cSDimitry Andric llvm::Expected<DirectoryEntryRef>
getDirectoryRef(StringRef DirName,bool CacheFailure)139519fc96cSDimitry Andric FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
14056d91b49SDimitry Andric   // stat doesn't like trailing separators except for root directory.
141dbe13110SDimitry Andric   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
142dbe13110SDimitry Andric   // (though it can strip '\\')
14356d91b49SDimitry Andric   if (DirName.size() > 1 &&
14456d91b49SDimitry Andric       DirName != llvm::sys::path::root_path(DirName) &&
14556d91b49SDimitry Andric       llvm::sys::path::is_separator(DirName.back()))
146dbe13110SDimitry Andric     DirName = DirName.substr(0, DirName.size()-1);
147e3b55780SDimitry Andric   std::optional<std::string> DirNameStr;
148c0981da4SDimitry Andric   if (is_style_windows(llvm::sys::path::Style::native)) {
149bfef3995SDimitry Andric     // Fixing a problem with "clang C:test.c" on Windows.
150bfef3995SDimitry Andric     // Stat("C:") does not recognize "C:" as a valid directory
151bfef3995SDimitry Andric     if (DirName.size() > 1 && DirName.back() == ':' &&
152344a3780SDimitry Andric         DirName.equals_insensitive(llvm::sys::path::root_name(DirName))) {
153bfef3995SDimitry Andric       DirNameStr = DirName.str() + '.';
154c0981da4SDimitry Andric       DirName = *DirNameStr;
155bfef3995SDimitry Andric     }
156c0981da4SDimitry Andric   }
157dbe13110SDimitry Andric 
158ec2b103cSEd Schouten   ++NumDirLookups;
159ec2b103cSEd Schouten 
160bca07a45SDimitry Andric   // See if there was already an entry in the map.  Note that the map
161bca07a45SDimitry Andric   // contains both virtual and real directories.
162519fc96cSDimitry Andric   auto SeenDirInsertResult =
163519fc96cSDimitry Andric       SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
164519fc96cSDimitry Andric   if (!SeenDirInsertResult.second) {
165519fc96cSDimitry Andric     if (SeenDirInsertResult.first->second)
166b60736ecSDimitry Andric       return DirectoryEntryRef(*SeenDirInsertResult.first);
167519fc96cSDimitry Andric     return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
168519fc96cSDimitry Andric   }
169ec2b103cSEd Schouten 
17022989816SDimitry Andric   // We've not seen this before. Fill it in.
171ec2b103cSEd Schouten   ++NumDirCacheMisses;
17222989816SDimitry Andric   auto &NamedDirEnt = *SeenDirInsertResult.first;
17322989816SDimitry Andric   assert(!NamedDirEnt.second && "should be newly-created");
174ec2b103cSEd Schouten 
175ec2b103cSEd Schouten   // Get the null-terminated directory name as stored as the key of the
176bca07a45SDimitry Andric   // SeenDirEntries map.
177bab175ecSDimitry Andric   StringRef InterndDirName = NamedDirEnt.first();
178ec2b103cSEd Schouten 
179ec2b103cSEd Schouten   // Check to see if the directory exists.
18022989816SDimitry Andric   llvm::vfs::Status Status;
181519fc96cSDimitry Andric   auto statError = getStatValue(InterndDirName, Status, false,
182519fc96cSDimitry Andric                                 nullptr /*directory lookup*/);
183519fc96cSDimitry Andric   if (statError) {
184bca07a45SDimitry Andric     // There's no real directory at the given path.
185519fc96cSDimitry Andric     if (CacheFailure)
186519fc96cSDimitry Andric       NamedDirEnt.second = statError;
187519fc96cSDimitry Andric     else
18836981b17SDimitry Andric       SeenDirEntries.erase(DirName);
189519fc96cSDimitry Andric     return llvm::errorCodeToError(statError);
190bca07a45SDimitry Andric   }
191ec2b103cSEd Schouten 
192ac9a064cSDimitry Andric   // It exists.
193ac9a064cSDimitry Andric   DirectoryEntry *&UDE = getRealDirEntry(Status);
194145449b1SDimitry Andric   NamedDirEnt.second = *UDE;
195bca07a45SDimitry Andric 
196b60736ecSDimitry Andric   return DirectoryEntryRef(NamedDirEnt);
197ec2b103cSEd Schouten }
198ec2b103cSEd Schouten 
199519fc96cSDimitry Andric llvm::ErrorOr<const DirectoryEntry *>
getDirectory(StringRef DirName,bool CacheFailure)200519fc96cSDimitry Andric FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
201519fc96cSDimitry Andric   auto Result = getDirectoryRef(DirName, CacheFailure);
202519fc96cSDimitry Andric   if (Result)
203519fc96cSDimitry Andric     return &Result->getDirEntry();
204519fc96cSDimitry Andric   return llvm::errorToErrorCode(Result.takeError());
205519fc96cSDimitry Andric }
206519fc96cSDimitry Andric 
207519fc96cSDimitry Andric llvm::ErrorOr<const FileEntry *>
getFile(StringRef Filename,bool openFile,bool CacheFailure)208519fc96cSDimitry Andric FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
209519fc96cSDimitry Andric   auto Result = getFileRef(Filename, openFile, CacheFailure);
210519fc96cSDimitry Andric   if (Result)
211519fc96cSDimitry Andric     return &Result->getFileEntry();
212519fc96cSDimitry Andric   return llvm::errorToErrorCode(Result.takeError());
213519fc96cSDimitry Andric }
214519fc96cSDimitry Andric 
215519fc96cSDimitry Andric llvm::Expected<FileEntryRef>
getFileRef(StringRef Filename,bool openFile,bool CacheFailure)216519fc96cSDimitry Andric FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
217ec2b103cSEd Schouten   ++NumFileLookups;
218ec2b103cSEd Schouten 
219ec2b103cSEd Schouten   // See if there is already an entry in the map.
220519fc96cSDimitry Andric   auto SeenFileInsertResult =
221519fc96cSDimitry Andric       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
222519fc96cSDimitry Andric   if (!SeenFileInsertResult.second) {
223519fc96cSDimitry Andric     if (!SeenFileInsertResult.first->second)
224519fc96cSDimitry Andric       return llvm::errorCodeToError(
225519fc96cSDimitry Andric           SeenFileInsertResult.first->second.getError());
226b60736ecSDimitry Andric     return FileEntryRef(*SeenFileInsertResult.first);
227519fc96cSDimitry Andric   }
228ec2b103cSEd Schouten 
22922989816SDimitry Andric   // We've not seen this before. Fill it in.
230676fbe81SDimitry Andric   ++NumFileCacheMisses;
231706b4fc4SDimitry Andric   auto *NamedFileEnt = &*SeenFileInsertResult.first;
232706b4fc4SDimitry Andric   assert(!NamedFileEnt->second && "should be newly-created");
233ec2b103cSEd Schouten 
234ec2b103cSEd Schouten   // Get the null-terminated file name as stored as the key of the
235bca07a45SDimitry Andric   // SeenFileEntries map.
236706b4fc4SDimitry Andric   StringRef InterndFileName = NamedFileEnt->first();
237ec2b103cSEd Schouten 
238bca07a45SDimitry Andric   // Look up the directory for the file.  When looking up something like
239bca07a45SDimitry Andric   // sys/foo.h we'll discover all of the search directories that have a 'sys'
240bca07a45SDimitry Andric   // subdirectory.  This will let us avoid having to waste time on known-to-fail
241bca07a45SDimitry Andric   // searches when we go to find sys/bar.h, because all the search directories
242bca07a45SDimitry Andric   // without a 'sys' subdir will get a cached failure result.
243519fc96cSDimitry Andric   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
244519fc96cSDimitry Andric   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
245b60736ecSDimitry Andric     std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
246519fc96cSDimitry Andric     if (CacheFailure)
247b60736ecSDimitry Andric       NamedFileEnt->second = Err;
248519fc96cSDimitry Andric     else
24936981b17SDimitry Andric       SeenFileEntries.erase(Filename);
25036981b17SDimitry Andric 
251b60736ecSDimitry Andric     return llvm::errorCodeToError(Err);
25236981b17SDimitry Andric   }
253b60736ecSDimitry Andric   DirectoryEntryRef DirInfo = *DirInfoOrErr;
25434d02d0bSRoman Divacky 
255ec2b103cSEd Schouten   // FIXME: Use the directory info to prune this, before doing the stat syscall.
256ec2b103cSEd Schouten   // FIXME: This will reduce the # syscalls.
257ec2b103cSEd Schouten 
25822989816SDimitry Andric   // Check to see if the file exists.
259676fbe81SDimitry Andric   std::unique_ptr<llvm::vfs::File> F;
26022989816SDimitry Andric   llvm::vfs::Status Status;
261519fc96cSDimitry Andric   auto statError = getStatValue(InterndFileName, Status, true,
262519fc96cSDimitry Andric                                 openFile ? &F : nullptr);
263519fc96cSDimitry Andric   if (statError) {
264bca07a45SDimitry Andric     // There's no real file at the given path.
265519fc96cSDimitry Andric     if (CacheFailure)
266706b4fc4SDimitry Andric       NamedFileEnt->second = statError;
267519fc96cSDimitry Andric     else
26836981b17SDimitry Andric       SeenFileEntries.erase(Filename);
26936981b17SDimitry Andric 
270519fc96cSDimitry Andric     return llvm::errorCodeToError(statError);
271ec2b103cSEd Schouten   }
272ec2b103cSEd Schouten 
2739f4dbff6SDimitry Andric   assert((openFile || !F) && "undesired open file");
27401af97d3SDimitry Andric 
275ec2b103cSEd Schouten   // It exists.  See if we have already opened a file with the same inode.
276ec2b103cSEd Schouten   // This occurs when one dir is symlinked to another, for example.
277145449b1SDimitry Andric   FileEntry *&UFE = UniqueRealFiles[Status.getUniqueID()];
278145449b1SDimitry Andric   bool ReusingEntry = UFE != nullptr;
279145449b1SDimitry Andric   if (!UFE)
280145449b1SDimitry Andric     UFE = new (FilesAlloc.Allocate()) FileEntry();
281ec2b103cSEd Schouten 
282e3b55780SDimitry Andric   if (!Status.ExposesExternalVFSPath || Status.getName() == Filename) {
283e3b55780SDimitry Andric     // Use the requested name. Set the FileEntry.
284145449b1SDimitry Andric     NamedFileEnt->second = FileEntryRef::MapValue(*UFE, DirInfo);
285b60736ecSDimitry Andric   } else {
286b60736ecSDimitry Andric     // Name mismatch. We need a redirect. First grab the actual entry we want
287b60736ecSDimitry Andric     // to return.
288c0981da4SDimitry Andric     //
289c0981da4SDimitry Andric     // This redirection logic intentionally leaks the external name of a
290c0981da4SDimitry Andric     // redirected file that uses 'use-external-name' in \a
291c0981da4SDimitry Andric     // vfs::RedirectionFileSystem. This allows clang to report the external
292c0981da4SDimitry Andric     // name to users (in diagnostics) and to tools that don't have access to
293c0981da4SDimitry Andric     // the VFS (in debug info and dependency '.d' files).
294c0981da4SDimitry Andric     //
295145449b1SDimitry Andric     // FIXME: This is pretty complex and has some very complicated interactions
296145449b1SDimitry Andric     // with the rest of clang. It's also inconsistent with how "real"
297145449b1SDimitry Andric     // filesystems behave and confuses parts of clang expect to see the
298145449b1SDimitry Andric     // name-as-accessed on the \a FileEntryRef.
299145449b1SDimitry Andric     //
300145449b1SDimitry Andric     // A potential plan to remove this is as follows -
301145449b1SDimitry Andric     //   - Update callers such as `HeaderSearch::findUsableModuleForHeader()`
302e3b55780SDimitry Andric     //     to explicitly use the `getNameAsRequested()` rather than just using
303145449b1SDimitry Andric     //     `getName()`.
304145449b1SDimitry Andric     //   - Add a `FileManager::getExternalPath` API for explicitly getting the
305145449b1SDimitry Andric     //     remapped external filename when there is one available. Adopt it in
306145449b1SDimitry Andric     //     callers like diagnostics/deps reporting instead of calling
307145449b1SDimitry Andric     //     `getName()` directly.
308145449b1SDimitry Andric     //   - Switch the meaning of `FileEntryRef::getName()` to get the requested
309145449b1SDimitry Andric     //     name, not the external name. Once that sticks, revert callers that
310145449b1SDimitry Andric     //     want the requested name back to calling `getName()`.
311145449b1SDimitry Andric     //   - Update the VFS to always return the requested name. This could also
312145449b1SDimitry Andric     //     return the external name, or just have an API to request it
313145449b1SDimitry Andric     //     lazily. The latter has the benefit of making accesses of the
314145449b1SDimitry Andric     //     external path easily tracked, but may also require extra work than
315145449b1SDimitry Andric     //     just returning up front.
316145449b1SDimitry Andric     //   - (Optionally) Add an API to VFS to get the external filename lazily
317145449b1SDimitry Andric     //     and update `FileManager::getExternalPath()` to use it instead. This
318145449b1SDimitry Andric     //     has the benefit of making such accesses easily tracked, though isn't
319145449b1SDimitry Andric     //     necessarily required (and could cause extra work than just adding to
320145449b1SDimitry Andric     //     eg. `vfs::Status` up front).
321b60736ecSDimitry Andric     auto &Redirection =
322b60736ecSDimitry Andric         *SeenFileEntries
323145449b1SDimitry Andric              .insert({Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)})
324b60736ecSDimitry Andric              .first;
325b60736ecSDimitry Andric     assert(Redirection.second->V.is<FileEntry *>() &&
326b60736ecSDimitry Andric            "filename redirected to a non-canonical filename?");
327145449b1SDimitry Andric     assert(Redirection.second->V.get<FileEntry *>() == UFE &&
32806d4ba38SDimitry Andric            "filename from getStatValue() refers to wrong file");
329b60736ecSDimitry Andric 
330b60736ecSDimitry Andric     // Cache the redirection in the previously-inserted entry, still available
331b60736ecSDimitry Andric     // in the tentative return value.
3327fa27ce4SDimitry Andric     NamedFileEnt->second = FileEntryRef::MapValue(Redirection, DirInfo);
33306d4ba38SDimitry Andric   }
33406d4ba38SDimitry Andric 
335b60736ecSDimitry Andric   FileEntryRef ReturnedRef(*NamedFileEnt);
336145449b1SDimitry Andric   if (ReusingEntry) { // Already have an entry with this inode, return it.
337b60736ecSDimitry Andric     return ReturnedRef;
338bca07a45SDimitry Andric   }
339ec2b103cSEd Schouten 
3409f4dbff6SDimitry Andric   // Otherwise, we don't have this file yet, add it.
341145449b1SDimitry Andric   UFE->Size = Status.getSize();
342145449b1SDimitry Andric   UFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
343145449b1SDimitry Andric   UFE->Dir = &DirInfo.getDirEntry();
344145449b1SDimitry Andric   UFE->UID = NextFileUID++;
345145449b1SDimitry Andric   UFE->UniqueID = Status.getUniqueID();
346145449b1SDimitry Andric   UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
347145449b1SDimitry Andric   UFE->File = std::move(F);
348676fbe81SDimitry Andric 
349145449b1SDimitry Andric   if (UFE->File) {
350145449b1SDimitry Andric     if (auto PathName = UFE->File->getName())
351145449b1SDimitry Andric       fillRealPathName(UFE, *PathName);
35222989816SDimitry Andric   } else if (!openFile) {
35322989816SDimitry Andric     // We should still fill the path even if we aren't opening the file.
354145449b1SDimitry Andric     fillRealPathName(UFE, InterndFileName);
35522989816SDimitry Andric   }
356b60736ecSDimitry Andric   return ReturnedRef;
357ec2b103cSEd Schouten }
358ec2b103cSEd Schouten 
getSTDIN()359b60736ecSDimitry Andric llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
360b60736ecSDimitry Andric   // Only read stdin once.
361b60736ecSDimitry Andric   if (STDIN)
362b60736ecSDimitry Andric     return *STDIN;
363b60736ecSDimitry Andric 
364b60736ecSDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> Content;
365b60736ecSDimitry Andric   if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
366b60736ecSDimitry Andric     Content = std::move(*ContentOrError);
367b60736ecSDimitry Andric   else
368b60736ecSDimitry Andric     return llvm::errorCodeToError(ContentOrError.getError());
369b60736ecSDimitry Andric 
370b60736ecSDimitry Andric   STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
371b60736ecSDimitry Andric                             Content->getBufferSize(), 0);
372b60736ecSDimitry Andric   FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
373b60736ecSDimitry Andric   FE.Content = std::move(Content);
374b60736ecSDimitry Andric   FE.IsNamedPipe = true;
375b60736ecSDimitry Andric   return *STDIN;
376b60736ecSDimitry Andric }
377b60736ecSDimitry Andric 
trackVFSUsage(bool Active)378ac9a064cSDimitry Andric void FileManager::trackVFSUsage(bool Active) {
379ac9a064cSDimitry Andric   FS->visit([Active](llvm::vfs::FileSystem &FileSys) {
380ac9a064cSDimitry Andric     if (auto *RFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&FileSys))
381ac9a064cSDimitry Andric       RFS->setUsageTrackingActive(Active);
382ac9a064cSDimitry Andric   });
383ac9a064cSDimitry Andric }
384ac9a064cSDimitry Andric 
getVirtualFile(StringRef Filename,off_t Size,time_t ModificationTime)385b60736ecSDimitry Andric const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
386b60736ecSDimitry Andric                                              time_t ModificationTime) {
387b60736ecSDimitry Andric   return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
388b60736ecSDimitry Andric }
389b60736ecSDimitry Andric 
getVirtualFileRef(StringRef Filename,off_t Size,time_t ModificationTime)390b60736ecSDimitry Andric FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
3914e58654bSRoman Divacky                                             time_t ModificationTime) {
39234d02d0bSRoman Divacky   ++NumFileLookups;
39334d02d0bSRoman Divacky 
39422989816SDimitry Andric   // See if there is already an entry in the map for an existing file.
395519fc96cSDimitry Andric   auto &NamedFileEnt = *SeenFileEntries.insert(
396519fc96cSDimitry Andric       {Filename, std::errc::no_such_file_or_directory}).first;
397519fc96cSDimitry Andric   if (NamedFileEnt.second) {
398b60736ecSDimitry Andric     FileEntryRef::MapValue Value = *NamedFileEnt.second;
399b60736ecSDimitry Andric     if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
400b60736ecSDimitry Andric       return FileEntryRef(NamedFileEnt);
4017fa27ce4SDimitry Andric     return FileEntryRef(*Value.V.get<const FileEntryRef::MapEntry *>());
402519fc96cSDimitry Andric   }
40334d02d0bSRoman Divacky 
40422989816SDimitry Andric   // We've not seen this before, or the file is cached as non-existent.
40534d02d0bSRoman Divacky   ++NumFileCacheMisses;
406bca07a45SDimitry Andric   addAncestorsAsVirtualDirs(Filename);
4079f4dbff6SDimitry Andric   FileEntry *UFE = nullptr;
40834d02d0bSRoman Divacky 
409bca07a45SDimitry Andric   // Now that all ancestors of Filename are in the cache, the
410bca07a45SDimitry Andric   // following call is guaranteed to find the DirectoryEntry from the
411344a3780SDimitry Andric   // cache. A virtual file can also have an empty filename, that could come
412344a3780SDimitry Andric   // from a source location preprocessor directive with an empty filename as
413344a3780SDimitry Andric   // an example, so we need to pretend it has a name to ensure a valid directory
414344a3780SDimitry Andric   // entry can be returned.
415344a3780SDimitry Andric   auto DirInfo = expectedToOptional(getDirectoryFromFile(
416344a3780SDimitry Andric       *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true));
417bca07a45SDimitry Andric   assert(DirInfo &&
418bca07a45SDimitry Andric          "The directory of a virtual file should already be in the cache.");
419bca07a45SDimitry Andric 
420bca07a45SDimitry Andric   // Check to see if the file exists. If so, drop the virtual file
42122989816SDimitry Andric   llvm::vfs::Status Status;
42206d4ba38SDimitry Andric   const char *InterndFileName = NamedFileEnt.first().data();
423519fc96cSDimitry Andric   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
42422989816SDimitry Andric     Status = llvm::vfs::Status(
42522989816SDimitry Andric       Status.getName(), Status.getUniqueID(),
42622989816SDimitry Andric       llvm::sys::toTimePoint(ModificationTime),
42722989816SDimitry Andric       Status.getUser(), Status.getGroup(), Size,
42822989816SDimitry Andric       Status.getType(), Status.getPermissions());
429bca07a45SDimitry Andric 
430145449b1SDimitry Andric     auto &RealFE = UniqueRealFiles[Status.getUniqueID()];
431145449b1SDimitry Andric     if (RealFE) {
432bca07a45SDimitry Andric       // If we had already opened this file, close it now so we don't
433bca07a45SDimitry Andric       // leak the descriptor. We're not going to use the file
434bca07a45SDimitry Andric       // descriptor anyway, since this is a virtual file.
435145449b1SDimitry Andric       if (RealFE->File)
436145449b1SDimitry Andric         RealFE->closeFile();
437bca07a45SDimitry Andric       // If we already have an entry with this inode, return it.
438b60736ecSDimitry Andric       //
439b60736ecSDimitry Andric       // FIXME: Surely this should add a reference by the new name, and return
440b60736ecSDimitry Andric       // it instead...
441145449b1SDimitry Andric       NamedFileEnt.second = FileEntryRef::MapValue(*RealFE, *DirInfo);
442b60736ecSDimitry Andric       return FileEntryRef(NamedFileEnt);
443145449b1SDimitry Andric     }
444145449b1SDimitry Andric     // File exists, but no entry - create it.
445145449b1SDimitry Andric     RealFE = new (FilesAlloc.Allocate()) FileEntry();
446145449b1SDimitry Andric     RealFE->UniqueID = Status.getUniqueID();
447145449b1SDimitry Andric     RealFE->IsNamedPipe =
448145449b1SDimitry Andric         Status.getType() == llvm::sys::fs::file_type::fifo_file;
449145449b1SDimitry Andric     fillRealPathName(RealFE, Status.getName());
4509f4dbff6SDimitry Andric 
451145449b1SDimitry Andric     UFE = RealFE;
45222989816SDimitry Andric   } else {
453145449b1SDimitry Andric     // File does not exist, create a virtual entry.
454145449b1SDimitry Andric     UFE = new (FilesAlloc.Allocate()) FileEntry();
455145449b1SDimitry Andric     VirtualFileEntries.push_back(UFE);
456bca07a45SDimitry Andric   }
457bca07a45SDimitry Andric 
458145449b1SDimitry Andric   NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
45934d02d0bSRoman Divacky   UFE->Size    = Size;
46034d02d0bSRoman Divacky   UFE->ModTime = ModificationTime;
461b60736ecSDimitry Andric   UFE->Dir     = &DirInfo->getDirEntry();
46234d02d0bSRoman Divacky   UFE->UID     = NextFileUID++;
4639f4dbff6SDimitry Andric   UFE->File.reset();
464b60736ecSDimitry Andric   return FileEntryRef(NamedFileEnt);
46534d02d0bSRoman Divacky }
46634d02d0bSRoman Divacky 
getBypassFile(FileEntryRef VF)467e3b55780SDimitry Andric OptionalFileEntryRef FileManager::getBypassFile(FileEntryRef VF) {
468519fc96cSDimitry Andric   // Stat of the file and return nullptr if it doesn't exist.
469519fc96cSDimitry Andric   llvm::vfs::Status Status;
470519fc96cSDimitry Andric   if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
471e3b55780SDimitry Andric     return std::nullopt;
472519fc96cSDimitry Andric 
473b60736ecSDimitry Andric   if (!SeenBypassFileEntries)
474b60736ecSDimitry Andric     SeenBypassFileEntries = std::make_unique<
475b60736ecSDimitry Andric         llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
476b60736ecSDimitry Andric 
477b60736ecSDimitry Andric   // If we've already bypassed just use the existing one.
478b60736ecSDimitry Andric   auto Insertion = SeenBypassFileEntries->insert(
479b60736ecSDimitry Andric       {VF.getName(), std::errc::no_such_file_or_directory});
480b60736ecSDimitry Andric   if (!Insertion.second)
481b60736ecSDimitry Andric     return FileEntryRef(*Insertion.first);
482b60736ecSDimitry Andric 
483b60736ecSDimitry Andric   // Fill in the new entry from the stat.
484145449b1SDimitry Andric   FileEntry *BFE = new (FilesAlloc.Allocate()) FileEntry();
485145449b1SDimitry Andric   BypassFileEntries.push_back(BFE);
486145449b1SDimitry Andric   Insertion.first->second = FileEntryRef::MapValue(*BFE, VF.getDir());
487145449b1SDimitry Andric   BFE->Size = Status.getSize();
488145449b1SDimitry Andric   BFE->Dir = VF.getFileEntry().Dir;
489145449b1SDimitry Andric   BFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
490145449b1SDimitry Andric   BFE->UID = NextFileUID++;
491b60736ecSDimitry Andric 
492b60736ecSDimitry Andric   // Save the entry in the bypass table and return.
493b60736ecSDimitry Andric   return FileEntryRef(*Insertion.first);
494519fc96cSDimitry Andric }
495519fc96cSDimitry Andric 
FixupRelativePath(SmallVectorImpl<char> & path) const49645b53394SDimitry Andric bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
49736981b17SDimitry Andric   StringRef pathRef(path.data(), path.size());
49801af97d3SDimitry Andric 
49901af97d3SDimitry Andric   if (FileSystemOpts.WorkingDir.empty()
50001af97d3SDimitry Andric       || llvm::sys::path::is_absolute(pathRef))
50145b53394SDimitry Andric     return false;
502bca07a45SDimitry Andric 
503dbe13110SDimitry Andric   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
50401af97d3SDimitry Andric   llvm::sys::path::append(NewPath, pathRef);
505bca07a45SDimitry Andric   path = NewPath;
50645b53394SDimitry Andric   return true;
50745b53394SDimitry Andric }
50845b53394SDimitry Andric 
makeAbsolutePath(SmallVectorImpl<char> & Path) const50945b53394SDimitry Andric bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
51045b53394SDimitry Andric   bool Changed = FixupRelativePath(Path);
51145b53394SDimitry Andric 
51245b53394SDimitry Andric   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
513461a67faSDimitry Andric     FS->makeAbsolute(Path);
51445b53394SDimitry Andric     Changed = true;
51545b53394SDimitry Andric   }
51645b53394SDimitry Andric 
51745b53394SDimitry Andric   return Changed;
518bca07a45SDimitry Andric }
519bca07a45SDimitry Andric 
fillRealPathName(FileEntry * UFE,llvm::StringRef FileName)520676fbe81SDimitry Andric void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
521676fbe81SDimitry Andric   llvm::SmallString<128> AbsPath(FileName);
522676fbe81SDimitry Andric   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
523676fbe81SDimitry Andric   // but can be very expensive on real file systems.
524676fbe81SDimitry Andric   // FIXME: the semantic of RealPathName is unclear, and the name might be
525676fbe81SDimitry Andric   // misleading. We need to clean up the interface here.
526676fbe81SDimitry Andric   makeAbsolutePath(AbsPath);
527676fbe81SDimitry Andric   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
5284df029ccSDimitry Andric   UFE->RealPathName = std::string(AbsPath);
529676fbe81SDimitry Andric }
530676fbe81SDimitry Andric 
53106d4ba38SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBufferForFile(FileEntryRef FE,bool isVolatile,bool RequiresNullTerminator,std::optional<int64_t> MaybeLimit)532b1c73532SDimitry Andric FileManager::getBufferForFile(FileEntryRef FE, bool isVolatile,
533ac9a064cSDimitry Andric                               bool RequiresNullTerminator,
534ac9a064cSDimitry Andric                               std::optional<int64_t> MaybeLimit) {
535b1c73532SDimitry Andric   const FileEntry *Entry = &FE.getFileEntry();
536b60736ecSDimitry Andric   // If the content is living on the file entry, return a reference to it.
537b60736ecSDimitry Andric   if (Entry->Content)
538b60736ecSDimitry Andric     return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
539b60736ecSDimitry Andric 
54056d91b49SDimitry Andric   uint64_t FileSize = Entry->getSize();
541ac9a064cSDimitry Andric 
542ac9a064cSDimitry Andric   if (MaybeLimit)
543ac9a064cSDimitry Andric     FileSize = *MaybeLimit;
544ac9a064cSDimitry Andric 
54556d91b49SDimitry Andric   // If there's a high enough chance that the file have changed since we
54656d91b49SDimitry Andric   // got its size, force a stat before opening it.
547b60736ecSDimitry Andric   if (isVolatile || Entry->isNamedPipe())
54856d91b49SDimitry Andric     FileSize = -1;
54956d91b49SDimitry Andric 
550b1c73532SDimitry Andric   StringRef Filename = FE.getName();
551bca07a45SDimitry Andric   // If the file is already open, use the open file descriptor.
5529f4dbff6SDimitry Andric   if (Entry->File) {
553cfca06d7SDimitry Andric     auto Result = Entry->File->getBuffer(Filename, FileSize,
554cfca06d7SDimitry Andric                                          RequiresNullTerminator, isVolatile);
5559f4dbff6SDimitry Andric     Entry->closeFile();
55606d4ba38SDimitry Andric     return Result;
557bca07a45SDimitry Andric   }
558bca07a45SDimitry Andric 
559bca07a45SDimitry Andric   // Otherwise, open the file.
560cfca06d7SDimitry Andric   return getBufferForFileImpl(Filename, FileSize, isVolatile,
561cfca06d7SDimitry Andric                               RequiresNullTerminator);
562519fc96cSDimitry Andric }
56301af97d3SDimitry Andric 
564519fc96cSDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBufferForFileImpl(StringRef Filename,int64_t FileSize,bool isVolatile,bool RequiresNullTerminator) const565519fc96cSDimitry Andric FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
566cfca06d7SDimitry Andric                                   bool isVolatile,
567ac9a064cSDimitry Andric                                   bool RequiresNullTerminator) const {
56806d4ba38SDimitry Andric   if (FileSystemOpts.WorkingDir.empty())
569cfca06d7SDimitry Andric     return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
570cfca06d7SDimitry Andric                                 isVolatile);
571bca07a45SDimitry Andric 
572519fc96cSDimitry Andric   SmallString<128> FilePath(Filename);
57301af97d3SDimitry Andric   FixupRelativePath(FilePath);
574cfca06d7SDimitry Andric   return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
575cfca06d7SDimitry Andric                               isVolatile);
576bca07a45SDimitry Andric }
577bca07a45SDimitry Andric 
578bca07a45SDimitry Andric /// getStatValue - Get the 'stat' information for the specified path,
579bca07a45SDimitry Andric /// using the cache to accelerate it if possible.  This returns true
580bca07a45SDimitry Andric /// if the path points to a virtual file or does not exist, or returns
581bca07a45SDimitry Andric /// false if it's an existent real file.  If FileDescriptor is NULL,
582bca07a45SDimitry Andric /// do directory look-up instead of file look-up.
583519fc96cSDimitry Andric std::error_code
getStatValue(StringRef Path,llvm::vfs::Status & Status,bool isFile,std::unique_ptr<llvm::vfs::File> * F)584519fc96cSDimitry Andric FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
585519fc96cSDimitry Andric                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
586bca07a45SDimitry Andric   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
587bca07a45SDimitry Andric   // absolute!
588bca07a45SDimitry Andric   if (FileSystemOpts.WorkingDir.empty())
589519fc96cSDimitry Andric     return FileSystemStatCache::get(Path, Status, isFile, F,
590519fc96cSDimitry Andric                                     StatCache.get(), *FS);
591bca07a45SDimitry Andric 
592dbe13110SDimitry Andric   SmallString<128> FilePath(Path);
59301af97d3SDimitry Andric   FixupRelativePath(FilePath);
594bca07a45SDimitry Andric 
595519fc96cSDimitry Andric   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
596519fc96cSDimitry Andric                                   StatCache.get(), *FS);
597bca07a45SDimitry Andric }
598bca07a45SDimitry Andric 
599519fc96cSDimitry Andric std::error_code
getNoncachedStatValue(StringRef Path,llvm::vfs::Status & Result)600519fc96cSDimitry Andric FileManager::getNoncachedStatValue(StringRef Path,
601676fbe81SDimitry Andric                                    llvm::vfs::Status &Result) {
602dbe13110SDimitry Andric   SmallString<128> FilePath(Path);
60301af97d3SDimitry Andric   FixupRelativePath(FilePath);
60401af97d3SDimitry Andric 
605676fbe81SDimitry Andric   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
6069f4dbff6SDimitry Andric   if (!S)
607519fc96cSDimitry Andric     return S.getError();
6089f4dbff6SDimitry Andric   Result = *S;
609519fc96cSDimitry Andric   return std::error_code();
61056d91b49SDimitry Andric }
61156d91b49SDimitry Andric 
GetUniqueIDMapping(SmallVectorImpl<OptionalFileEntryRef> & UIDToFiles) const612bca07a45SDimitry Andric void FileManager::GetUniqueIDMapping(
613b1c73532SDimitry Andric     SmallVectorImpl<OptionalFileEntryRef> &UIDToFiles) const {
614bca07a45SDimitry Andric   UIDToFiles.clear();
615bca07a45SDimitry Andric   UIDToFiles.resize(NextFileUID);
616bca07a45SDimitry Andric 
617b1c73532SDimitry Andric   for (const auto &Entry : SeenFileEntries) {
618b1c73532SDimitry Andric     // Only return files that exist and are not redirected.
619b1c73532SDimitry Andric     if (!Entry.getValue() || !Entry.getValue()->V.is<FileEntry *>())
620b1c73532SDimitry Andric       continue;
621b1c73532SDimitry Andric     FileEntryRef FE(Entry);
622b1c73532SDimitry Andric     // Add this file if it's the first one with the UID, or if its name is
623b1c73532SDimitry Andric     // better than the existing one.
624b1c73532SDimitry Andric     OptionalFileEntryRef &ExistingFE = UIDToFiles[FE.getUID()];
625b1c73532SDimitry Andric     if (!ExistingFE || FE.getName() < ExistingFE->getName())
626b1c73532SDimitry Andric       ExistingFE = FE;
627519fc96cSDimitry Andric   }
628bca07a45SDimitry Andric }
629bca07a45SDimitry Andric 
getCanonicalName(DirectoryEntryRef Dir)6307fa27ce4SDimitry Andric StringRef FileManager::getCanonicalName(DirectoryEntryRef Dir) {
631b1c73532SDimitry Andric   return getCanonicalName(Dir, Dir.getName());
632706b4fc4SDimitry Andric }
633706b4fc4SDimitry Andric 
getCanonicalName(FileEntryRef File)634b1c73532SDimitry Andric StringRef FileManager::getCanonicalName(FileEntryRef File) {
635b1c73532SDimitry Andric   return getCanonicalName(File, File.getName());
636b1c73532SDimitry Andric }
637b1c73532SDimitry Andric 
getCanonicalName(const void * Entry,StringRef Name)638b1c73532SDimitry Andric StringRef FileManager::getCanonicalName(const void *Entry, StringRef Name) {
639b1c73532SDimitry Andric   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known =
640b1c73532SDimitry Andric       CanonicalNames.find(Entry);
641706b4fc4SDimitry Andric   if (Known != CanonicalNames.end())
642706b4fc4SDimitry Andric     return Known->second;
643706b4fc4SDimitry Andric 
644b1c73532SDimitry Andric   // Name comes from FileEntry/DirectoryEntry::getName(), so it is safe to
645b1c73532SDimitry Andric   // store it in the DenseMap below.
646b1c73532SDimitry Andric   StringRef CanonicalName(Name);
647706b4fc4SDimitry Andric 
648b1c73532SDimitry Andric   SmallString<256> AbsPathBuf;
649b1c73532SDimitry Andric   SmallString<256> RealPathBuf;
650b1c73532SDimitry Andric   if (!FS->getRealPath(Name, RealPathBuf)) {
651b1c73532SDimitry Andric     if (is_style_windows(llvm::sys::path::Style::native)) {
652b1c73532SDimitry Andric       // For Windows paths, only use the real path if it doesn't resolve
653b1c73532SDimitry Andric       // a substitute drive, as those are used to avoid MAX_PATH issues.
654b1c73532SDimitry Andric       AbsPathBuf = Name;
655b1c73532SDimitry Andric       if (!FS->makeAbsolute(AbsPathBuf)) {
656b1c73532SDimitry Andric         if (llvm::sys::path::root_name(RealPathBuf) ==
657b1c73532SDimitry Andric             llvm::sys::path::root_name(AbsPathBuf)) {
658b1c73532SDimitry Andric           CanonicalName = RealPathBuf.str().copy(CanonicalNameStorage);
659b1c73532SDimitry Andric         } else {
660b1c73532SDimitry Andric           // Fallback to using the absolute path.
661b1c73532SDimitry Andric           // Simplifying /../ is semantically valid on Windows even in the
662b1c73532SDimitry Andric           // presence of symbolic links.
663b1c73532SDimitry Andric           llvm::sys::path::remove_dots(AbsPathBuf, /*remove_dot_dot=*/true);
664b1c73532SDimitry Andric           CanonicalName = AbsPathBuf.str().copy(CanonicalNameStorage);
665b1c73532SDimitry Andric         }
666b1c73532SDimitry Andric       }
667b1c73532SDimitry Andric     } else {
668b1c73532SDimitry Andric       CanonicalName = RealPathBuf.str().copy(CanonicalNameStorage);
669b1c73532SDimitry Andric     }
670b1c73532SDimitry Andric   }
671706b4fc4SDimitry Andric 
672b1c73532SDimitry Andric   CanonicalNames.insert({Entry, CanonicalName});
673809500fcSDimitry Andric   return CanonicalName;
674809500fcSDimitry Andric }
675bca07a45SDimitry Andric 
AddStats(const FileManager & Other)676ac9a064cSDimitry Andric void FileManager::AddStats(const FileManager &Other) {
677ac9a064cSDimitry Andric   assert(&Other != this && "Collecting stats into the same FileManager");
678ac9a064cSDimitry Andric   NumDirLookups += Other.NumDirLookups;
679ac9a064cSDimitry Andric   NumFileLookups += Other.NumFileLookups;
680ac9a064cSDimitry Andric   NumDirCacheMisses += Other.NumDirCacheMisses;
681ac9a064cSDimitry Andric   NumFileCacheMisses += Other.NumFileCacheMisses;
682ac9a064cSDimitry Andric }
683ac9a064cSDimitry Andric 
PrintStats() const684ec2b103cSEd Schouten void FileManager::PrintStats() const {
6854c8b2481SRoman Divacky   llvm::errs() << "\n*** File Manager Stats:\n";
686bca07a45SDimitry Andric   llvm::errs() << UniqueRealFiles.size() << " real files found, "
687bca07a45SDimitry Andric                << UniqueRealDirs.size() << " real dirs found.\n";
688bca07a45SDimitry Andric   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
689bca07a45SDimitry Andric                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
6904c8b2481SRoman Divacky   llvm::errs() << NumDirLookups << " dir lookups, "
691ec2b103cSEd Schouten                << NumDirCacheMisses << " dir cache misses.\n";
6924c8b2481SRoman Divacky   llvm::errs() << NumFileLookups << " file lookups, "
693ec2b103cSEd Schouten                << NumFileCacheMisses << " file cache misses.\n";
694ec2b103cSEd Schouten 
6954c8b2481SRoman Divacky   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
696ec2b103cSEd Schouten }
697