1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the FileManager interface.
11 //===----------------------------------------------------------------------===//
13 // TODO: This should index all interesting directories with dirent calls.
15 // opendir/readdir_r/closedir ?
17 //===----------------------------------------------------------------------===//
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"
38 using namespace clang
;
40 #define DEBUG_TYPE "file-search"
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 FileManager::FileManager(const FileSystemOptions
&FSO
,
47 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
)
48 : FS(std::move(FS
)), FileSystemOpts(FSO
), SeenDirEntries(64),
49 SeenFileEntries(64), NextFileUID(0) {
50 // If the caller doesn't provide a virtual file system, just grab the real
53 this->FS
= llvm::vfs::getRealFileSystem();
56 FileManager::~FileManager() = default;
58 void FileManager::setStatCache(std::unique_ptr
<FileSystemStatCache
> statCache
) {
59 assert(statCache
&& "No stat cache provided?");
60 StatCache
= std::move(statCache
);
63 void FileManager::clearStatCache() { StatCache
.reset(); }
65 /// Retrieve the directory that the given file name resides in.
66 /// Filename can point to either a real file or a virtual file.
67 static llvm::Expected
<DirectoryEntryRef
>
68 getDirectoryFromFile(FileManager
&FileMgr
, StringRef Filename
,
71 return llvm::errorCodeToError(
72 make_error_code(std::errc::no_such_file_or_directory
));
74 if (llvm::sys::path::is_separator(Filename
[Filename
.size() - 1]))
75 return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory
));
77 StringRef DirName
= llvm::sys::path::parent_path(Filename
);
78 // Use the current directory if file has no path component.
82 return FileMgr
.getDirectoryRef(DirName
, CacheFailure
);
85 DirectoryEntry
*&FileManager::getRealDirEntry(const llvm::vfs::Status
&Status
) {
86 assert(Status
.isDirectory() && "The directory should exist!");
87 // See if we have already opened a directory with the
88 // same inode (this occurs on Unix-like systems when one dir is
89 // symlinked to another, for example) or the same path (on
91 DirectoryEntry
*&UDE
= UniqueRealDirs
[Status
.getUniqueID()];
94 // We don't have this directory yet, add it. We use the string
95 // key from the SeenDirEntries map as the string.
96 UDE
= new (DirsAlloc
.Allocate()) DirectoryEntry();
101 /// Add all ancestors of the given path (pointing to either a file or
102 /// a directory) as virtual directories.
103 void FileManager::addAncestorsAsVirtualDirs(StringRef Path
) {
104 StringRef DirName
= llvm::sys::path::parent_path(Path
);
108 auto &NamedDirEnt
= *SeenDirEntries
.insert(
109 {DirName
, std::errc::no_such_file_or_directory
}).first
;
111 // When caching a virtual directory, we always cache its ancestors
112 // at the same time. Therefore, if DirName is already in the cache,
113 // we don't need to recurse as its ancestors must also already be in
114 // the cache (or it's a known non-virtual directory).
115 if (NamedDirEnt
.second
)
118 // Check to see if the directory exists.
119 llvm::vfs::Status Status
;
121 getStatValue(DirName
, Status
, false, nullptr /*directory lookup*/);
123 // There's no real directory at the given path.
124 // Add the virtual directory to the cache.
125 auto *UDE
= new (DirsAlloc
.Allocate()) DirectoryEntry();
126 NamedDirEnt
.second
= *UDE
;
127 VirtualDirectoryEntries
.push_back(UDE
);
129 // There is the real directory
130 DirectoryEntry
*&UDE
= getRealDirEntry(Status
);
131 NamedDirEnt
.second
= *UDE
;
134 // Recursively add the other ancestors.
135 addAncestorsAsVirtualDirs(DirName
);
138 llvm::Expected
<DirectoryEntryRef
>
139 FileManager::getDirectoryRef(StringRef DirName
, bool CacheFailure
) {
140 // stat doesn't like trailing separators except for root directory.
141 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
142 // (though it can strip '\\')
143 if (DirName
.size() > 1 &&
144 DirName
!= llvm::sys::path::root_path(DirName
) &&
145 llvm::sys::path::is_separator(DirName
.back()))
146 DirName
= DirName
.substr(0, DirName
.size()-1);
147 std::optional
<std::string
> DirNameStr
;
148 if (is_style_windows(llvm::sys::path::Style::native
)) {
149 // Fixing a problem with "clang C:test.c" on Windows.
150 // Stat("C:") does not recognize "C:" as a valid directory
151 if (DirName
.size() > 1 && DirName
.back() == ':' &&
152 DirName
.equals_insensitive(llvm::sys::path::root_name(DirName
))) {
153 DirNameStr
= DirName
.str() + '.';
154 DirName
= *DirNameStr
;
160 // See if there was already an entry in the map. Note that the map
161 // contains both virtual and real directories.
162 auto SeenDirInsertResult
=
163 SeenDirEntries
.insert({DirName
, std::errc::no_such_file_or_directory
});
164 if (!SeenDirInsertResult
.second
) {
165 if (SeenDirInsertResult
.first
->second
)
166 return DirectoryEntryRef(*SeenDirInsertResult
.first
);
167 return llvm::errorCodeToError(SeenDirInsertResult
.first
->second
.getError());
170 // We've not seen this before. Fill it in.
172 auto &NamedDirEnt
= *SeenDirInsertResult
.first
;
173 assert(!NamedDirEnt
.second
&& "should be newly-created");
175 // Get the null-terminated directory name as stored as the key of the
176 // SeenDirEntries map.
177 StringRef InterndDirName
= NamedDirEnt
.first();
179 // Check to see if the directory exists.
180 llvm::vfs::Status Status
;
181 auto statError
= getStatValue(InterndDirName
, Status
, false,
182 nullptr /*directory lookup*/);
184 // There's no real directory at the given path.
186 NamedDirEnt
.second
= statError
;
188 SeenDirEntries
.erase(DirName
);
189 return llvm::errorCodeToError(statError
);
193 DirectoryEntry
*&UDE
= getRealDirEntry(Status
);
194 NamedDirEnt
.second
= *UDE
;
196 return DirectoryEntryRef(NamedDirEnt
);
199 llvm::ErrorOr
<const DirectoryEntry
*>
200 FileManager::getDirectory(StringRef DirName
, bool CacheFailure
) {
201 auto Result
= getDirectoryRef(DirName
, CacheFailure
);
203 return &Result
->getDirEntry();
204 return llvm::errorToErrorCode(Result
.takeError());
207 llvm::ErrorOr
<const FileEntry
*>
208 FileManager::getFile(StringRef Filename
, bool openFile
, bool CacheFailure
) {
209 auto Result
= getFileRef(Filename
, openFile
, CacheFailure
);
211 return &Result
->getFileEntry();
212 return llvm::errorToErrorCode(Result
.takeError());
215 llvm::Expected
<FileEntryRef
> FileManager::getFileRef(StringRef Filename
,
221 // See if there is already an entry in the map.
222 auto SeenFileInsertResult
=
223 SeenFileEntries
.insert({Filename
, std::errc::no_such_file_or_directory
});
224 if (!SeenFileInsertResult
.second
) {
225 if (!SeenFileInsertResult
.first
->second
)
226 return llvm::errorCodeToError(
227 SeenFileInsertResult
.first
->second
.getError());
228 return FileEntryRef(*SeenFileInsertResult
.first
);
231 // We've not seen this before. Fill it in.
232 ++NumFileCacheMisses
;
233 auto *NamedFileEnt
= &*SeenFileInsertResult
.first
;
234 assert(!NamedFileEnt
->second
&& "should be newly-created");
236 // Get the null-terminated file name as stored as the key of the
237 // SeenFileEntries map.
238 StringRef InterndFileName
= NamedFileEnt
->first();
240 // Look up the directory for the file. When looking up something like
241 // sys/foo.h we'll discover all of the search directories that have a 'sys'
242 // subdirectory. This will let us avoid having to waste time on known-to-fail
243 // searches when we go to find sys/bar.h, because all the search directories
244 // without a 'sys' subdir will get a cached failure result.
245 auto DirInfoOrErr
= getDirectoryFromFile(*this, Filename
, CacheFailure
);
246 if (!DirInfoOrErr
) { // Directory doesn't exist, file can't exist.
247 std::error_code Err
= errorToErrorCode(DirInfoOrErr
.takeError());
249 NamedFileEnt
->second
= Err
;
251 SeenFileEntries
.erase(Filename
);
253 return llvm::errorCodeToError(Err
);
255 DirectoryEntryRef DirInfo
= *DirInfoOrErr
;
257 // FIXME: Use the directory info to prune this, before doing the stat syscall.
258 // FIXME: This will reduce the # syscalls.
260 // Check to see if the file exists.
261 std::unique_ptr
<llvm::vfs::File
> F
;
262 llvm::vfs::Status Status
;
263 auto statError
= getStatValue(InterndFileName
, Status
, true,
264 openFile
? &F
: nullptr, IsText
);
266 // There's no real file at the given path.
268 NamedFileEnt
->second
= statError
;
270 SeenFileEntries
.erase(Filename
);
272 return llvm::errorCodeToError(statError
);
275 assert((openFile
|| !F
) && "undesired open file");
277 // It exists. See if we have already opened a file with the same inode.
278 // This occurs when one dir is symlinked to another, for example.
279 FileEntry
*&UFE
= UniqueRealFiles
[Status
.getUniqueID()];
280 bool ReusingEntry
= UFE
!= nullptr;
282 UFE
= new (FilesAlloc
.Allocate()) FileEntry();
284 if (!Status
.ExposesExternalVFSPath
|| Status
.getName() == Filename
) {
285 // Use the requested name. Set the FileEntry.
286 NamedFileEnt
->second
= FileEntryRef::MapValue(*UFE
, DirInfo
);
288 // Name mismatch. We need a redirect. First grab the actual entry we want
291 // This redirection logic intentionally leaks the external name of a
292 // redirected file that uses 'use-external-name' in \a
293 // vfs::RedirectionFileSystem. This allows clang to report the external
294 // name to users (in diagnostics) and to tools that don't have access to
295 // the VFS (in debug info and dependency '.d' files).
297 // FIXME: This is pretty complex and has some very complicated interactions
298 // with the rest of clang. It's also inconsistent with how "real"
299 // filesystems behave and confuses parts of clang expect to see the
300 // name-as-accessed on the \a FileEntryRef.
302 // A potential plan to remove this is as follows -
303 // - Update callers such as `HeaderSearch::findUsableModuleForHeader()`
304 // to explicitly use the `getNameAsRequested()` rather than just using
306 // - Add a `FileManager::getExternalPath` API for explicitly getting the
307 // remapped external filename when there is one available. Adopt it in
308 // callers like diagnostics/deps reporting instead of calling
309 // `getName()` directly.
310 // - Switch the meaning of `FileEntryRef::getName()` to get the requested
311 // name, not the external name. Once that sticks, revert callers that
312 // want the requested name back to calling `getName()`.
313 // - Update the VFS to always return the requested name. This could also
314 // return the external name, or just have an API to request it
315 // lazily. The latter has the benefit of making accesses of the
316 // external path easily tracked, but may also require extra work than
317 // just returning up front.
318 // - (Optionally) Add an API to VFS to get the external filename lazily
319 // and update `FileManager::getExternalPath()` to use it instead. This
320 // has the benefit of making such accesses easily tracked, though isn't
321 // necessarily required (and could cause extra work than just adding to
322 // eg. `vfs::Status` up front).
325 .insert({Status
.getName(), FileEntryRef::MapValue(*UFE
, DirInfo
)})
327 assert(Redirection
.second
->V
.is
<FileEntry
*>() &&
328 "filename redirected to a non-canonical filename?");
329 assert(Redirection
.second
->V
.get
<FileEntry
*>() == UFE
&&
330 "filename from getStatValue() refers to wrong file");
332 // Cache the redirection in the previously-inserted entry, still available
333 // in the tentative return value.
334 NamedFileEnt
->second
= FileEntryRef::MapValue(Redirection
, DirInfo
);
337 FileEntryRef
ReturnedRef(*NamedFileEnt
);
338 if (ReusingEntry
) { // Already have an entry with this inode, return it.
342 // Otherwise, we don't have this file yet, add it.
343 UFE
->Size
= Status
.getSize();
344 UFE
->ModTime
= llvm::sys::toTimeT(Status
.getLastModificationTime());
345 UFE
->Dir
= &DirInfo
.getDirEntry();
346 UFE
->UID
= NextFileUID
++;
347 UFE
->UniqueID
= Status
.getUniqueID();
348 UFE
->IsNamedPipe
= Status
.getType() == llvm::sys::fs::file_type::fifo_file
;
349 UFE
->File
= std::move(F
);
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
);
361 llvm::Expected
<FileEntryRef
> FileManager::getSTDIN() {
362 // Only read stdin once.
366 std::unique_ptr
<llvm::MemoryBuffer
> Content
;
367 if (auto ContentOrError
= llvm::MemoryBuffer::getSTDIN())
368 Content
= std::move(*ContentOrError
);
370 return llvm::errorCodeToError(ContentOrError
.getError());
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;
380 void FileManager::trackVFSUsage(bool Active
) {
381 FS
->visit([Active
](llvm::vfs::FileSystem
&FileSys
) {
382 if (auto *RFS
= dyn_cast
<llvm::vfs::RedirectingFileSystem
>(&FileSys
))
383 RFS
->setUsageTrackingActive(Active
);
387 const FileEntry
*FileManager::getVirtualFile(StringRef Filename
, off_t Size
,
388 time_t ModificationTime
) {
389 return &getVirtualFileRef(Filename
, Size
, ModificationTime
).getFileEntry();
392 FileEntryRef
FileManager::getVirtualFileRef(StringRef Filename
, off_t Size
,
393 time_t ModificationTime
) {
396 // See if there is already an entry in the map for an existing file.
397 auto &NamedFileEnt
= *SeenFileEntries
.insert(
398 {Filename
, std::errc::no_such_file_or_directory
}).first
;
399 if (NamedFileEnt
.second
) {
400 FileEntryRef::MapValue Value
= *NamedFileEnt
.second
;
401 if (LLVM_LIKELY(Value
.V
.is
<FileEntry
*>()))
402 return FileEntryRef(NamedFileEnt
);
403 return FileEntryRef(*Value
.V
.get
<const FileEntryRef::MapEntry
*>());
406 // We've not seen this before, or the file is cached as non-existent.
407 ++NumFileCacheMisses
;
408 addAncestorsAsVirtualDirs(Filename
);
409 FileEntry
*UFE
= nullptr;
411 // Now that all ancestors of Filename are in the cache, the
412 // following call is guaranteed to find the DirectoryEntry from the
413 // cache. A virtual file can also have an empty filename, that could come
414 // from a source location preprocessor directive with an empty filename as
415 // an example, so we need to pretend it has a name to ensure a valid directory
416 // entry can be returned.
417 auto DirInfo
= expectedToOptional(getDirectoryFromFile(
418 *this, Filename
.empty() ? "." : Filename
, /*CacheFailure=*/true));
420 "The directory of a virtual file should already be in the cache.");
422 // Check to see if the file exists. If so, drop the virtual file
423 llvm::vfs::Status Status
;
424 const char *InterndFileName
= NamedFileEnt
.first().data();
425 if (!getStatValue(InterndFileName
, Status
, true, nullptr)) {
426 Status
= llvm::vfs::Status(
427 Status
.getName(), Status
.getUniqueID(),
428 llvm::sys::toTimePoint(ModificationTime
),
429 Status
.getUser(), Status
.getGroup(), Size
,
430 Status
.getType(), Status
.getPermissions());
432 auto &RealFE
= UniqueRealFiles
[Status
.getUniqueID()];
434 // If we had already opened this file, close it now so we don't
435 // leak the descriptor. We're not going to use the file
436 // descriptor anyway, since this is a virtual file.
439 // If we already have an entry with this inode, return it.
441 // FIXME: Surely this should add a reference by the new name, and return
443 NamedFileEnt
.second
= FileEntryRef::MapValue(*RealFE
, *DirInfo
);
444 return FileEntryRef(NamedFileEnt
);
446 // File exists, but no entry - create it.
447 RealFE
= new (FilesAlloc
.Allocate()) FileEntry();
448 RealFE
->UniqueID
= Status
.getUniqueID();
449 RealFE
->IsNamedPipe
=
450 Status
.getType() == llvm::sys::fs::file_type::fifo_file
;
451 fillRealPathName(RealFE
, Status
.getName());
455 // File does not exist, create a virtual entry.
456 UFE
= new (FilesAlloc
.Allocate()) FileEntry();
457 VirtualFileEntries
.push_back(UFE
);
460 NamedFileEnt
.second
= FileEntryRef::MapValue(*UFE
, *DirInfo
);
462 UFE
->ModTime
= ModificationTime
;
463 UFE
->Dir
= &DirInfo
->getDirEntry();
464 UFE
->UID
= NextFileUID
++;
466 return FileEntryRef(NamedFileEnt
);
469 OptionalFileEntryRef
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))
475 if (!SeenBypassFileEntries
)
476 SeenBypassFileEntries
= std::make_unique
<
477 llvm::StringMap
<llvm::ErrorOr
<FileEntryRef::MapValue
>>>();
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
);
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
->Size
= Status
.getSize();
490 BFE
->Dir
= VF
.getFileEntry().Dir
;
491 BFE
->ModTime
= llvm::sys::toTimeT(Status
.getLastModificationTime());
492 BFE
->UID
= NextFileUID
++;
494 // Save the entry in the bypass table and return.
495 return FileEntryRef(*Insertion
.first
);
498 bool FileManager::FixupRelativePath(SmallVectorImpl
<char> &path
) const {
499 StringRef
pathRef(path
.data(), path
.size());
501 if (FileSystemOpts
.WorkingDir
.empty()
502 || llvm::sys::path::is_absolute(pathRef
))
505 SmallString
<128> NewPath(FileSystemOpts
.WorkingDir
);
506 llvm::sys::path::append(NewPath
, pathRef
);
511 bool FileManager::makeAbsolutePath(SmallVectorImpl
<char> &Path
) const {
512 bool Changed
= FixupRelativePath(Path
);
514 if (!llvm::sys::path::is_absolute(StringRef(Path
.data(), Path
.size()))) {
515 FS
->makeAbsolute(Path
);
522 void FileManager::fillRealPathName(FileEntry
*UFE
, llvm::StringRef FileName
) {
523 llvm::SmallString
<128> AbsPath(FileName
);
524 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
525 // but can be very expensive on real file systems.
526 // FIXME: the semantic of RealPathName is unclear, and the name might be
527 // misleading. We need to clean up the interface here.
528 makeAbsolutePath(AbsPath
);
529 llvm::sys::path::remove_dots(AbsPath
, /*remove_dot_dot=*/true);
530 UFE
->RealPathName
= std::string(AbsPath
);
533 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>>
534 FileManager::getBufferForFile(FileEntryRef FE
, bool isVolatile
,
535 bool RequiresNullTerminator
,
536 std::optional
<int64_t> MaybeLimit
, bool IsText
) {
537 const FileEntry
*Entry
= &FE
.getFileEntry();
538 // If the content is living on the file entry, return a reference to it.
540 return llvm::MemoryBuffer::getMemBuffer(Entry
->Content
->getMemBufferRef());
542 uint64_t FileSize
= Entry
->getSize();
545 FileSize
= *MaybeLimit
;
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())
552 StringRef Filename
= FE
.getName();
553 // If the file is already open, use the open file descriptor.
555 auto Result
= Entry
->File
->getBuffer(Filename
, FileSize
,
556 RequiresNullTerminator
, isVolatile
);
561 // Otherwise, open the file.
562 return getBufferForFileImpl(Filename
, FileSize
, isVolatile
,
563 RequiresNullTerminator
, IsText
);
566 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>>
567 FileManager::getBufferForFileImpl(StringRef Filename
, int64_t FileSize
,
568 bool isVolatile
, bool RequiresNullTerminator
,
570 if (FileSystemOpts
.WorkingDir
.empty())
571 return FS
->getBufferForFile(Filename
, FileSize
, RequiresNullTerminator
,
574 SmallString
<128> FilePath(Filename
);
575 FixupRelativePath(FilePath
);
576 return FS
->getBufferForFile(FilePath
, FileSize
, RequiresNullTerminator
,
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
FileManager::getStatValue(StringRef Path
,
586 llvm::vfs::Status
&Status
,
588 std::unique_ptr
<llvm::vfs::File
> *F
,
590 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
592 if (FileSystemOpts
.WorkingDir
.empty())
593 return FileSystemStatCache::get(Path
, Status
, isFile
, F
, StatCache
.get(),
596 SmallString
<128> FilePath(Path
);
597 FixupRelativePath(FilePath
);
599 return FileSystemStatCache::get(FilePath
.c_str(), Status
, isFile
, F
,
600 StatCache
.get(), *FS
, IsText
);
604 FileManager::getNoncachedStatValue(StringRef Path
,
605 llvm::vfs::Status
&Result
) {
606 SmallString
<128> FilePath(Path
);
607 FixupRelativePath(FilePath
);
609 llvm::ErrorOr
<llvm::vfs::Status
> S
= FS
->status(FilePath
.c_str());
613 return std::error_code();
616 void FileManager::GetUniqueIDMapping(
617 SmallVectorImpl
<OptionalFileEntryRef
> &UIDToFiles
) const {
619 UIDToFiles
.resize(NextFileUID
);
621 for (const auto &Entry
: SeenFileEntries
) {
622 // Only return files that exist and are not redirected.
623 if (!Entry
.getValue() || !Entry
.getValue()->V
.is
<FileEntry
*>())
625 FileEntryRef
FE(Entry
);
626 // Add this file if it's the first one with the UID, or if its name is
627 // better than the existing one.
628 OptionalFileEntryRef
&ExistingFE
= UIDToFiles
[FE
.getUID()];
629 if (!ExistingFE
|| FE
.getName() < ExistingFE
->getName())
634 StringRef
FileManager::getCanonicalName(DirectoryEntryRef Dir
) {
635 return getCanonicalName(Dir
, Dir
.getName());
638 StringRef
FileManager::getCanonicalName(FileEntryRef File
) {
639 return getCanonicalName(File
, File
.getName());
642 StringRef
FileManager::getCanonicalName(const void *Entry
, StringRef Name
) {
643 llvm::DenseMap
<const void *, llvm::StringRef
>::iterator Known
=
644 CanonicalNames
.find(Entry
);
645 if (Known
!= CanonicalNames
.end())
646 return Known
->second
;
648 // Name comes from FileEntry/DirectoryEntry::getName(), so it is safe to
649 // store it in the DenseMap below.
650 StringRef
CanonicalName(Name
);
652 SmallString
<256> AbsPathBuf
;
653 SmallString
<256> RealPathBuf
;
654 if (!FS
->getRealPath(Name
, RealPathBuf
)) {
655 if (is_style_windows(llvm::sys::path::Style::native
)) {
656 // For Windows paths, only use the real path if it doesn't resolve
657 // a substitute drive, as those are used to avoid MAX_PATH issues.
659 if (!FS
->makeAbsolute(AbsPathBuf
)) {
660 if (llvm::sys::path::root_name(RealPathBuf
) ==
661 llvm::sys::path::root_name(AbsPathBuf
)) {
662 CanonicalName
= RealPathBuf
.str().copy(CanonicalNameStorage
);
664 // Fallback to using the absolute path.
665 // Simplifying /../ is semantically valid on Windows even in the
666 // presence of symbolic links.
667 llvm::sys::path::remove_dots(AbsPathBuf
, /*remove_dot_dot=*/true);
668 CanonicalName
= AbsPathBuf
.str().copy(CanonicalNameStorage
);
672 CanonicalName
= RealPathBuf
.str().copy(CanonicalNameStorage
);
676 CanonicalNames
.insert({Entry
, CanonicalName
});
677 return CanonicalName
;
680 void FileManager::AddStats(const FileManager
&Other
) {
681 assert(&Other
!= this && "Collecting stats into the same FileManager");
682 NumDirLookups
+= Other
.NumDirLookups
;
683 NumFileLookups
+= Other
.NumFileLookups
;
684 NumDirCacheMisses
+= Other
.NumDirCacheMisses
;
685 NumFileCacheMisses
+= Other
.NumFileCacheMisses
;
688 void FileManager::PrintStats() const {
689 llvm::errs() << "\n*** File Manager Stats:\n";
690 llvm::errs() << UniqueRealFiles
.size() << " real files found, "
691 << UniqueRealDirs
.size() << " real dirs found.\n";
692 llvm::errs() << VirtualFileEntries
.size() << " virtual files found, "
693 << VirtualDirectoryEntries
.size() << " virtual dirs found.\n";
694 llvm::errs() << NumDirLookups
<< " dir lookups, "
695 << NumDirCacheMisses
<< " dir cache misses.\n";
696 llvm::errs() << NumFileLookups
<< " file lookups, "
697 << NumFileCacheMisses
<< " file cache misses.\n";
699 getVirtualFileSystem().visit([](llvm::vfs::FileSystem
&VFS
) {
700 if (auto *T
= dyn_cast_or_null
<llvm::vfs::TracingFileSystem
>(&VFS
))
701 llvm::errs() << "\n*** Virtual File System Stats:\n"
702 << T
->NumStatusCalls
<< " status() calls\n"
703 << T
->NumOpenFileForReadCalls
<< " openFileForRead() calls\n"
704 << T
->NumDirBeginCalls
<< " dir_begin() calls\n"
705 << T
->NumGetRealPathCalls
<< " getRealPath() calls\n"
706 << T
->NumExistsCalls
<< " exists() calls\n"
707 << T
->NumIsLocalCalls
<< " isLocal() calls\n";
710 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;