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