xref: /llvm-project/llvm/lib/Support/VirtualFileSystem.cpp (revision 9e0398da8d00b6218aa16a2d602acc765105ed40)
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 namespace {
984 
985 /// Adaptor from InMemoryDir::iterator to directory_iterator.
986 class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl {
987   detail::InMemoryDirectory::const_iterator I;
988   detail::InMemoryDirectory::const_iterator E;
989   std::string RequestedDirName;
990 
991   void setCurrentEntry() {
992     if (I != E) {
993       SmallString<256> Path(RequestedDirName);
994       llvm::sys::path::append(Path, I->second->getFileName());
995       sys::fs::file_type Type = sys::fs::file_type::type_unknown;
996       switch (I->second->getKind()) {
997       case detail::IME_File:
998       case detail::IME_HardLink:
999         Type = sys::fs::file_type::regular_file;
1000         break;
1001       case detail::IME_Directory:
1002         Type = sys::fs::file_type::directory_file;
1003         break;
1004       }
1005       CurrentEntry = directory_entry(std::string(Path.str()), Type);
1006     } else {
1007       // When we're at the end, make CurrentEntry invalid and DirIterImpl will
1008       // do the rest.
1009       CurrentEntry = directory_entry();
1010     }
1011   }
1012 
1013 public:
1014   InMemoryDirIterator() = default;
1015 
1016   explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir,
1017                                std::string RequestedDirName)
1018       : I(Dir.begin()), E(Dir.end()),
1019         RequestedDirName(std::move(RequestedDirName)) {
1020     setCurrentEntry();
1021   }
1022 
1023   std::error_code increment() override {
1024     ++I;
1025     setCurrentEntry();
1026     return {};
1027   }
1028 };
1029 
1030 } // namespace
1031 
1032 directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
1033                                                  std::error_code &EC) {
1034   auto Node = lookupNode(Dir);
1035   if (!Node) {
1036     EC = Node.getError();
1037     return directory_iterator(std::make_shared<InMemoryDirIterator>());
1038   }
1039 
1040   if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
1041     return directory_iterator(
1042         std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
1043 
1044   EC = make_error_code(llvm::errc::not_a_directory);
1045   return directory_iterator(std::make_shared<InMemoryDirIterator>());
1046 }
1047 
1048 std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
1049   SmallString<128> Path;
1050   P.toVector(Path);
1051 
1052   // Fix up relative paths. This just prepends the current working directory.
1053   std::error_code EC = makeAbsolute(Path);
1054   assert(!EC);
1055   (void)EC;
1056 
1057   if (useNormalizedPaths())
1058     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1059 
1060   if (!Path.empty())
1061     WorkingDirectory = std::string(Path.str());
1062   return {};
1063 }
1064 
1065 std::error_code
1066 InMemoryFileSystem::getRealPath(const Twine &Path,
1067                                 SmallVectorImpl<char> &Output) const {
1068   auto CWD = getCurrentWorkingDirectory();
1069   if (!CWD || CWD->empty())
1070     return errc::operation_not_permitted;
1071   Path.toVector(Output);
1072   if (auto EC = makeAbsolute(Output))
1073     return EC;
1074   llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
1075   return {};
1076 }
1077 
1078 std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
1079   Result = false;
1080   return {};
1081 }
1082 
1083 void InMemoryFileSystem::printImpl(raw_ostream &OS, PrintType PrintContents,
1084                                    unsigned IndentLevel) const {
1085   printIndent(OS, IndentLevel);
1086   OS << "InMemoryFileSystem\n";
1087 }
1088 
1089 } // namespace vfs
1090 } // namespace llvm
1091 
1092 //===-----------------------------------------------------------------------===/
1093 // RedirectingFileSystem implementation
1094 //===-----------------------------------------------------------------------===/
1095 
1096 namespace {
1097 
1098 static llvm::sys::path::Style getExistingStyle(llvm::StringRef Path) {
1099   // Detect the path style in use by checking the first separator.
1100   llvm::sys::path::Style style = llvm::sys::path::Style::native;
1101   const size_t n = Path.find_first_of("/\\");
1102   // Can't distinguish between posix and windows_slash here.
1103   if (n != static_cast<size_t>(-1))
1104     style = (Path[n] == '/') ? llvm::sys::path::Style::posix
1105                              : llvm::sys::path::Style::windows_backslash;
1106   return style;
1107 }
1108 
1109 /// Removes leading "./" as well as path components like ".." and ".".
1110 static llvm::SmallString<256> canonicalize(llvm::StringRef Path) {
1111   // First detect the path style in use by checking the first separator.
1112   llvm::sys::path::Style style = getExistingStyle(Path);
1113 
1114   // Now remove the dots.  Explicitly specifying the path style prevents the
1115   // direction of the slashes from changing.
1116   llvm::SmallString<256> result =
1117       llvm::sys::path::remove_leading_dotslash(Path, style);
1118   llvm::sys::path::remove_dots(result, /*remove_dot_dot=*/true, style);
1119   return result;
1120 }
1121 
1122 /// Whether the error and entry specify a file/directory that was not found.
1123 static bool isFileNotFound(std::error_code EC,
1124                            RedirectingFileSystem::Entry *E = nullptr) {
1125   if (E && !isa<RedirectingFileSystem::DirectoryRemapEntry>(E))
1126     return false;
1127   return EC == llvm::errc::no_such_file_or_directory;
1128 }
1129 
1130 } // anonymous namespace
1131 
1132 
1133 RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
1134     : ExternalFS(std::move(FS)) {
1135   if (ExternalFS)
1136     if (auto ExternalWorkingDirectory =
1137             ExternalFS->getCurrentWorkingDirectory()) {
1138       WorkingDirectory = *ExternalWorkingDirectory;
1139     }
1140 }
1141 
1142 /// Directory iterator implementation for \c RedirectingFileSystem's
1143 /// directory entries.
1144 class llvm::vfs::RedirectingFSDirIterImpl
1145     : public llvm::vfs::detail::DirIterImpl {
1146   std::string Dir;
1147   RedirectingFileSystem::DirectoryEntry::iterator Current, End;
1148 
1149   std::error_code incrementImpl(bool IsFirstTime) {
1150     assert((IsFirstTime || Current != End) && "cannot iterate past end");
1151     if (!IsFirstTime)
1152       ++Current;
1153     if (Current != End) {
1154       SmallString<128> PathStr(Dir);
1155       llvm::sys::path::append(PathStr, (*Current)->getName());
1156       sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1157       switch ((*Current)->getKind()) {
1158       case RedirectingFileSystem::EK_Directory:
1159         LLVM_FALLTHROUGH;
1160       case RedirectingFileSystem::EK_DirectoryRemap:
1161         Type = sys::fs::file_type::directory_file;
1162         break;
1163       case RedirectingFileSystem::EK_File:
1164         Type = sys::fs::file_type::regular_file;
1165         break;
1166       }
1167       CurrentEntry = directory_entry(std::string(PathStr.str()), Type);
1168     } else {
1169       CurrentEntry = directory_entry();
1170     }
1171     return {};
1172   };
1173 
1174 public:
1175   RedirectingFSDirIterImpl(
1176       const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin,
1177       RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC)
1178       : Dir(Path.str()), Current(Begin), End(End) {
1179     EC = incrementImpl(/*IsFirstTime=*/true);
1180   }
1181 
1182   std::error_code increment() override {
1183     return incrementImpl(/*IsFirstTime=*/false);
1184   }
1185 };
1186 
1187 namespace {
1188 /// Directory iterator implementation for \c RedirectingFileSystem's
1189 /// directory remap entries that maps the paths reported by the external
1190 /// file system's directory iterator back to the virtual directory's path.
1191 class RedirectingFSDirRemapIterImpl : public llvm::vfs::detail::DirIterImpl {
1192   std::string Dir;
1193   llvm::sys::path::Style DirStyle;
1194   llvm::vfs::directory_iterator ExternalIter;
1195 
1196 public:
1197   RedirectingFSDirRemapIterImpl(std::string DirPath,
1198                                 llvm::vfs::directory_iterator ExtIter)
1199       : Dir(std::move(DirPath)), DirStyle(getExistingStyle(Dir)),
1200         ExternalIter(ExtIter) {
1201     if (ExternalIter != llvm::vfs::directory_iterator())
1202       setCurrentEntry();
1203   }
1204 
1205   void setCurrentEntry() {
1206     StringRef ExternalPath = ExternalIter->path();
1207     llvm::sys::path::Style ExternalStyle = getExistingStyle(ExternalPath);
1208     StringRef File = llvm::sys::path::filename(ExternalPath, ExternalStyle);
1209 
1210     SmallString<128> NewPath(Dir);
1211     llvm::sys::path::append(NewPath, DirStyle, File);
1212 
1213     CurrentEntry = directory_entry(std::string(NewPath), ExternalIter->type());
1214   }
1215 
1216   std::error_code increment() override {
1217     std::error_code EC;
1218     ExternalIter.increment(EC);
1219     if (!EC && ExternalIter != llvm::vfs::directory_iterator())
1220       setCurrentEntry();
1221     else
1222       CurrentEntry = directory_entry();
1223     return EC;
1224   }
1225 };
1226 } // namespace
1227 
1228 llvm::ErrorOr<std::string>
1229 RedirectingFileSystem::getCurrentWorkingDirectory() const {
1230   return WorkingDirectory;
1231 }
1232 
1233 std::error_code
1234 RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
1235   // Don't change the working directory if the path doesn't exist.
1236   if (!exists(Path))
1237     return errc::no_such_file_or_directory;
1238 
1239   SmallString<128> AbsolutePath;
1240   Path.toVector(AbsolutePath);
1241   if (std::error_code EC = makeAbsolute(AbsolutePath))
1242     return EC;
1243   WorkingDirectory = std::string(AbsolutePath.str());
1244   return {};
1245 }
1246 
1247 std::error_code RedirectingFileSystem::isLocal(const Twine &Path_,
1248                                                bool &Result) {
1249   SmallString<256> Path;
1250   Path_.toVector(Path);
1251 
1252   if (std::error_code EC = makeCanonical(Path))
1253     return {};
1254 
1255   return ExternalFS->isLocal(Path, Result);
1256 }
1257 
1258 std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
1259   // is_absolute(..., Style::windows_*) accepts paths with both slash types.
1260   if (llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::posix) ||
1261       llvm::sys::path::is_absolute(Path,
1262                                    llvm::sys::path::Style::windows_backslash))
1263     return {};
1264 
1265   auto WorkingDir = getCurrentWorkingDirectory();
1266   if (!WorkingDir)
1267     return WorkingDir.getError();
1268 
1269   // We can't use sys::fs::make_absolute because that assumes the path style
1270   // is native and there is no way to override that.  Since we know WorkingDir
1271   // is absolute, we can use it to determine which style we actually have and
1272   // append Path ourselves.
1273   sys::path::Style style = sys::path::Style::windows_backslash;
1274   if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) {
1275     style = sys::path::Style::posix;
1276   } else {
1277     // Distinguish between windows_backslash and windows_slash; getExistingStyle
1278     // returns posix for a path with windows_slash.
1279     if (getExistingStyle(WorkingDir.get()) !=
1280         sys::path::Style::windows_backslash)
1281       style = sys::path::Style::windows_slash;
1282   }
1283 
1284   std::string Result = WorkingDir.get();
1285   StringRef Dir(Result);
1286   if (!Dir.endswith(sys::path::get_separator(style))) {
1287     Result += sys::path::get_separator(style);
1288   }
1289   Result.append(Path.data(), Path.size());
1290   Path.assign(Result.begin(), Result.end());
1291 
1292   return {};
1293 }
1294 
1295 directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
1296                                                     std::error_code &EC) {
1297   SmallString<256> Path;
1298   Dir.toVector(Path);
1299 
1300   EC = makeCanonical(Path);
1301   if (EC)
1302     return {};
1303 
1304   ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
1305   if (!Result) {
1306     if (Redirection != RedirectKind::RedirectOnly &&
1307         isFileNotFound(Result.getError()))
1308       return ExternalFS->dir_begin(Path, EC);
1309 
1310     EC = Result.getError();
1311     return {};
1312   }
1313 
1314   // Use status to make sure the path exists and refers to a directory.
1315   ErrorOr<Status> S = status(Path, Dir, *Result);
1316   if (!S) {
1317     if (Redirection != RedirectKind::RedirectOnly &&
1318         isFileNotFound(S.getError(), Result->E))
1319       return ExternalFS->dir_begin(Dir, EC);
1320 
1321     EC = S.getError();
1322     return {};
1323   }
1324 
1325   if (!S->isDirectory()) {
1326     EC = errc::not_a_directory;
1327     return {};
1328   }
1329 
1330   // Create the appropriate directory iterator based on whether we found a
1331   // DirectoryRemapEntry or DirectoryEntry.
1332   directory_iterator RedirectIter;
1333   std::error_code RedirectEC;
1334   if (auto ExtRedirect = Result->getExternalRedirect()) {
1335     auto RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
1336     RedirectIter = ExternalFS->dir_begin(*ExtRedirect, RedirectEC);
1337 
1338     if (!RE->useExternalName(UseExternalNames)) {
1339       // Update the paths in the results to use the virtual directory's path.
1340       RedirectIter =
1341           directory_iterator(std::make_shared<RedirectingFSDirRemapIterImpl>(
1342               std::string(Path), RedirectIter));
1343     }
1344   } else {
1345     auto DE = cast<DirectoryEntry>(Result->E);
1346     RedirectIter =
1347         directory_iterator(std::make_shared<RedirectingFSDirIterImpl>(
1348             Path, DE->contents_begin(), DE->contents_end(), RedirectEC));
1349   }
1350 
1351   if (RedirectEC) {
1352     if (RedirectEC != errc::no_such_file_or_directory) {
1353       EC = RedirectEC;
1354       return {};
1355     }
1356     RedirectIter = {};
1357   }
1358 
1359   if (Redirection == RedirectKind::RedirectOnly) {
1360     EC = RedirectEC;
1361     return RedirectIter;
1362   }
1363 
1364   std::error_code ExternalEC;
1365   directory_iterator ExternalIter = ExternalFS->dir_begin(Path, ExternalEC);
1366   if (ExternalEC) {
1367     if (ExternalEC != errc::no_such_file_or_directory) {
1368       EC = ExternalEC;
1369       return {};
1370     }
1371     ExternalIter = {};
1372   }
1373 
1374   SmallVector<directory_iterator, 2> Iters;
1375   switch (Redirection) {
1376   case RedirectKind::Fallthrough:
1377     Iters.push_back(ExternalIter);
1378     Iters.push_back(RedirectIter);
1379     break;
1380   case RedirectKind::Fallback:
1381     Iters.push_back(RedirectIter);
1382     Iters.push_back(ExternalIter);
1383     break;
1384   default:
1385     llvm_unreachable("unhandled RedirectKind");
1386   }
1387 
1388   directory_iterator Combined{
1389       std::make_shared<CombiningDirIterImpl>(Iters, EC)};
1390   if (EC)
1391     return {};
1392   return Combined;
1393 }
1394 
1395 void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) {
1396   ExternalContentsPrefixDir = PrefixDir.str();
1397 }
1398 
1399 StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const {
1400   return ExternalContentsPrefixDir;
1401 }
1402 
1403 void RedirectingFileSystem::setFallthrough(bool Fallthrough) {
1404   if (Fallthrough) {
1405     Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
1406   } else {
1407     Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
1408   }
1409 }
1410 
1411 void RedirectingFileSystem::setRedirection(
1412     RedirectingFileSystem::RedirectKind Kind) {
1413   Redirection = Kind;
1414 }
1415 
1416 std::vector<StringRef> RedirectingFileSystem::getRoots() const {
1417   std::vector<StringRef> R;
1418   for (const auto &Root : Roots)
1419     R.push_back(Root->getName());
1420   return R;
1421 }
1422 
1423 void RedirectingFileSystem::printImpl(raw_ostream &OS, PrintType Type,
1424                                       unsigned IndentLevel) const {
1425   printIndent(OS, IndentLevel);
1426   OS << "RedirectingFileSystem (UseExternalNames: "
1427      << (UseExternalNames ? "true" : "false") << ")\n";
1428   if (Type == PrintType::Summary)
1429     return;
1430 
1431   for (const auto &Root : Roots)
1432     printEntry(OS, Root.get(), IndentLevel);
1433 
1434   printIndent(OS, IndentLevel);
1435   OS << "ExternalFS:\n";
1436   ExternalFS->print(OS, Type == PrintType::Contents ? PrintType::Summary : Type,
1437                     IndentLevel + 1);
1438 }
1439 
1440 void RedirectingFileSystem::printEntry(raw_ostream &OS,
1441                                        RedirectingFileSystem::Entry *E,
1442                                        unsigned IndentLevel) const {
1443   printIndent(OS, IndentLevel);
1444   OS << "'" << E->getName() << "'";
1445 
1446   switch (E->getKind()) {
1447   case EK_Directory: {
1448     auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(E);
1449 
1450     OS << "\n";
1451     for (std::unique_ptr<Entry> &SubEntry :
1452          llvm::make_range(DE->contents_begin(), DE->contents_end()))
1453       printEntry(OS, SubEntry.get(), IndentLevel + 1);
1454     break;
1455   }
1456   case EK_DirectoryRemap:
1457   case EK_File: {
1458     auto *RE = cast<RedirectingFileSystem::RemapEntry>(E);
1459     OS << " -> '" << RE->getExternalContentsPath() << "'";
1460     switch (RE->getUseName()) {
1461     case NK_NotSet:
1462       break;
1463     case NK_External:
1464       OS << " (UseExternalName: true)";
1465       break;
1466     case NK_Virtual:
1467       OS << " (UseExternalName: false)";
1468       break;
1469     }
1470     OS << "\n";
1471     break;
1472   }
1473   }
1474 }
1475 
1476 /// A helper class to hold the common YAML parsing state.
1477 class llvm::vfs::RedirectingFileSystemParser {
1478   yaml::Stream &Stream;
1479 
1480   void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1481 
1482   // false on error
1483   bool parseScalarString(yaml::Node *N, StringRef &Result,
1484                          SmallVectorImpl<char> &Storage) {
1485     const auto *S = dyn_cast<yaml::ScalarNode>(N);
1486 
1487     if (!S) {
1488       error(N, "expected string");
1489       return false;
1490     }
1491     Result = S->getValue(Storage);
1492     return true;
1493   }
1494 
1495   // false on error
1496   bool parseScalarBool(yaml::Node *N, bool &Result) {
1497     SmallString<5> Storage;
1498     StringRef Value;
1499     if (!parseScalarString(N, Value, Storage))
1500       return false;
1501 
1502     if (Value.equals_insensitive("true") || Value.equals_insensitive("on") ||
1503         Value.equals_insensitive("yes") || Value == "1") {
1504       Result = true;
1505       return true;
1506     } else if (Value.equals_insensitive("false") ||
1507                Value.equals_insensitive("off") ||
1508                Value.equals_insensitive("no") || Value == "0") {
1509       Result = false;
1510       return true;
1511     }
1512 
1513     error(N, "expected boolean value");
1514     return false;
1515   }
1516 
1517   Optional<RedirectingFileSystem::RedirectKind>
1518   parseRedirectKind(yaml::Node *N) {
1519     SmallString<12> Storage;
1520     StringRef Value;
1521     if (!parseScalarString(N, Value, Storage))
1522       return None;
1523 
1524     if (Value.equals_insensitive("fallthrough")) {
1525       return RedirectingFileSystem::RedirectKind::Fallthrough;
1526     } else if (Value.equals_insensitive("fallback")) {
1527       return RedirectingFileSystem::RedirectKind::Fallback;
1528     } else if (Value.equals_insensitive("redirect-only")) {
1529       return RedirectingFileSystem::RedirectKind::RedirectOnly;
1530     }
1531     return None;
1532   }
1533 
1534   struct KeyStatus {
1535     bool Required;
1536     bool Seen = false;
1537 
1538     KeyStatus(bool Required = false) : Required(Required) {}
1539   };
1540 
1541   using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1542 
1543   // false on error
1544   bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1545                                   DenseMap<StringRef, KeyStatus> &Keys) {
1546     if (!Keys.count(Key)) {
1547       error(KeyNode, "unknown key");
1548       return false;
1549     }
1550     KeyStatus &S = Keys[Key];
1551     if (S.Seen) {
1552       error(KeyNode, Twine("duplicate key '") + Key + "'");
1553       return false;
1554     }
1555     S.Seen = true;
1556     return true;
1557   }
1558 
1559   // false on error
1560   bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1561     for (const auto &I : Keys) {
1562       if (I.second.Required && !I.second.Seen) {
1563         error(Obj, Twine("missing key '") + I.first + "'");
1564         return false;
1565       }
1566     }
1567     return true;
1568   }
1569 
1570 public:
1571   static RedirectingFileSystem::Entry *
1572   lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1573                       RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1574     if (!ParentEntry) { // Look for a existent root
1575       for (const auto &Root : FS->Roots) {
1576         if (Name.equals(Root->getName())) {
1577           ParentEntry = Root.get();
1578           return ParentEntry;
1579         }
1580       }
1581     } else { // Advance to the next component
1582       auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
1583       for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1584            llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1585         auto *DirContent =
1586             dyn_cast<RedirectingFileSystem::DirectoryEntry>(Content.get());
1587         if (DirContent && Name.equals(Content->getName()))
1588           return DirContent;
1589       }
1590     }
1591 
1592     // ... or create a new one
1593     std::unique_ptr<RedirectingFileSystem::Entry> E =
1594         std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1595             Name, Status("", getNextVirtualUniqueID(),
1596                          std::chrono::system_clock::now(), 0, 0, 0,
1597                          file_type::directory_file, sys::fs::all_all));
1598 
1599     if (!ParentEntry) { // Add a new root to the overlay
1600       FS->Roots.push_back(std::move(E));
1601       ParentEntry = FS->Roots.back().get();
1602       return ParentEntry;
1603     }
1604 
1605     auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
1606     DE->addContent(std::move(E));
1607     return DE->getLastContent();
1608   }
1609 
1610 private:
1611   void uniqueOverlayTree(RedirectingFileSystem *FS,
1612                          RedirectingFileSystem::Entry *SrcE,
1613                          RedirectingFileSystem::Entry *NewParentE = nullptr) {
1614     StringRef Name = SrcE->getName();
1615     switch (SrcE->getKind()) {
1616     case RedirectingFileSystem::EK_Directory: {
1617       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
1618       // Empty directories could be present in the YAML as a way to
1619       // describe a file for a current directory after some of its subdir
1620       // is parsed. This only leads to redundant walks, ignore it.
1621       if (!Name.empty())
1622         NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1623       for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1624            llvm::make_range(DE->contents_begin(), DE->contents_end()))
1625         uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1626       break;
1627     }
1628     case RedirectingFileSystem::EK_DirectoryRemap: {
1629       assert(NewParentE && "Parent entry must exist");
1630       auto *DR = cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
1631       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1632       DE->addContent(
1633           std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1634               Name, DR->getExternalContentsPath(), DR->getUseName()));
1635       break;
1636     }
1637     case RedirectingFileSystem::EK_File: {
1638       assert(NewParentE && "Parent entry must exist");
1639       auto *FE = cast<RedirectingFileSystem::FileEntry>(SrcE);
1640       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1641       DE->addContent(std::make_unique<RedirectingFileSystem::FileEntry>(
1642           Name, FE->getExternalContentsPath(), FE->getUseName()));
1643       break;
1644     }
1645     }
1646   }
1647 
1648   std::unique_ptr<RedirectingFileSystem::Entry>
1649   parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1650     auto *M = dyn_cast<yaml::MappingNode>(N);
1651     if (!M) {
1652       error(N, "expected mapping node for file or directory entry");
1653       return nullptr;
1654     }
1655 
1656     KeyStatusPair Fields[] = {
1657         KeyStatusPair("name", true),
1658         KeyStatusPair("type", true),
1659         KeyStatusPair("contents", false),
1660         KeyStatusPair("external-contents", false),
1661         KeyStatusPair("use-external-name", false),
1662     };
1663 
1664     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1665 
1666     enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet;
1667     std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1668         EntryArrayContents;
1669     SmallString<256> ExternalContentsPath;
1670     SmallString<256> Name;
1671     yaml::Node *NameValueNode = nullptr;
1672     auto UseExternalName = RedirectingFileSystem::NK_NotSet;
1673     RedirectingFileSystem::EntryKind Kind;
1674 
1675     for (auto &I : *M) {
1676       StringRef Key;
1677       // Reuse the buffer for key and value, since we don't look at key after
1678       // parsing value.
1679       SmallString<256> Buffer;
1680       if (!parseScalarString(I.getKey(), Key, Buffer))
1681         return nullptr;
1682 
1683       if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1684         return nullptr;
1685 
1686       StringRef Value;
1687       if (Key == "name") {
1688         if (!parseScalarString(I.getValue(), Value, Buffer))
1689           return nullptr;
1690 
1691         NameValueNode = I.getValue();
1692         // Guarantee that old YAML files containing paths with ".." and "."
1693         // are properly canonicalized before read into the VFS.
1694         Name = canonicalize(Value).str();
1695       } else if (Key == "type") {
1696         if (!parseScalarString(I.getValue(), Value, Buffer))
1697           return nullptr;
1698         if (Value == "file")
1699           Kind = RedirectingFileSystem::EK_File;
1700         else if (Value == "directory")
1701           Kind = RedirectingFileSystem::EK_Directory;
1702         else if (Value == "directory-remap")
1703           Kind = RedirectingFileSystem::EK_DirectoryRemap;
1704         else {
1705           error(I.getValue(), "unknown value for 'type'");
1706           return nullptr;
1707         }
1708       } else if (Key == "contents") {
1709         if (ContentsField != CF_NotSet) {
1710           error(I.getKey(),
1711                 "entry already has 'contents' or 'external-contents'");
1712           return nullptr;
1713         }
1714         ContentsField = CF_List;
1715         auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
1716         if (!Contents) {
1717           // FIXME: this is only for directories, what about files?
1718           error(I.getValue(), "expected array");
1719           return nullptr;
1720         }
1721 
1722         for (auto &I : *Contents) {
1723           if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1724                   parseEntry(&I, FS, /*IsRootEntry*/ false))
1725             EntryArrayContents.push_back(std::move(E));
1726           else
1727             return nullptr;
1728         }
1729       } else if (Key == "external-contents") {
1730         if (ContentsField != CF_NotSet) {
1731           error(I.getKey(),
1732                 "entry already has 'contents' or 'external-contents'");
1733           return nullptr;
1734         }
1735         ContentsField = CF_External;
1736         if (!parseScalarString(I.getValue(), Value, Buffer))
1737           return nullptr;
1738 
1739         SmallString<256> FullPath;
1740         if (FS->IsRelativeOverlay) {
1741           FullPath = FS->getExternalContentsPrefixDir();
1742           assert(!FullPath.empty() &&
1743                  "External contents prefix directory must exist");
1744           llvm::sys::path::append(FullPath, Value);
1745         } else {
1746           FullPath = Value;
1747         }
1748 
1749         // Guarantee that old YAML files containing paths with ".." and "."
1750         // are properly canonicalized before read into the VFS.
1751         FullPath = canonicalize(FullPath);
1752         ExternalContentsPath = FullPath.str();
1753       } else if (Key == "use-external-name") {
1754         bool Val;
1755         if (!parseScalarBool(I.getValue(), Val))
1756           return nullptr;
1757         UseExternalName = Val ? RedirectingFileSystem::NK_External
1758                               : RedirectingFileSystem::NK_Virtual;
1759       } else {
1760         llvm_unreachable("key missing from Keys");
1761       }
1762     }
1763 
1764     if (Stream.failed())
1765       return nullptr;
1766 
1767     // check for missing keys
1768     if (ContentsField == CF_NotSet) {
1769       error(N, "missing key 'contents' or 'external-contents'");
1770       return nullptr;
1771     }
1772     if (!checkMissingKeys(N, Keys))
1773       return nullptr;
1774 
1775     // check invalid configuration
1776     if (Kind == RedirectingFileSystem::EK_Directory &&
1777         UseExternalName != RedirectingFileSystem::NK_NotSet) {
1778       error(N, "'use-external-name' is not supported for 'directory' entries");
1779       return nullptr;
1780     }
1781 
1782     if (Kind == RedirectingFileSystem::EK_DirectoryRemap &&
1783         ContentsField == CF_List) {
1784       error(N, "'contents' is not supported for 'directory-remap' entries");
1785       return nullptr;
1786     }
1787 
1788     sys::path::Style path_style = sys::path::Style::native;
1789     if (IsRootEntry) {
1790       // VFS root entries may be in either Posix or Windows style.  Figure out
1791       // which style we have, and use it consistently.
1792       if (sys::path::is_absolute(Name, sys::path::Style::posix)) {
1793         path_style = sys::path::Style::posix;
1794       } else if (sys::path::is_absolute(Name,
1795                                         sys::path::Style::windows_backslash)) {
1796         path_style = sys::path::Style::windows_backslash;
1797       } else {
1798         // Relative VFS root entries are made absolute to the current working
1799         // directory, then we can determine the path style from that.
1800         auto EC = sys::fs::make_absolute(Name);
1801         if (EC) {
1802           assert(NameValueNode && "Name presence should be checked earlier");
1803           error(
1804               NameValueNode,
1805               "entry with relative path at the root level is not discoverable");
1806           return nullptr;
1807         }
1808         path_style = sys::path::is_absolute(Name, sys::path::Style::posix)
1809                          ? sys::path::Style::posix
1810                          : sys::path::Style::windows_backslash;
1811       }
1812     }
1813 
1814     // Remove trailing slash(es), being careful not to remove the root path
1815     StringRef Trimmed = Name;
1816     size_t RootPathLen = sys::path::root_path(Trimmed, path_style).size();
1817     while (Trimmed.size() > RootPathLen &&
1818            sys::path::is_separator(Trimmed.back(), path_style))
1819       Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
1820 
1821     // Get the last component
1822     StringRef LastComponent = sys::path::filename(Trimmed, path_style);
1823 
1824     std::unique_ptr<RedirectingFileSystem::Entry> Result;
1825     switch (Kind) {
1826     case RedirectingFileSystem::EK_File:
1827       Result = std::make_unique<RedirectingFileSystem::FileEntry>(
1828           LastComponent, std::move(ExternalContentsPath), UseExternalName);
1829       break;
1830     case RedirectingFileSystem::EK_DirectoryRemap:
1831       Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1832           LastComponent, std::move(ExternalContentsPath), UseExternalName);
1833       break;
1834     case RedirectingFileSystem::EK_Directory:
1835       Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1836           LastComponent, std::move(EntryArrayContents),
1837           Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1838                  0, 0, 0, file_type::directory_file, sys::fs::all_all));
1839       break;
1840     }
1841 
1842     StringRef Parent = sys::path::parent_path(Trimmed, path_style);
1843     if (Parent.empty())
1844       return Result;
1845 
1846     // if 'name' contains multiple components, create implicit directory entries
1847     for (sys::path::reverse_iterator I = sys::path::rbegin(Parent, path_style),
1848                                      E = sys::path::rend(Parent);
1849          I != E; ++I) {
1850       std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
1851       Entries.push_back(std::move(Result));
1852       Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1853           *I, std::move(Entries),
1854           Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1855                  0, 0, 0, file_type::directory_file, sys::fs::all_all));
1856     }
1857     return Result;
1858   }
1859 
1860 public:
1861   RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1862 
1863   // false on error
1864   bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1865     auto *Top = dyn_cast<yaml::MappingNode>(Root);
1866     if (!Top) {
1867       error(Root, "expected mapping node");
1868       return false;
1869     }
1870 
1871     KeyStatusPair Fields[] = {
1872         KeyStatusPair("version", true),
1873         KeyStatusPair("case-sensitive", false),
1874         KeyStatusPair("use-external-names", false),
1875         KeyStatusPair("overlay-relative", false),
1876         KeyStatusPair("fallthrough", false),
1877         KeyStatusPair("redirecting-with", false),
1878         KeyStatusPair("roots", true),
1879     };
1880 
1881     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1882     std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
1883 
1884     // Parse configuration and 'roots'
1885     for (auto &I : *Top) {
1886       SmallString<10> KeyBuffer;
1887       StringRef Key;
1888       if (!parseScalarString(I.getKey(), Key, KeyBuffer))
1889         return false;
1890 
1891       if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1892         return false;
1893 
1894       if (Key == "roots") {
1895         auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
1896         if (!Roots) {
1897           error(I.getValue(), "expected array");
1898           return false;
1899         }
1900 
1901         for (auto &I : *Roots) {
1902           if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1903                   parseEntry(&I, FS, /*IsRootEntry*/ true))
1904             RootEntries.push_back(std::move(E));
1905           else
1906             return false;
1907         }
1908       } else if (Key == "version") {
1909         StringRef VersionString;
1910         SmallString<4> Storage;
1911         if (!parseScalarString(I.getValue(), VersionString, Storage))
1912           return false;
1913         int Version;
1914         if (VersionString.getAsInteger<int>(10, Version)) {
1915           error(I.getValue(), "expected integer");
1916           return false;
1917         }
1918         if (Version < 0) {
1919           error(I.getValue(), "invalid version number");
1920           return false;
1921         }
1922         if (Version != 0) {
1923           error(I.getValue(), "version mismatch, expected 0");
1924           return false;
1925         }
1926       } else if (Key == "case-sensitive") {
1927         if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
1928           return false;
1929       } else if (Key == "overlay-relative") {
1930         if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
1931           return false;
1932       } else if (Key == "use-external-names") {
1933         if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
1934           return false;
1935       } else if (Key == "fallthrough") {
1936         if (Keys["redirecting-with"].Seen) {
1937           error(I.getValue(),
1938                 "'fallthrough' and 'redirecting-with' are mutually exclusive");
1939           return false;
1940         }
1941 
1942         bool ShouldFallthrough = false;
1943         if (!parseScalarBool(I.getValue(), ShouldFallthrough))
1944           return false;
1945 
1946         if (ShouldFallthrough) {
1947           FS->Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
1948         } else {
1949           FS->Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
1950         }
1951       } else if (Key == "redirecting-with") {
1952         if (Keys["fallthrough"].Seen) {
1953           error(I.getValue(),
1954                 "'fallthrough' and 'redirecting-with' are mutually exclusive");
1955           return false;
1956         }
1957 
1958         if (auto Kind = parseRedirectKind(I.getValue())) {
1959           FS->Redirection = *Kind;
1960         } else {
1961           error(I.getValue(), "expected valid redirect kind");
1962           return false;
1963         }
1964       } else {
1965         llvm_unreachable("key missing from Keys");
1966       }
1967     }
1968 
1969     if (Stream.failed())
1970       return false;
1971 
1972     if (!checkMissingKeys(Top, Keys))
1973       return false;
1974 
1975     // Now that we sucessefully parsed the YAML file, canonicalize the internal
1976     // representation to a proper directory tree so that we can search faster
1977     // inside the VFS.
1978     for (auto &E : RootEntries)
1979       uniqueOverlayTree(FS, E.get());
1980 
1981     return true;
1982   }
1983 };
1984 
1985 std::unique_ptr<RedirectingFileSystem>
1986 RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1987                               SourceMgr::DiagHandlerTy DiagHandler,
1988                               StringRef YAMLFilePath, void *DiagContext,
1989                               IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1990   SourceMgr SM;
1991   yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
1992 
1993   SM.setDiagHandler(DiagHandler, DiagContext);
1994   yaml::document_iterator DI = Stream.begin();
1995   yaml::Node *Root = DI->getRoot();
1996   if (DI == Stream.end() || !Root) {
1997     SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
1998     return nullptr;
1999   }
2000 
2001   RedirectingFileSystemParser P(Stream);
2002 
2003   std::unique_ptr<RedirectingFileSystem> FS(
2004       new RedirectingFileSystem(ExternalFS));
2005 
2006   if (!YAMLFilePath.empty()) {
2007     // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
2008     // to each 'external-contents' path.
2009     //
2010     // Example:
2011     //    -ivfsoverlay dummy.cache/vfs/vfs.yaml
2012     // yields:
2013     //  FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
2014     //
2015     SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
2016     std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
2017     assert(!EC && "Overlay dir final path must be absolute");
2018     (void)EC;
2019     FS->setExternalContentsPrefixDir(OverlayAbsDir);
2020   }
2021 
2022   if (!P.parse(Root, FS.get()))
2023     return nullptr;
2024 
2025   return FS;
2026 }
2027 
2028 std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create(
2029     ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
2030     bool UseExternalNames, FileSystem &ExternalFS) {
2031   std::unique_ptr<RedirectingFileSystem> FS(
2032       new RedirectingFileSystem(&ExternalFS));
2033   FS->UseExternalNames = UseExternalNames;
2034 
2035   StringMap<RedirectingFileSystem::Entry *> Entries;
2036 
2037   for (auto &Mapping : llvm::reverse(RemappedFiles)) {
2038     SmallString<128> From = StringRef(Mapping.first);
2039     SmallString<128> To = StringRef(Mapping.second);
2040     {
2041       auto EC = ExternalFS.makeAbsolute(From);
2042       (void)EC;
2043       assert(!EC && "Could not make absolute path");
2044     }
2045 
2046     // Check if we've already mapped this file. The first one we see (in the
2047     // reverse iteration) wins.
2048     RedirectingFileSystem::Entry *&ToEntry = Entries[From];
2049     if (ToEntry)
2050       continue;
2051 
2052     // Add parent directories.
2053     RedirectingFileSystem::Entry *Parent = nullptr;
2054     StringRef FromDirectory = llvm::sys::path::parent_path(From);
2055     for (auto I = llvm::sys::path::begin(FromDirectory),
2056               E = llvm::sys::path::end(FromDirectory);
2057          I != E; ++I) {
2058       Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS.get(), *I,
2059                                                                 Parent);
2060     }
2061     assert(Parent && "File without a directory?");
2062     {
2063       auto EC = ExternalFS.makeAbsolute(To);
2064       (void)EC;
2065       assert(!EC && "Could not make absolute path");
2066     }
2067 
2068     // Add the file.
2069     auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>(
2070         llvm::sys::path::filename(From), To,
2071         UseExternalNames ? RedirectingFileSystem::NK_External
2072                          : RedirectingFileSystem::NK_Virtual);
2073     ToEntry = NewFile.get();
2074     cast<RedirectingFileSystem::DirectoryEntry>(Parent)->addContent(
2075         std::move(NewFile));
2076   }
2077 
2078   return FS;
2079 }
2080 
2081 RedirectingFileSystem::LookupResult::LookupResult(
2082     Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
2083     : E(E) {
2084   assert(E != nullptr);
2085   // If the matched entry is a DirectoryRemapEntry, set ExternalRedirect to the
2086   // path of the directory it maps to in the external file system plus any
2087   // remaining path components in the provided iterator.
2088   if (auto *DRE = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(E)) {
2089     SmallString<256> Redirect(DRE->getExternalContentsPath());
2090     sys::path::append(Redirect, Start, End,
2091                       getExistingStyle(DRE->getExternalContentsPath()));
2092     ExternalRedirect = std::string(Redirect);
2093   }
2094 }
2095 
2096 std::error_code
2097 RedirectingFileSystem::makeCanonical(SmallVectorImpl<char> &Path) const {
2098   if (std::error_code EC = makeAbsolute(Path))
2099     return EC;
2100 
2101   llvm::SmallString<256> CanonicalPath =
2102       canonicalize(StringRef(Path.data(), Path.size()));
2103   if (CanonicalPath.empty())
2104     return make_error_code(llvm::errc::invalid_argument);
2105 
2106   Path.assign(CanonicalPath.begin(), CanonicalPath.end());
2107   return {};
2108 }
2109 
2110 ErrorOr<RedirectingFileSystem::LookupResult>
2111 RedirectingFileSystem::lookupPath(StringRef Path) const {
2112   sys::path::const_iterator Start = sys::path::begin(Path);
2113   sys::path::const_iterator End = sys::path::end(Path);
2114   for (const auto &Root : Roots) {
2115     ErrorOr<RedirectingFileSystem::LookupResult> Result =
2116         lookupPathImpl(Start, End, Root.get());
2117     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
2118       return Result;
2119   }
2120   return make_error_code(llvm::errc::no_such_file_or_directory);
2121 }
2122 
2123 ErrorOr<RedirectingFileSystem::LookupResult>
2124 RedirectingFileSystem::lookupPathImpl(
2125     sys::path::const_iterator Start, sys::path::const_iterator End,
2126     RedirectingFileSystem::Entry *From) const {
2127   assert(!isTraversalComponent(*Start) &&
2128          !isTraversalComponent(From->getName()) &&
2129          "Paths should not contain traversal components");
2130 
2131   StringRef FromName = From->getName();
2132 
2133   // Forward the search to the next component in case this is an empty one.
2134   if (!FromName.empty()) {
2135     if (!pathComponentMatches(*Start, FromName))
2136       return make_error_code(llvm::errc::no_such_file_or_directory);
2137 
2138     ++Start;
2139 
2140     if (Start == End) {
2141       // Match!
2142       return LookupResult(From, Start, End);
2143     }
2144   }
2145 
2146   if (isa<RedirectingFileSystem::FileEntry>(From))
2147     return make_error_code(llvm::errc::not_a_directory);
2148 
2149   if (isa<RedirectingFileSystem::DirectoryRemapEntry>(From))
2150     return LookupResult(From, Start, End);
2151 
2152   auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(From);
2153   for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
2154        llvm::make_range(DE->contents_begin(), DE->contents_end())) {
2155     ErrorOr<RedirectingFileSystem::LookupResult> Result =
2156         lookupPathImpl(Start, End, DirEntry.get());
2157     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
2158       return Result;
2159   }
2160 
2161   return make_error_code(llvm::errc::no_such_file_or_directory);
2162 }
2163 
2164 static Status getRedirectedFileStatus(const Twine &OriginalPath,
2165                                       bool UseExternalNames,
2166                                       Status ExternalStatus) {
2167   // The path has been mapped by some nested VFS and exposes an external path,
2168   // don't override it with the original path.
2169   if (ExternalStatus.ExposesExternalVFSPath)
2170     return ExternalStatus;
2171 
2172   Status S = ExternalStatus;
2173   if (!UseExternalNames)
2174     S = Status::copyWithNewName(S, OriginalPath);
2175   else
2176     S.ExposesExternalVFSPath = true;
2177   S.IsVFSMapped = true;
2178   return S;
2179 }
2180 
2181 ErrorOr<Status> RedirectingFileSystem::status(
2182     const Twine &CanonicalPath, const Twine &OriginalPath,
2183     const RedirectingFileSystem::LookupResult &Result) {
2184   if (Optional<StringRef> ExtRedirect = Result.getExternalRedirect()) {
2185     SmallString<256> CanonicalRemappedPath((*ExtRedirect).str());
2186     if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
2187       return EC;
2188 
2189     ErrorOr<Status> S = ExternalFS->status(CanonicalRemappedPath);
2190     if (!S)
2191       return S;
2192     S = Status::copyWithNewName(*S, *ExtRedirect);
2193     auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result.E);
2194     return getRedirectedFileStatus(OriginalPath,
2195                                    RE->useExternalName(UseExternalNames), *S);
2196   }
2197 
2198   auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Result.E);
2199   return Status::copyWithNewName(DE->getStatus(), CanonicalPath);
2200 }
2201 
2202 ErrorOr<Status>
2203 RedirectingFileSystem::getExternalStatus(const Twine &CanonicalPath,
2204                                          const Twine &OriginalPath) const {
2205   auto Result = ExternalFS->status(CanonicalPath);
2206 
2207   // The path has been mapped by some nested VFS, don't override it with the
2208   // original path.
2209   if (!Result || Result->ExposesExternalVFSPath)
2210     return Result;
2211   return Status::copyWithNewName(Result.get(), OriginalPath);
2212 }
2213 
2214 ErrorOr<Status> RedirectingFileSystem::status(const Twine &OriginalPath) {
2215   SmallString<256> CanonicalPath;
2216   OriginalPath.toVector(CanonicalPath);
2217 
2218   if (std::error_code EC = makeCanonical(CanonicalPath))
2219     return EC;
2220 
2221   if (Redirection == RedirectKind::Fallback) {
2222     // Attempt to find the original file first, only falling back to the
2223     // mapped file if that fails.
2224     ErrorOr<Status> S = getExternalStatus(CanonicalPath, OriginalPath);
2225     if (S)
2226       return S;
2227   }
2228 
2229   ErrorOr<RedirectingFileSystem::LookupResult> Result =
2230       lookupPath(CanonicalPath);
2231   if (!Result) {
2232     // Was not able to map file, fallthrough to using the original path if
2233     // that was the specified redirection type.
2234     if (Redirection == RedirectKind::Fallthrough &&
2235         isFileNotFound(Result.getError()))
2236       return getExternalStatus(CanonicalPath, OriginalPath);
2237     return Result.getError();
2238   }
2239 
2240   ErrorOr<Status> S = status(CanonicalPath, OriginalPath, *Result);
2241   if (!S && Redirection == RedirectKind::Fallthrough &&
2242       isFileNotFound(S.getError(), Result->E)) {
2243     // Mapped the file but it wasn't found in the underlying filesystem,
2244     // fallthrough to using the original path if that was the specified
2245     // redirection type.
2246     return getExternalStatus(CanonicalPath, OriginalPath);
2247   }
2248 
2249   return S;
2250 }
2251 
2252 namespace {
2253 
2254 /// Provide a file wrapper with an overriden status.
2255 class FileWithFixedStatus : public File {
2256   std::unique_ptr<File> InnerFile;
2257   Status S;
2258 
2259 public:
2260   FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
2261       : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
2262 
2263   ErrorOr<Status> status() override { return S; }
2264   ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2265 
2266   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
2267             bool IsVolatile) override {
2268     return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
2269                                 IsVolatile);
2270   }
2271 
2272   std::error_code close() override { return InnerFile->close(); }
2273 
2274   void setPath(const Twine &Path) override { S = S.copyWithNewName(S, Path); }
2275 };
2276 
2277 } // namespace
2278 
2279 ErrorOr<std::unique_ptr<File>>
2280 File::getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P) {
2281   // See \c getRedirectedFileStatus - don't update path if it's exposing an
2282   // external path.
2283   if (!Result || (*Result)->status()->ExposesExternalVFSPath)
2284     return Result;
2285 
2286   ErrorOr<std::unique_ptr<File>> F = std::move(*Result);
2287   auto Name = F->get()->getName();
2288   if (Name && Name.get() != P.str())
2289     F->get()->setPath(P);
2290   return F;
2291 }
2292 
2293 ErrorOr<std::unique_ptr<File>>
2294 RedirectingFileSystem::openFileForRead(const Twine &OriginalPath) {
2295   SmallString<256> CanonicalPath;
2296   OriginalPath.toVector(CanonicalPath);
2297 
2298   if (std::error_code EC = makeCanonical(CanonicalPath))
2299     return EC;
2300 
2301   if (Redirection == RedirectKind::Fallback) {
2302     // Attempt to find the original file first, only falling back to the
2303     // mapped file if that fails.
2304     auto F = File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
2305                                OriginalPath);
2306     if (F)
2307       return F;
2308   }
2309 
2310   ErrorOr<RedirectingFileSystem::LookupResult> Result =
2311       lookupPath(CanonicalPath);
2312   if (!Result) {
2313     // Was not able to map file, fallthrough to using the original path if
2314     // that was the specified redirection type.
2315     if (Redirection == RedirectKind::Fallthrough &&
2316         isFileNotFound(Result.getError()))
2317       return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
2318                                OriginalPath);
2319     return Result.getError();
2320   }
2321 
2322   if (!Result->getExternalRedirect()) // FIXME: errc::not_a_file?
2323     return make_error_code(llvm::errc::invalid_argument);
2324 
2325   StringRef ExtRedirect = *Result->getExternalRedirect();
2326   SmallString<256> CanonicalRemappedPath(ExtRedirect.str());
2327   if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
2328     return EC;
2329 
2330   auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
2331 
2332   auto ExternalFile = File::getWithPath(
2333       ExternalFS->openFileForRead(CanonicalRemappedPath), ExtRedirect);
2334   if (!ExternalFile) {
2335     if (Redirection == RedirectKind::Fallthrough &&
2336         isFileNotFound(ExternalFile.getError(), Result->E)) {
2337       // Mapped the file but it wasn't found in the underlying filesystem,
2338       // fallthrough to using the original path if that was the specified
2339       // redirection type.
2340       return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
2341                                OriginalPath);
2342     }
2343     return ExternalFile;
2344   }
2345 
2346   auto ExternalStatus = (*ExternalFile)->status();
2347   if (!ExternalStatus)
2348     return ExternalStatus.getError();
2349 
2350   // Otherwise, the file was successfully remapped. Mark it as such. Also
2351   // replace the underlying path if the external name is being used.
2352   Status S = getRedirectedFileStatus(
2353       OriginalPath, RE->useExternalName(UseExternalNames), *ExternalStatus);
2354   return std::unique_ptr<File>(
2355       std::make_unique<FileWithFixedStatus>(std::move(*ExternalFile), S));
2356 }
2357 
2358 std::error_code
2359 RedirectingFileSystem::getRealPath(const Twine &OriginalPath,
2360                                    SmallVectorImpl<char> &Output) const {
2361   SmallString<256> CanonicalPath;
2362   OriginalPath.toVector(CanonicalPath);
2363 
2364   if (std::error_code EC = makeCanonical(CanonicalPath))
2365     return EC;
2366 
2367   if (Redirection == RedirectKind::Fallback) {
2368     // Attempt to find the original file first, only falling back to the
2369     // mapped file if that fails.
2370     std::error_code EC = ExternalFS->getRealPath(CanonicalPath, Output);
2371     if (!EC)
2372       return EC;
2373   }
2374 
2375   ErrorOr<RedirectingFileSystem::LookupResult> Result =
2376       lookupPath(CanonicalPath);
2377   if (!Result) {
2378     // Was not able to map file, fallthrough to using the original path if
2379     // that was the specified redirection type.
2380     if (Redirection == RedirectKind::Fallthrough &&
2381         isFileNotFound(Result.getError()))
2382       return ExternalFS->getRealPath(CanonicalPath, Output);
2383     return Result.getError();
2384   }
2385 
2386   // If we found FileEntry or DirectoryRemapEntry, look up the mapped
2387   // path in the external file system.
2388   if (auto ExtRedirect = Result->getExternalRedirect()) {
2389     auto P = ExternalFS->getRealPath(*ExtRedirect, Output);
2390     if (P && Redirection == RedirectKind::Fallthrough &&
2391         isFileNotFound(P, Result->E)) {
2392       // Mapped the file but it wasn't found in the underlying filesystem,
2393       // fallthrough to using the original path if that was the specified
2394       // redirection type.
2395       return ExternalFS->getRealPath(CanonicalPath, Output);
2396     }
2397     return P;
2398   }
2399 
2400   // If we found a DirectoryEntry, still fallthrough to the original path if
2401   // allowed, because directories don't have a single external contents path.
2402   if (Redirection == RedirectKind::Fallthrough)
2403     return ExternalFS->getRealPath(CanonicalPath, Output);
2404   return llvm::errc::invalid_argument;
2405 }
2406 
2407 std::unique_ptr<FileSystem>
2408 vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2409                     SourceMgr::DiagHandlerTy DiagHandler,
2410                     StringRef YAMLFilePath, void *DiagContext,
2411                     IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2412   return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
2413                                        YAMLFilePath, DiagContext,
2414                                        std::move(ExternalFS));
2415 }
2416 
2417 static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
2418                           SmallVectorImpl<StringRef> &Path,
2419                           SmallVectorImpl<YAMLVFSEntry> &Entries) {
2420   auto Kind = SrcE->getKind();
2421   if (Kind == RedirectingFileSystem::EK_Directory) {
2422     auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
2423     assert(DE && "Must be a directory");
2424     for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
2425          llvm::make_range(DE->contents_begin(), DE->contents_end())) {
2426       Path.push_back(SubEntry->getName());
2427       getVFSEntries(SubEntry.get(), Path, Entries);
2428       Path.pop_back();
2429     }
2430     return;
2431   }
2432 
2433   if (Kind == RedirectingFileSystem::EK_DirectoryRemap) {
2434     auto *DR = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
2435     assert(DR && "Must be a directory remap");
2436     SmallString<128> VPath;
2437     for (auto &Comp : Path)
2438       llvm::sys::path::append(VPath, Comp);
2439     Entries.push_back(
2440         YAMLVFSEntry(VPath.c_str(), DR->getExternalContentsPath()));
2441     return;
2442   }
2443 
2444   assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
2445   auto *FE = dyn_cast<RedirectingFileSystem::FileEntry>(SrcE);
2446   assert(FE && "Must be a file");
2447   SmallString<128> VPath;
2448   for (auto &Comp : Path)
2449     llvm::sys::path::append(VPath, Comp);
2450   Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
2451 }
2452 
2453 void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2454                              SourceMgr::DiagHandlerTy DiagHandler,
2455                              StringRef YAMLFilePath,
2456                              SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
2457                              void *DiagContext,
2458                              IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2459   std::unique_ptr<RedirectingFileSystem> VFS = RedirectingFileSystem::create(
2460       std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
2461       std::move(ExternalFS));
2462   if (!VFS)
2463     return;
2464   ErrorOr<RedirectingFileSystem::LookupResult> RootResult =
2465       VFS->lookupPath("/");
2466   if (!RootResult)
2467     return;
2468   SmallVector<StringRef, 8> Components;
2469   Components.push_back("/");
2470   getVFSEntries(RootResult->E, Components, CollectedEntries);
2471 }
2472 
2473 UniqueID vfs::getNextVirtualUniqueID() {
2474   static std::atomic<unsigned> UID;
2475   unsigned ID = ++UID;
2476   // The following assumes that uint64_t max will never collide with a real
2477   // dev_t value from the OS.
2478   return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
2479 }
2480 
2481 void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath,
2482                              bool IsDirectory) {
2483   assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
2484   assert(sys::path::is_absolute(RealPath) && "real path not absolute");
2485   assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
2486   Mappings.emplace_back(VirtualPath, RealPath, IsDirectory);
2487 }
2488 
2489 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
2490   addEntry(VirtualPath, RealPath, /*IsDirectory=*/false);
2491 }
2492 
2493 void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath,
2494                                         StringRef RealPath) {
2495   addEntry(VirtualPath, RealPath, /*IsDirectory=*/true);
2496 }
2497 
2498 namespace {
2499 
2500 class JSONWriter {
2501   llvm::raw_ostream &OS;
2502   SmallVector<StringRef, 16> DirStack;
2503 
2504   unsigned getDirIndent() { return 4 * DirStack.size(); }
2505   unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
2506   bool containedIn(StringRef Parent, StringRef Path);
2507   StringRef containedPart(StringRef Parent, StringRef Path);
2508   void startDirectory(StringRef Path);
2509   void endDirectory();
2510   void writeEntry(StringRef VPath, StringRef RPath);
2511 
2512 public:
2513   JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
2514 
2515   void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
2516              Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
2517              StringRef OverlayDir);
2518 };
2519 
2520 } // namespace
2521 
2522 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2523   using namespace llvm::sys;
2524 
2525   // Compare each path component.
2526   auto IParent = path::begin(Parent), EParent = path::end(Parent);
2527   for (auto IChild = path::begin(Path), EChild = path::end(Path);
2528        IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2529     if (*IParent != *IChild)
2530       return false;
2531   }
2532   // Have we exhausted the parent path?
2533   return IParent == EParent;
2534 }
2535 
2536 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2537   assert(!Parent.empty());
2538   assert(containedIn(Parent, Path));
2539   return Path.slice(Parent.size() + 1, StringRef::npos);
2540 }
2541 
2542 void JSONWriter::startDirectory(StringRef Path) {
2543   StringRef Name =
2544       DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
2545   DirStack.push_back(Path);
2546   unsigned Indent = getDirIndent();
2547   OS.indent(Indent) << "{\n";
2548   OS.indent(Indent + 2) << "'type': 'directory',\n";
2549   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
2550   OS.indent(Indent + 2) << "'contents': [\n";
2551 }
2552 
2553 void JSONWriter::endDirectory() {
2554   unsigned Indent = getDirIndent();
2555   OS.indent(Indent + 2) << "]\n";
2556   OS.indent(Indent) << "}";
2557 
2558   DirStack.pop_back();
2559 }
2560 
2561 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2562   unsigned Indent = getFileIndent();
2563   OS.indent(Indent) << "{\n";
2564   OS.indent(Indent + 2) << "'type': 'file',\n";
2565   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
2566   OS.indent(Indent + 2) << "'external-contents': \""
2567                         << llvm::yaml::escape(RPath) << "\"\n";
2568   OS.indent(Indent) << "}";
2569 }
2570 
2571 void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
2572                        Optional<bool> UseExternalNames,
2573                        Optional<bool> IsCaseSensitive,
2574                        Optional<bool> IsOverlayRelative,
2575                        StringRef OverlayDir) {
2576   using namespace llvm::sys;
2577 
2578   OS << "{\n"
2579         "  'version': 0,\n";
2580   if (IsCaseSensitive.hasValue())
2581     OS << "  'case-sensitive': '"
2582        << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
2583   if (UseExternalNames.hasValue())
2584     OS << "  'use-external-names': '"
2585        << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
2586   bool UseOverlayRelative = false;
2587   if (IsOverlayRelative.hasValue()) {
2588     UseOverlayRelative = IsOverlayRelative.getValue();
2589     OS << "  'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2590        << "',\n";
2591   }
2592   OS << "  'roots': [\n";
2593 
2594   if (!Entries.empty()) {
2595     const YAMLVFSEntry &Entry = Entries.front();
2596 
2597     startDirectory(
2598       Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath)
2599     );
2600 
2601     StringRef RPath = Entry.RPath;
2602     if (UseOverlayRelative) {
2603       unsigned OverlayDirLen = OverlayDir.size();
2604       assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2605              "Overlay dir must be contained in RPath");
2606       RPath = RPath.slice(OverlayDirLen, RPath.size());
2607     }
2608 
2609     bool IsCurrentDirEmpty = true;
2610     if (!Entry.IsDirectory) {
2611       writeEntry(path::filename(Entry.VPath), RPath);
2612       IsCurrentDirEmpty = false;
2613     }
2614 
2615     for (const auto &Entry : Entries.slice(1)) {
2616       StringRef Dir =
2617           Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath);
2618       if (Dir == DirStack.back()) {
2619         if (!IsCurrentDirEmpty) {
2620           OS << ",\n";
2621         }
2622       } else {
2623         bool IsDirPoppedFromStack = false;
2624         while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2625           OS << "\n";
2626           endDirectory();
2627           IsDirPoppedFromStack = true;
2628         }
2629         if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
2630           OS << ",\n";
2631         }
2632         startDirectory(Dir);
2633         IsCurrentDirEmpty = true;
2634       }
2635       StringRef RPath = Entry.RPath;
2636       if (UseOverlayRelative) {
2637         unsigned OverlayDirLen = OverlayDir.size();
2638         assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2639                "Overlay dir must be contained in RPath");
2640         RPath = RPath.slice(OverlayDirLen, RPath.size());
2641       }
2642       if (!Entry.IsDirectory) {
2643         writeEntry(path::filename(Entry.VPath), RPath);
2644         IsCurrentDirEmpty = false;
2645       }
2646     }
2647 
2648     while (!DirStack.empty()) {
2649       OS << "\n";
2650       endDirectory();
2651     }
2652     OS << "\n";
2653   }
2654 
2655   OS << "  ]\n"
2656      << "}\n";
2657 }
2658 
2659 void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2660   llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2661     return LHS.VPath < RHS.VPath;
2662   });
2663 
2664   JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
2665                        IsOverlayRelative, OverlayDir);
2666 }
2667 
2668 vfs::recursive_directory_iterator::recursive_directory_iterator(
2669     FileSystem &FS_, const Twine &Path, std::error_code &EC)
2670     : FS(&FS_) {
2671   directory_iterator I = FS->dir_begin(Path, EC);
2672   if (I != directory_iterator()) {
2673     State = std::make_shared<detail::RecDirIterState>();
2674     State->Stack.push(I);
2675   }
2676 }
2677 
2678 vfs::recursive_directory_iterator &
2679 recursive_directory_iterator::increment(std::error_code &EC) {
2680   assert(FS && State && !State->Stack.empty() && "incrementing past end");
2681   assert(!State->Stack.top()->path().empty() && "non-canonical end iterator");
2682   vfs::directory_iterator End;
2683 
2684   if (State->HasNoPushRequest)
2685     State->HasNoPushRequest = false;
2686   else {
2687     if (State->Stack.top()->type() == sys::fs::file_type::directory_file) {
2688       vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC);
2689       if (I != End) {
2690         State->Stack.push(I);
2691         return *this;
2692       }
2693     }
2694   }
2695 
2696   while (!State->Stack.empty() && State->Stack.top().increment(EC) == End)
2697     State->Stack.pop();
2698 
2699   if (State->Stack.empty())
2700     State.reset(); // end iterator
2701 
2702   return *this;
2703 }
2704