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