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