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