layout.c++ 107 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
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:
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.
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.
21

Kenton Varda's avatar
Kenton Varda committed
22
#define CAPNP_PRIVATE
23
#include "layout.h"
Kenton Varda's avatar
Kenton Varda committed
24
#include <kj/debug.h>
25
#include "arena.h"
26
#include "capability.h"
27
#include <string.h>
28
#include <stdlib.h>
29

30
namespace capnp {
31
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
32

33 34 35 36 37
static BrokenCapFactory* brokenCapFactory = nullptr;
// Horrible hack:  We need to be able to construct broken caps without any capability context,
// but we can't have a link-time dependency on libcapnp-rpc.

void setGlobalBrokenCapFactoryForLayoutCpp(BrokenCapFactory& factory) {
38 39
  // Called from capability.c++ when the capability API is used, to make sure that layout.c++
  // is ready for it.  May be called multiple times but always with the same value.
40 41 42
  __atomic_store_n(&brokenCapFactory, &factory, __ATOMIC_RELAXED);
}

43 44
// =======================================================================================

45 46
struct WirePointer {
  // A pointer, in exactly the format in which it appears on the wire.
47 48

  // Copying and moving is not allowed because the offset would become wrong.
49 50 51 52
  WirePointer(const WirePointer& other) = delete;
  WirePointer(WirePointer&& other) = delete;
  WirePointer& operator=(const WirePointer& other) = delete;
  WirePointer& operator=(WirePointer&& other) = delete;
53

54
  // -----------------------------------------------------------------
55
  // Common part of all pointers:  kind + offset
56 57 58
  //
  // Actually this is not terribly common.  The "offset" could actually be different things
  // depending on the context:
59 60
  // - For a regular (e.g. struct/list) pointer, a signed word offset from the word immediately
  //   following the pointer pointer.  (The off-by-one means the offset is more often zero, saving
61
  //   bytes on the wire when packed.)
62
  // - For an inline composite list tag (not really a pointer, but structured similarly), an
63
  //   element count.
64
  // - For a FAR pointer, an unsigned offset into the target segment.
65
  // - For a FAR landing pad, zero indicates that the target value immediately follows the pad while
66
  //   1 indicates that the pad is followed by another FAR pointer that actually points at the
67 68 69
  //   value.

  enum Kind {
70
    STRUCT = 0,
71 72
    // Reference points at / describes a struct.

73
    LIST = 1,
74 75 76 77 78 79
    // Reference points at / describes a list.

    FAR = 2,
    // Reference is a "far pointer", which points at data located in a different segment.  The
    // eventual target is one of the other kinds.

80 81 82
    OTHER = 3
    // Reference has type "other".  If the next 30 bits are all zero (i.e. the lower 32 bits contain
    // only the kind OTHER) then the pointer is a capability.  All other values are reserved.
83 84
  };

85 86
  WireValue<uint32_t> offsetAndKind;

87
  KJ_ALWAYS_INLINE(Kind kind() const) {
88 89
    return static_cast<Kind>(offsetAndKind.get() & 3);
  }
90 91 92 93 94 95
  KJ_ALWAYS_INLINE(bool isPositional() const) {
    return (offsetAndKind.get() & 2) == 0;  // match STRUCT and LIST but not FAR or OTHER
  }
  KJ_ALWAYS_INLINE(bool isCapability() const) {
    return offsetAndKind.get() == OTHER;
  }
96

97
  KJ_ALWAYS_INLINE(word* target()) {
98
    return reinterpret_cast<word*>(this) + 1 + (static_cast<int32_t>(offsetAndKind.get()) >> 2);
99
  }
100
  KJ_ALWAYS_INLINE(const word* target() const) {
101 102
    return reinterpret_cast<const word*>(this) + 1 +
        (static_cast<int32_t>(offsetAndKind.get()) >> 2);
103
  }
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  KJ_ALWAYS_INLINE(void setKindAndTarget(Kind kind, word* target, SegmentBuilder* segment)) {
    // Check that the target is really in the same segment, otherwise subtracting pointers is
    // undefined behavior.  As it turns out, it's undefined behavior that actually produces
    // unexpected results in a real-world situation that actually happened:  At one time,
    // OrphanBuilder's "tag" (a WirePointer) was allowed to be initialized as if it lived in
    // a particular segment when in fact it does not.  On 32-bit systems, where words might
    // only be 32-bit aligned, it's possible that the difference between `this` and `target` is
    // not a whole number of words.  But clang optimizes:
    //     (target - (word*)this - 1) << 2
    // to:
    //     (((ptrdiff_t)target - (ptrdiff_t)this - 8) >> 1)
    // So now when the pointers are not aligned the same, we can end up corrupting the bottom
    // two bits, where `kind` is stored.  For example, this turns a struct into a far pointer.
    // Ouch!
    KJ_DREQUIRE(segment->containsInterval(
        reinterpret_cast<word*>(this), reinterpret_cast<word*>(this + 1)));
    KJ_DREQUIRE(segment->containsInterval(target, target));
121
    offsetAndKind.set(((target - reinterpret_cast<word*>(this) - 1) << 2) | kind);
122
  }
123
  KJ_ALWAYS_INLINE(void setKindWithZeroOffset(Kind kind)) {
124 125
    offsetAndKind.set(kind);
  }
126 127 128 129 130 131 132 133 134 135
  KJ_ALWAYS_INLINE(void setKindAndTargetForEmptyStruct()) {
    // This pointer points at an empty struct.  Assuming the WirePointer itself is in-bounds, we
    // can set the target to point either at the WirePointer itself or immediately after it.  The
    // latter would cause the WirePointer to be "null" (since for an empty struct the upper 32
    // bits are going to be zero).  So we set an offset of -1, as if the struct were allocated
    // immediately before this pointer, to distinguish it from null.
    offsetAndKind.set(0xfffffffc);
  }
  KJ_ALWAYS_INLINE(void setKindForOrphan(Kind kind)) {
    // OrphanBuilder contains a WirePointer, but since it isn't located in a segment, it should
136 137 138 139
    // not have a valid offset (unless it is a FAR or OTHER pointer).  We set its offset to -1
    // because setting it to zero would mean a pointer to an empty struct would appear to be a null
    // pointer.
    KJ_DREQUIRE(isPositional());
140 141
    offsetAndKind.set(kind | 0xfffffffc);
  }
142

143
  KJ_ALWAYS_INLINE(ElementCount inlineCompositeListElementCount() const) {
144 145
    return (offsetAndKind.get() >> 2) * ELEMENTS;
  }
146
  KJ_ALWAYS_INLINE(void setKindAndInlineCompositeListElementCount(
147 148 149 150
      Kind kind, ElementCount elementCount)) {
    offsetAndKind.set(((elementCount / ELEMENTS) << 2) | kind);
  }

151
  KJ_ALWAYS_INLINE(WordCount farPositionInSegment() const) {
152
    KJ_DREQUIRE(kind() == FAR,
153
        "positionInSegment() should only be called on FAR pointers.");
154
    return (offsetAndKind.get() >> 3) * WORDS;
155
  }
156
  KJ_ALWAYS_INLINE(bool isDoubleFar() const) {
157
    KJ_DREQUIRE(kind() == FAR,
158
        "isDoubleFar() should only be called on FAR pointers.");
159
    return (offsetAndKind.get() >> 2) & 1;
160
  }
161
  KJ_ALWAYS_INLINE(void setFar(bool isDoubleFar, WordCount pos)) {
162 163
    offsetAndKind.set(((pos / WORDS) << 3) | (static_cast<uint32_t>(isDoubleFar) << 2) |
                      static_cast<uint32_t>(Kind::FAR));
164
  }
165 166 167 168
  KJ_ALWAYS_INLINE(void setCap(uint index)) {
    offsetAndKind.set(static_cast<uint32_t>(Kind::OTHER));
    capRef.index.set(index);
  }
169 170

  // -----------------------------------------------------------------
171
  // Part of pointer that depends on the kind.
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
  // Note:  Originally StructRef, ListRef, and FarRef were unnamed types, but this somehow
  //   tickled a bug in GCC:
  //     http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58192
  struct StructRef {
    WireValue<WordCount16> dataSize;
    WireValue<WirePointerCount16> ptrCount;

    inline WordCount wordSize() const {
      return dataSize.get() + ptrCount.get() * WORDS_PER_POINTER;
    }

    KJ_ALWAYS_INLINE(void set(WordCount ds, WirePointerCount rc)) {
      dataSize.set(ds);
      ptrCount.set(rc);
    }
    KJ_ALWAYS_INLINE(void set(StructSize size)) {
      dataSize.set(size.data);
      ptrCount.set(size.pointers);
    }
  };

  struct ListRef {
    WireValue<uint32_t> elementSizeAndCount;

    KJ_ALWAYS_INLINE(FieldSize elementSize() const) {
      return static_cast<FieldSize>(elementSizeAndCount.get() & 7);
    }
    KJ_ALWAYS_INLINE(ElementCount elementCount() const) {
      return (elementSizeAndCount.get() >> 3) * ELEMENTS;
    }
    KJ_ALWAYS_INLINE(WordCount inlineCompositeWordCount() const) {
      return elementCount() * (1 * WORDS / ELEMENTS);
    }

    KJ_ALWAYS_INLINE(void set(FieldSize es, ElementCount ec)) {
      KJ_DREQUIRE(ec < (1 << 29) * ELEMENTS, "Lists are limited to 2**29 elements.");
      elementSizeAndCount.set(((ec / ELEMENTS) << 3) | static_cast<int>(es));
    }

    KJ_ALWAYS_INLINE(void setInlineComposite(WordCount wc)) {
      KJ_DREQUIRE(wc < (1 << 29) * WORDS, "Inline composite lists are limited to 2**29 words.");
      elementSizeAndCount.set(((wc / WORDS) << 3) |
                              static_cast<int>(FieldSize::INLINE_COMPOSITE));
    }
  };

  struct FarRef {
    WireValue<SegmentId> segmentId;

    KJ_ALWAYS_INLINE(void set(SegmentId si)) {
      segmentId.set(si);
    }
  };

227 228 229 230 231
  struct CapRef {
    WireValue<uint32_t> index;
    // Index into the message's capability table.
  };

232
  union {
233 234
    uint32_t upper32Bits;

235
    StructRef structRef;
236

237 238 239
    ListRef listRef;

    FarRef farRef;
240 241

    CapRef capRef;
242
  };
243

244
  KJ_ALWAYS_INLINE(bool isNull() const) {
245 246 247 248
    // If the upper 32 bits are zero, this is a pointer to an empty struct.  We consider that to be
    // our "null" value.
    return (offsetAndKind.get() == 0) & (upper32Bits == 0);
  }
249
};
250
static_assert(sizeof(WirePointer) == sizeof(word),
251
    "capnp::WirePointer is not exactly one word.  This will probably break everything.");
252 253 254 255 256 257
static_assert(POINTERS * WORDS_PER_POINTER * BYTES_PER_WORD / BYTES == sizeof(WirePointer),
    "WORDS_PER_POINTER is wrong.");
static_assert(POINTERS * BYTES_PER_POINTER / BYTES == sizeof(WirePointer),
    "BYTES_PER_POINTER is wrong.");
static_assert(POINTERS * BITS_PER_POINTER / BITS_PER_BYTE / BYTES == sizeof(WirePointer),
    "BITS_PER_POINTER is wrong.");
258

259 260 261 262 263 264 265 266 267
namespace {

static const union {
  AlignedData<POINTER_SIZE_IN_WORDS / WORDS> word;
  WirePointer pointer;
} zero = {{{0}}};

}  // namespace

268 269
// =======================================================================================

270 271 272 273 274 275 276 277 278 279
namespace {

template <typename T>
struct SegmentAnd {
  SegmentBuilder* segment;
  T value;
};

}  // namespace

280
struct WireHelpers {
281
  static KJ_ALWAYS_INLINE(WordCount roundBytesUpToWords(ByteCount bytes)) {
Kenton Varda's avatar
Kenton Varda committed
282
    static_assert(sizeof(word) == 8, "This code assumes 64-bit words.");
283 284 285
    return (bytes + 7 * BYTES) / BYTES_PER_WORD;
  }

286
  static KJ_ALWAYS_INLINE(ByteCount roundBitsUpToBytes(BitCount bits)) {
287
    return (bits + 7 * BITS) / BITS_PER_BYTE;
Kenton Varda's avatar
Kenton Varda committed
288 289
  }

290 291 292 293 294 295 296 297 298 299 300 301 302
  // The maximum object size is 4GB - 1 byte.  If measured in bits, this would overflow a 32-bit
  // counter, so we need to accept BitCount64.  However, 32 bits is enough for the returned
  // ByteCounts and WordCounts.

  static KJ_ALWAYS_INLINE(WordCount roundBitsUpToWords(BitCount64 bits)) {
    static_assert(sizeof(word) == 8, "This code assumes 64-bit words.");
    return (bits + 63 * BITS) / BITS_PER_WORD;
  }

  static KJ_ALWAYS_INLINE(ByteCount roundBitsUpToBytes(BitCount64 bits)) {
    return (bits + 7 * BITS) / BITS_PER_BYTE;
  }

303
  static KJ_ALWAYS_INLINE(bool boundsCheck(
304
      SegmentReader* segment, const word* start, const word* end)) {
305
    // If segment is null, this is an unchecked message, so we don't do bounds checks.
306 307 308
    return segment == nullptr || segment->containsInterval(start, end);
  }

309
  static KJ_ALWAYS_INLINE(word* allocate(
310
      WirePointer*& ref, SegmentBuilder*& segment, WordCount amount,
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
      WirePointer::Kind kind, BuilderArena* orphanArena)) {
    // Allocate space in the mesasge for a new object, creating far pointers if necessary.
    //
    // * `ref` starts out being a reference to the pointer which shall be assigned to point at the
    //   new object.  On return, `ref` points to a pointer which needs to be initialized with
    //   the object's type information.  Normally this is the same pointer, but it can change if
    //   a far pointer was allocated -- in this case, `ref` will end up pointing to the far
    //   pointer's tag.  Either way, `allocate()` takes care of making sure that the original
    //   pointer ends up leading to the new object.  On return, only the upper 32 bit of `*ref`
    //   need to be filled in by the caller.
    // * `segment` starts out pointing to the segment containing `ref`.  On return, it points to
    //   the segment containing the allocated object, which is usually the same segment but could
    //   be a different one if the original segment was out of space.
    // * `amount` is the number of words to allocate.
    // * `kind` is the kind of object to allocate.  It is used to initialize the pointer.  It
    //   cannot be `FAR` -- far pointers are allocated automatically as needed.
    // * `orphanArena` is usually null.  If it is non-null, then we're allocating an orphan object.
    //   In this case, `segment` starts out null; the allocation takes place in an arbitrary
    //   segment belonging to the arena.  `ref` will be initialized as a non-far pointer, but its
    //   target offset will be set to zero.

    if (orphanArena == nullptr) {
      if (!ref->isNull()) zeroObject(segment, ref);

335 336 337 338 339 340 341
      if (amount == 0 * WORDS && kind == WirePointer::STRUCT) {
        // Note that the check for kind == WirePointer::STRUCT will hopefully cause this whole
        // branch to be optimized away from all the call sites that are allocating non-structs.
        ref->setKindAndTargetForEmptyStruct();
        return reinterpret_cast<word*>(ref);
      }

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
      word* ptr = segment->allocate(amount);

      if (ptr == nullptr) {
        // Need to allocate in a new segment.  We'll need to allocate an extra pointer worth of
        // space to act as the landing pad for a far pointer.

        WordCount amountPlusRef = amount + POINTER_SIZE_IN_WORDS;
        auto allocation = segment->getArena()->allocate(amountPlusRef);
        segment = allocation.segment;
        ptr = allocation.words;

        // Set up the original pointer to be a far pointer to the new segment.
        ref->setFar(false, segment->getOffsetTo(ptr));
        ref->farRef.set(segment->getSegmentId());

        // Initialize the landing pad to indicate that the data immediately follows the pad.
        ref = reinterpret_cast<WirePointer*>(ptr);
359
        ref->setKindAndTarget(kind, ptr + POINTER_SIZE_IN_WORDS, segment);
360 361 362 363

        // Allocated space follows new pointer.
        return ptr + POINTER_SIZE_IN_WORDS;
      } else {
364
        ref->setKindAndTarget(kind, ptr, segment);
365 366
        return ptr;
      }
367
    } else {
368
      // orphanArena is non-null.  Allocate an orphan.
369
      KJ_DASSERT(ref->isNull());
370 371
      auto allocation = orphanArena->allocate(amount);
      segment = allocation.segment;
372
      ref->setKindForOrphan(kind);
373
      return allocation.words;
374 375 376
    }
  }

377
  static KJ_ALWAYS_INLINE(word* followFarsNoWritableCheck(
378 379 380 381 382 383 384 385 386 387
      WirePointer*& ref, word* refTarget, SegmentBuilder*& segment)) {
    // If `ref` is a far pointer, follow it.  On return, `ref` will have been updated to point at
    // a WirePointer that contains the type information about the target object, and a pointer to
    // the object contents is returned.  The caller must NOT use `ref->target()` as this may or may
    // not actually return a valid pointer.  `segment` is also updated to point at the segment which
    // actually contains the object.
    //
    // If `ref` is not a far pointer, this simply returns `refTarget`.  Usually, `refTarget` should
    // be the same as `ref->target()`, but may not be in cases where `ref` is only a tag.

388
    if (ref->kind() == WirePointer::FAR) {
389
      segment = segment->getArena()->getSegment(ref->farRef.segmentId.get());
390 391
      WirePointer* pad =
          reinterpret_cast<WirePointer*>(segment->getPtrUnchecked(ref->farPositionInSegment()));
392 393 394
      if (!ref->isDoubleFar()) {
        ref = pad;
        return pad->target();
395
      }
396 397 398 399 400 401 402

      // Landing pad is another far pointer.  It is followed by a tag describing the pointed-to
      // object.
      ref = pad + 1;

      segment = segment->getArena()->getSegment(pad->farRef.segmentId.get());
      return segment->getPtrUnchecked(pad->farPositionInSegment());
403
    } else {
404
      return refTarget;
405 406 407
    }
  }

408 409 410 411 412 413 414
  static KJ_ALWAYS_INLINE(word* followFars(
      WirePointer*& ref, word* refTarget, SegmentBuilder*& segment)) {
    auto result = followFarsNoWritableCheck(ref, refTarget, segment);
    segment->checkWritable();
    return result;
  }

415 416 417
  static KJ_ALWAYS_INLINE(const word* followFars(
      const WirePointer*& ref, const word* refTarget, SegmentReader*& segment)) {
    // Like the other followFars() but operates on readers.
418

419
    // If the segment is null, this is an unchecked message, so there are no FAR pointers.
420
    if (segment != nullptr && ref->kind() == WirePointer::FAR) {
421
      // Look up the segment containing the landing pad.
422
      segment = segment->getArena()->tryGetSegment(ref->farRef.segmentId.get());
423
      KJ_REQUIRE(segment != nullptr, "Message contains far pointer to unknown segment.") {
424
        return nullptr;
Kenton Varda's avatar
Kenton Varda committed
425
      }
426

427 428
      // Find the landing pad and check that it is within bounds.
      const word* ptr = segment->getStartPtr() + ref->farPositionInSegment();
429
      WordCount padWords = (1 + ref->isDoubleFar()) * POINTER_SIZE_IN_WORDS;
430 431
      KJ_REQUIRE(boundsCheck(segment, ptr, ptr + padWords),
                 "Message contains out-of-bounds far pointer.") {
432
        return nullptr;
433 434
      }

435
      const WirePointer* pad = reinterpret_cast<const WirePointer*>(ptr);
436 437 438 439 440 441 442 443 444 445 446 447

      // If this is not a double-far then the landing pad is our final pointer.
      if (!ref->isDoubleFar()) {
        ref = pad;
        return pad->target();
      }

      // Landing pad is another far pointer.  It is followed by a tag describing the pointed-to
      // object.
      ref = pad + 1;

      segment = segment->getArena()->tryGetSegment(pad->farRef.segmentId.get());
448
      KJ_REQUIRE(segment != nullptr, "Message contains double-far pointer to unknown segment.") {
449
        return nullptr;
450
      }
451 452

      return segment->getStartPtr() + pad->farPositionInSegment();
453
    } else {
454
      return refTarget;
455 456 457
    }
  }

458 459
  // -----------------------------------------------------------------

460 461 462 463
  static void zeroObject(SegmentBuilder* segment, WirePointer* ref) {
    // Zero out the pointed-to object.  Use when the pointer is about to be overwritten making the
    // target object no longer reachable.

464 465 466
    // We shouldn't zero out external data linked into the message.
    if (!segment->isWritable()) return;

467 468 469 470 471 472 473
    switch (ref->kind()) {
      case WirePointer::STRUCT:
      case WirePointer::LIST:
        zeroObject(segment, ref, ref->target());
        break;
      case WirePointer::FAR: {
        segment = segment->getArena()->getSegment(ref->farRef.segmentId.get());
474 475 476 477 478 479 480 481 482 483 484 485 486 487
        if (segment->isWritable()) {  // Don't zero external data.
          WirePointer* pad =
              reinterpret_cast<WirePointer*>(segment->getPtrUnchecked(ref->farPositionInSegment()));

          if (ref->isDoubleFar()) {
            segment = segment->getArena()->getSegment(pad->farRef.segmentId.get());
            if (segment->isWritable()) {
              zeroObject(segment, pad + 1, segment->getPtrUnchecked(pad->farPositionInSegment()));
            }
            memset(pad, 0, sizeof(WirePointer) * 2);
          } else {
            zeroObject(segment, pad);
            memset(pad, 0, sizeof(WirePointer));
          }
488 489 490
        }
        break;
      }
491 492 493 494 495 496 497
      case WirePointer::OTHER:
        if (ref->isCapability()) {
          segment->getArena()->dropCap(ref->capRef.index.get());
        } else {
          KJ_FAIL_REQUIRE("Unknown pointer type.") { break; }
        }
        break;
498 499 500 501
    }
  }

  static void zeroObject(SegmentBuilder* segment, WirePointer* tag, word* ptr) {
502 503 504
    // We shouldn't zero out external data linked into the message.
    if (!segment->isWritable()) return;

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    switch (tag->kind()) {
      case WirePointer::STRUCT: {
        WirePointer* pointerSection =
            reinterpret_cast<WirePointer*>(ptr + tag->structRef.dataSize.get());
        uint count = tag->structRef.ptrCount.get() / POINTERS;
        for (uint i = 0; i < count; i++) {
          zeroObject(segment, pointerSection + i);
        }
        memset(ptr, 0, tag->structRef.wordSize() * BYTES_PER_WORD / BYTES);
        break;
      }
      case WirePointer::LIST: {
        switch (tag->listRef.elementSize()) {
          case FieldSize::VOID:
            // Nothing.
            break;
          case FieldSize::BIT:
          case FieldSize::BYTE:
          case FieldSize::TWO_BYTES:
          case FieldSize::FOUR_BYTES:
          case FieldSize::EIGHT_BYTES:
            memset(ptr, 0,
527 528
                roundBitsUpToWords(ElementCount64(tag->listRef.elementCount()) *
                                   dataBitsPerElement(tag->listRef.elementSize()))
529 530 531 532 533 534 535
                    * BYTES_PER_WORD / BYTES);
            break;
          case FieldSize::POINTER: {
            uint count = tag->listRef.elementCount() / ELEMENTS;
            for (uint i = 0; i < count; i++) {
              zeroObject(segment, reinterpret_cast<WirePointer*>(ptr) + i);
            }
536
            memset(ptr, 0, POINTER_SIZE_IN_WORDS * count * BYTES_PER_WORD / BYTES);
537 538 539 540 541
            break;
          }
          case FieldSize::INLINE_COMPOSITE: {
            WirePointer* elementTag = reinterpret_cast<WirePointer*>(ptr);

542
            KJ_ASSERT(elementTag->kind() == WirePointer::STRUCT,
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
                  "Don't know how to handle non-STRUCT inline composite.");
            WordCount dataSize = elementTag->structRef.dataSize.get();
            WirePointerCount pointerCount = elementTag->structRef.ptrCount.get();

            word* pos = ptr + POINTER_SIZE_IN_WORDS;
            uint count = elementTag->inlineCompositeListElementCount() / ELEMENTS;
            for (uint i = 0; i < count; i++) {
              pos += dataSize;

              for (uint j = 0; j < pointerCount / POINTERS; j++) {
                zeroObject(segment, reinterpret_cast<WirePointer*>(pos));
                pos += POINTER_SIZE_IN_WORDS;
              }
            }

558
            memset(ptr, 0, (elementTag->structRef.wordSize() * count + POINTER_SIZE_IN_WORDS)
559 560 561 562 563 564 565
                           * BYTES_PER_WORD / BYTES);
            break;
          }
        }
        break;
      }
      case WirePointer::FAR:
566 567 568
        KJ_FAIL_ASSERT("Unexpected FAR pointer.") {
          break;
        }
569
        break;
570 571 572 573 574
      case WirePointer::OTHER:
        KJ_FAIL_ASSERT("Unexpected OTHER pointer.") {
          break;
        }
        break;
575 576 577
    }
  }

578
  static KJ_ALWAYS_INLINE(
579 580 581 582 583
      void zeroPointerAndFars(SegmentBuilder* segment, WirePointer* ref)) {
    // Zero out the pointer itself and, if it is a far pointer, zero the landing pad as well, but
    // do not zero the object body.  Used when upgrading.

    if (ref->kind() == WirePointer::FAR) {
584 585 586 587 588
      SegmentBuilder* padSegment = segment->getArena()->getSegment(ref->farRef.segmentId.get());
      if (padSegment->isWritable()) {  // Don't zero external data.
        word* pad = padSegment->getPtrUnchecked(ref->farPositionInSegment());
        memset(pad, 0, sizeof(WirePointer) * (1 + ref->isDoubleFar()));
      }
589 590 591 592
    }
    memset(ref, 0, sizeof(*ref));
  }

593 594 595

  // -----------------------------------------------------------------

596 597
  static MessageSizeCounts totalSize(
      SegmentReader* segment, const WirePointer* ref, int nestingLimit) {
598 599
    // Compute the total size of the object pointed to, not counting far pointer overhead.

600 601
    MessageSizeCounts result = { 0 * WORDS, 0 };

602
    if (ref->isNull()) {
603
      return result;
604 605
    }

606
    KJ_REQUIRE(nestingLimit > 0, "Message is too deeply-nested.") {
607
      return result;
608 609 610
    }
    --nestingLimit;

611
    const word* ptr = followFars(ref, ref->target(), segment);
612 613

    switch (ref->kind()) {
614
      case WirePointer::STRUCT: {
615 616 617
        KJ_REQUIRE(boundsCheck(segment, ptr, ptr + ref->structRef.wordSize()),
                   "Message contained out-of-bounds struct pointer.") {
          return result;
618
        }
619
        result.wordCount += ref->structRef.wordSize();
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638

        const WirePointer* pointerSection =
            reinterpret_cast<const WirePointer*>(ptr + ref->structRef.dataSize.get());
        uint count = ref->structRef.ptrCount.get() / POINTERS;
        for (uint i = 0; i < count; i++) {
          result += totalSize(segment, pointerSection + i, nestingLimit);
        }
        break;
      }
      case WirePointer::LIST: {
        switch (ref->listRef.elementSize()) {
          case FieldSize::VOID:
            // Nothing.
            break;
          case FieldSize::BIT:
          case FieldSize::BYTE:
          case FieldSize::TWO_BYTES:
          case FieldSize::FOUR_BYTES:
          case FieldSize::EIGHT_BYTES: {
639
            WordCount totalWords = roundBitsUpToWords(
640 641
                ElementCount64(ref->listRef.elementCount()) *
                dataBitsPerElement(ref->listRef.elementSize()));
642 643 644
            KJ_REQUIRE(boundsCheck(segment, ptr, ptr + totalWords),
                       "Message contained out-of-bounds list pointer.") {
              return result;
645
            }
646
            result.wordCount += totalWords;
647 648 649 650 651
            break;
          }
          case FieldSize::POINTER: {
            WirePointerCount count = ref->listRef.elementCount() * (POINTERS / ELEMENTS);

652 653 654
            KJ_REQUIRE(boundsCheck(segment, ptr, ptr + count * WORDS_PER_POINTER),
                       "Message contained out-of-bounds list pointer.") {
              return result;
655 656
            }

657
            result.wordCount += count * WORDS_PER_POINTER;
658 659 660 661 662 663 664 665 666

            for (uint i = 0; i < count / POINTERS; i++) {
              result += totalSize(segment, reinterpret_cast<const WirePointer*>(ptr) + i,
                                  nestingLimit);
            }
            break;
          }
          case FieldSize::INLINE_COMPOSITE: {
            WordCount wordCount = ref->listRef.inlineCompositeWordCount();
667 668 669
            KJ_REQUIRE(boundsCheck(segment, ptr, ptr + wordCount + POINTER_SIZE_IN_WORDS),
                       "Message contained out-of-bounds list pointer.") {
              return result;
670 671
            }

672
            result.wordCount += wordCount + POINTER_SIZE_IN_WORDS;
673 674 675 676

            const WirePointer* elementTag = reinterpret_cast<const WirePointer*>(ptr);
            ElementCount count = elementTag->inlineCompositeListElementCount();

677 678 679
            KJ_REQUIRE(elementTag->kind() == WirePointer::STRUCT,
                       "Don't know how to handle non-STRUCT inline composite.") {
              return result;
680
            }
681

682 683 684
            KJ_REQUIRE(elementTag->structRef.wordSize() / ELEMENTS * count <= wordCount,
                       "Struct list pointer's elements overran size.") {
              return result;
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
            }

            WordCount dataSize = elementTag->structRef.dataSize.get();
            WirePointerCount pointerCount = elementTag->structRef.ptrCount.get();

            const word* pos = ptr + POINTER_SIZE_IN_WORDS;
            for (uint i = 0; i < count / ELEMENTS; i++) {
              pos += dataSize;

              for (uint j = 0; j < pointerCount / POINTERS; j++) {
                result += totalSize(segment, reinterpret_cast<const WirePointer*>(pos),
                                    nestingLimit);
                pos += POINTER_SIZE_IN_WORDS;
              }
            }
            break;
          }
        }
        break;
      }
      case WirePointer::FAR:
706
        KJ_FAIL_ASSERT("Unexpected FAR pointer.") {
707 708 709
          break;
        }
        break;
710
      case WirePointer::OTHER:
711 712 713 714 715
        if (ref->isCapability()) {
          result.capCount++;
        } else {
          KJ_FAIL_REQUIRE("Unknown pointer type.") { break; }
        }
716
        break;
717 718 719 720 721
    }

    return result;
  }

722
  // -----------------------------------------------------------------
723
  // Copy from an unchecked message.
724

725
  static KJ_ALWAYS_INLINE(
726
      void copyStruct(SegmentBuilder* segment, word* dst, const word* src,
727
                      WordCount dataSize, WirePointerCount pointerCount)) {
728 729
    memcpy(dst, src, dataSize * BYTES_PER_WORD / BYTES);

730 731
    const WirePointer* srcRefs = reinterpret_cast<const WirePointer*>(src + dataSize);
    WirePointer* dstRefs = reinterpret_cast<WirePointer*>(dst + dataSize);
732

733
    for (uint i = 0; i < pointerCount / POINTERS; i++) {
734
      SegmentBuilder* subSegment = segment;
735
      WirePointer* dstRef = dstRefs + i;
736
      copyMessage(subSegment, dstRef, srcRefs + i);
737 738 739
    }
  }

740
  static word* copyMessage(
741
      SegmentBuilder*& segment, WirePointer*& dst, const WirePointer* src) {
742 743
    // Not always-inline because it's recursive.

744
    switch (src->kind()) {
745
      case WirePointer::STRUCT: {
746
        if (src->isNull()) {
747
          memset(dst, 0, sizeof(WirePointer));
748
          return nullptr;
749 750
        } else {
          const word* srcPtr = src->target();
751 752
          word* dstPtr = allocate(
              dst, segment, src->structRef.wordSize(), WirePointer::STRUCT, nullptr);
753

754
          copyStruct(segment, dstPtr, srcPtr, src->structRef.dataSize.get(),
755
                     src->structRef.ptrCount.get());
756

757
          dst->structRef.set(src->structRef.dataSize.get(), src->structRef.ptrCount.get());
758
          return dstPtr;
759 760
        }
      }
761
      case WirePointer::LIST: {
762 763 764 765 766 767 768
        switch (src->listRef.elementSize()) {
          case FieldSize::VOID:
          case FieldSize::BIT:
          case FieldSize::BYTE:
          case FieldSize::TWO_BYTES:
          case FieldSize::FOUR_BYTES:
          case FieldSize::EIGHT_BYTES: {
769
            WordCount wordCount = roundBitsUpToWords(
770
                ElementCount64(src->listRef.elementCount()) *
771
                dataBitsPerElement(src->listRef.elementSize()));
772
            const word* srcPtr = src->target();
773
            word* dstPtr = allocate(dst, segment, wordCount, WirePointer::LIST, nullptr);
774 775
            memcpy(dstPtr, srcPtr, wordCount * BYTES_PER_WORD / BYTES);

776 777
            dst->listRef.set(src->listRef.elementSize(), src->listRef.elementCount());
            return dstPtr;
778 779
          }

780 781 782
          case FieldSize::POINTER: {
            const WirePointer* srcRefs = reinterpret_cast<const WirePointer*>(src->target());
            WirePointer* dstRefs = reinterpret_cast<WirePointer*>(
783
                allocate(dst, segment, src->listRef.elementCount() *
784
                    (1 * POINTERS / ELEMENTS) * WORDS_PER_POINTER,
785
                    WirePointer::LIST, nullptr));
786 787 788

            uint n = src->listRef.elementCount() / ELEMENTS;
            for (uint i = 0; i < n; i++) {
789
              SegmentBuilder* subSegment = segment;
790
              WirePointer* dstRef = dstRefs + i;
791
              copyMessage(subSegment, dstRef, srcRefs + i);
792 793
            }

794
            dst->listRef.set(FieldSize::POINTER, src->listRef.elementCount());
795
            return reinterpret_cast<word*>(dstRefs);
796 797 798 799 800
          }

          case FieldSize::INLINE_COMPOSITE: {
            const word* srcPtr = src->target();
            word* dstPtr = allocate(dst, segment,
801
                src->listRef.inlineCompositeWordCount() + POINTER_SIZE_IN_WORDS,
802
                WirePointer::LIST, nullptr);
803

804
            dst->listRef.setInlineComposite(src->listRef.inlineCompositeWordCount());
805

806 807
            const WirePointer* srcTag = reinterpret_cast<const WirePointer*>(srcPtr);
            memcpy(dstPtr, srcTag, sizeof(WirePointer));
808

809 810
            const word* srcElement = srcPtr + POINTER_SIZE_IN_WORDS;
            word* dstElement = dstPtr + POINTER_SIZE_IN_WORDS;
811

812
            KJ_ASSERT(srcTag->kind() == WirePointer::STRUCT,
813 814
                "INLINE_COMPOSITE of lists is not yet supported.");

815
            uint n = srcTag->inlineCompositeListElementCount() / ELEMENTS;
816
            for (uint i = 0; i < n; i++) {
817
              copyStruct(segment, dstElement, srcElement,
818
                  srcTag->structRef.dataSize.get(), srcTag->structRef.ptrCount.get());
819 820
              srcElement += srcTag->structRef.wordSize();
              dstElement += srcTag->structRef.wordSize();
821
            }
822
            return dstPtr;
823 824 825 826
          }
        }
        break;
      }
827 828
      case WirePointer::OTHER:
        KJ_FAIL_REQUIRE("Unchecked messages cannot contain OTHER pointers (e.g. capabilities).");
829 830 831
        break;
      case WirePointer::FAR:
        KJ_FAIL_REQUIRE("Unchecked messages cannot contain far pointers.");
832 833 834
        break;
    }

835
    return nullptr;
836 837
  }

838 839
  static void transferPointer(SegmentBuilder* dstSegment, WirePointer* dst,
                              SegmentBuilder* srcSegment, WirePointer* src) {
840 841
    // Make *dst point to the same object as *src.  Both must reside in the same message, but can
    // be in different segments.  Not always-inline because this is rarely used.
842 843 844 845 846
    //
    // Caller MUST zero out the source pointer after calling this, to make sure no later code
    // mistakenly thinks the source location still owns the object.  transferPointer() doesn't do
    // this zeroing itself because many callers transfer several pointers in a loop then zero out
    // the whole section.
847 848 849 850

    KJ_DASSERT(dst->isNull());
    // We expect the caller to ensure the target is already null so won't leak.

851
    if (src->isNull()) {
852 853
      memset(dst, 0, sizeof(WirePointer));
    } else if (src->kind() == WirePointer::FAR) {
854
      // Far pointers are position-independent, so we can just copy.
855
      memcpy(dst, src, sizeof(WirePointer));
856 857 858 859 860 861 862 863 864 865 866 867
    } else {
      transferPointer(dstSegment, dst, srcSegment, src, src->target());
    }
  }

  static void transferPointer(SegmentBuilder* dstSegment, WirePointer* dst,
                              SegmentBuilder* srcSegment, const WirePointer* srcTag,
                              word* srcPtr) {
    // Like the other overload, but splits src into a tag and a target.  Particularly useful for
    // OrphanBuilder.

    if (dstSegment == srcSegment) {
868
      // Same segment, so create a direct pointer.
869
      dst->setKindAndTarget(srcTag->kind(), srcPtr, dstSegment);
870 871

      // We can just copy the upper 32 bits.  (Use memcpy() to comply with aliasing rules.)
872
      memcpy(&dst->upper32Bits, &srcTag->upper32Bits, sizeof(srcTag->upper32Bits));
873 874 875 876
    } else {
      // Need to create a far pointer.  Try to allocate it in the same segment as the source, so
      // that it doesn't need to be a double-far.

877 878
      WirePointer* landingPad =
          reinterpret_cast<WirePointer*>(srcSegment->allocate(1 * WORDS));
879 880
      if (landingPad == nullptr) {
        // Darn, need a double-far.
881 882 883
        auto allocation = srcSegment->getArena()->allocate(2 * WORDS);
        SegmentBuilder* farSegment = allocation.segment;
        landingPad = reinterpret_cast<WirePointer*>(allocation.words);
884

885
        landingPad[0].setFar(false, srcSegment->getOffsetTo(srcPtr));
886 887
        landingPad[0].farRef.segmentId.set(srcSegment->getSegmentId());

888 889
        landingPad[1].setKindWithZeroOffset(srcTag->kind());
        memcpy(&landingPad[1].upper32Bits, &srcTag->upper32Bits, sizeof(srcTag->upper32Bits));
890 891 892 893 894

        dst->setFar(true, farSegment->getOffsetTo(reinterpret_cast<word*>(landingPad)));
        dst->farRef.set(farSegment->getSegmentId());
      } else {
        // Simple landing pad is just a pointer.
895
        landingPad->setKindAndTarget(srcTag->kind(), srcPtr, srcSegment);
896
        memcpy(&landingPad->upper32Bits, &srcTag->upper32Bits, sizeof(srcTag->upper32Bits));
897 898 899 900 901 902 903

        dst->setFar(false, srcSegment->getOffsetTo(reinterpret_cast<word*>(landingPad)));
        dst->farRef.set(srcSegment->getSegmentId());
      }
    }
  }

904 905
  // -----------------------------------------------------------------

906
  static KJ_ALWAYS_INLINE(StructBuilder initStructPointer(
907 908
      WirePointer* ref, SegmentBuilder* segment, StructSize size,
      BuilderArena* orphanArena = nullptr)) {
909
    // Allocate space for the new struct.  Newly-allocated space is automatically zeroed.
910
    word* ptr = allocate(ref, segment, size.total(), WirePointer::STRUCT, orphanArena);
911

912
    // Initialize the pointer.
913
    ref->structRef.set(size);
914 915

    // Build the StructBuilder.
916
    return StructBuilder(segment, ptr, reinterpret_cast<WirePointer*>(ptr + size.data),
917
                         size.data * BITS_PER_WORD, size.pointers, 0 * BITS);
918
  }
919

920
  static KJ_ALWAYS_INLINE(StructBuilder getWritableStructPointer(
921
      WirePointer* ref, SegmentBuilder* segment, StructSize size, const word* defaultValue)) {
922 923 924 925 926
    return getWritableStructPointer(ref, ref->target(), segment, size, defaultValue);
  }

  static KJ_ALWAYS_INLINE(StructBuilder getWritableStructPointer(
      WirePointer* ref, word* refTarget, SegmentBuilder* segment, StructSize size,
927
      const word* defaultValue, BuilderArena* orphanArena = nullptr)) {
928
    if (ref->isNull()) {
929
    useDefault:
Kenton Varda's avatar
Kenton Varda committed
930
      if (defaultValue == nullptr ||
931
          reinterpret_cast<const WirePointer*>(defaultValue)->isNull()) {
932
        return initStructPointer(ref, segment, size, orphanArena);
933
      }
934
      refTarget = copyMessage(segment, ref, reinterpret_cast<const WirePointer*>(defaultValue));
935 936
      defaultValue = nullptr;  // If the default value is itself invalid, don't use it again.
    }
937

938 939
    WirePointer* oldRef = ref;
    SegmentBuilder* oldSegment = segment;
940
    word* oldPtr = followFars(oldRef, refTarget, oldSegment);
941

942
    KJ_REQUIRE(oldRef->kind() == WirePointer::STRUCT,
943 944 945
        "Message contains non-struct pointer where struct pointer was expected.") {
      goto useDefault;
    }
946

947 948 949 950
    WordCount oldDataSize = oldRef->structRef.dataSize.get();
    WirePointerCount oldPointerCount = oldRef->structRef.ptrCount.get();
    WirePointer* oldPointerSection =
        reinterpret_cast<WirePointer*>(oldPtr + oldDataSize);
951

952 953 954 955
    if (oldDataSize < size.data || oldPointerCount < size.pointers) {
      // The space allocated for this struct is too small.  Unlike with readers, we can't just
      // run with it and do bounds checks at access time, because how would we handle writes?
      // Instead, we have to copy the struct to a new space now.
956

957 958 959 960
      WordCount newDataSize = std::max<WordCount>(oldDataSize, size.data);
      WirePointerCount newPointerCount =
          std::max<WirePointerCount>(oldPointerCount, size.pointers);
      WordCount totalSize = newDataSize + newPointerCount * WORDS_PER_POINTER;
961

962 963
      // Don't let allocate() zero out the object just yet.
      zeroPointerAndFars(segment, ref);
964

965
      word* ptr = allocate(ref, segment, totalSize, WirePointer::STRUCT, orphanArena);
966
      ref->structRef.set(newDataSize, newPointerCount);
967

968 969
      // Copy data section.
      memcpy(ptr, oldPtr, oldDataSize * BYTES_PER_WORD / BYTES);
970

971 972 973 974
      // Copy pointer section.
      WirePointer* newPointerSection = reinterpret_cast<WirePointer*>(ptr + newDataSize);
      for (uint i = 0; i < oldPointerCount / POINTERS; i++) {
        transferPointer(segment, newPointerSection + i, oldSegment, oldPointerSection + i);
975
      }
976 977 978 979 980 981 982 983 984 985 986 987 988 989

      // Zero out old location.  This has two purposes:
      // 1) We don't want to leak the original contents of the struct when the message is written
      //    out as it may contain secrets that the caller intends to remove from the new copy.
      // 2) Zeros will be deflated by packing, making this dead memory almost-free if it ever
      //    hits the wire.
      memset(oldPtr, 0,
             (oldDataSize + oldPointerCount * WORDS_PER_POINTER) * BYTES_PER_WORD / BYTES);

      return StructBuilder(segment, ptr, newPointerSection, newDataSize * BITS_PER_WORD,
                           newPointerCount, 0 * BITS);
    } else {
      return StructBuilder(oldSegment, oldPtr, oldPointerSection, oldDataSize * BITS_PER_WORD,
                           oldPointerCount, 0 * BITS);
990
    }
991 992
  }

993
  static KJ_ALWAYS_INLINE(ListBuilder initListPointer(
994
      WirePointer* ref, SegmentBuilder* segment, ElementCount elementCount,
995
      FieldSize elementSize, BuilderArena* orphanArena = nullptr)) {
996
    KJ_DREQUIRE(elementSize != FieldSize::INLINE_COMPOSITE,
997
        "Should have called initStructListPointer() instead.");
998

999
    BitCount dataSize = dataBitsPerElement(elementSize) * ELEMENTS;
1000 1001
    WirePointerCount pointerCount = pointersPerElement(elementSize) * ELEMENTS;
    auto step = (dataSize + pointerCount * BITS_PER_POINTER) / ELEMENTS;
1002

1003
    // Calculate size of the list.
1004
    WordCount wordCount = roundBitsUpToWords(ElementCount64(elementCount) * step);
1005

1006
    // Allocate the list.
1007
    word* ptr = allocate(ref, segment, wordCount, WirePointer::LIST, orphanArena);
1008

1009
    // Initialize the pointer.
1010
    ref->listRef.set(elementSize, elementCount);
1011

1012
    // Build the ListBuilder.
1013
    return ListBuilder(segment, ptr, step, elementCount, dataSize, pointerCount);
1014
  }
1015

1016
  static KJ_ALWAYS_INLINE(ListBuilder initStructListPointer(
1017
      WirePointer* ref, SegmentBuilder* segment, ElementCount elementCount,
1018
      StructSize elementSize, BuilderArena* orphanArena = nullptr)) {
1019
    if (elementSize.preferredListEncoding != FieldSize::INLINE_COMPOSITE) {
1020
      // Small data-only struct.  Allocate a list of primitives instead.
1021 1022
      return initListPointer(ref, segment, elementCount, elementSize.preferredListEncoding,
                             orphanArena);
1023 1024
    }

1025
    auto wordsPerElement = elementSize.total() / ELEMENTS;
1026

1027
    // Allocate the list, prefixed by a single WirePointer.
1028
    WordCount wordCount = elementCount * wordsPerElement;
1029 1030
    word* ptr = allocate(ref, segment, POINTER_SIZE_IN_WORDS + wordCount, WirePointer::LIST,
                         orphanArena);
1031

1032
    // Initialize the pointer.
1033
    // INLINE_COMPOSITE lists replace the element count with the word count.
1034
    ref->listRef.setInlineComposite(wordCount);
1035

1036
    // Initialize the list tag.
1037 1038 1039 1040
    reinterpret_cast<WirePointer*>(ptr)->setKindAndInlineCompositeListElementCount(
        WirePointer::STRUCT, elementCount);
    reinterpret_cast<WirePointer*>(ptr)->structRef.set(elementSize);
    ptr += POINTER_SIZE_IN_WORDS;
1041

1042
    // Build the ListBuilder.
1043 1044
    return ListBuilder(segment, ptr, wordsPerElement * BITS_PER_WORD, elementCount,
                       elementSize.data * BITS_PER_WORD, elementSize.pointers);
1045 1046
  }

1047
  static KJ_ALWAYS_INLINE(ListBuilder getWritableListPointer(
1048 1049
      WirePointer* origRef, SegmentBuilder* origSegment, FieldSize elementSize,
      const word* defaultValue)) {
1050 1051 1052 1053 1054 1055
    return getWritableListPointer(origRef, origRef->target(), origSegment, elementSize,
                                  defaultValue);
  }

  static KJ_ALWAYS_INLINE(ListBuilder getWritableListPointer(
      WirePointer* origRef, word* origRefTarget, SegmentBuilder* origSegment, FieldSize elementSize,
1056
      const word* defaultValue, BuilderArena* orphanArena = nullptr)) {
1057
    KJ_DREQUIRE(elementSize != FieldSize::INLINE_COMPOSITE,
1058
             "Use getStructList{Element,Field}() for structs.");
1059

1060 1061
    if (origRef->isNull()) {
    useDefault:
Kenton Varda's avatar
Kenton Varda committed
1062
      if (defaultValue == nullptr ||
1063
          reinterpret_cast<const WirePointer*>(defaultValue)->isNull()) {
1064
        return ListBuilder();
1065
      }
1066 1067
      origRefTarget = copyMessage(
          origSegment, origRef, reinterpret_cast<const WirePointer*>(defaultValue));
1068 1069
      defaultValue = nullptr;  // If the default value is itself invalid, don't use it again.
    }
1070

1071 1072 1073 1074
    // We must verify that the pointer has the right size.  Unlike in
    // getWritableStructListReference(), we never need to "upgrade" the data, because this
    // method is called only for non-struct lists, and there is no allowed upgrade path *to*
    // a non-struct list, only *from* them.
1075

1076 1077
    WirePointer* ref = origRef;
    SegmentBuilder* segment = origSegment;
1078
    word* ptr = followFars(ref, origRefTarget, segment);
1079

1080
    KJ_REQUIRE(ref->kind() == WirePointer::LIST,
1081 1082 1083
        "Called getList{Field,Element}() but existing pointer is not a list.") {
      goto useDefault;
    }
1084

1085
    FieldSize oldSize = ref->listRef.elementSize();
1086

1087 1088 1089 1090 1091 1092
    if (oldSize == FieldSize::INLINE_COMPOSITE) {
      // The existing element size is INLINE_COMPOSITE, which means that it is at least two
      // words, which makes it bigger than the expected element size.  Since fields can only
      // grow when upgraded, the existing data must have been written with a newer version of
      // the protocol.  We therefore never need to upgrade the data in this case, but we do
      // need to validate that it is a valid upgrade from what we expected.
1093

1094 1095
      // Read the tag to get the actual element count.
      WirePointer* tag = reinterpret_cast<WirePointer*>(ptr);
1096
      KJ_REQUIRE(tag->kind() == WirePointer::STRUCT,
1097 1098
          "INLINE_COMPOSITE list with non-STRUCT elements not supported.");
      ptr += POINTER_SIZE_IN_WORDS;
1099

1100 1101
      WordCount dataSize = tag->structRef.dataSize.get();
      WirePointerCount pointerCount = tag->structRef.ptrCount.get();
1102

1103 1104 1105 1106
      switch (elementSize) {
        case FieldSize::VOID:
          // Anything is a valid upgrade from Void.
          break;
1107

1108 1109 1110 1111 1112
        case FieldSize::BIT:
        case FieldSize::BYTE:
        case FieldSize::TWO_BYTES:
        case FieldSize::FOUR_BYTES:
        case FieldSize::EIGHT_BYTES:
1113 1114 1115 1116
          KJ_REQUIRE(dataSize >= 1 * WORDS,
                     "Existing list value is incompatible with expected type.") {
            goto useDefault;
          }
1117
          break;
1118

1119
        case FieldSize::POINTER:
1120 1121 1122 1123
          KJ_REQUIRE(pointerCount >= 1 * POINTERS,
                     "Existing list value is incompatible with expected type.") {
            goto useDefault;
          }
1124 1125 1126
          // Adjust the pointer to point at the reference segment.
          ptr += dataSize;
          break;
1127

1128
        case FieldSize::INLINE_COMPOSITE:
1129
          KJ_FAIL_ASSERT("Can't get here.");
1130 1131
          break;
      }
1132

1133
      // OK, looks valid.
1134

1135 1136 1137 1138 1139 1140 1141
      return ListBuilder(segment, ptr,
                         tag->structRef.wordSize() * BITS_PER_WORD / ELEMENTS,
                         tag->inlineCompositeListElementCount(),
                         dataSize * BITS_PER_WORD, pointerCount);
    } else {
      BitCount dataSize = dataBitsPerElement(oldSize) * ELEMENTS;
      WirePointerCount pointerCount = pointersPerElement(oldSize) * ELEMENTS;
1142

1143 1144 1145 1146 1147 1148 1149 1150
      KJ_REQUIRE(dataSize >= dataBitsPerElement(elementSize) * ELEMENTS,
                 "Existing list value is incompatible with expected type.") {
        goto useDefault;
      }
      KJ_REQUIRE(pointerCount >= pointersPerElement(elementSize) * ELEMENTS,
                 "Existing list value is incompatible with expected type.") {
        goto useDefault;
      }
1151

1152 1153 1154
      auto step = (dataSize + pointerCount * BITS_PER_POINTER) / ELEMENTS;
      return ListBuilder(segment, ptr, step, ref->listRef.elementCount(),
                         dataSize, pointerCount);
1155
    }
1156 1157
  }

1158
  static KJ_ALWAYS_INLINE(ListBuilder getWritableStructListPointer(
1159 1160
      WirePointer* origRef, SegmentBuilder* origSegment, StructSize elementSize,
      const word* defaultValue)) {
1161 1162 1163 1164 1165
    return getWritableStructListPointer(origRef, origRef->target(), origSegment, elementSize,
                                        defaultValue);
  }
  static KJ_ALWAYS_INLINE(ListBuilder getWritableStructListPointer(
      WirePointer* origRef, word* origRefTarget, SegmentBuilder* origSegment,
1166
      StructSize elementSize, const word* defaultValue, BuilderArena* orphanArena = nullptr)) {
1167 1168 1169 1170 1171 1172
    if (origRef->isNull()) {
    useDefault:
      if (defaultValue == nullptr ||
          reinterpret_cast<const WirePointer*>(defaultValue)->isNull()) {
        return ListBuilder();
      }
1173 1174
      origRefTarget = copyMessage(
          origSegment, origRef, reinterpret_cast<const WirePointer*>(defaultValue));
1175 1176
      defaultValue = nullptr;  // If the default value is itself invalid, don't use it again.
    }
1177

1178
    // We must verify that the pointer has the right size and potentially upgrade it if not.
1179

1180 1181
    WirePointer* oldRef = origRef;
    SegmentBuilder* oldSegment = origSegment;
1182
    word* oldPtr = followFars(oldRef, origRefTarget, oldSegment);
1183

1184 1185
    KJ_REQUIRE(oldRef->kind() == WirePointer::LIST,
               "Called getList{Field,Element}() but existing pointer is not a list.") {
1186 1187 1188 1189
      goto useDefault;
    }

    FieldSize oldSize = oldRef->listRef.elementSize();
1190

1191 1192
    if (oldSize == FieldSize::INLINE_COMPOSITE) {
      // Existing list is INLINE_COMPOSITE, but we need to verify that the sizes match.
1193

1194 1195
      WirePointer* oldTag = reinterpret_cast<WirePointer*>(oldPtr);
      oldPtr += POINTER_SIZE_IN_WORDS;
1196 1197
      KJ_REQUIRE(oldTag->kind() == WirePointer::STRUCT,
                 "INLINE_COMPOSITE list with non-STRUCT elements not supported.") {
1198 1199 1200
        goto useDefault;
      }

1201 1202 1203 1204
      WordCount oldDataSize = oldTag->structRef.dataSize.get();
      WirePointerCount oldPointerCount = oldTag->structRef.ptrCount.get();
      auto oldStep = (oldDataSize + oldPointerCount * WORDS_PER_POINTER) / ELEMENTS;
      ElementCount elementCount = oldTag->inlineCompositeListElementCount();
1205

1206 1207 1208 1209 1210
      if (oldDataSize >= elementSize.data && oldPointerCount >= elementSize.pointers) {
        // Old size is at least as large as we need.  Ship it.
        return ListBuilder(oldSegment, oldPtr, oldStep * BITS_PER_WORD, elementCount,
                           oldDataSize * BITS_PER_WORD, oldPointerCount);
      }
1211

1212 1213
      // The structs in this list are smaller than expected, probably written using an older
      // version of the protocol.  We need to make a copy and expand them.
1214

1215 1216 1217 1218 1219
      WordCount newDataSize = std::max<WordCount>(oldDataSize, elementSize.data);
      WirePointerCount newPointerCount =
          std::max<WirePointerCount>(oldPointerCount, elementSize.pointers);
      auto newStep = (newDataSize + newPointerCount * WORDS_PER_POINTER) / ELEMENTS;
      WordCount totalSize = newStep * elementCount;
1220

1221 1222
      // Don't let allocate() zero out the object just yet.
      zeroPointerAndFars(origSegment, origRef);
1223

1224
      word* newPtr = allocate(origRef, origSegment, totalSize + POINTER_SIZE_IN_WORDS,
1225
                              WirePointer::LIST, orphanArena);
1226
      origRef->listRef.setInlineComposite(totalSize);
1227

1228 1229 1230 1231
      WirePointer* newTag = reinterpret_cast<WirePointer*>(newPtr);
      newTag->setKindAndInlineCompositeListElementCount(WirePointer::STRUCT, elementCount);
      newTag->structRef.set(newDataSize, newPointerCount);
      newPtr += POINTER_SIZE_IN_WORDS;
1232

1233 1234 1235 1236 1237
      word* src = oldPtr;
      word* dst = newPtr;
      for (uint i = 0; i < elementCount / ELEMENTS; i++) {
        // Copy data section.
        memcpy(dst, src, oldDataSize * BYTES_PER_WORD / BYTES);
1238

1239 1240 1241 1242 1243
        // Copy pointer section.
        WirePointer* newPointerSection = reinterpret_cast<WirePointer*>(dst + newDataSize);
        WirePointer* oldPointerSection = reinterpret_cast<WirePointer*>(src + oldDataSize);
        for (uint i = 0; i < oldPointerCount / POINTERS; i++) {
          transferPointer(origSegment, newPointerSection + i, oldSegment, oldPointerSection + i);
1244 1245
        }

1246 1247 1248
        dst += newStep * (1 * ELEMENTS);
        src += oldStep * (1 * ELEMENTS);
      }
1249

1250 1251
      // Zero out old location.  See explanation in getWritableStructPointer().
      memset(oldPtr, 0, oldStep * elementCount * BYTES_PER_WORD / BYTES);
1252

1253 1254 1255 1256
      return ListBuilder(origSegment, newPtr, newStep * BITS_PER_WORD, elementCount,
                         newDataSize * BITS_PER_WORD, newPointerCount);
    } else if (oldSize == elementSize.preferredListEncoding) {
      // Old size matches exactly.
1257

1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
      auto dataSize = dataBitsPerElement(oldSize);
      auto pointerCount = pointersPerElement(oldSize);
      auto step = dataSize + pointerCount * BITS_PER_POINTER;

      return ListBuilder(oldSegment, oldPtr, step, oldRef->listRef.elementCount(),
                         dataSize * (1 * ELEMENTS), pointerCount * (1 * ELEMENTS));
    } else {
      switch (elementSize.preferredListEncoding) {
        case FieldSize::VOID:
          // No expectations.
          break;
        case FieldSize::POINTER:
1270 1271
          KJ_REQUIRE(oldSize == FieldSize::POINTER || oldSize == FieldSize::VOID,
                     "Struct list has incompatible element size.") {
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
            goto useDefault;
          }
          break;
        case FieldSize::INLINE_COMPOSITE:
          // Old size can be anything.
          break;
        case FieldSize::BIT:
        case FieldSize::BYTE:
        case FieldSize::TWO_BYTES:
        case FieldSize::FOUR_BYTES:
        case FieldSize::EIGHT_BYTES:
          // Preferred size is data-only.
1284 1285
          KJ_REQUIRE(oldSize != FieldSize::POINTER,
                     "Struct list has incompatible element size.") {
1286 1287 1288 1289
            goto useDefault;
          }
          break;
      }
1290

1291 1292
      // OK, the old size is compatible with the preferred, but is not exactly the same.  We may
      // need to upgrade it.
1293

1294 1295 1296 1297
      BitCount oldDataSize = dataBitsPerElement(oldSize) * ELEMENTS;
      WirePointerCount oldPointerCount = pointersPerElement(oldSize) * ELEMENTS;
      auto oldStep = (oldDataSize + oldPointerCount * BITS_PER_POINTER) / ELEMENTS;
      ElementCount elementCount = oldRef->listRef.elementCount();
1298

1299 1300 1301 1302 1303
      if (oldSize >= elementSize.preferredListEncoding) {
        // The old size is at least as large as the preferred, so we don't need to upgrade.
        return ListBuilder(oldSegment, oldPtr, oldStep, elementCount,
                           oldDataSize, oldPointerCount);
      }
1304

1305
      // Upgrade is necessary.
1306

1307 1308 1309 1310 1311
      if (oldSize == FieldSize::VOID) {
        // Nothing to copy, just allocate a new list.
        return initStructListPointer(origRef, origSegment, elementCount, elementSize);
      } else if (elementSize.preferredListEncoding == FieldSize::INLINE_COMPOSITE) {
        // Upgrading to an inline composite list.
1312

1313 1314
        WordCount newDataSize = elementSize.data;
        WirePointerCount newPointerCount = elementSize.pointers;
1315

1316 1317 1318 1319 1320 1321
        if (oldSize == FieldSize::POINTER) {
          newPointerCount = std::max(newPointerCount, 1 * POINTERS);
        } else {
          // Old list contains data elements, so we need at least 1 word of data.
          newDataSize = std::max(newDataSize, 1 * WORDS);
        }
1322

1323 1324
        auto newStep = (newDataSize + newPointerCount * WORDS_PER_POINTER) / ELEMENTS;
        WordCount totalWords = elementCount * newStep;
1325

1326 1327
        // Don't let allocate() zero out the object just yet.
        zeroPointerAndFars(origSegment, origRef);
1328

1329
        word* newPtr = allocate(origRef, origSegment, totalWords + POINTER_SIZE_IN_WORDS,
1330
                                WirePointer::LIST, orphanArena);
1331
        origRef->listRef.setInlineComposite(totalWords);
1332

1333 1334 1335 1336
        WirePointer* tag = reinterpret_cast<WirePointer*>(newPtr);
        tag->setKindAndInlineCompositeListElementCount(WirePointer::STRUCT, elementCount);
        tag->structRef.set(newDataSize, newPointerCount);
        newPtr += POINTER_SIZE_IN_WORDS;
1337

1338 1339 1340 1341 1342 1343 1344
        if (oldSize == FieldSize::POINTER) {
          WirePointer* dst = reinterpret_cast<WirePointer*>(newPtr + newDataSize);
          WirePointer* src = reinterpret_cast<WirePointer*>(oldPtr);
          for (uint i = 0; i < elementCount / ELEMENTS; i++) {
            transferPointer(origSegment, dst, oldSegment, src);
            dst += newStep / WORDS_PER_POINTER * (1 * ELEMENTS);
            ++src;
1345
          }
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        } else if (oldSize == FieldSize::BIT) {
          word* dst = newPtr;
          char* src = reinterpret_cast<char*>(oldPtr);
          for (uint i = 0; i < elementCount / ELEMENTS; i++) {
            *reinterpret_cast<char*>(dst) = (src[i/8] >> (i%8)) & 1;
            dst += newStep * (1 * ELEMENTS);
          }
        } else {
          word* dst = newPtr;
          char* src = reinterpret_cast<char*>(oldPtr);
          ByteCount oldByteStep = oldDataSize / BITS_PER_BYTE;
          for (uint i = 0; i < elementCount / ELEMENTS; i++) {
            memcpy(dst, src, oldByteStep / BYTES);
            src += oldByteStep / BYTES;
            dst += newStep * (1 * ELEMENTS);
          }
        }
1363

1364
        // Zero out old location.  See explanation in getWritableStructPointer().
1365
        memset(oldPtr, 0, roundBitsUpToBytes(oldStep * elementCount) / BYTES);
1366

1367 1368
        return ListBuilder(origSegment, newPtr, newStep * BITS_PER_WORD, elementCount,
                           newDataSize * BITS_PER_WORD, newPointerCount);
1369

1370 1371 1372
      } else {
        // If oldSize were POINTER or EIGHT_BYTES then the preferred size must be
        // INLINE_COMPOSITE because any other compatible size would not require an upgrade.
1373
        KJ_ASSERT(oldSize < FieldSize::EIGHT_BYTES);
1374

1375 1376
        // If the preferred size were BIT then oldSize must be VOID, but we handled that case
        // above.
1377
        KJ_ASSERT(elementSize.preferredListEncoding >= FieldSize::BIT);
1378

1379 1380 1381
        // OK, so the expected list elements are all data and between 1 byte and 1 word each,
        // and the old element are data between 1 bit and 4 bytes.  We're upgrading from one
        // primitive data type to another, larger one.
1382

1383 1384
        BitCount newDataSize =
            dataBitsPerElement(elementSize.preferredListEncoding) * ELEMENTS;
1385

1386
        WordCount totalWords =
1387
            roundBitsUpToWords(BitCount64(newDataSize) * (elementCount / ELEMENTS));
1388

1389 1390
        // Don't let allocate() zero out the object just yet.
        zeroPointerAndFars(origSegment, origRef);
1391

1392
        word* newPtr = allocate(origRef, origSegment, totalWords, WirePointer::LIST, orphanArena);
1393
        origRef->listRef.set(elementSize.preferredListEncoding, elementCount);
1394

1395 1396 1397 1398 1399 1400 1401
        char* newBytePtr = reinterpret_cast<char*>(newPtr);
        char* oldBytePtr = reinterpret_cast<char*>(oldPtr);
        ByteCount newDataByteSize = newDataSize / BITS_PER_BYTE;
        if (oldSize == FieldSize::BIT) {
          for (uint i = 0; i < elementCount / ELEMENTS; i++) {
            *newBytePtr = (oldBytePtr[i/8] >> (i%8)) & 1;
            newBytePtr += newDataByteSize / BYTES;
1402
          }
1403 1404 1405 1406 1407 1408 1409 1410
        } else {
          ByteCount oldDataByteSize = oldDataSize / BITS_PER_BYTE;
          for (uint i = 0; i < elementCount / ELEMENTS; i++) {
            memcpy(newBytePtr, oldBytePtr, oldDataByteSize / BYTES);
            oldBytePtr += oldDataByteSize / BYTES;
            newBytePtr += newDataByteSize / BYTES;
          }
        }
1411

1412
        // Zero out old location.  See explanation in getWritableStructPointer().
1413
        memset(oldPtr, 0, roundBitsUpToBytes(oldStep * elementCount) / BYTES);
1414

1415 1416
        return ListBuilder(origSegment, newPtr, newDataSize / ELEMENTS, elementCount,
                           newDataSize, 0 * POINTERS);
1417
      }
1418 1419 1420
    }
  }

1421 1422 1423
  static KJ_ALWAYS_INLINE(SegmentAnd<Text::Builder> initTextPointer(
      WirePointer* ref, SegmentBuilder* segment, ByteCount size,
      BuilderArena* orphanArena = nullptr)) {
Kenton Varda's avatar
Kenton Varda committed
1424 1425 1426 1427
    // The byte list must include a NUL terminator.
    ByteCount byteSize = size + 1 * BYTES;

    // Allocate the space.
1428 1429
    word* ptr = allocate(
        ref, segment, roundBytesUpToWords(byteSize), WirePointer::LIST, orphanArena);
Kenton Varda's avatar
Kenton Varda committed
1430

1431
    // Initialize the pointer.
Kenton Varda's avatar
Kenton Varda committed
1432 1433 1434
    ref->listRef.set(FieldSize::BYTE, byteSize * (1 * ELEMENTS / BYTES));

    // Build the Text::Builder.  This will initialize the NUL terminator.
1435
    return { segment, Text::Builder(reinterpret_cast<char*>(ptr), size / BYTES) };
Kenton Varda's avatar
Kenton Varda committed
1436 1437
  }

1438 1439 1440 1441 1442 1443
  static KJ_ALWAYS_INLINE(SegmentAnd<Text::Builder> setTextPointer(
      WirePointer* ref, SegmentBuilder* segment, Text::Reader value,
      BuilderArena* orphanArena = nullptr)) {
    auto allocation = initTextPointer(ref, segment, value.size() * BYTES, orphanArena);
    memcpy(allocation.value.begin(), value.begin(), value.size());
    return allocation;
Kenton Varda's avatar
Kenton Varda committed
1444 1445
  }

1446
  static KJ_ALWAYS_INLINE(Text::Builder getWritableTextPointer(
1447
      WirePointer* ref, SegmentBuilder* segment,
Kenton Varda's avatar
Kenton Varda committed
1448
      const void* defaultValue, ByteCount defaultSize)) {
1449 1450 1451 1452 1453 1454
    return getWritableTextPointer(ref, ref->target(), segment, defaultValue, defaultSize);
  }

  static KJ_ALWAYS_INLINE(Text::Builder getWritableTextPointer(
      WirePointer* ref, word* refTarget, SegmentBuilder* segment,
      const void* defaultValue, ByteCount defaultSize)) {
Kenton Varda's avatar
Kenton Varda committed
1455
    if (ref->isNull()) {
1456 1457 1458
      if (defaultSize == 0 * BYTES) {
        return nullptr;
      } else {
1459
        Text::Builder builder = initTextPointer(ref, segment, defaultSize).value;
1460 1461 1462
        memcpy(builder.begin(), defaultValue, defaultSize / BYTES);
        return builder;
      }
Kenton Varda's avatar
Kenton Varda committed
1463
    } else {
1464
      word* ptr = followFars(ref, refTarget, segment);
Kenton Varda's avatar
Kenton Varda committed
1465

1466
      KJ_REQUIRE(ref->kind() == WirePointer::LIST,
1467
          "Called getText{Field,Element}() but existing pointer is not a list.");
1468
      KJ_REQUIRE(ref->listRef.elementSize() == FieldSize::BYTE,
1469
          "Called getText{Field,Element}() but existing list pointer is not byte-sized.");
Kenton Varda's avatar
Kenton Varda committed
1470 1471 1472 1473 1474 1475

      // Subtract 1 from the size for the NUL terminator.
      return Text::Builder(reinterpret_cast<char*>(ptr), ref->listRef.elementCount() / ELEMENTS - 1);
    }
  }

1476 1477 1478
  static KJ_ALWAYS_INLINE(SegmentAnd<Data::Builder> initDataPointer(
      WirePointer* ref, SegmentBuilder* segment, ByteCount size,
      BuilderArena* orphanArena = nullptr)) {
Kenton Varda's avatar
Kenton Varda committed
1479
    // Allocate the space.
1480
    word* ptr = allocate(ref, segment, roundBytesUpToWords(size), WirePointer::LIST, orphanArena);
Kenton Varda's avatar
Kenton Varda committed
1481

1482
    // Initialize the pointer.
Kenton Varda's avatar
Kenton Varda committed
1483 1484 1485
    ref->listRef.set(FieldSize::BYTE, size * (1 * ELEMENTS / BYTES));

    // Build the Data::Builder.
1486
    return { segment, Data::Builder(reinterpret_cast<byte*>(ptr), size / BYTES) };
Kenton Varda's avatar
Kenton Varda committed
1487 1488
  }

1489 1490 1491 1492 1493 1494
  static KJ_ALWAYS_INLINE(SegmentAnd<Data::Builder> setDataPointer(
      WirePointer* ref, SegmentBuilder* segment, Data::Reader value,
      BuilderArena* orphanArena = nullptr)) {
    auto allocation = initDataPointer(ref, segment, value.size() * BYTES, orphanArena);
    memcpy(allocation.value.begin(), value.begin(), value.size());
    return allocation;
Kenton Varda's avatar
Kenton Varda committed
1495 1496
  }

1497
  static KJ_ALWAYS_INLINE(Data::Builder getWritableDataPointer(
1498
      WirePointer* ref, SegmentBuilder* segment,
Kenton Varda's avatar
Kenton Varda committed
1499
      const void* defaultValue, ByteCount defaultSize)) {
1500 1501 1502 1503 1504 1505
    return getWritableDataPointer(ref, ref->target(), segment, defaultValue, defaultSize);
  }

  static KJ_ALWAYS_INLINE(Data::Builder getWritableDataPointer(
      WirePointer* ref, word* refTarget, SegmentBuilder* segment,
      const void* defaultValue, ByteCount defaultSize)) {
Kenton Varda's avatar
Kenton Varda committed
1506
    if (ref->isNull()) {
1507 1508 1509
      if (defaultSize == 0 * BYTES) {
        return nullptr;
      } else {
1510
        Data::Builder builder = initDataPointer(ref, segment, defaultSize).value;
1511 1512 1513
        memcpy(builder.begin(), defaultValue, defaultSize / BYTES);
        return builder;
      }
Kenton Varda's avatar
Kenton Varda committed
1514
    } else {
1515
      word* ptr = followFars(ref, refTarget, segment);
Kenton Varda's avatar
Kenton Varda committed
1516

1517
      KJ_REQUIRE(ref->kind() == WirePointer::LIST,
1518
          "Called getData{Field,Element}() but existing pointer is not a list.");
1519
      KJ_REQUIRE(ref->listRef.elementSize() == FieldSize::BYTE,
1520
          "Called getData{Field,Element}() but existing list pointer is not byte-sized.");
Kenton Varda's avatar
Kenton Varda committed
1521

1522
      return Data::Builder(reinterpret_cast<byte*>(ptr), ref->listRef.elementCount() / ELEMENTS);
Kenton Varda's avatar
Kenton Varda committed
1523 1524 1525
    }
  }

1526 1527 1528
  static SegmentAnd<word*> setStructPointer(
      SegmentBuilder* segment, WirePointer* ref, StructReader value,
      BuilderArena* orphanArena = nullptr) {
1529
    WordCount dataSize = roundBitsUpToWords(value.dataSize);
1530 1531
    WordCount totalSize = dataSize + value.pointerCount * WORDS_PER_POINTER;

1532
    word* ptr = allocate(ref, segment, totalSize, WirePointer::STRUCT, orphanArena);
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
    ref->structRef.set(dataSize, value.pointerCount);

    if (value.dataSize == 1 * BITS) {
      *reinterpret_cast<char*>(ptr) = value.getDataField<bool>(0 * ELEMENTS);
    } else {
      memcpy(ptr, value.data, value.dataSize / BITS_PER_BYTE / BYTES);
    }

    WirePointer* pointerSection = reinterpret_cast<WirePointer*>(ptr + dataSize);
    for (uint i = 0; i < value.pointerCount / POINTERS; i++) {
1543 1544
      copyPointer(segment, pointerSection + i, value.segment, value.pointers + i,
                  value.nestingLimit);
1545
    }
1546

1547
    return { segment, ptr };
1548 1549
  }

1550
  static void setCapabilityPointer(
1551
      SegmentBuilder* segment, WirePointer* ref, kj::Own<ClientHook>&& cap,
1552 1553
      BuilderArena* orphanArena = nullptr) {
    if (orphanArena == nullptr) {
1554
      ref->setCap(segment->getArena()->injectCap(kj::mv(cap)));
1555
    } else {
1556
      ref->setCap(orphanArena->injectCap(kj::mv(cap)));
1557 1558 1559
    }
  }

1560 1561 1562
  static SegmentAnd<word*> setListPointer(
      SegmentBuilder* segment, WirePointer* ref, ListReader value,
      BuilderArena* orphanArena = nullptr) {
1563
    WordCount totalSize = roundBitsUpToWords(value.elementCount * value.step);
1564 1565 1566

    if (value.step * ELEMENTS <= BITS_PER_WORD * WORDS) {
      // List of non-structs.
1567
      word* ptr = allocate(ref, segment, totalSize, WirePointer::LIST, orphanArena);
1568 1569 1570 1571 1572

      if (value.structPointerCount == 1 * POINTERS) {
        // List of pointers.
        ref->listRef.set(FieldSize::POINTER, value.elementCount);
        for (uint i = 0; i < value.elementCount / ELEMENTS; i++) {
1573 1574 1575
          copyPointer(segment, reinterpret_cast<WirePointer*>(ptr) + i,
                      value.segment, reinterpret_cast<const WirePointer*>(value.ptr) + i,
                      value.nestingLimit);
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
        }
      } else {
        // List of data.
        FieldSize elementSize = FieldSize::VOID;
        switch (value.step * ELEMENTS / BITS) {
          case 0: elementSize = FieldSize::VOID; break;
          case 1: elementSize = FieldSize::BIT; break;
          case 8: elementSize = FieldSize::BYTE; break;
          case 16: elementSize = FieldSize::TWO_BYTES; break;
          case 32: elementSize = FieldSize::FOUR_BYTES; break;
          case 64: elementSize = FieldSize::EIGHT_BYTES; break;
          default:
1588
            KJ_FAIL_ASSERT("invalid list step size", value.step * ELEMENTS / BITS);
1589 1590 1591 1592 1593 1594
            break;
        }

        ref->listRef.set(elementSize, value.elementCount);
        memcpy(ptr, value.ptr, totalSize * BYTES_PER_WORD / BYTES);
      }
1595

1596
      return { segment, ptr };
1597 1598
    } else {
      // List of structs.
1599 1600
      word* ptr = allocate(ref, segment, totalSize + POINTER_SIZE_IN_WORDS, WirePointer::LIST,
                           orphanArena);
1601 1602
      ref->listRef.setInlineComposite(totalSize);

1603
      WordCount dataSize = roundBitsUpToWords(value.structDataSize);
1604 1605 1606 1607 1608
      WirePointerCount pointerCount = value.structPointerCount;

      WirePointer* tag = reinterpret_cast<WirePointer*>(ptr);
      tag->setKindAndInlineCompositeListElementCount(WirePointer::STRUCT, value.elementCount);
      tag->structRef.set(dataSize, pointerCount);
1609
      word* dst = ptr + POINTER_SIZE_IN_WORDS;
1610 1611 1612

      const word* src = reinterpret_cast<const word*>(value.ptr);
      for (uint i = 0; i < value.elementCount / ELEMENTS; i++) {
1613 1614
        memcpy(dst, src, value.structDataSize / BITS_PER_BYTE / BYTES);
        dst += dataSize;
1615 1616 1617
        src += dataSize;

        for (uint j = 0; j < pointerCount / POINTERS; j++) {
1618 1619
          copyPointer(segment, reinterpret_cast<WirePointer*>(dst),
              value.segment, reinterpret_cast<const WirePointer*>(src), value.nestingLimit);
1620
          dst += POINTER_SIZE_IN_WORDS;
1621 1622 1623
          src += POINTER_SIZE_IN_WORDS;
        }
      }
1624

1625
      return { segment, ptr };
1626 1627 1628
    }
  }

1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
  static KJ_ALWAYS_INLINE(SegmentAnd<word*> copyPointer(
      SegmentBuilder* dstSegment, WirePointer* dst,
      SegmentReader* srcSegment, const WirePointer* src,
      int nestingLimit, BuilderArena* orphanArena = nullptr)) {
    return copyPointer(dstSegment, dst, srcSegment, src, src->target(), nestingLimit, orphanArena);
  }

  static SegmentAnd<word*> copyPointer(
      SegmentBuilder* dstSegment, WirePointer* dst,
      SegmentReader* srcSegment, const WirePointer* src, const word* srcTarget,
      int nestingLimit, BuilderArena* orphanArena = nullptr) {
    // Deep-copy the object pointed to by src into dst.  It turns out we can't reuse
    // readStructPointer(), etc. because they do type checking whereas here we want to accept any
    // valid pointer.

1644
    if (src->isNull()) {
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
    useDefault:
      memset(dst, 0, sizeof(*dst));
      return { dstSegment, nullptr };
    }

    const word* ptr = WireHelpers::followFars(src, srcTarget, srcSegment);
    if (KJ_UNLIKELY(ptr == nullptr)) {
      // Already reported the error.
      goto useDefault;
    }

    switch (src->kind()) {
      case WirePointer::STRUCT:
        KJ_REQUIRE(nestingLimit > 0,
David Renshaw's avatar
David Renshaw committed
1659
              "Message is too deeply-nested or contains cycles.  See capnp::ReaderOptions.") {
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
          goto useDefault;
        }

        KJ_REQUIRE(boundsCheck(srcSegment, ptr, ptr + src->structRef.wordSize()),
                   "Message contained out-of-bounds struct pointer.") {
          goto useDefault;
        }
        return setStructPointer(dstSegment, dst,
            StructReader(srcSegment, ptr,
                         reinterpret_cast<const WirePointer*>(ptr + src->structRef.dataSize.get()),
                         src->structRef.dataSize.get() * BITS_PER_WORD,
                         src->structRef.ptrCount.get(),
                         0 * BITS, nestingLimit - 1),
            orphanArena);

      case WirePointer::LIST: {
        FieldSize elementSize = src->listRef.elementSize();

        KJ_REQUIRE(nestingLimit > 0,
David Renshaw's avatar
David Renshaw committed
1679
              "Message is too deeply-nested or contains cycles.  See capnp::ReaderOptions.") {
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
          goto useDefault;
        }

        if (elementSize == FieldSize::INLINE_COMPOSITE) {
          WordCount wordCount = src->listRef.inlineCompositeWordCount();
          const WirePointer* tag = reinterpret_cast<const WirePointer*>(ptr);
          ptr += POINTER_SIZE_IN_WORDS;

          KJ_REQUIRE(boundsCheck(srcSegment, ptr - POINTER_SIZE_IN_WORDS, ptr + wordCount),
                     "Message contains out-of-bounds list pointer.") {
            goto useDefault;
          }

          KJ_REQUIRE(tag->kind() == WirePointer::STRUCT,
                     "INLINE_COMPOSITE lists of non-STRUCT type are not supported.") {
            goto useDefault;
          }

          ElementCount elementCount = tag->inlineCompositeListElementCount();
          auto wordsPerElement = tag->structRef.wordSize() / ELEMENTS;

          KJ_REQUIRE(wordsPerElement * elementCount <= wordCount,
                     "INLINE_COMPOSITE list's elements overrun its word count.") {
            goto useDefault;
          }

          return setListPointer(dstSegment, dst,
              ListReader(srcSegment, ptr, elementCount, wordsPerElement * BITS_PER_WORD,
                         tag->structRef.dataSize.get() * BITS_PER_WORD,
                         tag->structRef.ptrCount.get(), nestingLimit - 1),
              orphanArena);
        } else {
          BitCount dataSize = dataBitsPerElement(elementSize) * ELEMENTS;
          WirePointerCount pointerCount = pointersPerElement(elementSize) * ELEMENTS;
          auto step = (dataSize + pointerCount * BITS_PER_POINTER) / ELEMENTS;
          ElementCount elementCount = src->listRef.elementCount();
          WordCount wordCount = roundBitsUpToWords(ElementCount64(elementCount) * step);

          KJ_REQUIRE(boundsCheck(srcSegment, ptr, ptr + wordCount),
                     "Message contains out-of-bounds list pointer.") {
            goto useDefault;
          }

          return setListPointer(dstSegment, dst,
              ListReader(srcSegment, ptr, elementCount, step, dataSize, pointerCount,
                         nestingLimit - 1),
              orphanArena);
        }
      }

1730 1731
      case WirePointer::FAR:
        KJ_FAIL_ASSERT("Far pointer should have been handled above.") {
1732 1733 1734
          goto useDefault;
        }

1735 1736
      case WirePointer::OTHER: {
        KJ_REQUIRE(src->isCapability(), "Unknown pointer type.") {
1737 1738 1739
          goto useDefault;
        }

1740 1741 1742
        KJ_IF_MAYBE(cap, srcSegment->getArena()->extractCap(src->capRef.index.get())) {
          setCapabilityPointer(dstSegment, dst, kj::mv(*cap), orphanArena);
          return { dstSegment, nullptr };
1743
        } else {
1744
          KJ_FAIL_REQUIRE("Message contained invalid capability pointer.") {
1745 1746 1747
            goto useDefault;
          }
        }
1748
      }
1749
    }
Kenton Varda's avatar
Kenton Varda committed
1750 1751

    KJ_UNREACHABLE;
1752 1753
  }

1754
  static void adopt(SegmentBuilder* segment, WirePointer* ref, OrphanBuilder&& value) {
1755
    KJ_REQUIRE(value.segment == nullptr || value.segment->getArena() == segment->getArena(),
1756 1757 1758 1759 1760 1761
               "Adopted object must live in the same message.");

    if (!ref->isNull()) {
      zeroObject(segment, ref);
    }

1762
    if (value == nullptr) {
1763 1764
      // Set null.
      memset(ref, 0, sizeof(*ref));
1765
    } else if (value.tagAsPtr()->isPositional()) {
1766
      WireHelpers::transferPointer(segment, ref, value.segment, value.tagAsPtr(), value.location);
1767 1768 1769
    } else {
      // FAR and OTHER pointers are position-independent, so we can just copy.
      memcpy(ref, value.tagAsPtr(), sizeof(WirePointer));
1770 1771 1772 1773 1774 1775 1776 1777 1778
    }

    // Take ownership away from the OrphanBuilder.
    memset(value.tagAsPtr(), 0, sizeof(WirePointer));
    value.location = nullptr;
    value.segment = nullptr;
  }

  static OrphanBuilder disown(SegmentBuilder* segment, WirePointer* ref) {
1779 1780 1781 1782
    word* location;

    if (ref->isNull()) {
      location = nullptr;
1783 1784 1785
    } else if (ref->kind() == WirePointer::OTHER) {
      KJ_REQUIRE(ref->isCapability(), "Unknown pointer type.") { break; }
      location = reinterpret_cast<word*>(ref);  // dummy so that it is non-null
1786 1787
    } else {
      WirePointer* refCopy = ref;
1788
      location = followFarsNoWritableCheck(refCopy, ref->target(), segment);
1789 1790 1791
    }

    OrphanBuilder result(ref, segment, location);
1792

1793
    if (!ref->isNull() && ref->isPositional()) {
1794
      result.tagAsPtr()->setKindForOrphan(ref->kind());
1795
    }
1796 1797 1798 1799 1800

    // Zero out the pointer that was disowned.
    memset(ref, 0, sizeof(*ref));

    return result;
1801 1802
  }

1803 1804
  // -----------------------------------------------------------------

1805
  static KJ_ALWAYS_INLINE(StructReader readStructPointer(
1806
      SegmentReader* segment, const WirePointer* ref, const word* defaultValue,
1807
      int nestingLimit)) {
1808 1809 1810 1811 1812 1813
    return readStructPointer(segment, ref, ref->target(), defaultValue, nestingLimit);
  }

  static KJ_ALWAYS_INLINE(StructReader readStructPointer(
      SegmentReader* segment, const WirePointer* ref, const word* refTarget,
      const word* defaultValue, int nestingLimit)) {
1814
    if (ref->isNull()) {
1815
    useDefault:
Kenton Varda's avatar
Kenton Varda committed
1816
      if (defaultValue == nullptr ||
1817
          reinterpret_cast<const WirePointer*>(defaultValue)->isNull()) {
1818
        return StructReader();
1819
      }
1820
      segment = nullptr;
1821
      ref = reinterpret_cast<const WirePointer*>(defaultValue);
1822
      refTarget = ref->target();
1823 1824
      defaultValue = nullptr;  // If the default value is itself invalid, don't use it again.
    }
1825

1826
    KJ_REQUIRE(nestingLimit > 0,
David Renshaw's avatar
David Renshaw committed
1827
               "Message is too deeply-nested or contains cycles.  See capnp::ReaderOptions.") {
1828 1829
      goto useDefault;
    }
1830

1831
    const word* ptr = followFars(ref, refTarget, segment);
1832
    if (KJ_UNLIKELY(ptr == nullptr)) {
1833 1834 1835
      // Already reported the error.
      goto useDefault;
    }
1836

1837 1838
    KJ_REQUIRE(ref->kind() == WirePointer::STRUCT,
               "Message contains non-struct pointer where struct pointer was expected.") {
1839 1840 1841
      goto useDefault;
    }

1842 1843
    KJ_REQUIRE(boundsCheck(segment, ptr, ptr + ref->structRef.wordSize()),
               "Message contained out-of-bounds struct pointer.") {
1844
      goto useDefault;
1845
    }
1846

1847
    return StructReader(
1848
        segment, ptr, reinterpret_cast<const WirePointer*>(ptr + ref->structRef.dataSize.get()),
1849
        ref->structRef.dataSize.get() * BITS_PER_WORD,
1850
        ref->structRef.ptrCount.get(),
1851
        0 * BITS, nestingLimit - 1);
1852 1853
  }

1854 1855 1856 1857
  static KJ_ALWAYS_INLINE(kj::Own<ClientHook> readCapabilityPointer(
      SegmentReader* segment, const WirePointer* ref, int nestingLimit)) {
    kj::Maybe<kj::Own<ClientHook>> maybeCap;

1858 1859 1860 1861 1862 1863
    KJ_REQUIRE(brokenCapFactory != nullptr,
               "Trying to read capabilities without ever having created a capability context.  "
               "To read capabilities from a message, you must imbue it with CapReaderContext, or "
               "use the Cap'n Proto RPC system.");

    if (ref->isNull()) {
1864
      return brokenCapFactory->newBrokenCap("Calling null capability pointer.");
1865 1866 1867 1868 1869
    } else if (!ref->isCapability()) {
      KJ_FAIL_REQUIRE(
          "Message contains non-capability pointer where capability pointer was expected.") {
        break;
      }
1870
      return brokenCapFactory->newBrokenCap(
1871
          "Calling capability extracted from a non-capability pointer.");
1872
    } else KJ_IF_MAYBE(cap, segment->getArena()->extractCap(ref->capRef.index.get())) {
1873 1874
      return kj::mv(*cap);
    } else {
1875 1876 1877 1878
      KJ_FAIL_REQUIRE("Message contains invalid capability pointer.") {
        break;
      }
      return brokenCapFactory->newBrokenCap("Calling invalid capability pointer.");
1879 1880 1881
    }
  }

1882
  static KJ_ALWAYS_INLINE(ListReader readListPointer(
1883
      SegmentReader* segment, const WirePointer* ref, const word* defaultValue,
1884
      FieldSize expectedElementSize, int nestingLimit)) {
1885 1886 1887 1888 1889 1890 1891
    return readListPointer(segment, ref, ref->target(), defaultValue,
                           expectedElementSize, nestingLimit);
  }

  static KJ_ALWAYS_INLINE(ListReader readListPointer(
      SegmentReader* segment, const WirePointer* ref, const word* refTarget,
      const word* defaultValue, FieldSize expectedElementSize, int nestingLimit)) {
1892
    if (ref->isNull()) {
1893
    useDefault:
Kenton Varda's avatar
Kenton Varda committed
1894
      if (defaultValue == nullptr ||
1895
          reinterpret_cast<const WirePointer*>(defaultValue)->isNull()) {
1896
        return ListReader();
1897
      }
1898
      segment = nullptr;
1899
      ref = reinterpret_cast<const WirePointer*>(defaultValue);
1900
      refTarget = ref->target();
1901 1902
      defaultValue = nullptr;  // If the default value is itself invalid, don't use it again.
    }
1903

1904
    KJ_REQUIRE(nestingLimit > 0,
David Renshaw's avatar
David Renshaw committed
1905
               "Message is too deeply-nested or contains cycles.  See capnp::ReaderOptions.") {
1906 1907
      goto useDefault;
    }
1908

1909
    const word* ptr = followFars(ref, refTarget, segment);
1910
    if (KJ_UNLIKELY(ptr == nullptr)) {
1911 1912 1913 1914
      // Already reported error.
      goto useDefault;
    }

1915 1916
    KJ_REQUIRE(ref->kind() == WirePointer::LIST,
               "Message contains non-list pointer where list pointer was expected.") {
1917
      goto useDefault;
1918 1919
    }

1920
    if (ref->listRef.elementSize() == FieldSize::INLINE_COMPOSITE) {
1921
      decltype(WORDS/ELEMENTS) wordsPerElement;
1922
      ElementCount size;
1923

1924
      WordCount wordCount = ref->listRef.inlineCompositeWordCount();
1925

1926 1927 1928
      // An INLINE_COMPOSITE list points to a tag, which is formatted like a pointer.
      const WirePointer* tag = reinterpret_cast<const WirePointer*>(ptr);
      ptr += POINTER_SIZE_IN_WORDS;
1929

1930 1931
      KJ_REQUIRE(boundsCheck(segment, ptr - POINTER_SIZE_IN_WORDS, ptr + wordCount),
                 "Message contains out-of-bounds list pointer.") {
1932 1933
        goto useDefault;
      }
1934

1935 1936
      KJ_REQUIRE(tag->kind() == WirePointer::STRUCT,
                 "INLINE_COMPOSITE lists of non-STRUCT type are not supported.") {
1937 1938
        goto useDefault;
      }
1939

1940 1941
      size = tag->inlineCompositeListElementCount();
      wordsPerElement = tag->structRef.wordSize() / ELEMENTS;
1942

1943 1944
      KJ_REQUIRE(size * wordsPerElement <= wordCount,
                 "INLINE_COMPOSITE list's elements overrun its word count.") {
1945 1946
        goto useDefault;
      }
1947

1948 1949 1950 1951
      // If a struct list was not expected, then presumably a non-struct list was upgraded to a
      // struct list.  We need to manipulate the pointer to point at the first field of the
      // struct.  Together with the "stepBits", this will allow the struct list to be accessed as
      // if it were a primitive list without branching.
1952

1953 1954 1955 1956
      // Check whether the size is compatible.
      switch (expectedElementSize) {
        case FieldSize::VOID:
          break;
1957

1958 1959 1960 1961 1962
        case FieldSize::BIT:
        case FieldSize::BYTE:
        case FieldSize::TWO_BYTES:
        case FieldSize::FOUR_BYTES:
        case FieldSize::EIGHT_BYTES:
1963 1964
          KJ_REQUIRE(tag->structRef.dataSize.get() > 0 * WORDS,
                     "Expected a primitive list, but got a list of pointer-only structs.") {
1965 1966 1967
            goto useDefault;
          }
          break;
1968

1969 1970 1971
        case FieldSize::POINTER:
          // We expected a list of pointers but got a list of structs.  Assuming the first field
          // in the struct is the pointer we were looking for, we want to munge the pointer to
1972
          // point at the first element's pointer section.
1973
          ptr += tag->structRef.dataSize.get();
1974 1975
          KJ_REQUIRE(tag->structRef.ptrCount.get() > 0 * POINTERS,
                     "Expected a pointer list, but got a list of data-only structs.") {
1976 1977 1978 1979 1980 1981
            goto useDefault;
          }
          break;

        case FieldSize::INLINE_COMPOSITE:
          break;
1982 1983
      }

1984
      return ListReader(
1985 1986
          segment, ptr, size, wordsPerElement * BITS_PER_WORD,
          tag->structRef.dataSize.get() * BITS_PER_WORD,
1987
          tag->structRef.ptrCount.get(), nestingLimit - 1);
1988 1989

    } else {
1990
      // This is a primitive or pointer list, but all such lists can also be interpreted as struct
1991
      // lists.  We need to compute the data size and pointer count for such structs.
1992
      BitCount dataSize = dataBitsPerElement(ref->listRef.elementSize()) * ELEMENTS;
1993
      WirePointerCount pointerCount =
1994
          pointersPerElement(ref->listRef.elementSize()) * ELEMENTS;
1995
      auto step = (dataSize + pointerCount * BITS_PER_POINTER) / ELEMENTS;
1996

1997
      KJ_REQUIRE(boundsCheck(segment, ptr, ptr +
1998
                     roundBitsUpToWords(ElementCount64(ref->listRef.elementCount()) * step)),
1999
                 "Message contains out-of-bounds list pointer.") {
2000
        goto useDefault;
2001 2002
      }

2003 2004 2005 2006
      // Verify that the elements are at least as large as the expected type.  Note that if we
      // expected INLINE_COMPOSITE, the expected sizes here will be zero, because bounds checking
      // will be performed at field access time.  So this check here is for the case where we
      // expected a list of some primitive or pointer type.
2007

2008 2009 2010 2011
      BitCount expectedDataBitsPerElement =
          dataBitsPerElement(expectedElementSize) * ELEMENTS;
      WirePointerCount expectedPointersPerElement =
          pointersPerElement(expectedElementSize) * ELEMENTS;
2012

2013 2014
      KJ_REQUIRE(expectedDataBitsPerElement <= dataSize,
                 "Message contained list with incompatible element type.") {
2015 2016
        goto useDefault;
      }
2017 2018
      KJ_REQUIRE(expectedPointersPerElement <= pointerCount,
                 "Message contained list with incompatible element type.") {
2019
        goto useDefault;
2020
      }
2021 2022

      return ListReader(segment, ptr, ref->listRef.elementCount(), step,
2023
                        dataSize, pointerCount, nestingLimit - 1);
2024 2025
    }
  }
Kenton Varda's avatar
Kenton Varda committed
2026

2027
  static KJ_ALWAYS_INLINE(Text::Reader readTextPointer(
2028
      SegmentReader* segment, const WirePointer* ref,
Kenton Varda's avatar
Kenton Varda committed
2029
      const void* defaultValue, ByteCount defaultSize)) {
2030 2031 2032 2033 2034 2035
    return readTextPointer(segment, ref, ref->target(), defaultValue, defaultSize);
  }

  static KJ_ALWAYS_INLINE(Text::Reader readTextPointer(
      SegmentReader* segment, const WirePointer* ref, const word* refTarget,
      const void* defaultValue, ByteCount defaultSize)) {
2036
    if (ref->isNull()) {
Kenton Varda's avatar
Kenton Varda committed
2037
    useDefault:
2038
      if (defaultValue == nullptr) defaultValue = "";
Kenton Varda's avatar
Kenton Varda committed
2039 2040
      return Text::Reader(reinterpret_cast<const char*>(defaultValue), defaultSize / BYTES);
    } else {
2041
      const word* ptr = followFars(ref, refTarget, segment);
Kenton Varda's avatar
Kenton Varda committed
2042

2043
      if (KJ_UNLIKELY(ptr == nullptr)) {
2044
        // Already reported error.
Kenton Varda's avatar
Kenton Varda committed
2045 2046 2047
        goto useDefault;
      }

2048 2049
      uint size = ref->listRef.elementCount() / ELEMENTS;

2050 2051
      KJ_REQUIRE(ref->kind() == WirePointer::LIST,
                 "Message contains non-list pointer where text was expected.") {
Kenton Varda's avatar
Kenton Varda committed
2052 2053 2054
        goto useDefault;
      }

2055 2056
      KJ_REQUIRE(ref->listRef.elementSize() == FieldSize::BYTE,
                 "Message contains list pointer of non-bytes where text was expected.") {
Kenton Varda's avatar
Kenton Varda committed
2057 2058 2059
        goto useDefault;
      }

2060
      KJ_REQUIRE(boundsCheck(segment, ptr, ptr +
2061
                     roundBytesUpToWords(ref->listRef.elementCount() * (1 * BYTES / ELEMENTS))),
2062
                 "Message contained out-of-bounds text pointer.") {
Kenton Varda's avatar
Kenton Varda committed
2063 2064 2065
        goto useDefault;
      }

2066
      KJ_REQUIRE(size > 0, "Message contains text that is not NUL-terminated.") {
2067 2068 2069
        goto useDefault;
      }

Kenton Varda's avatar
Kenton Varda committed
2070 2071 2072
      const char* cptr = reinterpret_cast<const char*>(ptr);
      --size;  // NUL terminator

2073
      KJ_REQUIRE(cptr[size] == '\0', "Message contains text that is not NUL-terminated.") {
Kenton Varda's avatar
Kenton Varda committed
2074 2075 2076 2077 2078 2079 2080
        goto useDefault;
      }

      return Text::Reader(cptr, size);
    }
  }

2081
  static KJ_ALWAYS_INLINE(Data::Reader readDataPointer(
2082
      SegmentReader* segment, const WirePointer* ref,
Kenton Varda's avatar
Kenton Varda committed
2083
      const void* defaultValue, ByteCount defaultSize)) {
2084 2085 2086 2087 2088 2089
    return readDataPointer(segment, ref, ref->target(), defaultValue, defaultSize);
  }

  static KJ_ALWAYS_INLINE(Data::Reader readDataPointer(
      SegmentReader* segment, const WirePointer* ref, const word* refTarget,
      const void* defaultValue, ByteCount defaultSize)) {
2090
    if (ref->isNull()) {
Kenton Varda's avatar
Kenton Varda committed
2091
    useDefault:
2092
      return Data::Reader(reinterpret_cast<const byte*>(defaultValue), defaultSize / BYTES);
Kenton Varda's avatar
Kenton Varda committed
2093
    } else {
2094
      const word* ptr = followFars(ref, refTarget, segment);
Kenton Varda's avatar
Kenton Varda committed
2095

2096
      if (KJ_UNLIKELY(ptr == nullptr)) {
2097
        // Already reported error.
Kenton Varda's avatar
Kenton Varda committed
2098 2099 2100
        goto useDefault;
      }

2101 2102
      uint size = ref->listRef.elementCount() / ELEMENTS;

2103 2104
      KJ_REQUIRE(ref->kind() == WirePointer::LIST,
                 "Message contains non-list pointer where data was expected.") {
Kenton Varda's avatar
Kenton Varda committed
2105 2106 2107
        goto useDefault;
      }

2108 2109
      KJ_REQUIRE(ref->listRef.elementSize() == FieldSize::BYTE,
                 "Message contains list pointer of non-bytes where data was expected.") {
Kenton Varda's avatar
Kenton Varda committed
2110 2111 2112
        goto useDefault;
      }

2113
      KJ_REQUIRE(boundsCheck(segment, ptr, ptr +
2114
                     roundBytesUpToWords(ref->listRef.elementCount() * (1 * BYTES / ELEMENTS))),
2115
                 "Message contained out-of-bounds data pointer.") {
Kenton Varda's avatar
Kenton Varda committed
2116 2117 2118
        goto useDefault;
      }

2119
      return Data::Reader(reinterpret_cast<const byte*>(ptr), size);
Kenton Varda's avatar
Kenton Varda committed
2120 2121
    }
  }
2122 2123 2124
};

// =======================================================================================
2125
// PointerBuilder
2126

2127 2128
StructBuilder PointerBuilder::initStruct(StructSize size) {
  return WireHelpers::initStructPointer(pointer, segment, size);
2129 2130
}

2131 2132
StructBuilder PointerBuilder::getStruct(StructSize size, const word* defaultValue) {
  return WireHelpers::getWritableStructPointer(pointer, segment, size, defaultValue);
2133 2134
}

2135 2136
ListBuilder PointerBuilder::initList(FieldSize elementSize, ElementCount elementCount) {
  return WireHelpers::initListPointer(pointer, segment, elementCount, elementSize);
2137 2138
}

2139 2140
ListBuilder PointerBuilder::initStructList(ElementCount elementCount, StructSize elementSize) {
  return WireHelpers::initStructListPointer(pointer, segment, elementCount, elementSize);
2141 2142
}

2143 2144
ListBuilder PointerBuilder::getList(FieldSize elementSize, const word* defaultValue) {
  return WireHelpers::getWritableListPointer(pointer, segment, elementSize, defaultValue);
2145
}
2146

2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
ListBuilder PointerBuilder::getStructList(StructSize elementSize, const word* defaultValue) {
  return WireHelpers::getWritableStructListPointer(pointer, segment, elementSize, defaultValue);
}

template <>
Text::Builder PointerBuilder::initBlob<Text>(ByteCount size) {
  return WireHelpers::initTextPointer(pointer, segment, size).value;
}
template <>
void PointerBuilder::setBlob<Text>(Text::Reader value) {
  WireHelpers::setTextPointer(pointer, segment, value);
}
template <>
Text::Builder PointerBuilder::getBlob<Text>(const void* defaultValue, ByteCount defaultSize) {
  return WireHelpers::getWritableTextPointer(pointer, segment, defaultValue, defaultSize);
2162 2163
}

2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
template <>
Data::Builder PointerBuilder::initBlob<Data>(ByteCount size) {
  return WireHelpers::initDataPointer(pointer, segment, size).value;
}
template <>
void PointerBuilder::setBlob<Data>(Data::Reader value) {
  WireHelpers::setDataPointer(pointer, segment, value);
}
template <>
Data::Builder PointerBuilder::getBlob<Data>(const void* defaultValue, ByteCount defaultSize) {
  return WireHelpers::getWritableDataPointer(pointer, segment, defaultValue, defaultSize);
2175 2176
}

2177 2178
void PointerBuilder::setStruct(const StructReader& value) {
  WireHelpers::setStructPointer(segment, pointer, value);
2179 2180
}

2181 2182
void PointerBuilder::setList(const ListReader& value) {
  WireHelpers::setListPointer(segment, pointer, value);
2183 2184
}

2185
kj::Own<ClientHook> PointerBuilder::getCapability() {
2186
  return WireHelpers::readCapabilityPointer(
2187
      segment, pointer, kj::maxValue);
2188 2189
}

2190
void PointerBuilder::setCapability(kj::Own<ClientHook>&& cap) {
2191 2192 2193
  WireHelpers::setCapabilityPointer(segment, pointer, kj::mv(cap));
}

2194 2195
void PointerBuilder::adopt(OrphanBuilder&& value) {
  WireHelpers::adopt(segment, pointer, kj::mv(value));
Kenton Varda's avatar
Kenton Varda committed
2196
}
2197 2198 2199

OrphanBuilder PointerBuilder::disown() {
  return WireHelpers::disown(segment, pointer);
Kenton Varda's avatar
Kenton Varda committed
2200 2201
}

2202 2203 2204 2205 2206 2207 2208
void PointerBuilder::clear() {
  WireHelpers::zeroObject(segment, pointer);
  memset(pointer, 0, sizeof(WirePointer));
}

bool PointerBuilder::isNull() {
  return pointer->isNull();
Kenton Varda's avatar
Kenton Varda committed
2209
}
2210

2211 2212 2213 2214 2215
void PointerBuilder::transferFrom(PointerBuilder other) {
  WireHelpers::transferPointer(segment, pointer, other.segment, other.pointer);
}

void PointerBuilder::copyFrom(PointerReader other) {
2216
  WireHelpers::copyPointer(segment, pointer, other.segment, other.pointer, other.nestingLimit);
2217 2218 2219
}

PointerReader PointerBuilder::asReader() const {
2220
  return PointerReader(segment, pointer, kj::maxValue);
2221 2222
}

2223 2224
BuilderArena* PointerBuilder::getArena() const {
  return segment->getArena();
2225 2226
}

2227 2228 2229
// =======================================================================================
// PointerReader

Kenton Varda's avatar
Kenton Varda committed
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
PointerReader PointerReader::getRoot(SegmentReader* segment, const word* location,
                                     int nestingLimit) {
  KJ_REQUIRE(WireHelpers::boundsCheck(segment, location, location + POINTER_SIZE_IN_WORDS),
             "Root location out-of-bounds.") {
    location = nullptr;
  }

  return PointerReader(segment, reinterpret_cast<const WirePointer*>(location), nestingLimit);
}

2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
StructReader PointerReader::getStruct(const word* defaultValue) const {
  const WirePointer* ref = pointer == nullptr ? &zero.pointer : pointer;
  return WireHelpers::readStructPointer(segment, ref, defaultValue, nestingLimit);
}

ListReader PointerReader::getList(FieldSize expectedElementSize, const word* defaultValue) const {
  const WirePointer* ref = pointer == nullptr ? &zero.pointer : pointer;
  return WireHelpers::readListPointer(
      segment, ref, defaultValue, expectedElementSize, nestingLimit);
}

2251
template <>
2252 2253 2254
Text::Reader PointerReader::getBlob<Text>(const void* defaultValue, ByteCount defaultSize) const {
  const WirePointer* ref = pointer == nullptr ? &zero.pointer : pointer;
  return WireHelpers::readTextPointer(segment, ref, defaultValue, defaultSize);
Kenton Varda's avatar
Kenton Varda committed
2255
}
2256

2257
template <>
2258 2259 2260
Data::Reader PointerReader::getBlob<Data>(const void* defaultValue, ByteCount defaultSize) const {
  const WirePointer* ref = pointer == nullptr ? &zero.pointer : pointer;
  return WireHelpers::readDataPointer(segment, ref, defaultValue, defaultSize);
Kenton Varda's avatar
Kenton Varda committed
2261 2262
}

2263
kj::Own<ClientHook> PointerReader::getCapability() const {
2264 2265 2266 2267
  const WirePointer* ref = pointer == nullptr ? &zero.pointer : pointer;
  return WireHelpers::readCapabilityPointer(segment, ref, nestingLimit);
}

2268 2269 2270
const word* PointerReader::getUnchecked() const {
  KJ_REQUIRE(segment == nullptr, "getUncheckedPointer() only allowed on unchecked messages.");
  return reinterpret_cast<const word*>(pointer);
2271 2272
}

2273
MessageSizeCounts PointerReader::targetSize() const {
Kenton Varda's avatar
Kenton Varda committed
2274 2275 2276
  return WireHelpers::totalSize(segment, pointer, nestingLimit);
}

2277 2278
bool PointerReader::isNull() const {
  return pointer == nullptr || pointer->isNull();
2279 2280
}

2281 2282 2283 2284
kj::Maybe<Arena&> PointerReader::getArena() const {
  return segment == nullptr ? nullptr : segment->getArena();
}

2285 2286 2287
// =======================================================================================
// StructBuilder

2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
void StructBuilder::clearAll() {
  if (dataSize == 1 * BITS) {
    setDataField<bool>(1 * ELEMENTS, false);
  } else {
    memset(data, 0, dataSize / BITS_PER_BYTE / BYTES);
  }

  for (uint i = 0; i < pointerCount / POINTERS; i++) {
    WireHelpers::zeroObject(segment, pointers + i);
  }
  memset(pointers, 0, pointerCount * BYTES_PER_POINTER / BYTES);
}

2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326
void StructBuilder::transferContentFrom(StructBuilder other) {
  // Determine the amount of data the builders have in common.
  BitCount sharedDataSize = kj::min(dataSize, other.dataSize);

  if (dataSize > sharedDataSize) {
    // Since the target is larger than the source, make sure to zero out the extra bits that the
    // source doesn't have.
    if (dataSize == 1 * BITS) {
      setDataField<bool>(0 * ELEMENTS, false);
    } else {
      byte* unshared = reinterpret_cast<byte*>(data) + sharedDataSize / BITS_PER_BYTE / BYTES;
      memset(unshared, 0, (dataSize - sharedDataSize) / BITS_PER_BYTE / BYTES);
    }
  }

  // Copy over the shared part.
  if (sharedDataSize == 1 * BITS) {
    setDataField<bool>(0 * ELEMENTS, other.getDataField<bool>(0 * ELEMENTS));
  } else {
    memcpy(data, other.data, sharedDataSize / BITS_PER_BYTE / BYTES);
  }

  // Zero out all pointers in the target.
  for (uint i = 0; i < pointerCount / POINTERS; i++) {
    WireHelpers::zeroObject(segment, pointers + i);
  }
2327
  memset(pointers, 0, pointerCount * BYTES_PER_POINTER / BYTES);
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340

  // Transfer the pointers.
  WirePointerCount sharedPointerCount = kj::min(pointerCount, other.pointerCount);
  for (uint i = 0; i < sharedPointerCount / POINTERS; i++) {
    WireHelpers::transferPointer(segment, pointers + i, other.segment, other.pointers + i);
  }

  // Zero out the pointers that were transferred in the source because it no longer has ownership.
  // If the source had any extra pointers that the destination didn't have space for, we
  // intentionally leave them be, so that they'll be cleaned up later.
  memset(other.pointers, 0, sharedPointerCount * BYTES_PER_POINTER / BYTES);
}

2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
void StructBuilder::copyContentFrom(StructReader other) {
  // Determine the amount of data the builders have in common.
  BitCount sharedDataSize = kj::min(dataSize, other.dataSize);

  if (dataSize > sharedDataSize) {
    // Since the target is larger than the source, make sure to zero out the extra bits that the
    // source doesn't have.
    if (dataSize == 1 * BITS) {
      setDataField<bool>(0 * ELEMENTS, false);
    } else {
      byte* unshared = reinterpret_cast<byte*>(data) + sharedDataSize / BITS_PER_BYTE / BYTES;
      memset(unshared, 0, (dataSize - sharedDataSize) / BITS_PER_BYTE / BYTES);
    }
  }

  // Copy over the shared part.
  if (sharedDataSize == 1 * BITS) {
    setDataField<bool>(0 * ELEMENTS, other.getDataField<bool>(0 * ELEMENTS));
  } else {
    memcpy(data, other.data, sharedDataSize / BITS_PER_BYTE / BYTES);
  }

  // Zero out all pointers in the target.
  for (uint i = 0; i < pointerCount / POINTERS; i++) {
    WireHelpers::zeroObject(segment, pointers + i);
  }
  memset(pointers, 0, pointerCount * BYTES_PER_POINTER / BYTES);

  // Copy the pointers.
  WirePointerCount sharedPointerCount = kj::min(pointerCount, other.pointerCount);
  for (uint i = 0; i < sharedPointerCount / POINTERS; i++) {
2372 2373
    WireHelpers::copyPointer(segment, pointers + i,
        other.segment, other.pointers + i, other.nestingLimit);
2374 2375 2376
  }
}

2377
StructReader StructBuilder::asReader() const {
2378
  return StructReader(segment, data, pointers,
2379
      dataSize, pointerCount, bit0Offset, kj::maxValue);
2380 2381
}

2382 2383 2384 2385
BuilderArena* StructBuilder::getArena() {
  return segment->getArena();
}

2386 2387 2388
// =======================================================================================
// StructReader

2389 2390 2391
MessageSizeCounts StructReader::totalSize() const {
  MessageSizeCounts result = {
    WireHelpers::roundBitsUpToWords(dataSize) + pointerCount * WORDS_PER_POINTER, 0 };
2392 2393 2394 2395 2396 2397 2398 2399

  for (uint i = 0; i < pointerCount / POINTERS; i++) {
    result += WireHelpers::totalSize(segment, pointers + i, nestingLimit);
  }

  if (segment != nullptr) {
    // This traversal should not count against the read limit, because it's highly likely that
    // the caller is going to traverse the object again, e.g. to copy it.
2400
    segment->unread(result.wordCount);
2401 2402 2403 2404 2405
  }

  return result;
}

2406 2407 2408
// =======================================================================================
// ListBuilder

2409
Text::Builder ListBuilder::asText() {
2410 2411
  KJ_REQUIRE(structDataSize == 8 * BITS && structPointerCount == 0 * POINTERS,
             "Expected Text, got list of non-bytes.") {
2412 2413 2414 2415 2416
    return Text::Builder();
  }

  size_t size = elementCount / ELEMENTS;

2417
  KJ_REQUIRE(size > 0, "Message contains text that is not NUL-terminated.") {
2418 2419 2420 2421 2422 2423
    return Text::Builder();
  }

  char* cptr = reinterpret_cast<char*>(ptr);
  --size;  // NUL terminator

2424
  KJ_REQUIRE(cptr[size] == '\0', "Message contains text that is not NUL-terminated.") {
2425 2426 2427 2428 2429 2430 2431
    return Text::Builder();
  }

  return Text::Builder(cptr, size);
}

Data::Builder ListBuilder::asData() {
2432 2433
  KJ_REQUIRE(structDataSize == 8 * BITS && structPointerCount == 0 * POINTERS,
             "Expected Text, got list of non-bytes.") {
2434 2435 2436
    return Data::Builder();
  }

2437
  return Data::Builder(reinterpret_cast<byte*>(ptr), elementCount / ELEMENTS);
2438 2439
}

2440
StructBuilder ListBuilder::getStructElement(ElementCount index) {
2441 2442
  BitCount64 indexBit = ElementCount64(index) * step;
  byte* structData = ptr + indexBit / BITS_PER_BYTE;
2443
  return StructBuilder(segment, structData,
2444 2445
      reinterpret_cast<WirePointer*>(structData + structDataSize / BITS_PER_BYTE),
      structDataSize, structPointerCount, indexBit % BITS_PER_BYTE);
2446 2447
}

2448
ListReader ListBuilder::asReader() const {
2449
  return ListReader(segment, ptr, elementCount, step, structDataSize, structPointerCount,
2450
                    kj::maxValue);
2451 2452
}

2453 2454 2455 2456
BuilderArena* ListBuilder::getArena() {
  return segment->getArena();
}

2457 2458 2459
// =======================================================================================
// ListReader

2460
Text::Reader ListReader::asText() {
2461 2462
  KJ_REQUIRE(structDataSize == 8 * BITS && structPointerCount == 0 * POINTERS,
             "Expected Text, got list of non-bytes.") {
2463 2464 2465 2466 2467
    return Text::Reader();
  }

  size_t size = elementCount / ELEMENTS;

2468
  KJ_REQUIRE(size > 0, "Message contains text that is not NUL-terminated.") {
2469 2470 2471 2472 2473 2474
    return Text::Reader();
  }

  const char* cptr = reinterpret_cast<const char*>(ptr);
  --size;  // NUL terminator

2475
  KJ_REQUIRE(cptr[size] == '\0', "Message contains text that is not NUL-terminated.") {
2476 2477 2478 2479 2480 2481 2482
    return Text::Reader();
  }

  return Text::Reader(cptr, size);
}

Data::Reader ListReader::asData() {
2483 2484
  KJ_REQUIRE(structDataSize == 8 * BITS && structPointerCount == 0 * POINTERS,
             "Expected Text, got list of non-bytes.") {
2485 2486 2487
    return Data::Reader();
  }

2488
  return Data::Reader(reinterpret_cast<const byte*>(ptr), elementCount / ELEMENTS);
2489 2490
}

2491
StructReader ListReader::getStructElement(ElementCount index) const {
2492
  KJ_REQUIRE(nestingLimit > 0,
David Renshaw's avatar
David Renshaw committed
2493
             "Message is too deeply-nested or contains cycles.  See capnp::ReaderOptions.") {
2494
    return StructReader();
2495
  }
2496

2497 2498
  BitCount64 indexBit = ElementCount64(index) * step;
  const byte* structData = ptr + indexBit / BITS_PER_BYTE;
2499 2500
  const WirePointer* structPointers =
      reinterpret_cast<const WirePointer*>(structData + structDataSize / BITS_PER_BYTE);
2501 2502

  // This check should pass if there are no bugs in the list pointer validation code.
2503
  KJ_DASSERT(structPointerCount == 0 * POINTERS ||
Kenton Varda's avatar
Kenton Varda committed
2504
         (uintptr_t)structPointers % sizeof(void*) == 0,
2505
         "Pointer section of struct list element not aligned.");
2506

2507
  return StructReader(
2508
      segment, structData, structPointers,
2509
      structDataSize, structPointerCount,
2510
      indexBit % BITS_PER_BYTE, nestingLimit - 1);
2511
}
2512

2513 2514 2515 2516 2517
// =======================================================================================
// OrphanBuilder

OrphanBuilder OrphanBuilder::initStruct(BuilderArena* arena, StructSize size) {
  OrphanBuilder result;
2518 2519
  StructBuilder builder = WireHelpers::initStructPointer(result.tagAsPtr(), nullptr, size, arena);
  result.segment = builder.segment;
2520
  result.location = builder.getLocation();
2521 2522 2523 2524 2525 2526
  return result;
}

OrphanBuilder OrphanBuilder::initList(
    BuilderArena* arena, ElementCount elementCount, FieldSize elementSize) {
  OrphanBuilder result;
2527 2528 2529
  ListBuilder builder = WireHelpers::initListPointer(
      result.tagAsPtr(), nullptr, elementCount, elementSize, arena);
  result.segment = builder.segment;
2530
  result.location = builder.getLocation();
2531 2532 2533 2534 2535
  return result;
}

OrphanBuilder OrphanBuilder::initStructList(
    BuilderArena* arena, ElementCount elementCount, StructSize elementSize) {
2536 2537 2538 2539 2540 2541
  OrphanBuilder result;
  ListBuilder builder = WireHelpers::initStructListPointer(
      result.tagAsPtr(), nullptr, elementCount, elementSize, arena);
  result.segment = builder.segment;
  result.location = builder.getLocation();
  return result;
2542 2543 2544 2545
}

OrphanBuilder OrphanBuilder::initText(BuilderArena* arena, ByteCount size) {
  OrphanBuilder result;
2546 2547 2548
  auto allocation = WireHelpers::initTextPointer(result.tagAsPtr(), nullptr, size, arena);
  result.segment = allocation.segment;
  result.location = reinterpret_cast<word*>(allocation.value.begin());
2549 2550 2551 2552 2553
  return result;
}

OrphanBuilder OrphanBuilder::initData(BuilderArena* arena, ByteCount size) {
  OrphanBuilder result;
2554 2555 2556
  auto allocation = WireHelpers::initDataPointer(result.tagAsPtr(), nullptr, size, arena);
  result.segment = allocation.segment;
  result.location = reinterpret_cast<word*>(allocation.value.begin());
2557 2558 2559 2560 2561
  return result;
}

OrphanBuilder OrphanBuilder::copy(BuilderArena* arena, StructReader copyFrom) {
  OrphanBuilder result;
2562 2563 2564
  auto allocation = WireHelpers::setStructPointer(nullptr, result.tagAsPtr(), copyFrom, arena);
  result.segment = allocation.segment;
  result.location = reinterpret_cast<word*>(allocation.value);
2565 2566 2567 2568 2569
  return result;
}

OrphanBuilder OrphanBuilder::copy(BuilderArena* arena, ListReader copyFrom) {
  OrphanBuilder result;
2570 2571 2572
  auto allocation = WireHelpers::setListPointer(nullptr, result.tagAsPtr(), copyFrom, arena);
  result.segment = allocation.segment;
  result.location = reinterpret_cast<word*>(allocation.value);
2573 2574 2575
  return result;
}

2576 2577
OrphanBuilder OrphanBuilder::copy(BuilderArena* arena, PointerReader copyFrom) {
  OrphanBuilder result;
2578 2579
  auto allocation = WireHelpers::copyPointer(
      nullptr, result.tagAsPtr(), copyFrom.segment, copyFrom.pointer, copyFrom.nestingLimit, arena);
2580 2581 2582 2583 2584
  result.segment = allocation.segment;
  result.location = reinterpret_cast<word*>(allocation.value);
  return result;
}

2585 2586
OrphanBuilder OrphanBuilder::copy(BuilderArena* arena, Text::Reader copyFrom) {
  OrphanBuilder result;
2587 2588 2589 2590
  auto allocation = WireHelpers::setTextPointer(
      result.tagAsPtr(), nullptr, copyFrom, arena);
  result.segment = allocation.segment;
  result.location = reinterpret_cast<word*>(allocation.value.begin());
2591 2592 2593 2594 2595
  return result;
}

OrphanBuilder OrphanBuilder::copy(BuilderArena* arena, Data::Reader copyFrom) {
  OrphanBuilder result;
2596 2597 2598 2599
  auto allocation = WireHelpers::setDataPointer(
      result.tagAsPtr(), nullptr, copyFrom, arena);
  result.segment = allocation.segment;
  result.location = reinterpret_cast<word*>(allocation.value.begin());
2600 2601 2602
  return result;
}

2603
OrphanBuilder OrphanBuilder::copy(BuilderArena* arena, kj::Own<ClientHook> copyFrom) {
2604
  OrphanBuilder result;
2605 2606 2607
  WireHelpers::setCapabilityPointer(nullptr, result.tagAsPtr(), kj::mv(copyFrom), arena);
  result.segment = arena->getSegment(SegmentId(0));
  result.location = &result.tag;  // dummy to make location non-null
2608 2609 2610
  return result;
}

2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
OrphanBuilder OrphanBuilder::referenceExternalData(BuilderArena* arena, Data::Reader data) {
  KJ_REQUIRE(reinterpret_cast<uintptr_t>(data.begin()) % sizeof(void*) == 0,
             "Cannot referenceExternalData() that is not aligned.");

  auto wordCount = WireHelpers::roundBytesUpToWords(data.size() * BYTES);
  kj::ArrayPtr<const word> words(reinterpret_cast<const word*>(data.begin()), wordCount / WORDS);

  OrphanBuilder result;
  result.tagAsPtr()->setKindForOrphan(WirePointer::LIST);
  result.tagAsPtr()->listRef.set(FieldSize::BYTE, data.size() * ELEMENTS);
  result.segment = arena->addExternalSegment(words);

  // const_cast OK here because we will check whether the segment is writable when we try to get
  // a builder.
  result.location = const_cast<word*>(words.begin());

  return result;
}

2630
StructBuilder OrphanBuilder::asStruct(StructSize size) {
2631 2632
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));

2633
  StructBuilder result = WireHelpers::getWritableStructPointer(
2634
      tagAsPtr(), location, segment, size, nullptr, segment->getArena());
2635 2636

  // Watch out, the pointer could have been updated if the object had to be relocated.
2637
  location = reinterpret_cast<word*>(result.data);
2638 2639 2640 2641 2642

  return result;
}

ListBuilder OrphanBuilder::asList(FieldSize elementSize) {
2643 2644
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));

2645
  ListBuilder result = WireHelpers::getWritableListPointer(
2646
      tagAsPtr(), location, segment, elementSize, nullptr, segment->getArena());
2647 2648

  // Watch out, the pointer could have been updated if the object had to be relocated.
2649 2650 2651
  // (Actually, currently this is not true for primitive lists, but let's not turn into a bug if
  // it changes!)
  location = result.getLocation();
2652 2653 2654 2655 2656

  return result;
}

ListBuilder OrphanBuilder::asStructList(StructSize elementSize) {
2657 2658
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));

2659
  ListBuilder result = WireHelpers::getWritableStructListPointer(
2660
      tagAsPtr(), location, segment, elementSize, nullptr, segment->getArena());
2661 2662

  // Watch out, the pointer could have been updated if the object had to be relocated.
2663
  location = result.getLocation();
2664 2665 2666 2667 2668

  return result;
}

Text::Builder OrphanBuilder::asText() {
2669 2670
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));

2671 2672 2673 2674 2675
  // Never relocates.
  return WireHelpers::getWritableTextPointer(tagAsPtr(), location, segment, nullptr, 0 * BYTES);
}

Data::Builder OrphanBuilder::asData() {
2676 2677
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));

2678 2679 2680 2681
  // Never relocates.
  return WireHelpers::getWritableDataPointer(tagAsPtr(), location, segment, nullptr, 0 * BYTES);
}

2682
StructReader OrphanBuilder::asStructReader(StructSize size) const {
2683
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));
2684
  return WireHelpers::readStructPointer(
2685
      segment, tagAsPtr(), location, nullptr, kj::maxValue);
2686 2687 2688
}

ListReader OrphanBuilder::asListReader(FieldSize elementSize) const {
2689
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));
2690
  return WireHelpers::readListPointer(
2691
      segment, tagAsPtr(), location, nullptr, elementSize, kj::maxValue);
2692 2693
}

2694
kj::Own<ClientHook> OrphanBuilder::asCapability() const {
2695
  return WireHelpers::readCapabilityPointer(segment, tagAsPtr(), kj::maxValue);
2696 2697
}

2698
Text::Reader OrphanBuilder::asTextReader() const {
2699
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));
2700 2701 2702 2703
  return WireHelpers::readTextPointer(segment, tagAsPtr(), location, nullptr, 0 * BYTES);
}

Data::Reader OrphanBuilder::asDataReader() const {
2704
  KJ_DASSERT(tagAsPtr()->isNull() == (location == nullptr));
2705 2706 2707
  return WireHelpers::readDataPointer(segment, tagAsPtr(), location, nullptr, 0 * BYTES);
}

2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
void OrphanBuilder::truncate(ElementCount size, bool isText) {
  if (isText) size += 1 * ELEMENTS;

  WirePointer* ref = tagAsPtr();
  SegmentBuilder* segment = this->segment;

  word* target = WireHelpers::followFars(ref, location, segment);

  KJ_REQUIRE(ref->kind() == WirePointer::LIST, "Can't truncate non-list.") {
    return;
  }

  // TODO(soon): Implement truncation of all sizes.
  KJ_ASSERT(ref->listRef.elementSize() == FieldSize::BYTE,
            "Not implemented: truncate non-blob.");

  auto oldSize = ref->listRef.elementCount();
  KJ_REQUIRE(size <= oldSize, "Truncate size must be smaller than existing size.") {
    return;
  }

  ref->listRef.set(ref->listRef.elementSize(), size);

  byte* begin = reinterpret_cast<byte*>(target);
  byte* truncPoint = begin + size * (1 * BYTES / ELEMENTS);
  byte* end = begin + oldSize * (1 * BYTES / ELEMENTS);
  memset(truncPoint - isText, 0, end - truncPoint + isText);

  word* truncWord = target + WireHelpers::roundBytesUpToWords(size * (1 * BYTES / ELEMENTS));
  word* endWord = target + WireHelpers::roundBytesUpToWords(oldSize * (1 * BYTES / ELEMENTS));

  segment->tryTruncate(endWord, truncWord);
}

2742
void OrphanBuilder::euthanize() {
2743 2744 2745
  // Carefully catch any exceptions and rethrow them as recoverable exceptions since we may be in
  // a destructor.
  auto exception = kj::runCatchingExceptions([&]() {
2746
    if (tagAsPtr()->isPositional()) {
2747
      WireHelpers::zeroObject(segment, tagAsPtr(), location);
2748 2749
    } else {
      WireHelpers::zeroObject(segment, tagAsPtr());
2750
    }
2751

2752
    memset(&tag, 0, sizeof(tag));
2753 2754 2755 2756 2757 2758 2759
    segment = nullptr;
    location = nullptr;
  });

  KJ_IF_MAYBE(e, exception) {
    kj::getExceptionCallback().onRecoverableException(kj::mv(*e));
  }
2760 2761
}

2762
}  // namespace _ (private)
2763
}  // namespace capnp