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