1fc51490bSJonas Devlieghere //===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
2fc51490bSJonas Devlieghere //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fc51490bSJonas Devlieghere //
7fc51490bSJonas Devlieghere //===----------------------------------------------------------------------===//
8fc51490bSJonas Devlieghere //
9fc51490bSJonas Devlieghere // This file implements the VirtualFileSystem interface.
10fc51490bSJonas Devlieghere //
11fc51490bSJonas Devlieghere //===----------------------------------------------------------------------===//
12fc51490bSJonas Devlieghere 
13fc51490bSJonas Devlieghere #include "llvm/Support/VirtualFileSystem.h"
14fc51490bSJonas Devlieghere #include "llvm/ADT/ArrayRef.h"
15fc51490bSJonas Devlieghere #include "llvm/ADT/DenseMap.h"
16fc51490bSJonas Devlieghere #include "llvm/ADT/IntrusiveRefCntPtr.h"
17fc51490bSJonas Devlieghere #include "llvm/ADT/None.h"
18fc51490bSJonas Devlieghere #include "llvm/ADT/Optional.h"
19fc51490bSJonas Devlieghere #include "llvm/ADT/STLExtras.h"
20fc51490bSJonas Devlieghere #include "llvm/ADT/SmallString.h"
21fc51490bSJonas Devlieghere #include "llvm/ADT/SmallVector.h"
22fc51490bSJonas Devlieghere #include "llvm/ADT/StringRef.h"
23fc51490bSJonas Devlieghere #include "llvm/ADT/StringSet.h"
24fc51490bSJonas Devlieghere #include "llvm/ADT/Twine.h"
25fc51490bSJonas Devlieghere #include "llvm/ADT/iterator_range.h"
26fc51490bSJonas Devlieghere #include "llvm/Config/llvm-config.h"
27fc51490bSJonas Devlieghere #include "llvm/Support/Casting.h"
28fc51490bSJonas Devlieghere #include "llvm/Support/Chrono.h"
29fc51490bSJonas Devlieghere #include "llvm/Support/Compiler.h"
30fc51490bSJonas Devlieghere #include "llvm/Support/Debug.h"
31fc51490bSJonas Devlieghere #include "llvm/Support/Errc.h"
32fc51490bSJonas Devlieghere #include "llvm/Support/ErrorHandling.h"
33fc51490bSJonas Devlieghere #include "llvm/Support/ErrorOr.h"
34fc51490bSJonas Devlieghere #include "llvm/Support/FileSystem.h"
3522555bafSSam McCall #include "llvm/Support/FileSystem/UniqueID.h"
36fc51490bSJonas Devlieghere #include "llvm/Support/MemoryBuffer.h"
37fc51490bSJonas Devlieghere #include "llvm/Support/Path.h"
38fc51490bSJonas Devlieghere #include "llvm/Support/Process.h"
39fc51490bSJonas Devlieghere #include "llvm/Support/SMLoc.h"
40fc51490bSJonas Devlieghere #include "llvm/Support/SourceMgr.h"
41fc51490bSJonas Devlieghere #include "llvm/Support/YAMLParser.h"
42fc51490bSJonas Devlieghere #include "llvm/Support/raw_ostream.h"
43fc51490bSJonas Devlieghere #include <algorithm>
44fc51490bSJonas Devlieghere #include <atomic>
45fc51490bSJonas Devlieghere #include <cassert>
46fc51490bSJonas Devlieghere #include <cstdint>
47fc51490bSJonas Devlieghere #include <iterator>
48fc51490bSJonas Devlieghere #include <limits>
49fc51490bSJonas Devlieghere #include <map>
50fc51490bSJonas Devlieghere #include <memory>
51fc51490bSJonas Devlieghere #include <mutex>
52fc51490bSJonas Devlieghere #include <string>
53fc51490bSJonas Devlieghere #include <system_error>
54fc51490bSJonas Devlieghere #include <utility>
55fc51490bSJonas Devlieghere #include <vector>
56fc51490bSJonas Devlieghere 
57fc51490bSJonas Devlieghere using namespace llvm;
58fc51490bSJonas Devlieghere using namespace llvm::vfs;
59fc51490bSJonas Devlieghere 
60cc418a3aSReid Kleckner using llvm::sys::fs::file_t;
61fc51490bSJonas Devlieghere using llvm::sys::fs::file_status;
62fc51490bSJonas Devlieghere using llvm::sys::fs::file_type;
63cc418a3aSReid Kleckner using llvm::sys::fs::kInvalidFile;
64fc51490bSJonas Devlieghere using llvm::sys::fs::perms;
65fc51490bSJonas Devlieghere using llvm::sys::fs::UniqueID;
66fc51490bSJonas Devlieghere 
67fc51490bSJonas Devlieghere Status::Status(const file_status &Status)
68fc51490bSJonas Devlieghere     : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
69fc51490bSJonas Devlieghere       User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
70fc51490bSJonas Devlieghere       Type(Status.type()), Perms(Status.permissions()) {}
71fc51490bSJonas Devlieghere 
72e7b94649SDuncan P. N. Exon Smith Status::Status(const Twine &Name, UniqueID UID, sys::TimePoint<> MTime,
73fc51490bSJonas Devlieghere                uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
74fc51490bSJonas Devlieghere                perms Perms)
75e7b94649SDuncan P. N. Exon Smith     : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
76e7b94649SDuncan P. N. Exon Smith       Size(Size), Type(Type), Perms(Perms) {}
77fc51490bSJonas Devlieghere 
78f6680345SJan Svoboda Status Status::copyWithNewSize(const Status &In, uint64_t NewSize) {
79f6680345SJan Svoboda   return Status(In.getName(), In.getUniqueID(), In.getLastModificationTime(),
80f6680345SJan Svoboda                 In.getUser(), In.getGroup(), NewSize, In.getType(),
81f6680345SJan Svoboda                 In.getPermissions());
82f6680345SJan Svoboda }
83f6680345SJan Svoboda 
84e7b94649SDuncan P. N. Exon Smith Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
85fc51490bSJonas Devlieghere   return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
86fc51490bSJonas Devlieghere                 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
87fc51490bSJonas Devlieghere                 In.getPermissions());
88fc51490bSJonas Devlieghere }
89fc51490bSJonas Devlieghere 
90e7b94649SDuncan P. N. Exon Smith Status Status::copyWithNewName(const file_status &In, const Twine &NewName) {
91fc51490bSJonas Devlieghere   return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
92fc51490bSJonas Devlieghere                 In.getUser(), In.getGroup(), In.getSize(), In.type(),
93fc51490bSJonas Devlieghere                 In.permissions());
94fc51490bSJonas Devlieghere }
95fc51490bSJonas Devlieghere 
96fc51490bSJonas Devlieghere bool Status::equivalent(const Status &Other) const {
97fc51490bSJonas Devlieghere   assert(isStatusKnown() && Other.isStatusKnown());
98fc51490bSJonas Devlieghere   return getUniqueID() == Other.getUniqueID();
99fc51490bSJonas Devlieghere }
100fc51490bSJonas Devlieghere 
101fc51490bSJonas Devlieghere bool Status::isDirectory() const { return Type == file_type::directory_file; }
102fc51490bSJonas Devlieghere 
103fc51490bSJonas Devlieghere bool Status::isRegularFile() const { return Type == file_type::regular_file; }
104fc51490bSJonas Devlieghere 
105fc51490bSJonas Devlieghere bool Status::isOther() const {
106fc51490bSJonas Devlieghere   return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
107fc51490bSJonas Devlieghere }
108fc51490bSJonas Devlieghere 
109fc51490bSJonas Devlieghere bool Status::isSymlink() const { return Type == file_type::symlink_file; }
110fc51490bSJonas Devlieghere 
111fc51490bSJonas Devlieghere bool Status::isStatusKnown() const { return Type != file_type::status_error; }
112fc51490bSJonas Devlieghere 
113fc51490bSJonas Devlieghere bool Status::exists() const {
114fc51490bSJonas Devlieghere   return isStatusKnown() && Type != file_type::file_not_found;
115fc51490bSJonas Devlieghere }
116fc51490bSJonas Devlieghere 
117fc51490bSJonas Devlieghere File::~File() = default;
118fc51490bSJonas Devlieghere 
119fc51490bSJonas Devlieghere FileSystem::~FileSystem() = default;
120fc51490bSJonas Devlieghere 
121fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<MemoryBuffer>>
122fc51490bSJonas Devlieghere FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
123fc51490bSJonas Devlieghere                              bool RequiresNullTerminator, bool IsVolatile) {
124fc51490bSJonas Devlieghere   auto F = openFileForRead(Name);
125fc51490bSJonas Devlieghere   if (!F)
126fc51490bSJonas Devlieghere     return F.getError();
127fc51490bSJonas Devlieghere 
128fc51490bSJonas Devlieghere   return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
129fc51490bSJonas Devlieghere }
130fc51490bSJonas Devlieghere 
131fc51490bSJonas Devlieghere std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
132fc51490bSJonas Devlieghere   if (llvm::sys::path::is_absolute(Path))
133fc51490bSJonas Devlieghere     return {};
134fc51490bSJonas Devlieghere 
135fc51490bSJonas Devlieghere   auto WorkingDir = getCurrentWorkingDirectory();
136fc51490bSJonas Devlieghere   if (!WorkingDir)
137fc51490bSJonas Devlieghere     return WorkingDir.getError();
138fc51490bSJonas Devlieghere 
1391ad53ca2SPavel Labath   llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
1401ad53ca2SPavel Labath   return {};
141fc51490bSJonas Devlieghere }
142fc51490bSJonas Devlieghere 
143fc51490bSJonas Devlieghere std::error_code FileSystem::getRealPath(const Twine &Path,
14499538e89SSam McCall                                         SmallVectorImpl<char> &Output) const {
145fc51490bSJonas Devlieghere   return errc::operation_not_permitted;
146fc51490bSJonas Devlieghere }
147fc51490bSJonas Devlieghere 
148cbb5c868SJonas Devlieghere std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
149cbb5c868SJonas Devlieghere   return errc::operation_not_permitted;
150cbb5c868SJonas Devlieghere }
151cbb5c868SJonas Devlieghere 
152fc51490bSJonas Devlieghere bool FileSystem::exists(const Twine &Path) {
153fc51490bSJonas Devlieghere   auto Status = status(Path);
154fc51490bSJonas Devlieghere   return Status && Status->exists();
155fc51490bSJonas Devlieghere }
156fc51490bSJonas Devlieghere 
157fc51490bSJonas Devlieghere #ifndef NDEBUG
158fc51490bSJonas Devlieghere static bool isTraversalComponent(StringRef Component) {
159fc51490bSJonas Devlieghere   return Component.equals("..") || Component.equals(".");
160fc51490bSJonas Devlieghere }
161fc51490bSJonas Devlieghere 
162fc51490bSJonas Devlieghere static bool pathHasTraversal(StringRef Path) {
163fc51490bSJonas Devlieghere   using namespace llvm::sys;
164fc51490bSJonas Devlieghere 
165fc51490bSJonas Devlieghere   for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
166fc51490bSJonas Devlieghere     if (isTraversalComponent(Comp))
167fc51490bSJonas Devlieghere       return true;
168fc51490bSJonas Devlieghere   return false;
169fc51490bSJonas Devlieghere }
170fc51490bSJonas Devlieghere #endif
171fc51490bSJonas Devlieghere 
172fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
173fc51490bSJonas Devlieghere // RealFileSystem implementation
174fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
175fc51490bSJonas Devlieghere 
176fc51490bSJonas Devlieghere namespace {
177fc51490bSJonas Devlieghere 
178fc51490bSJonas Devlieghere /// Wrapper around a raw file descriptor.
179fc51490bSJonas Devlieghere class RealFile : public File {
180fc51490bSJonas Devlieghere   friend class RealFileSystem;
181fc51490bSJonas Devlieghere 
182cc418a3aSReid Kleckner   file_t FD;
183fc51490bSJonas Devlieghere   Status S;
184fc51490bSJonas Devlieghere   std::string RealName;
185fc51490bSJonas Devlieghere 
186115a6ecdSSimon Pilgrim   RealFile(file_t RawFD, StringRef NewName, StringRef NewRealPathName)
187115a6ecdSSimon Pilgrim       : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
188fc51490bSJonas Devlieghere                      llvm::sys::fs::file_type::status_error, {}),
189fc51490bSJonas Devlieghere         RealName(NewRealPathName.str()) {
190cc418a3aSReid Kleckner     assert(FD != kInvalidFile && "Invalid or inactive file descriptor");
191fc51490bSJonas Devlieghere   }
192fc51490bSJonas Devlieghere 
193fc51490bSJonas Devlieghere public:
194fc51490bSJonas Devlieghere   ~RealFile() override;
195fc51490bSJonas Devlieghere 
196fc51490bSJonas Devlieghere   ErrorOr<Status> status() override;
197fc51490bSJonas Devlieghere   ErrorOr<std::string> getName() override;
198fc51490bSJonas Devlieghere   ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
199fc51490bSJonas Devlieghere                                                    int64_t FileSize,
200fc51490bSJonas Devlieghere                                                    bool RequiresNullTerminator,
201fc51490bSJonas Devlieghere                                                    bool IsVolatile) override;
202fc51490bSJonas Devlieghere   std::error_code close() override;
20386e2af80SKeith Smiley   void setPath(const Twine &Path) override;
204fc51490bSJonas Devlieghere };
205fc51490bSJonas Devlieghere 
206fc51490bSJonas Devlieghere } // namespace
207fc51490bSJonas Devlieghere 
208fc51490bSJonas Devlieghere RealFile::~RealFile() { close(); }
209fc51490bSJonas Devlieghere 
210fc51490bSJonas Devlieghere ErrorOr<Status> RealFile::status() {
211cc418a3aSReid Kleckner   assert(FD != kInvalidFile && "cannot stat closed file");
212fc51490bSJonas Devlieghere   if (!S.isStatusKnown()) {
213fc51490bSJonas Devlieghere     file_status RealStatus;
214fc51490bSJonas Devlieghere     if (std::error_code EC = sys::fs::status(FD, RealStatus))
215fc51490bSJonas Devlieghere       return EC;
216fc51490bSJonas Devlieghere     S = Status::copyWithNewName(RealStatus, S.getName());
217fc51490bSJonas Devlieghere   }
218fc51490bSJonas Devlieghere   return S;
219fc51490bSJonas Devlieghere }
220fc51490bSJonas Devlieghere 
221fc51490bSJonas Devlieghere ErrorOr<std::string> RealFile::getName() {
222fc51490bSJonas Devlieghere   return RealName.empty() ? S.getName().str() : RealName;
223fc51490bSJonas Devlieghere }
224fc51490bSJonas Devlieghere 
225fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<MemoryBuffer>>
226fc51490bSJonas Devlieghere RealFile::getBuffer(const Twine &Name, int64_t FileSize,
227fc51490bSJonas Devlieghere                     bool RequiresNullTerminator, bool IsVolatile) {
228cc418a3aSReid Kleckner   assert(FD != kInvalidFile && "cannot get buffer for closed file");
229fc51490bSJonas Devlieghere   return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
230fc51490bSJonas Devlieghere                                    IsVolatile);
231fc51490bSJonas Devlieghere }
232fc51490bSJonas Devlieghere 
233fc51490bSJonas Devlieghere std::error_code RealFile::close() {
234cc418a3aSReid Kleckner   std::error_code EC = sys::fs::closeFile(FD);
235cc418a3aSReid Kleckner   FD = kInvalidFile;
236fc51490bSJonas Devlieghere   return EC;
237fc51490bSJonas Devlieghere }
238fc51490bSJonas Devlieghere 
23986e2af80SKeith Smiley void RealFile::setPath(const Twine &Path) {
24086e2af80SKeith Smiley   RealName = Path.str();
24186e2af80SKeith Smiley   if (auto Status = status())
24286e2af80SKeith Smiley     S = Status.get().copyWithNewName(Status.get(), Path);
24386e2af80SKeith Smiley }
24486e2af80SKeith Smiley 
245fc51490bSJonas Devlieghere namespace {
246fc51490bSJonas Devlieghere 
24715e475e2SSam McCall /// A file system according to your operating system.
24815e475e2SSam McCall /// This may be linked to the process's working directory, or maintain its own.
24915e475e2SSam McCall ///
25015e475e2SSam McCall /// Currently, its own working directory is emulated by storing the path and
25115e475e2SSam McCall /// sending absolute paths to llvm::sys::fs:: functions.
25215e475e2SSam McCall /// A more principled approach would be to push this down a level, modelling
25315e475e2SSam McCall /// the working dir as an llvm::sys::fs::WorkingDir or similar.
25415e475e2SSam McCall /// This would enable the use of openat()-style functions on some platforms.
255fc51490bSJonas Devlieghere class RealFileSystem : public FileSystem {
256fc51490bSJonas Devlieghere public:
25715e475e2SSam McCall   explicit RealFileSystem(bool LinkCWDToProcess) {
25815e475e2SSam McCall     if (!LinkCWDToProcess) {
25915e475e2SSam McCall       SmallString<128> PWD, RealPWD;
26015e475e2SSam McCall       if (llvm::sys::fs::current_path(PWD))
26115e475e2SSam McCall         return; // Awful, but nothing to do here.
26215e475e2SSam McCall       if (llvm::sys::fs::real_path(PWD, RealPWD))
26315e475e2SSam McCall         WD = {PWD, PWD};
26415e475e2SSam McCall       else
26515e475e2SSam McCall         WD = {PWD, RealPWD};
26615e475e2SSam McCall     }
26715e475e2SSam McCall   }
26815e475e2SSam McCall 
269fc51490bSJonas Devlieghere   ErrorOr<Status> status(const Twine &Path) override;
270fc51490bSJonas Devlieghere   ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
271fc51490bSJonas Devlieghere   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
272fc51490bSJonas Devlieghere 
273fc51490bSJonas Devlieghere   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
274fc51490bSJonas Devlieghere   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
275cbb5c868SJonas Devlieghere   std::error_code isLocal(const Twine &Path, bool &Result) override;
27699538e89SSam McCall   std::error_code getRealPath(const Twine &Path,
27799538e89SSam McCall                               SmallVectorImpl<char> &Output) const override;
278fc51490bSJonas Devlieghere 
279fc51490bSJonas Devlieghere private:
28015e475e2SSam McCall   // If this FS has its own working dir, use it to make Path absolute.
28115e475e2SSam McCall   // The returned twine is safe to use as long as both Storage and Path live.
28215e475e2SSam McCall   Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const {
28315e475e2SSam McCall     if (!WD)
28415e475e2SSam McCall       return Path;
28515e475e2SSam McCall     Path.toVector(Storage);
28615e475e2SSam McCall     sys::fs::make_absolute(WD->Resolved, Storage);
28715e475e2SSam McCall     return Storage;
28815e475e2SSam McCall   }
28915e475e2SSam McCall 
29015e475e2SSam McCall   struct WorkingDirectory {
29115e475e2SSam McCall     // The current working directory, without symlinks resolved. (echo $PWD).
29215e475e2SSam McCall     SmallString<128> Specified;
29315e475e2SSam McCall     // The current working directory, with links resolved. (readlink .).
29415e475e2SSam McCall     SmallString<128> Resolved;
29515e475e2SSam McCall   };
29615e475e2SSam McCall   Optional<WorkingDirectory> WD;
297fc51490bSJonas Devlieghere };
298fc51490bSJonas Devlieghere 
299fc51490bSJonas Devlieghere } // namespace
300fc51490bSJonas Devlieghere 
301fc51490bSJonas Devlieghere ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
30215e475e2SSam McCall   SmallString<256> Storage;
303fc51490bSJonas Devlieghere   sys::fs::file_status RealStatus;
30415e475e2SSam McCall   if (std::error_code EC =
30515e475e2SSam McCall           sys::fs::status(adjustPath(Path, Storage), RealStatus))
306fc51490bSJonas Devlieghere     return EC;
307e7b94649SDuncan P. N. Exon Smith   return Status::copyWithNewName(RealStatus, Path);
308fc51490bSJonas Devlieghere }
309fc51490bSJonas Devlieghere 
310fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
311fc51490bSJonas Devlieghere RealFileSystem::openFileForRead(const Twine &Name) {
31215e475e2SSam McCall   SmallString<256> RealName, Storage;
313cc418a3aSReid Kleckner   Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead(
314cc418a3aSReid Kleckner       adjustPath(Name, Storage), sys::fs::OF_None, &RealName);
315cc418a3aSReid Kleckner   if (!FDOrErr)
316cc418a3aSReid Kleckner     return errorToErrorCode(FDOrErr.takeError());
317cc418a3aSReid Kleckner   return std::unique_ptr<File>(
318cc418a3aSReid Kleckner       new RealFile(*FDOrErr, Name.str(), RealName.str()));
319fc51490bSJonas Devlieghere }
320fc51490bSJonas Devlieghere 
321fc51490bSJonas Devlieghere llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
32215e475e2SSam McCall   if (WD)
323adcd0268SBenjamin Kramer     return std::string(WD->Specified.str());
32415e475e2SSam McCall 
32515e475e2SSam McCall   SmallString<128> Dir;
326fc51490bSJonas Devlieghere   if (std::error_code EC = llvm::sys::fs::current_path(Dir))
327fc51490bSJonas Devlieghere     return EC;
328adcd0268SBenjamin Kramer   return std::string(Dir.str());
329fc51490bSJonas Devlieghere }
330fc51490bSJonas Devlieghere 
331fc51490bSJonas Devlieghere std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
33215e475e2SSam McCall   if (!WD)
33315e475e2SSam McCall     return llvm::sys::fs::set_current_path(Path);
334fc51490bSJonas Devlieghere 
33515e475e2SSam McCall   SmallString<128> Absolute, Resolved, Storage;
33615e475e2SSam McCall   adjustPath(Path, Storage).toVector(Absolute);
33715e475e2SSam McCall   bool IsDir;
33815e475e2SSam McCall   if (auto Err = llvm::sys::fs::is_directory(Absolute, IsDir))
33915e475e2SSam McCall     return Err;
34015e475e2SSam McCall   if (!IsDir)
34115e475e2SSam McCall     return std::make_error_code(std::errc::not_a_directory);
34215e475e2SSam McCall   if (auto Err = llvm::sys::fs::real_path(Absolute, Resolved))
34315e475e2SSam McCall     return Err;
34415e475e2SSam McCall   WD = {Absolute, Resolved};
345fc51490bSJonas Devlieghere   return std::error_code();
346fc51490bSJonas Devlieghere }
347fc51490bSJonas Devlieghere 
348cbb5c868SJonas Devlieghere std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
34915e475e2SSam McCall   SmallString<256> Storage;
35015e475e2SSam McCall   return llvm::sys::fs::is_local(adjustPath(Path, Storage), Result);
351cbb5c868SJonas Devlieghere }
352cbb5c868SJonas Devlieghere 
35399538e89SSam McCall std::error_code
35499538e89SSam McCall RealFileSystem::getRealPath(const Twine &Path,
35599538e89SSam McCall                             SmallVectorImpl<char> &Output) const {
35615e475e2SSam McCall   SmallString<256> Storage;
35715e475e2SSam McCall   return llvm::sys::fs::real_path(adjustPath(Path, Storage), Output);
358fc51490bSJonas Devlieghere }
359fc51490bSJonas Devlieghere 
360fc51490bSJonas Devlieghere IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
36115e475e2SSam McCall   static IntrusiveRefCntPtr<FileSystem> FS(new RealFileSystem(true));
362fc51490bSJonas Devlieghere   return FS;
363fc51490bSJonas Devlieghere }
364fc51490bSJonas Devlieghere 
36515e475e2SSam McCall std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() {
3660eaee545SJonas Devlieghere   return std::make_unique<RealFileSystem>(false);
36715e475e2SSam McCall }
36815e475e2SSam McCall 
369fc51490bSJonas Devlieghere namespace {
370fc51490bSJonas Devlieghere 
371fc51490bSJonas Devlieghere class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
372fc51490bSJonas Devlieghere   llvm::sys::fs::directory_iterator Iter;
373fc51490bSJonas Devlieghere 
374fc51490bSJonas Devlieghere public:
375fc51490bSJonas Devlieghere   RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
376fc51490bSJonas Devlieghere     if (Iter != llvm::sys::fs::directory_iterator())
377fc51490bSJonas Devlieghere       CurrentEntry = directory_entry(Iter->path(), Iter->type());
378fc51490bSJonas Devlieghere   }
379fc51490bSJonas Devlieghere 
380fc51490bSJonas Devlieghere   std::error_code increment() override {
381fc51490bSJonas Devlieghere     std::error_code EC;
382fc51490bSJonas Devlieghere     Iter.increment(EC);
383fc51490bSJonas Devlieghere     CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
384fc51490bSJonas Devlieghere                        ? directory_entry()
385fc51490bSJonas Devlieghere                        : directory_entry(Iter->path(), Iter->type());
386fc51490bSJonas Devlieghere     return EC;
387fc51490bSJonas Devlieghere   }
388fc51490bSJonas Devlieghere };
389fc51490bSJonas Devlieghere 
390fc51490bSJonas Devlieghere } // namespace
391fc51490bSJonas Devlieghere 
392fc51490bSJonas Devlieghere directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
393fc51490bSJonas Devlieghere                                              std::error_code &EC) {
39415e475e2SSam McCall   SmallString<128> Storage;
39515e475e2SSam McCall   return directory_iterator(
39615e475e2SSam McCall       std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
397fc51490bSJonas Devlieghere }
398fc51490bSJonas Devlieghere 
399fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
400fc51490bSJonas Devlieghere // OverlayFileSystem implementation
401fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
402fc51490bSJonas Devlieghere 
403fc51490bSJonas Devlieghere OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
404fc51490bSJonas Devlieghere   FSList.push_back(std::move(BaseFS));
405fc51490bSJonas Devlieghere }
406fc51490bSJonas Devlieghere 
407fc51490bSJonas Devlieghere void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
408fc51490bSJonas Devlieghere   FSList.push_back(FS);
409fc51490bSJonas Devlieghere   // Synchronize added file systems by duplicating the working directory from
410fc51490bSJonas Devlieghere   // the first one in the list.
411fc51490bSJonas Devlieghere   FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
412fc51490bSJonas Devlieghere }
413fc51490bSJonas Devlieghere 
414fc51490bSJonas Devlieghere ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
415fc51490bSJonas Devlieghere   // FIXME: handle symlinks that cross file systems
416fc51490bSJonas Devlieghere   for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
417fc51490bSJonas Devlieghere     ErrorOr<Status> Status = (*I)->status(Path);
418fc51490bSJonas Devlieghere     if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
419fc51490bSJonas Devlieghere       return Status;
420fc51490bSJonas Devlieghere   }
421fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
422fc51490bSJonas Devlieghere }
423fc51490bSJonas Devlieghere 
424fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
425fc51490bSJonas Devlieghere OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
426fc51490bSJonas Devlieghere   // FIXME: handle symlinks that cross file systems
427fc51490bSJonas Devlieghere   for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
428fc51490bSJonas Devlieghere     auto Result = (*I)->openFileForRead(Path);
429fc51490bSJonas Devlieghere     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
430fc51490bSJonas Devlieghere       return Result;
431fc51490bSJonas Devlieghere   }
432fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
433fc51490bSJonas Devlieghere }
434fc51490bSJonas Devlieghere 
435fc51490bSJonas Devlieghere llvm::ErrorOr<std::string>
436fc51490bSJonas Devlieghere OverlayFileSystem::getCurrentWorkingDirectory() const {
437fc51490bSJonas Devlieghere   // All file systems are synchronized, just take the first working directory.
438fc51490bSJonas Devlieghere   return FSList.front()->getCurrentWorkingDirectory();
439fc51490bSJonas Devlieghere }
440fc51490bSJonas Devlieghere 
441fc51490bSJonas Devlieghere std::error_code
442fc51490bSJonas Devlieghere OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
443fc51490bSJonas Devlieghere   for (auto &FS : FSList)
444fc51490bSJonas Devlieghere     if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
445fc51490bSJonas Devlieghere       return EC;
446fc51490bSJonas Devlieghere   return {};
447fc51490bSJonas Devlieghere }
448fc51490bSJonas Devlieghere 
449cbb5c868SJonas Devlieghere std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
450cbb5c868SJonas Devlieghere   for (auto &FS : FSList)
451cbb5c868SJonas Devlieghere     if (FS->exists(Path))
452cbb5c868SJonas Devlieghere       return FS->isLocal(Path, Result);
453cbb5c868SJonas Devlieghere   return errc::no_such_file_or_directory;
454cbb5c868SJonas Devlieghere }
455cbb5c868SJonas Devlieghere 
45699538e89SSam McCall std::error_code
45799538e89SSam McCall OverlayFileSystem::getRealPath(const Twine &Path,
45899538e89SSam McCall                                SmallVectorImpl<char> &Output) const {
4593322354bSKazu Hirata   for (const auto &FS : FSList)
460fc51490bSJonas Devlieghere     if (FS->exists(Path))
46199538e89SSam McCall       return FS->getRealPath(Path, Output);
462fc51490bSJonas Devlieghere   return errc::no_such_file_or_directory;
463fc51490bSJonas Devlieghere }
464fc51490bSJonas Devlieghere 
465fc51490bSJonas Devlieghere llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
466fc51490bSJonas Devlieghere 
467fc51490bSJonas Devlieghere namespace {
468fc51490bSJonas Devlieghere 
469719f7784SNathan Hawes /// Combines and deduplicates directory entries across multiple file systems.
470719f7784SNathan Hawes class CombiningDirIterImpl : public llvm::vfs::detail::DirIterImpl {
471719f7784SNathan Hawes   using FileSystemPtr = llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>;
472719f7784SNathan Hawes 
473719f7784SNathan Hawes   /// File systems to check for entries in. Processed in reverse order.
474719f7784SNathan Hawes   SmallVector<FileSystemPtr, 8> FSList;
475719f7784SNathan Hawes   /// The directory iterator for the current filesystem.
476fc51490bSJonas Devlieghere   directory_iterator CurrentDirIter;
477719f7784SNathan Hawes   /// The path of the directory to iterate the entries of.
478719f7784SNathan Hawes   std::string DirPath;
479719f7784SNathan Hawes   /// The set of names already returned as entries.
480fc51490bSJonas Devlieghere   llvm::StringSet<> SeenNames;
481fc51490bSJonas Devlieghere 
482719f7784SNathan Hawes   /// Sets \c CurrentDirIter to an iterator of \c DirPath in the next file
483719f7784SNathan Hawes   /// system in the list, or leaves it as is (at its end position) if we've
484719f7784SNathan Hawes   /// already gone through them all.
485fc51490bSJonas Devlieghere   std::error_code incrementFS() {
486719f7784SNathan Hawes     while (!FSList.empty()) {
487fc51490bSJonas Devlieghere       std::error_code EC;
488719f7784SNathan Hawes       CurrentDirIter = FSList.back()->dir_begin(DirPath, EC);
489719f7784SNathan Hawes       FSList.pop_back();
490fc51490bSJonas Devlieghere       if (EC && EC != errc::no_such_file_or_directory)
491fc51490bSJonas Devlieghere         return EC;
492fc51490bSJonas Devlieghere       if (CurrentDirIter != directory_iterator())
493fc51490bSJonas Devlieghere         break; // found
494fc51490bSJonas Devlieghere     }
495fc51490bSJonas Devlieghere     return {};
496fc51490bSJonas Devlieghere   }
497fc51490bSJonas Devlieghere 
498fc51490bSJonas Devlieghere   std::error_code incrementDirIter(bool IsFirstTime) {
499fc51490bSJonas Devlieghere     assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
500fc51490bSJonas Devlieghere            "incrementing past end");
501fc51490bSJonas Devlieghere     std::error_code EC;
502fc51490bSJonas Devlieghere     if (!IsFirstTime)
503fc51490bSJonas Devlieghere       CurrentDirIter.increment(EC);
504fc51490bSJonas Devlieghere     if (!EC && CurrentDirIter == directory_iterator())
505fc51490bSJonas Devlieghere       EC = incrementFS();
506fc51490bSJonas Devlieghere     return EC;
507fc51490bSJonas Devlieghere   }
508fc51490bSJonas Devlieghere 
509fc51490bSJonas Devlieghere   std::error_code incrementImpl(bool IsFirstTime) {
510fc51490bSJonas Devlieghere     while (true) {
511fc51490bSJonas Devlieghere       std::error_code EC = incrementDirIter(IsFirstTime);
512fc51490bSJonas Devlieghere       if (EC || CurrentDirIter == directory_iterator()) {
513fc51490bSJonas Devlieghere         CurrentEntry = directory_entry();
514fc51490bSJonas Devlieghere         return EC;
515fc51490bSJonas Devlieghere       }
516fc51490bSJonas Devlieghere       CurrentEntry = *CurrentDirIter;
517fc51490bSJonas Devlieghere       StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
518fc51490bSJonas Devlieghere       if (SeenNames.insert(Name).second)
519fc51490bSJonas Devlieghere         return EC; // name not seen before
520fc51490bSJonas Devlieghere     }
521fc51490bSJonas Devlieghere     llvm_unreachable("returned above");
522fc51490bSJonas Devlieghere   }
523fc51490bSJonas Devlieghere 
524fc51490bSJonas Devlieghere public:
525719f7784SNathan Hawes   CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems, std::string Dir,
526fc51490bSJonas Devlieghere                        std::error_code &EC)
527719f7784SNathan Hawes       : FSList(FileSystems.begin(), FileSystems.end()),
528719f7784SNathan Hawes         DirPath(std::move(Dir)) {
529719f7784SNathan Hawes     if (!FSList.empty()) {
530719f7784SNathan Hawes       CurrentDirIter = FSList.back()->dir_begin(DirPath, EC);
531719f7784SNathan Hawes       FSList.pop_back();
532719f7784SNathan Hawes       if (!EC || EC == errc::no_such_file_or_directory)
533719f7784SNathan Hawes         EC = incrementImpl(true);
534719f7784SNathan Hawes     }
535719f7784SNathan Hawes   }
536719f7784SNathan Hawes 
537719f7784SNathan Hawes   CombiningDirIterImpl(directory_iterator FirstIter, FileSystemPtr Fallback,
538719f7784SNathan Hawes                        std::string FallbackDir, std::error_code &EC)
539719f7784SNathan Hawes       : FSList({Fallback}), CurrentDirIter(FirstIter),
540719f7784SNathan Hawes         DirPath(std::move(FallbackDir)) {
541719f7784SNathan Hawes     if (!EC || EC == errc::no_such_file_or_directory)
542fc51490bSJonas Devlieghere       EC = incrementImpl(true);
543fc51490bSJonas Devlieghere   }
544fc51490bSJonas Devlieghere 
545fc51490bSJonas Devlieghere   std::error_code increment() override { return incrementImpl(false); }
546fc51490bSJonas Devlieghere };
547fc51490bSJonas Devlieghere 
548fc51490bSJonas Devlieghere } // namespace
549fc51490bSJonas Devlieghere 
550fc51490bSJonas Devlieghere directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
551fc51490bSJonas Devlieghere                                                 std::error_code &EC) {
552fc51490bSJonas Devlieghere   return directory_iterator(
553719f7784SNathan Hawes       std::make_shared<CombiningDirIterImpl>(FSList, Dir.str(), EC));
554fc51490bSJonas Devlieghere }
555fc51490bSJonas Devlieghere 
556a87b70d1SRichard Trieu void ProxyFileSystem::anchor() {}
557a87b70d1SRichard Trieu 
558fc51490bSJonas Devlieghere namespace llvm {
559fc51490bSJonas Devlieghere namespace vfs {
560fc51490bSJonas Devlieghere 
561fc51490bSJonas Devlieghere namespace detail {
562fc51490bSJonas Devlieghere 
563fc51490bSJonas Devlieghere enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink };
564fc51490bSJonas Devlieghere 
565fc51490bSJonas Devlieghere /// The in memory file system is a tree of Nodes. Every node can either be a
566fc51490bSJonas Devlieghere /// file , hardlink or a directory.
567fc51490bSJonas Devlieghere class InMemoryNode {
568fc51490bSJonas Devlieghere   InMemoryNodeKind Kind;
569fc51490bSJonas Devlieghere   std::string FileName;
570fc51490bSJonas Devlieghere 
571fc51490bSJonas Devlieghere public:
572fc51490bSJonas Devlieghere   InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
573adcd0268SBenjamin Kramer       : Kind(Kind), FileName(std::string(llvm::sys::path::filename(FileName))) {
574adcd0268SBenjamin Kramer   }
575fc51490bSJonas Devlieghere   virtual ~InMemoryNode() = default;
576fc51490bSJonas Devlieghere 
577*9e24d14aSJan Svoboda   /// Return the \p Status for this node. \p RequestedName should be the name
578*9e24d14aSJan Svoboda   /// through which the caller referred to this node. It will override
579*9e24d14aSJan Svoboda   /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
580*9e24d14aSJan Svoboda   virtual Status getStatus(const Twine &RequestedName) const = 0;
581*9e24d14aSJan Svoboda 
582fc51490bSJonas Devlieghere   /// Get the filename of this node (the name without the directory part).
583fc51490bSJonas Devlieghere   StringRef getFileName() const { return FileName; }
584fc51490bSJonas Devlieghere   InMemoryNodeKind getKind() const { return Kind; }
585fc51490bSJonas Devlieghere   virtual std::string toString(unsigned Indent) const = 0;
586fc51490bSJonas Devlieghere };
587fc51490bSJonas Devlieghere 
588fc51490bSJonas Devlieghere class InMemoryFile : public InMemoryNode {
589fc51490bSJonas Devlieghere   Status Stat;
590fc51490bSJonas Devlieghere   std::unique_ptr<llvm::MemoryBuffer> Buffer;
591fc51490bSJonas Devlieghere 
592fc51490bSJonas Devlieghere public:
593fc51490bSJonas Devlieghere   InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
594fc51490bSJonas Devlieghere       : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
595fc51490bSJonas Devlieghere         Buffer(std::move(Buffer)) {}
596fc51490bSJonas Devlieghere 
597*9e24d14aSJan Svoboda   Status getStatus(const Twine &RequestedName) const override {
598fc51490bSJonas Devlieghere     return Status::copyWithNewName(Stat, RequestedName);
599fc51490bSJonas Devlieghere   }
600fc51490bSJonas Devlieghere   llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
601fc51490bSJonas Devlieghere 
602fc51490bSJonas Devlieghere   std::string toString(unsigned Indent) const override {
603fc51490bSJonas Devlieghere     return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
604fc51490bSJonas Devlieghere   }
605fc51490bSJonas Devlieghere 
606fc51490bSJonas Devlieghere   static bool classof(const InMemoryNode *N) {
607fc51490bSJonas Devlieghere     return N->getKind() == IME_File;
608fc51490bSJonas Devlieghere   }
609fc51490bSJonas Devlieghere };
610fc51490bSJonas Devlieghere 
611fc51490bSJonas Devlieghere namespace {
612fc51490bSJonas Devlieghere 
613fc51490bSJonas Devlieghere class InMemoryHardLink : public InMemoryNode {
614fc51490bSJonas Devlieghere   const InMemoryFile &ResolvedFile;
615fc51490bSJonas Devlieghere 
616fc51490bSJonas Devlieghere public:
617fc51490bSJonas Devlieghere   InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
618fc51490bSJonas Devlieghere       : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
619fc51490bSJonas Devlieghere   const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
620fc51490bSJonas Devlieghere 
621*9e24d14aSJan Svoboda   Status getStatus(const Twine &RequestedName) const override {
622*9e24d14aSJan Svoboda     return ResolvedFile.getStatus(RequestedName);
623*9e24d14aSJan Svoboda   }
624*9e24d14aSJan Svoboda 
625fc51490bSJonas Devlieghere   std::string toString(unsigned Indent) const override {
626fc51490bSJonas Devlieghere     return std::string(Indent, ' ') + "HardLink to -> " +
627fc51490bSJonas Devlieghere            ResolvedFile.toString(0);
628fc51490bSJonas Devlieghere   }
629fc51490bSJonas Devlieghere 
630fc51490bSJonas Devlieghere   static bool classof(const InMemoryNode *N) {
631fc51490bSJonas Devlieghere     return N->getKind() == IME_HardLink;
632fc51490bSJonas Devlieghere   }
633fc51490bSJonas Devlieghere };
634fc51490bSJonas Devlieghere 
635fc51490bSJonas Devlieghere /// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
636fc51490bSJonas Devlieghere /// \p InMemoryFileAdaptor mimic as much as possible the behavior of
637fc51490bSJonas Devlieghere /// \p RealFile.
638fc51490bSJonas Devlieghere class InMemoryFileAdaptor : public File {
639fc51490bSJonas Devlieghere   const InMemoryFile &Node;
640fc51490bSJonas Devlieghere   /// The name to use when returning a Status for this file.
641fc51490bSJonas Devlieghere   std::string RequestedName;
642fc51490bSJonas Devlieghere 
643fc51490bSJonas Devlieghere public:
644fc51490bSJonas Devlieghere   explicit InMemoryFileAdaptor(const InMemoryFile &Node,
645fc51490bSJonas Devlieghere                                std::string RequestedName)
646fc51490bSJonas Devlieghere       : Node(Node), RequestedName(std::move(RequestedName)) {}
647fc51490bSJonas Devlieghere 
648fc51490bSJonas Devlieghere   llvm::ErrorOr<Status> status() override {
649fc51490bSJonas Devlieghere     return Node.getStatus(RequestedName);
650fc51490bSJonas Devlieghere   }
651fc51490bSJonas Devlieghere 
652fc51490bSJonas Devlieghere   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
653fc51490bSJonas Devlieghere   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
654fc51490bSJonas Devlieghere             bool IsVolatile) override {
655fc51490bSJonas Devlieghere     llvm::MemoryBuffer *Buf = Node.getBuffer();
656fc51490bSJonas Devlieghere     return llvm::MemoryBuffer::getMemBuffer(
657fc51490bSJonas Devlieghere         Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
658fc51490bSJonas Devlieghere   }
659fc51490bSJonas Devlieghere 
660fc51490bSJonas Devlieghere   std::error_code close() override { return {}; }
66186e2af80SKeith Smiley 
66286e2af80SKeith Smiley   void setPath(const Twine &Path) override { RequestedName = Path.str(); }
663fc51490bSJonas Devlieghere };
664fc51490bSJonas Devlieghere } // namespace
665fc51490bSJonas Devlieghere 
666fc51490bSJonas Devlieghere class InMemoryDirectory : public InMemoryNode {
667fc51490bSJonas Devlieghere   Status Stat;
668fc51490bSJonas Devlieghere   llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries;
669fc51490bSJonas Devlieghere 
670fc51490bSJonas Devlieghere public:
671fc51490bSJonas Devlieghere   InMemoryDirectory(Status Stat)
672fc51490bSJonas Devlieghere       : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
673fc51490bSJonas Devlieghere 
674fc51490bSJonas Devlieghere   /// Return the \p Status for this node. \p RequestedName should be the name
675fc51490bSJonas Devlieghere   /// through which the caller referred to this node. It will override
676fc51490bSJonas Devlieghere   /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
677*9e24d14aSJan Svoboda   Status getStatus(const Twine &RequestedName) const override {
678fc51490bSJonas Devlieghere     return Status::copyWithNewName(Stat, RequestedName);
679fc51490bSJonas Devlieghere   }
68022555bafSSam McCall 
68122555bafSSam McCall   UniqueID getUniqueID() const { return Stat.getUniqueID(); }
68222555bafSSam McCall 
683fc51490bSJonas Devlieghere   InMemoryNode *getChild(StringRef Name) {
684fc51490bSJonas Devlieghere     auto I = Entries.find(Name);
685fc51490bSJonas Devlieghere     if (I != Entries.end())
686fc51490bSJonas Devlieghere       return I->second.get();
687fc51490bSJonas Devlieghere     return nullptr;
688fc51490bSJonas Devlieghere   }
689fc51490bSJonas Devlieghere 
690fc51490bSJonas Devlieghere   InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
691fc51490bSJonas Devlieghere     return Entries.insert(make_pair(Name, std::move(Child)))
692fc51490bSJonas Devlieghere         .first->second.get();
693fc51490bSJonas Devlieghere   }
694fc51490bSJonas Devlieghere 
695fc51490bSJonas Devlieghere   using const_iterator = decltype(Entries)::const_iterator;
696fc51490bSJonas Devlieghere 
697fc51490bSJonas Devlieghere   const_iterator begin() const { return Entries.begin(); }
698fc51490bSJonas Devlieghere   const_iterator end() const { return Entries.end(); }
699fc51490bSJonas Devlieghere 
700fc51490bSJonas Devlieghere   std::string toString(unsigned Indent) const override {
701fc51490bSJonas Devlieghere     std::string Result =
702fc51490bSJonas Devlieghere         (std::string(Indent, ' ') + Stat.getName() + "\n").str();
703fc51490bSJonas Devlieghere     for (const auto &Entry : Entries)
704fc51490bSJonas Devlieghere       Result += Entry.second->toString(Indent + 2);
705fc51490bSJonas Devlieghere     return Result;
706fc51490bSJonas Devlieghere   }
707fc51490bSJonas Devlieghere 
708fc51490bSJonas Devlieghere   static bool classof(const InMemoryNode *N) {
709fc51490bSJonas Devlieghere     return N->getKind() == IME_Directory;
710fc51490bSJonas Devlieghere   }
711fc51490bSJonas Devlieghere };
712fc51490bSJonas Devlieghere 
713fc51490bSJonas Devlieghere } // namespace detail
714fc51490bSJonas Devlieghere 
71522555bafSSam McCall // The UniqueID of in-memory files is derived from path and content.
71622555bafSSam McCall // This avoids difficulties in creating exactly equivalent in-memory FSes,
71722555bafSSam McCall // as often needed in multithreaded programs.
71822555bafSSam McCall static sys::fs::UniqueID getUniqueID(hash_code Hash) {
71922555bafSSam McCall   return sys::fs::UniqueID(std::numeric_limits<uint64_t>::max(),
72022555bafSSam McCall                            uint64_t(size_t(Hash)));
72122555bafSSam McCall }
72222555bafSSam McCall static sys::fs::UniqueID getFileID(sys::fs::UniqueID Parent,
72322555bafSSam McCall                                    llvm::StringRef Name,
72422555bafSSam McCall                                    llvm::StringRef Contents) {
72522555bafSSam McCall   return getUniqueID(llvm::hash_combine(Parent.getFile(), Name, Contents));
72622555bafSSam McCall }
72722555bafSSam McCall static sys::fs::UniqueID getDirectoryID(sys::fs::UniqueID Parent,
72822555bafSSam McCall                                         llvm::StringRef Name) {
72922555bafSSam McCall   return getUniqueID(llvm::hash_combine(Parent.getFile(), Name));
73022555bafSSam McCall }
73122555bafSSam McCall 
732fc51490bSJonas Devlieghere InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
733fc51490bSJonas Devlieghere     : Root(new detail::InMemoryDirectory(
73422555bafSSam McCall           Status("", getDirectoryID(llvm::sys::fs::UniqueID(), ""),
73522555bafSSam McCall                  llvm::sys::TimePoint<>(), 0, 0, 0,
73622555bafSSam McCall                  llvm::sys::fs::file_type::directory_file,
737fc51490bSJonas Devlieghere                  llvm::sys::fs::perms::all_all))),
738fc51490bSJonas Devlieghere       UseNormalizedPaths(UseNormalizedPaths) {}
739fc51490bSJonas Devlieghere 
740fc51490bSJonas Devlieghere InMemoryFileSystem::~InMemoryFileSystem() = default;
741fc51490bSJonas Devlieghere 
742fc51490bSJonas Devlieghere std::string InMemoryFileSystem::toString() const {
743fc51490bSJonas Devlieghere   return Root->toString(/*Indent=*/0);
744fc51490bSJonas Devlieghere }
745fc51490bSJonas Devlieghere 
746fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
747fc51490bSJonas Devlieghere                                  std::unique_ptr<llvm::MemoryBuffer> Buffer,
748fc51490bSJonas Devlieghere                                  Optional<uint32_t> User,
749fc51490bSJonas Devlieghere                                  Optional<uint32_t> Group,
750fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::file_type> Type,
751fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::perms> Perms,
752fc51490bSJonas Devlieghere                                  const detail::InMemoryFile *HardLinkTarget) {
753fc51490bSJonas Devlieghere   SmallString<128> Path;
754fc51490bSJonas Devlieghere   P.toVector(Path);
755fc51490bSJonas Devlieghere 
756fc51490bSJonas Devlieghere   // Fix up relative paths. This just prepends the current working directory.
757fc51490bSJonas Devlieghere   std::error_code EC = makeAbsolute(Path);
758fc51490bSJonas Devlieghere   assert(!EC);
759fc51490bSJonas Devlieghere   (void)EC;
760fc51490bSJonas Devlieghere 
761fc51490bSJonas Devlieghere   if (useNormalizedPaths())
762fc51490bSJonas Devlieghere     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
763fc51490bSJonas Devlieghere 
764fc51490bSJonas Devlieghere   if (Path.empty())
765fc51490bSJonas Devlieghere     return false;
766fc51490bSJonas Devlieghere 
767fc51490bSJonas Devlieghere   detail::InMemoryDirectory *Dir = Root.get();
768fc51490bSJonas Devlieghere   auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
769fc51490bSJonas Devlieghere   const auto ResolvedUser = User.getValueOr(0);
770fc51490bSJonas Devlieghere   const auto ResolvedGroup = Group.getValueOr(0);
771fc51490bSJonas Devlieghere   const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
772fc51490bSJonas Devlieghere   const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
773fc51490bSJonas Devlieghere   assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer");
774fc51490bSJonas Devlieghere   // Any intermediate directories we create should be accessible by
775fc51490bSJonas Devlieghere   // the owner, even if Perms says otherwise for the final path.
776fc51490bSJonas Devlieghere   const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
777fc51490bSJonas Devlieghere   while (true) {
778fc51490bSJonas Devlieghere     StringRef Name = *I;
779fc51490bSJonas Devlieghere     detail::InMemoryNode *Node = Dir->getChild(Name);
780fc51490bSJonas Devlieghere     ++I;
781fc51490bSJonas Devlieghere     if (!Node) {
782fc51490bSJonas Devlieghere       if (I == E) {
783fc51490bSJonas Devlieghere         // End of the path.
784fc51490bSJonas Devlieghere         std::unique_ptr<detail::InMemoryNode> Child;
785fc51490bSJonas Devlieghere         if (HardLinkTarget)
786fc51490bSJonas Devlieghere           Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget));
787fc51490bSJonas Devlieghere         else {
788fc51490bSJonas Devlieghere           // Create a new file or directory.
78922555bafSSam McCall           Status Stat(
79022555bafSSam McCall               P.str(),
79122555bafSSam McCall               (ResolvedType == sys::fs::file_type::directory_file)
79222555bafSSam McCall                   ? getDirectoryID(Dir->getUniqueID(), Name)
79322555bafSSam McCall                   : getFileID(Dir->getUniqueID(), Name, Buffer->getBuffer()),
794fc51490bSJonas Devlieghere               llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
795fc51490bSJonas Devlieghere               ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
796fc51490bSJonas Devlieghere               ResolvedPerms);
797fc51490bSJonas Devlieghere           if (ResolvedType == sys::fs::file_type::directory_file) {
798fc51490bSJonas Devlieghere             Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
799fc51490bSJonas Devlieghere           } else {
800fc51490bSJonas Devlieghere             Child.reset(
801fc51490bSJonas Devlieghere                 new detail::InMemoryFile(std::move(Stat), std::move(Buffer)));
802fc51490bSJonas Devlieghere           }
803fc51490bSJonas Devlieghere         }
804fc51490bSJonas Devlieghere         Dir->addChild(Name, std::move(Child));
805fc51490bSJonas Devlieghere         return true;
806fc51490bSJonas Devlieghere       }
807fc51490bSJonas Devlieghere 
808fc51490bSJonas Devlieghere       // Create a new directory. Use the path up to here.
809fc51490bSJonas Devlieghere       Status Stat(
810fc51490bSJonas Devlieghere           StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
81122555bafSSam McCall           getDirectoryID(Dir->getUniqueID(), Name),
81222555bafSSam McCall           llvm::sys::toTimePoint(ModificationTime), ResolvedUser, ResolvedGroup,
81322555bafSSam McCall           0, sys::fs::file_type::directory_file, NewDirectoryPerms);
814fc51490bSJonas Devlieghere       Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
8150eaee545SJonas Devlieghere           Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
816fc51490bSJonas Devlieghere       continue;
817fc51490bSJonas Devlieghere     }
818fc51490bSJonas Devlieghere 
819fc51490bSJonas Devlieghere     if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
820fc51490bSJonas Devlieghere       Dir = NewDir;
821fc51490bSJonas Devlieghere     } else {
822fc51490bSJonas Devlieghere       assert((isa<detail::InMemoryFile>(Node) ||
823fc51490bSJonas Devlieghere               isa<detail::InMemoryHardLink>(Node)) &&
824fc51490bSJonas Devlieghere              "Must be either file, hardlink or directory!");
825fc51490bSJonas Devlieghere 
826fc51490bSJonas Devlieghere       // Trying to insert a directory in place of a file.
827fc51490bSJonas Devlieghere       if (I != E)
828fc51490bSJonas Devlieghere         return false;
829fc51490bSJonas Devlieghere 
830fc51490bSJonas Devlieghere       // Return false only if the new file is different from the existing one.
831fc51490bSJonas Devlieghere       if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
832fc51490bSJonas Devlieghere         return Link->getResolvedFile().getBuffer()->getBuffer() ==
833fc51490bSJonas Devlieghere                Buffer->getBuffer();
834fc51490bSJonas Devlieghere       }
835fc51490bSJonas Devlieghere       return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
836fc51490bSJonas Devlieghere              Buffer->getBuffer();
837fc51490bSJonas Devlieghere     }
838fc51490bSJonas Devlieghere   }
839fc51490bSJonas Devlieghere }
840fc51490bSJonas Devlieghere 
841fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
842fc51490bSJonas Devlieghere                                  std::unique_ptr<llvm::MemoryBuffer> Buffer,
843fc51490bSJonas Devlieghere                                  Optional<uint32_t> User,
844fc51490bSJonas Devlieghere                                  Optional<uint32_t> Group,
845fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::file_type> Type,
846fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::perms> Perms) {
847fc51490bSJonas Devlieghere   return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
848fc51490bSJonas Devlieghere                  Perms, /*HardLinkTarget=*/nullptr);
849fc51490bSJonas Devlieghere }
850fc51490bSJonas Devlieghere 
851fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
852e763e032SDuncan P. N. Exon Smith                                       const llvm::MemoryBufferRef &Buffer,
853fc51490bSJonas Devlieghere                                       Optional<uint32_t> User,
854fc51490bSJonas Devlieghere                                       Optional<uint32_t> Group,
855fc51490bSJonas Devlieghere                                       Optional<llvm::sys::fs::file_type> Type,
856fc51490bSJonas Devlieghere                                       Optional<llvm::sys::fs::perms> Perms) {
857e763e032SDuncan P. N. Exon Smith   return addFile(P, ModificationTime, llvm::MemoryBuffer::getMemBuffer(Buffer),
858fc51490bSJonas Devlieghere                  std::move(User), std::move(Group), std::move(Type),
859fc51490bSJonas Devlieghere                  std::move(Perms));
860fc51490bSJonas Devlieghere }
861fc51490bSJonas Devlieghere 
862fc51490bSJonas Devlieghere static ErrorOr<const detail::InMemoryNode *>
863fc51490bSJonas Devlieghere lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
864fc51490bSJonas Devlieghere                    const Twine &P) {
865fc51490bSJonas Devlieghere   SmallString<128> Path;
866fc51490bSJonas Devlieghere   P.toVector(Path);
867fc51490bSJonas Devlieghere 
868fc51490bSJonas Devlieghere   // Fix up relative paths. This just prepends the current working directory.
869fc51490bSJonas Devlieghere   std::error_code EC = FS.makeAbsolute(Path);
870fc51490bSJonas Devlieghere   assert(!EC);
871fc51490bSJonas Devlieghere   (void)EC;
872fc51490bSJonas Devlieghere 
873fc51490bSJonas Devlieghere   if (FS.useNormalizedPaths())
874fc51490bSJonas Devlieghere     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
875fc51490bSJonas Devlieghere 
876fc51490bSJonas Devlieghere   if (Path.empty())
877fc51490bSJonas Devlieghere     return Dir;
878fc51490bSJonas Devlieghere 
879fc51490bSJonas Devlieghere   auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
880fc51490bSJonas Devlieghere   while (true) {
881fc51490bSJonas Devlieghere     detail::InMemoryNode *Node = Dir->getChild(*I);
882fc51490bSJonas Devlieghere     ++I;
883fc51490bSJonas Devlieghere     if (!Node)
884fc51490bSJonas Devlieghere       return errc::no_such_file_or_directory;
885fc51490bSJonas Devlieghere 
886fc51490bSJonas Devlieghere     // Return the file if it's at the end of the path.
887fc51490bSJonas Devlieghere     if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
888fc51490bSJonas Devlieghere       if (I == E)
889fc51490bSJonas Devlieghere         return File;
890fc51490bSJonas Devlieghere       return errc::no_such_file_or_directory;
891fc51490bSJonas Devlieghere     }
892fc51490bSJonas Devlieghere 
893fc51490bSJonas Devlieghere     // If Node is HardLink then return the resolved file.
894fc51490bSJonas Devlieghere     if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
895fc51490bSJonas Devlieghere       if (I == E)
896fc51490bSJonas Devlieghere         return &File->getResolvedFile();
897fc51490bSJonas Devlieghere       return errc::no_such_file_or_directory;
898fc51490bSJonas Devlieghere     }
899fc51490bSJonas Devlieghere     // Traverse directories.
900fc51490bSJonas Devlieghere     Dir = cast<detail::InMemoryDirectory>(Node);
901fc51490bSJonas Devlieghere     if (I == E)
902fc51490bSJonas Devlieghere       return Dir;
903fc51490bSJonas Devlieghere   }
904fc51490bSJonas Devlieghere }
905fc51490bSJonas Devlieghere 
906fc51490bSJonas Devlieghere bool InMemoryFileSystem::addHardLink(const Twine &FromPath,
907fc51490bSJonas Devlieghere                                      const Twine &ToPath) {
908fc51490bSJonas Devlieghere   auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath);
909fc51490bSJonas Devlieghere   auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath);
910fc51490bSJonas Devlieghere   // FromPath must not have been added before. ToPath must have been added
911fc51490bSJonas Devlieghere   // before. Resolved ToPath must be a File.
912fc51490bSJonas Devlieghere   if (!ToNode || FromNode || !isa<detail::InMemoryFile>(*ToNode))
913fc51490bSJonas Devlieghere     return false;
914fc51490bSJonas Devlieghere   return this->addFile(FromPath, 0, nullptr, None, None, None, None,
915fc51490bSJonas Devlieghere                        cast<detail::InMemoryFile>(*ToNode));
916fc51490bSJonas Devlieghere }
917fc51490bSJonas Devlieghere 
918fc51490bSJonas Devlieghere llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
919fc51490bSJonas Devlieghere   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
920fc51490bSJonas Devlieghere   if (Node)
921*9e24d14aSJan Svoboda     return (*Node)->getStatus(Path);
922fc51490bSJonas Devlieghere   return Node.getError();
923fc51490bSJonas Devlieghere }
924fc51490bSJonas Devlieghere 
925fc51490bSJonas Devlieghere llvm::ErrorOr<std::unique_ptr<File>>
926fc51490bSJonas Devlieghere InMemoryFileSystem::openFileForRead(const Twine &Path) {
927fc51490bSJonas Devlieghere   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
928fc51490bSJonas Devlieghere   if (!Node)
929fc51490bSJonas Devlieghere     return Node.getError();
930fc51490bSJonas Devlieghere 
931fc51490bSJonas Devlieghere   // When we have a file provide a heap-allocated wrapper for the memory buffer
932fc51490bSJonas Devlieghere   // to match the ownership semantics for File.
933fc51490bSJonas Devlieghere   if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
934fc51490bSJonas Devlieghere     return std::unique_ptr<File>(
935fc51490bSJonas Devlieghere         new detail::InMemoryFileAdaptor(*F, Path.str()));
936fc51490bSJonas Devlieghere 
937fc51490bSJonas Devlieghere   // FIXME: errc::not_a_file?
938fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::invalid_argument);
939fc51490bSJonas Devlieghere }
940fc51490bSJonas Devlieghere 
941fc51490bSJonas Devlieghere namespace {
942fc51490bSJonas Devlieghere 
943fc51490bSJonas Devlieghere /// Adaptor from InMemoryDir::iterator to directory_iterator.
944fc51490bSJonas Devlieghere class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl {
945fc51490bSJonas Devlieghere   detail::InMemoryDirectory::const_iterator I;
946fc51490bSJonas Devlieghere   detail::InMemoryDirectory::const_iterator E;
947fc51490bSJonas Devlieghere   std::string RequestedDirName;
948fc51490bSJonas Devlieghere 
949fc51490bSJonas Devlieghere   void setCurrentEntry() {
950fc51490bSJonas Devlieghere     if (I != E) {
951fc51490bSJonas Devlieghere       SmallString<256> Path(RequestedDirName);
952fc51490bSJonas Devlieghere       llvm::sys::path::append(Path, I->second->getFileName());
953e1000f1dSSimon Pilgrim       sys::fs::file_type Type = sys::fs::file_type::type_unknown;
954fc51490bSJonas Devlieghere       switch (I->second->getKind()) {
955fc51490bSJonas Devlieghere       case detail::IME_File:
956fc51490bSJonas Devlieghere       case detail::IME_HardLink:
957fc51490bSJonas Devlieghere         Type = sys::fs::file_type::regular_file;
958fc51490bSJonas Devlieghere         break;
959fc51490bSJonas Devlieghere       case detail::IME_Directory:
960fc51490bSJonas Devlieghere         Type = sys::fs::file_type::directory_file;
961fc51490bSJonas Devlieghere         break;
962fc51490bSJonas Devlieghere       }
963adcd0268SBenjamin Kramer       CurrentEntry = directory_entry(std::string(Path.str()), Type);
964fc51490bSJonas Devlieghere     } else {
965fc51490bSJonas Devlieghere       // When we're at the end, make CurrentEntry invalid and DirIterImpl will
966fc51490bSJonas Devlieghere       // do the rest.
967fc51490bSJonas Devlieghere       CurrentEntry = directory_entry();
968fc51490bSJonas Devlieghere     }
969fc51490bSJonas Devlieghere   }
970fc51490bSJonas Devlieghere 
971fc51490bSJonas Devlieghere public:
972fc51490bSJonas Devlieghere   InMemoryDirIterator() = default;
973fc51490bSJonas Devlieghere 
974fc51490bSJonas Devlieghere   explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir,
975fc51490bSJonas Devlieghere                                std::string RequestedDirName)
976fc51490bSJonas Devlieghere       : I(Dir.begin()), E(Dir.end()),
977fc51490bSJonas Devlieghere         RequestedDirName(std::move(RequestedDirName)) {
978fc51490bSJonas Devlieghere     setCurrentEntry();
979fc51490bSJonas Devlieghere   }
980fc51490bSJonas Devlieghere 
981fc51490bSJonas Devlieghere   std::error_code increment() override {
982fc51490bSJonas Devlieghere     ++I;
983fc51490bSJonas Devlieghere     setCurrentEntry();
984fc51490bSJonas Devlieghere     return {};
985fc51490bSJonas Devlieghere   }
986fc51490bSJonas Devlieghere };
987fc51490bSJonas Devlieghere 
988fc51490bSJonas Devlieghere } // namespace
989fc51490bSJonas Devlieghere 
990fc51490bSJonas Devlieghere directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
991fc51490bSJonas Devlieghere                                                  std::error_code &EC) {
992fc51490bSJonas Devlieghere   auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
993fc51490bSJonas Devlieghere   if (!Node) {
994fc51490bSJonas Devlieghere     EC = Node.getError();
995fc51490bSJonas Devlieghere     return directory_iterator(std::make_shared<InMemoryDirIterator>());
996fc51490bSJonas Devlieghere   }
997fc51490bSJonas Devlieghere 
998fc51490bSJonas Devlieghere   if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
999fc51490bSJonas Devlieghere     return directory_iterator(
1000fc51490bSJonas Devlieghere         std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
1001fc51490bSJonas Devlieghere 
1002fc51490bSJonas Devlieghere   EC = make_error_code(llvm::errc::not_a_directory);
1003fc51490bSJonas Devlieghere   return directory_iterator(std::make_shared<InMemoryDirIterator>());
1004fc51490bSJonas Devlieghere }
1005fc51490bSJonas Devlieghere 
1006fc51490bSJonas Devlieghere std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
1007fc51490bSJonas Devlieghere   SmallString<128> Path;
1008fc51490bSJonas Devlieghere   P.toVector(Path);
1009fc51490bSJonas Devlieghere 
1010fc51490bSJonas Devlieghere   // Fix up relative paths. This just prepends the current working directory.
1011fc51490bSJonas Devlieghere   std::error_code EC = makeAbsolute(Path);
1012fc51490bSJonas Devlieghere   assert(!EC);
1013fc51490bSJonas Devlieghere   (void)EC;
1014fc51490bSJonas Devlieghere 
1015fc51490bSJonas Devlieghere   if (useNormalizedPaths())
1016fc51490bSJonas Devlieghere     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1017fc51490bSJonas Devlieghere 
1018fc51490bSJonas Devlieghere   if (!Path.empty())
1019adcd0268SBenjamin Kramer     WorkingDirectory = std::string(Path.str());
1020fc51490bSJonas Devlieghere   return {};
1021fc51490bSJonas Devlieghere }
1022fc51490bSJonas Devlieghere 
102399538e89SSam McCall std::error_code
102499538e89SSam McCall InMemoryFileSystem::getRealPath(const Twine &Path,
102599538e89SSam McCall                                 SmallVectorImpl<char> &Output) const {
1026fc51490bSJonas Devlieghere   auto CWD = getCurrentWorkingDirectory();
1027fc51490bSJonas Devlieghere   if (!CWD || CWD->empty())
1028fc51490bSJonas Devlieghere     return errc::operation_not_permitted;
1029fc51490bSJonas Devlieghere   Path.toVector(Output);
1030fc51490bSJonas Devlieghere   if (auto EC = makeAbsolute(Output))
1031fc51490bSJonas Devlieghere     return EC;
1032fc51490bSJonas Devlieghere   llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
1033fc51490bSJonas Devlieghere   return {};
1034fc51490bSJonas Devlieghere }
1035fc51490bSJonas Devlieghere 
1036cbb5c868SJonas Devlieghere std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
1037cbb5c868SJonas Devlieghere   Result = false;
1038cbb5c868SJonas Devlieghere   return {};
1039cbb5c868SJonas Devlieghere }
1040cbb5c868SJonas Devlieghere 
1041fc51490bSJonas Devlieghere } // namespace vfs
1042fc51490bSJonas Devlieghere } // namespace llvm
1043fc51490bSJonas Devlieghere 
1044fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
1045fc51490bSJonas Devlieghere // RedirectingFileSystem implementation
1046fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
1047fc51490bSJonas Devlieghere 
1048da45bd23SAdrian McCarthy namespace {
1049da45bd23SAdrian McCarthy 
1050ecb00a77SNathan Hawes static llvm::sys::path::Style getExistingStyle(llvm::StringRef Path) {
1051ecb00a77SNathan Hawes   // Detect the path style in use by checking the first separator.
1052da45bd23SAdrian McCarthy   llvm::sys::path::Style style = llvm::sys::path::Style::native;
1053da45bd23SAdrian McCarthy   const size_t n = Path.find_first_of("/\\");
105446ec93a4SMartin Storsjö   // Can't distinguish between posix and windows_slash here.
1055da45bd23SAdrian McCarthy   if (n != static_cast<size_t>(-1))
1056da45bd23SAdrian McCarthy     style = (Path[n] == '/') ? llvm::sys::path::Style::posix
105746ec93a4SMartin Storsjö                              : llvm::sys::path::Style::windows_backslash;
1058ecb00a77SNathan Hawes   return style;
1059ecb00a77SNathan Hawes }
1060ecb00a77SNathan Hawes 
1061ecb00a77SNathan Hawes /// Removes leading "./" as well as path components like ".." and ".".
1062ecb00a77SNathan Hawes static llvm::SmallString<256> canonicalize(llvm::StringRef Path) {
1063ecb00a77SNathan Hawes   // First detect the path style in use by checking the first separator.
1064ecb00a77SNathan Hawes   llvm::sys::path::Style style = getExistingStyle(Path);
1065da45bd23SAdrian McCarthy 
1066da45bd23SAdrian McCarthy   // Now remove the dots.  Explicitly specifying the path style prevents the
1067da45bd23SAdrian McCarthy   // direction of the slashes from changing.
1068da45bd23SAdrian McCarthy   llvm::SmallString<256> result =
1069da45bd23SAdrian McCarthy       llvm::sys::path::remove_leading_dotslash(Path, style);
1070da45bd23SAdrian McCarthy   llvm::sys::path::remove_dots(result, /*remove_dot_dot=*/true, style);
1071da45bd23SAdrian McCarthy   return result;
1072da45bd23SAdrian McCarthy }
1073da45bd23SAdrian McCarthy 
1074da45bd23SAdrian McCarthy } // anonymous namespace
1075da45bd23SAdrian McCarthy 
1076da45bd23SAdrian McCarthy 
107721703543SJonas Devlieghere RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
107821703543SJonas Devlieghere     : ExternalFS(std::move(FS)) {
107921703543SJonas Devlieghere   if (ExternalFS)
108021703543SJonas Devlieghere     if (auto ExternalWorkingDirectory =
108121703543SJonas Devlieghere             ExternalFS->getCurrentWorkingDirectory()) {
108221703543SJonas Devlieghere       WorkingDirectory = *ExternalWorkingDirectory;
108321703543SJonas Devlieghere     }
108421703543SJonas Devlieghere }
108521703543SJonas Devlieghere 
1086719f7784SNathan Hawes /// Directory iterator implementation for \c RedirectingFileSystem's
1087719f7784SNathan Hawes /// directory entries.
1088719f7784SNathan Hawes class llvm::vfs::RedirectingFSDirIterImpl
10891a0ce65aSJonas Devlieghere     : public llvm::vfs::detail::DirIterImpl {
1090fc51490bSJonas Devlieghere   std::string Dir;
1091719f7784SNathan Hawes   RedirectingFileSystem::DirectoryEntry::iterator Current, End;
1092fc51490bSJonas Devlieghere 
1093719f7784SNathan Hawes   std::error_code incrementImpl(bool IsFirstTime) {
1094719f7784SNathan Hawes     assert((IsFirstTime || Current != End) && "cannot iterate past end");
1095719f7784SNathan Hawes     if (!IsFirstTime)
1096719f7784SNathan Hawes       ++Current;
1097719f7784SNathan Hawes     if (Current != End) {
1098719f7784SNathan Hawes       SmallString<128> PathStr(Dir);
1099719f7784SNathan Hawes       llvm::sys::path::append(PathStr, (*Current)->getName());
1100719f7784SNathan Hawes       sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1101719f7784SNathan Hawes       switch ((*Current)->getKind()) {
1102719f7784SNathan Hawes       case RedirectingFileSystem::EK_Directory:
1103ecb00a77SNathan Hawes         LLVM_FALLTHROUGH;
1104ecb00a77SNathan Hawes       case RedirectingFileSystem::EK_DirectoryRemap:
1105719f7784SNathan Hawes         Type = sys::fs::file_type::directory_file;
1106719f7784SNathan Hawes         break;
1107719f7784SNathan Hawes       case RedirectingFileSystem::EK_File:
1108719f7784SNathan Hawes         Type = sys::fs::file_type::regular_file;
1109719f7784SNathan Hawes         break;
1110719f7784SNathan Hawes       }
1111719f7784SNathan Hawes       CurrentEntry = directory_entry(std::string(PathStr.str()), Type);
1112719f7784SNathan Hawes     } else {
1113719f7784SNathan Hawes       CurrentEntry = directory_entry();
1114719f7784SNathan Hawes     }
1115719f7784SNathan Hawes     return {};
1116719f7784SNathan Hawes   };
1117fc51490bSJonas Devlieghere 
1118fc51490bSJonas Devlieghere public:
1119719f7784SNathan Hawes   RedirectingFSDirIterImpl(
1120719f7784SNathan Hawes       const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin,
1121719f7784SNathan Hawes       RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC)
1122719f7784SNathan Hawes       : Dir(Path.str()), Current(Begin), End(End) {
1123719f7784SNathan Hawes     EC = incrementImpl(/*IsFirstTime=*/true);
1124719f7784SNathan Hawes   }
1125fc51490bSJonas Devlieghere 
1126719f7784SNathan Hawes   std::error_code increment() override {
1127719f7784SNathan Hawes     return incrementImpl(/*IsFirstTime=*/false);
1128719f7784SNathan Hawes   }
1129fc51490bSJonas Devlieghere };
1130fc51490bSJonas Devlieghere 
11319b8b1645SBenjamin Kramer namespace {
1132ecb00a77SNathan Hawes /// Directory iterator implementation for \c RedirectingFileSystem's
1133ecb00a77SNathan Hawes /// directory remap entries that maps the paths reported by the external
1134ecb00a77SNathan Hawes /// file system's directory iterator back to the virtual directory's path.
1135ecb00a77SNathan Hawes class RedirectingFSDirRemapIterImpl : public llvm::vfs::detail::DirIterImpl {
1136ecb00a77SNathan Hawes   std::string Dir;
1137ecb00a77SNathan Hawes   llvm::sys::path::Style DirStyle;
1138ecb00a77SNathan Hawes   llvm::vfs::directory_iterator ExternalIter;
1139ecb00a77SNathan Hawes 
1140ecb00a77SNathan Hawes public:
1141ecb00a77SNathan Hawes   RedirectingFSDirRemapIterImpl(std::string DirPath,
1142ecb00a77SNathan Hawes                                 llvm::vfs::directory_iterator ExtIter)
1143ecb00a77SNathan Hawes       : Dir(std::move(DirPath)), DirStyle(getExistingStyle(Dir)),
1144ecb00a77SNathan Hawes         ExternalIter(ExtIter) {
1145ecb00a77SNathan Hawes     if (ExternalIter != llvm::vfs::directory_iterator())
1146ecb00a77SNathan Hawes       setCurrentEntry();
1147ecb00a77SNathan Hawes   }
1148ecb00a77SNathan Hawes 
1149ecb00a77SNathan Hawes   void setCurrentEntry() {
1150ecb00a77SNathan Hawes     StringRef ExternalPath = ExternalIter->path();
1151ecb00a77SNathan Hawes     llvm::sys::path::Style ExternalStyle = getExistingStyle(ExternalPath);
1152ecb00a77SNathan Hawes     StringRef File = llvm::sys::path::filename(ExternalPath, ExternalStyle);
1153ecb00a77SNathan Hawes 
1154ecb00a77SNathan Hawes     SmallString<128> NewPath(Dir);
1155ecb00a77SNathan Hawes     llvm::sys::path::append(NewPath, DirStyle, File);
1156ecb00a77SNathan Hawes 
1157ecb00a77SNathan Hawes     CurrentEntry = directory_entry(std::string(NewPath), ExternalIter->type());
1158ecb00a77SNathan Hawes   }
1159ecb00a77SNathan Hawes 
1160ecb00a77SNathan Hawes   std::error_code increment() override {
1161ecb00a77SNathan Hawes     std::error_code EC;
1162ecb00a77SNathan Hawes     ExternalIter.increment(EC);
1163ecb00a77SNathan Hawes     if (!EC && ExternalIter != llvm::vfs::directory_iterator())
1164ecb00a77SNathan Hawes       setCurrentEntry();
1165ecb00a77SNathan Hawes     else
1166ecb00a77SNathan Hawes       CurrentEntry = directory_entry();
1167ecb00a77SNathan Hawes     return EC;
1168ecb00a77SNathan Hawes   }
1169ecb00a77SNathan Hawes };
11709b8b1645SBenjamin Kramer } // namespace
1171ecb00a77SNathan Hawes 
11721a0ce65aSJonas Devlieghere llvm::ErrorOr<std::string>
11731a0ce65aSJonas Devlieghere RedirectingFileSystem::getCurrentWorkingDirectory() const {
117421703543SJonas Devlieghere   return WorkingDirectory;
1175fc51490bSJonas Devlieghere }
1176fc51490bSJonas Devlieghere 
11771a0ce65aSJonas Devlieghere std::error_code
11781a0ce65aSJonas Devlieghere RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
117921703543SJonas Devlieghere   // Don't change the working directory if the path doesn't exist.
118021703543SJonas Devlieghere   if (!exists(Path))
118121703543SJonas Devlieghere     return errc::no_such_file_or_directory;
118221703543SJonas Devlieghere 
118321703543SJonas Devlieghere   SmallString<128> AbsolutePath;
118421703543SJonas Devlieghere   Path.toVector(AbsolutePath);
118521703543SJonas Devlieghere   if (std::error_code EC = makeAbsolute(AbsolutePath))
118621703543SJonas Devlieghere     return EC;
1187adcd0268SBenjamin Kramer   WorkingDirectory = std::string(AbsolutePath.str());
118821703543SJonas Devlieghere   return {};
1189fc51490bSJonas Devlieghere }
1190fc51490bSJonas Devlieghere 
11910be9ca7cSJonas Devlieghere std::error_code RedirectingFileSystem::isLocal(const Twine &Path_,
11921a0ce65aSJonas Devlieghere                                                bool &Result) {
11930be9ca7cSJonas Devlieghere   SmallString<256> Path;
11940be9ca7cSJonas Devlieghere   Path_.toVector(Path);
11950be9ca7cSJonas Devlieghere 
11960be9ca7cSJonas Devlieghere   if (std::error_code EC = makeCanonical(Path))
11970be9ca7cSJonas Devlieghere     return {};
11980be9ca7cSJonas Devlieghere 
1199cbb5c868SJonas Devlieghere   return ExternalFS->isLocal(Path, Result);
1200cbb5c868SJonas Devlieghere }
1201cbb5c868SJonas Devlieghere 
1202738b5c96SAdrian McCarthy std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
120346ec93a4SMartin Storsjö   // is_absolute(..., Style::windows_*) accepts paths with both slash types.
1204738b5c96SAdrian McCarthy   if (llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::posix) ||
120546ec93a4SMartin Storsjö       llvm::sys::path::is_absolute(Path,
120646ec93a4SMartin Storsjö                                    llvm::sys::path::Style::windows_backslash))
1207738b5c96SAdrian McCarthy     return {};
1208738b5c96SAdrian McCarthy 
1209738b5c96SAdrian McCarthy   auto WorkingDir = getCurrentWorkingDirectory();
1210738b5c96SAdrian McCarthy   if (!WorkingDir)
1211738b5c96SAdrian McCarthy     return WorkingDir.getError();
1212738b5c96SAdrian McCarthy 
1213da45bd23SAdrian McCarthy   // We can't use sys::fs::make_absolute because that assumes the path style
1214da45bd23SAdrian McCarthy   // is native and there is no way to override that.  Since we know WorkingDir
1215da45bd23SAdrian McCarthy   // is absolute, we can use it to determine which style we actually have and
1216da45bd23SAdrian McCarthy   // append Path ourselves.
121746ec93a4SMartin Storsjö   sys::path::Style style = sys::path::Style::windows_backslash;
1218da45bd23SAdrian McCarthy   if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) {
1219da45bd23SAdrian McCarthy     style = sys::path::Style::posix;
122046ec93a4SMartin Storsjö   } else {
122146ec93a4SMartin Storsjö     // Distinguish between windows_backslash and windows_slash; getExistingStyle
122246ec93a4SMartin Storsjö     // returns posix for a path with windows_slash.
122346ec93a4SMartin Storsjö     if (getExistingStyle(WorkingDir.get()) !=
122446ec93a4SMartin Storsjö         sys::path::Style::windows_backslash)
122546ec93a4SMartin Storsjö       style = sys::path::Style::windows_slash;
1226da45bd23SAdrian McCarthy   }
1227da45bd23SAdrian McCarthy 
1228da45bd23SAdrian McCarthy   std::string Result = WorkingDir.get();
1229da45bd23SAdrian McCarthy   StringRef Dir(Result);
1230da45bd23SAdrian McCarthy   if (!Dir.endswith(sys::path::get_separator(style))) {
1231da45bd23SAdrian McCarthy     Result += sys::path::get_separator(style);
1232da45bd23SAdrian McCarthy   }
1233da45bd23SAdrian McCarthy   Result.append(Path.data(), Path.size());
1234da45bd23SAdrian McCarthy   Path.assign(Result.begin(), Result.end());
1235da45bd23SAdrian McCarthy 
1236738b5c96SAdrian McCarthy   return {};
1237738b5c96SAdrian McCarthy }
1238738b5c96SAdrian McCarthy 
12391a0ce65aSJonas Devlieghere directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
12401a0ce65aSJonas Devlieghere                                                     std::error_code &EC) {
12410be9ca7cSJonas Devlieghere   SmallString<256> Path;
12420be9ca7cSJonas Devlieghere   Dir.toVector(Path);
12430be9ca7cSJonas Devlieghere 
12440be9ca7cSJonas Devlieghere   EC = makeCanonical(Path);
12450be9ca7cSJonas Devlieghere   if (EC)
12460be9ca7cSJonas Devlieghere     return {};
12470be9ca7cSJonas Devlieghere 
1248ecb00a77SNathan Hawes   ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
1249ecb00a77SNathan Hawes   if (!Result) {
1250ecb00a77SNathan Hawes     EC = Result.getError();
1251719f7784SNathan Hawes     if (shouldFallBackToExternalFS(EC))
12520be9ca7cSJonas Devlieghere       return ExternalFS->dir_begin(Path, EC);
1253fc51490bSJonas Devlieghere     return {};
1254fc51490bSJonas Devlieghere   }
1255ecb00a77SNathan Hawes 
1256ecb00a77SNathan Hawes   // Use status to make sure the path exists and refers to a directory.
125786e2af80SKeith Smiley   ErrorOr<Status> S = status(Path, Dir, *Result);
1258fc51490bSJonas Devlieghere   if (!S) {
1259ecb00a77SNathan Hawes     if (shouldFallBackToExternalFS(S.getError(), Result->E))
1260ecb00a77SNathan Hawes       return ExternalFS->dir_begin(Dir, EC);
1261fc51490bSJonas Devlieghere     EC = S.getError();
1262fc51490bSJonas Devlieghere     return {};
1263fc51490bSJonas Devlieghere   }
1264fc51490bSJonas Devlieghere   if (!S->isDirectory()) {
1265fc51490bSJonas Devlieghere     EC = std::error_code(static_cast<int>(errc::not_a_directory),
1266fc51490bSJonas Devlieghere                          std::system_category());
1267fc51490bSJonas Devlieghere     return {};
1268fc51490bSJonas Devlieghere   }
1269fc51490bSJonas Devlieghere 
1270ecb00a77SNathan Hawes   // Create the appropriate directory iterator based on whether we found a
1271ecb00a77SNathan Hawes   // DirectoryRemapEntry or DirectoryEntry.
1272ecb00a77SNathan Hawes   directory_iterator DirIter;
1273ecb00a77SNathan Hawes   if (auto ExtRedirect = Result->getExternalRedirect()) {
1274ecb00a77SNathan Hawes     auto RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
1275ecb00a77SNathan Hawes     DirIter = ExternalFS->dir_begin(*ExtRedirect, EC);
1276ecb00a77SNathan Hawes 
1277ecb00a77SNathan Hawes     if (!RE->useExternalName(UseExternalNames)) {
1278ecb00a77SNathan Hawes       // Update the paths in the results to use the virtual directory's path.
1279ecb00a77SNathan Hawes       DirIter =
1280ecb00a77SNathan Hawes           directory_iterator(std::make_shared<RedirectingFSDirRemapIterImpl>(
1281ecb00a77SNathan Hawes               std::string(Path), DirIter));
1282ecb00a77SNathan Hawes     }
1283ecb00a77SNathan Hawes   } else {
1284ecb00a77SNathan Hawes     auto DE = cast<DirectoryEntry>(Result->E);
1285ecb00a77SNathan Hawes     DirIter = directory_iterator(std::make_shared<RedirectingFSDirIterImpl>(
1286ecb00a77SNathan Hawes         Path, DE->contents_begin(), DE->contents_end(), EC));
1287ecb00a77SNathan Hawes   }
1288719f7784SNathan Hawes 
1289719f7784SNathan Hawes   if (!shouldUseExternalFS())
1290719f7784SNathan Hawes     return DirIter;
1291719f7784SNathan Hawes   return directory_iterator(std::make_shared<CombiningDirIterImpl>(
1292719f7784SNathan Hawes       DirIter, ExternalFS, std::string(Path), EC));
1293fc51490bSJonas Devlieghere }
1294fc51490bSJonas Devlieghere 
12951a0ce65aSJonas Devlieghere void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) {
1296fc51490bSJonas Devlieghere   ExternalContentsPrefixDir = PrefixDir.str();
1297fc51490bSJonas Devlieghere }
1298fc51490bSJonas Devlieghere 
12991a0ce65aSJonas Devlieghere StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const {
1300fc51490bSJonas Devlieghere   return ExternalContentsPrefixDir;
1301fc51490bSJonas Devlieghere }
1302fc51490bSJonas Devlieghere 
130337469061SJonas Devlieghere void RedirectingFileSystem::setFallthrough(bool Fallthrough) {
130437469061SJonas Devlieghere   IsFallthrough = Fallthrough;
130537469061SJonas Devlieghere }
130637469061SJonas Devlieghere 
130737469061SJonas Devlieghere std::vector<StringRef> RedirectingFileSystem::getRoots() const {
130837469061SJonas Devlieghere   std::vector<StringRef> R;
130937469061SJonas Devlieghere   for (const auto &Root : Roots)
131037469061SJonas Devlieghere     R.push_back(Root->getName());
131137469061SJonas Devlieghere   return R;
131237469061SJonas Devlieghere }
131337469061SJonas Devlieghere 
131497fc8eb4SJonas Devlieghere void RedirectingFileSystem::dump(raw_ostream &OS) const {
1315fc51490bSJonas Devlieghere   for (const auto &Root : Roots)
131697fc8eb4SJonas Devlieghere     dumpEntry(OS, Root.get());
1317fc51490bSJonas Devlieghere }
1318fc51490bSJonas Devlieghere 
131997fc8eb4SJonas Devlieghere void RedirectingFileSystem::dumpEntry(raw_ostream &OS,
132097fc8eb4SJonas Devlieghere                                       RedirectingFileSystem::Entry *E,
13211a0ce65aSJonas Devlieghere                                       int NumSpaces) const {
1322fc51490bSJonas Devlieghere   StringRef Name = E->getName();
1323fc51490bSJonas Devlieghere   for (int i = 0, e = NumSpaces; i < e; ++i)
132497fc8eb4SJonas Devlieghere     OS << " ";
132597fc8eb4SJonas Devlieghere   OS << "'" << Name.str().c_str() << "'"
1326fc51490bSJonas Devlieghere      << "\n";
1327fc51490bSJonas Devlieghere 
13281a0ce65aSJonas Devlieghere   if (E->getKind() == RedirectingFileSystem::EK_Directory) {
1329719f7784SNathan Hawes     auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(E);
1330fc51490bSJonas Devlieghere     assert(DE && "Should be a directory");
1331fc51490bSJonas Devlieghere 
1332fc51490bSJonas Devlieghere     for (std::unique_ptr<Entry> &SubEntry :
1333fc51490bSJonas Devlieghere          llvm::make_range(DE->contents_begin(), DE->contents_end()))
133497fc8eb4SJonas Devlieghere       dumpEntry(OS, SubEntry.get(), NumSpaces + 2);
1335fc51490bSJonas Devlieghere   }
1336fc51490bSJonas Devlieghere }
133797fc8eb4SJonas Devlieghere 
133897fc8eb4SJonas Devlieghere #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
133997fc8eb4SJonas Devlieghere LLVM_DUMP_METHOD void RedirectingFileSystem::dump() const { dump(dbgs()); }
1340fc51490bSJonas Devlieghere #endif
1341fc51490bSJonas Devlieghere 
1342fc51490bSJonas Devlieghere /// A helper class to hold the common YAML parsing state.
13431a0ce65aSJonas Devlieghere class llvm::vfs::RedirectingFileSystemParser {
1344fc51490bSJonas Devlieghere   yaml::Stream &Stream;
1345fc51490bSJonas Devlieghere 
1346fc51490bSJonas Devlieghere   void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1347fc51490bSJonas Devlieghere 
1348fc51490bSJonas Devlieghere   // false on error
1349fc51490bSJonas Devlieghere   bool parseScalarString(yaml::Node *N, StringRef &Result,
1350fc51490bSJonas Devlieghere                          SmallVectorImpl<char> &Storage) {
1351fc51490bSJonas Devlieghere     const auto *S = dyn_cast<yaml::ScalarNode>(N);
1352fc51490bSJonas Devlieghere 
1353fc51490bSJonas Devlieghere     if (!S) {
1354fc51490bSJonas Devlieghere       error(N, "expected string");
1355fc51490bSJonas Devlieghere       return false;
1356fc51490bSJonas Devlieghere     }
1357fc51490bSJonas Devlieghere     Result = S->getValue(Storage);
1358fc51490bSJonas Devlieghere     return true;
1359fc51490bSJonas Devlieghere   }
1360fc51490bSJonas Devlieghere 
1361fc51490bSJonas Devlieghere   // false on error
1362fc51490bSJonas Devlieghere   bool parseScalarBool(yaml::Node *N, bool &Result) {
1363fc51490bSJonas Devlieghere     SmallString<5> Storage;
1364fc51490bSJonas Devlieghere     StringRef Value;
1365fc51490bSJonas Devlieghere     if (!parseScalarString(N, Value, Storage))
1366fc51490bSJonas Devlieghere       return false;
1367fc51490bSJonas Devlieghere 
136842f74e82SMartin Storsjö     if (Value.equals_insensitive("true") || Value.equals_insensitive("on") ||
136942f74e82SMartin Storsjö         Value.equals_insensitive("yes") || Value == "1") {
1370fc51490bSJonas Devlieghere       Result = true;
1371fc51490bSJonas Devlieghere       return true;
137242f74e82SMartin Storsjö     } else if (Value.equals_insensitive("false") ||
137342f74e82SMartin Storsjö                Value.equals_insensitive("off") ||
137442f74e82SMartin Storsjö                Value.equals_insensitive("no") || Value == "0") {
1375fc51490bSJonas Devlieghere       Result = false;
1376fc51490bSJonas Devlieghere       return true;
1377fc51490bSJonas Devlieghere     }
1378fc51490bSJonas Devlieghere 
1379fc51490bSJonas Devlieghere     error(N, "expected boolean value");
1380fc51490bSJonas Devlieghere     return false;
1381fc51490bSJonas Devlieghere   }
1382fc51490bSJonas Devlieghere 
1383fc51490bSJonas Devlieghere   struct KeyStatus {
1384fc51490bSJonas Devlieghere     bool Required;
1385fc51490bSJonas Devlieghere     bool Seen = false;
1386fc51490bSJonas Devlieghere 
1387fc51490bSJonas Devlieghere     KeyStatus(bool Required = false) : Required(Required) {}
1388fc51490bSJonas Devlieghere   };
1389fc51490bSJonas Devlieghere 
1390fc51490bSJonas Devlieghere   using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1391fc51490bSJonas Devlieghere 
1392fc51490bSJonas Devlieghere   // false on error
1393fc51490bSJonas Devlieghere   bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1394fc51490bSJonas Devlieghere                                   DenseMap<StringRef, KeyStatus> &Keys) {
1395fc51490bSJonas Devlieghere     if (!Keys.count(Key)) {
1396fc51490bSJonas Devlieghere       error(KeyNode, "unknown key");
1397fc51490bSJonas Devlieghere       return false;
1398fc51490bSJonas Devlieghere     }
1399fc51490bSJonas Devlieghere     KeyStatus &S = Keys[Key];
1400fc51490bSJonas Devlieghere     if (S.Seen) {
1401fc51490bSJonas Devlieghere       error(KeyNode, Twine("duplicate key '") + Key + "'");
1402fc51490bSJonas Devlieghere       return false;
1403fc51490bSJonas Devlieghere     }
1404fc51490bSJonas Devlieghere     S.Seen = true;
1405fc51490bSJonas Devlieghere     return true;
1406fc51490bSJonas Devlieghere   }
1407fc51490bSJonas Devlieghere 
1408fc51490bSJonas Devlieghere   // false on error
1409fc51490bSJonas Devlieghere   bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1410fc51490bSJonas Devlieghere     for (const auto &I : Keys) {
1411fc51490bSJonas Devlieghere       if (I.second.Required && !I.second.Seen) {
1412fc51490bSJonas Devlieghere         error(Obj, Twine("missing key '") + I.first + "'");
1413fc51490bSJonas Devlieghere         return false;
1414fc51490bSJonas Devlieghere       }
1415fc51490bSJonas Devlieghere     }
1416fc51490bSJonas Devlieghere     return true;
1417fc51490bSJonas Devlieghere   }
1418fc51490bSJonas Devlieghere 
141975cd8d75SDuncan P. N. Exon Smith public:
142075cd8d75SDuncan P. N. Exon Smith   static RedirectingFileSystem::Entry *
14211a0ce65aSJonas Devlieghere   lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
14221a0ce65aSJonas Devlieghere                       RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1423fc51490bSJonas Devlieghere     if (!ParentEntry) { // Look for a existent root
1424fc51490bSJonas Devlieghere       for (const auto &Root : FS->Roots) {
1425fc51490bSJonas Devlieghere         if (Name.equals(Root->getName())) {
1426fc51490bSJonas Devlieghere           ParentEntry = Root.get();
1427fc51490bSJonas Devlieghere           return ParentEntry;
1428fc51490bSJonas Devlieghere         }
1429fc51490bSJonas Devlieghere       }
1430fc51490bSJonas Devlieghere     } else { // Advance to the next component
1431719f7784SNathan Hawes       auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
14321a0ce65aSJonas Devlieghere       for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1433fc51490bSJonas Devlieghere            llvm::make_range(DE->contents_begin(), DE->contents_end())) {
14341a0ce65aSJonas Devlieghere         auto *DirContent =
1435719f7784SNathan Hawes             dyn_cast<RedirectingFileSystem::DirectoryEntry>(Content.get());
1436fc51490bSJonas Devlieghere         if (DirContent && Name.equals(Content->getName()))
1437fc51490bSJonas Devlieghere           return DirContent;
1438fc51490bSJonas Devlieghere       }
1439fc51490bSJonas Devlieghere     }
1440fc51490bSJonas Devlieghere 
1441fc51490bSJonas Devlieghere     // ... or create a new one
14421a0ce65aSJonas Devlieghere     std::unique_ptr<RedirectingFileSystem::Entry> E =
1443719f7784SNathan Hawes         std::make_unique<RedirectingFileSystem::DirectoryEntry>(
14441a0ce65aSJonas Devlieghere             Name, Status("", getNextVirtualUniqueID(),
14451a0ce65aSJonas Devlieghere                          std::chrono::system_clock::now(), 0, 0, 0,
14461a0ce65aSJonas Devlieghere                          file_type::directory_file, sys::fs::all_all));
1447fc51490bSJonas Devlieghere 
1448fc51490bSJonas Devlieghere     if (!ParentEntry) { // Add a new root to the overlay
1449fc51490bSJonas Devlieghere       FS->Roots.push_back(std::move(E));
1450fc51490bSJonas Devlieghere       ParentEntry = FS->Roots.back().get();
1451fc51490bSJonas Devlieghere       return ParentEntry;
1452fc51490bSJonas Devlieghere     }
1453fc51490bSJonas Devlieghere 
1454719f7784SNathan Hawes     auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
1455fc51490bSJonas Devlieghere     DE->addContent(std::move(E));
1456fc51490bSJonas Devlieghere     return DE->getLastContent();
1457fc51490bSJonas Devlieghere   }
1458fc51490bSJonas Devlieghere 
145975cd8d75SDuncan P. N. Exon Smith private:
14601a0ce65aSJonas Devlieghere   void uniqueOverlayTree(RedirectingFileSystem *FS,
14611a0ce65aSJonas Devlieghere                          RedirectingFileSystem::Entry *SrcE,
14621a0ce65aSJonas Devlieghere                          RedirectingFileSystem::Entry *NewParentE = nullptr) {
1463fc51490bSJonas Devlieghere     StringRef Name = SrcE->getName();
1464fc51490bSJonas Devlieghere     switch (SrcE->getKind()) {
14651a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_Directory: {
1466719f7784SNathan Hawes       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
1467fc51490bSJonas Devlieghere       // Empty directories could be present in the YAML as a way to
1468fc51490bSJonas Devlieghere       // describe a file for a current directory after some of its subdir
1469fc51490bSJonas Devlieghere       // is parsed. This only leads to redundant walks, ignore it.
1470fc51490bSJonas Devlieghere       if (!Name.empty())
1471fc51490bSJonas Devlieghere         NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
14721a0ce65aSJonas Devlieghere       for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1473fc51490bSJonas Devlieghere            llvm::make_range(DE->contents_begin(), DE->contents_end()))
1474fc51490bSJonas Devlieghere         uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1475fc51490bSJonas Devlieghere       break;
1476fc51490bSJonas Devlieghere     }
1477ecb00a77SNathan Hawes     case RedirectingFileSystem::EK_DirectoryRemap: {
1478ecb00a77SNathan Hawes       assert(NewParentE && "Parent entry must exist");
1479ecb00a77SNathan Hawes       auto *DR = cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
1480ecb00a77SNathan Hawes       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1481ecb00a77SNathan Hawes       DE->addContent(
1482ecb00a77SNathan Hawes           std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1483ecb00a77SNathan Hawes               Name, DR->getExternalContentsPath(), DR->getUseName()));
1484ecb00a77SNathan Hawes       break;
1485ecb00a77SNathan Hawes     }
14861a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_File: {
1487fc51490bSJonas Devlieghere       assert(NewParentE && "Parent entry must exist");
1488719f7784SNathan Hawes       auto *FE = cast<RedirectingFileSystem::FileEntry>(SrcE);
1489719f7784SNathan Hawes       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1490719f7784SNathan Hawes       DE->addContent(std::make_unique<RedirectingFileSystem::FileEntry>(
1491fc51490bSJonas Devlieghere           Name, FE->getExternalContentsPath(), FE->getUseName()));
1492fc51490bSJonas Devlieghere       break;
1493fc51490bSJonas Devlieghere     }
1494fc51490bSJonas Devlieghere     }
1495fc51490bSJonas Devlieghere   }
1496fc51490bSJonas Devlieghere 
14971a0ce65aSJonas Devlieghere   std::unique_ptr<RedirectingFileSystem::Entry>
14981a0ce65aSJonas Devlieghere   parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1499fc51490bSJonas Devlieghere     auto *M = dyn_cast<yaml::MappingNode>(N);
1500fc51490bSJonas Devlieghere     if (!M) {
1501fc51490bSJonas Devlieghere       error(N, "expected mapping node for file or directory entry");
1502fc51490bSJonas Devlieghere       return nullptr;
1503fc51490bSJonas Devlieghere     }
1504fc51490bSJonas Devlieghere 
1505fc51490bSJonas Devlieghere     KeyStatusPair Fields[] = {
1506fc51490bSJonas Devlieghere         KeyStatusPair("name", true),
1507fc51490bSJonas Devlieghere         KeyStatusPair("type", true),
1508fc51490bSJonas Devlieghere         KeyStatusPair("contents", false),
1509fc51490bSJonas Devlieghere         KeyStatusPair("external-contents", false),
1510fc51490bSJonas Devlieghere         KeyStatusPair("use-external-name", false),
1511fc51490bSJonas Devlieghere     };
1512fc51490bSJonas Devlieghere 
1513fc51490bSJonas Devlieghere     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1514fc51490bSJonas Devlieghere 
1515ecb00a77SNathan Hawes     enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet;
15161a0ce65aSJonas Devlieghere     std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
15171a0ce65aSJonas Devlieghere         EntryArrayContents;
1518da45bd23SAdrian McCarthy     SmallString<256> ExternalContentsPath;
1519da45bd23SAdrian McCarthy     SmallString<256> Name;
1520cfe6fe06SSimon Pilgrim     yaml::Node *NameValueNode = nullptr;
1521ecb00a77SNathan Hawes     auto UseExternalName = RedirectingFileSystem::NK_NotSet;
15221a0ce65aSJonas Devlieghere     RedirectingFileSystem::EntryKind Kind;
1523fc51490bSJonas Devlieghere 
1524fc51490bSJonas Devlieghere     for (auto &I : *M) {
1525fc51490bSJonas Devlieghere       StringRef Key;
1526fc51490bSJonas Devlieghere       // Reuse the buffer for key and value, since we don't look at key after
1527fc51490bSJonas Devlieghere       // parsing value.
1528fc51490bSJonas Devlieghere       SmallString<256> Buffer;
1529fc51490bSJonas Devlieghere       if (!parseScalarString(I.getKey(), Key, Buffer))
1530fc51490bSJonas Devlieghere         return nullptr;
1531fc51490bSJonas Devlieghere 
1532fc51490bSJonas Devlieghere       if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1533fc51490bSJonas Devlieghere         return nullptr;
1534fc51490bSJonas Devlieghere 
1535fc51490bSJonas Devlieghere       StringRef Value;
1536fc51490bSJonas Devlieghere       if (Key == "name") {
1537fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), Value, Buffer))
1538fc51490bSJonas Devlieghere           return nullptr;
1539fc51490bSJonas Devlieghere 
1540fc51490bSJonas Devlieghere         NameValueNode = I.getValue();
1541fc51490bSJonas Devlieghere         // Guarantee that old YAML files containing paths with ".." and "."
1542fc51490bSJonas Devlieghere         // are properly canonicalized before read into the VFS.
1543da45bd23SAdrian McCarthy         Name = canonicalize(Value).str();
1544fc51490bSJonas Devlieghere       } else if (Key == "type") {
1545fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), Value, Buffer))
1546fc51490bSJonas Devlieghere           return nullptr;
1547fc51490bSJonas Devlieghere         if (Value == "file")
15481a0ce65aSJonas Devlieghere           Kind = RedirectingFileSystem::EK_File;
1549fc51490bSJonas Devlieghere         else if (Value == "directory")
15501a0ce65aSJonas Devlieghere           Kind = RedirectingFileSystem::EK_Directory;
1551ecb00a77SNathan Hawes         else if (Value == "directory-remap")
1552ecb00a77SNathan Hawes           Kind = RedirectingFileSystem::EK_DirectoryRemap;
1553fc51490bSJonas Devlieghere         else {
1554fc51490bSJonas Devlieghere           error(I.getValue(), "unknown value for 'type'");
1555fc51490bSJonas Devlieghere           return nullptr;
1556fc51490bSJonas Devlieghere         }
1557fc51490bSJonas Devlieghere       } else if (Key == "contents") {
1558ecb00a77SNathan Hawes         if (ContentsField != CF_NotSet) {
1559fc51490bSJonas Devlieghere           error(I.getKey(),
1560fc51490bSJonas Devlieghere                 "entry already has 'contents' or 'external-contents'");
1561fc51490bSJonas Devlieghere           return nullptr;
1562fc51490bSJonas Devlieghere         }
1563ecb00a77SNathan Hawes         ContentsField = CF_List;
1564fc51490bSJonas Devlieghere         auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
1565fc51490bSJonas Devlieghere         if (!Contents) {
1566fc51490bSJonas Devlieghere           // FIXME: this is only for directories, what about files?
1567fc51490bSJonas Devlieghere           error(I.getValue(), "expected array");
1568fc51490bSJonas Devlieghere           return nullptr;
1569fc51490bSJonas Devlieghere         }
1570fc51490bSJonas Devlieghere 
1571fc51490bSJonas Devlieghere         for (auto &I : *Contents) {
15721a0ce65aSJonas Devlieghere           if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1573fc51490bSJonas Devlieghere                   parseEntry(&I, FS, /*IsRootEntry*/ false))
1574fc51490bSJonas Devlieghere             EntryArrayContents.push_back(std::move(E));
1575fc51490bSJonas Devlieghere           else
1576fc51490bSJonas Devlieghere             return nullptr;
1577fc51490bSJonas Devlieghere         }
1578fc51490bSJonas Devlieghere       } else if (Key == "external-contents") {
1579ecb00a77SNathan Hawes         if (ContentsField != CF_NotSet) {
1580fc51490bSJonas Devlieghere           error(I.getKey(),
1581fc51490bSJonas Devlieghere                 "entry already has 'contents' or 'external-contents'");
1582fc51490bSJonas Devlieghere           return nullptr;
1583fc51490bSJonas Devlieghere         }
1584ecb00a77SNathan Hawes         ContentsField = CF_External;
1585fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), Value, Buffer))
1586fc51490bSJonas Devlieghere           return nullptr;
1587fc51490bSJonas Devlieghere 
1588fc51490bSJonas Devlieghere         SmallString<256> FullPath;
1589fc51490bSJonas Devlieghere         if (FS->IsRelativeOverlay) {
1590fc51490bSJonas Devlieghere           FullPath = FS->getExternalContentsPrefixDir();
1591fc51490bSJonas Devlieghere           assert(!FullPath.empty() &&
1592fc51490bSJonas Devlieghere                  "External contents prefix directory must exist");
1593fc51490bSJonas Devlieghere           llvm::sys::path::append(FullPath, Value);
1594fc51490bSJonas Devlieghere         } else {
1595fc51490bSJonas Devlieghere           FullPath = Value;
1596fc51490bSJonas Devlieghere         }
1597fc51490bSJonas Devlieghere 
1598fc51490bSJonas Devlieghere         // Guarantee that old YAML files containing paths with ".." and "."
1599fc51490bSJonas Devlieghere         // are properly canonicalized before read into the VFS.
1600da45bd23SAdrian McCarthy         FullPath = canonicalize(FullPath);
1601da45bd23SAdrian McCarthy         ExternalContentsPath = FullPath.str();
1602fc51490bSJonas Devlieghere       } else if (Key == "use-external-name") {
1603fc51490bSJonas Devlieghere         bool Val;
1604fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), Val))
1605fc51490bSJonas Devlieghere           return nullptr;
1606ecb00a77SNathan Hawes         UseExternalName = Val ? RedirectingFileSystem::NK_External
1607ecb00a77SNathan Hawes                               : RedirectingFileSystem::NK_Virtual;
1608fc51490bSJonas Devlieghere       } else {
1609fc51490bSJonas Devlieghere         llvm_unreachable("key missing from Keys");
1610fc51490bSJonas Devlieghere       }
1611fc51490bSJonas Devlieghere     }
1612fc51490bSJonas Devlieghere 
1613fc51490bSJonas Devlieghere     if (Stream.failed())
1614fc51490bSJonas Devlieghere       return nullptr;
1615fc51490bSJonas Devlieghere 
1616fc51490bSJonas Devlieghere     // check for missing keys
1617ecb00a77SNathan Hawes     if (ContentsField == CF_NotSet) {
1618fc51490bSJonas Devlieghere       error(N, "missing key 'contents' or 'external-contents'");
1619fc51490bSJonas Devlieghere       return nullptr;
1620fc51490bSJonas Devlieghere     }
1621fc51490bSJonas Devlieghere     if (!checkMissingKeys(N, Keys))
1622fc51490bSJonas Devlieghere       return nullptr;
1623fc51490bSJonas Devlieghere 
1624fc51490bSJonas Devlieghere     // check invalid configuration
16251a0ce65aSJonas Devlieghere     if (Kind == RedirectingFileSystem::EK_Directory &&
1626ecb00a77SNathan Hawes         UseExternalName != RedirectingFileSystem::NK_NotSet) {
1627ecb00a77SNathan Hawes       error(N, "'use-external-name' is not supported for 'directory' entries");
1628ecb00a77SNathan Hawes       return nullptr;
1629ecb00a77SNathan Hawes     }
1630ecb00a77SNathan Hawes 
1631ecb00a77SNathan Hawes     if (Kind == RedirectingFileSystem::EK_DirectoryRemap &&
1632ecb00a77SNathan Hawes         ContentsField == CF_List) {
1633ecb00a77SNathan Hawes       error(N, "'contents' is not supported for 'directory-remap' entries");
1634fc51490bSJonas Devlieghere       return nullptr;
1635fc51490bSJonas Devlieghere     }
1636fc51490bSJonas Devlieghere 
1637738b5c96SAdrian McCarthy     sys::path::Style path_style = sys::path::Style::native;
1638738b5c96SAdrian McCarthy     if (IsRootEntry) {
1639738b5c96SAdrian McCarthy       // VFS root entries may be in either Posix or Windows style.  Figure out
1640738b5c96SAdrian McCarthy       // which style we have, and use it consistently.
1641738b5c96SAdrian McCarthy       if (sys::path::is_absolute(Name, sys::path::Style::posix)) {
1642738b5c96SAdrian McCarthy         path_style = sys::path::Style::posix;
164346ec93a4SMartin Storsjö       } else if (sys::path::is_absolute(Name,
164446ec93a4SMartin Storsjö                                         sys::path::Style::windows_backslash)) {
164546ec93a4SMartin Storsjö         path_style = sys::path::Style::windows_backslash;
1646738b5c96SAdrian McCarthy       } else {
16474f61749eSRichard Howell         // Relative VFS root entries are made absolute to the current working
16484f61749eSRichard Howell         // directory, then we can determine the path style from that.
16494f61749eSRichard Howell         auto EC = sys::fs::make_absolute(Name);
16504f61749eSRichard Howell         if (EC) {
1651fc51490bSJonas Devlieghere           assert(NameValueNode && "Name presence should be checked earlier");
16524f61749eSRichard Howell           error(
16534f61749eSRichard Howell               NameValueNode,
1654fc51490bSJonas Devlieghere               "entry with relative path at the root level is not discoverable");
1655fc51490bSJonas Devlieghere           return nullptr;
1656fc51490bSJonas Devlieghere         }
16574f61749eSRichard Howell         path_style = sys::path::is_absolute(Name, sys::path::Style::posix)
16584f61749eSRichard Howell                          ? sys::path::Style::posix
16594f61749eSRichard Howell                          : sys::path::Style::windows_backslash;
16604f61749eSRichard Howell       }
1661738b5c96SAdrian McCarthy     }
1662fc51490bSJonas Devlieghere 
1663fc51490bSJonas Devlieghere     // Remove trailing slash(es), being careful not to remove the root path
16641def2579SDavid Blaikie     StringRef Trimmed = Name;
1665738b5c96SAdrian McCarthy     size_t RootPathLen = sys::path::root_path(Trimmed, path_style).size();
1666fc51490bSJonas Devlieghere     while (Trimmed.size() > RootPathLen &&
1667738b5c96SAdrian McCarthy            sys::path::is_separator(Trimmed.back(), path_style))
1668fc51490bSJonas Devlieghere       Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
1669738b5c96SAdrian McCarthy 
1670fc51490bSJonas Devlieghere     // Get the last component
1671738b5c96SAdrian McCarthy     StringRef LastComponent = sys::path::filename(Trimmed, path_style);
1672fc51490bSJonas Devlieghere 
16731a0ce65aSJonas Devlieghere     std::unique_ptr<RedirectingFileSystem::Entry> Result;
1674fc51490bSJonas Devlieghere     switch (Kind) {
16751a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_File:
1676719f7784SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::FileEntry>(
1677fc51490bSJonas Devlieghere           LastComponent, std::move(ExternalContentsPath), UseExternalName);
1678fc51490bSJonas Devlieghere       break;
1679ecb00a77SNathan Hawes     case RedirectingFileSystem::EK_DirectoryRemap:
1680ecb00a77SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1681ecb00a77SNathan Hawes           LastComponent, std::move(ExternalContentsPath), UseExternalName);
1682ecb00a77SNathan Hawes       break;
16831a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_Directory:
1684719f7784SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1685fc51490bSJonas Devlieghere           LastComponent, std::move(EntryArrayContents),
1686719f7784SNathan Hawes           Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1687719f7784SNathan Hawes                  0, 0, 0, file_type::directory_file, sys::fs::all_all));
1688fc51490bSJonas Devlieghere       break;
1689fc51490bSJonas Devlieghere     }
1690fc51490bSJonas Devlieghere 
1691738b5c96SAdrian McCarthy     StringRef Parent = sys::path::parent_path(Trimmed, path_style);
1692fc51490bSJonas Devlieghere     if (Parent.empty())
1693fc51490bSJonas Devlieghere       return Result;
1694fc51490bSJonas Devlieghere 
1695fc51490bSJonas Devlieghere     // if 'name' contains multiple components, create implicit directory entries
1696738b5c96SAdrian McCarthy     for (sys::path::reverse_iterator I = sys::path::rbegin(Parent, path_style),
1697fc51490bSJonas Devlieghere                                      E = sys::path::rend(Parent);
1698fc51490bSJonas Devlieghere          I != E; ++I) {
16991a0ce65aSJonas Devlieghere       std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
1700fc51490bSJonas Devlieghere       Entries.push_back(std::move(Result));
1701719f7784SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1702fc51490bSJonas Devlieghere           *I, std::move(Entries),
1703719f7784SNathan Hawes           Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1704719f7784SNathan Hawes                  0, 0, 0, file_type::directory_file, sys::fs::all_all));
1705fc51490bSJonas Devlieghere     }
1706fc51490bSJonas Devlieghere     return Result;
1707fc51490bSJonas Devlieghere   }
1708fc51490bSJonas Devlieghere 
1709fc51490bSJonas Devlieghere public:
1710fc51490bSJonas Devlieghere   RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1711fc51490bSJonas Devlieghere 
1712fc51490bSJonas Devlieghere   // false on error
1713fc51490bSJonas Devlieghere   bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1714fc51490bSJonas Devlieghere     auto *Top = dyn_cast<yaml::MappingNode>(Root);
1715fc51490bSJonas Devlieghere     if (!Top) {
1716fc51490bSJonas Devlieghere       error(Root, "expected mapping node");
1717fc51490bSJonas Devlieghere       return false;
1718fc51490bSJonas Devlieghere     }
1719fc51490bSJonas Devlieghere 
1720fc51490bSJonas Devlieghere     KeyStatusPair Fields[] = {
1721fc51490bSJonas Devlieghere         KeyStatusPair("version", true),
1722fc51490bSJonas Devlieghere         KeyStatusPair("case-sensitive", false),
1723fc51490bSJonas Devlieghere         KeyStatusPair("use-external-names", false),
1724fc51490bSJonas Devlieghere         KeyStatusPair("overlay-relative", false),
172591e13164SVolodymyr Sapsai         KeyStatusPair("fallthrough", false),
1726fc51490bSJonas Devlieghere         KeyStatusPair("roots", true),
1727fc51490bSJonas Devlieghere     };
1728fc51490bSJonas Devlieghere 
1729fc51490bSJonas Devlieghere     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
17301a0ce65aSJonas Devlieghere     std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
1731fc51490bSJonas Devlieghere 
1732fc51490bSJonas Devlieghere     // Parse configuration and 'roots'
1733fc51490bSJonas Devlieghere     for (auto &I : *Top) {
1734fc51490bSJonas Devlieghere       SmallString<10> KeyBuffer;
1735fc51490bSJonas Devlieghere       StringRef Key;
1736fc51490bSJonas Devlieghere       if (!parseScalarString(I.getKey(), Key, KeyBuffer))
1737fc51490bSJonas Devlieghere         return false;
1738fc51490bSJonas Devlieghere 
1739fc51490bSJonas Devlieghere       if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1740fc51490bSJonas Devlieghere         return false;
1741fc51490bSJonas Devlieghere 
1742fc51490bSJonas Devlieghere       if (Key == "roots") {
1743fc51490bSJonas Devlieghere         auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
1744fc51490bSJonas Devlieghere         if (!Roots) {
1745fc51490bSJonas Devlieghere           error(I.getValue(), "expected array");
1746fc51490bSJonas Devlieghere           return false;
1747fc51490bSJonas Devlieghere         }
1748fc51490bSJonas Devlieghere 
1749fc51490bSJonas Devlieghere         for (auto &I : *Roots) {
17501a0ce65aSJonas Devlieghere           if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1751fc51490bSJonas Devlieghere                   parseEntry(&I, FS, /*IsRootEntry*/ true))
1752fc51490bSJonas Devlieghere             RootEntries.push_back(std::move(E));
1753fc51490bSJonas Devlieghere           else
1754fc51490bSJonas Devlieghere             return false;
1755fc51490bSJonas Devlieghere         }
1756fc51490bSJonas Devlieghere       } else if (Key == "version") {
1757fc51490bSJonas Devlieghere         StringRef VersionString;
1758fc51490bSJonas Devlieghere         SmallString<4> Storage;
1759fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), VersionString, Storage))
1760fc51490bSJonas Devlieghere           return false;
1761fc51490bSJonas Devlieghere         int Version;
1762fc51490bSJonas Devlieghere         if (VersionString.getAsInteger<int>(10, Version)) {
1763fc51490bSJonas Devlieghere           error(I.getValue(), "expected integer");
1764fc51490bSJonas Devlieghere           return false;
1765fc51490bSJonas Devlieghere         }
1766fc51490bSJonas Devlieghere         if (Version < 0) {
1767fc51490bSJonas Devlieghere           error(I.getValue(), "invalid version number");
1768fc51490bSJonas Devlieghere           return false;
1769fc51490bSJonas Devlieghere         }
1770fc51490bSJonas Devlieghere         if (Version != 0) {
1771fc51490bSJonas Devlieghere           error(I.getValue(), "version mismatch, expected 0");
1772fc51490bSJonas Devlieghere           return false;
1773fc51490bSJonas Devlieghere         }
1774fc51490bSJonas Devlieghere       } else if (Key == "case-sensitive") {
1775fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
1776fc51490bSJonas Devlieghere           return false;
1777fc51490bSJonas Devlieghere       } else if (Key == "overlay-relative") {
1778fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
1779fc51490bSJonas Devlieghere           return false;
1780fc51490bSJonas Devlieghere       } else if (Key == "use-external-names") {
1781fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
1782fc51490bSJonas Devlieghere           return false;
178391e13164SVolodymyr Sapsai       } else if (Key == "fallthrough") {
178491e13164SVolodymyr Sapsai         if (!parseScalarBool(I.getValue(), FS->IsFallthrough))
178591e13164SVolodymyr Sapsai           return false;
1786fc51490bSJonas Devlieghere       } else {
1787fc51490bSJonas Devlieghere         llvm_unreachable("key missing from Keys");
1788fc51490bSJonas Devlieghere       }
1789fc51490bSJonas Devlieghere     }
1790fc51490bSJonas Devlieghere 
1791fc51490bSJonas Devlieghere     if (Stream.failed())
1792fc51490bSJonas Devlieghere       return false;
1793fc51490bSJonas Devlieghere 
1794fc51490bSJonas Devlieghere     if (!checkMissingKeys(Top, Keys))
1795fc51490bSJonas Devlieghere       return false;
1796fc51490bSJonas Devlieghere 
1797fc51490bSJonas Devlieghere     // Now that we sucessefully parsed the YAML file, canonicalize the internal
1798fc51490bSJonas Devlieghere     // representation to a proper directory tree so that we can search faster
1799fc51490bSJonas Devlieghere     // inside the VFS.
1800fc51490bSJonas Devlieghere     for (auto &E : RootEntries)
1801fc51490bSJonas Devlieghere       uniqueOverlayTree(FS, E.get());
1802fc51490bSJonas Devlieghere 
1803fc51490bSJonas Devlieghere     return true;
1804fc51490bSJonas Devlieghere   }
1805fc51490bSJonas Devlieghere };
1806fc51490bSJonas Devlieghere 
1807a22eda54SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem>
1808fc51490bSJonas Devlieghere RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1809fc51490bSJonas Devlieghere                               SourceMgr::DiagHandlerTy DiagHandler,
1810fc51490bSJonas Devlieghere                               StringRef YAMLFilePath, void *DiagContext,
1811fc51490bSJonas Devlieghere                               IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1812fc51490bSJonas Devlieghere   SourceMgr SM;
1813fc51490bSJonas Devlieghere   yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
1814fc51490bSJonas Devlieghere 
1815fc51490bSJonas Devlieghere   SM.setDiagHandler(DiagHandler, DiagContext);
1816fc51490bSJonas Devlieghere   yaml::document_iterator DI = Stream.begin();
1817fc51490bSJonas Devlieghere   yaml::Node *Root = DI->getRoot();
1818fc51490bSJonas Devlieghere   if (DI == Stream.end() || !Root) {
1819fc51490bSJonas Devlieghere     SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
1820fc51490bSJonas Devlieghere     return nullptr;
1821fc51490bSJonas Devlieghere   }
1822fc51490bSJonas Devlieghere 
1823fc51490bSJonas Devlieghere   RedirectingFileSystemParser P(Stream);
1824fc51490bSJonas Devlieghere 
1825fc51490bSJonas Devlieghere   std::unique_ptr<RedirectingFileSystem> FS(
182621703543SJonas Devlieghere       new RedirectingFileSystem(ExternalFS));
1827fc51490bSJonas Devlieghere 
1828fc51490bSJonas Devlieghere   if (!YAMLFilePath.empty()) {
1829fc51490bSJonas Devlieghere     // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1830fc51490bSJonas Devlieghere     // to each 'external-contents' path.
1831fc51490bSJonas Devlieghere     //
1832fc51490bSJonas Devlieghere     // Example:
1833fc51490bSJonas Devlieghere     //    -ivfsoverlay dummy.cache/vfs/vfs.yaml
1834fc51490bSJonas Devlieghere     // yields:
1835fc51490bSJonas Devlieghere     //  FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1836fc51490bSJonas Devlieghere     //
1837fc51490bSJonas Devlieghere     SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1838fc51490bSJonas Devlieghere     std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1839fc51490bSJonas Devlieghere     assert(!EC && "Overlay dir final path must be absolute");
1840fc51490bSJonas Devlieghere     (void)EC;
1841fc51490bSJonas Devlieghere     FS->setExternalContentsPrefixDir(OverlayAbsDir);
1842fc51490bSJonas Devlieghere   }
1843fc51490bSJonas Devlieghere 
1844fc51490bSJonas Devlieghere   if (!P.parse(Root, FS.get()))
1845fc51490bSJonas Devlieghere     return nullptr;
1846fc51490bSJonas Devlieghere 
1847a22eda54SDuncan P. N. Exon Smith   return FS;
1848fc51490bSJonas Devlieghere }
1849fc51490bSJonas Devlieghere 
185075cd8d75SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create(
185175cd8d75SDuncan P. N. Exon Smith     ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
185275cd8d75SDuncan P. N. Exon Smith     bool UseExternalNames, FileSystem &ExternalFS) {
185375cd8d75SDuncan P. N. Exon Smith   std::unique_ptr<RedirectingFileSystem> FS(
185475cd8d75SDuncan P. N. Exon Smith       new RedirectingFileSystem(&ExternalFS));
185575cd8d75SDuncan P. N. Exon Smith   FS->UseExternalNames = UseExternalNames;
185675cd8d75SDuncan P. N. Exon Smith 
185775cd8d75SDuncan P. N. Exon Smith   StringMap<RedirectingFileSystem::Entry *> Entries;
185875cd8d75SDuncan P. N. Exon Smith 
185975cd8d75SDuncan P. N. Exon Smith   for (auto &Mapping : llvm::reverse(RemappedFiles)) {
186075cd8d75SDuncan P. N. Exon Smith     SmallString<128> From = StringRef(Mapping.first);
186175cd8d75SDuncan P. N. Exon Smith     SmallString<128> To = StringRef(Mapping.second);
186275cd8d75SDuncan P. N. Exon Smith     {
186375cd8d75SDuncan P. N. Exon Smith       auto EC = ExternalFS.makeAbsolute(From);
186475cd8d75SDuncan P. N. Exon Smith       (void)EC;
186575cd8d75SDuncan P. N. Exon Smith       assert(!EC && "Could not make absolute path");
186675cd8d75SDuncan P. N. Exon Smith     }
186775cd8d75SDuncan P. N. Exon Smith 
186875cd8d75SDuncan P. N. Exon Smith     // Check if we've already mapped this file. The first one we see (in the
186975cd8d75SDuncan P. N. Exon Smith     // reverse iteration) wins.
187075cd8d75SDuncan P. N. Exon Smith     RedirectingFileSystem::Entry *&ToEntry = Entries[From];
187175cd8d75SDuncan P. N. Exon Smith     if (ToEntry)
187275cd8d75SDuncan P. N. Exon Smith       continue;
187375cd8d75SDuncan P. N. Exon Smith 
187475cd8d75SDuncan P. N. Exon Smith     // Add parent directories.
187575cd8d75SDuncan P. N. Exon Smith     RedirectingFileSystem::Entry *Parent = nullptr;
187675cd8d75SDuncan P. N. Exon Smith     StringRef FromDirectory = llvm::sys::path::parent_path(From);
187775cd8d75SDuncan P. N. Exon Smith     for (auto I = llvm::sys::path::begin(FromDirectory),
187875cd8d75SDuncan P. N. Exon Smith               E = llvm::sys::path::end(FromDirectory);
187975cd8d75SDuncan P. N. Exon Smith          I != E; ++I) {
188075cd8d75SDuncan P. N. Exon Smith       Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS.get(), *I,
188175cd8d75SDuncan P. N. Exon Smith                                                                 Parent);
188275cd8d75SDuncan P. N. Exon Smith     }
188375cd8d75SDuncan P. N. Exon Smith     assert(Parent && "File without a directory?");
188475cd8d75SDuncan P. N. Exon Smith     {
188575cd8d75SDuncan P. N. Exon Smith       auto EC = ExternalFS.makeAbsolute(To);
188675cd8d75SDuncan P. N. Exon Smith       (void)EC;
188775cd8d75SDuncan P. N. Exon Smith       assert(!EC && "Could not make absolute path");
188875cd8d75SDuncan P. N. Exon Smith     }
188975cd8d75SDuncan P. N. Exon Smith 
189075cd8d75SDuncan P. N. Exon Smith     // Add the file.
1891719f7784SNathan Hawes     auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>(
189275cd8d75SDuncan P. N. Exon Smith         llvm::sys::path::filename(From), To,
1893ecb00a77SNathan Hawes         UseExternalNames ? RedirectingFileSystem::NK_External
1894ecb00a77SNathan Hawes                          : RedirectingFileSystem::NK_Virtual);
189575cd8d75SDuncan P. N. Exon Smith     ToEntry = NewFile.get();
1896719f7784SNathan Hawes     cast<RedirectingFileSystem::DirectoryEntry>(Parent)->addContent(
189775cd8d75SDuncan P. N. Exon Smith         std::move(NewFile));
189875cd8d75SDuncan P. N. Exon Smith   }
189975cd8d75SDuncan P. N. Exon Smith 
190075cd8d75SDuncan P. N. Exon Smith   return FS;
190175cd8d75SDuncan P. N. Exon Smith }
190275cd8d75SDuncan P. N. Exon Smith 
1903ecb00a77SNathan Hawes RedirectingFileSystem::LookupResult::LookupResult(
1904ecb00a77SNathan Hawes     Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
1905ecb00a77SNathan Hawes     : E(E) {
1906ecb00a77SNathan Hawes   assert(E != nullptr);
1907ecb00a77SNathan Hawes   // If the matched entry is a DirectoryRemapEntry, set ExternalRedirect to the
1908ecb00a77SNathan Hawes   // path of the directory it maps to in the external file system plus any
1909ecb00a77SNathan Hawes   // remaining path components in the provided iterator.
1910ecb00a77SNathan Hawes   if (auto *DRE = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(E)) {
1911ecb00a77SNathan Hawes     SmallString<256> Redirect(DRE->getExternalContentsPath());
1912ecb00a77SNathan Hawes     sys::path::append(Redirect, Start, End,
1913ecb00a77SNathan Hawes                       getExistingStyle(DRE->getExternalContentsPath()));
1914ecb00a77SNathan Hawes     ExternalRedirect = std::string(Redirect);
1915ecb00a77SNathan Hawes   }
1916ecb00a77SNathan Hawes }
1917ecb00a77SNathan Hawes 
1918719f7784SNathan Hawes bool RedirectingFileSystem::shouldFallBackToExternalFS(
1919ecb00a77SNathan Hawes     std::error_code EC, RedirectingFileSystem::Entry *E) const {
1920ecb00a77SNathan Hawes   if (E && !isa<RedirectingFileSystem::DirectoryRemapEntry>(E))
1921ecb00a77SNathan Hawes     return false;
1922719f7784SNathan Hawes   return shouldUseExternalFS() && EC == llvm::errc::no_such_file_or_directory;
192349556b87SYang Fan }
1924719f7784SNathan Hawes 
19250be9ca7cSJonas Devlieghere std::error_code
19260be9ca7cSJonas Devlieghere RedirectingFileSystem::makeCanonical(SmallVectorImpl<char> &Path) const {
1927fc51490bSJonas Devlieghere   if (std::error_code EC = makeAbsolute(Path))
1928fc51490bSJonas Devlieghere     return EC;
1929fc51490bSJonas Devlieghere 
19300be9ca7cSJonas Devlieghere   llvm::SmallString<256> CanonicalPath =
19310be9ca7cSJonas Devlieghere       canonicalize(StringRef(Path.data(), Path.size()));
19320be9ca7cSJonas Devlieghere   if (CanonicalPath.empty())
1933fc51490bSJonas Devlieghere     return make_error_code(llvm::errc::invalid_argument);
1934fc51490bSJonas Devlieghere 
19350be9ca7cSJonas Devlieghere   Path.assign(CanonicalPath.begin(), CanonicalPath.end());
19360be9ca7cSJonas Devlieghere   return {};
19370be9ca7cSJonas Devlieghere }
19380be9ca7cSJonas Devlieghere 
1939ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult>
19400be9ca7cSJonas Devlieghere RedirectingFileSystem::lookupPath(StringRef Path) const {
1941fc51490bSJonas Devlieghere   sys::path::const_iterator Start = sys::path::begin(Path);
1942fc51490bSJonas Devlieghere   sys::path::const_iterator End = sys::path::end(Path);
1943fc51490bSJonas Devlieghere   for (const auto &Root : Roots) {
1944ecb00a77SNathan Hawes     ErrorOr<RedirectingFileSystem::LookupResult> Result =
1945ecb00a77SNathan Hawes         lookupPathImpl(Start, End, Root.get());
1946fc51490bSJonas Devlieghere     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1947fc51490bSJonas Devlieghere       return Result;
1948fc51490bSJonas Devlieghere   }
1949fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
1950fc51490bSJonas Devlieghere }
1951fc51490bSJonas Devlieghere 
1952ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult>
1953ecb00a77SNathan Hawes RedirectingFileSystem::lookupPathImpl(
1954ecb00a77SNathan Hawes     sys::path::const_iterator Start, sys::path::const_iterator End,
19551a0ce65aSJonas Devlieghere     RedirectingFileSystem::Entry *From) const {
1956fc51490bSJonas Devlieghere   assert(!isTraversalComponent(*Start) &&
1957fc51490bSJonas Devlieghere          !isTraversalComponent(From->getName()) &&
1958fc51490bSJonas Devlieghere          "Paths should not contain traversal components");
1959fc51490bSJonas Devlieghere 
1960fc51490bSJonas Devlieghere   StringRef FromName = From->getName();
1961fc51490bSJonas Devlieghere 
1962fc51490bSJonas Devlieghere   // Forward the search to the next component in case this is an empty one.
1963fc51490bSJonas Devlieghere   if (!FromName.empty()) {
19641275ab16SAdrian McCarthy     if (!pathComponentMatches(*Start, FromName))
1965fc51490bSJonas Devlieghere       return make_error_code(llvm::errc::no_such_file_or_directory);
1966fc51490bSJonas Devlieghere 
1967fc51490bSJonas Devlieghere     ++Start;
1968fc51490bSJonas Devlieghere 
1969fc51490bSJonas Devlieghere     if (Start == End) {
1970fc51490bSJonas Devlieghere       // Match!
1971ecb00a77SNathan Hawes       return LookupResult(From, Start, End);
1972fc51490bSJonas Devlieghere     }
1973fc51490bSJonas Devlieghere   }
1974fc51490bSJonas Devlieghere 
1975ecb00a77SNathan Hawes   if (isa<RedirectingFileSystem::FileEntry>(From))
1976fc51490bSJonas Devlieghere     return make_error_code(llvm::errc::not_a_directory);
1977fc51490bSJonas Devlieghere 
1978ecb00a77SNathan Hawes   if (isa<RedirectingFileSystem::DirectoryRemapEntry>(From))
1979ecb00a77SNathan Hawes     return LookupResult(From, Start, End);
1980ecb00a77SNathan Hawes 
1981ecb00a77SNathan Hawes   auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(From);
19821a0ce65aSJonas Devlieghere   for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
1983fc51490bSJonas Devlieghere        llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1984ecb00a77SNathan Hawes     ErrorOr<RedirectingFileSystem::LookupResult> Result =
1985ecb00a77SNathan Hawes         lookupPathImpl(Start, End, DirEntry.get());
1986fc51490bSJonas Devlieghere     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1987fc51490bSJonas Devlieghere       return Result;
1988fc51490bSJonas Devlieghere   }
19891275ab16SAdrian McCarthy 
1990fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
1991fc51490bSJonas Devlieghere }
1992fc51490bSJonas Devlieghere 
199386e2af80SKeith Smiley static Status getRedirectedFileStatus(const Twine &OriginalPath,
199486e2af80SKeith Smiley                                       bool UseExternalNames,
1995fc51490bSJonas Devlieghere                                       Status ExternalStatus) {
1996fc51490bSJonas Devlieghere   Status S = ExternalStatus;
1997fc51490bSJonas Devlieghere   if (!UseExternalNames)
199886e2af80SKeith Smiley     S = Status::copyWithNewName(S, OriginalPath);
1999fc51490bSJonas Devlieghere   S.IsVFSMapped = true;
2000fc51490bSJonas Devlieghere   return S;
2001fc51490bSJonas Devlieghere }
2002fc51490bSJonas Devlieghere 
2003ecb00a77SNathan Hawes ErrorOr<Status> RedirectingFileSystem::status(
200486e2af80SKeith Smiley     const Twine &CanonicalPath, const Twine &OriginalPath,
200586e2af80SKeith Smiley     const RedirectingFileSystem::LookupResult &Result) {
2006ecb00a77SNathan Hawes   if (Optional<StringRef> ExtRedirect = Result.getExternalRedirect()) {
200786e2af80SKeith Smiley     SmallString<256> CanonicalRemappedPath((*ExtRedirect).str());
200886e2af80SKeith Smiley     if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
200986e2af80SKeith Smiley       return EC;
201086e2af80SKeith Smiley 
201186e2af80SKeith Smiley     ErrorOr<Status> S = ExternalFS->status(CanonicalRemappedPath);
2012ecb00a77SNathan Hawes     if (!S)
2013fc51490bSJonas Devlieghere       return S;
201486e2af80SKeith Smiley     S = Status::copyWithNewName(*S, *ExtRedirect);
2015ecb00a77SNathan Hawes     auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result.E);
201686e2af80SKeith Smiley     return getRedirectedFileStatus(OriginalPath,
201786e2af80SKeith Smiley                                    RE->useExternalName(UseExternalNames), *S);
2018fc51490bSJonas Devlieghere   }
2019ecb00a77SNathan Hawes 
2020ecb00a77SNathan Hawes   auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Result.E);
202186e2af80SKeith Smiley   return Status::copyWithNewName(DE->getStatus(), CanonicalPath);
2022fc51490bSJonas Devlieghere }
2023fc51490bSJonas Devlieghere 
202486e2af80SKeith Smiley ErrorOr<Status>
202586e2af80SKeith Smiley RedirectingFileSystem::getExternalStatus(const Twine &CanonicalPath,
202686e2af80SKeith Smiley                                          const Twine &OriginalPath) const {
202786e2af80SKeith Smiley   if (auto Result = ExternalFS->status(CanonicalPath)) {
202886e2af80SKeith Smiley     return Result.get().copyWithNewName(Result.get(), OriginalPath);
202986e2af80SKeith Smiley   } else {
203086e2af80SKeith Smiley     return Result.getError();
203186e2af80SKeith Smiley   }
203286e2af80SKeith Smiley }
20330be9ca7cSJonas Devlieghere 
203486e2af80SKeith Smiley ErrorOr<Status> RedirectingFileSystem::status(const Twine &OriginalPath) {
203586e2af80SKeith Smiley   SmallString<256> CanonicalPath;
203686e2af80SKeith Smiley   OriginalPath.toVector(CanonicalPath);
203786e2af80SKeith Smiley 
203886e2af80SKeith Smiley   if (std::error_code EC = makeCanonical(CanonicalPath))
20390be9ca7cSJonas Devlieghere     return EC;
20400be9ca7cSJonas Devlieghere 
204186e2af80SKeith Smiley   ErrorOr<RedirectingFileSystem::LookupResult> Result =
204286e2af80SKeith Smiley       lookupPath(CanonicalPath);
204391e13164SVolodymyr Sapsai   if (!Result) {
204486e2af80SKeith Smiley     if (shouldFallBackToExternalFS(Result.getError())) {
204586e2af80SKeith Smiley       return getExternalStatus(CanonicalPath, OriginalPath);
204686e2af80SKeith Smiley     }
2047fc51490bSJonas Devlieghere     return Result.getError();
204891e13164SVolodymyr Sapsai   }
2049ecb00a77SNathan Hawes 
205086e2af80SKeith Smiley   ErrorOr<Status> S = status(CanonicalPath, OriginalPath, *Result);
205186e2af80SKeith Smiley   if (!S && shouldFallBackToExternalFS(S.getError(), Result->E)) {
205286e2af80SKeith Smiley     return getExternalStatus(CanonicalPath, OriginalPath);
205386e2af80SKeith Smiley   }
205486e2af80SKeith Smiley 
2055ecb00a77SNathan Hawes   return S;
2056fc51490bSJonas Devlieghere }
2057fc51490bSJonas Devlieghere 
2058fc51490bSJonas Devlieghere namespace {
2059fc51490bSJonas Devlieghere 
2060fc51490bSJonas Devlieghere /// Provide a file wrapper with an overriden status.
2061fc51490bSJonas Devlieghere class FileWithFixedStatus : public File {
2062fc51490bSJonas Devlieghere   std::unique_ptr<File> InnerFile;
2063fc51490bSJonas Devlieghere   Status S;
2064fc51490bSJonas Devlieghere 
2065fc51490bSJonas Devlieghere public:
2066fc51490bSJonas Devlieghere   FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
2067fc51490bSJonas Devlieghere       : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
2068fc51490bSJonas Devlieghere 
2069fc51490bSJonas Devlieghere   ErrorOr<Status> status() override { return S; }
2070fc51490bSJonas Devlieghere   ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2071fc51490bSJonas Devlieghere 
2072fc51490bSJonas Devlieghere   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
2073fc51490bSJonas Devlieghere             bool IsVolatile) override {
2074fc51490bSJonas Devlieghere     return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
2075fc51490bSJonas Devlieghere                                 IsVolatile);
2076fc51490bSJonas Devlieghere   }
2077fc51490bSJonas Devlieghere 
2078fc51490bSJonas Devlieghere   std::error_code close() override { return InnerFile->close(); }
207986e2af80SKeith Smiley 
208086e2af80SKeith Smiley   void setPath(const Twine &Path) override { S = S.copyWithNewName(S, Path); }
2081fc51490bSJonas Devlieghere };
2082fc51490bSJonas Devlieghere 
2083fc51490bSJonas Devlieghere } // namespace
2084fc51490bSJonas Devlieghere 
2085fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
208686e2af80SKeith Smiley File::getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P) {
208786e2af80SKeith Smiley   if (!Result)
208886e2af80SKeith Smiley     return Result;
20890be9ca7cSJonas Devlieghere 
209086e2af80SKeith Smiley   ErrorOr<std::unique_ptr<File>> F = std::move(*Result);
209186e2af80SKeith Smiley   auto Name = F->get()->getName();
209286e2af80SKeith Smiley   if (Name && Name.get() != P.str())
209386e2af80SKeith Smiley     F->get()->setPath(P);
209486e2af80SKeith Smiley   return F;
209586e2af80SKeith Smiley }
209686e2af80SKeith Smiley 
209786e2af80SKeith Smiley ErrorOr<std::unique_ptr<File>>
209886e2af80SKeith Smiley RedirectingFileSystem::openFileForRead(const Twine &OriginalPath) {
209986e2af80SKeith Smiley   SmallString<256> CanonicalPath;
210086e2af80SKeith Smiley   OriginalPath.toVector(CanonicalPath);
210186e2af80SKeith Smiley 
210286e2af80SKeith Smiley   if (std::error_code EC = makeCanonical(CanonicalPath))
21030be9ca7cSJonas Devlieghere     return EC;
21040be9ca7cSJonas Devlieghere 
210586e2af80SKeith Smiley   ErrorOr<RedirectingFileSystem::LookupResult> Result =
210686e2af80SKeith Smiley       lookupPath(CanonicalPath);
2107ecb00a77SNathan Hawes   if (!Result) {
2108ecb00a77SNathan Hawes     if (shouldFallBackToExternalFS(Result.getError()))
210986e2af80SKeith Smiley       return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
211086e2af80SKeith Smiley                                OriginalPath);
211186e2af80SKeith Smiley 
2112ecb00a77SNathan Hawes     return Result.getError();
211391e13164SVolodymyr Sapsai   }
2114fc51490bSJonas Devlieghere 
2115ecb00a77SNathan Hawes   if (!Result->getExternalRedirect()) // FIXME: errc::not_a_file?
2116fc51490bSJonas Devlieghere     return make_error_code(llvm::errc::invalid_argument);
2117fc51490bSJonas Devlieghere 
2118ecb00a77SNathan Hawes   StringRef ExtRedirect = *Result->getExternalRedirect();
211986e2af80SKeith Smiley   SmallString<256> CanonicalRemappedPath(ExtRedirect.str());
212086e2af80SKeith Smiley   if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
212186e2af80SKeith Smiley     return EC;
212286e2af80SKeith Smiley 
2123ecb00a77SNathan Hawes   auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
2124fc51490bSJonas Devlieghere 
212586e2af80SKeith Smiley   auto ExternalFile = File::getWithPath(
212686e2af80SKeith Smiley       ExternalFS->openFileForRead(CanonicalRemappedPath), ExtRedirect);
2127ecb00a77SNathan Hawes   if (!ExternalFile) {
2128ecb00a77SNathan Hawes     if (shouldFallBackToExternalFS(ExternalFile.getError(), Result->E))
212986e2af80SKeith Smiley       return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
213086e2af80SKeith Smiley                                OriginalPath);
2131ecb00a77SNathan Hawes     return ExternalFile;
2132ecb00a77SNathan Hawes   }
2133ecb00a77SNathan Hawes 
2134ecb00a77SNathan Hawes   auto ExternalStatus = (*ExternalFile)->status();
2135fc51490bSJonas Devlieghere   if (!ExternalStatus)
2136fc51490bSJonas Devlieghere     return ExternalStatus.getError();
2137fc51490bSJonas Devlieghere 
2138fc51490bSJonas Devlieghere   // FIXME: Update the status with the name and VFSMapped.
2139ecb00a77SNathan Hawes   Status S = getRedirectedFileStatus(
214086e2af80SKeith Smiley       OriginalPath, RE->useExternalName(UseExternalNames), *ExternalStatus);
2141fc51490bSJonas Devlieghere   return std::unique_ptr<File>(
2142ecb00a77SNathan Hawes       std::make_unique<FileWithFixedStatus>(std::move(*ExternalFile), S));
2143fc51490bSJonas Devlieghere }
2144fc51490bSJonas Devlieghere 
21457610033fSVolodymyr Sapsai std::error_code
21460be9ca7cSJonas Devlieghere RedirectingFileSystem::getRealPath(const Twine &Path_,
21477610033fSVolodymyr Sapsai                                    SmallVectorImpl<char> &Output) const {
21480be9ca7cSJonas Devlieghere   SmallString<256> Path;
21490be9ca7cSJonas Devlieghere   Path_.toVector(Path);
21500be9ca7cSJonas Devlieghere 
21510be9ca7cSJonas Devlieghere   if (std::error_code EC = makeCanonical(Path))
21520be9ca7cSJonas Devlieghere     return EC;
21530be9ca7cSJonas Devlieghere 
2154ecb00a77SNathan Hawes   ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
21557610033fSVolodymyr Sapsai   if (!Result) {
2156719f7784SNathan Hawes     if (shouldFallBackToExternalFS(Result.getError()))
21577610033fSVolodymyr Sapsai       return ExternalFS->getRealPath(Path, Output);
21587610033fSVolodymyr Sapsai     return Result.getError();
21597610033fSVolodymyr Sapsai   }
21607610033fSVolodymyr Sapsai 
2161ecb00a77SNathan Hawes   // If we found FileEntry or DirectoryRemapEntry, look up the mapped
2162ecb00a77SNathan Hawes   // path in the external file system.
2163ecb00a77SNathan Hawes   if (auto ExtRedirect = Result->getExternalRedirect()) {
2164ecb00a77SNathan Hawes     auto P = ExternalFS->getRealPath(*ExtRedirect, Output);
2165ecb00a77SNathan Hawes     if (!P && shouldFallBackToExternalFS(P, Result->E)) {
2166ecb00a77SNathan Hawes       return ExternalFS->getRealPath(Path, Output);
21677610033fSVolodymyr Sapsai     }
2168ecb00a77SNathan Hawes     return P;
2169ecb00a77SNathan Hawes   }
2170ecb00a77SNathan Hawes 
2171ecb00a77SNathan Hawes   // If we found a DirectoryEntry, still fall back to ExternalFS if allowed,
21727610033fSVolodymyr Sapsai   // because directories don't have a single external contents path.
217321703543SJonas Devlieghere   return shouldUseExternalFS() ? ExternalFS->getRealPath(Path, Output)
21747610033fSVolodymyr Sapsai                                : llvm::errc::invalid_argument;
21757610033fSVolodymyr Sapsai }
21767610033fSVolodymyr Sapsai 
2177a22eda54SDuncan P. N. Exon Smith std::unique_ptr<FileSystem>
2178fc51490bSJonas Devlieghere vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2179fc51490bSJonas Devlieghere                     SourceMgr::DiagHandlerTy DiagHandler,
2180fc51490bSJonas Devlieghere                     StringRef YAMLFilePath, void *DiagContext,
2181fc51490bSJonas Devlieghere                     IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2182fc51490bSJonas Devlieghere   return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
2183fc51490bSJonas Devlieghere                                        YAMLFilePath, DiagContext,
2184fc51490bSJonas Devlieghere                                        std::move(ExternalFS));
2185fc51490bSJonas Devlieghere }
2186fc51490bSJonas Devlieghere 
21871a0ce65aSJonas Devlieghere static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
21881a0ce65aSJonas Devlieghere                           SmallVectorImpl<StringRef> &Path,
2189fc51490bSJonas Devlieghere                           SmallVectorImpl<YAMLVFSEntry> &Entries) {
2190fc51490bSJonas Devlieghere   auto Kind = SrcE->getKind();
21911a0ce65aSJonas Devlieghere   if (Kind == RedirectingFileSystem::EK_Directory) {
2192719f7784SNathan Hawes     auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
2193fc51490bSJonas Devlieghere     assert(DE && "Must be a directory");
21941a0ce65aSJonas Devlieghere     for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
2195fc51490bSJonas Devlieghere          llvm::make_range(DE->contents_begin(), DE->contents_end())) {
2196fc51490bSJonas Devlieghere       Path.push_back(SubEntry->getName());
2197fc51490bSJonas Devlieghere       getVFSEntries(SubEntry.get(), Path, Entries);
2198fc51490bSJonas Devlieghere       Path.pop_back();
2199fc51490bSJonas Devlieghere     }
2200fc51490bSJonas Devlieghere     return;
2201fc51490bSJonas Devlieghere   }
2202fc51490bSJonas Devlieghere 
2203ecb00a77SNathan Hawes   if (Kind == RedirectingFileSystem::EK_DirectoryRemap) {
2204ecb00a77SNathan Hawes     auto *DR = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
2205ecb00a77SNathan Hawes     assert(DR && "Must be a directory remap");
2206ecb00a77SNathan Hawes     SmallString<128> VPath;
2207ecb00a77SNathan Hawes     for (auto &Comp : Path)
2208ecb00a77SNathan Hawes       llvm::sys::path::append(VPath, Comp);
2209ecb00a77SNathan Hawes     Entries.push_back(
2210ecb00a77SNathan Hawes         YAMLVFSEntry(VPath.c_str(), DR->getExternalContentsPath()));
2211ecb00a77SNathan Hawes     return;
2212ecb00a77SNathan Hawes   }
2213ecb00a77SNathan Hawes 
22141a0ce65aSJonas Devlieghere   assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
2215719f7784SNathan Hawes   auto *FE = dyn_cast<RedirectingFileSystem::FileEntry>(SrcE);
2216fc51490bSJonas Devlieghere   assert(FE && "Must be a file");
2217fc51490bSJonas Devlieghere   SmallString<128> VPath;
2218fc51490bSJonas Devlieghere   for (auto &Comp : Path)
2219fc51490bSJonas Devlieghere     llvm::sys::path::append(VPath, Comp);
2220fc51490bSJonas Devlieghere   Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
2221fc51490bSJonas Devlieghere }
2222fc51490bSJonas Devlieghere 
2223fc51490bSJonas Devlieghere void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2224fc51490bSJonas Devlieghere                              SourceMgr::DiagHandlerTy DiagHandler,
2225fc51490bSJonas Devlieghere                              StringRef YAMLFilePath,
2226fc51490bSJonas Devlieghere                              SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
2227fc51490bSJonas Devlieghere                              void *DiagContext,
2228fc51490bSJonas Devlieghere                              IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2229a22eda54SDuncan P. N. Exon Smith   std::unique_ptr<RedirectingFileSystem> VFS = RedirectingFileSystem::create(
2230fc51490bSJonas Devlieghere       std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
2231fc51490bSJonas Devlieghere       std::move(ExternalFS));
22322509f9fbSAlex Lorenz   if (!VFS)
22332509f9fbSAlex Lorenz     return;
2234ecb00a77SNathan Hawes   ErrorOr<RedirectingFileSystem::LookupResult> RootResult =
2235ecb00a77SNathan Hawes       VFS->lookupPath("/");
2236ecb00a77SNathan Hawes   if (!RootResult)
2237fc51490bSJonas Devlieghere     return;
2238fc51490bSJonas Devlieghere   SmallVector<StringRef, 8> Components;
2239fc51490bSJonas Devlieghere   Components.push_back("/");
2240ecb00a77SNathan Hawes   getVFSEntries(RootResult->E, Components, CollectedEntries);
2241fc51490bSJonas Devlieghere }
2242fc51490bSJonas Devlieghere 
2243fc51490bSJonas Devlieghere UniqueID vfs::getNextVirtualUniqueID() {
2244fc51490bSJonas Devlieghere   static std::atomic<unsigned> UID;
2245fc51490bSJonas Devlieghere   unsigned ID = ++UID;
2246fc51490bSJonas Devlieghere   // The following assumes that uint64_t max will never collide with a real
2247fc51490bSJonas Devlieghere   // dev_t value from the OS.
2248fc51490bSJonas Devlieghere   return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
2249fc51490bSJonas Devlieghere }
2250fc51490bSJonas Devlieghere 
22513ef33e69SJonas Devlieghere void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath,
22523ef33e69SJonas Devlieghere                              bool IsDirectory) {
2253fc51490bSJonas Devlieghere   assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
2254fc51490bSJonas Devlieghere   assert(sys::path::is_absolute(RealPath) && "real path not absolute");
2255fc51490bSJonas Devlieghere   assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
22563ef33e69SJonas Devlieghere   Mappings.emplace_back(VirtualPath, RealPath, IsDirectory);
22573ef33e69SJonas Devlieghere }
22583ef33e69SJonas Devlieghere 
22593ef33e69SJonas Devlieghere void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
22603ef33e69SJonas Devlieghere   addEntry(VirtualPath, RealPath, /*IsDirectory=*/false);
22613ef33e69SJonas Devlieghere }
22623ef33e69SJonas Devlieghere 
22633ef33e69SJonas Devlieghere void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath,
22643ef33e69SJonas Devlieghere                                         StringRef RealPath) {
22653ef33e69SJonas Devlieghere   addEntry(VirtualPath, RealPath, /*IsDirectory=*/true);
2266fc51490bSJonas Devlieghere }
2267fc51490bSJonas Devlieghere 
2268fc51490bSJonas Devlieghere namespace {
2269fc51490bSJonas Devlieghere 
2270fc51490bSJonas Devlieghere class JSONWriter {
2271fc51490bSJonas Devlieghere   llvm::raw_ostream &OS;
2272fc51490bSJonas Devlieghere   SmallVector<StringRef, 16> DirStack;
2273fc51490bSJonas Devlieghere 
2274fc51490bSJonas Devlieghere   unsigned getDirIndent() { return 4 * DirStack.size(); }
2275fc51490bSJonas Devlieghere   unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
2276fc51490bSJonas Devlieghere   bool containedIn(StringRef Parent, StringRef Path);
2277fc51490bSJonas Devlieghere   StringRef containedPart(StringRef Parent, StringRef Path);
2278fc51490bSJonas Devlieghere   void startDirectory(StringRef Path);
2279fc51490bSJonas Devlieghere   void endDirectory();
2280fc51490bSJonas Devlieghere   void writeEntry(StringRef VPath, StringRef RPath);
2281fc51490bSJonas Devlieghere 
2282fc51490bSJonas Devlieghere public:
2283fc51490bSJonas Devlieghere   JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
2284fc51490bSJonas Devlieghere 
2285fc51490bSJonas Devlieghere   void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
2286fc51490bSJonas Devlieghere              Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
22877faf7ae0SVolodymyr Sapsai              StringRef OverlayDir);
2288fc51490bSJonas Devlieghere };
2289fc51490bSJonas Devlieghere 
2290fc51490bSJonas Devlieghere } // namespace
2291fc51490bSJonas Devlieghere 
2292fc51490bSJonas Devlieghere bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2293fc51490bSJonas Devlieghere   using namespace llvm::sys;
2294fc51490bSJonas Devlieghere 
2295fc51490bSJonas Devlieghere   // Compare each path component.
2296fc51490bSJonas Devlieghere   auto IParent = path::begin(Parent), EParent = path::end(Parent);
2297fc51490bSJonas Devlieghere   for (auto IChild = path::begin(Path), EChild = path::end(Path);
2298fc51490bSJonas Devlieghere        IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2299fc51490bSJonas Devlieghere     if (*IParent != *IChild)
2300fc51490bSJonas Devlieghere       return false;
2301fc51490bSJonas Devlieghere   }
2302fc51490bSJonas Devlieghere   // Have we exhausted the parent path?
2303fc51490bSJonas Devlieghere   return IParent == EParent;
2304fc51490bSJonas Devlieghere }
2305fc51490bSJonas Devlieghere 
2306fc51490bSJonas Devlieghere StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2307fc51490bSJonas Devlieghere   assert(!Parent.empty());
2308fc51490bSJonas Devlieghere   assert(containedIn(Parent, Path));
2309fc51490bSJonas Devlieghere   return Path.slice(Parent.size() + 1, StringRef::npos);
2310fc51490bSJonas Devlieghere }
2311fc51490bSJonas Devlieghere 
2312fc51490bSJonas Devlieghere void JSONWriter::startDirectory(StringRef Path) {
2313fc51490bSJonas Devlieghere   StringRef Name =
2314fc51490bSJonas Devlieghere       DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
2315fc51490bSJonas Devlieghere   DirStack.push_back(Path);
2316fc51490bSJonas Devlieghere   unsigned Indent = getDirIndent();
2317fc51490bSJonas Devlieghere   OS.indent(Indent) << "{\n";
2318fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'type': 'directory',\n";
2319fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
2320fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'contents': [\n";
2321fc51490bSJonas Devlieghere }
2322fc51490bSJonas Devlieghere 
2323fc51490bSJonas Devlieghere void JSONWriter::endDirectory() {
2324fc51490bSJonas Devlieghere   unsigned Indent = getDirIndent();
2325fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "]\n";
2326fc51490bSJonas Devlieghere   OS.indent(Indent) << "}";
2327fc51490bSJonas Devlieghere 
2328fc51490bSJonas Devlieghere   DirStack.pop_back();
2329fc51490bSJonas Devlieghere }
2330fc51490bSJonas Devlieghere 
2331fc51490bSJonas Devlieghere void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2332fc51490bSJonas Devlieghere   unsigned Indent = getFileIndent();
2333fc51490bSJonas Devlieghere   OS.indent(Indent) << "{\n";
2334fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'type': 'file',\n";
2335fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
2336fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'external-contents': \""
2337fc51490bSJonas Devlieghere                         << llvm::yaml::escape(RPath) << "\"\n";
2338fc51490bSJonas Devlieghere   OS.indent(Indent) << "}";
2339fc51490bSJonas Devlieghere }
2340fc51490bSJonas Devlieghere 
2341fc51490bSJonas Devlieghere void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
2342fc51490bSJonas Devlieghere                        Optional<bool> UseExternalNames,
2343fc51490bSJonas Devlieghere                        Optional<bool> IsCaseSensitive,
2344fc51490bSJonas Devlieghere                        Optional<bool> IsOverlayRelative,
2345fc51490bSJonas Devlieghere                        StringRef OverlayDir) {
2346fc51490bSJonas Devlieghere   using namespace llvm::sys;
2347fc51490bSJonas Devlieghere 
2348fc51490bSJonas Devlieghere   OS << "{\n"
2349fc51490bSJonas Devlieghere         "  'version': 0,\n";
2350fc51490bSJonas Devlieghere   if (IsCaseSensitive.hasValue())
2351fc51490bSJonas Devlieghere     OS << "  'case-sensitive': '"
2352fc51490bSJonas Devlieghere        << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
2353fc51490bSJonas Devlieghere   if (UseExternalNames.hasValue())
2354fc51490bSJonas Devlieghere     OS << "  'use-external-names': '"
2355fc51490bSJonas Devlieghere        << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
2356fc51490bSJonas Devlieghere   bool UseOverlayRelative = false;
2357fc51490bSJonas Devlieghere   if (IsOverlayRelative.hasValue()) {
2358fc51490bSJonas Devlieghere     UseOverlayRelative = IsOverlayRelative.getValue();
2359fc51490bSJonas Devlieghere     OS << "  'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2360fc51490bSJonas Devlieghere        << "',\n";
2361fc51490bSJonas Devlieghere   }
2362fc51490bSJonas Devlieghere   OS << "  'roots': [\n";
2363fc51490bSJonas Devlieghere 
2364fc51490bSJonas Devlieghere   if (!Entries.empty()) {
2365fc51490bSJonas Devlieghere     const YAMLVFSEntry &Entry = Entries.front();
2366759465eeSJan Korous 
2367759465eeSJan Korous     startDirectory(
2368759465eeSJan Korous       Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath)
2369759465eeSJan Korous     );
2370fc51490bSJonas Devlieghere 
2371fc51490bSJonas Devlieghere     StringRef RPath = Entry.RPath;
2372fc51490bSJonas Devlieghere     if (UseOverlayRelative) {
2373fc51490bSJonas Devlieghere       unsigned OverlayDirLen = OverlayDir.size();
2374fc51490bSJonas Devlieghere       assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2375fc51490bSJonas Devlieghere              "Overlay dir must be contained in RPath");
2376fc51490bSJonas Devlieghere       RPath = RPath.slice(OverlayDirLen, RPath.size());
2377fc51490bSJonas Devlieghere     }
2378fc51490bSJonas Devlieghere 
2379759465eeSJan Korous     bool IsCurrentDirEmpty = true;
2380759465eeSJan Korous     if (!Entry.IsDirectory) {
2381fc51490bSJonas Devlieghere       writeEntry(path::filename(Entry.VPath), RPath);
2382759465eeSJan Korous       IsCurrentDirEmpty = false;
2383759465eeSJan Korous     }
2384fc51490bSJonas Devlieghere 
2385fc51490bSJonas Devlieghere     for (const auto &Entry : Entries.slice(1)) {
23863ef33e69SJonas Devlieghere       StringRef Dir =
23873ef33e69SJonas Devlieghere           Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath);
23883ef33e69SJonas Devlieghere       if (Dir == DirStack.back()) {
2389759465eeSJan Korous         if (!IsCurrentDirEmpty) {
2390fc51490bSJonas Devlieghere           OS << ",\n";
23913ef33e69SJonas Devlieghere         }
23923ef33e69SJonas Devlieghere       } else {
2393759465eeSJan Korous         bool IsDirPoppedFromStack = false;
2394fc51490bSJonas Devlieghere         while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2395fc51490bSJonas Devlieghere           OS << "\n";
2396fc51490bSJonas Devlieghere           endDirectory();
2397759465eeSJan Korous           IsDirPoppedFromStack = true;
2398fc51490bSJonas Devlieghere         }
2399759465eeSJan Korous         if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
2400fc51490bSJonas Devlieghere           OS << ",\n";
2401759465eeSJan Korous         }
2402fc51490bSJonas Devlieghere         startDirectory(Dir);
2403759465eeSJan Korous         IsCurrentDirEmpty = true;
2404fc51490bSJonas Devlieghere       }
2405fc51490bSJonas Devlieghere       StringRef RPath = Entry.RPath;
2406fc51490bSJonas Devlieghere       if (UseOverlayRelative) {
2407fc51490bSJonas Devlieghere         unsigned OverlayDirLen = OverlayDir.size();
2408fc51490bSJonas Devlieghere         assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2409fc51490bSJonas Devlieghere                "Overlay dir must be contained in RPath");
2410fc51490bSJonas Devlieghere         RPath = RPath.slice(OverlayDirLen, RPath.size());
2411fc51490bSJonas Devlieghere       }
2412759465eeSJan Korous       if (!Entry.IsDirectory) {
2413fc51490bSJonas Devlieghere         writeEntry(path::filename(Entry.VPath), RPath);
2414759465eeSJan Korous         IsCurrentDirEmpty = false;
2415759465eeSJan Korous       }
2416fc51490bSJonas Devlieghere     }
2417fc51490bSJonas Devlieghere 
2418fc51490bSJonas Devlieghere     while (!DirStack.empty()) {
2419fc51490bSJonas Devlieghere       OS << "\n";
2420fc51490bSJonas Devlieghere       endDirectory();
2421fc51490bSJonas Devlieghere     }
2422fc51490bSJonas Devlieghere     OS << "\n";
2423fc51490bSJonas Devlieghere   }
2424fc51490bSJonas Devlieghere 
2425fc51490bSJonas Devlieghere   OS << "  ]\n"
2426fc51490bSJonas Devlieghere      << "}\n";
2427fc51490bSJonas Devlieghere }
2428fc51490bSJonas Devlieghere 
2429fc51490bSJonas Devlieghere void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2430fc51490bSJonas Devlieghere   llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2431fc51490bSJonas Devlieghere     return LHS.VPath < RHS.VPath;
2432fc51490bSJonas Devlieghere   });
2433fc51490bSJonas Devlieghere 
2434fc51490bSJonas Devlieghere   JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
24357faf7ae0SVolodymyr Sapsai                        IsOverlayRelative, OverlayDir);
2436fc51490bSJonas Devlieghere }
2437fc51490bSJonas Devlieghere 
2438fc51490bSJonas Devlieghere vfs::recursive_directory_iterator::recursive_directory_iterator(
2439fc51490bSJonas Devlieghere     FileSystem &FS_, const Twine &Path, std::error_code &EC)
2440fc51490bSJonas Devlieghere     : FS(&FS_) {
2441fc51490bSJonas Devlieghere   directory_iterator I = FS->dir_begin(Path, EC);
2442fc51490bSJonas Devlieghere   if (I != directory_iterator()) {
244341fb951fSJonas Devlieghere     State = std::make_shared<detail::RecDirIterState>();
244441fb951fSJonas Devlieghere     State->Stack.push(I);
2445fc51490bSJonas Devlieghere   }
2446fc51490bSJonas Devlieghere }
2447fc51490bSJonas Devlieghere 
2448fc51490bSJonas Devlieghere vfs::recursive_directory_iterator &
2449fc51490bSJonas Devlieghere recursive_directory_iterator::increment(std::error_code &EC) {
245041fb951fSJonas Devlieghere   assert(FS && State && !State->Stack.empty() && "incrementing past end");
245141fb951fSJonas Devlieghere   assert(!State->Stack.top()->path().empty() && "non-canonical end iterator");
2452fc51490bSJonas Devlieghere   vfs::directory_iterator End;
245341fb951fSJonas Devlieghere 
245441fb951fSJonas Devlieghere   if (State->HasNoPushRequest)
245541fb951fSJonas Devlieghere     State->HasNoPushRequest = false;
245641fb951fSJonas Devlieghere   else {
245741fb951fSJonas Devlieghere     if (State->Stack.top()->type() == sys::fs::file_type::directory_file) {
245841fb951fSJonas Devlieghere       vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC);
2459fc51490bSJonas Devlieghere       if (I != End) {
246041fb951fSJonas Devlieghere         State->Stack.push(I);
2461fc51490bSJonas Devlieghere         return *this;
2462fc51490bSJonas Devlieghere       }
2463fc51490bSJonas Devlieghere     }
246441fb951fSJonas Devlieghere   }
2465fc51490bSJonas Devlieghere 
246641fb951fSJonas Devlieghere   while (!State->Stack.empty() && State->Stack.top().increment(EC) == End)
246741fb951fSJonas Devlieghere     State->Stack.pop();
2468fc51490bSJonas Devlieghere 
246941fb951fSJonas Devlieghere   if (State->Stack.empty())
2470fc51490bSJonas Devlieghere     State.reset(); // end iterator
2471fc51490bSJonas Devlieghere 
2472fc51490bSJonas Devlieghere   return *this;
2473fc51490bSJonas Devlieghere }
2474