1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the FileManager interface.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // TODO: This should index all interesting directories with dirent calls.
14 //  getdirentries ?
15 //  opendir/readdir_r/closedir ?
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemStatCache.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <climits>
32 #include <cstdint>
33 #include <cstdlib>
34 #include <string>
35 #include <utility>
36 
37 using namespace clang;
38 
39 #define DEBUG_TYPE "file-search"
40 
41 ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
42 ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
43 ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
44                          "Number of directory cache misses.");
45 ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
46 
47 //===----------------------------------------------------------------------===//
48 // Common logic.
49 //===----------------------------------------------------------------------===//
50 
51 FileManager::FileManager(const FileSystemOptions &FSO,
52                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
53     : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
54       SeenFileEntries(64), NextFileUID(0) {
55   // If the caller doesn't provide a virtual file system, just grab the real
56   // file system.
57   if (!this->FS)
58     this->FS = llvm::vfs::getRealFileSystem();
59 }
60 
61 FileManager::~FileManager() = default;
62 
63 void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64   assert(statCache && "No stat cache provided?");
65   StatCache = std::move(statCache);
66 }
67 
68 void FileManager::clearStatCache() { StatCache.reset(); }
69 
70 /// Retrieve the directory that the given file name resides in.
71 /// Filename can point to either a real file or a virtual file.
72 static llvm::Expected<DirectoryEntryRef>
73 getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
74                      bool CacheFailure) {
75   if (Filename.empty())
76     return llvm::errorCodeToError(
77         make_error_code(std::errc::no_such_file_or_directory));
78 
79   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
80     return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory));
81 
82   StringRef DirName = llvm::sys::path::parent_path(Filename);
83   // Use the current directory if file has no path component.
84   if (DirName.empty())
85     DirName = ".";
86 
87   return FileMgr.getDirectoryRef(DirName, CacheFailure);
88 }
89 
90 /// Add all ancestors of the given path (pointing to either a file or
91 /// a directory) as virtual directories.
92 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
93   StringRef DirName = llvm::sys::path::parent_path(Path);
94   if (DirName.empty())
95     DirName = ".";
96 
97   auto &NamedDirEnt = *SeenDirEntries.insert(
98         {DirName, std::errc::no_such_file_or_directory}).first;
99 
100   // When caching a virtual directory, we always cache its ancestors
101   // at the same time.  Therefore, if DirName is already in the cache,
102   // we don't need to recurse as its ancestors must also already be in
103   // the cache (or it's a known non-virtual directory).
104   if (NamedDirEnt.second)
105     return;
106 
107   // Add the virtual directory to the cache.
108   auto UDE = std::make_unique<DirectoryEntry>();
109   UDE->Name = NamedDirEnt.first();
110   NamedDirEnt.second = *UDE.get();
111   VirtualDirectoryEntries.push_back(std::move(UDE));
112 
113   // Recursively add the other ancestors.
114   addAncestorsAsVirtualDirs(DirName);
115 }
116 
117 llvm::Expected<DirectoryEntryRef>
118 FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
119   // stat doesn't like trailing separators except for root directory.
120   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
121   // (though it can strip '\\')
122   if (DirName.size() > 1 &&
123       DirName != llvm::sys::path::root_path(DirName) &&
124       llvm::sys::path::is_separator(DirName.back()))
125     DirName = DirName.substr(0, DirName.size()-1);
126   Optional<std::string> DirNameStr;
127   if (is_style_windows(llvm::sys::path::Style::native)) {
128     // Fixing a problem with "clang C:test.c" on Windows.
129     // Stat("C:") does not recognize "C:" as a valid directory
130     if (DirName.size() > 1 && DirName.back() == ':' &&
131         DirName.equals_insensitive(llvm::sys::path::root_name(DirName))) {
132       DirNameStr = DirName.str() + '.';
133       DirName = *DirNameStr;
134     }
135   }
136 
137   ++NumDirLookups;
138 
139   // See if there was already an entry in the map.  Note that the map
140   // contains both virtual and real directories.
141   auto SeenDirInsertResult =
142       SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
143   if (!SeenDirInsertResult.second) {
144     if (SeenDirInsertResult.first->second)
145       return DirectoryEntryRef(*SeenDirInsertResult.first);
146     return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
147   }
148 
149   // We've not seen this before. Fill it in.
150   ++NumDirCacheMisses;
151   auto &NamedDirEnt = *SeenDirInsertResult.first;
152   assert(!NamedDirEnt.second && "should be newly-created");
153 
154   // Get the null-terminated directory name as stored as the key of the
155   // SeenDirEntries map.
156   StringRef InterndDirName = NamedDirEnt.first();
157 
158   // Check to see if the directory exists.
159   llvm::vfs::Status Status;
160   auto statError = getStatValue(InterndDirName, Status, false,
161                                 nullptr /*directory lookup*/);
162   if (statError) {
163     // There's no real directory at the given path.
164     if (CacheFailure)
165       NamedDirEnt.second = statError;
166     else
167       SeenDirEntries.erase(DirName);
168     return llvm::errorCodeToError(statError);
169   }
170 
171   // It exists.  See if we have already opened a directory with the
172   // same inode (this occurs on Unix-like systems when one dir is
173   // symlinked to another, for example) or the same path (on
174   // Windows).
175   DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
176 
177   NamedDirEnt.second = UDE;
178   if (UDE.getName().empty()) {
179     // We don't have this directory yet, add it.  We use the string
180     // key from the SeenDirEntries map as the string.
181     UDE.Name  = InterndDirName;
182   }
183 
184   return DirectoryEntryRef(NamedDirEnt);
185 }
186 
187 llvm::ErrorOr<const DirectoryEntry *>
188 FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
189   auto Result = getDirectoryRef(DirName, CacheFailure);
190   if (Result)
191     return &Result->getDirEntry();
192   return llvm::errorToErrorCode(Result.takeError());
193 }
194 
195 llvm::ErrorOr<const FileEntry *>
196 FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
197   auto Result = getFileRef(Filename, openFile, CacheFailure);
198   if (Result)
199     return &Result->getFileEntry();
200   return llvm::errorToErrorCode(Result.takeError());
201 }
202 
203 llvm::Expected<FileEntryRef>
204 FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
205   ++NumFileLookups;
206 
207   // See if there is already an entry in the map.
208   auto SeenFileInsertResult =
209       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
210   if (!SeenFileInsertResult.second) {
211     if (!SeenFileInsertResult.first->second)
212       return llvm::errorCodeToError(
213           SeenFileInsertResult.first->second.getError());
214     // Construct and return and FileEntryRef, unless it's a redirect to another
215     // filename.
216     FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
217     if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
218       return FileEntryRef(*SeenFileInsertResult.first);
219     return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
220         Value.V.get<const void *>()));
221   }
222 
223   // We've not seen this before. Fill it in.
224   ++NumFileCacheMisses;
225   auto *NamedFileEnt = &*SeenFileInsertResult.first;
226   assert(!NamedFileEnt->second && "should be newly-created");
227 
228   // Get the null-terminated file name as stored as the key of the
229   // SeenFileEntries map.
230   StringRef InterndFileName = NamedFileEnt->first();
231 
232   // Look up the directory for the file.  When looking up something like
233   // sys/foo.h we'll discover all of the search directories that have a 'sys'
234   // subdirectory.  This will let us avoid having to waste time on known-to-fail
235   // searches when we go to find sys/bar.h, because all the search directories
236   // without a 'sys' subdir will get a cached failure result.
237   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
238   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
239     std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
240     if (CacheFailure)
241       NamedFileEnt->second = Err;
242     else
243       SeenFileEntries.erase(Filename);
244 
245     return llvm::errorCodeToError(Err);
246   }
247   DirectoryEntryRef DirInfo = *DirInfoOrErr;
248 
249   // FIXME: Use the directory info to prune this, before doing the stat syscall.
250   // FIXME: This will reduce the # syscalls.
251 
252   // Check to see if the file exists.
253   std::unique_ptr<llvm::vfs::File> F;
254   llvm::vfs::Status Status;
255   auto statError = getStatValue(InterndFileName, Status, true,
256                                 openFile ? &F : nullptr);
257   if (statError) {
258     // There's no real file at the given path.
259     if (CacheFailure)
260       NamedFileEnt->second = statError;
261     else
262       SeenFileEntries.erase(Filename);
263 
264     return llvm::errorCodeToError(statError);
265   }
266 
267   assert((openFile || !F) && "undesired open file");
268 
269   // It exists.  See if we have already opened a file with the same inode.
270   // This occurs when one dir is symlinked to another, for example.
271   FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
272 
273   // FIXME: This should just check `!Status.ExposesExternalVFSPath`, but the
274   // else branch also ends up fixing up relative paths to be the actually
275   // looked up absolute path. This isn't necessarily desired, but does seem to
276   // be relied on in some clients.
277   if (Status.getName() == Filename) {
278     // The name matches. Set the FileEntry.
279     NamedFileEnt->second = FileEntryRef::MapValue(UFE, DirInfo);
280   } else {
281     // We need a redirect. First grab the actual entry we want to return.
282     //
283     // This redirection logic intentionally leaks the external name of a
284     // redirected file that uses 'use-external-name' in \a
285     // vfs::RedirectionFileSystem. This allows clang to report the external
286     // name to users (in diagnostics) and to tools that don't have access to
287     // the VFS (in debug info and dependency '.d' files).
288     //
289     // FIXME: This is pretty complicated. It's also inconsistent with how
290     // "real" filesystems behave and confuses parts of clang expect to see the
291     // name-as-accessed on the \a FileEntryRef. To remove this we should
292     // implement the FIXME on `ExposesExternalVFSPath`, ie. update the
293     // `FileEntryRef::getName()` path to *always* be the virtual path and have
294     // clients request the external path only when required through a separate
295     // API.
296     auto &Redirection =
297         *SeenFileEntries
298              .insert({Status.getName(), FileEntryRef::MapValue(UFE, DirInfo)})
299              .first;
300     assert(Redirection.second->V.is<FileEntry *>() &&
301            "filename redirected to a non-canonical filename?");
302     assert(Redirection.second->V.get<FileEntry *>() == &UFE &&
303            "filename from getStatValue() refers to wrong file");
304 
305     // Cache the redirection in the previously-inserted entry, still available
306     // in the tentative return value.
307     NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
308 
309     // Fix the tentative return value.
310     NamedFileEnt = &Redirection;
311   }
312 
313   FileEntryRef ReturnedRef(*NamedFileEnt);
314   if (UFE.isValid()) { // Already have an entry with this inode, return it.
315 
316     // FIXME: This hack ensures that `getDir()` will use the path that was
317     // used to lookup this file, even if we found a file by different path
318     // first. This is required in order to find a module's structure when its
319     // headers/module map are mapped in the VFS.
320     //
321     // This should be removed once `HeaderSearch` is updated to use `*Ref`s
322     // *and* the redirection hack above is removed. The removal of the latter
323     // is required since otherwise the ref will have the exposed external VFS
324     // path still.
325     if (&DirInfo.getDirEntry() != UFE.Dir && Status.ExposesExternalVFSPath)
326       UFE.Dir = &DirInfo.getDirEntry();
327 
328     // Always update LastRef to the last name by which a file was accessed.
329     // FIXME: Neither this nor always using the first reference is correct; we
330     // want to switch towards a design where we return a FileName object that
331     // encapsulates both the name by which the file was accessed and the
332     // corresponding FileEntry.
333     // FIXME: LastRef should be removed from FileEntry once all clients adopt
334     // FileEntryRef.
335     UFE.LastRef = ReturnedRef;
336 
337     return ReturnedRef;
338   }
339 
340   // Otherwise, we don't have this file yet, add it.
341   UFE.LastRef = ReturnedRef;
342   UFE.Size    = Status.getSize();
343   UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
344   UFE.Dir     = &DirInfo.getDirEntry();
345   UFE.UID     = NextFileUID++;
346   UFE.UniqueID = Status.getUniqueID();
347   UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
348   UFE.File = std::move(F);
349   UFE.IsValid = true;
350 
351   if (UFE.File) {
352     if (auto PathName = UFE.File->getName())
353       fillRealPathName(&UFE, *PathName);
354   } else if (!openFile) {
355     // We should still fill the path even if we aren't opening the file.
356     fillRealPathName(&UFE, InterndFileName);
357   }
358   return ReturnedRef;
359 }
360 
361 llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
362   // Only read stdin once.
363   if (STDIN)
364     return *STDIN;
365 
366   std::unique_ptr<llvm::MemoryBuffer> Content;
367   if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
368     Content = std::move(*ContentOrError);
369   else
370     return llvm::errorCodeToError(ContentOrError.getError());
371 
372   STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
373                             Content->getBufferSize(), 0);
374   FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
375   FE.Content = std::move(Content);
376   FE.IsNamedPipe = true;
377   return *STDIN;
378 }
379 
380 const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
381                                              time_t ModificationTime) {
382   return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
383 }
384 
385 FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
386                                             time_t ModificationTime) {
387   ++NumFileLookups;
388 
389   // See if there is already an entry in the map for an existing file.
390   auto &NamedFileEnt = *SeenFileEntries.insert(
391       {Filename, std::errc::no_such_file_or_directory}).first;
392   if (NamedFileEnt.second) {
393     FileEntryRef::MapValue Value = *NamedFileEnt.second;
394     if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
395       return FileEntryRef(NamedFileEnt);
396     return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
397         Value.V.get<const void *>()));
398   }
399 
400   // We've not seen this before, or the file is cached as non-existent.
401   ++NumFileCacheMisses;
402   addAncestorsAsVirtualDirs(Filename);
403   FileEntry *UFE = nullptr;
404 
405   // Now that all ancestors of Filename are in the cache, the
406   // following call is guaranteed to find the DirectoryEntry from the
407   // cache. A virtual file can also have an empty filename, that could come
408   // from a source location preprocessor directive with an empty filename as
409   // an example, so we need to pretend it has a name to ensure a valid directory
410   // entry can be returned.
411   auto DirInfo = expectedToOptional(getDirectoryFromFile(
412       *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true));
413   assert(DirInfo &&
414          "The directory of a virtual file should already be in the cache.");
415 
416   // Check to see if the file exists. If so, drop the virtual file
417   llvm::vfs::Status Status;
418   const char *InterndFileName = NamedFileEnt.first().data();
419   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
420     UFE = &UniqueRealFiles[Status.getUniqueID()];
421     Status = llvm::vfs::Status(
422       Status.getName(), Status.getUniqueID(),
423       llvm::sys::toTimePoint(ModificationTime),
424       Status.getUser(), Status.getGroup(), Size,
425       Status.getType(), Status.getPermissions());
426 
427     NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
428 
429     // If we had already opened this file, close it now so we don't
430     // leak the descriptor. We're not going to use the file
431     // descriptor anyway, since this is a virtual file.
432     if (UFE->File)
433       UFE->closeFile();
434 
435     // If we already have an entry with this inode, return it.
436     //
437     // FIXME: Surely this should add a reference by the new name, and return
438     // it instead...
439     if (UFE->isValid())
440       return FileEntryRef(NamedFileEnt);
441 
442     UFE->UniqueID = Status.getUniqueID();
443     UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
444     fillRealPathName(UFE, Status.getName());
445   } else {
446     VirtualFileEntries.push_back(std::make_unique<FileEntry>());
447     UFE = VirtualFileEntries.back().get();
448     NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
449   }
450 
451   UFE->LastRef = FileEntryRef(NamedFileEnt);
452   UFE->Size    = Size;
453   UFE->ModTime = ModificationTime;
454   UFE->Dir     = &DirInfo->getDirEntry();
455   UFE->UID     = NextFileUID++;
456   UFE->IsValid = true;
457   UFE->File.reset();
458   return FileEntryRef(NamedFileEnt);
459 }
460 
461 llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
462   // Stat of the file and return nullptr if it doesn't exist.
463   llvm::vfs::Status Status;
464   if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
465     return None;
466 
467   if (!SeenBypassFileEntries)
468     SeenBypassFileEntries = std::make_unique<
469         llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
470 
471   // If we've already bypassed just use the existing one.
472   auto Insertion = SeenBypassFileEntries->insert(
473       {VF.getName(), std::errc::no_such_file_or_directory});
474   if (!Insertion.second)
475     return FileEntryRef(*Insertion.first);
476 
477   // Fill in the new entry from the stat.
478   BypassFileEntries.push_back(std::make_unique<FileEntry>());
479   const FileEntry &VFE = VF.getFileEntry();
480   FileEntry &BFE = *BypassFileEntries.back();
481   Insertion.first->second = FileEntryRef::MapValue(BFE, VF.getDir());
482   BFE.LastRef = FileEntryRef(*Insertion.first);
483   BFE.Size = Status.getSize();
484   BFE.Dir = VFE.Dir;
485   BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
486   BFE.UID = NextFileUID++;
487   BFE.IsValid = true;
488 
489   // Save the entry in the bypass table and return.
490   return FileEntryRef(*Insertion.first);
491 }
492 
493 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
494   StringRef pathRef(path.data(), path.size());
495 
496   if (FileSystemOpts.WorkingDir.empty()
497       || llvm::sys::path::is_absolute(pathRef))
498     return false;
499 
500   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
501   llvm::sys::path::append(NewPath, pathRef);
502   path = NewPath;
503   return true;
504 }
505 
506 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
507   bool Changed = FixupRelativePath(Path);
508 
509   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
510     FS->makeAbsolute(Path);
511     Changed = true;
512   }
513 
514   return Changed;
515 }
516 
517 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
518   llvm::SmallString<128> AbsPath(FileName);
519   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
520   // but can be very expensive on real file systems.
521   // FIXME: the semantic of RealPathName is unclear, and the name might be
522   // misleading. We need to clean up the interface here.
523   makeAbsolutePath(AbsPath);
524   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
525   UFE->RealPathName = std::string(AbsPath.str());
526 }
527 
528 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
529 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
530                               bool RequiresNullTerminator) {
531   // If the content is living on the file entry, return a reference to it.
532   if (Entry->Content)
533     return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
534 
535   uint64_t FileSize = Entry->getSize();
536   // If there's a high enough chance that the file have changed since we
537   // got its size, force a stat before opening it.
538   if (isVolatile || Entry->isNamedPipe())
539     FileSize = -1;
540 
541   StringRef Filename = Entry->getName();
542   // If the file is already open, use the open file descriptor.
543   if (Entry->File) {
544     auto Result = Entry->File->getBuffer(Filename, FileSize,
545                                          RequiresNullTerminator, isVolatile);
546     Entry->closeFile();
547     return Result;
548   }
549 
550   // Otherwise, open the file.
551   return getBufferForFileImpl(Filename, FileSize, isVolatile,
552                               RequiresNullTerminator);
553 }
554 
555 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
556 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
557                                   bool isVolatile,
558                                   bool RequiresNullTerminator) {
559   if (FileSystemOpts.WorkingDir.empty())
560     return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
561                                 isVolatile);
562 
563   SmallString<128> FilePath(Filename);
564   FixupRelativePath(FilePath);
565   return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
566                               isVolatile);
567 }
568 
569 /// getStatValue - Get the 'stat' information for the specified path,
570 /// using the cache to accelerate it if possible.  This returns true
571 /// if the path points to a virtual file or does not exist, or returns
572 /// false if it's an existent real file.  If FileDescriptor is NULL,
573 /// do directory look-up instead of file look-up.
574 std::error_code
575 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
576                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
577   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
578   // absolute!
579   if (FileSystemOpts.WorkingDir.empty())
580     return FileSystemStatCache::get(Path, Status, isFile, F,
581                                     StatCache.get(), *FS);
582 
583   SmallString<128> FilePath(Path);
584   FixupRelativePath(FilePath);
585 
586   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
587                                   StatCache.get(), *FS);
588 }
589 
590 std::error_code
591 FileManager::getNoncachedStatValue(StringRef Path,
592                                    llvm::vfs::Status &Result) {
593   SmallString<128> FilePath(Path);
594   FixupRelativePath(FilePath);
595 
596   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
597   if (!S)
598     return S.getError();
599   Result = *S;
600   return std::error_code();
601 }
602 
603 void FileManager::GetUniqueIDMapping(
604                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
605   UIDToFiles.clear();
606   UIDToFiles.resize(NextFileUID);
607 
608   // Map file entries
609   for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
610                        llvm::BumpPtrAllocator>::const_iterator
611            FE = SeenFileEntries.begin(),
612            FEEnd = SeenFileEntries.end();
613        FE != FEEnd; ++FE)
614     if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
615       if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
616         UIDToFiles[FE->getUID()] = FE;
617     }
618 
619   // Map virtual file entries
620   for (const auto &VFE : VirtualFileEntries)
621     UIDToFiles[VFE->getUID()] = VFE.get();
622 }
623 
624 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
625   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
626     = CanonicalNames.find(Dir);
627   if (Known != CanonicalNames.end())
628     return Known->second;
629 
630   StringRef CanonicalName(Dir->getName());
631 
632   SmallString<4096> CanonicalNameBuf;
633   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
634     CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
635 
636   CanonicalNames.insert({Dir, CanonicalName});
637   return CanonicalName;
638 }
639 
640 StringRef FileManager::getCanonicalName(const FileEntry *File) {
641   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
642     = CanonicalNames.find(File);
643   if (Known != CanonicalNames.end())
644     return Known->second;
645 
646   StringRef CanonicalName(File->getName());
647 
648   SmallString<4096> CanonicalNameBuf;
649   if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
650     CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
651 
652   CanonicalNames.insert({File, CanonicalName});
653   return CanonicalName;
654 }
655 
656 void FileManager::PrintStats() const {
657   llvm::errs() << "\n*** File Manager Stats:\n";
658   llvm::errs() << UniqueRealFiles.size() << " real files found, "
659                << UniqueRealDirs.size() << " real dirs found.\n";
660   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
661                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
662   llvm::errs() << NumDirLookups << " dir lookups, "
663                << NumDirCacheMisses << " dir cache misses.\n";
664   llvm::errs() << NumFileLookups << " file lookups, "
665                << NumFileCacheMisses << " file cache misses.\n";
666 
667   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
668 }
669