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
FileManager(const FileSystemOptions & FSO,IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)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
setStatCache(std::unique_ptr<FileSystemStatCache> statCache)63 void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64 assert(statCache && "No stat cache provided?");
65 StatCache = std::move(statCache);
66 }
67
clearStatCache()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>
getDirectoryFromFile(FileManager & FileMgr,StringRef Filename,bool CacheFailure)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.
addAncestorsAsVirtualDirs(StringRef Path)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>
getDirectoryRef(StringRef DirName,bool CacheFailure)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 #ifdef _WIN32
127 // Fixing a problem with "clang C:test.c" on Windows.
128 // Stat("C:") does not recognize "C:" as a valid directory
129 std::string DirNameStr;
130 if (DirName.size() > 1 && DirName.back() == ':' &&
131 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
132 DirNameStr = DirName.str() + '.';
133 DirName = DirNameStr;
134 }
135 #endif
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 *>
getDirectory(StringRef DirName,bool CacheFailure)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 *>
getFile(StringRef Filename,bool openFile,bool CacheFailure)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>
getFileRef(StringRef Filename,bool openFile,bool CacheFailure)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 if (Status.getName() == Filename) {
274 // The name matches. Set the FileEntry.
275 NamedFileEnt->second = FileEntryRef::MapValue(UFE, DirInfo);
276 } else {
277 // Name mismatch. We need a redirect. First grab the actual entry we want
278 // to return.
279 auto &Redirection =
280 *SeenFileEntries
281 .insert({Status.getName(), FileEntryRef::MapValue(UFE, DirInfo)})
282 .first;
283 assert(Redirection.second->V.is<FileEntry *>() &&
284 "filename redirected to a non-canonical filename?");
285 assert(Redirection.second->V.get<FileEntry *>() == &UFE &&
286 "filename from getStatValue() refers to wrong file");
287
288 // Cache the redirection in the previously-inserted entry, still available
289 // in the tentative return value.
290 NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
291
292 // Fix the tentative return value.
293 NamedFileEnt = &Redirection;
294 }
295
296 FileEntryRef ReturnedRef(*NamedFileEnt);
297 if (UFE.isValid()) { // Already have an entry with this inode, return it.
298
299 // FIXME: this hack ensures that if we look up a file by a virtual path in
300 // the VFS that the getDir() will have the virtual path, even if we found
301 // the file by a 'real' path first. This is required in order to find a
302 // module's structure when its headers/module map are mapped in the VFS.
303 // We should remove this as soon as we can properly support a file having
304 // multiple names.
305 if (&DirInfo.getDirEntry() != UFE.Dir && Status.IsVFSMapped)
306 UFE.Dir = &DirInfo.getDirEntry();
307
308 // Always update LastRef to the last name by which a file was accessed.
309 // FIXME: Neither this nor always using the first reference is correct; we
310 // want to switch towards a design where we return a FileName object that
311 // encapsulates both the name by which the file was accessed and the
312 // corresponding FileEntry.
313 // FIXME: LastRef should be removed from FileEntry once all clients adopt
314 // FileEntryRef.
315 UFE.LastRef = ReturnedRef;
316
317 return ReturnedRef;
318 }
319
320 // Otherwise, we don't have this file yet, add it.
321 UFE.LastRef = ReturnedRef;
322 UFE.Size = Status.getSize();
323 UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
324 UFE.Dir = &DirInfo.getDirEntry();
325 UFE.UID = NextFileUID++;
326 UFE.UniqueID = Status.getUniqueID();
327 UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
328 UFE.File = std::move(F);
329 UFE.IsValid = true;
330
331 if (UFE.File) {
332 if (auto PathName = UFE.File->getName())
333 fillRealPathName(&UFE, *PathName);
334 } else if (!openFile) {
335 // We should still fill the path even if we aren't opening the file.
336 fillRealPathName(&UFE, InterndFileName);
337 }
338 return ReturnedRef;
339 }
340
getVirtualFile(StringRef Filename,off_t Size,time_t ModificationTime)341 const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
342 time_t ModificationTime) {
343 return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
344 }
345
getVirtualFileRef(StringRef Filename,off_t Size,time_t ModificationTime)346 FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
347 time_t ModificationTime) {
348 ++NumFileLookups;
349
350 // See if there is already an entry in the map for an existing file.
351 auto &NamedFileEnt = *SeenFileEntries.insert(
352 {Filename, std::errc::no_such_file_or_directory}).first;
353 if (NamedFileEnt.second) {
354 FileEntryRef::MapValue Value = *NamedFileEnt.second;
355 if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
356 return FileEntryRef(NamedFileEnt);
357 return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
358 Value.V.get<const void *>()));
359 }
360
361 // We've not seen this before, or the file is cached as non-existent.
362 ++NumFileCacheMisses;
363 addAncestorsAsVirtualDirs(Filename);
364 FileEntry *UFE = nullptr;
365
366 // Now that all ancestors of Filename are in the cache, the
367 // following call is guaranteed to find the DirectoryEntry from the
368 // cache.
369 auto DirInfo = expectedToOptional(
370 getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true));
371 assert(DirInfo &&
372 "The directory of a virtual file should already be in the cache.");
373
374 // Check to see if the file exists. If so, drop the virtual file
375 llvm::vfs::Status Status;
376 const char *InterndFileName = NamedFileEnt.first().data();
377 if (!getStatValue(InterndFileName, Status, true, nullptr)) {
378 UFE = &UniqueRealFiles[Status.getUniqueID()];
379 Status = llvm::vfs::Status(
380 Status.getName(), Status.getUniqueID(),
381 llvm::sys::toTimePoint(ModificationTime),
382 Status.getUser(), Status.getGroup(), Size,
383 Status.getType(), Status.getPermissions());
384
385 NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
386
387 // If we had already opened this file, close it now so we don't
388 // leak the descriptor. We're not going to use the file
389 // descriptor anyway, since this is a virtual file.
390 if (UFE->File)
391 UFE->closeFile();
392
393 // If we already have an entry with this inode, return it.
394 //
395 // FIXME: Surely this should add a reference by the new name, and return
396 // it instead...
397 if (UFE->isValid())
398 return FileEntryRef(NamedFileEnt);
399
400 UFE->UniqueID = Status.getUniqueID();
401 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
402 fillRealPathName(UFE, Status.getName());
403 } else {
404 VirtualFileEntries.push_back(std::make_unique<FileEntry>());
405 UFE = VirtualFileEntries.back().get();
406 NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
407 }
408
409 UFE->LastRef = FileEntryRef(NamedFileEnt);
410 UFE->Size = Size;
411 UFE->ModTime = ModificationTime;
412 UFE->Dir = &DirInfo->getDirEntry();
413 UFE->UID = NextFileUID++;
414 UFE->IsValid = true;
415 UFE->File.reset();
416 return FileEntryRef(NamedFileEnt);
417 }
418
getBypassFile(FileEntryRef VF)419 llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
420 // Stat of the file and return nullptr if it doesn't exist.
421 llvm::vfs::Status Status;
422 if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
423 return None;
424
425 if (!SeenBypassFileEntries)
426 SeenBypassFileEntries = std::make_unique<
427 llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
428
429 // If we've already bypassed just use the existing one.
430 auto Insertion = SeenBypassFileEntries->insert(
431 {VF.getName(), std::errc::no_such_file_or_directory});
432 if (!Insertion.second)
433 return FileEntryRef(*Insertion.first);
434
435 // Fill in the new entry from the stat.
436 BypassFileEntries.push_back(std::make_unique<FileEntry>());
437 const FileEntry &VFE = VF.getFileEntry();
438 FileEntry &BFE = *BypassFileEntries.back();
439 Insertion.first->second = FileEntryRef::MapValue(BFE, VF.getDir());
440 BFE.LastRef = FileEntryRef(*Insertion.first);
441 BFE.Size = Status.getSize();
442 BFE.Dir = VFE.Dir;
443 BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
444 BFE.UID = NextFileUID++;
445 BFE.IsValid = true;
446
447 // Save the entry in the bypass table and return.
448 return FileEntryRef(*Insertion.first);
449 }
450
FixupRelativePath(SmallVectorImpl<char> & path) const451 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
452 StringRef pathRef(path.data(), path.size());
453
454 if (FileSystemOpts.WorkingDir.empty()
455 || llvm::sys::path::is_absolute(pathRef))
456 return false;
457
458 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
459 llvm::sys::path::append(NewPath, pathRef);
460 path = NewPath;
461 return true;
462 }
463
makeAbsolutePath(SmallVectorImpl<char> & Path) const464 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
465 bool Changed = FixupRelativePath(Path);
466
467 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
468 FS->makeAbsolute(Path);
469 Changed = true;
470 }
471
472 return Changed;
473 }
474
fillRealPathName(FileEntry * UFE,llvm::StringRef FileName)475 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
476 llvm::SmallString<128> AbsPath(FileName);
477 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
478 // but can be very expensive on real file systems.
479 // FIXME: the semantic of RealPathName is unclear, and the name might be
480 // misleading. We need to clean up the interface here.
481 makeAbsolutePath(AbsPath);
482 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
483 UFE->RealPathName = std::string(AbsPath.str());
484 }
485
486 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBufferForFile(const FileEntry * Entry,bool isVolatile,bool RequiresNullTerminator)487 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
488 bool RequiresNullTerminator) {
489 uint64_t FileSize = Entry->getSize();
490 // If there's a high enough chance that the file have changed since we
491 // got its size, force a stat before opening it.
492 if (isVolatile)
493 FileSize = -1;
494
495 StringRef Filename = Entry->getName();
496 // If the file is already open, use the open file descriptor.
497 if (Entry->File) {
498 auto Result = Entry->File->getBuffer(Filename, FileSize,
499 RequiresNullTerminator, isVolatile);
500 Entry->closeFile();
501 return Result;
502 }
503
504 // Otherwise, open the file.
505 return getBufferForFileImpl(Filename, FileSize, isVolatile,
506 RequiresNullTerminator);
507 }
508
509 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBufferForFileImpl(StringRef Filename,int64_t FileSize,bool isVolatile,bool RequiresNullTerminator)510 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
511 bool isVolatile,
512 bool RequiresNullTerminator) {
513 if (FileSystemOpts.WorkingDir.empty())
514 return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
515 isVolatile);
516
517 SmallString<128> FilePath(Filename);
518 FixupRelativePath(FilePath);
519 return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
520 isVolatile);
521 }
522
523 /// getStatValue - Get the 'stat' information for the specified path,
524 /// using the cache to accelerate it if possible. This returns true
525 /// if the path points to a virtual file or does not exist, or returns
526 /// false if it's an existent real file. If FileDescriptor is NULL,
527 /// do directory look-up instead of file look-up.
528 std::error_code
getStatValue(StringRef Path,llvm::vfs::Status & Status,bool isFile,std::unique_ptr<llvm::vfs::File> * F)529 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
530 bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
531 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
532 // absolute!
533 if (FileSystemOpts.WorkingDir.empty())
534 return FileSystemStatCache::get(Path, Status, isFile, F,
535 StatCache.get(), *FS);
536
537 SmallString<128> FilePath(Path);
538 FixupRelativePath(FilePath);
539
540 return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
541 StatCache.get(), *FS);
542 }
543
544 std::error_code
getNoncachedStatValue(StringRef Path,llvm::vfs::Status & Result)545 FileManager::getNoncachedStatValue(StringRef Path,
546 llvm::vfs::Status &Result) {
547 SmallString<128> FilePath(Path);
548 FixupRelativePath(FilePath);
549
550 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
551 if (!S)
552 return S.getError();
553 Result = *S;
554 return std::error_code();
555 }
556
GetUniqueIDMapping(SmallVectorImpl<const FileEntry * > & UIDToFiles) const557 void FileManager::GetUniqueIDMapping(
558 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
559 UIDToFiles.clear();
560 UIDToFiles.resize(NextFileUID);
561
562 // Map file entries
563 for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
564 llvm::BumpPtrAllocator>::const_iterator
565 FE = SeenFileEntries.begin(),
566 FEEnd = SeenFileEntries.end();
567 FE != FEEnd; ++FE)
568 if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
569 if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
570 UIDToFiles[FE->getUID()] = FE;
571 }
572
573 // Map virtual file entries
574 for (const auto &VFE : VirtualFileEntries)
575 UIDToFiles[VFE->getUID()] = VFE.get();
576 }
577
getCanonicalName(const DirectoryEntry * Dir)578 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
579 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
580 = CanonicalNames.find(Dir);
581 if (Known != CanonicalNames.end())
582 return Known->second;
583
584 StringRef CanonicalName(Dir->getName());
585
586 SmallString<4096> CanonicalNameBuf;
587 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
588 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
589
590 CanonicalNames.insert({Dir, CanonicalName});
591 return CanonicalName;
592 }
593
getCanonicalName(const FileEntry * File)594 StringRef FileManager::getCanonicalName(const FileEntry *File) {
595 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
596 = CanonicalNames.find(File);
597 if (Known != CanonicalNames.end())
598 return Known->second;
599
600 StringRef CanonicalName(File->getName());
601
602 SmallString<4096> CanonicalNameBuf;
603 if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
604 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
605
606 CanonicalNames.insert({File, CanonicalName});
607 return CanonicalName;
608 }
609
PrintStats() const610 void FileManager::PrintStats() const {
611 llvm::errs() << "\n*** File Manager Stats:\n";
612 llvm::errs() << UniqueRealFiles.size() << " real files found, "
613 << UniqueRealDirs.size() << " real dirs found.\n";
614 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
615 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
616 llvm::errs() << NumDirLookups << " dir lookups, "
617 << NumDirCacheMisses << " dir cache misses.\n";
618 llvm::errs() << NumFileLookups << " file lookups, "
619 << NumFileCacheMisses << " file cache misses.\n";
620
621 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
622 }
623