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