schema-loader.c++ 45.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Kenton Varda's avatar
Kenton Varda committed
24
#define CAPNP_PRIVATE
25 26 27 28 29
#include "schema-loader.h"
#include <unordered_map>
#include <map>
#include "message.h"
#include "arena.h"
Kenton Varda's avatar
Kenton Varda committed
30
#include <kj/debug.h>
31
#include <kj/exception.h>
32
#include <kj/arena.h>
33

34
namespace capnp {
35

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
class SchemaLoader::InitializerImpl: public _::RawSchema::Initializer {
public:
  inline explicit InitializerImpl(const SchemaLoader& loader): loader(loader), callback(nullptr) {}
  inline InitializerImpl(const SchemaLoader& loader, const LazyLoadCallback& callback)
      : loader(loader), callback(callback) {}

  inline kj::Maybe<const LazyLoadCallback&> getCallback() const { return callback; }

  void init(const _::RawSchema* schema) const override;

  inline bool operator==(decltype(nullptr)) const { return callback == nullptr; }

private:
  const SchemaLoader& loader;
  kj::Maybe<const LazyLoadCallback&> callback;
};

53 54
class SchemaLoader::Impl {
public:
55 56 57 58 59
  inline explicit Impl(const SchemaLoader& loader): initializer(loader) {}
  inline Impl(const SchemaLoader& loader, const LazyLoadCallback& callback)
      : initializer(loader, callback) {}

  _::RawSchema* load(const schema::Node::Reader& reader, bool isPlaceholder);
60

61
  _::RawSchema* loadNative(const _::RawSchema* nativeSchema);
62

63
  _::RawSchema* loadEmpty(uint64_t id, kj::StringPtr name, schema::Node::Body::Which kind);
64 65
  // Create a dummy empty schema of the given kind for the given id and load it.

66 67 68 69 70 71
  struct TryGetResult {
    _::RawSchema* schema;
    kj::Maybe<const LazyLoadCallback&> callback;
  };

  TryGetResult tryGet(uint64_t typeId) const;
72
  kj::Array<Schema> getAllLoaded() const;
73

74
  kj::Arena arena;
75 76

private:
77
  std::unordered_map<uint64_t, _::RawSchema*> schemas;
78 79

  InitializerImpl initializer;
80 81 82 83 84 85 86 87
};

// =======================================================================================

class SchemaLoader::Validator {
public:
  Validator(SchemaLoader::Impl& loader): loader(loader) {}

88
  bool validate(const schema::Node::Reader& node) {
89 90 91 92
    isValid = true;
    nodeName = node.getDisplayName();
    dependencies.clear();

93
    KJ_CONTEXT("validating schema node", nodeName, (uint)node.getBody().which());
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

    switch (node.getBody().which()) {
      case schema::Node::Body::FILE_NODE:
        validate(node.getBody().getFileNode());
        break;
      case schema::Node::Body::STRUCT_NODE:
        validate(node.getBody().getStructNode());
        break;
      case schema::Node::Body::ENUM_NODE:
        validate(node.getBody().getEnumNode());
        break;
      case schema::Node::Body::INTERFACE_NODE:
        validate(node.getBody().getInterfaceNode());
        break;
      case schema::Node::Body::CONST_NODE:
        validate(node.getBody().getConstNode());
        break;
      case schema::Node::Body::ANNOTATION_NODE:
        validate(node.getBody().getAnnotationNode());
        break;
    }

    // We accept and pass through node types we don't recognize.
    return isValid;
  }

120
  const _::RawSchema** makeDependencyArray(uint32_t* count) {
121
    *count = dependencies.size();
122 123
    kj::ArrayPtr<const _::RawSchema*> result =
        loader.arena.allocateArray<const _::RawSchema*>(*count);
124 125 126 127
    uint pos = 0;
    for (auto& dep: dependencies) {
      result[pos++] = dep.second;
    }
128
    KJ_DASSERT(pos == *count);
129
    return result.begin();
130 131
  }

132
  const _::RawSchema::MemberInfo* makeMemberInfoArray(uint32_t* count) {
133
    *count = members.size();
134 135
    kj::ArrayPtr<_::RawSchema::MemberInfo> result =
        loader.arena.allocateArray<_::RawSchema::MemberInfo>(*count);
136 137
    uint pos = 0;
    for (auto& member: members) {
138 139
      result[pos++] = {kj::implicitCast<uint16_t>(member.first.first),
                       kj::implicitCast<uint16_t>(member.second)};
140
    }
141
    KJ_DASSERT(pos == *count);
142
    return result.begin();
143 144 145 146 147 148
  }

private:
  SchemaLoader::Impl& loader;
  Text::Reader nodeName;
  bool isValid;
149
  std::map<uint64_t, _::RawSchema*> dependencies;
150 151 152 153 154

  // Maps (unionIndex, name) -> index for each member.
  std::map<std::pair<uint, Text::Reader>, uint> members;

#define VALIDATE_SCHEMA(condition, ...) \
155
  KJ_REQUIRE(condition, ##__VA_ARGS__) { isValid = false; return; }
156
#define FAIL_VALIDATE_SCHEMA(...) \
157
  KJ_FAIL_REQUIRE(__VA_ARGS__) { isValid = false; return; }
158

159
  void validate(const schema::FileNode::Reader& fileNode) {
160 161 162
    // Nothing needs validation.
  }

163
  void validate(const schema::StructNode::Reader& structNode) {
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    uint dataSizeInBits;
    uint pointerCount;

    switch (structNode.getPreferredListEncoding()) {
      case schema::ElementSize::EMPTY:
        dataSizeInBits = 0;
        pointerCount = 0;
        break;
      case schema::ElementSize::BIT:
        dataSizeInBits = 1;
        pointerCount = 0;
        break;
      case schema::ElementSize::BYTE:
        dataSizeInBits = 8;
        pointerCount = 0;
        break;
      case schema::ElementSize::TWO_BYTES:
        dataSizeInBits = 16;
        pointerCount = 0;
        break;
      case schema::ElementSize::FOUR_BYTES:
        dataSizeInBits = 32;
        pointerCount = 0;
        break;
      case schema::ElementSize::EIGHT_BYTES:
        dataSizeInBits = 64;
        pointerCount = 0;
        break;
      case schema::ElementSize::POINTER:
        dataSizeInBits = 0;
        pointerCount = 1;
        break;
      case schema::ElementSize::INLINE_COMPOSITE:
        dataSizeInBits = structNode.getDataSectionWordSize() * 64;
        pointerCount = structNode.getPointerSectionSize();
        break;
      default:
        FAIL_VALIDATE_SCHEMA("Invalid preferredListEncoding.");
        dataSizeInBits = 0;
        pointerCount = 0;
        break;
    }

    VALIDATE_SCHEMA(structNode.getDataSectionWordSize() == (dataSizeInBits + 63) / 64 &&
                    structNode.getPointerSectionSize() == pointerCount,
                    "Struct size does not match preferredListEncoding.");

    uint ordinalCount = 0;

    auto members = structNode.getMembers();
    for (auto member: members) {
      ++ordinalCount;
      if (member.getBody().which() == schema::StructNode::Member::Body::UNION_MEMBER) {
        ordinalCount += member.getBody().getUnionMember().getMembers().size();
      }
    }

221
    KJ_STACK_ARRAY(bool, sawCodeOrder, members.size(), 32, 256);
222
    memset(sawCodeOrder.begin(), 0, sawCodeOrder.size() * sizeof(sawCodeOrder[0]));
223
    KJ_STACK_ARRAY(bool, sawOrdinal, ordinalCount, 32, 256);
224 225 226 227
    memset(sawOrdinal.begin(), 0, sawOrdinal.size() * sizeof(sawOrdinal[0]));

    uint index = 0;
    for (auto member: members) {
228
      KJ_CONTEXT("validating struct member", member.getName());
229 230 231 232
      validate(member, sawCodeOrder, sawOrdinal, dataSizeInBits, pointerCount, 0, index++);
    }
  }

233
  void validateMemberName(kj::StringPtr name, uint unionIndex, uint index) {
234 235 236 237 238
    bool isNewName = members.insert(std::make_pair(
        std::pair<uint, Text::Reader>(unionIndex, name), index)).second;
    VALIDATE_SCHEMA(isNewName, "duplicate name", name);
  }

239
  void validate(const schema::StructNode::Member::Reader& member,
240
                kj::ArrayPtr<bool> sawCodeOrder, kj::ArrayPtr<bool> sawOrdinal,
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
                uint dataSizeInBits, uint pointerCount,
                uint unionIndex, uint index) {
    validateMemberName(member.getName(), unionIndex, index);

    VALIDATE_SCHEMA(member.getOrdinal() < sawOrdinal.size() &&
                    !sawOrdinal[member.getOrdinal()],
                    "Invalid ordinal.");
    sawOrdinal[member.getOrdinal()] = true;
    VALIDATE_SCHEMA(member.getCodeOrder() < sawCodeOrder.size() &&
                    !sawCodeOrder[member.getCodeOrder()],
                    "Invalid codeOrder.");
    sawCodeOrder[member.getCodeOrder()] = true;

    switch (member.getBody().which()) {
      case schema::StructNode::Member::Body::FIELD_MEMBER: {
        auto field = member.getBody().getFieldMember();

        uint fieldBits;
        bool fieldIsPointer;
        validate(field.getType(), field.getDefaultValue(), &fieldBits, &fieldIsPointer);
        VALIDATE_SCHEMA(fieldBits * (field.getOffset() + 1) <= dataSizeInBits &&
                        fieldIsPointer * (field.getOffset() + 1) <= pointerCount,
                        "field offset out-of-bounds",
                        field.getOffset(), dataSizeInBits, pointerCount);
        break;
      }

      case schema::StructNode::Member::Body::UNION_MEMBER: {
        auto u = member.getBody().getUnionMember();

        VALIDATE_SCHEMA((u.getDiscriminantOffset() + 1) * 16 <= dataSizeInBits,
                        "Schema invalid: Union discriminant out-of-bounds.");

        auto uMembers = u.getMembers();
275
        KJ_STACK_ARRAY(bool, uSawCodeOrder, uMembers.size(), 32, 256);
276 277 278 279
        memset(uSawCodeOrder.begin(), 0, uSawCodeOrder.size() * sizeof(uSawCodeOrder[0]));

        uint subIndex = 0;
        for (auto uMember: uMembers) {
280
          KJ_CONTEXT("validating union member", uMember.getName());
281 282 283 284 285 286 287 288 289 290 291
          VALIDATE_SCHEMA(
              uMember.getBody().which() == schema::StructNode::Member::Body::FIELD_MEMBER,
              "Union members must be fields.");
          validate(uMember, uSawCodeOrder, sawOrdinal, dataSizeInBits, pointerCount,
                   index + 1, subIndex++);
        }
        break;
      }
    }
  }

292
  void validate(const schema::EnumNode::Reader& enumNode) {
293 294
    auto enumerants = enumNode.getEnumerants();

295
    KJ_STACK_ARRAY(bool, sawCodeOrder, enumerants.size(), 32, 256);
296 297 298 299 300 301 302 303 304 305 306 307 308
    memset(sawCodeOrder.begin(), 0, sawCodeOrder.size() * sizeof(sawCodeOrder[0]));

    uint index = 0;
    for (auto enumerant: enumerants) {
      validateMemberName(enumerant.getName(), 0, index++);

      VALIDATE_SCHEMA(enumerant.getCodeOrder() < enumerants.size() &&
                      !sawCodeOrder[enumerant.getCodeOrder()],
                      "invalid codeOrder", enumerant.getName());
      sawCodeOrder[enumerant.getCodeOrder()] = true;
    }
  }

309
  void validate(const schema::InterfaceNode::Reader& interfaceNode) {
310 311
    auto methods = interfaceNode.getMethods();

312
    KJ_STACK_ARRAY(bool, sawCodeOrder, methods.size(), 32, 256);
313 314 315 316
    memset(sawCodeOrder.begin(), 0, sawCodeOrder.size() * sizeof(sawCodeOrder[0]));

    uint index = 0;
    for (auto method: methods) {
317
      KJ_CONTEXT("validating method", method.getName());
318 319 320 321 322 323 324 325 326
      validateMemberName(method.getName(), 0, index++);

      VALIDATE_SCHEMA(method.getCodeOrder() < methods.size() &&
                      !sawCodeOrder[method.getCodeOrder()],
                      "invalid codeOrder");
      sawCodeOrder[method.getCodeOrder()] = true;

      auto params = method.getParams();
      for (auto param: params) {
327
        KJ_CONTEXT("validating parameter", param.getName());
328 329 330 331 332 333 334 335 336 337 338
        uint dummy1;
        bool dummy2;
        validate(param.getType(), param.getDefaultValue(), &dummy1, &dummy2);
      }

      VALIDATE_SCHEMA(method.getRequiredParamCount() <= params.size(),
                      "invalid requiredParamCount");
      validate(method.getReturnType());
    }
  }

339
  void validate(const schema::ConstNode::Reader& constNode) {
340 341 342 343 344
    uint dummy1;
    bool dummy2;
    validate(constNode.getType(), constNode.getValue(), &dummy1, &dummy2);
  }

345
  void validate(const schema::AnnotationNode::Reader& annotationNode) {
346 347 348
    validate(annotationNode.getType());
  }

349
  void validate(const schema::Type::Reader& type, const schema::Value::Reader& value,
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
                uint* dataSizeInBits, bool* isPointer) {
    validate(type);

    schema::Value::Body::Which expectedValueType = schema::Value::Body::VOID_VALUE;
    bool hadCase = false;
    switch (type.getBody().which()) {
#define HANDLE_TYPE(name, bits, ptr) \
      case schema::Type::Body::name##_TYPE: \
        expectedValueType = schema::Value::Body::name##_VALUE; \
        *dataSizeInBits = bits; *isPointer = ptr; \
        hadCase = true; \
        break;
      HANDLE_TYPE(VOID, 0, false)
      HANDLE_TYPE(BOOL, 1, false)
      HANDLE_TYPE(INT8, 8, false)
      HANDLE_TYPE(INT16, 16, false)
      HANDLE_TYPE(INT32, 32, false)
      HANDLE_TYPE(INT64, 64, false)
      HANDLE_TYPE(UINT8, 8, false)
      HANDLE_TYPE(UINT16, 16, false)
      HANDLE_TYPE(UINT32, 32, false)
      HANDLE_TYPE(UINT64, 64, false)
      HANDLE_TYPE(FLOAT32, 32, false)
      HANDLE_TYPE(FLOAT64, 64, false)
      HANDLE_TYPE(TEXT, 0, true)
      HANDLE_TYPE(DATA, 0, true)
      HANDLE_TYPE(LIST, 0, true)
      HANDLE_TYPE(ENUM, 16, false)
      HANDLE_TYPE(STRUCT, 0, true)
      HANDLE_TYPE(INTERFACE, 0, true)
      HANDLE_TYPE(OBJECT, 0, true)
#undef HANDLE_TYPE
    }

    if (hadCase) {
      VALIDATE_SCHEMA(value.getBody().which() == expectedValueType, "Value did not match type.");
    }
  }

389
  void validate(const schema::Type::Reader& type) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    switch (type.getBody().which()) {
      case schema::Type::Body::VOID_TYPE:
      case schema::Type::Body::BOOL_TYPE:
      case schema::Type::Body::INT8_TYPE:
      case schema::Type::Body::INT16_TYPE:
      case schema::Type::Body::INT32_TYPE:
      case schema::Type::Body::INT64_TYPE:
      case schema::Type::Body::UINT8_TYPE:
      case schema::Type::Body::UINT16_TYPE:
      case schema::Type::Body::UINT32_TYPE:
      case schema::Type::Body::UINT64_TYPE:
      case schema::Type::Body::FLOAT32_TYPE:
      case schema::Type::Body::FLOAT64_TYPE:
      case schema::Type::Body::TEXT_TYPE:
      case schema::Type::Body::DATA_TYPE:
      case schema::Type::Body::OBJECT_TYPE:
        break;

      case schema::Type::Body::STRUCT_TYPE:
        validateTypeId(type.getBody().getStructType(), schema::Node::Body::STRUCT_NODE);
        break;
      case schema::Type::Body::ENUM_TYPE:
        validateTypeId(type.getBody().getEnumType(), schema::Node::Body::ENUM_NODE);
        break;
      case schema::Type::Body::INTERFACE_TYPE:
        validateTypeId(type.getBody().getInterfaceType(), schema::Node::Body::INTERFACE_NODE);
        break;

      case schema::Type::Body::LIST_TYPE:
        validate(type.getBody().getListType());
        break;
    }

    // We intentionally allow unknown types.
  }

  void validateTypeId(uint64_t id, schema::Node::Body::Which expectedKind) {
427
    _::RawSchema* existing = loader.tryGet(id).schema;
428 429 430 431
    if (existing != nullptr) {
      auto node = readMessageUnchecked<schema::Node>(existing->encodedNode);
      VALIDATE_SCHEMA(node.getBody().which() == expectedKind,
          "expected a different kind of node for this ID",
Kenton Varda's avatar
Kenton Varda committed
432
          id, (uint)expectedKind, (uint)node.getBody().which(), node.getDisplayName());
433 434 435 436 437
      dependencies.insert(std::make_pair(id, existing));
      return;
    }

    dependencies.insert(std::make_pair(id, loader.loadEmpty(
438
        id, kj::str("(unknown type used by ", nodeName , ")"), expectedKind)));
439 440 441 442 443 444 445 446 447 448 449 450
  }

#undef VALIDATE_SCHEMA
#undef FAIL_VALIDATE_SCHEMA
};

// =======================================================================================

class SchemaLoader::CompatibilityChecker {
public:
  CompatibilityChecker(SchemaLoader::Impl& loader): loader(loader) {}

451 452
  bool shouldReplace(const schema::Node::Reader& existingNode,
                     const schema::Node::Reader& replacement,
453
                     bool preferReplacementIfEquivalent) {
454 455
    KJ_CONTEXT("checking compatibility with previously-loaded node of the same id",
               existingNode.getDisplayName());
456

457
    KJ_DREQUIRE(existingNode.getId() == replacement.getId());
458 459 460 461 462 463

    nodeName = existingNode.getDisplayName();
    compatibility = EQUIVALENT;

    checkCompatibility(existingNode, replacement);

464 465
    // Prefer the newer schema.
    return preferReplacementIfEquivalent ? compatibility != OLDER : compatibility == NEWER;
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  }

private:
  SchemaLoader::Impl& loader;
  Text::Reader nodeName;

  enum Compatibility {
    EQUIVALENT,
    OLDER,
    NEWER,
    INCOMPATIBLE
  };
  Compatibility compatibility;

#define VALIDATE_SCHEMA(condition, ...) \
481
  KJ_REQUIRE(condition, ##__VA_ARGS__) { compatibility = INCOMPATIBLE; return; }
482
#define FAIL_VALIDATE_SCHEMA(...) \
483
  KJ_FAIL_REQUIRE(__VA_ARGS__) { compatibility = INCOMPATIBLE; return; }
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

  void replacementIsNewer() {
    switch (compatibility) {
      case EQUIVALENT:
        compatibility = NEWER;
        break;
      case OLDER:
        FAIL_VALIDATE_SCHEMA("Schema node contains some changes that are upgrades and some "
            "that are downgrades.  All changes must be in the same direction for compatibility.");
        break;
      case NEWER:
        break;
      case INCOMPATIBLE:
        break;
    }
  }

  void replacementIsOlder() {
    switch (compatibility) {
      case EQUIVALENT:
        compatibility = OLDER;
        break;
      case OLDER:
        break;
      case NEWER:
        FAIL_VALIDATE_SCHEMA("Schema node contains some changes that are upgrades and some "
            "that are downgrades.  All changes must be in the same direction for compatibility.");
        break;
      case INCOMPATIBLE:
        break;
    }
  }

517 518
  void checkCompatibility(const schema::Node::Reader& node,
                          const schema::Node::Reader& replacement) {
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    // Returns whether `replacement` is equivalent, older than, newer than, or incompatible with
    // `node`.  If exceptions are enabled, this will throw an exception on INCOMPATIBLE.

    VALIDATE_SCHEMA(node.getBody().which() == replacement.getBody().which(),
                    "kind of declaration changed");

    // No need to check compatibility of the non-body parts of the node:
    // - Arbitrary renaming and moving between scopes is allowed.
    // - Annotations are ignored for compatibility purposes.

    switch (node.getBody().which()) {
      case schema::Node::Body::FILE_NODE:
        checkCompatibility(node.getBody().getFileNode(),
                           replacement.getBody().getFileNode());
        break;
      case schema::Node::Body::STRUCT_NODE:
        checkCompatibility(node.getBody().getStructNode(),
                           replacement.getBody().getStructNode());
        break;
      case schema::Node::Body::ENUM_NODE:
        checkCompatibility(node.getBody().getEnumNode(),
                           replacement.getBody().getEnumNode());
        break;
      case schema::Node::Body::INTERFACE_NODE:
        checkCompatibility(node.getBody().getInterfaceNode(),
                           replacement.getBody().getInterfaceNode());
        break;
      case schema::Node::Body::CONST_NODE:
        checkCompatibility(node.getBody().getConstNode(),
                           replacement.getBody().getConstNode());
        break;
      case schema::Node::Body::ANNOTATION_NODE:
        checkCompatibility(node.getBody().getAnnotationNode(),
                           replacement.getBody().getAnnotationNode());
        break;
    }
  }

557 558
  void checkCompatibility(const schema::FileNode::Reader& file,
                          const schema::FileNode::Reader& replacement) {
559 560 561
    // Nothing to compare.
  }

562 563
  void checkCompatibility(const schema::StructNode::Reader& structNode,
                          const schema::StructNode::Reader& replacement) {
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    if (replacement.getDataSectionWordSize() > structNode.getDataSectionWordSize()) {
      replacementIsNewer();
    } else if (replacement.getDataSectionWordSize() < structNode.getDataSectionWordSize()) {
      replacementIsOlder();
    }
    if (replacement.getPointerSectionSize() > structNode.getPointerSectionSize()) {
      replacementIsNewer();
    } else if (replacement.getPointerSectionSize() < structNode.getPointerSectionSize()) {
      replacementIsOlder();
    }

    // We can do a simple comparison of preferredListEncoding here because the only case where it
    // isn't correct to compare this way is when one side is BIT/BYTE/*_BYTES while the other side
    // is POINTER, and if that were the case then the above comparisons would already have failed
    // or one of the nodes would have failed validation.
    if (replacement.getPreferredListEncoding() > structNode.getPreferredListEncoding()) {
      replacementIsNewer();
    } else if (replacement.getPreferredListEncoding() < structNode.getPreferredListEncoding()) {
      replacementIsOlder();
    }

    // The shared members should occupy corresponding positions in the member lists, since the
    // lists are sorted by ordinal.
    auto members = structNode.getMembers();
    auto replacementMembers = replacement.getMembers();
    uint count = std::min(members.size(), replacementMembers.size());

    if (replacementMembers.size() > members.size()) {
      replacementIsNewer();
    } else if (replacementMembers.size() < members.size()) {
      replacementIsOlder();
    }

    for (uint i = 0; i < count; i++) {
      checkCompatibility(members[i], replacementMembers[i]);
    }
  }

602 603
  void checkCompatibility(const schema::StructNode::Member::Reader& member,
                          const schema::StructNode::Member::Reader& replacement) {
604
    KJ_CONTEXT("comparing struct member", member.getName());
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

    switch (member.getBody().which()) {
      case schema::StructNode::Member::Body::FIELD_MEMBER: {
        auto field = member.getBody().getFieldMember();
        auto replacementField = replacement.getBody().getFieldMember();

        checkCompatibility(field.getType(), replacementField.getType(),
                           NO_UPGRADE_TO_STRUCT);
        checkDefaultCompatibility(field.getDefaultValue(), replacementField.getDefaultValue());

        VALIDATE_SCHEMA(field.getOffset() == replacementField.getOffset(),
                        "field position changed");
        break;
      }
      case schema::StructNode::Member::Body::UNION_MEMBER: {
        auto existingUnion = member.getBody().getUnionMember();
        auto replacementUnion = replacement.getBody().getUnionMember();

        VALIDATE_SCHEMA(
            existingUnion.getDiscriminantOffset() == replacementUnion.getDiscriminantOffset(),
            "union discriminant position changed");

        auto members = existingUnion.getMembers();
        auto replacementMembers = replacementUnion.getMembers();
        uint count = std::min(members.size(), replacementMembers.size());

        if (replacementMembers.size() > members.size()) {
          replacementIsNewer();
        } else if (replacementMembers.size() < members.size()) {
          replacementIsOlder();
        }

        for (uint i = 0; i < count; i++) {
          checkCompatibility(members[i], replacementMembers[i]);
        }
        break;
      }
    }
  }

645 646
  void checkCompatibility(const schema::EnumNode::Reader& enumNode,
                          const schema::EnumNode::Reader& replacement) {
647 648 649 650 651 652 653 654 655
    uint size = enumNode.getEnumerants().size();
    uint replacementSize = replacement.getEnumerants().size();
    if (replacementSize > size) {
      replacementIsNewer();
    } else if (replacementSize < size) {
      replacementIsOlder();
    }
  }

656 657
  void checkCompatibility(const schema::InterfaceNode::Reader& interfaceNode,
                          const schema::InterfaceNode::Reader& replacement) {
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    auto methods = interfaceNode.getMethods();
    auto replacementMethods = replacement.getMethods();

    if (replacementMethods.size() > methods.size()) {
      replacementIsNewer();
    } else if (replacementMethods.size() < methods.size()) {
      replacementIsOlder();
    }

    uint count = std::min(methods.size(), replacementMethods.size());

    for (uint i = 0; i < count; i++) {
      checkCompatibility(methods[i], replacementMethods[i]);
    }
  }

674 675
  void checkCompatibility(const schema::InterfaceNode::Method::Reader& method,
                          const schema::InterfaceNode::Method::Reader& replacement) {
676
    KJ_CONTEXT("comparing method", method.getName());
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691

    auto params = method.getParams();
    auto replacementParams = replacement.getParams();

    if (replacementParams.size() > params.size()) {
      replacementIsNewer();
    } else if (replacementParams.size() < params.size()) {
      replacementIsOlder();
    }

    uint count = std::min(params.size(), replacementParams.size());
    for (uint i = 0; i < count; i++) {
      auto param = params[i];
      auto replacementParam = replacementParams[i];

692
      KJ_CONTEXT("comparing parameter", param.getName());
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

      checkCompatibility(param.getType(), replacementParam.getType(),
                         NO_UPGRADE_TO_STRUCT);
      checkDefaultCompatibility(param.getDefaultValue(), replacementParam.getDefaultValue());
    }

    // Before checking that the required parameter counts are equal, check if the user added new
    // parameters without defaulting them, as this is the most common reason for this error and we
    // can provide a nicer error message.
    VALIDATE_SCHEMA(replacement.getRequiredParamCount() <= count &&
                    method.getRequiredParamCount() <= count,
        "Updated method signature contains additional parameters that lack default values");

    VALIDATE_SCHEMA(replacement.getRequiredParamCount() == method.getRequiredParamCount(),
        "Updated method signature has different number of required parameters (parameters without "
        "default values)");

    checkCompatibility(method.getReturnType(), replacement.getReturnType(),
                       ALLOW_UPGRADE_TO_STRUCT);
  }

714 715
  void checkCompatibility(const schema::ConstNode::Reader& constNode,
                          const schema::ConstNode::Reader& replacement) {
716 717 718
    // Who cares?  These don't appear on the wire.
  }

719 720
  void checkCompatibility(const schema::AnnotationNode::Reader& annotationNode,
                          const schema::AnnotationNode::Reader& replacement) {
721 722 723 724 725 726 727 728
    // Who cares?  These don't appear on the wire.
  }

  enum UpgradeToStructMode {
    ALLOW_UPGRADE_TO_STRUCT,
    NO_UPGRADE_TO_STRUCT
  };

729 730
  void checkCompatibility(const schema::Type::Reader& type,
                          const schema::Type::Reader& replacement,
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
                          UpgradeToStructMode upgradeToStructMode) {
    if (replacement.getBody().which() != type.getBody().which()) {
      // Check for allowed "upgrade" to Data or Object.
      if (replacement.getBody().which() == schema::Type::Body::DATA_TYPE &&
          canUpgradeToData(type)) {
        replacementIsNewer();
        return;
      } else if (type.getBody().which() == schema::Type::Body::DATA_TYPE &&
                 canUpgradeToData(replacement)) {
        replacementIsOlder();
        return;
      } else if (replacement.getBody().which() == schema::Type::Body::OBJECT_TYPE &&
                 canUpgradeToObject(type)) {
        replacementIsNewer();
        return;
      } else if (type.getBody().which() == schema::Type::Body::OBJECT_TYPE &&
                 canUpgradeToObject(replacement)) {
        replacementIsOlder();
        return;
      }

      if (upgradeToStructMode == ALLOW_UPGRADE_TO_STRUCT) {
        if (type.getBody().which() == schema::Type::Body::STRUCT_TYPE) {
          checkUpgradeToStruct(replacement, type.getBody().getStructType());
          return;
        } else if (replacement.getBody().which() == schema::Type::Body::STRUCT_TYPE) {
          checkUpgradeToStruct(type, replacement.getBody().getStructType());
          return;
        }
      }

      FAIL_VALIDATE_SCHEMA("a type was changed");
    }

    switch (type.getBody().which()) {
      case schema::Type::Body::VOID_TYPE:
      case schema::Type::Body::BOOL_TYPE:
      case schema::Type::Body::INT8_TYPE:
      case schema::Type::Body::INT16_TYPE:
      case schema::Type::Body::INT32_TYPE:
      case schema::Type::Body::INT64_TYPE:
      case schema::Type::Body::UINT8_TYPE:
      case schema::Type::Body::UINT16_TYPE:
      case schema::Type::Body::UINT32_TYPE:
      case schema::Type::Body::UINT64_TYPE:
      case schema::Type::Body::FLOAT32_TYPE:
      case schema::Type::Body::FLOAT64_TYPE:
      case schema::Type::Body::TEXT_TYPE:
      case schema::Type::Body::DATA_TYPE:
      case schema::Type::Body::OBJECT_TYPE:
        return;

      case schema::Type::Body::LIST_TYPE:
784 785 786 787
        checkCompatibility(type.getBody().getListType(),
                           replacement.getBody().getListType(),
                           ALLOW_UPGRADE_TO_STRUCT);
        return;
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

      case schema::Type::Body::ENUM_TYPE:
        VALIDATE_SCHEMA(replacement.getBody().getEnumType() == type.getBody().getEnumType(),
                        "type changed enum type");
        return;

      case schema::Type::Body::STRUCT_TYPE:
        // TODO(someday):  If the IDs don't match, we should compare the two structs for
        //   compatibility.  This is tricky, though, because the new type's target may not yet be
        //   loaded.  In that case we could take the old type, make a copy of it, assign the new
        //   ID to the copy, and load() that.  That forces any struct type loaded for that ID to
        //   be compatible.  However, that has another problem, which is that it could be that the
        //   whole reason the type was replaced was to fork that type, and so an incompatibility
        //   could be very much expected.  This could be a rat hole...
        VALIDATE_SCHEMA(replacement.getBody().getStructType() == type.getBody().getStructType(),
                        "type changed to incompatible struct type");
        return;

      case schema::Type::Body::INTERFACE_TYPE:
        VALIDATE_SCHEMA(
            replacement.getBody().getInterfaceType() == type.getBody().getInterfaceType(),
            "type changed to incompatible interface type");
        return;
    }

    // We assume unknown types (from newer versions of Cap'n Proto?) are equivalent.
  }

816
  void checkUpgradeToStruct(const schema::Type::Reader& type, uint64_t structTypeId) {
817 818 819 820 821 822 823
    // We can't just look up the target struct and check it because it may not have been loaded
    // yet.  Instead, we contrive a struct that looks like what we want and load() that, which
    // guarantees that any incompatibility will be caught either now or when the real version of
    // that struct is loaded.

    word scratch[32];
    memset(scratch, 0, sizeof(scratch));
824
    MallocMessageBuilder builder(kj::arrayPtr(scratch, sizeof(scratch)));
825 826
    auto node = builder.initRoot<schema::Node>();
    node.setId(structTypeId);
827
    node.setDisplayName(kj::str("(unknown type used in ", nodeName, ")"));
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
    auto structNode = node.getBody().initStructNode();

    switch (type.getBody().which()) {
      case schema::Type::Body::VOID_TYPE:
        structNode.setDataSectionWordSize(0);
        structNode.setPointerSectionSize(0);
        structNode.setPreferredListEncoding(schema::ElementSize::EMPTY);
        break;

      case schema::Type::Body::BOOL_TYPE:
        structNode.setDataSectionWordSize(1);
        structNode.setPointerSectionSize(0);
        structNode.setPreferredListEncoding(schema::ElementSize::BIT);
        break;

      case schema::Type::Body::INT8_TYPE:
      case schema::Type::Body::UINT8_TYPE:
        structNode.setDataSectionWordSize(1);
        structNode.setPointerSectionSize(0);
        structNode.setPreferredListEncoding(schema::ElementSize::BYTE);
        break;

      case schema::Type::Body::INT16_TYPE:
      case schema::Type::Body::UINT16_TYPE:
      case schema::Type::Body::ENUM_TYPE:
        structNode.setDataSectionWordSize(1);
        structNode.setPointerSectionSize(0);
        structNode.setPreferredListEncoding(schema::ElementSize::TWO_BYTES);
        break;

      case schema::Type::Body::INT32_TYPE:
      case schema::Type::Body::UINT32_TYPE:
      case schema::Type::Body::FLOAT32_TYPE:
        structNode.setDataSectionWordSize(1);
        structNode.setPointerSectionSize(0);
        structNode.setPreferredListEncoding(schema::ElementSize::FOUR_BYTES);
        break;

      case schema::Type::Body::INT64_TYPE:
      case schema::Type::Body::UINT64_TYPE:
      case schema::Type::Body::FLOAT64_TYPE:
        structNode.setDataSectionWordSize(1);
        structNode.setPointerSectionSize(0);
        structNode.setPreferredListEncoding(schema::ElementSize::EIGHT_BYTES);
        break;

      case schema::Type::Body::TEXT_TYPE:
      case schema::Type::Body::DATA_TYPE:
      case schema::Type::Body::LIST_TYPE:
      case schema::Type::Body::STRUCT_TYPE:
      case schema::Type::Body::INTERFACE_TYPE:
      case schema::Type::Body::OBJECT_TYPE:
        structNode.setDataSectionWordSize(0);
        structNode.setPointerSectionSize(1);
        structNode.setPreferredListEncoding(schema::ElementSize::POINTER);
        break;
    }

    auto member = structNode.initMembers(1)[0];
    member.setName("member0");
    member.setOrdinal(0);
    member.setCodeOrder(0);
    member.getBody().initFieldMember().setType(type);

892
    loader.load(node, true);
893 894
  }

895
  bool canUpgradeToData(const schema::Type::Reader& type) {
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    if (type.getBody().which() == schema::Type::Body::TEXT_TYPE) {
      return true;
    } else if (type.getBody().which() == schema::Type::Body::LIST_TYPE) {
      switch (type.getBody().getListType().getBody().which()) {
        case schema::Type::Body::INT8_TYPE:
        case schema::Type::Body::UINT8_TYPE:
          return true;
        default:
          return false;
      }
    } else {
      return false;
    }
  }

911
  bool canUpgradeToObject(const schema::Type::Reader& type) {
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
    switch (type.getBody().which()) {
      case schema::Type::Body::VOID_TYPE:
      case schema::Type::Body::BOOL_TYPE:
      case schema::Type::Body::INT8_TYPE:
      case schema::Type::Body::INT16_TYPE:
      case schema::Type::Body::INT32_TYPE:
      case schema::Type::Body::INT64_TYPE:
      case schema::Type::Body::UINT8_TYPE:
      case schema::Type::Body::UINT16_TYPE:
      case schema::Type::Body::UINT32_TYPE:
      case schema::Type::Body::UINT64_TYPE:
      case schema::Type::Body::FLOAT32_TYPE:
      case schema::Type::Body::FLOAT64_TYPE:
      case schema::Type::Body::ENUM_TYPE:
        return false;

      case schema::Type::Body::TEXT_TYPE:
      case schema::Type::Body::DATA_TYPE:
      case schema::Type::Body::LIST_TYPE:
      case schema::Type::Body::STRUCT_TYPE:
      case schema::Type::Body::INTERFACE_TYPE:
      case schema::Type::Body::OBJECT_TYPE:
        return true;
    }

    // Be lenient with unknown types.
    return true;
  }

941 942
  void checkDefaultCompatibility(const schema::Value::Reader& value,
                                 const schema::Value::Reader& replacement) {
943 944
    // Note that we test default compatibility only after testing type compatibility, and default
    // values have already been validated as matching their types, so this should pass.
945
    KJ_ASSERT(value.getBody().which() == replacement.getBody().which()) {
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
      compatibility = INCOMPATIBLE;
      return;
    }

    switch (value.getBody().which()) {
#define HANDLE_TYPE(discrim, name) \
      case schema::Value::Body::discrim##_VALUE: \
        VALIDATE_SCHEMA(value.getBody().get##name##Value() == \
                        replacement.getBody().get##name##Value(), \
                        "default value changed"); \
        break;
      HANDLE_TYPE(VOID, Void);
      HANDLE_TYPE(BOOL, Bool);
      HANDLE_TYPE(INT8, Int8);
      HANDLE_TYPE(INT16, Int16);
      HANDLE_TYPE(INT32, Int32);
      HANDLE_TYPE(INT64, Int64);
      HANDLE_TYPE(UINT8, Uint8);
      HANDLE_TYPE(UINT16, Uint16);
      HANDLE_TYPE(UINT32, Uint32);
      HANDLE_TYPE(UINT64, Uint64);
      HANDLE_TYPE(FLOAT32, Float32);
      HANDLE_TYPE(FLOAT64, Float64);
      HANDLE_TYPE(ENUM, Enum);
#undef HANDLE_TYPE

      case schema::Value::Body::TEXT_VALUE:
      case schema::Value::Body::DATA_VALUE:
      case schema::Value::Body::LIST_VALUE:
      case schema::Value::Body::STRUCT_VALUE:
      case schema::Value::Body::INTERFACE_VALUE:
      case schema::Value::Body::OBJECT_VALUE:
        // It's not a big deal if default values for pointers change, and it would be difficult for
        // us to compare these defaults here, so just let it slide.
        break;
    }
  }
};

// =======================================================================================

987
_::RawSchema* SchemaLoader::Impl::load(const schema::Node::Reader& reader, bool isPlaceholder) {
988 989
  // Make a copy of the node which can be used unchecked.
  size_t size = reader.totalSizeInWords() + 1;
990 991 992
  kj::ArrayPtr<word> validated = arena.allocateArray<word>(size);
  memset(validated.begin(), 0, size * sizeof(word));
  copyToUnchecked(reader, validated);
993 994 995

  // Validate the copy.
  Validator validator(*this);
996
  auto validatedReader = readMessageUnchecked<schema::Node>(validated.begin());
997 998 999 1000 1001 1002 1003 1004 1005

  if (!validator.validate(validatedReader)) {
    // Not valid.  Construct an empty schema of the same type and return that.
    return loadEmpty(validatedReader.getId(),
                     validatedReader.getDisplayName(),
                     validatedReader.getBody().which());
  }

  // Check if we already have a schema for this ID.
1006
  _::RawSchema*& slot = schemas[validatedReader.getId()];
1007
  bool shouldReplace;
1008 1009
  if (slot == nullptr) {
    // Nope, allocate a new RawSchema.
1010
    slot = &arena.allocate<_::RawSchema>();
1011 1012 1013
    slot->id = validatedReader.getId();
    slot->canCastTo = nullptr;
    shouldReplace = true;
1014 1015
  } else {
    // Yes, check if it is compatible and figure out which schema is newer.
1016 1017 1018 1019 1020 1021 1022

    if (slot->lazyInitializer == nullptr) {
      // The existing slot is not a placeholder, so whether we overwrite it or not, we cannot
      // end up with a placeholder.
      isPlaceholder = false;
    }

1023 1024
    auto existing = readMessageUnchecked<schema::Node>(slot->encodedNode);
    CompatibilityChecker checker(*this);
1025 1026 1027 1028 1029

    // Prefer to replace the existing schema if the existing schema is a placeholder.  Otherwise,
    // prefer to keep the existing schema.
    shouldReplace = checker.shouldReplace(
        existing, validatedReader, slot->lazyInitializer != nullptr);
1030 1031
  }

1032 1033 1034
  if (shouldReplace) {
    // Initialize the RawSchema.
    slot->encodedNode = validated.begin();
Kenton Varda's avatar
Kenton Varda committed
1035
    slot->encodedSize = validated.size();
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    slot->dependencies = validator.makeDependencyArray(&slot->dependencyCount);
    slot->membersByName = validator.makeMemberInfoArray(&slot->memberCount);
  }

  if (isPlaceholder) {
    slot->lazyInitializer = &initializer;
  } else {
    // If this schema is not newly-allocated, it may already be in the wild, specifically in the
    // dependency list of other schemas.  Once the initializer is null, it is live, so we must do
    // a release-store here.
    __atomic_store_n(&slot->lazyInitializer, nullptr, __ATOMIC_RELEASE);
  }
1048 1049 1050 1051

  return slot;
}

1052
_::RawSchema* SchemaLoader::Impl::loadNative(const _::RawSchema* nativeSchema) {
1053 1054
  _::RawSchema*& slot = schemas[nativeSchema->id];
  bool shouldReplace;
1055
  if (slot == nullptr) {
1056
    slot = &arena.allocate<_::RawSchema>();
1057
    shouldReplace = true;
1058
  } else if (slot->canCastTo != nullptr) {
1059 1060
    // Already loaded natively, or we're currently in the process of loading natively and there
    // was a dependency cycle.
1061
    KJ_REQUIRE(slot->canCastTo == nativeSchema,
1062
        "two different compiled-in type have the same type ID",
1063 1064
        nativeSchema->id,
        readMessageUnchecked<schema::Node>(nativeSchema->encodedNode).getDisplayName(),
1065 1066 1067 1068 1069 1070
        readMessageUnchecked<schema::Node>(slot->canCastTo->encodedNode).getDisplayName());
    return slot;
  } else {
    auto existing = readMessageUnchecked<schema::Node>(slot->encodedNode);
    auto native = readMessageUnchecked<schema::Node>(nativeSchema->encodedNode);
    CompatibilityChecker checker(*this);
1071
    shouldReplace = checker.shouldReplace(existing, native, true);
1072 1073
  }

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
  // Since we recurse below, the slot in the hash map could move around.  Copy out the pointer
  // for subsequent use.
  _::RawSchema* result = slot;

  if (shouldReplace) {
    // Set the schema to a copy of the native schema.
    *kj::implicitCast<_::RawSchema*>(result) = *nativeSchema;

    // Indicate that casting is safe.  Note that it's important to set this before recursively
    // loading dependencies, so that cycles don't cause infinite loops!
    result->canCastTo = nativeSchema;

    // Except that we need to set the dependency list to point at other loader-owned RawSchemas.
    kj::ArrayPtr<const _::RawSchema*> dependencies =
        arena.allocateArray<const _::RawSchema*>(result->dependencyCount);
    for (uint i = 0; i < nativeSchema->dependencyCount; i++) {
      dependencies[i] = loadNative(nativeSchema->dependencies[i]);
    }
    result->dependencies = dependencies.begin();
  } else {
    // The existing schema is newer.
1095

1096 1097 1098
    // Indicate that casting is safe.  Note that it's important to set this before recursively
    // loading dependencies, so that cycles don't cause infinite loops!
    result->canCastTo = nativeSchema;
1099

1100 1101 1102 1103
    // Make sure the dependencies are loaded and compatible.
    for (uint i = 0; i < nativeSchema->dependencyCount; i++) {
      loadNative(nativeSchema->dependencies[i]);
    }
1104 1105
  }

1106 1107 1108 1109 1110 1111
  // If this schema is not newly-allocated, it may already be in the wild, specifically in the
  // dependency list of other schemas.  Once the initializer is null, it is live, so we must do
  // a release-store here.
  __atomic_store_n(&result->lazyInitializer, nullptr, __ATOMIC_RELEASE);

  return result;
1112 1113
}

1114
_::RawSchema* SchemaLoader::Impl::loadEmpty(
1115
    uint64_t id, kj::StringPtr name, schema::Node::Body::Which kind) {
1116 1117
  word scratch[32];
  memset(scratch, 0, sizeof(scratch));
1118
  MallocMessageBuilder builder(kj::arrayPtr(scratch, sizeof(scratch)));
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
  auto node = builder.initRoot<schema::Node>();
  node.setId(id);
  node.setDisplayName(name);
  switch (kind) {
    case schema::Node::Body::STRUCT_NODE: node.getBody().initStructNode(); break;
    case schema::Node::Body::ENUM_NODE: node.getBody().initEnumNode(); break;
    case schema::Node::Body::INTERFACE_NODE: node.getBody().initInterfaceNode(); break;

    case schema::Node::Body::FILE_NODE:
    case schema::Node::Body::CONST_NODE:
    case schema::Node::Body::ANNOTATION_NODE:
1130
      KJ_FAIL_REQUIRE("Not a type.");
1131 1132 1133
      break;
  }

1134
  return load(node, true);
1135 1136
}

1137
SchemaLoader::Impl::TryGetResult SchemaLoader::Impl::tryGet(uint64_t typeId) const {
1138 1139
  auto iter = schemas.find(typeId);
  if (iter == schemas.end()) {
1140
    return {nullptr, initializer.getCallback()};
1141
  } else {
1142
    return {iter->second, initializer.getCallback()};
1143 1144 1145
  }
}

1146
kj::Array<Schema> SchemaLoader::Impl::getAllLoaded() const {
1147 1148 1149 1150 1151 1152
  size_t count = 0;
  for (auto& schema: schemas) {
    if (schema.second->lazyInitializer == nullptr) ++count;
  }

  kj::Array<Schema> result = kj::heapArray<Schema>(count);
1153 1154
  size_t i = 0;
  for (auto& schema: schemas) {
1155
    if (schema.second->lazyInitializer == nullptr) result[i++] = Schema(schema.second);
1156 1157 1158 1159
  }
  return result;
}

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
void SchemaLoader::InitializerImpl::init(const _::RawSchema* schema) const {
  KJ_IF_MAYBE(c, callback) {
    c->load(loader, schema->id);
  }

  if (schema->lazyInitializer != nullptr) {
    // The callback declined to load a schema.  We need to disable the initializer so that it
    // doesn't get invoked again later, as we can no longer modify this schema once it is in use.

    // Lock the loader for read to make sure no one is concurrently loading a replacement for this
    // schema node.
1171
    auto lock = loader.impl.lockShared();
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

    // Get the mutable version of the schema.
    _::RawSchema* mutableSchema = lock->get()->tryGet(schema->id).schema;
    KJ_ASSERT(mutableSchema == schema,
              "A schema not belonging to this loader used its initializer.");

    // Disable the initializer.
    __atomic_store_n(&mutableSchema->lazyInitializer, nullptr, __ATOMIC_RELEASE);
  }
}

1183 1184
// =======================================================================================

1185 1186 1187
SchemaLoader::SchemaLoader(): impl(kj::heap<Impl>(*this)) {}
SchemaLoader::SchemaLoader(const LazyLoadCallback& callback)
    : impl(kj::heap<Impl>(*this, callback)) {}
1188
SchemaLoader::~SchemaLoader() noexcept(false) {}
1189 1190

Schema SchemaLoader::get(uint64_t id) const {
1191 1192 1193 1194 1195
  KJ_IF_MAYBE(result, tryGet(id)) {
    return *result;
  } else {
    KJ_FAIL_REQUIRE("no schema node loaded for id", id);
  }
1196 1197
}

1198
kj::Maybe<Schema> SchemaLoader::tryGet(uint64_t id) const {
1199
  auto getResult = impl.lockShared()->get()->tryGet(id);
1200 1201 1202 1203
  if (getResult.schema == nullptr || getResult.schema->lazyInitializer != nullptr) {
    KJ_IF_MAYBE(c, getResult.callback) {
      c->load(*this, id);
    }
1204
    getResult = impl.lockShared()->get()->tryGet(id);
1205 1206 1207
  }
  if (getResult.schema != nullptr && getResult.schema->lazyInitializer == nullptr) {
    return Schema(getResult.schema);
1208
  } else {
1209
    return nullptr;
1210 1211 1212
  }
}

1213
Schema SchemaLoader::load(const schema::Node::Reader& reader) {
1214
  return Schema(impl.lockExclusive()->get()->load(reader, false));
1215 1216
}

Kenton Varda's avatar
Kenton Varda committed
1217
Schema SchemaLoader::loadOnce(const schema::Node::Reader& reader) const {
1218
  auto locked = impl.lockExclusive();
1219 1220 1221 1222 1223 1224 1225 1226
  auto getResult = locked->get()->tryGet(reader.getId());
  if (getResult.schema == nullptr || getResult.schema->lazyInitializer != nullptr) {
    // Doesn't exist yet, or the existing schema is a placeholder and therefore has not yet been
    // seen publicly.  Go ahead and load the incoming reader.
    return Schema(locked->get()->load(reader, false));
  } else {
    return Schema(getResult.schema);
  }
1227 1228
}

1229
kj::Array<Schema> SchemaLoader::getAllLoaded() const {
1230
  return impl.lockShared()->get()->getAllLoaded();
1231 1232
}

1233
void SchemaLoader::loadNative(const _::RawSchema* nativeSchema) {
1234
  impl.lockExclusive()->get()->loadNative(nativeSchema);
1235 1236
}

1237
}  // namespace capnp