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