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