blob: a7b8b024a47807fc5cfa09b0e3712dd5229f4526 [file] [log] [blame]
Eugene Zelenko5a520112018-03-28 22:09:09 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
Ben Langmuirc8130a72014-02-20 21:59:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko5a520112018-03-28 22:09:09 +00009//
Ben Langmuirc8130a72014-02-20 21:59:23 +000010// This file implements the VirtualFileSystem interface.
Eugene Zelenko5a520112018-03-28 22:09:09 +000011//
Ben Langmuirc8130a72014-02-20 21:59:23 +000012//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/VirtualFileSystem.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000015#include "clang/Basic/LLVM.h"
16#include "llvm/ADT/ArrayRef.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000018#include "llvm/ADT/IntrusiveRefCntPtr.h"
19#include "llvm/ADT/Optional.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000020#include "llvm/ADT/STLExtras.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000024#include "llvm/ADT/StringSet.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000025#include "llvm/ADT/Twine.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "llvm/ADT/iterator_range.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000027#include "llvm/Config/llvm-config.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000028#include "llvm/Support/Compiler.h"
29#include "llvm/Support/Casting.h"
30#include "llvm/Support/Chrono.h"
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +000031#include "llvm/Support/Debug.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000032#include "llvm/Support/Errc.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000033#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/ErrorOr.h"
35#include "llvm/Support/FileSystem.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000036#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000037#include "llvm/Support/Path.h"
David Majnemer6a6206d2016-03-04 05:26:14 +000038#include "llvm/Support/Process.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000039#include "llvm/Support/SMLoc.h"
40#include "llvm/Support/SourceMgr.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000041#include "llvm/Support/YAMLParser.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000042#include "llvm/Support/raw_ostream.h"
43#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000044#include <atomic>
Eugene Zelenko5a520112018-03-28 22:09:09 +000045#include <cassert>
46#include <cstdint>
47#include <iterator>
48#include <limits>
49#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000050#include <memory>
Eugene Zelenko5a520112018-03-28 22:09:09 +000051#include <string>
52#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000053#include <utility>
Eugene Zelenko5a520112018-03-28 22:09:09 +000054#include <vector>
Ben Langmuirc8130a72014-02-20 21:59:23 +000055
56using namespace clang;
Eugene Zelenko5a520112018-03-28 22:09:09 +000057using namespace vfs;
Ben Langmuirc8130a72014-02-20 21:59:23 +000058using namespace llvm;
Eugene Zelenko5a520112018-03-28 22:09:09 +000059
Ben Langmuirc8130a72014-02-20 21:59:23 +000060using llvm::sys::fs::file_status;
61using llvm::sys::fs::file_type;
62using llvm::sys::fs::perms;
63using llvm::sys::fs::UniqueID;
64
65Status::Status(const file_status &Status)
66 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
67 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Eugene Zelenko5a520112018-03-28 22:09:09 +000068 Type(Status.type()), Perms(Status.permissions()) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000069
Pavel Labathac71c8e2016-11-09 10:52:22 +000070Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime,
Benjamin Kramer268b51a2015-10-05 13:15:33 +000071 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
72 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000073 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Eugene Zelenko5a520112018-03-28 22:09:09 +000074 Type(Type), Perms(Perms) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000075
Jordan Rupprechta8fb7292018-07-24 20:28:07 +000076Status Status::copyWithNewName(const Status &In, StringRef NewName) {
77 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
78 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
79 In.getPermissions());
80}
Benjamin Kramer268b51a2015-10-05 13:15:33 +000081
Jordan Rupprechta8fb7292018-07-24 20:28:07 +000082Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
83 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
84 In.getUser(), In.getGroup(), In.getSize(), In.type(),
85 In.permissions());
Benjamin Kramer268b51a2015-10-05 13:15:33 +000086}
87
Ben Langmuirc8130a72014-02-20 21:59:23 +000088bool Status::equivalent(const Status &Other) const {
Benjamin Kramerd5152912017-07-20 11:57:02 +000089 assert(isStatusKnown() && Other.isStatusKnown());
Ben Langmuirc8130a72014-02-20 21:59:23 +000090 return getUniqueID() == Other.getUniqueID();
91}
Eugene Zelenko5a520112018-03-28 22:09:09 +000092
Ben Langmuirc8130a72014-02-20 21:59:23 +000093bool Status::isDirectory() const {
94 return Type == file_type::directory_file;
95}
Eugene Zelenko5a520112018-03-28 22:09:09 +000096
Ben Langmuirc8130a72014-02-20 21:59:23 +000097bool Status::isRegularFile() const {
98 return Type == file_type::regular_file;
99}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000100
Ben Langmuirc8130a72014-02-20 21:59:23 +0000101bool Status::isOther() const {
102 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
103}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000104
Ben Langmuirc8130a72014-02-20 21:59:23 +0000105bool Status::isSymlink() const {
106 return Type == file_type::symlink_file;
107}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000108
Ben Langmuirc8130a72014-02-20 21:59:23 +0000109bool Status::isStatusKnown() const {
110 return Type != file_type::status_error;
111}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000112
Ben Langmuirc8130a72014-02-20 21:59:23 +0000113bool Status::exists() const {
114 return isStatusKnown() && Type != file_type::file_not_found;
115}
116
Eugene Zelenko5a520112018-03-28 22:09:09 +0000117File::~File() = default;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000118
Eugene Zelenko5a520112018-03-28 22:09:09 +0000119FileSystem::~FileSystem() = default;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000120
Benjamin Kramera8857962014-10-26 22:44:13 +0000121ErrorOr<std::unique_ptr<MemoryBuffer>>
122FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
123 bool RequiresNullTerminator, bool IsVolatile) {
124 auto F = openFileForRead(Name);
125 if (!F)
126 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000127
Benjamin Kramera8857962014-10-26 22:44:13 +0000128 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000129}
130
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000131std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +0000132 if (llvm::sys::path::is_absolute(Path))
Eugene Zelenko5a520112018-03-28 22:09:09 +0000133 return {};
Bob Wilsonf43354f2016-03-26 18:55:13 +0000134
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000135 auto WorkingDir = getCurrentWorkingDirectory();
136 if (!WorkingDir)
137 return WorkingDir.getError();
138
139 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
140}
141
Eric Liu5fb18fe2018-05-17 10:26:23 +0000142std::error_code FileSystem::getRealPath(const Twine &Path,
143 SmallVectorImpl<char> &Output) const {
144 return errc::operation_not_permitted;
145}
146
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000147bool FileSystem::exists(const Twine &Path) {
148 auto Status = status(Path);
149 return Status && Status->exists();
150}
151
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000152#ifndef NDEBUG
153static bool isTraversalComponent(StringRef Component) {
154 return Component.equals("..") || Component.equals(".");
155}
156
157static bool pathHasTraversal(StringRef Path) {
158 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000159
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000160 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
161 if (isTraversalComponent(Comp))
162 return true;
163 return false;
164}
165#endif
166
Ben Langmuirc8130a72014-02-20 21:59:23 +0000167//===-----------------------------------------------------------------------===/
168// RealFileSystem implementation
169//===-----------------------------------------------------------------------===/
170
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000171namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000172
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000173/// Wrapper around a raw file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000174class RealFile : public File {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000175 friend class RealFileSystem;
176
Ben Langmuirc8130a72014-02-20 21:59:23 +0000177 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000178 Status S;
Taewook Ohf42103c2016-06-13 20:40:21 +0000179 std::string RealName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000180
Taewook Ohf42103c2016-06-13 20:40:21 +0000181 RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000182 : FD(FD), S(NewName, {}, {}, {}, {}, {},
Taewook Ohf42103c2016-06-13 20:40:21 +0000183 llvm::sys::fs::file_type::status_error, {}),
184 RealName(NewRealPathName.str()) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000185 assert(FD >= 0 && "Invalid or inactive file descriptor");
186 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000187
Ben Langmuirc8130a72014-02-20 21:59:23 +0000188public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000189 ~RealFile() override;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000190
Craig Toppera798a9d2014-03-02 09:32:10 +0000191 ErrorOr<Status> status() override;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000192 ErrorOr<std::string> getName() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000193 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
194 int64_t FileSize,
195 bool RequiresNullTerminator,
196 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000197 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000198};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000199
200} // namespace
201
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000202RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000203
204ErrorOr<Status> RealFile::status() {
205 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000206 if (!S.isStatusKnown()) {
207 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000208 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000209 return EC;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000210 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000211 }
212 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000213}
214
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000215ErrorOr<std::string> RealFile::getName() {
216 return RealName.empty() ? S.getName().str() : RealName;
Taewook Ohf42103c2016-06-13 20:40:21 +0000217}
218
Benjamin Kramera8857962014-10-26 22:44:13 +0000219ErrorOr<std::unique_ptr<MemoryBuffer>>
220RealFile::getBuffer(const Twine &Name, int64_t FileSize,
221 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000222 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000223 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
224 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000225}
226
Rafael Espindola8e650d72014-06-12 20:37:59 +0000227std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000228 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000229 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000230 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000231}
232
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000233namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000234
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000235/// The file system according to your operating system.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000236class RealFileSystem : public FileSystem {
237public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000238 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000239 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000240 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000241
242 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
243 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Eric Liu5fb18fe2018-05-17 10:26:23 +0000244 std::error_code getRealPath(const Twine &Path,
245 SmallVectorImpl<char> &Output) const override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000246};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000247
248} // namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000249
250ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
251 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000252 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000253 return EC;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000254 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000255}
256
Benjamin Kramera8857962014-10-26 22:44:13 +0000257ErrorOr<std::unique_ptr<File>>
258RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000259 int FD;
Taewook Ohf42103c2016-06-13 20:40:21 +0000260 SmallString<256> RealName;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000261 if (std::error_code EC =
262 sys::fs::openFileForRead(Name, FD, sys::fs::OF_None, &RealName))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000263 return EC;
Taewook Ohf42103c2016-06-13 20:40:21 +0000264 return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000265}
266
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000267llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
268 SmallString<256> Dir;
269 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
270 return EC;
271 return Dir.str().str();
272}
273
274std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
275 // FIXME: chdir is thread hostile; on the other hand, creating the same
276 // behavior as chdir is complex: chdir resolves the path once, thus
277 // guaranteeing that all subsequent relative path operations work
278 // on the same path the original chdir resulted in. This makes a
279 // difference for example on network filesystems, where symlinks might be
280 // switched during runtime of the tool. Fixing this depends on having a
281 // file system abstraction that allows openat() style interactions.
Pavel Labathdcbd6142017-01-24 11:14:29 +0000282 return llvm::sys::fs::set_current_path(Path);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000283}
284
Eric Liu5fb18fe2018-05-17 10:26:23 +0000285std::error_code
286RealFileSystem::getRealPath(const Twine &Path,
287 SmallVectorImpl<char> &Output) const {
288 return llvm::sys::fs::real_path(Path, Output);
289}
290
Ben Langmuirc8130a72014-02-20 21:59:23 +0000291IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
292 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
293 return FS;
294}
295
Ben Langmuir740812b2014-06-24 19:37:16 +0000296namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000297
Ben Langmuir740812b2014-06-24 19:37:16 +0000298class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000299 llvm::sys::fs::directory_iterator Iter;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000300
Ben Langmuir740812b2014-06-24 19:37:16 +0000301public:
Juergen Ributzka4a259562017-03-10 21:23:29 +0000302 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
Max Moroze0975672018-04-04 19:47:25 +0000303 if (Iter != llvm::sys::fs::directory_iterator()) {
Ben Langmuir740812b2014-06-24 19:37:16 +0000304 llvm::sys::fs::file_status S;
Max Moroze0975672018-04-04 19:47:25 +0000305 std::error_code ErrorCode = llvm::sys::fs::status(Iter->path(), S, true);
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000306 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Max Moroze0975672018-04-04 19:47:25 +0000307 if (!EC)
308 EC = ErrorCode;
Ben Langmuir740812b2014-06-24 19:37:16 +0000309 }
310 }
311
312 std::error_code increment() override {
313 std::error_code EC;
314 Iter.increment(EC);
Max Moroze0975672018-04-04 19:47:25 +0000315 if (Iter == llvm::sys::fs::directory_iterator()) {
Ben Langmuir740812b2014-06-24 19:37:16 +0000316 CurrentEntry = Status();
317 } else {
318 llvm::sys::fs::file_status S;
Max Moroze0975672018-04-04 19:47:25 +0000319 std::error_code ErrorCode = llvm::sys::fs::status(Iter->path(), S, true);
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000320 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Max Moroze0975672018-04-04 19:47:25 +0000321 if (!EC)
322 EC = ErrorCode;
Ben Langmuir740812b2014-06-24 19:37:16 +0000323 }
324 return EC;
325 }
326};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000327
328} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000329
330directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
331 std::error_code &EC) {
332 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
333}
334
Ben Langmuirc8130a72014-02-20 21:59:23 +0000335//===-----------------------------------------------------------------------===/
336// OverlayFileSystem implementation
337//===-----------------------------------------------------------------------===/
Eugene Zelenko5a520112018-03-28 22:09:09 +0000338
Ben Langmuirc8130a72014-02-20 21:59:23 +0000339OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000340 FSList.push_back(std::move(BaseFS));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000341}
342
343void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
344 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000345 // Synchronize added file systems by duplicating the working directory from
346 // the first one in the list.
347 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000348}
349
350ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
351 // FIXME: handle symlinks that cross file systems
352 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
353 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000354 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000355 return Status;
356 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000357 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000358}
359
Benjamin Kramera8857962014-10-26 22:44:13 +0000360ErrorOr<std::unique_ptr<File>>
361OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000362 // FIXME: handle symlinks that cross file systems
363 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000364 auto Result = (*I)->openFileForRead(Path);
365 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
366 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000367 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000368 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000369}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000370
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000371llvm::ErrorOr<std::string>
372OverlayFileSystem::getCurrentWorkingDirectory() const {
373 // All file systems are synchronized, just take the first working directory.
374 return FSList.front()->getCurrentWorkingDirectory();
375}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000376
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000377std::error_code
378OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
379 for (auto &FS : FSList)
380 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
381 return EC;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000382 return {};
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000383}
384
Eric Liua840a462018-05-18 13:22:49 +0000385std::error_code
386OverlayFileSystem::getRealPath(const Twine &Path,
387 SmallVectorImpl<char> &Output) const {
388 for (auto &FS : FSList)
389 if (FS->exists(Path))
390 return FS->getRealPath(Path, Output);
391 return errc::no_such_file_or_directory;
392}
393
Eugene Zelenko5a520112018-03-28 22:09:09 +0000394clang::vfs::detail::DirIterImpl::~DirIterImpl() = default;
Ben Langmuir740812b2014-06-24 19:37:16 +0000395
396namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000397
Ben Langmuir740812b2014-06-24 19:37:16 +0000398class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
399 OverlayFileSystem &Overlays;
400 std::string Path;
401 OverlayFileSystem::iterator CurrentFS;
402 directory_iterator CurrentDirIter;
403 llvm::StringSet<> SeenNames;
404
405 std::error_code incrementFS() {
406 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
407 ++CurrentFS;
408 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
409 std::error_code EC;
410 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
411 if (EC && EC != errc::no_such_file_or_directory)
412 return EC;
413 if (CurrentDirIter != directory_iterator())
414 break; // found
415 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000416 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +0000417 }
418
419 std::error_code incrementDirIter(bool IsFirstTime) {
420 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
421 "incrementing past end");
422 std::error_code EC;
423 if (!IsFirstTime)
424 CurrentDirIter.increment(EC);
425 if (!EC && CurrentDirIter == directory_iterator())
426 EC = incrementFS();
427 return EC;
428 }
429
430 std::error_code incrementImpl(bool IsFirstTime) {
431 while (true) {
432 std::error_code EC = incrementDirIter(IsFirstTime);
433 if (EC || CurrentDirIter == directory_iterator()) {
434 CurrentEntry = Status();
435 return EC;
436 }
437 CurrentEntry = *CurrentDirIter;
438 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000439 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000440 return EC; // name not seen before
441 }
442 llvm_unreachable("returned above");
443 }
444
445public:
446 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
447 std::error_code &EC)
448 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
449 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
450 EC = incrementImpl(true);
451 }
452
453 std::error_code increment() override { return incrementImpl(false); }
454};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000455
456} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000457
458directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
459 std::error_code &EC) {
460 return directory_iterator(
461 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
462}
463
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000464namespace clang {
465namespace vfs {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000466
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000467namespace detail {
468
469enum InMemoryNodeKind { IME_File, IME_Directory };
470
471/// The in memory file system is a tree of Nodes. Every node can either be a
472/// file or a directory.
473class InMemoryNode {
Simon Marchia37ef292018-07-11 14:08:17 +0000474 Status Stat;
Eric Liub71e6f42018-07-11 18:43:07 +0000475 InMemoryNodeKind Kind;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000476
Simon Marchiddbabc62018-08-06 21:48:20 +0000477protected:
478 /// Return Stat. This should only be used for internal/debugging use. When
479 /// clients wants the Status of this node, they should use
480 /// \p getStatus(StringRef).
481 const Status &getStatus() const { return Stat; }
482
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000483public:
484 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
Eric Liub71e6f42018-07-11 18:43:07 +0000485 : Stat(std::move(Stat)), Kind(Kind) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000486 virtual ~InMemoryNode() = default;
487
Simon Marchiddbabc62018-08-06 21:48:20 +0000488 /// Return the \p Status for this node. \p RequestedName should be the name
489 /// through which the caller referred to this node. It will override
490 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
491 Status getStatus(StringRef RequestedName) const {
492 return Status::copyWithNewName(Stat, RequestedName);
493 }
494
495 /// Get the filename of this node (the name without the directory part).
496 StringRef getFileName() const {
497 return llvm::sys::path::filename(Stat.getName());
498 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000499 InMemoryNodeKind getKind() const { return Kind; }
500 virtual std::string toString(unsigned Indent) const = 0;
501};
502
503namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000504
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000505class InMemoryFile : public InMemoryNode {
506 std::unique_ptr<llvm::MemoryBuffer> Buffer;
507
508public:
509 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
510 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
511
512 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000513
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000514 std::string toString(unsigned Indent) const override {
515 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
516 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000517
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000518 static bool classof(const InMemoryNode *N) {
519 return N->getKind() == IME_File;
520 }
521};
522
Simon Marchiddbabc62018-08-06 21:48:20 +0000523/// Adapt a InMemoryFile for VFS' File interface. The goal is to make
524/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
525/// \p RealFile.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000526class InMemoryFileAdaptor : public File {
527 InMemoryFile &Node;
Simon Marchiddbabc62018-08-06 21:48:20 +0000528 /// The name to use when returning a Status for this file.
529 std::string RequestedName;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000530
Simon Marchia37ef292018-07-11 14:08:17 +0000531public:
Simon Marchiddbabc62018-08-06 21:48:20 +0000532 explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string RequestedName)
533 : Node(Node), RequestedName(std::move(RequestedName)) {}
Simon Marchia37ef292018-07-11 14:08:17 +0000534
Simon Marchiddbabc62018-08-06 21:48:20 +0000535 llvm::ErrorOr<Status> status() override {
536 return Node.getStatus(RequestedName);
537 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000538
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000539 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000540 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
541 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000542 llvm::MemoryBuffer *Buf = Node.getBuffer();
543 return llvm::MemoryBuffer::getMemBuffer(
544 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
545 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000546
547 std::error_code close() override { return {}; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000548};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000549
550} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000551
552class InMemoryDirectory : public InMemoryNode {
553 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
554
555public:
556 InMemoryDirectory(Status Stat)
557 : InMemoryNode(std::move(Stat), IME_Directory) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000558
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000559 InMemoryNode *getChild(StringRef Name) {
560 auto I = Entries.find(Name);
561 if (I != Entries.end())
562 return I->second.get();
563 return nullptr;
564 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000565
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000566 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
567 return Entries.insert(make_pair(Name, std::move(Child)))
568 .first->second.get();
569 }
570
Eugene Zelenko5a520112018-03-28 22:09:09 +0000571 using const_iterator = decltype(Entries)::const_iterator;
572
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000573 const_iterator begin() const { return Entries.begin(); }
574 const_iterator end() const { return Entries.end(); }
575
576 std::string toString(unsigned Indent) const override {
577 std::string Result =
578 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000579 for (const auto &Entry : Entries)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000580 Result += Entry.second->toString(Indent + 2);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000581 return Result;
582 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000583
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000584 static bool classof(const InMemoryNode *N) {
585 return N->getKind() == IME_Directory;
586 }
587};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000588
589} // namespace detail
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000590
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000591InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000592 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000593 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
594 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000595 llvm::sys::fs::perms::all_all))),
596 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000597
Eugene Zelenko5a520112018-03-28 22:09:09 +0000598InMemoryFileSystem::~InMemoryFileSystem() = default;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000599
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000600std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000601 return Root->toString(/*Indent=*/0);
602}
603
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000604bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000605 std::unique_ptr<llvm::MemoryBuffer> Buffer,
606 Optional<uint32_t> User,
607 Optional<uint32_t> Group,
608 Optional<llvm::sys::fs::file_type> Type,
609 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000610 SmallString<128> Path;
611 P.toVector(Path);
612
613 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000614 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000615 assert(!EC);
616 (void)EC;
617
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000618 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000619 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000620
621 if (Path.empty())
622 return false;
623
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000624 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000625 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
626 const auto ResolvedUser = User.getValueOr(0);
627 const auto ResolvedGroup = Group.getValueOr(0);
628 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
629 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
630 // Any intermediate directories we create should be accessible by
631 // the owner, even if Perms says otherwise for the final path.
632 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000633 while (true) {
634 StringRef Name = *I;
635 detail::InMemoryNode *Node = Dir->getChild(Name);
636 ++I;
637 if (!Node) {
638 if (I == E) {
Ben Hamilton78381012017-11-16 19:34:08 +0000639 // End of the path, create a new file or directory.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000640 Status Stat(P.str(), getNextVirtualUniqueID(),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000641 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
642 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
643 ResolvedPerms);
Ben Hamilton78381012017-11-16 19:34:08 +0000644 std::unique_ptr<detail::InMemoryNode> Child;
645 if (ResolvedType == sys::fs::file_type::directory_file) {
646 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
647 } else {
648 Child.reset(new detail::InMemoryFile(std::move(Stat),
649 std::move(Buffer)));
650 }
651 Dir->addChild(Name, std::move(Child));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000652 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000653 }
654
655 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000656 Status Stat(
657 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000658 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
659 ResolvedUser, ResolvedGroup, Buffer->getBufferSize(),
660 sys::fs::file_type::directory_file, NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000661 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
662 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
663 continue;
664 }
665
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000666 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000667 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000668 } else {
669 assert(isa<detail::InMemoryFile>(Node) &&
670 "Must be either file or directory!");
671
672 // Trying to insert a directory in place of a file.
673 if (I != E)
674 return false;
675
676 // Return false only if the new file is different from the existing one.
677 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
678 Buffer->getBuffer();
679 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000680 }
681}
682
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000683bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000684 llvm::MemoryBuffer *Buffer,
685 Optional<uint32_t> User,
686 Optional<uint32_t> Group,
687 Optional<llvm::sys::fs::file_type> Type,
688 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000689 return addFile(P, ModificationTime,
690 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000691 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
692 std::move(User), std::move(Group), std::move(Type),
693 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000694}
695
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000696static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000697lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
698 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000699 SmallString<128> Path;
700 P.toVector(Path);
701
702 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000703 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000704 assert(!EC);
705 (void)EC;
706
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000707 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000708 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000709
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000710 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000711 return Dir;
712
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000713 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000714 while (true) {
715 detail::InMemoryNode *Node = Dir->getChild(*I);
716 ++I;
717 if (!Node)
718 return errc::no_such_file_or_directory;
719
720 // Return the file if it's at the end of the path.
721 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
722 if (I == E)
723 return File;
724 return errc::no_such_file_or_directory;
725 }
726
727 // Traverse directories.
728 Dir = cast<detail::InMemoryDirectory>(Node);
729 if (I == E)
730 return Dir;
731 }
732}
733
734llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000735 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000736 if (Node)
Simon Marchiddbabc62018-08-06 21:48:20 +0000737 return (*Node)->getStatus(Path.str());
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000738 return Node.getError();
739}
740
741llvm::ErrorOr<std::unique_ptr<File>>
742InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000743 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000744 if (!Node)
745 return Node.getError();
746
747 // When we have a file provide a heap-allocated wrapper for the memory buffer
748 // to match the ownership semantics for File.
749 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
Simon Marchiddbabc62018-08-06 21:48:20 +0000750 return std::unique_ptr<File>(
751 new detail::InMemoryFileAdaptor(*F, Path.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000752
753 // FIXME: errc::not_a_file?
754 return make_error_code(llvm::errc::invalid_argument);
755}
756
757namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000758
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000759/// Adaptor from InMemoryDir::iterator to directory_iterator.
760class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
761 detail::InMemoryDirectory::const_iterator I;
762 detail::InMemoryDirectory::const_iterator E;
Simon Marchiddbabc62018-08-06 21:48:20 +0000763 std::string RequestedDirName;
764
765 void setCurrentEntry() {
766 if (I != E) {
767 SmallString<256> Path(RequestedDirName);
768 llvm::sys::path::append(Path, I->second->getFileName());
769 CurrentEntry = I->second->getStatus(Path);
770 } else {
771 // When we're at the end, make CurrentEntry invalid and DirIterImpl will
772 // do the rest.
773 CurrentEntry = Status();
774 }
775 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000776
777public:
Eugene Zelenko5a520112018-03-28 22:09:09 +0000778 InMemoryDirIterator() = default;
779
Simon Marchiddbabc62018-08-06 21:48:20 +0000780 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir,
781 std::string RequestedDirName)
782 : I(Dir.begin()), E(Dir.end()),
783 RequestedDirName(std::move(RequestedDirName)) {
784 setCurrentEntry();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000785 }
786
787 std::error_code increment() override {
788 ++I;
Simon Marchiddbabc62018-08-06 21:48:20 +0000789 setCurrentEntry();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000790 return {};
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000791 }
792};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000793
794} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000795
796directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
797 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000798 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000799 if (!Node) {
800 EC = Node.getError();
801 return directory_iterator(std::make_shared<InMemoryDirIterator>());
802 }
803
804 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
Simon Marchiddbabc62018-08-06 21:48:20 +0000805 return directory_iterator(
806 std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000807
808 EC = make_error_code(llvm::errc::not_a_directory);
809 return directory_iterator(std::make_shared<InMemoryDirIterator>());
810}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000811
812std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
813 SmallString<128> Path;
814 P.toVector(Path);
815
816 // Fix up relative paths. This just prepends the current working directory.
817 std::error_code EC = makeAbsolute(Path);
818 assert(!EC);
819 (void)EC;
820
821 if (useNormalizedPaths())
822 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
823
824 if (!Path.empty())
825 WorkingDirectory = Path.str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000826 return {};
Benjamin Kramere9e76072016-01-09 16:33:16 +0000827}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000828
Eric Liu33dd6192018-05-24 11:17:00 +0000829std::error_code
830InMemoryFileSystem::getRealPath(const Twine &Path,
831 SmallVectorImpl<char> &Output) const {
832 auto CWD = getCurrentWorkingDirectory();
833 if (!CWD || CWD->empty())
834 return errc::operation_not_permitted;
835 Path.toVector(Output);
836 if (auto EC = makeAbsolute(Output))
837 return EC;
838 llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
839 return {};
840}
841
Eugene Zelenko5a520112018-03-28 22:09:09 +0000842} // namespace vfs
843} // namespace clang
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000844
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000845//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000846// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000847//===-----------------------------------------------------------------------===/
848
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000849namespace {
850
851enum EntryKind {
852 EK_Directory,
853 EK_File
854};
855
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000856/// A single file or directory in the VFS.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000857class Entry {
858 EntryKind Kind;
859 std::string Name;
860
861public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000862 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000863 virtual ~Entry() = default;
864
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000865 StringRef getName() const { return Name; }
866 EntryKind getKind() const { return Kind; }
867};
868
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000869class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000870 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000871 Status S;
872
873public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000874 RedirectingDirectoryEntry(StringRef Name,
875 std::vector<std::unique_ptr<Entry>> Contents,
876 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000877 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000878 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000879 RedirectingDirectoryEntry(StringRef Name, Status S)
880 : Entry(EK_Directory, Name), S(std::move(S)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000881
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000882 Status getStatus() { return S; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000883
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000884 void addContent(std::unique_ptr<Entry> Content) {
885 Contents.push_back(std::move(Content));
886 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000887
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000888 Entry *getLastContent() const { return Contents.back().get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000889
890 using iterator = decltype(Contents)::iterator;
891
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000892 iterator contents_begin() { return Contents.begin(); }
893 iterator contents_end() { return Contents.end(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000894
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000895 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
896};
897
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000898class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000899public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000900 enum NameKind {
901 NK_NotSet,
902 NK_External,
903 NK_Virtual
904 };
Eugene Zelenko5a520112018-03-28 22:09:09 +0000905
Ben Langmuirb59cf672014-02-27 00:25:12 +0000906private:
907 std::string ExternalContentsPath;
908 NameKind UseName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000909
Ben Langmuirb59cf672014-02-27 00:25:12 +0000910public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000911 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
912 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000913 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
914 UseName(UseName) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000915
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000916 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000917
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000918 /// whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000919 bool useExternalName(bool GlobalUseExternalName) const {
920 return UseName == NK_NotSet ? GlobalUseExternalName
921 : (UseName == NK_External);
922 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000923
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000924 NameKind getUseName() const { return UseName; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000925
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000926 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
927};
928
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000929class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000930
931class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
932 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000933 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000934 RedirectingDirectoryEntry::iterator Current, End;
935
Ben Langmuir740812b2014-06-24 19:37:16 +0000936public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000937 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000938 RedirectingDirectoryEntry::iterator Begin,
939 RedirectingDirectoryEntry::iterator End,
940 std::error_code &EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +0000941
Ben Langmuir740812b2014-06-24 19:37:16 +0000942 std::error_code increment() override;
943};
944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000945/// A virtual file system parsed from a YAML file.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000946///
947/// Currently, this class allows creating virtual directories and mapping
948/// virtual file paths to existing external files, available in \c ExternalFS.
949///
950/// The basic structure of the parsed file is:
951/// \verbatim
952/// {
953/// 'version': <version number>,
954/// <optional configuration>
955/// 'roots': [
956/// <directory entries>
957/// ]
958/// }
959/// \endverbatim
960///
961/// All configuration options are optional.
962/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000963/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000964/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000965/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000966///
967/// Virtual directories are represented as
968/// \verbatim
969/// {
970/// 'type': 'directory',
971/// 'name': <string>,
972/// 'contents': [ <file or directory entries> ]
973/// }
974/// \endverbatim
975///
976/// The default attributes for virtual directories are:
977/// \verbatim
978/// MTime = now() when created
979/// Perms = 0777
980/// User = Group = 0
981/// Size = 0
982/// UniqueID = unspecified unique value
983/// \endverbatim
984///
985/// Re-mapped files are represented as
986/// \verbatim
987/// {
988/// 'type': 'file',
989/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000990/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000991/// 'external-contents': <path to external file>)
992/// }
993/// \endverbatim
994///
995/// and inherit their attributes from the external contents.
996///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000997/// In both cases, the 'name' field may contain multiple path components (e.g.
998/// /path/to/file). However, any directory that contains more than one child
999/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001000class RedirectingFileSystem : public vfs::FileSystem {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001001 friend class RedirectingFileSystemParser;
1002
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001003 /// The root(s) of the virtual file system.
1004 std::vector<std::unique_ptr<Entry>> Roots;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001005
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001006 /// The file system to use for external references.
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001007 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001008
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001009 /// If IsRelativeOverlay is set, this represents the directory
1010 /// path that should be prefixed to each 'external-contents' entry
1011 /// when reading from YAML files.
1012 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001013
1014 /// @name Configuration
1015 /// @{
1016
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001017 /// Whether to perform case-sensitive comparisons.
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001018 ///
1019 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +00001020 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001021
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001022 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
1023 /// be prefixed in every 'external-contents' when reading from YAML files.
1024 bool IsRelativeOverlay = false;
1025
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001026 /// Whether to use to use the value of 'external-contents' for the
Ben Langmuirb59cf672014-02-27 00:25:12 +00001027 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +00001028 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001029
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001030 /// Whether an invalid path obtained via 'external-contents' should
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001031 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
1032 /// the entry and continue with the next. Allows YAML files to be shared
1033 /// across multiple compiler invocations regardless of prior existent
1034 /// paths in 'external-contents'. This global value is overridable on a
1035 /// per-file basis.
1036 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001037 /// @}
1038
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001039 /// Virtual file paths and external files could be canonicalized without "..",
1040 /// "." and "./" in their paths. FIXME: some unittests currently fail on
1041 /// win32 when using remove_dots and remove_leading_dotslash on paths.
1042 bool UseCanonicalizedPaths =
Nico Weber1865df42018-04-27 19:11:14 +00001043#ifdef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001044 false;
1045#else
1046 true;
1047#endif
1048
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001049private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001050 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001051 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001052
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001053 /// Looks up the path <tt>[Start, End)</tt> in \p From, possibly
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001054 /// recursing into the contents of \p From if it is a directory.
1055 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
1056 sys::path::const_iterator End, Entry *From);
1057
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001058 /// Get the status of a given an \c Entry.
Ben Langmuir740812b2014-06-24 19:37:16 +00001059 ErrorOr<Status> status(const Twine &Path, Entry *E);
1060
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001061public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001062 /// Looks up \p Path in \c Roots.
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001063 ErrorOr<Entry *> lookupPath(const Twine &Path);
1064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001065 /// Parses \p Buffer, which is expected to be in YAML format and
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001066 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001067 static RedirectingFileSystem *
1068 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001069 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
1070 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001071
Craig Toppera798a9d2014-03-02 09:32:10 +00001072 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +00001073 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +00001074
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001075 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
1076 return ExternalFS->getCurrentWorkingDirectory();
1077 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001078
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001079 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
1080 return ExternalFS->setCurrentWorkingDirectory(Path);
1081 }
1082
Ben Langmuir740812b2014-06-24 19:37:16 +00001083 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
1084 ErrorOr<Entry *> E = lookupPath(Dir);
1085 if (!E) {
1086 EC = E.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001087 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001088 }
1089 ErrorOr<Status> S = status(Dir, *E);
1090 if (!S) {
1091 EC = S.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001092 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001093 }
1094 if (!S->isDirectory()) {
1095 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1096 std::system_category());
Eugene Zelenko5a520112018-03-28 22:09:09 +00001097 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001098 }
1099
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001100 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +00001101 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
1102 *this, D->contents_begin(), D->contents_end(), EC));
1103 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001104
1105 void setExternalContentsPrefixDir(StringRef PrefixDir) {
1106 ExternalContentsPrefixDir = PrefixDir.str();
1107 }
1108
1109 StringRef getExternalContentsPrefixDir() const {
1110 return ExternalContentsPrefixDir;
1111 }
1112
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001113 bool ignoreNonExistentContents() const {
1114 return IgnoreNonExistentContents;
1115 }
1116
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001117#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1118LLVM_DUMP_METHOD void dump() const {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001119 for (const auto &Root : Roots)
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001120 dumpEntry(Root.get());
1121 }
1122
1123LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
1124 StringRef Name = E->getName();
1125 for (int i = 0, e = NumSpaces; i < e; ++i)
1126 dbgs() << " ";
1127 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
1128
1129 if (E->getKind() == EK_Directory) {
1130 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
1131 assert(DE && "Should be a directory");
1132
1133 for (std::unique_ptr<Entry> &SubEntry :
1134 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1135 dumpEntry(SubEntry.get(), NumSpaces+2);
1136 }
1137 }
1138#endif
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001139};
1140
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001141/// A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001142class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001143 yaml::Stream &Stream;
1144
1145 void error(yaml::Node *N, const Twine &Msg) {
1146 Stream.printError(N, Msg);
1147 }
1148
1149 // false on error
1150 bool parseScalarString(yaml::Node *N, StringRef &Result,
1151 SmallVectorImpl<char> &Storage) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001152 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1153
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001154 if (!S) {
1155 error(N, "expected string");
1156 return false;
1157 }
1158 Result = S->getValue(Storage);
1159 return true;
1160 }
1161
1162 // false on error
1163 bool parseScalarBool(yaml::Node *N, bool &Result) {
1164 SmallString<5> Storage;
1165 StringRef Value;
1166 if (!parseScalarString(N, Value, Storage))
1167 return false;
1168
1169 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1170 Value.equals_lower("yes") || Value == "1") {
1171 Result = true;
1172 return true;
1173 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1174 Value.equals_lower("no") || Value == "0") {
1175 Result = false;
1176 return true;
1177 }
1178
1179 error(N, "expected boolean value");
1180 return false;
1181 }
1182
1183 struct KeyStatus {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001184 bool Required;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001185 bool Seen = false;
1186
1187 KeyStatus(bool Required = false) : Required(Required) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001188 };
Eugene Zelenko5a520112018-03-28 22:09:09 +00001189
1190 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001191
1192 // false on error
1193 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1194 DenseMap<StringRef, KeyStatus> &Keys) {
1195 if (!Keys.count(Key)) {
1196 error(KeyNode, "unknown key");
1197 return false;
1198 }
1199 KeyStatus &S = Keys[Key];
1200 if (S.Seen) {
1201 error(KeyNode, Twine("duplicate key '") + Key + "'");
1202 return false;
1203 }
1204 S.Seen = true;
1205 return true;
1206 }
1207
1208 // false on error
1209 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001210 for (const auto &I : Keys) {
1211 if (I.second.Required && !I.second.Seen) {
1212 error(Obj, Twine("missing key '") + I.first + "'");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001213 return false;
1214 }
1215 }
1216 return true;
1217 }
1218
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001219 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1220 Entry *ParentEntry = nullptr) {
1221 if (!ParentEntry) { // Look for a existent root
Eugene Zelenko5a520112018-03-28 22:09:09 +00001222 for (const auto &Root : FS->Roots) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001223 if (Name.equals(Root->getName())) {
1224 ParentEntry = Root.get();
1225 return ParentEntry;
1226 }
1227 }
1228 } else { // Advance to the next component
1229 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1230 for (std::unique_ptr<Entry> &Content :
1231 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1232 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1233 if (DirContent && Name.equals(Content->getName()))
1234 return DirContent;
1235 }
1236 }
1237
1238 // ... or create a new one
1239 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001240 Name,
1241 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1242 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001243
1244 if (!ParentEntry) { // Add a new root to the overlay
1245 FS->Roots.push_back(std::move(E));
1246 ParentEntry = FS->Roots.back().get();
1247 return ParentEntry;
1248 }
1249
1250 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1251 DE->addContent(std::move(E));
1252 return DE->getLastContent();
1253 }
1254
1255 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1256 Entry *NewParentE = nullptr) {
1257 StringRef Name = SrcE->getName();
1258 switch (SrcE->getKind()) {
1259 case EK_Directory: {
1260 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1261 assert(DE && "Must be a directory");
1262 // Empty directories could be present in the YAML as a way to
1263 // describe a file for a current directory after some of its subdir
1264 // is parsed. This only leads to redundant walks, ignore it.
1265 if (!Name.empty())
1266 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1267 for (std::unique_ptr<Entry> &SubEntry :
1268 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1269 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1270 break;
1271 }
1272 case EK_File: {
1273 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1274 assert(FE && "Must be a file");
1275 assert(NewParentE && "Parent entry must exist");
1276 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1277 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1278 Name, FE->getExternalContentsPath(), FE->getUseName()));
1279 break;
1280 }
1281 }
1282 }
1283
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001284 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001285 auto *M = dyn_cast<yaml::MappingNode>(N);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001286 if (!M) {
1287 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001288 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001289 }
1290
1291 KeyStatusPair Fields[] = {
1292 KeyStatusPair("name", true),
1293 KeyStatusPair("type", true),
1294 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001295 KeyStatusPair("external-contents", false),
1296 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001297 };
1298
Craig Topperac67c052015-11-30 03:11:10 +00001299 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001300
1301 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001302 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001303 std::string ExternalContentsPath;
1304 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001305 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001306 EntryKind Kind;
1307
Eugene Zelenko5a520112018-03-28 22:09:09 +00001308 for (auto &I : *M) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001309 StringRef Key;
1310 // Reuse the buffer for key and value, since we don't look at key after
1311 // parsing value.
1312 SmallString<256> Buffer;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001313 if (!parseScalarString(I.getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001314 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001315
Eugene Zelenko5a520112018-03-28 22:09:09 +00001316 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001317 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001318
1319 StringRef Value;
1320 if (Key == "name") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001321 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001322 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001323
1324 if (FS->UseCanonicalizedPaths) {
1325 SmallString<256> Path(Value);
1326 // Guarantee that old YAML files containing paths with ".." and "."
1327 // are properly canonicalized before read into the VFS.
1328 Path = sys::path::remove_leading_dotslash(Path);
1329 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1330 Name = Path.str();
1331 } else {
1332 Name = Value;
1333 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001334 } else if (Key == "type") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001335 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001336 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001337 if (Value == "file")
1338 Kind = EK_File;
1339 else if (Value == "directory")
1340 Kind = EK_Directory;
1341 else {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001342 error(I.getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001343 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001344 }
1345 } else if (Key == "contents") {
1346 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001347 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001348 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001349 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001350 }
1351 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001352 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001353 if (!Contents) {
1354 // FIXME: this is only for directories, what about files?
Eugene Zelenko5a520112018-03-28 22:09:09 +00001355 error(I.getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001356 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001357 }
1358
Eugene Zelenko5a520112018-03-28 22:09:09 +00001359 for (auto &I : *Contents) {
1360 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001361 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001362 else
Craig Topperf1186c52014-05-08 06:41:40 +00001363 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001364 }
1365 } else if (Key == "external-contents") {
1366 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001367 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001368 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001369 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001370 }
1371 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001372 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001373 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001374
1375 SmallString<256> FullPath;
1376 if (FS->IsRelativeOverlay) {
1377 FullPath = FS->getExternalContentsPrefixDir();
1378 assert(!FullPath.empty() &&
1379 "External contents prefix directory must exist");
1380 llvm::sys::path::append(FullPath, Value);
1381 } else {
1382 FullPath = Value;
1383 }
1384
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001385 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001386 // Guarantee that old YAML files containing paths with ".." and "."
1387 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001388 FullPath = sys::path::remove_leading_dotslash(FullPath);
1389 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001390 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001391 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001392 } else if (Key == "use-external-name") {
1393 bool Val;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001394 if (!parseScalarBool(I.getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001395 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001396 UseExternalName = Val ? RedirectingFileEntry::NK_External
1397 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001398 } else {
1399 llvm_unreachable("key missing from Keys");
1400 }
1401 }
1402
1403 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001404 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001405
1406 // check for missing keys
1407 if (!HasContents) {
1408 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001409 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001410 }
1411 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001412 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001413
Ben Langmuirb59cf672014-02-27 00:25:12 +00001414 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001415 if (Kind == EK_Directory &&
1416 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001417 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001418 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001419 }
1420
Ben Langmuir93853232014-03-05 21:32:20 +00001421 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001422 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001423 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1424 while (Trimmed.size() > RootPathLen &&
1425 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001426 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1427 // Get the last component
1428 StringRef LastComponent = sys::path::filename(Trimmed);
1429
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001430 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001431 switch (Kind) {
1432 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001433 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001434 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001435 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001436 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001437 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001438 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001439 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1440 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001441 break;
1442 }
1443
1444 StringRef Parent = sys::path::parent_path(Trimmed);
1445 if (Parent.empty())
1446 return Result;
1447
1448 // if 'name' contains multiple components, create implicit directory entries
1449 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1450 E = sys::path::rend(Parent);
1451 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001452 std::vector<std::unique_ptr<Entry>> Entries;
1453 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001454 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001455 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001456 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1457 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001458 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001459 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001460 }
1461
1462public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001463 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001464
1465 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001466 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001467 auto *Top = dyn_cast<yaml::MappingNode>(Root);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001468 if (!Top) {
1469 error(Root, "expected mapping node");
1470 return false;
1471 }
1472
1473 KeyStatusPair Fields[] = {
1474 KeyStatusPair("version", true),
1475 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001476 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001477 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001478 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001479 KeyStatusPair("roots", true),
1480 };
1481
Craig Topperac67c052015-11-30 03:11:10 +00001482 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001483 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001484
1485 // Parse configuration and 'roots'
Eugene Zelenko5a520112018-03-28 22:09:09 +00001486 for (auto &I : *Top) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001487 SmallString<10> KeyBuffer;
1488 StringRef Key;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001489 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001490 return false;
1491
Eugene Zelenko5a520112018-03-28 22:09:09 +00001492 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001493 return false;
1494
1495 if (Key == "roots") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001496 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001497 if (!Roots) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001498 error(I.getValue(), "expected array");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001499 return false;
1500 }
1501
Eugene Zelenko5a520112018-03-28 22:09:09 +00001502 for (auto &I : *Roots) {
1503 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001504 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001505 else
1506 return false;
1507 }
1508 } else if (Key == "version") {
1509 StringRef VersionString;
1510 SmallString<4> Storage;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001511 if (!parseScalarString(I.getValue(), VersionString, Storage))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001512 return false;
1513 int Version;
1514 if (VersionString.getAsInteger<int>(10, Version)) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001515 error(I.getValue(), "expected integer");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001516 return false;
1517 }
1518 if (Version < 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001519 error(I.getValue(), "invalid version number");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001520 return false;
1521 }
1522 if (Version != 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001523 error(I.getValue(), "version mismatch, expected 0");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001524 return false;
1525 }
1526 } else if (Key == "case-sensitive") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001527 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001528 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001529 } else if (Key == "overlay-relative") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001530 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001531 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001532 } else if (Key == "use-external-names") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001533 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
Ben Langmuirb59cf672014-02-27 00:25:12 +00001534 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001535 } else if (Key == "ignore-non-existent-contents") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001536 if (!parseScalarBool(I.getValue(), FS->IgnoreNonExistentContents))
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001537 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001538 } else {
1539 llvm_unreachable("key missing from Keys");
1540 }
1541 }
1542
1543 if (Stream.failed())
1544 return false;
1545
1546 if (!checkMissingKeys(Top, Keys))
1547 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001548
1549 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1550 // representation to a proper directory tree so that we can search faster
1551 // inside the VFS.
Eugene Zelenko5a520112018-03-28 22:09:09 +00001552 for (auto &E : RootEntries)
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001553 uniqueOverlayTree(FS, E.get());
1554
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001555 return true;
1556 }
1557};
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001558
Eugene Zelenko5a520112018-03-28 22:09:09 +00001559} // namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001560
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001561RedirectingFileSystem *
1562RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1563 SourceMgr::DiagHandlerTy DiagHandler,
1564 StringRef YAMLFilePath, void *DiagContext,
1565 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001566 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001567 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001568
Ben Langmuir97882e72014-02-24 20:56:37 +00001569 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001570 yaml::document_iterator DI = Stream.begin();
1571 yaml::Node *Root = DI->getRoot();
1572 if (DI == Stream.end() || !Root) {
1573 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001574 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001575 }
1576
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001577 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001578
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001579 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001580 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001581
1582 if (!YAMLFilePath.empty()) {
1583 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1584 // to each 'external-contents' path.
1585 //
1586 // Example:
1587 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1588 // yields:
1589 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1590 //
1591 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1592 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1593 assert(!EC && "Overlay dir final path must be absolute");
1594 (void)EC;
1595 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1596 }
1597
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001598 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001599 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001600
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001601 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001602}
1603
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001604ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001605 SmallString<256> Path;
1606 Path_.toVector(Path);
1607
1608 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001609 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001610 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001611
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001612 // Canonicalize path by removing ".", "..", "./", etc components. This is
1613 // a VFS request, do bot bother about symlinks in the path components
1614 // but canonicalize in order to perform the correct entry search.
1615 if (UseCanonicalizedPaths) {
1616 Path = sys::path::remove_leading_dotslash(Path);
1617 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1618 }
1619
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001620 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001621 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001622
1623 sys::path::const_iterator Start = sys::path::begin(Path);
1624 sys::path::const_iterator End = sys::path::end(Path);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001625 for (const auto &Root : Roots) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001626 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001627 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001628 return Result;
1629 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001630 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001631}
1632
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001633ErrorOr<Entry *>
1634RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1635 sys::path::const_iterator End, Entry *From) {
Nico Weber1865df42018-04-27 19:11:14 +00001636#ifndef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001637 assert(!isTraversalComponent(*Start) &&
1638 !isTraversalComponent(From->getName()) &&
1639 "Paths should not contain traversal components");
1640#else
1641 // FIXME: this is here to support windows, remove it once canonicalized
1642 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001643 if (Start->equals("."))
1644 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001645#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001646
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001647 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001648
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001649 // Forward the search to the next component in case this is an empty one.
1650 if (!FromName.empty()) {
1651 if (CaseSensitive ? !Start->equals(FromName)
1652 : !Start->equals_lower(FromName))
1653 // failure to match
1654 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001655
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001656 ++Start;
1657
1658 if (Start == End) {
1659 // Match!
1660 return From;
1661 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001662 }
1663
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001664 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001665 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001666 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001667
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001668 for (const std::unique_ptr<Entry> &DirEntry :
1669 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1670 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001671 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001672 return Result;
1673 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001674 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001675}
1676
Ben Langmuirf13302e2015-12-10 23:41:39 +00001677static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1678 Status ExternalStatus) {
1679 Status S = ExternalStatus;
1680 if (!UseExternalNames)
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001681 S = Status::copyWithNewName(S, Path.str());
Ben Langmuirf13302e2015-12-10 23:41:39 +00001682 S.IsVFSMapped = true;
1683 return S;
1684}
1685
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001686ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001687 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001688 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001689 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001690 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001691 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001692 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1693 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001694 return S;
1695 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001696 auto *DE = cast<RedirectingDirectoryEntry>(E);
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001697 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001698 }
1699}
1700
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001701ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001702 ErrorOr<Entry *> Result = lookupPath(Path);
1703 if (!Result)
1704 return Result.getError();
1705 return status(Path, *Result);
1706}
1707
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001708namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001709
Ben Langmuirf13302e2015-12-10 23:41:39 +00001710/// Provide a file wrapper with an overriden status.
1711class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001712 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001713 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001714
1715public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001716 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001717 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001718
Ben Langmuirf13302e2015-12-10 23:41:39 +00001719 ErrorOr<Status> status() override { return S; }
1720 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Eugene Zelenko5a520112018-03-28 22:09:09 +00001721
Benjamin Kramer737501c2015-10-05 21:20:19 +00001722 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1723 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001724 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1725 IsVolatile);
1726 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001727
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001728 std::error_code close() override { return InnerFile->close(); }
1729};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001730
1731} // namespace
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001732
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001733ErrorOr<std::unique_ptr<File>>
1734RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001735 ErrorOr<Entry *> E = lookupPath(Path);
1736 if (!E)
1737 return E.getError();
1738
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001739 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001740 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001741 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001742
Benjamin Kramera8857962014-10-26 22:44:13 +00001743 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1744 if (!Result)
1745 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001746
Ben Langmuirf13302e2015-12-10 23:41:39 +00001747 auto ExternalStatus = (*Result)->status();
1748 if (!ExternalStatus)
1749 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001750
Ben Langmuirf13302e2015-12-10 23:41:39 +00001751 // FIXME: Update the status with the name and VFSMapped.
1752 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1753 *ExternalStatus);
1754 return std::unique_ptr<File>(
1755 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001756}
1757
1758IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001759vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001760 SourceMgr::DiagHandlerTy DiagHandler,
1761 StringRef YAMLFilePath,
1762 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001763 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001764 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001765 YAMLFilePath, DiagContext,
1766 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001767}
1768
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001769static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1770 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1771 auto Kind = SrcE->getKind();
1772 if (Kind == EK_Directory) {
1773 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1774 assert(DE && "Must be a directory");
1775 for (std::unique_ptr<Entry> &SubEntry :
1776 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1777 Path.push_back(SubEntry->getName());
1778 getVFSEntries(SubEntry.get(), Path, Entries);
1779 Path.pop_back();
1780 }
1781 return;
1782 }
1783
1784 assert(Kind == EK_File && "Must be a EK_File");
1785 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1786 assert(FE && "Must be a file");
1787 SmallString<128> VPath;
1788 for (auto &Comp : Path)
1789 llvm::sys::path::append(VPath, Comp);
1790 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1791}
1792
1793void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1794 SourceMgr::DiagHandlerTy DiagHandler,
1795 StringRef YAMLFilePath,
1796 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1797 void *DiagContext,
1798 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1799 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1800 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1801 std::move(ExternalFS));
1802 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1803 if (!RootE)
1804 return;
1805 SmallVector<StringRef, 8> Components;
1806 Components.push_back("/");
1807 getVFSEntries(*RootE, Components, CollectedEntries);
1808}
1809
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001810UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001811 static std::atomic<unsigned> UID;
1812 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001813 // The following assumes that uint64_t max will never collide with a real
1814 // dev_t value from the OS.
1815 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1816}
Justin Bogner9c785292014-05-20 21:43:27 +00001817
Justin Bogner9c785292014-05-20 21:43:27 +00001818void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1819 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1820 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1821 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1822 Mappings.emplace_back(VirtualPath, RealPath);
1823}
1824
Justin Bogner44fa450342014-05-21 22:46:51 +00001825namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001826
Justin Bogner44fa450342014-05-21 22:46:51 +00001827class JSONWriter {
1828 llvm::raw_ostream &OS;
1829 SmallVector<StringRef, 16> DirStack;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001830
1831 unsigned getDirIndent() { return 4 * DirStack.size(); }
1832 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
Justin Bogner44fa450342014-05-21 22:46:51 +00001833 bool containedIn(StringRef Parent, StringRef Path);
1834 StringRef containedPart(StringRef Parent, StringRef Path);
1835 void startDirectory(StringRef Path);
1836 void endDirectory();
1837 void writeEntry(StringRef VPath, StringRef RPath);
1838
1839public:
1840 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001841
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001842 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1843 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001844 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001845};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001846
1847} // namespace
Justin Bogner9c785292014-05-20 21:43:27 +00001848
Justin Bogner44fa450342014-05-21 22:46:51 +00001849bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001850 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001851
Justin Bogner1c078f22014-05-20 22:12:58 +00001852 // Compare each path component.
1853 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1854 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1855 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1856 if (*IParent != *IChild)
1857 return false;
1858 }
1859 // Have we exhausted the parent path?
1860 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001861}
1862
Justin Bogner44fa450342014-05-21 22:46:51 +00001863StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1864 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001865 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001866 return Path.slice(Parent.size() + 1, StringRef::npos);
1867}
1868
Justin Bogner44fa450342014-05-21 22:46:51 +00001869void JSONWriter::startDirectory(StringRef Path) {
1870 StringRef Name =
1871 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1872 DirStack.push_back(Path);
1873 unsigned Indent = getDirIndent();
1874 OS.indent(Indent) << "{\n";
1875 OS.indent(Indent + 2) << "'type': 'directory',\n";
1876 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1877 OS.indent(Indent + 2) << "'contents': [\n";
1878}
1879
1880void JSONWriter::endDirectory() {
1881 unsigned Indent = getDirIndent();
1882 OS.indent(Indent + 2) << "]\n";
1883 OS.indent(Indent) << "}";
1884
1885 DirStack.pop_back();
1886}
1887
1888void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1889 unsigned Indent = getFileIndent();
1890 OS.indent(Indent) << "{\n";
1891 OS.indent(Indent + 2) << "'type': 'file',\n";
1892 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1893 OS.indent(Indent + 2) << "'external-contents': \""
1894 << llvm::yaml::escape(RPath) << "\"\n";
1895 OS.indent(Indent) << "}";
1896}
1897
1898void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001899 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001900 Optional<bool> IsCaseSensitive,
1901 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001902 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001903 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001904 using namespace llvm::sys;
1905
1906 OS << "{\n"
1907 " 'version': 0,\n";
1908 if (IsCaseSensitive.hasValue())
1909 OS << " 'case-sensitive': '"
1910 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001911 if (UseExternalNames.hasValue())
1912 OS << " 'use-external-names': '"
1913 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001914 bool UseOverlayRelative = false;
1915 if (IsOverlayRelative.hasValue()) {
1916 UseOverlayRelative = IsOverlayRelative.getValue();
1917 OS << " 'overlay-relative': '"
1918 << (UseOverlayRelative ? "true" : "false") << "',\n";
1919 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001920 if (IgnoreNonExistentContents.hasValue())
1921 OS << " 'ignore-non-existent-contents': '"
1922 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001923 OS << " 'roots': [\n";
1924
Justin Bogner73466402014-07-15 01:24:35 +00001925 if (!Entries.empty()) {
1926 const YAMLVFSEntry &Entry = Entries.front();
1927 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001928
1929 StringRef RPath = Entry.RPath;
1930 if (UseOverlayRelative) {
1931 unsigned OverlayDirLen = OverlayDir.size();
1932 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1933 "Overlay dir must be contained in RPath");
1934 RPath = RPath.slice(OverlayDirLen, RPath.size());
1935 }
1936
1937 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001938
Justin Bogner73466402014-07-15 01:24:35 +00001939 for (const auto &Entry : Entries.slice(1)) {
1940 StringRef Dir = path::parent_path(Entry.VPath);
1941 if (Dir == DirStack.back())
1942 OS << ",\n";
1943 else {
1944 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1945 OS << "\n";
1946 endDirectory();
1947 }
1948 OS << ",\n";
1949 startDirectory(Dir);
1950 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001951 StringRef RPath = Entry.RPath;
1952 if (UseOverlayRelative) {
1953 unsigned OverlayDirLen = OverlayDir.size();
1954 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1955 "Overlay dir must be contained in RPath");
1956 RPath = RPath.slice(OverlayDirLen, RPath.size());
1957 }
1958 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001959 }
1960
1961 while (!DirStack.empty()) {
1962 OS << "\n";
1963 endDirectory();
1964 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001965 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001966 }
1967
Justin Bogner73466402014-07-15 01:24:35 +00001968 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001969 << "}\n";
1970}
1971
Justin Bogner9c785292014-05-20 21:43:27 +00001972void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001973 llvm::sort(Mappings.begin(), Mappings.end(),
1974 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001975 return LHS.VPath < RHS.VPath;
1976 });
1977
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001978 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001979 IsOverlayRelative, IgnoreNonExistentContents,
1980 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001981}
Ben Langmuir740812b2014-06-24 19:37:16 +00001982
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001983VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1984 const Twine &_Path, RedirectingFileSystem &FS,
1985 RedirectingDirectoryEntry::iterator Begin,
1986 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001987 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001988 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001989 SmallString<128> PathStr(Dir);
1990 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001991 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001992 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001993 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001994 return;
1995 }
1996 // Skip entries which do not map to a reliable external content.
1997 if (FS.ignoreNonExistentContents() &&
1998 S.getError() == llvm::errc::no_such_file_or_directory) {
1999 ++Current;
2000 continue;
2001 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00002002 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002003 break;
2004 }
Ben Langmuir740812b2014-06-24 19:37:16 +00002005 }
2006}
2007
2008std::error_code VFSFromYamlDirIterImpl::increment() {
2009 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002010 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00002011 SmallString<128> PathStr(Dir);
2012 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00002013 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002014 if (!S) {
2015 // Skip entries which do not map to a reliable external content.
2016 if (FS.ignoreNonExistentContents() &&
2017 S.getError() == llvm::errc::no_such_file_or_directory) {
2018 continue;
2019 } else {
2020 return S.getError();
2021 }
2022 }
Ben Langmuir740812b2014-06-24 19:37:16 +00002023 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002024 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00002025 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002026
2027 if (Current == End)
2028 CurrentEntry = Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +00002029 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00002030}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002031
2032vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
2033 const Twine &Path,
2034 std::error_code &EC)
2035 : FS(&FS_) {
2036 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00002037 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002038 State = std::make_shared<IterState>();
2039 State->push(I);
2040 }
2041}
2042
2043vfs::recursive_directory_iterator &
2044recursive_directory_iterator::increment(std::error_code &EC) {
2045 assert(FS && State && !State->empty() && "incrementing past end");
2046 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
2047 vfs::directory_iterator End;
2048 if (State->top()->isDirectory()) {
2049 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002050 if (I != End) {
2051 State->push(I);
2052 return *this;
2053 }
2054 }
2055
2056 while (!State->empty() && State->top().increment(EC) == End)
2057 State->pop();
2058
2059 if (State->empty())
2060 State.reset(); // end iterator
2061
2062 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002063}