1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
|
// Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#define CAPNP_PRIVATE
#include "message.h"
#include <kj/debug.h>
#include "arena.h"
#include "orphan.h"
#include <stdlib.h>
#include <errno.h>
namespace capnp {
namespace {
class DummyCapTableReader: public _::CapTableReader {
public:
kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) override {
#if CAPNP_LITE
KJ_UNIMPLEMENTED("no cap tables in lite mode");
#else
return kj::none;
#endif
}
};
static KJ_CONSTEXPR(const) DummyCapTableReader dummyCapTableReader = DummyCapTableReader();
} // namespace
MessageReader::MessageReader(ReaderOptions options): options(options), allocatedArena(false) {}
MessageReader::~MessageReader() noexcept(false) {
if (allocatedArena) {
arena()->~ReaderArena();
}
}
bool MessageReader::isCanonical() {
if (!allocatedArena) {
static_assert(sizeof(_::ReaderArena) <= sizeof(arenaSpace),
"arenaSpace is too small to hold a ReaderArena. Please increase it. This will break "
"ABI compatibility.");
kj::ctor(*arena(), this);
allocatedArena = true;
}
_::SegmentReader *segment = arena()->tryGetSegment(_::SegmentId(0));
if (segment == nullptr) {
// The message has no segments
return false;
}
if (arena()->tryGetSegment(_::SegmentId(1))) {
// The message has more than one segment
return false;
}
const word* readHead = segment->getStartPtr() + 1;
bool rootIsCanonical = _::PointerReader::getRoot(segment, nullptr,
segment->getStartPtr(),
this->getOptions().nestingLimit)
.isCanonical(&readHead);
bool allWordsConsumed = segment->getOffsetTo(readHead) == segment->getSize();
return rootIsCanonical && allWordsConsumed;
}
size_t MessageReader::sizeInWords() {
return arena()->sizeInWords();
}
AnyPointer::Reader MessageReader::getRootInternal() {
if (!allocatedArena) {
static_assert(sizeof(_::ReaderArena) <= sizeof(arenaSpace),
"arenaSpace is too small to hold a ReaderArena. Please increase it. This will break "
"ABI compatibility.");
kj::ctor(*arena(), this);
allocatedArena = true;
}
_::SegmentReader* segment = arena()->tryGetSegment(_::SegmentId(0));
KJ_REQUIRE(segment != nullptr &&
segment->checkObject(segment->getStartPtr(), ONE * WORDS),
"Message did not contain a root pointer.");
// const_cast here is safe because dummyCapTableReader has no state.
return AnyPointer::Reader(_::PointerReader::getRoot(
segment, const_cast<DummyCapTableReader*>(&dummyCapTableReader),
segment->getStartPtr(), options.nestingLimit));
}
// -------------------------------------------------------------------
MessageBuilder::MessageBuilder(): allocatedArena(false) {}
MessageBuilder::~MessageBuilder() noexcept(false) {
if (allocatedArena) {
kj::dtor(*arena());
}
}
MessageBuilder::MessageBuilder(kj::ArrayPtr<SegmentInit> segments)
: allocatedArena(false) {
kj::ctor(*arena(), this, segments);
allocatedArena = true;
}
_::SegmentBuilder* MessageBuilder::getRootSegment() {
if (allocatedArena) {
return arena()->getSegment(_::SegmentId(0));
} else {
static_assert(sizeof(_::BuilderArena) <= sizeof(arenaSpace),
"arenaSpace is too small to hold a BuilderArena. Please increase it.");
kj::ctor(*arena(), this);
allocatedArena = true;
auto allocation = arena()->allocate(POINTER_SIZE_IN_WORDS);
KJ_ASSERT(allocation.segment->getSegmentId() == _::SegmentId(0),
"First allocated word of new arena was not in segment ID 0.");
KJ_ASSERT(allocation.words == allocation.segment->getPtrUnchecked(ZERO * WORDS),
"First allocated word of new arena was not the first word in its segment.");
return allocation.segment;
}
}
AnyPointer::Builder MessageBuilder::getRootInternal() {
_::SegmentBuilder* rootSegment = getRootSegment();
return AnyPointer::Builder(_::PointerBuilder::getRoot(
rootSegment, arena()->getLocalCapTable(), rootSegment->getPtrUnchecked(ZERO * WORDS)));
}
kj::ArrayPtr<const kj::ArrayPtr<const word>> MessageBuilder::getSegmentsForOutput() {
if (allocatedArena) {
return arena()->getSegmentsForOutput();
} else {
return nullptr;
}
}
Orphanage MessageBuilder::getOrphanage() {
// We must ensure that the arena and root pointer have been allocated before the Orphanage
// can be used.
if (!allocatedArena) getRootSegment();
return Orphanage(arena(), arena()->getLocalCapTable());
}
bool MessageBuilder::isCanonical() {
_::SegmentReader *segment = getRootSegment();
if (segment == nullptr) {
// The message has no segments
return false;
}
if (arena()->tryGetSegment(_::SegmentId(1))) {
// The message has more than one segment
return false;
}
const word* readHead = segment->getStartPtr() + 1;
return _::PointerReader::getRoot(segment, nullptr, segment->getStartPtr(), kj::maxValue)
.isCanonical(&readHead);
}
size_t MessageBuilder::sizeInWords() {
return arena()->sizeInWords();
}
kj::Own<_::CapTableBuilder> MessageBuilder::releaseBuiltinCapTable() {
return arena()->releaseLocalCapTable();
}
// =======================================================================================
SegmentArrayMessageReader::SegmentArrayMessageReader(
kj::ArrayPtr<const kj::ArrayPtr<const word>> segments, ReaderOptions options)
: MessageReader(options), segments(segments) {}
SegmentArrayMessageReader::~SegmentArrayMessageReader() noexcept(false) {}
kj::ArrayPtr<const word> SegmentArrayMessageReader::getSegment(uint id) {
if (id < segments.size()) {
return segments[id];
} else {
return nullptr;
}
}
// -------------------------------------------------------------------
MallocMessageBuilder::MallocMessageBuilder(
uint firstSegmentWords, AllocationStrategy allocationStrategy)
: nextSize(firstSegmentWords), allocationStrategy(allocationStrategy),
ownFirstSegment(true), returnedFirstSegment(false), firstSegment(nullptr) {}
MallocMessageBuilder::MallocMessageBuilder(
kj::ArrayPtr<word> firstSegment, AllocationStrategy allocationStrategy)
: nextSize(firstSegment.size()), allocationStrategy(allocationStrategy),
ownFirstSegment(false), returnedFirstSegment(false), firstSegment(firstSegment.begin()) {
KJ_REQUIRE(firstSegment.size() > 0, "First segment size must be non-zero.");
// Checking just the first word should catch most cases of failing to zero the segment.
KJ_REQUIRE(*reinterpret_cast<uint64_t*>(firstSegment.begin()) == 0,
"First segment must be zeroed.");
}
MallocMessageBuilder::~MallocMessageBuilder() noexcept(false) {
if (returnedFirstSegment) {
if (ownFirstSegment) {
free(firstSegment);
} else {
// Must zero first segment.
// Both getSegmentsForOutput() and the assertion may throw; if so, skip zeroing.
kj::logExceptionsIfUnwinding([&]() {
kj::ArrayPtr<const kj::ArrayPtr<const word>> segments = getSegmentsForOutput();
if (segments.size() > 0) {
KJ_ASSERT(segments[0].begin() == firstSegment,
"First segment in getSegmentsForOutput() is not the first segment allocated?");
kj::asBytes(static_cast<word*>(firstSegment), segments[0].size()).fill(0);
}
});
}
for (word* ptr: moreSegments) {
free(ptr);
}
}
}
kj::ArrayPtr<word> MallocMessageBuilder::allocateSegment(uint minimumSize) {
KJ_REQUIRE(bounded(minimumSize) * WORDS <= MAX_SEGMENT_WORDS,
"MallocMessageBuilder asked to allocate segment above maximum serializable size.");
KJ_ASSERT(bounded(nextSize) * WORDS <= MAX_SEGMENT_WORDS,
"MallocMessageBuilder nextSize out of bounds.");
if (!returnedFirstSegment && !ownFirstSegment) {
kj::ArrayPtr<word> result = kj::arrayPtr(firstSegment, nextSize);
if (result.size() >= minimumSize) {
returnedFirstSegment = true;
return result;
}
// If the provided first segment wasn't big enough, we discard it and proceed to allocate
// our own. This never happens in practice since minimumSize is always 1 for the first
// segment.
ownFirstSegment = true;
}
uint size = kj::max(minimumSize, nextSize);
word* result = reinterpret_cast<word*>(calloc(size, sizeof(word)));
if (result == nullptr) {
KJ_FAIL_SYSCALL("calloc(size, sizeof(word))", ENOMEM, size);
}
if (!returnedFirstSegment) {
firstSegment = result;
returnedFirstSegment = true;
// After the first segment, we want nextSize to equal the total size allocated so far.
if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) nextSize = size;
} else {
moreSegments.add(result);
if (allocationStrategy == AllocationStrategy::GROW_HEURISTICALLY) {
// set nextSize = min(nextSize+size, MAX_SEGMENT_WORDS)
// while protecting against possible overflow of (nextSize+size)
nextSize = (size <= unbound(MAX_SEGMENT_WORDS / WORDS) - nextSize)
? nextSize + size : unbound(MAX_SEGMENT_WORDS / WORDS);
}
}
return kj::arrayPtr(result, size);
}
// -------------------------------------------------------------------
FlatMessageBuilder::FlatMessageBuilder(kj::ArrayPtr<word> array): array(array), allocated(false) {}
FlatMessageBuilder::~FlatMessageBuilder() noexcept(false) {}
void FlatMessageBuilder::requireFilled() {
KJ_REQUIRE(getSegmentsForOutput()[0].end() == array.end(),
"FlatMessageBuilder's buffer was too large.");
}
kj::ArrayPtr<word> FlatMessageBuilder::allocateSegment(uint minimumSize) {
KJ_REQUIRE(!allocated, "FlatMessageBuilder's buffer was not large enough.");
allocated = true;
return array;
}
} // namespace capnp
|