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