1d8e91e46SDimitry Andric //===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
2d8e91e46SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d8e91e46SDimitry Andric //
7d8e91e46SDimitry Andric //===----------------------------------------------------------------------===//
8d8e91e46SDimitry Andric //
9d8e91e46SDimitry Andric // This file implements the VirtualFileSystem interface.
10d8e91e46SDimitry Andric //
11d8e91e46SDimitry Andric //===----------------------------------------------------------------------===//
12d8e91e46SDimitry Andric
13d8e91e46SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
14d8e91e46SDimitry Andric #include "llvm/ADT/ArrayRef.h"
15d8e91e46SDimitry Andric #include "llvm/ADT/DenseMap.h"
16d8e91e46SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h"
17d8e91e46SDimitry Andric #include "llvm/ADT/STLExtras.h"
18d8e91e46SDimitry Andric #include "llvm/ADT/SmallString.h"
19d8e91e46SDimitry Andric #include "llvm/ADT/SmallVector.h"
20d8e91e46SDimitry Andric #include "llvm/ADT/StringRef.h"
21d8e91e46SDimitry Andric #include "llvm/ADT/StringSet.h"
22d8e91e46SDimitry Andric #include "llvm/ADT/Twine.h"
23d8e91e46SDimitry Andric #include "llvm/ADT/iterator_range.h"
24d8e91e46SDimitry Andric #include "llvm/Config/llvm-config.h"
25d8e91e46SDimitry Andric #include "llvm/Support/Casting.h"
26d8e91e46SDimitry Andric #include "llvm/Support/Chrono.h"
27d8e91e46SDimitry Andric #include "llvm/Support/Compiler.h"
28d8e91e46SDimitry Andric #include "llvm/Support/Debug.h"
29d8e91e46SDimitry Andric #include "llvm/Support/Errc.h"
30d8e91e46SDimitry Andric #include "llvm/Support/ErrorHandling.h"
31d8e91e46SDimitry Andric #include "llvm/Support/ErrorOr.h"
32d8e91e46SDimitry Andric #include "llvm/Support/FileSystem.h"
33c0981da4SDimitry Andric #include "llvm/Support/FileSystem/UniqueID.h"
34d8e91e46SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
35d8e91e46SDimitry Andric #include "llvm/Support/Path.h"
36d8e91e46SDimitry Andric #include "llvm/Support/SMLoc.h"
37d8e91e46SDimitry Andric #include "llvm/Support/SourceMgr.h"
38d8e91e46SDimitry Andric #include "llvm/Support/YAMLParser.h"
39d8e91e46SDimitry Andric #include "llvm/Support/raw_ostream.h"
40d8e91e46SDimitry Andric #include <algorithm>
41d8e91e46SDimitry Andric #include <atomic>
42d8e91e46SDimitry Andric #include <cassert>
43d8e91e46SDimitry Andric #include <cstdint>
44d8e91e46SDimitry Andric #include <iterator>
45d8e91e46SDimitry Andric #include <limits>
467fa27ce4SDimitry Andric #include <map>
47d8e91e46SDimitry Andric #include <memory>
48e3b55780SDimitry Andric #include <optional>
49d8e91e46SDimitry Andric #include <string>
50d8e91e46SDimitry Andric #include <system_error>
51d8e91e46SDimitry Andric #include <utility>
52d8e91e46SDimitry Andric #include <vector>
53d8e91e46SDimitry Andric
54d8e91e46SDimitry Andric using namespace llvm;
55d8e91e46SDimitry Andric using namespace llvm::vfs;
56d8e91e46SDimitry Andric
57e6d15924SDimitry Andric using llvm::sys::fs::file_t;
58d8e91e46SDimitry Andric using llvm::sys::fs::file_status;
59d8e91e46SDimitry Andric using llvm::sys::fs::file_type;
60e6d15924SDimitry Andric using llvm::sys::fs::kInvalidFile;
61d8e91e46SDimitry Andric using llvm::sys::fs::perms;
62d8e91e46SDimitry Andric using llvm::sys::fs::UniqueID;
63d8e91e46SDimitry Andric
Status(const file_status & Status)64d8e91e46SDimitry Andric Status::Status(const file_status &Status)
65d8e91e46SDimitry Andric : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
66d8e91e46SDimitry Andric User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
67d8e91e46SDimitry Andric Type(Status.type()), Perms(Status.permissions()) {}
68d8e91e46SDimitry Andric
Status(const Twine & Name,UniqueID UID,sys::TimePoint<> MTime,uint32_t User,uint32_t Group,uint64_t Size,file_type Type,perms Perms)69e6d15924SDimitry Andric Status::Status(const Twine &Name, UniqueID UID, sys::TimePoint<> MTime,
70d8e91e46SDimitry Andric uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
71d8e91e46SDimitry Andric perms Perms)
72e6d15924SDimitry Andric : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
73e6d15924SDimitry Andric Size(Size), Type(Type), Perms(Perms) {}
74d8e91e46SDimitry Andric
copyWithNewSize(const Status & In,uint64_t NewSize)7577fc4c14SDimitry Andric Status Status::copyWithNewSize(const Status &In, uint64_t NewSize) {
7677fc4c14SDimitry Andric return Status(In.getName(), In.getUniqueID(), In.getLastModificationTime(),
7777fc4c14SDimitry Andric In.getUser(), In.getGroup(), NewSize, In.getType(),
7877fc4c14SDimitry Andric In.getPermissions());
7977fc4c14SDimitry Andric }
8077fc4c14SDimitry Andric
copyWithNewName(const Status & In,const Twine & NewName)81e6d15924SDimitry Andric Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
82d8e91e46SDimitry Andric return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
83d8e91e46SDimitry Andric In.getUser(), In.getGroup(), In.getSize(), In.getType(),
84d8e91e46SDimitry Andric In.getPermissions());
85d8e91e46SDimitry Andric }
86d8e91e46SDimitry Andric
copyWithNewName(const file_status & In,const Twine & NewName)87e6d15924SDimitry Andric Status Status::copyWithNewName(const file_status &In, const Twine &NewName) {
88d8e91e46SDimitry Andric return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
89d8e91e46SDimitry Andric In.getUser(), In.getGroup(), In.getSize(), In.type(),
90d8e91e46SDimitry Andric In.permissions());
91d8e91e46SDimitry Andric }
92d8e91e46SDimitry Andric
equivalent(const Status & Other) const93d8e91e46SDimitry Andric bool Status::equivalent(const Status &Other) const {
94d8e91e46SDimitry Andric assert(isStatusKnown() && Other.isStatusKnown());
95d8e91e46SDimitry Andric return getUniqueID() == Other.getUniqueID();
96d8e91e46SDimitry Andric }
97d8e91e46SDimitry Andric
isDirectory() const98d8e91e46SDimitry Andric bool Status::isDirectory() const { return Type == file_type::directory_file; }
99d8e91e46SDimitry Andric
isRegularFile() const100d8e91e46SDimitry Andric bool Status::isRegularFile() const { return Type == file_type::regular_file; }
101d8e91e46SDimitry Andric
isOther() const102d8e91e46SDimitry Andric bool Status::isOther() const {
103d8e91e46SDimitry Andric return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
104d8e91e46SDimitry Andric }
105d8e91e46SDimitry Andric
isSymlink() const106d8e91e46SDimitry Andric bool Status::isSymlink() const { return Type == file_type::symlink_file; }
107d8e91e46SDimitry Andric
isStatusKnown() const108d8e91e46SDimitry Andric bool Status::isStatusKnown() const { return Type != file_type::status_error; }
109d8e91e46SDimitry Andric
exists() const110d8e91e46SDimitry Andric bool Status::exists() const {
111d8e91e46SDimitry Andric return isStatusKnown() && Type != file_type::file_not_found;
112d8e91e46SDimitry Andric }
113d8e91e46SDimitry Andric
114d8e91e46SDimitry Andric File::~File() = default;
115d8e91e46SDimitry Andric
116d8e91e46SDimitry Andric FileSystem::~FileSystem() = default;
117d8e91e46SDimitry Andric
118d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getBufferForFile(const llvm::Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)119d8e91e46SDimitry Andric FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
120d8e91e46SDimitry Andric bool RequiresNullTerminator, bool IsVolatile) {
121d8e91e46SDimitry Andric auto F = openFileForRead(Name);
122d8e91e46SDimitry Andric if (!F)
123d8e91e46SDimitry Andric return F.getError();
124d8e91e46SDimitry Andric
125d8e91e46SDimitry Andric return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
126d8e91e46SDimitry Andric }
127d8e91e46SDimitry Andric
makeAbsolute(SmallVectorImpl<char> & Path) const128d8e91e46SDimitry Andric std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
129d8e91e46SDimitry Andric if (llvm::sys::path::is_absolute(Path))
130d8e91e46SDimitry Andric return {};
131d8e91e46SDimitry Andric
132d8e91e46SDimitry Andric auto WorkingDir = getCurrentWorkingDirectory();
133d8e91e46SDimitry Andric if (!WorkingDir)
134d8e91e46SDimitry Andric return WorkingDir.getError();
135d8e91e46SDimitry Andric
136d8e91e46SDimitry Andric llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
137d8e91e46SDimitry Andric return {};
138d8e91e46SDimitry Andric }
139d8e91e46SDimitry Andric
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output)140d8e91e46SDimitry Andric std::error_code FileSystem::getRealPath(const Twine &Path,
141ac9a064cSDimitry Andric SmallVectorImpl<char> &Output) {
142d8e91e46SDimitry Andric return errc::operation_not_permitted;
143d8e91e46SDimitry Andric }
144d8e91e46SDimitry Andric
isLocal(const Twine & Path,bool & Result)145d8e91e46SDimitry Andric std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
146d8e91e46SDimitry Andric return errc::operation_not_permitted;
147d8e91e46SDimitry Andric }
148d8e91e46SDimitry Andric
exists(const Twine & Path)149d8e91e46SDimitry Andric bool FileSystem::exists(const Twine &Path) {
150d8e91e46SDimitry Andric auto Status = status(Path);
151d8e91e46SDimitry Andric return Status && Status->exists();
152d8e91e46SDimitry Andric }
153d8e91e46SDimitry Andric
equivalent(const Twine & A,const Twine & B)154ac9a064cSDimitry Andric llvm::ErrorOr<bool> FileSystem::equivalent(const Twine &A, const Twine &B) {
155ac9a064cSDimitry Andric auto StatusA = status(A);
156ac9a064cSDimitry Andric if (!StatusA)
157ac9a064cSDimitry Andric return StatusA.getError();
158ac9a064cSDimitry Andric auto StatusB = status(B);
159ac9a064cSDimitry Andric if (!StatusB)
160ac9a064cSDimitry Andric return StatusB.getError();
161ac9a064cSDimitry Andric return StatusA->equivalent(*StatusB);
162ac9a064cSDimitry Andric }
163ac9a064cSDimitry Andric
164145449b1SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const165145449b1SDimitry Andric void FileSystem::dump() const { print(dbgs(), PrintType::RecursiveContents); }
166145449b1SDimitry Andric #endif
167145449b1SDimitry Andric
168d8e91e46SDimitry Andric #ifndef NDEBUG
isTraversalComponent(StringRef Component)169d8e91e46SDimitry Andric static bool isTraversalComponent(StringRef Component) {
170ac9a064cSDimitry Andric return Component == ".." || Component == ".";
171d8e91e46SDimitry Andric }
172d8e91e46SDimitry Andric
pathHasTraversal(StringRef Path)173d8e91e46SDimitry Andric static bool pathHasTraversal(StringRef Path) {
174d8e91e46SDimitry Andric using namespace llvm::sys;
175d8e91e46SDimitry Andric
176d8e91e46SDimitry Andric for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
177d8e91e46SDimitry Andric if (isTraversalComponent(Comp))
178d8e91e46SDimitry Andric return true;
179d8e91e46SDimitry Andric return false;
180d8e91e46SDimitry Andric }
181d8e91e46SDimitry Andric #endif
182d8e91e46SDimitry Andric
183d8e91e46SDimitry Andric //===-----------------------------------------------------------------------===/
184d8e91e46SDimitry Andric // RealFileSystem implementation
185d8e91e46SDimitry Andric //===-----------------------------------------------------------------------===/
186d8e91e46SDimitry Andric
187d8e91e46SDimitry Andric namespace {
188d8e91e46SDimitry Andric
189d8e91e46SDimitry Andric /// Wrapper around a raw file descriptor.
190d8e91e46SDimitry Andric class RealFile : public File {
191d8e91e46SDimitry Andric friend class RealFileSystem;
192d8e91e46SDimitry Andric
193e6d15924SDimitry Andric file_t FD;
194d8e91e46SDimitry Andric Status S;
195d8e91e46SDimitry Andric std::string RealName;
196d8e91e46SDimitry Andric
RealFile(file_t RawFD,StringRef NewName,StringRef NewRealPathName)1971d5ae102SDimitry Andric RealFile(file_t RawFD, StringRef NewName, StringRef NewRealPathName)
1981d5ae102SDimitry Andric : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
199d8e91e46SDimitry Andric llvm::sys::fs::file_type::status_error, {}),
200d8e91e46SDimitry Andric RealName(NewRealPathName.str()) {
201e6d15924SDimitry Andric assert(FD != kInvalidFile && "Invalid or inactive file descriptor");
202d8e91e46SDimitry Andric }
203d8e91e46SDimitry Andric
204d8e91e46SDimitry Andric public:
205d8e91e46SDimitry Andric ~RealFile() override;
206d8e91e46SDimitry Andric
207d8e91e46SDimitry Andric ErrorOr<Status> status() override;
208d8e91e46SDimitry Andric ErrorOr<std::string> getName() override;
209d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
210d8e91e46SDimitry Andric int64_t FileSize,
211d8e91e46SDimitry Andric bool RequiresNullTerminator,
212d8e91e46SDimitry Andric bool IsVolatile) override;
213d8e91e46SDimitry Andric std::error_code close() override;
214c0981da4SDimitry Andric void setPath(const Twine &Path) override;
215d8e91e46SDimitry Andric };
216d8e91e46SDimitry Andric
217d8e91e46SDimitry Andric } // namespace
218d8e91e46SDimitry Andric
~RealFile()219d8e91e46SDimitry Andric RealFile::~RealFile() { close(); }
220d8e91e46SDimitry Andric
status()221d8e91e46SDimitry Andric ErrorOr<Status> RealFile::status() {
222e6d15924SDimitry Andric assert(FD != kInvalidFile && "cannot stat closed file");
223d8e91e46SDimitry Andric if (!S.isStatusKnown()) {
224d8e91e46SDimitry Andric file_status RealStatus;
225d8e91e46SDimitry Andric if (std::error_code EC = sys::fs::status(FD, RealStatus))
226d8e91e46SDimitry Andric return EC;
227d8e91e46SDimitry Andric S = Status::copyWithNewName(RealStatus, S.getName());
228d8e91e46SDimitry Andric }
229d8e91e46SDimitry Andric return S;
230d8e91e46SDimitry Andric }
231d8e91e46SDimitry Andric
getName()232d8e91e46SDimitry Andric ErrorOr<std::string> RealFile::getName() {
233d8e91e46SDimitry Andric return RealName.empty() ? S.getName().str() : RealName;
234d8e91e46SDimitry Andric }
235d8e91e46SDimitry Andric
236d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)237d8e91e46SDimitry Andric RealFile::getBuffer(const Twine &Name, int64_t FileSize,
238d8e91e46SDimitry Andric bool RequiresNullTerminator, bool IsVolatile) {
239e6d15924SDimitry Andric assert(FD != kInvalidFile && "cannot get buffer for closed file");
240d8e91e46SDimitry Andric return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
241d8e91e46SDimitry Andric IsVolatile);
242d8e91e46SDimitry Andric }
243d8e91e46SDimitry Andric
close()244d8e91e46SDimitry Andric std::error_code RealFile::close() {
245e6d15924SDimitry Andric std::error_code EC = sys::fs::closeFile(FD);
246e6d15924SDimitry Andric FD = kInvalidFile;
247d8e91e46SDimitry Andric return EC;
248d8e91e46SDimitry Andric }
249d8e91e46SDimitry Andric
setPath(const Twine & Path)250c0981da4SDimitry Andric void RealFile::setPath(const Twine &Path) {
251c0981da4SDimitry Andric RealName = Path.str();
252c0981da4SDimitry Andric if (auto Status = status())
253c0981da4SDimitry Andric S = Status.get().copyWithNewName(Status.get(), Path);
254c0981da4SDimitry Andric }
255c0981da4SDimitry Andric
256d8e91e46SDimitry Andric namespace {
257d8e91e46SDimitry Andric
258e6d15924SDimitry Andric /// A file system according to your operating system.
259e6d15924SDimitry Andric /// This may be linked to the process's working directory, or maintain its own.
260e6d15924SDimitry Andric ///
261e6d15924SDimitry Andric /// Currently, its own working directory is emulated by storing the path and
262e6d15924SDimitry Andric /// sending absolute paths to llvm::sys::fs:: functions.
263e6d15924SDimitry Andric /// A more principled approach would be to push this down a level, modelling
264e6d15924SDimitry Andric /// the working dir as an llvm::sys::fs::WorkingDir or similar.
265e6d15924SDimitry Andric /// This would enable the use of openat()-style functions on some platforms.
266d8e91e46SDimitry Andric class RealFileSystem : public FileSystem {
267d8e91e46SDimitry Andric public:
RealFileSystem(bool LinkCWDToProcess)268e6d15924SDimitry Andric explicit RealFileSystem(bool LinkCWDToProcess) {
269e6d15924SDimitry Andric if (!LinkCWDToProcess) {
270e6d15924SDimitry Andric SmallString<128> PWD, RealPWD;
2717fa27ce4SDimitry Andric if (std::error_code EC = llvm::sys::fs::current_path(PWD))
2727fa27ce4SDimitry Andric WD = EC;
2737fa27ce4SDimitry Andric else if (llvm::sys::fs::real_path(PWD, RealPWD))
2747fa27ce4SDimitry Andric WD = WorkingDirectory{PWD, PWD};
275e6d15924SDimitry Andric else
2767fa27ce4SDimitry Andric WD = WorkingDirectory{PWD, RealPWD};
277e6d15924SDimitry Andric }
278e6d15924SDimitry Andric }
279e6d15924SDimitry Andric
280d8e91e46SDimitry Andric ErrorOr<Status> status(const Twine &Path) override;
281d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
282d8e91e46SDimitry Andric directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
283d8e91e46SDimitry Andric
284d8e91e46SDimitry Andric llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
285d8e91e46SDimitry Andric std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
286d8e91e46SDimitry Andric std::error_code isLocal(const Twine &Path, bool &Result) override;
287d8e91e46SDimitry Andric std::error_code getRealPath(const Twine &Path,
288ac9a064cSDimitry Andric SmallVectorImpl<char> &Output) override;
289d8e91e46SDimitry Andric
290145449b1SDimitry Andric protected:
291145449b1SDimitry Andric void printImpl(raw_ostream &OS, PrintType Type,
292145449b1SDimitry Andric unsigned IndentLevel) const override;
293145449b1SDimitry Andric
294d8e91e46SDimitry Andric private:
295e6d15924SDimitry Andric // If this FS has its own working dir, use it to make Path absolute.
296e6d15924SDimitry Andric // The returned twine is safe to use as long as both Storage and Path live.
adjustPath(const Twine & Path,SmallVectorImpl<char> & Storage) const297e6d15924SDimitry Andric Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const {
2987fa27ce4SDimitry Andric if (!WD || !*WD)
299e6d15924SDimitry Andric return Path;
300e6d15924SDimitry Andric Path.toVector(Storage);
3017fa27ce4SDimitry Andric sys::fs::make_absolute(WD->get().Resolved, Storage);
302e6d15924SDimitry Andric return Storage;
303e6d15924SDimitry Andric }
304e6d15924SDimitry Andric
305e6d15924SDimitry Andric struct WorkingDirectory {
306e6d15924SDimitry Andric // The current working directory, without symlinks resolved. (echo $PWD).
307e6d15924SDimitry Andric SmallString<128> Specified;
308e6d15924SDimitry Andric // The current working directory, with links resolved. (readlink .).
309e6d15924SDimitry Andric SmallString<128> Resolved;
310e6d15924SDimitry Andric };
3117fa27ce4SDimitry Andric std::optional<llvm::ErrorOr<WorkingDirectory>> WD;
312d8e91e46SDimitry Andric };
313d8e91e46SDimitry Andric
314d8e91e46SDimitry Andric } // namespace
315d8e91e46SDimitry Andric
status(const Twine & Path)316d8e91e46SDimitry Andric ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
317e6d15924SDimitry Andric SmallString<256> Storage;
318d8e91e46SDimitry Andric sys::fs::file_status RealStatus;
319e6d15924SDimitry Andric if (std::error_code EC =
320e6d15924SDimitry Andric sys::fs::status(adjustPath(Path, Storage), RealStatus))
321d8e91e46SDimitry Andric return EC;
322e6d15924SDimitry Andric return Status::copyWithNewName(RealStatus, Path);
323d8e91e46SDimitry Andric }
324d8e91e46SDimitry Andric
325d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Name)326d8e91e46SDimitry Andric RealFileSystem::openFileForRead(const Twine &Name) {
327e6d15924SDimitry Andric SmallString<256> RealName, Storage;
328e6d15924SDimitry Andric Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead(
329e6d15924SDimitry Andric adjustPath(Name, Storage), sys::fs::OF_None, &RealName);
330e6d15924SDimitry Andric if (!FDOrErr)
331e6d15924SDimitry Andric return errorToErrorCode(FDOrErr.takeError());
332e6d15924SDimitry Andric return std::unique_ptr<File>(
333e6d15924SDimitry Andric new RealFile(*FDOrErr, Name.str(), RealName.str()));
334d8e91e46SDimitry Andric }
335d8e91e46SDimitry Andric
getCurrentWorkingDirectory() const336d8e91e46SDimitry Andric llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
3377fa27ce4SDimitry Andric if (WD && *WD)
3384df029ccSDimitry Andric return std::string(WD->get().Specified);
339e6d15924SDimitry Andric if (WD)
3407fa27ce4SDimitry Andric return WD->getError();
341e6d15924SDimitry Andric
342e6d15924SDimitry Andric SmallString<128> Dir;
343d8e91e46SDimitry Andric if (std::error_code EC = llvm::sys::fs::current_path(Dir))
344d8e91e46SDimitry Andric return EC;
3454df029ccSDimitry Andric return std::string(Dir);
346d8e91e46SDimitry Andric }
347d8e91e46SDimitry Andric
setCurrentWorkingDirectory(const Twine & Path)348d8e91e46SDimitry Andric std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
349e6d15924SDimitry Andric if (!WD)
350e6d15924SDimitry Andric return llvm::sys::fs::set_current_path(Path);
351d8e91e46SDimitry Andric
352e6d15924SDimitry Andric SmallString<128> Absolute, Resolved, Storage;
353e6d15924SDimitry Andric adjustPath(Path, Storage).toVector(Absolute);
354e6d15924SDimitry Andric bool IsDir;
355e6d15924SDimitry Andric if (auto Err = llvm::sys::fs::is_directory(Absolute, IsDir))
356e6d15924SDimitry Andric return Err;
357e6d15924SDimitry Andric if (!IsDir)
358e6d15924SDimitry Andric return std::make_error_code(std::errc::not_a_directory);
359e6d15924SDimitry Andric if (auto Err = llvm::sys::fs::real_path(Absolute, Resolved))
360e6d15924SDimitry Andric return Err;
3617fa27ce4SDimitry Andric WD = WorkingDirectory{Absolute, Resolved};
362d8e91e46SDimitry Andric return std::error_code();
363d8e91e46SDimitry Andric }
364d8e91e46SDimitry Andric
isLocal(const Twine & Path,bool & Result)365d8e91e46SDimitry Andric std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
366e6d15924SDimitry Andric SmallString<256> Storage;
367e6d15924SDimitry Andric return llvm::sys::fs::is_local(adjustPath(Path, Storage), Result);
368d8e91e46SDimitry Andric }
369d8e91e46SDimitry Andric
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output)370ac9a064cSDimitry Andric std::error_code RealFileSystem::getRealPath(const Twine &Path,
371ac9a064cSDimitry Andric SmallVectorImpl<char> &Output) {
372e6d15924SDimitry Andric SmallString<256> Storage;
373e6d15924SDimitry Andric return llvm::sys::fs::real_path(adjustPath(Path, Storage), Output);
374d8e91e46SDimitry Andric }
375d8e91e46SDimitry Andric
printImpl(raw_ostream & OS,PrintType Type,unsigned IndentLevel) const376145449b1SDimitry Andric void RealFileSystem::printImpl(raw_ostream &OS, PrintType Type,
377145449b1SDimitry Andric unsigned IndentLevel) const {
378145449b1SDimitry Andric printIndent(OS, IndentLevel);
379145449b1SDimitry Andric OS << "RealFileSystem using ";
380145449b1SDimitry Andric if (WD)
381145449b1SDimitry Andric OS << "own";
382145449b1SDimitry Andric else
383145449b1SDimitry Andric OS << "process";
384145449b1SDimitry Andric OS << " CWD\n";
385145449b1SDimitry Andric }
386145449b1SDimitry Andric
getRealFileSystem()387d8e91e46SDimitry Andric IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
388e6d15924SDimitry Andric static IntrusiveRefCntPtr<FileSystem> FS(new RealFileSystem(true));
389d8e91e46SDimitry Andric return FS;
390d8e91e46SDimitry Andric }
391d8e91e46SDimitry Andric
createPhysicalFileSystem()392e6d15924SDimitry Andric std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() {
3931d5ae102SDimitry Andric return std::make_unique<RealFileSystem>(false);
394e6d15924SDimitry Andric }
395e6d15924SDimitry Andric
396d8e91e46SDimitry Andric namespace {
397d8e91e46SDimitry Andric
398d8e91e46SDimitry Andric class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
399d8e91e46SDimitry Andric llvm::sys::fs::directory_iterator Iter;
400d8e91e46SDimitry Andric
401d8e91e46SDimitry Andric public:
RealFSDirIter(const Twine & Path,std::error_code & EC)402d8e91e46SDimitry Andric RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
403d8e91e46SDimitry Andric if (Iter != llvm::sys::fs::directory_iterator())
404d8e91e46SDimitry Andric CurrentEntry = directory_entry(Iter->path(), Iter->type());
405d8e91e46SDimitry Andric }
406d8e91e46SDimitry Andric
increment()407d8e91e46SDimitry Andric std::error_code increment() override {
408d8e91e46SDimitry Andric std::error_code EC;
409d8e91e46SDimitry Andric Iter.increment(EC);
410d8e91e46SDimitry Andric CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
411d8e91e46SDimitry Andric ? directory_entry()
412d8e91e46SDimitry Andric : directory_entry(Iter->path(), Iter->type());
413d8e91e46SDimitry Andric return EC;
414d8e91e46SDimitry Andric }
415d8e91e46SDimitry Andric };
416d8e91e46SDimitry Andric
417d8e91e46SDimitry Andric } // namespace
418d8e91e46SDimitry Andric
dir_begin(const Twine & Dir,std::error_code & EC)419d8e91e46SDimitry Andric directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
420d8e91e46SDimitry Andric std::error_code &EC) {
421e6d15924SDimitry Andric SmallString<128> Storage;
422e6d15924SDimitry Andric return directory_iterator(
423e6d15924SDimitry Andric std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
424d8e91e46SDimitry Andric }
425d8e91e46SDimitry Andric
426d8e91e46SDimitry Andric //===-----------------------------------------------------------------------===/
427d8e91e46SDimitry Andric // OverlayFileSystem implementation
428d8e91e46SDimitry Andric //===-----------------------------------------------------------------------===/
429d8e91e46SDimitry Andric
OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS)430d8e91e46SDimitry Andric OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
431d8e91e46SDimitry Andric FSList.push_back(std::move(BaseFS));
432d8e91e46SDimitry Andric }
433d8e91e46SDimitry Andric
pushOverlay(IntrusiveRefCntPtr<FileSystem> FS)434d8e91e46SDimitry Andric void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
435d8e91e46SDimitry Andric FSList.push_back(FS);
436d8e91e46SDimitry Andric // Synchronize added file systems by duplicating the working directory from
437d8e91e46SDimitry Andric // the first one in the list.
438d8e91e46SDimitry Andric FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
439d8e91e46SDimitry Andric }
440d8e91e46SDimitry Andric
status(const Twine & Path)441d8e91e46SDimitry Andric ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
442d8e91e46SDimitry Andric // FIXME: handle symlinks that cross file systems
443d8e91e46SDimitry Andric for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
444d8e91e46SDimitry Andric ErrorOr<Status> Status = (*I)->status(Path);
445d8e91e46SDimitry Andric if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
446d8e91e46SDimitry Andric return Status;
447d8e91e46SDimitry Andric }
448d8e91e46SDimitry Andric return make_error_code(llvm::errc::no_such_file_or_directory);
449d8e91e46SDimitry Andric }
450d8e91e46SDimitry Andric
exists(const Twine & Path)451ac9a064cSDimitry Andric bool OverlayFileSystem::exists(const Twine &Path) {
452ac9a064cSDimitry Andric // FIXME: handle symlinks that cross file systems
453ac9a064cSDimitry Andric for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
454ac9a064cSDimitry Andric if ((*I)->exists(Path))
455ac9a064cSDimitry Andric return true;
456ac9a064cSDimitry Andric }
457ac9a064cSDimitry Andric return false;
458ac9a064cSDimitry Andric }
459ac9a064cSDimitry Andric
460d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<File>>
openFileForRead(const llvm::Twine & Path)461d8e91e46SDimitry Andric OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
462d8e91e46SDimitry Andric // FIXME: handle symlinks that cross file systems
463d8e91e46SDimitry Andric for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
464d8e91e46SDimitry Andric auto Result = (*I)->openFileForRead(Path);
465d8e91e46SDimitry Andric if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
466d8e91e46SDimitry Andric return Result;
467d8e91e46SDimitry Andric }
468d8e91e46SDimitry Andric return make_error_code(llvm::errc::no_such_file_or_directory);
469d8e91e46SDimitry Andric }
470d8e91e46SDimitry Andric
471d8e91e46SDimitry Andric llvm::ErrorOr<std::string>
getCurrentWorkingDirectory() const472d8e91e46SDimitry Andric OverlayFileSystem::getCurrentWorkingDirectory() const {
473d8e91e46SDimitry Andric // All file systems are synchronized, just take the first working directory.
474d8e91e46SDimitry Andric return FSList.front()->getCurrentWorkingDirectory();
475d8e91e46SDimitry Andric }
476d8e91e46SDimitry Andric
477d8e91e46SDimitry Andric std::error_code
setCurrentWorkingDirectory(const Twine & Path)478d8e91e46SDimitry Andric OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
479d8e91e46SDimitry Andric for (auto &FS : FSList)
480d8e91e46SDimitry Andric if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
481d8e91e46SDimitry Andric return EC;
482d8e91e46SDimitry Andric return {};
483d8e91e46SDimitry Andric }
484d8e91e46SDimitry Andric
isLocal(const Twine & Path,bool & Result)485d8e91e46SDimitry Andric std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
486d8e91e46SDimitry Andric for (auto &FS : FSList)
487d8e91e46SDimitry Andric if (FS->exists(Path))
488d8e91e46SDimitry Andric return FS->isLocal(Path, Result);
489d8e91e46SDimitry Andric return errc::no_such_file_or_directory;
490d8e91e46SDimitry Andric }
491d8e91e46SDimitry Andric
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output)492ac9a064cSDimitry Andric std::error_code OverlayFileSystem::getRealPath(const Twine &Path,
493ac9a064cSDimitry Andric SmallVectorImpl<char> &Output) {
494c0981da4SDimitry Andric for (const auto &FS : FSList)
495d8e91e46SDimitry Andric if (FS->exists(Path))
496d8e91e46SDimitry Andric return FS->getRealPath(Path, Output);
497d8e91e46SDimitry Andric return errc::no_such_file_or_directory;
498d8e91e46SDimitry Andric }
499d8e91e46SDimitry Andric
visitChildFileSystems(VisitCallbackTy Callback)500ac9a064cSDimitry Andric void OverlayFileSystem::visitChildFileSystems(VisitCallbackTy Callback) {
501ac9a064cSDimitry Andric for (IntrusiveRefCntPtr<FileSystem> FS : overlays_range()) {
502ac9a064cSDimitry Andric Callback(*FS);
503ac9a064cSDimitry Andric FS->visitChildFileSystems(Callback);
504ac9a064cSDimitry Andric }
505ac9a064cSDimitry Andric }
506ac9a064cSDimitry Andric
printImpl(raw_ostream & OS,PrintType Type,unsigned IndentLevel) const507145449b1SDimitry Andric void OverlayFileSystem::printImpl(raw_ostream &OS, PrintType Type,
508145449b1SDimitry Andric unsigned IndentLevel) const {
509145449b1SDimitry Andric printIndent(OS, IndentLevel);
510145449b1SDimitry Andric OS << "OverlayFileSystem\n";
511145449b1SDimitry Andric if (Type == PrintType::Summary)
512145449b1SDimitry Andric return;
513145449b1SDimitry Andric
514145449b1SDimitry Andric if (Type == PrintType::Contents)
515145449b1SDimitry Andric Type = PrintType::Summary;
516b1c73532SDimitry Andric for (const auto &FS : overlays_range())
517145449b1SDimitry Andric FS->print(OS, Type, IndentLevel + 1);
518145449b1SDimitry Andric }
519145449b1SDimitry Andric
520d8e91e46SDimitry Andric llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
521d8e91e46SDimitry Andric
522d8e91e46SDimitry Andric namespace {
523d8e91e46SDimitry Andric
524344a3780SDimitry Andric /// Combines and deduplicates directory entries across multiple file systems.
525344a3780SDimitry Andric class CombiningDirIterImpl : public llvm::vfs::detail::DirIterImpl {
526344a3780SDimitry Andric using FileSystemPtr = llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>;
527344a3780SDimitry Andric
528145449b1SDimitry Andric /// Iterators to combine, processed in reverse order.
529145449b1SDimitry Andric SmallVector<directory_iterator, 8> IterList;
530145449b1SDimitry Andric /// The iterator currently being traversed.
531d8e91e46SDimitry Andric directory_iterator CurrentDirIter;
532344a3780SDimitry Andric /// The set of names already returned as entries.
533d8e91e46SDimitry Andric llvm::StringSet<> SeenNames;
534d8e91e46SDimitry Andric
535145449b1SDimitry Andric /// Sets \c CurrentDirIter to the next iterator in the list, or leaves it as
536145449b1SDimitry Andric /// is (at its end position) if we've already gone through them all.
incrementIter(bool IsFirstTime)537145449b1SDimitry Andric std::error_code incrementIter(bool IsFirstTime) {
538145449b1SDimitry Andric while (!IterList.empty()) {
539145449b1SDimitry Andric CurrentDirIter = IterList.back();
540145449b1SDimitry Andric IterList.pop_back();
541d8e91e46SDimitry Andric if (CurrentDirIter != directory_iterator())
542d8e91e46SDimitry Andric break; // found
543d8e91e46SDimitry Andric }
544145449b1SDimitry Andric
545145449b1SDimitry Andric if (IsFirstTime && CurrentDirIter == directory_iterator())
546145449b1SDimitry Andric return errc::no_such_file_or_directory;
547d8e91e46SDimitry Andric return {};
548d8e91e46SDimitry Andric }
549d8e91e46SDimitry Andric
incrementDirIter(bool IsFirstTime)550d8e91e46SDimitry Andric std::error_code incrementDirIter(bool IsFirstTime) {
551d8e91e46SDimitry Andric assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
552d8e91e46SDimitry Andric "incrementing past end");
553d8e91e46SDimitry Andric std::error_code EC;
554d8e91e46SDimitry Andric if (!IsFirstTime)
555d8e91e46SDimitry Andric CurrentDirIter.increment(EC);
556d8e91e46SDimitry Andric if (!EC && CurrentDirIter == directory_iterator())
557145449b1SDimitry Andric EC = incrementIter(IsFirstTime);
558d8e91e46SDimitry Andric return EC;
559d8e91e46SDimitry Andric }
560d8e91e46SDimitry Andric
incrementImpl(bool IsFirstTime)561d8e91e46SDimitry Andric std::error_code incrementImpl(bool IsFirstTime) {
562d8e91e46SDimitry Andric while (true) {
563d8e91e46SDimitry Andric std::error_code EC = incrementDirIter(IsFirstTime);
564d8e91e46SDimitry Andric if (EC || CurrentDirIter == directory_iterator()) {
565d8e91e46SDimitry Andric CurrentEntry = directory_entry();
566d8e91e46SDimitry Andric return EC;
567d8e91e46SDimitry Andric }
568d8e91e46SDimitry Andric CurrentEntry = *CurrentDirIter;
569d8e91e46SDimitry Andric StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
570d8e91e46SDimitry Andric if (SeenNames.insert(Name).second)
571d8e91e46SDimitry Andric return EC; // name not seen before
572d8e91e46SDimitry Andric }
573d8e91e46SDimitry Andric llvm_unreachable("returned above");
574d8e91e46SDimitry Andric }
575d8e91e46SDimitry Andric
576d8e91e46SDimitry Andric public:
CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems,std::string Dir,std::error_code & EC)577344a3780SDimitry Andric CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems, std::string Dir,
578145449b1SDimitry Andric std::error_code &EC) {
579b1c73532SDimitry Andric for (const auto &FS : FileSystems) {
580145449b1SDimitry Andric std::error_code FEC;
581145449b1SDimitry Andric directory_iterator Iter = FS->dir_begin(Dir, FEC);
582145449b1SDimitry Andric if (FEC && FEC != errc::no_such_file_or_directory) {
583145449b1SDimitry Andric EC = FEC;
584145449b1SDimitry Andric return;
585145449b1SDimitry Andric }
586145449b1SDimitry Andric if (!FEC)
587145449b1SDimitry Andric IterList.push_back(Iter);
588145449b1SDimitry Andric }
589344a3780SDimitry Andric EC = incrementImpl(true);
590344a3780SDimitry Andric }
591344a3780SDimitry Andric
CombiningDirIterImpl(ArrayRef<directory_iterator> DirIters,std::error_code & EC)592145449b1SDimitry Andric CombiningDirIterImpl(ArrayRef<directory_iterator> DirIters,
593145449b1SDimitry Andric std::error_code &EC)
594145449b1SDimitry Andric : IterList(DirIters.begin(), DirIters.end()) {
595d8e91e46SDimitry Andric EC = incrementImpl(true);
596d8e91e46SDimitry Andric }
597d8e91e46SDimitry Andric
increment()598d8e91e46SDimitry Andric std::error_code increment() override { return incrementImpl(false); }
599d8e91e46SDimitry Andric };
600d8e91e46SDimitry Andric
601d8e91e46SDimitry Andric } // namespace
602d8e91e46SDimitry Andric
dir_begin(const Twine & Dir,std::error_code & EC)603d8e91e46SDimitry Andric directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
604d8e91e46SDimitry Andric std::error_code &EC) {
605145449b1SDimitry Andric directory_iterator Combined = directory_iterator(
606344a3780SDimitry Andric std::make_shared<CombiningDirIterImpl>(FSList, Dir.str(), EC));
607145449b1SDimitry Andric if (EC)
608145449b1SDimitry Andric return {};
609145449b1SDimitry Andric return Combined;
610d8e91e46SDimitry Andric }
611d8e91e46SDimitry Andric
anchor()612d8e91e46SDimitry Andric void ProxyFileSystem::anchor() {}
613d8e91e46SDimitry Andric
614d8e91e46SDimitry Andric namespace llvm {
615d8e91e46SDimitry Andric namespace vfs {
616d8e91e46SDimitry Andric
617d8e91e46SDimitry Andric namespace detail {
618d8e91e46SDimitry Andric
619145449b1SDimitry Andric enum InMemoryNodeKind {
620145449b1SDimitry Andric IME_File,
621145449b1SDimitry Andric IME_Directory,
622145449b1SDimitry Andric IME_HardLink,
623145449b1SDimitry Andric IME_SymbolicLink,
624145449b1SDimitry Andric };
625d8e91e46SDimitry Andric
626d8e91e46SDimitry Andric /// The in memory file system is a tree of Nodes. Every node can either be a
627145449b1SDimitry Andric /// file, symlink, hardlink or a directory.
628d8e91e46SDimitry Andric class InMemoryNode {
629d8e91e46SDimitry Andric InMemoryNodeKind Kind;
630d8e91e46SDimitry Andric std::string FileName;
631d8e91e46SDimitry Andric
632d8e91e46SDimitry Andric public:
InMemoryNode(llvm::StringRef FileName,InMemoryNodeKind Kind)633d8e91e46SDimitry Andric InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
634cfca06d7SDimitry Andric : Kind(Kind), FileName(std::string(llvm::sys::path::filename(FileName))) {
635cfca06d7SDimitry Andric }
636d8e91e46SDimitry Andric virtual ~InMemoryNode() = default;
637d8e91e46SDimitry Andric
6386f8fc217SDimitry Andric /// Return the \p Status for this node. \p RequestedName should be the name
6396f8fc217SDimitry Andric /// through which the caller referred to this node. It will override
6406f8fc217SDimitry Andric /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
6416f8fc217SDimitry Andric virtual Status getStatus(const Twine &RequestedName) const = 0;
6426f8fc217SDimitry Andric
643d8e91e46SDimitry Andric /// Get the filename of this node (the name without the directory part).
getFileName() const644d8e91e46SDimitry Andric StringRef getFileName() const { return FileName; }
getKind() const645d8e91e46SDimitry Andric InMemoryNodeKind getKind() const { return Kind; }
646d8e91e46SDimitry Andric virtual std::string toString(unsigned Indent) const = 0;
647d8e91e46SDimitry Andric };
648d8e91e46SDimitry Andric
649d8e91e46SDimitry Andric class InMemoryFile : public InMemoryNode {
650d8e91e46SDimitry Andric Status Stat;
651d8e91e46SDimitry Andric std::unique_ptr<llvm::MemoryBuffer> Buffer;
652d8e91e46SDimitry Andric
653d8e91e46SDimitry Andric public:
InMemoryFile(Status Stat,std::unique_ptr<llvm::MemoryBuffer> Buffer)654d8e91e46SDimitry Andric InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
655d8e91e46SDimitry Andric : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
656d8e91e46SDimitry Andric Buffer(std::move(Buffer)) {}
657d8e91e46SDimitry Andric
getStatus(const Twine & RequestedName) const6586f8fc217SDimitry Andric Status getStatus(const Twine &RequestedName) const override {
659d8e91e46SDimitry Andric return Status::copyWithNewName(Stat, RequestedName);
660d8e91e46SDimitry Andric }
getBuffer() const661d8e91e46SDimitry Andric llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
662d8e91e46SDimitry Andric
toString(unsigned Indent) const663d8e91e46SDimitry Andric std::string toString(unsigned Indent) const override {
664d8e91e46SDimitry Andric return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
665d8e91e46SDimitry Andric }
666d8e91e46SDimitry Andric
classof(const InMemoryNode * N)667d8e91e46SDimitry Andric static bool classof(const InMemoryNode *N) {
668d8e91e46SDimitry Andric return N->getKind() == IME_File;
669d8e91e46SDimitry Andric }
670d8e91e46SDimitry Andric };
671d8e91e46SDimitry Andric
672d8e91e46SDimitry Andric namespace {
673d8e91e46SDimitry Andric
674d8e91e46SDimitry Andric class InMemoryHardLink : public InMemoryNode {
675d8e91e46SDimitry Andric const InMemoryFile &ResolvedFile;
676d8e91e46SDimitry Andric
677d8e91e46SDimitry Andric public:
InMemoryHardLink(StringRef Path,const InMemoryFile & ResolvedFile)678d8e91e46SDimitry Andric InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
679d8e91e46SDimitry Andric : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
getResolvedFile() const680d8e91e46SDimitry Andric const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
681d8e91e46SDimitry Andric
getStatus(const Twine & RequestedName) const6826f8fc217SDimitry Andric Status getStatus(const Twine &RequestedName) const override {
6836f8fc217SDimitry Andric return ResolvedFile.getStatus(RequestedName);
6846f8fc217SDimitry Andric }
6856f8fc217SDimitry Andric
toString(unsigned Indent) const686d8e91e46SDimitry Andric std::string toString(unsigned Indent) const override {
687d8e91e46SDimitry Andric return std::string(Indent, ' ') + "HardLink to -> " +
688d8e91e46SDimitry Andric ResolvedFile.toString(0);
689d8e91e46SDimitry Andric }
690d8e91e46SDimitry Andric
classof(const InMemoryNode * N)691d8e91e46SDimitry Andric static bool classof(const InMemoryNode *N) {
692d8e91e46SDimitry Andric return N->getKind() == IME_HardLink;
693d8e91e46SDimitry Andric }
694d8e91e46SDimitry Andric };
695d8e91e46SDimitry Andric
696145449b1SDimitry Andric class InMemorySymbolicLink : public InMemoryNode {
697145449b1SDimitry Andric std::string TargetPath;
698145449b1SDimitry Andric Status Stat;
699145449b1SDimitry Andric
700145449b1SDimitry Andric public:
InMemorySymbolicLink(StringRef Path,StringRef TargetPath,Status Stat)701145449b1SDimitry Andric InMemorySymbolicLink(StringRef Path, StringRef TargetPath, Status Stat)
702145449b1SDimitry Andric : InMemoryNode(Path, IME_SymbolicLink), TargetPath(std::move(TargetPath)),
703145449b1SDimitry Andric Stat(Stat) {}
704145449b1SDimitry Andric
toString(unsigned Indent) const705145449b1SDimitry Andric std::string toString(unsigned Indent) const override {
706145449b1SDimitry Andric return std::string(Indent, ' ') + "SymbolicLink to -> " + TargetPath;
707145449b1SDimitry Andric }
708145449b1SDimitry Andric
getStatus(const Twine & RequestedName) const709145449b1SDimitry Andric Status getStatus(const Twine &RequestedName) const override {
710145449b1SDimitry Andric return Status::copyWithNewName(Stat, RequestedName);
711145449b1SDimitry Andric }
712145449b1SDimitry Andric
getTargetPath() const713145449b1SDimitry Andric StringRef getTargetPath() const { return TargetPath; }
714145449b1SDimitry Andric
classof(const InMemoryNode * N)715145449b1SDimitry Andric static bool classof(const InMemoryNode *N) {
716145449b1SDimitry Andric return N->getKind() == IME_SymbolicLink;
717145449b1SDimitry Andric }
718145449b1SDimitry Andric };
719145449b1SDimitry Andric
720d8e91e46SDimitry Andric /// Adapt a InMemoryFile for VFS' File interface. The goal is to make
721d8e91e46SDimitry Andric /// \p InMemoryFileAdaptor mimic as much as possible the behavior of
722d8e91e46SDimitry Andric /// \p RealFile.
723d8e91e46SDimitry Andric class InMemoryFileAdaptor : public File {
724d8e91e46SDimitry Andric const InMemoryFile &Node;
725d8e91e46SDimitry Andric /// The name to use when returning a Status for this file.
726d8e91e46SDimitry Andric std::string RequestedName;
727d8e91e46SDimitry Andric
728d8e91e46SDimitry Andric public:
InMemoryFileAdaptor(const InMemoryFile & Node,std::string RequestedName)729d8e91e46SDimitry Andric explicit InMemoryFileAdaptor(const InMemoryFile &Node,
730d8e91e46SDimitry Andric std::string RequestedName)
731d8e91e46SDimitry Andric : Node(Node), RequestedName(std::move(RequestedName)) {}
732d8e91e46SDimitry Andric
status()733d8e91e46SDimitry Andric llvm::ErrorOr<Status> status() override {
734d8e91e46SDimitry Andric return Node.getStatus(RequestedName);
735d8e91e46SDimitry Andric }
736d8e91e46SDimitry Andric
737d8e91e46SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)738d8e91e46SDimitry Andric getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
739d8e91e46SDimitry Andric bool IsVolatile) override {
740d8e91e46SDimitry Andric llvm::MemoryBuffer *Buf = Node.getBuffer();
741d8e91e46SDimitry Andric return llvm::MemoryBuffer::getMemBuffer(
742d8e91e46SDimitry Andric Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
743d8e91e46SDimitry Andric }
744d8e91e46SDimitry Andric
close()745d8e91e46SDimitry Andric std::error_code close() override { return {}; }
746c0981da4SDimitry Andric
setPath(const Twine & Path)747c0981da4SDimitry Andric void setPath(const Twine &Path) override { RequestedName = Path.str(); }
748d8e91e46SDimitry Andric };
749d8e91e46SDimitry Andric } // namespace
750d8e91e46SDimitry Andric
751d8e91e46SDimitry Andric class InMemoryDirectory : public InMemoryNode {
752d8e91e46SDimitry Andric Status Stat;
7537fa27ce4SDimitry Andric std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
754d8e91e46SDimitry Andric
755d8e91e46SDimitry Andric public:
InMemoryDirectory(Status Stat)756d8e91e46SDimitry Andric InMemoryDirectory(Status Stat)
757d8e91e46SDimitry Andric : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
758d8e91e46SDimitry Andric
759d8e91e46SDimitry Andric /// Return the \p Status for this node. \p RequestedName should be the name
760d8e91e46SDimitry Andric /// through which the caller referred to this node. It will override
761d8e91e46SDimitry Andric /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
getStatus(const Twine & RequestedName) const7626f8fc217SDimitry Andric Status getStatus(const Twine &RequestedName) const override {
763d8e91e46SDimitry Andric return Status::copyWithNewName(Stat, RequestedName);
764d8e91e46SDimitry Andric }
765c0981da4SDimitry Andric
getUniqueID() const766c0981da4SDimitry Andric UniqueID getUniqueID() const { return Stat.getUniqueID(); }
767c0981da4SDimitry Andric
getChild(StringRef Name) const768145449b1SDimitry Andric InMemoryNode *getChild(StringRef Name) const {
7697fa27ce4SDimitry Andric auto I = Entries.find(Name.str());
770d8e91e46SDimitry Andric if (I != Entries.end())
771d8e91e46SDimitry Andric return I->second.get();
772d8e91e46SDimitry Andric return nullptr;
773d8e91e46SDimitry Andric }
774d8e91e46SDimitry Andric
addChild(StringRef Name,std::unique_ptr<InMemoryNode> Child)775d8e91e46SDimitry Andric InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
7767fa27ce4SDimitry Andric return Entries.emplace(Name, std::move(Child)).first->second.get();
777d8e91e46SDimitry Andric }
778d8e91e46SDimitry Andric
779d8e91e46SDimitry Andric using const_iterator = decltype(Entries)::const_iterator;
780d8e91e46SDimitry Andric
begin() const781d8e91e46SDimitry Andric const_iterator begin() const { return Entries.begin(); }
end() const782d8e91e46SDimitry Andric const_iterator end() const { return Entries.end(); }
783d8e91e46SDimitry Andric
toString(unsigned Indent) const784d8e91e46SDimitry Andric std::string toString(unsigned Indent) const override {
785d8e91e46SDimitry Andric std::string Result =
786d8e91e46SDimitry Andric (std::string(Indent, ' ') + Stat.getName() + "\n").str();
787d8e91e46SDimitry Andric for (const auto &Entry : Entries)
788d8e91e46SDimitry Andric Result += Entry.second->toString(Indent + 2);
789d8e91e46SDimitry Andric return Result;
790d8e91e46SDimitry Andric }
791d8e91e46SDimitry Andric
classof(const InMemoryNode * N)792d8e91e46SDimitry Andric static bool classof(const InMemoryNode *N) {
793d8e91e46SDimitry Andric return N->getKind() == IME_Directory;
794d8e91e46SDimitry Andric }
795d8e91e46SDimitry Andric };
796d8e91e46SDimitry Andric
797d8e91e46SDimitry Andric } // namespace detail
798d8e91e46SDimitry Andric
799c0981da4SDimitry Andric // The UniqueID of in-memory files is derived from path and content.
800c0981da4SDimitry Andric // This avoids difficulties in creating exactly equivalent in-memory FSes,
801c0981da4SDimitry Andric // as often needed in multithreaded programs.
getUniqueID(hash_code Hash)802c0981da4SDimitry Andric static sys::fs::UniqueID getUniqueID(hash_code Hash) {
803c0981da4SDimitry Andric return sys::fs::UniqueID(std::numeric_limits<uint64_t>::max(),
804c0981da4SDimitry Andric uint64_t(size_t(Hash)));
805c0981da4SDimitry Andric }
getFileID(sys::fs::UniqueID Parent,llvm::StringRef Name,llvm::StringRef Contents)806c0981da4SDimitry Andric static sys::fs::UniqueID getFileID(sys::fs::UniqueID Parent,
807c0981da4SDimitry Andric llvm::StringRef Name,
808c0981da4SDimitry Andric llvm::StringRef Contents) {
809c0981da4SDimitry Andric return getUniqueID(llvm::hash_combine(Parent.getFile(), Name, Contents));
810c0981da4SDimitry Andric }
getDirectoryID(sys::fs::UniqueID Parent,llvm::StringRef Name)811c0981da4SDimitry Andric static sys::fs::UniqueID getDirectoryID(sys::fs::UniqueID Parent,
812c0981da4SDimitry Andric llvm::StringRef Name) {
813c0981da4SDimitry Andric return getUniqueID(llvm::hash_combine(Parent.getFile(), Name));
814c0981da4SDimitry Andric }
815c0981da4SDimitry Andric
makeStatus() const8166f8fc217SDimitry Andric Status detail::NewInMemoryNodeInfo::makeStatus() const {
8176f8fc217SDimitry Andric UniqueID UID =
8186f8fc217SDimitry Andric (Type == sys::fs::file_type::directory_file)
8196f8fc217SDimitry Andric ? getDirectoryID(DirUID, Name)
8206f8fc217SDimitry Andric : getFileID(DirUID, Name, Buffer ? Buffer->getBuffer() : "");
8216f8fc217SDimitry Andric
8226f8fc217SDimitry Andric return Status(Path, UID, llvm::sys::toTimePoint(ModificationTime), User,
8236f8fc217SDimitry Andric Group, Buffer ? Buffer->getBufferSize() : 0, Type, Perms);
8246f8fc217SDimitry Andric }
8256f8fc217SDimitry Andric
InMemoryFileSystem(bool UseNormalizedPaths)826d8e91e46SDimitry Andric InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
827d8e91e46SDimitry Andric : Root(new detail::InMemoryDirectory(
828c0981da4SDimitry Andric Status("", getDirectoryID(llvm::sys::fs::UniqueID(), ""),
829c0981da4SDimitry Andric llvm::sys::TimePoint<>(), 0, 0, 0,
830c0981da4SDimitry Andric llvm::sys::fs::file_type::directory_file,
831d8e91e46SDimitry Andric llvm::sys::fs::perms::all_all))),
832d8e91e46SDimitry Andric UseNormalizedPaths(UseNormalizedPaths) {}
833d8e91e46SDimitry Andric
834d8e91e46SDimitry Andric InMemoryFileSystem::~InMemoryFileSystem() = default;
835d8e91e46SDimitry Andric
toString() const836d8e91e46SDimitry Andric std::string InMemoryFileSystem::toString() const {
837d8e91e46SDimitry Andric return Root->toString(/*Indent=*/0);
838d8e91e46SDimitry Andric }
839d8e91e46SDimitry Andric
addFile(const Twine & P,time_t ModificationTime,std::unique_ptr<llvm::MemoryBuffer> Buffer,std::optional<uint32_t> User,std::optional<uint32_t> Group,std::optional<llvm::sys::fs::file_type> Type,std::optional<llvm::sys::fs::perms> Perms,MakeNodeFn MakeNode)840d8e91e46SDimitry Andric bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
841d8e91e46SDimitry Andric std::unique_ptr<llvm::MemoryBuffer> Buffer,
842e3b55780SDimitry Andric std::optional<uint32_t> User,
843e3b55780SDimitry Andric std::optional<uint32_t> Group,
844e3b55780SDimitry Andric std::optional<llvm::sys::fs::file_type> Type,
845e3b55780SDimitry Andric std::optional<llvm::sys::fs::perms> Perms,
8466f8fc217SDimitry Andric MakeNodeFn MakeNode) {
847d8e91e46SDimitry Andric SmallString<128> Path;
848d8e91e46SDimitry Andric P.toVector(Path);
849d8e91e46SDimitry Andric
850d8e91e46SDimitry Andric // Fix up relative paths. This just prepends the current working directory.
851d8e91e46SDimitry Andric std::error_code EC = makeAbsolute(Path);
852d8e91e46SDimitry Andric assert(!EC);
853d8e91e46SDimitry Andric (void)EC;
854d8e91e46SDimitry Andric
855d8e91e46SDimitry Andric if (useNormalizedPaths())
856d8e91e46SDimitry Andric llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
857d8e91e46SDimitry Andric
858d8e91e46SDimitry Andric if (Path.empty())
859d8e91e46SDimitry Andric return false;
860d8e91e46SDimitry Andric
861d8e91e46SDimitry Andric detail::InMemoryDirectory *Dir = Root.get();
862d8e91e46SDimitry Andric auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
863145449b1SDimitry Andric const auto ResolvedUser = User.value_or(0);
864145449b1SDimitry Andric const auto ResolvedGroup = Group.value_or(0);
865145449b1SDimitry Andric const auto ResolvedType = Type.value_or(sys::fs::file_type::regular_file);
866145449b1SDimitry Andric const auto ResolvedPerms = Perms.value_or(sys::fs::all_all);
867d8e91e46SDimitry Andric // Any intermediate directories we create should be accessible by
868d8e91e46SDimitry Andric // the owner, even if Perms says otherwise for the final path.
869d8e91e46SDimitry Andric const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
870d8e91e46SDimitry Andric
871ac9a064cSDimitry Andric StringRef Name = *I;
872ac9a064cSDimitry Andric while (true) {
873ac9a064cSDimitry Andric Name = *I;
874ac9a064cSDimitry Andric ++I;
875ac9a064cSDimitry Andric if (I == E)
876ac9a064cSDimitry Andric break;
877ac9a064cSDimitry Andric detail::InMemoryNode *Node = Dir->getChild(Name);
878ac9a064cSDimitry Andric if (!Node) {
879ac9a064cSDimitry Andric // This isn't the last element, so we create a new directory.
880d8e91e46SDimitry Andric Status Stat(
881d8e91e46SDimitry Andric StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
882c0981da4SDimitry Andric getDirectoryID(Dir->getUniqueID(), Name),
883c0981da4SDimitry Andric llvm::sys::toTimePoint(ModificationTime), ResolvedUser, ResolvedGroup,
884c0981da4SDimitry Andric 0, sys::fs::file_type::directory_file, NewDirectoryPerms);
885d8e91e46SDimitry Andric Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
8861d5ae102SDimitry Andric Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
887d8e91e46SDimitry Andric continue;
888d8e91e46SDimitry Andric }
889ac9a064cSDimitry Andric // Creating file under another file.
890ac9a064cSDimitry Andric if (!isa<detail::InMemoryDirectory>(Node))
891ac9a064cSDimitry Andric return false;
892ac9a064cSDimitry Andric Dir = cast<detail::InMemoryDirectory>(Node);
893ac9a064cSDimitry Andric }
894ac9a064cSDimitry Andric detail::InMemoryNode *Node = Dir->getChild(Name);
895ac9a064cSDimitry Andric if (!Node) {
896ac9a064cSDimitry Andric Dir->addChild(Name,
897ac9a064cSDimitry Andric MakeNode({Dir->getUniqueID(), Path, Name, ModificationTime,
898ac9a064cSDimitry Andric std::move(Buffer), ResolvedUser, ResolvedGroup,
899ac9a064cSDimitry Andric ResolvedType, ResolvedPerms}));
900ac9a064cSDimitry Andric return true;
901ac9a064cSDimitry Andric }
902ac9a064cSDimitry Andric if (isa<detail::InMemoryDirectory>(Node))
903ac9a064cSDimitry Andric return ResolvedType == sys::fs::file_type::directory_file;
904d8e91e46SDimitry Andric
905d8e91e46SDimitry Andric assert((isa<detail::InMemoryFile>(Node) ||
906d8e91e46SDimitry Andric isa<detail::InMemoryHardLink>(Node)) &&
907d8e91e46SDimitry Andric "Must be either file, hardlink or directory!");
908d8e91e46SDimitry Andric
909d8e91e46SDimitry Andric // Return false only if the new file is different from the existing one.
910ac9a064cSDimitry Andric if (auto *Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
911d8e91e46SDimitry Andric return Link->getResolvedFile().getBuffer()->getBuffer() ==
912d8e91e46SDimitry Andric Buffer->getBuffer();
913d8e91e46SDimitry Andric }
914d8e91e46SDimitry Andric return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
915d8e91e46SDimitry Andric Buffer->getBuffer();
916d8e91e46SDimitry Andric }
917d8e91e46SDimitry Andric
addFile(const Twine & P,time_t ModificationTime,std::unique_ptr<llvm::MemoryBuffer> Buffer,std::optional<uint32_t> User,std::optional<uint32_t> Group,std::optional<llvm::sys::fs::file_type> Type,std::optional<llvm::sys::fs::perms> Perms)918d8e91e46SDimitry Andric bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
919d8e91e46SDimitry Andric std::unique_ptr<llvm::MemoryBuffer> Buffer,
920e3b55780SDimitry Andric std::optional<uint32_t> User,
921e3b55780SDimitry Andric std::optional<uint32_t> Group,
922e3b55780SDimitry Andric std::optional<llvm::sys::fs::file_type> Type,
923e3b55780SDimitry Andric std::optional<llvm::sys::fs::perms> Perms) {
924d8e91e46SDimitry Andric return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
9256f8fc217SDimitry Andric Perms,
9266f8fc217SDimitry Andric [](detail::NewInMemoryNodeInfo NNI)
9276f8fc217SDimitry Andric -> std::unique_ptr<detail::InMemoryNode> {
9286f8fc217SDimitry Andric Status Stat = NNI.makeStatus();
9296f8fc217SDimitry Andric if (Stat.getType() == sys::fs::file_type::directory_file)
9306f8fc217SDimitry Andric return std::make_unique<detail::InMemoryDirectory>(Stat);
9316f8fc217SDimitry Andric return std::make_unique<detail::InMemoryFile>(
9326f8fc217SDimitry Andric Stat, std::move(NNI.Buffer));
9336f8fc217SDimitry Andric });
934d8e91e46SDimitry Andric }
935d8e91e46SDimitry Andric
addFileNoOwn(const Twine & P,time_t ModificationTime,const llvm::MemoryBufferRef & Buffer,std::optional<uint32_t> User,std::optional<uint32_t> Group,std::optional<llvm::sys::fs::file_type> Type,std::optional<llvm::sys::fs::perms> Perms)936e3b55780SDimitry Andric bool InMemoryFileSystem::addFileNoOwn(
937e3b55780SDimitry Andric const Twine &P, time_t ModificationTime,
938e3b55780SDimitry Andric const llvm::MemoryBufferRef &Buffer, std::optional<uint32_t> User,
939e3b55780SDimitry Andric std::optional<uint32_t> Group, std::optional<llvm::sys::fs::file_type> Type,
940e3b55780SDimitry Andric std::optional<llvm::sys::fs::perms> Perms) {
941b60736ecSDimitry Andric return addFile(P, ModificationTime, llvm::MemoryBuffer::getMemBuffer(Buffer),
942d8e91e46SDimitry Andric std::move(User), std::move(Group), std::move(Type),
9436f8fc217SDimitry Andric std::move(Perms),
9446f8fc217SDimitry Andric [](detail::NewInMemoryNodeInfo NNI)
9456f8fc217SDimitry Andric -> std::unique_ptr<detail::InMemoryNode> {
9466f8fc217SDimitry Andric Status Stat = NNI.makeStatus();
9476f8fc217SDimitry Andric if (Stat.getType() == sys::fs::file_type::directory_file)
9486f8fc217SDimitry Andric return std::make_unique<detail::InMemoryDirectory>(Stat);
9496f8fc217SDimitry Andric return std::make_unique<detail::InMemoryFile>(
9506f8fc217SDimitry Andric Stat, std::move(NNI.Buffer));
9516f8fc217SDimitry Andric });
952d8e91e46SDimitry Andric }
953d8e91e46SDimitry Andric
954145449b1SDimitry Andric detail::NamedNodeOrError
lookupNode(const Twine & P,bool FollowFinalSymlink,size_t SymlinkDepth) const955145449b1SDimitry Andric InMemoryFileSystem::lookupNode(const Twine &P, bool FollowFinalSymlink,
956145449b1SDimitry Andric size_t SymlinkDepth) const {
957d8e91e46SDimitry Andric SmallString<128> Path;
958d8e91e46SDimitry Andric P.toVector(Path);
959d8e91e46SDimitry Andric
960d8e91e46SDimitry Andric // Fix up relative paths. This just prepends the current working directory.
961145449b1SDimitry Andric std::error_code EC = makeAbsolute(Path);
962d8e91e46SDimitry Andric assert(!EC);
963d8e91e46SDimitry Andric (void)EC;
964d8e91e46SDimitry Andric
965145449b1SDimitry Andric if (useNormalizedPaths())
966d8e91e46SDimitry Andric llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
967d8e91e46SDimitry Andric
968145449b1SDimitry Andric const detail::InMemoryDirectory *Dir = Root.get();
969d8e91e46SDimitry Andric if (Path.empty())
970145449b1SDimitry Andric return detail::NamedNodeOrError(Path, Dir);
971d8e91e46SDimitry Andric
972d8e91e46SDimitry Andric auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
973d8e91e46SDimitry Andric while (true) {
974d8e91e46SDimitry Andric detail::InMemoryNode *Node = Dir->getChild(*I);
975d8e91e46SDimitry Andric ++I;
976d8e91e46SDimitry Andric if (!Node)
977d8e91e46SDimitry Andric return errc::no_such_file_or_directory;
978d8e91e46SDimitry Andric
979145449b1SDimitry Andric if (auto Symlink = dyn_cast<detail::InMemorySymbolicLink>(Node)) {
980145449b1SDimitry Andric // If we're at the end of the path, and we're not following through
981145449b1SDimitry Andric // terminal symlinks, then we're done.
982145449b1SDimitry Andric if (I == E && !FollowFinalSymlink)
983145449b1SDimitry Andric return detail::NamedNodeOrError(Path, Symlink);
984145449b1SDimitry Andric
985145449b1SDimitry Andric if (SymlinkDepth > InMemoryFileSystem::MaxSymlinkDepth)
986145449b1SDimitry Andric return errc::no_such_file_or_directory;
987145449b1SDimitry Andric
988145449b1SDimitry Andric SmallString<128> TargetPath = Symlink->getTargetPath();
989145449b1SDimitry Andric if (std::error_code EC = makeAbsolute(TargetPath))
990145449b1SDimitry Andric return EC;
991145449b1SDimitry Andric
992145449b1SDimitry Andric // Keep going with the target. We always want to follow symlinks here
993145449b1SDimitry Andric // because we're either at the end of a path that we want to follow, or
994145449b1SDimitry Andric // not at the end of a path, in which case we need to follow the symlink
995145449b1SDimitry Andric // regardless.
996145449b1SDimitry Andric auto Target =
997145449b1SDimitry Andric lookupNode(TargetPath, /*FollowFinalSymlink=*/true, SymlinkDepth + 1);
998145449b1SDimitry Andric if (!Target || I == E)
999145449b1SDimitry Andric return Target;
1000145449b1SDimitry Andric
1001145449b1SDimitry Andric if (!isa<detail::InMemoryDirectory>(*Target))
1002145449b1SDimitry Andric return errc::no_such_file_or_directory;
1003145449b1SDimitry Andric
1004145449b1SDimitry Andric // Otherwise, continue on the search in the symlinked directory.
1005145449b1SDimitry Andric Dir = cast<detail::InMemoryDirectory>(*Target);
1006145449b1SDimitry Andric continue;
1007145449b1SDimitry Andric }
1008145449b1SDimitry Andric
1009d8e91e46SDimitry Andric // Return the file if it's at the end of the path.
1010d8e91e46SDimitry Andric if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
1011d8e91e46SDimitry Andric if (I == E)
1012145449b1SDimitry Andric return detail::NamedNodeOrError(Path, File);
1013d8e91e46SDimitry Andric return errc::no_such_file_or_directory;
1014d8e91e46SDimitry Andric }
1015d8e91e46SDimitry Andric
1016d8e91e46SDimitry Andric // If Node is HardLink then return the resolved file.
1017d8e91e46SDimitry Andric if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
1018d8e91e46SDimitry Andric if (I == E)
1019145449b1SDimitry Andric return detail::NamedNodeOrError(Path, &File->getResolvedFile());
1020d8e91e46SDimitry Andric return errc::no_such_file_or_directory;
1021d8e91e46SDimitry Andric }
1022d8e91e46SDimitry Andric // Traverse directories.
1023d8e91e46SDimitry Andric Dir = cast<detail::InMemoryDirectory>(Node);
1024d8e91e46SDimitry Andric if (I == E)
1025145449b1SDimitry Andric return detail::NamedNodeOrError(Path, Dir);
1026d8e91e46SDimitry Andric }
1027d8e91e46SDimitry Andric }
1028d8e91e46SDimitry Andric
addHardLink(const Twine & NewLink,const Twine & Target)1029145449b1SDimitry Andric bool InMemoryFileSystem::addHardLink(const Twine &NewLink,
1030145449b1SDimitry Andric const Twine &Target) {
1031145449b1SDimitry Andric auto NewLinkNode = lookupNode(NewLink, /*FollowFinalSymlink=*/false);
1032145449b1SDimitry Andric // Whether symlinks in the hardlink target are followed is
1033145449b1SDimitry Andric // implementation-defined in POSIX.
1034145449b1SDimitry Andric // We're following symlinks here to be consistent with macOS.
1035145449b1SDimitry Andric auto TargetNode = lookupNode(Target, /*FollowFinalSymlink=*/true);
1036d8e91e46SDimitry Andric // FromPath must not have been added before. ToPath must have been added
1037d8e91e46SDimitry Andric // before. Resolved ToPath must be a File.
1038145449b1SDimitry Andric if (!TargetNode || NewLinkNode || !isa<detail::InMemoryFile>(*TargetNode))
1039d8e91e46SDimitry Andric return false;
1040e3b55780SDimitry Andric return addFile(NewLink, 0, nullptr, std::nullopt, std::nullopt, std::nullopt,
1041e3b55780SDimitry Andric std::nullopt, [&](detail::NewInMemoryNodeInfo NNI) {
10426f8fc217SDimitry Andric return std::make_unique<detail::InMemoryHardLink>(
1043145449b1SDimitry Andric NNI.Path.str(),
1044145449b1SDimitry Andric *cast<detail::InMemoryFile>(*TargetNode));
1045145449b1SDimitry Andric });
1046145449b1SDimitry Andric }
1047145449b1SDimitry Andric
addSymbolicLink(const Twine & NewLink,const Twine & Target,time_t ModificationTime,std::optional<uint32_t> User,std::optional<uint32_t> Group,std::optional<llvm::sys::fs::perms> Perms)1048e3b55780SDimitry Andric bool InMemoryFileSystem::addSymbolicLink(
1049e3b55780SDimitry Andric const Twine &NewLink, const Twine &Target, time_t ModificationTime,
1050e3b55780SDimitry Andric std::optional<uint32_t> User, std::optional<uint32_t> Group,
1051e3b55780SDimitry Andric std::optional<llvm::sys::fs::perms> Perms) {
1052145449b1SDimitry Andric auto NewLinkNode = lookupNode(NewLink, /*FollowFinalSymlink=*/false);
1053145449b1SDimitry Andric if (NewLinkNode)
1054145449b1SDimitry Andric return false;
1055145449b1SDimitry Andric
1056145449b1SDimitry Andric SmallString<128> NewLinkStr, TargetStr;
1057145449b1SDimitry Andric NewLink.toVector(NewLinkStr);
1058145449b1SDimitry Andric Target.toVector(TargetStr);
1059145449b1SDimitry Andric
1060145449b1SDimitry Andric return addFile(NewLinkStr, ModificationTime, nullptr, User, Group,
1061145449b1SDimitry Andric sys::fs::file_type::symlink_file, Perms,
1062145449b1SDimitry Andric [&](detail::NewInMemoryNodeInfo NNI) {
1063145449b1SDimitry Andric return std::make_unique<detail::InMemorySymbolicLink>(
1064145449b1SDimitry Andric NewLinkStr, TargetStr, NNI.makeStatus());
10656f8fc217SDimitry Andric });
1066d8e91e46SDimitry Andric }
1067d8e91e46SDimitry Andric
status(const Twine & Path)1068d8e91e46SDimitry Andric llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
1069145449b1SDimitry Andric auto Node = lookupNode(Path, /*FollowFinalSymlink=*/true);
1070d8e91e46SDimitry Andric if (Node)
10716f8fc217SDimitry Andric return (*Node)->getStatus(Path);
1072d8e91e46SDimitry Andric return Node.getError();
1073d8e91e46SDimitry Andric }
1074d8e91e46SDimitry Andric
1075d8e91e46SDimitry Andric llvm::ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Path)1076d8e91e46SDimitry Andric InMemoryFileSystem::openFileForRead(const Twine &Path) {
1077145449b1SDimitry Andric auto Node = lookupNode(Path,/*FollowFinalSymlink=*/true);
1078d8e91e46SDimitry Andric if (!Node)
1079d8e91e46SDimitry Andric return Node.getError();
1080d8e91e46SDimitry Andric
1081d8e91e46SDimitry Andric // When we have a file provide a heap-allocated wrapper for the memory buffer
1082d8e91e46SDimitry Andric // to match the ownership semantics for File.
1083d8e91e46SDimitry Andric if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
1084d8e91e46SDimitry Andric return std::unique_ptr<File>(
1085d8e91e46SDimitry Andric new detail::InMemoryFileAdaptor(*F, Path.str()));
1086d8e91e46SDimitry Andric
1087d8e91e46SDimitry Andric // FIXME: errc::not_a_file?
1088d8e91e46SDimitry Andric return make_error_code(llvm::errc::invalid_argument);
1089d8e91e46SDimitry Andric }
1090d8e91e46SDimitry Andric
1091d8e91e46SDimitry Andric /// Adaptor from InMemoryDir::iterator to directory_iterator.
1092145449b1SDimitry Andric class InMemoryFileSystem::DirIterator : public llvm::vfs::detail::DirIterImpl {
1093145449b1SDimitry Andric const InMemoryFileSystem *FS;
1094d8e91e46SDimitry Andric detail::InMemoryDirectory::const_iterator I;
1095d8e91e46SDimitry Andric detail::InMemoryDirectory::const_iterator E;
1096d8e91e46SDimitry Andric std::string RequestedDirName;
1097d8e91e46SDimitry Andric
setCurrentEntry()1098d8e91e46SDimitry Andric void setCurrentEntry() {
1099d8e91e46SDimitry Andric if (I != E) {
1100d8e91e46SDimitry Andric SmallString<256> Path(RequestedDirName);
1101d8e91e46SDimitry Andric llvm::sys::path::append(Path, I->second->getFileName());
1102706b4fc4SDimitry Andric sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1103d8e91e46SDimitry Andric switch (I->second->getKind()) {
1104d8e91e46SDimitry Andric case detail::IME_File:
1105d8e91e46SDimitry Andric case detail::IME_HardLink:
1106d8e91e46SDimitry Andric Type = sys::fs::file_type::regular_file;
1107d8e91e46SDimitry Andric break;
1108d8e91e46SDimitry Andric case detail::IME_Directory:
1109d8e91e46SDimitry Andric Type = sys::fs::file_type::directory_file;
1110d8e91e46SDimitry Andric break;
1111145449b1SDimitry Andric case detail::IME_SymbolicLink:
1112145449b1SDimitry Andric if (auto SymlinkTarget =
1113145449b1SDimitry Andric FS->lookupNode(Path, /*FollowFinalSymlink=*/true)) {
1114145449b1SDimitry Andric Path = SymlinkTarget.getName();
1115145449b1SDimitry Andric Type = (*SymlinkTarget)->getStatus(Path).getType();
1116145449b1SDimitry Andric }
1117145449b1SDimitry Andric break;
1118d8e91e46SDimitry Andric }
11194df029ccSDimitry Andric CurrentEntry = directory_entry(std::string(Path), Type);
1120d8e91e46SDimitry Andric } else {
1121d8e91e46SDimitry Andric // When we're at the end, make CurrentEntry invalid and DirIterImpl will
1122d8e91e46SDimitry Andric // do the rest.
1123d8e91e46SDimitry Andric CurrentEntry = directory_entry();
1124d8e91e46SDimitry Andric }
1125d8e91e46SDimitry Andric }
1126d8e91e46SDimitry Andric
1127d8e91e46SDimitry Andric public:
1128145449b1SDimitry Andric DirIterator() = default;
1129d8e91e46SDimitry Andric
DirIterator(const InMemoryFileSystem * FS,const detail::InMemoryDirectory & Dir,std::string RequestedDirName)1130145449b1SDimitry Andric DirIterator(const InMemoryFileSystem *FS,
1131145449b1SDimitry Andric const detail::InMemoryDirectory &Dir,
1132d8e91e46SDimitry Andric std::string RequestedDirName)
1133145449b1SDimitry Andric : FS(FS), I(Dir.begin()), E(Dir.end()),
1134d8e91e46SDimitry Andric RequestedDirName(std::move(RequestedDirName)) {
1135d8e91e46SDimitry Andric setCurrentEntry();
1136d8e91e46SDimitry Andric }
1137d8e91e46SDimitry Andric
increment()1138d8e91e46SDimitry Andric std::error_code increment() override {
1139d8e91e46SDimitry Andric ++I;
1140d8e91e46SDimitry Andric setCurrentEntry();
1141d8e91e46SDimitry Andric return {};
1142d8e91e46SDimitry Andric }
1143d8e91e46SDimitry Andric };
1144d8e91e46SDimitry Andric
dir_begin(const Twine & Dir,std::error_code & EC)1145d8e91e46SDimitry Andric directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
1146d8e91e46SDimitry Andric std::error_code &EC) {
1147145449b1SDimitry Andric auto Node = lookupNode(Dir, /*FollowFinalSymlink=*/true);
1148d8e91e46SDimitry Andric if (!Node) {
1149d8e91e46SDimitry Andric EC = Node.getError();
1150145449b1SDimitry Andric return directory_iterator(std::make_shared<DirIterator>());
1151d8e91e46SDimitry Andric }
1152d8e91e46SDimitry Andric
1153d8e91e46SDimitry Andric if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
1154d8e91e46SDimitry Andric return directory_iterator(
1155145449b1SDimitry Andric std::make_shared<DirIterator>(this, *DirNode, Dir.str()));
1156d8e91e46SDimitry Andric
1157d8e91e46SDimitry Andric EC = make_error_code(llvm::errc::not_a_directory);
1158145449b1SDimitry Andric return directory_iterator(std::make_shared<DirIterator>());
1159d8e91e46SDimitry Andric }
1160d8e91e46SDimitry Andric
setCurrentWorkingDirectory(const Twine & P)1161d8e91e46SDimitry Andric std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
1162d8e91e46SDimitry Andric SmallString<128> Path;
1163d8e91e46SDimitry Andric P.toVector(Path);
1164d8e91e46SDimitry Andric
1165d8e91e46SDimitry Andric // Fix up relative paths. This just prepends the current working directory.
1166d8e91e46SDimitry Andric std::error_code EC = makeAbsolute(Path);
1167d8e91e46SDimitry Andric assert(!EC);
1168d8e91e46SDimitry Andric (void)EC;
1169d8e91e46SDimitry Andric
1170d8e91e46SDimitry Andric if (useNormalizedPaths())
1171d8e91e46SDimitry Andric llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1172d8e91e46SDimitry Andric
1173d8e91e46SDimitry Andric if (!Path.empty())
11744df029ccSDimitry Andric WorkingDirectory = std::string(Path);
1175d8e91e46SDimitry Andric return {};
1176d8e91e46SDimitry Andric }
1177d8e91e46SDimitry Andric
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output)1178ac9a064cSDimitry Andric std::error_code InMemoryFileSystem::getRealPath(const Twine &Path,
1179ac9a064cSDimitry Andric SmallVectorImpl<char> &Output) {
1180d8e91e46SDimitry Andric auto CWD = getCurrentWorkingDirectory();
1181d8e91e46SDimitry Andric if (!CWD || CWD->empty())
1182d8e91e46SDimitry Andric return errc::operation_not_permitted;
1183d8e91e46SDimitry Andric Path.toVector(Output);
1184d8e91e46SDimitry Andric if (auto EC = makeAbsolute(Output))
1185d8e91e46SDimitry Andric return EC;
1186d8e91e46SDimitry Andric llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
1187d8e91e46SDimitry Andric return {};
1188d8e91e46SDimitry Andric }
1189d8e91e46SDimitry Andric
isLocal(const Twine & Path,bool & Result)1190d8e91e46SDimitry Andric std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
1191d8e91e46SDimitry Andric Result = false;
1192d8e91e46SDimitry Andric return {};
1193d8e91e46SDimitry Andric }
1194d8e91e46SDimitry Andric
printImpl(raw_ostream & OS,PrintType PrintContents,unsigned IndentLevel) const1195145449b1SDimitry Andric void InMemoryFileSystem::printImpl(raw_ostream &OS, PrintType PrintContents,
1196145449b1SDimitry Andric unsigned IndentLevel) const {
1197145449b1SDimitry Andric printIndent(OS, IndentLevel);
1198145449b1SDimitry Andric OS << "InMemoryFileSystem\n";
1199145449b1SDimitry Andric }
1200145449b1SDimitry Andric
1201d8e91e46SDimitry Andric } // namespace vfs
1202d8e91e46SDimitry Andric } // namespace llvm
1203d8e91e46SDimitry Andric
1204d8e91e46SDimitry Andric //===-----------------------------------------------------------------------===/
1205d8e91e46SDimitry Andric // RedirectingFileSystem implementation
1206d8e91e46SDimitry Andric //===-----------------------------------------------------------------------===/
1207d8e91e46SDimitry Andric
1208cfca06d7SDimitry Andric namespace {
1209cfca06d7SDimitry Andric
getExistingStyle(llvm::StringRef Path)1210344a3780SDimitry Andric static llvm::sys::path::Style getExistingStyle(llvm::StringRef Path) {
1211344a3780SDimitry Andric // Detect the path style in use by checking the first separator.
1212cfca06d7SDimitry Andric llvm::sys::path::Style style = llvm::sys::path::Style::native;
1213cfca06d7SDimitry Andric const size_t n = Path.find_first_of("/\\");
1214c0981da4SDimitry Andric // Can't distinguish between posix and windows_slash here.
1215cfca06d7SDimitry Andric if (n != static_cast<size_t>(-1))
1216cfca06d7SDimitry Andric style = (Path[n] == '/') ? llvm::sys::path::Style::posix
1217c0981da4SDimitry Andric : llvm::sys::path::Style::windows_backslash;
1218344a3780SDimitry Andric return style;
1219344a3780SDimitry Andric }
1220344a3780SDimitry Andric
1221344a3780SDimitry Andric /// Removes leading "./" as well as path components like ".." and ".".
canonicalize(llvm::StringRef Path)1222344a3780SDimitry Andric static llvm::SmallString<256> canonicalize(llvm::StringRef Path) {
1223344a3780SDimitry Andric // First detect the path style in use by checking the first separator.
1224344a3780SDimitry Andric llvm::sys::path::Style style = getExistingStyle(Path);
1225cfca06d7SDimitry Andric
1226cfca06d7SDimitry Andric // Now remove the dots. Explicitly specifying the path style prevents the
1227cfca06d7SDimitry Andric // direction of the slashes from changing.
1228cfca06d7SDimitry Andric llvm::SmallString<256> result =
1229cfca06d7SDimitry Andric llvm::sys::path::remove_leading_dotslash(Path, style);
1230cfca06d7SDimitry Andric llvm::sys::path::remove_dots(result, /*remove_dot_dot=*/true, style);
1231cfca06d7SDimitry Andric return result;
1232cfca06d7SDimitry Andric }
1233cfca06d7SDimitry Andric
1234145449b1SDimitry Andric /// Whether the error and entry specify a file/directory that was not found.
isFileNotFound(std::error_code EC,RedirectingFileSystem::Entry * E=nullptr)1235145449b1SDimitry Andric static bool isFileNotFound(std::error_code EC,
1236145449b1SDimitry Andric RedirectingFileSystem::Entry *E = nullptr) {
1237145449b1SDimitry Andric if (E && !isa<RedirectingFileSystem::DirectoryRemapEntry>(E))
1238145449b1SDimitry Andric return false;
1239145449b1SDimitry Andric return EC == llvm::errc::no_such_file_or_directory;
1240145449b1SDimitry Andric }
1241145449b1SDimitry Andric
1242cfca06d7SDimitry Andric } // anonymous namespace
1243cfca06d7SDimitry Andric
1244cfca06d7SDimitry Andric
RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)12451d5ae102SDimitry Andric RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
12461d5ae102SDimitry Andric : ExternalFS(std::move(FS)) {
12471d5ae102SDimitry Andric if (ExternalFS)
12481d5ae102SDimitry Andric if (auto ExternalWorkingDirectory =
12491d5ae102SDimitry Andric ExternalFS->getCurrentWorkingDirectory()) {
12501d5ae102SDimitry Andric WorkingDirectory = *ExternalWorkingDirectory;
12511d5ae102SDimitry Andric }
12521d5ae102SDimitry Andric }
12531d5ae102SDimitry Andric
1254344a3780SDimitry Andric /// Directory iterator implementation for \c RedirectingFileSystem's
1255344a3780SDimitry Andric /// directory entries.
1256344a3780SDimitry Andric class llvm::vfs::RedirectingFSDirIterImpl
1257d8e91e46SDimitry Andric : public llvm::vfs::detail::DirIterImpl {
1258d8e91e46SDimitry Andric std::string Dir;
1259344a3780SDimitry Andric RedirectingFileSystem::DirectoryEntry::iterator Current, End;
1260d8e91e46SDimitry Andric
incrementImpl(bool IsFirstTime)1261344a3780SDimitry Andric std::error_code incrementImpl(bool IsFirstTime) {
1262344a3780SDimitry Andric assert((IsFirstTime || Current != End) && "cannot iterate past end");
1263344a3780SDimitry Andric if (!IsFirstTime)
1264344a3780SDimitry Andric ++Current;
1265344a3780SDimitry Andric if (Current != End) {
1266344a3780SDimitry Andric SmallString<128> PathStr(Dir);
1267344a3780SDimitry Andric llvm::sys::path::append(PathStr, (*Current)->getName());
1268344a3780SDimitry Andric sys::fs::file_type Type = sys::fs::file_type::type_unknown;
1269344a3780SDimitry Andric switch ((*Current)->getKind()) {
1270344a3780SDimitry Andric case RedirectingFileSystem::EK_Directory:
1271e3b55780SDimitry Andric [[fallthrough]];
1272344a3780SDimitry Andric case RedirectingFileSystem::EK_DirectoryRemap:
1273344a3780SDimitry Andric Type = sys::fs::file_type::directory_file;
1274344a3780SDimitry Andric break;
1275344a3780SDimitry Andric case RedirectingFileSystem::EK_File:
1276344a3780SDimitry Andric Type = sys::fs::file_type::regular_file;
1277344a3780SDimitry Andric break;
1278344a3780SDimitry Andric }
12794df029ccSDimitry Andric CurrentEntry = directory_entry(std::string(PathStr), Type);
1280344a3780SDimitry Andric } else {
1281344a3780SDimitry Andric CurrentEntry = directory_entry();
1282344a3780SDimitry Andric }
1283344a3780SDimitry Andric return {};
1284344a3780SDimitry Andric };
1285d8e91e46SDimitry Andric
1286d8e91e46SDimitry Andric public:
RedirectingFSDirIterImpl(const Twine & Path,RedirectingFileSystem::DirectoryEntry::iterator Begin,RedirectingFileSystem::DirectoryEntry::iterator End,std::error_code & EC)1287344a3780SDimitry Andric RedirectingFSDirIterImpl(
1288344a3780SDimitry Andric const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin,
1289344a3780SDimitry Andric RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC)
1290344a3780SDimitry Andric : Dir(Path.str()), Current(Begin), End(End) {
1291344a3780SDimitry Andric EC = incrementImpl(/*IsFirstTime=*/true);
1292344a3780SDimitry Andric }
1293d8e91e46SDimitry Andric
increment()1294344a3780SDimitry Andric std::error_code increment() override {
1295344a3780SDimitry Andric return incrementImpl(/*IsFirstTime=*/false);
1296344a3780SDimitry Andric }
1297344a3780SDimitry Andric };
1298344a3780SDimitry Andric
1299c0981da4SDimitry Andric namespace {
1300344a3780SDimitry Andric /// Directory iterator implementation for \c RedirectingFileSystem's
1301344a3780SDimitry Andric /// directory remap entries that maps the paths reported by the external
1302344a3780SDimitry Andric /// file system's directory iterator back to the virtual directory's path.
1303344a3780SDimitry Andric class RedirectingFSDirRemapIterImpl : public llvm::vfs::detail::DirIterImpl {
1304344a3780SDimitry Andric std::string Dir;
1305344a3780SDimitry Andric llvm::sys::path::Style DirStyle;
1306344a3780SDimitry Andric llvm::vfs::directory_iterator ExternalIter;
1307344a3780SDimitry Andric
1308344a3780SDimitry Andric public:
RedirectingFSDirRemapIterImpl(std::string DirPath,llvm::vfs::directory_iterator ExtIter)1309344a3780SDimitry Andric RedirectingFSDirRemapIterImpl(std::string DirPath,
1310344a3780SDimitry Andric llvm::vfs::directory_iterator ExtIter)
1311344a3780SDimitry Andric : Dir(std::move(DirPath)), DirStyle(getExistingStyle(Dir)),
1312344a3780SDimitry Andric ExternalIter(ExtIter) {
1313344a3780SDimitry Andric if (ExternalIter != llvm::vfs::directory_iterator())
1314344a3780SDimitry Andric setCurrentEntry();
1315344a3780SDimitry Andric }
1316344a3780SDimitry Andric
setCurrentEntry()1317344a3780SDimitry Andric void setCurrentEntry() {
1318344a3780SDimitry Andric StringRef ExternalPath = ExternalIter->path();
1319344a3780SDimitry Andric llvm::sys::path::Style ExternalStyle = getExistingStyle(ExternalPath);
1320344a3780SDimitry Andric StringRef File = llvm::sys::path::filename(ExternalPath, ExternalStyle);
1321344a3780SDimitry Andric
1322344a3780SDimitry Andric SmallString<128> NewPath(Dir);
1323344a3780SDimitry Andric llvm::sys::path::append(NewPath, DirStyle, File);
1324344a3780SDimitry Andric
1325344a3780SDimitry Andric CurrentEntry = directory_entry(std::string(NewPath), ExternalIter->type());
1326344a3780SDimitry Andric }
1327344a3780SDimitry Andric
increment()1328344a3780SDimitry Andric std::error_code increment() override {
1329344a3780SDimitry Andric std::error_code EC;
1330344a3780SDimitry Andric ExternalIter.increment(EC);
1331344a3780SDimitry Andric if (!EC && ExternalIter != llvm::vfs::directory_iterator())
1332344a3780SDimitry Andric setCurrentEntry();
1333344a3780SDimitry Andric else
1334344a3780SDimitry Andric CurrentEntry = directory_entry();
1335344a3780SDimitry Andric return EC;
1336344a3780SDimitry Andric }
1337d8e91e46SDimitry Andric };
1338c0981da4SDimitry Andric } // namespace
1339d8e91e46SDimitry Andric
1340d8e91e46SDimitry Andric llvm::ErrorOr<std::string>
getCurrentWorkingDirectory() const1341d8e91e46SDimitry Andric RedirectingFileSystem::getCurrentWorkingDirectory() const {
13421d5ae102SDimitry Andric return WorkingDirectory;
1343d8e91e46SDimitry Andric }
1344d8e91e46SDimitry Andric
1345d8e91e46SDimitry Andric std::error_code
setCurrentWorkingDirectory(const Twine & Path)1346d8e91e46SDimitry Andric RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
13471d5ae102SDimitry Andric // Don't change the working directory if the path doesn't exist.
13481d5ae102SDimitry Andric if (!exists(Path))
13491d5ae102SDimitry Andric return errc::no_such_file_or_directory;
13501d5ae102SDimitry Andric
13511d5ae102SDimitry Andric SmallString<128> AbsolutePath;
13521d5ae102SDimitry Andric Path.toVector(AbsolutePath);
13531d5ae102SDimitry Andric if (std::error_code EC = makeAbsolute(AbsolutePath))
13541d5ae102SDimitry Andric return EC;
13554df029ccSDimitry Andric WorkingDirectory = std::string(AbsolutePath);
13561d5ae102SDimitry Andric return {};
1357d8e91e46SDimitry Andric }
1358d8e91e46SDimitry Andric
isLocal(const Twine & Path_,bool & Result)1359b60736ecSDimitry Andric std::error_code RedirectingFileSystem::isLocal(const Twine &Path_,
1360d8e91e46SDimitry Andric bool &Result) {
1361b60736ecSDimitry Andric SmallString<256> Path;
1362b60736ecSDimitry Andric Path_.toVector(Path);
1363b60736ecSDimitry Andric
1364ac9a064cSDimitry Andric if (makeAbsolute(Path))
1365b60736ecSDimitry Andric return {};
1366b60736ecSDimitry Andric
1367d8e91e46SDimitry Andric return ExternalFS->isLocal(Path, Result);
1368d8e91e46SDimitry Andric }
1369d8e91e46SDimitry Andric
makeAbsolute(SmallVectorImpl<char> & Path) const1370706b4fc4SDimitry Andric std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
1371c0981da4SDimitry Andric // is_absolute(..., Style::windows_*) accepts paths with both slash types.
1372706b4fc4SDimitry Andric if (llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::posix) ||
1373c0981da4SDimitry Andric llvm::sys::path::is_absolute(Path,
1374c0981da4SDimitry Andric llvm::sys::path::Style::windows_backslash))
1375e3b55780SDimitry Andric // This covers windows absolute path with forward slash as well, as the
1376ac9a064cSDimitry Andric // forward slashes are treated as path separation in llvm::path
1377e3b55780SDimitry Andric // regardless of what path::Style is used.
1378706b4fc4SDimitry Andric return {};
1379706b4fc4SDimitry Andric
1380706b4fc4SDimitry Andric auto WorkingDir = getCurrentWorkingDirectory();
1381706b4fc4SDimitry Andric if (!WorkingDir)
1382706b4fc4SDimitry Andric return WorkingDir.getError();
1383706b4fc4SDimitry Andric
1384e3b55780SDimitry Andric return makeAbsolute(WorkingDir.get(), Path);
1385e3b55780SDimitry Andric }
1386e3b55780SDimitry Andric
1387e3b55780SDimitry Andric std::error_code
makeAbsolute(StringRef WorkingDir,SmallVectorImpl<char> & Path) const1388e3b55780SDimitry Andric RedirectingFileSystem::makeAbsolute(StringRef WorkingDir,
1389e3b55780SDimitry Andric SmallVectorImpl<char> &Path) const {
1390cfca06d7SDimitry Andric // We can't use sys::fs::make_absolute because that assumes the path style
1391cfca06d7SDimitry Andric // is native and there is no way to override that. Since we know WorkingDir
1392cfca06d7SDimitry Andric // is absolute, we can use it to determine which style we actually have and
1393cfca06d7SDimitry Andric // append Path ourselves.
1394e3b55780SDimitry Andric if (!WorkingDir.empty() &&
1395e3b55780SDimitry Andric !sys::path::is_absolute(WorkingDir, sys::path::Style::posix) &&
1396e3b55780SDimitry Andric !sys::path::is_absolute(WorkingDir,
1397e3b55780SDimitry Andric sys::path::Style::windows_backslash)) {
1398e3b55780SDimitry Andric return std::error_code();
1399e3b55780SDimitry Andric }
1400c0981da4SDimitry Andric sys::path::Style style = sys::path::Style::windows_backslash;
1401e3b55780SDimitry Andric if (sys::path::is_absolute(WorkingDir, sys::path::Style::posix)) {
1402cfca06d7SDimitry Andric style = sys::path::Style::posix;
1403c0981da4SDimitry Andric } else {
1404c0981da4SDimitry Andric // Distinguish between windows_backslash and windows_slash; getExistingStyle
1405c0981da4SDimitry Andric // returns posix for a path with windows_slash.
1406e3b55780SDimitry Andric if (getExistingStyle(WorkingDir) != sys::path::Style::windows_backslash)
1407c0981da4SDimitry Andric style = sys::path::Style::windows_slash;
1408cfca06d7SDimitry Andric }
1409cfca06d7SDimitry Andric
1410e3b55780SDimitry Andric std::string Result = std::string(WorkingDir);
1411cfca06d7SDimitry Andric StringRef Dir(Result);
1412b1c73532SDimitry Andric if (!Dir.ends_with(sys::path::get_separator(style))) {
1413cfca06d7SDimitry Andric Result += sys::path::get_separator(style);
1414cfca06d7SDimitry Andric }
1415e3b55780SDimitry Andric // backslashes '\' are legit path charactors under POSIX. Windows APIs
1416e3b55780SDimitry Andric // like CreateFile accepts forward slashes '/' as path
1417e3b55780SDimitry Andric // separator (even when mixed with backslashes). Therefore,
1418e3b55780SDimitry Andric // `Path` should be directly appended to `WorkingDir` without converting
1419e3b55780SDimitry Andric // path separator.
1420cfca06d7SDimitry Andric Result.append(Path.data(), Path.size());
1421cfca06d7SDimitry Andric Path.assign(Result.begin(), Result.end());
1422cfca06d7SDimitry Andric
1423706b4fc4SDimitry Andric return {};
1424706b4fc4SDimitry Andric }
1425706b4fc4SDimitry Andric
dir_begin(const Twine & Dir,std::error_code & EC)1426d8e91e46SDimitry Andric directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
1427d8e91e46SDimitry Andric std::error_code &EC) {
1428b60736ecSDimitry Andric SmallString<256> Path;
1429b60736ecSDimitry Andric Dir.toVector(Path);
1430b60736ecSDimitry Andric
1431ac9a064cSDimitry Andric EC = makeAbsolute(Path);
1432b60736ecSDimitry Andric if (EC)
1433b60736ecSDimitry Andric return {};
1434b60736ecSDimitry Andric
1435344a3780SDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
1436344a3780SDimitry Andric if (!Result) {
1437145449b1SDimitry Andric if (Redirection != RedirectKind::RedirectOnly &&
1438145449b1SDimitry Andric isFileNotFound(Result.getError()))
1439b60736ecSDimitry Andric return ExternalFS->dir_begin(Path, EC);
1440145449b1SDimitry Andric
1441145449b1SDimitry Andric EC = Result.getError();
1442d8e91e46SDimitry Andric return {};
1443d8e91e46SDimitry Andric }
1444344a3780SDimitry Andric
1445344a3780SDimitry Andric // Use status to make sure the path exists and refers to a directory.
1446c0981da4SDimitry Andric ErrorOr<Status> S = status(Path, Dir, *Result);
1447d8e91e46SDimitry Andric if (!S) {
1448145449b1SDimitry Andric if (Redirection != RedirectKind::RedirectOnly &&
1449145449b1SDimitry Andric isFileNotFound(S.getError(), Result->E))
1450344a3780SDimitry Andric return ExternalFS->dir_begin(Dir, EC);
1451145449b1SDimitry Andric
1452d8e91e46SDimitry Andric EC = S.getError();
1453d8e91e46SDimitry Andric return {};
1454d8e91e46SDimitry Andric }
1455145449b1SDimitry Andric
1456d8e91e46SDimitry Andric if (!S->isDirectory()) {
1457145449b1SDimitry Andric EC = errc::not_a_directory;
1458d8e91e46SDimitry Andric return {};
1459d8e91e46SDimitry Andric }
1460d8e91e46SDimitry Andric
1461344a3780SDimitry Andric // Create the appropriate directory iterator based on whether we found a
1462344a3780SDimitry Andric // DirectoryRemapEntry or DirectoryEntry.
1463145449b1SDimitry Andric directory_iterator RedirectIter;
1464145449b1SDimitry Andric std::error_code RedirectEC;
1465344a3780SDimitry Andric if (auto ExtRedirect = Result->getExternalRedirect()) {
1466344a3780SDimitry Andric auto RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
1467145449b1SDimitry Andric RedirectIter = ExternalFS->dir_begin(*ExtRedirect, RedirectEC);
1468344a3780SDimitry Andric
1469344a3780SDimitry Andric if (!RE->useExternalName(UseExternalNames)) {
1470344a3780SDimitry Andric // Update the paths in the results to use the virtual directory's path.
1471145449b1SDimitry Andric RedirectIter =
1472344a3780SDimitry Andric directory_iterator(std::make_shared<RedirectingFSDirRemapIterImpl>(
1473145449b1SDimitry Andric std::string(Path), RedirectIter));
1474344a3780SDimitry Andric }
1475344a3780SDimitry Andric } else {
1476344a3780SDimitry Andric auto DE = cast<DirectoryEntry>(Result->E);
1477145449b1SDimitry Andric RedirectIter =
1478145449b1SDimitry Andric directory_iterator(std::make_shared<RedirectingFSDirIterImpl>(
1479145449b1SDimitry Andric Path, DE->contents_begin(), DE->contents_end(), RedirectEC));
1480344a3780SDimitry Andric }
1481344a3780SDimitry Andric
1482145449b1SDimitry Andric if (RedirectEC) {
1483145449b1SDimitry Andric if (RedirectEC != errc::no_such_file_or_directory) {
1484145449b1SDimitry Andric EC = RedirectEC;
1485145449b1SDimitry Andric return {};
1486145449b1SDimitry Andric }
1487145449b1SDimitry Andric RedirectIter = {};
1488145449b1SDimitry Andric }
1489145449b1SDimitry Andric
1490145449b1SDimitry Andric if (Redirection == RedirectKind::RedirectOnly) {
1491145449b1SDimitry Andric EC = RedirectEC;
1492145449b1SDimitry Andric return RedirectIter;
1493145449b1SDimitry Andric }
1494145449b1SDimitry Andric
1495145449b1SDimitry Andric std::error_code ExternalEC;
1496145449b1SDimitry Andric directory_iterator ExternalIter = ExternalFS->dir_begin(Path, ExternalEC);
1497145449b1SDimitry Andric if (ExternalEC) {
1498145449b1SDimitry Andric if (ExternalEC != errc::no_such_file_or_directory) {
1499145449b1SDimitry Andric EC = ExternalEC;
1500145449b1SDimitry Andric return {};
1501145449b1SDimitry Andric }
1502145449b1SDimitry Andric ExternalIter = {};
1503145449b1SDimitry Andric }
1504145449b1SDimitry Andric
1505145449b1SDimitry Andric SmallVector<directory_iterator, 2> Iters;
1506145449b1SDimitry Andric switch (Redirection) {
1507145449b1SDimitry Andric case RedirectKind::Fallthrough:
1508145449b1SDimitry Andric Iters.push_back(ExternalIter);
1509145449b1SDimitry Andric Iters.push_back(RedirectIter);
1510145449b1SDimitry Andric break;
1511145449b1SDimitry Andric case RedirectKind::Fallback:
1512145449b1SDimitry Andric Iters.push_back(RedirectIter);
1513145449b1SDimitry Andric Iters.push_back(ExternalIter);
1514145449b1SDimitry Andric break;
1515145449b1SDimitry Andric default:
1516145449b1SDimitry Andric llvm_unreachable("unhandled RedirectKind");
1517145449b1SDimitry Andric }
1518145449b1SDimitry Andric
1519145449b1SDimitry Andric directory_iterator Combined{
1520145449b1SDimitry Andric std::make_shared<CombiningDirIterImpl>(Iters, EC)};
1521145449b1SDimitry Andric if (EC)
1522145449b1SDimitry Andric return {};
1523145449b1SDimitry Andric return Combined;
1524d8e91e46SDimitry Andric }
1525d8e91e46SDimitry Andric
setOverlayFileDir(StringRef Dir)1526e3b55780SDimitry Andric void RedirectingFileSystem::setOverlayFileDir(StringRef Dir) {
1527e3b55780SDimitry Andric OverlayFileDir = Dir.str();
1528d8e91e46SDimitry Andric }
1529d8e91e46SDimitry Andric
getOverlayFileDir() const1530e3b55780SDimitry Andric StringRef RedirectingFileSystem::getOverlayFileDir() const {
1531e3b55780SDimitry Andric return OverlayFileDir;
1532d8e91e46SDimitry Andric }
1533d8e91e46SDimitry Andric
setFallthrough(bool Fallthrough)1534b60736ecSDimitry Andric void RedirectingFileSystem::setFallthrough(bool Fallthrough) {
1535145449b1SDimitry Andric if (Fallthrough) {
1536145449b1SDimitry Andric Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
1537145449b1SDimitry Andric } else {
1538145449b1SDimitry Andric Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
1539145449b1SDimitry Andric }
1540145449b1SDimitry Andric }
1541145449b1SDimitry Andric
setRedirection(RedirectingFileSystem::RedirectKind Kind)1542145449b1SDimitry Andric void RedirectingFileSystem::setRedirection(
1543145449b1SDimitry Andric RedirectingFileSystem::RedirectKind Kind) {
1544145449b1SDimitry Andric Redirection = Kind;
1545b60736ecSDimitry Andric }
1546b60736ecSDimitry Andric
getRoots() const1547b60736ecSDimitry Andric std::vector<StringRef> RedirectingFileSystem::getRoots() const {
1548b60736ecSDimitry Andric std::vector<StringRef> R;
1549e3b55780SDimitry Andric R.reserve(Roots.size());
1550b60736ecSDimitry Andric for (const auto &Root : Roots)
1551b60736ecSDimitry Andric R.push_back(Root->getName());
1552b60736ecSDimitry Andric return R;
1553b60736ecSDimitry Andric }
1554b60736ecSDimitry Andric
printImpl(raw_ostream & OS,PrintType Type,unsigned IndentLevel) const1555145449b1SDimitry Andric void RedirectingFileSystem::printImpl(raw_ostream &OS, PrintType Type,
1556145449b1SDimitry Andric unsigned IndentLevel) const {
1557145449b1SDimitry Andric printIndent(OS, IndentLevel);
1558145449b1SDimitry Andric OS << "RedirectingFileSystem (UseExternalNames: "
1559145449b1SDimitry Andric << (UseExternalNames ? "true" : "false") << ")\n";
1560145449b1SDimitry Andric if (Type == PrintType::Summary)
1561145449b1SDimitry Andric return;
1562145449b1SDimitry Andric
1563d8e91e46SDimitry Andric for (const auto &Root : Roots)
1564145449b1SDimitry Andric printEntry(OS, Root.get(), IndentLevel);
1565145449b1SDimitry Andric
1566145449b1SDimitry Andric printIndent(OS, IndentLevel);
1567145449b1SDimitry Andric OS << "ExternalFS:\n";
1568145449b1SDimitry Andric ExternalFS->print(OS, Type == PrintType::Contents ? PrintType::Summary : Type,
1569145449b1SDimitry Andric IndentLevel + 1);
1570d8e91e46SDimitry Andric }
1571d8e91e46SDimitry Andric
printEntry(raw_ostream & OS,RedirectingFileSystem::Entry * E,unsigned IndentLevel) const1572145449b1SDimitry Andric void RedirectingFileSystem::printEntry(raw_ostream &OS,
15731d5ae102SDimitry Andric RedirectingFileSystem::Entry *E,
1574145449b1SDimitry Andric unsigned IndentLevel) const {
1575145449b1SDimitry Andric printIndent(OS, IndentLevel);
1576145449b1SDimitry Andric OS << "'" << E->getName() << "'";
1577d8e91e46SDimitry Andric
1578145449b1SDimitry Andric switch (E->getKind()) {
1579145449b1SDimitry Andric case EK_Directory: {
1580145449b1SDimitry Andric auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(E);
1581d8e91e46SDimitry Andric
1582145449b1SDimitry Andric OS << "\n";
1583d8e91e46SDimitry Andric for (std::unique_ptr<Entry> &SubEntry :
1584d8e91e46SDimitry Andric llvm::make_range(DE->contents_begin(), DE->contents_end()))
1585145449b1SDimitry Andric printEntry(OS, SubEntry.get(), IndentLevel + 1);
1586145449b1SDimitry Andric break;
1587145449b1SDimitry Andric }
1588145449b1SDimitry Andric case EK_DirectoryRemap:
1589145449b1SDimitry Andric case EK_File: {
1590145449b1SDimitry Andric auto *RE = cast<RedirectingFileSystem::RemapEntry>(E);
1591145449b1SDimitry Andric OS << " -> '" << RE->getExternalContentsPath() << "'";
1592145449b1SDimitry Andric switch (RE->getUseName()) {
1593145449b1SDimitry Andric case NK_NotSet:
1594145449b1SDimitry Andric break;
1595145449b1SDimitry Andric case NK_External:
1596145449b1SDimitry Andric OS << " (UseExternalName: true)";
1597145449b1SDimitry Andric break;
1598145449b1SDimitry Andric case NK_Virtual:
1599145449b1SDimitry Andric OS << " (UseExternalName: false)";
1600145449b1SDimitry Andric break;
1601145449b1SDimitry Andric }
1602145449b1SDimitry Andric OS << "\n";
1603145449b1SDimitry Andric break;
1604d8e91e46SDimitry Andric }
1605d8e91e46SDimitry Andric }
1606145449b1SDimitry Andric }
1607d8e91e46SDimitry Andric
visitChildFileSystems(VisitCallbackTy Callback)1608ac9a064cSDimitry Andric void RedirectingFileSystem::visitChildFileSystems(VisitCallbackTy Callback) {
1609ac9a064cSDimitry Andric if (ExternalFS) {
1610ac9a064cSDimitry Andric Callback(*ExternalFS);
1611ac9a064cSDimitry Andric ExternalFS->visitChildFileSystems(Callback);
1612ac9a064cSDimitry Andric }
1613ac9a064cSDimitry Andric }
1614ac9a064cSDimitry Andric
1615d8e91e46SDimitry Andric /// A helper class to hold the common YAML parsing state.
1616d8e91e46SDimitry Andric class llvm::vfs::RedirectingFileSystemParser {
1617d8e91e46SDimitry Andric yaml::Stream &Stream;
1618d8e91e46SDimitry Andric
error(yaml::Node * N,const Twine & Msg)1619d8e91e46SDimitry Andric void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1620d8e91e46SDimitry Andric
1621d8e91e46SDimitry Andric // false on error
parseScalarString(yaml::Node * N,StringRef & Result,SmallVectorImpl<char> & Storage)1622d8e91e46SDimitry Andric bool parseScalarString(yaml::Node *N, StringRef &Result,
1623d8e91e46SDimitry Andric SmallVectorImpl<char> &Storage) {
1624d8e91e46SDimitry Andric const auto *S = dyn_cast<yaml::ScalarNode>(N);
1625d8e91e46SDimitry Andric
1626d8e91e46SDimitry Andric if (!S) {
1627d8e91e46SDimitry Andric error(N, "expected string");
1628d8e91e46SDimitry Andric return false;
1629d8e91e46SDimitry Andric }
1630d8e91e46SDimitry Andric Result = S->getValue(Storage);
1631d8e91e46SDimitry Andric return true;
1632d8e91e46SDimitry Andric }
1633d8e91e46SDimitry Andric
1634d8e91e46SDimitry Andric // false on error
parseScalarBool(yaml::Node * N,bool & Result)1635d8e91e46SDimitry Andric bool parseScalarBool(yaml::Node *N, bool &Result) {
1636d8e91e46SDimitry Andric SmallString<5> Storage;
1637d8e91e46SDimitry Andric StringRef Value;
1638d8e91e46SDimitry Andric if (!parseScalarString(N, Value, Storage))
1639d8e91e46SDimitry Andric return false;
1640d8e91e46SDimitry Andric
1641344a3780SDimitry Andric if (Value.equals_insensitive("true") || Value.equals_insensitive("on") ||
1642344a3780SDimitry Andric Value.equals_insensitive("yes") || Value == "1") {
1643d8e91e46SDimitry Andric Result = true;
1644d8e91e46SDimitry Andric return true;
1645344a3780SDimitry Andric } else if (Value.equals_insensitive("false") ||
1646344a3780SDimitry Andric Value.equals_insensitive("off") ||
1647344a3780SDimitry Andric Value.equals_insensitive("no") || Value == "0") {
1648d8e91e46SDimitry Andric Result = false;
1649d8e91e46SDimitry Andric return true;
1650d8e91e46SDimitry Andric }
1651d8e91e46SDimitry Andric
1652d8e91e46SDimitry Andric error(N, "expected boolean value");
1653d8e91e46SDimitry Andric return false;
1654d8e91e46SDimitry Andric }
1655d8e91e46SDimitry Andric
1656e3b55780SDimitry Andric std::optional<RedirectingFileSystem::RedirectKind>
parseRedirectKind(yaml::Node * N)1657145449b1SDimitry Andric parseRedirectKind(yaml::Node *N) {
1658145449b1SDimitry Andric SmallString<12> Storage;
1659145449b1SDimitry Andric StringRef Value;
1660145449b1SDimitry Andric if (!parseScalarString(N, Value, Storage))
1661e3b55780SDimitry Andric return std::nullopt;
1662145449b1SDimitry Andric
1663145449b1SDimitry Andric if (Value.equals_insensitive("fallthrough")) {
1664145449b1SDimitry Andric return RedirectingFileSystem::RedirectKind::Fallthrough;
1665145449b1SDimitry Andric } else if (Value.equals_insensitive("fallback")) {
1666145449b1SDimitry Andric return RedirectingFileSystem::RedirectKind::Fallback;
1667145449b1SDimitry Andric } else if (Value.equals_insensitive("redirect-only")) {
1668145449b1SDimitry Andric return RedirectingFileSystem::RedirectKind::RedirectOnly;
1669145449b1SDimitry Andric }
1670e3b55780SDimitry Andric return std::nullopt;
1671e3b55780SDimitry Andric }
1672e3b55780SDimitry Andric
1673e3b55780SDimitry Andric std::optional<RedirectingFileSystem::RootRelativeKind>
parseRootRelativeKind(yaml::Node * N)1674e3b55780SDimitry Andric parseRootRelativeKind(yaml::Node *N) {
1675e3b55780SDimitry Andric SmallString<12> Storage;
1676e3b55780SDimitry Andric StringRef Value;
1677e3b55780SDimitry Andric if (!parseScalarString(N, Value, Storage))
1678e3b55780SDimitry Andric return std::nullopt;
1679e3b55780SDimitry Andric if (Value.equals_insensitive("cwd")) {
1680e3b55780SDimitry Andric return RedirectingFileSystem::RootRelativeKind::CWD;
1681e3b55780SDimitry Andric } else if (Value.equals_insensitive("overlay-dir")) {
1682e3b55780SDimitry Andric return RedirectingFileSystem::RootRelativeKind::OverlayDir;
1683e3b55780SDimitry Andric }
1684e3b55780SDimitry Andric return std::nullopt;
1685145449b1SDimitry Andric }
1686145449b1SDimitry Andric
1687d8e91e46SDimitry Andric struct KeyStatus {
1688d8e91e46SDimitry Andric bool Required;
1689d8e91e46SDimitry Andric bool Seen = false;
1690d8e91e46SDimitry Andric
KeyStatusllvm::vfs::RedirectingFileSystemParser::KeyStatus1691d8e91e46SDimitry Andric KeyStatus(bool Required = false) : Required(Required) {}
1692d8e91e46SDimitry Andric };
1693d8e91e46SDimitry Andric
1694d8e91e46SDimitry Andric using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1695d8e91e46SDimitry Andric
1696d8e91e46SDimitry Andric // false on error
checkDuplicateOrUnknownKey(yaml::Node * KeyNode,StringRef Key,DenseMap<StringRef,KeyStatus> & Keys)1697d8e91e46SDimitry Andric bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1698d8e91e46SDimitry Andric DenseMap<StringRef, KeyStatus> &Keys) {
1699d8e91e46SDimitry Andric if (!Keys.count(Key)) {
1700d8e91e46SDimitry Andric error(KeyNode, "unknown key");
1701d8e91e46SDimitry Andric return false;
1702d8e91e46SDimitry Andric }
1703d8e91e46SDimitry Andric KeyStatus &S = Keys[Key];
1704d8e91e46SDimitry Andric if (S.Seen) {
1705d8e91e46SDimitry Andric error(KeyNode, Twine("duplicate key '") + Key + "'");
1706d8e91e46SDimitry Andric return false;
1707d8e91e46SDimitry Andric }
1708d8e91e46SDimitry Andric S.Seen = true;
1709d8e91e46SDimitry Andric return true;
1710d8e91e46SDimitry Andric }
1711d8e91e46SDimitry Andric
1712d8e91e46SDimitry Andric // false on error
checkMissingKeys(yaml::Node * Obj,DenseMap<StringRef,KeyStatus> & Keys)1713d8e91e46SDimitry Andric bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1714d8e91e46SDimitry Andric for (const auto &I : Keys) {
1715d8e91e46SDimitry Andric if (I.second.Required && !I.second.Seen) {
1716d8e91e46SDimitry Andric error(Obj, Twine("missing key '") + I.first + "'");
1717d8e91e46SDimitry Andric return false;
1718d8e91e46SDimitry Andric }
1719d8e91e46SDimitry Andric }
1720d8e91e46SDimitry Andric return true;
1721d8e91e46SDimitry Andric }
1722d8e91e46SDimitry Andric
1723b60736ecSDimitry Andric public:
1724b60736ecSDimitry Andric static RedirectingFileSystem::Entry *
lookupOrCreateEntry(RedirectingFileSystem * FS,StringRef Name,RedirectingFileSystem::Entry * ParentEntry=nullptr)1725d8e91e46SDimitry Andric lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1726d8e91e46SDimitry Andric RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1727d8e91e46SDimitry Andric if (!ParentEntry) { // Look for a existent root
1728d8e91e46SDimitry Andric for (const auto &Root : FS->Roots) {
1729ac9a064cSDimitry Andric if (Name == Root->getName()) {
1730d8e91e46SDimitry Andric ParentEntry = Root.get();
1731d8e91e46SDimitry Andric return ParentEntry;
1732d8e91e46SDimitry Andric }
1733d8e91e46SDimitry Andric }
1734d8e91e46SDimitry Andric } else { // Advance to the next component
1735344a3780SDimitry Andric auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
1736d8e91e46SDimitry Andric for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1737d8e91e46SDimitry Andric llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1738d8e91e46SDimitry Andric auto *DirContent =
1739344a3780SDimitry Andric dyn_cast<RedirectingFileSystem::DirectoryEntry>(Content.get());
1740ac9a064cSDimitry Andric if (DirContent && Name == Content->getName())
1741d8e91e46SDimitry Andric return DirContent;
1742d8e91e46SDimitry Andric }
1743d8e91e46SDimitry Andric }
1744d8e91e46SDimitry Andric
1745d8e91e46SDimitry Andric // ... or create a new one
1746d8e91e46SDimitry Andric std::unique_ptr<RedirectingFileSystem::Entry> E =
1747344a3780SDimitry Andric std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1748d8e91e46SDimitry Andric Name, Status("", getNextVirtualUniqueID(),
1749d8e91e46SDimitry Andric std::chrono::system_clock::now(), 0, 0, 0,
1750d8e91e46SDimitry Andric file_type::directory_file, sys::fs::all_all));
1751d8e91e46SDimitry Andric
1752d8e91e46SDimitry Andric if (!ParentEntry) { // Add a new root to the overlay
1753d8e91e46SDimitry Andric FS->Roots.push_back(std::move(E));
1754d8e91e46SDimitry Andric ParentEntry = FS->Roots.back().get();
1755d8e91e46SDimitry Andric return ParentEntry;
1756d8e91e46SDimitry Andric }
1757d8e91e46SDimitry Andric
1758344a3780SDimitry Andric auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry);
1759d8e91e46SDimitry Andric DE->addContent(std::move(E));
1760d8e91e46SDimitry Andric return DE->getLastContent();
1761d8e91e46SDimitry Andric }
1762d8e91e46SDimitry Andric
1763b60736ecSDimitry Andric private:
uniqueOverlayTree(RedirectingFileSystem * FS,RedirectingFileSystem::Entry * SrcE,RedirectingFileSystem::Entry * NewParentE=nullptr)1764d8e91e46SDimitry Andric void uniqueOverlayTree(RedirectingFileSystem *FS,
1765d8e91e46SDimitry Andric RedirectingFileSystem::Entry *SrcE,
1766d8e91e46SDimitry Andric RedirectingFileSystem::Entry *NewParentE = nullptr) {
1767d8e91e46SDimitry Andric StringRef Name = SrcE->getName();
1768d8e91e46SDimitry Andric switch (SrcE->getKind()) {
1769d8e91e46SDimitry Andric case RedirectingFileSystem::EK_Directory: {
1770344a3780SDimitry Andric auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
1771d8e91e46SDimitry Andric // Empty directories could be present in the YAML as a way to
1772d8e91e46SDimitry Andric // describe a file for a current directory after some of its subdir
1773d8e91e46SDimitry Andric // is parsed. This only leads to redundant walks, ignore it.
1774d8e91e46SDimitry Andric if (!Name.empty())
1775d8e91e46SDimitry Andric NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1776d8e91e46SDimitry Andric for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1777d8e91e46SDimitry Andric llvm::make_range(DE->contents_begin(), DE->contents_end()))
1778d8e91e46SDimitry Andric uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1779d8e91e46SDimitry Andric break;
1780d8e91e46SDimitry Andric }
1781344a3780SDimitry Andric case RedirectingFileSystem::EK_DirectoryRemap: {
1782344a3780SDimitry Andric assert(NewParentE && "Parent entry must exist");
1783344a3780SDimitry Andric auto *DR = cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
1784344a3780SDimitry Andric auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1785344a3780SDimitry Andric DE->addContent(
1786344a3780SDimitry Andric std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1787344a3780SDimitry Andric Name, DR->getExternalContentsPath(), DR->getUseName()));
1788344a3780SDimitry Andric break;
1789344a3780SDimitry Andric }
1790d8e91e46SDimitry Andric case RedirectingFileSystem::EK_File: {
1791d8e91e46SDimitry Andric assert(NewParentE && "Parent entry must exist");
1792344a3780SDimitry Andric auto *FE = cast<RedirectingFileSystem::FileEntry>(SrcE);
1793344a3780SDimitry Andric auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE);
1794344a3780SDimitry Andric DE->addContent(std::make_unique<RedirectingFileSystem::FileEntry>(
1795d8e91e46SDimitry Andric Name, FE->getExternalContentsPath(), FE->getUseName()));
1796d8e91e46SDimitry Andric break;
1797d8e91e46SDimitry Andric }
1798d8e91e46SDimitry Andric }
1799d8e91e46SDimitry Andric }
1800d8e91e46SDimitry Andric
1801d8e91e46SDimitry Andric std::unique_ptr<RedirectingFileSystem::Entry>
parseEntry(yaml::Node * N,RedirectingFileSystem * FS,bool IsRootEntry)1802d8e91e46SDimitry Andric parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1803d8e91e46SDimitry Andric auto *M = dyn_cast<yaml::MappingNode>(N);
1804d8e91e46SDimitry Andric if (!M) {
1805d8e91e46SDimitry Andric error(N, "expected mapping node for file or directory entry");
1806d8e91e46SDimitry Andric return nullptr;
1807d8e91e46SDimitry Andric }
1808d8e91e46SDimitry Andric
1809d8e91e46SDimitry Andric KeyStatusPair Fields[] = {
1810d8e91e46SDimitry Andric KeyStatusPair("name", true),
1811d8e91e46SDimitry Andric KeyStatusPair("type", true),
1812d8e91e46SDimitry Andric KeyStatusPair("contents", false),
1813d8e91e46SDimitry Andric KeyStatusPair("external-contents", false),
1814d8e91e46SDimitry Andric KeyStatusPair("use-external-name", false),
1815d8e91e46SDimitry Andric };
1816d8e91e46SDimitry Andric
1817d8e91e46SDimitry Andric DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1818d8e91e46SDimitry Andric
1819344a3780SDimitry Andric enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet;
1820d8e91e46SDimitry Andric std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1821d8e91e46SDimitry Andric EntryArrayContents;
1822cfca06d7SDimitry Andric SmallString<256> ExternalContentsPath;
1823cfca06d7SDimitry Andric SmallString<256> Name;
1824e6d15924SDimitry Andric yaml::Node *NameValueNode = nullptr;
1825344a3780SDimitry Andric auto UseExternalName = RedirectingFileSystem::NK_NotSet;
1826d8e91e46SDimitry Andric RedirectingFileSystem::EntryKind Kind;
1827d8e91e46SDimitry Andric
1828d8e91e46SDimitry Andric for (auto &I : *M) {
1829d8e91e46SDimitry Andric StringRef Key;
1830d8e91e46SDimitry Andric // Reuse the buffer for key and value, since we don't look at key after
1831d8e91e46SDimitry Andric // parsing value.
1832d8e91e46SDimitry Andric SmallString<256> Buffer;
1833d8e91e46SDimitry Andric if (!parseScalarString(I.getKey(), Key, Buffer))
1834d8e91e46SDimitry Andric return nullptr;
1835d8e91e46SDimitry Andric
1836d8e91e46SDimitry Andric if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1837d8e91e46SDimitry Andric return nullptr;
1838d8e91e46SDimitry Andric
1839d8e91e46SDimitry Andric StringRef Value;
1840d8e91e46SDimitry Andric if (Key == "name") {
1841d8e91e46SDimitry Andric if (!parseScalarString(I.getValue(), Value, Buffer))
1842d8e91e46SDimitry Andric return nullptr;
1843d8e91e46SDimitry Andric
1844d8e91e46SDimitry Andric NameValueNode = I.getValue();
1845d8e91e46SDimitry Andric // Guarantee that old YAML files containing paths with ".." and "."
1846d8e91e46SDimitry Andric // are properly canonicalized before read into the VFS.
1847cfca06d7SDimitry Andric Name = canonicalize(Value).str();
1848d8e91e46SDimitry Andric } else if (Key == "type") {
1849d8e91e46SDimitry Andric if (!parseScalarString(I.getValue(), Value, Buffer))
1850d8e91e46SDimitry Andric return nullptr;
1851d8e91e46SDimitry Andric if (Value == "file")
1852d8e91e46SDimitry Andric Kind = RedirectingFileSystem::EK_File;
1853d8e91e46SDimitry Andric else if (Value == "directory")
1854d8e91e46SDimitry Andric Kind = RedirectingFileSystem::EK_Directory;
1855344a3780SDimitry Andric else if (Value == "directory-remap")
1856344a3780SDimitry Andric Kind = RedirectingFileSystem::EK_DirectoryRemap;
1857d8e91e46SDimitry Andric else {
1858d8e91e46SDimitry Andric error(I.getValue(), "unknown value for 'type'");
1859d8e91e46SDimitry Andric return nullptr;
1860d8e91e46SDimitry Andric }
1861d8e91e46SDimitry Andric } else if (Key == "contents") {
1862344a3780SDimitry Andric if (ContentsField != CF_NotSet) {
1863d8e91e46SDimitry Andric error(I.getKey(),
1864d8e91e46SDimitry Andric "entry already has 'contents' or 'external-contents'");
1865d8e91e46SDimitry Andric return nullptr;
1866d8e91e46SDimitry Andric }
1867344a3780SDimitry Andric ContentsField = CF_List;
1868d8e91e46SDimitry Andric auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
1869d8e91e46SDimitry Andric if (!Contents) {
1870d8e91e46SDimitry Andric // FIXME: this is only for directories, what about files?
1871d8e91e46SDimitry Andric error(I.getValue(), "expected array");
1872d8e91e46SDimitry Andric return nullptr;
1873d8e91e46SDimitry Andric }
1874d8e91e46SDimitry Andric
1875d8e91e46SDimitry Andric for (auto &I : *Contents) {
1876d8e91e46SDimitry Andric if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1877d8e91e46SDimitry Andric parseEntry(&I, FS, /*IsRootEntry*/ false))
1878d8e91e46SDimitry Andric EntryArrayContents.push_back(std::move(E));
1879d8e91e46SDimitry Andric else
1880d8e91e46SDimitry Andric return nullptr;
1881d8e91e46SDimitry Andric }
1882d8e91e46SDimitry Andric } else if (Key == "external-contents") {
1883344a3780SDimitry Andric if (ContentsField != CF_NotSet) {
1884d8e91e46SDimitry Andric error(I.getKey(),
1885d8e91e46SDimitry Andric "entry already has 'contents' or 'external-contents'");
1886d8e91e46SDimitry Andric return nullptr;
1887d8e91e46SDimitry Andric }
1888344a3780SDimitry Andric ContentsField = CF_External;
1889d8e91e46SDimitry Andric if (!parseScalarString(I.getValue(), Value, Buffer))
1890d8e91e46SDimitry Andric return nullptr;
1891d8e91e46SDimitry Andric
1892d8e91e46SDimitry Andric SmallString<256> FullPath;
1893d8e91e46SDimitry Andric if (FS->IsRelativeOverlay) {
1894e3b55780SDimitry Andric FullPath = FS->getOverlayFileDir();
1895d8e91e46SDimitry Andric assert(!FullPath.empty() &&
1896d8e91e46SDimitry Andric "External contents prefix directory must exist");
1897d8e91e46SDimitry Andric llvm::sys::path::append(FullPath, Value);
1898d8e91e46SDimitry Andric } else {
1899d8e91e46SDimitry Andric FullPath = Value;
1900d8e91e46SDimitry Andric }
1901d8e91e46SDimitry Andric
1902d8e91e46SDimitry Andric // Guarantee that old YAML files containing paths with ".." and "."
1903d8e91e46SDimitry Andric // are properly canonicalized before read into the VFS.
1904cfca06d7SDimitry Andric FullPath = canonicalize(FullPath);
1905d8e91e46SDimitry Andric ExternalContentsPath = FullPath.str();
1906d8e91e46SDimitry Andric } else if (Key == "use-external-name") {
1907d8e91e46SDimitry Andric bool Val;
1908d8e91e46SDimitry Andric if (!parseScalarBool(I.getValue(), Val))
1909d8e91e46SDimitry Andric return nullptr;
1910344a3780SDimitry Andric UseExternalName = Val ? RedirectingFileSystem::NK_External
1911344a3780SDimitry Andric : RedirectingFileSystem::NK_Virtual;
1912d8e91e46SDimitry Andric } else {
1913d8e91e46SDimitry Andric llvm_unreachable("key missing from Keys");
1914d8e91e46SDimitry Andric }
1915d8e91e46SDimitry Andric }
1916d8e91e46SDimitry Andric
1917d8e91e46SDimitry Andric if (Stream.failed())
1918d8e91e46SDimitry Andric return nullptr;
1919d8e91e46SDimitry Andric
1920d8e91e46SDimitry Andric // check for missing keys
1921344a3780SDimitry Andric if (ContentsField == CF_NotSet) {
1922d8e91e46SDimitry Andric error(N, "missing key 'contents' or 'external-contents'");
1923d8e91e46SDimitry Andric return nullptr;
1924d8e91e46SDimitry Andric }
1925d8e91e46SDimitry Andric if (!checkMissingKeys(N, Keys))
1926d8e91e46SDimitry Andric return nullptr;
1927d8e91e46SDimitry Andric
1928d8e91e46SDimitry Andric // check invalid configuration
1929d8e91e46SDimitry Andric if (Kind == RedirectingFileSystem::EK_Directory &&
1930344a3780SDimitry Andric UseExternalName != RedirectingFileSystem::NK_NotSet) {
1931344a3780SDimitry Andric error(N, "'use-external-name' is not supported for 'directory' entries");
1932344a3780SDimitry Andric return nullptr;
1933344a3780SDimitry Andric }
1934344a3780SDimitry Andric
1935344a3780SDimitry Andric if (Kind == RedirectingFileSystem::EK_DirectoryRemap &&
1936344a3780SDimitry Andric ContentsField == CF_List) {
1937344a3780SDimitry Andric error(N, "'contents' is not supported for 'directory-remap' entries");
1938d8e91e46SDimitry Andric return nullptr;
1939d8e91e46SDimitry Andric }
1940d8e91e46SDimitry Andric
1941706b4fc4SDimitry Andric sys::path::Style path_style = sys::path::Style::native;
1942706b4fc4SDimitry Andric if (IsRootEntry) {
1943706b4fc4SDimitry Andric // VFS root entries may be in either Posix or Windows style. Figure out
1944706b4fc4SDimitry Andric // which style we have, and use it consistently.
1945706b4fc4SDimitry Andric if (sys::path::is_absolute(Name, sys::path::Style::posix)) {
1946706b4fc4SDimitry Andric path_style = sys::path::Style::posix;
1947c0981da4SDimitry Andric } else if (sys::path::is_absolute(Name,
1948c0981da4SDimitry Andric sys::path::Style::windows_backslash)) {
1949c0981da4SDimitry Andric path_style = sys::path::Style::windows_backslash;
1950706b4fc4SDimitry Andric } else {
1951e3b55780SDimitry Andric // Relative VFS root entries are made absolute to either the overlay
1952e3b55780SDimitry Andric // directory, or the current working directory, then we can determine
1953e3b55780SDimitry Andric // the path style from that.
1954e3b55780SDimitry Andric std::error_code EC;
1955e3b55780SDimitry Andric if (FS->RootRelative ==
1956e3b55780SDimitry Andric RedirectingFileSystem::RootRelativeKind::OverlayDir) {
1957e3b55780SDimitry Andric StringRef FullPath = FS->getOverlayFileDir();
1958e3b55780SDimitry Andric assert(!FullPath.empty() && "Overlay file directory must exist");
1959e3b55780SDimitry Andric EC = FS->makeAbsolute(FullPath, Name);
1960e3b55780SDimitry Andric Name = canonicalize(Name);
1961e3b55780SDimitry Andric } else {
1962e3b55780SDimitry Andric EC = sys::fs::make_absolute(Name);
1963e3b55780SDimitry Andric }
19646f8fc217SDimitry Andric if (EC) {
1965d8e91e46SDimitry Andric assert(NameValueNode && "Name presence should be checked earlier");
19666f8fc217SDimitry Andric error(
19676f8fc217SDimitry Andric NameValueNode,
1968d8e91e46SDimitry Andric "entry with relative path at the root level is not discoverable");
1969d8e91e46SDimitry Andric return nullptr;
1970d8e91e46SDimitry Andric }
19716f8fc217SDimitry Andric path_style = sys::path::is_absolute(Name, sys::path::Style::posix)
19726f8fc217SDimitry Andric ? sys::path::Style::posix
19736f8fc217SDimitry Andric : sys::path::Style::windows_backslash;
19746f8fc217SDimitry Andric }
1975e3b55780SDimitry Andric // is::path::is_absolute(Name, sys::path::Style::windows_backslash) will
1976e3b55780SDimitry Andric // return true even if `Name` is using forward slashes. Distinguish
1977e3b55780SDimitry Andric // between windows_backslash and windows_slash.
1978e3b55780SDimitry Andric if (path_style == sys::path::Style::windows_backslash &&
1979e3b55780SDimitry Andric getExistingStyle(Name) != sys::path::Style::windows_backslash)
1980e3b55780SDimitry Andric path_style = sys::path::Style::windows_slash;
1981706b4fc4SDimitry Andric }
1982d8e91e46SDimitry Andric
1983d8e91e46SDimitry Andric // Remove trailing slash(es), being careful not to remove the root path
1984344a3780SDimitry Andric StringRef Trimmed = Name;
1985706b4fc4SDimitry Andric size_t RootPathLen = sys::path::root_path(Trimmed, path_style).size();
1986d8e91e46SDimitry Andric while (Trimmed.size() > RootPathLen &&
1987706b4fc4SDimitry Andric sys::path::is_separator(Trimmed.back(), path_style))
1988d8e91e46SDimitry Andric Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
1989706b4fc4SDimitry Andric
1990d8e91e46SDimitry Andric // Get the last component
1991706b4fc4SDimitry Andric StringRef LastComponent = sys::path::filename(Trimmed, path_style);
1992d8e91e46SDimitry Andric
1993d8e91e46SDimitry Andric std::unique_ptr<RedirectingFileSystem::Entry> Result;
1994d8e91e46SDimitry Andric switch (Kind) {
1995d8e91e46SDimitry Andric case RedirectingFileSystem::EK_File:
1996344a3780SDimitry Andric Result = std::make_unique<RedirectingFileSystem::FileEntry>(
1997344a3780SDimitry Andric LastComponent, std::move(ExternalContentsPath), UseExternalName);
1998344a3780SDimitry Andric break;
1999344a3780SDimitry Andric case RedirectingFileSystem::EK_DirectoryRemap:
2000344a3780SDimitry Andric Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
2001d8e91e46SDimitry Andric LastComponent, std::move(ExternalContentsPath), UseExternalName);
2002d8e91e46SDimitry Andric break;
2003d8e91e46SDimitry Andric case RedirectingFileSystem::EK_Directory:
2004344a3780SDimitry Andric Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
2005d8e91e46SDimitry Andric LastComponent, std::move(EntryArrayContents),
2006344a3780SDimitry Andric Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
2007344a3780SDimitry Andric 0, 0, 0, file_type::directory_file, sys::fs::all_all));
2008d8e91e46SDimitry Andric break;
2009d8e91e46SDimitry Andric }
2010d8e91e46SDimitry Andric
2011706b4fc4SDimitry Andric StringRef Parent = sys::path::parent_path(Trimmed, path_style);
2012d8e91e46SDimitry Andric if (Parent.empty())
2013d8e91e46SDimitry Andric return Result;
2014d8e91e46SDimitry Andric
2015d8e91e46SDimitry Andric // if 'name' contains multiple components, create implicit directory entries
2016706b4fc4SDimitry Andric for (sys::path::reverse_iterator I = sys::path::rbegin(Parent, path_style),
2017d8e91e46SDimitry Andric E = sys::path::rend(Parent);
2018d8e91e46SDimitry Andric I != E; ++I) {
2019d8e91e46SDimitry Andric std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
2020d8e91e46SDimitry Andric Entries.push_back(std::move(Result));
2021344a3780SDimitry Andric Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
2022d8e91e46SDimitry Andric *I, std::move(Entries),
2023344a3780SDimitry Andric Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
2024344a3780SDimitry Andric 0, 0, 0, file_type::directory_file, sys::fs::all_all));
2025d8e91e46SDimitry Andric }
2026d8e91e46SDimitry Andric return Result;
2027d8e91e46SDimitry Andric }
2028d8e91e46SDimitry Andric
2029d8e91e46SDimitry Andric public:
RedirectingFileSystemParser(yaml::Stream & S)2030d8e91e46SDimitry Andric RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
2031d8e91e46SDimitry Andric
2032d8e91e46SDimitry Andric // false on error
parse(yaml::Node * Root,RedirectingFileSystem * FS)2033d8e91e46SDimitry Andric bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
2034d8e91e46SDimitry Andric auto *Top = dyn_cast<yaml::MappingNode>(Root);
2035d8e91e46SDimitry Andric if (!Top) {
2036d8e91e46SDimitry Andric error(Root, "expected mapping node");
2037d8e91e46SDimitry Andric return false;
2038d8e91e46SDimitry Andric }
2039d8e91e46SDimitry Andric
2040d8e91e46SDimitry Andric KeyStatusPair Fields[] = {
2041d8e91e46SDimitry Andric KeyStatusPair("version", true),
2042d8e91e46SDimitry Andric KeyStatusPair("case-sensitive", false),
2043d8e91e46SDimitry Andric KeyStatusPair("use-external-names", false),
2044e3b55780SDimitry Andric KeyStatusPair("root-relative", false),
2045d8e91e46SDimitry Andric KeyStatusPair("overlay-relative", false),
2046d8e91e46SDimitry Andric KeyStatusPair("fallthrough", false),
2047145449b1SDimitry Andric KeyStatusPair("redirecting-with", false),
2048d8e91e46SDimitry Andric KeyStatusPair("roots", true),
2049d8e91e46SDimitry Andric };
2050d8e91e46SDimitry Andric
2051d8e91e46SDimitry Andric DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
2052d8e91e46SDimitry Andric std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
2053d8e91e46SDimitry Andric
2054d8e91e46SDimitry Andric // Parse configuration and 'roots'
2055d8e91e46SDimitry Andric for (auto &I : *Top) {
2056d8e91e46SDimitry Andric SmallString<10> KeyBuffer;
2057d8e91e46SDimitry Andric StringRef Key;
2058d8e91e46SDimitry Andric if (!parseScalarString(I.getKey(), Key, KeyBuffer))
2059d8e91e46SDimitry Andric return false;
2060d8e91e46SDimitry Andric
2061d8e91e46SDimitry Andric if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
2062d8e91e46SDimitry Andric return false;
2063d8e91e46SDimitry Andric
2064d8e91e46SDimitry Andric if (Key == "roots") {
2065d8e91e46SDimitry Andric auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
2066d8e91e46SDimitry Andric if (!Roots) {
2067d8e91e46SDimitry Andric error(I.getValue(), "expected array");
2068d8e91e46SDimitry Andric return false;
2069d8e91e46SDimitry Andric }
2070d8e91e46SDimitry Andric
2071d8e91e46SDimitry Andric for (auto &I : *Roots) {
2072d8e91e46SDimitry Andric if (std::unique_ptr<RedirectingFileSystem::Entry> E =
2073d8e91e46SDimitry Andric parseEntry(&I, FS, /*IsRootEntry*/ true))
2074d8e91e46SDimitry Andric RootEntries.push_back(std::move(E));
2075d8e91e46SDimitry Andric else
2076d8e91e46SDimitry Andric return false;
2077d8e91e46SDimitry Andric }
2078d8e91e46SDimitry Andric } else if (Key == "version") {
2079d8e91e46SDimitry Andric StringRef VersionString;
2080d8e91e46SDimitry Andric SmallString<4> Storage;
2081d8e91e46SDimitry Andric if (!parseScalarString(I.getValue(), VersionString, Storage))
2082d8e91e46SDimitry Andric return false;
2083d8e91e46SDimitry Andric int Version;
2084d8e91e46SDimitry Andric if (VersionString.getAsInteger<int>(10, Version)) {
2085d8e91e46SDimitry Andric error(I.getValue(), "expected integer");
2086d8e91e46SDimitry Andric return false;
2087d8e91e46SDimitry Andric }
2088d8e91e46SDimitry Andric if (Version < 0) {
2089d8e91e46SDimitry Andric error(I.getValue(), "invalid version number");
2090d8e91e46SDimitry Andric return false;
2091d8e91e46SDimitry Andric }
2092d8e91e46SDimitry Andric if (Version != 0) {
2093d8e91e46SDimitry Andric error(I.getValue(), "version mismatch, expected 0");
2094d8e91e46SDimitry Andric return false;
2095d8e91e46SDimitry Andric }
2096d8e91e46SDimitry Andric } else if (Key == "case-sensitive") {
2097d8e91e46SDimitry Andric if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
2098d8e91e46SDimitry Andric return false;
2099d8e91e46SDimitry Andric } else if (Key == "overlay-relative") {
2100d8e91e46SDimitry Andric if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
2101d8e91e46SDimitry Andric return false;
2102d8e91e46SDimitry Andric } else if (Key == "use-external-names") {
2103d8e91e46SDimitry Andric if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
2104d8e91e46SDimitry Andric return false;
2105d8e91e46SDimitry Andric } else if (Key == "fallthrough") {
2106145449b1SDimitry Andric if (Keys["redirecting-with"].Seen) {
2107145449b1SDimitry Andric error(I.getValue(),
2108145449b1SDimitry Andric "'fallthrough' and 'redirecting-with' are mutually exclusive");
2109d8e91e46SDimitry Andric return false;
2110145449b1SDimitry Andric }
2111145449b1SDimitry Andric
2112145449b1SDimitry Andric bool ShouldFallthrough = false;
2113145449b1SDimitry Andric if (!parseScalarBool(I.getValue(), ShouldFallthrough))
2114145449b1SDimitry Andric return false;
2115145449b1SDimitry Andric
2116145449b1SDimitry Andric if (ShouldFallthrough) {
2117145449b1SDimitry Andric FS->Redirection = RedirectingFileSystem::RedirectKind::Fallthrough;
2118145449b1SDimitry Andric } else {
2119145449b1SDimitry Andric FS->Redirection = RedirectingFileSystem::RedirectKind::RedirectOnly;
2120145449b1SDimitry Andric }
2121145449b1SDimitry Andric } else if (Key == "redirecting-with") {
2122145449b1SDimitry Andric if (Keys["fallthrough"].Seen) {
2123145449b1SDimitry Andric error(I.getValue(),
2124145449b1SDimitry Andric "'fallthrough' and 'redirecting-with' are mutually exclusive");
2125145449b1SDimitry Andric return false;
2126145449b1SDimitry Andric }
2127145449b1SDimitry Andric
2128145449b1SDimitry Andric if (auto Kind = parseRedirectKind(I.getValue())) {
2129145449b1SDimitry Andric FS->Redirection = *Kind;
2130145449b1SDimitry Andric } else {
2131145449b1SDimitry Andric error(I.getValue(), "expected valid redirect kind");
2132145449b1SDimitry Andric return false;
2133145449b1SDimitry Andric }
2134e3b55780SDimitry Andric } else if (Key == "root-relative") {
2135e3b55780SDimitry Andric if (auto Kind = parseRootRelativeKind(I.getValue())) {
2136e3b55780SDimitry Andric FS->RootRelative = *Kind;
2137e3b55780SDimitry Andric } else {
2138e3b55780SDimitry Andric error(I.getValue(), "expected valid root-relative kind");
2139e3b55780SDimitry Andric return false;
2140e3b55780SDimitry Andric }
2141d8e91e46SDimitry Andric } else {
2142d8e91e46SDimitry Andric llvm_unreachable("key missing from Keys");
2143d8e91e46SDimitry Andric }
2144d8e91e46SDimitry Andric }
2145d8e91e46SDimitry Andric
2146d8e91e46SDimitry Andric if (Stream.failed())
2147d8e91e46SDimitry Andric return false;
2148d8e91e46SDimitry Andric
2149d8e91e46SDimitry Andric if (!checkMissingKeys(Top, Keys))
2150d8e91e46SDimitry Andric return false;
2151d8e91e46SDimitry Andric
2152d8e91e46SDimitry Andric // Now that we sucessefully parsed the YAML file, canonicalize the internal
2153d8e91e46SDimitry Andric // representation to a proper directory tree so that we can search faster
2154d8e91e46SDimitry Andric // inside the VFS.
2155d8e91e46SDimitry Andric for (auto &E : RootEntries)
2156d8e91e46SDimitry Andric uniqueOverlayTree(FS, E.get());
2157d8e91e46SDimitry Andric
2158d8e91e46SDimitry Andric return true;
2159d8e91e46SDimitry Andric }
2160d8e91e46SDimitry Andric };
2161d8e91e46SDimitry Andric
2162b60736ecSDimitry Andric std::unique_ptr<RedirectingFileSystem>
create(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)2163d8e91e46SDimitry Andric RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
2164d8e91e46SDimitry Andric SourceMgr::DiagHandlerTy DiagHandler,
2165d8e91e46SDimitry Andric StringRef YAMLFilePath, void *DiagContext,
2166d8e91e46SDimitry Andric IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2167d8e91e46SDimitry Andric SourceMgr SM;
2168d8e91e46SDimitry Andric yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
2169d8e91e46SDimitry Andric
2170d8e91e46SDimitry Andric SM.setDiagHandler(DiagHandler, DiagContext);
2171d8e91e46SDimitry Andric yaml::document_iterator DI = Stream.begin();
2172d8e91e46SDimitry Andric yaml::Node *Root = DI->getRoot();
2173d8e91e46SDimitry Andric if (DI == Stream.end() || !Root) {
2174d8e91e46SDimitry Andric SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
2175d8e91e46SDimitry Andric return nullptr;
2176d8e91e46SDimitry Andric }
2177d8e91e46SDimitry Andric
2178d8e91e46SDimitry Andric RedirectingFileSystemParser P(Stream);
2179d8e91e46SDimitry Andric
2180d8e91e46SDimitry Andric std::unique_ptr<RedirectingFileSystem> FS(
21811d5ae102SDimitry Andric new RedirectingFileSystem(ExternalFS));
2182d8e91e46SDimitry Andric
2183d8e91e46SDimitry Andric if (!YAMLFilePath.empty()) {
2184d8e91e46SDimitry Andric // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
2185d8e91e46SDimitry Andric // to each 'external-contents' path.
2186d8e91e46SDimitry Andric //
2187d8e91e46SDimitry Andric // Example:
2188d8e91e46SDimitry Andric // -ivfsoverlay dummy.cache/vfs/vfs.yaml
2189d8e91e46SDimitry Andric // yields:
2190e3b55780SDimitry Andric // FS->OverlayFileDir => /<absolute_path_to>/dummy.cache/vfs
2191d8e91e46SDimitry Andric //
2192d8e91e46SDimitry Andric SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
2193d8e91e46SDimitry Andric std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
2194d8e91e46SDimitry Andric assert(!EC && "Overlay dir final path must be absolute");
2195d8e91e46SDimitry Andric (void)EC;
2196e3b55780SDimitry Andric FS->setOverlayFileDir(OverlayAbsDir);
2197d8e91e46SDimitry Andric }
2198d8e91e46SDimitry Andric
2199d8e91e46SDimitry Andric if (!P.parse(Root, FS.get()))
2200d8e91e46SDimitry Andric return nullptr;
2201d8e91e46SDimitry Andric
2202b60736ecSDimitry Andric return FS;
2203d8e91e46SDimitry Andric }
2204d8e91e46SDimitry Andric
create(ArrayRef<std::pair<std::string,std::string>> RemappedFiles,bool UseExternalNames,FileSystem & ExternalFS)2205b60736ecSDimitry Andric std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create(
2206b60736ecSDimitry Andric ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
2207b60736ecSDimitry Andric bool UseExternalNames, FileSystem &ExternalFS) {
2208b60736ecSDimitry Andric std::unique_ptr<RedirectingFileSystem> FS(
2209b60736ecSDimitry Andric new RedirectingFileSystem(&ExternalFS));
2210b60736ecSDimitry Andric FS->UseExternalNames = UseExternalNames;
2211d8e91e46SDimitry Andric
2212b60736ecSDimitry Andric StringMap<RedirectingFileSystem::Entry *> Entries;
2213b60736ecSDimitry Andric
2214b60736ecSDimitry Andric for (auto &Mapping : llvm::reverse(RemappedFiles)) {
2215b60736ecSDimitry Andric SmallString<128> From = StringRef(Mapping.first);
2216b60736ecSDimitry Andric SmallString<128> To = StringRef(Mapping.second);
2217b60736ecSDimitry Andric {
2218b60736ecSDimitry Andric auto EC = ExternalFS.makeAbsolute(From);
2219b60736ecSDimitry Andric (void)EC;
2220b60736ecSDimitry Andric assert(!EC && "Could not make absolute path");
2221b60736ecSDimitry Andric }
2222b60736ecSDimitry Andric
2223b60736ecSDimitry Andric // Check if we've already mapped this file. The first one we see (in the
2224b60736ecSDimitry Andric // reverse iteration) wins.
2225b60736ecSDimitry Andric RedirectingFileSystem::Entry *&ToEntry = Entries[From];
2226b60736ecSDimitry Andric if (ToEntry)
2227b60736ecSDimitry Andric continue;
2228b60736ecSDimitry Andric
2229b60736ecSDimitry Andric // Add parent directories.
2230b60736ecSDimitry Andric RedirectingFileSystem::Entry *Parent = nullptr;
2231b60736ecSDimitry Andric StringRef FromDirectory = llvm::sys::path::parent_path(From);
2232b60736ecSDimitry Andric for (auto I = llvm::sys::path::begin(FromDirectory),
2233b60736ecSDimitry Andric E = llvm::sys::path::end(FromDirectory);
2234b60736ecSDimitry Andric I != E; ++I) {
2235b60736ecSDimitry Andric Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS.get(), *I,
2236b60736ecSDimitry Andric Parent);
2237b60736ecSDimitry Andric }
2238b60736ecSDimitry Andric assert(Parent && "File without a directory?");
2239b60736ecSDimitry Andric {
2240b60736ecSDimitry Andric auto EC = ExternalFS.makeAbsolute(To);
2241b60736ecSDimitry Andric (void)EC;
2242b60736ecSDimitry Andric assert(!EC && "Could not make absolute path");
2243b60736ecSDimitry Andric }
2244b60736ecSDimitry Andric
2245b60736ecSDimitry Andric // Add the file.
2246344a3780SDimitry Andric auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>(
2247b60736ecSDimitry Andric llvm::sys::path::filename(From), To,
2248344a3780SDimitry Andric UseExternalNames ? RedirectingFileSystem::NK_External
2249344a3780SDimitry Andric : RedirectingFileSystem::NK_Virtual);
2250b60736ecSDimitry Andric ToEntry = NewFile.get();
2251344a3780SDimitry Andric cast<RedirectingFileSystem::DirectoryEntry>(Parent)->addContent(
2252b60736ecSDimitry Andric std::move(NewFile));
2253b60736ecSDimitry Andric }
2254b60736ecSDimitry Andric
2255b60736ecSDimitry Andric return FS;
2256b60736ecSDimitry Andric }
2257b60736ecSDimitry Andric
LookupResult(Entry * E,sys::path::const_iterator Start,sys::path::const_iterator End)2258344a3780SDimitry Andric RedirectingFileSystem::LookupResult::LookupResult(
2259344a3780SDimitry Andric Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
2260344a3780SDimitry Andric : E(E) {
2261344a3780SDimitry Andric assert(E != nullptr);
2262344a3780SDimitry Andric // If the matched entry is a DirectoryRemapEntry, set ExternalRedirect to the
2263344a3780SDimitry Andric // path of the directory it maps to in the external file system plus any
2264344a3780SDimitry Andric // remaining path components in the provided iterator.
2265344a3780SDimitry Andric if (auto *DRE = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(E)) {
2266344a3780SDimitry Andric SmallString<256> Redirect(DRE->getExternalContentsPath());
2267344a3780SDimitry Andric sys::path::append(Redirect, Start, End,
2268344a3780SDimitry Andric getExistingStyle(DRE->getExternalContentsPath()));
2269344a3780SDimitry Andric ExternalRedirect = std::string(Redirect);
2270344a3780SDimitry Andric }
2271344a3780SDimitry Andric }
2272344a3780SDimitry Andric
getPath(llvm::SmallVectorImpl<char> & Result) const22737fa27ce4SDimitry Andric void RedirectingFileSystem::LookupResult::getPath(
22747fa27ce4SDimitry Andric llvm::SmallVectorImpl<char> &Result) const {
22757fa27ce4SDimitry Andric Result.clear();
22767fa27ce4SDimitry Andric for (Entry *Parent : Parents)
22777fa27ce4SDimitry Andric llvm::sys::path::append(Result, Parent->getName());
22787fa27ce4SDimitry Andric llvm::sys::path::append(Result, E->getName());
22797fa27ce4SDimitry Andric }
22807fa27ce4SDimitry Andric
makeCanonicalForLookup(SmallVectorImpl<char> & Path) const2281ac9a064cSDimitry Andric std::error_code RedirectingFileSystem::makeCanonicalForLookup(
2282ac9a064cSDimitry Andric SmallVectorImpl<char> &Path) const {
2283d8e91e46SDimitry Andric if (std::error_code EC = makeAbsolute(Path))
2284d8e91e46SDimitry Andric return EC;
2285d8e91e46SDimitry Andric
2286b60736ecSDimitry Andric llvm::SmallString<256> CanonicalPath =
2287b60736ecSDimitry Andric canonicalize(StringRef(Path.data(), Path.size()));
2288b60736ecSDimitry Andric if (CanonicalPath.empty())
2289d8e91e46SDimitry Andric return make_error_code(llvm::errc::invalid_argument);
2290d8e91e46SDimitry Andric
2291b60736ecSDimitry Andric Path.assign(CanonicalPath.begin(), CanonicalPath.end());
2292b60736ecSDimitry Andric return {};
2293b60736ecSDimitry Andric }
2294b60736ecSDimitry Andric
2295344a3780SDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult>
lookupPath(StringRef Path) const2296b60736ecSDimitry Andric RedirectingFileSystem::lookupPath(StringRef Path) const {
2297ac9a064cSDimitry Andric llvm::SmallString<128> CanonicalPath(Path);
2298ac9a064cSDimitry Andric if (std::error_code EC = makeCanonicalForLookup(CanonicalPath))
2299ac9a064cSDimitry Andric return EC;
2300ac9a064cSDimitry Andric
2301ac9a064cSDimitry Andric // RedirectOnly means the VFS is always used.
2302ac9a064cSDimitry Andric if (UsageTrackingActive && Redirection == RedirectKind::RedirectOnly)
2303ac9a064cSDimitry Andric HasBeenUsed = true;
2304ac9a064cSDimitry Andric
2305ac9a064cSDimitry Andric sys::path::const_iterator Start = sys::path::begin(CanonicalPath);
2306ac9a064cSDimitry Andric sys::path::const_iterator End = sys::path::end(CanonicalPath);
23077fa27ce4SDimitry Andric llvm::SmallVector<Entry *, 32> Entries;
2308d8e91e46SDimitry Andric for (const auto &Root : Roots) {
2309344a3780SDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> Result =
23107fa27ce4SDimitry Andric lookupPathImpl(Start, End, Root.get(), Entries);
2311ac9a064cSDimitry Andric if (UsageTrackingActive && Result && isa<RemapEntry>(Result->E))
2312ac9a064cSDimitry Andric HasBeenUsed = true;
23137fa27ce4SDimitry Andric if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) {
23147fa27ce4SDimitry Andric Result->Parents = std::move(Entries);
2315d8e91e46SDimitry Andric return Result;
2316d8e91e46SDimitry Andric }
23177fa27ce4SDimitry Andric }
2318d8e91e46SDimitry Andric return make_error_code(llvm::errc::no_such_file_or_directory);
2319d8e91e46SDimitry Andric }
2320d8e91e46SDimitry Andric
2321344a3780SDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult>
lookupPathImpl(sys::path::const_iterator Start,sys::path::const_iterator End,RedirectingFileSystem::Entry * From,llvm::SmallVectorImpl<Entry * > & Entries) const2322344a3780SDimitry Andric RedirectingFileSystem::lookupPathImpl(
2323344a3780SDimitry Andric sys::path::const_iterator Start, sys::path::const_iterator End,
23247fa27ce4SDimitry Andric RedirectingFileSystem::Entry *From,
23257fa27ce4SDimitry Andric llvm::SmallVectorImpl<Entry *> &Entries) const {
2326d8e91e46SDimitry Andric assert(!isTraversalComponent(*Start) &&
2327d8e91e46SDimitry Andric !isTraversalComponent(From->getName()) &&
2328d8e91e46SDimitry Andric "Paths should not contain traversal components");
2329d8e91e46SDimitry Andric
2330d8e91e46SDimitry Andric StringRef FromName = From->getName();
2331d8e91e46SDimitry Andric
2332d8e91e46SDimitry Andric // Forward the search to the next component in case this is an empty one.
2333d8e91e46SDimitry Andric if (!FromName.empty()) {
2334706b4fc4SDimitry Andric if (!pathComponentMatches(*Start, FromName))
2335d8e91e46SDimitry Andric return make_error_code(llvm::errc::no_such_file_or_directory);
2336d8e91e46SDimitry Andric
2337d8e91e46SDimitry Andric ++Start;
2338d8e91e46SDimitry Andric
2339d8e91e46SDimitry Andric if (Start == End) {
2340d8e91e46SDimitry Andric // Match!
2341344a3780SDimitry Andric return LookupResult(From, Start, End);
2342d8e91e46SDimitry Andric }
2343d8e91e46SDimitry Andric }
2344d8e91e46SDimitry Andric
2345344a3780SDimitry Andric if (isa<RedirectingFileSystem::FileEntry>(From))
2346d8e91e46SDimitry Andric return make_error_code(llvm::errc::not_a_directory);
2347d8e91e46SDimitry Andric
2348344a3780SDimitry Andric if (isa<RedirectingFileSystem::DirectoryRemapEntry>(From))
2349344a3780SDimitry Andric return LookupResult(From, Start, End);
2350344a3780SDimitry Andric
2351344a3780SDimitry Andric auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(From);
2352d8e91e46SDimitry Andric for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
2353d8e91e46SDimitry Andric llvm::make_range(DE->contents_begin(), DE->contents_end())) {
23547fa27ce4SDimitry Andric Entries.push_back(From);
2355344a3780SDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> Result =
23567fa27ce4SDimitry Andric lookupPathImpl(Start, End, DirEntry.get(), Entries);
2357d8e91e46SDimitry Andric if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
2358d8e91e46SDimitry Andric return Result;
23597fa27ce4SDimitry Andric Entries.pop_back();
2360d8e91e46SDimitry Andric }
2361706b4fc4SDimitry Andric
2362d8e91e46SDimitry Andric return make_error_code(llvm::errc::no_such_file_or_directory);
2363d8e91e46SDimitry Andric }
2364d8e91e46SDimitry Andric
getRedirectedFileStatus(const Twine & OriginalPath,bool UseExternalNames,Status ExternalStatus)2365c0981da4SDimitry Andric static Status getRedirectedFileStatus(const Twine &OriginalPath,
2366c0981da4SDimitry Andric bool UseExternalNames,
2367d8e91e46SDimitry Andric Status ExternalStatus) {
2368145449b1SDimitry Andric // The path has been mapped by some nested VFS and exposes an external path,
2369145449b1SDimitry Andric // don't override it with the original path.
2370145449b1SDimitry Andric if (ExternalStatus.ExposesExternalVFSPath)
2371145449b1SDimitry Andric return ExternalStatus;
2372145449b1SDimitry Andric
2373d8e91e46SDimitry Andric Status S = ExternalStatus;
2374d8e91e46SDimitry Andric if (!UseExternalNames)
2375c0981da4SDimitry Andric S = Status::copyWithNewName(S, OriginalPath);
2376145449b1SDimitry Andric else
2377145449b1SDimitry Andric S.ExposesExternalVFSPath = true;
2378d8e91e46SDimitry Andric return S;
2379d8e91e46SDimitry Andric }
2380d8e91e46SDimitry Andric
status(const Twine & LookupPath,const Twine & OriginalPath,const RedirectingFileSystem::LookupResult & Result)2381344a3780SDimitry Andric ErrorOr<Status> RedirectingFileSystem::status(
2382ac9a064cSDimitry Andric const Twine &LookupPath, const Twine &OriginalPath,
2383c0981da4SDimitry Andric const RedirectingFileSystem::LookupResult &Result) {
2384e3b55780SDimitry Andric if (std::optional<StringRef> ExtRedirect = Result.getExternalRedirect()) {
2385ac9a064cSDimitry Andric SmallString<256> RemappedPath((*ExtRedirect).str());
2386ac9a064cSDimitry Andric if (std::error_code EC = makeAbsolute(RemappedPath))
2387c0981da4SDimitry Andric return EC;
2388c0981da4SDimitry Andric
2389ac9a064cSDimitry Andric ErrorOr<Status> S = ExternalFS->status(RemappedPath);
2390344a3780SDimitry Andric if (!S)
2391d8e91e46SDimitry Andric return S;
2392c0981da4SDimitry Andric S = Status::copyWithNewName(*S, *ExtRedirect);
2393344a3780SDimitry Andric auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result.E);
2394c0981da4SDimitry Andric return getRedirectedFileStatus(OriginalPath,
2395c0981da4SDimitry Andric RE->useExternalName(UseExternalNames), *S);
2396d8e91e46SDimitry Andric }
2397344a3780SDimitry Andric
2398344a3780SDimitry Andric auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Result.E);
2399ac9a064cSDimitry Andric return Status::copyWithNewName(DE->getStatus(), LookupPath);
2400d8e91e46SDimitry Andric }
2401d8e91e46SDimitry Andric
2402c0981da4SDimitry Andric ErrorOr<Status>
getExternalStatus(const Twine & LookupPath,const Twine & OriginalPath) const2403ac9a064cSDimitry Andric RedirectingFileSystem::getExternalStatus(const Twine &LookupPath,
2404c0981da4SDimitry Andric const Twine &OriginalPath) const {
2405ac9a064cSDimitry Andric auto Result = ExternalFS->status(LookupPath);
2406145449b1SDimitry Andric
2407145449b1SDimitry Andric // The path has been mapped by some nested VFS, don't override it with the
2408145449b1SDimitry Andric // original path.
2409145449b1SDimitry Andric if (!Result || Result->ExposesExternalVFSPath)
2410145449b1SDimitry Andric return Result;
2411145449b1SDimitry Andric return Status::copyWithNewName(Result.get(), OriginalPath);
2412c0981da4SDimitry Andric }
2413b60736ecSDimitry Andric
status(const Twine & OriginalPath)2414c0981da4SDimitry Andric ErrorOr<Status> RedirectingFileSystem::status(const Twine &OriginalPath) {
2415ac9a064cSDimitry Andric SmallString<256> Path;
2416ac9a064cSDimitry Andric OriginalPath.toVector(Path);
2417c0981da4SDimitry Andric
2418ac9a064cSDimitry Andric if (std::error_code EC = makeAbsolute(Path))
2419b60736ecSDimitry Andric return EC;
2420b60736ecSDimitry Andric
2421145449b1SDimitry Andric if (Redirection == RedirectKind::Fallback) {
2422145449b1SDimitry Andric // Attempt to find the original file first, only falling back to the
2423145449b1SDimitry Andric // mapped file if that fails.
2424ac9a064cSDimitry Andric ErrorOr<Status> S = getExternalStatus(Path, OriginalPath);
2425145449b1SDimitry Andric if (S)
2426145449b1SDimitry Andric return S;
2427145449b1SDimitry Andric }
2428145449b1SDimitry Andric
2429ac9a064cSDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2430d8e91e46SDimitry Andric if (!Result) {
2431145449b1SDimitry Andric // Was not able to map file, fallthrough to using the original path if
2432145449b1SDimitry Andric // that was the specified redirection type.
2433145449b1SDimitry Andric if (Redirection == RedirectKind::Fallthrough &&
2434145449b1SDimitry Andric isFileNotFound(Result.getError()))
2435ac9a064cSDimitry Andric return getExternalStatus(Path, OriginalPath);
2436d8e91e46SDimitry Andric return Result.getError();
2437d8e91e46SDimitry Andric }
2438344a3780SDimitry Andric
2439ac9a064cSDimitry Andric ErrorOr<Status> S = status(Path, OriginalPath, *Result);
2440145449b1SDimitry Andric if (!S && Redirection == RedirectKind::Fallthrough &&
2441145449b1SDimitry Andric isFileNotFound(S.getError(), Result->E)) {
2442145449b1SDimitry Andric // Mapped the file but it wasn't found in the underlying filesystem,
2443145449b1SDimitry Andric // fallthrough to using the original path if that was the specified
2444145449b1SDimitry Andric // redirection type.
2445ac9a064cSDimitry Andric return getExternalStatus(Path, OriginalPath);
2446c0981da4SDimitry Andric }
2447c0981da4SDimitry Andric
2448344a3780SDimitry Andric return S;
2449d8e91e46SDimitry Andric }
2450d8e91e46SDimitry Andric
exists(const Twine & OriginalPath)2451ac9a064cSDimitry Andric bool RedirectingFileSystem::exists(const Twine &OriginalPath) {
2452ac9a064cSDimitry Andric SmallString<256> Path;
2453ac9a064cSDimitry Andric OriginalPath.toVector(Path);
2454ac9a064cSDimitry Andric
2455ac9a064cSDimitry Andric if (makeAbsolute(Path))
2456ac9a064cSDimitry Andric return false;
2457ac9a064cSDimitry Andric
2458ac9a064cSDimitry Andric if (Redirection == RedirectKind::Fallback) {
2459ac9a064cSDimitry Andric // Attempt to find the original file first, only falling back to the
2460ac9a064cSDimitry Andric // mapped file if that fails.
2461ac9a064cSDimitry Andric if (ExternalFS->exists(Path))
2462ac9a064cSDimitry Andric return true;
2463ac9a064cSDimitry Andric }
2464ac9a064cSDimitry Andric
2465ac9a064cSDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2466ac9a064cSDimitry Andric if (!Result) {
2467ac9a064cSDimitry Andric // Was not able to map file, fallthrough to using the original path if
2468ac9a064cSDimitry Andric // that was the specified redirection type.
2469ac9a064cSDimitry Andric if (Redirection == RedirectKind::Fallthrough &&
2470ac9a064cSDimitry Andric isFileNotFound(Result.getError()))
2471ac9a064cSDimitry Andric return ExternalFS->exists(Path);
2472ac9a064cSDimitry Andric return false;
2473ac9a064cSDimitry Andric }
2474ac9a064cSDimitry Andric
2475ac9a064cSDimitry Andric std::optional<StringRef> ExtRedirect = Result->getExternalRedirect();
2476ac9a064cSDimitry Andric if (!ExtRedirect) {
2477ac9a064cSDimitry Andric assert(isa<RedirectingFileSystem::DirectoryEntry>(Result->E));
2478ac9a064cSDimitry Andric return true;
2479ac9a064cSDimitry Andric }
2480ac9a064cSDimitry Andric
2481ac9a064cSDimitry Andric SmallString<256> RemappedPath((*ExtRedirect).str());
2482ac9a064cSDimitry Andric if (makeAbsolute(RemappedPath))
2483ac9a064cSDimitry Andric return false;
2484ac9a064cSDimitry Andric
2485ac9a064cSDimitry Andric if (ExternalFS->exists(RemappedPath))
2486ac9a064cSDimitry Andric return true;
2487ac9a064cSDimitry Andric
2488ac9a064cSDimitry Andric if (Redirection == RedirectKind::Fallthrough) {
2489ac9a064cSDimitry Andric // Mapped the file but it wasn't found in the underlying filesystem,
2490ac9a064cSDimitry Andric // fallthrough to using the original path if that was the specified
2491ac9a064cSDimitry Andric // redirection type.
2492ac9a064cSDimitry Andric return ExternalFS->exists(Path);
2493ac9a064cSDimitry Andric }
2494ac9a064cSDimitry Andric
2495ac9a064cSDimitry Andric return false;
2496ac9a064cSDimitry Andric }
2497ac9a064cSDimitry Andric
2498d8e91e46SDimitry Andric namespace {
2499d8e91e46SDimitry Andric
2500d8e91e46SDimitry Andric /// Provide a file wrapper with an overriden status.
2501d8e91e46SDimitry Andric class FileWithFixedStatus : public File {
2502d8e91e46SDimitry Andric std::unique_ptr<File> InnerFile;
2503d8e91e46SDimitry Andric Status S;
2504d8e91e46SDimitry Andric
2505d8e91e46SDimitry Andric public:
FileWithFixedStatus(std::unique_ptr<File> InnerFile,Status S)2506d8e91e46SDimitry Andric FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
2507d8e91e46SDimitry Andric : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
2508d8e91e46SDimitry Andric
status()2509d8e91e46SDimitry Andric ErrorOr<Status> status() override { return S; }
2510d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2511d8e91e46SDimitry Andric
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)2512d8e91e46SDimitry Andric getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
2513d8e91e46SDimitry Andric bool IsVolatile) override {
2514d8e91e46SDimitry Andric return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
2515d8e91e46SDimitry Andric IsVolatile);
2516d8e91e46SDimitry Andric }
2517d8e91e46SDimitry Andric
close()2518d8e91e46SDimitry Andric std::error_code close() override { return InnerFile->close(); }
2519c0981da4SDimitry Andric
setPath(const Twine & Path)2520c0981da4SDimitry Andric void setPath(const Twine &Path) override { S = S.copyWithNewName(S, Path); }
2521d8e91e46SDimitry Andric };
2522d8e91e46SDimitry Andric
2523d8e91e46SDimitry Andric } // namespace
2524d8e91e46SDimitry Andric
2525d8e91e46SDimitry Andric ErrorOr<std::unique_ptr<File>>
getWithPath(ErrorOr<std::unique_ptr<File>> Result,const Twine & P)2526c0981da4SDimitry Andric File::getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P) {
2527145449b1SDimitry Andric // See \c getRedirectedFileStatus - don't update path if it's exposing an
2528145449b1SDimitry Andric // external path.
2529145449b1SDimitry Andric if (!Result || (*Result)->status()->ExposesExternalVFSPath)
2530c0981da4SDimitry Andric return Result;
2531b60736ecSDimitry Andric
2532c0981da4SDimitry Andric ErrorOr<std::unique_ptr<File>> F = std::move(*Result);
2533c0981da4SDimitry Andric auto Name = F->get()->getName();
2534c0981da4SDimitry Andric if (Name && Name.get() != P.str())
2535c0981da4SDimitry Andric F->get()->setPath(P);
2536c0981da4SDimitry Andric return F;
2537c0981da4SDimitry Andric }
2538c0981da4SDimitry Andric
2539c0981da4SDimitry Andric ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & OriginalPath)2540c0981da4SDimitry Andric RedirectingFileSystem::openFileForRead(const Twine &OriginalPath) {
2541ac9a064cSDimitry Andric SmallString<256> Path;
2542ac9a064cSDimitry Andric OriginalPath.toVector(Path);
2543c0981da4SDimitry Andric
2544ac9a064cSDimitry Andric if (std::error_code EC = makeAbsolute(Path))
2545b60736ecSDimitry Andric return EC;
2546b60736ecSDimitry Andric
2547145449b1SDimitry Andric if (Redirection == RedirectKind::Fallback) {
2548145449b1SDimitry Andric // Attempt to find the original file first, only falling back to the
2549145449b1SDimitry Andric // mapped file if that fails.
2550ac9a064cSDimitry Andric auto F = File::getWithPath(ExternalFS->openFileForRead(Path), OriginalPath);
2551145449b1SDimitry Andric if (F)
2552145449b1SDimitry Andric return F;
2553145449b1SDimitry Andric }
2554145449b1SDimitry Andric
2555ac9a064cSDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2556344a3780SDimitry Andric if (!Result) {
2557145449b1SDimitry Andric // Was not able to map file, fallthrough to using the original path if
2558145449b1SDimitry Andric // that was the specified redirection type.
2559145449b1SDimitry Andric if (Redirection == RedirectKind::Fallthrough &&
2560145449b1SDimitry Andric isFileNotFound(Result.getError()))
2561ac9a064cSDimitry Andric return File::getWithPath(ExternalFS->openFileForRead(Path), OriginalPath);
2562344a3780SDimitry Andric return Result.getError();
2563d8e91e46SDimitry Andric }
2564d8e91e46SDimitry Andric
2565344a3780SDimitry Andric if (!Result->getExternalRedirect()) // FIXME: errc::not_a_file?
2566d8e91e46SDimitry Andric return make_error_code(llvm::errc::invalid_argument);
2567d8e91e46SDimitry Andric
2568344a3780SDimitry Andric StringRef ExtRedirect = *Result->getExternalRedirect();
2569ac9a064cSDimitry Andric SmallString<256> RemappedPath(ExtRedirect.str());
2570ac9a064cSDimitry Andric if (std::error_code EC = makeAbsolute(RemappedPath))
2571c0981da4SDimitry Andric return EC;
2572c0981da4SDimitry Andric
2573344a3780SDimitry Andric auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result->E);
2574d8e91e46SDimitry Andric
2575ac9a064cSDimitry Andric auto ExternalFile =
2576ac9a064cSDimitry Andric File::getWithPath(ExternalFS->openFileForRead(RemappedPath), ExtRedirect);
2577344a3780SDimitry Andric if (!ExternalFile) {
2578145449b1SDimitry Andric if (Redirection == RedirectKind::Fallthrough &&
2579145449b1SDimitry Andric isFileNotFound(ExternalFile.getError(), Result->E)) {
2580145449b1SDimitry Andric // Mapped the file but it wasn't found in the underlying filesystem,
2581145449b1SDimitry Andric // fallthrough to using the original path if that was the specified
2582145449b1SDimitry Andric // redirection type.
2583ac9a064cSDimitry Andric return File::getWithPath(ExternalFS->openFileForRead(Path), OriginalPath);
2584145449b1SDimitry Andric }
2585344a3780SDimitry Andric return ExternalFile;
2586344a3780SDimitry Andric }
2587344a3780SDimitry Andric
2588344a3780SDimitry Andric auto ExternalStatus = (*ExternalFile)->status();
2589d8e91e46SDimitry Andric if (!ExternalStatus)
2590d8e91e46SDimitry Andric return ExternalStatus.getError();
2591d8e91e46SDimitry Andric
2592145449b1SDimitry Andric // Otherwise, the file was successfully remapped. Mark it as such. Also
2593145449b1SDimitry Andric // replace the underlying path if the external name is being used.
2594344a3780SDimitry Andric Status S = getRedirectedFileStatus(
2595c0981da4SDimitry Andric OriginalPath, RE->useExternalName(UseExternalNames), *ExternalStatus);
2596d8e91e46SDimitry Andric return std::unique_ptr<File>(
2597344a3780SDimitry Andric std::make_unique<FileWithFixedStatus>(std::move(*ExternalFile), S));
2598d8e91e46SDimitry Andric }
2599d8e91e46SDimitry Andric
2600d8e91e46SDimitry Andric std::error_code
getRealPath(const Twine & OriginalPath,SmallVectorImpl<char> & Output)2601145449b1SDimitry Andric RedirectingFileSystem::getRealPath(const Twine &OriginalPath,
2602ac9a064cSDimitry Andric SmallVectorImpl<char> &Output) {
2603ac9a064cSDimitry Andric SmallString<256> Path;
2604ac9a064cSDimitry Andric OriginalPath.toVector(Path);
2605b60736ecSDimitry Andric
2606ac9a064cSDimitry Andric if (std::error_code EC = makeAbsolute(Path))
2607b60736ecSDimitry Andric return EC;
2608b60736ecSDimitry Andric
2609145449b1SDimitry Andric if (Redirection == RedirectKind::Fallback) {
2610145449b1SDimitry Andric // Attempt to find the original file first, only falling back to the
2611145449b1SDimitry Andric // mapped file if that fails.
2612ac9a064cSDimitry Andric std::error_code EC = ExternalFS->getRealPath(Path, Output);
2613145449b1SDimitry Andric if (!EC)
2614145449b1SDimitry Andric return EC;
2615145449b1SDimitry Andric }
2616145449b1SDimitry Andric
2617ac9a064cSDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path);
2618d8e91e46SDimitry Andric if (!Result) {
2619145449b1SDimitry Andric // Was not able to map file, fallthrough to using the original path if
2620145449b1SDimitry Andric // that was the specified redirection type.
2621145449b1SDimitry Andric if (Redirection == RedirectKind::Fallthrough &&
2622145449b1SDimitry Andric isFileNotFound(Result.getError()))
2623ac9a064cSDimitry Andric return ExternalFS->getRealPath(Path, Output);
2624d8e91e46SDimitry Andric return Result.getError();
2625d8e91e46SDimitry Andric }
2626d8e91e46SDimitry Andric
2627344a3780SDimitry Andric // If we found FileEntry or DirectoryRemapEntry, look up the mapped
2628344a3780SDimitry Andric // path in the external file system.
2629344a3780SDimitry Andric if (auto ExtRedirect = Result->getExternalRedirect()) {
2630344a3780SDimitry Andric auto P = ExternalFS->getRealPath(*ExtRedirect, Output);
2631145449b1SDimitry Andric if (P && Redirection == RedirectKind::Fallthrough &&
2632145449b1SDimitry Andric isFileNotFound(P, Result->E)) {
2633145449b1SDimitry Andric // Mapped the file but it wasn't found in the underlying filesystem,
2634145449b1SDimitry Andric // fallthrough to using the original path if that was the specified
2635145449b1SDimitry Andric // redirection type.
2636ac9a064cSDimitry Andric return ExternalFS->getRealPath(Path, Output);
2637d8e91e46SDimitry Andric }
2638344a3780SDimitry Andric return P;
2639344a3780SDimitry Andric }
2640344a3780SDimitry Andric
26417fa27ce4SDimitry Andric // We found a DirectoryEntry, which does not have a single external contents
26427fa27ce4SDimitry Andric // path. Use the canonical virtual path.
26437fa27ce4SDimitry Andric if (Redirection == RedirectKind::Fallthrough) {
26447fa27ce4SDimitry Andric Result->getPath(Output);
26457fa27ce4SDimitry Andric return {};
26467fa27ce4SDimitry Andric }
2647145449b1SDimitry Andric return llvm::errc::invalid_argument;
2648d8e91e46SDimitry Andric }
2649d8e91e46SDimitry Andric
2650b60736ecSDimitry Andric std::unique_ptr<FileSystem>
getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)2651d8e91e46SDimitry Andric vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2652d8e91e46SDimitry Andric SourceMgr::DiagHandlerTy DiagHandler,
2653d8e91e46SDimitry Andric StringRef YAMLFilePath, void *DiagContext,
2654d8e91e46SDimitry Andric IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2655d8e91e46SDimitry Andric return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
2656d8e91e46SDimitry Andric YAMLFilePath, DiagContext,
2657d8e91e46SDimitry Andric std::move(ExternalFS));
2658d8e91e46SDimitry Andric }
2659d8e91e46SDimitry Andric
getVFSEntries(RedirectingFileSystem::Entry * SrcE,SmallVectorImpl<StringRef> & Path,SmallVectorImpl<YAMLVFSEntry> & Entries)2660d8e91e46SDimitry Andric static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
2661d8e91e46SDimitry Andric SmallVectorImpl<StringRef> &Path,
2662d8e91e46SDimitry Andric SmallVectorImpl<YAMLVFSEntry> &Entries) {
2663d8e91e46SDimitry Andric auto Kind = SrcE->getKind();
2664d8e91e46SDimitry Andric if (Kind == RedirectingFileSystem::EK_Directory) {
2665344a3780SDimitry Andric auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(SrcE);
2666d8e91e46SDimitry Andric assert(DE && "Must be a directory");
2667d8e91e46SDimitry Andric for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
2668d8e91e46SDimitry Andric llvm::make_range(DE->contents_begin(), DE->contents_end())) {
2669d8e91e46SDimitry Andric Path.push_back(SubEntry->getName());
2670d8e91e46SDimitry Andric getVFSEntries(SubEntry.get(), Path, Entries);
2671d8e91e46SDimitry Andric Path.pop_back();
2672d8e91e46SDimitry Andric }
2673d8e91e46SDimitry Andric return;
2674d8e91e46SDimitry Andric }
2675d8e91e46SDimitry Andric
2676344a3780SDimitry Andric if (Kind == RedirectingFileSystem::EK_DirectoryRemap) {
2677344a3780SDimitry Andric auto *DR = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE);
2678344a3780SDimitry Andric assert(DR && "Must be a directory remap");
2679344a3780SDimitry Andric SmallString<128> VPath;
2680344a3780SDimitry Andric for (auto &Comp : Path)
2681344a3780SDimitry Andric llvm::sys::path::append(VPath, Comp);
2682344a3780SDimitry Andric Entries.push_back(
2683344a3780SDimitry Andric YAMLVFSEntry(VPath.c_str(), DR->getExternalContentsPath()));
2684344a3780SDimitry Andric return;
2685344a3780SDimitry Andric }
2686344a3780SDimitry Andric
2687d8e91e46SDimitry Andric assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
2688344a3780SDimitry Andric auto *FE = dyn_cast<RedirectingFileSystem::FileEntry>(SrcE);
2689d8e91e46SDimitry Andric assert(FE && "Must be a file");
2690d8e91e46SDimitry Andric SmallString<128> VPath;
2691d8e91e46SDimitry Andric for (auto &Comp : Path)
2692d8e91e46SDimitry Andric llvm::sys::path::append(VPath, Comp);
2693d8e91e46SDimitry Andric Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
2694d8e91e46SDimitry Andric }
2695d8e91e46SDimitry Andric
collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,SmallVectorImpl<YAMLVFSEntry> & CollectedEntries,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)2696d8e91e46SDimitry Andric void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
2697d8e91e46SDimitry Andric SourceMgr::DiagHandlerTy DiagHandler,
2698d8e91e46SDimitry Andric StringRef YAMLFilePath,
2699d8e91e46SDimitry Andric SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
2700d8e91e46SDimitry Andric void *DiagContext,
2701d8e91e46SDimitry Andric IntrusiveRefCntPtr<FileSystem> ExternalFS) {
2702b60736ecSDimitry Andric std::unique_ptr<RedirectingFileSystem> VFS = RedirectingFileSystem::create(
2703d8e91e46SDimitry Andric std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
2704d8e91e46SDimitry Andric std::move(ExternalFS));
2705344a3780SDimitry Andric if (!VFS)
2706344a3780SDimitry Andric return;
2707344a3780SDimitry Andric ErrorOr<RedirectingFileSystem::LookupResult> RootResult =
2708344a3780SDimitry Andric VFS->lookupPath("/");
2709344a3780SDimitry Andric if (!RootResult)
2710d8e91e46SDimitry Andric return;
2711d8e91e46SDimitry Andric SmallVector<StringRef, 8> Components;
2712d8e91e46SDimitry Andric Components.push_back("/");
2713344a3780SDimitry Andric getVFSEntries(RootResult->E, Components, CollectedEntries);
2714d8e91e46SDimitry Andric }
2715d8e91e46SDimitry Andric
getNextVirtualUniqueID()2716d8e91e46SDimitry Andric UniqueID vfs::getNextVirtualUniqueID() {
2717d8e91e46SDimitry Andric static std::atomic<unsigned> UID;
2718d8e91e46SDimitry Andric unsigned ID = ++UID;
2719d8e91e46SDimitry Andric // The following assumes that uint64_t max will never collide with a real
2720d8e91e46SDimitry Andric // dev_t value from the OS.
2721d8e91e46SDimitry Andric return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
2722d8e91e46SDimitry Andric }
2723d8e91e46SDimitry Andric
addEntry(StringRef VirtualPath,StringRef RealPath,bool IsDirectory)2724cfca06d7SDimitry Andric void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath,
2725cfca06d7SDimitry Andric bool IsDirectory) {
2726d8e91e46SDimitry Andric assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
2727d8e91e46SDimitry Andric assert(sys::path::is_absolute(RealPath) && "real path not absolute");
2728d8e91e46SDimitry Andric assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
2729cfca06d7SDimitry Andric Mappings.emplace_back(VirtualPath, RealPath, IsDirectory);
2730cfca06d7SDimitry Andric }
2731cfca06d7SDimitry Andric
addFileMapping(StringRef VirtualPath,StringRef RealPath)2732cfca06d7SDimitry Andric void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
2733cfca06d7SDimitry Andric addEntry(VirtualPath, RealPath, /*IsDirectory=*/false);
2734cfca06d7SDimitry Andric }
2735cfca06d7SDimitry Andric
addDirectoryMapping(StringRef VirtualPath,StringRef RealPath)2736cfca06d7SDimitry Andric void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath,
2737cfca06d7SDimitry Andric StringRef RealPath) {
2738cfca06d7SDimitry Andric addEntry(VirtualPath, RealPath, /*IsDirectory=*/true);
2739d8e91e46SDimitry Andric }
2740d8e91e46SDimitry Andric
2741d8e91e46SDimitry Andric namespace {
2742d8e91e46SDimitry Andric
2743d8e91e46SDimitry Andric class JSONWriter {
2744d8e91e46SDimitry Andric llvm::raw_ostream &OS;
2745d8e91e46SDimitry Andric SmallVector<StringRef, 16> DirStack;
2746d8e91e46SDimitry Andric
getDirIndent()2747d8e91e46SDimitry Andric unsigned getDirIndent() { return 4 * DirStack.size(); }
getFileIndent()2748d8e91e46SDimitry Andric unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
2749d8e91e46SDimitry Andric bool containedIn(StringRef Parent, StringRef Path);
2750d8e91e46SDimitry Andric StringRef containedPart(StringRef Parent, StringRef Path);
2751d8e91e46SDimitry Andric void startDirectory(StringRef Path);
2752d8e91e46SDimitry Andric void endDirectory();
2753d8e91e46SDimitry Andric void writeEntry(StringRef VPath, StringRef RPath);
2754d8e91e46SDimitry Andric
2755d8e91e46SDimitry Andric public:
JSONWriter(llvm::raw_ostream & OS)2756d8e91e46SDimitry Andric JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
2757d8e91e46SDimitry Andric
2758e3b55780SDimitry Andric void write(ArrayRef<YAMLVFSEntry> Entries,
2759e3b55780SDimitry Andric std::optional<bool> UseExternalNames,
2760e3b55780SDimitry Andric std::optional<bool> IsCaseSensitive,
2761e3b55780SDimitry Andric std::optional<bool> IsOverlayRelative, StringRef OverlayDir);
2762d8e91e46SDimitry Andric };
2763d8e91e46SDimitry Andric
2764d8e91e46SDimitry Andric } // namespace
2765d8e91e46SDimitry Andric
containedIn(StringRef Parent,StringRef Path)2766d8e91e46SDimitry Andric bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2767d8e91e46SDimitry Andric using namespace llvm::sys;
2768d8e91e46SDimitry Andric
2769d8e91e46SDimitry Andric // Compare each path component.
2770d8e91e46SDimitry Andric auto IParent = path::begin(Parent), EParent = path::end(Parent);
2771d8e91e46SDimitry Andric for (auto IChild = path::begin(Path), EChild = path::end(Path);
2772d8e91e46SDimitry Andric IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2773d8e91e46SDimitry Andric if (*IParent != *IChild)
2774d8e91e46SDimitry Andric return false;
2775d8e91e46SDimitry Andric }
2776d8e91e46SDimitry Andric // Have we exhausted the parent path?
2777d8e91e46SDimitry Andric return IParent == EParent;
2778d8e91e46SDimitry Andric }
2779d8e91e46SDimitry Andric
containedPart(StringRef Parent,StringRef Path)2780d8e91e46SDimitry Andric StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2781d8e91e46SDimitry Andric assert(!Parent.empty());
2782d8e91e46SDimitry Andric assert(containedIn(Parent, Path));
2783d8e91e46SDimitry Andric return Path.slice(Parent.size() + 1, StringRef::npos);
2784d8e91e46SDimitry Andric }
2785d8e91e46SDimitry Andric
startDirectory(StringRef Path)2786d8e91e46SDimitry Andric void JSONWriter::startDirectory(StringRef Path) {
2787d8e91e46SDimitry Andric StringRef Name =
2788d8e91e46SDimitry Andric DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
2789d8e91e46SDimitry Andric DirStack.push_back(Path);
2790d8e91e46SDimitry Andric unsigned Indent = getDirIndent();
2791d8e91e46SDimitry Andric OS.indent(Indent) << "{\n";
2792d8e91e46SDimitry Andric OS.indent(Indent + 2) << "'type': 'directory',\n";
2793d8e91e46SDimitry Andric OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
2794d8e91e46SDimitry Andric OS.indent(Indent + 2) << "'contents': [\n";
2795d8e91e46SDimitry Andric }
2796d8e91e46SDimitry Andric
endDirectory()2797d8e91e46SDimitry Andric void JSONWriter::endDirectory() {
2798d8e91e46SDimitry Andric unsigned Indent = getDirIndent();
2799d8e91e46SDimitry Andric OS.indent(Indent + 2) << "]\n";
2800d8e91e46SDimitry Andric OS.indent(Indent) << "}";
2801d8e91e46SDimitry Andric
2802d8e91e46SDimitry Andric DirStack.pop_back();
2803d8e91e46SDimitry Andric }
2804d8e91e46SDimitry Andric
writeEntry(StringRef VPath,StringRef RPath)2805d8e91e46SDimitry Andric void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2806d8e91e46SDimitry Andric unsigned Indent = getFileIndent();
2807d8e91e46SDimitry Andric OS.indent(Indent) << "{\n";
2808d8e91e46SDimitry Andric OS.indent(Indent + 2) << "'type': 'file',\n";
2809d8e91e46SDimitry Andric OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
2810d8e91e46SDimitry Andric OS.indent(Indent + 2) << "'external-contents': \""
2811d8e91e46SDimitry Andric << llvm::yaml::escape(RPath) << "\"\n";
2812d8e91e46SDimitry Andric OS.indent(Indent) << "}";
2813d8e91e46SDimitry Andric }
2814d8e91e46SDimitry Andric
write(ArrayRef<YAMLVFSEntry> Entries,std::optional<bool> UseExternalNames,std::optional<bool> IsCaseSensitive,std::optional<bool> IsOverlayRelative,StringRef OverlayDir)2815d8e91e46SDimitry Andric void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
2816e3b55780SDimitry Andric std::optional<bool> UseExternalNames,
2817e3b55780SDimitry Andric std::optional<bool> IsCaseSensitive,
2818e3b55780SDimitry Andric std::optional<bool> IsOverlayRelative,
2819d8e91e46SDimitry Andric StringRef OverlayDir) {
2820d8e91e46SDimitry Andric using namespace llvm::sys;
2821d8e91e46SDimitry Andric
2822d8e91e46SDimitry Andric OS << "{\n"
2823d8e91e46SDimitry Andric " 'version': 0,\n";
2824145449b1SDimitry Andric if (IsCaseSensitive)
2825e3b55780SDimitry Andric OS << " 'case-sensitive': '" << (*IsCaseSensitive ? "true" : "false")
2826e3b55780SDimitry Andric << "',\n";
2827145449b1SDimitry Andric if (UseExternalNames)
2828e3b55780SDimitry Andric OS << " 'use-external-names': '" << (*UseExternalNames ? "true" : "false")
2829e3b55780SDimitry Andric << "',\n";
2830d8e91e46SDimitry Andric bool UseOverlayRelative = false;
2831145449b1SDimitry Andric if (IsOverlayRelative) {
2832e3b55780SDimitry Andric UseOverlayRelative = *IsOverlayRelative;
2833d8e91e46SDimitry Andric OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2834d8e91e46SDimitry Andric << "',\n";
2835d8e91e46SDimitry Andric }
2836d8e91e46SDimitry Andric OS << " 'roots': [\n";
2837d8e91e46SDimitry Andric
2838d8e91e46SDimitry Andric if (!Entries.empty()) {
2839d8e91e46SDimitry Andric const YAMLVFSEntry &Entry = Entries.front();
2840cfca06d7SDimitry Andric
2841cfca06d7SDimitry Andric startDirectory(
2842cfca06d7SDimitry Andric Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath)
2843cfca06d7SDimitry Andric );
2844d8e91e46SDimitry Andric
2845d8e91e46SDimitry Andric StringRef RPath = Entry.RPath;
2846d8e91e46SDimitry Andric if (UseOverlayRelative) {
2847ac9a064cSDimitry Andric assert(RPath.starts_with(OverlayDir) &&
2848d8e91e46SDimitry Andric "Overlay dir must be contained in RPath");
2849ac9a064cSDimitry Andric RPath = RPath.slice(OverlayDir.size(), RPath.size());
2850d8e91e46SDimitry Andric }
2851d8e91e46SDimitry Andric
2852cfca06d7SDimitry Andric bool IsCurrentDirEmpty = true;
2853cfca06d7SDimitry Andric if (!Entry.IsDirectory) {
2854d8e91e46SDimitry Andric writeEntry(path::filename(Entry.VPath), RPath);
2855cfca06d7SDimitry Andric IsCurrentDirEmpty = false;
2856cfca06d7SDimitry Andric }
2857d8e91e46SDimitry Andric
2858d8e91e46SDimitry Andric for (const auto &Entry : Entries.slice(1)) {
2859cfca06d7SDimitry Andric StringRef Dir =
2860cfca06d7SDimitry Andric Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath);
2861cfca06d7SDimitry Andric if (Dir == DirStack.back()) {
2862cfca06d7SDimitry Andric if (!IsCurrentDirEmpty) {
2863d8e91e46SDimitry Andric OS << ",\n";
2864cfca06d7SDimitry Andric }
2865cfca06d7SDimitry Andric } else {
2866cfca06d7SDimitry Andric bool IsDirPoppedFromStack = false;
2867d8e91e46SDimitry Andric while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2868d8e91e46SDimitry Andric OS << "\n";
2869d8e91e46SDimitry Andric endDirectory();
2870cfca06d7SDimitry Andric IsDirPoppedFromStack = true;
2871d8e91e46SDimitry Andric }
2872cfca06d7SDimitry Andric if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
2873d8e91e46SDimitry Andric OS << ",\n";
2874cfca06d7SDimitry Andric }
2875d8e91e46SDimitry Andric startDirectory(Dir);
2876cfca06d7SDimitry Andric IsCurrentDirEmpty = true;
2877d8e91e46SDimitry Andric }
2878d8e91e46SDimitry Andric StringRef RPath = Entry.RPath;
2879d8e91e46SDimitry Andric if (UseOverlayRelative) {
2880ac9a064cSDimitry Andric assert(RPath.starts_with(OverlayDir) &&
2881d8e91e46SDimitry Andric "Overlay dir must be contained in RPath");
2882ac9a064cSDimitry Andric RPath = RPath.slice(OverlayDir.size(), RPath.size());
2883d8e91e46SDimitry Andric }
2884cfca06d7SDimitry Andric if (!Entry.IsDirectory) {
2885d8e91e46SDimitry Andric writeEntry(path::filename(Entry.VPath), RPath);
2886cfca06d7SDimitry Andric IsCurrentDirEmpty = false;
2887cfca06d7SDimitry Andric }
2888d8e91e46SDimitry Andric }
2889d8e91e46SDimitry Andric
2890d8e91e46SDimitry Andric while (!DirStack.empty()) {
2891d8e91e46SDimitry Andric OS << "\n";
2892d8e91e46SDimitry Andric endDirectory();
2893d8e91e46SDimitry Andric }
2894d8e91e46SDimitry Andric OS << "\n";
2895d8e91e46SDimitry Andric }
2896d8e91e46SDimitry Andric
2897d8e91e46SDimitry Andric OS << " ]\n"
2898d8e91e46SDimitry Andric << "}\n";
2899d8e91e46SDimitry Andric }
2900d8e91e46SDimitry Andric
write(llvm::raw_ostream & OS)2901d8e91e46SDimitry Andric void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2902d8e91e46SDimitry Andric llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2903d8e91e46SDimitry Andric return LHS.VPath < RHS.VPath;
2904d8e91e46SDimitry Andric });
2905d8e91e46SDimitry Andric
2906d8e91e46SDimitry Andric JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
2907d8e91e46SDimitry Andric IsOverlayRelative, OverlayDir);
2908d8e91e46SDimitry Andric }
2909d8e91e46SDimitry Andric
recursive_directory_iterator(FileSystem & FS_,const Twine & Path,std::error_code & EC)2910d8e91e46SDimitry Andric vfs::recursive_directory_iterator::recursive_directory_iterator(
2911d8e91e46SDimitry Andric FileSystem &FS_, const Twine &Path, std::error_code &EC)
2912d8e91e46SDimitry Andric : FS(&FS_) {
2913d8e91e46SDimitry Andric directory_iterator I = FS->dir_begin(Path, EC);
2914d8e91e46SDimitry Andric if (I != directory_iterator()) {
2915d8e91e46SDimitry Andric State = std::make_shared<detail::RecDirIterState>();
2916ac9a064cSDimitry Andric State->Stack.push_back(I);
2917d8e91e46SDimitry Andric }
2918d8e91e46SDimitry Andric }
2919d8e91e46SDimitry Andric
2920d8e91e46SDimitry Andric vfs::recursive_directory_iterator &
increment(std::error_code & EC)2921d8e91e46SDimitry Andric recursive_directory_iterator::increment(std::error_code &EC) {
2922d8e91e46SDimitry Andric assert(FS && State && !State->Stack.empty() && "incrementing past end");
2923ac9a064cSDimitry Andric assert(!State->Stack.back()->path().empty() && "non-canonical end iterator");
2924d8e91e46SDimitry Andric vfs::directory_iterator End;
2925d8e91e46SDimitry Andric
2926d8e91e46SDimitry Andric if (State->HasNoPushRequest)
2927d8e91e46SDimitry Andric State->HasNoPushRequest = false;
2928d8e91e46SDimitry Andric else {
2929ac9a064cSDimitry Andric if (State->Stack.back()->type() == sys::fs::file_type::directory_file) {
2930ac9a064cSDimitry Andric vfs::directory_iterator I =
2931ac9a064cSDimitry Andric FS->dir_begin(State->Stack.back()->path(), EC);
2932d8e91e46SDimitry Andric if (I != End) {
2933ac9a064cSDimitry Andric State->Stack.push_back(I);
2934d8e91e46SDimitry Andric return *this;
2935d8e91e46SDimitry Andric }
2936d8e91e46SDimitry Andric }
2937d8e91e46SDimitry Andric }
2938d8e91e46SDimitry Andric
2939ac9a064cSDimitry Andric while (!State->Stack.empty() && State->Stack.back().increment(EC) == End)
2940ac9a064cSDimitry Andric State->Stack.pop_back();
2941d8e91e46SDimitry Andric
2942d8e91e46SDimitry Andric if (State->Stack.empty())
2943d8e91e46SDimitry Andric State.reset(); // end iterator
2944d8e91e46SDimitry Andric
2945d8e91e46SDimitry Andric return *this;
2946d8e91e46SDimitry Andric }
2947ac9a064cSDimitry Andric
2948ac9a064cSDimitry Andric const char FileSystem::ID = 0;
2949ac9a064cSDimitry Andric const char OverlayFileSystem::ID = 0;
2950ac9a064cSDimitry Andric const char ProxyFileSystem::ID = 0;
2951ac9a064cSDimitry Andric const char InMemoryFileSystem::ID = 0;
2952ac9a064cSDimitry Andric const char RedirectingFileSystem::ID = 0;
2953