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