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 = new (DirsAlloc.Allocate()) DirectoryEntry();
109   UDE->Name = NamedDirEnt.first();
110   NamedDirEnt.second = *UDE;
111   VirtualDirectoryEntries.push_back(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   if (!UDE) {
178     // We don't have this directory yet, add it.  We use the string
179     // key from the SeenDirEntries map as the string.
180     UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
181     UDE->Name = InterndDirName;
182   }
183   NamedDirEnt.second = *UDE;
184 
185   return DirectoryEntryRef(NamedDirEnt);
186 }
187 
188 llvm::ErrorOr<const DirectoryEntry *>
189 FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
190   auto Result = getDirectoryRef(DirName, CacheFailure);
191   if (Result)
192     return &Result->getDirEntry();
193   return llvm::errorToErrorCode(Result.takeError());
194 }
195 
196 llvm::ErrorOr<const FileEntry *>
197 FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
198   auto Result = getFileRef(Filename, openFile, CacheFailure);
199   if (Result)
200     return &Result->getFileEntry();
201   return llvm::errorToErrorCode(Result.takeError());
202 }
203 
204 llvm::Expected<FileEntryRef>
205 FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
206   ++NumFileLookups;
207 
208   // See if there is already an entry in the map.
209   auto SeenFileInsertResult =
210       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
211   if (!SeenFileInsertResult.second) {
212     if (!SeenFileInsertResult.first->second)
213       return llvm::errorCodeToError(
214           SeenFileInsertResult.first->second.getError());
215     // Construct and return and FileEntryRef, unless it's a redirect to another
216     // filename.
217     FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
218     if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
219       return FileEntryRef(*SeenFileInsertResult.first);
220     return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
221         Value.V.get<const void *>()));
222   }
223 
224   // We've not seen this before. Fill it in.
225   ++NumFileCacheMisses;
226   auto *NamedFileEnt = &*SeenFileInsertResult.first;
227   assert(!NamedFileEnt->second && "should be newly-created");
228 
229   // Get the null-terminated file name as stored as the key of the
230   // SeenFileEntries map.
231   StringRef InterndFileName = NamedFileEnt->first();
232 
233   // Look up the directory for the file.  When looking up something like
234   // sys/foo.h we'll discover all of the search directories that have a 'sys'
235   // subdirectory.  This will let us avoid having to waste time on known-to-fail
236   // searches when we go to find sys/bar.h, because all the search directories
237   // without a 'sys' subdir will get a cached failure result.
238   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
239   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
240     std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
241     if (CacheFailure)
242       NamedFileEnt->second = Err;
243     else
244       SeenFileEntries.erase(Filename);
245 
246     return llvm::errorCodeToError(Err);
247   }
248   DirectoryEntryRef DirInfo = *DirInfoOrErr;
249 
250   // FIXME: Use the directory info to prune this, before doing the stat syscall.
251   // FIXME: This will reduce the # syscalls.
252 
253   // Check to see if the file exists.
254   std::unique_ptr<llvm::vfs::File> F;
255   llvm::vfs::Status Status;
256   auto statError = getStatValue(InterndFileName, Status, true,
257                                 openFile ? &F : nullptr);
258   if (statError) {
259     // There's no real file at the given path.
260     if (CacheFailure)
261       NamedFileEnt->second = statError;
262     else
263       SeenFileEntries.erase(Filename);
264 
265     return llvm::errorCodeToError(statError);
266   }
267 
268   assert((openFile || !F) && "undesired open file");
269 
270   // It exists.  See if we have already opened a file with the same inode.
271   // This occurs when one dir is symlinked to another, for example.
272   FileEntry *&UFE = UniqueRealFiles[Status.getUniqueID()];
273   bool ReusingEntry = UFE != nullptr;
274   if (!UFE)
275     UFE = new (FilesAlloc.Allocate()) FileEntry();
276 
277   // FIXME: This should just check `!Status.ExposesExternalVFSPath`, but the
278   // else branch also ends up fixing up relative paths to be the actually
279   // looked up absolute path. This isn't necessarily desired, but does seem to
280   // be relied on in some clients.
281   if (Status.getName() == Filename) {
282     // The name matches. Set the FileEntry.
283     NamedFileEnt->second = FileEntryRef::MapValue(*UFE, DirInfo);
284   } else {
285     // We need a redirect. First grab the actual entry we want to return.
286     //
287     // This redirection logic intentionally leaks the external name of a
288     // redirected file that uses 'use-external-name' in \a
289     // vfs::RedirectionFileSystem. This allows clang to report the external
290     // name to users (in diagnostics) and to tools that don't have access to
291     // the VFS (in debug info and dependency '.d' files).
292     //
293     // FIXME: This is pretty complicated. It's also inconsistent with how
294     // "real" filesystems behave and confuses parts of clang expect to see the
295     // name-as-accessed on the \a FileEntryRef. To remove this we should
296     // implement the FIXME on `ExposesExternalVFSPath`, ie. update the
297     // `FileEntryRef::getName()` path to *always* be the virtual path and have
298     // clients request the external path only when required through a separate
299     // API.
300     auto &Redirection =
301         *SeenFileEntries
302              .insert({Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)})
303              .first;
304     assert(Redirection.second->V.is<FileEntry *>() &&
305            "filename redirected to a non-canonical filename?");
306     assert(Redirection.second->V.get<FileEntry *>() == UFE &&
307            "filename from getStatValue() refers to wrong file");
308 
309     // Cache the redirection in the previously-inserted entry, still available
310     // in the tentative return value.
311     NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
312 
313     // Fix the tentative return value.
314     NamedFileEnt = &Redirection;
315   }
316 
317   FileEntryRef ReturnedRef(*NamedFileEnt);
318   if (ReusingEntry) { // Already have an entry with this inode, return it.
319 
320     // FIXME: This hack ensures that `getDir()` will use the path that was
321     // used to lookup this file, even if we found a file by different path
322     // first. This is required in order to find a module's structure when its
323     // headers/module map are mapped in the VFS.
324     //
325     // This should be removed once `HeaderSearch` is updated to use `*Ref`s
326     // *and* the redirection hack above is removed. The removal of the latter
327     // is required since otherwise the ref will have the exposed external VFS
328     // path still.
329     if (&DirInfo.getDirEntry() != UFE->Dir && Status.ExposesExternalVFSPath)
330       UFE->Dir = &DirInfo.getDirEntry();
331 
332     // Always update LastRef to the last name by which a file was accessed.
333     // FIXME: Neither this nor always using the first reference is correct; we
334     // want to switch towards a design where we return a FileName object that
335     // encapsulates both the name by which the file was accessed and the
336     // corresponding FileEntry.
337     // FIXME: LastRef should be removed from FileEntry once all clients adopt
338     // FileEntryRef.
339     UFE->LastRef = ReturnedRef;
340 
341     return ReturnedRef;
342   }
343 
344   // Otherwise, we don't have this file yet, add it.
345   UFE->LastRef = ReturnedRef;
346   UFE->Size = Status.getSize();
347   UFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
348   UFE->Dir = &DirInfo.getDirEntry();
349   UFE->UID = NextFileUID++;
350   UFE->UniqueID = Status.getUniqueID();
351   UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
352   UFE->File = std::move(F);
353   UFE->IsValid = true;
354 
355   if (UFE->File) {
356     if (auto PathName = UFE->File->getName())
357       fillRealPathName(UFE, *PathName);
358   } else if (!openFile) {
359     // We should still fill the path even if we aren't opening the file.
360     fillRealPathName(UFE, InterndFileName);
361   }
362   return ReturnedRef;
363 }
364 
365 llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
366   // Only read stdin once.
367   if (STDIN)
368     return *STDIN;
369 
370   std::unique_ptr<llvm::MemoryBuffer> Content;
371   if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
372     Content = std::move(*ContentOrError);
373   else
374     return llvm::errorCodeToError(ContentOrError.getError());
375 
376   STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
377                             Content->getBufferSize(), 0);
378   FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
379   FE.Content = std::move(Content);
380   FE.IsNamedPipe = true;
381   return *STDIN;
382 }
383 
384 const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
385                                              time_t ModificationTime) {
386   return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
387 }
388 
389 FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
390                                             time_t ModificationTime) {
391   ++NumFileLookups;
392 
393   // See if there is already an entry in the map for an existing file.
394   auto &NamedFileEnt = *SeenFileEntries.insert(
395       {Filename, std::errc::no_such_file_or_directory}).first;
396   if (NamedFileEnt.second) {
397     FileEntryRef::MapValue Value = *NamedFileEnt.second;
398     if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
399       return FileEntryRef(NamedFileEnt);
400     return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
401         Value.V.get<const void *>()));
402   }
403 
404   // We've not seen this before, or the file is cached as non-existent.
405   ++NumFileCacheMisses;
406   addAncestorsAsVirtualDirs(Filename);
407   FileEntry *UFE = nullptr;
408 
409   // Now that all ancestors of Filename are in the cache, the
410   // following call is guaranteed to find the DirectoryEntry from the
411   // cache. A virtual file can also have an empty filename, that could come
412   // from a source location preprocessor directive with an empty filename as
413   // an example, so we need to pretend it has a name to ensure a valid directory
414   // entry can be returned.
415   auto DirInfo = expectedToOptional(getDirectoryFromFile(
416       *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true));
417   assert(DirInfo &&
418          "The directory of a virtual file should already be in the cache.");
419 
420   // Check to see if the file exists. If so, drop the virtual file
421   llvm::vfs::Status Status;
422   const char *InterndFileName = NamedFileEnt.first().data();
423   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
424     Status = llvm::vfs::Status(
425       Status.getName(), Status.getUniqueID(),
426       llvm::sys::toTimePoint(ModificationTime),
427       Status.getUser(), Status.getGroup(), Size,
428       Status.getType(), Status.getPermissions());
429 
430     auto &RealFE = UniqueRealFiles[Status.getUniqueID()];
431     if (RealFE) {
432       // If we had already opened this file, close it now so we don't
433       // leak the descriptor. We're not going to use the file
434       // descriptor anyway, since this is a virtual file.
435       if (RealFE->File)
436         RealFE->closeFile();
437       // If we already have an entry with this inode, return it.
438       //
439       // FIXME: Surely this should add a reference by the new name, and return
440       // it instead...
441       NamedFileEnt.second = FileEntryRef::MapValue(*RealFE, *DirInfo);
442       return FileEntryRef(NamedFileEnt);
443     }
444     // File exists, but no entry - create it.
445     RealFE = new (FilesAlloc.Allocate()) FileEntry();
446     RealFE->UniqueID = Status.getUniqueID();
447     RealFE->IsNamedPipe =
448         Status.getType() == llvm::sys::fs::file_type::fifo_file;
449     fillRealPathName(RealFE, Status.getName());
450 
451     UFE = RealFE;
452   } else {
453     // File does not exist, create a virtual entry.
454     UFE = new (FilesAlloc.Allocate()) FileEntry();
455     VirtualFileEntries.push_back(UFE);
456   }
457 
458   NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
459   UFE->LastRef = FileEntryRef(NamedFileEnt);
460   UFE->Size    = Size;
461   UFE->ModTime = ModificationTime;
462   UFE->Dir     = &DirInfo->getDirEntry();
463   UFE->UID     = NextFileUID++;
464   UFE->IsValid = true;
465   UFE->File.reset();
466   return FileEntryRef(NamedFileEnt);
467 }
468 
469 llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
470   // Stat of the file and return nullptr if it doesn't exist.
471   llvm::vfs::Status Status;
472   if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
473     return None;
474 
475   if (!SeenBypassFileEntries)
476     SeenBypassFileEntries = std::make_unique<
477         llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
478 
479   // If we've already bypassed just use the existing one.
480   auto Insertion = SeenBypassFileEntries->insert(
481       {VF.getName(), std::errc::no_such_file_or_directory});
482   if (!Insertion.second)
483     return FileEntryRef(*Insertion.first);
484 
485   // Fill in the new entry from the stat.
486   FileEntry *BFE = new (FilesAlloc.Allocate()) FileEntry();
487   BypassFileEntries.push_back(BFE);
488   Insertion.first->second = FileEntryRef::MapValue(*BFE, VF.getDir());
489   BFE->LastRef = FileEntryRef(*Insertion.first);
490   BFE->Size = Status.getSize();
491   BFE->Dir = VF.getFileEntry().Dir;
492   BFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
493   BFE->UID = NextFileUID++;
494   BFE->IsValid = true;
495 
496   // Save the entry in the bypass table and return.
497   return FileEntryRef(*Insertion.first);
498 }
499 
500 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
501   StringRef pathRef(path.data(), path.size());
502 
503   if (FileSystemOpts.WorkingDir.empty()
504       || llvm::sys::path::is_absolute(pathRef))
505     return false;
506 
507   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
508   llvm::sys::path::append(NewPath, pathRef);
509   path = NewPath;
510   return true;
511 }
512 
513 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
514   bool Changed = FixupRelativePath(Path);
515 
516   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
517     FS->makeAbsolute(Path);
518     Changed = true;
519   }
520 
521   return Changed;
522 }
523 
524 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
525   llvm::SmallString<128> AbsPath(FileName);
526   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
527   // but can be very expensive on real file systems.
528   // FIXME: the semantic of RealPathName is unclear, and the name might be
529   // misleading. We need to clean up the interface here.
530   makeAbsolutePath(AbsPath);
531   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
532   UFE->RealPathName = std::string(AbsPath.str());
533 }
534 
535 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
536 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
537                               bool RequiresNullTerminator) {
538   // If the content is living on the file entry, return a reference to it.
539   if (Entry->Content)
540     return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
541 
542   uint64_t FileSize = Entry->getSize();
543   // If there's a high enough chance that the file have changed since we
544   // got its size, force a stat before opening it.
545   if (isVolatile || Entry->isNamedPipe())
546     FileSize = -1;
547 
548   StringRef Filename = Entry->getName();
549   // If the file is already open, use the open file descriptor.
550   if (Entry->File) {
551     auto Result = Entry->File->getBuffer(Filename, FileSize,
552                                          RequiresNullTerminator, isVolatile);
553     Entry->closeFile();
554     return Result;
555   }
556 
557   // Otherwise, open the file.
558   return getBufferForFileImpl(Filename, FileSize, isVolatile,
559                               RequiresNullTerminator);
560 }
561 
562 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
563 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
564                                   bool isVolatile,
565                                   bool RequiresNullTerminator) {
566   if (FileSystemOpts.WorkingDir.empty())
567     return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
568                                 isVolatile);
569 
570   SmallString<128> FilePath(Filename);
571   FixupRelativePath(FilePath);
572   return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
573                               isVolatile);
574 }
575 
576 /// getStatValue - Get the 'stat' information for the specified path,
577 /// using the cache to accelerate it if possible.  This returns true
578 /// if the path points to a virtual file or does not exist, or returns
579 /// false if it's an existent real file.  If FileDescriptor is NULL,
580 /// do directory look-up instead of file look-up.
581 std::error_code
582 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
583                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
584   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
585   // absolute!
586   if (FileSystemOpts.WorkingDir.empty())
587     return FileSystemStatCache::get(Path, Status, isFile, F,
588                                     StatCache.get(), *FS);
589 
590   SmallString<128> FilePath(Path);
591   FixupRelativePath(FilePath);
592 
593   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
594                                   StatCache.get(), *FS);
595 }
596 
597 std::error_code
598 FileManager::getNoncachedStatValue(StringRef Path,
599                                    llvm::vfs::Status &Result) {
600   SmallString<128> FilePath(Path);
601   FixupRelativePath(FilePath);
602 
603   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
604   if (!S)
605     return S.getError();
606   Result = *S;
607   return std::error_code();
608 }
609 
610 void FileManager::GetUniqueIDMapping(
611     SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
612   UIDToFiles.clear();
613   UIDToFiles.resize(NextFileUID);
614 
615   // Map file entries
616   for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
617                        llvm::BumpPtrAllocator>::const_iterator
618            FE = SeenFileEntries.begin(),
619            FEEnd = SeenFileEntries.end();
620        FE != FEEnd; ++FE)
621     if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
622       if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
623         UIDToFiles[FE->getUID()] = FE;
624     }
625 
626   // Map virtual file entries
627   for (const auto &VFE : VirtualFileEntries)
628     UIDToFiles[VFE->getUID()] = VFE;
629 }
630 
631 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
632   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
633     = CanonicalNames.find(Dir);
634   if (Known != CanonicalNames.end())
635     return Known->second;
636 
637   StringRef CanonicalName(Dir->getName());
638 
639   SmallString<4096> CanonicalNameBuf;
640   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
641     CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
642 
643   CanonicalNames.insert({Dir, CanonicalName});
644   return CanonicalName;
645 }
646 
647 StringRef FileManager::getCanonicalName(const FileEntry *File) {
648   llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
649     = CanonicalNames.find(File);
650   if (Known != CanonicalNames.end())
651     return Known->second;
652 
653   StringRef CanonicalName(File->getName());
654 
655   SmallString<4096> CanonicalNameBuf;
656   if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
657     CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
658 
659   CanonicalNames.insert({File, CanonicalName});
660   return CanonicalName;
661 }
662 
663 void FileManager::PrintStats() const {
664   llvm::errs() << "\n*** File Manager Stats:\n";
665   llvm::errs() << UniqueRealFiles.size() << " real files found, "
666                << UniqueRealDirs.size() << " real dirs found.\n";
667   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
668                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
669   llvm::errs() << NumDirLookups << " dir lookups, "
670                << NumDirCacheMisses << " dir cache misses.\n";
671   llvm::errs() << NumFileLookups << " file lookups, "
672                << NumFileCacheMisses << " file cache misses.\n";
673 
674   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
675 }
676