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 
78e7b94649SDuncan P. N. Exon Smith Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
79fc51490bSJonas Devlieghere   return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
80fc51490bSJonas Devlieghere                 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
81fc51490bSJonas Devlieghere                 In.getPermissions());
82fc51490bSJonas Devlieghere }
83fc51490bSJonas Devlieghere 
84e7b94649SDuncan P. N. Exon Smith Status Status::copyWithNewName(const file_status &In, const Twine &NewName) {
85fc51490bSJonas Devlieghere   return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
86fc51490bSJonas Devlieghere                 In.getUser(), In.getGroup(), In.getSize(), In.type(),
87fc51490bSJonas Devlieghere                 In.permissions());
88fc51490bSJonas Devlieghere }
89fc51490bSJonas Devlieghere 
90fc51490bSJonas Devlieghere bool Status::equivalent(const Status &Other) const {
91fc51490bSJonas Devlieghere   assert(isStatusKnown() && Other.isStatusKnown());
92fc51490bSJonas Devlieghere   return getUniqueID() == Other.getUniqueID();
93fc51490bSJonas Devlieghere }
94fc51490bSJonas Devlieghere 
95fc51490bSJonas Devlieghere bool Status::isDirectory() const { return Type == file_type::directory_file; }
96fc51490bSJonas Devlieghere 
97fc51490bSJonas Devlieghere bool Status::isRegularFile() const { return Type == file_type::regular_file; }
98fc51490bSJonas Devlieghere 
99fc51490bSJonas Devlieghere bool Status::isOther() const {
100fc51490bSJonas Devlieghere   return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
101fc51490bSJonas Devlieghere }
102fc51490bSJonas Devlieghere 
103fc51490bSJonas Devlieghere bool Status::isSymlink() const { return Type == file_type::symlink_file; }
104fc51490bSJonas Devlieghere 
105fc51490bSJonas Devlieghere bool Status::isStatusKnown() const { return Type != file_type::status_error; }
106fc51490bSJonas Devlieghere 
107fc51490bSJonas Devlieghere bool Status::exists() const {
108fc51490bSJonas Devlieghere   return isStatusKnown() && Type != file_type::file_not_found;
109fc51490bSJonas Devlieghere }
110fc51490bSJonas Devlieghere 
111fc51490bSJonas Devlieghere File::~File() = default;
112fc51490bSJonas Devlieghere 
113fc51490bSJonas Devlieghere FileSystem::~FileSystem() = default;
114fc51490bSJonas Devlieghere 
115fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<MemoryBuffer>>
116fc51490bSJonas Devlieghere FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
117fc51490bSJonas Devlieghere                              bool RequiresNullTerminator, bool IsVolatile) {
118fc51490bSJonas Devlieghere   auto F = openFileForRead(Name);
119fc51490bSJonas Devlieghere   if (!F)
120fc51490bSJonas Devlieghere     return F.getError();
121fc51490bSJonas Devlieghere 
122fc51490bSJonas Devlieghere   return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
123fc51490bSJonas Devlieghere }
124fc51490bSJonas Devlieghere 
125fc51490bSJonas Devlieghere std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
126fc51490bSJonas Devlieghere   if (llvm::sys::path::is_absolute(Path))
127fc51490bSJonas Devlieghere     return {};
128fc51490bSJonas Devlieghere 
129fc51490bSJonas Devlieghere   auto WorkingDir = getCurrentWorkingDirectory();
130fc51490bSJonas Devlieghere   if (!WorkingDir)
131fc51490bSJonas Devlieghere     return WorkingDir.getError();
132fc51490bSJonas Devlieghere 
1331ad53ca2SPavel Labath   llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
1341ad53ca2SPavel Labath   return {};
135fc51490bSJonas Devlieghere }
136fc51490bSJonas Devlieghere 
137fc51490bSJonas Devlieghere std::error_code FileSystem::getRealPath(const Twine &Path,
13899538e89SSam McCall                                         SmallVectorImpl<char> &Output) const {
139fc51490bSJonas Devlieghere   return errc::operation_not_permitted;
140fc51490bSJonas Devlieghere }
141fc51490bSJonas Devlieghere 
142cbb5c868SJonas Devlieghere std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
143cbb5c868SJonas Devlieghere   return errc::operation_not_permitted;
144cbb5c868SJonas Devlieghere }
145cbb5c868SJonas Devlieghere 
146fc51490bSJonas Devlieghere bool FileSystem::exists(const Twine &Path) {
147fc51490bSJonas Devlieghere   auto Status = status(Path);
148fc51490bSJonas Devlieghere   return Status && Status->exists();
149fc51490bSJonas Devlieghere }
150fc51490bSJonas Devlieghere 
151fc51490bSJonas Devlieghere #ifndef NDEBUG
152fc51490bSJonas Devlieghere static bool isTraversalComponent(StringRef Component) {
153fc51490bSJonas Devlieghere   return Component.equals("..") || Component.equals(".");
154fc51490bSJonas Devlieghere }
155fc51490bSJonas Devlieghere 
156fc51490bSJonas Devlieghere static bool pathHasTraversal(StringRef Path) {
157fc51490bSJonas Devlieghere   using namespace llvm::sys;
158fc51490bSJonas Devlieghere 
159fc51490bSJonas Devlieghere   for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
160fc51490bSJonas Devlieghere     if (isTraversalComponent(Comp))
161fc51490bSJonas Devlieghere       return true;
162fc51490bSJonas Devlieghere   return false;
163fc51490bSJonas Devlieghere }
164fc51490bSJonas Devlieghere #endif
165fc51490bSJonas Devlieghere 
166fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
167fc51490bSJonas Devlieghere // RealFileSystem implementation
168fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
169fc51490bSJonas Devlieghere 
170fc51490bSJonas Devlieghere namespace {
171fc51490bSJonas Devlieghere 
172fc51490bSJonas Devlieghere /// Wrapper around a raw file descriptor.
173fc51490bSJonas Devlieghere class RealFile : public File {
174fc51490bSJonas Devlieghere   friend class RealFileSystem;
175fc51490bSJonas Devlieghere 
176cc418a3aSReid Kleckner   file_t FD;
177fc51490bSJonas Devlieghere   Status S;
178fc51490bSJonas Devlieghere   std::string RealName;
179fc51490bSJonas Devlieghere 
180115a6ecdSSimon Pilgrim   RealFile(file_t RawFD, StringRef NewName, StringRef NewRealPathName)
181115a6ecdSSimon Pilgrim       : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
182fc51490bSJonas Devlieghere                      llvm::sys::fs::file_type::status_error, {}),
183fc51490bSJonas Devlieghere         RealName(NewRealPathName.str()) {
184cc418a3aSReid Kleckner     assert(FD != kInvalidFile && "Invalid or inactive file descriptor");
185fc51490bSJonas Devlieghere   }
186fc51490bSJonas Devlieghere 
187fc51490bSJonas Devlieghere public:
188fc51490bSJonas Devlieghere   ~RealFile() override;
189fc51490bSJonas Devlieghere 
190fc51490bSJonas Devlieghere   ErrorOr<Status> status() override;
191fc51490bSJonas Devlieghere   ErrorOr<std::string> getName() override;
192fc51490bSJonas Devlieghere   ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
193fc51490bSJonas Devlieghere                                                    int64_t FileSize,
194fc51490bSJonas Devlieghere                                                    bool RequiresNullTerminator,
195fc51490bSJonas Devlieghere                                                    bool IsVolatile) override;
196fc51490bSJonas Devlieghere   std::error_code close() override;
197*86e2af80SKeith Smiley   void setPath(const Twine &Path) override;
198fc51490bSJonas Devlieghere };
199fc51490bSJonas Devlieghere 
200fc51490bSJonas Devlieghere } // namespace
201fc51490bSJonas Devlieghere 
202fc51490bSJonas Devlieghere RealFile::~RealFile() { close(); }
203fc51490bSJonas Devlieghere 
204fc51490bSJonas Devlieghere ErrorOr<Status> RealFile::status() {
205cc418a3aSReid Kleckner   assert(FD != kInvalidFile && "cannot stat closed file");
206fc51490bSJonas Devlieghere   if (!S.isStatusKnown()) {
207fc51490bSJonas Devlieghere     file_status RealStatus;
208fc51490bSJonas Devlieghere     if (std::error_code EC = sys::fs::status(FD, RealStatus))
209fc51490bSJonas Devlieghere       return EC;
210fc51490bSJonas Devlieghere     S = Status::copyWithNewName(RealStatus, S.getName());
211fc51490bSJonas Devlieghere   }
212fc51490bSJonas Devlieghere   return S;
213fc51490bSJonas Devlieghere }
214fc51490bSJonas Devlieghere 
215fc51490bSJonas Devlieghere ErrorOr<std::string> RealFile::getName() {
216fc51490bSJonas Devlieghere   return RealName.empty() ? S.getName().str() : RealName;
217fc51490bSJonas Devlieghere }
218fc51490bSJonas Devlieghere 
219fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<MemoryBuffer>>
220fc51490bSJonas Devlieghere RealFile::getBuffer(const Twine &Name, int64_t FileSize,
221fc51490bSJonas Devlieghere                     bool RequiresNullTerminator, bool IsVolatile) {
222cc418a3aSReid Kleckner   assert(FD != kInvalidFile && "cannot get buffer for closed file");
223fc51490bSJonas Devlieghere   return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
224fc51490bSJonas Devlieghere                                    IsVolatile);
225fc51490bSJonas Devlieghere }
226fc51490bSJonas Devlieghere 
227fc51490bSJonas Devlieghere std::error_code RealFile::close() {
228cc418a3aSReid Kleckner   std::error_code EC = sys::fs::closeFile(FD);
229cc418a3aSReid Kleckner   FD = kInvalidFile;
230fc51490bSJonas Devlieghere   return EC;
231fc51490bSJonas Devlieghere }
232fc51490bSJonas Devlieghere 
233*86e2af80SKeith Smiley void RealFile::setPath(const Twine &Path) {
234*86e2af80SKeith Smiley   RealName = Path.str();
235*86e2af80SKeith Smiley   if (auto Status = status())
236*86e2af80SKeith Smiley     S = Status.get().copyWithNewName(Status.get(), Path);
237*86e2af80SKeith Smiley }
238*86e2af80SKeith Smiley 
239fc51490bSJonas Devlieghere namespace {
240fc51490bSJonas Devlieghere 
24115e475e2SSam McCall /// A file system according to your operating system.
24215e475e2SSam McCall /// This may be linked to the process's working directory, or maintain its own.
24315e475e2SSam McCall ///
24415e475e2SSam McCall /// Currently, its own working directory is emulated by storing the path and
24515e475e2SSam McCall /// sending absolute paths to llvm::sys::fs:: functions.
24615e475e2SSam McCall /// A more principled approach would be to push this down a level, modelling
24715e475e2SSam McCall /// the working dir as an llvm::sys::fs::WorkingDir or similar.
24815e475e2SSam McCall /// This would enable the use of openat()-style functions on some platforms.
249fc51490bSJonas Devlieghere class RealFileSystem : public FileSystem {
250fc51490bSJonas Devlieghere public:
25115e475e2SSam McCall   explicit RealFileSystem(bool LinkCWDToProcess) {
25215e475e2SSam McCall     if (!LinkCWDToProcess) {
25315e475e2SSam McCall       SmallString<128> PWD, RealPWD;
25415e475e2SSam McCall       if (llvm::sys::fs::current_path(PWD))
25515e475e2SSam McCall         return; // Awful, but nothing to do here.
25615e475e2SSam McCall       if (llvm::sys::fs::real_path(PWD, RealPWD))
25715e475e2SSam McCall         WD = {PWD, PWD};
25815e475e2SSam McCall       else
25915e475e2SSam McCall         WD = {PWD, RealPWD};
26015e475e2SSam McCall     }
26115e475e2SSam McCall   }
26215e475e2SSam McCall 
263fc51490bSJonas Devlieghere   ErrorOr<Status> status(const Twine &Path) override;
264fc51490bSJonas Devlieghere   ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
265fc51490bSJonas Devlieghere   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
266fc51490bSJonas Devlieghere 
267fc51490bSJonas Devlieghere   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
268fc51490bSJonas Devlieghere   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
269cbb5c868SJonas Devlieghere   std::error_code isLocal(const Twine &Path, bool &Result) override;
27099538e89SSam McCall   std::error_code getRealPath(const Twine &Path,
27199538e89SSam McCall                               SmallVectorImpl<char> &Output) const override;
272fc51490bSJonas Devlieghere 
273fc51490bSJonas Devlieghere private:
27415e475e2SSam McCall   // If this FS has its own working dir, use it to make Path absolute.
27515e475e2SSam McCall   // The returned twine is safe to use as long as both Storage and Path live.
27615e475e2SSam McCall   Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const {
27715e475e2SSam McCall     if (!WD)
27815e475e2SSam McCall       return Path;
27915e475e2SSam McCall     Path.toVector(Storage);
28015e475e2SSam McCall     sys::fs::make_absolute(WD->Resolved, Storage);
28115e475e2SSam McCall     return Storage;
28215e475e2SSam McCall   }
28315e475e2SSam McCall 
28415e475e2SSam McCall   struct WorkingDirectory {
28515e475e2SSam McCall     // The current working directory, without symlinks resolved. (echo $PWD).
28615e475e2SSam McCall     SmallString<128> Specified;
28715e475e2SSam McCall     // The current working directory, with links resolved. (readlink .).
28815e475e2SSam McCall     SmallString<128> Resolved;
28915e475e2SSam McCall   };
29015e475e2SSam McCall   Optional<WorkingDirectory> WD;
291fc51490bSJonas Devlieghere };
292fc51490bSJonas Devlieghere 
293fc51490bSJonas Devlieghere } // namespace
294fc51490bSJonas Devlieghere 
295fc51490bSJonas Devlieghere ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
29615e475e2SSam McCall   SmallString<256> Storage;
297fc51490bSJonas Devlieghere   sys::fs::file_status RealStatus;
29815e475e2SSam McCall   if (std::error_code EC =
29915e475e2SSam McCall           sys::fs::status(adjustPath(Path, Storage), RealStatus))
300fc51490bSJonas Devlieghere     return EC;
301e7b94649SDuncan P. N. Exon Smith   return Status::copyWithNewName(RealStatus, Path);
302fc51490bSJonas Devlieghere }
303fc51490bSJonas Devlieghere 
304fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
305fc51490bSJonas Devlieghere RealFileSystem::openFileForRead(const Twine &Name) {
30615e475e2SSam McCall   SmallString<256> RealName, Storage;
307cc418a3aSReid Kleckner   Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead(
308cc418a3aSReid Kleckner       adjustPath(Name, Storage), sys::fs::OF_None, &RealName);
309cc418a3aSReid Kleckner   if (!FDOrErr)
310cc418a3aSReid Kleckner     return errorToErrorCode(FDOrErr.takeError());
311cc418a3aSReid Kleckner   return std::unique_ptr<File>(
312cc418a3aSReid Kleckner       new RealFile(*FDOrErr, Name.str(), RealName.str()));
313fc51490bSJonas Devlieghere }
314fc51490bSJonas Devlieghere 
315fc51490bSJonas Devlieghere llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
31615e475e2SSam McCall   if (WD)
317adcd0268SBenjamin Kramer     return std::string(WD->Specified.str());
31815e475e2SSam McCall 
31915e475e2SSam McCall   SmallString<128> Dir;
320fc51490bSJonas Devlieghere   if (std::error_code EC = llvm::sys::fs::current_path(Dir))
321fc51490bSJonas Devlieghere     return EC;
322adcd0268SBenjamin Kramer   return std::string(Dir.str());
323fc51490bSJonas Devlieghere }
324fc51490bSJonas Devlieghere 
325fc51490bSJonas Devlieghere std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
32615e475e2SSam McCall   if (!WD)
32715e475e2SSam McCall     return llvm::sys::fs::set_current_path(Path);
328fc51490bSJonas Devlieghere 
32915e475e2SSam McCall   SmallString<128> Absolute, Resolved, Storage;
33015e475e2SSam McCall   adjustPath(Path, Storage).toVector(Absolute);
33115e475e2SSam McCall   bool IsDir;
33215e475e2SSam McCall   if (auto Err = llvm::sys::fs::is_directory(Absolute, IsDir))
33315e475e2SSam McCall     return Err;
33415e475e2SSam McCall   if (!IsDir)
33515e475e2SSam McCall     return std::make_error_code(std::errc::not_a_directory);
33615e475e2SSam McCall   if (auto Err = llvm::sys::fs::real_path(Absolute, Resolved))
33715e475e2SSam McCall     return Err;
33815e475e2SSam McCall   WD = {Absolute, Resolved};
339fc51490bSJonas Devlieghere   return std::error_code();
340fc51490bSJonas Devlieghere }
341fc51490bSJonas Devlieghere 
342cbb5c868SJonas Devlieghere std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
34315e475e2SSam McCall   SmallString<256> Storage;
34415e475e2SSam McCall   return llvm::sys::fs::is_local(adjustPath(Path, Storage), Result);
345cbb5c868SJonas Devlieghere }
346cbb5c868SJonas Devlieghere 
34799538e89SSam McCall std::error_code
34899538e89SSam McCall RealFileSystem::getRealPath(const Twine &Path,
34999538e89SSam McCall                             SmallVectorImpl<char> &Output) const {
35015e475e2SSam McCall   SmallString<256> Storage;
35115e475e2SSam McCall   return llvm::sys::fs::real_path(adjustPath(Path, Storage), Output);
352fc51490bSJonas Devlieghere }
353fc51490bSJonas Devlieghere 
354fc51490bSJonas Devlieghere IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
35515e475e2SSam McCall   static IntrusiveRefCntPtr<FileSystem> FS(new RealFileSystem(true));
356fc51490bSJonas Devlieghere   return FS;
357fc51490bSJonas Devlieghere }
358fc51490bSJonas Devlieghere 
35915e475e2SSam McCall std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() {
3600eaee545SJonas Devlieghere   return std::make_unique<RealFileSystem>(false);
36115e475e2SSam McCall }
36215e475e2SSam McCall 
363fc51490bSJonas Devlieghere namespace {
364fc51490bSJonas Devlieghere 
365fc51490bSJonas Devlieghere class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
366fc51490bSJonas Devlieghere   llvm::sys::fs::directory_iterator Iter;
367fc51490bSJonas Devlieghere 
368fc51490bSJonas Devlieghere public:
369fc51490bSJonas Devlieghere   RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
370fc51490bSJonas Devlieghere     if (Iter != llvm::sys::fs::directory_iterator())
371fc51490bSJonas Devlieghere       CurrentEntry = directory_entry(Iter->path(), Iter->type());
372fc51490bSJonas Devlieghere   }
373fc51490bSJonas Devlieghere 
374fc51490bSJonas Devlieghere   std::error_code increment() override {
375fc51490bSJonas Devlieghere     std::error_code EC;
376fc51490bSJonas Devlieghere     Iter.increment(EC);
377fc51490bSJonas Devlieghere     CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
378fc51490bSJonas Devlieghere                        ? directory_entry()
379fc51490bSJonas Devlieghere                        : directory_entry(Iter->path(), Iter->type());
380fc51490bSJonas Devlieghere     return EC;
381fc51490bSJonas Devlieghere   }
382fc51490bSJonas Devlieghere };
383fc51490bSJonas Devlieghere 
384fc51490bSJonas Devlieghere } // namespace
385fc51490bSJonas Devlieghere 
386fc51490bSJonas Devlieghere directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
387fc51490bSJonas Devlieghere                                              std::error_code &EC) {
38815e475e2SSam McCall   SmallString<128> Storage;
38915e475e2SSam McCall   return directory_iterator(
39015e475e2SSam McCall       std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
391fc51490bSJonas Devlieghere }
392fc51490bSJonas Devlieghere 
393fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
394fc51490bSJonas Devlieghere // OverlayFileSystem implementation
395fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
396fc51490bSJonas Devlieghere 
397fc51490bSJonas Devlieghere OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
398fc51490bSJonas Devlieghere   FSList.push_back(std::move(BaseFS));
399fc51490bSJonas Devlieghere }
400fc51490bSJonas Devlieghere 
401fc51490bSJonas Devlieghere void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
402fc51490bSJonas Devlieghere   FSList.push_back(FS);
403fc51490bSJonas Devlieghere   // Synchronize added file systems by duplicating the working directory from
404fc51490bSJonas Devlieghere   // the first one in the list.
405fc51490bSJonas Devlieghere   FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
406fc51490bSJonas Devlieghere }
407fc51490bSJonas Devlieghere 
408fc51490bSJonas Devlieghere ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
409fc51490bSJonas Devlieghere   // FIXME: handle symlinks that cross file systems
410fc51490bSJonas Devlieghere   for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
411fc51490bSJonas Devlieghere     ErrorOr<Status> Status = (*I)->status(Path);
412fc51490bSJonas Devlieghere     if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
413fc51490bSJonas Devlieghere       return Status;
414fc51490bSJonas Devlieghere   }
415fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
416fc51490bSJonas Devlieghere }
417fc51490bSJonas Devlieghere 
418fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
419fc51490bSJonas Devlieghere OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
420fc51490bSJonas Devlieghere   // FIXME: handle symlinks that cross file systems
421fc51490bSJonas Devlieghere   for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
422fc51490bSJonas Devlieghere     auto Result = (*I)->openFileForRead(Path);
423fc51490bSJonas Devlieghere     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
424fc51490bSJonas Devlieghere       return Result;
425fc51490bSJonas Devlieghere   }
426fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
427fc51490bSJonas Devlieghere }
428fc51490bSJonas Devlieghere 
429fc51490bSJonas Devlieghere llvm::ErrorOr<std::string>
430fc51490bSJonas Devlieghere OverlayFileSystem::getCurrentWorkingDirectory() const {
431fc51490bSJonas Devlieghere   // All file systems are synchronized, just take the first working directory.
432fc51490bSJonas Devlieghere   return FSList.front()->getCurrentWorkingDirectory();
433fc51490bSJonas Devlieghere }
434fc51490bSJonas Devlieghere 
435fc51490bSJonas Devlieghere std::error_code
436fc51490bSJonas Devlieghere OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
437fc51490bSJonas Devlieghere   for (auto &FS : FSList)
438fc51490bSJonas Devlieghere     if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
439fc51490bSJonas Devlieghere       return EC;
440fc51490bSJonas Devlieghere   return {};
441fc51490bSJonas Devlieghere }
442fc51490bSJonas Devlieghere 
443cbb5c868SJonas Devlieghere std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
444cbb5c868SJonas Devlieghere   for (auto &FS : FSList)
445cbb5c868SJonas Devlieghere     if (FS->exists(Path))
446cbb5c868SJonas Devlieghere       return FS->isLocal(Path, Result);
447cbb5c868SJonas Devlieghere   return errc::no_such_file_or_directory;
448cbb5c868SJonas Devlieghere }
449cbb5c868SJonas Devlieghere 
45099538e89SSam McCall std::error_code
45199538e89SSam McCall OverlayFileSystem::getRealPath(const Twine &Path,
45299538e89SSam McCall                                SmallVectorImpl<char> &Output) const {
4533322354bSKazu Hirata   for (const auto &FS : FSList)
454fc51490bSJonas Devlieghere     if (FS->exists(Path))
45599538e89SSam McCall       return FS->getRealPath(Path, Output);
456fc51490bSJonas Devlieghere   return errc::no_such_file_or_directory;
457fc51490bSJonas Devlieghere }
458fc51490bSJonas Devlieghere 
459fc51490bSJonas Devlieghere llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
460fc51490bSJonas Devlieghere 
461fc51490bSJonas Devlieghere namespace {
462fc51490bSJonas Devlieghere 
463719f7784SNathan Hawes /// Combines and deduplicates directory entries across multiple file systems.
464719f7784SNathan Hawes class CombiningDirIterImpl : public llvm::vfs::detail::DirIterImpl {
465719f7784SNathan Hawes   using FileSystemPtr = llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>;
466719f7784SNathan Hawes 
467719f7784SNathan Hawes   /// File systems to check for entries in. Processed in reverse order.
468719f7784SNathan Hawes   SmallVector<FileSystemPtr, 8> FSList;
469719f7784SNathan Hawes   /// The directory iterator for the current filesystem.
470fc51490bSJonas Devlieghere   directory_iterator CurrentDirIter;
471719f7784SNathan Hawes   /// The path of the directory to iterate the entries of.
472719f7784SNathan Hawes   std::string DirPath;
473719f7784SNathan Hawes   /// The set of names already returned as entries.
474fc51490bSJonas Devlieghere   llvm::StringSet<> SeenNames;
475fc51490bSJonas Devlieghere 
476719f7784SNathan Hawes   /// Sets \c CurrentDirIter to an iterator of \c DirPath in the next file
477719f7784SNathan Hawes   /// system in the list, or leaves it as is (at its end position) if we've
478719f7784SNathan Hawes   /// already gone through them all.
479fc51490bSJonas Devlieghere   std::error_code incrementFS() {
480719f7784SNathan Hawes     while (!FSList.empty()) {
481fc51490bSJonas Devlieghere       std::error_code EC;
482719f7784SNathan Hawes       CurrentDirIter = FSList.back()->dir_begin(DirPath, EC);
483719f7784SNathan Hawes       FSList.pop_back();
484fc51490bSJonas Devlieghere       if (EC && EC != errc::no_such_file_or_directory)
485fc51490bSJonas Devlieghere         return EC;
486fc51490bSJonas Devlieghere       if (CurrentDirIter != directory_iterator())
487fc51490bSJonas Devlieghere         break; // found
488fc51490bSJonas Devlieghere     }
489fc51490bSJonas Devlieghere     return {};
490fc51490bSJonas Devlieghere   }
491fc51490bSJonas Devlieghere 
492fc51490bSJonas Devlieghere   std::error_code incrementDirIter(bool IsFirstTime) {
493fc51490bSJonas Devlieghere     assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
494fc51490bSJonas Devlieghere            "incrementing past end");
495fc51490bSJonas Devlieghere     std::error_code EC;
496fc51490bSJonas Devlieghere     if (!IsFirstTime)
497fc51490bSJonas Devlieghere       CurrentDirIter.increment(EC);
498fc51490bSJonas Devlieghere     if (!EC && CurrentDirIter == directory_iterator())
499fc51490bSJonas Devlieghere       EC = incrementFS();
500fc51490bSJonas Devlieghere     return EC;
501fc51490bSJonas Devlieghere   }
502fc51490bSJonas Devlieghere 
503fc51490bSJonas Devlieghere   std::error_code incrementImpl(bool IsFirstTime) {
504fc51490bSJonas Devlieghere     while (true) {
505fc51490bSJonas Devlieghere       std::error_code EC = incrementDirIter(IsFirstTime);
506fc51490bSJonas Devlieghere       if (EC || CurrentDirIter == directory_iterator()) {
507fc51490bSJonas Devlieghere         CurrentEntry = directory_entry();
508fc51490bSJonas Devlieghere         return EC;
509fc51490bSJonas Devlieghere       }
510fc51490bSJonas Devlieghere       CurrentEntry = *CurrentDirIter;
511fc51490bSJonas Devlieghere       StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
512fc51490bSJonas Devlieghere       if (SeenNames.insert(Name).second)
513fc51490bSJonas Devlieghere         return EC; // name not seen before
514fc51490bSJonas Devlieghere     }
515fc51490bSJonas Devlieghere     llvm_unreachable("returned above");
516fc51490bSJonas Devlieghere   }
517fc51490bSJonas Devlieghere 
518fc51490bSJonas Devlieghere public:
519719f7784SNathan Hawes   CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems, std::string Dir,
520fc51490bSJonas Devlieghere                        std::error_code &EC)
521719f7784SNathan Hawes       : FSList(FileSystems.begin(), FileSystems.end()),
522719f7784SNathan Hawes         DirPath(std::move(Dir)) {
523719f7784SNathan Hawes     if (!FSList.empty()) {
524719f7784SNathan Hawes       CurrentDirIter = FSList.back()->dir_begin(DirPath, EC);
525719f7784SNathan Hawes       FSList.pop_back();
526719f7784SNathan Hawes       if (!EC || EC == errc::no_such_file_or_directory)
527719f7784SNathan Hawes         EC = incrementImpl(true);
528719f7784SNathan Hawes     }
529719f7784SNathan Hawes   }
530719f7784SNathan Hawes 
531719f7784SNathan Hawes   CombiningDirIterImpl(directory_iterator FirstIter, FileSystemPtr Fallback,
532719f7784SNathan Hawes                        std::string FallbackDir, std::error_code &EC)
533719f7784SNathan Hawes       : FSList({Fallback}), CurrentDirIter(FirstIter),
534719f7784SNathan Hawes         DirPath(std::move(FallbackDir)) {
535719f7784SNathan Hawes     if (!EC || EC == errc::no_such_file_or_directory)
536fc51490bSJonas Devlieghere       EC = incrementImpl(true);
537fc51490bSJonas Devlieghere   }
538fc51490bSJonas Devlieghere 
539fc51490bSJonas Devlieghere   std::error_code increment() override { return incrementImpl(false); }
540fc51490bSJonas Devlieghere };
541fc51490bSJonas Devlieghere 
542fc51490bSJonas Devlieghere } // namespace
543fc51490bSJonas Devlieghere 
544fc51490bSJonas Devlieghere directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
545fc51490bSJonas Devlieghere                                                 std::error_code &EC) {
546fc51490bSJonas Devlieghere   return directory_iterator(
547719f7784SNathan Hawes       std::make_shared<CombiningDirIterImpl>(FSList, Dir.str(), EC));
548fc51490bSJonas Devlieghere }
549fc51490bSJonas Devlieghere 
550a87b70d1SRichard Trieu void ProxyFileSystem::anchor() {}
551a87b70d1SRichard Trieu 
552fc51490bSJonas Devlieghere namespace llvm {
553fc51490bSJonas Devlieghere namespace vfs {
554fc51490bSJonas Devlieghere 
555fc51490bSJonas Devlieghere namespace detail {
556fc51490bSJonas Devlieghere 
557fc51490bSJonas Devlieghere enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink };
558fc51490bSJonas Devlieghere 
559fc51490bSJonas Devlieghere /// The in memory file system is a tree of Nodes. Every node can either be a
560fc51490bSJonas Devlieghere /// file , hardlink or a directory.
561fc51490bSJonas Devlieghere class InMemoryNode {
562fc51490bSJonas Devlieghere   InMemoryNodeKind Kind;
563fc51490bSJonas Devlieghere   std::string FileName;
564fc51490bSJonas Devlieghere 
565fc51490bSJonas Devlieghere public:
566fc51490bSJonas Devlieghere   InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
567adcd0268SBenjamin Kramer       : Kind(Kind), FileName(std::string(llvm::sys::path::filename(FileName))) {
568adcd0268SBenjamin Kramer   }
569fc51490bSJonas Devlieghere   virtual ~InMemoryNode() = default;
570fc51490bSJonas Devlieghere 
571fc51490bSJonas Devlieghere   /// Get the filename of this node (the name without the directory part).
572fc51490bSJonas Devlieghere   StringRef getFileName() const { return FileName; }
573fc51490bSJonas Devlieghere   InMemoryNodeKind getKind() const { return Kind; }
574fc51490bSJonas Devlieghere   virtual std::string toString(unsigned Indent) const = 0;
575fc51490bSJonas Devlieghere };
576fc51490bSJonas Devlieghere 
577fc51490bSJonas Devlieghere class InMemoryFile : public InMemoryNode {
578fc51490bSJonas Devlieghere   Status Stat;
579fc51490bSJonas Devlieghere   std::unique_ptr<llvm::MemoryBuffer> Buffer;
580fc51490bSJonas Devlieghere 
581fc51490bSJonas Devlieghere public:
582fc51490bSJonas Devlieghere   InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
583fc51490bSJonas Devlieghere       : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
584fc51490bSJonas Devlieghere         Buffer(std::move(Buffer)) {}
585fc51490bSJonas Devlieghere 
586fc51490bSJonas Devlieghere   /// Return the \p Status for this node. \p RequestedName should be the name
587fc51490bSJonas Devlieghere   /// through which the caller referred to this node. It will override
588fc51490bSJonas Devlieghere   /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
589e7b94649SDuncan P. N. Exon Smith   Status getStatus(const Twine &RequestedName) const {
590fc51490bSJonas Devlieghere     return Status::copyWithNewName(Stat, RequestedName);
591fc51490bSJonas Devlieghere   }
592fc51490bSJonas Devlieghere   llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
593fc51490bSJonas Devlieghere 
594fc51490bSJonas Devlieghere   std::string toString(unsigned Indent) const override {
595fc51490bSJonas Devlieghere     return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
596fc51490bSJonas Devlieghere   }
597fc51490bSJonas Devlieghere 
598fc51490bSJonas Devlieghere   static bool classof(const InMemoryNode *N) {
599fc51490bSJonas Devlieghere     return N->getKind() == IME_File;
600fc51490bSJonas Devlieghere   }
601fc51490bSJonas Devlieghere };
602fc51490bSJonas Devlieghere 
603fc51490bSJonas Devlieghere namespace {
604fc51490bSJonas Devlieghere 
605fc51490bSJonas Devlieghere class InMemoryHardLink : public InMemoryNode {
606fc51490bSJonas Devlieghere   const InMemoryFile &ResolvedFile;
607fc51490bSJonas Devlieghere 
608fc51490bSJonas Devlieghere public:
609fc51490bSJonas Devlieghere   InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
610fc51490bSJonas Devlieghere       : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
611fc51490bSJonas Devlieghere   const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
612fc51490bSJonas Devlieghere 
613fc51490bSJonas Devlieghere   std::string toString(unsigned Indent) const override {
614fc51490bSJonas Devlieghere     return std::string(Indent, ' ') + "HardLink to -> " +
615fc51490bSJonas Devlieghere            ResolvedFile.toString(0);
616fc51490bSJonas Devlieghere   }
617fc51490bSJonas Devlieghere 
618fc51490bSJonas Devlieghere   static bool classof(const InMemoryNode *N) {
619fc51490bSJonas Devlieghere     return N->getKind() == IME_HardLink;
620fc51490bSJonas Devlieghere   }
621fc51490bSJonas Devlieghere };
622fc51490bSJonas Devlieghere 
623fc51490bSJonas Devlieghere /// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
624fc51490bSJonas Devlieghere /// \p InMemoryFileAdaptor mimic as much as possible the behavior of
625fc51490bSJonas Devlieghere /// \p RealFile.
626fc51490bSJonas Devlieghere class InMemoryFileAdaptor : public File {
627fc51490bSJonas Devlieghere   const InMemoryFile &Node;
628fc51490bSJonas Devlieghere   /// The name to use when returning a Status for this file.
629fc51490bSJonas Devlieghere   std::string RequestedName;
630fc51490bSJonas Devlieghere 
631fc51490bSJonas Devlieghere public:
632fc51490bSJonas Devlieghere   explicit InMemoryFileAdaptor(const InMemoryFile &Node,
633fc51490bSJonas Devlieghere                                std::string RequestedName)
634fc51490bSJonas Devlieghere       : Node(Node), RequestedName(std::move(RequestedName)) {}
635fc51490bSJonas Devlieghere 
636fc51490bSJonas Devlieghere   llvm::ErrorOr<Status> status() override {
637fc51490bSJonas Devlieghere     return Node.getStatus(RequestedName);
638fc51490bSJonas Devlieghere   }
639fc51490bSJonas Devlieghere 
640fc51490bSJonas Devlieghere   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
641fc51490bSJonas Devlieghere   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
642fc51490bSJonas Devlieghere             bool IsVolatile) override {
643fc51490bSJonas Devlieghere     llvm::MemoryBuffer *Buf = Node.getBuffer();
644fc51490bSJonas Devlieghere     return llvm::MemoryBuffer::getMemBuffer(
645fc51490bSJonas Devlieghere         Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
646fc51490bSJonas Devlieghere   }
647fc51490bSJonas Devlieghere 
648fc51490bSJonas Devlieghere   std::error_code close() override { return {}; }
649*86e2af80SKeith Smiley 
650*86e2af80SKeith Smiley   void setPath(const Twine &Path) override { RequestedName = Path.str(); }
651fc51490bSJonas Devlieghere };
652fc51490bSJonas Devlieghere } // namespace
653fc51490bSJonas Devlieghere 
654fc51490bSJonas Devlieghere class InMemoryDirectory : public InMemoryNode {
655fc51490bSJonas Devlieghere   Status Stat;
656fc51490bSJonas Devlieghere   llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries;
657fc51490bSJonas Devlieghere 
658fc51490bSJonas Devlieghere public:
659fc51490bSJonas Devlieghere   InMemoryDirectory(Status Stat)
660fc51490bSJonas Devlieghere       : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
661fc51490bSJonas Devlieghere 
662fc51490bSJonas Devlieghere   /// Return the \p Status for this node. \p RequestedName should be the name
663fc51490bSJonas Devlieghere   /// through which the caller referred to this node. It will override
664fc51490bSJonas Devlieghere   /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
665e7b94649SDuncan P. N. Exon Smith   Status getStatus(const Twine &RequestedName) const {
666fc51490bSJonas Devlieghere     return Status::copyWithNewName(Stat, RequestedName);
667fc51490bSJonas Devlieghere   }
66822555bafSSam McCall 
66922555bafSSam McCall   UniqueID getUniqueID() const { return Stat.getUniqueID(); }
67022555bafSSam McCall 
671fc51490bSJonas Devlieghere   InMemoryNode *getChild(StringRef Name) {
672fc51490bSJonas Devlieghere     auto I = Entries.find(Name);
673fc51490bSJonas Devlieghere     if (I != Entries.end())
674fc51490bSJonas Devlieghere       return I->second.get();
675fc51490bSJonas Devlieghere     return nullptr;
676fc51490bSJonas Devlieghere   }
677fc51490bSJonas Devlieghere 
678fc51490bSJonas Devlieghere   InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
679fc51490bSJonas Devlieghere     return Entries.insert(make_pair(Name, std::move(Child)))
680fc51490bSJonas Devlieghere         .first->second.get();
681fc51490bSJonas Devlieghere   }
682fc51490bSJonas Devlieghere 
683fc51490bSJonas Devlieghere   using const_iterator = decltype(Entries)::const_iterator;
684fc51490bSJonas Devlieghere 
685fc51490bSJonas Devlieghere   const_iterator begin() const { return Entries.begin(); }
686fc51490bSJonas Devlieghere   const_iterator end() const { return Entries.end(); }
687fc51490bSJonas Devlieghere 
688fc51490bSJonas Devlieghere   std::string toString(unsigned Indent) const override {
689fc51490bSJonas Devlieghere     std::string Result =
690fc51490bSJonas Devlieghere         (std::string(Indent, ' ') + Stat.getName() + "\n").str();
691fc51490bSJonas Devlieghere     for (const auto &Entry : Entries)
692fc51490bSJonas Devlieghere       Result += Entry.second->toString(Indent + 2);
693fc51490bSJonas Devlieghere     return Result;
694fc51490bSJonas Devlieghere   }
695fc51490bSJonas Devlieghere 
696fc51490bSJonas Devlieghere   static bool classof(const InMemoryNode *N) {
697fc51490bSJonas Devlieghere     return N->getKind() == IME_Directory;
698fc51490bSJonas Devlieghere   }
699fc51490bSJonas Devlieghere };
700fc51490bSJonas Devlieghere 
701fc51490bSJonas Devlieghere namespace {
702e7b94649SDuncan P. N. Exon Smith Status getNodeStatus(const InMemoryNode *Node, const Twine &RequestedName) {
703fc51490bSJonas Devlieghere   if (auto Dir = dyn_cast<detail::InMemoryDirectory>(Node))
704fc51490bSJonas Devlieghere     return Dir->getStatus(RequestedName);
705fc51490bSJonas Devlieghere   if (auto File = dyn_cast<detail::InMemoryFile>(Node))
706fc51490bSJonas Devlieghere     return File->getStatus(RequestedName);
707fc51490bSJonas Devlieghere   if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node))
708fc51490bSJonas Devlieghere     return Link->getResolvedFile().getStatus(RequestedName);
709fc51490bSJonas Devlieghere   llvm_unreachable("Unknown node type");
710fc51490bSJonas Devlieghere }
711fc51490bSJonas Devlieghere } // namespace
712fc51490bSJonas Devlieghere } // namespace detail
713fc51490bSJonas Devlieghere 
71422555bafSSam McCall // The UniqueID of in-memory files is derived from path and content.
71522555bafSSam McCall // This avoids difficulties in creating exactly equivalent in-memory FSes,
71622555bafSSam McCall // as often needed in multithreaded programs.
71722555bafSSam McCall static sys::fs::UniqueID getUniqueID(hash_code Hash) {
71822555bafSSam McCall   return sys::fs::UniqueID(std::numeric_limits<uint64_t>::max(),
71922555bafSSam McCall                            uint64_t(size_t(Hash)));
72022555bafSSam McCall }
72122555bafSSam McCall static sys::fs::UniqueID getFileID(sys::fs::UniqueID Parent,
72222555bafSSam McCall                                    llvm::StringRef Name,
72322555bafSSam McCall                                    llvm::StringRef Contents) {
72422555bafSSam McCall   return getUniqueID(llvm::hash_combine(Parent.getFile(), Name, Contents));
72522555bafSSam McCall }
72622555bafSSam McCall static sys::fs::UniqueID getDirectoryID(sys::fs::UniqueID Parent,
72722555bafSSam McCall                                         llvm::StringRef Name) {
72822555bafSSam McCall   return getUniqueID(llvm::hash_combine(Parent.getFile(), Name));
72922555bafSSam McCall }
73022555bafSSam McCall 
731fc51490bSJonas Devlieghere InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
732fc51490bSJonas Devlieghere     : Root(new detail::InMemoryDirectory(
73322555bafSSam McCall           Status("", getDirectoryID(llvm::sys::fs::UniqueID(), ""),
73422555bafSSam McCall                  llvm::sys::TimePoint<>(), 0, 0, 0,
73522555bafSSam McCall                  llvm::sys::fs::file_type::directory_file,
736fc51490bSJonas Devlieghere                  llvm::sys::fs::perms::all_all))),
737fc51490bSJonas Devlieghere       UseNormalizedPaths(UseNormalizedPaths) {}
738fc51490bSJonas Devlieghere 
739fc51490bSJonas Devlieghere InMemoryFileSystem::~InMemoryFileSystem() = default;
740fc51490bSJonas Devlieghere 
741fc51490bSJonas Devlieghere std::string InMemoryFileSystem::toString() const {
742fc51490bSJonas Devlieghere   return Root->toString(/*Indent=*/0);
743fc51490bSJonas Devlieghere }
744fc51490bSJonas Devlieghere 
745fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
746fc51490bSJonas Devlieghere                                  std::unique_ptr<llvm::MemoryBuffer> Buffer,
747fc51490bSJonas Devlieghere                                  Optional<uint32_t> User,
748fc51490bSJonas Devlieghere                                  Optional<uint32_t> Group,
749fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::file_type> Type,
750fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::perms> Perms,
751fc51490bSJonas Devlieghere                                  const detail::InMemoryFile *HardLinkTarget) {
752fc51490bSJonas Devlieghere   SmallString<128> Path;
753fc51490bSJonas Devlieghere   P.toVector(Path);
754fc51490bSJonas Devlieghere 
755fc51490bSJonas Devlieghere   // Fix up relative paths. This just prepends the current working directory.
756fc51490bSJonas Devlieghere   std::error_code EC = makeAbsolute(Path);
757fc51490bSJonas Devlieghere   assert(!EC);
758fc51490bSJonas Devlieghere   (void)EC;
759fc51490bSJonas Devlieghere 
760fc51490bSJonas Devlieghere   if (useNormalizedPaths())
761fc51490bSJonas Devlieghere     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
762fc51490bSJonas Devlieghere 
763fc51490bSJonas Devlieghere   if (Path.empty())
764fc51490bSJonas Devlieghere     return false;
765fc51490bSJonas Devlieghere 
766fc51490bSJonas Devlieghere   detail::InMemoryDirectory *Dir = Root.get();
767fc51490bSJonas Devlieghere   auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
768fc51490bSJonas Devlieghere   const auto ResolvedUser = User.getValueOr(0);
769fc51490bSJonas Devlieghere   const auto ResolvedGroup = Group.getValueOr(0);
770fc51490bSJonas Devlieghere   const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
771fc51490bSJonas Devlieghere   const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
772fc51490bSJonas Devlieghere   assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer");
773fc51490bSJonas Devlieghere   // Any intermediate directories we create should be accessible by
774fc51490bSJonas Devlieghere   // the owner, even if Perms says otherwise for the final path.
775fc51490bSJonas Devlieghere   const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
776fc51490bSJonas Devlieghere   while (true) {
777fc51490bSJonas Devlieghere     StringRef Name = *I;
778fc51490bSJonas Devlieghere     detail::InMemoryNode *Node = Dir->getChild(Name);
779fc51490bSJonas Devlieghere     ++I;
780fc51490bSJonas Devlieghere     if (!Node) {
781fc51490bSJonas Devlieghere       if (I == E) {
782fc51490bSJonas Devlieghere         // End of the path.
783fc51490bSJonas Devlieghere         std::unique_ptr<detail::InMemoryNode> Child;
784fc51490bSJonas Devlieghere         if (HardLinkTarget)
785fc51490bSJonas Devlieghere           Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget));
786fc51490bSJonas Devlieghere         else {
787fc51490bSJonas Devlieghere           // Create a new file or directory.
78822555bafSSam McCall           Status Stat(
78922555bafSSam McCall               P.str(),
79022555bafSSam McCall               (ResolvedType == sys::fs::file_type::directory_file)
79122555bafSSam McCall                   ? getDirectoryID(Dir->getUniqueID(), Name)
79222555bafSSam McCall                   : getFileID(Dir->getUniqueID(), Name, Buffer->getBuffer()),
793fc51490bSJonas Devlieghere               llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
794fc51490bSJonas Devlieghere               ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
795fc51490bSJonas Devlieghere               ResolvedPerms);
796fc51490bSJonas Devlieghere           if (ResolvedType == sys::fs::file_type::directory_file) {
797fc51490bSJonas Devlieghere             Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
798fc51490bSJonas Devlieghere           } else {
799fc51490bSJonas Devlieghere             Child.reset(
800fc51490bSJonas Devlieghere                 new detail::InMemoryFile(std::move(Stat), std::move(Buffer)));
801fc51490bSJonas Devlieghere           }
802fc51490bSJonas Devlieghere         }
803fc51490bSJonas Devlieghere         Dir->addChild(Name, std::move(Child));
804fc51490bSJonas Devlieghere         return true;
805fc51490bSJonas Devlieghere       }
806fc51490bSJonas Devlieghere 
807fc51490bSJonas Devlieghere       // Create a new directory. Use the path up to here.
808fc51490bSJonas Devlieghere       Status Stat(
809fc51490bSJonas Devlieghere           StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
81022555bafSSam McCall           getDirectoryID(Dir->getUniqueID(), Name),
81122555bafSSam McCall           llvm::sys::toTimePoint(ModificationTime), ResolvedUser, ResolvedGroup,
81222555bafSSam McCall           0, sys::fs::file_type::directory_file, NewDirectoryPerms);
813fc51490bSJonas Devlieghere       Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
8140eaee545SJonas Devlieghere           Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
815fc51490bSJonas Devlieghere       continue;
816fc51490bSJonas Devlieghere     }
817fc51490bSJonas Devlieghere 
818fc51490bSJonas Devlieghere     if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
819fc51490bSJonas Devlieghere       Dir = NewDir;
820fc51490bSJonas Devlieghere     } else {
821fc51490bSJonas Devlieghere       assert((isa<detail::InMemoryFile>(Node) ||
822fc51490bSJonas Devlieghere               isa<detail::InMemoryHardLink>(Node)) &&
823fc51490bSJonas Devlieghere              "Must be either file, hardlink or directory!");
824fc51490bSJonas Devlieghere 
825fc51490bSJonas Devlieghere       // Trying to insert a directory in place of a file.
826fc51490bSJonas Devlieghere       if (I != E)
827fc51490bSJonas Devlieghere         return false;
828fc51490bSJonas Devlieghere 
829fc51490bSJonas Devlieghere       // Return false only if the new file is different from the existing one.
830fc51490bSJonas Devlieghere       if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
831fc51490bSJonas Devlieghere         return Link->getResolvedFile().getBuffer()->getBuffer() ==
832fc51490bSJonas Devlieghere                Buffer->getBuffer();
833fc51490bSJonas Devlieghere       }
834fc51490bSJonas Devlieghere       return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
835fc51490bSJonas Devlieghere              Buffer->getBuffer();
836fc51490bSJonas Devlieghere     }
837fc51490bSJonas Devlieghere   }
838fc51490bSJonas Devlieghere }
839fc51490bSJonas Devlieghere 
840fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
841fc51490bSJonas Devlieghere                                  std::unique_ptr<llvm::MemoryBuffer> Buffer,
842fc51490bSJonas Devlieghere                                  Optional<uint32_t> User,
843fc51490bSJonas Devlieghere                                  Optional<uint32_t> Group,
844fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::file_type> Type,
845fc51490bSJonas Devlieghere                                  Optional<llvm::sys::fs::perms> Perms) {
846fc51490bSJonas Devlieghere   return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
847fc51490bSJonas Devlieghere                  Perms, /*HardLinkTarget=*/nullptr);
848fc51490bSJonas Devlieghere }
849fc51490bSJonas Devlieghere 
850fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
851e763e032SDuncan P. N. Exon Smith                                       const llvm::MemoryBufferRef &Buffer,
852fc51490bSJonas Devlieghere                                       Optional<uint32_t> User,
853fc51490bSJonas Devlieghere                                       Optional<uint32_t> Group,
854fc51490bSJonas Devlieghere                                       Optional<llvm::sys::fs::file_type> Type,
855fc51490bSJonas Devlieghere                                       Optional<llvm::sys::fs::perms> Perms) {
856e763e032SDuncan P. N. Exon Smith   return addFile(P, ModificationTime, llvm::MemoryBuffer::getMemBuffer(Buffer),
857fc51490bSJonas Devlieghere                  std::move(User), std::move(Group), std::move(Type),
858fc51490bSJonas Devlieghere                  std::move(Perms));
859fc51490bSJonas Devlieghere }
860fc51490bSJonas Devlieghere 
861fc51490bSJonas Devlieghere static ErrorOr<const detail::InMemoryNode *>
862fc51490bSJonas Devlieghere lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
863fc51490bSJonas Devlieghere                    const Twine &P) {
864fc51490bSJonas Devlieghere   SmallString<128> Path;
865fc51490bSJonas Devlieghere   P.toVector(Path);
866fc51490bSJonas Devlieghere 
867fc51490bSJonas Devlieghere   // Fix up relative paths. This just prepends the current working directory.
868fc51490bSJonas Devlieghere   std::error_code EC = FS.makeAbsolute(Path);
869fc51490bSJonas Devlieghere   assert(!EC);
870fc51490bSJonas Devlieghere   (void)EC;
871fc51490bSJonas Devlieghere 
872fc51490bSJonas Devlieghere   if (FS.useNormalizedPaths())
873fc51490bSJonas Devlieghere     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
874fc51490bSJonas Devlieghere 
875fc51490bSJonas Devlieghere   if (Path.empty())
876fc51490bSJonas Devlieghere     return Dir;
877fc51490bSJonas Devlieghere 
878fc51490bSJonas Devlieghere   auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
879fc51490bSJonas Devlieghere   while (true) {
880fc51490bSJonas Devlieghere     detail::InMemoryNode *Node = Dir->getChild(*I);
881fc51490bSJonas Devlieghere     ++I;
882fc51490bSJonas Devlieghere     if (!Node)
883fc51490bSJonas Devlieghere       return errc::no_such_file_or_directory;
884fc51490bSJonas Devlieghere 
885fc51490bSJonas Devlieghere     // Return the file if it's at the end of the path.
886fc51490bSJonas Devlieghere     if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
887fc51490bSJonas Devlieghere       if (I == E)
888fc51490bSJonas Devlieghere         return File;
889fc51490bSJonas Devlieghere       return errc::no_such_file_or_directory;
890fc51490bSJonas Devlieghere     }
891fc51490bSJonas Devlieghere 
892fc51490bSJonas Devlieghere     // If Node is HardLink then return the resolved file.
893fc51490bSJonas Devlieghere     if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
894fc51490bSJonas Devlieghere       if (I == E)
895fc51490bSJonas Devlieghere         return &File->getResolvedFile();
896fc51490bSJonas Devlieghere       return errc::no_such_file_or_directory;
897fc51490bSJonas Devlieghere     }
898fc51490bSJonas Devlieghere     // Traverse directories.
899fc51490bSJonas Devlieghere     Dir = cast<detail::InMemoryDirectory>(Node);
900fc51490bSJonas Devlieghere     if (I == E)
901fc51490bSJonas Devlieghere       return Dir;
902fc51490bSJonas Devlieghere   }
903fc51490bSJonas Devlieghere }
904fc51490bSJonas Devlieghere 
905fc51490bSJonas Devlieghere bool InMemoryFileSystem::addHardLink(const Twine &FromPath,
906fc51490bSJonas Devlieghere                                      const Twine &ToPath) {
907fc51490bSJonas Devlieghere   auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath);
908fc51490bSJonas Devlieghere   auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath);
909fc51490bSJonas Devlieghere   // FromPath must not have been added before. ToPath must have been added
910fc51490bSJonas Devlieghere   // before. Resolved ToPath must be a File.
911fc51490bSJonas Devlieghere   if (!ToNode || FromNode || !isa<detail::InMemoryFile>(*ToNode))
912fc51490bSJonas Devlieghere     return false;
913fc51490bSJonas Devlieghere   return this->addFile(FromPath, 0, nullptr, None, None, None, None,
914fc51490bSJonas Devlieghere                        cast<detail::InMemoryFile>(*ToNode));
915fc51490bSJonas Devlieghere }
916fc51490bSJonas Devlieghere 
917fc51490bSJonas Devlieghere llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
918fc51490bSJonas Devlieghere   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
919fc51490bSJonas Devlieghere   if (Node)
920e7b94649SDuncan P. N. Exon Smith     return detail::getNodeStatus(*Node, Path);
921fc51490bSJonas Devlieghere   return Node.getError();
922fc51490bSJonas Devlieghere }
923fc51490bSJonas Devlieghere 
924fc51490bSJonas Devlieghere llvm::ErrorOr<std::unique_ptr<File>>
925fc51490bSJonas Devlieghere InMemoryFileSystem::openFileForRead(const Twine &Path) {
926fc51490bSJonas Devlieghere   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
927fc51490bSJonas Devlieghere   if (!Node)
928fc51490bSJonas Devlieghere     return Node.getError();
929fc51490bSJonas Devlieghere 
930fc51490bSJonas Devlieghere   // When we have a file provide a heap-allocated wrapper for the memory buffer
931fc51490bSJonas Devlieghere   // to match the ownership semantics for File.
932fc51490bSJonas Devlieghere   if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
933fc51490bSJonas Devlieghere     return std::unique_ptr<File>(
934fc51490bSJonas Devlieghere         new detail::InMemoryFileAdaptor(*F, Path.str()));
935fc51490bSJonas Devlieghere 
936fc51490bSJonas Devlieghere   // FIXME: errc::not_a_file?
937fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::invalid_argument);
938fc51490bSJonas Devlieghere }
939fc51490bSJonas Devlieghere 
940fc51490bSJonas Devlieghere namespace {
941fc51490bSJonas Devlieghere 
942fc51490bSJonas Devlieghere /// Adaptor from InMemoryDir::iterator to directory_iterator.
943fc51490bSJonas Devlieghere class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl {
944fc51490bSJonas Devlieghere   detail::InMemoryDirectory::const_iterator I;
945fc51490bSJonas Devlieghere   detail::InMemoryDirectory::const_iterator E;
946fc51490bSJonas Devlieghere   std::string RequestedDirName;
947fc51490bSJonas Devlieghere 
948fc51490bSJonas Devlieghere   void setCurrentEntry() {
949fc51490bSJonas Devlieghere     if (I != E) {
950fc51490bSJonas Devlieghere       SmallString<256> Path(RequestedDirName);
951fc51490bSJonas Devlieghere       llvm::sys::path::append(Path, I->second->getFileName());
952e1000f1dSSimon Pilgrim       sys::fs::file_type Type = sys::fs::file_type::type_unknown;
953fc51490bSJonas Devlieghere       switch (I->second->getKind()) {
954fc51490bSJonas Devlieghere       case detail::IME_File:
955fc51490bSJonas Devlieghere       case detail::IME_HardLink:
956fc51490bSJonas Devlieghere         Type = sys::fs::file_type::regular_file;
957fc51490bSJonas Devlieghere         break;
958fc51490bSJonas Devlieghere       case detail::IME_Directory:
959fc51490bSJonas Devlieghere         Type = sys::fs::file_type::directory_file;
960fc51490bSJonas Devlieghere         break;
961fc51490bSJonas Devlieghere       }
962adcd0268SBenjamin Kramer       CurrentEntry = directory_entry(std::string(Path.str()), Type);
963fc51490bSJonas Devlieghere     } else {
964fc51490bSJonas Devlieghere       // When we're at the end, make CurrentEntry invalid and DirIterImpl will
965fc51490bSJonas Devlieghere       // do the rest.
966fc51490bSJonas Devlieghere       CurrentEntry = directory_entry();
967fc51490bSJonas Devlieghere     }
968fc51490bSJonas Devlieghere   }
969fc51490bSJonas Devlieghere 
970fc51490bSJonas Devlieghere public:
971fc51490bSJonas Devlieghere   InMemoryDirIterator() = default;
972fc51490bSJonas Devlieghere 
973fc51490bSJonas Devlieghere   explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir,
974fc51490bSJonas Devlieghere                                std::string RequestedDirName)
975fc51490bSJonas Devlieghere       : I(Dir.begin()), E(Dir.end()),
976fc51490bSJonas Devlieghere         RequestedDirName(std::move(RequestedDirName)) {
977fc51490bSJonas Devlieghere     setCurrentEntry();
978fc51490bSJonas Devlieghere   }
979fc51490bSJonas Devlieghere 
980fc51490bSJonas Devlieghere   std::error_code increment() override {
981fc51490bSJonas Devlieghere     ++I;
982fc51490bSJonas Devlieghere     setCurrentEntry();
983fc51490bSJonas Devlieghere     return {};
984fc51490bSJonas Devlieghere   }
985fc51490bSJonas Devlieghere };
986fc51490bSJonas Devlieghere 
987fc51490bSJonas Devlieghere } // namespace
988fc51490bSJonas Devlieghere 
989fc51490bSJonas Devlieghere directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
990fc51490bSJonas Devlieghere                                                  std::error_code &EC) {
991fc51490bSJonas Devlieghere   auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
992fc51490bSJonas Devlieghere   if (!Node) {
993fc51490bSJonas Devlieghere     EC = Node.getError();
994fc51490bSJonas Devlieghere     return directory_iterator(std::make_shared<InMemoryDirIterator>());
995fc51490bSJonas Devlieghere   }
996fc51490bSJonas Devlieghere 
997fc51490bSJonas Devlieghere   if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
998fc51490bSJonas Devlieghere     return directory_iterator(
999fc51490bSJonas Devlieghere         std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
1000fc51490bSJonas Devlieghere 
1001fc51490bSJonas Devlieghere   EC = make_error_code(llvm::errc::not_a_directory);
1002fc51490bSJonas Devlieghere   return directory_iterator(std::make_shared<InMemoryDirIterator>());
1003fc51490bSJonas Devlieghere }
1004fc51490bSJonas Devlieghere 
1005fc51490bSJonas Devlieghere std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
1006fc51490bSJonas Devlieghere   SmallString<128> Path;
1007fc51490bSJonas Devlieghere   P.toVector(Path);
1008fc51490bSJonas Devlieghere 
1009fc51490bSJonas Devlieghere   // Fix up relative paths. This just prepends the current working directory.
1010fc51490bSJonas Devlieghere   std::error_code EC = makeAbsolute(Path);
1011fc51490bSJonas Devlieghere   assert(!EC);
1012fc51490bSJonas Devlieghere   (void)EC;
1013fc51490bSJonas Devlieghere 
1014fc51490bSJonas Devlieghere   if (useNormalizedPaths())
1015fc51490bSJonas Devlieghere     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1016fc51490bSJonas Devlieghere 
1017fc51490bSJonas Devlieghere   if (!Path.empty())
1018adcd0268SBenjamin Kramer     WorkingDirectory = std::string(Path.str());
1019fc51490bSJonas Devlieghere   return {};
1020fc51490bSJonas Devlieghere }
1021fc51490bSJonas Devlieghere 
102299538e89SSam McCall std::error_code
102399538e89SSam McCall InMemoryFileSystem::getRealPath(const Twine &Path,
102499538e89SSam McCall                                 SmallVectorImpl<char> &Output) const {
1025fc51490bSJonas Devlieghere   auto CWD = getCurrentWorkingDirectory();
1026fc51490bSJonas Devlieghere   if (!CWD || CWD->empty())
1027fc51490bSJonas Devlieghere     return errc::operation_not_permitted;
1028fc51490bSJonas Devlieghere   Path.toVector(Output);
1029fc51490bSJonas Devlieghere   if (auto EC = makeAbsolute(Output))
1030fc51490bSJonas Devlieghere     return EC;
1031fc51490bSJonas Devlieghere   llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
1032fc51490bSJonas Devlieghere   return {};
1033fc51490bSJonas Devlieghere }
1034fc51490bSJonas Devlieghere 
1035cbb5c868SJonas Devlieghere std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
1036cbb5c868SJonas Devlieghere   Result = false;
1037cbb5c868SJonas Devlieghere   return {};
1038cbb5c868SJonas Devlieghere }
1039cbb5c868SJonas Devlieghere 
1040fc51490bSJonas Devlieghere } // namespace vfs
1041fc51490bSJonas Devlieghere } // namespace llvm
1042fc51490bSJonas Devlieghere 
1043fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
1044fc51490bSJonas Devlieghere // RedirectingFileSystem implementation
1045fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
1046fc51490bSJonas Devlieghere 
1047da45bd23SAdrian McCarthy namespace {
1048da45bd23SAdrian McCarthy 
1049ecb00a77SNathan Hawes static llvm::sys::path::Style getExistingStyle(llvm::StringRef Path) {
1050ecb00a77SNathan Hawes   // Detect the path style in use by checking the first separator.
1051da45bd23SAdrian McCarthy   llvm::sys::path::Style style = llvm::sys::path::Style::native;
1052da45bd23SAdrian McCarthy   const size_t n = Path.find_first_of("/\\");
105346ec93a4SMartin Storsjö   // Can't distinguish between posix and windows_slash here.
1054da45bd23SAdrian McCarthy   if (n != static_cast<size_t>(-1))
1055da45bd23SAdrian McCarthy     style = (Path[n] == '/') ? llvm::sys::path::Style::posix
105646ec93a4SMartin Storsjö                              : llvm::sys::path::Style::windows_backslash;
1057ecb00a77SNathan Hawes   return style;
1058ecb00a77SNathan Hawes }
1059ecb00a77SNathan Hawes 
1060ecb00a77SNathan Hawes /// Removes leading "./" as well as path components like ".." and ".".
1061ecb00a77SNathan Hawes static llvm::SmallString<256> canonicalize(llvm::StringRef Path) {
1062ecb00a77SNathan Hawes   // First detect the path style in use by checking the first separator.
1063ecb00a77SNathan Hawes   llvm::sys::path::Style style = getExistingStyle(Path);
1064da45bd23SAdrian McCarthy 
1065da45bd23SAdrian McCarthy   // Now remove the dots.  Explicitly specifying the path style prevents the
1066da45bd23SAdrian McCarthy   // direction of the slashes from changing.
1067da45bd23SAdrian McCarthy   llvm::SmallString<256> result =
1068da45bd23SAdrian McCarthy       llvm::sys::path::remove_leading_dotslash(Path, style);
1069da45bd23SAdrian McCarthy   llvm::sys::path::remove_dots(result, /*remove_dot_dot=*/true, style);
1070da45bd23SAdrian McCarthy   return result;
1071da45bd23SAdrian McCarthy }
1072da45bd23SAdrian McCarthy 
1073da45bd23SAdrian McCarthy } // anonymous namespace
1074da45bd23SAdrian McCarthy 
1075da45bd23SAdrian McCarthy 
107621703543SJonas Devlieghere RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
107721703543SJonas Devlieghere     : ExternalFS(std::move(FS)) {
107821703543SJonas Devlieghere   if (ExternalFS)
107921703543SJonas Devlieghere     if (auto ExternalWorkingDirectory =
108021703543SJonas Devlieghere             ExternalFS->getCurrentWorkingDirectory()) {
108121703543SJonas Devlieghere       WorkingDirectory = *ExternalWorkingDirectory;
108221703543SJonas Devlieghere     }
108321703543SJonas Devlieghere }
108421703543SJonas Devlieghere 
1085719f7784SNathan Hawes /// Directory iterator implementation for \c RedirectingFileSystem's
1086719f7784SNathan Hawes /// directory entries.
1087719f7784SNathan Hawes class llvm::vfs::RedirectingFSDirIterImpl
10881a0ce65aSJonas Devlieghere     : public llvm::vfs::detail::DirIterImpl {
1089fc51490bSJonas Devlieghere   std::string Dir;
1090719f7784SNathan Hawes   RedirectingFileSystem::DirectoryEntry::iterator Current, End;
1091fc51490bSJonas Devlieghere 
1092719f7784SNathan Hawes   std::error_code incrementImpl(bool IsFirstTime) {
1093719f7784SNathan Hawes     assert((IsFirstTime || Current != End) && "cannot iterate past end");
1094719f7784SNathan Hawes     if (!IsFirstTime)
1095719f7784SNathan Hawes       ++Current;
1096719f7784SNathan Hawes     if (Current != End) {
1097719f7784SNathan Hawes       SmallString<128> PathStr(Dir);
1098719f7784SNathan Hawes       llvm::sys::path::append(PathStr, (*Current)->getName());
1099719f7784SNathan Hawes       sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1100719f7784SNathan Hawes       switch ((*Current)->getKind()) {
1101719f7784SNathan Hawes       case RedirectingFileSystem::EK_Directory:
1102ecb00a77SNathan Hawes         LLVM_FALLTHROUGH;
1103ecb00a77SNathan Hawes       case RedirectingFileSystem::EK_DirectoryRemap:
1104719f7784SNathan Hawes         Type = sys::fs::file_type::directory_file;
1105719f7784SNathan Hawes         break;
1106719f7784SNathan Hawes       case RedirectingFileSystem::EK_File:
1107719f7784SNathan Hawes         Type = sys::fs::file_type::regular_file;
1108719f7784SNathan Hawes         break;
1109719f7784SNathan Hawes       }
1110719f7784SNathan Hawes       CurrentEntry = directory_entry(std::string(PathStr.str()), Type);
1111719f7784SNathan Hawes     } else {
1112719f7784SNathan Hawes       CurrentEntry = directory_entry();
1113719f7784SNathan Hawes     }
1114719f7784SNathan Hawes     return {};
1115719f7784SNathan Hawes   };
1116fc51490bSJonas Devlieghere 
1117fc51490bSJonas Devlieghere public:
1118719f7784SNathan Hawes   RedirectingFSDirIterImpl(
1119719f7784SNathan Hawes       const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin,
1120719f7784SNathan Hawes       RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC)
1121719f7784SNathan Hawes       : Dir(Path.str()), Current(Begin), End(End) {
1122719f7784SNathan Hawes     EC = incrementImpl(/*IsFirstTime=*/true);
1123719f7784SNathan Hawes   }
1124fc51490bSJonas Devlieghere 
1125719f7784SNathan Hawes   std::error_code increment() override {
1126719f7784SNathan Hawes     return incrementImpl(/*IsFirstTime=*/false);
1127719f7784SNathan Hawes   }
1128fc51490bSJonas Devlieghere };
1129fc51490bSJonas Devlieghere 
11309b8b1645SBenjamin Kramer namespace {
1131ecb00a77SNathan Hawes /// Directory iterator implementation for \c RedirectingFileSystem's
1132ecb00a77SNathan Hawes /// directory remap entries that maps the paths reported by the external
1133ecb00a77SNathan Hawes /// file system's directory iterator back to the virtual directory's path.
1134ecb00a77SNathan Hawes class RedirectingFSDirRemapIterImpl : public llvm::vfs::detail::DirIterImpl {
1135ecb00a77SNathan Hawes   std::string Dir;
1136ecb00a77SNathan Hawes   llvm::sys::path::Style DirStyle;
1137ecb00a77SNathan Hawes   llvm::vfs::directory_iterator ExternalIter;
1138ecb00a77SNathan Hawes 
1139ecb00a77SNathan Hawes public:
1140ecb00a77SNathan Hawes   RedirectingFSDirRemapIterImpl(std::string DirPath,
1141ecb00a77SNathan Hawes                                 llvm::vfs::directory_iterator ExtIter)
1142ecb00a77SNathan Hawes       : Dir(std::move(DirPath)), DirStyle(getExistingStyle(Dir)),
1143ecb00a77SNathan Hawes         ExternalIter(ExtIter) {
1144ecb00a77SNathan Hawes     if (ExternalIter != llvm::vfs::directory_iterator())
1145ecb00a77SNathan Hawes       setCurrentEntry();
1146ecb00a77SNathan Hawes   }
1147ecb00a77SNathan Hawes 
1148ecb00a77SNathan Hawes   void setCurrentEntry() {
1149ecb00a77SNathan Hawes     StringRef ExternalPath = ExternalIter->path();
1150ecb00a77SNathan Hawes     llvm::sys::path::Style ExternalStyle = getExistingStyle(ExternalPath);
1151ecb00a77SNathan Hawes     StringRef File = llvm::sys::path::filename(ExternalPath, ExternalStyle);
1152ecb00a77SNathan Hawes 
1153ecb00a77SNathan Hawes     SmallString<128> NewPath(Dir);
1154ecb00a77SNathan Hawes     llvm::sys::path::append(NewPath, DirStyle, File);
1155ecb00a77SNathan Hawes 
1156ecb00a77SNathan Hawes     CurrentEntry = directory_entry(std::string(NewPath), ExternalIter->type());
1157ecb00a77SNathan Hawes   }
1158ecb00a77SNathan Hawes 
1159ecb00a77SNathan Hawes   std::error_code increment() override {
1160ecb00a77SNathan Hawes     std::error_code EC;
1161ecb00a77SNathan Hawes     ExternalIter.increment(EC);
1162ecb00a77SNathan Hawes     if (!EC && ExternalIter != llvm::vfs::directory_iterator())
1163ecb00a77SNathan Hawes       setCurrentEntry();
1164ecb00a77SNathan Hawes     else
1165ecb00a77SNathan Hawes       CurrentEntry = directory_entry();
1166ecb00a77SNathan Hawes     return EC;
1167ecb00a77SNathan Hawes   }
1168ecb00a77SNathan Hawes };
11699b8b1645SBenjamin Kramer } // namespace
1170ecb00a77SNathan Hawes 
11711a0ce65aSJonas Devlieghere llvm::ErrorOr<std::string>
11721a0ce65aSJonas Devlieghere RedirectingFileSystem::getCurrentWorkingDirectory() const {
117321703543SJonas Devlieghere   return WorkingDirectory;
1174fc51490bSJonas Devlieghere }
1175fc51490bSJonas Devlieghere 
11761a0ce65aSJonas Devlieghere std::error_code
11771a0ce65aSJonas Devlieghere RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
117821703543SJonas Devlieghere   // Don't change the working directory if the path doesn't exist.
117921703543SJonas Devlieghere   if (!exists(Path))
118021703543SJonas Devlieghere     return errc::no_such_file_or_directory;
118121703543SJonas Devlieghere 
118221703543SJonas Devlieghere   SmallString<128> AbsolutePath;
118321703543SJonas Devlieghere   Path.toVector(AbsolutePath);
118421703543SJonas Devlieghere   if (std::error_code EC = makeAbsolute(AbsolutePath))
118521703543SJonas Devlieghere     return EC;
1186adcd0268SBenjamin Kramer   WorkingDirectory = std::string(AbsolutePath.str());
118721703543SJonas Devlieghere   return {};
1188fc51490bSJonas Devlieghere }
1189fc51490bSJonas Devlieghere 
11900be9ca7cSJonas Devlieghere std::error_code RedirectingFileSystem::isLocal(const Twine &Path_,
11911a0ce65aSJonas Devlieghere                                                bool &Result) {
11920be9ca7cSJonas Devlieghere   SmallString<256> Path;
11930be9ca7cSJonas Devlieghere   Path_.toVector(Path);
11940be9ca7cSJonas Devlieghere 
11950be9ca7cSJonas Devlieghere   if (std::error_code EC = makeCanonical(Path))
11960be9ca7cSJonas Devlieghere     return {};
11970be9ca7cSJonas Devlieghere 
1198cbb5c868SJonas Devlieghere   return ExternalFS->isLocal(Path, Result);
1199cbb5c868SJonas Devlieghere }
1200cbb5c868SJonas Devlieghere 
1201738b5c96SAdrian McCarthy std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
120246ec93a4SMartin Storsjö   // is_absolute(..., Style::windows_*) accepts paths with both slash types.
1203738b5c96SAdrian McCarthy   if (llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::posix) ||
120446ec93a4SMartin Storsjö       llvm::sys::path::is_absolute(Path,
120546ec93a4SMartin Storsjö                                    llvm::sys::path::Style::windows_backslash))
1206738b5c96SAdrian McCarthy     return {};
1207738b5c96SAdrian McCarthy 
1208738b5c96SAdrian McCarthy   auto WorkingDir = getCurrentWorkingDirectory();
1209738b5c96SAdrian McCarthy   if (!WorkingDir)
1210738b5c96SAdrian McCarthy     return WorkingDir.getError();
1211738b5c96SAdrian McCarthy 
1212da45bd23SAdrian McCarthy   // We can't use sys::fs::make_absolute because that assumes the path style
1213da45bd23SAdrian McCarthy   // is native and there is no way to override that.  Since we know WorkingDir
1214da45bd23SAdrian McCarthy   // is absolute, we can use it to determine which style we actually have and
1215da45bd23SAdrian McCarthy   // append Path ourselves.
121646ec93a4SMartin Storsjö   sys::path::Style style = sys::path::Style::windows_backslash;
1217da45bd23SAdrian McCarthy   if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) {
1218da45bd23SAdrian McCarthy     style = sys::path::Style::posix;
121946ec93a4SMartin Storsjö   } else {
122046ec93a4SMartin Storsjö     // Distinguish between windows_backslash and windows_slash; getExistingStyle
122146ec93a4SMartin Storsjö     // returns posix for a path with windows_slash.
122246ec93a4SMartin Storsjö     if (getExistingStyle(WorkingDir.get()) !=
122346ec93a4SMartin Storsjö         sys::path::Style::windows_backslash)
122446ec93a4SMartin Storsjö       style = sys::path::Style::windows_slash;
1225da45bd23SAdrian McCarthy   }
1226da45bd23SAdrian McCarthy 
1227da45bd23SAdrian McCarthy   std::string Result = WorkingDir.get();
1228da45bd23SAdrian McCarthy   StringRef Dir(Result);
1229da45bd23SAdrian McCarthy   if (!Dir.endswith(sys::path::get_separator(style))) {
1230da45bd23SAdrian McCarthy     Result += sys::path::get_separator(style);
1231da45bd23SAdrian McCarthy   }
1232da45bd23SAdrian McCarthy   Result.append(Path.data(), Path.size());
1233da45bd23SAdrian McCarthy   Path.assign(Result.begin(), Result.end());
1234da45bd23SAdrian McCarthy 
1235738b5c96SAdrian McCarthy   return {};
1236738b5c96SAdrian McCarthy }
1237738b5c96SAdrian McCarthy 
12381a0ce65aSJonas Devlieghere directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
12391a0ce65aSJonas Devlieghere                                                     std::error_code &EC) {
12400be9ca7cSJonas Devlieghere   SmallString<256> Path;
12410be9ca7cSJonas Devlieghere   Dir.toVector(Path);
12420be9ca7cSJonas Devlieghere 
12430be9ca7cSJonas Devlieghere   EC = makeCanonical(Path);
12440be9ca7cSJonas Devlieghere   if (EC)
12450be9ca7cSJonas Devlieghere     return {};
12460be9ca7cSJonas Devlieghere 
1247ecb00a77SNathan Hawes   ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
1248ecb00a77SNathan Hawes   if (!Result) {
1249ecb00a77SNathan Hawes     EC = Result.getError();
1250719f7784SNathan Hawes     if (shouldFallBackToExternalFS(EC))
12510be9ca7cSJonas Devlieghere       return ExternalFS->dir_begin(Path, EC);
1252fc51490bSJonas Devlieghere     return {};
1253fc51490bSJonas Devlieghere   }
1254ecb00a77SNathan Hawes 
1255ecb00a77SNathan Hawes   // Use status to make sure the path exists and refers to a directory.
1256*86e2af80SKeith Smiley   ErrorOr<Status> S = status(Path, Dir, *Result);
1257fc51490bSJonas Devlieghere   if (!S) {
1258ecb00a77SNathan Hawes     if (shouldFallBackToExternalFS(S.getError(), Result->E))
1259ecb00a77SNathan Hawes       return ExternalFS->dir_begin(Dir, EC);
1260fc51490bSJonas Devlieghere     EC = S.getError();
1261fc51490bSJonas Devlieghere     return {};
1262fc51490bSJonas Devlieghere   }
1263fc51490bSJonas Devlieghere   if (!S->isDirectory()) {
1264fc51490bSJonas Devlieghere     EC = std::error_code(static_cast<int>(errc::not_a_directory),
1265fc51490bSJonas Devlieghere                          std::system_category());
1266fc51490bSJonas Devlieghere     return {};
1267fc51490bSJonas Devlieghere   }
1268fc51490bSJonas Devlieghere 
1269ecb00a77SNathan Hawes   // Create the appropriate directory iterator based on whether we found a
1270ecb00a77SNathan Hawes   // DirectoryRemapEntry or DirectoryEntry.
1271ecb00a77SNathan Hawes   directory_iterator DirIter;
1272ecb00a77SNathan Hawes   if (auto ExtRedirect = Result->getExternalRedirect()) {
1273ecb00a77SNathan Hawes     auto RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
1274ecb00a77SNathan Hawes     DirIter = ExternalFS->dir_begin(*ExtRedirect, EC);
1275ecb00a77SNathan Hawes 
1276ecb00a77SNathan Hawes     if (!RE->useExternalName(UseExternalNames)) {
1277ecb00a77SNathan Hawes       // Update the paths in the results to use the virtual directory's path.
1278ecb00a77SNathan Hawes       DirIter =
1279ecb00a77SNathan Hawes           directory_iterator(std::make_shared<RedirectingFSDirRemapIterImpl>(
1280ecb00a77SNathan Hawes               std::string(Path), DirIter));
1281ecb00a77SNathan Hawes     }
1282ecb00a77SNathan Hawes   } else {
1283ecb00a77SNathan Hawes     auto DE = cast<DirectoryEntry>(Result->E);
1284ecb00a77SNathan Hawes     DirIter = directory_iterator(std::make_shared<RedirectingFSDirIterImpl>(
1285ecb00a77SNathan Hawes         Path, DE->contents_begin(), DE->contents_end(), EC));
1286ecb00a77SNathan Hawes   }
1287719f7784SNathan Hawes 
1288719f7784SNathan Hawes   if (!shouldUseExternalFS())
1289719f7784SNathan Hawes     return DirIter;
1290719f7784SNathan Hawes   return directory_iterator(std::make_shared<CombiningDirIterImpl>(
1291719f7784SNathan Hawes       DirIter, ExternalFS, std::string(Path), EC));
1292fc51490bSJonas Devlieghere }
1293fc51490bSJonas Devlieghere 
12941a0ce65aSJonas Devlieghere void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) {
1295fc51490bSJonas Devlieghere   ExternalContentsPrefixDir = PrefixDir.str();
1296fc51490bSJonas Devlieghere }
1297fc51490bSJonas Devlieghere 
12981a0ce65aSJonas Devlieghere StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const {
1299fc51490bSJonas Devlieghere   return ExternalContentsPrefixDir;
1300fc51490bSJonas Devlieghere }
1301fc51490bSJonas Devlieghere 
130237469061SJonas Devlieghere void RedirectingFileSystem::setFallthrough(bool Fallthrough) {
130337469061SJonas Devlieghere   IsFallthrough = Fallthrough;
130437469061SJonas Devlieghere }
130537469061SJonas Devlieghere 
130637469061SJonas Devlieghere std::vector<StringRef> RedirectingFileSystem::getRoots() const {
130737469061SJonas Devlieghere   std::vector<StringRef> R;
130837469061SJonas Devlieghere   for (const auto &Root : Roots)
130937469061SJonas Devlieghere     R.push_back(Root->getName());
131037469061SJonas Devlieghere   return R;
131137469061SJonas Devlieghere }
131237469061SJonas Devlieghere 
131397fc8eb4SJonas Devlieghere void RedirectingFileSystem::dump(raw_ostream &OS) const {
1314fc51490bSJonas Devlieghere   for (const auto &Root : Roots)
131597fc8eb4SJonas Devlieghere     dumpEntry(OS, Root.get());
1316fc51490bSJonas Devlieghere }
1317fc51490bSJonas Devlieghere 
131897fc8eb4SJonas Devlieghere void RedirectingFileSystem::dumpEntry(raw_ostream &OS,
131997fc8eb4SJonas Devlieghere                                       RedirectingFileSystem::Entry *E,
13201a0ce65aSJonas Devlieghere                                       int NumSpaces) const {
1321fc51490bSJonas Devlieghere   StringRef Name = E->getName();
1322fc51490bSJonas Devlieghere   for (int i = 0, e = NumSpaces; i < e; ++i)
132397fc8eb4SJonas Devlieghere     OS << " ";
132497fc8eb4SJonas Devlieghere   OS << "'" << Name.str().c_str() << "'"
1325fc51490bSJonas Devlieghere      << "\n";
1326fc51490bSJonas Devlieghere 
13271a0ce65aSJonas Devlieghere   if (E->getKind() == RedirectingFileSystem::EK_Directory) {
1328719f7784SNathan Hawes     auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(E);
1329fc51490bSJonas Devlieghere     assert(DE && "Should be a directory");
1330fc51490bSJonas Devlieghere 
1331fc51490bSJonas Devlieghere     for (std::unique_ptr<Entry> &SubEntry :
1332fc51490bSJonas Devlieghere          llvm::make_range(DE->contents_begin(), DE->contents_end()))
133397fc8eb4SJonas Devlieghere       dumpEntry(OS, SubEntry.get(), NumSpaces + 2);
1334fc51490bSJonas Devlieghere   }
1335fc51490bSJonas Devlieghere }
133697fc8eb4SJonas Devlieghere 
133797fc8eb4SJonas Devlieghere #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
133897fc8eb4SJonas Devlieghere LLVM_DUMP_METHOD void RedirectingFileSystem::dump() const { dump(dbgs()); }
1339fc51490bSJonas Devlieghere #endif
1340fc51490bSJonas Devlieghere 
1341fc51490bSJonas Devlieghere /// A helper class to hold the common YAML parsing state.
13421a0ce65aSJonas Devlieghere class llvm::vfs::RedirectingFileSystemParser {
1343fc51490bSJonas Devlieghere   yaml::Stream &Stream;
1344fc51490bSJonas Devlieghere 
1345fc51490bSJonas Devlieghere   void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1346fc51490bSJonas Devlieghere 
1347fc51490bSJonas Devlieghere   // false on error
1348fc51490bSJonas Devlieghere   bool parseScalarString(yaml::Node *N, StringRef &Result,
1349fc51490bSJonas Devlieghere                          SmallVectorImpl<char> &Storage) {
1350fc51490bSJonas Devlieghere     const auto *S = dyn_cast<yaml::ScalarNode>(N);
1351fc51490bSJonas Devlieghere 
1352fc51490bSJonas Devlieghere     if (!S) {
1353fc51490bSJonas Devlieghere       error(N, "expected string");
1354fc51490bSJonas Devlieghere       return false;
1355fc51490bSJonas Devlieghere     }
1356fc51490bSJonas Devlieghere     Result = S->getValue(Storage);
1357fc51490bSJonas Devlieghere     return true;
1358fc51490bSJonas Devlieghere   }
1359fc51490bSJonas Devlieghere 
1360fc51490bSJonas Devlieghere   // false on error
1361fc51490bSJonas Devlieghere   bool parseScalarBool(yaml::Node *N, bool &Result) {
1362fc51490bSJonas Devlieghere     SmallString<5> Storage;
1363fc51490bSJonas Devlieghere     StringRef Value;
1364fc51490bSJonas Devlieghere     if (!parseScalarString(N, Value, Storage))
1365fc51490bSJonas Devlieghere       return false;
1366fc51490bSJonas Devlieghere 
136742f74e82SMartin Storsjö     if (Value.equals_insensitive("true") || Value.equals_insensitive("on") ||
136842f74e82SMartin Storsjö         Value.equals_insensitive("yes") || Value == "1") {
1369fc51490bSJonas Devlieghere       Result = true;
1370fc51490bSJonas Devlieghere       return true;
137142f74e82SMartin Storsjö     } else if (Value.equals_insensitive("false") ||
137242f74e82SMartin Storsjö                Value.equals_insensitive("off") ||
137342f74e82SMartin Storsjö                Value.equals_insensitive("no") || Value == "0") {
1374fc51490bSJonas Devlieghere       Result = false;
1375fc51490bSJonas Devlieghere       return true;
1376fc51490bSJonas Devlieghere     }
1377fc51490bSJonas Devlieghere 
1378fc51490bSJonas Devlieghere     error(N, "expected boolean value");
1379fc51490bSJonas Devlieghere     return false;
1380fc51490bSJonas Devlieghere   }
1381fc51490bSJonas Devlieghere 
1382fc51490bSJonas Devlieghere   struct KeyStatus {
1383fc51490bSJonas Devlieghere     bool Required;
1384fc51490bSJonas Devlieghere     bool Seen = false;
1385fc51490bSJonas Devlieghere 
1386fc51490bSJonas Devlieghere     KeyStatus(bool Required = false) : Required(Required) {}
1387fc51490bSJonas Devlieghere   };
1388fc51490bSJonas Devlieghere 
1389fc51490bSJonas Devlieghere   using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1390fc51490bSJonas Devlieghere 
1391fc51490bSJonas Devlieghere   // false on error
1392fc51490bSJonas Devlieghere   bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1393fc51490bSJonas Devlieghere                                   DenseMap<StringRef, KeyStatus> &Keys) {
1394fc51490bSJonas Devlieghere     if (!Keys.count(Key)) {
1395fc51490bSJonas Devlieghere       error(KeyNode, "unknown key");
1396fc51490bSJonas Devlieghere       return false;
1397fc51490bSJonas Devlieghere     }
1398fc51490bSJonas Devlieghere     KeyStatus &S = Keys[Key];
1399fc51490bSJonas Devlieghere     if (S.Seen) {
1400fc51490bSJonas Devlieghere       error(KeyNode, Twine("duplicate key '") + Key + "'");
1401fc51490bSJonas Devlieghere       return false;
1402fc51490bSJonas Devlieghere     }
1403fc51490bSJonas Devlieghere     S.Seen = true;
1404fc51490bSJonas Devlieghere     return true;
1405fc51490bSJonas Devlieghere   }
1406fc51490bSJonas Devlieghere 
1407fc51490bSJonas Devlieghere   // false on error
1408fc51490bSJonas Devlieghere   bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1409fc51490bSJonas Devlieghere     for (const auto &I : Keys) {
1410fc51490bSJonas Devlieghere       if (I.second.Required && !I.second.Seen) {
1411fc51490bSJonas Devlieghere         error(Obj, Twine("missing key '") + I.first + "'");
1412fc51490bSJonas Devlieghere         return false;
1413fc51490bSJonas Devlieghere       }
1414fc51490bSJonas Devlieghere     }
1415fc51490bSJonas Devlieghere     return true;
1416fc51490bSJonas Devlieghere   }
1417fc51490bSJonas Devlieghere 
141875cd8d75SDuncan P. N. Exon Smith public:
141975cd8d75SDuncan P. N. Exon Smith   static RedirectingFileSystem::Entry *
14201a0ce65aSJonas Devlieghere   lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
14211a0ce65aSJonas Devlieghere                       RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1422fc51490bSJonas Devlieghere     if (!ParentEntry) { // Look for a existent root
1423fc51490bSJonas Devlieghere       for (const auto &Root : FS->Roots) {
1424fc51490bSJonas Devlieghere         if (Name.equals(Root->getName())) {
1425fc51490bSJonas Devlieghere           ParentEntry = Root.get();
1426fc51490bSJonas Devlieghere           return ParentEntry;
1427fc51490bSJonas Devlieghere         }
1428fc51490bSJonas Devlieghere       }
1429fc51490bSJonas Devlieghere     } else { // Advance to the next component
1430719f7784SNathan Hawes       auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
14311a0ce65aSJonas Devlieghere       for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1432fc51490bSJonas Devlieghere            llvm::make_range(DE->contents_begin(), DE->contents_end())) {
14331a0ce65aSJonas Devlieghere         auto *DirContent =
1434719f7784SNathan Hawes             dyn_cast<RedirectingFileSystem::DirectoryEntry>(Content.get());
1435fc51490bSJonas Devlieghere         if (DirContent && Name.equals(Content->getName()))
1436fc51490bSJonas Devlieghere           return DirContent;
1437fc51490bSJonas Devlieghere       }
1438fc51490bSJonas Devlieghere     }
1439fc51490bSJonas Devlieghere 
1440fc51490bSJonas Devlieghere     // ... or create a new one
14411a0ce65aSJonas Devlieghere     std::unique_ptr<RedirectingFileSystem::Entry> E =
1442719f7784SNathan Hawes         std::make_unique<RedirectingFileSystem::DirectoryEntry>(
14431a0ce65aSJonas Devlieghere             Name, Status("", getNextVirtualUniqueID(),
14441a0ce65aSJonas Devlieghere                          std::chrono::system_clock::now(), 0, 0, 0,
14451a0ce65aSJonas Devlieghere                          file_type::directory_file, sys::fs::all_all));
1446fc51490bSJonas Devlieghere 
1447fc51490bSJonas Devlieghere     if (!ParentEntry) { // Add a new root to the overlay
1448fc51490bSJonas Devlieghere       FS->Roots.push_back(std::move(E));
1449fc51490bSJonas Devlieghere       ParentEntry = FS->Roots.back().get();
1450fc51490bSJonas Devlieghere       return ParentEntry;
1451fc51490bSJonas Devlieghere     }
1452fc51490bSJonas Devlieghere 
1453719f7784SNathan Hawes     auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
1454fc51490bSJonas Devlieghere     DE->addContent(std::move(E));
1455fc51490bSJonas Devlieghere     return DE->getLastContent();
1456fc51490bSJonas Devlieghere   }
1457fc51490bSJonas Devlieghere 
145875cd8d75SDuncan P. N. Exon Smith private:
14591a0ce65aSJonas Devlieghere   void uniqueOverlayTree(RedirectingFileSystem *FS,
14601a0ce65aSJonas Devlieghere                          RedirectingFileSystem::Entry *SrcE,
14611a0ce65aSJonas Devlieghere                          RedirectingFileSystem::Entry *NewParentE = nullptr) {
1462fc51490bSJonas Devlieghere     StringRef Name = SrcE->getName();
1463fc51490bSJonas Devlieghere     switch (SrcE->getKind()) {
14641a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_Directory: {
1465719f7784SNathan Hawes       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
1466fc51490bSJonas Devlieghere       // Empty directories could be present in the YAML as a way to
1467fc51490bSJonas Devlieghere       // describe a file for a current directory after some of its subdir
1468fc51490bSJonas Devlieghere       // is parsed. This only leads to redundant walks, ignore it.
1469fc51490bSJonas Devlieghere       if (!Name.empty())
1470fc51490bSJonas Devlieghere         NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
14711a0ce65aSJonas Devlieghere       for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1472fc51490bSJonas Devlieghere            llvm::make_range(DE->contents_begin(), DE->contents_end()))
1473fc51490bSJonas Devlieghere         uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1474fc51490bSJonas Devlieghere       break;
1475fc51490bSJonas Devlieghere     }
1476ecb00a77SNathan Hawes     case RedirectingFileSystem::EK_DirectoryRemap: {
1477ecb00a77SNathan Hawes       assert(NewParentE && "Parent entry must exist");
1478ecb00a77SNathan Hawes       auto *DR = cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
1479ecb00a77SNathan Hawes       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1480ecb00a77SNathan Hawes       DE->addContent(
1481ecb00a77SNathan Hawes           std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1482ecb00a77SNathan Hawes               Name, DR->getExternalContentsPath(), DR->getUseName()));
1483ecb00a77SNathan Hawes       break;
1484ecb00a77SNathan Hawes     }
14851a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_File: {
1486fc51490bSJonas Devlieghere       assert(NewParentE && "Parent entry must exist");
1487719f7784SNathan Hawes       auto *FE = cast<RedirectingFileSystem::FileEntry>(SrcE);
1488719f7784SNathan Hawes       auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1489719f7784SNathan Hawes       DE->addContent(std::make_unique<RedirectingFileSystem::FileEntry>(
1490fc51490bSJonas Devlieghere           Name, FE->getExternalContentsPath(), FE->getUseName()));
1491fc51490bSJonas Devlieghere       break;
1492fc51490bSJonas Devlieghere     }
1493fc51490bSJonas Devlieghere     }
1494fc51490bSJonas Devlieghere   }
1495fc51490bSJonas Devlieghere 
14961a0ce65aSJonas Devlieghere   std::unique_ptr<RedirectingFileSystem::Entry>
14971a0ce65aSJonas Devlieghere   parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1498fc51490bSJonas Devlieghere     auto *M = dyn_cast<yaml::MappingNode>(N);
1499fc51490bSJonas Devlieghere     if (!M) {
1500fc51490bSJonas Devlieghere       error(N, "expected mapping node for file or directory entry");
1501fc51490bSJonas Devlieghere       return nullptr;
1502fc51490bSJonas Devlieghere     }
1503fc51490bSJonas Devlieghere 
1504fc51490bSJonas Devlieghere     KeyStatusPair Fields[] = {
1505fc51490bSJonas Devlieghere         KeyStatusPair("name", true),
1506fc51490bSJonas Devlieghere         KeyStatusPair("type", true),
1507fc51490bSJonas Devlieghere         KeyStatusPair("contents", false),
1508fc51490bSJonas Devlieghere         KeyStatusPair("external-contents", false),
1509fc51490bSJonas Devlieghere         KeyStatusPair("use-external-name", false),
1510fc51490bSJonas Devlieghere     };
1511fc51490bSJonas Devlieghere 
1512fc51490bSJonas Devlieghere     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1513fc51490bSJonas Devlieghere 
1514ecb00a77SNathan Hawes     enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet;
15151a0ce65aSJonas Devlieghere     std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
15161a0ce65aSJonas Devlieghere         EntryArrayContents;
1517da45bd23SAdrian McCarthy     SmallString<256> ExternalContentsPath;
1518da45bd23SAdrian McCarthy     SmallString<256> Name;
1519cfe6fe06SSimon Pilgrim     yaml::Node *NameValueNode = nullptr;
1520ecb00a77SNathan Hawes     auto UseExternalName = RedirectingFileSystem::NK_NotSet;
15211a0ce65aSJonas Devlieghere     RedirectingFileSystem::EntryKind Kind;
1522fc51490bSJonas Devlieghere 
1523fc51490bSJonas Devlieghere     for (auto &I : *M) {
1524fc51490bSJonas Devlieghere       StringRef Key;
1525fc51490bSJonas Devlieghere       // Reuse the buffer for key and value, since we don't look at key after
1526fc51490bSJonas Devlieghere       // parsing value.
1527fc51490bSJonas Devlieghere       SmallString<256> Buffer;
1528fc51490bSJonas Devlieghere       if (!parseScalarString(I.getKey(), Key, Buffer))
1529fc51490bSJonas Devlieghere         return nullptr;
1530fc51490bSJonas Devlieghere 
1531fc51490bSJonas Devlieghere       if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1532fc51490bSJonas Devlieghere         return nullptr;
1533fc51490bSJonas Devlieghere 
1534fc51490bSJonas Devlieghere       StringRef Value;
1535fc51490bSJonas Devlieghere       if (Key == "name") {
1536fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), Value, Buffer))
1537fc51490bSJonas Devlieghere           return nullptr;
1538fc51490bSJonas Devlieghere 
1539fc51490bSJonas Devlieghere         NameValueNode = I.getValue();
1540fc51490bSJonas Devlieghere         // Guarantee that old YAML files containing paths with ".." and "."
1541fc51490bSJonas Devlieghere         // are properly canonicalized before read into the VFS.
1542da45bd23SAdrian McCarthy         Name = canonicalize(Value).str();
1543fc51490bSJonas Devlieghere       } else if (Key == "type") {
1544fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), Value, Buffer))
1545fc51490bSJonas Devlieghere           return nullptr;
1546fc51490bSJonas Devlieghere         if (Value == "file")
15471a0ce65aSJonas Devlieghere           Kind = RedirectingFileSystem::EK_File;
1548fc51490bSJonas Devlieghere         else if (Value == "directory")
15491a0ce65aSJonas Devlieghere           Kind = RedirectingFileSystem::EK_Directory;
1550ecb00a77SNathan Hawes         else if (Value == "directory-remap")
1551ecb00a77SNathan Hawes           Kind = RedirectingFileSystem::EK_DirectoryRemap;
1552fc51490bSJonas Devlieghere         else {
1553fc51490bSJonas Devlieghere           error(I.getValue(), "unknown value for 'type'");
1554fc51490bSJonas Devlieghere           return nullptr;
1555fc51490bSJonas Devlieghere         }
1556fc51490bSJonas Devlieghere       } else if (Key == "contents") {
1557ecb00a77SNathan Hawes         if (ContentsField != CF_NotSet) {
1558fc51490bSJonas Devlieghere           error(I.getKey(),
1559fc51490bSJonas Devlieghere                 "entry already has 'contents' or 'external-contents'");
1560fc51490bSJonas Devlieghere           return nullptr;
1561fc51490bSJonas Devlieghere         }
1562ecb00a77SNathan Hawes         ContentsField = CF_List;
1563fc51490bSJonas Devlieghere         auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
1564fc51490bSJonas Devlieghere         if (!Contents) {
1565fc51490bSJonas Devlieghere           // FIXME: this is only for directories, what about files?
1566fc51490bSJonas Devlieghere           error(I.getValue(), "expected array");
1567fc51490bSJonas Devlieghere           return nullptr;
1568fc51490bSJonas Devlieghere         }
1569fc51490bSJonas Devlieghere 
1570fc51490bSJonas Devlieghere         for (auto &I : *Contents) {
15711a0ce65aSJonas Devlieghere           if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1572fc51490bSJonas Devlieghere                   parseEntry(&I, FS, /*IsRootEntry*/ false))
1573fc51490bSJonas Devlieghere             EntryArrayContents.push_back(std::move(E));
1574fc51490bSJonas Devlieghere           else
1575fc51490bSJonas Devlieghere             return nullptr;
1576fc51490bSJonas Devlieghere         }
1577fc51490bSJonas Devlieghere       } else if (Key == "external-contents") {
1578ecb00a77SNathan Hawes         if (ContentsField != CF_NotSet) {
1579fc51490bSJonas Devlieghere           error(I.getKey(),
1580fc51490bSJonas Devlieghere                 "entry already has 'contents' or 'external-contents'");
1581fc51490bSJonas Devlieghere           return nullptr;
1582fc51490bSJonas Devlieghere         }
1583ecb00a77SNathan Hawes         ContentsField = CF_External;
1584fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), Value, Buffer))
1585fc51490bSJonas Devlieghere           return nullptr;
1586fc51490bSJonas Devlieghere 
1587fc51490bSJonas Devlieghere         SmallString<256> FullPath;
1588fc51490bSJonas Devlieghere         if (FS->IsRelativeOverlay) {
1589fc51490bSJonas Devlieghere           FullPath = FS->getExternalContentsPrefixDir();
1590fc51490bSJonas Devlieghere           assert(!FullPath.empty() &&
1591fc51490bSJonas Devlieghere                  "External contents prefix directory must exist");
1592fc51490bSJonas Devlieghere           llvm::sys::path::append(FullPath, Value);
1593fc51490bSJonas Devlieghere         } else {
1594fc51490bSJonas Devlieghere           FullPath = Value;
1595fc51490bSJonas Devlieghere         }
1596fc51490bSJonas Devlieghere 
1597fc51490bSJonas Devlieghere         // Guarantee that old YAML files containing paths with ".." and "."
1598fc51490bSJonas Devlieghere         // are properly canonicalized before read into the VFS.
1599da45bd23SAdrian McCarthy         FullPath = canonicalize(FullPath);
1600da45bd23SAdrian McCarthy         ExternalContentsPath = FullPath.str();
1601fc51490bSJonas Devlieghere       } else if (Key == "use-external-name") {
1602fc51490bSJonas Devlieghere         bool Val;
1603fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), Val))
1604fc51490bSJonas Devlieghere           return nullptr;
1605ecb00a77SNathan Hawes         UseExternalName = Val ? RedirectingFileSystem::NK_External
1606ecb00a77SNathan Hawes                               : RedirectingFileSystem::NK_Virtual;
1607fc51490bSJonas Devlieghere       } else {
1608fc51490bSJonas Devlieghere         llvm_unreachable("key missing from Keys");
1609fc51490bSJonas Devlieghere       }
1610fc51490bSJonas Devlieghere     }
1611fc51490bSJonas Devlieghere 
1612fc51490bSJonas Devlieghere     if (Stream.failed())
1613fc51490bSJonas Devlieghere       return nullptr;
1614fc51490bSJonas Devlieghere 
1615fc51490bSJonas Devlieghere     // check for missing keys
1616ecb00a77SNathan Hawes     if (ContentsField == CF_NotSet) {
1617fc51490bSJonas Devlieghere       error(N, "missing key 'contents' or 'external-contents'");
1618fc51490bSJonas Devlieghere       return nullptr;
1619fc51490bSJonas Devlieghere     }
1620fc51490bSJonas Devlieghere     if (!checkMissingKeys(N, Keys))
1621fc51490bSJonas Devlieghere       return nullptr;
1622fc51490bSJonas Devlieghere 
1623fc51490bSJonas Devlieghere     // check invalid configuration
16241a0ce65aSJonas Devlieghere     if (Kind == RedirectingFileSystem::EK_Directory &&
1625ecb00a77SNathan Hawes         UseExternalName != RedirectingFileSystem::NK_NotSet) {
1626ecb00a77SNathan Hawes       error(N, "'use-external-name' is not supported for 'directory' entries");
1627ecb00a77SNathan Hawes       return nullptr;
1628ecb00a77SNathan Hawes     }
1629ecb00a77SNathan Hawes 
1630ecb00a77SNathan Hawes     if (Kind == RedirectingFileSystem::EK_DirectoryRemap &&
1631ecb00a77SNathan Hawes         ContentsField == CF_List) {
1632ecb00a77SNathan Hawes       error(N, "'contents' is not supported for 'directory-remap' entries");
1633fc51490bSJonas Devlieghere       return nullptr;
1634fc51490bSJonas Devlieghere     }
1635fc51490bSJonas Devlieghere 
1636738b5c96SAdrian McCarthy     sys::path::Style path_style = sys::path::Style::native;
1637738b5c96SAdrian McCarthy     if (IsRootEntry) {
1638738b5c96SAdrian McCarthy       // VFS root entries may be in either Posix or Windows style.  Figure out
1639738b5c96SAdrian McCarthy       // which style we have, and use it consistently.
1640738b5c96SAdrian McCarthy       if (sys::path::is_absolute(Name, sys::path::Style::posix)) {
1641738b5c96SAdrian McCarthy         path_style = sys::path::Style::posix;
164246ec93a4SMartin Storsjö       } else if (sys::path::is_absolute(Name,
164346ec93a4SMartin Storsjö                                         sys::path::Style::windows_backslash)) {
164446ec93a4SMartin Storsjö         path_style = sys::path::Style::windows_backslash;
1645738b5c96SAdrian McCarthy       } else {
1646fc51490bSJonas Devlieghere         assert(NameValueNode && "Name presence should be checked earlier");
1647fc51490bSJonas Devlieghere         error(NameValueNode,
1648fc51490bSJonas Devlieghere               "entry with relative path at the root level is not discoverable");
1649fc51490bSJonas Devlieghere         return nullptr;
1650fc51490bSJonas Devlieghere       }
1651738b5c96SAdrian McCarthy     }
1652fc51490bSJonas Devlieghere 
1653fc51490bSJonas Devlieghere     // Remove trailing slash(es), being careful not to remove the root path
16541def2579SDavid Blaikie     StringRef Trimmed = Name;
1655738b5c96SAdrian McCarthy     size_t RootPathLen = sys::path::root_path(Trimmed, path_style).size();
1656fc51490bSJonas Devlieghere     while (Trimmed.size() > RootPathLen &&
1657738b5c96SAdrian McCarthy            sys::path::is_separator(Trimmed.back(), path_style))
1658fc51490bSJonas Devlieghere       Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
1659738b5c96SAdrian McCarthy 
1660fc51490bSJonas Devlieghere     // Get the last component
1661738b5c96SAdrian McCarthy     StringRef LastComponent = sys::path::filename(Trimmed, path_style);
1662fc51490bSJonas Devlieghere 
16631a0ce65aSJonas Devlieghere     std::unique_ptr<RedirectingFileSystem::Entry> Result;
1664fc51490bSJonas Devlieghere     switch (Kind) {
16651a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_File:
1666719f7784SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::FileEntry>(
1667fc51490bSJonas Devlieghere           LastComponent, std::move(ExternalContentsPath), UseExternalName);
1668fc51490bSJonas Devlieghere       break;
1669ecb00a77SNathan Hawes     case RedirectingFileSystem::EK_DirectoryRemap:
1670ecb00a77SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1671ecb00a77SNathan Hawes           LastComponent, std::move(ExternalContentsPath), UseExternalName);
1672ecb00a77SNathan Hawes       break;
16731a0ce65aSJonas Devlieghere     case RedirectingFileSystem::EK_Directory:
1674719f7784SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1675fc51490bSJonas Devlieghere           LastComponent, std::move(EntryArrayContents),
1676719f7784SNathan Hawes           Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1677719f7784SNathan Hawes                  0, 0, 0, file_type::directory_file, sys::fs::all_all));
1678fc51490bSJonas Devlieghere       break;
1679fc51490bSJonas Devlieghere     }
1680fc51490bSJonas Devlieghere 
1681738b5c96SAdrian McCarthy     StringRef Parent = sys::path::parent_path(Trimmed, path_style);
1682fc51490bSJonas Devlieghere     if (Parent.empty())
1683fc51490bSJonas Devlieghere       return Result;
1684fc51490bSJonas Devlieghere 
1685fc51490bSJonas Devlieghere     // if 'name' contains multiple components, create implicit directory entries
1686738b5c96SAdrian McCarthy     for (sys::path::reverse_iterator I = sys::path::rbegin(Parent, path_style),
1687fc51490bSJonas Devlieghere                                      E = sys::path::rend(Parent);
1688fc51490bSJonas Devlieghere          I != E; ++I) {
16891a0ce65aSJonas Devlieghere       std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
1690fc51490bSJonas Devlieghere       Entries.push_back(std::move(Result));
1691719f7784SNathan Hawes       Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1692fc51490bSJonas Devlieghere           *I, std::move(Entries),
1693719f7784SNathan Hawes           Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1694719f7784SNathan Hawes                  0, 0, 0, file_type::directory_file, sys::fs::all_all));
1695fc51490bSJonas Devlieghere     }
1696fc51490bSJonas Devlieghere     return Result;
1697fc51490bSJonas Devlieghere   }
1698fc51490bSJonas Devlieghere 
1699fc51490bSJonas Devlieghere public:
1700fc51490bSJonas Devlieghere   RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1701fc51490bSJonas Devlieghere 
1702fc51490bSJonas Devlieghere   // false on error
1703fc51490bSJonas Devlieghere   bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1704fc51490bSJonas Devlieghere     auto *Top = dyn_cast<yaml::MappingNode>(Root);
1705fc51490bSJonas Devlieghere     if (!Top) {
1706fc51490bSJonas Devlieghere       error(Root, "expected mapping node");
1707fc51490bSJonas Devlieghere       return false;
1708fc51490bSJonas Devlieghere     }
1709fc51490bSJonas Devlieghere 
1710fc51490bSJonas Devlieghere     KeyStatusPair Fields[] = {
1711fc51490bSJonas Devlieghere         KeyStatusPair("version", true),
1712fc51490bSJonas Devlieghere         KeyStatusPair("case-sensitive", false),
1713fc51490bSJonas Devlieghere         KeyStatusPair("use-external-names", false),
1714fc51490bSJonas Devlieghere         KeyStatusPair("overlay-relative", false),
171591e13164SVolodymyr Sapsai         KeyStatusPair("fallthrough", false),
1716fc51490bSJonas Devlieghere         KeyStatusPair("roots", true),
1717fc51490bSJonas Devlieghere     };
1718fc51490bSJonas Devlieghere 
1719fc51490bSJonas Devlieghere     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
17201a0ce65aSJonas Devlieghere     std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
1721fc51490bSJonas Devlieghere 
1722fc51490bSJonas Devlieghere     // Parse configuration and 'roots'
1723fc51490bSJonas Devlieghere     for (auto &I : *Top) {
1724fc51490bSJonas Devlieghere       SmallString<10> KeyBuffer;
1725fc51490bSJonas Devlieghere       StringRef Key;
1726fc51490bSJonas Devlieghere       if (!parseScalarString(I.getKey(), Key, KeyBuffer))
1727fc51490bSJonas Devlieghere         return false;
1728fc51490bSJonas Devlieghere 
1729fc51490bSJonas Devlieghere       if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1730fc51490bSJonas Devlieghere         return false;
1731fc51490bSJonas Devlieghere 
1732fc51490bSJonas Devlieghere       if (Key == "roots") {
1733fc51490bSJonas Devlieghere         auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
1734fc51490bSJonas Devlieghere         if (!Roots) {
1735fc51490bSJonas Devlieghere           error(I.getValue(), "expected array");
1736fc51490bSJonas Devlieghere           return false;
1737fc51490bSJonas Devlieghere         }
1738fc51490bSJonas Devlieghere 
1739fc51490bSJonas Devlieghere         for (auto &I : *Roots) {
17401a0ce65aSJonas Devlieghere           if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1741fc51490bSJonas Devlieghere                   parseEntry(&I, FS, /*IsRootEntry*/ true))
1742fc51490bSJonas Devlieghere             RootEntries.push_back(std::move(E));
1743fc51490bSJonas Devlieghere           else
1744fc51490bSJonas Devlieghere             return false;
1745fc51490bSJonas Devlieghere         }
1746fc51490bSJonas Devlieghere       } else if (Key == "version") {
1747fc51490bSJonas Devlieghere         StringRef VersionString;
1748fc51490bSJonas Devlieghere         SmallString<4> Storage;
1749fc51490bSJonas Devlieghere         if (!parseScalarString(I.getValue(), VersionString, Storage))
1750fc51490bSJonas Devlieghere           return false;
1751fc51490bSJonas Devlieghere         int Version;
1752fc51490bSJonas Devlieghere         if (VersionString.getAsInteger<int>(10, Version)) {
1753fc51490bSJonas Devlieghere           error(I.getValue(), "expected integer");
1754fc51490bSJonas Devlieghere           return false;
1755fc51490bSJonas Devlieghere         }
1756fc51490bSJonas Devlieghere         if (Version < 0) {
1757fc51490bSJonas Devlieghere           error(I.getValue(), "invalid version number");
1758fc51490bSJonas Devlieghere           return false;
1759fc51490bSJonas Devlieghere         }
1760fc51490bSJonas Devlieghere         if (Version != 0) {
1761fc51490bSJonas Devlieghere           error(I.getValue(), "version mismatch, expected 0");
1762fc51490bSJonas Devlieghere           return false;
1763fc51490bSJonas Devlieghere         }
1764fc51490bSJonas Devlieghere       } else if (Key == "case-sensitive") {
1765fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
1766fc51490bSJonas Devlieghere           return false;
1767fc51490bSJonas Devlieghere       } else if (Key == "overlay-relative") {
1768fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
1769fc51490bSJonas Devlieghere           return false;
1770fc51490bSJonas Devlieghere       } else if (Key == "use-external-names") {
1771fc51490bSJonas Devlieghere         if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
1772fc51490bSJonas Devlieghere           return false;
177391e13164SVolodymyr Sapsai       } else if (Key == "fallthrough") {
177491e13164SVolodymyr Sapsai         if (!parseScalarBool(I.getValue(), FS->IsFallthrough))
177591e13164SVolodymyr Sapsai           return false;
1776fc51490bSJonas Devlieghere       } else {
1777fc51490bSJonas Devlieghere         llvm_unreachable("key missing from Keys");
1778fc51490bSJonas Devlieghere       }
1779fc51490bSJonas Devlieghere     }
1780fc51490bSJonas Devlieghere 
1781fc51490bSJonas Devlieghere     if (Stream.failed())
1782fc51490bSJonas Devlieghere       return false;
1783fc51490bSJonas Devlieghere 
1784fc51490bSJonas Devlieghere     if (!checkMissingKeys(Top, Keys))
1785fc51490bSJonas Devlieghere       return false;
1786fc51490bSJonas Devlieghere 
1787fc51490bSJonas Devlieghere     // Now that we sucessefully parsed the YAML file, canonicalize the internal
1788fc51490bSJonas Devlieghere     // representation to a proper directory tree so that we can search faster
1789fc51490bSJonas Devlieghere     // inside the VFS.
1790fc51490bSJonas Devlieghere     for (auto &E : RootEntries)
1791fc51490bSJonas Devlieghere       uniqueOverlayTree(FS, E.get());
1792fc51490bSJonas Devlieghere 
1793fc51490bSJonas Devlieghere     return true;
1794fc51490bSJonas Devlieghere   }
1795fc51490bSJonas Devlieghere };
1796fc51490bSJonas Devlieghere 
1797a22eda54SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem>
1798fc51490bSJonas Devlieghere RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1799fc51490bSJonas Devlieghere                               SourceMgr::DiagHandlerTy DiagHandler,
1800fc51490bSJonas Devlieghere                               StringRef YAMLFilePath, void *DiagContext,
1801fc51490bSJonas Devlieghere                               IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1802fc51490bSJonas Devlieghere   SourceMgr SM;
1803fc51490bSJonas Devlieghere   yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
1804fc51490bSJonas Devlieghere 
1805fc51490bSJonas Devlieghere   SM.setDiagHandler(DiagHandler, DiagContext);
1806fc51490bSJonas Devlieghere   yaml::document_iterator DI = Stream.begin();
1807fc51490bSJonas Devlieghere   yaml::Node *Root = DI->getRoot();
1808fc51490bSJonas Devlieghere   if (DI == Stream.end() || !Root) {
1809fc51490bSJonas Devlieghere     SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
1810fc51490bSJonas Devlieghere     return nullptr;
1811fc51490bSJonas Devlieghere   }
1812fc51490bSJonas Devlieghere 
1813fc51490bSJonas Devlieghere   RedirectingFileSystemParser P(Stream);
1814fc51490bSJonas Devlieghere 
1815fc51490bSJonas Devlieghere   std::unique_ptr<RedirectingFileSystem> FS(
181621703543SJonas Devlieghere       new RedirectingFileSystem(ExternalFS));
1817fc51490bSJonas Devlieghere 
1818fc51490bSJonas Devlieghere   if (!YAMLFilePath.empty()) {
1819fc51490bSJonas Devlieghere     // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1820fc51490bSJonas Devlieghere     // to each 'external-contents' path.
1821fc51490bSJonas Devlieghere     //
1822fc51490bSJonas Devlieghere     // Example:
1823fc51490bSJonas Devlieghere     //    -ivfsoverlay dummy.cache/vfs/vfs.yaml
1824fc51490bSJonas Devlieghere     // yields:
1825fc51490bSJonas Devlieghere     //  FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1826fc51490bSJonas Devlieghere     //
1827fc51490bSJonas Devlieghere     SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1828fc51490bSJonas Devlieghere     std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1829fc51490bSJonas Devlieghere     assert(!EC && "Overlay dir final path must be absolute");
1830fc51490bSJonas Devlieghere     (void)EC;
1831fc51490bSJonas Devlieghere     FS->setExternalContentsPrefixDir(OverlayAbsDir);
1832fc51490bSJonas Devlieghere   }
1833fc51490bSJonas Devlieghere 
1834fc51490bSJonas Devlieghere   if (!P.parse(Root, FS.get()))
1835fc51490bSJonas Devlieghere     return nullptr;
1836fc51490bSJonas Devlieghere 
1837a22eda54SDuncan P. N. Exon Smith   return FS;
1838fc51490bSJonas Devlieghere }
1839fc51490bSJonas Devlieghere 
184075cd8d75SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create(
184175cd8d75SDuncan P. N. Exon Smith     ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
184275cd8d75SDuncan P. N. Exon Smith     bool UseExternalNames, FileSystem &ExternalFS) {
184375cd8d75SDuncan P. N. Exon Smith   std::unique_ptr<RedirectingFileSystem> FS(
184475cd8d75SDuncan P. N. Exon Smith       new RedirectingFileSystem(&ExternalFS));
184575cd8d75SDuncan P. N. Exon Smith   FS->UseExternalNames = UseExternalNames;
184675cd8d75SDuncan P. N. Exon Smith 
184775cd8d75SDuncan P. N. Exon Smith   StringMap<RedirectingFileSystem::Entry *> Entries;
184875cd8d75SDuncan P. N. Exon Smith 
184975cd8d75SDuncan P. N. Exon Smith   for (auto &Mapping : llvm::reverse(RemappedFiles)) {
185075cd8d75SDuncan P. N. Exon Smith     SmallString<128> From = StringRef(Mapping.first);
185175cd8d75SDuncan P. N. Exon Smith     SmallString<128> To = StringRef(Mapping.second);
185275cd8d75SDuncan P. N. Exon Smith     {
185375cd8d75SDuncan P. N. Exon Smith       auto EC = ExternalFS.makeAbsolute(From);
185475cd8d75SDuncan P. N. Exon Smith       (void)EC;
185575cd8d75SDuncan P. N. Exon Smith       assert(!EC && "Could not make absolute path");
185675cd8d75SDuncan P. N. Exon Smith     }
185775cd8d75SDuncan P. N. Exon Smith 
185875cd8d75SDuncan P. N. Exon Smith     // Check if we've already mapped this file. The first one we see (in the
185975cd8d75SDuncan P. N. Exon Smith     // reverse iteration) wins.
186075cd8d75SDuncan P. N. Exon Smith     RedirectingFileSystem::Entry *&ToEntry = Entries[From];
186175cd8d75SDuncan P. N. Exon Smith     if (ToEntry)
186275cd8d75SDuncan P. N. Exon Smith       continue;
186375cd8d75SDuncan P. N. Exon Smith 
186475cd8d75SDuncan P. N. Exon Smith     // Add parent directories.
186575cd8d75SDuncan P. N. Exon Smith     RedirectingFileSystem::Entry *Parent = nullptr;
186675cd8d75SDuncan P. N. Exon Smith     StringRef FromDirectory = llvm::sys::path::parent_path(From);
186775cd8d75SDuncan P. N. Exon Smith     for (auto I = llvm::sys::path::begin(FromDirectory),
186875cd8d75SDuncan P. N. Exon Smith               E = llvm::sys::path::end(FromDirectory);
186975cd8d75SDuncan P. N. Exon Smith          I != E; ++I) {
187075cd8d75SDuncan P. N. Exon Smith       Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS.get(), *I,
187175cd8d75SDuncan P. N. Exon Smith                                                                 Parent);
187275cd8d75SDuncan P. N. Exon Smith     }
187375cd8d75SDuncan P. N. Exon Smith     assert(Parent && "File without a directory?");
187475cd8d75SDuncan P. N. Exon Smith     {
187575cd8d75SDuncan P. N. Exon Smith       auto EC = ExternalFS.makeAbsolute(To);
187675cd8d75SDuncan P. N. Exon Smith       (void)EC;
187775cd8d75SDuncan P. N. Exon Smith       assert(!EC && "Could not make absolute path");
187875cd8d75SDuncan P. N. Exon Smith     }
187975cd8d75SDuncan P. N. Exon Smith 
188075cd8d75SDuncan P. N. Exon Smith     // Add the file.
1881719f7784SNathan Hawes     auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>(
188275cd8d75SDuncan P. N. Exon Smith         llvm::sys::path::filename(From), To,
1883ecb00a77SNathan Hawes         UseExternalNames ? RedirectingFileSystem::NK_External
1884ecb00a77SNathan Hawes                          : RedirectingFileSystem::NK_Virtual);
188575cd8d75SDuncan P. N. Exon Smith     ToEntry = NewFile.get();
1886719f7784SNathan Hawes     cast<RedirectingFileSystem::DirectoryEntry>(Parent)->addContent(
188775cd8d75SDuncan P. N. Exon Smith         std::move(NewFile));
188875cd8d75SDuncan P. N. Exon Smith   }
188975cd8d75SDuncan P. N. Exon Smith 
189075cd8d75SDuncan P. N. Exon Smith   return FS;
189175cd8d75SDuncan P. N. Exon Smith }
189275cd8d75SDuncan P. N. Exon Smith 
1893ecb00a77SNathan Hawes RedirectingFileSystem::LookupResult::LookupResult(
1894ecb00a77SNathan Hawes     Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
1895ecb00a77SNathan Hawes     : E(E) {
1896ecb00a77SNathan Hawes   assert(E != nullptr);
1897ecb00a77SNathan Hawes   // If the matched entry is a DirectoryRemapEntry, set ExternalRedirect to the
1898ecb00a77SNathan Hawes   // path of the directory it maps to in the external file system plus any
1899ecb00a77SNathan Hawes   // remaining path components in the provided iterator.
1900ecb00a77SNathan Hawes   if (auto *DRE = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(E)) {
1901ecb00a77SNathan Hawes     SmallString<256> Redirect(DRE->getExternalContentsPath());
1902ecb00a77SNathan Hawes     sys::path::append(Redirect, Start, End,
1903ecb00a77SNathan Hawes                       getExistingStyle(DRE->getExternalContentsPath()));
1904ecb00a77SNathan Hawes     ExternalRedirect = std::string(Redirect);
1905ecb00a77SNathan Hawes   }
1906ecb00a77SNathan Hawes }
1907ecb00a77SNathan Hawes 
1908719f7784SNathan Hawes bool RedirectingFileSystem::shouldFallBackToExternalFS(
1909ecb00a77SNathan Hawes     std::error_code EC, RedirectingFileSystem::Entry *E) const {
1910ecb00a77SNathan Hawes   if (E && !isa<RedirectingFileSystem::DirectoryRemapEntry>(E))
1911ecb00a77SNathan Hawes     return false;
1912719f7784SNathan Hawes   return shouldUseExternalFS() && EC == llvm::errc::no_such_file_or_directory;
191349556b87SYang Fan }
1914719f7784SNathan Hawes 
19150be9ca7cSJonas Devlieghere std::error_code
19160be9ca7cSJonas Devlieghere RedirectingFileSystem::makeCanonical(SmallVectorImpl<char> &Path) const {
1917fc51490bSJonas Devlieghere   if (std::error_code EC = makeAbsolute(Path))
1918fc51490bSJonas Devlieghere     return EC;
1919fc51490bSJonas Devlieghere 
19200be9ca7cSJonas Devlieghere   llvm::SmallString<256> CanonicalPath =
19210be9ca7cSJonas Devlieghere       canonicalize(StringRef(Path.data(), Path.size()));
19220be9ca7cSJonas Devlieghere   if (CanonicalPath.empty())
1923fc51490bSJonas Devlieghere     return make_error_code(llvm::errc::invalid_argument);
1924fc51490bSJonas Devlieghere 
19250be9ca7cSJonas Devlieghere   Path.assign(CanonicalPath.begin(), CanonicalPath.end());
19260be9ca7cSJonas Devlieghere   return {};
19270be9ca7cSJonas Devlieghere }
19280be9ca7cSJonas Devlieghere 
1929ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult>
19300be9ca7cSJonas Devlieghere RedirectingFileSystem::lookupPath(StringRef Path) const {
1931fc51490bSJonas Devlieghere   sys::path::const_iterator Start = sys::path::begin(Path);
1932fc51490bSJonas Devlieghere   sys::path::const_iterator End = sys::path::end(Path);
1933fc51490bSJonas Devlieghere   for (const auto &Root : Roots) {
1934ecb00a77SNathan Hawes     ErrorOr<RedirectingFileSystem::LookupResult> Result =
1935ecb00a77SNathan Hawes         lookupPathImpl(Start, End, Root.get());
1936fc51490bSJonas Devlieghere     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1937fc51490bSJonas Devlieghere       return Result;
1938fc51490bSJonas Devlieghere   }
1939fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
1940fc51490bSJonas Devlieghere }
1941fc51490bSJonas Devlieghere 
1942ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult>
1943ecb00a77SNathan Hawes RedirectingFileSystem::lookupPathImpl(
1944ecb00a77SNathan Hawes     sys::path::const_iterator Start, sys::path::const_iterator End,
19451a0ce65aSJonas Devlieghere     RedirectingFileSystem::Entry *From) const {
1946fc51490bSJonas Devlieghere   assert(!isTraversalComponent(*Start) &&
1947fc51490bSJonas Devlieghere          !isTraversalComponent(From->getName()) &&
1948fc51490bSJonas Devlieghere          "Paths should not contain traversal components");
1949fc51490bSJonas Devlieghere 
1950fc51490bSJonas Devlieghere   StringRef FromName = From->getName();
1951fc51490bSJonas Devlieghere 
1952fc51490bSJonas Devlieghere   // Forward the search to the next component in case this is an empty one.
1953fc51490bSJonas Devlieghere   if (!FromName.empty()) {
19541275ab16SAdrian McCarthy     if (!pathComponentMatches(*Start, FromName))
1955fc51490bSJonas Devlieghere       return make_error_code(llvm::errc::no_such_file_or_directory);
1956fc51490bSJonas Devlieghere 
1957fc51490bSJonas Devlieghere     ++Start;
1958fc51490bSJonas Devlieghere 
1959fc51490bSJonas Devlieghere     if (Start == End) {
1960fc51490bSJonas Devlieghere       // Match!
1961ecb00a77SNathan Hawes       return LookupResult(From, Start, End);
1962fc51490bSJonas Devlieghere     }
1963fc51490bSJonas Devlieghere   }
1964fc51490bSJonas Devlieghere 
1965ecb00a77SNathan Hawes   if (isa<RedirectingFileSystem::FileEntry>(From))
1966fc51490bSJonas Devlieghere     return make_error_code(llvm::errc::not_a_directory);
1967fc51490bSJonas Devlieghere 
1968ecb00a77SNathan Hawes   if (isa<RedirectingFileSystem::DirectoryRemapEntry>(From))
1969ecb00a77SNathan Hawes     return LookupResult(From, Start, End);
1970ecb00a77SNathan Hawes 
1971ecb00a77SNathan Hawes   auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(From);
19721a0ce65aSJonas Devlieghere   for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
1973fc51490bSJonas Devlieghere        llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1974ecb00a77SNathan Hawes     ErrorOr<RedirectingFileSystem::LookupResult> Result =
1975ecb00a77SNathan Hawes         lookupPathImpl(Start, End, DirEntry.get());
1976fc51490bSJonas Devlieghere     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1977fc51490bSJonas Devlieghere       return Result;
1978fc51490bSJonas Devlieghere   }
19791275ab16SAdrian McCarthy 
1980fc51490bSJonas Devlieghere   return make_error_code(llvm::errc::no_such_file_or_directory);
1981fc51490bSJonas Devlieghere }
1982fc51490bSJonas Devlieghere 
1983*86e2af80SKeith Smiley static Status getRedirectedFileStatus(const Twine &OriginalPath,
1984*86e2af80SKeith Smiley                                       bool UseExternalNames,
1985fc51490bSJonas Devlieghere                                       Status ExternalStatus) {
1986fc51490bSJonas Devlieghere   Status S = ExternalStatus;
1987fc51490bSJonas Devlieghere   if (!UseExternalNames)
1988*86e2af80SKeith Smiley     S = Status::copyWithNewName(S, OriginalPath);
1989fc51490bSJonas Devlieghere   S.IsVFSMapped = true;
1990fc51490bSJonas Devlieghere   return S;
1991fc51490bSJonas Devlieghere }
1992fc51490bSJonas Devlieghere 
1993ecb00a77SNathan Hawes ErrorOr<Status> RedirectingFileSystem::status(
1994*86e2af80SKeith Smiley     const Twine &CanonicalPath, const Twine &OriginalPath,
1995*86e2af80SKeith Smiley     const RedirectingFileSystem::LookupResult &Result) {
1996ecb00a77SNathan Hawes   if (Optional<StringRef> ExtRedirect = Result.getExternalRedirect()) {
1997*86e2af80SKeith Smiley     SmallString<256> CanonicalRemappedPath((*ExtRedirect).str());
1998*86e2af80SKeith Smiley     if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
1999*86e2af80SKeith Smiley       return EC;
2000*86e2af80SKeith Smiley 
2001*86e2af80SKeith Smiley     ErrorOr<Status> S = ExternalFS->status(CanonicalRemappedPath);
2002ecb00a77SNathan Hawes     if (!S)
2003fc51490bSJonas Devlieghere       return S;
2004*86e2af80SKeith Smiley     S = Status::copyWithNewName(*S, *ExtRedirect);
2005ecb00a77SNathan Hawes     auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result.E);
2006*86e2af80SKeith Smiley     return getRedirectedFileStatus(OriginalPath,
2007*86e2af80SKeith Smiley                                    RE->useExternalName(UseExternalNames), *S);
2008fc51490bSJonas Devlieghere   }
2009ecb00a77SNathan Hawes 
2010ecb00a77SNathan Hawes   auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Result.E);
2011*86e2af80SKeith Smiley   return Status::copyWithNewName(DE->getStatus(), CanonicalPath);
2012fc51490bSJonas Devlieghere }
2013fc51490bSJonas Devlieghere 
2014*86e2af80SKeith Smiley ErrorOr<Status>
2015*86e2af80SKeith Smiley RedirectingFileSystem::getExternalStatus(const Twine &CanonicalPath,
2016*86e2af80SKeith Smiley                                          const Twine &OriginalPath) const {
2017*86e2af80SKeith Smiley   if (auto Result = ExternalFS->status(CanonicalPath)) {
2018*86e2af80SKeith Smiley     return Result.get().copyWithNewName(Result.get(), OriginalPath);
2019*86e2af80SKeith Smiley   } else {
2020*86e2af80SKeith Smiley     return Result.getError();
2021*86e2af80SKeith Smiley   }
2022*86e2af80SKeith Smiley }
20230be9ca7cSJonas Devlieghere 
2024*86e2af80SKeith Smiley ErrorOr<Status> RedirectingFileSystem::status(const Twine &OriginalPath) {
2025*86e2af80SKeith Smiley   SmallString<256> CanonicalPath;
2026*86e2af80SKeith Smiley   OriginalPath.toVector(CanonicalPath);
2027*86e2af80SKeith Smiley 
2028*86e2af80SKeith Smiley   if (std::error_code EC = makeCanonical(CanonicalPath))
20290be9ca7cSJonas Devlieghere     return EC;
20300be9ca7cSJonas Devlieghere 
2031*86e2af80SKeith Smiley   ErrorOr<RedirectingFileSystem::LookupResult> Result =
2032*86e2af80SKeith Smiley       lookupPath(CanonicalPath);
203391e13164SVolodymyr Sapsai   if (!Result) {
2034*86e2af80SKeith Smiley     if (shouldFallBackToExternalFS(Result.getError())) {
2035*86e2af80SKeith Smiley       return getExternalStatus(CanonicalPath, OriginalPath);
2036*86e2af80SKeith Smiley     }
2037fc51490bSJonas Devlieghere     return Result.getError();
203891e13164SVolodymyr Sapsai   }
2039ecb00a77SNathan Hawes 
2040*86e2af80SKeith Smiley   ErrorOr<Status> S = status(CanonicalPath, OriginalPath, *Result);
2041*86e2af80SKeith Smiley   if (!S && shouldFallBackToExternalFS(S.getError(), Result->E)) {
2042*86e2af80SKeith Smiley     return getExternalStatus(CanonicalPath, OriginalPath);
2043*86e2af80SKeith Smiley   }
2044*86e2af80SKeith Smiley 
2045ecb00a77SNathan Hawes   return S;
2046fc51490bSJonas Devlieghere }
2047fc51490bSJonas Devlieghere 
2048fc51490bSJonas Devlieghere namespace {
2049fc51490bSJonas Devlieghere 
2050fc51490bSJonas Devlieghere /// Provide a file wrapper with an overriden status.
2051fc51490bSJonas Devlieghere class FileWithFixedStatus : public File {
2052fc51490bSJonas Devlieghere   std::unique_ptr<File> InnerFile;
2053fc51490bSJonas Devlieghere   Status S;
2054fc51490bSJonas Devlieghere 
2055fc51490bSJonas Devlieghere public:
2056fc51490bSJonas Devlieghere   FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
2057fc51490bSJonas Devlieghere       : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
2058fc51490bSJonas Devlieghere 
2059fc51490bSJonas Devlieghere   ErrorOr<Status> status() override { return S; }
2060fc51490bSJonas Devlieghere   ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2061fc51490bSJonas Devlieghere 
2062fc51490bSJonas Devlieghere   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
2063fc51490bSJonas Devlieghere             bool IsVolatile) override {
2064fc51490bSJonas Devlieghere     return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
2065fc51490bSJonas Devlieghere                                 IsVolatile);
2066fc51490bSJonas Devlieghere   }
2067fc51490bSJonas Devlieghere 
2068fc51490bSJonas Devlieghere   std::error_code close() override { return InnerFile->close(); }
2069*86e2af80SKeith Smiley 
2070*86e2af80SKeith Smiley   void setPath(const Twine &Path) override { S = S.copyWithNewName(S, Path); }
2071fc51490bSJonas Devlieghere };
2072fc51490bSJonas Devlieghere 
2073fc51490bSJonas Devlieghere } // namespace
2074fc51490bSJonas Devlieghere 
2075fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
2076*86e2af80SKeith Smiley File::getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P) {
2077*86e2af80SKeith Smiley   if (!Result)
2078*86e2af80SKeith Smiley     return Result;
20790be9ca7cSJonas Devlieghere 
2080*86e2af80SKeith Smiley   ErrorOr<std::unique_ptr<File>> F = std::move(*Result);
2081*86e2af80SKeith Smiley   auto Name = F->get()->getName();
2082*86e2af80SKeith Smiley   if (Name && Name.get() != P.str())
2083*86e2af80SKeith Smiley     F->get()->setPath(P);
2084*86e2af80SKeith Smiley   return F;
2085*86e2af80SKeith Smiley }
2086*86e2af80SKeith Smiley 
2087*86e2af80SKeith Smiley ErrorOr<std::unique_ptr<File>>
2088*86e2af80SKeith Smiley RedirectingFileSystem::openFileForRead(const Twine &OriginalPath) {
2089*86e2af80SKeith Smiley   SmallString<256> CanonicalPath;
2090*86e2af80SKeith Smiley   OriginalPath.toVector(CanonicalPath);
2091*86e2af80SKeith Smiley 
2092*86e2af80SKeith Smiley   if (std::error_code EC = makeCanonical(CanonicalPath))
20930be9ca7cSJonas Devlieghere     return EC;
20940be9ca7cSJonas Devlieghere 
2095*86e2af80SKeith Smiley   ErrorOr<RedirectingFileSystem::LookupResult> Result =
2096*86e2af80SKeith Smiley       lookupPath(CanonicalPath);
2097ecb00a77SNathan Hawes   if (!Result) {
2098ecb00a77SNathan Hawes     if (shouldFallBackToExternalFS(Result.getError()))
2099*86e2af80SKeith Smiley       return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
2100*86e2af80SKeith Smiley                                OriginalPath);
2101*86e2af80SKeith Smiley 
2102ecb00a77SNathan Hawes     return Result.getError();
210391e13164SVolodymyr Sapsai   }
2104fc51490bSJonas Devlieghere 
2105ecb00a77SNathan Hawes   if (!Result->getExternalRedirect()) // FIXME: errc::not_a_file?
2106fc51490bSJonas Devlieghere     return make_error_code(llvm::errc::invalid_argument);
2107fc51490bSJonas Devlieghere 
2108ecb00a77SNathan Hawes   StringRef ExtRedirect = *Result->getExternalRedirect();
2109*86e2af80SKeith Smiley   SmallString<256> CanonicalRemappedPath(ExtRedirect.str());
2110*86e2af80SKeith Smiley   if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
2111*86e2af80SKeith Smiley     return EC;
2112*86e2af80SKeith Smiley 
2113ecb00a77SNathan Hawes   auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
2114fc51490bSJonas Devlieghere 
2115*86e2af80SKeith Smiley   auto ExternalFile = File::getWithPath(
2116*86e2af80SKeith Smiley       ExternalFS->openFileForRead(CanonicalRemappedPath), ExtRedirect);
2117ecb00a77SNathan Hawes   if (!ExternalFile) {
2118ecb00a77SNathan Hawes     if (shouldFallBackToExternalFS(ExternalFile.getError(), Result->E))
2119*86e2af80SKeith Smiley       return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
2120*86e2af80SKeith Smiley                                OriginalPath);
2121ecb00a77SNathan Hawes     return ExternalFile;
2122ecb00a77SNathan Hawes   }
2123ecb00a77SNathan Hawes 
2124ecb00a77SNathan Hawes   auto ExternalStatus = (*ExternalFile)->status();
2125fc51490bSJonas Devlieghere   if (!ExternalStatus)
2126fc51490bSJonas Devlieghere     return ExternalStatus.getError();
2127fc51490bSJonas Devlieghere 
2128fc51490bSJonas Devlieghere   // FIXME: Update the status with the name and VFSMapped.
2129ecb00a77SNathan Hawes   Status S = getRedirectedFileStatus(
2130*86e2af80SKeith Smiley       OriginalPath, RE->useExternalName(UseExternalNames), *ExternalStatus);
2131fc51490bSJonas Devlieghere   return std::unique_ptr<File>(
2132ecb00a77SNathan Hawes       std::make_unique<FileWithFixedStatus>(std::move(*ExternalFile), S));
2133fc51490bSJonas Devlieghere }
2134fc51490bSJonas Devlieghere 
21357610033fSVolodymyr Sapsai std::error_code
21360be9ca7cSJonas Devlieghere RedirectingFileSystem::getRealPath(const Twine &Path_,
21377610033fSVolodymyr Sapsai                                    SmallVectorImpl<char> &Output) const {
21380be9ca7cSJonas Devlieghere   SmallString<256> Path;
21390be9ca7cSJonas Devlieghere   Path_.toVector(Path);
21400be9ca7cSJonas Devlieghere 
21410be9ca7cSJonas Devlieghere   if (std::error_code EC = makeCanonical(Path))
21420be9ca7cSJonas Devlieghere     return EC;
21430be9ca7cSJonas Devlieghere 
2144ecb00a77SNathan Hawes   ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
21457610033fSVolodymyr Sapsai   if (!Result) {
2146719f7784SNathan Hawes     if (shouldFallBackToExternalFS(Result.getError()))
21477610033fSVolodymyr Sapsai       return ExternalFS->getRealPath(Path, Output);
21487610033fSVolodymyr Sapsai     return Result.getError();
21497610033fSVolodymyr Sapsai   }
21507610033fSVolodymyr Sapsai 
2151ecb00a77SNathan Hawes   // If we found FileEntry or DirectoryRemapEntry, look up the mapped
2152ecb00a77SNathan Hawes   // path in the external file system.
2153ecb00a77SNathan Hawes   if (auto ExtRedirect = Result->getExternalRedirect()) {
2154ecb00a77SNathan Hawes     auto P = ExternalFS->getRealPath(*ExtRedirect, Output);
2155ecb00a77SNathan Hawes     if (!P && shouldFallBackToExternalFS(P, Result->E)) {
2156ecb00a77SNathan Hawes       return ExternalFS->getRealPath(Path, Output);
21577610033fSVolodymyr Sapsai     }
2158ecb00a77SNathan Hawes     return P;
2159ecb00a77SNathan Hawes   }
2160ecb00a77SNathan Hawes 
2161ecb00a77SNathan Hawes   // If we found a DirectoryEntry, still fall back to ExternalFS if allowed,
21627610033fSVolodymyr Sapsai   // because directories don't have a single external contents path.
216321703543SJonas Devlieghere   return shouldUseExternalFS() ? ExternalFS->getRealPath(Path, Output)
21647610033fSVolodymyr Sapsai                                : llvm::errc::invalid_argument;
21657610033fSVolodymyr Sapsai }
21667610033fSVolodymyr Sapsai 
2167a22eda54SDuncan P. N. Exon Smith std::unique_ptr<FileSystem>
2168fc51490bSJonas Devlieghere vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2169fc51490bSJonas Devlieghere                     SourceMgr::DiagHandlerTy DiagHandler,
2170fc51490bSJonas Devlieghere                     StringRef YAMLFilePath, void *DiagContext,
2171fc51490bSJonas Devlieghere                     IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2172fc51490bSJonas Devlieghere   return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
2173fc51490bSJonas Devlieghere                                        YAMLFilePath, DiagContext,
2174fc51490bSJonas Devlieghere                                        std::move(ExternalFS));
2175fc51490bSJonas Devlieghere }
2176fc51490bSJonas Devlieghere 
21771a0ce65aSJonas Devlieghere static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
21781a0ce65aSJonas Devlieghere                           SmallVectorImpl<StringRef> &Path,
2179fc51490bSJonas Devlieghere                           SmallVectorImpl<YAMLVFSEntry> &Entries) {
2180fc51490bSJonas Devlieghere   auto Kind = SrcE->getKind();
21811a0ce65aSJonas Devlieghere   if (Kind == RedirectingFileSystem::EK_Directory) {
2182719f7784SNathan Hawes     auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
2183fc51490bSJonas Devlieghere     assert(DE && "Must be a directory");
21841a0ce65aSJonas Devlieghere     for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
2185fc51490bSJonas Devlieghere          llvm::make_range(DE->contents_begin(), DE->contents_end())) {
2186fc51490bSJonas Devlieghere       Path.push_back(SubEntry->getName());
2187fc51490bSJonas Devlieghere       getVFSEntries(SubEntry.get(), Path, Entries);
2188fc51490bSJonas Devlieghere       Path.pop_back();
2189fc51490bSJonas Devlieghere     }
2190fc51490bSJonas Devlieghere     return;
2191fc51490bSJonas Devlieghere   }
2192fc51490bSJonas Devlieghere 
2193ecb00a77SNathan Hawes   if (Kind == RedirectingFileSystem::EK_DirectoryRemap) {
2194ecb00a77SNathan Hawes     auto *DR = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
2195ecb00a77SNathan Hawes     assert(DR && "Must be a directory remap");
2196ecb00a77SNathan Hawes     SmallString<128> VPath;
2197ecb00a77SNathan Hawes     for (auto &Comp : Path)
2198ecb00a77SNathan Hawes       llvm::sys::path::append(VPath, Comp);
2199ecb00a77SNathan Hawes     Entries.push_back(
2200ecb00a77SNathan Hawes         YAMLVFSEntry(VPath.c_str(), DR->getExternalContentsPath()));
2201ecb00a77SNathan Hawes     return;
2202ecb00a77SNathan Hawes   }
2203ecb00a77SNathan Hawes 
22041a0ce65aSJonas Devlieghere   assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
2205719f7784SNathan Hawes   auto *FE = dyn_cast<RedirectingFileSystem::FileEntry>(SrcE);
2206fc51490bSJonas Devlieghere   assert(FE && "Must be a file");
2207fc51490bSJonas Devlieghere   SmallString<128> VPath;
2208fc51490bSJonas Devlieghere   for (auto &Comp : Path)
2209fc51490bSJonas Devlieghere     llvm::sys::path::append(VPath, Comp);
2210fc51490bSJonas Devlieghere   Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
2211fc51490bSJonas Devlieghere }
2212fc51490bSJonas Devlieghere 
2213fc51490bSJonas Devlieghere void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2214fc51490bSJonas Devlieghere                              SourceMgr::DiagHandlerTy DiagHandler,
2215fc51490bSJonas Devlieghere                              StringRef YAMLFilePath,
2216fc51490bSJonas Devlieghere                              SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
2217fc51490bSJonas Devlieghere                              void *DiagContext,
2218fc51490bSJonas Devlieghere                              IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2219a22eda54SDuncan P. N. Exon Smith   std::unique_ptr<RedirectingFileSystem> VFS = RedirectingFileSystem::create(
2220fc51490bSJonas Devlieghere       std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
2221fc51490bSJonas Devlieghere       std::move(ExternalFS));
22222509f9fbSAlex Lorenz   if (!VFS)
22232509f9fbSAlex Lorenz     return;
2224ecb00a77SNathan Hawes   ErrorOr<RedirectingFileSystem::LookupResult> RootResult =
2225ecb00a77SNathan Hawes       VFS->lookupPath("/");
2226ecb00a77SNathan Hawes   if (!RootResult)
2227fc51490bSJonas Devlieghere     return;
2228fc51490bSJonas Devlieghere   SmallVector<StringRef, 8> Components;
2229fc51490bSJonas Devlieghere   Components.push_back("/");
2230ecb00a77SNathan Hawes   getVFSEntries(RootResult->E, Components, CollectedEntries);
2231fc51490bSJonas Devlieghere }
2232fc51490bSJonas Devlieghere 
2233fc51490bSJonas Devlieghere UniqueID vfs::getNextVirtualUniqueID() {
2234fc51490bSJonas Devlieghere   static std::atomic<unsigned> UID;
2235fc51490bSJonas Devlieghere   unsigned ID = ++UID;
2236fc51490bSJonas Devlieghere   // The following assumes that uint64_t max will never collide with a real
2237fc51490bSJonas Devlieghere   // dev_t value from the OS.
2238fc51490bSJonas Devlieghere   return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
2239fc51490bSJonas Devlieghere }
2240fc51490bSJonas Devlieghere 
22413ef33e69SJonas Devlieghere void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath,
22423ef33e69SJonas Devlieghere                              bool IsDirectory) {
2243fc51490bSJonas Devlieghere   assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
2244fc51490bSJonas Devlieghere   assert(sys::path::is_absolute(RealPath) && "real path not absolute");
2245fc51490bSJonas Devlieghere   assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
22463ef33e69SJonas Devlieghere   Mappings.emplace_back(VirtualPath, RealPath, IsDirectory);
22473ef33e69SJonas Devlieghere }
22483ef33e69SJonas Devlieghere 
22493ef33e69SJonas Devlieghere void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
22503ef33e69SJonas Devlieghere   addEntry(VirtualPath, RealPath, /*IsDirectory=*/false);
22513ef33e69SJonas Devlieghere }
22523ef33e69SJonas Devlieghere 
22533ef33e69SJonas Devlieghere void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath,
22543ef33e69SJonas Devlieghere                                         StringRef RealPath) {
22553ef33e69SJonas Devlieghere   addEntry(VirtualPath, RealPath, /*IsDirectory=*/true);
2256fc51490bSJonas Devlieghere }
2257fc51490bSJonas Devlieghere 
2258fc51490bSJonas Devlieghere namespace {
2259fc51490bSJonas Devlieghere 
2260fc51490bSJonas Devlieghere class JSONWriter {
2261fc51490bSJonas Devlieghere   llvm::raw_ostream &OS;
2262fc51490bSJonas Devlieghere   SmallVector<StringRef, 16> DirStack;
2263fc51490bSJonas Devlieghere 
2264fc51490bSJonas Devlieghere   unsigned getDirIndent() { return 4 * DirStack.size(); }
2265fc51490bSJonas Devlieghere   unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
2266fc51490bSJonas Devlieghere   bool containedIn(StringRef Parent, StringRef Path);
2267fc51490bSJonas Devlieghere   StringRef containedPart(StringRef Parent, StringRef Path);
2268fc51490bSJonas Devlieghere   void startDirectory(StringRef Path);
2269fc51490bSJonas Devlieghere   void endDirectory();
2270fc51490bSJonas Devlieghere   void writeEntry(StringRef VPath, StringRef RPath);
2271fc51490bSJonas Devlieghere 
2272fc51490bSJonas Devlieghere public:
2273fc51490bSJonas Devlieghere   JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
2274fc51490bSJonas Devlieghere 
2275fc51490bSJonas Devlieghere   void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
2276fc51490bSJonas Devlieghere              Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
22777faf7ae0SVolodymyr Sapsai              StringRef OverlayDir);
2278fc51490bSJonas Devlieghere };
2279fc51490bSJonas Devlieghere 
2280fc51490bSJonas Devlieghere } // namespace
2281fc51490bSJonas Devlieghere 
2282fc51490bSJonas Devlieghere bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2283fc51490bSJonas Devlieghere   using namespace llvm::sys;
2284fc51490bSJonas Devlieghere 
2285fc51490bSJonas Devlieghere   // Compare each path component.
2286fc51490bSJonas Devlieghere   auto IParent = path::begin(Parent), EParent = path::end(Parent);
2287fc51490bSJonas Devlieghere   for (auto IChild = path::begin(Path), EChild = path::end(Path);
2288fc51490bSJonas Devlieghere        IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2289fc51490bSJonas Devlieghere     if (*IParent != *IChild)
2290fc51490bSJonas Devlieghere       return false;
2291fc51490bSJonas Devlieghere   }
2292fc51490bSJonas Devlieghere   // Have we exhausted the parent path?
2293fc51490bSJonas Devlieghere   return IParent == EParent;
2294fc51490bSJonas Devlieghere }
2295fc51490bSJonas Devlieghere 
2296fc51490bSJonas Devlieghere StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2297fc51490bSJonas Devlieghere   assert(!Parent.empty());
2298fc51490bSJonas Devlieghere   assert(containedIn(Parent, Path));
2299fc51490bSJonas Devlieghere   return Path.slice(Parent.size() + 1, StringRef::npos);
2300fc51490bSJonas Devlieghere }
2301fc51490bSJonas Devlieghere 
2302fc51490bSJonas Devlieghere void JSONWriter::startDirectory(StringRef Path) {
2303fc51490bSJonas Devlieghere   StringRef Name =
2304fc51490bSJonas Devlieghere       DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
2305fc51490bSJonas Devlieghere   DirStack.push_back(Path);
2306fc51490bSJonas Devlieghere   unsigned Indent = getDirIndent();
2307fc51490bSJonas Devlieghere   OS.indent(Indent) << "{\n";
2308fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'type': 'directory',\n";
2309fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
2310fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'contents': [\n";
2311fc51490bSJonas Devlieghere }
2312fc51490bSJonas Devlieghere 
2313fc51490bSJonas Devlieghere void JSONWriter::endDirectory() {
2314fc51490bSJonas Devlieghere   unsigned Indent = getDirIndent();
2315fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "]\n";
2316fc51490bSJonas Devlieghere   OS.indent(Indent) << "}";
2317fc51490bSJonas Devlieghere 
2318fc51490bSJonas Devlieghere   DirStack.pop_back();
2319fc51490bSJonas Devlieghere }
2320fc51490bSJonas Devlieghere 
2321fc51490bSJonas Devlieghere void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2322fc51490bSJonas Devlieghere   unsigned Indent = getFileIndent();
2323fc51490bSJonas Devlieghere   OS.indent(Indent) << "{\n";
2324fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'type': 'file',\n";
2325fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
2326fc51490bSJonas Devlieghere   OS.indent(Indent + 2) << "'external-contents': \""
2327fc51490bSJonas Devlieghere                         << llvm::yaml::escape(RPath) << "\"\n";
2328fc51490bSJonas Devlieghere   OS.indent(Indent) << "}";
2329fc51490bSJonas Devlieghere }
2330fc51490bSJonas Devlieghere 
2331fc51490bSJonas Devlieghere void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
2332fc51490bSJonas Devlieghere                        Optional<bool> UseExternalNames,
2333fc51490bSJonas Devlieghere                        Optional<bool> IsCaseSensitive,
2334fc51490bSJonas Devlieghere                        Optional<bool> IsOverlayRelative,
2335fc51490bSJonas Devlieghere                        StringRef OverlayDir) {
2336fc51490bSJonas Devlieghere   using namespace llvm::sys;
2337fc51490bSJonas Devlieghere 
2338fc51490bSJonas Devlieghere   OS << "{\n"
2339fc51490bSJonas Devlieghere         "  'version': 0,\n";
2340fc51490bSJonas Devlieghere   if (IsCaseSensitive.hasValue())
2341fc51490bSJonas Devlieghere     OS << "  'case-sensitive': '"
2342fc51490bSJonas Devlieghere        << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
2343fc51490bSJonas Devlieghere   if (UseExternalNames.hasValue())
2344fc51490bSJonas Devlieghere     OS << "  'use-external-names': '"
2345fc51490bSJonas Devlieghere        << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
2346fc51490bSJonas Devlieghere   bool UseOverlayRelative = false;
2347fc51490bSJonas Devlieghere   if (IsOverlayRelative.hasValue()) {
2348fc51490bSJonas Devlieghere     UseOverlayRelative = IsOverlayRelative.getValue();
2349fc51490bSJonas Devlieghere     OS << "  'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2350fc51490bSJonas Devlieghere        << "',\n";
2351fc51490bSJonas Devlieghere   }
2352fc51490bSJonas Devlieghere   OS << "  'roots': [\n";
2353fc51490bSJonas Devlieghere 
2354fc51490bSJonas Devlieghere   if (!Entries.empty()) {
2355fc51490bSJonas Devlieghere     const YAMLVFSEntry &Entry = Entries.front();
2356759465eeSJan Korous 
2357759465eeSJan Korous     startDirectory(
2358759465eeSJan Korous       Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath)
2359759465eeSJan Korous     );
2360fc51490bSJonas Devlieghere 
2361fc51490bSJonas Devlieghere     StringRef RPath = Entry.RPath;
2362fc51490bSJonas Devlieghere     if (UseOverlayRelative) {
2363fc51490bSJonas Devlieghere       unsigned OverlayDirLen = OverlayDir.size();
2364fc51490bSJonas Devlieghere       assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2365fc51490bSJonas Devlieghere              "Overlay dir must be contained in RPath");
2366fc51490bSJonas Devlieghere       RPath = RPath.slice(OverlayDirLen, RPath.size());
2367fc51490bSJonas Devlieghere     }
2368fc51490bSJonas Devlieghere 
2369759465eeSJan Korous     bool IsCurrentDirEmpty = true;
2370759465eeSJan Korous     if (!Entry.IsDirectory) {
2371fc51490bSJonas Devlieghere       writeEntry(path::filename(Entry.VPath), RPath);
2372759465eeSJan Korous       IsCurrentDirEmpty = false;
2373759465eeSJan Korous     }
2374fc51490bSJonas Devlieghere 
2375fc51490bSJonas Devlieghere     for (const auto &Entry : Entries.slice(1)) {
23763ef33e69SJonas Devlieghere       StringRef Dir =
23773ef33e69SJonas Devlieghere           Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath);
23783ef33e69SJonas Devlieghere       if (Dir == DirStack.back()) {
2379759465eeSJan Korous         if (!IsCurrentDirEmpty) {
2380fc51490bSJonas Devlieghere           OS << ",\n";
23813ef33e69SJonas Devlieghere         }
23823ef33e69SJonas Devlieghere       } else {
2383759465eeSJan Korous         bool IsDirPoppedFromStack = false;
2384fc51490bSJonas Devlieghere         while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2385fc51490bSJonas Devlieghere           OS << "\n";
2386fc51490bSJonas Devlieghere           endDirectory();
2387759465eeSJan Korous           IsDirPoppedFromStack = true;
2388fc51490bSJonas Devlieghere         }
2389759465eeSJan Korous         if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
2390fc51490bSJonas Devlieghere           OS << ",\n";
2391759465eeSJan Korous         }
2392fc51490bSJonas Devlieghere         startDirectory(Dir);
2393759465eeSJan Korous         IsCurrentDirEmpty = true;
2394fc51490bSJonas Devlieghere       }
2395fc51490bSJonas Devlieghere       StringRef RPath = Entry.RPath;
2396fc51490bSJonas Devlieghere       if (UseOverlayRelative) {
2397fc51490bSJonas Devlieghere         unsigned OverlayDirLen = OverlayDir.size();
2398fc51490bSJonas Devlieghere         assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2399fc51490bSJonas Devlieghere                "Overlay dir must be contained in RPath");
2400fc51490bSJonas Devlieghere         RPath = RPath.slice(OverlayDirLen, RPath.size());
2401fc51490bSJonas Devlieghere       }
2402759465eeSJan Korous       if (!Entry.IsDirectory) {
2403fc51490bSJonas Devlieghere         writeEntry(path::filename(Entry.VPath), RPath);
2404759465eeSJan Korous         IsCurrentDirEmpty = false;
2405759465eeSJan Korous       }
2406fc51490bSJonas Devlieghere     }
2407fc51490bSJonas Devlieghere 
2408fc51490bSJonas Devlieghere     while (!DirStack.empty()) {
2409fc51490bSJonas Devlieghere       OS << "\n";
2410fc51490bSJonas Devlieghere       endDirectory();
2411fc51490bSJonas Devlieghere     }
2412fc51490bSJonas Devlieghere     OS << "\n";
2413fc51490bSJonas Devlieghere   }
2414fc51490bSJonas Devlieghere 
2415fc51490bSJonas Devlieghere   OS << "  ]\n"
2416fc51490bSJonas Devlieghere      << "}\n";
2417fc51490bSJonas Devlieghere }
2418fc51490bSJonas Devlieghere 
2419fc51490bSJonas Devlieghere void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2420fc51490bSJonas Devlieghere   llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2421fc51490bSJonas Devlieghere     return LHS.VPath < RHS.VPath;
2422fc51490bSJonas Devlieghere   });
2423fc51490bSJonas Devlieghere 
2424fc51490bSJonas Devlieghere   JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
24257faf7ae0SVolodymyr Sapsai                        IsOverlayRelative, OverlayDir);
2426fc51490bSJonas Devlieghere }
2427fc51490bSJonas Devlieghere 
2428fc51490bSJonas Devlieghere vfs::recursive_directory_iterator::recursive_directory_iterator(
2429fc51490bSJonas Devlieghere     FileSystem &FS_, const Twine &Path, std::error_code &EC)
2430fc51490bSJonas Devlieghere     : FS(&FS_) {
2431fc51490bSJonas Devlieghere   directory_iterator I = FS->dir_begin(Path, EC);
2432fc51490bSJonas Devlieghere   if (I != directory_iterator()) {
243341fb951fSJonas Devlieghere     State = std::make_shared<detail::RecDirIterState>();
243441fb951fSJonas Devlieghere     State->Stack.push(I);
2435fc51490bSJonas Devlieghere   }
2436fc51490bSJonas Devlieghere }
2437fc51490bSJonas Devlieghere 
2438fc51490bSJonas Devlieghere vfs::recursive_directory_iterator &
2439fc51490bSJonas Devlieghere recursive_directory_iterator::increment(std::error_code &EC) {
244041fb951fSJonas Devlieghere   assert(FS && State && !State->Stack.empty() && "incrementing past end");
244141fb951fSJonas Devlieghere   assert(!State->Stack.top()->path().empty() && "non-canonical end iterator");
2442fc51490bSJonas Devlieghere   vfs::directory_iterator End;
244341fb951fSJonas Devlieghere 
244441fb951fSJonas Devlieghere   if (State->HasNoPushRequest)
244541fb951fSJonas Devlieghere     State->HasNoPushRequest = false;
244641fb951fSJonas Devlieghere   else {
244741fb951fSJonas Devlieghere     if (State->Stack.top()->type() == sys::fs::file_type::directory_file) {
244841fb951fSJonas Devlieghere       vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC);
2449fc51490bSJonas Devlieghere       if (I != End) {
245041fb951fSJonas Devlieghere         State->Stack.push(I);
2451fc51490bSJonas Devlieghere         return *this;
2452fc51490bSJonas Devlieghere       }
2453fc51490bSJonas Devlieghere     }
245441fb951fSJonas Devlieghere   }
2455fc51490bSJonas Devlieghere 
245641fb951fSJonas Devlieghere   while (!State->Stack.empty() && State->Stack.top().increment(EC) == End)
245741fb951fSJonas Devlieghere     State->Stack.pop();
2458fc51490bSJonas Devlieghere 
245941fb951fSJonas Devlieghere   if (State->Stack.empty())
2460fc51490bSJonas Devlieghere     State.reset(); // end iterator
2461fc51490bSJonas Devlieghere 
2462fc51490bSJonas Devlieghere   return *this;
2463fc51490bSJonas Devlieghere }
2464