blob: f8acde94ca92cdcb0404efdbaff117a0531af336 [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
Benjamin Kramer268b51a2015-10-05 13:15:33 +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}
81
82Status 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());
86}
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;
Taewook Ohf42103c2016-06-13 20:40:21 +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;
Benjamin Kramer268b51a2015-10-05 13:15:33 +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
Taewook Ohf42103c2016-06-13 20:40:21 +0000215ErrorOr<std::string> RealFile::getName() {
216 return RealName.empty() ? S.getName().str() : RealName;
217}
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;
Benjamin Kramer268b51a2015-10-05 13:15:33 +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);
Juergen Ributzkaf9787432017-03-14 00:14:40 +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);
Benjamin Kramer268b51a2015-10-05 13:15:33 +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 {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000474 InMemoryNodeKind Kind;
Simon Marchia37ef292018-07-11 14:08:17 +0000475 Status Stat;
476
477protected:
478 /// Return Stat. This should only be used for internal/debugging use. When
479 /// clients wants the Status of this node, they should use
480 /// \p getStatus(StringRef).
481 const Status& getStatus() const {
482 return Stat;
483 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000484
485public:
486 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
Simon Marchia37ef292018-07-11 14:08:17 +0000487 : Kind(Kind), Stat(std::move(Stat)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000488 virtual ~InMemoryNode() = default;
489
Simon Marchia37ef292018-07-11 14:08:17 +0000490 /// Return the \p Status for this node. \p RequestedName should be the name
491 /// through which the caller referred to this node. It will override
492 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
493 Status getStatus(StringRef RequestedName) const {
494 return Status::copyWithNewName(Stat, RequestedName);
495 }
496
497 /// Get the filename of this node (the name without the directory part).
498 StringRef getFileName() const {
499 return llvm::sys::path::filename(Stat.getName());
500 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000501 InMemoryNodeKind getKind() const { return Kind; }
502 virtual std::string toString(unsigned Indent) const = 0;
503};
504
505namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000506
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000507class InMemoryFile : public InMemoryNode {
508 std::unique_ptr<llvm::MemoryBuffer> Buffer;
509
510public:
511 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
512 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
513
514 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000515
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000516 std::string toString(unsigned Indent) const override {
517 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
518 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000519
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000520 static bool classof(const InMemoryNode *N) {
521 return N->getKind() == IME_File;
522 }
523};
524
Simon Marchia37ef292018-07-11 14:08:17 +0000525/// Adapt a InMemoryFile for VFS' File interface. The goal is to make
526/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
527/// \p RealFile.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000528class InMemoryFileAdaptor : public File {
529 InMemoryFile &Node;
530
Simon Marchia37ef292018-07-11 14:08:17 +0000531 /// The name to use when returning a Status for this file.
532 std::string RequestedName;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000533
Simon Marchia37ef292018-07-11 14:08:17 +0000534public:
535 explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string RequestedName)
536 : Node(Node), RequestedName(std::move(RequestedName)) {}
537
538 llvm::ErrorOr<Status> status() override {
539 return Node.getStatus(RequestedName);
540 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000541
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000542 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000543 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
544 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000545 llvm::MemoryBuffer *Buf = Node.getBuffer();
546 return llvm::MemoryBuffer::getMemBuffer(
547 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
548 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000549
550 std::error_code close() override { return {}; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000551};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000552
553} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000554
555class InMemoryDirectory : public InMemoryNode {
556 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
557
558public:
559 InMemoryDirectory(Status Stat)
560 : InMemoryNode(std::move(Stat), IME_Directory) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000561
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000562 InMemoryNode *getChild(StringRef Name) {
563 auto I = Entries.find(Name);
564 if (I != Entries.end())
565 return I->second.get();
566 return nullptr;
567 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000568
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000569 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
570 return Entries.insert(make_pair(Name, std::move(Child)))
571 .first->second.get();
572 }
573
Eugene Zelenko5a520112018-03-28 22:09:09 +0000574 using const_iterator = decltype(Entries)::const_iterator;
575
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000576 const_iterator begin() const { return Entries.begin(); }
577 const_iterator end() const { return Entries.end(); }
578
579 std::string toString(unsigned Indent) const override {
580 std::string Result =
581 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000582 for (const auto &Entry : Entries)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000583 Result += Entry.second->toString(Indent + 2);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000584 return Result;
585 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000586
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000587 static bool classof(const InMemoryNode *N) {
588 return N->getKind() == IME_Directory;
589 }
590};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000591
592} // namespace detail
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000593
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000594InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000595 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000596 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
597 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000598 llvm::sys::fs::perms::all_all))),
599 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000600
Eugene Zelenko5a520112018-03-28 22:09:09 +0000601InMemoryFileSystem::~InMemoryFileSystem() = default;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000602
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000603std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000604 return Root->toString(/*Indent=*/0);
605}
606
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000607bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000608 std::unique_ptr<llvm::MemoryBuffer> Buffer,
609 Optional<uint32_t> User,
610 Optional<uint32_t> Group,
611 Optional<llvm::sys::fs::file_type> Type,
612 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000613 SmallString<128> Path;
614 P.toVector(Path);
615
616 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000617 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000618 assert(!EC);
619 (void)EC;
620
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000621 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000622 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000623
624 if (Path.empty())
625 return false;
626
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000627 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000628 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
629 const auto ResolvedUser = User.getValueOr(0);
630 const auto ResolvedGroup = Group.getValueOr(0);
631 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
632 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
633 // Any intermediate directories we create should be accessible by
634 // the owner, even if Perms says otherwise for the final path.
635 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000636 while (true) {
637 StringRef Name = *I;
638 detail::InMemoryNode *Node = Dir->getChild(Name);
639 ++I;
640 if (!Node) {
641 if (I == E) {
Ben Hamilton78381012017-11-16 19:34:08 +0000642 // End of the path, create a new file or directory.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000643 Status Stat(P.str(), getNextVirtualUniqueID(),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000644 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
645 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
646 ResolvedPerms);
Ben Hamilton78381012017-11-16 19:34:08 +0000647 std::unique_ptr<detail::InMemoryNode> Child;
648 if (ResolvedType == sys::fs::file_type::directory_file) {
649 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
650 } else {
651 Child.reset(new detail::InMemoryFile(std::move(Stat),
652 std::move(Buffer)));
653 }
654 Dir->addChild(Name, std::move(Child));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000655 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000656 }
657
658 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000659 Status Stat(
660 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000661 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
662 ResolvedUser, ResolvedGroup, Buffer->getBufferSize(),
663 sys::fs::file_type::directory_file, NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000664 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
665 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
666 continue;
667 }
668
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000669 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000670 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000671 } else {
672 assert(isa<detail::InMemoryFile>(Node) &&
673 "Must be either file or directory!");
674
675 // Trying to insert a directory in place of a file.
676 if (I != E)
677 return false;
678
679 // Return false only if the new file is different from the existing one.
680 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
681 Buffer->getBuffer();
682 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000683 }
684}
685
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000686bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000687 llvm::MemoryBuffer *Buffer,
688 Optional<uint32_t> User,
689 Optional<uint32_t> Group,
690 Optional<llvm::sys::fs::file_type> Type,
691 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000692 return addFile(P, ModificationTime,
693 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000694 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
695 std::move(User), std::move(Group), std::move(Type),
696 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000697}
698
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000699static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000700lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
701 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000702 SmallString<128> Path;
703 P.toVector(Path);
704
705 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000706 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000707 assert(!EC);
708 (void)EC;
709
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000710 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000711 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000712
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000713 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000714 return Dir;
715
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000716 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000717 while (true) {
718 detail::InMemoryNode *Node = Dir->getChild(*I);
719 ++I;
720 if (!Node)
721 return errc::no_such_file_or_directory;
722
723 // Return the file if it's at the end of the path.
724 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
725 if (I == E)
726 return File;
727 return errc::no_such_file_or_directory;
728 }
729
730 // Traverse directories.
731 Dir = cast<detail::InMemoryDirectory>(Node);
732 if (I == E)
733 return Dir;
734 }
735}
736
737llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000738 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000739 if (Node)
Simon Marchia37ef292018-07-11 14:08:17 +0000740 return (*Node)->getStatus(Path.str());
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000741 return Node.getError();
742}
743
744llvm::ErrorOr<std::unique_ptr<File>>
745InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000746 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000747 if (!Node)
748 return Node.getError();
749
750 // When we have a file provide a heap-allocated wrapper for the memory buffer
751 // to match the ownership semantics for File.
752 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
Simon Marchia37ef292018-07-11 14:08:17 +0000753 return std::unique_ptr<File>(
754 new detail::InMemoryFileAdaptor(*F, Path.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000755
756 // FIXME: errc::not_a_file?
757 return make_error_code(llvm::errc::invalid_argument);
758}
759
760namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000761
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000762/// Adaptor from InMemoryDir::iterator to directory_iterator.
763class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
764 detail::InMemoryDirectory::const_iterator I;
765 detail::InMemoryDirectory::const_iterator E;
Simon Marchia37ef292018-07-11 14:08:17 +0000766 std::string RequestedDirName;
767
768 void setCurrentEntry() {
769 if (I != E) {
770 SmallString<256> Path(RequestedDirName);
771 llvm::sys::path::append(Path, I->second->getFileName());
772 CurrentEntry = I->second->getStatus(Path.str());
773 } else {
774 // When we're at the end, make CurrentEntry invalid and DirIterImpl will
775 // do the rest.
776 CurrentEntry = Status();
777 }
778 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000779
780public:
Eugene Zelenko5a520112018-03-28 22:09:09 +0000781 InMemoryDirIterator() = default;
782
Simon Marchia37ef292018-07-11 14:08:17 +0000783 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir,
784 std::string RequestedDirName)
785 : I(Dir.begin()), E(Dir.end()),
786 RequestedDirName(std::move(RequestedDirName)) {
787 setCurrentEntry();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000788 }
789
790 std::error_code increment() override {
791 ++I;
Simon Marchia37ef292018-07-11 14:08:17 +0000792 setCurrentEntry();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000793 return {};
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000794 }
795};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000796
797} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000798
799directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
800 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000801 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000802 if (!Node) {
803 EC = Node.getError();
804 return directory_iterator(std::make_shared<InMemoryDirIterator>());
805 }
806
807 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
Simon Marchia37ef292018-07-11 14:08:17 +0000808 return directory_iterator(
809 std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000810
811 EC = make_error_code(llvm::errc::not_a_directory);
812 return directory_iterator(std::make_shared<InMemoryDirIterator>());
813}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000814
815std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
816 SmallString<128> Path;
817 P.toVector(Path);
818
819 // Fix up relative paths. This just prepends the current working directory.
820 std::error_code EC = makeAbsolute(Path);
821 assert(!EC);
822 (void)EC;
823
824 if (useNormalizedPaths())
825 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
826
827 if (!Path.empty())
828 WorkingDirectory = Path.str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000829 return {};
Benjamin Kramere9e76072016-01-09 16:33:16 +0000830}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000831
Eric Liu33dd6192018-05-24 11:17:00 +0000832std::error_code
833InMemoryFileSystem::getRealPath(const Twine &Path,
834 SmallVectorImpl<char> &Output) const {
835 auto CWD = getCurrentWorkingDirectory();
836 if (!CWD || CWD->empty())
837 return errc::operation_not_permitted;
838 Path.toVector(Output);
839 if (auto EC = makeAbsolute(Output))
840 return EC;
841 llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
842 return {};
843}
844
Eugene Zelenko5a520112018-03-28 22:09:09 +0000845} // namespace vfs
846} // namespace clang
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000847
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000848//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000849// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000850//===-----------------------------------------------------------------------===/
851
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000852namespace {
853
854enum EntryKind {
855 EK_Directory,
856 EK_File
857};
858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000859/// A single file or directory in the VFS.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000860class Entry {
861 EntryKind Kind;
862 std::string Name;
863
864public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000865 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000866 virtual ~Entry() = default;
867
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000868 StringRef getName() const { return Name; }
869 EntryKind getKind() const { return Kind; }
870};
871
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000872class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000873 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000874 Status S;
875
876public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000877 RedirectingDirectoryEntry(StringRef Name,
878 std::vector<std::unique_ptr<Entry>> Contents,
879 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000880 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000881 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000882 RedirectingDirectoryEntry(StringRef Name, Status S)
883 : Entry(EK_Directory, Name), S(std::move(S)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000884
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000885 Status getStatus() { return S; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000886
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000887 void addContent(std::unique_ptr<Entry> Content) {
888 Contents.push_back(std::move(Content));
889 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000890
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000891 Entry *getLastContent() const { return Contents.back().get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000892
893 using iterator = decltype(Contents)::iterator;
894
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000895 iterator contents_begin() { return Contents.begin(); }
896 iterator contents_end() { return Contents.end(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000897
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000898 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
899};
900
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000901class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000902public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000903 enum NameKind {
904 NK_NotSet,
905 NK_External,
906 NK_Virtual
907 };
Eugene Zelenko5a520112018-03-28 22:09:09 +0000908
Ben Langmuirb59cf672014-02-27 00:25:12 +0000909private:
910 std::string ExternalContentsPath;
911 NameKind UseName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000912
Ben Langmuirb59cf672014-02-27 00:25:12 +0000913public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000914 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
915 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000916 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
917 UseName(UseName) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000918
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000919 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000920
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000921 /// whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000922 bool useExternalName(bool GlobalUseExternalName) const {
923 return UseName == NK_NotSet ? GlobalUseExternalName
924 : (UseName == NK_External);
925 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000926
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000927 NameKind getUseName() const { return UseName; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000928
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000929 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
930};
931
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000932class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000933
934class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
935 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000936 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000937 RedirectingDirectoryEntry::iterator Current, End;
938
Ben Langmuir740812b2014-06-24 19:37:16 +0000939public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000940 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000941 RedirectingDirectoryEntry::iterator Begin,
942 RedirectingDirectoryEntry::iterator End,
943 std::error_code &EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +0000944
Ben Langmuir740812b2014-06-24 19:37:16 +0000945 std::error_code increment() override;
946};
947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000948/// A virtual file system parsed from a YAML file.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000949///
950/// Currently, this class allows creating virtual directories and mapping
951/// virtual file paths to existing external files, available in \c ExternalFS.
952///
953/// The basic structure of the parsed file is:
954/// \verbatim
955/// {
956/// 'version': <version number>,
957/// <optional configuration>
958/// 'roots': [
959/// <directory entries>
960/// ]
961/// }
962/// \endverbatim
963///
964/// All configuration options are optional.
965/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000966/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000967/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000968/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000969///
970/// Virtual directories are represented as
971/// \verbatim
972/// {
973/// 'type': 'directory',
974/// 'name': <string>,
975/// 'contents': [ <file or directory entries> ]
976/// }
977/// \endverbatim
978///
979/// The default attributes for virtual directories are:
980/// \verbatim
981/// MTime = now() when created
982/// Perms = 0777
983/// User = Group = 0
984/// Size = 0
985/// UniqueID = unspecified unique value
986/// \endverbatim
987///
988/// Re-mapped files are represented as
989/// \verbatim
990/// {
991/// 'type': 'file',
992/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000993/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000994/// 'external-contents': <path to external file>)
995/// }
996/// \endverbatim
997///
998/// and inherit their attributes from the external contents.
999///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001000/// In both cases, the 'name' field may contain multiple path components (e.g.
1001/// /path/to/file). However, any directory that contains more than one child
1002/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001003class RedirectingFileSystem : public vfs::FileSystem {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001004 friend class RedirectingFileSystemParser;
1005
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001006 /// The root(s) of the virtual file system.
1007 std::vector<std::unique_ptr<Entry>> Roots;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001008
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001009 /// The file system to use for external references.
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001010 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001011
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001012 /// If IsRelativeOverlay is set, this represents the directory
1013 /// path that should be prefixed to each 'external-contents' entry
1014 /// when reading from YAML files.
1015 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001016
1017 /// @name Configuration
1018 /// @{
1019
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001020 /// Whether to perform case-sensitive comparisons.
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001021 ///
1022 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +00001023 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001024
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001025 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
1026 /// be prefixed in every 'external-contents' when reading from YAML files.
1027 bool IsRelativeOverlay = false;
1028
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001029 /// Whether to use to use the value of 'external-contents' for the
Ben Langmuirb59cf672014-02-27 00:25:12 +00001030 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +00001031 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001032
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001033 /// Whether an invalid path obtained via 'external-contents' should
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001034 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
1035 /// the entry and continue with the next. Allows YAML files to be shared
1036 /// across multiple compiler invocations regardless of prior existent
1037 /// paths in 'external-contents'. This global value is overridable on a
1038 /// per-file basis.
1039 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001040 /// @}
1041
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001042 /// Virtual file paths and external files could be canonicalized without "..",
1043 /// "." and "./" in their paths. FIXME: some unittests currently fail on
1044 /// win32 when using remove_dots and remove_leading_dotslash on paths.
1045 bool UseCanonicalizedPaths =
Nico Weber1865df42018-04-27 19:11:14 +00001046#ifdef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001047 false;
1048#else
1049 true;
1050#endif
1051
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001052private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001053 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001054 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001055
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001056 /// Looks up the path <tt>[Start, End)</tt> in \p From, possibly
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001057 /// recursing into the contents of \p From if it is a directory.
1058 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
1059 sys::path::const_iterator End, Entry *From);
1060
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001061 /// Get the status of a given an \c Entry.
Ben Langmuir740812b2014-06-24 19:37:16 +00001062 ErrorOr<Status> status(const Twine &Path, Entry *E);
1063
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001064public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001065 /// Looks up \p Path in \c Roots.
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001066 ErrorOr<Entry *> lookupPath(const Twine &Path);
1067
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001068 /// Parses \p Buffer, which is expected to be in YAML format and
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001069 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001070 static RedirectingFileSystem *
1071 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001072 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
1073 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001074
Craig Toppera798a9d2014-03-02 09:32:10 +00001075 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +00001076 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +00001077
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001078 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
1079 return ExternalFS->getCurrentWorkingDirectory();
1080 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001081
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001082 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
1083 return ExternalFS->setCurrentWorkingDirectory(Path);
1084 }
1085
Ben Langmuir740812b2014-06-24 19:37:16 +00001086 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
1087 ErrorOr<Entry *> E = lookupPath(Dir);
1088 if (!E) {
1089 EC = E.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001090 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001091 }
1092 ErrorOr<Status> S = status(Dir, *E);
1093 if (!S) {
1094 EC = S.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001095 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001096 }
1097 if (!S->isDirectory()) {
1098 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1099 std::system_category());
Eugene Zelenko5a520112018-03-28 22:09:09 +00001100 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001101 }
1102
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001103 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +00001104 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
1105 *this, D->contents_begin(), D->contents_end(), EC));
1106 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001107
1108 void setExternalContentsPrefixDir(StringRef PrefixDir) {
1109 ExternalContentsPrefixDir = PrefixDir.str();
1110 }
1111
1112 StringRef getExternalContentsPrefixDir() const {
1113 return ExternalContentsPrefixDir;
1114 }
1115
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001116 bool ignoreNonExistentContents() const {
1117 return IgnoreNonExistentContents;
1118 }
1119
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001120#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1121LLVM_DUMP_METHOD void dump() const {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001122 for (const auto &Root : Roots)
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001123 dumpEntry(Root.get());
1124 }
1125
1126LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
1127 StringRef Name = E->getName();
1128 for (int i = 0, e = NumSpaces; i < e; ++i)
1129 dbgs() << " ";
1130 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
1131
1132 if (E->getKind() == EK_Directory) {
1133 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
1134 assert(DE && "Should be a directory");
1135
1136 for (std::unique_ptr<Entry> &SubEntry :
1137 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1138 dumpEntry(SubEntry.get(), NumSpaces+2);
1139 }
1140 }
1141#endif
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001142};
1143
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001144/// A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001145class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001146 yaml::Stream &Stream;
1147
1148 void error(yaml::Node *N, const Twine &Msg) {
1149 Stream.printError(N, Msg);
1150 }
1151
1152 // false on error
1153 bool parseScalarString(yaml::Node *N, StringRef &Result,
1154 SmallVectorImpl<char> &Storage) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001155 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1156
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001157 if (!S) {
1158 error(N, "expected string");
1159 return false;
1160 }
1161 Result = S->getValue(Storage);
1162 return true;
1163 }
1164
1165 // false on error
1166 bool parseScalarBool(yaml::Node *N, bool &Result) {
1167 SmallString<5> Storage;
1168 StringRef Value;
1169 if (!parseScalarString(N, Value, Storage))
1170 return false;
1171
1172 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1173 Value.equals_lower("yes") || Value == "1") {
1174 Result = true;
1175 return true;
1176 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1177 Value.equals_lower("no") || Value == "0") {
1178 Result = false;
1179 return true;
1180 }
1181
1182 error(N, "expected boolean value");
1183 return false;
1184 }
1185
1186 struct KeyStatus {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001187 bool Required;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001188 bool Seen = false;
1189
1190 KeyStatus(bool Required = false) : Required(Required) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001191 };
Eugene Zelenko5a520112018-03-28 22:09:09 +00001192
1193 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001194
1195 // false on error
1196 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1197 DenseMap<StringRef, KeyStatus> &Keys) {
1198 if (!Keys.count(Key)) {
1199 error(KeyNode, "unknown key");
1200 return false;
1201 }
1202 KeyStatus &S = Keys[Key];
1203 if (S.Seen) {
1204 error(KeyNode, Twine("duplicate key '") + Key + "'");
1205 return false;
1206 }
1207 S.Seen = true;
1208 return true;
1209 }
1210
1211 // false on error
1212 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001213 for (const auto &I : Keys) {
1214 if (I.second.Required && !I.second.Seen) {
1215 error(Obj, Twine("missing key '") + I.first + "'");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001216 return false;
1217 }
1218 }
1219 return true;
1220 }
1221
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001222 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1223 Entry *ParentEntry = nullptr) {
1224 if (!ParentEntry) { // Look for a existent root
Eugene Zelenko5a520112018-03-28 22:09:09 +00001225 for (const auto &Root : FS->Roots) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001226 if (Name.equals(Root->getName())) {
1227 ParentEntry = Root.get();
1228 return ParentEntry;
1229 }
1230 }
1231 } else { // Advance to the next component
1232 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1233 for (std::unique_ptr<Entry> &Content :
1234 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1235 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1236 if (DirContent && Name.equals(Content->getName()))
1237 return DirContent;
1238 }
1239 }
1240
1241 // ... or create a new one
1242 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001243 Name,
1244 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1245 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001246
1247 if (!ParentEntry) { // Add a new root to the overlay
1248 FS->Roots.push_back(std::move(E));
1249 ParentEntry = FS->Roots.back().get();
1250 return ParentEntry;
1251 }
1252
1253 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1254 DE->addContent(std::move(E));
1255 return DE->getLastContent();
1256 }
1257
1258 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1259 Entry *NewParentE = nullptr) {
1260 StringRef Name = SrcE->getName();
1261 switch (SrcE->getKind()) {
1262 case EK_Directory: {
1263 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1264 assert(DE && "Must be a directory");
1265 // Empty directories could be present in the YAML as a way to
1266 // describe a file for a current directory after some of its subdir
1267 // is parsed. This only leads to redundant walks, ignore it.
1268 if (!Name.empty())
1269 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1270 for (std::unique_ptr<Entry> &SubEntry :
1271 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1272 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1273 break;
1274 }
1275 case EK_File: {
1276 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1277 assert(FE && "Must be a file");
1278 assert(NewParentE && "Parent entry must exist");
1279 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1280 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1281 Name, FE->getExternalContentsPath(), FE->getUseName()));
1282 break;
1283 }
1284 }
1285 }
1286
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001287 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001288 auto *M = dyn_cast<yaml::MappingNode>(N);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001289 if (!M) {
1290 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001291 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001292 }
1293
1294 KeyStatusPair Fields[] = {
1295 KeyStatusPair("name", true),
1296 KeyStatusPair("type", true),
1297 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001298 KeyStatusPair("external-contents", false),
1299 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001300 };
1301
Craig Topperac67c052015-11-30 03:11:10 +00001302 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001303
1304 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001305 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001306 std::string ExternalContentsPath;
1307 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001308 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001309 EntryKind Kind;
1310
Eugene Zelenko5a520112018-03-28 22:09:09 +00001311 for (auto &I : *M) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001312 StringRef Key;
1313 // Reuse the buffer for key and value, since we don't look at key after
1314 // parsing value.
1315 SmallString<256> Buffer;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001316 if (!parseScalarString(I.getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001317 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001318
Eugene Zelenko5a520112018-03-28 22:09:09 +00001319 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001320 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001321
1322 StringRef Value;
1323 if (Key == "name") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001324 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001325 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001326
1327 if (FS->UseCanonicalizedPaths) {
1328 SmallString<256> Path(Value);
1329 // Guarantee that old YAML files containing paths with ".." and "."
1330 // are properly canonicalized before read into the VFS.
1331 Path = sys::path::remove_leading_dotslash(Path);
1332 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1333 Name = Path.str();
1334 } else {
1335 Name = Value;
1336 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001337 } else if (Key == "type") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001338 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001339 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001340 if (Value == "file")
1341 Kind = EK_File;
1342 else if (Value == "directory")
1343 Kind = EK_Directory;
1344 else {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001345 error(I.getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001346 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001347 }
1348 } else if (Key == "contents") {
1349 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001350 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001351 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001352 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001353 }
1354 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001355 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001356 if (!Contents) {
1357 // FIXME: this is only for directories, what about files?
Eugene Zelenko5a520112018-03-28 22:09:09 +00001358 error(I.getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001359 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001360 }
1361
Eugene Zelenko5a520112018-03-28 22:09:09 +00001362 for (auto &I : *Contents) {
1363 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001364 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001365 else
Craig Topperf1186c52014-05-08 06:41:40 +00001366 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001367 }
1368 } else if (Key == "external-contents") {
1369 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001370 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001371 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001372 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001373 }
1374 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001375 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001376 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001377
1378 SmallString<256> FullPath;
1379 if (FS->IsRelativeOverlay) {
1380 FullPath = FS->getExternalContentsPrefixDir();
1381 assert(!FullPath.empty() &&
1382 "External contents prefix directory must exist");
1383 llvm::sys::path::append(FullPath, Value);
1384 } else {
1385 FullPath = Value;
1386 }
1387
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001388 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001389 // Guarantee that old YAML files containing paths with ".." and "."
1390 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001391 FullPath = sys::path::remove_leading_dotslash(FullPath);
1392 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001393 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001394 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001395 } else if (Key == "use-external-name") {
1396 bool Val;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001397 if (!parseScalarBool(I.getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001398 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001399 UseExternalName = Val ? RedirectingFileEntry::NK_External
1400 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001401 } else {
1402 llvm_unreachable("key missing from Keys");
1403 }
1404 }
1405
1406 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001407 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001408
1409 // check for missing keys
1410 if (!HasContents) {
1411 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001412 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001413 }
1414 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001415 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001416
Ben Langmuirb59cf672014-02-27 00:25:12 +00001417 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001418 if (Kind == EK_Directory &&
1419 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001420 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001421 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001422 }
1423
Ben Langmuir93853232014-03-05 21:32:20 +00001424 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001425 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001426 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1427 while (Trimmed.size() > RootPathLen &&
1428 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001429 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1430 // Get the last component
1431 StringRef LastComponent = sys::path::filename(Trimmed);
1432
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001433 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001434 switch (Kind) {
1435 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001436 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001437 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001438 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001439 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001440 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001441 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001442 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1443 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001444 break;
1445 }
1446
1447 StringRef Parent = sys::path::parent_path(Trimmed);
1448 if (Parent.empty())
1449 return Result;
1450
1451 // if 'name' contains multiple components, create implicit directory entries
1452 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1453 E = sys::path::rend(Parent);
1454 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001455 std::vector<std::unique_ptr<Entry>> Entries;
1456 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001457 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001458 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001459 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1460 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001461 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001462 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001463 }
1464
1465public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001466 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001467
1468 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001469 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001470 auto *Top = dyn_cast<yaml::MappingNode>(Root);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001471 if (!Top) {
1472 error(Root, "expected mapping node");
1473 return false;
1474 }
1475
1476 KeyStatusPair Fields[] = {
1477 KeyStatusPair("version", true),
1478 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001479 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001480 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001481 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001482 KeyStatusPair("roots", true),
1483 };
1484
Craig Topperac67c052015-11-30 03:11:10 +00001485 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001486 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001487
1488 // Parse configuration and 'roots'
Eugene Zelenko5a520112018-03-28 22:09:09 +00001489 for (auto &I : *Top) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001490 SmallString<10> KeyBuffer;
1491 StringRef Key;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001492 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001493 return false;
1494
Eugene Zelenko5a520112018-03-28 22:09:09 +00001495 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001496 return false;
1497
1498 if (Key == "roots") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001499 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001500 if (!Roots) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001501 error(I.getValue(), "expected array");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001502 return false;
1503 }
1504
Eugene Zelenko5a520112018-03-28 22:09:09 +00001505 for (auto &I : *Roots) {
1506 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001507 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001508 else
1509 return false;
1510 }
1511 } else if (Key == "version") {
1512 StringRef VersionString;
1513 SmallString<4> Storage;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001514 if (!parseScalarString(I.getValue(), VersionString, Storage))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001515 return false;
1516 int Version;
1517 if (VersionString.getAsInteger<int>(10, Version)) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001518 error(I.getValue(), "expected integer");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001519 return false;
1520 }
1521 if (Version < 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001522 error(I.getValue(), "invalid version number");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001523 return false;
1524 }
1525 if (Version != 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001526 error(I.getValue(), "version mismatch, expected 0");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001527 return false;
1528 }
1529 } else if (Key == "case-sensitive") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001530 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001531 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001532 } else if (Key == "overlay-relative") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001533 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001534 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001535 } else if (Key == "use-external-names") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001536 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
Ben Langmuirb59cf672014-02-27 00:25:12 +00001537 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001538 } else if (Key == "ignore-non-existent-contents") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001539 if (!parseScalarBool(I.getValue(), FS->IgnoreNonExistentContents))
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001540 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001541 } else {
1542 llvm_unreachable("key missing from Keys");
1543 }
1544 }
1545
1546 if (Stream.failed())
1547 return false;
1548
1549 if (!checkMissingKeys(Top, Keys))
1550 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001551
1552 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1553 // representation to a proper directory tree so that we can search faster
1554 // inside the VFS.
Eugene Zelenko5a520112018-03-28 22:09:09 +00001555 for (auto &E : RootEntries)
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001556 uniqueOverlayTree(FS, E.get());
1557
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001558 return true;
1559 }
1560};
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001561
Eugene Zelenko5a520112018-03-28 22:09:09 +00001562} // namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001563
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001564RedirectingFileSystem *
1565RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1566 SourceMgr::DiagHandlerTy DiagHandler,
1567 StringRef YAMLFilePath, void *DiagContext,
1568 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001569 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001570 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001571
Ben Langmuir97882e72014-02-24 20:56:37 +00001572 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001573 yaml::document_iterator DI = Stream.begin();
1574 yaml::Node *Root = DI->getRoot();
1575 if (DI == Stream.end() || !Root) {
1576 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001577 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001578 }
1579
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001580 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001581
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001582 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001583 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001584
1585 if (!YAMLFilePath.empty()) {
1586 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1587 // to each 'external-contents' path.
1588 //
1589 // Example:
1590 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1591 // yields:
1592 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1593 //
1594 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1595 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1596 assert(!EC && "Overlay dir final path must be absolute");
1597 (void)EC;
1598 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1599 }
1600
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001601 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001602 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001603
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001604 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001605}
1606
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001607ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001608 SmallString<256> Path;
1609 Path_.toVector(Path);
1610
1611 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001612 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001613 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001614
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001615 // Canonicalize path by removing ".", "..", "./", etc components. This is
1616 // a VFS request, do bot bother about symlinks in the path components
1617 // but canonicalize in order to perform the correct entry search.
1618 if (UseCanonicalizedPaths) {
1619 Path = sys::path::remove_leading_dotslash(Path);
1620 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1621 }
1622
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001623 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001624 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001625
1626 sys::path::const_iterator Start = sys::path::begin(Path);
1627 sys::path::const_iterator End = sys::path::end(Path);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001628 for (const auto &Root : Roots) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001629 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001630 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001631 return Result;
1632 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001633 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001634}
1635
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001636ErrorOr<Entry *>
1637RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1638 sys::path::const_iterator End, Entry *From) {
Nico Weber1865df42018-04-27 19:11:14 +00001639#ifndef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001640 assert(!isTraversalComponent(*Start) &&
1641 !isTraversalComponent(From->getName()) &&
1642 "Paths should not contain traversal components");
1643#else
1644 // FIXME: this is here to support windows, remove it once canonicalized
1645 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001646 if (Start->equals("."))
1647 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001648#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001649
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001650 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001651
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001652 // Forward the search to the next component in case this is an empty one.
1653 if (!FromName.empty()) {
1654 if (CaseSensitive ? !Start->equals(FromName)
1655 : !Start->equals_lower(FromName))
1656 // failure to match
1657 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001658
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001659 ++Start;
1660
1661 if (Start == End) {
1662 // Match!
1663 return From;
1664 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001665 }
1666
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001667 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001668 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001669 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001670
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001671 for (const std::unique_ptr<Entry> &DirEntry :
1672 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1673 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001674 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001675 return Result;
1676 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001677 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001678}
1679
Ben Langmuirf13302e2015-12-10 23:41:39 +00001680static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1681 Status ExternalStatus) {
1682 Status S = ExternalStatus;
1683 if (!UseExternalNames)
1684 S = Status::copyWithNewName(S, Path.str());
1685 S.IsVFSMapped = true;
1686 return S;
1687}
1688
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001689ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001690 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001691 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001692 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001693 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001694 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001695 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1696 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001697 return S;
1698 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001699 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001700 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001701 }
1702}
1703
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001704ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001705 ErrorOr<Entry *> Result = lookupPath(Path);
1706 if (!Result)
1707 return Result.getError();
1708 return status(Path, *Result);
1709}
1710
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001711namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001712
Ben Langmuirf13302e2015-12-10 23:41:39 +00001713/// Provide a file wrapper with an overriden status.
1714class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001715 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001716 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001717
1718public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001719 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001720 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001721
Ben Langmuirf13302e2015-12-10 23:41:39 +00001722 ErrorOr<Status> status() override { return S; }
1723 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Eugene Zelenko5a520112018-03-28 22:09:09 +00001724
Benjamin Kramer737501c2015-10-05 21:20:19 +00001725 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1726 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001727 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1728 IsVolatile);
1729 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001730
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001731 std::error_code close() override { return InnerFile->close(); }
1732};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001733
1734} // namespace
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001735
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001736ErrorOr<std::unique_ptr<File>>
1737RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001738 ErrorOr<Entry *> E = lookupPath(Path);
1739 if (!E)
1740 return E.getError();
1741
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001742 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001743 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001744 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001745
Benjamin Kramera8857962014-10-26 22:44:13 +00001746 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1747 if (!Result)
1748 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001749
Ben Langmuirf13302e2015-12-10 23:41:39 +00001750 auto ExternalStatus = (*Result)->status();
1751 if (!ExternalStatus)
1752 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001753
Ben Langmuirf13302e2015-12-10 23:41:39 +00001754 // FIXME: Update the status with the name and VFSMapped.
1755 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1756 *ExternalStatus);
1757 return std::unique_ptr<File>(
1758 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001759}
1760
1761IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001762vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001763 SourceMgr::DiagHandlerTy DiagHandler,
1764 StringRef YAMLFilePath,
1765 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001766 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001767 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001768 YAMLFilePath, DiagContext,
1769 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001770}
1771
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001772static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1773 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1774 auto Kind = SrcE->getKind();
1775 if (Kind == EK_Directory) {
1776 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1777 assert(DE && "Must be a directory");
1778 for (std::unique_ptr<Entry> &SubEntry :
1779 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1780 Path.push_back(SubEntry->getName());
1781 getVFSEntries(SubEntry.get(), Path, Entries);
1782 Path.pop_back();
1783 }
1784 return;
1785 }
1786
1787 assert(Kind == EK_File && "Must be a EK_File");
1788 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1789 assert(FE && "Must be a file");
1790 SmallString<128> VPath;
1791 for (auto &Comp : Path)
1792 llvm::sys::path::append(VPath, Comp);
1793 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1794}
1795
1796void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1797 SourceMgr::DiagHandlerTy DiagHandler,
1798 StringRef YAMLFilePath,
1799 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1800 void *DiagContext,
1801 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1802 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1803 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1804 std::move(ExternalFS));
1805 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1806 if (!RootE)
1807 return;
1808 SmallVector<StringRef, 8> Components;
1809 Components.push_back("/");
1810 getVFSEntries(*RootE, Components, CollectedEntries);
1811}
1812
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001813UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001814 static std::atomic<unsigned> UID;
1815 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001816 // The following assumes that uint64_t max will never collide with a real
1817 // dev_t value from the OS.
1818 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1819}
Justin Bogner9c785292014-05-20 21:43:27 +00001820
Justin Bogner9c785292014-05-20 21:43:27 +00001821void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1822 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1823 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1824 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1825 Mappings.emplace_back(VirtualPath, RealPath);
1826}
1827
Justin Bogner44fa450342014-05-21 22:46:51 +00001828namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001829
Justin Bogner44fa450342014-05-21 22:46:51 +00001830class JSONWriter {
1831 llvm::raw_ostream &OS;
1832 SmallVector<StringRef, 16> DirStack;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001833
1834 unsigned getDirIndent() { return 4 * DirStack.size(); }
1835 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
Justin Bogner44fa450342014-05-21 22:46:51 +00001836 bool containedIn(StringRef Parent, StringRef Path);
1837 StringRef containedPart(StringRef Parent, StringRef Path);
1838 void startDirectory(StringRef Path);
1839 void endDirectory();
1840 void writeEntry(StringRef VPath, StringRef RPath);
1841
1842public:
1843 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001844
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001845 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1846 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001847 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001848};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001849
1850} // namespace
Justin Bogner9c785292014-05-20 21:43:27 +00001851
Justin Bogner44fa450342014-05-21 22:46:51 +00001852bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001853 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001854
Justin Bogner1c078f22014-05-20 22:12:58 +00001855 // Compare each path component.
1856 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1857 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1858 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1859 if (*IParent != *IChild)
1860 return false;
1861 }
1862 // Have we exhausted the parent path?
1863 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001864}
1865
Justin Bogner44fa450342014-05-21 22:46:51 +00001866StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1867 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001868 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001869 return Path.slice(Parent.size() + 1, StringRef::npos);
1870}
1871
Justin Bogner44fa450342014-05-21 22:46:51 +00001872void JSONWriter::startDirectory(StringRef Path) {
1873 StringRef Name =
1874 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1875 DirStack.push_back(Path);
1876 unsigned Indent = getDirIndent();
1877 OS.indent(Indent) << "{\n";
1878 OS.indent(Indent + 2) << "'type': 'directory',\n";
1879 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1880 OS.indent(Indent + 2) << "'contents': [\n";
1881}
1882
1883void JSONWriter::endDirectory() {
1884 unsigned Indent = getDirIndent();
1885 OS.indent(Indent + 2) << "]\n";
1886 OS.indent(Indent) << "}";
1887
1888 DirStack.pop_back();
1889}
1890
1891void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1892 unsigned Indent = getFileIndent();
1893 OS.indent(Indent) << "{\n";
1894 OS.indent(Indent + 2) << "'type': 'file',\n";
1895 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1896 OS.indent(Indent + 2) << "'external-contents': \""
1897 << llvm::yaml::escape(RPath) << "\"\n";
1898 OS.indent(Indent) << "}";
1899}
1900
1901void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001902 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001903 Optional<bool> IsCaseSensitive,
1904 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001905 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001906 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001907 using namespace llvm::sys;
1908
1909 OS << "{\n"
1910 " 'version': 0,\n";
1911 if (IsCaseSensitive.hasValue())
1912 OS << " 'case-sensitive': '"
1913 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001914 if (UseExternalNames.hasValue())
1915 OS << " 'use-external-names': '"
1916 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001917 bool UseOverlayRelative = false;
1918 if (IsOverlayRelative.hasValue()) {
1919 UseOverlayRelative = IsOverlayRelative.getValue();
1920 OS << " 'overlay-relative': '"
1921 << (UseOverlayRelative ? "true" : "false") << "',\n";
1922 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001923 if (IgnoreNonExistentContents.hasValue())
1924 OS << " 'ignore-non-existent-contents': '"
1925 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001926 OS << " 'roots': [\n";
1927
Justin Bogner73466402014-07-15 01:24:35 +00001928 if (!Entries.empty()) {
1929 const YAMLVFSEntry &Entry = Entries.front();
1930 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001931
1932 StringRef RPath = Entry.RPath;
1933 if (UseOverlayRelative) {
1934 unsigned OverlayDirLen = OverlayDir.size();
1935 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1936 "Overlay dir must be contained in RPath");
1937 RPath = RPath.slice(OverlayDirLen, RPath.size());
1938 }
1939
1940 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001941
Justin Bogner73466402014-07-15 01:24:35 +00001942 for (const auto &Entry : Entries.slice(1)) {
1943 StringRef Dir = path::parent_path(Entry.VPath);
1944 if (Dir == DirStack.back())
1945 OS << ",\n";
1946 else {
1947 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1948 OS << "\n";
1949 endDirectory();
1950 }
1951 OS << ",\n";
1952 startDirectory(Dir);
1953 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001954 StringRef RPath = Entry.RPath;
1955 if (UseOverlayRelative) {
1956 unsigned OverlayDirLen = OverlayDir.size();
1957 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1958 "Overlay dir must be contained in RPath");
1959 RPath = RPath.slice(OverlayDirLen, RPath.size());
1960 }
1961 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001962 }
1963
1964 while (!DirStack.empty()) {
1965 OS << "\n";
1966 endDirectory();
1967 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001968 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001969 }
1970
Justin Bogner73466402014-07-15 01:24:35 +00001971 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001972 << "}\n";
1973}
1974
Justin Bogner9c785292014-05-20 21:43:27 +00001975void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001976 llvm::sort(Mappings.begin(), Mappings.end(),
1977 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001978 return LHS.VPath < RHS.VPath;
1979 });
1980
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001981 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001982 IsOverlayRelative, IgnoreNonExistentContents,
1983 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001984}
Ben Langmuir740812b2014-06-24 19:37:16 +00001985
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001986VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1987 const Twine &_Path, RedirectingFileSystem &FS,
1988 RedirectingDirectoryEntry::iterator Begin,
1989 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001990 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001991 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001992 SmallString<128> PathStr(Dir);
1993 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001994 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001995 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001996 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001997 return;
1998 }
1999 // Skip entries which do not map to a reliable external content.
2000 if (FS.ignoreNonExistentContents() &&
2001 S.getError() == llvm::errc::no_such_file_or_directory) {
2002 ++Current;
2003 continue;
2004 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00002005 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002006 break;
2007 }
Ben Langmuir740812b2014-06-24 19:37:16 +00002008 }
2009}
2010
2011std::error_code VFSFromYamlDirIterImpl::increment() {
2012 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002013 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00002014 SmallString<128> PathStr(Dir);
2015 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00002016 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002017 if (!S) {
2018 // Skip entries which do not map to a reliable external content.
2019 if (FS.ignoreNonExistentContents() &&
2020 S.getError() == llvm::errc::no_such_file_or_directory) {
2021 continue;
2022 } else {
2023 return S.getError();
2024 }
2025 }
Ben Langmuir740812b2014-06-24 19:37:16 +00002026 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002027 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00002028 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002029
2030 if (Current == End)
2031 CurrentEntry = Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +00002032 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00002033}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002034
2035vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
2036 const Twine &Path,
2037 std::error_code &EC)
2038 : FS(&FS_) {
2039 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00002040 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002041 State = std::make_shared<IterState>();
2042 State->push(I);
2043 }
2044}
2045
2046vfs::recursive_directory_iterator &
2047recursive_directory_iterator::increment(std::error_code &EC) {
2048 assert(FS && State && !State->empty() && "incrementing past end");
2049 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
2050 vfs::directory_iterator End;
2051 if (State->top()->isDirectory()) {
2052 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002053 if (I != End) {
2054 State->push(I);
2055 return *this;
2056 }
2057 }
2058
2059 while (!State->empty() && State->top().increment(EC) == End)
2060 State->pop();
2061
2062 if (State->empty())
2063 State.reset(); // end iterator
2064
2065 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002066}