1//===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
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 VirtualFileSystem interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Support/VirtualFileSystem.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/IntrusiveRefCntPtr.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/StringSet.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Config/llvm-config.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/Chrono.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/Errc.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/ErrorOr.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/FileSystem/UniqueID.h"
34#include "llvm/Support/IOSandbox.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/SMLoc.h"
38#include "llvm/Support/SourceMgr.h"
39#include "llvm/Support/YAMLParser.h"
40#include "llvm/Support/raw_ostream.h"
41#include <atomic>
42#include <cassert>
43#include <cstdint>
44#include <iterator>
45#include <limits>
46#include <map>
47#include <memory>
48#include <optional>
49#include <string>
50#include <system_error>
51#include <utility>
52#include <vector>
53
54using namespace llvm;
55using namespace llvm::vfs;
56
57using llvm::sys::fs::file_t;
58using llvm::sys::fs::file_status;
59using llvm::sys::fs::file_type;
60using llvm::sys::fs::kInvalidFile;
61using llvm::sys::fs::perms;
62using llvm::sys::fs::UniqueID;
63
64Status::Status(const file_status &Status)
65 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
66 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
67 Type(Status.type()), Perms(Status.permissions()) {}
68
69Status::Status(const Twine &Name, UniqueID UID, sys::TimePoint<> MTime,
70 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
71 perms Perms)
72 : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
73 Size(Size), Type(Type), Perms(Perms) {}
74
75Status Status::copyWithNewSize(const Status &In, uint64_t NewSize) {
76 return Status(In.getName(), In.getUniqueID(), In.getLastModificationTime(),
77 In.getUser(), In.getGroup(), NewSize, In.getType(),
78 In.getPermissions());
79}
80
81Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
82 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
83 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
84 In.getPermissions());
85}
86
87Status Status::copyWithNewName(const file_status &In, const Twine &NewName) {
88 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
89 In.getUser(), In.getGroup(), In.getSize(), In.type(),
90 In.permissions());
91}
92
93bool Status::equivalent(const Status &Other) const {
94 assert(isStatusKnown() && Other.isStatusKnown());
95 return getUniqueID() == Other.getUniqueID();
96}
97
98bool Status::isDirectory() const { return Type == file_type::directory_file; }
99
100bool Status::isRegularFile() const { return Type == file_type::regular_file; }
101
102bool Status::isOther() const {
103 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
104}
105
106bool Status::isSymlink() const { return Type == file_type::symlink_file; }
107
108bool Status::isStatusKnown() const { return Type != file_type::status_error; }
109
110bool Status::exists() const {
111 return isStatusKnown() && Type != file_type::file_not_found;
112}
113
114File::~File() = default;
115
116FileSystem::~FileSystem() = default;
117
118ErrorOr<std::unique_ptr<MemoryBuffer>>
119FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
120 bool RequiresNullTerminator, bool IsVolatile,
121 bool IsText) {
122 auto F = IsText ? openFileForRead(Path: Name) : openFileForReadBinary(Path: Name);
123 if (!F)
124 return F.getError();
125
126 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
127}
128
129std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
130 if (llvm::sys::path::is_absolute(path: Path))
131 return {};
132
133 auto WorkingDir = getCurrentWorkingDirectory();
134 if (!WorkingDir)
135 return WorkingDir.getError();
136
137 sys::path::make_absolute(current_directory: WorkingDir.get(), path&: Path);
138 return {};
139}
140
141std::error_code FileSystem::getRealPath(const Twine &Path,
142 SmallVectorImpl<char> &Output) {
143 return errc::operation_not_permitted;
144}
145
146std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
147 return errc::operation_not_permitted;
148}
149
150bool FileSystem::exists(const Twine &Path) {
151 auto Status = status(Path);
152 return Status && Status->exists();
153}
154
155llvm::ErrorOr<bool> FileSystem::equivalent(const Twine &A, const Twine &B) {
156 auto StatusA = status(Path: A);
157 if (!StatusA)
158 return StatusA.getError();
159 auto StatusB = status(Path: B);
160 if (!StatusB)
161 return StatusB.getError();
162 return StatusA->equivalent(Other: *StatusB);
163}
164
165#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
166void FileSystem::dump() const { print(dbgs(), PrintType::RecursiveContents); }
167#endif
168
169#ifndef NDEBUG
170static bool isTraversalComponent(StringRef Component) {
171 return Component == ".." || Component == ".";
172}
173
174static bool pathHasTraversal(StringRef Path) {
175 using namespace llvm::sys;
176
177 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
178 if (isTraversalComponent(Comp))
179 return true;
180 return false;
181}
182#endif
183
184//===-----------------------------------------------------------------------===/
185// RealFileSystem implementation
186//===-----------------------------------------------------------------------===/
187
188namespace {
189
190/// Wrapper around a raw file descriptor.
191class RealFile : public File {
192 friend class RealFileSystem;
193
194 file_t FD;
195 Status S;
196 std::string RealName;
197
198 RealFile(file_t RawFD, StringRef NewName, StringRef NewRealPathName)
199 : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
200 llvm::sys::fs::file_type::status_error, {}),
201 RealName(NewRealPathName.str()) {
202 assert(FD != kInvalidFile && "Invalid or inactive file descriptor");
203 }
204
205public:
206 ~RealFile() override;
207
208 ErrorOr<Status> status() override;
209 ErrorOr<std::string> getName() override;
210 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
211 int64_t FileSize,
212 bool RequiresNullTerminator,
213 bool IsVolatile) override;
214 std::error_code close() override;
215 void setPath(const Twine &Path) override;
216};
217
218} // namespace
219
220RealFile::~RealFile() { close(); }
221
222ErrorOr<Status> RealFile::status() {
223 auto BypassSandbox = sys::sandbox::scopedDisable();
224
225 assert(FD != kInvalidFile && "cannot stat closed file");
226 if (!S.isStatusKnown()) {
227 file_status RealStatus;
228 if (std::error_code EC = sys::fs::status(FD, Result&: RealStatus))
229 return EC;
230 S = Status::copyWithNewName(In: RealStatus, NewName: S.getName());
231 }
232 return S;
233}
234
235ErrorOr<std::string> RealFile::getName() {
236 return RealName.empty() ? S.getName().str() : RealName;
237}
238
239ErrorOr<std::unique_ptr<MemoryBuffer>>
240RealFile::getBuffer(const Twine &Name, int64_t FileSize,
241 bool RequiresNullTerminator, bool IsVolatile) {
242 auto BypassSandbox = sys::sandbox::scopedDisable();
243
244 assert(FD != kInvalidFile && "cannot get buffer for closed file");
245 return MemoryBuffer::getOpenFile(FD, Filename: Name, FileSize, RequiresNullTerminator,
246 IsVolatile);
247}
248
249std::error_code RealFile::close() {
250 auto BypassSandbox = sys::sandbox::scopedDisable();
251
252 std::error_code EC = sys::fs::closeFile(F&: FD);
253 FD = kInvalidFile;
254 return EC;
255}
256
257void RealFile::setPath(const Twine &Path) {
258 auto BypassSandbox = sys::sandbox::scopedDisable();
259
260 RealName = Path.str();
261 if (auto Status = status())
262 S = Status.get().copyWithNewName(In: Status.get(), NewName: Path);
263}
264
265namespace {
266
267/// A file system according to your operating system.
268/// This may be linked to the process's working directory, or maintain its own.
269///
270/// Currently, its own working directory is emulated by storing the path and
271/// sending absolute paths to llvm::sys::fs:: functions.
272/// A more principled approach would be to push this down a level, modelling
273/// the working dir as an llvm::sys::fs::WorkingDir or similar.
274/// This would enable the use of openat()-style functions on some platforms.
275class RealFileSystem : public FileSystem {
276public:
277 explicit RealFileSystem(bool LinkCWDToProcess) {
278 if (!LinkCWDToProcess) {
279 SmallString<128> PWD, RealPWD;
280 if (std::error_code EC = llvm::sys::fs::current_path(result&: PWD))
281 WD = EC;
282 else if (llvm::sys::fs::real_path(path: PWD, output&: RealPWD))
283 WD = WorkingDirectory{.Specified: PWD, .Resolved: PWD};
284 else
285 WD = WorkingDirectory{.Specified: PWD, .Resolved: RealPWD};
286 }
287 }
288
289 ErrorOr<Status> status(const Twine &Path) override;
290 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
291 ErrorOr<std::unique_ptr<File>>
292 openFileForReadBinary(const Twine &Path) override;
293 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
294
295 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
296 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
297 std::error_code isLocal(const Twine &Path, bool &Result) override;
298 std::error_code getRealPath(const Twine &Path,
299 SmallVectorImpl<char> &Output) override;
300
301protected:
302 void printImpl(raw_ostream &OS, PrintType Type,
303 unsigned IndentLevel) const override;
304
305private:
306 // If this FS has its own working dir, use it to make Path absolute.
307 // The returned twine is safe to use as long as both Storage and Path live.
308 Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const {
309 if (!WD || !*WD)
310 return Path;
311 Path.toVector(Out&: Storage);
312 sys::path::make_absolute(current_directory: WD->get().Resolved, path&: Storage);
313 return Storage;
314 }
315
316 ErrorOr<std::unique_ptr<File>>
317 openFileForReadWithFlags(const Twine &Name, sys::fs::OpenFlags Flags) {
318 SmallString<256> RealName, Storage;
319 Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead(
320 Name: adjustPath(Path: Name, Storage), Flags, RealPath: &RealName);
321 if (!FDOrErr)
322 return errorToErrorCode(Err: FDOrErr.takeError());
323 return std::unique_ptr<File>(
324 new RealFile(*FDOrErr, Name.str(), RealName.str()));
325 }
326
327 struct WorkingDirectory {
328 // The current working directory, without symlinks resolved. (echo $PWD).
329 SmallString<128> Specified;
330 // The current working directory, with links resolved. (readlink .).
331 SmallString<128> Resolved;
332 };
333 std::optional<llvm::ErrorOr<WorkingDirectory>> WD;
334};
335
336} // namespace
337
338ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
339 auto BypassSandbox = sys::sandbox::scopedDisable();
340
341 SmallString<256> Storage;
342 sys::fs::file_status RealStatus;
343 if (std::error_code EC =
344 sys::fs::status(path: adjustPath(Path, Storage), result&: RealStatus))
345 return EC;
346 return Status::copyWithNewName(In: RealStatus, NewName: Path);
347}
348
349ErrorOr<std::unique_ptr<File>>
350RealFileSystem::openFileForRead(const Twine &Name) {
351 auto BypassSandbox = sys::sandbox::scopedDisable();
352
353 return openFileForReadWithFlags(Name, Flags: sys::fs::OF_Text);
354}
355
356ErrorOr<std::unique_ptr<File>>
357RealFileSystem::openFileForReadBinary(const Twine &Name) {
358 auto BypassSandbox = sys::sandbox::scopedDisable();
359
360 return openFileForReadWithFlags(Name, Flags: sys::fs::OF_None);
361}
362
363llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
364 auto BypassSandbox = sys::sandbox::scopedDisable();
365
366 if (WD && *WD)
367 return std::string(WD->get().Specified);
368 if (WD)
369 return WD->getError();
370
371 SmallString<128> Dir;
372 if (std::error_code EC = llvm::sys::fs::current_path(result&: Dir))
373 return EC;
374 return std::string(Dir);
375}
376
377std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
378 auto BypassSandbox = sys::sandbox::scopedDisable();
379
380 if (!WD)
381 return llvm::sys::fs::set_current_path(Path);
382
383 SmallString<128> Absolute, Resolved, Storage;
384 adjustPath(Path, Storage).toVector(Out&: Absolute);
385 bool IsDir;
386 if (auto Err = llvm::sys::fs::is_directory(path: Absolute, result&: IsDir))
387 return Err;
388 if (!IsDir)
389 return std::make_error_code(e: std::errc::not_a_directory);
390 if (auto Err = llvm::sys::fs::real_path(path: Absolute, output&: Resolved))
391 return Err;
392 WD = WorkingDirectory{.Specified: Absolute, .Resolved: Resolved};
393 return std::error_code();
394}
395
396std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
397 auto BypassSandbox = sys::sandbox::scopedDisable();
398
399 SmallString<256> Storage;
400 return llvm::sys::fs::is_local(path: adjustPath(Path, Storage), result&: Result);
401}
402
403std::error_code RealFileSystem::getRealPath(const Twine &Path,
404 SmallVectorImpl<char> &Output) {
405 auto BypassSandbox = sys::sandbox::scopedDisable();
406
407 SmallString<256> Storage;
408 return llvm::sys::fs::real_path(path: adjustPath(Path, Storage), output&: Output);
409}
410
411void RealFileSystem::printImpl(raw_ostream &OS, PrintType Type,
412 unsigned IndentLevel) const {
413 printIndent(OS, IndentLevel);
414 OS << "RealFileSystem using ";
415 if (WD)
416 OS << "own";
417 else
418 OS << "process";
419 OS << " CWD\n";
420}
421
422IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
423 static IntrusiveRefCntPtr<FileSystem> FS =
424 makeIntrusiveRefCnt<RealFileSystem>(A: true);
425 sys::sandbox::violationIfEnabled();
426
427 return FS;
428}
429
430std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() {
431 sys::sandbox::violationIfEnabled();
432
433 return std::make_unique<RealFileSystem>(args: false);
434}
435
436namespace {
437
438class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
439 llvm::sys::fs::directory_iterator Iter;
440
441public:
442 RealFSDirIter(const Twine &Path, std::error_code &EC) {
443 auto BypassSandbox = sys::sandbox::scopedDisable();
444
445 Iter = sys::fs::directory_iterator(Path, EC);
446 if (Iter != sys::fs::directory_iterator())
447 CurrentEntry = directory_entry(Iter->path(), Iter->type());
448 }
449
450 std::error_code increment() override {
451 auto BypassSandbox = sys::sandbox::scopedDisable();
452
453 std::error_code EC;
454 Iter.increment(ec&: EC);
455 CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
456 ? directory_entry()
457 : directory_entry(Iter->path(), Iter->type());
458 return EC;
459 }
460};
461
462} // namespace
463
464directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
465 std::error_code &EC) {
466 auto BypassSandbox = sys::sandbox::scopedDisable();
467
468 SmallString<128> Storage;
469 return directory_iterator(
470 std::make_shared<RealFSDirIter>(args: adjustPath(Path: Dir, Storage), args&: EC));
471}
472
473//===-----------------------------------------------------------------------===/
474// OverlayFileSystem implementation
475//===-----------------------------------------------------------------------===/
476
477OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
478 FSList.push_back(Elt: std::move(BaseFS));
479}
480
481void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
482 FSList.push_back(Elt: FS);
483 // Synchronize added file systems by duplicating the working directory from
484 // the first one in the list.
485 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
486}
487
488ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
489 // FIXME: handle symlinks that cross file systems
490 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
491 ErrorOr<Status> Status = (*I)->status(Path);
492 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
493 return Status;
494 }
495 return make_error_code(E: llvm::errc::no_such_file_or_directory);
496}
497
498bool OverlayFileSystem::exists(const Twine &Path) {
499 // FIXME: handle symlinks that cross file systems
500 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
501 if ((*I)->exists(Path))
502 return true;
503 }
504 return false;
505}
506
507ErrorOr<std::unique_ptr<File>>
508OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
509 // FIXME: handle symlinks that cross file systems
510 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
511 auto Result = (*I)->openFileForRead(Path);
512 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
513 return Result;
514 }
515 return make_error_code(E: llvm::errc::no_such_file_or_directory);
516}
517
518llvm::ErrorOr<std::string>
519OverlayFileSystem::getCurrentWorkingDirectory() const {
520 // All file systems are synchronized, just take the first working directory.
521 return FSList.front()->getCurrentWorkingDirectory();
522}
523
524std::error_code
525OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
526 for (auto &FS : FSList)
527 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
528 return EC;
529 return {};
530}
531
532std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
533 for (auto &FS : FSList)
534 if (FS->exists(Path))
535 return FS->isLocal(Path, Result);
536 return errc::no_such_file_or_directory;
537}
538
539std::error_code OverlayFileSystem::getRealPath(const Twine &Path,
540 SmallVectorImpl<char> &Output) {
541 for (const auto &FS : FSList)
542 if (FS->exists(Path))
543 return FS->getRealPath(Path, Output);
544 return errc::no_such_file_or_directory;
545}
546
547void OverlayFileSystem::visitChildFileSystems(VisitCallbackTy Callback) {
548 for (IntrusiveRefCntPtr<FileSystem> FS : overlays_range()) {
549 Callback(*FS);
550 FS->visitChildFileSystems(Callback);
551 }
552}
553
554void OverlayFileSystem::printImpl(raw_ostream &OS, PrintType Type,
555 unsigned IndentLevel) const {
556 printIndent(OS, IndentLevel);
557 OS << "OverlayFileSystem\n";
558 if (Type == PrintType::Summary)
559 return;
560
561 if (Type == PrintType::Contents)
562 Type = PrintType::Summary;
563 for (const auto &FS : overlays_range())
564 FS->print(OS, Type, IndentLevel: IndentLevel + 1);
565}
566
567llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
568
569namespace {
570
571/// Combines and deduplicates directory entries across multiple file systems.
572class CombiningDirIterImpl : public llvm::vfs::detail::DirIterImpl {
573 using FileSystemPtr = llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>;
574
575 /// Iterators to combine, processed in reverse order.
576 SmallVector<directory_iterator, 8> IterList;
577 /// The iterator currently being traversed.
578 directory_iterator CurrentDirIter;
579 /// The set of names already returned as entries.
580 llvm::StringSet<> SeenNames;
581
582 /// Sets \c CurrentDirIter to the next iterator in the list, or leaves it as
583 /// is (at its end position) if we've already gone through them all.
584 std::error_code incrementIter(bool IsFirstTime) {
585 while (!IterList.empty()) {
586 CurrentDirIter = IterList.back();
587 IterList.pop_back();
588 if (CurrentDirIter != directory_iterator())
589 break; // found
590 }
591
592 if (IsFirstTime && CurrentDirIter == directory_iterator())
593 return errc::no_such_file_or_directory;
594 return {};
595 }
596
597 std::error_code incrementDirIter(bool IsFirstTime) {
598 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
599 "incrementing past end");
600 std::error_code EC;
601 if (!IsFirstTime)
602 CurrentDirIter.increment(EC);
603 if (!EC && CurrentDirIter == directory_iterator())
604 EC = incrementIter(IsFirstTime);
605 return EC;
606 }
607
608 std::error_code incrementImpl(bool IsFirstTime) {
609 while (true) {
610 std::error_code EC = incrementDirIter(IsFirstTime);
611 if (EC || CurrentDirIter == directory_iterator()) {
612 CurrentEntry = directory_entry();
613 return EC;
614 }
615 CurrentEntry = *CurrentDirIter;
616 StringRef Name = llvm::sys::path::filename(path: CurrentEntry.path());
617 if (SeenNames.insert(key: Name).second)
618 return EC; // name not seen before
619 }
620 llvm_unreachable("returned above");
621 }
622
623public:
624 CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems, std::string Dir,
625 std::error_code &EC) {
626 for (const auto &FS : FileSystems) {
627 std::error_code FEC;
628 directory_iterator Iter = FS->dir_begin(Dir, EC&: FEC);
629 if (FEC && FEC != errc::no_such_file_or_directory) {
630 EC = FEC;
631 return;
632 }
633 if (!FEC)
634 IterList.push_back(Elt: Iter);
635 }
636 EC = incrementImpl(IsFirstTime: true);
637 }
638
639 CombiningDirIterImpl(ArrayRef<directory_iterator> DirIters,
640 std::error_code &EC)
641 : IterList(DirIters) {
642 EC = incrementImpl(IsFirstTime: true);
643 }
644
645 std::error_code increment() override { return incrementImpl(IsFirstTime: false); }
646};
647
648} // namespace
649
650directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
651 std::error_code &EC) {
652 directory_iterator Combined = directory_iterator(
653 std::make_shared<CombiningDirIterImpl>(args&: FSList, args: Dir.str(), args&: EC));
654 if (EC)
655 return {};
656 return Combined;
657}
658
659void ProxyFileSystem::anchor() {}
660
661namespace llvm {
662namespace vfs {
663
664namespace detail {
665
666enum InMemoryNodeKind {
667 IME_File,
668 IME_Directory,
669 IME_HardLink,
670 IME_SymbolicLink,
671};
672
673/// The in memory file system is a tree of Nodes. Every node can either be a
674/// file, symlink, hardlink or a directory.
675class InMemoryNode {
676 InMemoryNodeKind Kind;
677 std::string FileName;
678
679public:
680 InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
681 : Kind(Kind), FileName(std::string(llvm::sys::path::filename(path: FileName))) {
682 }
683 virtual ~InMemoryNode() = default;
684
685 /// Return the \p Status for this node. \p RequestedName should be the name
686 /// through which the caller referred to this node. It will override
687 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
688 virtual Status getStatus(const Twine &RequestedName) const = 0;
689
690 /// Get the filename of this node (the name without the directory part).
691 StringRef getFileName() const { return FileName; }
692 InMemoryNodeKind getKind() const { return Kind; }
693 virtual std::string toString(unsigned Indent) const = 0;
694};
695
696class InMemoryFile : public InMemoryNode {
697 Status Stat;
698 std::unique_ptr<llvm::MemoryBuffer> Buffer;
699
700public:
701 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
702 : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
703 Buffer(std::move(Buffer)) {}
704
705 Status getStatus(const Twine &RequestedName) const override {
706 return Status::copyWithNewName(In: Stat, NewName: RequestedName);
707 }
708 llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
709
710 std::string toString(unsigned Indent) const override {
711 return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
712 }
713
714 static bool classof(const InMemoryNode *N) {
715 return N->getKind() == IME_File;
716 }
717};
718
719namespace {
720
721class InMemoryHardLink : public InMemoryNode {
722 const InMemoryFile &ResolvedFile;
723
724public:
725 InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
726 : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
727 const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
728
729 Status getStatus(const Twine &RequestedName) const override {
730 return ResolvedFile.getStatus(RequestedName);
731 }
732
733 std::string toString(unsigned Indent) const override {
734 return std::string(Indent, ' ') + "HardLink to -> " +
735 ResolvedFile.toString(Indent: 0);
736 }
737
738 static bool classof(const InMemoryNode *N) {
739 return N->getKind() == IME_HardLink;
740 }
741};
742
743class InMemorySymbolicLink : public InMemoryNode {
744 std::string TargetPath;
745 Status Stat;
746
747public:
748 InMemorySymbolicLink(StringRef Path, StringRef TargetPath, Status Stat)
749 : InMemoryNode(Path, IME_SymbolicLink), TargetPath(std::move(TargetPath)),
750 Stat(Stat) {}
751
752 std::string toString(unsigned Indent) const override {
753 return std::string(Indent, ' ') + "SymbolicLink to -> " + TargetPath;
754 }
755
756 Status getStatus(const Twine &RequestedName) const override {
757 return Status::copyWithNewName(In: Stat, NewName: RequestedName);
758 }
759
760 StringRef getTargetPath() const { return TargetPath; }
761
762 static bool classof(const InMemoryNode *N) {
763 return N->getKind() == IME_SymbolicLink;
764 }
765};
766
767/// Adapt a InMemoryFile for VFS' File interface. The goal is to make
768/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
769/// \p RealFile.
770class InMemoryFileAdaptor : public File {
771 const InMemoryFile &Node;
772 /// The name to use when returning a Status for this file.
773 std::string RequestedName;
774
775public:
776 explicit InMemoryFileAdaptor(const InMemoryFile &Node,
777 std::string RequestedName)
778 : Node(Node), RequestedName(std::move(RequestedName)) {}
779
780 llvm::ErrorOr<Status> status() override {
781 return Node.getStatus(RequestedName);
782 }
783
784 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
785 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
786 bool IsVolatile) override {
787 llvm::MemoryBuffer *Buf = Node.getBuffer();
788 return llvm::MemoryBuffer::getMemBuffer(
789 InputData: Buf->getBuffer(), BufferName: Buf->getBufferIdentifier(), RequiresNullTerminator);
790 }
791
792 std::error_code close() override { return {}; }
793
794 void setPath(const Twine &Path) override { RequestedName = Path.str(); }
795};
796} // namespace
797
798class InMemoryDirectory : public InMemoryNode {
799 Status Stat;
800 std::map<std::string, std::unique_ptr<InMemoryNode>, std::less<>> Entries;
801
802public:
803 InMemoryDirectory(Status Stat)
804 : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
805
806 /// Return the \p Status for this node. \p RequestedName should be the name
807 /// through which the caller referred to this node. It will override
808 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
809 Status getStatus(const Twine &RequestedName) const override {
810 return Status::copyWithNewName(In: Stat, NewName: RequestedName);
811 }
812
813 UniqueID getUniqueID() const { return Stat.getUniqueID(); }
814
815 InMemoryNode *getChild(StringRef Name) const {
816 auto I = Entries.find(x: Name);
817 if (I != Entries.end())
818 return I->second.get();
819 return nullptr;
820 }
821
822 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
823 return Entries.emplace(args&: Name, args: std::move(Child)).first->second.get();
824 }
825
826 using const_iterator = decltype(Entries)::const_iterator;
827
828 const_iterator begin() const { return Entries.begin(); }
829 const_iterator end() const { return Entries.end(); }
830
831 std::string toString(unsigned Indent) const override {
832 std::string Result =
833 (std::string(Indent, ' ') + Stat.getName() + "\n").str();
834 for (const auto &Entry : Entries)
835 Result += Entry.second->toString(Indent: Indent + 2);
836 return Result;
837 }
838
839 static bool classof(const InMemoryNode *N) {
840 return N->getKind() == IME_Directory;
841 }
842};
843
844} // namespace detail
845
846// The UniqueID of in-memory files is derived from path and content.
847// This avoids difficulties in creating exactly equivalent in-memory FSes,
848// as often needed in multithreaded programs.
849static sys::fs::UniqueID getUniqueID(hash_code Hash) {
850 return sys::fs::UniqueID(std::numeric_limits<uint64_t>::max(),
851 uint64_t(size_t(Hash)));
852}
853static sys::fs::UniqueID getFileID(sys::fs::UniqueID Parent,
854 llvm::StringRef Name,
855 llvm::StringRef Contents) {
856 return getUniqueID(Hash: llvm::hash_combine(args: Parent.getFile(), args: Name, args: Contents));
857}
858static sys::fs::UniqueID getDirectoryID(sys::fs::UniqueID Parent,
859 llvm::StringRef Name) {
860 return getUniqueID(Hash: llvm::hash_combine(args: Parent.getFile(), args: Name));
861}
862
863Status detail::NewInMemoryNodeInfo::makeStatus() const {
864 UniqueID UID =
865 (Type == sys::fs::file_type::directory_file)
866 ? getDirectoryID(Parent: DirUID, Name)
867 : getFileID(Parent: DirUID, Name, Contents: Buffer ? Buffer->getBuffer() : "");
868
869 return Status(Path, UID, llvm::sys::toTimePoint(T: ModificationTime), User,
870 Group, Buffer ? Buffer->getBufferSize() : 0, Type, Perms);
871}
872
873InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
874 : Root(new detail::InMemoryDirectory(
875 Status("", getDirectoryID(Parent: llvm::sys::fs::UniqueID(), Name: ""),
876 llvm::sys::TimePoint<>(), 0, 0, 0,
877 llvm::sys::fs::file_type::directory_file,
878 llvm::sys::fs::perms::all_all))),
879 UseNormalizedPaths(UseNormalizedPaths) {}
880
881InMemoryFileSystem::~InMemoryFileSystem() = default;
882
883std::string InMemoryFileSystem::toString() const {
884 return Root->toString(/*Indent=*/0);
885}
886
887bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
888 std::unique_ptr<llvm::MemoryBuffer> Buffer,
889 std::optional<uint32_t> User,
890 std::optional<uint32_t> Group,
891 std::optional<llvm::sys::fs::file_type> Type,
892 std::optional<llvm::sys::fs::perms> Perms,
893 MakeNodeFn MakeNode) {
894 SmallString<128> Path;
895 P.toVector(Out&: Path);
896
897 // Fix up relative paths. This just prepends the current working directory.
898 std::error_code EC = makeAbsolute(Path);
899 assert(!EC);
900 (void)EC;
901
902 if (useNormalizedPaths())
903 llvm::sys::path::remove_dots(path&: Path, /*remove_dot_dot=*/true);
904
905 if (Path.empty())
906 return false;
907
908 detail::InMemoryDirectory *Dir = Root.get();
909 auto I = llvm::sys::path::begin(path: Path), E = sys::path::end(path: Path);
910 const auto ResolvedUser = User.value_or(u: 0);
911 const auto ResolvedGroup = Group.value_or(u: 0);
912 const auto ResolvedType = Type.value_or(u: sys::fs::file_type::regular_file);
913 const auto ResolvedPerms = Perms.value_or(u: sys::fs::all_all);
914 // Any intermediate directories we create should be accessible by
915 // the owner, even if Perms says otherwise for the final path.
916 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
917
918 StringRef Name = *I;
919 while (true) {
920 Name = *I;
921 ++I;
922 if (I == E)
923 break;
924 detail::InMemoryNode *Node = Dir->getChild(Name);
925 if (!Node) {
926 // This isn't the last element, so we create a new directory.
927 Status Stat(
928 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
929 getDirectoryID(Parent: Dir->getUniqueID(), Name),
930 llvm::sys::toTimePoint(T: ModificationTime), ResolvedUser, ResolvedGroup,
931 0, sys::fs::file_type::directory_file, NewDirectoryPerms);
932 Dir = cast<detail::InMemoryDirectory>(Val: Dir->addChild(
933 Name, Child: std::make_unique<detail::InMemoryDirectory>(args: std::move(Stat))));
934 continue;
935 }
936 // Creating file under another file.
937 if (!isa<detail::InMemoryDirectory>(Val: Node))
938 return false;
939 Dir = cast<detail::InMemoryDirectory>(Val: Node);
940 }
941 detail::InMemoryNode *Node = Dir->getChild(Name);
942 if (!Node) {
943 Dir->addChild(Name,
944 Child: MakeNode({.DirUID: Dir->getUniqueID(), .Path: Path, .Name: Name, .ModificationTime: ModificationTime,
945 .Buffer: std::move(Buffer), .User: ResolvedUser, .Group: ResolvedGroup,
946 .Type: ResolvedType, .Perms: ResolvedPerms}));
947 return true;
948 }
949 if (isa<detail::InMemoryDirectory>(Val: Node))
950 return ResolvedType == sys::fs::file_type::directory_file;
951
952 assert((isa<detail::InMemoryFile>(Node) ||
953 isa<detail::InMemoryHardLink>(Node)) &&
954 "Must be either file, hardlink or directory!");
955
956 // Return false only if the new file is different from the existing one.
957 if (auto *Link = dyn_cast<detail::InMemoryHardLink>(Val: Node)) {
958 return Link->getResolvedFile().getBuffer()->getBuffer() ==
959 Buffer->getBuffer();
960 }
961 return cast<detail::InMemoryFile>(Val: Node)->getBuffer()->getBuffer() ==
962 Buffer->getBuffer();
963}
964
965bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
966 std::unique_ptr<llvm::MemoryBuffer> Buffer,
967 std::optional<uint32_t> User,
968 std::optional<uint32_t> Group,
969 std::optional<llvm::sys::fs::file_type> Type,
970 std::optional<llvm::sys::fs::perms> Perms) {
971 return addFile(P, ModificationTime, Buffer: std::move(Buffer), User, Group, Type,
972 Perms,
973 MakeNode: [](detail::NewInMemoryNodeInfo NNI)
974 -> std::unique_ptr<detail::InMemoryNode> {
975 Status Stat = NNI.makeStatus();
976 if (Stat.getType() == sys::fs::file_type::directory_file)
977 return std::make_unique<detail::InMemoryDirectory>(args&: Stat);
978 return std::make_unique<detail::InMemoryFile>(
979 args&: Stat, args: std::move(NNI.Buffer));
980 });
981}
982
983bool InMemoryFileSystem::addFileNoOwn(
984 const Twine &P, time_t ModificationTime,
985 const llvm::MemoryBufferRef &Buffer, std::optional<uint32_t> User,
986 std::optional<uint32_t> Group, std::optional<llvm::sys::fs::file_type> Type,
987 std::optional<llvm::sys::fs::perms> Perms) {
988 return addFile(P, ModificationTime, Buffer: llvm::MemoryBuffer::getMemBuffer(Ref: Buffer),
989 User: std::move(User), Group: std::move(Group), Type: std::move(Type),
990 Perms: std::move(Perms),
991 MakeNode: [](detail::NewInMemoryNodeInfo NNI)
992 -> std::unique_ptr<detail::InMemoryNode> {
993 Status Stat = NNI.makeStatus();
994 if (Stat.getType() == sys::fs::file_type::directory_file)
995 return std::make_unique<detail::InMemoryDirectory>(args&: Stat);
996 return std::make_unique<detail::InMemoryFile>(
997 args&: Stat, args: std::move(NNI.Buffer));
998 });
999}
1000
1001detail::NamedNodeOrError
1002InMemoryFileSystem::lookupNode(const Twine &P, bool FollowFinalSymlink,
1003 size_t SymlinkDepth) const {
1004 SmallString<128> Path;
1005 P.toVector(Out&: Path);
1006
1007 // Fix up relative paths. This just prepends the current working directory.
1008 std::error_code EC = makeAbsolute(Path);
1009 assert(!EC);
1010 (void)EC;
1011
1012 if (useNormalizedPaths())
1013 llvm::sys::path::remove_dots(path&: Path, /*remove_dot_dot=*/true);
1014
1015 const detail::InMemoryDirectory *Dir = Root.get();
1016 if (Path.empty())
1017 return detail::NamedNodeOrError(Path, Dir);
1018
1019 auto I = llvm::sys::path::begin(path: Path), E = llvm::sys::path::end(path: Path);
1020 while (true) {
1021 detail::InMemoryNode *Node = Dir->getChild(Name: *I);
1022 ++I;
1023 if (!Node)
1024 return errc::no_such_file_or_directory;
1025
1026 if (auto Symlink = dyn_cast<detail::InMemorySymbolicLink>(Val: Node)) {
1027 // If we're at the end of the path, and we're not following through
1028 // terminal symlinks, then we're done.
1029 if (I == E && !FollowFinalSymlink)
1030 return detail::NamedNodeOrError(Path, Symlink);
1031
1032 if (SymlinkDepth > InMemoryFileSystem::MaxSymlinkDepth)
1033 return errc::no_such_file_or_directory;
1034
1035 SmallString<128> TargetPath = Symlink->getTargetPath();
1036 if (std::error_code EC = makeAbsolute(Path&: TargetPath))
1037 return EC;
1038
1039 // Keep going with the target. We always want to follow symlinks here
1040 // because we're either at the end of a path that we want to follow, or
1041 // not at the end of a path, in which case we need to follow the symlink
1042 // regardless.
1043 auto Target =
1044 lookupNode(P: TargetPath, /*FollowFinalSymlink=*/true, SymlinkDepth: SymlinkDepth + 1);
1045 if (!Target || I == E)
1046 return Target;
1047
1048 if (!isa<detail::InMemoryDirectory>(Val: *Target))
1049 return errc::no_such_file_or_directory;
1050
1051 // Otherwise, continue on the search in the symlinked directory.
1052 Dir = cast<detail::InMemoryDirectory>(Val: *Target);
1053 continue;
1054 }
1055
1056 // Return the file if it's at the end of the path.
1057 if (auto File = dyn_cast<detail::InMemoryFile>(Val: Node)) {
1058 if (I == E)
1059 return detail::NamedNodeOrError(Path, File);
1060 return errc::no_such_file_or_directory;
1061 }
1062
1063 // If Node is HardLink then return the resolved file.
1064 if (auto File = dyn_cast<detail::InMemoryHardLink>(Val: Node)) {
1065 if (I == E)
1066 return detail::NamedNodeOrError(Path, &File->getResolvedFile());
1067 return errc::no_such_file_or_directory;
1068 }
1069 // Traverse directories.
1070 Dir = cast<detail::InMemoryDirectory>(Val: Node);
1071 if (I == E)
1072 return detail::NamedNodeOrError(Path, Dir);
1073 }
1074}
1075
1076bool InMemoryFileSystem::addHardLink(const Twine &NewLink,
1077 const Twine &Target) {
1078 auto NewLinkNode = lookupNode(P: NewLink, /*FollowFinalSymlink=*/false);
1079 // Whether symlinks in the hardlink target are followed is
1080 // implementation-defined in POSIX.
1081 // We're following symlinks here to be consistent with macOS.
1082 auto TargetNode = lookupNode(P: Target, /*FollowFinalSymlink=*/true);
1083 // FromPath must not have been added before. ToPath must have been added
1084 // before. Resolved ToPath must be a File.
1085 if (!TargetNode || NewLinkNode || !isa<detail::InMemoryFile>(Val: *TargetNode))
1086 return false;
1087 return addFile(P: NewLink, ModificationTime: 0, Buffer: nullptr, User: std::nullopt, Group: std::nullopt, Type: std::nullopt,
1088 Perms: std::nullopt, MakeNode: [&](detail::NewInMemoryNodeInfo NNI) {
1089 return std::make_unique<detail::InMemoryHardLink>(
1090 args: NNI.Path.str(),
1091 args: *cast<detail::InMemoryFile>(Val: *TargetNode));
1092 });
1093}
1094
1095bool InMemoryFileSystem::addSymbolicLink(
1096 const Twine &NewLink, const Twine &Target, time_t ModificationTime,
1097 std::optional<uint32_t> User, std::optional<uint32_t> Group,
1098 std::optional<llvm::sys::fs::perms> Perms) {
1099 auto NewLinkNode = lookupNode(P: NewLink, /*FollowFinalSymlink=*/false);
1100 if (NewLinkNode)
1101 return false;
1102
1103 SmallString<128> NewLinkStr, TargetStr;
1104 NewLink.toVector(Out&: NewLinkStr);
1105 Target.toVector(Out&: TargetStr);
1106
1107 return addFile(P: NewLinkStr, ModificationTime, Buffer: nullptr, User, Group,
1108 Type: sys::fs::file_type::symlink_file, Perms,
1109 MakeNode: [&](detail::NewInMemoryNodeInfo NNI) {
1110 return std::make_unique<detail::InMemorySymbolicLink>(
1111 args&: NewLinkStr, args&: TargetStr, args: NNI.makeStatus());
1112 });
1113}
1114
1115llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
1116 auto Node = lookupNode(P: Path, /*FollowFinalSymlink=*/true);
1117 if (Node)
1118 return (*Node)->getStatus(RequestedName: Path);
1119 return Node.getError();
1120}
1121
1122llvm::ErrorOr<std::unique_ptr<File>>
1123InMemoryFileSystem::openFileForRead(const Twine &Path) {
1124 auto Node = lookupNode(P: Path,/*FollowFinalSymlink=*/true);
1125 if (!Node)
1126 return Node.getError();
1127
1128 // When we have a file provide a heap-allocated wrapper for the memory buffer
1129 // to match the ownership semantics for File.
1130 if (auto *F = dyn_cast<detail::InMemoryFile>(Val: *Node))
1131 return std::unique_ptr<File>(
1132 new detail::InMemoryFileAdaptor(*F, Path.str()));
1133
1134 // FIXME: errc::not_a_file?
1135 return make_error_code(E: llvm::errc::invalid_argument);
1136}
1137
1138/// Adaptor from InMemoryDir::iterator to directory_iterator.
1139class InMemoryFileSystem::DirIterator : public llvm::vfs::detail::DirIterImpl {
1140 const InMemoryFileSystem *FS;
1141 detail::InMemoryDirectory::const_iterator I;
1142 detail::InMemoryDirectory::const_iterator E;
1143 std::string RequestedDirName;
1144
1145 void setCurrentEntry() {
1146 if (I != E) {
1147 SmallString<256> Path(RequestedDirName);
1148 llvm::sys::path::append(path&: Path, a: I->second->getFileName());
1149 sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1150 switch (I->second->getKind()) {
1151 case detail::IME_File:
1152 case detail::IME_HardLink:
1153 Type = sys::fs::file_type::regular_file;
1154 break;
1155 case detail::IME_Directory:
1156 Type = sys::fs::file_type::directory_file;
1157 break;
1158 case detail::IME_SymbolicLink:
1159 if (auto SymlinkTarget =
1160 FS->lookupNode(P: Path, /*FollowFinalSymlink=*/true)) {
1161 Path = SymlinkTarget.getName();
1162 Type = (*SymlinkTarget)->getStatus(RequestedName: Path).getType();
1163 }
1164 break;
1165 }
1166 CurrentEntry = directory_entry(std::string(Path), Type);
1167 } else {
1168 // When we're at the end, make CurrentEntry invalid and DirIterImpl will
1169 // do the rest.
1170 CurrentEntry = directory_entry();
1171 }
1172 }
1173
1174public:
1175 DirIterator() = default;
1176
1177 DirIterator(const InMemoryFileSystem *FS,
1178 const detail::InMemoryDirectory &Dir,
1179 std::string RequestedDirName)
1180 : FS(FS), I(Dir.begin()), E(Dir.end()),
1181 RequestedDirName(std::move(RequestedDirName)) {
1182 setCurrentEntry();
1183 }
1184
1185 std::error_code increment() override {
1186 ++I;
1187 setCurrentEntry();
1188 return {};
1189 }
1190};
1191
1192directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
1193 std::error_code &EC) {
1194 auto Node = lookupNode(P: Dir, /*FollowFinalSymlink=*/true);
1195 if (!Node) {
1196 EC = Node.getError();
1197 return directory_iterator(std::make_shared<DirIterator>());
1198 }
1199
1200 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(Val: *Node))
1201 return directory_iterator(
1202 std::make_shared<DirIterator>(args: this, args: *DirNode, args: Dir.str()));
1203
1204 EC = make_error_code(E: llvm::errc::not_a_directory);
1205 return directory_iterator(std::make_shared<DirIterator>());
1206}
1207
1208std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
1209 SmallString<128> Path;
1210 P.toVector(Out&: Path);
1211
1212 // Fix up relative paths. This just prepends the current working directory.
1213 std::error_code EC = makeAbsolute(Path);
1214 assert(!EC);
1215 (void)EC;
1216
1217 if (useNormalizedPaths())
1218 llvm::sys::path::remove_dots(path&: Path, /*remove_dot_dot=*/true);
1219
1220 if (!Path.empty())
1221 WorkingDirectory = std::string(Path);
1222 return {};
1223}
1224
1225std::error_code InMemoryFileSystem::getRealPath(const Twine &Path,
1226 SmallVectorImpl<char> &Output) {
1227 auto CWD = getCurrentWorkingDirectory();
1228 if (!CWD || CWD->empty())
1229 return errc::operation_not_permitted;
1230 Path.toVector(Out&: Output);
1231 if (auto EC = makeAbsolute(Path&: Output))
1232 return EC;
1233 llvm::sys::path::remove_dots(path&: Output, /*remove_dot_dot=*/true);
1234 return {};
1235}
1236
1237std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
1238 Result = false;
1239 return {};
1240}
1241
1242void InMemoryFileSystem::printImpl(raw_ostream &OS, PrintType PrintContents,
1243 unsigned IndentLevel) const {
1244 printIndent(OS, IndentLevel);
1245 OS << "InMemoryFileSystem\n";
1246}
1247
1248} // namespace vfs
1249} // namespace llvm
1250
1251//===-----------------------------------------------------------------------===/
1252// RedirectingFileSystem implementation
1253//===-----------------------------------------------------------------------===/
1254
1255namespace {
1256
1257static llvm::sys::path::Style getExistingStyle(llvm::StringRef Path) {
1258 // Detect the path style in use by checking the first separator.
1259 llvm::sys::path::Style style = llvm::sys::path::Style::native;
1260 const size_t n = Path.find_first_of(Chars: "/\\");
1261 // Can't distinguish between posix and windows_slash here.
1262 if (n != static_cast<size_t>(-1))
1263 style = (Path[n] == '/') ? llvm::sys::path::Style::posix
1264 : llvm::sys::path::Style::windows_backslash;
1265 return style;
1266}
1267
1268/// Removes leading "./" as well as path components like ".." and ".".
1269static llvm::SmallString<256> canonicalize(llvm::StringRef Path) {
1270 // First detect the path style in use by checking the first separator.
1271 llvm::sys::path::Style style = getExistingStyle(Path);
1272
1273 // Now remove the dots. Explicitly specifying the path style prevents the
1274 // direction of the slashes from changing.
1275 llvm::SmallString<256> result =
1276 llvm::sys::path::remove_leading_dotslash(path: Path, style);
1277 llvm::sys::path::remove_dots(path&: result, /*remove_dot_dot=*/true, style);
1278 return result;
1279}
1280
1281/// Whether the error and entry specify a file/directory that was not found.
1282static bool isFileNotFound(std::error_code EC,
1283 RedirectingFileSystem::Entry *E = nullptr) {
1284 if (E && !isa<RedirectingFileSystem::DirectoryRemapEntry>(Val: E))
1285 return false;
1286 return EC == llvm::errc::no_such_file_or_directory;
1287}
1288
1289} // anonymous namespace
1290
1291
1292RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
1293 : ExternalFS(std::move(FS)) {
1294 if (ExternalFS)
1295 if (auto ExternalWorkingDirectory =
1296 ExternalFS->getCurrentWorkingDirectory()) {
1297 WorkingDirectory = *ExternalWorkingDirectory;
1298 }
1299}
1300
1301/// Directory iterator implementation for \c RedirectingFileSystem's
1302/// directory entries.
1303class llvm::vfs::RedirectingFSDirIterImpl
1304 : public llvm::vfs::detail::DirIterImpl {
1305 std::string Dir;
1306 RedirectingFileSystem::DirectoryEntry::iterator Current, End;
1307
1308 std::error_code incrementImpl(bool IsFirstTime) {
1309 assert((IsFirstTime || Current != End) && "cannot iterate past end");
1310 if (!IsFirstTime)
1311 ++Current;
1312 if (Current != End) {
1313 SmallString<128> PathStr(Dir);
1314 llvm::sys::path::append(path&: PathStr, a: (*Current)->getName());
1315 sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1316 switch ((*Current)->getKind()) {
1317 case RedirectingFileSystem::EK_Directory:
1318 [[fallthrough]];
1319 case RedirectingFileSystem::EK_DirectoryRemap:
1320 Type = sys::fs::file_type::directory_file;
1321 break;
1322 case RedirectingFileSystem::EK_File:
1323 Type = sys::fs::file_type::regular_file;
1324 break;
1325 }
1326 CurrentEntry = directory_entry(std::string(PathStr), Type);
1327 } else {
1328 CurrentEntry = directory_entry();
1329 }
1330 return {};
1331 };
1332
1333public:
1334 RedirectingFSDirIterImpl(
1335 const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin,
1336 RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC)
1337 : Dir(Path.str()), Current(Begin), End(End) {
1338 EC = incrementImpl(/*IsFirstTime=*/true);
1339 }
1340
1341 std::error_code increment() override {
1342 return incrementImpl(/*IsFirstTime=*/false);
1343 }
1344};
1345
1346namespace {
1347/// Directory iterator implementation for \c RedirectingFileSystem's
1348/// directory remap entries that maps the paths reported by the external
1349/// file system's directory iterator back to the virtual directory's path.
1350class RedirectingFSDirRemapIterImpl : public llvm::vfs::detail::DirIterImpl {
1351 std::string Dir;
1352 llvm::sys::path::Style DirStyle;
1353 llvm::vfs::directory_iterator ExternalIter;
1354
1355public:
1356 RedirectingFSDirRemapIterImpl(std::string DirPath,
1357 llvm::vfs::directory_iterator ExtIter)
1358 : Dir(std::move(DirPath)), DirStyle(getExistingStyle(Path: Dir)),
1359 ExternalIter(ExtIter) {
1360 if (ExternalIter != llvm::vfs::directory_iterator())
1361 setCurrentEntry();
1362 }
1363
1364 void setCurrentEntry() {
1365 StringRef ExternalPath = ExternalIter->path();
1366 llvm::sys::path::Style ExternalStyle = getExistingStyle(Path: ExternalPath);
1367 StringRef File = llvm::sys::path::filename(path: ExternalPath, style: ExternalStyle);
1368
1369 SmallString<128> NewPath(Dir);
1370 llvm::sys::path::append(path&: NewPath, style: DirStyle, a: File);
1371
1372 CurrentEntry = directory_entry(std::string(NewPath), ExternalIter->type());
1373 }
1374
1375 std::error_code increment() override {
1376 std::error_code EC;
1377 ExternalIter.increment(EC);
1378 if (!EC && ExternalIter != llvm::vfs::directory_iterator())
1379 setCurrentEntry();
1380 else
1381 CurrentEntry = directory_entry();
1382 return EC;
1383 }
1384};
1385} // namespace
1386
1387llvm::ErrorOr<std::string>
1388RedirectingFileSystem::getCurrentWorkingDirectory() const {
1389 return WorkingDirectory;
1390}
1391
1392std::error_code
1393RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
1394 // Don't change the working directory if the path doesn't exist.
1395 if (!exists(Path))
1396 return errc::no_such_file_or_directory;
1397
1398 SmallString<128> AbsolutePath;
1399 Path.toVector(Out&: AbsolutePath);
1400 if (std::error_code EC = makeAbsolute(Path&: AbsolutePath))
1401 return EC;
1402 WorkingDirectory = std::string(AbsolutePath);
1403 return {};
1404}
1405
1406std::error_code RedirectingFileSystem::isLocal(const Twine &Path_,
1407 bool &Result) {
1408 SmallString<256> Path;
1409 Path_.toVector(Out&: Path);
1410
1411 if (makeAbsolute(Path))
1412 return {};
1413
1414 return ExternalFS->isLocal(Path, Result);
1415}
1416
1417std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
1418 // is_absolute(..., Style::windows_*) accepts paths with both slash types.
1419 if (llvm::sys::path::is_absolute(path: Path, style: llvm::sys::path::Style::posix) ||
1420 llvm::sys::path::is_absolute(path: Path,
1421 style: llvm::sys::path::Style::windows_backslash))
1422 // This covers windows absolute path with forward slash as well, as the
1423 // forward slashes are treated as path separation in llvm::path
1424 // regardless of what path::Style is used.
1425 return {};
1426
1427 auto WorkingDir = getCurrentWorkingDirectory();
1428 if (!WorkingDir)
1429 return WorkingDir.getError();
1430
1431 return makeAbsolute(WorkingDir: WorkingDir.get(), Path);
1432}
1433
1434std::error_code
1435RedirectingFileSystem::makeAbsolute(StringRef WorkingDir,
1436 SmallVectorImpl<char> &Path) const {
1437 // We can't use sys::fs::make_absolute because that assumes the path style
1438 // is native and there is no way to override that. Since we know WorkingDir
1439 // is absolute, we can use it to determine which style we actually have and
1440 // append Path ourselves.
1441 if (!WorkingDir.empty() &&
1442 !sys::path::is_absolute(path: WorkingDir, style: sys::path::Style::posix) &&
1443 !sys::path::is_absolute(path: WorkingDir,
1444 style: sys::path::Style::windows_backslash)) {
1445 return std::error_code();
1446 }
1447 sys::path::Style style = sys::path::Style::windows_backslash;
1448 if (sys::path::is_absolute(path: WorkingDir, style: sys::path::Style::posix)) {
1449 style = sys::path::Style::posix;
1450 } else {
1451 // Distinguish between windows_backslash and windows_slash; getExistingStyle
1452 // returns posix for a path with windows_slash.
1453 if (getExistingStyle(Path: WorkingDir) != sys::path::Style::windows_backslash)
1454 style = sys::path::Style::windows_slash;
1455 }
1456
1457 std::string Result = std::string(WorkingDir);
1458 StringRef Dir(Result);
1459 if (!Dir.ends_with(Suffix: sys::path::get_separator(style))) {
1460 Result += sys::path::get_separator(style);
1461 }
1462 // backslashes '\' are legit path charactors under POSIX. Windows APIs
1463 // like CreateFile accepts forward slashes '/' as path
1464 // separator (even when mixed with backslashes). Therefore,
1465 // `Path` should be directly appended to `WorkingDir` without converting
1466 // path separator.
1467 Result.append(s: Path.data(), n: Path.size());
1468 Path.assign(in_start: Result.begin(), in_end: Result.end());
1469
1470 return {};
1471}
1472
1473directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
1474 std::error_code &EC) {
1475 SmallString<256> Path;
1476 Dir.toVector(Out&: Path);
1477
1478 EC = makeAbsolute(Path);
1479 if (EC)
1480 return {};
1481
1482 ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
1483 if (!Result) {
1484 if (Redirection != RedirectKind::RedirectOnly &&
1485 isFileNotFound(EC: Result.getError()))
1486 return ExternalFS->dir_begin(Dir: Path, EC);
1487
1488 EC = Result.getError();
1489 return {};
1490 }
1491
1492 // Use status to make sure the path exists and refers to a directory.
1493 ErrorOr<Status> S = status(LookupPath: Path, OriginalPath: Dir, Result: *Result);
1494 if (!S) {
1495 if (Redirection != RedirectKind::RedirectOnly &&
1496 isFileNotFound(EC: S.getError(), E: Result->E))
1497 return ExternalFS->dir_begin(Dir, EC);
1498
1499 EC = S.getError();
1500 return {};
1501 }
1502
1503 if (!S->isDirectory()) {
1504 EC = errc::not_a_directory;
1505 return {};
1506 }
1507
1508 // Create the appropriate directory iterator based on whether we found a
1509 // DirectoryRemapEntry or DirectoryEntry.
1510 directory_iterator RedirectIter;
1511 std::error_code RedirectEC;
1512 if (auto ExtRedirect = Result->getExternalRedirect()) {
1513 auto RE = cast<RedirectingFileSystem::RemapEntry>(Val: Result->E);
1514 RedirectIter = ExternalFS->dir_begin(Dir: *ExtRedirect, EC&: RedirectEC);
1515
1516 if (!RE->useExternalName(GlobalUseExternalName: UseExternalNames)) {
1517 // Update the paths in the results to use the virtual directory's path.
1518 RedirectIter =
1519 directory_iterator(std::make_shared<RedirectingFSDirRemapIterImpl>(
1520 args: std::string(Path), args&: RedirectIter));
1521 }
1522 } else {
1523 auto DE = cast<DirectoryEntry>(Val: Result->E);
1524 RedirectIter =
1525 directory_iterator(std::make_shared<RedirectingFSDirIterImpl>(
1526 args&: Path, args: DE->contents_begin(), args: DE->contents_end(), args&: RedirectEC));
1527 }
1528
1529 if (RedirectEC) {
1530 if (RedirectEC != errc::no_such_file_or_directory) {
1531 EC = RedirectEC;
1532 return {};
1533 }
1534 RedirectIter = {};
1535 }
1536
1537 if (Redirection == RedirectKind::RedirectOnly) {
1538 EC = RedirectEC;
1539 return RedirectIter;
1540 }
1541
1542 std::error_code ExternalEC;
1543 directory_iterator ExternalIter = ExternalFS->dir_begin(Dir: Path, EC&: ExternalEC);
1544 if (ExternalEC) {
1545 if (ExternalEC != errc::no_such_file_or_directory) {
1546 EC = ExternalEC;
1547 return {};
1548 }
1549 ExternalIter = {};
1550 }
1551
1552 SmallVector<directory_iterator, 2> Iters;
1553 switch (Redirection) {
1554 case RedirectKind::Fallthrough:
1555 Iters.push_back(Elt: ExternalIter);
1556 Iters.push_back(Elt: RedirectIter);
1557 break;
1558 case RedirectKind::Fallback:
1559 Iters.push_back(Elt: RedirectIter);
1560 Iters.push_back(Elt: ExternalIter);
1561 break;
1562 default:
1563 llvm_unreachable("unhandled RedirectKind");
1564 }
1565
1566 directory_iterator Combined{
1567 std::make_shared<CombiningDirIterImpl>(args&: Iters, args&: EC)};
1568 if (EC)
1569 return {};
1570 return Combined;
1571}
1572
1573void RedirectingFileSystem::setOverlayFileDir(StringRef Dir) {
1574 OverlayFileDir = Dir.str();
1575}
1576
1577StringRef RedirectingFileSystem::getOverlayFileDir() const {
1578 return OverlayFileDir;
1579}
1580
1581void RedirectingFileSystem::setFallthrough(bool Fallthrough) {
1582 if (Fallthrough) {
1583 Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
1584 } else {
1585 Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
1586 }
1587}
1588
1589void RedirectingFileSystem::setRedirection(
1590 RedirectingFileSystem::RedirectKind Kind) {
1591 Redirection = Kind;
1592}
1593
1594std::vector<StringRef> RedirectingFileSystem::getRoots() const {
1595 std::vector<StringRef> R;
1596 R.reserve(n: Roots.size());
1597 for (const auto &Root : Roots)
1598 R.push_back(x: Root->getName());
1599 return R;
1600}
1601
1602void RedirectingFileSystem::printImpl(raw_ostream &OS, PrintType Type,
1603 unsigned IndentLevel) const {
1604 printIndent(OS, IndentLevel);
1605 OS << "RedirectingFileSystem (UseExternalNames: "
1606 << (UseExternalNames ? "true" : "false") << ")\n";
1607 if (Type == PrintType::Summary)
1608 return;
1609
1610 for (const auto &Root : Roots)
1611 printEntry(OS, E: Root.get(), IndentLevel);
1612
1613 printIndent(OS, IndentLevel);
1614 OS << "ExternalFS:\n";
1615 ExternalFS->print(OS, Type: Type == PrintType::Contents ? PrintType::Summary : Type,
1616 IndentLevel: IndentLevel + 1);
1617}
1618
1619void RedirectingFileSystem::printEntry(raw_ostream &OS,
1620 RedirectingFileSystem::Entry *E,
1621 unsigned IndentLevel) const {
1622 printIndent(OS, IndentLevel);
1623 OS << "'" << E->getName() << "'";
1624
1625 switch (E->getKind()) {
1626 case EK_Directory: {
1627 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Val: E);
1628
1629 OS << "\n";
1630 for (std::unique_ptr<Entry> &SubEntry :
1631 llvm::make_range(x: DE->contents_begin(), y: DE->contents_end()))
1632 printEntry(OS, E: SubEntry.get(), IndentLevel: IndentLevel + 1);
1633 break;
1634 }
1635 case EK_DirectoryRemap:
1636 case EK_File: {
1637 auto *RE = cast<RedirectingFileSystem::RemapEntry>(Val: E);
1638 OS << " -> '" << RE->getExternalContentsPath() << "'";
1639 switch (RE->getUseName()) {
1640 case NK_NotSet:
1641 break;
1642 case NK_External:
1643 OS << " (UseExternalName: true)";
1644 break;
1645 case NK_Virtual:
1646 OS << " (UseExternalName: false)";
1647 break;
1648 }
1649 OS << "\n";
1650 break;
1651 }
1652 }
1653}
1654
1655void RedirectingFileSystem::visitChildFileSystems(VisitCallbackTy Callback) {
1656 if (ExternalFS) {
1657 Callback(*ExternalFS);
1658 ExternalFS->visitChildFileSystems(Callback);
1659 }
1660}
1661
1662/// A helper class to hold the common YAML parsing state.
1663class llvm::vfs::RedirectingFileSystemParser {
1664 yaml::Stream &Stream;
1665
1666 void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1667
1668 // false on error
1669 bool parseScalarString(yaml::Node *N, StringRef &Result,
1670 SmallVectorImpl<char> &Storage) {
1671 const auto *S = dyn_cast<yaml::ScalarNode>(Val: N);
1672
1673 if (!S) {
1674 error(N, Msg: "expected string");
1675 return false;
1676 }
1677 Result = S->getValue(Storage);
1678 return true;
1679 }
1680
1681 // false on error
1682 bool parseScalarBool(yaml::Node *N, bool &Result) {
1683 SmallString<5> Storage;
1684 StringRef Value;
1685 if (!parseScalarString(N, Result&: Value, Storage))
1686 return false;
1687
1688 if (Value.equals_insensitive(RHS: "true") || Value.equals_insensitive(RHS: "on") ||
1689 Value.equals_insensitive(RHS: "yes") || Value == "1") {
1690 Result = true;
1691 return true;
1692 } else if (Value.equals_insensitive(RHS: "false") ||
1693 Value.equals_insensitive(RHS: "off") ||
1694 Value.equals_insensitive(RHS: "no") || Value == "0") {
1695 Result = false;
1696 return true;
1697 }
1698
1699 error(N, Msg: "expected boolean value");
1700 return false;
1701 }
1702
1703 std::optional<RedirectingFileSystem::RedirectKind>
1704 parseRedirectKind(yaml::Node *N) {
1705 SmallString<12> Storage;
1706 StringRef Value;
1707 if (!parseScalarString(N, Result&: Value, Storage))
1708 return std::nullopt;
1709
1710 if (Value.equals_insensitive(RHS: "fallthrough")) {
1711 return RedirectingFileSystem::RedirectKind::Fallthrough;
1712 } else if (Value.equals_insensitive(RHS: "fallback")) {
1713 return RedirectingFileSystem::RedirectKind::Fallback;
1714 } else if (Value.equals_insensitive(RHS: "redirect-only")) {
1715 return RedirectingFileSystem::RedirectKind::RedirectOnly;
1716 }
1717 return std::nullopt;
1718 }
1719
1720 std::optional<RedirectingFileSystem::RootRelativeKind>
1721 parseRootRelativeKind(yaml::Node *N) {
1722 SmallString<12> Storage;
1723 StringRef Value;
1724 if (!parseScalarString(N, Result&: Value, Storage))
1725 return std::nullopt;
1726 if (Value.equals_insensitive(RHS: "cwd")) {
1727 return RedirectingFileSystem::RootRelativeKind::CWD;
1728 } else if (Value.equals_insensitive(RHS: "overlay-dir")) {
1729 return RedirectingFileSystem::RootRelativeKind::OverlayDir;
1730 }
1731 return std::nullopt;
1732 }
1733
1734 struct KeyStatus {
1735 bool Required;
1736 bool Seen = false;
1737
1738 KeyStatus(bool Required = false) : Required(Required) {}
1739 };
1740
1741 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1742
1743 // false on error
1744 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1745 DenseMap<StringRef, KeyStatus> &Keys) {
1746 auto It = Keys.find(Val: Key);
1747 if (It == Keys.end()) {
1748 error(N: KeyNode, Msg: "unknown key");
1749 return false;
1750 }
1751 KeyStatus &S = It->second;
1752 if (S.Seen) {
1753 error(N: KeyNode, Msg: Twine("duplicate key '") + Key + "'");
1754 return false;
1755 }
1756 S.Seen = true;
1757 return true;
1758 }
1759
1760 // false on error
1761 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1762 for (const auto &I : Keys) {
1763 if (I.second.Required && !I.second.Seen) {
1764 error(N: Obj, Msg: Twine("missing key '") + I.first + "'");
1765 return false;
1766 }
1767 }
1768 return true;
1769 }
1770
1771public:
1772 static RedirectingFileSystem::Entry *
1773 lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1774 RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1775 if (!ParentEntry) { // Look for a existent root
1776 for (const auto &Root : FS->Roots) {
1777 if (Name == Root->getName()) {
1778 ParentEntry = Root.get();
1779 return ParentEntry;
1780 }
1781 }
1782 } else { // Advance to the next component
1783 auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(Val: ParentEntry);
1784 for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1785 llvm::make_range(x: DE->contents_begin(), y: DE->contents_end())) {
1786 auto *DirContent =
1787 dyn_cast<RedirectingFileSystem::DirectoryEntry>(Val: Content.get());
1788 if (DirContent && Name == Content->getName())
1789 return DirContent;
1790 }
1791 }
1792
1793 // ... or create a new one
1794 std::unique_ptr<RedirectingFileSystem::Entry> E =
1795 std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1796 args&: Name, args: Status("", getNextVirtualUniqueID(),
1797 std::chrono::system_clock::now(), 0, 0, 0,
1798 file_type::directory_file, sys::fs::all_all));
1799
1800 if (!ParentEntry) { // Add a new root to the overlay
1801 FS->Roots.push_back(x: std::move(E));
1802 ParentEntry = FS->Roots.back().get();
1803 return ParentEntry;
1804 }
1805
1806 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Val: ParentEntry);
1807 DE->addContent(Content: std::move(E));
1808 return DE->getLastContent();
1809 }
1810
1811private:
1812 void uniqueOverlayTree(RedirectingFileSystem *FS,
1813 RedirectingFileSystem::Entry *SrcE,
1814 RedirectingFileSystem::Entry *NewParentE = nullptr) {
1815 StringRef Name = SrcE->getName();
1816 switch (SrcE->getKind()) {
1817 case RedirectingFileSystem::EK_Directory: {
1818 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Val: SrcE);
1819 // Empty directories could be present in the YAML as a way to
1820 // describe a file for a current directory after some of its subdir
1821 // is parsed. This only leads to redundant walks, ignore it.
1822 if (!Name.empty())
1823 NewParentE = lookupOrCreateEntry(FS, Name, ParentEntry: NewParentE);
1824 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1825 llvm::make_range(x: DE->contents_begin(), y: DE->contents_end()))
1826 uniqueOverlayTree(FS, SrcE: SubEntry.get(), NewParentE);
1827 break;
1828 }
1829 case RedirectingFileSystem::EK_DirectoryRemap: {
1830 assert(NewParentE && "Parent entry must exist");
1831 auto *DR = cast<RedirectingFileSystem::DirectoryRemapEntry>(Val: SrcE);
1832 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Val: NewParentE);
1833 DE->addContent(
1834 Content: std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1835 args&: Name, args: DR->getExternalContentsPath(), args: DR->getUseName()));
1836 break;
1837 }
1838 case RedirectingFileSystem::EK_File: {
1839 assert(NewParentE && "Parent entry must exist");
1840 auto *FE = cast<RedirectingFileSystem::FileEntry>(Val: SrcE);
1841 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Val: NewParentE);
1842 DE->addContent(Content: std::make_unique<RedirectingFileSystem::FileEntry>(
1843 args&: Name, args: FE->getExternalContentsPath(), args: FE->getUseName()));
1844 break;
1845 }
1846 }
1847 }
1848
1849 std::unique_ptr<RedirectingFileSystem::Entry>
1850 parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1851 auto *M = dyn_cast<yaml::MappingNode>(Val: N);
1852 if (!M) {
1853 error(N, Msg: "expected mapping node for file or directory entry");
1854 return nullptr;
1855 }
1856
1857 KeyStatusPair Fields[] = {
1858 KeyStatusPair("name", true),
1859 KeyStatusPair("type", true),
1860 KeyStatusPair("contents", false),
1861 KeyStatusPair("external-contents", false),
1862 KeyStatusPair("use-external-name", false),
1863 };
1864
1865 DenseMap<StringRef, KeyStatus> Keys(std::begin(arr&: Fields), std::end(arr&: Fields));
1866
1867 enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet;
1868 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1869 EntryArrayContents;
1870 SmallString<256> ExternalContentsPath;
1871 SmallString<256> Name;
1872 yaml::Node *NameValueNode = nullptr;
1873 auto UseExternalName = RedirectingFileSystem::NK_NotSet;
1874 RedirectingFileSystem::EntryKind Kind;
1875
1876 for (auto &I : *M) {
1877 StringRef Key;
1878 // Reuse the buffer for key and value, since we don't look at key after
1879 // parsing value.
1880 SmallString<256> Buffer;
1881 if (!parseScalarString(N: I.getKey(), Result&: Key, Storage&: Buffer))
1882 return nullptr;
1883
1884 if (!checkDuplicateOrUnknownKey(KeyNode: I.getKey(), Key, Keys))
1885 return nullptr;
1886
1887 StringRef Value;
1888 if (Key == "name") {
1889 if (!parseScalarString(N: I.getValue(), Result&: Value, Storage&: Buffer))
1890 return nullptr;
1891
1892 NameValueNode = I.getValue();
1893 // Guarantee that old YAML files containing paths with ".." and "."
1894 // are properly canonicalized before read into the VFS.
1895 Name = canonicalize(Path: Value).str();
1896 } else if (Key == "type") {
1897 if (!parseScalarString(N: I.getValue(), Result&: Value, Storage&: Buffer))
1898 return nullptr;
1899 if (Value == "file")
1900 Kind = RedirectingFileSystem::EK_File;
1901 else if (Value == "directory")
1902 Kind = RedirectingFileSystem::EK_Directory;
1903 else if (Value == "directory-remap")
1904 Kind = RedirectingFileSystem::EK_DirectoryRemap;
1905 else {
1906 error(N: I.getValue(), Msg: "unknown value for 'type'");
1907 return nullptr;
1908 }
1909 } else if (Key == "contents") {
1910 if (ContentsField != CF_NotSet) {
1911 error(N: I.getKey(),
1912 Msg: "entry already has 'contents' or 'external-contents'");
1913 return nullptr;
1914 }
1915 ContentsField = CF_List;
1916 auto *Contents = dyn_cast<yaml::SequenceNode>(Val: I.getValue());
1917 if (!Contents) {
1918 // FIXME: this is only for directories, what about files?
1919 error(N: I.getValue(), Msg: "expected array");
1920 return nullptr;
1921 }
1922
1923 for (auto &I : *Contents) {
1924 if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1925 parseEntry(N: &I, FS, /*IsRootEntry*/ false))
1926 EntryArrayContents.push_back(x: std::move(E));
1927 else
1928 return nullptr;
1929 }
1930 } else if (Key == "external-contents") {
1931 if (ContentsField != CF_NotSet) {
1932 error(N: I.getKey(),
1933 Msg: "entry already has 'contents' or 'external-contents'");
1934 return nullptr;
1935 }
1936 ContentsField = CF_External;
1937 if (!parseScalarString(N: I.getValue(), Result&: Value, Storage&: Buffer))
1938 return nullptr;
1939
1940 SmallString<256> FullPath;
1941 if (FS->IsRelativeOverlay) {
1942 FullPath = FS->getOverlayFileDir();
1943 assert(!FullPath.empty() &&
1944 "External contents prefix directory must exist");
1945 SmallString<256> AbsFullPath = Value;
1946 if (FS->makeAbsolute(WorkingDir: FullPath, Path&: AbsFullPath)) {
1947 error(N, Msg: "failed to make 'external-contents' absolute");
1948 return nullptr;
1949 }
1950 FullPath = AbsFullPath;
1951 } else {
1952 FullPath = Value;
1953 }
1954
1955 // Guarantee that old YAML files containing paths with ".." and "."
1956 // are properly canonicalized before read into the VFS.
1957 FullPath = canonicalize(Path: FullPath);
1958 ExternalContentsPath = FullPath.str();
1959 } else if (Key == "use-external-name") {
1960 bool Val;
1961 if (!parseScalarBool(N: I.getValue(), Result&: Val))
1962 return nullptr;
1963 UseExternalName = Val ? RedirectingFileSystem::NK_External
1964 : RedirectingFileSystem::NK_Virtual;
1965 } else {
1966 llvm_unreachable("key missing from Keys");
1967 }
1968 }
1969
1970 if (Stream.failed())
1971 return nullptr;
1972
1973 // check for missing keys
1974 if (ContentsField == CF_NotSet) {
1975 error(N, Msg: "missing key 'contents' or 'external-contents'");
1976 return nullptr;
1977 }
1978 if (!checkMissingKeys(Obj: N, Keys))
1979 return nullptr;
1980
1981 // check invalid configuration
1982 if (Kind == RedirectingFileSystem::EK_Directory &&
1983 UseExternalName != RedirectingFileSystem::NK_NotSet) {
1984 error(N, Msg: "'use-external-name' is not supported for 'directory' entries");
1985 return nullptr;
1986 }
1987
1988 if (Kind == RedirectingFileSystem::EK_DirectoryRemap &&
1989 ContentsField == CF_List) {
1990 error(N, Msg: "'contents' is not supported for 'directory-remap' entries");
1991 return nullptr;
1992 }
1993
1994 sys::path::Style path_style = sys::path::Style::native;
1995 if (IsRootEntry) {
1996 // VFS root entries may be in either Posix or Windows style. Figure out
1997 // which style we have, and use it consistently.
1998 if (sys::path::is_absolute(path: Name, style: sys::path::Style::posix)) {
1999 path_style = sys::path::Style::posix;
2000 } else if (sys::path::is_absolute(path: Name,
2001 style: sys::path::Style::windows_backslash)) {
2002 path_style = sys::path::Style::windows_backslash;
2003 } else {
2004 // Relative VFS root entries are made absolute to either the overlay
2005 // directory, or the current working directory, then we can determine
2006 // the path style from that.
2007 std::error_code EC;
2008 if (FS->RootRelative ==
2009 RedirectingFileSystem::RootRelativeKind::OverlayDir) {
2010 StringRef FullPath = FS->getOverlayFileDir();
2011 assert(!FullPath.empty() && "Overlay file directory must exist");
2012 EC = FS->makeAbsolute(WorkingDir: FullPath, Path&: Name);
2013 Name = canonicalize(Path: Name);
2014 } else {
2015 EC = FS->makeAbsolute(Path&: Name);
2016 }
2017 if (EC) {
2018 assert(NameValueNode && "Name presence should be checked earlier");
2019 error(
2020 N: NameValueNode,
2021 Msg: "entry with relative path at the root level is not discoverable");
2022 return nullptr;
2023 }
2024 path_style = sys::path::is_absolute(path: Name, style: sys::path::Style::posix)
2025 ? sys::path::Style::posix
2026 : sys::path::Style::windows_backslash;
2027 }
2028 // is::path::is_absolute(Name, sys::path::Style::windows_backslash) will
2029 // return true even if `Name` is using forward slashes. Distinguish
2030 // between windows_backslash and windows_slash.
2031 if (path_style == sys::path::Style::windows_backslash &&
2032 getExistingStyle(Path: Name) != sys::path::Style::windows_backslash)
2033 path_style = sys::path::Style::windows_slash;
2034 }
2035
2036 // Remove trailing slash(es), being careful not to remove the root path
2037 StringRef Trimmed = Name;
2038 size_t RootPathLen = sys::path::root_path(path: Trimmed, style: path_style).size();
2039 while (Trimmed.size() > RootPathLen &&
2040 sys::path::is_separator(value: Trimmed.back(), style: path_style))
2041 Trimmed = Trimmed.slice(Start: 0, End: Trimmed.size() - 1);
2042
2043 // Get the last component
2044 StringRef LastComponent = sys::path::filename(path: Trimmed, style: path_style);
2045
2046 std::unique_ptr<RedirectingFileSystem::Entry> Result;
2047 switch (Kind) {
2048 case RedirectingFileSystem::EK_File:
2049 Result = std::make_unique<RedirectingFileSystem::FileEntry>(
2050 args&: LastComponent, args: std::move(ExternalContentsPath), args&: UseExternalName);
2051 break;
2052 case RedirectingFileSystem::EK_DirectoryRemap:
2053 Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
2054 args&: LastComponent, args: std::move(ExternalContentsPath), args&: UseExternalName);
2055 break;
2056 case RedirectingFileSystem::EK_Directory:
2057 Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
2058 args&: LastComponent, args: std::move(EntryArrayContents),
2059 args: Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
2060 0, 0, 0, file_type::directory_file, sys::fs::all_all));
2061 break;
2062 }
2063
2064 StringRef Parent = sys::path::parent_path(path: Trimmed, style: path_style);
2065 if (Parent.empty())
2066 return Result;
2067
2068 // if 'name' contains multiple components, create implicit directory entries
2069 for (sys::path::reverse_iterator I = sys::path::rbegin(path: Parent, style: path_style),
2070 E = sys::path::rend(path: Parent);
2071 I != E; ++I) {
2072 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
2073 Entries.push_back(x: std::move(Result));
2074 Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
2075 args: *I, args: std::move(Entries),
2076 args: Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
2077 0, 0, 0, file_type::directory_file, sys::fs::all_all));
2078 }
2079 return Result;
2080 }
2081
2082public:
2083 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
2084
2085 // false on error
2086 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
2087 auto *Top = dyn_cast<yaml::MappingNode>(Val: Root);
2088 if (!Top) {
2089 error(N: Root, Msg: "expected mapping node");
2090 return false;
2091 }
2092
2093 KeyStatusPair Fields[] = {
2094 KeyStatusPair("version", true),
2095 KeyStatusPair("case-sensitive", false),
2096 KeyStatusPair("use-external-names", false),
2097 KeyStatusPair("root-relative", false),
2098 KeyStatusPair("overlay-relative", false),
2099 KeyStatusPair("fallthrough", false),
2100 KeyStatusPair("redirecting-with", false),
2101 KeyStatusPair("roots", true),
2102 };
2103
2104 DenseMap<StringRef, KeyStatus> Keys(std::begin(arr&: Fields), std::end(arr&: Fields));
2105 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
2106
2107 // Parse configuration and 'roots'
2108 for (auto &I : *Top) {
2109 SmallString<10> KeyBuffer;
2110 StringRef Key;
2111 if (!parseScalarString(N: I.getKey(), Result&: Key, Storage&: KeyBuffer))
2112 return false;
2113
2114 if (!checkDuplicateOrUnknownKey(KeyNode: I.getKey(), Key, Keys))
2115 return false;
2116
2117 if (Key == "roots") {
2118 auto *Roots = dyn_cast<yaml::SequenceNode>(Val: I.getValue());
2119 if (!Roots) {
2120 error(N: I.getValue(), Msg: "expected array");
2121 return false;
2122 }
2123
2124 for (auto &I : *Roots) {
2125 if (std::unique_ptr<RedirectingFileSystem::Entry> E =
2126 parseEntry(N: &I, FS, /*IsRootEntry*/ true))
2127 RootEntries.push_back(x: std::move(E));
2128 else
2129 return false;
2130 }
2131 } else if (Key == "version") {
2132 StringRef VersionString;
2133 SmallString<4> Storage;
2134 if (!parseScalarString(N: I.getValue(), Result&: VersionString, Storage))
2135 return false;
2136 int Version;
2137 if (VersionString.getAsInteger<int>(Radix: 10, Result&: Version)) {
2138 error(N: I.getValue(), Msg: "expected integer");
2139 return false;
2140 }
2141 if (Version < 0) {
2142 error(N: I.getValue(), Msg: "invalid version number");
2143 return false;
2144 }
2145 if (Version != 0) {
2146 error(N: I.getValue(), Msg: "version mismatch, expected 0");
2147 return false;
2148 }
2149 } else if (Key == "case-sensitive") {
2150 if (!parseScalarBool(N: I.getValue(), Result&: FS->CaseSensitive))
2151 return false;
2152 } else if (Key == "overlay-relative") {
2153 if (!parseScalarBool(N: I.getValue(), Result&: FS->IsRelativeOverlay))
2154 return false;
2155 } else if (Key == "use-external-names") {
2156 if (!parseScalarBool(N: I.getValue(), Result&: FS->UseExternalNames))
2157 return false;
2158 } else if (Key == "fallthrough") {
2159 if (Keys["redirecting-with"].Seen) {
2160 error(N: I.getValue(),
2161 Msg: "'fallthrough' and 'redirecting-with' are mutually exclusive");
2162 return false;
2163 }
2164
2165 bool ShouldFallthrough = false;
2166 if (!parseScalarBool(N: I.getValue(), Result&: ShouldFallthrough))
2167 return false;
2168
2169 if (ShouldFallthrough) {
2170 FS->Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
2171 } else {
2172 FS->Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
2173 }
2174 } else if (Key == "redirecting-with") {
2175 if (Keys["fallthrough"].Seen) {
2176 error(N: I.getValue(),
2177 Msg: "'fallthrough' and 'redirecting-with' are mutually exclusive");
2178 return false;
2179 }
2180
2181 if (auto Kind = parseRedirectKind(N: I.getValue())) {
2182 FS->Redirection = *Kind;
2183 } else {
2184 error(N: I.getValue(), Msg: "expected valid redirect kind");
2185 return false;
2186 }
2187 } else if (Key == "root-relative") {
2188 if (auto Kind = parseRootRelativeKind(N: I.getValue())) {
2189 FS->RootRelative = *Kind;
2190 } else {
2191 error(N: I.getValue(), Msg: "expected valid root-relative kind");
2192 return false;
2193 }
2194 } else {
2195 llvm_unreachable("key missing from Keys");
2196 }
2197 }
2198
2199 if (Stream.failed())
2200 return false;
2201
2202 if (!checkMissingKeys(Obj: Top, Keys))
2203 return false;
2204
2205 // Now that we sucessefully parsed the YAML file, canonicalize the internal
2206 // representation to a proper directory tree so that we can search faster
2207 // inside the VFS.
2208 for (auto &E : RootEntries)
2209 uniqueOverlayTree(FS, SrcE: E.get());
2210
2211 return true;
2212 }
2213};
2214
2215std::unique_ptr<RedirectingFileSystem>
2216RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
2217 SourceMgr::DiagHandlerTy DiagHandler,
2218 StringRef YAMLFilePath, void *DiagContext,
2219 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2220 SourceMgr SM;
2221 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
2222
2223 SM.setDiagHandler(DH: DiagHandler, Ctx: DiagContext);
2224 yaml::document_iterator DI = Stream.begin();
2225 yaml::Node *Root = DI->getRoot();
2226 if (DI == Stream.end() || !Root) {
2227 SM.PrintMessage(Loc: SMLoc(), Kind: SourceMgr::DK_Error, Msg: "expected root node");
2228 return nullptr;
2229 }
2230
2231 RedirectingFileSystemParser P(Stream);
2232
2233 std::unique_ptr<RedirectingFileSystem> FS(
2234 new RedirectingFileSystem(ExternalFS));
2235
2236 if (!YAMLFilePath.empty()) {
2237 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
2238 // to each 'external-contents' path.
2239 //
2240 // Example:
2241 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
2242 // yields:
2243 // FS->OverlayFileDir => /<absolute_path_to>/dummy.cache/vfs
2244 //
2245 SmallString<256> OverlayAbsDir = sys::path::parent_path(path: YAMLFilePath);
2246 std::error_code EC = FS->makeAbsolute(Path&: OverlayAbsDir);
2247 assert(!EC && "Overlay dir final path must be absolute");
2248 (void)EC;
2249 FS->setOverlayFileDir(OverlayAbsDir);
2250 }
2251
2252 if (!P.parse(Root, FS: FS.get()))
2253 return nullptr;
2254
2255 return FS;
2256}
2257
2258std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create(
2259 ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
2260 bool UseExternalNames, llvm::IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2261 std::unique_ptr<RedirectingFileSystem> FS(
2262 new RedirectingFileSystem(ExternalFS));
2263 FS->UseExternalNames = UseExternalNames;
2264
2265 StringMap<RedirectingFileSystem::Entry *> Entries;
2266
2267 for (auto &Mapping : llvm::reverse(C&: RemappedFiles)) {
2268 SmallString<128> From = StringRef(Mapping.first);
2269 SmallString<128> To = StringRef(Mapping.second);
2270 {
2271 auto EC = ExternalFS->makeAbsolute(Path&: From);
2272 (void)EC;
2273 assert(!EC && "Could not make absolute path");
2274 }
2275
2276 // Check if we've already mapped this file. The first one we see (in the
2277 // reverse iteration) wins.
2278 RedirectingFileSystem::Entry *&ToEntry = Entries[From];
2279 if (ToEntry)
2280 continue;
2281
2282 // Add parent directories.
2283 RedirectingFileSystem::Entry *Parent = nullptr;
2284 StringRef FromDirectory = llvm::sys::path::parent_path(path: From);
2285 for (auto I = llvm::sys::path::begin(path: FromDirectory),
2286 E = llvm::sys::path::end(path: FromDirectory);
2287 I != E; ++I) {
2288 Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS: FS.get(), Name: *I,
2289 ParentEntry: Parent);
2290 }
2291 assert(Parent && "File without a directory?");
2292 {
2293 auto EC = ExternalFS->makeAbsolute(Path&: To);
2294 (void)EC;
2295 assert(!EC && "Could not make absolute path");
2296 }
2297
2298 // Add the file.
2299 auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>(
2300 args: llvm::sys::path::filename(path: From), args&: To,
2301 args: UseExternalNames ? RedirectingFileSystem::NK_External
2302 : RedirectingFileSystem::NK_Virtual);
2303 ToEntry = NewFile.get();
2304 cast<RedirectingFileSystem::DirectoryEntry>(Val: Parent)->addContent(
2305 Content: std::move(NewFile));
2306 }
2307
2308 return FS;
2309}
2310
2311RedirectingFileSystem::LookupResult::LookupResult(
2312 Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
2313 : E(E) {
2314 assert(E != nullptr);
2315 // If the matched entry is a DirectoryRemapEntry, set ExternalRedirect to the
2316 // path of the directory it maps to in the external file system plus any
2317 // remaining path components in the provided iterator.
2318 if (auto *DRE = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(Val: E)) {
2319 SmallString<256> Redirect(DRE->getExternalContentsPath());
2320 sys::path::append(path&: Redirect, begin: Start, end: End,
2321 style: getExistingStyle(Path: DRE->getExternalContentsPath()));
2322 ExternalRedirect = std::string(Redirect);
2323 }
2324}
2325
2326void RedirectingFileSystem::LookupResult::getPath(
2327 llvm::SmallVectorImpl<char> &Result) const {
2328 Result.clear();
2329 for (Entry *Parent : Parents)
2330 llvm::sys::path::append(path&: Result, a: Parent->getName());
2331 llvm::sys::path::append(path&: Result, a: E->getName());
2332}
2333
2334std::error_code RedirectingFileSystem::makeCanonicalForLookup(
2335 SmallVectorImpl<char> &Path) const {
2336 if (std::error_code EC = makeAbsolute(Path))
2337 return EC;
2338
2339 llvm::SmallString<256> CanonicalPath =
2340 canonicalize(Path: StringRef(Path.data(), Path.size()));
2341 if (CanonicalPath.empty())
2342 return make_error_code(E: llvm::errc::invalid_argument);
2343
2344 Path.assign(in_start: CanonicalPath.begin(), in_end: CanonicalPath.end());
2345 return {};
2346}
2347
2348ErrorOr<RedirectingFileSystem::LookupResult>
2349RedirectingFileSystem::lookupPath(StringRef Path) const {
2350 llvm::SmallString<128> CanonicalPath(Path);
2351 if (std::error_code EC = makeCanonicalForLookup(Path&: CanonicalPath))
2352 return EC;
2353
2354 // RedirectOnly means the VFS is always used.
2355 if (UsageTrackingActive && Redirection == RedirectKind::RedirectOnly)
2356 HasBeenUsed = true;
2357
2358 sys::path::const_iterator Start = sys::path::begin(path: CanonicalPath);
2359 sys::path::const_iterator End = sys::path::end(path: CanonicalPath);
2360 llvm::SmallVector<Entry *, 32> Entries;
2361 for (const auto &Root : Roots) {
2362 ErrorOr<RedirectingFileSystem::LookupResult> Result =
2363 lookupPathImpl(Start, End, From: Root.get(), Entries);
2364 if (UsageTrackingActive && Result && isa<RemapEntry>(Val: Result->E))
2365 HasBeenUsed = true;
2366 if (Result) {
2367 Result->Parents = std::move(Entries);
2368 return Result;
2369 }
2370
2371 if (Result.getError() != llvm::errc::no_such_file_or_directory)
2372 return Result;
2373 }
2374 return make_error_code(E: llvm::errc::no_such_file_or_directory);
2375}
2376
2377ErrorOr<RedirectingFileSystem::LookupResult>
2378RedirectingFileSystem::lookupPathImpl(
2379 sys::path::const_iterator Start, sys::path::const_iterator End,
2380 RedirectingFileSystem::Entry *From,
2381 llvm::SmallVectorImpl<Entry *> &Entries) const {
2382 assert(!isTraversalComponent(*Start) &&
2383 !isTraversalComponent(From->getName()) &&
2384 "Paths should not contain traversal components");
2385
2386 StringRef FromName = From->getName();
2387
2388 // Forward the search to the next component in case this is an empty one.
2389 if (!FromName.empty()) {
2390 if (!pathComponentMatches(lhs: *Start, rhs: FromName))
2391 return make_error_code(E: llvm::errc::no_such_file_or_directory);
2392
2393 ++Start;
2394
2395 if (Start == End) {
2396 // Match!
2397 return LookupResult(From, Start, End);
2398 }
2399 }
2400
2401 if (isa<RedirectingFileSystem::FileEntry>(Val: From))
2402 return make_error_code(E: llvm::errc::not_a_directory);
2403
2404 if (isa<RedirectingFileSystem::DirectoryRemapEntry>(Val: From))
2405 return LookupResult(From, Start, End);
2406
2407 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Val: From);
2408 for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
2409 llvm::make_range(x: DE->contents_begin(), y: DE->contents_end())) {
2410 Entries.push_back(Elt: From);
2411 ErrorOr<RedirectingFileSystem::LookupResult> Result =
2412 lookupPathImpl(Start, End, From: DirEntry.get(), Entries);
2413 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
2414 return Result;
2415 Entries.pop_back();
2416 }
2417
2418 return make_error_code(E: llvm::errc::no_such_file_or_directory);
2419}
2420
2421static Status getRedirectedFileStatus(const Twine &OriginalPath,
2422 bool UseExternalNames,
2423 Status ExternalStatus) {
2424 // The path has been mapped by some nested VFS and exposes an external path,
2425 // don't override it with the original path.
2426 if (ExternalStatus.ExposesExternalVFSPath)
2427 return ExternalStatus;
2428
2429 Status S = ExternalStatus;
2430 if (!UseExternalNames)
2431 S = Status::copyWithNewName(In: S, NewName: OriginalPath);
2432 else
2433 S.ExposesExternalVFSPath = true;
2434 return S;
2435}
2436
2437ErrorOr<Status> RedirectingFileSystem::status(
2438 const Twine &LookupPath, const Twine &OriginalPath,
2439 const RedirectingFileSystem::LookupResult &Result) {
2440 if (std::optional<StringRef> ExtRedirect = Result.getExternalRedirect()) {
2441 SmallString<256> RemappedPath((*ExtRedirect).str());
2442 if (std::error_code EC = makeAbsolute(Path&: RemappedPath))
2443 return EC;
2444
2445 ErrorOr<Status> S = ExternalFS->status(Path: RemappedPath);
2446 if (!S)
2447 return S;
2448 S = Status::copyWithNewName(In: *S, NewName: *ExtRedirect);
2449 auto *RE = cast<RedirectingFileSystem::RemapEntry>(Val: Result.E);
2450 return getRedirectedFileStatus(OriginalPath,
2451 UseExternalNames: RE->useExternalName(GlobalUseExternalName: UseExternalNames), ExternalStatus: *S);
2452 }
2453
2454 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Val: Result.E);
2455 return Status::copyWithNewName(In: DE->getStatus(), NewName: LookupPath);
2456}
2457
2458ErrorOr<Status>
2459RedirectingFileSystem::getExternalStatus(const Twine &LookupPath,
2460 const Twine &OriginalPath) const {
2461 auto Result = ExternalFS->status(Path: LookupPath);
2462
2463 // The path has been mapped by some nested VFS, don't override it with the
2464 // original path.
2465 if (!Result || Result->ExposesExternalVFSPath)
2466 return Result;
2467 return Status::copyWithNewName(In: Result.get(), NewName: OriginalPath);
2468}
2469
2470ErrorOr<Status> RedirectingFileSystem::status(const Twine &OriginalPath) {
2471 SmallString<256> Path;
2472 OriginalPath.toVector(Out&: Path);
2473
2474 if (std::error_code EC = makeAbsolute(Path))
2475 return EC;
2476
2477 if (Redirection == RedirectKind::Fallback) {
2478 // Attempt to find the original file first, only falling back to the
2479 // mapped file if that fails.
2480 ErrorOr<Status> S = getExternalStatus(LookupPath: Path, OriginalPath);
2481 if (S)
2482 return S;
2483 }
2484
2485 ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2486 if (!Result) {
2487 // Was not able to map file, fallthrough to using the original path if
2488 // that was the specified redirection type.
2489 if (Redirection == RedirectKind::Fallthrough &&
2490 isFileNotFound(EC: Result.getError()))
2491 return getExternalStatus(LookupPath: Path, OriginalPath);
2492 return Result.getError();
2493 }
2494
2495 ErrorOr<Status> S = status(LookupPath: Path, OriginalPath, Result: *Result);
2496 if (!S && Redirection == RedirectKind::Fallthrough &&
2497 isFileNotFound(EC: S.getError(), E: Result->E)) {
2498 // Mapped the file but it wasn't found in the underlying filesystem,
2499 // fallthrough to using the original path if that was the specified
2500 // redirection type.
2501 return getExternalStatus(LookupPath: Path, OriginalPath);
2502 }
2503
2504 return S;
2505}
2506
2507bool RedirectingFileSystem::exists(const Twine &OriginalPath) {
2508 SmallString<256> Path;
2509 OriginalPath.toVector(Out&: Path);
2510
2511 if (makeAbsolute(Path))
2512 return false;
2513
2514 if (Redirection == RedirectKind::Fallback) {
2515 // Attempt to find the original file first, only falling back to the
2516 // mapped file if that fails.
2517 if (ExternalFS->exists(Path))
2518 return true;
2519 }
2520
2521 ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2522 if (!Result) {
2523 // Was not able to map file, fallthrough to using the original path if
2524 // that was the specified redirection type.
2525 if (Redirection == RedirectKind::Fallthrough &&
2526 isFileNotFound(EC: Result.getError()))
2527 return ExternalFS->exists(Path);
2528 return false;
2529 }
2530
2531 std::optional<StringRef> ExtRedirect = Result->getExternalRedirect();
2532 if (!ExtRedirect) {
2533 assert(isa<RedirectingFileSystem::DirectoryEntry>(Result->E));
2534 return true;
2535 }
2536
2537 SmallString<256> RemappedPath((*ExtRedirect).str());
2538 if (makeAbsolute(Path&: RemappedPath))
2539 return false;
2540
2541 if (ExternalFS->exists(Path: RemappedPath))
2542 return true;
2543
2544 if (Redirection == RedirectKind::Fallthrough) {
2545 // Mapped the file but it wasn't found in the underlying filesystem,
2546 // fallthrough to using the original path if that was the specified
2547 // redirection type.
2548 return ExternalFS->exists(Path);
2549 }
2550
2551 return false;
2552}
2553
2554namespace {
2555
2556/// Provide a file wrapper with an overriden status.
2557class FileWithFixedStatus : public File {
2558 std::unique_ptr<File> InnerFile;
2559 Status S;
2560
2561public:
2562 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
2563 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
2564
2565 ErrorOr<Status> status() override { return S; }
2566 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2567
2568 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
2569 bool IsVolatile) override {
2570 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
2571 IsVolatile);
2572 }
2573
2574 std::error_code close() override { return InnerFile->close(); }
2575
2576 void setPath(const Twine &Path) override { S = S.copyWithNewName(In: S, NewName: Path); }
2577};
2578
2579} // namespace
2580
2581ErrorOr<std::unique_ptr<File>>
2582File::getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P) {
2583 // See \c getRedirectedFileStatus - don't update path if it's exposing an
2584 // external path.
2585 if (!Result || (*Result)->status()->ExposesExternalVFSPath)
2586 return Result;
2587
2588 ErrorOr<std::unique_ptr<File>> F = std::move(*Result);
2589 auto Name = F->get()->getName();
2590 if (Name && Name.get() != P.str())
2591 F->get()->setPath(P);
2592 return F;
2593}
2594
2595ErrorOr<std::unique_ptr<File>>
2596RedirectingFileSystem::openFileForRead(const Twine &OriginalPath) {
2597 SmallString<256> Path;
2598 OriginalPath.toVector(Out&: Path);
2599
2600 if (std::error_code EC = makeAbsolute(Path))
2601 return EC;
2602
2603 if (Redirection == RedirectKind::Fallback) {
2604 // Attempt to find the original file first, only falling back to the
2605 // mapped file if that fails.
2606 auto F = File::getWithPath(Result: ExternalFS->openFileForRead(Path), P: OriginalPath);
2607 if (F)
2608 return F;
2609 }
2610
2611 ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2612 if (!Result) {
2613 // Was not able to map file, fallthrough to using the original path if
2614 // that was the specified redirection type.
2615 if (Redirection == RedirectKind::Fallthrough &&
2616 isFileNotFound(EC: Result.getError()))
2617 return File::getWithPath(Result: ExternalFS->openFileForRead(Path), P: OriginalPath);
2618 return Result.getError();
2619 }
2620
2621 if (!Result->getExternalRedirect()) // FIXME: errc::not_a_file?
2622 return make_error_code(E: llvm::errc::invalid_argument);
2623
2624 StringRef ExtRedirect = *Result->getExternalRedirect();
2625 SmallString<256> RemappedPath(ExtRedirect.str());
2626 if (std::error_code EC = makeAbsolute(Path&: RemappedPath))
2627 return EC;
2628
2629 auto *RE = cast<RedirectingFileSystem::RemapEntry>(Val: Result->E);
2630
2631 auto ExternalFile =
2632 File::getWithPath(Result: ExternalFS->openFileForRead(Path: RemappedPath), P: ExtRedirect);
2633 if (!ExternalFile) {
2634 if (Redirection == RedirectKind::Fallthrough &&
2635 isFileNotFound(EC: ExternalFile.getError(), E: Result->E)) {
2636 // Mapped the file but it wasn't found in the underlying filesystem,
2637 // fallthrough to using the original path if that was the specified
2638 // redirection type.
2639 return File::getWithPath(Result: ExternalFS->openFileForRead(Path), P: OriginalPath);
2640 }
2641 return ExternalFile;
2642 }
2643
2644 auto ExternalStatus = (*ExternalFile)->status();
2645 if (!ExternalStatus)
2646 return ExternalStatus.getError();
2647
2648 // Otherwise, the file was successfully remapped. Mark it as such. Also
2649 // replace the underlying path if the external name is being used.
2650 Status S = getRedirectedFileStatus(
2651 OriginalPath, UseExternalNames: RE->useExternalName(GlobalUseExternalName: UseExternalNames), ExternalStatus: *ExternalStatus);
2652 return std::unique_ptr<File>(
2653 std::make_unique<FileWithFixedStatus>(args: std::move(*ExternalFile), args&: S));
2654}
2655
2656std::error_code
2657RedirectingFileSystem::getRealPath(const Twine &OriginalPath,
2658 SmallVectorImpl<char> &Output) {
2659 SmallString<256> Path;
2660 OriginalPath.toVector(Out&: Path);
2661
2662 if (std::error_code EC = makeAbsolute(Path))
2663 return EC;
2664
2665 if (Redirection == RedirectKind::Fallback) {
2666 // Attempt to find the original file first, only falling back to the
2667 // mapped file if that fails.
2668 std::error_code EC = ExternalFS->getRealPath(Path, Output);
2669 if (!EC)
2670 return EC;
2671 }
2672
2673 ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2674 if (!Result) {
2675 // Was not able to map file, fallthrough to using the original path if
2676 // that was the specified redirection type.
2677 if (Redirection == RedirectKind::Fallthrough &&
2678 isFileNotFound(EC: Result.getError()))
2679 return ExternalFS->getRealPath(Path, Output);
2680 return Result.getError();
2681 }
2682
2683 // If we found FileEntry or DirectoryRemapEntry, look up the mapped
2684 // path in the external file system.
2685 if (auto ExtRedirect = Result->getExternalRedirect()) {
2686 auto P = ExternalFS->getRealPath(Path: *ExtRedirect, Output);
2687 if (P && Redirection == RedirectKind::Fallthrough &&
2688 isFileNotFound(EC: P, E: Result->E)) {
2689 // Mapped the file but it wasn't found in the underlying filesystem,
2690 // fallthrough to using the original path if that was the specified
2691 // redirection type.
2692 return ExternalFS->getRealPath(Path, Output);
2693 }
2694 return P;
2695 }
2696
2697 // We found a DirectoryEntry, which does not have a single external contents
2698 // path. Use the canonical virtual path.
2699 if (Redirection == RedirectKind::Fallthrough) {
2700 Result->getPath(Result&: Output);
2701 return {};
2702 }
2703 return llvm::errc::invalid_argument;
2704}
2705
2706std::unique_ptr<FileSystem>
2707vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2708 SourceMgr::DiagHandlerTy DiagHandler,
2709 StringRef YAMLFilePath, void *DiagContext,
2710 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2711 return RedirectingFileSystem::create(Buffer: std::move(Buffer), DiagHandler,
2712 YAMLFilePath, DiagContext,
2713 ExternalFS: std::move(ExternalFS));
2714}
2715
2716static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
2717 SmallVectorImpl<StringRef> &Path,
2718 SmallVectorImpl<YAMLVFSEntry> &Entries) {
2719 auto Kind = SrcE->getKind();
2720 if (Kind == RedirectingFileSystem::EK_Directory) {
2721 auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(Val: SrcE);
2722 assert(DE && "Must be a directory");
2723 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
2724 llvm::make_range(x: DE->contents_begin(), y: DE->contents_end())) {
2725 Path.push_back(Elt: SubEntry->getName());
2726 getVFSEntries(SrcE: SubEntry.get(), Path, Entries);
2727 Path.pop_back();
2728 }
2729 return;
2730 }
2731
2732 if (Kind == RedirectingFileSystem::EK_DirectoryRemap) {
2733 auto *DR = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(Val: SrcE);
2734 assert(DR && "Must be a directory remap");
2735 SmallString<128> VPath;
2736 for (auto &Comp : Path)
2737 llvm::sys::path::append(path&: VPath, a: Comp);
2738 Entries.push_back(
2739 Elt: YAMLVFSEntry(VPath.c_str(), DR->getExternalContentsPath()));
2740 return;
2741 }
2742
2743 assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
2744 auto *FE = dyn_cast<RedirectingFileSystem::FileEntry>(Val: SrcE);
2745 assert(FE && "Must be a file");
2746 SmallString<128> VPath;
2747 for (auto &Comp : Path)
2748 llvm::sys::path::append(path&: VPath, a: Comp);
2749 Entries.push_back(Elt: YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
2750}
2751
2752void vfs::collectVFSEntries(RedirectingFileSystem &VFS,
2753 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries) {
2754 ErrorOr<RedirectingFileSystem::LookupResult> RootResult = VFS.lookupPath(Path: "/");
2755 if (!RootResult)
2756 return;
2757 SmallVector<StringRef, 8> Components;
2758 Components.push_back(Elt: "/");
2759 getVFSEntries(SrcE: RootResult->E, Path&: Components, Entries&: CollectedEntries);
2760}
2761
2762UniqueID vfs::getNextVirtualUniqueID() {
2763 static std::atomic<unsigned> UID;
2764 unsigned ID = ++UID;
2765 // The following assumes that uint64_t max will never collide with a real
2766 // dev_t value from the OS.
2767 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
2768}
2769
2770void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath,
2771 bool IsDirectory) {
2772 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
2773 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
2774 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
2775 Mappings.emplace_back(args&: VirtualPath, args&: RealPath, args&: IsDirectory);
2776}
2777
2778void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
2779 addEntry(VirtualPath, RealPath, /*IsDirectory=*/false);
2780}
2781
2782void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath,
2783 StringRef RealPath) {
2784 addEntry(VirtualPath, RealPath, /*IsDirectory=*/true);
2785}
2786
2787namespace {
2788
2789class JSONWriter {
2790 llvm::raw_ostream &OS;
2791 SmallVector<StringRef, 16> DirStack;
2792
2793 unsigned getDirIndent() { return 4 * DirStack.size(); }
2794 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
2795 bool containedIn(StringRef Parent, StringRef Path);
2796 StringRef containedPart(StringRef Parent, StringRef Path);
2797 void startDirectory(StringRef Path);
2798 void endDirectory();
2799 void writeEntry(StringRef VPath, StringRef RPath);
2800
2801public:
2802 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
2803
2804 void write(ArrayRef<YAMLVFSEntry> Entries,
2805 std::optional<bool> UseExternalNames,
2806 std::optional<bool> IsCaseSensitive,
2807 std::optional<bool> IsOverlayRelative, StringRef OverlayDir);
2808};
2809
2810} // namespace
2811
2812bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2813 using namespace llvm::sys;
2814
2815 // Compare each path component.
2816 auto IParent = path::begin(path: Parent), EParent = path::end(path: Parent);
2817 for (auto IChild = path::begin(path: Path), EChild = path::end(path: Path);
2818 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2819 if (*IParent != *IChild)
2820 return false;
2821 }
2822 // Have we exhausted the parent path?
2823 return IParent == EParent;
2824}
2825
2826StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2827 assert(!Parent.empty());
2828 assert(containedIn(Parent, Path));
2829 return Path.substr(Start: Parent.size() + 1);
2830}
2831
2832void JSONWriter::startDirectory(StringRef Path) {
2833 StringRef Name =
2834 DirStack.empty() ? Path : containedPart(Parent: DirStack.back(), Path);
2835 DirStack.push_back(Elt: Path);
2836 unsigned Indent = getDirIndent();
2837 OS.indent(NumSpaces: Indent) << "{\n";
2838 OS.indent(NumSpaces: Indent + 2) << "'type': 'directory',\n";
2839 OS.indent(NumSpaces: Indent + 2) << "'name': \"" << llvm::yaml::escape(Input: Name) << "\",\n";
2840 OS.indent(NumSpaces: Indent + 2) << "'contents': [\n";
2841}
2842
2843void JSONWriter::endDirectory() {
2844 unsigned Indent = getDirIndent();
2845 OS.indent(NumSpaces: Indent + 2) << "]\n";
2846 OS.indent(NumSpaces: Indent) << "}";
2847
2848 DirStack.pop_back();
2849}
2850
2851void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2852 unsigned Indent = getFileIndent();
2853 OS.indent(NumSpaces: Indent) << "{\n";
2854 OS.indent(NumSpaces: Indent + 2) << "'type': 'file',\n";
2855 OS.indent(NumSpaces: Indent + 2) << "'name': \"" << llvm::yaml::escape(Input: VPath) << "\",\n";
2856 OS.indent(NumSpaces: Indent + 2) << "'external-contents': \""
2857 << llvm::yaml::escape(Input: RPath) << "\"\n";
2858 OS.indent(NumSpaces: Indent) << "}";
2859}
2860
2861void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
2862 std::optional<bool> UseExternalNames,
2863 std::optional<bool> IsCaseSensitive,
2864 std::optional<bool> IsOverlayRelative,
2865 StringRef OverlayDir) {
2866 using namespace llvm::sys;
2867
2868 OS << "{\n"
2869 " 'version': 0,\n";
2870 if (IsCaseSensitive)
2871 OS << " 'case-sensitive': '" << (*IsCaseSensitive ? "true" : "false")
2872 << "',\n";
2873 if (UseExternalNames)
2874 OS << " 'use-external-names': '" << (*UseExternalNames ? "true" : "false")
2875 << "',\n";
2876 bool UseOverlayRelative = false;
2877 if (IsOverlayRelative) {
2878 UseOverlayRelative = *IsOverlayRelative;
2879 OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2880 << "',\n";
2881 }
2882 OS << " 'roots': [\n";
2883
2884 if (!Entries.empty()) {
2885 const YAMLVFSEntry &Entry = Entries.front();
2886
2887 startDirectory(
2888 Path: Entry.IsDirectory ? Entry.VPath : path::parent_path(path: Entry.VPath)
2889 );
2890
2891 StringRef RPath = Entry.RPath;
2892 if (UseOverlayRelative) {
2893 assert(RPath.starts_with(OverlayDir) &&
2894 "Overlay dir must be contained in RPath");
2895 RPath = RPath.substr(Start: OverlayDir.size());
2896 }
2897
2898 bool IsCurrentDirEmpty = true;
2899 if (!Entry.IsDirectory) {
2900 writeEntry(VPath: path::filename(path: Entry.VPath), RPath);
2901 IsCurrentDirEmpty = false;
2902 }
2903
2904 for (const auto &Entry : Entries.slice(N: 1)) {
2905 StringRef Dir =
2906 Entry.IsDirectory ? Entry.VPath : path::parent_path(path: Entry.VPath);
2907 if (Dir == DirStack.back()) {
2908 if (!IsCurrentDirEmpty) {
2909 OS << ",\n";
2910 }
2911 } else {
2912 bool IsDirPoppedFromStack = false;
2913 while (!DirStack.empty() && !containedIn(Parent: DirStack.back(), Path: Dir)) {
2914 OS << "\n";
2915 endDirectory();
2916 IsDirPoppedFromStack = true;
2917 }
2918 if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
2919 OS << ",\n";
2920 }
2921 startDirectory(Path: Dir);
2922 IsCurrentDirEmpty = true;
2923 }
2924 StringRef RPath = Entry.RPath;
2925 if (UseOverlayRelative) {
2926 assert(RPath.starts_with(OverlayDir) &&
2927 "Overlay dir must be contained in RPath");
2928 RPath = RPath.substr(Start: OverlayDir.size());
2929 }
2930 if (!Entry.IsDirectory) {
2931 writeEntry(VPath: path::filename(path: Entry.VPath), RPath);
2932 IsCurrentDirEmpty = false;
2933 }
2934 }
2935
2936 while (!DirStack.empty()) {
2937 OS << "\n";
2938 endDirectory();
2939 }
2940 OS << "\n";
2941 }
2942
2943 OS << " ]\n"
2944 << "}\n";
2945}
2946
2947void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2948 llvm::sort(C&: Mappings, Comp: [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2949 return LHS.VPath < RHS.VPath;
2950 });
2951
2952 JSONWriter(OS).write(Entries: Mappings, UseExternalNames, IsCaseSensitive,
2953 IsOverlayRelative, OverlayDir);
2954}
2955
2956vfs::recursive_directory_iterator::recursive_directory_iterator(
2957 FileSystem &FS_, const Twine &Path, std::error_code &EC)
2958 : FS(&FS_) {
2959 directory_iterator I = FS->dir_begin(Dir: Path, EC);
2960 if (I != directory_iterator()) {
2961 State = std::make_shared<detail::RecDirIterState>();
2962 State->Stack.push_back(x: I);
2963 }
2964}
2965
2966vfs::recursive_directory_iterator &
2967recursive_directory_iterator::increment(std::error_code &EC) {
2968 assert(FS && State && !State->Stack.empty() && "incrementing past end");
2969 assert(!State->Stack.back()->path().empty() && "non-canonical end iterator");
2970 vfs::directory_iterator End;
2971
2972 if (State->HasNoPushRequest)
2973 State->HasNoPushRequest = false;
2974 else {
2975 if (State->Stack.back()->type() == sys::fs::file_type::directory_file) {
2976 vfs::directory_iterator I =
2977 FS->dir_begin(Dir: State->Stack.back()->path(), EC);
2978 if (I != End) {
2979 State->Stack.push_back(x: I);
2980 return *this;
2981 }
2982 }
2983 }
2984
2985 while (!State->Stack.empty() && State->Stack.back().increment(EC) == End)
2986 State->Stack.pop_back();
2987
2988 if (State->Stack.empty())
2989 State.reset(); // end iterator
2990
2991 return *this;
2992}
2993
2994void TracingFileSystem::printImpl(raw_ostream &OS, PrintType Type,
2995 unsigned IndentLevel) const {
2996 printIndent(OS, IndentLevel);
2997 OS << "TracingFileSystem\n";
2998 if (Type == PrintType::Summary)
2999 return;
3000
3001 printIndent(OS, IndentLevel);
3002 OS << "NumStatusCalls=" << NumStatusCalls << "\n";
3003 printIndent(OS, IndentLevel);
3004 OS << "NumOpenFileForReadCalls=" << NumOpenFileForReadCalls << "\n";
3005 printIndent(OS, IndentLevel);
3006 OS << "NumDirBeginCalls=" << NumDirBeginCalls << "\n";
3007 printIndent(OS, IndentLevel);
3008 OS << "NumGetRealPathCalls=" << NumGetRealPathCalls << "\n";
3009 printIndent(OS, IndentLevel);
3010 OS << "NumExistsCalls=" << NumExistsCalls << "\n";
3011 printIndent(OS, IndentLevel);
3012 OS << "NumIsLocalCalls=" << NumIsLocalCalls << "\n";
3013
3014 if (Type == PrintType::Contents)
3015 Type = PrintType::Summary;
3016 getUnderlyingFS().print(OS, Type, IndentLevel: IndentLevel + 1);
3017}
3018
3019const char FileSystem::ID = 0;
3020const char OverlayFileSystem::ID = 0;
3021const char ProxyFileSystem::ID = 0;
3022const char InMemoryFileSystem::ID = 0;
3023const char RedirectingFileSystem::ID = 0;
3024const char TracingFileSystem::ID = 0;
3025