annotate win32-mingw/include/capnp/layout.h @ 50:37d53a7e8262

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