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/SMLoc.h"
39fc51490bSJonas Devlieghere #include "llvm/Support/SourceMgr.h"
40fc51490bSJonas Devlieghere #include "llvm/Support/YAMLParser.h"
41fc51490bSJonas Devlieghere #include "llvm/Support/raw_ostream.h"
42fc51490bSJonas Devlieghere #include <algorithm>
43fc51490bSJonas Devlieghere #include <atomic>
44fc51490bSJonas Devlieghere #include <cassert>
45fc51490bSJonas Devlieghere #include <cstdint>
46fc51490bSJonas Devlieghere #include <iterator>
47fc51490bSJonas Devlieghere #include <limits>
48fc51490bSJonas Devlieghere #include <memory>
49fc51490bSJonas Devlieghere #include <string>
50fc51490bSJonas Devlieghere #include <system_error>
51fc51490bSJonas Devlieghere #include <utility>
52fc51490bSJonas Devlieghere #include <vector>
53fc51490bSJonas Devlieghere
54fc51490bSJonas Devlieghere using namespace llvm;
55fc51490bSJonas Devlieghere using namespace llvm::vfs;
56fc51490bSJonas Devlieghere
57cc418a3aSReid Kleckner using llvm::sys::fs::file_t;
58fc51490bSJonas Devlieghere using llvm::sys::fs::file_status;
59fc51490bSJonas Devlieghere using llvm::sys::fs::file_type;
60cc418a3aSReid Kleckner using llvm::sys::fs::kInvalidFile;
61fc51490bSJonas Devlieghere using llvm::sys::fs::perms;
62fc51490bSJonas Devlieghere using llvm::sys::fs::UniqueID;
63fc51490bSJonas Devlieghere
Status(const file_status & Status)64fc51490bSJonas Devlieghere Status::Status(const file_status &Status)
65fc51490bSJonas Devlieghere : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
66fc51490bSJonas Devlieghere User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
67fc51490bSJonas Devlieghere Type(Status.type()), Perms(Status.permissions()) {}
68fc51490bSJonas Devlieghere
Status(const Twine & Name,UniqueID UID,sys::TimePoint<> MTime,uint32_t User,uint32_t Group,uint64_t Size,file_type Type,perms Perms)69e7b94649SDuncan P. N. Exon Smith Status::Status(const Twine &Name, UniqueID UID, sys::TimePoint<> MTime,
70fc51490bSJonas Devlieghere uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
71fc51490bSJonas Devlieghere perms Perms)
72e7b94649SDuncan P. N. Exon Smith : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
73e7b94649SDuncan P. N. Exon Smith Size(Size), Type(Type), Perms(Perms) {}
74fc51490bSJonas Devlieghere
copyWithNewSize(const Status & In,uint64_t NewSize)75f6680345SJan Svoboda Status Status::copyWithNewSize(const Status &In, uint64_t NewSize) {
76f6680345SJan Svoboda return Status(In.getName(), In.getUniqueID(), In.getLastModificationTime(),
77f6680345SJan Svoboda In.getUser(), In.getGroup(), NewSize, In.getType(),
78f6680345SJan Svoboda In.getPermissions());
79f6680345SJan Svoboda }
80f6680345SJan Svoboda
copyWithNewName(const Status & In,const Twine & NewName)81e7b94649SDuncan P. N. Exon Smith Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
82fc51490bSJonas Devlieghere return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
83fc51490bSJonas Devlieghere In.getUser(), In.getGroup(), In.getSize(), In.getType(),
84fc51490bSJonas Devlieghere In.getPermissions());
85fc51490bSJonas Devlieghere }
86fc51490bSJonas Devlieghere
copyWithNewName(const file_status & In,const Twine & NewName)87e7b94649SDuncan P. N. Exon Smith Status Status::copyWithNewName(const file_status &In, const Twine &NewName) {
88fc51490bSJonas Devlieghere return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
89fc51490bSJonas Devlieghere In.getUser(), In.getGroup(), In.getSize(), In.type(),
90fc51490bSJonas Devlieghere In.permissions());
91fc51490bSJonas Devlieghere }
92fc51490bSJonas Devlieghere
equivalent(const Status & Other) const93fc51490bSJonas Devlieghere bool Status::equivalent(const Status &Other) const {
94fc51490bSJonas Devlieghere assert(isStatusKnown() && Other.isStatusKnown());
95fc51490bSJonas Devlieghere return getUniqueID() == Other.getUniqueID();
96fc51490bSJonas Devlieghere }
97fc51490bSJonas Devlieghere
isDirectory() const98fc51490bSJonas Devlieghere bool Status::isDirectory() const { return Type == file_type::directory_file; }
99fc51490bSJonas Devlieghere
isRegularFile() const100fc51490bSJonas Devlieghere bool Status::isRegularFile() const { return Type == file_type::regular_file; }
101fc51490bSJonas Devlieghere
isOther() const102fc51490bSJonas Devlieghere bool Status::isOther() const {
103fc51490bSJonas Devlieghere return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
104fc51490bSJonas Devlieghere }
105fc51490bSJonas Devlieghere
isSymlink() const106fc51490bSJonas Devlieghere bool Status::isSymlink() const { return Type == file_type::symlink_file; }
107fc51490bSJonas Devlieghere
isStatusKnown() const108fc51490bSJonas Devlieghere bool Status::isStatusKnown() const { return Type != file_type::status_error; }
109fc51490bSJonas Devlieghere
exists() const110fc51490bSJonas Devlieghere bool Status::exists() const {
111fc51490bSJonas Devlieghere return isStatusKnown() && Type != file_type::file_not_found;
112fc51490bSJonas Devlieghere }
113fc51490bSJonas Devlieghere
114fc51490bSJonas Devlieghere File::~File() = default;
115fc51490bSJonas Devlieghere
116fc51490bSJonas Devlieghere FileSystem::~FileSystem() = default;
117fc51490bSJonas Devlieghere
118fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<MemoryBuffer>>
getBufferForFile(const llvm::Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)119fc51490bSJonas Devlieghere FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
120fc51490bSJonas Devlieghere bool RequiresNullTerminator, bool IsVolatile) {
121fc51490bSJonas Devlieghere auto F = openFileForRead(Name);
122fc51490bSJonas Devlieghere if (!F)
123fc51490bSJonas Devlieghere return F.getError();
124fc51490bSJonas Devlieghere
125fc51490bSJonas Devlieghere return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
126fc51490bSJonas Devlieghere }
127fc51490bSJonas Devlieghere
makeAbsolute(SmallVectorImpl<char> & Path) const128fc51490bSJonas Devlieghere std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
129fc51490bSJonas Devlieghere if (llvm::sys::path::is_absolute(Path))
130fc51490bSJonas Devlieghere return {};
131fc51490bSJonas Devlieghere
132fc51490bSJonas Devlieghere auto WorkingDir = getCurrentWorkingDirectory();
133fc51490bSJonas Devlieghere if (!WorkingDir)
134fc51490bSJonas Devlieghere return WorkingDir.getError();
135fc51490bSJonas Devlieghere
1361ad53ca2SPavel Labath llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
1371ad53ca2SPavel Labath return {};
138fc51490bSJonas Devlieghere }
139fc51490bSJonas Devlieghere
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const140fc51490bSJonas Devlieghere std::error_code FileSystem::getRealPath(const Twine &Path,
14199538e89SSam McCall SmallVectorImpl<char> &Output) const {
142fc51490bSJonas Devlieghere return errc::operation_not_permitted;
143fc51490bSJonas Devlieghere }
144fc51490bSJonas Devlieghere
isLocal(const Twine & Path,bool & Result)145cbb5c868SJonas Devlieghere std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
146cbb5c868SJonas Devlieghere return errc::operation_not_permitted;
147cbb5c868SJonas Devlieghere }
148cbb5c868SJonas Devlieghere
exists(const Twine & Path)149fc51490bSJonas Devlieghere bool FileSystem::exists(const Twine &Path) {
150fc51490bSJonas Devlieghere auto Status = status(Path);
151fc51490bSJonas Devlieghere return Status && Status->exists();
152fc51490bSJonas Devlieghere }
153fc51490bSJonas Devlieghere
15441255241SBen Barham #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const15541255241SBen Barham void FileSystem::dump() const { print(dbgs(), PrintType::RecursiveContents); }
15641255241SBen Barham #endif
15741255241SBen Barham
158fc51490bSJonas Devlieghere #ifndef NDEBUG
isTraversalComponent(StringRef Component)159fc51490bSJonas Devlieghere static bool isTraversalComponent(StringRef Component) {
160fc51490bSJonas Devlieghere return Component.equals("..") || Component.equals(".");
161fc51490bSJonas Devlieghere }
162fc51490bSJonas Devlieghere
pathHasTraversal(StringRef Path)163fc51490bSJonas Devlieghere static bool pathHasTraversal(StringRef Path) {
164fc51490bSJonas Devlieghere using namespace llvm::sys;
165fc51490bSJonas Devlieghere
166fc51490bSJonas Devlieghere for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
167fc51490bSJonas Devlieghere if (isTraversalComponent(Comp))
168fc51490bSJonas Devlieghere return true;
169fc51490bSJonas Devlieghere return false;
170fc51490bSJonas Devlieghere }
171fc51490bSJonas Devlieghere #endif
172fc51490bSJonas Devlieghere
173fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
174fc51490bSJonas Devlieghere // RealFileSystem implementation
175fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
176fc51490bSJonas Devlieghere
177fc51490bSJonas Devlieghere namespace {
178fc51490bSJonas Devlieghere
179fc51490bSJonas Devlieghere /// Wrapper around a raw file descriptor.
180fc51490bSJonas Devlieghere class RealFile : public File {
181fc51490bSJonas Devlieghere friend class RealFileSystem;
182fc51490bSJonas Devlieghere
183cc418a3aSReid Kleckner file_t FD;
184fc51490bSJonas Devlieghere Status S;
185fc51490bSJonas Devlieghere std::string RealName;
186fc51490bSJonas Devlieghere
RealFile(file_t RawFD,StringRef NewName,StringRef NewRealPathName)187115a6ecdSSimon Pilgrim RealFile(file_t RawFD, StringRef NewName, StringRef NewRealPathName)
188115a6ecdSSimon Pilgrim : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
189fc51490bSJonas Devlieghere llvm::sys::fs::file_type::status_error, {}),
190fc51490bSJonas Devlieghere RealName(NewRealPathName.str()) {
191cc418a3aSReid Kleckner assert(FD != kInvalidFile && "Invalid or inactive file descriptor");
192fc51490bSJonas Devlieghere }
193fc51490bSJonas Devlieghere
194fc51490bSJonas Devlieghere public:
195fc51490bSJonas Devlieghere ~RealFile() override;
196fc51490bSJonas Devlieghere
197fc51490bSJonas Devlieghere ErrorOr<Status> status() override;
198fc51490bSJonas Devlieghere ErrorOr<std::string> getName() override;
199fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
200fc51490bSJonas Devlieghere int64_t FileSize,
201fc51490bSJonas Devlieghere bool RequiresNullTerminator,
202fc51490bSJonas Devlieghere bool IsVolatile) override;
203fc51490bSJonas Devlieghere std::error_code close() override;
20486e2af80SKeith Smiley void setPath(const Twine &Path) override;
205fc51490bSJonas Devlieghere };
206fc51490bSJonas Devlieghere
207fc51490bSJonas Devlieghere } // namespace
208fc51490bSJonas Devlieghere
~RealFile()209fc51490bSJonas Devlieghere RealFile::~RealFile() { close(); }
210fc51490bSJonas Devlieghere
status()211fc51490bSJonas Devlieghere ErrorOr<Status> RealFile::status() {
212cc418a3aSReid Kleckner assert(FD != kInvalidFile && "cannot stat closed file");
213fc51490bSJonas Devlieghere if (!S.isStatusKnown()) {
214fc51490bSJonas Devlieghere file_status RealStatus;
215fc51490bSJonas Devlieghere if (std::error_code EC = sys::fs::status(FD, RealStatus))
216fc51490bSJonas Devlieghere return EC;
217fc51490bSJonas Devlieghere S = Status::copyWithNewName(RealStatus, S.getName());
218fc51490bSJonas Devlieghere }
219fc51490bSJonas Devlieghere return S;
220fc51490bSJonas Devlieghere }
221fc51490bSJonas Devlieghere
getName()222fc51490bSJonas Devlieghere ErrorOr<std::string> RealFile::getName() {
223fc51490bSJonas Devlieghere return RealName.empty() ? S.getName().str() : RealName;
224fc51490bSJonas Devlieghere }
225fc51490bSJonas Devlieghere
226fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)227fc51490bSJonas Devlieghere RealFile::getBuffer(const Twine &Name, int64_t FileSize,
228fc51490bSJonas Devlieghere bool RequiresNullTerminator, bool IsVolatile) {
229cc418a3aSReid Kleckner assert(FD != kInvalidFile && "cannot get buffer for closed file");
230fc51490bSJonas Devlieghere return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
231fc51490bSJonas Devlieghere IsVolatile);
232fc51490bSJonas Devlieghere }
233fc51490bSJonas Devlieghere
close()234fc51490bSJonas Devlieghere std::error_code RealFile::close() {
235cc418a3aSReid Kleckner std::error_code EC = sys::fs::closeFile(FD);
236cc418a3aSReid Kleckner FD = kInvalidFile;
237fc51490bSJonas Devlieghere return EC;
238fc51490bSJonas Devlieghere }
239fc51490bSJonas Devlieghere
setPath(const Twine & Path)24086e2af80SKeith Smiley void RealFile::setPath(const Twine &Path) {
24186e2af80SKeith Smiley RealName = Path.str();
24286e2af80SKeith Smiley if (auto Status = status())
24386e2af80SKeith Smiley S = Status.get().copyWithNewName(Status.get(), Path);
24486e2af80SKeith Smiley }
24586e2af80SKeith Smiley
246fc51490bSJonas Devlieghere namespace {
247fc51490bSJonas Devlieghere
24815e475e2SSam McCall /// A file system according to your operating system.
24915e475e2SSam McCall /// This may be linked to the process's working directory, or maintain its own.
25015e475e2SSam McCall ///
25115e475e2SSam McCall /// Currently, its own working directory is emulated by storing the path and
25215e475e2SSam McCall /// sending absolute paths to llvm::sys::fs:: functions.
25315e475e2SSam McCall /// A more principled approach would be to push this down a level, modelling
25415e475e2SSam McCall /// the working dir as an llvm::sys::fs::WorkingDir or similar.
25515e475e2SSam McCall /// This would enable the use of openat()-style functions on some platforms.
256fc51490bSJonas Devlieghere class RealFileSystem : public FileSystem {
257fc51490bSJonas Devlieghere public:
RealFileSystem(bool LinkCWDToProcess)25815e475e2SSam McCall explicit RealFileSystem(bool LinkCWDToProcess) {
25915e475e2SSam McCall if (!LinkCWDToProcess) {
26015e475e2SSam McCall SmallString<128> PWD, RealPWD;
26115e475e2SSam McCall if (llvm::sys::fs::current_path(PWD))
26215e475e2SSam McCall return; // Awful, but nothing to do here.
26315e475e2SSam McCall if (llvm::sys::fs::real_path(PWD, RealPWD))
26415e475e2SSam McCall WD = {PWD, PWD};
26515e475e2SSam McCall else
26615e475e2SSam McCall WD = {PWD, RealPWD};
26715e475e2SSam McCall }
26815e475e2SSam McCall }
26915e475e2SSam McCall
270fc51490bSJonas Devlieghere ErrorOr<Status> status(const Twine &Path) override;
271fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
272fc51490bSJonas Devlieghere directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
273fc51490bSJonas Devlieghere
274fc51490bSJonas Devlieghere llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
275fc51490bSJonas Devlieghere std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
276cbb5c868SJonas Devlieghere std::error_code isLocal(const Twine &Path, bool &Result) override;
27799538e89SSam McCall std::error_code getRealPath(const Twine &Path,
27899538e89SSam McCall SmallVectorImpl<char> &Output) const override;
279fc51490bSJonas Devlieghere
28041255241SBen Barham protected:
28141255241SBen Barham void printImpl(raw_ostream &OS, PrintType Type,
28241255241SBen Barham unsigned IndentLevel) const override;
28341255241SBen Barham
284fc51490bSJonas Devlieghere private:
28515e475e2SSam McCall // If this FS has its own working dir, use it to make Path absolute.
28615e475e2SSam McCall // The returned twine is safe to use as long as both Storage and Path live.
adjustPath(const Twine & Path,SmallVectorImpl<char> & Storage) const28715e475e2SSam McCall Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const {
28815e475e2SSam McCall if (!WD)
28915e475e2SSam McCall return Path;
29015e475e2SSam McCall Path.toVector(Storage);
29115e475e2SSam McCall sys::fs::make_absolute(WD->Resolved, Storage);
29215e475e2SSam McCall return Storage;
29315e475e2SSam McCall }
29415e475e2SSam McCall
29515e475e2SSam McCall struct WorkingDirectory {
29615e475e2SSam McCall // The current working directory, without symlinks resolved. (echo $PWD).
29715e475e2SSam McCall SmallString<128> Specified;
29815e475e2SSam McCall // The current working directory, with links resolved. (readlink .).
29915e475e2SSam McCall SmallString<128> Resolved;
30015e475e2SSam McCall };
30115e475e2SSam McCall Optional<WorkingDirectory> WD;
302fc51490bSJonas Devlieghere };
303fc51490bSJonas Devlieghere
304fc51490bSJonas Devlieghere } // namespace
305fc51490bSJonas Devlieghere
status(const Twine & Path)306fc51490bSJonas Devlieghere ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
30715e475e2SSam McCall SmallString<256> Storage;
308fc51490bSJonas Devlieghere sys::fs::file_status RealStatus;
30915e475e2SSam McCall if (std::error_code EC =
31015e475e2SSam McCall sys::fs::status(adjustPath(Path, Storage), RealStatus))
311fc51490bSJonas Devlieghere return EC;
312e7b94649SDuncan P. N. Exon Smith return Status::copyWithNewName(RealStatus, Path);
313fc51490bSJonas Devlieghere }
314fc51490bSJonas Devlieghere
315fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Name)316fc51490bSJonas Devlieghere RealFileSystem::openFileForRead(const Twine &Name) {
31715e475e2SSam McCall SmallString<256> RealName, Storage;
318cc418a3aSReid Kleckner Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead(
319cc418a3aSReid Kleckner adjustPath(Name, Storage), sys::fs::OF_None, &RealName);
320cc418a3aSReid Kleckner if (!FDOrErr)
321cc418a3aSReid Kleckner return errorToErrorCode(FDOrErr.takeError());
322cc418a3aSReid Kleckner return std::unique_ptr<File>(
323cc418a3aSReid Kleckner new RealFile(*FDOrErr, Name.str(), RealName.str()));
324fc51490bSJonas Devlieghere }
325fc51490bSJonas Devlieghere
getCurrentWorkingDirectory() const326fc51490bSJonas Devlieghere llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
32715e475e2SSam McCall if (WD)
328adcd0268SBenjamin Kramer return std::string(WD->Specified.str());
32915e475e2SSam McCall
33015e475e2SSam McCall SmallString<128> Dir;
331fc51490bSJonas Devlieghere if (std::error_code EC = llvm::sys::fs::current_path(Dir))
332fc51490bSJonas Devlieghere return EC;
333adcd0268SBenjamin Kramer return std::string(Dir.str());
334fc51490bSJonas Devlieghere }
335fc51490bSJonas Devlieghere
setCurrentWorkingDirectory(const Twine & Path)336fc51490bSJonas Devlieghere std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
33715e475e2SSam McCall if (!WD)
33815e475e2SSam McCall return llvm::sys::fs::set_current_path(Path);
339fc51490bSJonas Devlieghere
34015e475e2SSam McCall SmallString<128> Absolute, Resolved, Storage;
34115e475e2SSam McCall adjustPath(Path, Storage).toVector(Absolute);
34215e475e2SSam McCall bool IsDir;
34315e475e2SSam McCall if (auto Err = llvm::sys::fs::is_directory(Absolute, IsDir))
34415e475e2SSam McCall return Err;
34515e475e2SSam McCall if (!IsDir)
34615e475e2SSam McCall return std::make_error_code(std::errc::not_a_directory);
34715e475e2SSam McCall if (auto Err = llvm::sys::fs::real_path(Absolute, Resolved))
34815e475e2SSam McCall return Err;
34915e475e2SSam McCall WD = {Absolute, Resolved};
350fc51490bSJonas Devlieghere return std::error_code();
351fc51490bSJonas Devlieghere }
352fc51490bSJonas Devlieghere
isLocal(const Twine & Path,bool & Result)353cbb5c868SJonas Devlieghere std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
35415e475e2SSam McCall SmallString<256> Storage;
35515e475e2SSam McCall return llvm::sys::fs::is_local(adjustPath(Path, Storage), Result);
356cbb5c868SJonas Devlieghere }
357cbb5c868SJonas Devlieghere
35899538e89SSam McCall std::error_code
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const35999538e89SSam McCall RealFileSystem::getRealPath(const Twine &Path,
36099538e89SSam McCall SmallVectorImpl<char> &Output) const {
36115e475e2SSam McCall SmallString<256> Storage;
36215e475e2SSam McCall return llvm::sys::fs::real_path(adjustPath(Path, Storage), Output);
363fc51490bSJonas Devlieghere }
364fc51490bSJonas Devlieghere
printImpl(raw_ostream & OS,PrintType Type,unsigned IndentLevel) const36541255241SBen Barham void RealFileSystem::printImpl(raw_ostream &OS, PrintType Type,
36641255241SBen Barham unsigned IndentLevel) const {
36741255241SBen Barham printIndent(OS, IndentLevel);
36841255241SBen Barham OS << "RealFileSystem using ";
36941255241SBen Barham if (WD)
37041255241SBen Barham OS << "own";
37141255241SBen Barham else
37241255241SBen Barham OS << "process";
37341255241SBen Barham OS << " CWD\n";
37441255241SBen Barham }
37541255241SBen Barham
getRealFileSystem()376fc51490bSJonas Devlieghere IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
37715e475e2SSam McCall static IntrusiveRefCntPtr<FileSystem> FS(new RealFileSystem(true));
378fc51490bSJonas Devlieghere return FS;
379fc51490bSJonas Devlieghere }
380fc51490bSJonas Devlieghere
createPhysicalFileSystem()38115e475e2SSam McCall std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() {
3820eaee545SJonas Devlieghere return std::make_unique<RealFileSystem>(false);
38315e475e2SSam McCall }
38415e475e2SSam McCall
385fc51490bSJonas Devlieghere namespace {
386fc51490bSJonas Devlieghere
387fc51490bSJonas Devlieghere class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
388fc51490bSJonas Devlieghere llvm::sys::fs::directory_iterator Iter;
389fc51490bSJonas Devlieghere
390fc51490bSJonas Devlieghere public:
RealFSDirIter(const Twine & Path,std::error_code & EC)391fc51490bSJonas Devlieghere RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
392fc51490bSJonas Devlieghere if (Iter != llvm::sys::fs::directory_iterator())
393fc51490bSJonas Devlieghere CurrentEntry = directory_entry(Iter->path(), Iter->type());
394fc51490bSJonas Devlieghere }
395fc51490bSJonas Devlieghere
increment()396fc51490bSJonas Devlieghere std::error_code increment() override {
397fc51490bSJonas Devlieghere std::error_code EC;
398fc51490bSJonas Devlieghere Iter.increment(EC);
399fc51490bSJonas Devlieghere CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
400fc51490bSJonas Devlieghere ? directory_entry()
401fc51490bSJonas Devlieghere : directory_entry(Iter->path(), Iter->type());
402fc51490bSJonas Devlieghere return EC;
403fc51490bSJonas Devlieghere }
404fc51490bSJonas Devlieghere };
405fc51490bSJonas Devlieghere
406fc51490bSJonas Devlieghere } // namespace
407fc51490bSJonas Devlieghere
dir_begin(const Twine & Dir,std::error_code & EC)408fc51490bSJonas Devlieghere directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
409fc51490bSJonas Devlieghere std::error_code &EC) {
41015e475e2SSam McCall SmallString<128> Storage;
41115e475e2SSam McCall return directory_iterator(
41215e475e2SSam McCall std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
413fc51490bSJonas Devlieghere }
414fc51490bSJonas Devlieghere
415fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
416fc51490bSJonas Devlieghere // OverlayFileSystem implementation
417fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
418fc51490bSJonas Devlieghere
OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS)419fc51490bSJonas Devlieghere OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
420fc51490bSJonas Devlieghere FSList.push_back(std::move(BaseFS));
421fc51490bSJonas Devlieghere }
422fc51490bSJonas Devlieghere
pushOverlay(IntrusiveRefCntPtr<FileSystem> FS)423fc51490bSJonas Devlieghere void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
424fc51490bSJonas Devlieghere FSList.push_back(FS);
425fc51490bSJonas Devlieghere // Synchronize added file systems by duplicating the working directory from
426fc51490bSJonas Devlieghere // the first one in the list.
427fc51490bSJonas Devlieghere FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
428fc51490bSJonas Devlieghere }
429fc51490bSJonas Devlieghere
status(const Twine & Path)430fc51490bSJonas Devlieghere ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
431fc51490bSJonas Devlieghere // FIXME: handle symlinks that cross file systems
432fc51490bSJonas Devlieghere for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
433fc51490bSJonas Devlieghere ErrorOr<Status> Status = (*I)->status(Path);
434fc51490bSJonas Devlieghere if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
435fc51490bSJonas Devlieghere return Status;
436fc51490bSJonas Devlieghere }
437fc51490bSJonas Devlieghere return make_error_code(llvm::errc::no_such_file_or_directory);
438fc51490bSJonas Devlieghere }
439fc51490bSJonas Devlieghere
440fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
openFileForRead(const llvm::Twine & Path)441fc51490bSJonas Devlieghere OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
442fc51490bSJonas Devlieghere // FIXME: handle symlinks that cross file systems
443fc51490bSJonas Devlieghere for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
444fc51490bSJonas Devlieghere auto Result = (*I)->openFileForRead(Path);
445fc51490bSJonas Devlieghere if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
446fc51490bSJonas Devlieghere return Result;
447fc51490bSJonas Devlieghere }
448fc51490bSJonas Devlieghere return make_error_code(llvm::errc::no_such_file_or_directory);
449fc51490bSJonas Devlieghere }
450fc51490bSJonas Devlieghere
451fc51490bSJonas Devlieghere llvm::ErrorOr<std::string>
getCurrentWorkingDirectory() const452fc51490bSJonas Devlieghere OverlayFileSystem::getCurrentWorkingDirectory() const {
453fc51490bSJonas Devlieghere // All file systems are synchronized, just take the first working directory.
454fc51490bSJonas Devlieghere return FSList.front()->getCurrentWorkingDirectory();
455fc51490bSJonas Devlieghere }
456fc51490bSJonas Devlieghere
457fc51490bSJonas Devlieghere std::error_code
setCurrentWorkingDirectory(const Twine & Path)458fc51490bSJonas Devlieghere OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
459fc51490bSJonas Devlieghere for (auto &FS : FSList)
460fc51490bSJonas Devlieghere if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
461fc51490bSJonas Devlieghere return EC;
462fc51490bSJonas Devlieghere return {};
463fc51490bSJonas Devlieghere }
464fc51490bSJonas Devlieghere
isLocal(const Twine & Path,bool & Result)465cbb5c868SJonas Devlieghere std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
466cbb5c868SJonas Devlieghere for (auto &FS : FSList)
467cbb5c868SJonas Devlieghere if (FS->exists(Path))
468cbb5c868SJonas Devlieghere return FS->isLocal(Path, Result);
469cbb5c868SJonas Devlieghere return errc::no_such_file_or_directory;
470cbb5c868SJonas Devlieghere }
471cbb5c868SJonas Devlieghere
47299538e89SSam McCall std::error_code
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const47399538e89SSam McCall OverlayFileSystem::getRealPath(const Twine &Path,
47499538e89SSam McCall SmallVectorImpl<char> &Output) const {
4753322354bSKazu Hirata for (const auto &FS : FSList)
476fc51490bSJonas Devlieghere if (FS->exists(Path))
47799538e89SSam McCall return FS->getRealPath(Path, Output);
478fc51490bSJonas Devlieghere return errc::no_such_file_or_directory;
479fc51490bSJonas Devlieghere }
480fc51490bSJonas Devlieghere
printImpl(raw_ostream & OS,PrintType Type,unsigned IndentLevel) const48141255241SBen Barham void OverlayFileSystem::printImpl(raw_ostream &OS, PrintType Type,
48241255241SBen Barham unsigned IndentLevel) const {
48341255241SBen Barham printIndent(OS, IndentLevel);
48441255241SBen Barham OS << "OverlayFileSystem\n";
48541255241SBen Barham if (Type == PrintType::Summary)
48641255241SBen Barham return;
48741255241SBen Barham
48841255241SBen Barham if (Type == PrintType::Contents)
48941255241SBen Barham Type = PrintType::Summary;
49041255241SBen Barham for (auto FS : overlays_range())
49141255241SBen Barham FS->print(OS, Type, IndentLevel + 1);
49241255241SBen Barham }
49341255241SBen Barham
494fc51490bSJonas Devlieghere llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
495fc51490bSJonas Devlieghere
496fc51490bSJonas Devlieghere namespace {
497fc51490bSJonas Devlieghere
498719f7784SNathan Hawes /// Combines and deduplicates directory entries across multiple file systems.
499719f7784SNathan Hawes class CombiningDirIterImpl : public llvm::vfs::detail::DirIterImpl {
500719f7784SNathan Hawes using FileSystemPtr = llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>;
501719f7784SNathan Hawes
502502f14d6SBen Barham /// Iterators to combine, processed in reverse order.
503502f14d6SBen Barham SmallVector<directory_iterator, 8> IterList;
504502f14d6SBen Barham /// The iterator currently being traversed.
505fc51490bSJonas Devlieghere directory_iterator CurrentDirIter;
506719f7784SNathan Hawes /// The set of names already returned as entries.
507fc51490bSJonas Devlieghere llvm::StringSet<> SeenNames;
508fc51490bSJonas Devlieghere
509502f14d6SBen Barham /// Sets \c CurrentDirIter to the next iterator in the list, or leaves it as
510502f14d6SBen Barham /// is (at its end position) if we've already gone through them all.
incrementIter(bool IsFirstTime)511502f14d6SBen Barham std::error_code incrementIter(bool IsFirstTime) {
512502f14d6SBen Barham while (!IterList.empty()) {
513502f14d6SBen Barham CurrentDirIter = IterList.back();
514502f14d6SBen Barham IterList.pop_back();
515fc51490bSJonas Devlieghere if (CurrentDirIter != directory_iterator())
516fc51490bSJonas Devlieghere break; // found
517fc51490bSJonas Devlieghere }
518502f14d6SBen Barham
519502f14d6SBen Barham if (IsFirstTime && CurrentDirIter == directory_iterator())
520ed4f0cb8SBen Barham return errc::no_such_file_or_directory;
521fc51490bSJonas Devlieghere return {};
522fc51490bSJonas Devlieghere }
523fc51490bSJonas Devlieghere
incrementDirIter(bool IsFirstTime)524fc51490bSJonas Devlieghere std::error_code incrementDirIter(bool IsFirstTime) {
525fc51490bSJonas Devlieghere assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
526fc51490bSJonas Devlieghere "incrementing past end");
527fc51490bSJonas Devlieghere std::error_code EC;
528fc51490bSJonas Devlieghere if (!IsFirstTime)
529fc51490bSJonas Devlieghere CurrentDirIter.increment(EC);
530fc51490bSJonas Devlieghere if (!EC && CurrentDirIter == directory_iterator())
531502f14d6SBen Barham EC = incrementIter(IsFirstTime);
532fc51490bSJonas Devlieghere return EC;
533fc51490bSJonas Devlieghere }
534fc51490bSJonas Devlieghere
incrementImpl(bool IsFirstTime)535fc51490bSJonas Devlieghere std::error_code incrementImpl(bool IsFirstTime) {
536fc51490bSJonas Devlieghere while (true) {
537fc51490bSJonas Devlieghere std::error_code EC = incrementDirIter(IsFirstTime);
538fc51490bSJonas Devlieghere if (EC || CurrentDirIter == directory_iterator()) {
539fc51490bSJonas Devlieghere CurrentEntry = directory_entry();
540fc51490bSJonas Devlieghere return EC;
541fc51490bSJonas Devlieghere }
542fc51490bSJonas Devlieghere CurrentEntry = *CurrentDirIter;
543fc51490bSJonas Devlieghere StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
544fc51490bSJonas Devlieghere if (SeenNames.insert(Name).second)
545fc51490bSJonas Devlieghere return EC; // name not seen before
546fc51490bSJonas Devlieghere }
547fc51490bSJonas Devlieghere llvm_unreachable("returned above");
548fc51490bSJonas Devlieghere }
549fc51490bSJonas Devlieghere
550fc51490bSJonas Devlieghere public:
CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems,std::string Dir,std::error_code & EC)551719f7784SNathan Hawes CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems, std::string Dir,
552502f14d6SBen Barham std::error_code &EC) {
553502f14d6SBen Barham for (auto FS : FileSystems) {
554502f14d6SBen Barham std::error_code FEC;
555502f14d6SBen Barham directory_iterator Iter = FS->dir_begin(Dir, FEC);
556502f14d6SBen Barham if (FEC && FEC != errc::no_such_file_or_directory) {
557502f14d6SBen Barham EC = FEC;
558502f14d6SBen Barham return;
559502f14d6SBen Barham }
560502f14d6SBen Barham if (!FEC)
561502f14d6SBen Barham IterList.push_back(Iter);
562502f14d6SBen Barham }
563719f7784SNathan Hawes EC = incrementImpl(true);
564719f7784SNathan Hawes }
565719f7784SNathan Hawes
CombiningDirIterImpl(ArrayRef<directory_iterator> DirIters,std::error_code & EC)566502f14d6SBen Barham CombiningDirIterImpl(ArrayRef<directory_iterator> DirIters,
567502f14d6SBen Barham std::error_code &EC)
568502f14d6SBen Barham : IterList(DirIters.begin(), DirIters.end()) {
569fc51490bSJonas Devlieghere EC = incrementImpl(true);
570fc51490bSJonas Devlieghere }
571fc51490bSJonas Devlieghere
increment()572fc51490bSJonas Devlieghere std::error_code increment() override { return incrementImpl(false); }
573fc51490bSJonas Devlieghere };
574fc51490bSJonas Devlieghere
575fc51490bSJonas Devlieghere } // namespace
576fc51490bSJonas Devlieghere
dir_begin(const Twine & Dir,std::error_code & EC)577fc51490bSJonas Devlieghere directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
578fc51490bSJonas Devlieghere std::error_code &EC) {
579502f14d6SBen Barham directory_iterator Combined = directory_iterator(
580719f7784SNathan Hawes std::make_shared<CombiningDirIterImpl>(FSList, Dir.str(), EC));
581502f14d6SBen Barham if (EC)
582502f14d6SBen Barham return {};
583502f14d6SBen Barham return Combined;
584fc51490bSJonas Devlieghere }
585fc51490bSJonas Devlieghere
anchor()586a87b70d1SRichard Trieu void ProxyFileSystem::anchor() {}
587a87b70d1SRichard Trieu
588fc51490bSJonas Devlieghere namespace llvm {
589fc51490bSJonas Devlieghere namespace vfs {
590fc51490bSJonas Devlieghere
591fc51490bSJonas Devlieghere namespace detail {
592fc51490bSJonas Devlieghere
593a44c6453SJan Svoboda enum InMemoryNodeKind {
594a44c6453SJan Svoboda IME_File,
595a44c6453SJan Svoboda IME_Directory,
596a44c6453SJan Svoboda IME_HardLink,
597a44c6453SJan Svoboda IME_SymbolicLink,
598a44c6453SJan Svoboda };
599fc51490bSJonas Devlieghere
600fc51490bSJonas Devlieghere /// The in memory file system is a tree of Nodes. Every node can either be a
601a44c6453SJan Svoboda /// file, symlink, hardlink or a directory.
602fc51490bSJonas Devlieghere class InMemoryNode {
603fc51490bSJonas Devlieghere InMemoryNodeKind Kind;
604fc51490bSJonas Devlieghere std::string FileName;
605fc51490bSJonas Devlieghere
606fc51490bSJonas Devlieghere public:
InMemoryNode(llvm::StringRef FileName,InMemoryNodeKind Kind)607fc51490bSJonas Devlieghere InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
608adcd0268SBenjamin Kramer : Kind(Kind), FileName(std::string(llvm::sys::path::filename(FileName))) {
609adcd0268SBenjamin Kramer }
610fc51490bSJonas Devlieghere virtual ~InMemoryNode() = default;
611fc51490bSJonas Devlieghere
6129e24d14aSJan Svoboda /// Return the \p Status for this node. \p RequestedName should be the name
6139e24d14aSJan Svoboda /// through which the caller referred to this node. It will override
6149e24d14aSJan Svoboda /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
6159e24d14aSJan Svoboda virtual Status getStatus(const Twine &RequestedName) const = 0;
6169e24d14aSJan Svoboda
617fc51490bSJonas Devlieghere /// Get the filename of this node (the name without the directory part).
getFileName() const618fc51490bSJonas Devlieghere StringRef getFileName() const { return FileName; }
getKind() const619fc51490bSJonas Devlieghere InMemoryNodeKind getKind() const { return Kind; }
620fc51490bSJonas Devlieghere virtual std::string toString(unsigned Indent) const = 0;
621fc51490bSJonas Devlieghere };
622fc51490bSJonas Devlieghere
623fc51490bSJonas Devlieghere class InMemoryFile : public InMemoryNode {
624fc51490bSJonas Devlieghere Status Stat;
625fc51490bSJonas Devlieghere std::unique_ptr<llvm::MemoryBuffer> Buffer;
626fc51490bSJonas Devlieghere
627fc51490bSJonas Devlieghere public:
InMemoryFile(Status Stat,std::unique_ptr<llvm::MemoryBuffer> Buffer)628fc51490bSJonas Devlieghere InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
629fc51490bSJonas Devlieghere : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
630fc51490bSJonas Devlieghere Buffer(std::move(Buffer)) {}
631fc51490bSJonas Devlieghere
getStatus(const Twine & RequestedName) const6329e24d14aSJan Svoboda Status getStatus(const Twine &RequestedName) const override {
633fc51490bSJonas Devlieghere return Status::copyWithNewName(Stat, RequestedName);
634fc51490bSJonas Devlieghere }
getBuffer() const635fc51490bSJonas Devlieghere llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
636fc51490bSJonas Devlieghere
toString(unsigned Indent) const637fc51490bSJonas Devlieghere std::string toString(unsigned Indent) const override {
638fc51490bSJonas Devlieghere return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
639fc51490bSJonas Devlieghere }
640fc51490bSJonas Devlieghere
classof(const InMemoryNode * N)641fc51490bSJonas Devlieghere static bool classof(const InMemoryNode *N) {
642fc51490bSJonas Devlieghere return N->getKind() == IME_File;
643fc51490bSJonas Devlieghere }
644fc51490bSJonas Devlieghere };
645fc51490bSJonas Devlieghere
646fc51490bSJonas Devlieghere namespace {
647fc51490bSJonas Devlieghere
648fc51490bSJonas Devlieghere class InMemoryHardLink : public InMemoryNode {
649fc51490bSJonas Devlieghere const InMemoryFile &ResolvedFile;
650fc51490bSJonas Devlieghere
651fc51490bSJonas Devlieghere public:
InMemoryHardLink(StringRef Path,const InMemoryFile & ResolvedFile)652fc51490bSJonas Devlieghere InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
653fc51490bSJonas Devlieghere : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
getResolvedFile() const654fc51490bSJonas Devlieghere const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
655fc51490bSJonas Devlieghere
getStatus(const Twine & RequestedName) const6569e24d14aSJan Svoboda Status getStatus(const Twine &RequestedName) const override {
6579e24d14aSJan Svoboda return ResolvedFile.getStatus(RequestedName);
6589e24d14aSJan Svoboda }
6599e24d14aSJan Svoboda
toString(unsigned Indent) const660fc51490bSJonas Devlieghere std::string toString(unsigned Indent) const override {
661fc51490bSJonas Devlieghere return std::string(Indent, ' ') + "HardLink to -> " +
662fc51490bSJonas Devlieghere ResolvedFile.toString(0);
663fc51490bSJonas Devlieghere }
664fc51490bSJonas Devlieghere
classof(const InMemoryNode * N)665fc51490bSJonas Devlieghere static bool classof(const InMemoryNode *N) {
666fc51490bSJonas Devlieghere return N->getKind() == IME_HardLink;
667fc51490bSJonas Devlieghere }
668fc51490bSJonas Devlieghere };
669fc51490bSJonas Devlieghere
670a44c6453SJan Svoboda class InMemorySymbolicLink : public InMemoryNode {
671a44c6453SJan Svoboda std::string TargetPath;
672a44c6453SJan Svoboda Status Stat;
673a44c6453SJan Svoboda
674a44c6453SJan Svoboda public:
InMemorySymbolicLink(StringRef Path,StringRef TargetPath,Status Stat)675a44c6453SJan Svoboda InMemorySymbolicLink(StringRef Path, StringRef TargetPath, Status Stat)
676a44c6453SJan Svoboda : InMemoryNode(Path, IME_SymbolicLink), TargetPath(std::move(TargetPath)),
677a44c6453SJan Svoboda Stat(Stat) {}
678a44c6453SJan Svoboda
toString(unsigned Indent) const679a44c6453SJan Svoboda std::string toString(unsigned Indent) const override {
680a44c6453SJan Svoboda return std::string(Indent, ' ') + "SymbolicLink to -> " + TargetPath;
681a44c6453SJan Svoboda }
682a44c6453SJan Svoboda
getStatus(const Twine & RequestedName) const683a44c6453SJan Svoboda Status getStatus(const Twine &RequestedName) const override {
684a44c6453SJan Svoboda return Status::copyWithNewName(Stat, RequestedName);
685a44c6453SJan Svoboda }
686a44c6453SJan Svoboda
getTargetPath() const687a44c6453SJan Svoboda StringRef getTargetPath() const { return TargetPath; }
688a44c6453SJan Svoboda
classof(const InMemoryNode * N)689a44c6453SJan Svoboda static bool classof(const InMemoryNode *N) {
690a44c6453SJan Svoboda return N->getKind() == IME_SymbolicLink;
691a44c6453SJan Svoboda }
692a44c6453SJan Svoboda };
693a44c6453SJan Svoboda
694fc51490bSJonas Devlieghere /// Adapt a InMemoryFile for VFS' File interface. The goal is to make
695fc51490bSJonas Devlieghere /// \p InMemoryFileAdaptor mimic as much as possible the behavior of
696fc51490bSJonas Devlieghere /// \p RealFile.
697fc51490bSJonas Devlieghere class InMemoryFileAdaptor : public File {
698fc51490bSJonas Devlieghere const InMemoryFile &Node;
699fc51490bSJonas Devlieghere /// The name to use when returning a Status for this file.
700fc51490bSJonas Devlieghere std::string RequestedName;
701fc51490bSJonas Devlieghere
702fc51490bSJonas Devlieghere public:
InMemoryFileAdaptor(const InMemoryFile & Node,std::string RequestedName)703fc51490bSJonas Devlieghere explicit InMemoryFileAdaptor(const InMemoryFile &Node,
704fc51490bSJonas Devlieghere std::string RequestedName)
705fc51490bSJonas Devlieghere : Node(Node), RequestedName(std::move(RequestedName)) {}
706fc51490bSJonas Devlieghere
status()707fc51490bSJonas Devlieghere llvm::ErrorOr<Status> status() override {
708fc51490bSJonas Devlieghere return Node.getStatus(RequestedName);
709fc51490bSJonas Devlieghere }
710fc51490bSJonas Devlieghere
711fc51490bSJonas Devlieghere llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)712fc51490bSJonas Devlieghere getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
713fc51490bSJonas Devlieghere bool IsVolatile) override {
714fc51490bSJonas Devlieghere llvm::MemoryBuffer *Buf = Node.getBuffer();
715fc51490bSJonas Devlieghere return llvm::MemoryBuffer::getMemBuffer(
716fc51490bSJonas Devlieghere Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
717fc51490bSJonas Devlieghere }
718fc51490bSJonas Devlieghere
close()719fc51490bSJonas Devlieghere std::error_code close() override { return {}; }
72086e2af80SKeith Smiley
setPath(const Twine & Path)72186e2af80SKeith Smiley void setPath(const Twine &Path) override { RequestedName = Path.str(); }
722fc51490bSJonas Devlieghere };
723fc51490bSJonas Devlieghere } // namespace
724fc51490bSJonas Devlieghere
725fc51490bSJonas Devlieghere class InMemoryDirectory : public InMemoryNode {
726fc51490bSJonas Devlieghere Status Stat;
727fc51490bSJonas Devlieghere llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries;
728fc51490bSJonas Devlieghere
729fc51490bSJonas Devlieghere public:
InMemoryDirectory(Status Stat)730fc51490bSJonas Devlieghere InMemoryDirectory(Status Stat)
731fc51490bSJonas Devlieghere : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
732fc51490bSJonas Devlieghere
733fc51490bSJonas Devlieghere /// Return the \p Status for this node. \p RequestedName should be the name
734fc51490bSJonas Devlieghere /// through which the caller referred to this node. It will override
735fc51490bSJonas Devlieghere /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
getStatus(const Twine & RequestedName) const7369e24d14aSJan Svoboda Status getStatus(const Twine &RequestedName) const override {
737fc51490bSJonas Devlieghere return Status::copyWithNewName(Stat, RequestedName);
738fc51490bSJonas Devlieghere }
73922555bafSSam McCall
getUniqueID() const74022555bafSSam McCall UniqueID getUniqueID() const { return Stat.getUniqueID(); }
74122555bafSSam McCall
getChild(StringRef Name) const7429e0398daSJan Svoboda InMemoryNode *getChild(StringRef Name) const {
743fc51490bSJonas Devlieghere auto I = Entries.find(Name);
744fc51490bSJonas Devlieghere if (I != Entries.end())
745fc51490bSJonas Devlieghere return I->second.get();
746fc51490bSJonas Devlieghere return nullptr;
747fc51490bSJonas Devlieghere }
748fc51490bSJonas Devlieghere
addChild(StringRef Name,std::unique_ptr<InMemoryNode> Child)749fc51490bSJonas Devlieghere InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
750fc51490bSJonas Devlieghere return Entries.insert(make_pair(Name, std::move(Child)))
751fc51490bSJonas Devlieghere .first->second.get();
752fc51490bSJonas Devlieghere }
753fc51490bSJonas Devlieghere
754fc51490bSJonas Devlieghere using const_iterator = decltype(Entries)::const_iterator;
755fc51490bSJonas Devlieghere
begin() const756fc51490bSJonas Devlieghere const_iterator begin() const { return Entries.begin(); }
end() const757fc51490bSJonas Devlieghere const_iterator end() const { return Entries.end(); }
758fc51490bSJonas Devlieghere
toString(unsigned Indent) const759fc51490bSJonas Devlieghere std::string toString(unsigned Indent) const override {
760fc51490bSJonas Devlieghere std::string Result =
761fc51490bSJonas Devlieghere (std::string(Indent, ' ') + Stat.getName() + "\n").str();
762fc51490bSJonas Devlieghere for (const auto &Entry : Entries)
763fc51490bSJonas Devlieghere Result += Entry.second->toString(Indent + 2);
764fc51490bSJonas Devlieghere return Result;
765fc51490bSJonas Devlieghere }
766fc51490bSJonas Devlieghere
classof(const InMemoryNode * N)767fc51490bSJonas Devlieghere static bool classof(const InMemoryNode *N) {
768fc51490bSJonas Devlieghere return N->getKind() == IME_Directory;
769fc51490bSJonas Devlieghere }
770fc51490bSJonas Devlieghere };
771fc51490bSJonas Devlieghere
772fc51490bSJonas Devlieghere } // namespace detail
773fc51490bSJonas Devlieghere
77422555bafSSam McCall // The UniqueID of in-memory files is derived from path and content.
77522555bafSSam McCall // This avoids difficulties in creating exactly equivalent in-memory FSes,
77622555bafSSam McCall // as often needed in multithreaded programs.
getUniqueID(hash_code Hash)77722555bafSSam McCall static sys::fs::UniqueID getUniqueID(hash_code Hash) {
77822555bafSSam McCall return sys::fs::UniqueID(std::numeric_limits<uint64_t>::max(),
77922555bafSSam McCall uint64_t(size_t(Hash)));
78022555bafSSam McCall }
getFileID(sys::fs::UniqueID Parent,llvm::StringRef Name,llvm::StringRef Contents)78122555bafSSam McCall static sys::fs::UniqueID getFileID(sys::fs::UniqueID Parent,
78222555bafSSam McCall llvm::StringRef Name,
78322555bafSSam McCall llvm::StringRef Contents) {
78422555bafSSam McCall return getUniqueID(llvm::hash_combine(Parent.getFile(), Name, Contents));
78522555bafSSam McCall }
getDirectoryID(sys::fs::UniqueID Parent,llvm::StringRef Name)78622555bafSSam McCall static sys::fs::UniqueID getDirectoryID(sys::fs::UniqueID Parent,
78722555bafSSam McCall llvm::StringRef Name) {
78822555bafSSam McCall return getUniqueID(llvm::hash_combine(Parent.getFile(), Name));
78922555bafSSam McCall }
79022555bafSSam McCall
makeStatus() const7919011903eSJan Svoboda Status detail::NewInMemoryNodeInfo::makeStatus() const {
7929011903eSJan Svoboda UniqueID UID =
7939011903eSJan Svoboda (Type == sys::fs::file_type::directory_file)
7949011903eSJan Svoboda ? getDirectoryID(DirUID, Name)
7959011903eSJan Svoboda : getFileID(DirUID, Name, Buffer ? Buffer->getBuffer() : "");
7969011903eSJan Svoboda
7979011903eSJan Svoboda return Status(Path, UID, llvm::sys::toTimePoint(ModificationTime), User,
7989011903eSJan Svoboda Group, Buffer ? Buffer->getBufferSize() : 0, Type, Perms);
7999011903eSJan Svoboda }
8009011903eSJan Svoboda
InMemoryFileSystem(bool UseNormalizedPaths)801fc51490bSJonas Devlieghere InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
802fc51490bSJonas Devlieghere : Root(new detail::InMemoryDirectory(
80322555bafSSam McCall Status("", getDirectoryID(llvm::sys::fs::UniqueID(), ""),
80422555bafSSam McCall llvm::sys::TimePoint<>(), 0, 0, 0,
80522555bafSSam McCall llvm::sys::fs::file_type::directory_file,
806fc51490bSJonas Devlieghere llvm::sys::fs::perms::all_all))),
807fc51490bSJonas Devlieghere UseNormalizedPaths(UseNormalizedPaths) {}
808fc51490bSJonas Devlieghere
809fc51490bSJonas Devlieghere InMemoryFileSystem::~InMemoryFileSystem() = default;
810fc51490bSJonas Devlieghere
toString() const811fc51490bSJonas Devlieghere std::string InMemoryFileSystem::toString() const {
812fc51490bSJonas Devlieghere return Root->toString(/*Indent=*/0);
813fc51490bSJonas Devlieghere }
814fc51490bSJonas Devlieghere
addFile(const Twine & P,time_t ModificationTime,std::unique_ptr<llvm::MemoryBuffer> Buffer,Optional<uint32_t> User,Optional<uint32_t> Group,Optional<llvm::sys::fs::file_type> Type,Optional<llvm::sys::fs::perms> Perms,MakeNodeFn MakeNode)815fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
816fc51490bSJonas Devlieghere std::unique_ptr<llvm::MemoryBuffer> Buffer,
817fc51490bSJonas Devlieghere Optional<uint32_t> User,
818fc51490bSJonas Devlieghere Optional<uint32_t> Group,
819fc51490bSJonas Devlieghere Optional<llvm::sys::fs::file_type> Type,
820fc51490bSJonas Devlieghere Optional<llvm::sys::fs::perms> Perms,
8219011903eSJan Svoboda MakeNodeFn MakeNode) {
822fc51490bSJonas Devlieghere SmallString<128> Path;
823fc51490bSJonas Devlieghere P.toVector(Path);
824fc51490bSJonas Devlieghere
825fc51490bSJonas Devlieghere // Fix up relative paths. This just prepends the current working directory.
826fc51490bSJonas Devlieghere std::error_code EC = makeAbsolute(Path);
827fc51490bSJonas Devlieghere assert(!EC);
828fc51490bSJonas Devlieghere (void)EC;
829fc51490bSJonas Devlieghere
830fc51490bSJonas Devlieghere if (useNormalizedPaths())
831fc51490bSJonas Devlieghere llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
832fc51490bSJonas Devlieghere
833fc51490bSJonas Devlieghere if (Path.empty())
834fc51490bSJonas Devlieghere return false;
835fc51490bSJonas Devlieghere
836fc51490bSJonas Devlieghere detail::InMemoryDirectory *Dir = Root.get();
837fc51490bSJonas Devlieghere auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
838129b531cSKazu Hirata const auto ResolvedUser = User.value_or(0);
839129b531cSKazu Hirata const auto ResolvedGroup = Group.value_or(0);
840129b531cSKazu Hirata const auto ResolvedType = Type.value_or(sys::fs::file_type::regular_file);
841129b531cSKazu Hirata const auto ResolvedPerms = Perms.value_or(sys::fs::all_all);
842fc51490bSJonas Devlieghere // Any intermediate directories we create should be accessible by
843fc51490bSJonas Devlieghere // the owner, even if Perms says otherwise for the final path.
844fc51490bSJonas Devlieghere const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
845fc51490bSJonas Devlieghere while (true) {
846fc51490bSJonas Devlieghere StringRef Name = *I;
847fc51490bSJonas Devlieghere detail::InMemoryNode *Node = Dir->getChild(Name);
848fc51490bSJonas Devlieghere ++I;
849fc51490bSJonas Devlieghere if (!Node) {
850fc51490bSJonas Devlieghere if (I == E) {
851fc51490bSJonas Devlieghere // End of the path.
8529011903eSJan Svoboda Dir->addChild(
8539011903eSJan Svoboda Name, MakeNode({Dir->getUniqueID(), Path, Name, ModificationTime,
8549011903eSJan Svoboda std::move(Buffer), ResolvedUser, ResolvedGroup,
8559011903eSJan Svoboda ResolvedType, ResolvedPerms}));
856fc51490bSJonas Devlieghere return true;
857fc51490bSJonas Devlieghere }
858fc51490bSJonas Devlieghere
859fc51490bSJonas Devlieghere // Create a new directory. Use the path up to here.
860fc51490bSJonas Devlieghere Status Stat(
861fc51490bSJonas Devlieghere StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
86222555bafSSam McCall getDirectoryID(Dir->getUniqueID(), Name),
86322555bafSSam McCall llvm::sys::toTimePoint(ModificationTime), ResolvedUser, ResolvedGroup,
86422555bafSSam McCall 0, sys::fs::file_type::directory_file, NewDirectoryPerms);
865fc51490bSJonas Devlieghere Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
8660eaee545SJonas Devlieghere Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
867fc51490bSJonas Devlieghere continue;
868fc51490bSJonas Devlieghere }
869fc51490bSJonas Devlieghere
870fc51490bSJonas Devlieghere if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
871fc51490bSJonas Devlieghere Dir = NewDir;
872fc51490bSJonas Devlieghere } else {
873fc51490bSJonas Devlieghere assert((isa<detail::InMemoryFile>(Node) ||
874fc51490bSJonas Devlieghere isa<detail::InMemoryHardLink>(Node)) &&
875fc51490bSJonas Devlieghere "Must be either file, hardlink or directory!");
876fc51490bSJonas Devlieghere
877fc51490bSJonas Devlieghere // Trying to insert a directory in place of a file.
878fc51490bSJonas Devlieghere if (I != E)
879fc51490bSJonas Devlieghere return false;
880fc51490bSJonas Devlieghere
881fc51490bSJonas Devlieghere // Return false only if the new file is different from the existing one.
882fc51490bSJonas Devlieghere if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
883fc51490bSJonas Devlieghere return Link->getResolvedFile().getBuffer()->getBuffer() ==
884fc51490bSJonas Devlieghere Buffer->getBuffer();
885fc51490bSJonas Devlieghere }
886fc51490bSJonas Devlieghere return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
887fc51490bSJonas Devlieghere Buffer->getBuffer();
888fc51490bSJonas Devlieghere }
889fc51490bSJonas Devlieghere }
890fc51490bSJonas Devlieghere }
891fc51490bSJonas Devlieghere
addFile(const Twine & P,time_t ModificationTime,std::unique_ptr<llvm::MemoryBuffer> Buffer,Optional<uint32_t> User,Optional<uint32_t> Group,Optional<llvm::sys::fs::file_type> Type,Optional<llvm::sys::fs::perms> Perms)892fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
893fc51490bSJonas Devlieghere std::unique_ptr<llvm::MemoryBuffer> Buffer,
894fc51490bSJonas Devlieghere Optional<uint32_t> User,
895fc51490bSJonas Devlieghere Optional<uint32_t> Group,
896fc51490bSJonas Devlieghere Optional<llvm::sys::fs::file_type> Type,
897fc51490bSJonas Devlieghere Optional<llvm::sys::fs::perms> Perms) {
898fc51490bSJonas Devlieghere return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
8999011903eSJan Svoboda Perms,
9009011903eSJan Svoboda [](detail::NewInMemoryNodeInfo NNI)
9019011903eSJan Svoboda -> std::unique_ptr<detail::InMemoryNode> {
9029011903eSJan Svoboda Status Stat = NNI.makeStatus();
9039011903eSJan Svoboda if (Stat.getType() == sys::fs::file_type::directory_file)
9049011903eSJan Svoboda return std::make_unique<detail::InMemoryDirectory>(Stat);
9059011903eSJan Svoboda return std::make_unique<detail::InMemoryFile>(
9069011903eSJan Svoboda Stat, std::move(NNI.Buffer));
9079011903eSJan Svoboda });
908fc51490bSJonas Devlieghere }
909fc51490bSJonas Devlieghere
addFileNoOwn(const Twine & P,time_t ModificationTime,const llvm::MemoryBufferRef & Buffer,Optional<uint32_t> User,Optional<uint32_t> Group,Optional<llvm::sys::fs::file_type> Type,Optional<llvm::sys::fs::perms> Perms)910fc51490bSJonas Devlieghere bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
911e763e032SDuncan P. N. Exon Smith const llvm::MemoryBufferRef &Buffer,
912fc51490bSJonas Devlieghere Optional<uint32_t> User,
913fc51490bSJonas Devlieghere Optional<uint32_t> Group,
914fc51490bSJonas Devlieghere Optional<llvm::sys::fs::file_type> Type,
915fc51490bSJonas Devlieghere Optional<llvm::sys::fs::perms> Perms) {
916e763e032SDuncan P. N. Exon Smith return addFile(P, ModificationTime, llvm::MemoryBuffer::getMemBuffer(Buffer),
917fc51490bSJonas Devlieghere std::move(User), std::move(Group), std::move(Type),
9189011903eSJan Svoboda std::move(Perms),
9199011903eSJan Svoboda [](detail::NewInMemoryNodeInfo NNI)
9209011903eSJan Svoboda -> std::unique_ptr<detail::InMemoryNode> {
9219011903eSJan Svoboda Status Stat = NNI.makeStatus();
9229011903eSJan Svoboda if (Stat.getType() == sys::fs::file_type::directory_file)
9239011903eSJan Svoboda return std::make_unique<detail::InMemoryDirectory>(Stat);
9249011903eSJan Svoboda return std::make_unique<detail::InMemoryFile>(
9259011903eSJan Svoboda Stat, std::move(NNI.Buffer));
9269011903eSJan Svoboda });
927fc51490bSJonas Devlieghere }
928fc51490bSJonas Devlieghere
929a44c6453SJan Svoboda detail::NamedNodeOrError
lookupNode(const Twine & P,bool FollowFinalSymlink,size_t SymlinkDepth) const930a44c6453SJan Svoboda InMemoryFileSystem::lookupNode(const Twine &P, bool FollowFinalSymlink,
931a44c6453SJan Svoboda size_t SymlinkDepth) const {
932fc51490bSJonas Devlieghere SmallString<128> Path;
933fc51490bSJonas Devlieghere P.toVector(Path);
934fc51490bSJonas Devlieghere
935fc51490bSJonas Devlieghere // Fix up relative paths. This just prepends the current working directory.
9369e0398daSJan Svoboda std::error_code EC = makeAbsolute(Path);
937fc51490bSJonas Devlieghere assert(!EC);
938fc51490bSJonas Devlieghere (void)EC;
939fc51490bSJonas Devlieghere
9409e0398daSJan Svoboda if (useNormalizedPaths())
941fc51490bSJonas Devlieghere llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
942fc51490bSJonas Devlieghere
9439e0398daSJan Svoboda const detail::InMemoryDirectory *Dir = Root.get();
944fc51490bSJonas Devlieghere if (Path.empty())
945a44c6453SJan Svoboda return detail::NamedNodeOrError(Path, Dir);
946fc51490bSJonas Devlieghere
947fc51490bSJonas Devlieghere auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
948fc51490bSJonas Devlieghere while (true) {
949fc51490bSJonas Devlieghere detail::InMemoryNode *Node = Dir->getChild(*I);
950fc51490bSJonas Devlieghere ++I;
951fc51490bSJonas Devlieghere if (!Node)
952fc51490bSJonas Devlieghere return errc::no_such_file_or_directory;
953fc51490bSJonas Devlieghere
954a44c6453SJan Svoboda if (auto Symlink = dyn_cast<detail::InMemorySymbolicLink>(Node)) {
955a44c6453SJan Svoboda // If we're at the end of the path, and we're not following through
956a44c6453SJan Svoboda // terminal symlinks, then we're done.
957a44c6453SJan Svoboda if (I == E && !FollowFinalSymlink)
958a44c6453SJan Svoboda return detail::NamedNodeOrError(Path, Symlink);
959a44c6453SJan Svoboda
960a44c6453SJan Svoboda if (SymlinkDepth > InMemoryFileSystem::MaxSymlinkDepth)
961a44c6453SJan Svoboda return errc::no_such_file_or_directory;
962a44c6453SJan Svoboda
963a44c6453SJan Svoboda SmallString<128> TargetPath = Symlink->getTargetPath();
964a44c6453SJan Svoboda if (std::error_code EC = makeAbsolute(TargetPath))
965a44c6453SJan Svoboda return EC;
966a44c6453SJan Svoboda
967a44c6453SJan Svoboda // Keep going with the target. We always want to follow symlinks here
968a44c6453SJan Svoboda // because we're either at the end of a path that we want to follow, or
969a44c6453SJan Svoboda // not at the end of a path, in which case we need to follow the symlink
970a44c6453SJan Svoboda // regardless.
971a44c6453SJan Svoboda auto Target =
972a44c6453SJan Svoboda lookupNode(TargetPath, /*FollowFinalSymlink=*/true, SymlinkDepth + 1);
973a44c6453SJan Svoboda if (!Target || I == E)
974a44c6453SJan Svoboda return Target;
975a44c6453SJan Svoboda
976a44c6453SJan Svoboda if (!isa<detail::InMemoryDirectory>(*Target))
977a44c6453SJan Svoboda return errc::no_such_file_or_directory;
978a44c6453SJan Svoboda
979a44c6453SJan Svoboda // Otherwise, continue on the search in the symlinked directory.
980a44c6453SJan Svoboda Dir = cast<detail::InMemoryDirectory>(*Target);
981a44c6453SJan Svoboda continue;
982a44c6453SJan Svoboda }
983a44c6453SJan Svoboda
984fc51490bSJonas Devlieghere // Return the file if it's at the end of the path.
985fc51490bSJonas Devlieghere if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
986fc51490bSJonas Devlieghere if (I == E)
987a44c6453SJan Svoboda return detail::NamedNodeOrError(Path, File);
988fc51490bSJonas Devlieghere return errc::no_such_file_or_directory;
989fc51490bSJonas Devlieghere }
990fc51490bSJonas Devlieghere
991fc51490bSJonas Devlieghere // If Node is HardLink then return the resolved file.
992fc51490bSJonas Devlieghere if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
993fc51490bSJonas Devlieghere if (I == E)
994a44c6453SJan Svoboda return detail::NamedNodeOrError(Path, &File->getResolvedFile());
995fc51490bSJonas Devlieghere return errc::no_such_file_or_directory;
996fc51490bSJonas Devlieghere }
997fc51490bSJonas Devlieghere // Traverse directories.
998fc51490bSJonas Devlieghere Dir = cast<detail::InMemoryDirectory>(Node);
999fc51490bSJonas Devlieghere if (I == E)
1000a44c6453SJan Svoboda return detail::NamedNodeOrError(Path, Dir);
1001fc51490bSJonas Devlieghere }
1002fc51490bSJonas Devlieghere }
1003fc51490bSJonas Devlieghere
addHardLink(const Twine & NewLink,const Twine & Target)10041ff5330eSJan Svoboda bool InMemoryFileSystem::addHardLink(const Twine &NewLink,
10051ff5330eSJan Svoboda const Twine &Target) {
1006a44c6453SJan Svoboda auto NewLinkNode = lookupNode(NewLink, /*FollowFinalSymlink=*/false);
1007a44c6453SJan Svoboda // Whether symlinks in the hardlink target are followed is
1008a44c6453SJan Svoboda // implementation-defined in POSIX.
1009a44c6453SJan Svoboda // We're following symlinks here to be consistent with macOS.
1010a44c6453SJan Svoboda auto TargetNode = lookupNode(Target, /*FollowFinalSymlink=*/true);
1011fc51490bSJonas Devlieghere // FromPath must not have been added before. ToPath must have been added
1012fc51490bSJonas Devlieghere // before. Resolved ToPath must be a File.
10131ff5330eSJan Svoboda if (!TargetNode || NewLinkNode || !isa<detail::InMemoryFile>(*TargetNode))
1014fc51490bSJonas Devlieghere return false;
10151ff5330eSJan Svoboda return addFile(NewLink, 0, nullptr, None, None, None, None,
10169011903eSJan Svoboda [&](detail::NewInMemoryNodeInfo NNI) {
10179011903eSJan Svoboda return std::make_unique<detail::InMemoryHardLink>(
10181ff5330eSJan Svoboda NNI.Path.str(),
10191ff5330eSJan Svoboda *cast<detail::InMemoryFile>(*TargetNode));
10209011903eSJan Svoboda });
1021fc51490bSJonas Devlieghere }
1022fc51490bSJonas Devlieghere
addSymbolicLink(const Twine & NewLink,const Twine & Target,time_t ModificationTime,Optional<uint32_t> User,Optional<uint32_t> Group,Optional<llvm::sys::fs::perms> Perms)1023a44c6453SJan Svoboda bool InMemoryFileSystem::addSymbolicLink(const Twine &NewLink,
1024a44c6453SJan Svoboda const Twine &Target,
1025a44c6453SJan Svoboda time_t ModificationTime,
1026a44c6453SJan Svoboda Optional<uint32_t> User,
1027a44c6453SJan Svoboda Optional<uint32_t> Group,
1028a44c6453SJan Svoboda Optional<llvm::sys::fs::perms> Perms) {
1029a44c6453SJan Svoboda auto NewLinkNode = lookupNode(NewLink, /*FollowFinalSymlink=*/false);
1030a44c6453SJan Svoboda if (NewLinkNode)
1031a44c6453SJan Svoboda return false;
1032a44c6453SJan Svoboda
1033a44c6453SJan Svoboda SmallString<128> NewLinkStr, TargetStr;
1034a44c6453SJan Svoboda NewLink.toVector(NewLinkStr);
1035a44c6453SJan Svoboda Target.toVector(TargetStr);
1036a44c6453SJan Svoboda
1037a44c6453SJan Svoboda return addFile(NewLinkStr, ModificationTime, nullptr, User, Group,
1038a44c6453SJan Svoboda sys::fs::file_type::symlink_file, Perms,
1039a44c6453SJan Svoboda [&](detail::NewInMemoryNodeInfo NNI) {
1040a44c6453SJan Svoboda return std::make_unique<detail::InMemorySymbolicLink>(
1041a44c6453SJan Svoboda NewLinkStr, TargetStr, NNI.makeStatus());
1042a44c6453SJan Svoboda });
1043a44c6453SJan Svoboda }
1044a44c6453SJan Svoboda
status(const Twine & Path)1045fc51490bSJonas Devlieghere llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
1046a44c6453SJan Svoboda auto Node = lookupNode(Path, /*FollowFinalSymlink=*/true);
1047fc51490bSJonas Devlieghere if (Node)
10489e24d14aSJan Svoboda return (*Node)->getStatus(Path);
1049fc51490bSJonas Devlieghere return Node.getError();
1050fc51490bSJonas Devlieghere }
1051fc51490bSJonas Devlieghere
1052fc51490bSJonas Devlieghere llvm::ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Path)1053fc51490bSJonas Devlieghere InMemoryFileSystem::openFileForRead(const Twine &Path) {
1054a44c6453SJan Svoboda auto Node = lookupNode(Path,/*FollowFinalSymlink=*/true);
1055fc51490bSJonas Devlieghere if (!Node)
1056fc51490bSJonas Devlieghere return Node.getError();
1057fc51490bSJonas Devlieghere
1058fc51490bSJonas Devlieghere // When we have a file provide a heap-allocated wrapper for the memory buffer
1059fc51490bSJonas Devlieghere // to match the ownership semantics for File.
1060fc51490bSJonas Devlieghere if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
1061fc51490bSJonas Devlieghere return std::unique_ptr<File>(
1062fc51490bSJonas Devlieghere new detail::InMemoryFileAdaptor(*F, Path.str()));
1063fc51490bSJonas Devlieghere
1064fc51490bSJonas Devlieghere // FIXME: errc::not_a_file?
1065fc51490bSJonas Devlieghere return make_error_code(llvm::errc::invalid_argument);
1066fc51490bSJonas Devlieghere }
1067fc51490bSJonas Devlieghere
1068fc51490bSJonas Devlieghere /// Adaptor from InMemoryDir::iterator to directory_iterator.
1069b439a08dSJan Svoboda class InMemoryFileSystem::DirIterator : public llvm::vfs::detail::DirIterImpl {
1070a44c6453SJan Svoboda const InMemoryFileSystem *FS;
1071fc51490bSJonas Devlieghere detail::InMemoryDirectory::const_iterator I;
1072fc51490bSJonas Devlieghere detail::InMemoryDirectory::const_iterator E;
1073fc51490bSJonas Devlieghere std::string RequestedDirName;
1074fc51490bSJonas Devlieghere
setCurrentEntry()1075fc51490bSJonas Devlieghere void setCurrentEntry() {
1076fc51490bSJonas Devlieghere if (I != E) {
1077fc51490bSJonas Devlieghere SmallString<256> Path(RequestedDirName);
1078fc51490bSJonas Devlieghere llvm::sys::path::append(Path, I->second->getFileName());
1079e1000f1dSSimon Pilgrim sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1080fc51490bSJonas Devlieghere switch (I->second->getKind()) {
1081fc51490bSJonas Devlieghere case detail::IME_File:
1082fc51490bSJonas Devlieghere case detail::IME_HardLink:
1083fc51490bSJonas Devlieghere Type = sys::fs::file_type::regular_file;
1084fc51490bSJonas Devlieghere break;
1085fc51490bSJonas Devlieghere case detail::IME_Directory:
1086fc51490bSJonas Devlieghere Type = sys::fs::file_type::directory_file;
1087fc51490bSJonas Devlieghere break;
1088a44c6453SJan Svoboda case detail::IME_SymbolicLink:
1089a44c6453SJan Svoboda if (auto SymlinkTarget =
1090a44c6453SJan Svoboda FS->lookupNode(Path, /*FollowFinalSymlink=*/true)) {
1091a44c6453SJan Svoboda Path = SymlinkTarget.getName();
1092a44c6453SJan Svoboda Type = (*SymlinkTarget)->getStatus(Path).getType();
1093a44c6453SJan Svoboda }
1094a44c6453SJan Svoboda break;
1095fc51490bSJonas Devlieghere }
1096adcd0268SBenjamin Kramer CurrentEntry = directory_entry(std::string(Path.str()), Type);
1097fc51490bSJonas Devlieghere } else {
1098fc51490bSJonas Devlieghere // When we're at the end, make CurrentEntry invalid and DirIterImpl will
1099fc51490bSJonas Devlieghere // do the rest.
1100fc51490bSJonas Devlieghere CurrentEntry = directory_entry();
1101fc51490bSJonas Devlieghere }
1102fc51490bSJonas Devlieghere }
1103fc51490bSJonas Devlieghere
1104fc51490bSJonas Devlieghere public:
1105b439a08dSJan Svoboda DirIterator() = default;
1106fc51490bSJonas Devlieghere
DirIterator(const InMemoryFileSystem * FS,const detail::InMemoryDirectory & Dir,std::string RequestedDirName)1107a44c6453SJan Svoboda DirIterator(const InMemoryFileSystem *FS,
1108a44c6453SJan Svoboda const detail::InMemoryDirectory &Dir,
1109fc51490bSJonas Devlieghere std::string RequestedDirName)
1110a44c6453SJan Svoboda : FS(FS), I(Dir.begin()), E(Dir.end()),
1111fc51490bSJonas Devlieghere RequestedDirName(std::move(RequestedDirName)) {
1112fc51490bSJonas Devlieghere setCurrentEntry();
1113fc51490bSJonas Devlieghere }
1114fc51490bSJonas Devlieghere
increment()1115fc51490bSJonas Devlieghere std::error_code increment() override {
1116fc51490bSJonas Devlieghere ++I;
1117fc51490bSJonas Devlieghere setCurrentEntry();
1118fc51490bSJonas Devlieghere return {};
1119fc51490bSJonas Devlieghere }
1120fc51490bSJonas Devlieghere };
1121fc51490bSJonas Devlieghere
dir_begin(const Twine & Dir,std::error_code & EC)1122fc51490bSJonas Devlieghere directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
1123fc51490bSJonas Devlieghere std::error_code &EC) {
1124a44c6453SJan Svoboda auto Node = lookupNode(Dir, /*FollowFinalSymlink=*/true);
1125fc51490bSJonas Devlieghere if (!Node) {
1126fc51490bSJonas Devlieghere EC = Node.getError();
1127b439a08dSJan Svoboda return directory_iterator(std::make_shared<DirIterator>());
1128fc51490bSJonas Devlieghere }
1129fc51490bSJonas Devlieghere
1130fc51490bSJonas Devlieghere if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
1131fc51490bSJonas Devlieghere return directory_iterator(
1132a44c6453SJan Svoboda std::make_shared<DirIterator>(this, *DirNode, Dir.str()));
1133fc51490bSJonas Devlieghere
1134fc51490bSJonas Devlieghere EC = make_error_code(llvm::errc::not_a_directory);
1135b439a08dSJan Svoboda return directory_iterator(std::make_shared<DirIterator>());
1136fc51490bSJonas Devlieghere }
1137fc51490bSJonas Devlieghere
setCurrentWorkingDirectory(const Twine & P)1138fc51490bSJonas Devlieghere std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
1139fc51490bSJonas Devlieghere SmallString<128> Path;
1140fc51490bSJonas Devlieghere P.toVector(Path);
1141fc51490bSJonas Devlieghere
1142fc51490bSJonas Devlieghere // Fix up relative paths. This just prepends the current working directory.
1143fc51490bSJonas Devlieghere std::error_code EC = makeAbsolute(Path);
1144fc51490bSJonas Devlieghere assert(!EC);
1145fc51490bSJonas Devlieghere (void)EC;
1146fc51490bSJonas Devlieghere
1147fc51490bSJonas Devlieghere if (useNormalizedPaths())
1148fc51490bSJonas Devlieghere llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1149fc51490bSJonas Devlieghere
1150fc51490bSJonas Devlieghere if (!Path.empty())
1151adcd0268SBenjamin Kramer WorkingDirectory = std::string(Path.str());
1152fc51490bSJonas Devlieghere return {};
1153fc51490bSJonas Devlieghere }
1154fc51490bSJonas Devlieghere
115599538e89SSam McCall std::error_code
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const115699538e89SSam McCall InMemoryFileSystem::getRealPath(const Twine &Path,
115799538e89SSam McCall SmallVectorImpl<char> &Output) const {
1158fc51490bSJonas Devlieghere auto CWD = getCurrentWorkingDirectory();
1159fc51490bSJonas Devlieghere if (!CWD || CWD->empty())
1160fc51490bSJonas Devlieghere return errc::operation_not_permitted;
1161fc51490bSJonas Devlieghere Path.toVector(Output);
1162fc51490bSJonas Devlieghere if (auto EC = makeAbsolute(Output))
1163fc51490bSJonas Devlieghere return EC;
1164fc51490bSJonas Devlieghere llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
1165fc51490bSJonas Devlieghere return {};
1166fc51490bSJonas Devlieghere }
1167fc51490bSJonas Devlieghere
isLocal(const Twine & Path,bool & Result)1168cbb5c868SJonas Devlieghere std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
1169cbb5c868SJonas Devlieghere Result = false;
1170cbb5c868SJonas Devlieghere return {};
1171cbb5c868SJonas Devlieghere }
1172cbb5c868SJonas Devlieghere
printImpl(raw_ostream & OS,PrintType PrintContents,unsigned IndentLevel) const117341255241SBen Barham void InMemoryFileSystem::printImpl(raw_ostream &OS, PrintType PrintContents,
117441255241SBen Barham unsigned IndentLevel) const {
117541255241SBen Barham printIndent(OS, IndentLevel);
117641255241SBen Barham OS << "InMemoryFileSystem\n";
117741255241SBen Barham }
117841255241SBen Barham
1179fc51490bSJonas Devlieghere } // namespace vfs
1180fc51490bSJonas Devlieghere } // namespace llvm
1181fc51490bSJonas Devlieghere
1182fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
1183fc51490bSJonas Devlieghere // RedirectingFileSystem implementation
1184fc51490bSJonas Devlieghere //===-----------------------------------------------------------------------===/
1185fc51490bSJonas Devlieghere
1186da45bd23SAdrian McCarthy namespace {
1187da45bd23SAdrian McCarthy
getExistingStyle(llvm::StringRef Path)1188ecb00a77SNathan Hawes static llvm::sys::path::Style getExistingStyle(llvm::StringRef Path) {
1189ecb00a77SNathan Hawes // Detect the path style in use by checking the first separator.
1190da45bd23SAdrian McCarthy llvm::sys::path::Style style = llvm::sys::path::Style::native;
1191da45bd23SAdrian McCarthy const size_t n = Path.find_first_of("/\\");
119246ec93a4SMartin Storsjö // Can't distinguish between posix and windows_slash here.
1193da45bd23SAdrian McCarthy if (n != static_cast<size_t>(-1))
1194da45bd23SAdrian McCarthy style = (Path[n] == '/') ? llvm::sys::path::Style::posix
119546ec93a4SMartin Storsjö : llvm::sys::path::Style::windows_backslash;
1196ecb00a77SNathan Hawes return style;
1197ecb00a77SNathan Hawes }
1198ecb00a77SNathan Hawes
1199ecb00a77SNathan Hawes /// Removes leading "./" as well as path components like ".." and ".".
canonicalize(llvm::StringRef Path)1200ecb00a77SNathan Hawes static llvm::SmallString<256> canonicalize(llvm::StringRef Path) {
1201ecb00a77SNathan Hawes // First detect the path style in use by checking the first separator.
1202ecb00a77SNathan Hawes llvm::sys::path::Style style = getExistingStyle(Path);
1203da45bd23SAdrian McCarthy
1204da45bd23SAdrian McCarthy // Now remove the dots. Explicitly specifying the path style prevents the
1205da45bd23SAdrian McCarthy // direction of the slashes from changing.
1206da45bd23SAdrian McCarthy llvm::SmallString<256> result =
1207da45bd23SAdrian McCarthy llvm::sys::path::remove_leading_dotslash(Path, style);
1208da45bd23SAdrian McCarthy llvm::sys::path::remove_dots(result, /*remove_dot_dot=*/true, style);
1209da45bd23SAdrian McCarthy return result;
1210da45bd23SAdrian McCarthy }
1211da45bd23SAdrian McCarthy
1212502f14d6SBen Barham /// Whether the error and entry specify a file/directory that was not found.
isFileNotFound(std::error_code EC,RedirectingFileSystem::Entry * E=nullptr)1213502f14d6SBen Barham static bool isFileNotFound(std::error_code EC,
1214502f14d6SBen Barham RedirectingFileSystem::Entry *E = nullptr) {
1215502f14d6SBen Barham if (E && !isa<RedirectingFileSystem::DirectoryRemapEntry>(E))
1216502f14d6SBen Barham return false;
1217502f14d6SBen Barham return EC == llvm::errc::no_such_file_or_directory;
1218502f14d6SBen Barham }
1219502f14d6SBen Barham
1220da45bd23SAdrian McCarthy } // anonymous namespace
1221da45bd23SAdrian McCarthy
1222da45bd23SAdrian McCarthy
RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)122321703543SJonas Devlieghere RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
122421703543SJonas Devlieghere : ExternalFS(std::move(FS)) {
122521703543SJonas Devlieghere if (ExternalFS)
122621703543SJonas Devlieghere if (auto ExternalWorkingDirectory =
122721703543SJonas Devlieghere ExternalFS->getCurrentWorkingDirectory()) {
122821703543SJonas Devlieghere WorkingDirectory = *ExternalWorkingDirectory;
122921703543SJonas Devlieghere }
123021703543SJonas Devlieghere }
123121703543SJonas Devlieghere
1232719f7784SNathan Hawes /// Directory iterator implementation for \c RedirectingFileSystem's
1233719f7784SNathan Hawes /// directory entries.
1234719f7784SNathan Hawes class llvm::vfs::RedirectingFSDirIterImpl
12351a0ce65aSJonas Devlieghere : public llvm::vfs::detail::DirIterImpl {
1236fc51490bSJonas Devlieghere std::string Dir;
1237719f7784SNathan Hawes RedirectingFileSystem::DirectoryEntry::iterator Current, End;
1238fc51490bSJonas Devlieghere
incrementImpl(bool IsFirstTime)1239719f7784SNathan Hawes std::error_code incrementImpl(bool IsFirstTime) {
1240719f7784SNathan Hawes assert((IsFirstTime || Current != End) && "cannot iterate past end");
1241719f7784SNathan Hawes if (!IsFirstTime)
1242719f7784SNathan Hawes ++Current;
1243719f7784SNathan Hawes if (Current != End) {
1244719f7784SNathan Hawes SmallString<128> PathStr(Dir);
1245719f7784SNathan Hawes llvm::sys::path::append(PathStr, (*Current)->getName());
1246719f7784SNathan Hawes sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1247719f7784SNathan Hawes switch ((*Current)->getKind()) {
1248719f7784SNathan Hawes case RedirectingFileSystem::EK_Directory:
1249ecb00a77SNathan Hawes LLVM_FALLTHROUGH;
1250ecb00a77SNathan Hawes case RedirectingFileSystem::EK_DirectoryRemap:
1251719f7784SNathan Hawes Type = sys::fs::file_type::directory_file;
1252719f7784SNathan Hawes break;
1253719f7784SNathan Hawes case RedirectingFileSystem::EK_File:
1254719f7784SNathan Hawes Type = sys::fs::file_type::regular_file;
1255719f7784SNathan Hawes break;
1256719f7784SNathan Hawes }
1257719f7784SNathan Hawes CurrentEntry = directory_entry(std::string(PathStr.str()), Type);
1258719f7784SNathan Hawes } else {
1259719f7784SNathan Hawes CurrentEntry = directory_entry();
1260719f7784SNathan Hawes }
1261719f7784SNathan Hawes return {};
1262719f7784SNathan Hawes };
1263fc51490bSJonas Devlieghere
1264fc51490bSJonas Devlieghere public:
RedirectingFSDirIterImpl(const Twine & Path,RedirectingFileSystem::DirectoryEntry::iterator Begin,RedirectingFileSystem::DirectoryEntry::iterator End,std::error_code & EC)1265719f7784SNathan Hawes RedirectingFSDirIterImpl(
1266719f7784SNathan Hawes const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin,
1267719f7784SNathan Hawes RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC)
1268719f7784SNathan Hawes : Dir(Path.str()), Current(Begin), End(End) {
1269719f7784SNathan Hawes EC = incrementImpl(/*IsFirstTime=*/true);
1270719f7784SNathan Hawes }
1271fc51490bSJonas Devlieghere
increment()1272719f7784SNathan Hawes std::error_code increment() override {
1273719f7784SNathan Hawes return incrementImpl(/*IsFirstTime=*/false);
1274719f7784SNathan Hawes }
1275fc51490bSJonas Devlieghere };
1276fc51490bSJonas Devlieghere
12779b8b1645SBenjamin Kramer namespace {
1278ecb00a77SNathan Hawes /// Directory iterator implementation for \c RedirectingFileSystem's
1279ecb00a77SNathan Hawes /// directory remap entries that maps the paths reported by the external
1280ecb00a77SNathan Hawes /// file system's directory iterator back to the virtual directory's path.
1281ecb00a77SNathan Hawes class RedirectingFSDirRemapIterImpl : public llvm::vfs::detail::DirIterImpl {
1282ecb00a77SNathan Hawes std::string Dir;
1283ecb00a77SNathan Hawes llvm::sys::path::Style DirStyle;
1284ecb00a77SNathan Hawes llvm::vfs::directory_iterator ExternalIter;
1285ecb00a77SNathan Hawes
1286ecb00a77SNathan Hawes public:
RedirectingFSDirRemapIterImpl(std::string DirPath,llvm::vfs::directory_iterator ExtIter)1287ecb00a77SNathan Hawes RedirectingFSDirRemapIterImpl(std::string DirPath,
1288ecb00a77SNathan Hawes llvm::vfs::directory_iterator ExtIter)
1289ecb00a77SNathan Hawes : Dir(std::move(DirPath)), DirStyle(getExistingStyle(Dir)),
1290ecb00a77SNathan Hawes ExternalIter(ExtIter) {
1291ecb00a77SNathan Hawes if (ExternalIter != llvm::vfs::directory_iterator())
1292ecb00a77SNathan Hawes setCurrentEntry();
1293ecb00a77SNathan Hawes }
1294ecb00a77SNathan Hawes
setCurrentEntry()1295ecb00a77SNathan Hawes void setCurrentEntry() {
1296ecb00a77SNathan Hawes StringRef ExternalPath = ExternalIter->path();
1297ecb00a77SNathan Hawes llvm::sys::path::Style ExternalStyle = getExistingStyle(ExternalPath);
1298ecb00a77SNathan Hawes StringRef File = llvm::sys::path::filename(ExternalPath, ExternalStyle);
1299ecb00a77SNathan Hawes
1300ecb00a77SNathan Hawes SmallString<128> NewPath(Dir);
1301ecb00a77SNathan Hawes llvm::sys::path::append(NewPath, DirStyle, File);
1302ecb00a77SNathan Hawes
1303ecb00a77SNathan Hawes CurrentEntry = directory_entry(std::string(NewPath), ExternalIter->type());
1304ecb00a77SNathan Hawes }
1305ecb00a77SNathan Hawes
increment()1306ecb00a77SNathan Hawes std::error_code increment() override {
1307ecb00a77SNathan Hawes std::error_code EC;
1308ecb00a77SNathan Hawes ExternalIter.increment(EC);
1309ecb00a77SNathan Hawes if (!EC && ExternalIter != llvm::vfs::directory_iterator())
1310ecb00a77SNathan Hawes setCurrentEntry();
1311ecb00a77SNathan Hawes else
1312ecb00a77SNathan Hawes CurrentEntry = directory_entry();
1313ecb00a77SNathan Hawes return EC;
1314ecb00a77SNathan Hawes }
1315ecb00a77SNathan Hawes };
13169b8b1645SBenjamin Kramer } // namespace
1317ecb00a77SNathan Hawes
13181a0ce65aSJonas Devlieghere llvm::ErrorOr<std::string>
getCurrentWorkingDirectory() const13191a0ce65aSJonas Devlieghere RedirectingFileSystem::getCurrentWorkingDirectory() const {
132021703543SJonas Devlieghere return WorkingDirectory;
1321fc51490bSJonas Devlieghere }
1322fc51490bSJonas Devlieghere
13231a0ce65aSJonas Devlieghere std::error_code
setCurrentWorkingDirectory(const Twine & Path)13241a0ce65aSJonas Devlieghere RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
132521703543SJonas Devlieghere // Don't change the working directory if the path doesn't exist.
132621703543SJonas Devlieghere if (!exists(Path))
132721703543SJonas Devlieghere return errc::no_such_file_or_directory;
132821703543SJonas Devlieghere
132921703543SJonas Devlieghere SmallString<128> AbsolutePath;
133021703543SJonas Devlieghere Path.toVector(AbsolutePath);
133121703543SJonas Devlieghere if (std::error_code EC = makeAbsolute(AbsolutePath))
133221703543SJonas Devlieghere return EC;
1333adcd0268SBenjamin Kramer WorkingDirectory = std::string(AbsolutePath.str());
133421703543SJonas Devlieghere return {};
1335fc51490bSJonas Devlieghere }
1336fc51490bSJonas Devlieghere
isLocal(const Twine & Path_,bool & Result)13370be9ca7cSJonas Devlieghere std::error_code RedirectingFileSystem::isLocal(const Twine &Path_,
13381a0ce65aSJonas Devlieghere bool &Result) {
13390be9ca7cSJonas Devlieghere SmallString<256> Path;
13400be9ca7cSJonas Devlieghere Path_.toVector(Path);
13410be9ca7cSJonas Devlieghere
13420be9ca7cSJonas Devlieghere if (std::error_code EC = makeCanonical(Path))
13430be9ca7cSJonas Devlieghere return {};
13440be9ca7cSJonas Devlieghere
1345cbb5c868SJonas Devlieghere return ExternalFS->isLocal(Path, Result);
1346cbb5c868SJonas Devlieghere }
1347cbb5c868SJonas Devlieghere
makeAbsolute(SmallVectorImpl<char> & Path) const1348738b5c96SAdrian McCarthy std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
134946ec93a4SMartin Storsjö // is_absolute(..., Style::windows_*) accepts paths with both slash types.
1350738b5c96SAdrian McCarthy if (llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::posix) ||
135146ec93a4SMartin Storsjö llvm::sys::path::is_absolute(Path,
135246ec93a4SMartin Storsjö llvm::sys::path::Style::windows_backslash))
1353738b5c96SAdrian McCarthy return {};
1354738b5c96SAdrian McCarthy
1355738b5c96SAdrian McCarthy auto WorkingDir = getCurrentWorkingDirectory();
1356738b5c96SAdrian McCarthy if (!WorkingDir)
1357738b5c96SAdrian McCarthy return WorkingDir.getError();
1358738b5c96SAdrian McCarthy
1359da45bd23SAdrian McCarthy // We can't use sys::fs::make_absolute because that assumes the path style
1360da45bd23SAdrian McCarthy // is native and there is no way to override that. Since we know WorkingDir
1361da45bd23SAdrian McCarthy // is absolute, we can use it to determine which style we actually have and
1362da45bd23SAdrian McCarthy // append Path ourselves.
136346ec93a4SMartin Storsjö sys::path::Style style = sys::path::Style::windows_backslash;
1364da45bd23SAdrian McCarthy if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) {
1365da45bd23SAdrian McCarthy style = sys::path::Style::posix;
136646ec93a4SMartin Storsjö } else {
136746ec93a4SMartin Storsjö // Distinguish between windows_backslash and windows_slash; getExistingStyle
136846ec93a4SMartin Storsjö // returns posix for a path with windows_slash.
136946ec93a4SMartin Storsjö if (getExistingStyle(WorkingDir.get()) !=
137046ec93a4SMartin Storsjö sys::path::Style::windows_backslash)
137146ec93a4SMartin Storsjö style = sys::path::Style::windows_slash;
1372da45bd23SAdrian McCarthy }
1373da45bd23SAdrian McCarthy
1374da45bd23SAdrian McCarthy std::string Result = WorkingDir.get();
1375da45bd23SAdrian McCarthy StringRef Dir(Result);
1376da45bd23SAdrian McCarthy if (!Dir.endswith(sys::path::get_separator(style))) {
1377da45bd23SAdrian McCarthy Result += sys::path::get_separator(style);
1378da45bd23SAdrian McCarthy }
1379da45bd23SAdrian McCarthy Result.append(Path.data(), Path.size());
1380da45bd23SAdrian McCarthy Path.assign(Result.begin(), Result.end());
1381da45bd23SAdrian McCarthy
1382738b5c96SAdrian McCarthy return {};
1383738b5c96SAdrian McCarthy }
1384738b5c96SAdrian McCarthy
dir_begin(const Twine & Dir,std::error_code & EC)13851a0ce65aSJonas Devlieghere directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
13861a0ce65aSJonas Devlieghere std::error_code &EC) {
13870be9ca7cSJonas Devlieghere SmallString<256> Path;
13880be9ca7cSJonas Devlieghere Dir.toVector(Path);
13890be9ca7cSJonas Devlieghere
13900be9ca7cSJonas Devlieghere EC = makeCanonical(Path);
13910be9ca7cSJonas Devlieghere if (EC)
13920be9ca7cSJonas Devlieghere return {};
13930be9ca7cSJonas Devlieghere
1394ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
1395ecb00a77SNathan Hawes if (!Result) {
1396502f14d6SBen Barham if (Redirection != RedirectKind::RedirectOnly &&
1397502f14d6SBen Barham isFileNotFound(Result.getError()))
13980be9ca7cSJonas Devlieghere return ExternalFS->dir_begin(Path, EC);
1399502f14d6SBen Barham
1400502f14d6SBen Barham EC = Result.getError();
1401fc51490bSJonas Devlieghere return {};
1402fc51490bSJonas Devlieghere }
1403ecb00a77SNathan Hawes
1404ecb00a77SNathan Hawes // Use status to make sure the path exists and refers to a directory.
140586e2af80SKeith Smiley ErrorOr<Status> S = status(Path, Dir, *Result);
1406fc51490bSJonas Devlieghere if (!S) {
1407502f14d6SBen Barham if (Redirection != RedirectKind::RedirectOnly &&
1408502f14d6SBen Barham isFileNotFound(S.getError(), Result->E))
1409ecb00a77SNathan Hawes return ExternalFS->dir_begin(Dir, EC);
1410502f14d6SBen Barham
1411fc51490bSJonas Devlieghere EC = S.getError();
1412fc51490bSJonas Devlieghere return {};
1413fc51490bSJonas Devlieghere }
1414502f14d6SBen Barham
1415fc51490bSJonas Devlieghere if (!S->isDirectory()) {
1416ed4f0cb8SBen Barham EC = errc::not_a_directory;
1417fc51490bSJonas Devlieghere return {};
1418fc51490bSJonas Devlieghere }
1419fc51490bSJonas Devlieghere
1420ecb00a77SNathan Hawes // Create the appropriate directory iterator based on whether we found a
1421ecb00a77SNathan Hawes // DirectoryRemapEntry or DirectoryEntry.
1422502f14d6SBen Barham directory_iterator RedirectIter;
1423502f14d6SBen Barham std::error_code RedirectEC;
1424ecb00a77SNathan Hawes if (auto ExtRedirect = Result->getExternalRedirect()) {
1425ecb00a77SNathan Hawes auto RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
1426502f14d6SBen Barham RedirectIter = ExternalFS->dir_begin(*ExtRedirect, RedirectEC);
1427ecb00a77SNathan Hawes
1428ecb00a77SNathan Hawes if (!RE->useExternalName(UseExternalNames)) {
1429ecb00a77SNathan Hawes // Update the paths in the results to use the virtual directory's path.
1430502f14d6SBen Barham RedirectIter =
1431ecb00a77SNathan Hawes directory_iterator(std::make_shared<RedirectingFSDirRemapIterImpl>(
1432502f14d6SBen Barham std::string(Path), RedirectIter));
1433ecb00a77SNathan Hawes }
1434ecb00a77SNathan Hawes } else {
1435ecb00a77SNathan Hawes auto DE = cast<DirectoryEntry>(Result->E);
1436502f14d6SBen Barham RedirectIter =
1437502f14d6SBen Barham directory_iterator(std::make_shared<RedirectingFSDirIterImpl>(
1438502f14d6SBen Barham Path, DE->contents_begin(), DE->contents_end(), RedirectEC));
1439ecb00a77SNathan Hawes }
1440719f7784SNathan Hawes
1441502f14d6SBen Barham if (RedirectEC) {
1442502f14d6SBen Barham if (RedirectEC != errc::no_such_file_or_directory) {
1443502f14d6SBen Barham EC = RedirectEC;
1444502f14d6SBen Barham return {};
1445502f14d6SBen Barham }
1446502f14d6SBen Barham RedirectIter = {};
1447502f14d6SBen Barham }
1448502f14d6SBen Barham
1449502f14d6SBen Barham if (Redirection == RedirectKind::RedirectOnly) {
1450502f14d6SBen Barham EC = RedirectEC;
1451502f14d6SBen Barham return RedirectIter;
1452502f14d6SBen Barham }
1453502f14d6SBen Barham
1454502f14d6SBen Barham std::error_code ExternalEC;
1455502f14d6SBen Barham directory_iterator ExternalIter = ExternalFS->dir_begin(Path, ExternalEC);
1456502f14d6SBen Barham if (ExternalEC) {
1457502f14d6SBen Barham if (ExternalEC != errc::no_such_file_or_directory) {
1458502f14d6SBen Barham EC = ExternalEC;
1459502f14d6SBen Barham return {};
1460502f14d6SBen Barham }
1461502f14d6SBen Barham ExternalIter = {};
1462502f14d6SBen Barham }
1463502f14d6SBen Barham
1464502f14d6SBen Barham SmallVector<directory_iterator, 2> Iters;
1465502f14d6SBen Barham switch (Redirection) {
1466502f14d6SBen Barham case RedirectKind::Fallthrough:
1467502f14d6SBen Barham Iters.push_back(ExternalIter);
1468502f14d6SBen Barham Iters.push_back(RedirectIter);
1469502f14d6SBen Barham break;
1470502f14d6SBen Barham case RedirectKind::Fallback:
1471502f14d6SBen Barham Iters.push_back(RedirectIter);
1472502f14d6SBen Barham Iters.push_back(ExternalIter);
1473502f14d6SBen Barham break;
1474502f14d6SBen Barham default:
1475502f14d6SBen Barham llvm_unreachable("unhandled RedirectKind");
1476502f14d6SBen Barham }
1477502f14d6SBen Barham
1478502f14d6SBen Barham directory_iterator Combined{
1479502f14d6SBen Barham std::make_shared<CombiningDirIterImpl>(Iters, EC)};
1480502f14d6SBen Barham if (EC)
1481502f14d6SBen Barham return {};
1482502f14d6SBen Barham return Combined;
1483fc51490bSJonas Devlieghere }
1484fc51490bSJonas Devlieghere
setExternalContentsPrefixDir(StringRef PrefixDir)14851a0ce65aSJonas Devlieghere void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) {
1486fc51490bSJonas Devlieghere ExternalContentsPrefixDir = PrefixDir.str();
1487fc51490bSJonas Devlieghere }
1488fc51490bSJonas Devlieghere
getExternalContentsPrefixDir() const14891a0ce65aSJonas Devlieghere StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const {
1490fc51490bSJonas Devlieghere return ExternalContentsPrefixDir;
1491fc51490bSJonas Devlieghere }
1492fc51490bSJonas Devlieghere
setFallthrough(bool Fallthrough)1493a5cff6afSBen Barham void RedirectingFileSystem::setFallthrough(bool Fallthrough) {
1494a5cff6afSBen Barham if (Fallthrough) {
1495a5cff6afSBen Barham Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
1496a5cff6afSBen Barham } else {
1497a5cff6afSBen Barham Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
1498a5cff6afSBen Barham }
1499a5cff6afSBen Barham }
1500a5cff6afSBen Barham
setRedirection(RedirectingFileSystem::RedirectKind Kind)1501502f14d6SBen Barham void RedirectingFileSystem::setRedirection(
1502502f14d6SBen Barham RedirectingFileSystem::RedirectKind Kind) {
1503502f14d6SBen Barham Redirection = Kind;
150437469061SJonas Devlieghere }
150537469061SJonas Devlieghere
getRoots() const150637469061SJonas Devlieghere std::vector<StringRef> RedirectingFileSystem::getRoots() const {
150737469061SJonas Devlieghere std::vector<StringRef> R;
150837469061SJonas Devlieghere for (const auto &Root : Roots)
150937469061SJonas Devlieghere R.push_back(Root->getName());
151037469061SJonas Devlieghere return R;
151137469061SJonas Devlieghere }
151237469061SJonas Devlieghere
printImpl(raw_ostream & OS,PrintType Type,unsigned IndentLevel) const151341255241SBen Barham void RedirectingFileSystem::printImpl(raw_ostream &OS, PrintType Type,
151441255241SBen Barham unsigned IndentLevel) const {
151541255241SBen Barham printIndent(OS, IndentLevel);
151641255241SBen Barham OS << "RedirectingFileSystem (UseExternalNames: "
151741255241SBen Barham << (UseExternalNames ? "true" : "false") << ")\n";
151841255241SBen Barham if (Type == PrintType::Summary)
151941255241SBen Barham return;
152041255241SBen Barham
1521fc51490bSJonas Devlieghere for (const auto &Root : Roots)
152241255241SBen Barham printEntry(OS, Root.get(), IndentLevel);
152341255241SBen Barham
152441255241SBen Barham printIndent(OS, IndentLevel);
152541255241SBen Barham OS << "ExternalFS:\n";
152641255241SBen Barham ExternalFS->print(OS, Type == PrintType::Contents ? PrintType::Summary : Type,
152741255241SBen Barham IndentLevel + 1);
1528fc51490bSJonas Devlieghere }
1529fc51490bSJonas Devlieghere
printEntry(raw_ostream & OS,RedirectingFileSystem::Entry * E,unsigned IndentLevel) const1530cc63ae42SBen Barham void RedirectingFileSystem::printEntry(raw_ostream &OS,
153197fc8eb4SJonas Devlieghere RedirectingFileSystem::Entry *E,
153241255241SBen Barham unsigned IndentLevel) const {
153341255241SBen Barham printIndent(OS, IndentLevel);
153441255241SBen Barham OS << "'" << E->getName() << "'";
1535fc51490bSJonas Devlieghere
153641255241SBen Barham switch (E->getKind()) {
153741255241SBen Barham case EK_Directory: {
153841255241SBen Barham auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(E);
1539fc51490bSJonas Devlieghere
154041255241SBen Barham OS << "\n";
1541fc51490bSJonas Devlieghere for (std::unique_ptr<Entry> &SubEntry :
1542fc51490bSJonas Devlieghere llvm::make_range(DE->contents_begin(), DE->contents_end()))
154341255241SBen Barham printEntry(OS, SubEntry.get(), IndentLevel + 1);
154441255241SBen Barham break;
154541255241SBen Barham }
154641255241SBen Barham case EK_DirectoryRemap:
154741255241SBen Barham case EK_File: {
154841255241SBen Barham auto *RE = cast<RedirectingFileSystem::RemapEntry>(E);
154941255241SBen Barham OS << " -> '" << RE->getExternalContentsPath() << "'";
155041255241SBen Barham switch (RE->getUseName()) {
155141255241SBen Barham case NK_NotSet:
155241255241SBen Barham break;
155341255241SBen Barham case NK_External:
155441255241SBen Barham OS << " (UseExternalName: true)";
155541255241SBen Barham break;
155641255241SBen Barham case NK_Virtual:
155741255241SBen Barham OS << " (UseExternalName: false)";
155841255241SBen Barham break;
155941255241SBen Barham }
156041255241SBen Barham OS << "\n";
156141255241SBen Barham break;
1562fc51490bSJonas Devlieghere }
1563fc51490bSJonas Devlieghere }
156441255241SBen Barham }
1565fc51490bSJonas Devlieghere
1566fc51490bSJonas Devlieghere /// A helper class to hold the common YAML parsing state.
15671a0ce65aSJonas Devlieghere class llvm::vfs::RedirectingFileSystemParser {
1568fc51490bSJonas Devlieghere yaml::Stream &Stream;
1569fc51490bSJonas Devlieghere
error(yaml::Node * N,const Twine & Msg)1570fc51490bSJonas Devlieghere void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1571fc51490bSJonas Devlieghere
1572fc51490bSJonas Devlieghere // false on error
parseScalarString(yaml::Node * N,StringRef & Result,SmallVectorImpl<char> & Storage)1573fc51490bSJonas Devlieghere bool parseScalarString(yaml::Node *N, StringRef &Result,
1574fc51490bSJonas Devlieghere SmallVectorImpl<char> &Storage) {
1575fc51490bSJonas Devlieghere const auto *S = dyn_cast<yaml::ScalarNode>(N);
1576fc51490bSJonas Devlieghere
1577fc51490bSJonas Devlieghere if (!S) {
1578fc51490bSJonas Devlieghere error(N, "expected string");
1579fc51490bSJonas Devlieghere return false;
1580fc51490bSJonas Devlieghere }
1581fc51490bSJonas Devlieghere Result = S->getValue(Storage);
1582fc51490bSJonas Devlieghere return true;
1583fc51490bSJonas Devlieghere }
1584fc51490bSJonas Devlieghere
1585fc51490bSJonas Devlieghere // false on error
parseScalarBool(yaml::Node * N,bool & Result)1586fc51490bSJonas Devlieghere bool parseScalarBool(yaml::Node *N, bool &Result) {
1587fc51490bSJonas Devlieghere SmallString<5> Storage;
1588fc51490bSJonas Devlieghere StringRef Value;
1589fc51490bSJonas Devlieghere if (!parseScalarString(N, Value, Storage))
1590fc51490bSJonas Devlieghere return false;
1591fc51490bSJonas Devlieghere
159242f74e82SMartin Storsjö if (Value.equals_insensitive("true") || Value.equals_insensitive("on") ||
159342f74e82SMartin Storsjö Value.equals_insensitive("yes") || Value == "1") {
1594fc51490bSJonas Devlieghere Result = true;
1595fc51490bSJonas Devlieghere return true;
159642f74e82SMartin Storsjö } else if (Value.equals_insensitive("false") ||
159742f74e82SMartin Storsjö Value.equals_insensitive("off") ||
159842f74e82SMartin Storsjö Value.equals_insensitive("no") || Value == "0") {
1599fc51490bSJonas Devlieghere Result = false;
1600fc51490bSJonas Devlieghere return true;
1601fc51490bSJonas Devlieghere }
1602fc51490bSJonas Devlieghere
1603fc51490bSJonas Devlieghere error(N, "expected boolean value");
1604fc51490bSJonas Devlieghere return false;
1605fc51490bSJonas Devlieghere }
1606fc51490bSJonas Devlieghere
1607502f14d6SBen Barham Optional<RedirectingFileSystem::RedirectKind>
parseRedirectKind(yaml::Node * N)1608502f14d6SBen Barham parseRedirectKind(yaml::Node *N) {
1609502f14d6SBen Barham SmallString<12> Storage;
1610502f14d6SBen Barham StringRef Value;
1611502f14d6SBen Barham if (!parseScalarString(N, Value, Storage))
1612502f14d6SBen Barham return None;
1613502f14d6SBen Barham
1614502f14d6SBen Barham if (Value.equals_insensitive("fallthrough")) {
1615502f14d6SBen Barham return RedirectingFileSystem::RedirectKind::Fallthrough;
1616502f14d6SBen Barham } else if (Value.equals_insensitive("fallback")) {
1617502f14d6SBen Barham return RedirectingFileSystem::RedirectKind::Fallback;
1618502f14d6SBen Barham } else if (Value.equals_insensitive("redirect-only")) {
1619502f14d6SBen Barham return RedirectingFileSystem::RedirectKind::RedirectOnly;
1620502f14d6SBen Barham }
1621502f14d6SBen Barham return None;
1622502f14d6SBen Barham }
1623502f14d6SBen Barham
1624fc51490bSJonas Devlieghere struct KeyStatus {
1625fc51490bSJonas Devlieghere bool Required;
1626fc51490bSJonas Devlieghere bool Seen = false;
1627fc51490bSJonas Devlieghere
KeyStatusllvm::vfs::RedirectingFileSystemParser::KeyStatus1628fc51490bSJonas Devlieghere KeyStatus(bool Required = false) : Required(Required) {}
1629fc51490bSJonas Devlieghere };
1630fc51490bSJonas Devlieghere
1631fc51490bSJonas Devlieghere using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1632fc51490bSJonas Devlieghere
1633fc51490bSJonas Devlieghere // false on error
checkDuplicateOrUnknownKey(yaml::Node * KeyNode,StringRef Key,DenseMap<StringRef,KeyStatus> & Keys)1634fc51490bSJonas Devlieghere bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1635fc51490bSJonas Devlieghere DenseMap<StringRef, KeyStatus> &Keys) {
1636fc51490bSJonas Devlieghere if (!Keys.count(Key)) {
1637fc51490bSJonas Devlieghere error(KeyNode, "unknown key");
1638fc51490bSJonas Devlieghere return false;
1639fc51490bSJonas Devlieghere }
1640fc51490bSJonas Devlieghere KeyStatus &S = Keys[Key];
1641fc51490bSJonas Devlieghere if (S.Seen) {
1642fc51490bSJonas Devlieghere error(KeyNode, Twine("duplicate key '") + Key + "'");
1643fc51490bSJonas Devlieghere return false;
1644fc51490bSJonas Devlieghere }
1645fc51490bSJonas Devlieghere S.Seen = true;
1646fc51490bSJonas Devlieghere return true;
1647fc51490bSJonas Devlieghere }
1648fc51490bSJonas Devlieghere
1649fc51490bSJonas Devlieghere // false on error
checkMissingKeys(yaml::Node * Obj,DenseMap<StringRef,KeyStatus> & Keys)1650fc51490bSJonas Devlieghere bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1651fc51490bSJonas Devlieghere for (const auto &I : Keys) {
1652fc51490bSJonas Devlieghere if (I.second.Required && !I.second.Seen) {
1653fc51490bSJonas Devlieghere error(Obj, Twine("missing key '") + I.first + "'");
1654fc51490bSJonas Devlieghere return false;
1655fc51490bSJonas Devlieghere }
1656fc51490bSJonas Devlieghere }
1657fc51490bSJonas Devlieghere return true;
1658fc51490bSJonas Devlieghere }
1659fc51490bSJonas Devlieghere
166075cd8d75SDuncan P. N. Exon Smith public:
166175cd8d75SDuncan P. N. Exon Smith static RedirectingFileSystem::Entry *
lookupOrCreateEntry(RedirectingFileSystem * FS,StringRef Name,RedirectingFileSystem::Entry * ParentEntry=nullptr)16621a0ce65aSJonas Devlieghere lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
16631a0ce65aSJonas Devlieghere RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1664fc51490bSJonas Devlieghere if (!ParentEntry) { // Look for a existent root
1665fc51490bSJonas Devlieghere for (const auto &Root : FS->Roots) {
1666fc51490bSJonas Devlieghere if (Name.equals(Root->getName())) {
1667fc51490bSJonas Devlieghere ParentEntry = Root.get();
1668fc51490bSJonas Devlieghere return ParentEntry;
1669fc51490bSJonas Devlieghere }
1670fc51490bSJonas Devlieghere }
1671fc51490bSJonas Devlieghere } else { // Advance to the next component
1672719f7784SNathan Hawes auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
16731a0ce65aSJonas Devlieghere for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1674fc51490bSJonas Devlieghere llvm::make_range(DE->contents_begin(), DE->contents_end())) {
16751a0ce65aSJonas Devlieghere auto *DirContent =
1676719f7784SNathan Hawes dyn_cast<RedirectingFileSystem::DirectoryEntry>(Content.get());
1677fc51490bSJonas Devlieghere if (DirContent && Name.equals(Content->getName()))
1678fc51490bSJonas Devlieghere return DirContent;
1679fc51490bSJonas Devlieghere }
1680fc51490bSJonas Devlieghere }
1681fc51490bSJonas Devlieghere
1682fc51490bSJonas Devlieghere // ... or create a new one
16831a0ce65aSJonas Devlieghere std::unique_ptr<RedirectingFileSystem::Entry> E =
1684719f7784SNathan Hawes std::make_unique<RedirectingFileSystem::DirectoryEntry>(
16851a0ce65aSJonas Devlieghere Name, Status("", getNextVirtualUniqueID(),
16861a0ce65aSJonas Devlieghere std::chrono::system_clock::now(), 0, 0, 0,
16871a0ce65aSJonas Devlieghere file_type::directory_file, sys::fs::all_all));
1688fc51490bSJonas Devlieghere
1689fc51490bSJonas Devlieghere if (!ParentEntry) { // Add a new root to the overlay
1690fc51490bSJonas Devlieghere FS->Roots.push_back(std::move(E));
1691fc51490bSJonas Devlieghere ParentEntry = FS->Roots.back().get();
1692fc51490bSJonas Devlieghere return ParentEntry;
1693fc51490bSJonas Devlieghere }
1694fc51490bSJonas Devlieghere
1695719f7784SNathan Hawes auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
1696fc51490bSJonas Devlieghere DE->addContent(std::move(E));
1697fc51490bSJonas Devlieghere return DE->getLastContent();
1698fc51490bSJonas Devlieghere }
1699fc51490bSJonas Devlieghere
170075cd8d75SDuncan P. N. Exon Smith private:
uniqueOverlayTree(RedirectingFileSystem * FS,RedirectingFileSystem::Entry * SrcE,RedirectingFileSystem::Entry * NewParentE=nullptr)17011a0ce65aSJonas Devlieghere void uniqueOverlayTree(RedirectingFileSystem *FS,
17021a0ce65aSJonas Devlieghere RedirectingFileSystem::Entry *SrcE,
17031a0ce65aSJonas Devlieghere RedirectingFileSystem::Entry *NewParentE = nullptr) {
1704fc51490bSJonas Devlieghere StringRef Name = SrcE->getName();
1705fc51490bSJonas Devlieghere switch (SrcE->getKind()) {
17061a0ce65aSJonas Devlieghere case RedirectingFileSystem::EK_Directory: {
1707719f7784SNathan Hawes auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
1708fc51490bSJonas Devlieghere // Empty directories could be present in the YAML as a way to
1709fc51490bSJonas Devlieghere // describe a file for a current directory after some of its subdir
1710fc51490bSJonas Devlieghere // is parsed. This only leads to redundant walks, ignore it.
1711fc51490bSJonas Devlieghere if (!Name.empty())
1712fc51490bSJonas Devlieghere NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
17131a0ce65aSJonas Devlieghere for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1714fc51490bSJonas Devlieghere llvm::make_range(DE->contents_begin(), DE->contents_end()))
1715fc51490bSJonas Devlieghere uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1716fc51490bSJonas Devlieghere break;
1717fc51490bSJonas Devlieghere }
1718ecb00a77SNathan Hawes case RedirectingFileSystem::EK_DirectoryRemap: {
1719ecb00a77SNathan Hawes assert(NewParentE && "Parent entry must exist");
1720ecb00a77SNathan Hawes auto *DR = cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
1721ecb00a77SNathan Hawes auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1722ecb00a77SNathan Hawes DE->addContent(
1723ecb00a77SNathan Hawes std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1724ecb00a77SNathan Hawes Name, DR->getExternalContentsPath(), DR->getUseName()));
1725ecb00a77SNathan Hawes break;
1726ecb00a77SNathan Hawes }
17271a0ce65aSJonas Devlieghere case RedirectingFileSystem::EK_File: {
1728fc51490bSJonas Devlieghere assert(NewParentE && "Parent entry must exist");
1729719f7784SNathan Hawes auto *FE = cast<RedirectingFileSystem::FileEntry>(SrcE);
1730719f7784SNathan Hawes auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1731719f7784SNathan Hawes DE->addContent(std::make_unique<RedirectingFileSystem::FileEntry>(
1732fc51490bSJonas Devlieghere Name, FE->getExternalContentsPath(), FE->getUseName()));
1733fc51490bSJonas Devlieghere break;
1734fc51490bSJonas Devlieghere }
1735fc51490bSJonas Devlieghere }
1736fc51490bSJonas Devlieghere }
1737fc51490bSJonas Devlieghere
17381a0ce65aSJonas Devlieghere std::unique_ptr<RedirectingFileSystem::Entry>
parseEntry(yaml::Node * N,RedirectingFileSystem * FS,bool IsRootEntry)17391a0ce65aSJonas Devlieghere parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1740fc51490bSJonas Devlieghere auto *M = dyn_cast<yaml::MappingNode>(N);
1741fc51490bSJonas Devlieghere if (!M) {
1742fc51490bSJonas Devlieghere error(N, "expected mapping node for file or directory entry");
1743fc51490bSJonas Devlieghere return nullptr;
1744fc51490bSJonas Devlieghere }
1745fc51490bSJonas Devlieghere
1746fc51490bSJonas Devlieghere KeyStatusPair Fields[] = {
1747fc51490bSJonas Devlieghere KeyStatusPair("name", true),
1748fc51490bSJonas Devlieghere KeyStatusPair("type", true),
1749fc51490bSJonas Devlieghere KeyStatusPair("contents", false),
1750fc51490bSJonas Devlieghere KeyStatusPair("external-contents", false),
1751fc51490bSJonas Devlieghere KeyStatusPair("use-external-name", false),
1752fc51490bSJonas Devlieghere };
1753fc51490bSJonas Devlieghere
1754fc51490bSJonas Devlieghere DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1755fc51490bSJonas Devlieghere
1756ecb00a77SNathan Hawes enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet;
17571a0ce65aSJonas Devlieghere std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
17581a0ce65aSJonas Devlieghere EntryArrayContents;
1759da45bd23SAdrian McCarthy SmallString<256> ExternalContentsPath;
1760da45bd23SAdrian McCarthy SmallString<256> Name;
1761cfe6fe06SSimon Pilgrim yaml::Node *NameValueNode = nullptr;
1762ecb00a77SNathan Hawes auto UseExternalName = RedirectingFileSystem::NK_NotSet;
17631a0ce65aSJonas Devlieghere RedirectingFileSystem::EntryKind Kind;
1764fc51490bSJonas Devlieghere
1765fc51490bSJonas Devlieghere for (auto &I : *M) {
1766fc51490bSJonas Devlieghere StringRef Key;
1767fc51490bSJonas Devlieghere // Reuse the buffer for key and value, since we don't look at key after
1768fc51490bSJonas Devlieghere // parsing value.
1769fc51490bSJonas Devlieghere SmallString<256> Buffer;
1770fc51490bSJonas Devlieghere if (!parseScalarString(I.getKey(), Key, Buffer))
1771fc51490bSJonas Devlieghere return nullptr;
1772fc51490bSJonas Devlieghere
1773fc51490bSJonas Devlieghere if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1774fc51490bSJonas Devlieghere return nullptr;
1775fc51490bSJonas Devlieghere
1776fc51490bSJonas Devlieghere StringRef Value;
1777fc51490bSJonas Devlieghere if (Key == "name") {
1778fc51490bSJonas Devlieghere if (!parseScalarString(I.getValue(), Value, Buffer))
1779fc51490bSJonas Devlieghere return nullptr;
1780fc51490bSJonas Devlieghere
1781fc51490bSJonas Devlieghere NameValueNode = I.getValue();
1782fc51490bSJonas Devlieghere // Guarantee that old YAML files containing paths with ".." and "."
1783fc51490bSJonas Devlieghere // are properly canonicalized before read into the VFS.
1784da45bd23SAdrian McCarthy Name = canonicalize(Value).str();
1785fc51490bSJonas Devlieghere } else if (Key == "type") {
1786fc51490bSJonas Devlieghere if (!parseScalarString(I.getValue(), Value, Buffer))
1787fc51490bSJonas Devlieghere return nullptr;
1788fc51490bSJonas Devlieghere if (Value == "file")
17891a0ce65aSJonas Devlieghere Kind = RedirectingFileSystem::EK_File;
1790fc51490bSJonas Devlieghere else if (Value == "directory")
17911a0ce65aSJonas Devlieghere Kind = RedirectingFileSystem::EK_Directory;
1792ecb00a77SNathan Hawes else if (Value == "directory-remap")
1793ecb00a77SNathan Hawes Kind = RedirectingFileSystem::EK_DirectoryRemap;
1794fc51490bSJonas Devlieghere else {
1795fc51490bSJonas Devlieghere error(I.getValue(), "unknown value for 'type'");
1796fc51490bSJonas Devlieghere return nullptr;
1797fc51490bSJonas Devlieghere }
1798fc51490bSJonas Devlieghere } else if (Key == "contents") {
1799ecb00a77SNathan Hawes if (ContentsField != CF_NotSet) {
1800fc51490bSJonas Devlieghere error(I.getKey(),
1801fc51490bSJonas Devlieghere "entry already has 'contents' or 'external-contents'");
1802fc51490bSJonas Devlieghere return nullptr;
1803fc51490bSJonas Devlieghere }
1804ecb00a77SNathan Hawes ContentsField = CF_List;
1805fc51490bSJonas Devlieghere auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
1806fc51490bSJonas Devlieghere if (!Contents) {
1807fc51490bSJonas Devlieghere // FIXME: this is only for directories, what about files?
1808fc51490bSJonas Devlieghere error(I.getValue(), "expected array");
1809fc51490bSJonas Devlieghere return nullptr;
1810fc51490bSJonas Devlieghere }
1811fc51490bSJonas Devlieghere
1812fc51490bSJonas Devlieghere for (auto &I : *Contents) {
18131a0ce65aSJonas Devlieghere if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1814fc51490bSJonas Devlieghere parseEntry(&I, FS, /*IsRootEntry*/ false))
1815fc51490bSJonas Devlieghere EntryArrayContents.push_back(std::move(E));
1816fc51490bSJonas Devlieghere else
1817fc51490bSJonas Devlieghere return nullptr;
1818fc51490bSJonas Devlieghere }
1819fc51490bSJonas Devlieghere } else if (Key == "external-contents") {
1820ecb00a77SNathan Hawes if (ContentsField != CF_NotSet) {
1821fc51490bSJonas Devlieghere error(I.getKey(),
1822fc51490bSJonas Devlieghere "entry already has 'contents' or 'external-contents'");
1823fc51490bSJonas Devlieghere return nullptr;
1824fc51490bSJonas Devlieghere }
1825ecb00a77SNathan Hawes ContentsField = CF_External;
1826fc51490bSJonas Devlieghere if (!parseScalarString(I.getValue(), Value, Buffer))
1827fc51490bSJonas Devlieghere return nullptr;
1828fc51490bSJonas Devlieghere
1829fc51490bSJonas Devlieghere SmallString<256> FullPath;
1830fc51490bSJonas Devlieghere if (FS->IsRelativeOverlay) {
1831fc51490bSJonas Devlieghere FullPath = FS->getExternalContentsPrefixDir();
1832fc51490bSJonas Devlieghere assert(!FullPath.empty() &&
1833fc51490bSJonas Devlieghere "External contents prefix directory must exist");
1834fc51490bSJonas Devlieghere llvm::sys::path::append(FullPath, Value);
1835fc51490bSJonas Devlieghere } else {
1836fc51490bSJonas Devlieghere FullPath = Value;
1837fc51490bSJonas Devlieghere }
1838fc51490bSJonas Devlieghere
1839fc51490bSJonas Devlieghere // Guarantee that old YAML files containing paths with ".." and "."
1840fc51490bSJonas Devlieghere // are properly canonicalized before read into the VFS.
1841da45bd23SAdrian McCarthy FullPath = canonicalize(FullPath);
1842da45bd23SAdrian McCarthy ExternalContentsPath = FullPath.str();
1843fc51490bSJonas Devlieghere } else if (Key == "use-external-name") {
1844fc51490bSJonas Devlieghere bool Val;
1845fc51490bSJonas Devlieghere if (!parseScalarBool(I.getValue(), Val))
1846fc51490bSJonas Devlieghere return nullptr;
1847ecb00a77SNathan Hawes UseExternalName = Val ? RedirectingFileSystem::NK_External
1848ecb00a77SNathan Hawes : RedirectingFileSystem::NK_Virtual;
1849fc51490bSJonas Devlieghere } else {
1850fc51490bSJonas Devlieghere llvm_unreachable("key missing from Keys");
1851fc51490bSJonas Devlieghere }
1852fc51490bSJonas Devlieghere }
1853fc51490bSJonas Devlieghere
1854fc51490bSJonas Devlieghere if (Stream.failed())
1855fc51490bSJonas Devlieghere return nullptr;
1856fc51490bSJonas Devlieghere
1857fc51490bSJonas Devlieghere // check for missing keys
1858ecb00a77SNathan Hawes if (ContentsField == CF_NotSet) {
1859fc51490bSJonas Devlieghere error(N, "missing key 'contents' or 'external-contents'");
1860fc51490bSJonas Devlieghere return nullptr;
1861fc51490bSJonas Devlieghere }
1862fc51490bSJonas Devlieghere if (!checkMissingKeys(N, Keys))
1863fc51490bSJonas Devlieghere return nullptr;
1864fc51490bSJonas Devlieghere
1865fc51490bSJonas Devlieghere // check invalid configuration
18661a0ce65aSJonas Devlieghere if (Kind == RedirectingFileSystem::EK_Directory &&
1867ecb00a77SNathan Hawes UseExternalName != RedirectingFileSystem::NK_NotSet) {
1868ecb00a77SNathan Hawes error(N, "'use-external-name' is not supported for 'directory' entries");
1869ecb00a77SNathan Hawes return nullptr;
1870ecb00a77SNathan Hawes }
1871ecb00a77SNathan Hawes
1872ecb00a77SNathan Hawes if (Kind == RedirectingFileSystem::EK_DirectoryRemap &&
1873ecb00a77SNathan Hawes ContentsField == CF_List) {
1874ecb00a77SNathan Hawes error(N, "'contents' is not supported for 'directory-remap' entries");
1875fc51490bSJonas Devlieghere return nullptr;
1876fc51490bSJonas Devlieghere }
1877fc51490bSJonas Devlieghere
1878738b5c96SAdrian McCarthy sys::path::Style path_style = sys::path::Style::native;
1879738b5c96SAdrian McCarthy if (IsRootEntry) {
1880738b5c96SAdrian McCarthy // VFS root entries may be in either Posix or Windows style. Figure out
1881738b5c96SAdrian McCarthy // which style we have, and use it consistently.
1882738b5c96SAdrian McCarthy if (sys::path::is_absolute(Name, sys::path::Style::posix)) {
1883738b5c96SAdrian McCarthy path_style = sys::path::Style::posix;
188446ec93a4SMartin Storsjö } else if (sys::path::is_absolute(Name,
188546ec93a4SMartin Storsjö sys::path::Style::windows_backslash)) {
188646ec93a4SMartin Storsjö path_style = sys::path::Style::windows_backslash;
1887738b5c96SAdrian McCarthy } else {
18884f61749eSRichard Howell // Relative VFS root entries are made absolute to the current working
18894f61749eSRichard Howell // directory, then we can determine the path style from that.
18904f61749eSRichard Howell auto EC = sys::fs::make_absolute(Name);
18914f61749eSRichard Howell if (EC) {
1892fc51490bSJonas Devlieghere assert(NameValueNode && "Name presence should be checked earlier");
18934f61749eSRichard Howell error(
18944f61749eSRichard Howell NameValueNode,
1895fc51490bSJonas Devlieghere "entry with relative path at the root level is not discoverable");
1896fc51490bSJonas Devlieghere return nullptr;
1897fc51490bSJonas Devlieghere }
18984f61749eSRichard Howell path_style = sys::path::is_absolute(Name, sys::path::Style::posix)
18994f61749eSRichard Howell ? sys::path::Style::posix
19004f61749eSRichard Howell : sys::path::Style::windows_backslash;
19014f61749eSRichard Howell }
1902738b5c96SAdrian McCarthy }
1903fc51490bSJonas Devlieghere
1904fc51490bSJonas Devlieghere // Remove trailing slash(es), being careful not to remove the root path
19051def2579SDavid Blaikie StringRef Trimmed = Name;
1906738b5c96SAdrian McCarthy size_t RootPathLen = sys::path::root_path(Trimmed, path_style).size();
1907fc51490bSJonas Devlieghere while (Trimmed.size() > RootPathLen &&
1908738b5c96SAdrian McCarthy sys::path::is_separator(Trimmed.back(), path_style))
1909fc51490bSJonas Devlieghere Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
1910738b5c96SAdrian McCarthy
1911fc51490bSJonas Devlieghere // Get the last component
1912738b5c96SAdrian McCarthy StringRef LastComponent = sys::path::filename(Trimmed, path_style);
1913fc51490bSJonas Devlieghere
19141a0ce65aSJonas Devlieghere std::unique_ptr<RedirectingFileSystem::Entry> Result;
1915fc51490bSJonas Devlieghere switch (Kind) {
19161a0ce65aSJonas Devlieghere case RedirectingFileSystem::EK_File:
1917719f7784SNathan Hawes Result = std::make_unique<RedirectingFileSystem::FileEntry>(
1918fc51490bSJonas Devlieghere LastComponent, std::move(ExternalContentsPath), UseExternalName);
1919fc51490bSJonas Devlieghere break;
1920ecb00a77SNathan Hawes case RedirectingFileSystem::EK_DirectoryRemap:
1921ecb00a77SNathan Hawes Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1922ecb00a77SNathan Hawes LastComponent, std::move(ExternalContentsPath), UseExternalName);
1923ecb00a77SNathan Hawes break;
19241a0ce65aSJonas Devlieghere case RedirectingFileSystem::EK_Directory:
1925719f7784SNathan Hawes Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1926fc51490bSJonas Devlieghere LastComponent, std::move(EntryArrayContents),
1927719f7784SNathan Hawes Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1928719f7784SNathan Hawes 0, 0, 0, file_type::directory_file, sys::fs::all_all));
1929fc51490bSJonas Devlieghere break;
1930fc51490bSJonas Devlieghere }
1931fc51490bSJonas Devlieghere
1932738b5c96SAdrian McCarthy StringRef Parent = sys::path::parent_path(Trimmed, path_style);
1933fc51490bSJonas Devlieghere if (Parent.empty())
1934fc51490bSJonas Devlieghere return Result;
1935fc51490bSJonas Devlieghere
1936fc51490bSJonas Devlieghere // if 'name' contains multiple components, create implicit directory entries
1937738b5c96SAdrian McCarthy for (sys::path::reverse_iterator I = sys::path::rbegin(Parent, path_style),
1938fc51490bSJonas Devlieghere E = sys::path::rend(Parent);
1939fc51490bSJonas Devlieghere I != E; ++I) {
19401a0ce65aSJonas Devlieghere std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
1941fc51490bSJonas Devlieghere Entries.push_back(std::move(Result));
1942719f7784SNathan Hawes Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1943fc51490bSJonas Devlieghere *I, std::move(Entries),
1944719f7784SNathan Hawes Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1945719f7784SNathan Hawes 0, 0, 0, file_type::directory_file, sys::fs::all_all));
1946fc51490bSJonas Devlieghere }
1947fc51490bSJonas Devlieghere return Result;
1948fc51490bSJonas Devlieghere }
1949fc51490bSJonas Devlieghere
1950fc51490bSJonas Devlieghere public:
RedirectingFileSystemParser(yaml::Stream & S)1951fc51490bSJonas Devlieghere RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1952fc51490bSJonas Devlieghere
1953fc51490bSJonas Devlieghere // false on error
parse(yaml::Node * Root,RedirectingFileSystem * FS)1954fc51490bSJonas Devlieghere bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1955fc51490bSJonas Devlieghere auto *Top = dyn_cast<yaml::MappingNode>(Root);
1956fc51490bSJonas Devlieghere if (!Top) {
1957fc51490bSJonas Devlieghere error(Root, "expected mapping node");
1958fc51490bSJonas Devlieghere return false;
1959fc51490bSJonas Devlieghere }
1960fc51490bSJonas Devlieghere
1961fc51490bSJonas Devlieghere KeyStatusPair Fields[] = {
1962fc51490bSJonas Devlieghere KeyStatusPair("version", true),
1963fc51490bSJonas Devlieghere KeyStatusPair("case-sensitive", false),
1964fc51490bSJonas Devlieghere KeyStatusPair("use-external-names", false),
1965fc51490bSJonas Devlieghere KeyStatusPair("overlay-relative", false),
196691e13164SVolodymyr Sapsai KeyStatusPair("fallthrough", false),
1967502f14d6SBen Barham KeyStatusPair("redirecting-with", false),
1968fc51490bSJonas Devlieghere KeyStatusPair("roots", true),
1969fc51490bSJonas Devlieghere };
1970fc51490bSJonas Devlieghere
1971fc51490bSJonas Devlieghere DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
19721a0ce65aSJonas Devlieghere std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
1973fc51490bSJonas Devlieghere
1974fc51490bSJonas Devlieghere // Parse configuration and 'roots'
1975fc51490bSJonas Devlieghere for (auto &I : *Top) {
1976fc51490bSJonas Devlieghere SmallString<10> KeyBuffer;
1977fc51490bSJonas Devlieghere StringRef Key;
1978fc51490bSJonas Devlieghere if (!parseScalarString(I.getKey(), Key, KeyBuffer))
1979fc51490bSJonas Devlieghere return false;
1980fc51490bSJonas Devlieghere
1981fc51490bSJonas Devlieghere if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1982fc51490bSJonas Devlieghere return false;
1983fc51490bSJonas Devlieghere
1984fc51490bSJonas Devlieghere if (Key == "roots") {
1985fc51490bSJonas Devlieghere auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
1986fc51490bSJonas Devlieghere if (!Roots) {
1987fc51490bSJonas Devlieghere error(I.getValue(), "expected array");
1988fc51490bSJonas Devlieghere return false;
1989fc51490bSJonas Devlieghere }
1990fc51490bSJonas Devlieghere
1991fc51490bSJonas Devlieghere for (auto &I : *Roots) {
19921a0ce65aSJonas Devlieghere if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1993fc51490bSJonas Devlieghere parseEntry(&I, FS, /*IsRootEntry*/ true))
1994fc51490bSJonas Devlieghere RootEntries.push_back(std::move(E));
1995fc51490bSJonas Devlieghere else
1996fc51490bSJonas Devlieghere return false;
1997fc51490bSJonas Devlieghere }
1998fc51490bSJonas Devlieghere } else if (Key == "version") {
1999fc51490bSJonas Devlieghere StringRef VersionString;
2000fc51490bSJonas Devlieghere SmallString<4> Storage;
2001fc51490bSJonas Devlieghere if (!parseScalarString(I.getValue(), VersionString, Storage))
2002fc51490bSJonas Devlieghere return false;
2003fc51490bSJonas Devlieghere int Version;
2004fc51490bSJonas Devlieghere if (VersionString.getAsInteger<int>(10, Version)) {
2005fc51490bSJonas Devlieghere error(I.getValue(), "expected integer");
2006fc51490bSJonas Devlieghere return false;
2007fc51490bSJonas Devlieghere }
2008fc51490bSJonas Devlieghere if (Version < 0) {
2009fc51490bSJonas Devlieghere error(I.getValue(), "invalid version number");
2010fc51490bSJonas Devlieghere return false;
2011fc51490bSJonas Devlieghere }
2012fc51490bSJonas Devlieghere if (Version != 0) {
2013fc51490bSJonas Devlieghere error(I.getValue(), "version mismatch, expected 0");
2014fc51490bSJonas Devlieghere return false;
2015fc51490bSJonas Devlieghere }
2016fc51490bSJonas Devlieghere } else if (Key == "case-sensitive") {
2017fc51490bSJonas Devlieghere if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
2018fc51490bSJonas Devlieghere return false;
2019fc51490bSJonas Devlieghere } else if (Key == "overlay-relative") {
2020fc51490bSJonas Devlieghere if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
2021fc51490bSJonas Devlieghere return false;
2022fc51490bSJonas Devlieghere } else if (Key == "use-external-names") {
2023fc51490bSJonas Devlieghere if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
2024fc51490bSJonas Devlieghere return false;
202591e13164SVolodymyr Sapsai } else if (Key == "fallthrough") {
2026502f14d6SBen Barham if (Keys["redirecting-with"].Seen) {
2027502f14d6SBen Barham error(I.getValue(),
2028502f14d6SBen Barham "'fallthrough' and 'redirecting-with' are mutually exclusive");
202991e13164SVolodymyr Sapsai return false;
2030502f14d6SBen Barham }
2031502f14d6SBen Barham
2032502f14d6SBen Barham bool ShouldFallthrough = false;
2033502f14d6SBen Barham if (!parseScalarBool(I.getValue(), ShouldFallthrough))
2034502f14d6SBen Barham return false;
2035502f14d6SBen Barham
2036502f14d6SBen Barham if (ShouldFallthrough) {
2037502f14d6SBen Barham FS->Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
2038502f14d6SBen Barham } else {
2039502f14d6SBen Barham FS->Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
2040502f14d6SBen Barham }
2041502f14d6SBen Barham } else if (Key == "redirecting-with") {
2042502f14d6SBen Barham if (Keys["fallthrough"].Seen) {
2043502f14d6SBen Barham error(I.getValue(),
2044502f14d6SBen Barham "'fallthrough' and 'redirecting-with' are mutually exclusive");
2045502f14d6SBen Barham return false;
2046502f14d6SBen Barham }
2047502f14d6SBen Barham
2048502f14d6SBen Barham if (auto Kind = parseRedirectKind(I.getValue())) {
2049502f14d6SBen Barham FS->Redirection = *Kind;
2050502f14d6SBen Barham } else {
2051502f14d6SBen Barham error(I.getValue(), "expected valid redirect kind");
2052502f14d6SBen Barham return false;
2053502f14d6SBen Barham }
2054fc51490bSJonas Devlieghere } else {
2055fc51490bSJonas Devlieghere llvm_unreachable("key missing from Keys");
2056fc51490bSJonas Devlieghere }
2057fc51490bSJonas Devlieghere }
2058fc51490bSJonas Devlieghere
2059fc51490bSJonas Devlieghere if (Stream.failed())
2060fc51490bSJonas Devlieghere return false;
2061fc51490bSJonas Devlieghere
2062fc51490bSJonas Devlieghere if (!checkMissingKeys(Top, Keys))
2063fc51490bSJonas Devlieghere return false;
2064fc51490bSJonas Devlieghere
2065fc51490bSJonas Devlieghere // Now that we sucessefully parsed the YAML file, canonicalize the internal
2066fc51490bSJonas Devlieghere // representation to a proper directory tree so that we can search faster
2067fc51490bSJonas Devlieghere // inside the VFS.
2068fc51490bSJonas Devlieghere for (auto &E : RootEntries)
2069fc51490bSJonas Devlieghere uniqueOverlayTree(FS, E.get());
2070fc51490bSJonas Devlieghere
2071fc51490bSJonas Devlieghere return true;
2072fc51490bSJonas Devlieghere }
2073fc51490bSJonas Devlieghere };
2074fc51490bSJonas Devlieghere
2075a22eda54SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem>
create(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)2076fc51490bSJonas Devlieghere RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
2077fc51490bSJonas Devlieghere SourceMgr::DiagHandlerTy DiagHandler,
2078fc51490bSJonas Devlieghere StringRef YAMLFilePath, void *DiagContext,
2079fc51490bSJonas Devlieghere IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2080fc51490bSJonas Devlieghere SourceMgr SM;
2081fc51490bSJonas Devlieghere yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
2082fc51490bSJonas Devlieghere
2083fc51490bSJonas Devlieghere SM.setDiagHandler(DiagHandler, DiagContext);
2084fc51490bSJonas Devlieghere yaml::document_iterator DI = Stream.begin();
2085fc51490bSJonas Devlieghere yaml::Node *Root = DI->getRoot();
2086fc51490bSJonas Devlieghere if (DI == Stream.end() || !Root) {
2087fc51490bSJonas Devlieghere SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
2088fc51490bSJonas Devlieghere return nullptr;
2089fc51490bSJonas Devlieghere }
2090fc51490bSJonas Devlieghere
2091fc51490bSJonas Devlieghere RedirectingFileSystemParser P(Stream);
2092fc51490bSJonas Devlieghere
2093fc51490bSJonas Devlieghere std::unique_ptr<RedirectingFileSystem> FS(
209421703543SJonas Devlieghere new RedirectingFileSystem(ExternalFS));
2095fc51490bSJonas Devlieghere
2096fc51490bSJonas Devlieghere if (!YAMLFilePath.empty()) {
2097fc51490bSJonas Devlieghere // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
2098fc51490bSJonas Devlieghere // to each 'external-contents' path.
2099fc51490bSJonas Devlieghere //
2100fc51490bSJonas Devlieghere // Example:
2101fc51490bSJonas Devlieghere // -ivfsoverlay dummy.cache/vfs/vfs.yaml
2102fc51490bSJonas Devlieghere // yields:
2103fc51490bSJonas Devlieghere // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
2104fc51490bSJonas Devlieghere //
2105fc51490bSJonas Devlieghere SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
2106fc51490bSJonas Devlieghere std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
2107fc51490bSJonas Devlieghere assert(!EC && "Overlay dir final path must be absolute");
2108fc51490bSJonas Devlieghere (void)EC;
2109fc51490bSJonas Devlieghere FS->setExternalContentsPrefixDir(OverlayAbsDir);
2110fc51490bSJonas Devlieghere }
2111fc51490bSJonas Devlieghere
2112fc51490bSJonas Devlieghere if (!P.parse(Root, FS.get()))
2113fc51490bSJonas Devlieghere return nullptr;
2114fc51490bSJonas Devlieghere
2115a22eda54SDuncan P. N. Exon Smith return FS;
2116fc51490bSJonas Devlieghere }
2117fc51490bSJonas Devlieghere
create(ArrayRef<std::pair<std::string,std::string>> RemappedFiles,bool UseExternalNames,FileSystem & ExternalFS)211875cd8d75SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create(
211975cd8d75SDuncan P. N. Exon Smith ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
212075cd8d75SDuncan P. N. Exon Smith bool UseExternalNames, FileSystem &ExternalFS) {
212175cd8d75SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem> FS(
212275cd8d75SDuncan P. N. Exon Smith new RedirectingFileSystem(&ExternalFS));
212375cd8d75SDuncan P. N. Exon Smith FS->UseExternalNames = UseExternalNames;
212475cd8d75SDuncan P. N. Exon Smith
212575cd8d75SDuncan P. N. Exon Smith StringMap<RedirectingFileSystem::Entry *> Entries;
212675cd8d75SDuncan P. N. Exon Smith
212775cd8d75SDuncan P. N. Exon Smith for (auto &Mapping : llvm::reverse(RemappedFiles)) {
212875cd8d75SDuncan P. N. Exon Smith SmallString<128> From = StringRef(Mapping.first);
212975cd8d75SDuncan P. N. Exon Smith SmallString<128> To = StringRef(Mapping.second);
213075cd8d75SDuncan P. N. Exon Smith {
213175cd8d75SDuncan P. N. Exon Smith auto EC = ExternalFS.makeAbsolute(From);
213275cd8d75SDuncan P. N. Exon Smith (void)EC;
213375cd8d75SDuncan P. N. Exon Smith assert(!EC && "Could not make absolute path");
213475cd8d75SDuncan P. N. Exon Smith }
213575cd8d75SDuncan P. N. Exon Smith
213675cd8d75SDuncan P. N. Exon Smith // Check if we've already mapped this file. The first one we see (in the
213775cd8d75SDuncan P. N. Exon Smith // reverse iteration) wins.
213875cd8d75SDuncan P. N. Exon Smith RedirectingFileSystem::Entry *&ToEntry = Entries[From];
213975cd8d75SDuncan P. N. Exon Smith if (ToEntry)
214075cd8d75SDuncan P. N. Exon Smith continue;
214175cd8d75SDuncan P. N. Exon Smith
214275cd8d75SDuncan P. N. Exon Smith // Add parent directories.
214375cd8d75SDuncan P. N. Exon Smith RedirectingFileSystem::Entry *Parent = nullptr;
214475cd8d75SDuncan P. N. Exon Smith StringRef FromDirectory = llvm::sys::path::parent_path(From);
214575cd8d75SDuncan P. N. Exon Smith for (auto I = llvm::sys::path::begin(FromDirectory),
214675cd8d75SDuncan P. N. Exon Smith E = llvm::sys::path::end(FromDirectory);
214775cd8d75SDuncan P. N. Exon Smith I != E; ++I) {
214875cd8d75SDuncan P. N. Exon Smith Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS.get(), *I,
214975cd8d75SDuncan P. N. Exon Smith Parent);
215075cd8d75SDuncan P. N. Exon Smith }
215175cd8d75SDuncan P. N. Exon Smith assert(Parent && "File without a directory?");
215275cd8d75SDuncan P. N. Exon Smith {
215375cd8d75SDuncan P. N. Exon Smith auto EC = ExternalFS.makeAbsolute(To);
215475cd8d75SDuncan P. N. Exon Smith (void)EC;
215575cd8d75SDuncan P. N. Exon Smith assert(!EC && "Could not make absolute path");
215675cd8d75SDuncan P. N. Exon Smith }
215775cd8d75SDuncan P. N. Exon Smith
215875cd8d75SDuncan P. N. Exon Smith // Add the file.
2159719f7784SNathan Hawes auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>(
216075cd8d75SDuncan P. N. Exon Smith llvm::sys::path::filename(From), To,
2161ecb00a77SNathan Hawes UseExternalNames ? RedirectingFileSystem::NK_External
2162ecb00a77SNathan Hawes : RedirectingFileSystem::NK_Virtual);
216375cd8d75SDuncan P. N. Exon Smith ToEntry = NewFile.get();
2164719f7784SNathan Hawes cast<RedirectingFileSystem::DirectoryEntry>(Parent)->addContent(
216575cd8d75SDuncan P. N. Exon Smith std::move(NewFile));
216675cd8d75SDuncan P. N. Exon Smith }
216775cd8d75SDuncan P. N. Exon Smith
216875cd8d75SDuncan P. N. Exon Smith return FS;
216975cd8d75SDuncan P. N. Exon Smith }
217075cd8d75SDuncan P. N. Exon Smith
LookupResult(Entry * E,sys::path::const_iterator Start,sys::path::const_iterator End)2171ecb00a77SNathan Hawes RedirectingFileSystem::LookupResult::LookupResult(
2172ecb00a77SNathan Hawes Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
2173ecb00a77SNathan Hawes : E(E) {
2174ecb00a77SNathan Hawes assert(E != nullptr);
2175ecb00a77SNathan Hawes // If the matched entry is a DirectoryRemapEntry, set ExternalRedirect to the
2176ecb00a77SNathan Hawes // path of the directory it maps to in the external file system plus any
2177ecb00a77SNathan Hawes // remaining path components in the provided iterator.
2178ecb00a77SNathan Hawes if (auto *DRE = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(E)) {
2179ecb00a77SNathan Hawes SmallString<256> Redirect(DRE->getExternalContentsPath());
2180ecb00a77SNathan Hawes sys::path::append(Redirect, Start, End,
2181ecb00a77SNathan Hawes getExistingStyle(DRE->getExternalContentsPath()));
2182ecb00a77SNathan Hawes ExternalRedirect = std::string(Redirect);
2183ecb00a77SNathan Hawes }
2184ecb00a77SNathan Hawes }
2185ecb00a77SNathan Hawes
21860be9ca7cSJonas Devlieghere std::error_code
makeCanonical(SmallVectorImpl<char> & Path) const21870be9ca7cSJonas Devlieghere RedirectingFileSystem::makeCanonical(SmallVectorImpl<char> &Path) const {
2188fc51490bSJonas Devlieghere if (std::error_code EC = makeAbsolute(Path))
2189fc51490bSJonas Devlieghere return EC;
2190fc51490bSJonas Devlieghere
21910be9ca7cSJonas Devlieghere llvm::SmallString<256> CanonicalPath =
21920be9ca7cSJonas Devlieghere canonicalize(StringRef(Path.data(), Path.size()));
21930be9ca7cSJonas Devlieghere if (CanonicalPath.empty())
2194fc51490bSJonas Devlieghere return make_error_code(llvm::errc::invalid_argument);
2195fc51490bSJonas Devlieghere
21960be9ca7cSJonas Devlieghere Path.assign(CanonicalPath.begin(), CanonicalPath.end());
21970be9ca7cSJonas Devlieghere return {};
21980be9ca7cSJonas Devlieghere }
21990be9ca7cSJonas Devlieghere
2200ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult>
lookupPath(StringRef Path) const22010be9ca7cSJonas Devlieghere RedirectingFileSystem::lookupPath(StringRef Path) const {
2202fc51490bSJonas Devlieghere sys::path::const_iterator Start = sys::path::begin(Path);
2203fc51490bSJonas Devlieghere sys::path::const_iterator End = sys::path::end(Path);
2204fc51490bSJonas Devlieghere for (const auto &Root : Roots) {
2205ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult> Result =
2206ecb00a77SNathan Hawes lookupPathImpl(Start, End, Root.get());
2207fc51490bSJonas Devlieghere if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
2208fc51490bSJonas Devlieghere return Result;
2209fc51490bSJonas Devlieghere }
2210fc51490bSJonas Devlieghere return make_error_code(llvm::errc::no_such_file_or_directory);
2211fc51490bSJonas Devlieghere }
2212fc51490bSJonas Devlieghere
2213ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult>
lookupPathImpl(sys::path::const_iterator Start,sys::path::const_iterator End,RedirectingFileSystem::Entry * From) const2214ecb00a77SNathan Hawes RedirectingFileSystem::lookupPathImpl(
2215ecb00a77SNathan Hawes sys::path::const_iterator Start, sys::path::const_iterator End,
22161a0ce65aSJonas Devlieghere RedirectingFileSystem::Entry *From) const {
2217fc51490bSJonas Devlieghere assert(!isTraversalComponent(*Start) &&
2218fc51490bSJonas Devlieghere !isTraversalComponent(From->getName()) &&
2219fc51490bSJonas Devlieghere "Paths should not contain traversal components");
2220fc51490bSJonas Devlieghere
2221fc51490bSJonas Devlieghere StringRef FromName = From->getName();
2222fc51490bSJonas Devlieghere
2223fc51490bSJonas Devlieghere // Forward the search to the next component in case this is an empty one.
2224fc51490bSJonas Devlieghere if (!FromName.empty()) {
22251275ab16SAdrian McCarthy if (!pathComponentMatches(*Start, FromName))
2226fc51490bSJonas Devlieghere return make_error_code(llvm::errc::no_such_file_or_directory);
2227fc51490bSJonas Devlieghere
2228fc51490bSJonas Devlieghere ++Start;
2229fc51490bSJonas Devlieghere
2230fc51490bSJonas Devlieghere if (Start == End) {
2231fc51490bSJonas Devlieghere // Match!
2232ecb00a77SNathan Hawes return LookupResult(From, Start, End);
2233fc51490bSJonas Devlieghere }
2234fc51490bSJonas Devlieghere }
2235fc51490bSJonas Devlieghere
2236ecb00a77SNathan Hawes if (isa<RedirectingFileSystem::FileEntry>(From))
2237fc51490bSJonas Devlieghere return make_error_code(llvm::errc::not_a_directory);
2238fc51490bSJonas Devlieghere
2239ecb00a77SNathan Hawes if (isa<RedirectingFileSystem::DirectoryRemapEntry>(From))
2240ecb00a77SNathan Hawes return LookupResult(From, Start, End);
2241ecb00a77SNathan Hawes
2242ecb00a77SNathan Hawes auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(From);
22431a0ce65aSJonas Devlieghere for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
2244fc51490bSJonas Devlieghere llvm::make_range(DE->contents_begin(), DE->contents_end())) {
2245ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult> Result =
2246ecb00a77SNathan Hawes lookupPathImpl(Start, End, DirEntry.get());
2247fc51490bSJonas Devlieghere if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
2248fc51490bSJonas Devlieghere return Result;
2249fc51490bSJonas Devlieghere }
22501275ab16SAdrian McCarthy
2251fc51490bSJonas Devlieghere return make_error_code(llvm::errc::no_such_file_or_directory);
2252fc51490bSJonas Devlieghere }
2253fc51490bSJonas Devlieghere
getRedirectedFileStatus(const Twine & OriginalPath,bool UseExternalNames,Status ExternalStatus)225486e2af80SKeith Smiley static Status getRedirectedFileStatus(const Twine &OriginalPath,
225586e2af80SKeith Smiley bool UseExternalNames,
2256fc51490bSJonas Devlieghere Status ExternalStatus) {
2257fe2478d4SBen Barham // The path has been mapped by some nested VFS and exposes an external path,
2258fe2478d4SBen Barham // don't override it with the original path.
2259fe2478d4SBen Barham if (ExternalStatus.ExposesExternalVFSPath)
2260fe2478d4SBen Barham return ExternalStatus;
2261fe2478d4SBen Barham
2262fc51490bSJonas Devlieghere Status S = ExternalStatus;
2263fc51490bSJonas Devlieghere if (!UseExternalNames)
226486e2af80SKeith Smiley S = Status::copyWithNewName(S, OriginalPath);
2265fe2478d4SBen Barham else
2266fe2478d4SBen Barham S.ExposesExternalVFSPath = true;
2267f65b0b5dSBen Barham S.IsVFSMapped = true;
2268fc51490bSJonas Devlieghere return S;
2269fc51490bSJonas Devlieghere }
2270fc51490bSJonas Devlieghere
status(const Twine & CanonicalPath,const Twine & OriginalPath,const RedirectingFileSystem::LookupResult & Result)2271ecb00a77SNathan Hawes ErrorOr<Status> RedirectingFileSystem::status(
227286e2af80SKeith Smiley const Twine &CanonicalPath, const Twine &OriginalPath,
227386e2af80SKeith Smiley const RedirectingFileSystem::LookupResult &Result) {
2274ecb00a77SNathan Hawes if (Optional<StringRef> ExtRedirect = Result.getExternalRedirect()) {
227586e2af80SKeith Smiley SmallString<256> CanonicalRemappedPath((*ExtRedirect).str());
227686e2af80SKeith Smiley if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
227786e2af80SKeith Smiley return EC;
227886e2af80SKeith Smiley
227986e2af80SKeith Smiley ErrorOr<Status> S = ExternalFS->status(CanonicalRemappedPath);
2280ecb00a77SNathan Hawes if (!S)
2281fc51490bSJonas Devlieghere return S;
228286e2af80SKeith Smiley S = Status::copyWithNewName(*S, *ExtRedirect);
2283ecb00a77SNathan Hawes auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result.E);
228486e2af80SKeith Smiley return getRedirectedFileStatus(OriginalPath,
228586e2af80SKeith Smiley RE->useExternalName(UseExternalNames), *S);
2286fc51490bSJonas Devlieghere }
2287ecb00a77SNathan Hawes
2288ecb00a77SNathan Hawes auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Result.E);
228986e2af80SKeith Smiley return Status::copyWithNewName(DE->getStatus(), CanonicalPath);
2290fc51490bSJonas Devlieghere }
2291fc51490bSJonas Devlieghere
229286e2af80SKeith Smiley ErrorOr<Status>
getExternalStatus(const Twine & CanonicalPath,const Twine & OriginalPath) const229386e2af80SKeith Smiley RedirectingFileSystem::getExternalStatus(const Twine &CanonicalPath,
229486e2af80SKeith Smiley const Twine &OriginalPath) const {
2295fe2478d4SBen Barham auto Result = ExternalFS->status(CanonicalPath);
2296fe2478d4SBen Barham
2297fe2478d4SBen Barham // The path has been mapped by some nested VFS, don't override it with the
2298fe2478d4SBen Barham // original path.
2299fe2478d4SBen Barham if (!Result || Result->ExposesExternalVFSPath)
2300fe2478d4SBen Barham return Result;
2301fe2478d4SBen Barham return Status::copyWithNewName(Result.get(), OriginalPath);
230286e2af80SKeith Smiley }
23030be9ca7cSJonas Devlieghere
status(const Twine & OriginalPath)230486e2af80SKeith Smiley ErrorOr<Status> RedirectingFileSystem::status(const Twine &OriginalPath) {
230586e2af80SKeith Smiley SmallString<256> CanonicalPath;
230686e2af80SKeith Smiley OriginalPath.toVector(CanonicalPath);
230786e2af80SKeith Smiley
230886e2af80SKeith Smiley if (std::error_code EC = makeCanonical(CanonicalPath))
23090be9ca7cSJonas Devlieghere return EC;
23100be9ca7cSJonas Devlieghere
2311502f14d6SBen Barham if (Redirection == RedirectKind::Fallback) {
2312502f14d6SBen Barham // Attempt to find the original file first, only falling back to the
2313502f14d6SBen Barham // mapped file if that fails.
2314502f14d6SBen Barham ErrorOr<Status> S = getExternalStatus(CanonicalPath, OriginalPath);
2315502f14d6SBen Barham if (S)
2316502f14d6SBen Barham return S;
2317502f14d6SBen Barham }
2318502f14d6SBen Barham
231986e2af80SKeith Smiley ErrorOr<RedirectingFileSystem::LookupResult> Result =
232086e2af80SKeith Smiley lookupPath(CanonicalPath);
232191e13164SVolodymyr Sapsai if (!Result) {
2322502f14d6SBen Barham // Was not able to map file, fallthrough to using the original path if
2323502f14d6SBen Barham // that was the specified redirection type.
2324502f14d6SBen Barham if (Redirection == RedirectKind::Fallthrough &&
2325502f14d6SBen Barham isFileNotFound(Result.getError()))
232686e2af80SKeith Smiley return getExternalStatus(CanonicalPath, OriginalPath);
2327fc51490bSJonas Devlieghere return Result.getError();
232891e13164SVolodymyr Sapsai }
2329ecb00a77SNathan Hawes
233086e2af80SKeith Smiley ErrorOr<Status> S = status(CanonicalPath, OriginalPath, *Result);
2331502f14d6SBen Barham if (!S && Redirection == RedirectKind::Fallthrough &&
2332502f14d6SBen Barham isFileNotFound(S.getError(), Result->E)) {
2333502f14d6SBen Barham // Mapped the file but it wasn't found in the underlying filesystem,
2334502f14d6SBen Barham // fallthrough to using the original path if that was the specified
2335502f14d6SBen Barham // redirection type.
233686e2af80SKeith Smiley return getExternalStatus(CanonicalPath, OriginalPath);
233786e2af80SKeith Smiley }
233886e2af80SKeith Smiley
2339ecb00a77SNathan Hawes return S;
2340fc51490bSJonas Devlieghere }
2341fc51490bSJonas Devlieghere
2342fc51490bSJonas Devlieghere namespace {
2343fc51490bSJonas Devlieghere
2344fc51490bSJonas Devlieghere /// Provide a file wrapper with an overriden status.
2345fc51490bSJonas Devlieghere class FileWithFixedStatus : public File {
2346fc51490bSJonas Devlieghere std::unique_ptr<File> InnerFile;
2347fc51490bSJonas Devlieghere Status S;
2348fc51490bSJonas Devlieghere
2349fc51490bSJonas Devlieghere public:
FileWithFixedStatus(std::unique_ptr<File> InnerFile,Status S)2350fc51490bSJonas Devlieghere FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
2351fc51490bSJonas Devlieghere : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
2352fc51490bSJonas Devlieghere
status()2353fc51490bSJonas Devlieghere ErrorOr<Status> status() override { return S; }
2354fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2355fc51490bSJonas Devlieghere
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)2356fc51490bSJonas Devlieghere getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
2357fc51490bSJonas Devlieghere bool IsVolatile) override {
2358fc51490bSJonas Devlieghere return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
2359fc51490bSJonas Devlieghere IsVolatile);
2360fc51490bSJonas Devlieghere }
2361fc51490bSJonas Devlieghere
close()2362fc51490bSJonas Devlieghere std::error_code close() override { return InnerFile->close(); }
236386e2af80SKeith Smiley
setPath(const Twine & Path)236486e2af80SKeith Smiley void setPath(const Twine &Path) override { S = S.copyWithNewName(S, Path); }
2365fc51490bSJonas Devlieghere };
2366fc51490bSJonas Devlieghere
2367fc51490bSJonas Devlieghere } // namespace
2368fc51490bSJonas Devlieghere
2369fc51490bSJonas Devlieghere ErrorOr<std::unique_ptr<File>>
getWithPath(ErrorOr<std::unique_ptr<File>> Result,const Twine & P)237086e2af80SKeith Smiley File::getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P) {
2371fe2478d4SBen Barham // See \c getRedirectedFileStatus - don't update path if it's exposing an
2372fe2478d4SBen Barham // external path.
2373fe2478d4SBen Barham if (!Result || (*Result)->status()->ExposesExternalVFSPath)
237486e2af80SKeith Smiley return Result;
23750be9ca7cSJonas Devlieghere
237686e2af80SKeith Smiley ErrorOr<std::unique_ptr<File>> F = std::move(*Result);
237786e2af80SKeith Smiley auto Name = F->get()->getName();
237886e2af80SKeith Smiley if (Name && Name.get() != P.str())
237986e2af80SKeith Smiley F->get()->setPath(P);
238086e2af80SKeith Smiley return F;
238186e2af80SKeith Smiley }
238286e2af80SKeith Smiley
238386e2af80SKeith Smiley ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & OriginalPath)238486e2af80SKeith Smiley RedirectingFileSystem::openFileForRead(const Twine &OriginalPath) {
238586e2af80SKeith Smiley SmallString<256> CanonicalPath;
238686e2af80SKeith Smiley OriginalPath.toVector(CanonicalPath);
238786e2af80SKeith Smiley
238886e2af80SKeith Smiley if (std::error_code EC = makeCanonical(CanonicalPath))
23890be9ca7cSJonas Devlieghere return EC;
23900be9ca7cSJonas Devlieghere
2391502f14d6SBen Barham if (Redirection == RedirectKind::Fallback) {
2392502f14d6SBen Barham // Attempt to find the original file first, only falling back to the
2393502f14d6SBen Barham // mapped file if that fails.
2394502f14d6SBen Barham auto F = File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
2395502f14d6SBen Barham OriginalPath);
2396502f14d6SBen Barham if (F)
2397502f14d6SBen Barham return F;
2398502f14d6SBen Barham }
2399502f14d6SBen Barham
240086e2af80SKeith Smiley ErrorOr<RedirectingFileSystem::LookupResult> Result =
240186e2af80SKeith Smiley lookupPath(CanonicalPath);
2402ecb00a77SNathan Hawes if (!Result) {
2403502f14d6SBen Barham // Was not able to map file, fallthrough to using the original path if
2404502f14d6SBen Barham // that was the specified redirection type.
2405502f14d6SBen Barham if (Redirection == RedirectKind::Fallthrough &&
2406502f14d6SBen Barham isFileNotFound(Result.getError()))
240786e2af80SKeith Smiley return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
240886e2af80SKeith Smiley OriginalPath);
2409ecb00a77SNathan Hawes return Result.getError();
241091e13164SVolodymyr Sapsai }
2411fc51490bSJonas Devlieghere
2412ecb00a77SNathan Hawes if (!Result->getExternalRedirect()) // FIXME: errc::not_a_file?
2413fc51490bSJonas Devlieghere return make_error_code(llvm::errc::invalid_argument);
2414fc51490bSJonas Devlieghere
2415ecb00a77SNathan Hawes StringRef ExtRedirect = *Result->getExternalRedirect();
241686e2af80SKeith Smiley SmallString<256> CanonicalRemappedPath(ExtRedirect.str());
241786e2af80SKeith Smiley if (std::error_code EC = makeCanonical(CanonicalRemappedPath))
241886e2af80SKeith Smiley return EC;
241986e2af80SKeith Smiley
2420ecb00a77SNathan Hawes auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
2421fc51490bSJonas Devlieghere
242286e2af80SKeith Smiley auto ExternalFile = File::getWithPath(
242386e2af80SKeith Smiley ExternalFS->openFileForRead(CanonicalRemappedPath), ExtRedirect);
2424ecb00a77SNathan Hawes if (!ExternalFile) {
2425502f14d6SBen Barham if (Redirection == RedirectKind::Fallthrough &&
2426502f14d6SBen Barham isFileNotFound(ExternalFile.getError(), Result->E)) {
2427502f14d6SBen Barham // Mapped the file but it wasn't found in the underlying filesystem,
2428502f14d6SBen Barham // fallthrough to using the original path if that was the specified
2429502f14d6SBen Barham // redirection type.
243086e2af80SKeith Smiley return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath),
243186e2af80SKeith Smiley OriginalPath);
2432502f14d6SBen Barham }
2433ecb00a77SNathan Hawes return ExternalFile;
2434ecb00a77SNathan Hawes }
2435ecb00a77SNathan Hawes
2436ecb00a77SNathan Hawes auto ExternalStatus = (*ExternalFile)->status();
2437fc51490bSJonas Devlieghere if (!ExternalStatus)
2438fc51490bSJonas Devlieghere return ExternalStatus.getError();
2439fc51490bSJonas Devlieghere
2440502f14d6SBen Barham // Otherwise, the file was successfully remapped. Mark it as such. Also
2441502f14d6SBen Barham // replace the underlying path if the external name is being used.
2442ecb00a77SNathan Hawes Status S = getRedirectedFileStatus(
244386e2af80SKeith Smiley OriginalPath, RE->useExternalName(UseExternalNames), *ExternalStatus);
2444fc51490bSJonas Devlieghere return std::unique_ptr<File>(
2445ecb00a77SNathan Hawes std::make_unique<FileWithFixedStatus>(std::move(*ExternalFile), S));
2446fc51490bSJonas Devlieghere }
2447fc51490bSJonas Devlieghere
24487610033fSVolodymyr Sapsai std::error_code
getRealPath(const Twine & OriginalPath,SmallVectorImpl<char> & Output) const2449502f14d6SBen Barham RedirectingFileSystem::getRealPath(const Twine &OriginalPath,
24507610033fSVolodymyr Sapsai SmallVectorImpl<char> &Output) const {
2451502f14d6SBen Barham SmallString<256> CanonicalPath;
2452502f14d6SBen Barham OriginalPath.toVector(CanonicalPath);
24530be9ca7cSJonas Devlieghere
2454502f14d6SBen Barham if (std::error_code EC = makeCanonical(CanonicalPath))
24550be9ca7cSJonas Devlieghere return EC;
24560be9ca7cSJonas Devlieghere
2457502f14d6SBen Barham if (Redirection == RedirectKind::Fallback) {
2458502f14d6SBen Barham // Attempt to find the original file first, only falling back to the
2459502f14d6SBen Barham // mapped file if that fails.
2460502f14d6SBen Barham std::error_code EC = ExternalFS->getRealPath(CanonicalPath, Output);
2461502f14d6SBen Barham if (!EC)
2462502f14d6SBen Barham return EC;
2463502f14d6SBen Barham }
2464502f14d6SBen Barham
2465502f14d6SBen Barham ErrorOr<RedirectingFileSystem::LookupResult> Result =
2466502f14d6SBen Barham lookupPath(CanonicalPath);
24677610033fSVolodymyr Sapsai if (!Result) {
2468502f14d6SBen Barham // Was not able to map file, fallthrough to using the original path if
2469502f14d6SBen Barham // that was the specified redirection type.
2470502f14d6SBen Barham if (Redirection == RedirectKind::Fallthrough &&
2471502f14d6SBen Barham isFileNotFound(Result.getError()))
2472502f14d6SBen Barham return ExternalFS->getRealPath(CanonicalPath, Output);
24737610033fSVolodymyr Sapsai return Result.getError();
24747610033fSVolodymyr Sapsai }
24757610033fSVolodymyr Sapsai
2476ecb00a77SNathan Hawes // If we found FileEntry or DirectoryRemapEntry, look up the mapped
2477ecb00a77SNathan Hawes // path in the external file system.
2478ecb00a77SNathan Hawes if (auto ExtRedirect = Result->getExternalRedirect()) {
2479ecb00a77SNathan Hawes auto P = ExternalFS->getRealPath(*ExtRedirect, Output);
2480502f14d6SBen Barham if (P && Redirection == RedirectKind::Fallthrough &&
2481502f14d6SBen Barham isFileNotFound(P, Result->E)) {
2482502f14d6SBen Barham // Mapped the file but it wasn't found in the underlying filesystem,
2483502f14d6SBen Barham // fallthrough to using the original path if that was the specified
2484502f14d6SBen Barham // redirection type.
2485502f14d6SBen Barham return ExternalFS->getRealPath(CanonicalPath, Output);
24867610033fSVolodymyr Sapsai }
2487ecb00a77SNathan Hawes return P;
2488ecb00a77SNathan Hawes }
2489ecb00a77SNathan Hawes
2490502f14d6SBen Barham // If we found a DirectoryEntry, still fallthrough to the original path if
2491502f14d6SBen Barham // allowed, because directories don't have a single external contents path.
2492502f14d6SBen Barham if (Redirection == RedirectKind::Fallthrough)
2493502f14d6SBen Barham return ExternalFS->getRealPath(CanonicalPath, Output);
2494502f14d6SBen Barham return llvm::errc::invalid_argument;
24957610033fSVolodymyr Sapsai }
24967610033fSVolodymyr Sapsai
2497a22eda54SDuncan P. N. Exon Smith std::unique_ptr<FileSystem>
getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)2498fc51490bSJonas Devlieghere vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2499fc51490bSJonas Devlieghere SourceMgr::DiagHandlerTy DiagHandler,
2500fc51490bSJonas Devlieghere StringRef YAMLFilePath, void *DiagContext,
2501fc51490bSJonas Devlieghere IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2502fc51490bSJonas Devlieghere return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
2503fc51490bSJonas Devlieghere YAMLFilePath, DiagContext,
2504fc51490bSJonas Devlieghere std::move(ExternalFS));
2505fc51490bSJonas Devlieghere }
2506fc51490bSJonas Devlieghere
getVFSEntries(RedirectingFileSystem::Entry * SrcE,SmallVectorImpl<StringRef> & Path,SmallVectorImpl<YAMLVFSEntry> & Entries)25071a0ce65aSJonas Devlieghere static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
25081a0ce65aSJonas Devlieghere SmallVectorImpl<StringRef> &Path,
2509fc51490bSJonas Devlieghere SmallVectorImpl<YAMLVFSEntry> &Entries) {
2510fc51490bSJonas Devlieghere auto Kind = SrcE->getKind();
25111a0ce65aSJonas Devlieghere if (Kind == RedirectingFileSystem::EK_Directory) {
2512719f7784SNathan Hawes auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
2513fc51490bSJonas Devlieghere assert(DE && "Must be a directory");
25141a0ce65aSJonas Devlieghere for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
2515fc51490bSJonas Devlieghere llvm::make_range(DE->contents_begin(), DE->contents_end())) {
2516fc51490bSJonas Devlieghere Path.push_back(SubEntry->getName());
2517fc51490bSJonas Devlieghere getVFSEntries(SubEntry.get(), Path, Entries);
2518fc51490bSJonas Devlieghere Path.pop_back();
2519fc51490bSJonas Devlieghere }
2520fc51490bSJonas Devlieghere return;
2521fc51490bSJonas Devlieghere }
2522fc51490bSJonas Devlieghere
2523ecb00a77SNathan Hawes if (Kind == RedirectingFileSystem::EK_DirectoryRemap) {
2524ecb00a77SNathan Hawes auto *DR = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
2525ecb00a77SNathan Hawes assert(DR && "Must be a directory remap");
2526ecb00a77SNathan Hawes SmallString<128> VPath;
2527ecb00a77SNathan Hawes for (auto &Comp : Path)
2528ecb00a77SNathan Hawes llvm::sys::path::append(VPath, Comp);
2529ecb00a77SNathan Hawes Entries.push_back(
2530ecb00a77SNathan Hawes YAMLVFSEntry(VPath.c_str(), DR->getExternalContentsPath()));
2531ecb00a77SNathan Hawes return;
2532ecb00a77SNathan Hawes }
2533ecb00a77SNathan Hawes
25341a0ce65aSJonas Devlieghere assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
2535719f7784SNathan Hawes auto *FE = dyn_cast<RedirectingFileSystem::FileEntry>(SrcE);
2536fc51490bSJonas Devlieghere assert(FE && "Must be a file");
2537fc51490bSJonas Devlieghere SmallString<128> VPath;
2538fc51490bSJonas Devlieghere for (auto &Comp : Path)
2539fc51490bSJonas Devlieghere llvm::sys::path::append(VPath, Comp);
2540fc51490bSJonas Devlieghere Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
2541fc51490bSJonas Devlieghere }
2542fc51490bSJonas Devlieghere
collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,SmallVectorImpl<YAMLVFSEntry> & CollectedEntries,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)2543fc51490bSJonas Devlieghere void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2544fc51490bSJonas Devlieghere SourceMgr::DiagHandlerTy DiagHandler,
2545fc51490bSJonas Devlieghere StringRef YAMLFilePath,
2546fc51490bSJonas Devlieghere SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
2547fc51490bSJonas Devlieghere void *DiagContext,
2548fc51490bSJonas Devlieghere IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2549a22eda54SDuncan P. N. Exon Smith std::unique_ptr<RedirectingFileSystem> VFS = RedirectingFileSystem::create(
2550fc51490bSJonas Devlieghere std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
2551fc51490bSJonas Devlieghere std::move(ExternalFS));
25522509f9fbSAlex Lorenz if (!VFS)
25532509f9fbSAlex Lorenz return;
2554ecb00a77SNathan Hawes ErrorOr<RedirectingFileSystem::LookupResult> RootResult =
2555ecb00a77SNathan Hawes VFS->lookupPath("/");
2556ecb00a77SNathan Hawes if (!RootResult)
2557fc51490bSJonas Devlieghere return;
2558fc51490bSJonas Devlieghere SmallVector<StringRef, 8> Components;
2559fc51490bSJonas Devlieghere Components.push_back("/");
2560ecb00a77SNathan Hawes getVFSEntries(RootResult->E, Components, CollectedEntries);
2561fc51490bSJonas Devlieghere }
2562fc51490bSJonas Devlieghere
getNextVirtualUniqueID()2563fc51490bSJonas Devlieghere UniqueID vfs::getNextVirtualUniqueID() {
2564fc51490bSJonas Devlieghere static std::atomic<unsigned> UID;
2565fc51490bSJonas Devlieghere unsigned ID = ++UID;
2566fc51490bSJonas Devlieghere // The following assumes that uint64_t max will never collide with a real
2567fc51490bSJonas Devlieghere // dev_t value from the OS.
2568fc51490bSJonas Devlieghere return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
2569fc51490bSJonas Devlieghere }
2570fc51490bSJonas Devlieghere
addEntry(StringRef VirtualPath,StringRef RealPath,bool IsDirectory)25713ef33e69SJonas Devlieghere void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath,
25723ef33e69SJonas Devlieghere bool IsDirectory) {
2573fc51490bSJonas Devlieghere assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
2574fc51490bSJonas Devlieghere assert(sys::path::is_absolute(RealPath) && "real path not absolute");
2575fc51490bSJonas Devlieghere assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
25763ef33e69SJonas Devlieghere Mappings.emplace_back(VirtualPath, RealPath, IsDirectory);
25773ef33e69SJonas Devlieghere }
25783ef33e69SJonas Devlieghere
addFileMapping(StringRef VirtualPath,StringRef RealPath)25793ef33e69SJonas Devlieghere void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
25803ef33e69SJonas Devlieghere addEntry(VirtualPath, RealPath, /*IsDirectory=*/false);
25813ef33e69SJonas Devlieghere }
25823ef33e69SJonas Devlieghere
addDirectoryMapping(StringRef VirtualPath,StringRef RealPath)25833ef33e69SJonas Devlieghere void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath,
25843ef33e69SJonas Devlieghere StringRef RealPath) {
25853ef33e69SJonas Devlieghere addEntry(VirtualPath, RealPath, /*IsDirectory=*/true);
2586fc51490bSJonas Devlieghere }
2587fc51490bSJonas Devlieghere
2588fc51490bSJonas Devlieghere namespace {
2589fc51490bSJonas Devlieghere
2590fc51490bSJonas Devlieghere class JSONWriter {
2591fc51490bSJonas Devlieghere llvm::raw_ostream &OS;
2592fc51490bSJonas Devlieghere SmallVector<StringRef, 16> DirStack;
2593fc51490bSJonas Devlieghere
getDirIndent()2594fc51490bSJonas Devlieghere unsigned getDirIndent() { return 4 * DirStack.size(); }
getFileIndent()2595fc51490bSJonas Devlieghere unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
2596fc51490bSJonas Devlieghere bool containedIn(StringRef Parent, StringRef Path);
2597fc51490bSJonas Devlieghere StringRef containedPart(StringRef Parent, StringRef Path);
2598fc51490bSJonas Devlieghere void startDirectory(StringRef Path);
2599fc51490bSJonas Devlieghere void endDirectory();
2600fc51490bSJonas Devlieghere void writeEntry(StringRef VPath, StringRef RPath);
2601fc51490bSJonas Devlieghere
2602fc51490bSJonas Devlieghere public:
JSONWriter(llvm::raw_ostream & OS)2603fc51490bSJonas Devlieghere JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
2604fc51490bSJonas Devlieghere
2605fc51490bSJonas Devlieghere void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
2606fc51490bSJonas Devlieghere Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
26077faf7ae0SVolodymyr Sapsai StringRef OverlayDir);
2608fc51490bSJonas Devlieghere };
2609fc51490bSJonas Devlieghere
2610fc51490bSJonas Devlieghere } // namespace
2611fc51490bSJonas Devlieghere
containedIn(StringRef Parent,StringRef Path)2612fc51490bSJonas Devlieghere bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2613fc51490bSJonas Devlieghere using namespace llvm::sys;
2614fc51490bSJonas Devlieghere
2615fc51490bSJonas Devlieghere // Compare each path component.
2616fc51490bSJonas Devlieghere auto IParent = path::begin(Parent), EParent = path::end(Parent);
2617fc51490bSJonas Devlieghere for (auto IChild = path::begin(Path), EChild = path::end(Path);
2618fc51490bSJonas Devlieghere IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2619fc51490bSJonas Devlieghere if (*IParent != *IChild)
2620fc51490bSJonas Devlieghere return false;
2621fc51490bSJonas Devlieghere }
2622fc51490bSJonas Devlieghere // Have we exhausted the parent path?
2623fc51490bSJonas Devlieghere return IParent == EParent;
2624fc51490bSJonas Devlieghere }
2625fc51490bSJonas Devlieghere
containedPart(StringRef Parent,StringRef Path)2626fc51490bSJonas Devlieghere StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2627fc51490bSJonas Devlieghere assert(!Parent.empty());
2628fc51490bSJonas Devlieghere assert(containedIn(Parent, Path));
2629fc51490bSJonas Devlieghere return Path.slice(Parent.size() + 1, StringRef::npos);
2630fc51490bSJonas Devlieghere }
2631fc51490bSJonas Devlieghere
startDirectory(StringRef Path)2632fc51490bSJonas Devlieghere void JSONWriter::startDirectory(StringRef Path) {
2633fc51490bSJonas Devlieghere StringRef Name =
2634fc51490bSJonas Devlieghere DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
2635fc51490bSJonas Devlieghere DirStack.push_back(Path);
2636fc51490bSJonas Devlieghere unsigned Indent = getDirIndent();
2637fc51490bSJonas Devlieghere OS.indent(Indent) << "{\n";
2638fc51490bSJonas Devlieghere OS.indent(Indent + 2) << "'type': 'directory',\n";
2639fc51490bSJonas Devlieghere OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
2640fc51490bSJonas Devlieghere OS.indent(Indent + 2) << "'contents': [\n";
2641fc51490bSJonas Devlieghere }
2642fc51490bSJonas Devlieghere
endDirectory()2643fc51490bSJonas Devlieghere void JSONWriter::endDirectory() {
2644fc51490bSJonas Devlieghere unsigned Indent = getDirIndent();
2645fc51490bSJonas Devlieghere OS.indent(Indent + 2) << "]\n";
2646fc51490bSJonas Devlieghere OS.indent(Indent) << "}";
2647fc51490bSJonas Devlieghere
2648fc51490bSJonas Devlieghere DirStack.pop_back();
2649fc51490bSJonas Devlieghere }
2650fc51490bSJonas Devlieghere
writeEntry(StringRef VPath,StringRef RPath)2651fc51490bSJonas Devlieghere void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2652fc51490bSJonas Devlieghere unsigned Indent = getFileIndent();
2653fc51490bSJonas Devlieghere OS.indent(Indent) << "{\n";
2654fc51490bSJonas Devlieghere OS.indent(Indent + 2) << "'type': 'file',\n";
2655fc51490bSJonas Devlieghere OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
2656fc51490bSJonas Devlieghere OS.indent(Indent + 2) << "'external-contents': \""
2657fc51490bSJonas Devlieghere << llvm::yaml::escape(RPath) << "\"\n";
2658fc51490bSJonas Devlieghere OS.indent(Indent) << "}";
2659fc51490bSJonas Devlieghere }
2660fc51490bSJonas Devlieghere
write(ArrayRef<YAMLVFSEntry> Entries,Optional<bool> UseExternalNames,Optional<bool> IsCaseSensitive,Optional<bool> IsOverlayRelative,StringRef OverlayDir)2661fc51490bSJonas Devlieghere void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
2662fc51490bSJonas Devlieghere Optional<bool> UseExternalNames,
2663fc51490bSJonas Devlieghere Optional<bool> IsCaseSensitive,
2664fc51490bSJonas Devlieghere Optional<bool> IsOverlayRelative,
2665fc51490bSJonas Devlieghere StringRef OverlayDir) {
2666fc51490bSJonas Devlieghere using namespace llvm::sys;
2667fc51490bSJonas Devlieghere
2668fc51490bSJonas Devlieghere OS << "{\n"
2669fc51490bSJonas Devlieghere " 'version': 0,\n";
2670a7938c74SKazu Hirata if (IsCaseSensitive)
26713b7c3a65SKazu Hirata OS << " 'case-sensitive': '"
2672*611ffcf4SKazu Hirata << (IsCaseSensitive.value() ? "true" : "false") << "',\n";
2673a7938c74SKazu Hirata if (UseExternalNames)
26743b7c3a65SKazu Hirata OS << " 'use-external-names': '"
2675*611ffcf4SKazu Hirata << (UseExternalNames.value() ? "true" : "false") << "',\n";
2676fc51490bSJonas Devlieghere bool UseOverlayRelative = false;
2677a7938c74SKazu Hirata if (IsOverlayRelative) {
2678*611ffcf4SKazu Hirata UseOverlayRelative = IsOverlayRelative.value();
2679fc51490bSJonas Devlieghere OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2680fc51490bSJonas Devlieghere << "',\n";
2681fc51490bSJonas Devlieghere }
2682fc51490bSJonas Devlieghere OS << " 'roots': [\n";
2683fc51490bSJonas Devlieghere
2684fc51490bSJonas Devlieghere if (!Entries.empty()) {
2685fc51490bSJonas Devlieghere const YAMLVFSEntry &Entry = Entries.front();
2686759465eeSJan Korous
2687759465eeSJan Korous startDirectory(
2688759465eeSJan Korous Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath)
2689759465eeSJan Korous );
2690fc51490bSJonas Devlieghere
2691fc51490bSJonas Devlieghere StringRef RPath = Entry.RPath;
2692fc51490bSJonas Devlieghere if (UseOverlayRelative) {
2693fc51490bSJonas Devlieghere unsigned OverlayDirLen = OverlayDir.size();
2694fc51490bSJonas Devlieghere assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2695fc51490bSJonas Devlieghere "Overlay dir must be contained in RPath");
2696fc51490bSJonas Devlieghere RPath = RPath.slice(OverlayDirLen, RPath.size());
2697fc51490bSJonas Devlieghere }
2698fc51490bSJonas Devlieghere
2699759465eeSJan Korous bool IsCurrentDirEmpty = true;
2700759465eeSJan Korous if (!Entry.IsDirectory) {
2701fc51490bSJonas Devlieghere writeEntry(path::filename(Entry.VPath), RPath);
2702759465eeSJan Korous IsCurrentDirEmpty = false;
2703759465eeSJan Korous }
2704fc51490bSJonas Devlieghere
2705fc51490bSJonas Devlieghere for (const auto &Entry : Entries.slice(1)) {
27063ef33e69SJonas Devlieghere StringRef Dir =
27073ef33e69SJonas Devlieghere Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath);
27083ef33e69SJonas Devlieghere if (Dir == DirStack.back()) {
2709759465eeSJan Korous if (!IsCurrentDirEmpty) {
2710fc51490bSJonas Devlieghere OS << ",\n";
27113ef33e69SJonas Devlieghere }
27123ef33e69SJonas Devlieghere } else {
2713759465eeSJan Korous bool IsDirPoppedFromStack = false;
2714fc51490bSJonas Devlieghere while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2715fc51490bSJonas Devlieghere OS << "\n";
2716fc51490bSJonas Devlieghere endDirectory();
2717759465eeSJan Korous IsDirPoppedFromStack = true;
2718fc51490bSJonas Devlieghere }
2719759465eeSJan Korous if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
2720fc51490bSJonas Devlieghere OS << ",\n";
2721759465eeSJan Korous }
2722fc51490bSJonas Devlieghere startDirectory(Dir);
2723759465eeSJan Korous IsCurrentDirEmpty = true;
2724fc51490bSJonas Devlieghere }
2725fc51490bSJonas Devlieghere StringRef RPath = Entry.RPath;
2726fc51490bSJonas Devlieghere if (UseOverlayRelative) {
2727fc51490bSJonas Devlieghere unsigned OverlayDirLen = OverlayDir.size();
2728fc51490bSJonas Devlieghere assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2729fc51490bSJonas Devlieghere "Overlay dir must be contained in RPath");
2730fc51490bSJonas Devlieghere RPath = RPath.slice(OverlayDirLen, RPath.size());
2731fc51490bSJonas Devlieghere }
2732759465eeSJan Korous if (!Entry.IsDirectory) {
2733fc51490bSJonas Devlieghere writeEntry(path::filename(Entry.VPath), RPath);
2734759465eeSJan Korous IsCurrentDirEmpty = false;
2735759465eeSJan Korous }
2736fc51490bSJonas Devlieghere }
2737fc51490bSJonas Devlieghere
2738fc51490bSJonas Devlieghere while (!DirStack.empty()) {
2739fc51490bSJonas Devlieghere OS << "\n";
2740fc51490bSJonas Devlieghere endDirectory();
2741fc51490bSJonas Devlieghere }
2742fc51490bSJonas Devlieghere OS << "\n";
2743fc51490bSJonas Devlieghere }
2744fc51490bSJonas Devlieghere
2745fc51490bSJonas Devlieghere OS << " ]\n"
2746fc51490bSJonas Devlieghere << "}\n";
2747fc51490bSJonas Devlieghere }
2748fc51490bSJonas Devlieghere
write(llvm::raw_ostream & OS)2749fc51490bSJonas Devlieghere void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2750fc51490bSJonas Devlieghere llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2751fc51490bSJonas Devlieghere return LHS.VPath < RHS.VPath;
2752fc51490bSJonas Devlieghere });
2753fc51490bSJonas Devlieghere
2754fc51490bSJonas Devlieghere JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
27557faf7ae0SVolodymyr Sapsai IsOverlayRelative, OverlayDir);
2756fc51490bSJonas Devlieghere }
2757fc51490bSJonas Devlieghere
recursive_directory_iterator(FileSystem & FS_,const Twine & Path,std::error_code & EC)2758fc51490bSJonas Devlieghere vfs::recursive_directory_iterator::recursive_directory_iterator(
2759fc51490bSJonas Devlieghere FileSystem &FS_, const Twine &Path, std::error_code &EC)
2760fc51490bSJonas Devlieghere : FS(&FS_) {
2761fc51490bSJonas Devlieghere directory_iterator I = FS->dir_begin(Path, EC);
2762fc51490bSJonas Devlieghere if (I != directory_iterator()) {
276341fb951fSJonas Devlieghere State = std::make_shared<detail::RecDirIterState>();
276441fb951fSJonas Devlieghere State->Stack.push(I);
2765fc51490bSJonas Devlieghere }
2766fc51490bSJonas Devlieghere }
2767fc51490bSJonas Devlieghere
2768fc51490bSJonas Devlieghere vfs::recursive_directory_iterator &
increment(std::error_code & EC)2769fc51490bSJonas Devlieghere recursive_directory_iterator::increment(std::error_code &EC) {
277041fb951fSJonas Devlieghere assert(FS && State && !State->Stack.empty() && "incrementing past end");
277141fb951fSJonas Devlieghere assert(!State->Stack.top()->path().empty() && "non-canonical end iterator");
2772fc51490bSJonas Devlieghere vfs::directory_iterator End;
277341fb951fSJonas Devlieghere
277441fb951fSJonas Devlieghere if (State->HasNoPushRequest)
277541fb951fSJonas Devlieghere State->HasNoPushRequest = false;
277641fb951fSJonas Devlieghere else {
277741fb951fSJonas Devlieghere if (State->Stack.top()->type() == sys::fs::file_type::directory_file) {
277841fb951fSJonas Devlieghere vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC);
2779fc51490bSJonas Devlieghere if (I != End) {
278041fb951fSJonas Devlieghere State->Stack.push(I);
2781fc51490bSJonas Devlieghere return *this;
2782fc51490bSJonas Devlieghere }
2783fc51490bSJonas Devlieghere }
278441fb951fSJonas Devlieghere }
2785fc51490bSJonas Devlieghere
278641fb951fSJonas Devlieghere while (!State->Stack.empty() && State->Stack.top().increment(EC) == End)
278741fb951fSJonas Devlieghere State->Stack.pop();
2788fc51490bSJonas Devlieghere
278941fb951fSJonas Devlieghere if (State->Stack.empty())
2790fc51490bSJonas Devlieghere State.reset(); // end iterator
2791fc51490bSJonas Devlieghere
2792fc51490bSJonas Devlieghere return *this;
2793fc51490bSJonas Devlieghere }
2794