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