annotate win64-msvc/include/capnp/layout.h @ 47:d93140aac40b

Current Capnp libs and headers from git
author Chris Cannam
date Thu, 20 Oct 2016 18:15:38 +0100
parents
children 0f2d93caa50c
rev   line source
Chris@47 1 // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
Chris@47 2 // Licensed under the MIT License:
Chris@47 3 //
Chris@47 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@47 5 // of this software and associated documentation files (the "Software"), to deal
Chris@47 6 // in the Software without restriction, including without limitation the rights
Chris@47 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@47 8 // copies of the Software, and to permit persons to whom the Software is
Chris@47 9 // furnished to do so, subject to the following conditions:
Chris@47 10 //
Chris@47 11 // The above copyright notice and this permission notice shall be included in
Chris@47 12 // all copies or substantial portions of the Software.
Chris@47 13 //
Chris@47 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@47 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@47 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@47 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@47 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@47 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@47 20 // THE SOFTWARE.
Chris@47 21
Chris@47 22 // This file is NOT intended for use by clients, except in generated code.
Chris@47 23 //
Chris@47 24 // This file defines low-level, non-type-safe classes for traversing the Cap'n Proto memory layout
Chris@47 25 // (which is also its wire format). Code generated by the Cap'n Proto compiler uses these classes,
Chris@47 26 // as does other parts of the Cap'n proto library which provide a higher-level interface for
Chris@47 27 // dynamic introspection.
Chris@47 28
Chris@47 29 #ifndef CAPNP_LAYOUT_H_
Chris@47 30 #define CAPNP_LAYOUT_H_
Chris@47 31
Chris@47 32 #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
Chris@47 33 #pragma GCC system_header
Chris@47 34 #endif
Chris@47 35
Chris@47 36 #include <kj/common.h>
Chris@47 37 #include <kj/memory.h>
Chris@47 38 #include "common.h"
Chris@47 39 #include "blob.h"
Chris@47 40 #include "endian.h"
Chris@47 41
Chris@47 42 #if (defined(__mips__) || defined(__hppa__)) && !defined(CAPNP_CANONICALIZE_NAN)
Chris@47 43 #define CAPNP_CANONICALIZE_NAN 1
Chris@47 44 // Explicitly detect NaNs and canonicalize them to the quiet NaN value as would be returned by
Chris@47 45 // __builtin_nan("") on systems implementing the IEEE-754 recommended (but not required) NaN
Chris@47 46 // signalling/quiet differentiation (such as x86). Unfortunately, some architectures -- in
Chris@47 47 // particular, MIPS -- represent quiet vs. signalling nans differently than the rest of the world.
Chris@47 48 // Canonicalizing them makes output consistent (which is important!), but hurts performance
Chris@47 49 // slightly.
Chris@47 50 //
Chris@47 51 // Note that trying to convert MIPS NaNs to standard NaNs without losing data doesn't work.
Chris@47 52 // Signaling vs. quiet is indicated by a bit, with the meaning being the opposite on MIPS vs.
Chris@47 53 // everyone else. It would be great if we could just flip that bit, but we can't, because if the
Chris@47 54 // significand is all-zero, then the value is infinity rather than NaN. This means that on most
Chris@47 55 // machines, where the bit indicates quietness, there is one more quiet NaN value than signalling
Chris@47 56 // NaN value, whereas on MIPS there is one more sNaN than qNaN, and thus there is no isomorphic
Chris@47 57 // mapping that properly preserves quietness. Instead of doing something hacky, we just give up
Chris@47 58 // and blow away NaN payloads, because no one uses them anyway.
Chris@47 59 #endif
Chris@47 60
Chris@47 61 namespace capnp {
Chris@47 62
Chris@47 63 #if !CAPNP_LITE
Chris@47 64 class ClientHook;
Chris@47 65 #endif // !CAPNP_LITE
Chris@47 66
Chris@47 67 namespace _ { // private
Chris@47 68
Chris@47 69 class PointerBuilder;
Chris@47 70 class PointerReader;
Chris@47 71 class StructBuilder;
Chris@47 72 class StructReader;
Chris@47 73 class ListBuilder;
Chris@47 74 class ListReader;
Chris@47 75 class OrphanBuilder;
Chris@47 76 struct WirePointer;
Chris@47 77 struct WireHelpers;
Chris@47 78 class SegmentReader;
Chris@47 79 class SegmentBuilder;
Chris@47 80 class Arena;
Chris@47 81 class BuilderArena;
Chris@47 82
Chris@47 83 // =============================================================================
Chris@47 84
Chris@47 85 typedef decltype(BITS / ELEMENTS) BitsPerElement;
Chris@47 86 typedef decltype(POINTERS / ELEMENTS) PointersPerElement;
Chris@47 87
Chris@47 88 static constexpr BitsPerElement BITS_PER_ELEMENT_TABLE[8] = {
Chris@47 89 0 * BITS / ELEMENTS,
Chris@47 90 1 * BITS / ELEMENTS,
Chris@47 91 8 * BITS / ELEMENTS,
Chris@47 92 16 * BITS / ELEMENTS,
Chris@47 93 32 * BITS / ELEMENTS,
Chris@47 94 64 * BITS / ELEMENTS,
Chris@47 95 0 * BITS / ELEMENTS,
Chris@47 96 0 * BITS / ELEMENTS
Chris@47 97 };
Chris@47 98
Chris@47 99 inline KJ_CONSTEXPR() BitsPerElement dataBitsPerElement(ElementSize size) {
Chris@47 100 return _::BITS_PER_ELEMENT_TABLE[static_cast<int>(size)];
Chris@47 101 }
Chris@47 102
Chris@47 103 inline constexpr PointersPerElement pointersPerElement(ElementSize size) {
Chris@47 104 return size == ElementSize::POINTER ? 1 * POINTERS / ELEMENTS : 0 * POINTERS / ELEMENTS;
Chris@47 105 }
Chris@47 106
Chris@47 107 template <size_t size> struct ElementSizeForByteSize;
Chris@47 108 template <> struct ElementSizeForByteSize<1> { static constexpr ElementSize value = ElementSize::BYTE; };
Chris@47 109 template <> struct ElementSizeForByteSize<2> { static constexpr ElementSize value = ElementSize::TWO_BYTES; };
Chris@47 110 template <> struct ElementSizeForByteSize<4> { static constexpr ElementSize value = ElementSize::FOUR_BYTES; };
Chris@47 111 template <> struct ElementSizeForByteSize<8> { static constexpr ElementSize value = ElementSize::EIGHT_BYTES; };
Chris@47 112
Chris@47 113 template <typename T> struct ElementSizeForType {
Chris@47 114 static constexpr ElementSize value =
Chris@47 115 // Primitive types that aren't special-cased below can be determined from sizeof().
Chris@47 116 CAPNP_KIND(T) == Kind::PRIMITIVE ? ElementSizeForByteSize<sizeof(T)>::value :
Chris@47 117 CAPNP_KIND(T) == Kind::ENUM ? ElementSize::TWO_BYTES :
Chris@47 118 CAPNP_KIND(T) == Kind::STRUCT ? ElementSize::INLINE_COMPOSITE :
Chris@47 119
Chris@47 120 // Everything else is a pointer.
Chris@47 121 ElementSize::POINTER;
Chris@47 122 };
Chris@47 123
Chris@47 124 // Void and bool are special.
Chris@47 125 template <> struct ElementSizeForType<Void> { static constexpr ElementSize value = ElementSize::VOID; };
Chris@47 126 template <> struct ElementSizeForType<bool> { static constexpr ElementSize value = ElementSize::BIT; };
Chris@47 127
Chris@47 128 // Lists and blobs are pointers, not structs.
Chris@47 129 template <typename T, bool b> struct ElementSizeForType<List<T, b>> {
Chris@47 130 static constexpr ElementSize value = ElementSize::POINTER;
Chris@47 131 };
Chris@47 132 template <> struct ElementSizeForType<Text> {
Chris@47 133 static constexpr ElementSize value = ElementSize::POINTER;
Chris@47 134 };
Chris@47 135 template <> struct ElementSizeForType<Data> {
Chris@47 136 static constexpr ElementSize value = ElementSize::POINTER;
Chris@47 137 };
Chris@47 138
Chris@47 139 template <typename T>
Chris@47 140 inline constexpr ElementSize elementSizeForType() {
Chris@47 141 return ElementSizeForType<T>::value;
Chris@47 142 }
Chris@47 143
Chris@47 144 struct MessageSizeCounts {
Chris@47 145 WordCount64 wordCount;
Chris@47 146 uint capCount;
Chris@47 147
Chris@47 148 MessageSizeCounts& operator+=(const MessageSizeCounts& other) {
Chris@47 149 wordCount += other.wordCount;
Chris@47 150 capCount += other.capCount;
Chris@47 151 return *this;
Chris@47 152 }
Chris@47 153
Chris@47 154 MessageSize asPublic() {
Chris@47 155 return MessageSize { wordCount / WORDS, capCount };
Chris@47 156 }
Chris@47 157 };
Chris@47 158
Chris@47 159 // =============================================================================
Chris@47 160
Chris@47 161 template <int wordCount>
Chris@47 162 union AlignedData {
Chris@47 163 // Useful for declaring static constant data blobs as an array of bytes, but forcing those
Chris@47 164 // bytes to be word-aligned.
Chris@47 165
Chris@47 166 uint8_t bytes[wordCount * sizeof(word)];
Chris@47 167 word words[wordCount];
Chris@47 168 };
Chris@47 169
Chris@47 170 struct StructSize {
Chris@47 171 WordCount16 data;
Chris@47 172 WirePointerCount16 pointers;
Chris@47 173
Chris@47 174 inline constexpr WordCount total() const { return data + pointers * WORDS_PER_POINTER; }
Chris@47 175
Chris@47 176 StructSize() = default;
Chris@47 177 inline constexpr StructSize(WordCount data, WirePointerCount pointers)
Chris@47 178 : data(data), pointers(pointers) {}
Chris@47 179 };
Chris@47 180
Chris@47 181 template <typename T, typename CapnpPrivate = typename T::_capnpPrivate>
Chris@47 182 inline constexpr StructSize structSize() {
Chris@47 183 return StructSize(CapnpPrivate::dataWordSize * WORDS, CapnpPrivate::pointerCount * POINTERS);
Chris@47 184 }
Chris@47 185
Chris@47 186 template <typename T, typename CapnpPrivate = typename T::_capnpPrivate,
Chris@47 187 typename = kj::EnableIf<CAPNP_KIND(T) == Kind::STRUCT>>
Chris@47 188 inline constexpr StructSize minStructSizeForElement() {
Chris@47 189 // If T is a struct, return its struct size. Otherwise return the minimum struct size big enough
Chris@47 190 // to hold a T.
Chris@47 191
Chris@47 192 return StructSize(CapnpPrivate::dataWordSize * WORDS, CapnpPrivate::pointerCount * POINTERS);
Chris@47 193 }
Chris@47 194
Chris@47 195 template <typename T, typename = kj::EnableIf<CAPNP_KIND(T) != Kind::STRUCT>>
Chris@47 196 inline constexpr StructSize minStructSizeForElement() {
Chris@47 197 // If T is a struct, return its struct size. Otherwise return the minimum struct size big enough
Chris@47 198 // to hold a T.
Chris@47 199
Chris@47 200 return StructSize(
Chris@47 201 dataBitsPerElement(elementSizeForType<T>()) * ELEMENTS > 0 * BITS ? 1 * WORDS : 0 * WORDS,
Chris@47 202 pointersPerElement(elementSizeForType<T>()) * ELEMENTS);
Chris@47 203 }
Chris@47 204
Chris@47 205 // -------------------------------------------------------------------
Chris@47 206 // Masking of default values
Chris@47 207
Chris@47 208 template <typename T, Kind kind = CAPNP_KIND(T)> struct Mask_;
Chris@47 209 template <typename T> struct Mask_<T, Kind::PRIMITIVE> { typedef T Type; };
Chris@47 210 template <typename T> struct Mask_<T, Kind::ENUM> { typedef uint16_t Type; };
Chris@47 211 template <> struct Mask_<float, Kind::PRIMITIVE> { typedef uint32_t Type; };
Chris@47 212 template <> struct Mask_<double, Kind::PRIMITIVE> { typedef uint64_t Type; };
Chris@47 213
Chris@47 214 template <typename T> struct Mask_<T, Kind::OTHER> {
Chris@47 215 // Union discriminants end up here.
Chris@47 216 static_assert(sizeof(T) == 2, "Don't know how to mask this type.");
Chris@47 217 typedef uint16_t Type;
Chris@47 218 };
Chris@47 219
Chris@47 220 template <typename T>
Chris@47 221 using Mask = typename Mask_<T>::Type;
Chris@47 222
Chris@47 223 template <typename T>
Chris@47 224 KJ_ALWAYS_INLINE(Mask<T> mask(T value, Mask<T> mask));
Chris@47 225 template <typename T>
Chris@47 226 KJ_ALWAYS_INLINE(T unmask(Mask<T> value, Mask<T> mask));
Chris@47 227
Chris@47 228 template <typename T>
Chris@47 229 inline Mask<T> mask(T value, Mask<T> mask) {
Chris@47 230 return static_cast<Mask<T> >(value) ^ mask;
Chris@47 231 }
Chris@47 232
Chris@47 233 template <>
Chris@47 234 inline uint32_t mask<float>(float value, uint32_t mask) {
Chris@47 235 #if CAPNP_CANONICALIZE_NAN
Chris@47 236 if (value != value) {
Chris@47 237 return 0x7fc00000u ^ mask;
Chris@47 238 }
Chris@47 239 #endif
Chris@47 240
Chris@47 241 uint32_t i;
Chris@47 242 static_assert(sizeof(i) == sizeof(value), "float is not 32 bits?");
Chris@47 243 memcpy(&i, &value, sizeof(value));
Chris@47 244 return i ^ mask;
Chris@47 245 }
Chris@47 246
Chris@47 247 template <>
Chris@47 248 inline uint64_t mask<double>(double value, uint64_t mask) {
Chris@47 249 #if CAPNP_CANONICALIZE_NAN
Chris@47 250 if (value != value) {
Chris@47 251 return 0x7ff8000000000000ull ^ mask;
Chris@47 252 }
Chris@47 253 #endif
Chris@47 254
Chris@47 255 uint64_t i;
Chris@47 256 static_assert(sizeof(i) == sizeof(value), "double is not 64 bits?");
Chris@47 257 memcpy(&i, &value, sizeof(value));
Chris@47 258 return i ^ mask;
Chris@47 259 }
Chris@47 260
Chris@47 261 template <typename T>
Chris@47 262 inline T unmask(Mask<T> value, Mask<T> mask) {
Chris@47 263 return static_cast<T>(value ^ mask);
Chris@47 264 }
Chris@47 265
Chris@47 266 template <>
Chris@47 267 inline float unmask<float>(uint32_t value, uint32_t mask) {
Chris@47 268 value ^= mask;
Chris@47 269 float result;
Chris@47 270 static_assert(sizeof(result) == sizeof(value), "float is not 32 bits?");
Chris@47 271 memcpy(&result, &value, sizeof(value));
Chris@47 272 return result;
Chris@47 273 }
Chris@47 274
Chris@47 275 template <>
Chris@47 276 inline double unmask<double>(uint64_t value, uint64_t mask) {
Chris@47 277 value ^= mask;
Chris@47 278 double result;
Chris@47 279 static_assert(sizeof(result) == sizeof(value), "double is not 64 bits?");
Chris@47 280 memcpy(&result, &value, sizeof(value));
Chris@47 281 return result;
Chris@47 282 }
Chris@47 283
Chris@47 284 // -------------------------------------------------------------------
Chris@47 285
Chris@47 286 class CapTableReader {
Chris@47 287 public:
Chris@47 288 #if !CAPNP_LITE
Chris@47 289 virtual kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) = 0;
Chris@47 290 // Extract the capability at the given index. If the index is invalid, returns null.
Chris@47 291 #endif // !CAPNP_LITE
Chris@47 292 };
Chris@47 293
Chris@47 294 class CapTableBuilder: public CapTableReader {
Chris@47 295 public:
Chris@47 296 #if !CAPNP_LITE
Chris@47 297 virtual uint injectCap(kj::Own<ClientHook>&& cap) = 0;
Chris@47 298 // Add the capability to the message and return its index. If the same ClientHook is injected
Chris@47 299 // twice, this may return the same index both times, but in this case dropCap() needs to be
Chris@47 300 // called an equal number of times to actually remove the cap.
Chris@47 301
Chris@47 302 virtual void dropCap(uint index) = 0;
Chris@47 303 // Remove a capability injected earlier. Called when the pointer is overwritten or zero'd out.
Chris@47 304 #endif // !CAPNP_LITE
Chris@47 305 };
Chris@47 306
Chris@47 307 // -------------------------------------------------------------------
Chris@47 308
Chris@47 309 class PointerBuilder: public kj::DisallowConstCopy {
Chris@47 310 // Represents a single pointer, usually embedded in a struct or a list.
Chris@47 311
Chris@47 312 public:
Chris@47 313 inline PointerBuilder(): segment(nullptr), capTable(nullptr), pointer(nullptr) {}
Chris@47 314
Chris@47 315 static inline PointerBuilder getRoot(
Chris@47 316 SegmentBuilder* segment, CapTableBuilder* capTable, word* location);
Chris@47 317 // Get a PointerBuilder representing a message root located in the given segment at the given
Chris@47 318 // location.
Chris@47 319
Chris@47 320 inline bool isNull() { return getPointerType() == PointerType::NULL_; }
Chris@47 321 PointerType getPointerType();
Chris@47 322
Chris@47 323 StructBuilder getStruct(StructSize size, const word* defaultValue);
Chris@47 324 ListBuilder getList(ElementSize elementSize, const word* defaultValue);
Chris@47 325 ListBuilder getStructList(StructSize elementSize, const word* defaultValue);
Chris@47 326 ListBuilder getListAnySize(const word* defaultValue);
Chris@47 327 template <typename T> typename T::Builder getBlob(const void* defaultValue,ByteCount defaultSize);
Chris@47 328 #if !CAPNP_LITE
Chris@47 329 kj::Own<ClientHook> getCapability();
Chris@47 330 #endif // !CAPNP_LITE
Chris@47 331 // Get methods: Get the value. If it is null, initialize it to a copy of the default value.
Chris@47 332 // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a
Chris@47 333 // simple byte array for blobs.
Chris@47 334
Chris@47 335 StructBuilder initStruct(StructSize size);
Chris@47 336 ListBuilder initList(ElementSize elementSize, ElementCount elementCount);
Chris@47 337 ListBuilder initStructList(ElementCount elementCount, StructSize size);
Chris@47 338 template <typename T> typename T::Builder initBlob(ByteCount size);
Chris@47 339 // Init methods: Initialize the pointer to a newly-allocated object, discarding the existing
Chris@47 340 // object.
Chris@47 341
Chris@47 342 void setStruct(const StructReader& value, bool canonical = false);
Chris@47 343 void setList(const ListReader& value, bool canonical = false);
Chris@47 344 template <typename T> void setBlob(typename T::Reader value);
Chris@47 345 #if !CAPNP_LITE
Chris@47 346 void setCapability(kj::Own<ClientHook>&& cap);
Chris@47 347 #endif // !CAPNP_LITE
Chris@47 348 // Set methods: Initialize the pointer to a newly-allocated copy of the given value, discarding
Chris@47 349 // the existing object.
Chris@47 350
Chris@47 351 void adopt(OrphanBuilder&& orphan);
Chris@47 352 // Set the pointer to point at the given orphaned value.
Chris@47 353
Chris@47 354 OrphanBuilder disown();
Chris@47 355 // Set the pointer to null and return its previous value as an orphan.
Chris@47 356
Chris@47 357 void clear();
Chris@47 358 // Clear the pointer to null, discarding its previous value.
Chris@47 359
Chris@47 360 void transferFrom(PointerBuilder other);
Chris@47 361 // Equivalent to `adopt(other.disown())`.
Chris@47 362
Chris@47 363 void copyFrom(PointerReader other, bool canonical = false);
Chris@47 364 // Equivalent to `set(other.get())`.
Chris@47 365 // If you set the canonical flag, it will attempt to lay the target out
Chris@47 366 // canonically, provided enough space is available.
Chris@47 367
Chris@47 368 PointerReader asReader() const;
Chris@47 369
Chris@47 370 BuilderArena* getArena() const;
Chris@47 371 // Get the arena containing this pointer.
Chris@47 372
Chris@47 373 CapTableBuilder* getCapTable();
Chris@47 374 // Gets the capability context in which this object is operating.
Chris@47 375
Chris@47 376 PointerBuilder imbue(CapTableBuilder* capTable);
Chris@47 377 // Return a copy of this builder except using the given capability context.
Chris@47 378
Chris@47 379 private:
Chris@47 380 SegmentBuilder* segment; // Memory segment in which the pointer resides.
Chris@47 381 CapTableBuilder* capTable; // Table of capability indexes.
Chris@47 382 WirePointer* pointer; // Pointer to the pointer.
Chris@47 383
Chris@47 384 inline PointerBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, WirePointer* pointer)
Chris@47 385 : segment(segment), capTable(capTable), pointer(pointer) {}
Chris@47 386
Chris@47 387 friend class StructBuilder;
Chris@47 388 friend class ListBuilder;
Chris@47 389 friend class OrphanBuilder;
Chris@47 390 };
Chris@47 391
Chris@47 392 class PointerReader {
Chris@47 393 public:
Chris@47 394 inline PointerReader()
Chris@47 395 : segment(nullptr), capTable(nullptr), pointer(nullptr), nestingLimit(0x7fffffff) {}
Chris@47 396
Chris@47 397 static PointerReader getRoot(SegmentReader* segment, CapTableReader* capTable,
Chris@47 398 const word* location, int nestingLimit);
Chris@47 399 // Get a PointerReader representing a message root located in the given segment at the given
Chris@47 400 // location.
Chris@47 401
Chris@47 402 static inline PointerReader getRootUnchecked(const word* location);
Chris@47 403 // Get a PointerReader for an unchecked message.
Chris@47 404
Chris@47 405 MessageSizeCounts targetSize() const;
Chris@47 406 // Return the total size of the target object and everything to which it points. Does not count
Chris@47 407 // far pointer overhead. This is useful for deciding how much space is needed to copy the object
Chris@47 408 // into a flat array. However, the caller is advised NOT to treat this value as secure. Instead,
Chris@47 409 // use the result as a hint for allocating the first segment, do the copy, and then throw an
Chris@47 410 // exception if it overruns.
Chris@47 411
Chris@47 412 inline bool isNull() const { return getPointerType() == PointerType::NULL_; }
Chris@47 413 PointerType getPointerType() const;
Chris@47 414
Chris@47 415 StructReader getStruct(const word* defaultValue) const;
Chris@47 416 ListReader getList(ElementSize expectedElementSize, const word* defaultValue) const;
Chris@47 417 ListReader getListAnySize(const word* defaultValue) const;
Chris@47 418 template <typename T>
Chris@47 419 typename T::Reader getBlob(const void* defaultValue, ByteCount defaultSize) const;
Chris@47 420 #if !CAPNP_LITE
Chris@47 421 kj::Own<ClientHook> getCapability() const;
Chris@47 422 #endif // !CAPNP_LITE
Chris@47 423 // Get methods: Get the value. If it is null, return the default value instead.
Chris@47 424 // The default value is encoded as an "unchecked message" for structs, lists, and objects, or a
Chris@47 425 // simple byte array for blobs.
Chris@47 426
Chris@47 427 const word* getUnchecked() const;
Chris@47 428 // If this is an unchecked message, get a word* pointing at the location of the pointer. This
Chris@47 429 // word* can actually be passed to readUnchecked() to read the designated sub-object later. If
Chris@47 430 // this isn't an unchecked message, throws an exception.
Chris@47 431
Chris@47 432 kj::Maybe<Arena&> getArena() const;
Chris@47 433 // Get the arena containing this pointer.
Chris@47 434
Chris@47 435 CapTableReader* getCapTable();
Chris@47 436 // Gets the capability context in which this object is operating.
Chris@47 437
Chris@47 438 PointerReader imbue(CapTableReader* capTable) const;
Chris@47 439 // Return a copy of this reader except using the given capability context.
Chris@47 440
Chris@47 441 bool isCanonical(const word **readHead);
Chris@47 442 // Validate this pointer's canonicity, subject to the conditions:
Chris@47 443 // * All data to the left of readHead has been read thus far (for pointer
Chris@47 444 // ordering)
Chris@47 445 // * All pointers in preorder have already been checked
Chris@47 446 // * This pointer is in the first and only segment of the message
Chris@47 447
Chris@47 448 private:
Chris@47 449 SegmentReader* segment; // Memory segment in which the pointer resides.
Chris@47 450 CapTableReader* capTable; // Table of capability indexes.
Chris@47 451 const WirePointer* pointer; // Pointer to the pointer. null = treat as null pointer.
Chris@47 452
Chris@47 453 int nestingLimit;
Chris@47 454 // Limits the depth of message structures to guard against stack-overflow-based DoS attacks.
Chris@47 455 // Once this reaches zero, further pointers will be pruned.
Chris@47 456
Chris@47 457 inline PointerReader(SegmentReader* segment, CapTableReader* capTable,
Chris@47 458 const WirePointer* pointer, int nestingLimit)
Chris@47 459 : segment(segment), capTable(capTable), pointer(pointer), nestingLimit(nestingLimit) {}
Chris@47 460
Chris@47 461 friend class StructReader;
Chris@47 462 friend class ListReader;
Chris@47 463 friend class PointerBuilder;
Chris@47 464 friend class OrphanBuilder;
Chris@47 465 };
Chris@47 466
Chris@47 467 // -------------------------------------------------------------------
Chris@47 468
Chris@47 469 class StructBuilder: public kj::DisallowConstCopy {
Chris@47 470 public:
Chris@47 471 inline StructBuilder(): segment(nullptr), capTable(nullptr), data(nullptr), pointers(nullptr) {}
Chris@47 472
Chris@47 473 inline word* getLocation() { return reinterpret_cast<word*>(data); }
Chris@47 474 // Get the object's location. Only valid for independently-allocated objects (i.e. not list
Chris@47 475 // elements).
Chris@47 476
Chris@47 477 inline BitCount getDataSectionSize() const { return dataSize; }
Chris@47 478 inline WirePointerCount getPointerSectionSize() const { return pointerCount; }
Chris@47 479 inline kj::ArrayPtr<byte> getDataSectionAsBlob();
Chris@47 480 inline _::ListBuilder getPointerSectionAsList();
Chris@47 481
Chris@47 482 template <typename T>
Chris@47 483 KJ_ALWAYS_INLINE(bool hasDataField(ElementCount offset));
Chris@47 484 // Return true if the field is set to something other than its default value.
Chris@47 485
Chris@47 486 template <typename T>
Chris@47 487 KJ_ALWAYS_INLINE(T getDataField(ElementCount offset));
Chris@47 488 // Gets the data field value of the given type at the given offset. The offset is measured in
Chris@47 489 // multiples of the field size, determined by the type.
Chris@47 490
Chris@47 491 template <typename T>
Chris@47 492 KJ_ALWAYS_INLINE(T getDataField(ElementCount offset, Mask<T> mask));
Chris@47 493 // Like getDataField() but applies the given XOR mask to the data on load. Used for reading
Chris@47 494 // fields with non-zero default values.
Chris@47 495
Chris@47 496 template <typename T>
Chris@47 497 KJ_ALWAYS_INLINE(void setDataField(
Chris@47 498 ElementCount offset, kj::NoInfer<T> value));
Chris@47 499 // Sets the data field value at the given offset.
Chris@47 500
Chris@47 501 template <typename T>
Chris@47 502 KJ_ALWAYS_INLINE(void setDataField(
Chris@47 503 ElementCount offset, kj::NoInfer<T> value, Mask<T> mask));
Chris@47 504 // Like setDataField() but applies the given XOR mask before storing. Used for writing fields
Chris@47 505 // with non-zero default values.
Chris@47 506
Chris@47 507 KJ_ALWAYS_INLINE(PointerBuilder getPointerField(WirePointerCount ptrIndex));
Chris@47 508 // Get a builder for a pointer field given the index within the pointer section.
Chris@47 509
Chris@47 510 void clearAll();
Chris@47 511 // Clear all pointers and data.
Chris@47 512
Chris@47 513 void transferContentFrom(StructBuilder other);
Chris@47 514 // Adopt all pointers from `other`, and also copy all data. If `other`'s sections are larger
Chris@47 515 // than this, the extra data is not transferred, meaning there is a risk of data loss when
Chris@47 516 // transferring from messages built with future versions of the protocol.
Chris@47 517
Chris@47 518 void copyContentFrom(StructReader other);
Chris@47 519 // Copy content from `other`. If `other`'s sections are larger than this, the extra data is not
Chris@47 520 // copied, meaning there is a risk of data loss when copying from messages built with future
Chris@47 521 // versions of the protocol.
Chris@47 522
Chris@47 523 StructReader asReader() const;
Chris@47 524 // Gets a StructReader pointing at the same memory.
Chris@47 525
Chris@47 526 BuilderArena* getArena();
Chris@47 527 // Gets the arena in which this object is allocated.
Chris@47 528
Chris@47 529 CapTableBuilder* getCapTable();
Chris@47 530 // Gets the capability context in which this object is operating.
Chris@47 531
Chris@47 532 StructBuilder imbue(CapTableBuilder* capTable);
Chris@47 533 // Return a copy of this builder except using the given capability context.
Chris@47 534
Chris@47 535 private:
Chris@47 536 SegmentBuilder* segment; // Memory segment in which the struct resides.
Chris@47 537 CapTableBuilder* capTable; // Table of capability indexes.
Chris@47 538 void* data; // Pointer to the encoded data.
Chris@47 539 WirePointer* pointers; // Pointer to the encoded pointers.
Chris@47 540
Chris@47 541 BitCount32 dataSize;
Chris@47 542 // Size of data section. We use a bit count rather than a word count to more easily handle the
Chris@47 543 // case of struct lists encoded with less than a word per element.
Chris@47 544
Chris@47 545 WirePointerCount16 pointerCount; // Size of the pointer section.
Chris@47 546
Chris@47 547 inline StructBuilder(SegmentBuilder* segment, CapTableBuilder* capTable,
Chris@47 548 void* data, WirePointer* pointers,
Chris@47 549 BitCount dataSize, WirePointerCount pointerCount)
Chris@47 550 : segment(segment), capTable(capTable), data(data), pointers(pointers),
Chris@47 551 dataSize(dataSize), pointerCount(pointerCount) {}
Chris@47 552
Chris@47 553 friend class ListBuilder;
Chris@47 554 friend struct WireHelpers;
Chris@47 555 friend class OrphanBuilder;
Chris@47 556 };
Chris@47 557
Chris@47 558 class StructReader {
Chris@47 559 public:
Chris@47 560 inline StructReader()
Chris@47 561 : segment(nullptr), capTable(nullptr), data(nullptr), pointers(nullptr), dataSize(0),
Chris@47 562 pointerCount(0), nestingLimit(0x7fffffff) {}
Chris@47 563 inline StructReader(kj::ArrayPtr<const word> data)
Chris@47 564 : segment(nullptr), capTable(nullptr), data(data.begin()), pointers(nullptr),
Chris@47 565 dataSize(data.size() * WORDS * BITS_PER_WORD), pointerCount(0), nestingLimit(0x7fffffff) {}
Chris@47 566
Chris@47 567 const void* getLocation() const { return data; }
Chris@47 568
Chris@47 569 inline BitCount getDataSectionSize() const { return dataSize; }
Chris@47 570 inline WirePointerCount getPointerSectionSize() const { return pointerCount; }
Chris@47 571 inline kj::ArrayPtr<const byte> getDataSectionAsBlob();
Chris@47 572 inline _::ListReader getPointerSectionAsList();
Chris@47 573
Chris@47 574 kj::Array<word> canonicalize();
Chris@47 575
Chris@47 576 template <typename T>
Chris@47 577 KJ_ALWAYS_INLINE(bool hasDataField(ElementCount offset) const);
Chris@47 578 // Return true if the field is set to something other than its default value.
Chris@47 579
Chris@47 580 template <typename T>
Chris@47 581 KJ_ALWAYS_INLINE(T getDataField(ElementCount offset) const);
Chris@47 582 // Get the data field value of the given type at the given offset. The offset is measured in
Chris@47 583 // multiples of the field size, determined by the type. Returns zero if the offset is past the
Chris@47 584 // end of the struct's data section.
Chris@47 585
Chris@47 586 template <typename T>
Chris@47 587 KJ_ALWAYS_INLINE(
Chris@47 588 T getDataField(ElementCount offset, Mask<T> mask) const);
Chris@47 589 // Like getDataField(offset), but applies the given XOR mask to the result. Used for reading
Chris@47 590 // fields with non-zero default values.
Chris@47 591
Chris@47 592 KJ_ALWAYS_INLINE(PointerReader getPointerField(WirePointerCount ptrIndex) const);
Chris@47 593 // Get a reader for a pointer field given the index within the pointer section. If the index
Chris@47 594 // is out-of-bounds, returns a null pointer.
Chris@47 595
Chris@47 596 MessageSizeCounts totalSize() const;
Chris@47 597 // Return the total size of the struct and everything to which it points. Does not count far
Chris@47 598 // pointer overhead. This is useful for deciding how much space is needed to copy the struct
Chris@47 599 // into a flat array. However, the caller is advised NOT to treat this value as secure. Instead,
Chris@47 600 // use the result as a hint for allocating the first segment, do the copy, and then throw an
Chris@47 601 // exception if it overruns.
Chris@47 602
Chris@47 603 CapTableReader* getCapTable();
Chris@47 604 // Gets the capability context in which this object is operating.
Chris@47 605
Chris@47 606 StructReader imbue(CapTableReader* capTable) const;
Chris@47 607 // Return a copy of this reader except using the given capability context.
Chris@47 608
Chris@47 609 bool isCanonical(const word **readHead, const word **ptrHead,
Chris@47 610 bool *dataTrunc, bool *ptrTrunc);
Chris@47 611 // Validate this pointer's canonicity, subject to the conditions:
Chris@47 612 // * All data to the left of readHead has been read thus far (for pointer
Chris@47 613 // ordering)
Chris@47 614 // * All pointers in preorder have already been checked
Chris@47 615 // * This pointer is in the first and only segment of the message
Chris@47 616 //
Chris@47 617 // If this function returns false, the struct is non-canonical. If it
Chris@47 618 // returns true, then:
Chris@47 619 // * If it is a composite in a list, it is canonical if at least one struct
Chris@47 620 // in the list outputs dataTrunc = 1, and at least one outputs ptrTrunc = 1
Chris@47 621 // * If it is derived from a struct pointer, it is canonical if
Chris@47 622 // dataTrunc = 1 AND ptrTrunc = 1
Chris@47 623
Chris@47 624 private:
Chris@47 625 SegmentReader* segment; // Memory segment in which the struct resides.
Chris@47 626 CapTableReader* capTable; // Table of capability indexes.
Chris@47 627
Chris@47 628 const void* data;
Chris@47 629 const WirePointer* pointers;
Chris@47 630
Chris@47 631 BitCount32 dataSize;
Chris@47 632 // Size of data section. We use a bit count rather than a word count to more easily handle the
Chris@47 633 // case of struct lists encoded with less than a word per element.
Chris@47 634
Chris@47 635 WirePointerCount16 pointerCount; // Size of the pointer section.
Chris@47 636
Chris@47 637 int nestingLimit;
Chris@47 638 // Limits the depth of message structures to guard against stack-overflow-based DoS attacks.
Chris@47 639 // Once this reaches zero, further pointers will be pruned.
Chris@47 640 // TODO(perf): Limit to 16 bits for better packing?
Chris@47 641
Chris@47 642 inline StructReader(SegmentReader* segment, CapTableReader* capTable,
Chris@47 643 const void* data, const WirePointer* pointers,
Chris@47 644 BitCount dataSize, WirePointerCount pointerCount, int nestingLimit)
Chris@47 645 : segment(segment), capTable(capTable), data(data), pointers(pointers),
Chris@47 646 dataSize(dataSize), pointerCount(pointerCount),
Chris@47 647 nestingLimit(nestingLimit) {}
Chris@47 648
Chris@47 649 friend class ListReader;
Chris@47 650 friend class StructBuilder;
Chris@47 651 friend struct WireHelpers;
Chris@47 652 };
Chris@47 653
Chris@47 654 // -------------------------------------------------------------------
Chris@47 655
Chris@47 656 class ListBuilder: public kj::DisallowConstCopy {
Chris@47 657 public:
Chris@47 658 inline explicit ListBuilder(ElementSize elementSize)
Chris@47 659 : segment(nullptr), capTable(nullptr), ptr(nullptr), elementCount(0 * ELEMENTS),
Chris@47 660 step(0 * BITS / ELEMENTS), structDataSize(0 * BITS), structPointerCount(0 * POINTERS),
Chris@47 661 elementSize(elementSize) {}
Chris@47 662
Chris@47 663 inline word* getLocation() {
Chris@47 664 // Get the object's location.
Chris@47 665
Chris@47 666 if (elementSize == ElementSize::INLINE_COMPOSITE && ptr != nullptr) {
Chris@47 667 return reinterpret_cast<word*>(ptr) - POINTER_SIZE_IN_WORDS;
Chris@47 668 } else {
Chris@47 669 return reinterpret_cast<word*>(ptr);
Chris@47 670 }
Chris@47 671 }
Chris@47 672
Chris@47 673 inline ElementSize getElementSize() const { return elementSize; }
Chris@47 674
Chris@47 675 inline ElementCount size() const;
Chris@47 676 // The number of elements in the list.
Chris@47 677
Chris@47 678 Text::Builder asText();
Chris@47 679 Data::Builder asData();
Chris@47 680 // Reinterpret the list as a blob. Throws an exception if the elements are not byte-sized.
Chris@47 681
Chris@47 682 template <typename T>
Chris@47 683 KJ_ALWAYS_INLINE(T getDataElement(ElementCount index));
Chris@47 684 // Get the element of the given type at the given index.
Chris@47 685
Chris@47 686 template <typename T>
Chris@47 687 KJ_ALWAYS_INLINE(void setDataElement(
Chris@47 688 ElementCount index, kj::NoInfer<T> value));
Chris@47 689 // Set the element at the given index.
Chris@47 690
Chris@47 691 KJ_ALWAYS_INLINE(PointerBuilder getPointerElement(ElementCount index));
Chris@47 692
Chris@47 693 StructBuilder getStructElement(ElementCount index);
Chris@47 694
Chris@47 695 ListReader asReader() const;
Chris@47 696 // Get a ListReader pointing at the same memory.
Chris@47 697
Chris@47 698 BuilderArena* getArena();
Chris@47 699 // Gets the arena in which this object is allocated.
Chris@47 700
Chris@47 701 CapTableBuilder* getCapTable();
Chris@47 702 // Gets the capability context in which this object is operating.
Chris@47 703
Chris@47 704 ListBuilder imbue(CapTableBuilder* capTable);
Chris@47 705 // Return a copy of this builder except using the given capability context.
Chris@47 706
Chris@47 707 private:
Chris@47 708 SegmentBuilder* segment; // Memory segment in which the list resides.
Chris@47 709 CapTableBuilder* capTable; // Table of capability indexes.
Chris@47 710
Chris@47 711 byte* ptr; // Pointer to list content.
Chris@47 712
Chris@47 713 ElementCount elementCount; // Number of elements in the list.
Chris@47 714
Chris@47 715 decltype(BITS / ELEMENTS) step;
Chris@47 716 // The distance between elements.
Chris@47 717
Chris@47 718 BitCount32 structDataSize;
Chris@47 719 WirePointerCount16 structPointerCount;
Chris@47 720 // The struct properties to use when interpreting the elements as structs. All lists can be
Chris@47 721 // interpreted as struct lists, so these are always filled in.
Chris@47 722
Chris@47 723 ElementSize elementSize;
Chris@47 724 // The element size as a ElementSize. This is only really needed to disambiguate INLINE_COMPOSITE
Chris@47 725 // from other types when the overall size is exactly zero or one words.
Chris@47 726
Chris@47 727 inline ListBuilder(SegmentBuilder* segment, CapTableBuilder* capTable, void* ptr,
Chris@47 728 decltype(BITS / ELEMENTS) step, ElementCount size,
Chris@47 729 BitCount structDataSize, WirePointerCount structPointerCount,
Chris@47 730 ElementSize elementSize)
Chris@47 731 : segment(segment), capTable(capTable), ptr(reinterpret_cast<byte*>(ptr)),
Chris@47 732 elementCount(size), step(step), structDataSize(structDataSize),
Chris@47 733 structPointerCount(structPointerCount), elementSize(elementSize) {}
Chris@47 734
Chris@47 735 friend class StructBuilder;
Chris@47 736 friend struct WireHelpers;
Chris@47 737 friend class OrphanBuilder;
Chris@47 738 };
Chris@47 739
Chris@47 740 class ListReader {
Chris@47 741 public:
Chris@47 742 inline explicit ListReader(ElementSize elementSize)
Chris@47 743 : segment(nullptr), capTable(nullptr), ptr(nullptr), elementCount(0),
Chris@47 744 step(0 * BITS / ELEMENTS), structDataSize(0), structPointerCount(0),
Chris@47 745 elementSize(elementSize), nestingLimit(0x7fffffff) {}
Chris@47 746
Chris@47 747 inline ElementCount size() const;
Chris@47 748 // The number of elements in the list.
Chris@47 749
Chris@47 750 inline ElementSize getElementSize() const { return elementSize; }
Chris@47 751
Chris@47 752 Text::Reader asText();
Chris@47 753 Data::Reader asData();
Chris@47 754 // Reinterpret the list as a blob. Throws an exception if the elements are not byte-sized.
Chris@47 755
Chris@47 756 kj::ArrayPtr<const byte> asRawBytes();
Chris@47 757
Chris@47 758 template <typename T>
Chris@47 759 KJ_ALWAYS_INLINE(T getDataElement(ElementCount index) const);
Chris@47 760 // Get the element of the given type at the given index.
Chris@47 761
Chris@47 762 KJ_ALWAYS_INLINE(PointerReader getPointerElement(ElementCount index) const);
Chris@47 763
Chris@47 764 StructReader getStructElement(ElementCount index) const;
Chris@47 765
Chris@47 766 CapTableReader* getCapTable();
Chris@47 767 // Gets the capability context in which this object is operating.
Chris@47 768
Chris@47 769 ListReader imbue(CapTableReader* capTable) const;
Chris@47 770 // Return a copy of this reader except using the given capability context.
Chris@47 771
Chris@47 772 bool isCanonical(const word **readHead);
Chris@47 773 // Validate this pointer's canonicity, subject to the conditions:
Chris@47 774 // * All data to the left of readHead has been read thus far (for pointer
Chris@47 775 // ordering)
Chris@47 776 // * All pointers in preorder have already been checked
Chris@47 777 // * This pointer is in the first and only segment of the message
Chris@47 778
Chris@47 779 private:
Chris@47 780 SegmentReader* segment; // Memory segment in which the list resides.
Chris@47 781 CapTableReader* capTable; // Table of capability indexes.
Chris@47 782
Chris@47 783 const byte* ptr; // Pointer to list content.
Chris@47 784
Chris@47 785 ElementCount elementCount; // Number of elements in the list.
Chris@47 786
Chris@47 787 decltype(BITS / ELEMENTS) step;
Chris@47 788 // The distance between elements.
Chris@47 789
Chris@47 790 BitCount32 structDataSize;
Chris@47 791 WirePointerCount16 structPointerCount;
Chris@47 792 // The struct properties to use when interpreting the elements as structs. All lists can be
Chris@47 793 // interpreted as struct lists, so these are always filled in.
Chris@47 794
Chris@47 795 ElementSize elementSize;
Chris@47 796 // The element size as a ElementSize. This is only really needed to disambiguate INLINE_COMPOSITE
Chris@47 797 // from other types when the overall size is exactly zero or one words.
Chris@47 798
Chris@47 799 int nestingLimit;
Chris@47 800 // Limits the depth of message structures to guard against stack-overflow-based DoS attacks.
Chris@47 801 // Once this reaches zero, further pointers will be pruned.
Chris@47 802
Chris@47 803 inline ListReader(SegmentReader* segment, CapTableReader* capTable, const void* ptr,
Chris@47 804 ElementCount elementCount, decltype(BITS / ELEMENTS) step,
Chris@47 805 BitCount structDataSize, WirePointerCount structPointerCount,
Chris@47 806 ElementSize elementSize, int nestingLimit)
Chris@47 807 : segment(segment), capTable(capTable), ptr(reinterpret_cast<const byte*>(ptr)),
Chris@47 808 elementCount(elementCount), step(step), structDataSize(structDataSize),
Chris@47 809 structPointerCount(structPointerCount), elementSize(elementSize),
Chris@47 810 nestingLimit(nestingLimit) {}
Chris@47 811
Chris@47 812 friend class StructReader;
Chris@47 813 friend class ListBuilder;
Chris@47 814 friend struct WireHelpers;
Chris@47 815 friend class OrphanBuilder;
Chris@47 816 };
Chris@47 817
Chris@47 818 // -------------------------------------------------------------------
Chris@47 819
Chris@47 820 class OrphanBuilder {
Chris@47 821 public:
Chris@47 822 inline OrphanBuilder(): segment(nullptr), capTable(nullptr), location(nullptr) {
Chris@47 823 memset(&tag, 0, sizeof(tag));
Chris@47 824 }
Chris@47 825 OrphanBuilder(const OrphanBuilder& other) = delete;
Chris@47 826 inline OrphanBuilder(OrphanBuilder&& other) noexcept;
Chris@47 827 inline ~OrphanBuilder() noexcept(false);
Chris@47 828
Chris@47 829 static OrphanBuilder initStruct(BuilderArena* arena, CapTableBuilder* capTable, StructSize size);
Chris@47 830 static OrphanBuilder initList(BuilderArena* arena, CapTableBuilder* capTable,
Chris@47 831 ElementCount elementCount, ElementSize elementSize);
Chris@47 832 static OrphanBuilder initStructList(BuilderArena* arena, CapTableBuilder* capTable,
Chris@47 833 ElementCount elementCount, StructSize elementSize);
Chris@47 834 static OrphanBuilder initText(BuilderArena* arena, CapTableBuilder* capTable, ByteCount size);
Chris@47 835 static OrphanBuilder initData(BuilderArena* arena, CapTableBuilder* capTable, ByteCount size);
Chris@47 836
Chris@47 837 static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, StructReader copyFrom);
Chris@47 838 static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, ListReader copyFrom);
Chris@47 839 static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, PointerReader copyFrom);
Chris@47 840 static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, Text::Reader copyFrom);
Chris@47 841 static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable, Data::Reader copyFrom);
Chris@47 842 #if !CAPNP_LITE
Chris@47 843 static OrphanBuilder copy(BuilderArena* arena, CapTableBuilder* capTable,
Chris@47 844 kj::Own<ClientHook> copyFrom);
Chris@47 845 #endif // !CAPNP_LITE
Chris@47 846
Chris@47 847 static OrphanBuilder concat(BuilderArena* arena, CapTableBuilder* capTable,
Chris@47 848 ElementSize expectedElementSize, StructSize expectedStructSize,
Chris@47 849 kj::ArrayPtr<const ListReader> lists);
Chris@47 850
Chris@47 851 static OrphanBuilder referenceExternalData(BuilderArena* arena, Data::Reader data);
Chris@47 852
Chris@47 853 OrphanBuilder& operator=(const OrphanBuilder& other) = delete;
Chris@47 854 inline OrphanBuilder& operator=(OrphanBuilder&& other);
Chris@47 855
Chris@47 856 inline bool operator==(decltype(nullptr)) const { return location == nullptr; }
Chris@47 857 inline bool operator!=(decltype(nullptr)) const { return location != nullptr; }
Chris@47 858
Chris@47 859 StructBuilder asStruct(StructSize size);
Chris@47 860 // Interpret as a struct, or throw an exception if not a struct.
Chris@47 861
Chris@47 862 ListBuilder asList(ElementSize elementSize);
Chris@47 863 // Interpret as a list, or throw an exception if not a list. elementSize cannot be
Chris@47 864 // INLINE_COMPOSITE -- use asStructList() instead.
Chris@47 865
Chris@47 866 ListBuilder asStructList(StructSize elementSize);
Chris@47 867 // Interpret as a struct list, or throw an exception if not a list.
Chris@47 868
Chris@47 869 Text::Builder asText();
Chris@47 870 Data::Builder asData();
Chris@47 871 // Interpret as a blob, or throw an exception if not a blob.
Chris@47 872
Chris@47 873 StructReader asStructReader(StructSize size) const;
Chris@47 874 ListReader asListReader(ElementSize elementSize) const;
Chris@47 875 #if !CAPNP_LITE
Chris@47 876 kj::Own<ClientHook> asCapability() const;
Chris@47 877 #endif // !CAPNP_LITE
Chris@47 878 Text::Reader asTextReader() const;
Chris@47 879 Data::Reader asDataReader() const;
Chris@47 880
Chris@47 881 bool truncate(ElementCount size, bool isText) KJ_WARN_UNUSED_RESULT;
Chris@47 882 // Resize the orphan list to the given size. Returns false if the list is currently empty but
Chris@47 883 // the requested size is non-zero, in which case the caller will need to allocate a new list.
Chris@47 884
Chris@47 885 void truncate(ElementCount size, ElementSize elementSize);
Chris@47 886 void truncate(ElementCount size, StructSize elementSize);
Chris@47 887 void truncateText(ElementCount size);
Chris@47 888 // Versions of truncate() that know how to allocate a new list if needed.
Chris@47 889
Chris@47 890 private:
Chris@47 891 static_assert(1 * POINTERS * WORDS_PER_POINTER == 1 * WORDS,
Chris@47 892 "This struct assumes a pointer is one word.");
Chris@47 893 word tag;
Chris@47 894 // Contains an encoded WirePointer representing this object. WirePointer is defined in
Chris@47 895 // layout.c++, but fits in a word.
Chris@47 896 //
Chris@47 897 // This may be a FAR pointer. Even in that case, `location` points to the eventual destination
Chris@47 898 // of that far pointer. The reason we keep the far pointer around rather than just making `tag`
Chris@47 899 // represent the final destination is because if the eventual adopter of the pointer is not in
Chris@47 900 // the target's segment then it may be useful to reuse the far pointer landing pad.
Chris@47 901 //
Chris@47 902 // If `tag` is not a far pointer, its offset is garbage; only `location` points to the actual
Chris@47 903 // target.
Chris@47 904
Chris@47 905 SegmentBuilder* segment;
Chris@47 906 // Segment in which the object resides.
Chris@47 907
Chris@47 908 CapTableBuilder* capTable;
Chris@47 909 // Table of capability indexes.
Chris@47 910
Chris@47 911 word* location;
Chris@47 912 // Pointer to the object, or nullptr if the pointer is null. For capabilities, we make this
Chris@47 913 // 0x1 just so that it is non-null for operator==, but it is never used.
Chris@47 914
Chris@47 915 inline OrphanBuilder(const void* tagPtr, SegmentBuilder* segment,
Chris@47 916 CapTableBuilder* capTable, word* location)
Chris@47 917 : segment(segment), capTable(capTable), location(location) {
Chris@47 918 memcpy(&tag, tagPtr, sizeof(tag));
Chris@47 919 }
Chris@47 920
Chris@47 921 inline WirePointer* tagAsPtr() { return reinterpret_cast<WirePointer*>(&tag); }
Chris@47 922 inline const WirePointer* tagAsPtr() const { return reinterpret_cast<const WirePointer*>(&tag); }
Chris@47 923
Chris@47 924 void euthanize();
Chris@47 925 // Erase the target object, zeroing it out and possibly reclaiming the memory. Called when
Chris@47 926 // the OrphanBuilder is being destroyed or overwritten and it is non-null.
Chris@47 927
Chris@47 928 friend struct WireHelpers;
Chris@47 929 };
Chris@47 930
Chris@47 931 // =======================================================================================
Chris@47 932 // Internal implementation details...
Chris@47 933
Chris@47 934 // These are defined in the source file.
Chris@47 935 template <> typename Text::Builder PointerBuilder::initBlob<Text>(ByteCount size);
Chris@47 936 template <> void PointerBuilder::setBlob<Text>(typename Text::Reader value);
Chris@47 937 template <> typename Text::Builder PointerBuilder::getBlob<Text>(const void* defaultValue, ByteCount defaultSize);
Chris@47 938 template <> typename Text::Reader PointerReader::getBlob<Text>(const void* defaultValue, ByteCount defaultSize) const;
Chris@47 939
Chris@47 940 template <> typename Data::Builder PointerBuilder::initBlob<Data>(ByteCount size);
Chris@47 941 template <> void PointerBuilder::setBlob<Data>(typename Data::Reader value);
Chris@47 942 template <> typename Data::Builder PointerBuilder::getBlob<Data>(const void* defaultValue, ByteCount defaultSize);
Chris@47 943 template <> typename Data::Reader PointerReader::getBlob<Data>(const void* defaultValue, ByteCount defaultSize) const;
Chris@47 944
Chris@47 945 inline PointerBuilder PointerBuilder::getRoot(
Chris@47 946 SegmentBuilder* segment, CapTableBuilder* capTable, word* location) {
Chris@47 947 return PointerBuilder(segment, capTable, reinterpret_cast<WirePointer*>(location));
Chris@47 948 }
Chris@47 949
Chris@47 950 inline PointerReader PointerReader::getRootUnchecked(const word* location) {
Chris@47 951 return PointerReader(nullptr, nullptr,
Chris@47 952 reinterpret_cast<const WirePointer*>(location), 0x7fffffff);
Chris@47 953 }
Chris@47 954
Chris@47 955 // -------------------------------------------------------------------
Chris@47 956
Chris@47 957 inline kj::ArrayPtr<byte> StructBuilder::getDataSectionAsBlob() {
Chris@47 958 return kj::ArrayPtr<byte>(reinterpret_cast<byte*>(data), dataSize / BITS_PER_BYTE / BYTES);
Chris@47 959 }
Chris@47 960
Chris@47 961 inline _::ListBuilder StructBuilder::getPointerSectionAsList() {
Chris@47 962 return _::ListBuilder(segment, capTable, pointers, 1 * POINTERS * BITS_PER_POINTER / ELEMENTS,
Chris@47 963 pointerCount * (1 * ELEMENTS / POINTERS),
Chris@47 964 0 * BITS, 1 * POINTERS, ElementSize::POINTER);
Chris@47 965 }
Chris@47 966
Chris@47 967 template <typename T>
Chris@47 968 inline bool StructBuilder::hasDataField(ElementCount offset) {
Chris@47 969 return getDataField<Mask<T>>(offset) != 0;
Chris@47 970 }
Chris@47 971
Chris@47 972 template <>
Chris@47 973 inline bool StructBuilder::hasDataField<Void>(ElementCount offset) {
Chris@47 974 return false;
Chris@47 975 }
Chris@47 976
Chris@47 977 template <typename T>
Chris@47 978 inline T StructBuilder::getDataField(ElementCount offset) {
Chris@47 979 return reinterpret_cast<WireValue<T>*>(data)[offset / ELEMENTS].get();
Chris@47 980 }
Chris@47 981
Chris@47 982 template <>
Chris@47 983 inline bool StructBuilder::getDataField<bool>(ElementCount offset) {
Chris@47 984 BitCount boffset = offset * (1 * BITS / ELEMENTS);
Chris@47 985 byte* b = reinterpret_cast<byte*>(data) + boffset / BITS_PER_BYTE;
Chris@47 986 return (*reinterpret_cast<uint8_t*>(b) & (1 << (boffset % BITS_PER_BYTE / BITS))) != 0;
Chris@47 987 }
Chris@47 988
Chris@47 989 template <>
Chris@47 990 inline Void StructBuilder::getDataField<Void>(ElementCount offset) {
Chris@47 991 return VOID;
Chris@47 992 }
Chris@47 993
Chris@47 994 template <typename T>
Chris@47 995 inline T StructBuilder::getDataField(ElementCount offset, Mask<T> mask) {
Chris@47 996 return unmask<T>(getDataField<Mask<T> >(offset), mask);
Chris@47 997 }
Chris@47 998
Chris@47 999 template <typename T>
Chris@47 1000 inline void StructBuilder::setDataField(ElementCount offset, kj::NoInfer<T> value) {
Chris@47 1001 reinterpret_cast<WireValue<T>*>(data)[offset / ELEMENTS].set(value);
Chris@47 1002 }
Chris@47 1003
Chris@47 1004 #if CAPNP_CANONICALIZE_NAN
Chris@47 1005 // Use mask() on floats and doubles to make sure we canonicalize NaNs.
Chris@47 1006 template <>
Chris@47 1007 inline void StructBuilder::setDataField<float>(ElementCount offset, float value) {
Chris@47 1008 setDataField<uint32_t>(offset, mask<float>(value, 0));
Chris@47 1009 }
Chris@47 1010 template <>
Chris@47 1011 inline void StructBuilder::setDataField<double>(ElementCount offset, double value) {
Chris@47 1012 setDataField<uint64_t>(offset, mask<double>(value, 0));
Chris@47 1013 }
Chris@47 1014 #endif
Chris@47 1015
Chris@47 1016 template <>
Chris@47 1017 inline void StructBuilder::setDataField<bool>(ElementCount offset, bool value) {
Chris@47 1018 BitCount boffset = offset * (1 * BITS / ELEMENTS);
Chris@47 1019 byte* b = reinterpret_cast<byte*>(data) + boffset / BITS_PER_BYTE;
Chris@47 1020 uint bitnum = boffset % BITS_PER_BYTE / BITS;
Chris@47 1021 *reinterpret_cast<uint8_t*>(b) = (*reinterpret_cast<uint8_t*>(b) & ~(1 << bitnum))
Chris@47 1022 | (static_cast<uint8_t>(value) << bitnum);
Chris@47 1023 }
Chris@47 1024
Chris@47 1025 template <>
Chris@47 1026 inline void StructBuilder::setDataField<Void>(ElementCount offset, Void value) {}
Chris@47 1027
Chris@47 1028 template <typename T>
Chris@47 1029 inline void StructBuilder::setDataField(ElementCount offset, kj::NoInfer<T> value, Mask<T> m) {
Chris@47 1030 setDataField<Mask<T> >(offset, mask<T>(value, m));
Chris@47 1031 }
Chris@47 1032
Chris@47 1033 inline PointerBuilder StructBuilder::getPointerField(WirePointerCount ptrIndex) {
Chris@47 1034 // Hacky because WirePointer is defined in the .c++ file (so is incomplete here).
Chris@47 1035 return PointerBuilder(segment, capTable, reinterpret_cast<WirePointer*>(
Chris@47 1036 reinterpret_cast<word*>(pointers) + ptrIndex * WORDS_PER_POINTER));
Chris@47 1037 }
Chris@47 1038
Chris@47 1039 // -------------------------------------------------------------------
Chris@47 1040
Chris@47 1041 inline kj::ArrayPtr<const byte> StructReader::getDataSectionAsBlob() {
Chris@47 1042 return kj::ArrayPtr<const byte>(reinterpret_cast<const byte*>(data), dataSize / BITS_PER_BYTE / BYTES);
Chris@47 1043 }
Chris@47 1044
Chris@47 1045 inline _::ListReader StructReader::getPointerSectionAsList() {
Chris@47 1046 return _::ListReader(segment, capTable, pointers, pointerCount * (1 * ELEMENTS / POINTERS),
Chris@47 1047 1 * POINTERS * BITS_PER_POINTER / ELEMENTS, 0 * BITS, 1 * POINTERS,
Chris@47 1048 ElementSize::POINTER, nestingLimit);
Chris@47 1049 }
Chris@47 1050
Chris@47 1051 template <typename T>
Chris@47 1052 inline bool StructReader::hasDataField(ElementCount offset) const {
Chris@47 1053 return getDataField<Mask<T>>(offset) != 0;
Chris@47 1054 }
Chris@47 1055
Chris@47 1056 template <>
Chris@47 1057 inline bool StructReader::hasDataField<Void>(ElementCount offset) const {
Chris@47 1058 return false;
Chris@47 1059 }
Chris@47 1060
Chris@47 1061 template <typename T>
Chris@47 1062 inline T StructReader::getDataField(ElementCount offset) const {
Chris@47 1063 if ((offset + 1 * ELEMENTS) * capnp::bitsPerElement<T>() <= dataSize) {
Chris@47 1064 return reinterpret_cast<const WireValue<T>*>(data)[offset / ELEMENTS].get();
Chris@47 1065 } else {
Chris@47 1066 return static_cast<T>(0);
Chris@47 1067 }
Chris@47 1068 }
Chris@47 1069
Chris@47 1070 template <>
Chris@47 1071 inline bool StructReader::getDataField<bool>(ElementCount offset) const {
Chris@47 1072 BitCount boffset = offset * (1 * BITS / ELEMENTS);
Chris@47 1073 if (boffset < dataSize) {
Chris@47 1074 const byte* b = reinterpret_cast<const byte*>(data) + boffset / BITS_PER_BYTE;
Chris@47 1075 return (*reinterpret_cast<const uint8_t*>(b) & (1 << (boffset % BITS_PER_BYTE / BITS))) != 0;
Chris@47 1076 } else {
Chris@47 1077 return false;
Chris@47 1078 }
Chris@47 1079 }
Chris@47 1080
Chris@47 1081 template <>
Chris@47 1082 inline Void StructReader::getDataField<Void>(ElementCount offset) const {
Chris@47 1083 return VOID;
Chris@47 1084 }
Chris@47 1085
Chris@47 1086 template <typename T>
Chris@47 1087 T StructReader::getDataField(ElementCount offset, Mask<T> mask) const {
Chris@47 1088 return unmask<T>(getDataField<Mask<T> >(offset), mask);
Chris@47 1089 }
Chris@47 1090
Chris@47 1091 inline PointerReader StructReader::getPointerField(WirePointerCount ptrIndex) const {
Chris@47 1092 if (ptrIndex < pointerCount) {
Chris@47 1093 // Hacky because WirePointer is defined in the .c++ file (so is incomplete here).
Chris@47 1094 return PointerReader(segment, capTable, reinterpret_cast<const WirePointer*>(
Chris@47 1095 reinterpret_cast<const word*>(pointers) + ptrIndex * WORDS_PER_POINTER), nestingLimit);
Chris@47 1096 } else{
Chris@47 1097 return PointerReader();
Chris@47 1098 }
Chris@47 1099 }
Chris@47 1100
Chris@47 1101 // -------------------------------------------------------------------
Chris@47 1102
Chris@47 1103 inline ElementCount ListBuilder::size() const { return elementCount; }
Chris@47 1104
Chris@47 1105 template <typename T>
Chris@47 1106 inline T ListBuilder::getDataElement(ElementCount index) {
Chris@47 1107 return reinterpret_cast<WireValue<T>*>(ptr + index * step / BITS_PER_BYTE)->get();
Chris@47 1108
Chris@47 1109 // TODO(perf): Benchmark this alternate implementation, which I suspect may make better use of
Chris@47 1110 // the x86 SIB byte. Also use it for all the other getData/setData implementations below, and
Chris@47 1111 // the various non-inline methods that look up pointers.
Chris@47 1112 // Also if using this, consider changing ptr back to void* instead of byte*.
Chris@47 1113 // return reinterpret_cast<WireValue<T>*>(ptr)[
Chris@47 1114 // index / ELEMENTS * (step / capnp::bitsPerElement<T>())].get();
Chris@47 1115 }
Chris@47 1116
Chris@47 1117 template <>
Chris@47 1118 inline bool ListBuilder::getDataElement<bool>(ElementCount index) {
Chris@47 1119 // Ignore step for bit lists because bit lists cannot be upgraded to struct lists.
Chris@47 1120 BitCount bindex = index * (1 * BITS / ELEMENTS);
Chris@47 1121 byte* b = ptr + bindex / BITS_PER_BYTE;
Chris@47 1122 return (*reinterpret_cast<uint8_t*>(b) & (1 << (bindex % BITS_PER_BYTE / BITS))) != 0;
Chris@47 1123 }
Chris@47 1124
Chris@47 1125 template <>
Chris@47 1126 inline Void ListBuilder::getDataElement<Void>(ElementCount index) {
Chris@47 1127 return VOID;
Chris@47 1128 }
Chris@47 1129
Chris@47 1130 template <typename T>
Chris@47 1131 inline void ListBuilder::setDataElement(ElementCount index, kj::NoInfer<T> value) {
Chris@47 1132 reinterpret_cast<WireValue<T>*>(ptr + index * step / BITS_PER_BYTE)->set(value);
Chris@47 1133 }
Chris@47 1134
Chris@47 1135 #if CAPNP_CANONICALIZE_NAN
Chris@47 1136 // Use mask() on floats and doubles to make sure we canonicalize NaNs.
Chris@47 1137 template <>
Chris@47 1138 inline void ListBuilder::setDataElement<float>(ElementCount index, float value) {
Chris@47 1139 setDataElement<uint32_t>(index, mask<float>(value, 0));
Chris@47 1140 }
Chris@47 1141 template <>
Chris@47 1142 inline void ListBuilder::setDataElement<double>(ElementCount index, double value) {
Chris@47 1143 setDataElement<uint64_t>(index, mask<double>(value, 0));
Chris@47 1144 }
Chris@47 1145 #endif
Chris@47 1146
Chris@47 1147 template <>
Chris@47 1148 inline void ListBuilder::setDataElement<bool>(ElementCount index, bool value) {
Chris@47 1149 // Ignore stepBytes for bit lists because bit lists cannot be upgraded to struct lists.
Chris@47 1150 BitCount bindex = index * (1 * BITS / ELEMENTS);
Chris@47 1151 byte* b = ptr + bindex / BITS_PER_BYTE;
Chris@47 1152 uint bitnum = bindex % BITS_PER_BYTE / BITS;
Chris@47 1153 *reinterpret_cast<uint8_t*>(b) = (*reinterpret_cast<uint8_t*>(b) & ~(1 << bitnum))
Chris@47 1154 | (static_cast<uint8_t>(value) << bitnum);
Chris@47 1155 }
Chris@47 1156
Chris@47 1157 template <>
Chris@47 1158 inline void ListBuilder::setDataElement<Void>(ElementCount index, Void value) {}
Chris@47 1159
Chris@47 1160 inline PointerBuilder ListBuilder::getPointerElement(ElementCount index) {
Chris@47 1161 return PointerBuilder(segment, capTable,
Chris@47 1162 reinterpret_cast<WirePointer*>(ptr + index * step / BITS_PER_BYTE));
Chris@47 1163 }
Chris@47 1164
Chris@47 1165 // -------------------------------------------------------------------
Chris@47 1166
Chris@47 1167 inline ElementCount ListReader::size() const { return elementCount; }
Chris@47 1168
Chris@47 1169 template <typename T>
Chris@47 1170 inline T ListReader::getDataElement(ElementCount index) const {
Chris@47 1171 return reinterpret_cast<const WireValue<T>*>(ptr + index * step / BITS_PER_BYTE)->get();
Chris@47 1172 }
Chris@47 1173
Chris@47 1174 template <>
Chris@47 1175 inline bool ListReader::getDataElement<bool>(ElementCount index) const {
Chris@47 1176 // Ignore step for bit lists because bit lists cannot be upgraded to struct lists.
Chris@47 1177 BitCount bindex = index * (1 * BITS / ELEMENTS);
Chris@47 1178 const byte* b = ptr + bindex / BITS_PER_BYTE;
Chris@47 1179 return (*reinterpret_cast<const uint8_t*>(b) & (1 << (bindex % BITS_PER_BYTE / BITS))) != 0;
Chris@47 1180 }
Chris@47 1181
Chris@47 1182 template <>
Chris@47 1183 inline Void ListReader::getDataElement<Void>(ElementCount index) const {
Chris@47 1184 return VOID;
Chris@47 1185 }
Chris@47 1186
Chris@47 1187 inline PointerReader ListReader::getPointerElement(ElementCount index) const {
Chris@47 1188 return PointerReader(segment, capTable,
Chris@47 1189 reinterpret_cast<const WirePointer*>(ptr + index * step / BITS_PER_BYTE), nestingLimit);
Chris@47 1190 }
Chris@47 1191
Chris@47 1192 // -------------------------------------------------------------------
Chris@47 1193
Chris@47 1194 inline OrphanBuilder::OrphanBuilder(OrphanBuilder&& other) noexcept
Chris@47 1195 : segment(other.segment), capTable(other.capTable), location(other.location) {
Chris@47 1196 memcpy(&tag, &other.tag, sizeof(tag)); // Needs memcpy to comply with aliasing rules.
Chris@47 1197 other.segment = nullptr;
Chris@47 1198 other.location = nullptr;
Chris@47 1199 }
Chris@47 1200
Chris@47 1201 inline OrphanBuilder::~OrphanBuilder() noexcept(false) {
Chris@47 1202 if (segment != nullptr) euthanize();
Chris@47 1203 }
Chris@47 1204
Chris@47 1205 inline OrphanBuilder& OrphanBuilder::operator=(OrphanBuilder&& other) {
Chris@47 1206 // With normal smart pointers, it's important to handle the case where the incoming pointer
Chris@47 1207 // is actually transitively owned by this one. In this case, euthanize() would destroy `other`
Chris@47 1208 // before we copied it. This isn't possible in the case of `OrphanBuilder` because it only
Chris@47 1209 // owns message objects, and `other` is not itself a message object, therefore cannot possibly
Chris@47 1210 // be transitively owned by `this`.
Chris@47 1211
Chris@47 1212 if (segment != nullptr) euthanize();
Chris@47 1213 segment = other.segment;
Chris@47 1214 capTable = other.capTable;
Chris@47 1215 location = other.location;
Chris@47 1216 memcpy(&tag, &other.tag, sizeof(tag)); // Needs memcpy to comply with aliasing rules.
Chris@47 1217 other.segment = nullptr;
Chris@47 1218 other.location = nullptr;
Chris@47 1219 return *this;
Chris@47 1220 }
Chris@47 1221
Chris@47 1222 } // namespace _ (private)
Chris@47 1223 } // namespace capnp
Chris@47 1224
Chris@47 1225 #endif // CAPNP_LAYOUT_H_