blob: bcfcbdbb90149abd0e3dd6455323afab0aa15777 [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
477public:
478 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
Eric Liub71e6f42018-07-11 18:43:07 +0000479 : Stat(std::move(Stat)), Kind(Kind) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000480 virtual ~InMemoryNode() = default;
481
Reid Kleckner4d23f452018-07-26 23:21:51 +0000482 const Status &getStatus() const { return Stat; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000483 InMemoryNodeKind getKind() const { return Kind; }
484 virtual std::string toString(unsigned Indent) const = 0;
485};
486
487namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000488
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000489class InMemoryFile : public InMemoryNode {
490 std::unique_ptr<llvm::MemoryBuffer> Buffer;
491
492public:
493 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
494 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
495
496 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000497
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000498 std::string toString(unsigned Indent) const override {
499 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
500 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000501
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000502 static bool classof(const InMemoryNode *N) {
503 return N->getKind() == IME_File;
504 }
505};
506
Reid Kleckner4d23f452018-07-26 23:21:51 +0000507/// Adapt a InMemoryFile for VFS' File interface.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000508class InMemoryFileAdaptor : public File {
509 InMemoryFile &Node;
510
Simon Marchia37ef292018-07-11 14:08:17 +0000511public:
Reid Kleckner4d23f452018-07-26 23:21:51 +0000512 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
Simon Marchia37ef292018-07-11 14:08:17 +0000513
Reid Kleckner4d23f452018-07-26 23:21:51 +0000514 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000515
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000516 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000517 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
518 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000519 llvm::MemoryBuffer *Buf = Node.getBuffer();
520 return llvm::MemoryBuffer::getMemBuffer(
521 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
522 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000523
524 std::error_code close() override { return {}; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000525};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000526
527} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000528
529class InMemoryDirectory : public InMemoryNode {
530 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
531
532public:
533 InMemoryDirectory(Status Stat)
534 : InMemoryNode(std::move(Stat), IME_Directory) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000535
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000536 InMemoryNode *getChild(StringRef Name) {
537 auto I = Entries.find(Name);
538 if (I != Entries.end())
539 return I->second.get();
540 return nullptr;
541 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000542
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000543 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
544 return Entries.insert(make_pair(Name, std::move(Child)))
545 .first->second.get();
546 }
547
Eugene Zelenko5a520112018-03-28 22:09:09 +0000548 using const_iterator = decltype(Entries)::const_iterator;
549
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000550 const_iterator begin() const { return Entries.begin(); }
551 const_iterator end() const { return Entries.end(); }
552
553 std::string toString(unsigned Indent) const override {
554 std::string Result =
555 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000556 for (const auto &Entry : Entries)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000557 Result += Entry.second->toString(Indent + 2);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000558 return Result;
559 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000560
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000561 static bool classof(const InMemoryNode *N) {
562 return N->getKind() == IME_Directory;
563 }
564};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000565
566} // namespace detail
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000567
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000568InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000569 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000570 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
571 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000572 llvm::sys::fs::perms::all_all))),
573 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000574
Eugene Zelenko5a520112018-03-28 22:09:09 +0000575InMemoryFileSystem::~InMemoryFileSystem() = default;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000576
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000577std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000578 return Root->toString(/*Indent=*/0);
579}
580
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000581bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000582 std::unique_ptr<llvm::MemoryBuffer> Buffer,
583 Optional<uint32_t> User,
584 Optional<uint32_t> Group,
585 Optional<llvm::sys::fs::file_type> Type,
586 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000587 SmallString<128> Path;
588 P.toVector(Path);
589
590 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000591 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000592 assert(!EC);
593 (void)EC;
594
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000595 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000596 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000597
598 if (Path.empty())
599 return false;
600
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000601 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000602 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
603 const auto ResolvedUser = User.getValueOr(0);
604 const auto ResolvedGroup = Group.getValueOr(0);
605 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
606 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
607 // Any intermediate directories we create should be accessible by
608 // the owner, even if Perms says otherwise for the final path.
609 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000610 while (true) {
611 StringRef Name = *I;
612 detail::InMemoryNode *Node = Dir->getChild(Name);
613 ++I;
614 if (!Node) {
615 if (I == E) {
Ben Hamilton78381012017-11-16 19:34:08 +0000616 // End of the path, create a new file or directory.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000617 Status Stat(P.str(), getNextVirtualUniqueID(),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000618 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
619 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
620 ResolvedPerms);
Ben Hamilton78381012017-11-16 19:34:08 +0000621 std::unique_ptr<detail::InMemoryNode> Child;
622 if (ResolvedType == sys::fs::file_type::directory_file) {
623 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
624 } else {
625 Child.reset(new detail::InMemoryFile(std::move(Stat),
626 std::move(Buffer)));
627 }
628 Dir->addChild(Name, std::move(Child));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000629 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000630 }
631
632 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000633 Status Stat(
634 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000635 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
636 ResolvedUser, ResolvedGroup, Buffer->getBufferSize(),
637 sys::fs::file_type::directory_file, NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000638 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
639 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
640 continue;
641 }
642
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000643 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000644 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000645 } else {
646 assert(isa<detail::InMemoryFile>(Node) &&
647 "Must be either file or directory!");
648
649 // Trying to insert a directory in place of a file.
650 if (I != E)
651 return false;
652
653 // Return false only if the new file is different from the existing one.
654 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
655 Buffer->getBuffer();
656 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000657 }
658}
659
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000660bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000661 llvm::MemoryBuffer *Buffer,
662 Optional<uint32_t> User,
663 Optional<uint32_t> Group,
664 Optional<llvm::sys::fs::file_type> Type,
665 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000666 return addFile(P, ModificationTime,
667 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000668 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
669 std::move(User), std::move(Group), std::move(Type),
670 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000671}
672
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000673static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000674lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
675 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000676 SmallString<128> Path;
677 P.toVector(Path);
678
679 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000680 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000681 assert(!EC);
682 (void)EC;
683
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000684 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000685 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000686
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000687 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000688 return Dir;
689
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000690 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000691 while (true) {
692 detail::InMemoryNode *Node = Dir->getChild(*I);
693 ++I;
694 if (!Node)
695 return errc::no_such_file_or_directory;
696
697 // Return the file if it's at the end of the path.
698 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
699 if (I == E)
700 return File;
701 return errc::no_such_file_or_directory;
702 }
703
704 // Traverse directories.
705 Dir = cast<detail::InMemoryDirectory>(Node);
706 if (I == E)
707 return Dir;
708 }
709}
710
711llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000712 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000713 if (Node)
Reid Kleckner4d23f452018-07-26 23:21:51 +0000714 return (*Node)->getStatus();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000715 return Node.getError();
716}
717
718llvm::ErrorOr<std::unique_ptr<File>>
719InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000720 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000721 if (!Node)
722 return Node.getError();
723
724 // When we have a file provide a heap-allocated wrapper for the memory buffer
725 // to match the ownership semantics for File.
726 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
Reid Kleckner4d23f452018-07-26 23:21:51 +0000727 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000728
729 // FIXME: errc::not_a_file?
730 return make_error_code(llvm::errc::invalid_argument);
731}
732
733namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000734
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000735/// Adaptor from InMemoryDir::iterator to directory_iterator.
736class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
737 detail::InMemoryDirectory::const_iterator I;
738 detail::InMemoryDirectory::const_iterator E;
739
740public:
Eugene Zelenko5a520112018-03-28 22:09:09 +0000741 InMemoryDirIterator() = default;
742
Reid Kleckner4d23f452018-07-26 23:21:51 +0000743 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
744 : I(Dir.begin()), E(Dir.end()) {
745 if (I != E)
746 CurrentEntry = I->second->getStatus();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000747 }
748
749 std::error_code increment() override {
750 ++I;
Reid Kleckner4d23f452018-07-26 23:21:51 +0000751 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
752 // the rest.
753 CurrentEntry = I != E ? I->second->getStatus() : Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000754 return {};
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000755 }
756};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000757
758} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000759
760directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
761 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000762 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000763 if (!Node) {
764 EC = Node.getError();
765 return directory_iterator(std::make_shared<InMemoryDirIterator>());
766 }
767
768 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
Reid Kleckner4d23f452018-07-26 23:21:51 +0000769 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000770
771 EC = make_error_code(llvm::errc::not_a_directory);
772 return directory_iterator(std::make_shared<InMemoryDirIterator>());
773}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000774
775std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
776 SmallString<128> Path;
777 P.toVector(Path);
778
779 // Fix up relative paths. This just prepends the current working directory.
780 std::error_code EC = makeAbsolute(Path);
781 assert(!EC);
782 (void)EC;
783
784 if (useNormalizedPaths())
785 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
786
787 if (!Path.empty())
788 WorkingDirectory = Path.str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000789 return {};
Benjamin Kramere9e76072016-01-09 16:33:16 +0000790}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000791
Eric Liu33dd6192018-05-24 11:17:00 +0000792std::error_code
793InMemoryFileSystem::getRealPath(const Twine &Path,
794 SmallVectorImpl<char> &Output) const {
795 auto CWD = getCurrentWorkingDirectory();
796 if (!CWD || CWD->empty())
797 return errc::operation_not_permitted;
798 Path.toVector(Output);
799 if (auto EC = makeAbsolute(Output))
800 return EC;
801 llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
802 return {};
803}
804
Eugene Zelenko5a520112018-03-28 22:09:09 +0000805} // namespace vfs
806} // namespace clang
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000807
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000808//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000809// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000810//===-----------------------------------------------------------------------===/
811
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000812namespace {
813
814enum EntryKind {
815 EK_Directory,
816 EK_File
817};
818
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000819/// A single file or directory in the VFS.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000820class Entry {
821 EntryKind Kind;
822 std::string Name;
823
824public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000825 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000826 virtual ~Entry() = default;
827
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000828 StringRef getName() const { return Name; }
829 EntryKind getKind() const { return Kind; }
830};
831
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000832class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000833 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000834 Status S;
835
836public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000837 RedirectingDirectoryEntry(StringRef Name,
838 std::vector<std::unique_ptr<Entry>> Contents,
839 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000840 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000841 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000842 RedirectingDirectoryEntry(StringRef Name, Status S)
843 : Entry(EK_Directory, Name), S(std::move(S)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000844
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000845 Status getStatus() { return S; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000846
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000847 void addContent(std::unique_ptr<Entry> Content) {
848 Contents.push_back(std::move(Content));
849 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000850
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000851 Entry *getLastContent() const { return Contents.back().get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000852
853 using iterator = decltype(Contents)::iterator;
854
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000855 iterator contents_begin() { return Contents.begin(); }
856 iterator contents_end() { return Contents.end(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000857
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000858 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
859};
860
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000861class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000862public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000863 enum NameKind {
864 NK_NotSet,
865 NK_External,
866 NK_Virtual
867 };
Eugene Zelenko5a520112018-03-28 22:09:09 +0000868
Ben Langmuirb59cf672014-02-27 00:25:12 +0000869private:
870 std::string ExternalContentsPath;
871 NameKind UseName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000872
Ben Langmuirb59cf672014-02-27 00:25:12 +0000873public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000874 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
875 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000876 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
877 UseName(UseName) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000878
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000879 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000880
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000881 /// whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000882 bool useExternalName(bool GlobalUseExternalName) const {
883 return UseName == NK_NotSet ? GlobalUseExternalName
884 : (UseName == NK_External);
885 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000886
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000887 NameKind getUseName() const { return UseName; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000888
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000889 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
890};
891
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000892class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000893
894class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
895 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000896 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000897 RedirectingDirectoryEntry::iterator Current, End;
898
Ben Langmuir740812b2014-06-24 19:37:16 +0000899public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000900 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000901 RedirectingDirectoryEntry::iterator Begin,
902 RedirectingDirectoryEntry::iterator End,
903 std::error_code &EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +0000904
Ben Langmuir740812b2014-06-24 19:37:16 +0000905 std::error_code increment() override;
906};
907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000908/// A virtual file system parsed from a YAML file.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000909///
910/// Currently, this class allows creating virtual directories and mapping
911/// virtual file paths to existing external files, available in \c ExternalFS.
912///
913/// The basic structure of the parsed file is:
914/// \verbatim
915/// {
916/// 'version': <version number>,
917/// <optional configuration>
918/// 'roots': [
919/// <directory entries>
920/// ]
921/// }
922/// \endverbatim
923///
924/// All configuration options are optional.
925/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000926/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000927/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000928/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000929///
930/// Virtual directories are represented as
931/// \verbatim
932/// {
933/// 'type': 'directory',
934/// 'name': <string>,
935/// 'contents': [ <file or directory entries> ]
936/// }
937/// \endverbatim
938///
939/// The default attributes for virtual directories are:
940/// \verbatim
941/// MTime = now() when created
942/// Perms = 0777
943/// User = Group = 0
944/// Size = 0
945/// UniqueID = unspecified unique value
946/// \endverbatim
947///
948/// Re-mapped files are represented as
949/// \verbatim
950/// {
951/// 'type': 'file',
952/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000953/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000954/// 'external-contents': <path to external file>)
955/// }
956/// \endverbatim
957///
958/// and inherit their attributes from the external contents.
959///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000960/// In both cases, the 'name' field may contain multiple path components (e.g.
961/// /path/to/file). However, any directory that contains more than one child
962/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000963class RedirectingFileSystem : public vfs::FileSystem {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000964 friend class RedirectingFileSystemParser;
965
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000966 /// The root(s) of the virtual file system.
967 std::vector<std::unique_ptr<Entry>> Roots;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000969 /// The file system to use for external references.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000970 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000971
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000972 /// If IsRelativeOverlay is set, this represents the directory
973 /// path that should be prefixed to each 'external-contents' entry
974 /// when reading from YAML files.
975 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000976
977 /// @name Configuration
978 /// @{
979
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000980 /// Whether to perform case-sensitive comparisons.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000981 ///
982 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000983 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000984
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000985 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
986 /// be prefixed in every 'external-contents' when reading from YAML files.
987 bool IsRelativeOverlay = false;
988
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000989 /// Whether to use to use the value of 'external-contents' for the
Ben Langmuirb59cf672014-02-27 00:25:12 +0000990 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000991 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000992
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000993 /// Whether an invalid path obtained via 'external-contents' should
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000994 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
995 /// the entry and continue with the next. Allows YAML files to be shared
996 /// across multiple compiler invocations regardless of prior existent
997 /// paths in 'external-contents'. This global value is overridable on a
998 /// per-file basis.
999 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001000 /// @}
1001
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001002 /// Virtual file paths and external files could be canonicalized without "..",
1003 /// "." and "./" in their paths. FIXME: some unittests currently fail on
1004 /// win32 when using remove_dots and remove_leading_dotslash on paths.
1005 bool UseCanonicalizedPaths =
Nico Weber1865df42018-04-27 19:11:14 +00001006#ifdef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001007 false;
1008#else
1009 true;
1010#endif
1011
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001012private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001013 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001014 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001015
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001016 /// Looks up the path <tt>[Start, End)</tt> in \p From, possibly
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001017 /// recursing into the contents of \p From if it is a directory.
1018 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
1019 sys::path::const_iterator End, Entry *From);
1020
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001021 /// Get the status of a given an \c Entry.
Ben Langmuir740812b2014-06-24 19:37:16 +00001022 ErrorOr<Status> status(const Twine &Path, Entry *E);
1023
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001024public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001025 /// Looks up \p Path in \c Roots.
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001026 ErrorOr<Entry *> lookupPath(const Twine &Path);
1027
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001028 /// Parses \p Buffer, which is expected to be in YAML format and
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001029 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001030 static RedirectingFileSystem *
1031 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001032 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
1033 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001034
Craig Toppera798a9d2014-03-02 09:32:10 +00001035 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +00001036 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +00001037
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001038 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
1039 return ExternalFS->getCurrentWorkingDirectory();
1040 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001041
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001042 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
1043 return ExternalFS->setCurrentWorkingDirectory(Path);
1044 }
1045
Ben Langmuir740812b2014-06-24 19:37:16 +00001046 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
1047 ErrorOr<Entry *> E = lookupPath(Dir);
1048 if (!E) {
1049 EC = E.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001050 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001051 }
1052 ErrorOr<Status> S = status(Dir, *E);
1053 if (!S) {
1054 EC = S.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001055 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001056 }
1057 if (!S->isDirectory()) {
1058 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1059 std::system_category());
Eugene Zelenko5a520112018-03-28 22:09:09 +00001060 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001061 }
1062
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001063 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +00001064 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
1065 *this, D->contents_begin(), D->contents_end(), EC));
1066 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001067
1068 void setExternalContentsPrefixDir(StringRef PrefixDir) {
1069 ExternalContentsPrefixDir = PrefixDir.str();
1070 }
1071
1072 StringRef getExternalContentsPrefixDir() const {
1073 return ExternalContentsPrefixDir;
1074 }
1075
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001076 bool ignoreNonExistentContents() const {
1077 return IgnoreNonExistentContents;
1078 }
1079
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001080#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1081LLVM_DUMP_METHOD void dump() const {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001082 for (const auto &Root : Roots)
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001083 dumpEntry(Root.get());
1084 }
1085
1086LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
1087 StringRef Name = E->getName();
1088 for (int i = 0, e = NumSpaces; i < e; ++i)
1089 dbgs() << " ";
1090 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
1091
1092 if (E->getKind() == EK_Directory) {
1093 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
1094 assert(DE && "Should be a directory");
1095
1096 for (std::unique_ptr<Entry> &SubEntry :
1097 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1098 dumpEntry(SubEntry.get(), NumSpaces+2);
1099 }
1100 }
1101#endif
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001102};
1103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001104/// A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001105class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001106 yaml::Stream &Stream;
1107
1108 void error(yaml::Node *N, const Twine &Msg) {
1109 Stream.printError(N, Msg);
1110 }
1111
1112 // false on error
1113 bool parseScalarString(yaml::Node *N, StringRef &Result,
1114 SmallVectorImpl<char> &Storage) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001115 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1116
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001117 if (!S) {
1118 error(N, "expected string");
1119 return false;
1120 }
1121 Result = S->getValue(Storage);
1122 return true;
1123 }
1124
1125 // false on error
1126 bool parseScalarBool(yaml::Node *N, bool &Result) {
1127 SmallString<5> Storage;
1128 StringRef Value;
1129 if (!parseScalarString(N, Value, Storage))
1130 return false;
1131
1132 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1133 Value.equals_lower("yes") || Value == "1") {
1134 Result = true;
1135 return true;
1136 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1137 Value.equals_lower("no") || Value == "0") {
1138 Result = false;
1139 return true;
1140 }
1141
1142 error(N, "expected boolean value");
1143 return false;
1144 }
1145
1146 struct KeyStatus {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001147 bool Required;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001148 bool Seen = false;
1149
1150 KeyStatus(bool Required = false) : Required(Required) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001151 };
Eugene Zelenko5a520112018-03-28 22:09:09 +00001152
1153 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001154
1155 // false on error
1156 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1157 DenseMap<StringRef, KeyStatus> &Keys) {
1158 if (!Keys.count(Key)) {
1159 error(KeyNode, "unknown key");
1160 return false;
1161 }
1162 KeyStatus &S = Keys[Key];
1163 if (S.Seen) {
1164 error(KeyNode, Twine("duplicate key '") + Key + "'");
1165 return false;
1166 }
1167 S.Seen = true;
1168 return true;
1169 }
1170
1171 // false on error
1172 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001173 for (const auto &I : Keys) {
1174 if (I.second.Required && !I.second.Seen) {
1175 error(Obj, Twine("missing key '") + I.first + "'");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001176 return false;
1177 }
1178 }
1179 return true;
1180 }
1181
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001182 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1183 Entry *ParentEntry = nullptr) {
1184 if (!ParentEntry) { // Look for a existent root
Eugene Zelenko5a520112018-03-28 22:09:09 +00001185 for (const auto &Root : FS->Roots) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001186 if (Name.equals(Root->getName())) {
1187 ParentEntry = Root.get();
1188 return ParentEntry;
1189 }
1190 }
1191 } else { // Advance to the next component
1192 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1193 for (std::unique_ptr<Entry> &Content :
1194 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1195 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1196 if (DirContent && Name.equals(Content->getName()))
1197 return DirContent;
1198 }
1199 }
1200
1201 // ... or create a new one
1202 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001203 Name,
1204 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1205 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001206
1207 if (!ParentEntry) { // Add a new root to the overlay
1208 FS->Roots.push_back(std::move(E));
1209 ParentEntry = FS->Roots.back().get();
1210 return ParentEntry;
1211 }
1212
1213 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1214 DE->addContent(std::move(E));
1215 return DE->getLastContent();
1216 }
1217
1218 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1219 Entry *NewParentE = nullptr) {
1220 StringRef Name = SrcE->getName();
1221 switch (SrcE->getKind()) {
1222 case EK_Directory: {
1223 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1224 assert(DE && "Must be a directory");
1225 // Empty directories could be present in the YAML as a way to
1226 // describe a file for a current directory after some of its subdir
1227 // is parsed. This only leads to redundant walks, ignore it.
1228 if (!Name.empty())
1229 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1230 for (std::unique_ptr<Entry> &SubEntry :
1231 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1232 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1233 break;
1234 }
1235 case EK_File: {
1236 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1237 assert(FE && "Must be a file");
1238 assert(NewParentE && "Parent entry must exist");
1239 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1240 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1241 Name, FE->getExternalContentsPath(), FE->getUseName()));
1242 break;
1243 }
1244 }
1245 }
1246
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001247 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001248 auto *M = dyn_cast<yaml::MappingNode>(N);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001249 if (!M) {
1250 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001251 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001252 }
1253
1254 KeyStatusPair Fields[] = {
1255 KeyStatusPair("name", true),
1256 KeyStatusPair("type", true),
1257 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001258 KeyStatusPair("external-contents", false),
1259 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001260 };
1261
Craig Topperac67c052015-11-30 03:11:10 +00001262 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001263
1264 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001265 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001266 std::string ExternalContentsPath;
1267 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001268 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001269 EntryKind Kind;
1270
Eugene Zelenko5a520112018-03-28 22:09:09 +00001271 for (auto &I : *M) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001272 StringRef Key;
1273 // Reuse the buffer for key and value, since we don't look at key after
1274 // parsing value.
1275 SmallString<256> Buffer;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001276 if (!parseScalarString(I.getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001277 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001278
Eugene Zelenko5a520112018-03-28 22:09:09 +00001279 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001280 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001281
1282 StringRef Value;
1283 if (Key == "name") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001284 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001285 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001286
1287 if (FS->UseCanonicalizedPaths) {
1288 SmallString<256> Path(Value);
1289 // Guarantee that old YAML files containing paths with ".." and "."
1290 // are properly canonicalized before read into the VFS.
1291 Path = sys::path::remove_leading_dotslash(Path);
1292 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1293 Name = Path.str();
1294 } else {
1295 Name = Value;
1296 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001297 } else if (Key == "type") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001298 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001299 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001300 if (Value == "file")
1301 Kind = EK_File;
1302 else if (Value == "directory")
1303 Kind = EK_Directory;
1304 else {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001305 error(I.getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001306 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001307 }
1308 } else if (Key == "contents") {
1309 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001310 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001311 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001312 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001313 }
1314 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001315 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001316 if (!Contents) {
1317 // FIXME: this is only for directories, what about files?
Eugene Zelenko5a520112018-03-28 22:09:09 +00001318 error(I.getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001319 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001320 }
1321
Eugene Zelenko5a520112018-03-28 22:09:09 +00001322 for (auto &I : *Contents) {
1323 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001324 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001325 else
Craig Topperf1186c52014-05-08 06:41:40 +00001326 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001327 }
1328 } else if (Key == "external-contents") {
1329 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001330 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001331 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001332 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001333 }
1334 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001335 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001336 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001337
1338 SmallString<256> FullPath;
1339 if (FS->IsRelativeOverlay) {
1340 FullPath = FS->getExternalContentsPrefixDir();
1341 assert(!FullPath.empty() &&
1342 "External contents prefix directory must exist");
1343 llvm::sys::path::append(FullPath, Value);
1344 } else {
1345 FullPath = Value;
1346 }
1347
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001348 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001349 // Guarantee that old YAML files containing paths with ".." and "."
1350 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001351 FullPath = sys::path::remove_leading_dotslash(FullPath);
1352 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001353 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001354 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001355 } else if (Key == "use-external-name") {
1356 bool Val;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001357 if (!parseScalarBool(I.getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001358 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001359 UseExternalName = Val ? RedirectingFileEntry::NK_External
1360 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001361 } else {
1362 llvm_unreachable("key missing from Keys");
1363 }
1364 }
1365
1366 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001367 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001368
1369 // check for missing keys
1370 if (!HasContents) {
1371 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001372 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001373 }
1374 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001375 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001376
Ben Langmuirb59cf672014-02-27 00:25:12 +00001377 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001378 if (Kind == EK_Directory &&
1379 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001380 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001381 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001382 }
1383
Ben Langmuir93853232014-03-05 21:32:20 +00001384 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001385 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001386 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1387 while (Trimmed.size() > RootPathLen &&
1388 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001389 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1390 // Get the last component
1391 StringRef LastComponent = sys::path::filename(Trimmed);
1392
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001393 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001394 switch (Kind) {
1395 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001396 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001397 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001398 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001399 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001400 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001401 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001402 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1403 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001404 break;
1405 }
1406
1407 StringRef Parent = sys::path::parent_path(Trimmed);
1408 if (Parent.empty())
1409 return Result;
1410
1411 // if 'name' contains multiple components, create implicit directory entries
1412 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1413 E = sys::path::rend(Parent);
1414 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001415 std::vector<std::unique_ptr<Entry>> Entries;
1416 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001417 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001418 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001419 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1420 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001421 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001422 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001423 }
1424
1425public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001426 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001427
1428 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001429 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001430 auto *Top = dyn_cast<yaml::MappingNode>(Root);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001431 if (!Top) {
1432 error(Root, "expected mapping node");
1433 return false;
1434 }
1435
1436 KeyStatusPair Fields[] = {
1437 KeyStatusPair("version", true),
1438 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001439 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001440 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001441 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001442 KeyStatusPair("roots", true),
1443 };
1444
Craig Topperac67c052015-11-30 03:11:10 +00001445 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001446 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001447
1448 // Parse configuration and 'roots'
Eugene Zelenko5a520112018-03-28 22:09:09 +00001449 for (auto &I : *Top) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001450 SmallString<10> KeyBuffer;
1451 StringRef Key;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001452 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001453 return false;
1454
Eugene Zelenko5a520112018-03-28 22:09:09 +00001455 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001456 return false;
1457
1458 if (Key == "roots") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001459 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001460 if (!Roots) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001461 error(I.getValue(), "expected array");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001462 return false;
1463 }
1464
Eugene Zelenko5a520112018-03-28 22:09:09 +00001465 for (auto &I : *Roots) {
1466 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001467 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001468 else
1469 return false;
1470 }
1471 } else if (Key == "version") {
1472 StringRef VersionString;
1473 SmallString<4> Storage;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001474 if (!parseScalarString(I.getValue(), VersionString, Storage))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001475 return false;
1476 int Version;
1477 if (VersionString.getAsInteger<int>(10, Version)) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001478 error(I.getValue(), "expected integer");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001479 return false;
1480 }
1481 if (Version < 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001482 error(I.getValue(), "invalid version number");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001483 return false;
1484 }
1485 if (Version != 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001486 error(I.getValue(), "version mismatch, expected 0");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001487 return false;
1488 }
1489 } else if (Key == "case-sensitive") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001490 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001491 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001492 } else if (Key == "overlay-relative") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001493 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001494 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001495 } else if (Key == "use-external-names") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001496 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
Ben Langmuirb59cf672014-02-27 00:25:12 +00001497 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001498 } else if (Key == "ignore-non-existent-contents") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001499 if (!parseScalarBool(I.getValue(), FS->IgnoreNonExistentContents))
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001500 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001501 } else {
1502 llvm_unreachable("key missing from Keys");
1503 }
1504 }
1505
1506 if (Stream.failed())
1507 return false;
1508
1509 if (!checkMissingKeys(Top, Keys))
1510 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001511
1512 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1513 // representation to a proper directory tree so that we can search faster
1514 // inside the VFS.
Eugene Zelenko5a520112018-03-28 22:09:09 +00001515 for (auto &E : RootEntries)
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001516 uniqueOverlayTree(FS, E.get());
1517
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001518 return true;
1519 }
1520};
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001521
Eugene Zelenko5a520112018-03-28 22:09:09 +00001522} // namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001523
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001524RedirectingFileSystem *
1525RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1526 SourceMgr::DiagHandlerTy DiagHandler,
1527 StringRef YAMLFilePath, void *DiagContext,
1528 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001529 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001530 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001531
Ben Langmuir97882e72014-02-24 20:56:37 +00001532 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001533 yaml::document_iterator DI = Stream.begin();
1534 yaml::Node *Root = DI->getRoot();
1535 if (DI == Stream.end() || !Root) {
1536 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001537 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001538 }
1539
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001540 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001541
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001542 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001543 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001544
1545 if (!YAMLFilePath.empty()) {
1546 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1547 // to each 'external-contents' path.
1548 //
1549 // Example:
1550 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1551 // yields:
1552 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1553 //
1554 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1555 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1556 assert(!EC && "Overlay dir final path must be absolute");
1557 (void)EC;
1558 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1559 }
1560
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001561 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001562 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001563
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001564 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001565}
1566
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001567ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001568 SmallString<256> Path;
1569 Path_.toVector(Path);
1570
1571 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001572 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001573 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001574
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001575 // Canonicalize path by removing ".", "..", "./", etc components. This is
1576 // a VFS request, do bot bother about symlinks in the path components
1577 // but canonicalize in order to perform the correct entry search.
1578 if (UseCanonicalizedPaths) {
1579 Path = sys::path::remove_leading_dotslash(Path);
1580 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1581 }
1582
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001583 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001584 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001585
1586 sys::path::const_iterator Start = sys::path::begin(Path);
1587 sys::path::const_iterator End = sys::path::end(Path);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001588 for (const auto &Root : Roots) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001589 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001590 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001591 return Result;
1592 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001593 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001594}
1595
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001596ErrorOr<Entry *>
1597RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1598 sys::path::const_iterator End, Entry *From) {
Nico Weber1865df42018-04-27 19:11:14 +00001599#ifndef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001600 assert(!isTraversalComponent(*Start) &&
1601 !isTraversalComponent(From->getName()) &&
1602 "Paths should not contain traversal components");
1603#else
1604 // FIXME: this is here to support windows, remove it once canonicalized
1605 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001606 if (Start->equals("."))
1607 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001608#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001609
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001610 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001611
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001612 // Forward the search to the next component in case this is an empty one.
1613 if (!FromName.empty()) {
1614 if (CaseSensitive ? !Start->equals(FromName)
1615 : !Start->equals_lower(FromName))
1616 // failure to match
1617 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001618
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001619 ++Start;
1620
1621 if (Start == End) {
1622 // Match!
1623 return From;
1624 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001625 }
1626
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001627 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001628 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001629 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001630
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001631 for (const std::unique_ptr<Entry> &DirEntry :
1632 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1633 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001634 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001635 return Result;
1636 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001637 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001638}
1639
Ben Langmuirf13302e2015-12-10 23:41:39 +00001640static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1641 Status ExternalStatus) {
1642 Status S = ExternalStatus;
1643 if (!UseExternalNames)
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001644 S = Status::copyWithNewName(S, Path.str());
Ben Langmuirf13302e2015-12-10 23:41:39 +00001645 S.IsVFSMapped = true;
1646 return S;
1647}
1648
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001649ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001650 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001651 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001652 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001653 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001654 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001655 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1656 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001657 return S;
1658 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001659 auto *DE = cast<RedirectingDirectoryEntry>(E);
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001660 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001661 }
1662}
1663
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001664ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001665 ErrorOr<Entry *> Result = lookupPath(Path);
1666 if (!Result)
1667 return Result.getError();
1668 return status(Path, *Result);
1669}
1670
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001671namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001672
Ben Langmuirf13302e2015-12-10 23:41:39 +00001673/// Provide a file wrapper with an overriden status.
1674class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001675 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001676 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001677
1678public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001679 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001680 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001681
Ben Langmuirf13302e2015-12-10 23:41:39 +00001682 ErrorOr<Status> status() override { return S; }
1683 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Eugene Zelenko5a520112018-03-28 22:09:09 +00001684
Benjamin Kramer737501c2015-10-05 21:20:19 +00001685 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1686 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001687 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1688 IsVolatile);
1689 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001690
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001691 std::error_code close() override { return InnerFile->close(); }
1692};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001693
1694} // namespace
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001695
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001696ErrorOr<std::unique_ptr<File>>
1697RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001698 ErrorOr<Entry *> E = lookupPath(Path);
1699 if (!E)
1700 return E.getError();
1701
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001702 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001703 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001704 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001705
Benjamin Kramera8857962014-10-26 22:44:13 +00001706 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1707 if (!Result)
1708 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001709
Ben Langmuirf13302e2015-12-10 23:41:39 +00001710 auto ExternalStatus = (*Result)->status();
1711 if (!ExternalStatus)
1712 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001713
Ben Langmuirf13302e2015-12-10 23:41:39 +00001714 // FIXME: Update the status with the name and VFSMapped.
1715 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1716 *ExternalStatus);
1717 return std::unique_ptr<File>(
1718 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001719}
1720
1721IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001722vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001723 SourceMgr::DiagHandlerTy DiagHandler,
1724 StringRef YAMLFilePath,
1725 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001726 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001727 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001728 YAMLFilePath, DiagContext,
1729 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001730}
1731
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001732static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1733 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1734 auto Kind = SrcE->getKind();
1735 if (Kind == EK_Directory) {
1736 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1737 assert(DE && "Must be a directory");
1738 for (std::unique_ptr<Entry> &SubEntry :
1739 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1740 Path.push_back(SubEntry->getName());
1741 getVFSEntries(SubEntry.get(), Path, Entries);
1742 Path.pop_back();
1743 }
1744 return;
1745 }
1746
1747 assert(Kind == EK_File && "Must be a EK_File");
1748 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1749 assert(FE && "Must be a file");
1750 SmallString<128> VPath;
1751 for (auto &Comp : Path)
1752 llvm::sys::path::append(VPath, Comp);
1753 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1754}
1755
1756void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1757 SourceMgr::DiagHandlerTy DiagHandler,
1758 StringRef YAMLFilePath,
1759 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1760 void *DiagContext,
1761 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1762 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1763 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1764 std::move(ExternalFS));
1765 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1766 if (!RootE)
1767 return;
1768 SmallVector<StringRef, 8> Components;
1769 Components.push_back("/");
1770 getVFSEntries(*RootE, Components, CollectedEntries);
1771}
1772
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001773UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001774 static std::atomic<unsigned> UID;
1775 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001776 // The following assumes that uint64_t max will never collide with a real
1777 // dev_t value from the OS.
1778 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1779}
Justin Bogner9c785292014-05-20 21:43:27 +00001780
Justin Bogner9c785292014-05-20 21:43:27 +00001781void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1782 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1783 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1784 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1785 Mappings.emplace_back(VirtualPath, RealPath);
1786}
1787
Justin Bogner44fa450342014-05-21 22:46:51 +00001788namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001789
Justin Bogner44fa450342014-05-21 22:46:51 +00001790class JSONWriter {
1791 llvm::raw_ostream &OS;
1792 SmallVector<StringRef, 16> DirStack;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001793
1794 unsigned getDirIndent() { return 4 * DirStack.size(); }
1795 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
Justin Bogner44fa450342014-05-21 22:46:51 +00001796 bool containedIn(StringRef Parent, StringRef Path);
1797 StringRef containedPart(StringRef Parent, StringRef Path);
1798 void startDirectory(StringRef Path);
1799 void endDirectory();
1800 void writeEntry(StringRef VPath, StringRef RPath);
1801
1802public:
1803 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001804
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001805 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1806 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001807 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001808};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001809
1810} // namespace
Justin Bogner9c785292014-05-20 21:43:27 +00001811
Justin Bogner44fa450342014-05-21 22:46:51 +00001812bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001813 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001814
Justin Bogner1c078f22014-05-20 22:12:58 +00001815 // Compare each path component.
1816 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1817 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1818 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1819 if (*IParent != *IChild)
1820 return false;
1821 }
1822 // Have we exhausted the parent path?
1823 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001824}
1825
Justin Bogner44fa450342014-05-21 22:46:51 +00001826StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1827 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001828 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001829 return Path.slice(Parent.size() + 1, StringRef::npos);
1830}
1831
Justin Bogner44fa450342014-05-21 22:46:51 +00001832void JSONWriter::startDirectory(StringRef Path) {
1833 StringRef Name =
1834 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1835 DirStack.push_back(Path);
1836 unsigned Indent = getDirIndent();
1837 OS.indent(Indent) << "{\n";
1838 OS.indent(Indent + 2) << "'type': 'directory',\n";
1839 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1840 OS.indent(Indent + 2) << "'contents': [\n";
1841}
1842
1843void JSONWriter::endDirectory() {
1844 unsigned Indent = getDirIndent();
1845 OS.indent(Indent + 2) << "]\n";
1846 OS.indent(Indent) << "}";
1847
1848 DirStack.pop_back();
1849}
1850
1851void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1852 unsigned Indent = getFileIndent();
1853 OS.indent(Indent) << "{\n";
1854 OS.indent(Indent + 2) << "'type': 'file',\n";
1855 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1856 OS.indent(Indent + 2) << "'external-contents': \""
1857 << llvm::yaml::escape(RPath) << "\"\n";
1858 OS.indent(Indent) << "}";
1859}
1860
1861void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001862 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001863 Optional<bool> IsCaseSensitive,
1864 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001865 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001866 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001867 using namespace llvm::sys;
1868
1869 OS << "{\n"
1870 " 'version': 0,\n";
1871 if (IsCaseSensitive.hasValue())
1872 OS << " 'case-sensitive': '"
1873 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001874 if (UseExternalNames.hasValue())
1875 OS << " 'use-external-names': '"
1876 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001877 bool UseOverlayRelative = false;
1878 if (IsOverlayRelative.hasValue()) {
1879 UseOverlayRelative = IsOverlayRelative.getValue();
1880 OS << " 'overlay-relative': '"
1881 << (UseOverlayRelative ? "true" : "false") << "',\n";
1882 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001883 if (IgnoreNonExistentContents.hasValue())
1884 OS << " 'ignore-non-existent-contents': '"
1885 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001886 OS << " 'roots': [\n";
1887
Justin Bogner73466402014-07-15 01:24:35 +00001888 if (!Entries.empty()) {
1889 const YAMLVFSEntry &Entry = Entries.front();
1890 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001891
1892 StringRef RPath = Entry.RPath;
1893 if (UseOverlayRelative) {
1894 unsigned OverlayDirLen = OverlayDir.size();
1895 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1896 "Overlay dir must be contained in RPath");
1897 RPath = RPath.slice(OverlayDirLen, RPath.size());
1898 }
1899
1900 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001901
Justin Bogner73466402014-07-15 01:24:35 +00001902 for (const auto &Entry : Entries.slice(1)) {
1903 StringRef Dir = path::parent_path(Entry.VPath);
1904 if (Dir == DirStack.back())
1905 OS << ",\n";
1906 else {
1907 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1908 OS << "\n";
1909 endDirectory();
1910 }
1911 OS << ",\n";
1912 startDirectory(Dir);
1913 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001914 StringRef RPath = Entry.RPath;
1915 if (UseOverlayRelative) {
1916 unsigned OverlayDirLen = OverlayDir.size();
1917 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1918 "Overlay dir must be contained in RPath");
1919 RPath = RPath.slice(OverlayDirLen, RPath.size());
1920 }
1921 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001922 }
1923
1924 while (!DirStack.empty()) {
1925 OS << "\n";
1926 endDirectory();
1927 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001928 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001929 }
1930
Justin Bogner73466402014-07-15 01:24:35 +00001931 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001932 << "}\n";
1933}
1934
Justin Bogner9c785292014-05-20 21:43:27 +00001935void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001936 llvm::sort(Mappings.begin(), Mappings.end(),
1937 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001938 return LHS.VPath < RHS.VPath;
1939 });
1940
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001941 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001942 IsOverlayRelative, IgnoreNonExistentContents,
1943 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001944}
Ben Langmuir740812b2014-06-24 19:37:16 +00001945
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001946VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1947 const Twine &_Path, RedirectingFileSystem &FS,
1948 RedirectingDirectoryEntry::iterator Begin,
1949 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001950 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001951 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001952 SmallString<128> PathStr(Dir);
1953 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001954 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001955 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001956 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001957 return;
1958 }
1959 // Skip entries which do not map to a reliable external content.
1960 if (FS.ignoreNonExistentContents() &&
1961 S.getError() == llvm::errc::no_such_file_or_directory) {
1962 ++Current;
1963 continue;
1964 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00001965 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001966 break;
1967 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001968 }
1969}
1970
1971std::error_code VFSFromYamlDirIterImpl::increment() {
1972 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001973 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001974 SmallString<128> PathStr(Dir);
1975 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001976 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001977 if (!S) {
1978 // Skip entries which do not map to a reliable external content.
1979 if (FS.ignoreNonExistentContents() &&
1980 S.getError() == llvm::errc::no_such_file_or_directory) {
1981 continue;
1982 } else {
1983 return S.getError();
1984 }
1985 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001986 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001987 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00001988 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001989
1990 if (Current == End)
1991 CurrentEntry = Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001992 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001993}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001994
1995vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1996 const Twine &Path,
1997 std::error_code &EC)
1998 : FS(&FS_) {
1999 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00002000 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002001 State = std::make_shared<IterState>();
2002 State->push(I);
2003 }
2004}
2005
2006vfs::recursive_directory_iterator &
2007recursive_directory_iterator::increment(std::error_code &EC) {
2008 assert(FS && State && !State->empty() && "incrementing past end");
2009 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
2010 vfs::directory_iterator End;
2011 if (State->top()->isDirectory()) {
2012 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002013 if (I != End) {
2014 State->push(I);
2015 return *this;
2016 }
2017 }
2018
2019 while (!State->empty() && State->top().increment(EC) == End)
2020 State->pop();
2021
2022 if (State->empty())
2023 State.reset(); // end iterator
2024
2025 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002026}