message.h 25.4 KB
Newer Older
1
// Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
Kenton Varda's avatar
Kenton Varda committed
2
// Licensed under the MIT License:
Kenton Varda's avatar
Kenton Varda committed
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// 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:
Kenton Varda's avatar
Kenton Varda committed
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
Kenton Varda's avatar
Kenton Varda committed
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// 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.
Kenton Varda's avatar
Kenton Varda committed
21

Kenton Varda's avatar
Kenton Varda committed
22
#include <kj/common.h>
23
#include <kj/memory.h>
24
#include <kj/mutex.h>
Matthew Maurer's avatar
Matthew Maurer committed
25
#include <kj/debug.h>
26
#include <kj/vector.h>
27
#include "common.h"
28
#include "layout.h"
29
#include "any.h"
Kenton Varda's avatar
Kenton Varda committed
30

31
#pragma once
Kenton Varda's avatar
Kenton Varda committed
32

33
#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
34 35 36
#pragma GCC system_header
#endif

37
namespace capnp {
Kenton Varda's avatar
Kenton Varda committed
38

39
namespace _ {  // private
40 41
  class ReaderArena;
  class BuilderArena;
Kenton Varda's avatar
Kenton Varda committed
42
  struct CloneImpl;
43 44
}

45
class StructSchema;
Kenton Varda's avatar
Kenton Varda committed
46
class Orphanage;
47 48
template <typename T>
class Orphan;
Kenton Varda's avatar
Kenton Varda committed
49

50
// =======================================================================================
Kenton Varda's avatar
Kenton Varda committed
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
struct ReaderOptions {
  // Options controlling how data is read.

  uint64_t traversalLimitInWords = 8 * 1024 * 1024;
  // Limits how many total words of data are allowed to be traversed.  Traversal is counted when
  // a new struct or list builder is obtained, e.g. from a get() accessor.  This means that calling
  // the getter for the same sub-struct multiple times will cause it to be double-counted.  Once
  // the traversal limit is reached, an error will be reported.
  //
  // This limit exists for security reasons.  It is possible for an attacker to construct a message
  // in which multiple pointers point at the same location.  This is technically invalid, but hard
  // to detect.  Using such a message, an attacker could cause a message which is small on the wire
  // to appear much larger when actually traversed, possibly exhausting server resources leading to
  // denial-of-service.
  //
  // It makes sense to set a traversal limit that is much larger than the underlying message.
  // Together with sensible coding practices (e.g. trying to avoid calling sub-object getters
  // multiple times, which is expensive anyway), this should provide adequate protection without
  // inconvenience.
  //
  // The default limit is 64 MiB.  This may or may not be a sensible number for any given use case,
  // but probably at least prevents easy exploitation while also avoiding causing problems in most
  // typical cases.

76
  int nestingLimit = 64;
77 78 79 80 81 82 83 84 85 86 87
  // Limits how deeply-nested a message structure can be, e.g. structs containing other structs or
  // lists of structs.
  //
  // Like the traversal limit, this limit exists for security reasons.  Since it is common to use
  // recursive code to traverse recursive data structures, an attacker could easily cause a stack
  // overflow by sending a very-deeply-nested (or even cyclic) message, without the message even
  // being very large.  The default limit of 64 is probably low enough to prevent any chance of
  // stack overflow, yet high enough that it is never a problem in practice.
};

class MessageReader {
88 89 90 91 92 93 94 95 96 97
  // Abstract interface for an object used to read a Cap'n Proto message.  Subclasses of
  // MessageReader are responsible for reading the raw, flat message content.  Callers should
  // usually call `messageReader.getRoot<MyStructType>()` to get a `MyStructType::Reader`
  // representing the root of the message, then use that to traverse the message content.
  //
  // Some common subclasses of `MessageReader` include `SegmentArrayMessageReader`, whose
  // constructor accepts pointers to the raw data, and `StreamFdMessageReader` (from
  // `serialize.h`), which reads the message from a file descriptor.  One might implement other
  // subclasses to handle things like reading from shared memory segments, mmap()ed files, etc.

Kenton Varda's avatar
Kenton Varda committed
98
public:
99 100 101 102 103
  MessageReader(ReaderOptions options);
  // It is suggested that subclasses take ReaderOptions as a constructor parameter, but give it a
  // default value of "ReaderOptions()".  The base class constructor doesn't have a default value
  // in order to remind subclasses that they really need to give the user a way to provide this.

104
  virtual ~MessageReader() noexcept(false);
Kenton Varda's avatar
Kenton Varda committed
105

106
  virtual kj::ArrayPtr<const word> getSegment(uint id) = 0;
107 108
  // Gets the segment with the given ID, or returns null if no such segment exists. This method
  // will be called at most once for each segment ID.
109 110 111 112
  //
  // The returned array must be aligned properly for the host architecture. This means that on
  // x86/x64, alignment is optional, though recommended for performance, whereas on many other
  // architectures, alignment is required.
113

114 115
  inline const ReaderOptions& getOptions();
  // Get the options passed to the constructor.
116

117 118
  template <typename RootType>
  typename RootType::Reader getRoot();
Kenton Varda's avatar
Kenton Varda committed
119 120
  // Get the root struct of the message, interpreting it as the given struct type.

Kenton Varda's avatar
Kenton Varda committed
121 122 123
  template <typename RootType, typename SchemaType>
  typename RootType::Reader getRoot(SchemaType schema);
  // Dynamically interpret the root struct of the message using the given schema (a StructSchema).
124
  // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
Kenton Varda's avatar
Kenton Varda committed
125
  // use this.
126

Matthew Maurer's avatar
Matthew Maurer committed
127 128 129
  bool isCanonical();
  // Returns whether the message encoded in the reader is in canonical form.

130 131 132
  size_t sizeInWords();
  // Add up the size of all segments.

133 134 135 136 137
private:
  ReaderOptions options;

  // Space in which we can construct a ReaderArena.  We don't use ReaderArena directly here
  // because we don't want clients to have to #include arena.h, which itself includes a bunch of
138
  // other headers.  We don't use a pointer to a ReaderArena because that would require an
139
  // extra malloc on every message which could be expensive when processing small messages.
140
  void* arenaSpace[18 + sizeof(kj::MutexGuarded<void*>) / sizeof(void*)];
141
  bool allocatedArena;
Kenton Varda's avatar
Kenton Varda committed
142

143
  _::ReaderArena* arena() { return reinterpret_cast<_::ReaderArena*>(arenaSpace); }
144
  AnyPointer::Reader getRootInternal();
145
};
146

147
class MessageBuilder {
148 149 150 151 152 153 154 155 156 157 158
  // Abstract interface for an object used to allocate and build a message.  Subclasses of
  // MessageBuilder are responsible for allocating the space in which the message will be written.
  // The most common subclass is `MallocMessageBuilder`, but other subclasses may be used to do
  // tricky things like allocate messages in shared memory or mmap()ed files.
  //
  // Creating a new message ususually means allocating a new MessageBuilder (ideally on the stack)
  // and then calling `messageBuilder.initRoot<MyStructType>()` to get a `MyStructType::Builder`.
  // That, in turn, can be used to fill in the message content.  When done, you can call
  // `messageBuilder.getSegmentsForOutput()` to get a list of flat data arrays containing the
  // message.

159
public:
160
  MessageBuilder();
161
  virtual ~MessageBuilder() noexcept(false);
162
  KJ_DISALLOW_COPY(MessageBuilder);
Kenton Varda's avatar
Kenton Varda committed
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
  struct SegmentInit {
    kj::ArrayPtr<word> space;

    size_t wordsUsed;
    // Number of words in `space` which are used; the rest are free space in which additional
    // objects may be allocated.
  };

  explicit MessageBuilder(kj::ArrayPtr<SegmentInit> segments);
  // Create a MessageBuilder backed by existing memory. This is an advanced interface that most
  // people should not use. THIS METHOD IS INSECURE; see below.
  //
  // This allows a MessageBuilder to be constructed to modify an in-memory message without first
  // making a copy of the content. This is especially useful in conjunction with mmap().
  //
  // The contents of each segment must outlive the MessageBuilder, but the SegmentInit array itself
  // only need outlive the constructor.
  //
  // SECURITY: Do not use this in conjunction with untrusted data. This constructor assumes that
  //   the input message is valid. This constructor is designed to be used with data you control,
  //   e.g. an mmap'd file which is owned and accessed by only one program. When reading data you
  //   do not trust, you *must* load it into a Reader and then copy into a Builder as a means of
  //   validating the content.
  //
  // WARNING: It is NOT safe to initialize a MessageBuilder in this way from memory that is
  //   currently in use by another MessageBuilder or MessageReader. Other readers/builders will
  //   not observe changes to the segment sizes nor newly-allocated segments caused by allocating
  //   new objects in this message.

193
  virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) = 0;
194 195 196 197 198
  // Allocates an array of at least the given number of zero'd words, throwing an exception or
  // crashing if this is not possible.  It is expected that this method will usually return more
  // space than requested, and the caller should use that extra space as much as possible before
  // allocating more.  The returned space remains valid at least until the MessageBuilder is
  // destroyed.
199
  //
200 201 202
  // allocateSegment() is responsible for zeroing the memory before returning. This is required
  // because otherwise the Cap'n Proto implementation would have to zero the memory anyway, and
  // many allocators are able to provide already-zero'd memory more efficiently.
203 204 205 206
  //
  // The returned array must be aligned properly for the host architecture. This means that on
  // x86/x64, alignment is optional, though recommended for performance, whereas on many other
  // architectures, alignment is required.
207 208 209

  template <typename RootType>
  typename RootType::Builder initRoot();
Kenton Varda's avatar
Kenton Varda committed
210 211
  // Initialize the root struct of the message as the given struct type.

212 213 214 215
  template <typename Reader>
  void setRoot(Reader&& value);
  // Set the root struct to a deep copy of the given struct.

216 217
  template <typename RootType>
  typename RootType::Builder getRoot();
Kenton Varda's avatar
Kenton Varda committed
218 219
  // Get the root struct of the message, interpreting it as the given struct type.

Kenton Varda's avatar
Kenton Varda committed
220 221 222
  template <typename RootType, typename SchemaType>
  typename RootType::Builder getRoot(SchemaType schema);
  // Dynamically interpret the root struct of the message using the given schema (a StructSchema).
223
  // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
Kenton Varda's avatar
Kenton Varda committed
224 225
  // use this.

Kenton Varda's avatar
Kenton Varda committed
226 227 228
  template <typename RootType, typename SchemaType>
  typename RootType::Builder initRoot(SchemaType schema);
  // Dynamically init the root struct of the message using the given schema (a StructSchema).
229
  // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
Kenton Varda's avatar
Kenton Varda committed
230
  // use this.
231

232 233 234 235
  template <typename T>
  void adoptRoot(Orphan<T>&& orphan);
  // Like setRoot() but adopts the orphan without copying.

236
  kj::ArrayPtr<const kj::ArrayPtr<const word>> getSegmentsForOutput();
237 238
  // Get the raw data that makes up the message.

239 240
  Orphanage getOrphanage();

Matthew Maurer's avatar
Matthew Maurer committed
241 242 243
  bool isCanonical();
  // Check whether the message builder is in canonical form

244 245 246
  size_t sizeInWords();
  // Add up the allocated space from all segments.

247
private:
248
  void* arenaSpace[22];
249 250 251 252
  // Space in which we can construct a BuilderArena.  We don't use BuilderArena directly here
  // because we don't want clients to have to #include arena.h, which itself includes a bunch of
  // big STL headers.  We don't use a pointer to a BuilderArena because that would require an
  // extra malloc on every message which could be expensive when processing small messages.
253

254
  bool allocatedArena = false;
255 256 257 258 259
  // We have to initialize the arena lazily because when we do so we want to allocate the root
  // pointer immediately, and this will allocate a segment, which requires a virtual function
  // call on the MessageBuilder.  We can't do such a call in the constructor since the subclass
  // isn't constructed yet.  This is kind of annoying because it means that getOrphanage() is
  // not thread-safe, but that shouldn't be a huge deal...
260

261
  _::BuilderArena* arena() { return reinterpret_cast<_::BuilderArena*>(arenaSpace); }
262
  _::SegmentBuilder* getRootSegment();
263
  AnyPointer::Builder getRootInternal();
264 265 266 267

  kj::Own<_::CapTableBuilder> releaseBuiltinCapTable();
  // Hack for clone() to extract the cap table.

Kenton Varda's avatar
Kenton Varda committed
268 269 270 271
  friend struct _::CloneImpl;
  // We can't declare clone() as a friend directly because old versions of GCC incorrectly demand
  // that the first declaration (even if it is a friend declaration) specify the default type args,
  // whereas correct compilers do not permit default type args to be specified on a friend decl.
Kenton Varda's avatar
Kenton Varda committed
272 273
};

274
template <typename RootType>
275
typename RootType::Reader readMessageUnchecked(const word* data);
276 277 278 279 280
// IF THE INPUT IS INVALID, THIS MAY CRASH, CORRUPT MEMORY, CREATE A SECURITY HOLE IN YOUR APP,
// MURDER YOUR FIRST-BORN CHILD, AND/OR BRING ABOUT ETERNAL DAMNATION ON ALL OF HUMANITY.  DO NOT
// USE UNLESS YOU UNDERSTAND THE CONSEQUENCES.
//
// Given a pointer to a known-valid message located in a single contiguous memory segment,
281 282 283
// returns a reader for that message.  No bounds-checking will be done while traversing this
// message.  Use this only if you have already verified that all pointers are valid and in-bounds,
// and there are no far pointers in the message.
284
//
285 286 287 288 289
// To create a message that can be passed to this function, build a message using a MallocAllocator
// whose preferred segment size is larger than the message size.  This guarantees that the message
// will be allocated as a single segment, meaning getSegmentsForOutput() returns a single word
// array.  That word array is your message; you may pass a pointer to its first word into
// readMessageUnchecked() to read the message.
290 291 292 293 294
//
// This can be particularly handy for embedding messages in generated code:  you can
// embed the raw bytes (using AlignedData) then make a Reader for it using this.  This is the way
// default values are embedded in code generated by the Cap'n Proto compiler.  E.g., if you have
// a message MyMessage, you can read its default value like so:
295 296 297
//    MyMessage::Reader reader = Message<MyMessage>::readMessageUnchecked(MyMessage::DEFAULT.words);
//
// To sanitize a message from an untrusted source such that it can be safely passed to
298 299 300
// readMessageUnchecked(), use copyToUnchecked().

template <typename Reader>
301
void copyToUnchecked(Reader&& reader, kj::ArrayPtr<word> uncheckedBuffer);
302 303
// Copy the content of the given reader into the given buffer, such that it can safely be passed to
// readMessageUnchecked().  The buffer's size must be exactly reader.totalSizeInWords() + 1,
304
// otherwise an exception will be thrown.  The buffer must be zero'd before calling.
Kenton Varda's avatar
Kenton Varda committed
305

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
template <typename RootType>
typename RootType::Reader readDataStruct(kj::ArrayPtr<const word> data);
// Interprets the given data as a single, data-only struct. Only primitive fields (booleans,
// numbers, and enums) will be readable; all pointers will be null. This is useful if you want
// to use Cap'n Proto as a language/platform-neutral way to pack some bits.
//
// The input is a word array rather than a byte array to enforce alignment. If you have a byte
// array which you know is word-aligned (or if your platform supports unaligned reads and you don't
// mind the performance penalty), then you can use `reinterpret_cast` to convert a byte array into
// a word array:
//
//     kj::arrayPtr(reinterpret_cast<const word*>(bytes.begin()),
//                  reinterpret_cast<const word*>(bytes.end()))

template <typename BuilderType>
typename kj::ArrayPtr<const word> writeDataStruct(BuilderType builder);
// Given a struct builder, get the underlying data section as a word array, suitable for passing
// to `readDataStruct()`.
//
// Note that you may call `.toBytes()` on the returned value to convert to `ArrayPtr<const byte>`.

327
template <typename Type>
Kenton Varda's avatar
Kenton Varda committed
328
static typename Type::Reader defaultValue();
329 330 331 332
// Get a default instance of the given struct or list type.
//
// TODO(cleanup):  Find a better home for this function?

333 334 335 336
template <typename Reader, typename = FromReader<Reader>>
kj::Own<kj::Decay<Reader>> clone(Reader&& reader);
// Make a deep copy of the given Reader on the heap, producing an owned pointer.

337
// =======================================================================================
Kenton Varda's avatar
Kenton Varda committed
338

339 340 341 342
class SegmentArrayMessageReader: public MessageReader {
  // A simple MessageReader that reads from an array of word arrays representing all segments.
  // In particular you can read directly from the output of MessageBuilder::getSegmentsForOutput()
  // (although it would probably make more sense to call builder.getRoot().asReader() in that case).
Kenton Varda's avatar
Kenton Varda committed
343

344
public:
345
  SegmentArrayMessageReader(kj::ArrayPtr<const kj::ArrayPtr<const word>> segments,
346 347 348
                            ReaderOptions options = ReaderOptions());
  // Creates a message pointing at the given segment array, without taking ownership of the
  // segments.  All arrays passed in must remain valid until the MessageReader is destroyed.
Kenton Varda's avatar
Kenton Varda committed
349

350
  KJ_DISALLOW_COPY(SegmentArrayMessageReader);
351
  ~SegmentArrayMessageReader() noexcept(false);
352

353
  virtual kj::ArrayPtr<const word> getSegment(uint id) override;
354

355
private:
356
  kj::ArrayPtr<const kj::ArrayPtr<const word>> segments;
357
};
358

359
enum class AllocationStrategy: uint8_t {
360 361 362 363 364 365 366 367 368 369 370 371 372 373
  FIXED_SIZE,
  // The builder will prefer to allocate the same amount of space for each segment with no
  // heuristic growth.  It will still allocate larger segments when the preferred size is too small
  // for some single object.  This mode is generally not recommended, but can be particularly useful
  // for testing in order to force a message to allocate a predictable number of segments.  Note
  // that you can force every single object in the message to be located in a separate segment by
  // using this mode with firstSegmentWords = 0.

  GROW_HEURISTICALLY
  // The builder will heuristically decide how much space to allocate for each segment.  Each
  // allocated segment will be progressively larger than the previous segments on the assumption
  // that message sizes are exponentially distributed.  The total number of segments that will be
  // allocated for a message of size n is O(log n).
};
Kenton Varda's avatar
Kenton Varda committed
374

375 376
constexpr uint SUGGESTED_FIRST_SEGMENT_WORDS = 1024;
constexpr AllocationStrategy SUGGESTED_ALLOCATION_STRATEGY = AllocationStrategy::GROW_HEURISTICALLY;
Kenton Varda's avatar
Kenton Varda committed
377

378 379 380 381
class MallocMessageBuilder: public MessageBuilder {
  // A simple MessageBuilder that uses malloc() (actually, calloc()) to allocate segments.  This
  // implementation should be reasonable for any case that doesn't require writing the message to
  // a specific location in memory.
382

383
public:
Kenton Varda's avatar
Kenton Varda committed
384
  explicit MallocMessageBuilder(uint firstSegmentWords = SUGGESTED_FIRST_SEGMENT_WORDS,
385 386 387 388 389 390 391 392 393 394 395 396 397
      AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY);
  // Creates a BuilderContext which allocates at least the given number of words for the first
  // segment, and then uses the given strategy to decide how much to allocate for subsequent
  // segments.  When choosing a value for firstSegmentWords, consider that:
  // 1) Reading and writing messages gets slower when multiple segments are involved, so it's good
  //    if most messages fit in a single segment.
  // 2) Unused bytes will not be written to the wire, so generally it is not a big deal to allocate
  //    more space than you need.  It only becomes problematic if you are allocating many messages
  //    in parallel and thus use lots of memory, or if you allocate so much extra space that just
  //    zeroing it out becomes a bottleneck.
  // The defaults have been chosen to be reasonable for most people, so don't change them unless you
  // have reason to believe you need to.

398
  explicit MallocMessageBuilder(kj::ArrayPtr<word> firstSegment,
399 400 401 402
      AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY);
  // This version always returns the given array for the first segment, and then proceeds with the
  // allocation strategy.  This is useful for optimization when building lots of small messages in
  // a tight loop:  you can reuse the space for the first segment.
Kenton Varda's avatar
Kenton Varda committed
403 404 405
  //
  // firstSegment MUST be zero-initialized.  MallocMessageBuilder's destructor will write new zeros
  // over any space that was used so that it can be reused.
406

407
  KJ_DISALLOW_COPY(MallocMessageBuilder);
408
  virtual ~MallocMessageBuilder() noexcept(false);
409

410
  virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) override;
411 412 413 414 415

private:
  uint nextSize;
  AllocationStrategy allocationStrategy;

416
  bool ownFirstSegment;
417 418
  bool returnedFirstSegment;

419
  void* firstSegment;
420
  kj::Vector<void*> moreSegments;
Kenton Varda's avatar
Kenton Varda committed
421 422
};

423
class FlatMessageBuilder: public MessageBuilder {
424 425 426 427 428 429 430 431 432 433 434
  // THIS IS NOT THE CLASS YOU'RE LOOKING FOR.
  //
  // If you want to write a message into already-existing scratch space, use `MallocMessageBuilder`
  // and pass the scratch space to its constructor.  It will then only fall back to malloc() if
  // the scratch space is not large enough.
  //
  // Do NOT use this class unless you really know what you're doing.  This class is problematic
  // because it requires advance knowledge of the size of your message, which is usually impossible
  // to determine without actually building the message.  The class was created primarily to
  // implement `copyToUnchecked()`, which itself exists only to support other internal parts of
  // the Cap'n Proto implementation.
435 436

public:
437 438
  explicit FlatMessageBuilder(kj::ArrayPtr<word> array);
  KJ_DISALLOW_COPY(FlatMessageBuilder);
439
  virtual ~FlatMessageBuilder() noexcept(false);
440 441 442 443

  void requireFilled();
  // Throws an exception if the flat array is not exactly full.

444
  virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) override;
445 446

private:
447
  kj::ArrayPtr<word> array;
448 449 450
  bool allocated;
};

Kenton Varda's avatar
Kenton Varda committed
451
// =======================================================================================
452
// implementation details
Kenton Varda's avatar
Kenton Varda committed
453

454 455
inline const ReaderOptions& MessageReader::getOptions() {
  return options;
Kenton Varda's avatar
Kenton Varda committed
456 457
}

458
template <typename RootType>
459
inline typename RootType::Reader MessageReader::getRoot() {
Kenton Varda's avatar
Kenton Varda committed
460
  return getRootInternal().getAs<RootType>();
Kenton Varda's avatar
Kenton Varda committed
461 462
}

463
template <typename RootType>
464
inline typename RootType::Builder MessageBuilder::initRoot() {
Kenton Varda's avatar
Kenton Varda committed
465
  return getRootInternal().initAs<RootType>();
Kenton Varda's avatar
Kenton Varda committed
466 467
}

468 469
template <typename Reader>
inline void MessageBuilder::setRoot(Reader&& value) {
Kenton Varda's avatar
Kenton Varda committed
470
  getRootInternal().setAs<FromReader<Reader>>(value);
471 472
}

473
template <typename RootType>
474
inline typename RootType::Builder MessageBuilder::getRoot() {
Kenton Varda's avatar
Kenton Varda committed
475
  return getRootInternal().getAs<RootType>();
Kenton Varda's avatar
Kenton Varda committed
476 477
}

478 479
template <typename T>
void MessageBuilder::adoptRoot(Orphan<T>&& orphan) {
Kenton Varda's avatar
Kenton Varda committed
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
  return getRootInternal().adopt(kj::mv(orphan));
}

template <typename RootType, typename SchemaType>
typename RootType::Reader MessageReader::getRoot(SchemaType schema) {
  return getRootInternal().getAs<RootType>(schema);
}

template <typename RootType, typename SchemaType>
typename RootType::Builder MessageBuilder::getRoot(SchemaType schema) {
  return getRootInternal().getAs<RootType>(schema);
}

template <typename RootType, typename SchemaType>
typename RootType::Builder MessageBuilder::initRoot(SchemaType schema) {
  return getRootInternal().initAs<RootType>(schema);
496 497
}

498
template <typename RootType>
499
typename RootType::Reader readMessageUnchecked(const word* data) {
500
  return AnyPointer::Reader(_::PointerReader::getRootUnchecked(data)).getAs<RootType>();
501 502
}

503
template <typename Reader>
504
void copyToUnchecked(Reader&& reader, kj::ArrayPtr<word> uncheckedBuffer) {
505
  FlatMessageBuilder builder(uncheckedBuffer);
Kenton Varda's avatar
Kenton Varda committed
506
  builder.setRoot(kj::fwd<Reader>(reader));
507 508 509
  builder.requireFilled();
}

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
template <typename RootType>
typename RootType::Reader readDataStruct(kj::ArrayPtr<const word> data) {
  return typename RootType::Reader(_::StructReader(data));
}

template <typename BuilderType>
typename kj::ArrayPtr<const word> writeDataStruct(BuilderType builder) {
  auto bytes = _::PointerHelpers<FromBuilder<BuilderType>>::getInternalBuilder(kj::mv(builder))
      .getDataSectionAsBlob();
  return kj::arrayPtr(reinterpret_cast<word*>(bytes.begin()),
                      reinterpret_cast<word*>(bytes.end()));
}

template <typename Type>
static typename Type::Reader defaultValue() {
  return typename Type::Reader(_::StructReader());
}

Kenton Varda's avatar
Kenton Varda committed
528 529 530 531 532 533 534 535
namespace _ {
  struct CloneImpl {
    static inline kj::Own<_::CapTableBuilder> releaseBuiltinCapTable(MessageBuilder& message) {
      return message.releaseBuiltinCapTable();
    }
  };
};

536 537 538 539 540 541 542 543 544 545 546 547 548
template <typename Reader, typename>
kj::Own<kj::Decay<Reader>> clone(Reader&& reader) {
  auto size = reader.totalSize();
  auto buffer = kj::heapArray<capnp::word>(size.wordCount + 1);
  memset(buffer.asBytes().begin(), 0, buffer.asBytes().size());
  if (size.capCount == 0) {
    copyToUnchecked(reader, buffer);
    auto result = readMessageUnchecked<FromReader<Reader>>(buffer.begin());
    return kj::attachVal(result, kj::mv(buffer));
  } else {
    FlatMessageBuilder builder(buffer);
    builder.setRoot(kj::fwd<Reader>(reader));
    builder.requireFilled();
Kenton Varda's avatar
Kenton Varda committed
549
    auto capTable = _::CloneImpl::releaseBuiltinCapTable(builder);
550 551 552 553 554
    AnyPointer::Reader raw(_::PointerReader::getRootUnchecked(buffer.begin()).imbue(capTable));
    return kj::attachVal(raw.getAs<FromReader<Reader>>(), kj::mv(buffer), kj::mv(capTable));
  }
}

555 556 557 558 559
template <typename T>
kj::Array<word> canonicalize(T&& reader) {
    return _::PointerHelpers<FromReader<T>>::getInternalReader(reader).canonicalize();
}

560
}  // namespace capnp