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