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