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