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