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