cannam@148
|
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
|
cannam@148
|
2 // Licensed under the MIT License:
|
cannam@148
|
3 //
|
cannam@148
|
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
|
cannam@148
|
5 // of this software and associated documentation files (the "Software"), to deal
|
cannam@148
|
6 // in the Software without restriction, including without limitation the rights
|
cannam@148
|
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
cannam@148
|
8 // copies of the Software, and to permit persons to whom the Software is
|
cannam@148
|
9 // furnished to do so, subject to the following conditions:
|
cannam@148
|
10 //
|
cannam@148
|
11 // The above copyright notice and this permission notice shall be included in
|
cannam@148
|
12 // all copies or substantial portions of the Software.
|
cannam@148
|
13 //
|
cannam@148
|
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
cannam@148
|
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
cannam@148
|
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
cannam@148
|
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
cannam@148
|
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
cannam@148
|
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
cannam@148
|
20 // THE SOFTWARE.
|
cannam@148
|
21
|
cannam@148
|
22 #ifndef CAPNP_ARENA_H_
|
cannam@148
|
23 #define CAPNP_ARENA_H_
|
cannam@148
|
24
|
cannam@148
|
25 #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
|
cannam@148
|
26 #pragma GCC system_header
|
cannam@148
|
27 #endif
|
cannam@148
|
28
|
cannam@148
|
29 #ifndef CAPNP_PRIVATE
|
cannam@148
|
30 #error "This header is only meant to be included by Cap'n Proto's own source code."
|
cannam@148
|
31 #endif
|
cannam@148
|
32
|
cannam@148
|
33 #include <kj/common.h>
|
cannam@148
|
34 #include <kj/mutex.h>
|
cannam@148
|
35 #include <kj/exception.h>
|
cannam@148
|
36 #include <kj/vector.h>
|
cannam@148
|
37 #include <kj/units.h>
|
cannam@148
|
38 #include "common.h"
|
cannam@148
|
39 #include "message.h"
|
cannam@148
|
40 #include "layout.h"
|
cannam@148
|
41 #include <unordered_map>
|
cannam@148
|
42
|
cannam@148
|
43 #if !CAPNP_LITE
|
cannam@148
|
44 #include "capability.h"
|
cannam@148
|
45 #endif // !CAPNP_LITE
|
cannam@148
|
46
|
cannam@148
|
47 namespace capnp {
|
cannam@148
|
48
|
cannam@148
|
49 #if !CAPNP_LITE
|
cannam@148
|
50 class ClientHook;
|
cannam@148
|
51 #endif // !CAPNP_LITE
|
cannam@148
|
52
|
cannam@148
|
53 namespace _ { // private
|
cannam@148
|
54
|
cannam@148
|
55 class SegmentReader;
|
cannam@148
|
56 class SegmentBuilder;
|
cannam@148
|
57 class Arena;
|
cannam@148
|
58 class BuilderArena;
|
cannam@148
|
59 class ReadLimiter;
|
cannam@148
|
60
|
cannam@148
|
61 class Segment;
|
cannam@148
|
62 typedef kj::Id<uint32_t, Segment> SegmentId;
|
cannam@148
|
63
|
cannam@148
|
64 class ReadLimiter {
|
cannam@148
|
65 // Used to keep track of how much data has been processed from a message, and cut off further
|
cannam@148
|
66 // processing if and when a particular limit is reached. This is primarily intended to guard
|
cannam@148
|
67 // against maliciously-crafted messages which contain cycles or overlapping structures. Cycles
|
cannam@148
|
68 // and overlapping are not permitted by the Cap'n Proto format because in many cases they could
|
cannam@148
|
69 // be used to craft a deceptively small message which could consume excessive server resources to
|
cannam@148
|
70 // process, perhaps even sending it into an infinite loop. Actually detecting overlaps would be
|
cannam@148
|
71 // time-consuming, so instead we just keep track of how many words worth of data structures the
|
cannam@148
|
72 // receiver has actually dereferenced and error out if this gets too high.
|
cannam@148
|
73 //
|
cannam@148
|
74 // This counting takes place as you call getters (for non-primitive values) on the message
|
cannam@148
|
75 // readers. If you call the same getter twice, the data it returns may be double-counted. This
|
cannam@148
|
76 // should not be a big deal in most cases -- just set the read limit high enough that it will
|
cannam@148
|
77 // only trigger in unreasonable cases.
|
cannam@148
|
78 //
|
cannam@148
|
79 // This class is "safe" to use from multiple threads for its intended use case. Threads may
|
cannam@148
|
80 // overwrite each others' changes to the counter, but this is OK because it only means that the
|
cannam@148
|
81 // limit is enforced a bit less strictly -- it will still kick in eventually.
|
cannam@148
|
82
|
cannam@148
|
83 public:
|
cannam@148
|
84 inline explicit ReadLimiter(); // No limit.
|
cannam@148
|
85 inline explicit ReadLimiter(WordCount64 limit); // Limit to the given number of words.
|
cannam@148
|
86
|
cannam@148
|
87 inline void reset(WordCount64 limit);
|
cannam@148
|
88
|
cannam@148
|
89 KJ_ALWAYS_INLINE(bool canRead(WordCount64 amount, Arena* arena));
|
cannam@148
|
90
|
cannam@148
|
91 void unread(WordCount64 amount);
|
cannam@148
|
92 // Adds back some words to the limit. Useful when the caller knows they are double-reading
|
cannam@148
|
93 // some data.
|
cannam@148
|
94
|
cannam@148
|
95 private:
|
cannam@148
|
96 volatile uint64_t limit;
|
cannam@148
|
97 // Current limit, decremented each time catRead() is called. Volatile because multiple threads
|
cannam@148
|
98 // could be trying to modify it at once. (This is not real thread-safety, but good enough for
|
cannam@148
|
99 // the purpose of this class. See class comment.)
|
cannam@148
|
100
|
cannam@148
|
101 KJ_DISALLOW_COPY(ReadLimiter);
|
cannam@148
|
102 };
|
cannam@148
|
103
|
cannam@148
|
104 #if !CAPNP_LITE
|
cannam@148
|
105 class BrokenCapFactory {
|
cannam@148
|
106 // Callback for constructing broken caps. We use this so that we can avoid arena.c++ having a
|
cannam@148
|
107 // link-time dependency on capability code that lives in libcapnp-rpc.
|
cannam@148
|
108
|
cannam@148
|
109 public:
|
cannam@148
|
110 virtual kj::Own<ClientHook> newBrokenCap(kj::StringPtr description) = 0;
|
cannam@148
|
111 virtual kj::Own<ClientHook> newNullCap() = 0;
|
cannam@148
|
112 };
|
cannam@148
|
113 #endif // !CAPNP_LITE
|
cannam@148
|
114
|
cannam@148
|
115 class SegmentReader {
|
cannam@148
|
116 public:
|
cannam@148
|
117 inline SegmentReader(Arena* arena, SegmentId id, const word* ptr, SegmentWordCount size,
|
cannam@148
|
118 ReadLimiter* readLimiter);
|
cannam@148
|
119
|
cannam@148
|
120 KJ_ALWAYS_INLINE(const word* checkOffset(const word* from, ptrdiff_t offset));
|
cannam@148
|
121 // Adds the given offset to the given pointer, checks that it is still within the bounds of the
|
cannam@148
|
122 // segment, then returns it. Note that the "end" pointer of the segment (which technically points
|
cannam@148
|
123 // to the word after the last in the segment) is considered in-bounds for this purpose, so you
|
cannam@148
|
124 // can't necessarily dereference it. You must call checkObject() next to check that the object
|
cannam@148
|
125 // you want to read is entirely in-bounds.
|
cannam@148
|
126 //
|
cannam@148
|
127 // If `from + offset` is out-of-range, this returns a pointer to the end of the segment. Thus,
|
cannam@148
|
128 // any non-zero-sized object will fail `checkObject()`. We do this instead of throwing to save
|
cannam@148
|
129 // some code footprint.
|
cannam@148
|
130
|
cannam@148
|
131 KJ_ALWAYS_INLINE(bool checkObject(const word* start, WordCountN<31> size));
|
cannam@148
|
132 // Assuming that `start` is in-bounds for this segment (probably checked using `checkOffset()`),
|
cannam@148
|
133 // check that `start + size` is also in-bounds, and hence the whole area in-between is valid.
|
cannam@148
|
134
|
cannam@148
|
135 KJ_ALWAYS_INLINE(bool amplifiedRead(WordCount virtualAmount));
|
cannam@148
|
136 // Indicates that the reader should pretend that `virtualAmount` additional data was read even
|
cannam@148
|
137 // though no actual pointer was traversed. This is used e.g. when reading a struct list pointer
|
cannam@148
|
138 // where the element sizes are zero -- the sender could set the list size arbitrarily high and
|
cannam@148
|
139 // cause the receiver to iterate over this list even though the message itself is small, so we
|
cannam@148
|
140 // need to defend against DoS attacks based on this.
|
cannam@148
|
141
|
cannam@148
|
142 inline Arena* getArena();
|
cannam@148
|
143 inline SegmentId getSegmentId();
|
cannam@148
|
144
|
cannam@148
|
145 inline const word* getStartPtr();
|
cannam@148
|
146 inline SegmentWordCount getOffsetTo(const word* ptr);
|
cannam@148
|
147 inline SegmentWordCount getSize();
|
cannam@148
|
148
|
cannam@148
|
149 inline kj::ArrayPtr<const word> getArray();
|
cannam@148
|
150
|
cannam@148
|
151 inline void unread(WordCount64 amount);
|
cannam@148
|
152 // Add back some words to the ReadLimiter.
|
cannam@148
|
153
|
cannam@148
|
154 private:
|
cannam@148
|
155 Arena* arena;
|
cannam@148
|
156 SegmentId id;
|
cannam@148
|
157 kj::ArrayPtr<const word> ptr; // size guaranteed to fit in SEGMENT_WORD_COUNT_BITS bits
|
cannam@148
|
158 ReadLimiter* readLimiter;
|
cannam@148
|
159
|
cannam@148
|
160 KJ_DISALLOW_COPY(SegmentReader);
|
cannam@148
|
161
|
cannam@148
|
162 friend class SegmentBuilder;
|
cannam@148
|
163
|
cannam@148
|
164 static void abortCheckObjectFault();
|
cannam@148
|
165 // Called in debug mode in cases that would segfault in opt mode. (Should be impossible!)
|
cannam@148
|
166 };
|
cannam@148
|
167
|
cannam@148
|
168 class SegmentBuilder: public SegmentReader {
|
cannam@148
|
169 public:
|
cannam@148
|
170 inline SegmentBuilder(BuilderArena* arena, SegmentId id, word* ptr, SegmentWordCount size,
|
cannam@148
|
171 ReadLimiter* readLimiter, SegmentWordCount wordsUsed = ZERO * WORDS);
|
cannam@148
|
172 inline SegmentBuilder(BuilderArena* arena, SegmentId id, const word* ptr, SegmentWordCount size,
|
cannam@148
|
173 ReadLimiter* readLimiter);
|
cannam@148
|
174 inline SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr),
|
cannam@148
|
175 ReadLimiter* readLimiter);
|
cannam@148
|
176
|
cannam@148
|
177 KJ_ALWAYS_INLINE(word* allocate(SegmentWordCount amount));
|
cannam@148
|
178
|
cannam@148
|
179 KJ_ALWAYS_INLINE(void checkWritable());
|
cannam@148
|
180 // Throw an exception if the segment is read-only (meaning it is a reference to external data).
|
cannam@148
|
181
|
cannam@148
|
182 KJ_ALWAYS_INLINE(word* getPtrUnchecked(SegmentWordCount offset));
|
cannam@148
|
183 // Get a writable pointer into the segment. Throws an exception if the segment is read-only (i.e.
|
cannam@148
|
184 // a reference to external immutable data).
|
cannam@148
|
185
|
cannam@148
|
186 inline BuilderArena* getArena();
|
cannam@148
|
187
|
cannam@148
|
188 inline kj::ArrayPtr<const word> currentlyAllocated();
|
cannam@148
|
189
|
cannam@148
|
190 inline void reset();
|
cannam@148
|
191
|
cannam@148
|
192 inline bool isWritable() { return !readOnly; }
|
cannam@148
|
193
|
cannam@148
|
194 inline void tryTruncate(word* from, word* to);
|
cannam@148
|
195 // If `from` points just past the current end of the segment, then move the end back to `to`.
|
cannam@148
|
196 // Otherwise, do nothing.
|
cannam@148
|
197
|
cannam@148
|
198 inline bool tryExtend(word* from, word* to);
|
cannam@148
|
199 // If `from` points just past the current end of the segment, and `to` is within the segment
|
cannam@148
|
200 // boundaries, then move the end up to `to` and return true. Otherwise, do nothing and return
|
cannam@148
|
201 // false.
|
cannam@148
|
202
|
cannam@148
|
203 private:
|
cannam@148
|
204 word* pos;
|
cannam@148
|
205 // Pointer to a pointer to the current end point of the segment, i.e. the location where the
|
cannam@148
|
206 // next object should be allocated.
|
cannam@148
|
207
|
cannam@148
|
208 bool readOnly;
|
cannam@148
|
209
|
cannam@148
|
210 void throwNotWritable();
|
cannam@148
|
211
|
cannam@148
|
212 KJ_DISALLOW_COPY(SegmentBuilder);
|
cannam@148
|
213 };
|
cannam@148
|
214
|
cannam@148
|
215 class Arena {
|
cannam@148
|
216 public:
|
cannam@148
|
217 virtual ~Arena() noexcept(false);
|
cannam@148
|
218
|
cannam@148
|
219 virtual SegmentReader* tryGetSegment(SegmentId id) = 0;
|
cannam@148
|
220 // Gets the segment with the given ID, or return nullptr if no such segment exists.
|
cannam@148
|
221
|
cannam@148
|
222 virtual void reportReadLimitReached() = 0;
|
cannam@148
|
223 // Called to report that the read limit has been reached. See ReadLimiter, below. This invokes
|
cannam@148
|
224 // the VALIDATE_INPUT() macro which may throw an exception; if it returns normally, the caller
|
cannam@148
|
225 // will need to continue with default values.
|
cannam@148
|
226 };
|
cannam@148
|
227
|
cannam@148
|
228 class ReaderArena final: public Arena {
|
cannam@148
|
229 public:
|
cannam@148
|
230 explicit ReaderArena(MessageReader* message);
|
cannam@148
|
231 ~ReaderArena() noexcept(false);
|
cannam@148
|
232 KJ_DISALLOW_COPY(ReaderArena);
|
cannam@148
|
233
|
cannam@148
|
234 // implements Arena ------------------------------------------------
|
cannam@148
|
235 SegmentReader* tryGetSegment(SegmentId id) override;
|
cannam@148
|
236 void reportReadLimitReached() override;
|
cannam@148
|
237
|
cannam@148
|
238 private:
|
cannam@148
|
239 MessageReader* message;
|
cannam@148
|
240 ReadLimiter readLimiter;
|
cannam@148
|
241
|
cannam@148
|
242 // Optimize for single-segment messages so that small messages are handled quickly.
|
cannam@148
|
243 SegmentReader segment0;
|
cannam@148
|
244
|
cannam@148
|
245 typedef std::unordered_map<uint, kj::Own<SegmentReader>> SegmentMap;
|
cannam@148
|
246 kj::MutexGuarded<kj::Maybe<kj::Own<SegmentMap>>> moreSegments;
|
cannam@148
|
247 // We need to mutex-guard the segment map because we lazily initialize segments when they are
|
cannam@148
|
248 // first requested, but a Reader is allowed to be used concurrently in multiple threads. Luckily
|
cannam@148
|
249 // this only applies to large messages.
|
cannam@148
|
250 //
|
cannam@148
|
251 // TODO(perf): Thread-local thing instead? Some kind of lockless map? Or do sharing of data
|
cannam@148
|
252 // in a different way, where you have to construct a new MessageReader in each thread (but
|
cannam@148
|
253 // possibly backed by the same data)?
|
cannam@148
|
254
|
cannam@148
|
255 ReaderArena(MessageReader* message, kj::ArrayPtr<const word> firstSegment);
|
cannam@148
|
256 ReaderArena(MessageReader* message, const word* firstSegment, SegmentWordCount firstSegmentSize);
|
cannam@148
|
257 };
|
cannam@148
|
258
|
cannam@148
|
259 class BuilderArena final: public Arena {
|
cannam@148
|
260 // A BuilderArena that does not allow the injection of capabilities.
|
cannam@148
|
261
|
cannam@148
|
262 public:
|
cannam@148
|
263 explicit BuilderArena(MessageBuilder* message);
|
cannam@148
|
264 BuilderArena(MessageBuilder* message, kj::ArrayPtr<MessageBuilder::SegmentInit> segments);
|
cannam@148
|
265 ~BuilderArena() noexcept(false);
|
cannam@148
|
266 KJ_DISALLOW_COPY(BuilderArena);
|
cannam@148
|
267
|
cannam@148
|
268 inline SegmentBuilder* getRootSegment() { return &segment0; }
|
cannam@148
|
269
|
cannam@148
|
270 kj::ArrayPtr<const kj::ArrayPtr<const word>> getSegmentsForOutput();
|
cannam@148
|
271 // Get an array of all the segments, suitable for writing out. This only returns the allocated
|
cannam@148
|
272 // portion of each segment, whereas tryGetSegment() returns something that includes
|
cannam@148
|
273 // not-yet-allocated space.
|
cannam@148
|
274
|
cannam@148
|
275 inline CapTableBuilder* getLocalCapTable() {
|
cannam@148
|
276 // Return a CapTableBuilder that merely implements local loopback. That is, you can set
|
cannam@148
|
277 // capabilities, then read the same capabilities back, but there is no intent ever to transmit
|
cannam@148
|
278 // these capabilities. A MessageBuilder that isn't imbued with some other CapTable uses this
|
cannam@148
|
279 // by default.
|
cannam@148
|
280 //
|
cannam@148
|
281 // TODO(cleanup): It's sort of a hack that this exists. In theory, perhaps, unimbued
|
cannam@148
|
282 // MessageBuilders should throw exceptions on any attempt to access capability fields, like
|
cannam@148
|
283 // unimbued MessageReaders do. However, lots of code exists which uses MallocMessageBuilder
|
cannam@148
|
284 // as a temporary holder for data to be copied in and out (without being serialized), and it
|
cannam@148
|
285 // is expected that such data can include capabilities, which is admittedly reasonable.
|
cannam@148
|
286 // Therefore, all MessageBuilders must have a cap table by default. Arguably we should
|
cannam@148
|
287 // deprecate this usage and instead define a new helper type for this exact purpose.
|
cannam@148
|
288
|
cannam@148
|
289 return &localCapTable;
|
cannam@148
|
290 }
|
cannam@148
|
291
|
cannam@148
|
292 SegmentBuilder* getSegment(SegmentId id);
|
cannam@148
|
293 // Get the segment with the given id. Crashes or throws an exception if no such segment exists.
|
cannam@148
|
294
|
cannam@148
|
295 struct AllocateResult {
|
cannam@148
|
296 SegmentBuilder* segment;
|
cannam@148
|
297 word* words;
|
cannam@148
|
298 };
|
cannam@148
|
299
|
cannam@148
|
300 AllocateResult allocate(SegmentWordCount amount);
|
cannam@148
|
301 // Find a segment with at least the given amount of space available and allocate the space.
|
cannam@148
|
302 // Note that allocating directly from a particular segment is much faster, but allocating from
|
cannam@148
|
303 // the arena is guaranteed to succeed. Therefore callers should try to allocate from a specific
|
cannam@148
|
304 // segment first if there is one, then fall back to the arena.
|
cannam@148
|
305
|
cannam@148
|
306 SegmentBuilder* addExternalSegment(kj::ArrayPtr<const word> content);
|
cannam@148
|
307 // Add a new segment to the arena which points to some existing memory region. The segment is
|
cannam@148
|
308 // assumed to be completley full; the arena will never allocate from it. In fact, the segment
|
cannam@148
|
309 // is considered read-only. Any attempt to get a Builder pointing into this segment will throw
|
cannam@148
|
310 // an exception. Readers are allowed, however.
|
cannam@148
|
311 //
|
cannam@148
|
312 // This can be used to inject some external data into a message without a copy, e.g. embedding a
|
cannam@148
|
313 // large mmap'd file into a message as `Data` without forcing that data to actually be read in
|
cannam@148
|
314 // from disk (until the message itself is written out). `Orphanage` provides the public API for
|
cannam@148
|
315 // this feature.
|
cannam@148
|
316
|
cannam@148
|
317 // implements Arena ------------------------------------------------
|
cannam@148
|
318 SegmentReader* tryGetSegment(SegmentId id) override;
|
cannam@148
|
319 void reportReadLimitReached() override;
|
cannam@148
|
320
|
cannam@148
|
321 private:
|
cannam@148
|
322 MessageBuilder* message;
|
cannam@148
|
323 ReadLimiter dummyLimiter;
|
cannam@148
|
324
|
cannam@148
|
325 class LocalCapTable: public CapTableBuilder {
|
cannam@148
|
326 #if !CAPNP_LITE
|
cannam@148
|
327 public:
|
cannam@148
|
328 kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) override;
|
cannam@148
|
329 uint injectCap(kj::Own<ClientHook>&& cap) override;
|
cannam@148
|
330 void dropCap(uint index) override;
|
cannam@148
|
331
|
cannam@148
|
332 private:
|
cannam@148
|
333 kj::Vector<kj::Maybe<kj::Own<ClientHook>>> capTable;
|
cannam@148
|
334 #endif // ! CAPNP_LITE
|
cannam@148
|
335 };
|
cannam@148
|
336
|
cannam@148
|
337 LocalCapTable localCapTable;
|
cannam@148
|
338
|
cannam@148
|
339 SegmentBuilder segment0;
|
cannam@148
|
340 kj::ArrayPtr<const word> segment0ForOutput;
|
cannam@148
|
341
|
cannam@148
|
342 struct MultiSegmentState {
|
cannam@148
|
343 kj::Vector<kj::Own<SegmentBuilder>> builders;
|
cannam@148
|
344 kj::Vector<kj::ArrayPtr<const word>> forOutput;
|
cannam@148
|
345 };
|
cannam@148
|
346 kj::Maybe<kj::Own<MultiSegmentState>> moreSegments;
|
cannam@148
|
347
|
cannam@148
|
348 SegmentBuilder* segmentWithSpace = nullptr;
|
cannam@148
|
349 // When allocating, look for space in this segment first before resorting to allocating a new
|
cannam@148
|
350 // segment. This is not necessarily the last segment because addExternalSegment() may add a
|
cannam@148
|
351 // segment that is already-full, in which case we don't update this pointer.
|
cannam@148
|
352
|
cannam@148
|
353 template <typename T> // Can be `word` or `const word`.
|
cannam@148
|
354 SegmentBuilder* addSegmentInternal(kj::ArrayPtr<T> content);
|
cannam@148
|
355 };
|
cannam@148
|
356
|
cannam@148
|
357 // =======================================================================================
|
cannam@148
|
358
|
cannam@148
|
359 inline ReadLimiter::ReadLimiter()
|
cannam@148
|
360 : limit(kj::maxValue) {}
|
cannam@148
|
361
|
cannam@148
|
362 inline ReadLimiter::ReadLimiter(WordCount64 limit): limit(unbound(limit / WORDS)) {}
|
cannam@148
|
363
|
cannam@148
|
364 inline void ReadLimiter::reset(WordCount64 limit) { this->limit = unbound(limit / WORDS); }
|
cannam@148
|
365
|
cannam@148
|
366 inline bool ReadLimiter::canRead(WordCount64 amount, Arena* arena) {
|
cannam@148
|
367 // Be careful not to store an underflowed value into `limit`, even if multiple threads are
|
cannam@148
|
368 // decrementing it.
|
cannam@148
|
369 uint64_t current = limit;
|
cannam@148
|
370 if (KJ_UNLIKELY(unbound(amount / WORDS) > current)) {
|
cannam@148
|
371 arena->reportReadLimitReached();
|
cannam@148
|
372 return false;
|
cannam@148
|
373 } else {
|
cannam@148
|
374 limit = current - unbound(amount / WORDS);
|
cannam@148
|
375 return true;
|
cannam@148
|
376 }
|
cannam@148
|
377 }
|
cannam@148
|
378
|
cannam@148
|
379 // -------------------------------------------------------------------
|
cannam@148
|
380
|
cannam@148
|
381 inline SegmentReader::SegmentReader(Arena* arena, SegmentId id, const word* ptr,
|
cannam@148
|
382 SegmentWordCount size, ReadLimiter* readLimiter)
|
cannam@148
|
383 : arena(arena), id(id), ptr(kj::arrayPtr(ptr, unbound(size / WORDS))),
|
cannam@148
|
384 readLimiter(readLimiter) {}
|
cannam@148
|
385
|
cannam@148
|
386 inline const word* SegmentReader::checkOffset(const word* from, ptrdiff_t offset) {
|
cannam@148
|
387 ptrdiff_t min = ptr.begin() - from;
|
cannam@148
|
388 ptrdiff_t max = ptr.end() - from;
|
cannam@148
|
389 if (offset >= min && offset <= max) {
|
cannam@148
|
390 return from + offset;
|
cannam@148
|
391 } else {
|
cannam@148
|
392 return ptr.end();
|
cannam@148
|
393 }
|
cannam@148
|
394 }
|
cannam@148
|
395
|
cannam@148
|
396 inline bool SegmentReader::checkObject(const word* start, WordCountN<31> size) {
|
cannam@148
|
397 auto startOffset = intervalLength(ptr.begin(), start, MAX_SEGMENT_WORDS);
|
cannam@148
|
398 #ifdef KJ_DEBUG
|
cannam@148
|
399 if (startOffset > bounded(ptr.size()) * WORDS) {
|
cannam@148
|
400 abortCheckObjectFault();
|
cannam@148
|
401 }
|
cannam@148
|
402 #endif
|
cannam@148
|
403 return startOffset + size <= bounded(ptr.size()) * WORDS &&
|
cannam@148
|
404 readLimiter->canRead(size, arena);
|
cannam@148
|
405 }
|
cannam@148
|
406
|
cannam@148
|
407 inline bool SegmentReader::amplifiedRead(WordCount virtualAmount) {
|
cannam@148
|
408 return readLimiter->canRead(virtualAmount, arena);
|
cannam@148
|
409 }
|
cannam@148
|
410
|
cannam@148
|
411 inline Arena* SegmentReader::getArena() { return arena; }
|
cannam@148
|
412 inline SegmentId SegmentReader::getSegmentId() { return id; }
|
cannam@148
|
413 inline const word* SegmentReader::getStartPtr() { return ptr.begin(); }
|
cannam@148
|
414 inline SegmentWordCount SegmentReader::getOffsetTo(const word* ptr) {
|
cannam@148
|
415 KJ_IREQUIRE(this->ptr.begin() <= ptr && ptr <= this->ptr.end());
|
cannam@148
|
416 return intervalLength(this->ptr.begin(), ptr, MAX_SEGMENT_WORDS);
|
cannam@148
|
417 }
|
cannam@148
|
418 inline SegmentWordCount SegmentReader::getSize() {
|
cannam@148
|
419 return assumeBits<SEGMENT_WORD_COUNT_BITS>(ptr.size()) * WORDS;
|
cannam@148
|
420 }
|
cannam@148
|
421 inline kj::ArrayPtr<const word> SegmentReader::getArray() { return ptr; }
|
cannam@148
|
422 inline void SegmentReader::unread(WordCount64 amount) { readLimiter->unread(amount); }
|
cannam@148
|
423
|
cannam@148
|
424 // -------------------------------------------------------------------
|
cannam@148
|
425
|
cannam@148
|
426 inline SegmentBuilder::SegmentBuilder(
|
cannam@148
|
427 BuilderArena* arena, SegmentId id, word* ptr, SegmentWordCount size,
|
cannam@148
|
428 ReadLimiter* readLimiter, SegmentWordCount wordsUsed)
|
cannam@148
|
429 : SegmentReader(arena, id, ptr, size, readLimiter),
|
cannam@148
|
430 pos(ptr + wordsUsed), readOnly(false) {}
|
cannam@148
|
431 inline SegmentBuilder::SegmentBuilder(
|
cannam@148
|
432 BuilderArena* arena, SegmentId id, const word* ptr, SegmentWordCount size,
|
cannam@148
|
433 ReadLimiter* readLimiter)
|
cannam@148
|
434 : SegmentReader(arena, id, ptr, size, readLimiter),
|
cannam@148
|
435 // const_cast is safe here because the member won't ever be dereferenced because it appears
|
cannam@148
|
436 // to point to the end of the segment anyway.
|
cannam@148
|
437 pos(const_cast<word*>(ptr + size)), readOnly(true) {}
|
cannam@148
|
438 inline SegmentBuilder::SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr),
|
cannam@148
|
439 ReadLimiter* readLimiter)
|
cannam@148
|
440 : SegmentReader(arena, id, nullptr, ZERO * WORDS, readLimiter),
|
cannam@148
|
441 pos(nullptr), readOnly(false) {}
|
cannam@148
|
442
|
cannam@148
|
443 inline word* SegmentBuilder::allocate(SegmentWordCount amount) {
|
cannam@148
|
444 if (intervalLength(pos, ptr.end(), MAX_SEGMENT_WORDS) < amount) {
|
cannam@148
|
445 // Not enough space in the segment for this allocation.
|
cannam@148
|
446 return nullptr;
|
cannam@148
|
447 } else {
|
cannam@148
|
448 // Success.
|
cannam@148
|
449 word* result = pos;
|
cannam@148
|
450 pos = pos + amount;
|
cannam@148
|
451 return result;
|
cannam@148
|
452 }
|
cannam@148
|
453 }
|
cannam@148
|
454
|
cannam@148
|
455 inline void SegmentBuilder::checkWritable() {
|
cannam@148
|
456 if (KJ_UNLIKELY(readOnly)) throwNotWritable();
|
cannam@148
|
457 }
|
cannam@148
|
458
|
cannam@148
|
459 inline word* SegmentBuilder::getPtrUnchecked(SegmentWordCount offset) {
|
cannam@148
|
460 return const_cast<word*>(ptr.begin() + offset);
|
cannam@148
|
461 }
|
cannam@148
|
462
|
cannam@148
|
463 inline BuilderArena* SegmentBuilder::getArena() {
|
cannam@148
|
464 // Down-cast safe because SegmentBuilder's constructor always initializes its SegmentReader base
|
cannam@148
|
465 // class with an Arena pointer that actually points to a BuilderArena.
|
cannam@148
|
466 return static_cast<BuilderArena*>(arena);
|
cannam@148
|
467 }
|
cannam@148
|
468
|
cannam@148
|
469 inline kj::ArrayPtr<const word> SegmentBuilder::currentlyAllocated() {
|
cannam@148
|
470 return kj::arrayPtr(ptr.begin(), pos - ptr.begin());
|
cannam@148
|
471 }
|
cannam@148
|
472
|
cannam@148
|
473 inline void SegmentBuilder::reset() {
|
cannam@148
|
474 word* start = getPtrUnchecked(ZERO * WORDS);
|
cannam@148
|
475 memset(start, 0, (pos - start) * sizeof(word));
|
cannam@148
|
476 pos = start;
|
cannam@148
|
477 }
|
cannam@148
|
478
|
cannam@148
|
479 inline void SegmentBuilder::tryTruncate(word* from, word* to) {
|
cannam@148
|
480 if (pos == from) pos = to;
|
cannam@148
|
481 }
|
cannam@148
|
482
|
cannam@148
|
483 inline bool SegmentBuilder::tryExtend(word* from, word* to) {
|
cannam@148
|
484 // Careful about overflow.
|
cannam@148
|
485 if (pos == from && to <= ptr.end() && to >= from) {
|
cannam@148
|
486 pos = to;
|
cannam@148
|
487 return true;
|
cannam@148
|
488 } else {
|
cannam@148
|
489 return false;
|
cannam@148
|
490 }
|
cannam@148
|
491 }
|
cannam@148
|
492
|
cannam@148
|
493 } // namespace _ (private)
|
cannam@148
|
494 } // namespace capnp
|
cannam@148
|
495
|
cannam@148
|
496 #endif // CAPNP_ARENA_H_
|