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