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