c-api.cc 99.8 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 24 25 26 27 28 29 30 31
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This implementation is originally from
// https://github.com/WebAssembly/wasm-c-api/:

// Copyright 2019 Andreas Rossberg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <cstring>
#include <iostream>

#include "third_party/wasm-api/wasm.h"
#include "third_party/wasm-api/wasm.hh"

#include "include/libplatform/libplatform.h"
#include "include/v8.h"
#include "src/api-inl.h"
#include "src/wasm/leb-helper.h"
32
#include "src/wasm/module-instantiate.h"
33 34
#include "src/wasm/wasm-constants.h"
#include "src/wasm/wasm-objects.h"
35
#include "src/wasm/wasm-result.h"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
#include "src/wasm/wasm-serialization.h"

// BEGIN FILE wasm-bin.cc

namespace wasm {
namespace bin {

////////////////////////////////////////////////////////////////////////////////
// Encoding

void encode_header(char*& ptr) {
  std::memcpy(ptr,
              "\x00"
              "asm\x01\x00\x00\x00",
              8);
  ptr += 8;
}

void encode_size32(char*& ptr, size_t n) {
  assert(n <= 0xffffffff);
  for (int i = 0; i < 5; ++i) {
    *ptr++ = (n & 0x7f) | (i == 4 ? 0x00 : 0x80);
    n = n >> 7;
  }
}

void encode_valtype(char*& ptr, const ValType* type) {
  switch (type->kind()) {
    case I32:
      *ptr++ = 0x7f;
      break;
    case I64:
      *ptr++ = 0x7e;
      break;
    case F32:
      *ptr++ = 0x7d;
      break;
    case F64:
      *ptr++ = 0x7c;
      break;
    case FUNCREF:
      *ptr++ = 0x70;
      break;
    case ANYREF:
      *ptr++ = 0x6f;
      break;
    default:
      UNREACHABLE();
  }
}

auto zero_size(const ValType* type) -> size_t {
  switch (type->kind()) {
    case I32:
      return 1;
    case I64:
      return 1;
    case F32:
      return 4;
    case F64:
      return 8;
    case FUNCREF:
      return 0;
    case ANYREF:
      return 0;
    default:
      UNREACHABLE();
  }
}

void encode_const_zero(char*& ptr, const ValType* type) {
  switch (type->kind()) {
    case I32:
      *ptr++ = 0x41;
      break;
    case I64:
      *ptr++ = 0x42;
      break;
    case F32:
      *ptr++ = 0x43;
      break;
    case F64:
      *ptr++ = 0x44;
      break;
    default:
      UNREACHABLE();
  }
  for (size_t i = 0; i < zero_size(type); ++i) *ptr++ = 0;
}

auto wrapper(const FuncType* type) -> vec<byte_t> {
  auto in_arity = type->params().size();
  auto out_arity = type->results().size();
  auto size = 39 + in_arity + out_arity;
  auto binary = vec<byte_t>::make_uninitialized(size);
  auto ptr = binary.get();

  encode_header(ptr);

  *ptr++ = i::wasm::kTypeSectionCode;
  encode_size32(ptr, 12 + in_arity + out_arity);  // size
  *ptr++ = 1;                                     // length
  *ptr++ = i::wasm::kWasmFunctionTypeCode;
  encode_size32(ptr, in_arity);
  for (size_t i = 0; i < in_arity; ++i) {
    encode_valtype(ptr, type->params()[i].get());
  }
  encode_size32(ptr, out_arity);
  for (size_t i = 0; i < out_arity; ++i) {
    encode_valtype(ptr, type->results()[i].get());
  }

  *ptr++ = i::wasm::kImportSectionCode;
  *ptr++ = 5;  // size
  *ptr++ = 1;  // length
  *ptr++ = 0;  // module length
  *ptr++ = 0;  // name length
  *ptr++ = i::wasm::kExternalFunction;
  *ptr++ = 0;  // type index

  *ptr++ = i::wasm::kExportSectionCode;
  *ptr++ = 4;  // size
  *ptr++ = 1;  // length
  *ptr++ = 0;  // name length
  *ptr++ = i::wasm::kExternalFunction;
  *ptr++ = 0;  // func index

  assert(ptr - binary.get() == static_cast<ptrdiff_t>(size));
  return binary;
}

////////////////////////////////////////////////////////////////////////////////
// Decoding

// Numbers

auto u32(const byte_t*& pos) -> uint32_t {
  uint32_t n = 0;
  uint32_t shift = 0;
  byte_t b;
  do {
    b = *pos++;
    n += (b & 0x7f) << shift;
    shift += 7;
  } while ((b & 0x80) != 0);
  return n;
}

auto u64(const byte_t*& pos) -> uint64_t {
  uint64_t n = 0;
  uint64_t shift = 0;
  byte_t b;
  do {
    b = *pos++;
    n += (b & 0x7f) << shift;
    shift += 7;
  } while ((b & 0x80) != 0);
  return n;
}

void u32_skip(const byte_t*& pos) { bin::u32(pos); }

// Names

auto name(const byte_t*& pos) -> Name {
  auto size = bin::u32(pos);
  auto start = pos;
  auto name = Name::make_uninitialized(size);
  std::memcpy(name.get(), start, size);
  pos += size;
  return name;
}

// Types

auto valtype(const byte_t*& pos) -> own<wasm::ValType*> {
  switch (*pos++) {
    case i::wasm::kLocalI32:
      return ValType::make(I32);
    case i::wasm::kLocalI64:
      return ValType::make(I64);
    case i::wasm::kLocalF32:
      return ValType::make(F32);
    case i::wasm::kLocalF64:
      return ValType::make(F64);
    case i::wasm::kLocalAnyFunc:
      return ValType::make(FUNCREF);
    case i::wasm::kLocalAnyRef:
      return ValType::make(ANYREF);
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
  }
  return {};
}

auto mutability(const byte_t*& pos) -> Mutability {
  return *pos++ ? VAR : CONST;
}

auto limits(const byte_t*& pos) -> Limits {
  auto tag = *pos++;
  auto min = bin::u32(pos);
  if ((tag & 0x01) == 0) {
    return Limits(min);
  } else {
    auto max = bin::u32(pos);
    return Limits(min, max);
  }
}

auto stacktype(const byte_t*& pos) -> vec<ValType*> {
  size_t size = bin::u32(pos);
  auto v = vec<ValType*>::make_uninitialized(size);
  for (uint32_t i = 0; i < size; ++i) v[i] = bin::valtype(pos);
  return v;
}

auto functype(const byte_t*& pos) -> own<FuncType*> {
  assert(*pos == i::wasm::kWasmFunctionTypeCode);
  ++pos;
  auto params = bin::stacktype(pos);
  auto results = bin::stacktype(pos);
  return FuncType::make(std::move(params), std::move(results));
}

auto globaltype(const byte_t*& pos) -> own<GlobalType*> {
  auto content = bin::valtype(pos);
  auto mutability = bin::mutability(pos);
  return GlobalType::make(std::move(content), mutability);
}

auto tabletype(const byte_t*& pos) -> own<TableType*> {
  auto elem = bin::valtype(pos);
  auto limits = bin::limits(pos);
  return TableType::make(std::move(elem), limits);
}

auto memorytype(const byte_t*& pos) -> own<MemoryType*> {
  auto limits = bin::limits(pos);
  return MemoryType::make(limits);
}

// Expressions

void expr_skip(const byte_t*& pos) {
  switch (*pos++) {
    case i::wasm::kExprI32Const:
    case i::wasm::kExprI64Const:
    case i::wasm::kExprGetGlobal: {
      bin::u32_skip(pos);
    } break;
    case i::wasm::kExprF32Const: {
      pos += 4;
    } break;
    case i::wasm::kExprF64Const: {
      pos += 8;
    } break;
    default: {
      // TODO(wasm+): support new expression forms
      UNREACHABLE();
    }
  }
  ++pos;  // end
}

// Sections

304
auto section(const vec<const byte_t>& binary, i::wasm::SectionCode sec)
305 306 307 308 309 310 311 312 313 314 315 316 317
    -> const byte_t* {
  const byte_t* end = binary.get() + binary.size();
  const byte_t* pos = binary.get() + 8;  // skip header
  while (pos < end && *pos++ != sec) {
    auto size = bin::u32(pos);
    pos += size;
  }
  if (pos == end) return nullptr;
  bin::u32_skip(pos);
  return pos;
}

// Only for asserts/DCHECKs.
318
auto section_end(const vec<const byte_t>& binary, i::wasm::SectionCode sec)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    -> const byte_t* {
  const byte_t* end = binary.get() + binary.size();
  const byte_t* pos = binary.get() + 8;  // skip header
  while (pos < end && *pos != sec) {
    ++pos;
    auto size = bin::u32(pos);
    pos += size;
  }
  if (pos == end) return nullptr;
  ++pos;
  auto size = bin::u32(pos);
  return pos + size;
}

// Type section

335
auto types(const vec<const byte_t>& binary) -> vec<FuncType*> {
336 337 338 339 340 341 342 343 344 345 346 347 348 349
  auto pos = bin::section(binary, i::wasm::kTypeSectionCode);
  if (pos == nullptr) return vec<FuncType*>::make();
  size_t size = bin::u32(pos);
  // TODO(wasm+): support new deftypes
  auto v = vec<FuncType*>::make_uninitialized(size);
  for (uint32_t i = 0; i < size; ++i) {
    v[i] = bin::functype(pos);
  }
  assert(pos == bin::section_end(binary, i::wasm::kTypeSectionCode));
  return v;
}

// Import section

350
auto imports(const vec<const byte_t>& binary, const vec<FuncType*>& types)
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 389 390 391 392
    -> vec<ImportType*> {
  auto pos = bin::section(binary, i::wasm::kImportSectionCode);
  if (pos == nullptr) return vec<ImportType*>::make();
  size_t size = bin::u32(pos);
  auto v = vec<ImportType*>::make_uninitialized(size);
  for (uint32_t i = 0; i < size; ++i) {
    auto module = bin::name(pos);
    auto name = bin::name(pos);
    own<ExternType*> type;
    switch (*pos++) {
      case i::wasm::kExternalFunction:
        type = types[bin::u32(pos)]->copy();
        break;
      case i::wasm::kExternalTable:
        type = bin::tabletype(pos);
        break;
      case i::wasm::kExternalMemory:
        type = bin::memorytype(pos);
        break;
      case i::wasm::kExternalGlobal:
        type = bin::globaltype(pos);
        break;
      default:
        UNREACHABLE();
    }
    v[i] =
        ImportType::make(std::move(module), std::move(name), std::move(type));
  }
  assert(pos == bin::section_end(binary, i::wasm::kImportSectionCode));
  return v;
}

auto count(const vec<ImportType*>& imports, ExternKind kind) -> uint32_t {
  uint32_t n = 0;
  for (uint32_t i = 0; i < imports.size(); ++i) {
    if (imports[i]->type()->kind() == kind) ++n;
  }
  return n;
}

// Function section

393
auto funcs(const vec<const byte_t>& binary, const vec<ImportType*>& imports,
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
           const vec<FuncType*>& types) -> vec<FuncType*> {
  auto pos = bin::section(binary, i::wasm::kFunctionSectionCode);
  size_t size = pos != nullptr ? bin::u32(pos) : 0;
  auto v =
      vec<FuncType*>::make_uninitialized(size + count(imports, EXTERN_FUNC));
  size_t j = 0;
  for (uint32_t i = 0; i < imports.size(); ++i) {
    auto et = imports[i]->type();
    if (et->kind() == EXTERN_FUNC) {
      v[j++] = et->func()->copy();
    }
  }
  if (pos != nullptr) {
    for (; j < v.size(); ++j) {
      v[j] = types[bin::u32(pos)]->copy();
    }
    assert(pos == bin::section_end(binary, i::wasm::kFunctionSectionCode));
  }
  return v;
}

// Global section

417
auto globals(const vec<const byte_t>& binary, const vec<ImportType*>& imports)
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    -> vec<GlobalType*> {
  auto pos = bin::section(binary, i::wasm::kGlobalSectionCode);
  size_t size = pos != nullptr ? bin::u32(pos) : 0;
  auto v = vec<GlobalType*>::make_uninitialized(size +
                                                count(imports, EXTERN_GLOBAL));
  size_t j = 0;
  for (uint32_t i = 0; i < imports.size(); ++i) {
    auto et = imports[i]->type();
    if (et->kind() == EXTERN_GLOBAL) {
      v[j++] = et->global()->copy();
    }
  }
  if (pos != nullptr) {
    for (; j < v.size(); ++j) {
      v[j] = bin::globaltype(pos);
      expr_skip(pos);
    }
    assert(pos == bin::section_end(binary, i::wasm::kGlobalSectionCode));
  }
  return v;
}

// Table section

442
auto tables(const vec<const byte_t>& binary, const vec<ImportType*>& imports)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    -> vec<TableType*> {
  auto pos = bin::section(binary, i::wasm::kTableSectionCode);
  size_t size = pos != nullptr ? bin::u32(pos) : 0;
  auto v =
      vec<TableType*>::make_uninitialized(size + count(imports, EXTERN_TABLE));
  size_t j = 0;
  for (uint32_t i = 0; i < imports.size(); ++i) {
    auto et = imports[i]->type();
    if (et->kind() == EXTERN_TABLE) {
      v[j++] = et->table()->copy();
    }
  }
  if (pos != nullptr) {
    for (; j < v.size(); ++j) {
      v[j] = bin::tabletype(pos);
    }
    assert(pos == bin::section_end(binary, i::wasm::kTableSectionCode));
  }
  return v;
}

// Memory section

466
auto memories(const vec<const byte_t>& binary, const vec<ImportType*>& imports)
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    -> vec<MemoryType*> {
  auto pos = bin::section(binary, i::wasm::kMemorySectionCode);
  size_t size = pos != nullptr ? bin::u32(pos) : 0;
  auto v = vec<MemoryType*>::make_uninitialized(size +
                                                count(imports, EXTERN_MEMORY));
  size_t j = 0;
  for (uint32_t i = 0; i < imports.size(); ++i) {
    auto et = imports[i]->type();
    if (et->kind() == EXTERN_MEMORY) {
      v[j++] = et->memory()->copy();
    }
  }
  if (pos != nullptr) {
    for (; j < v.size(); ++j) {
      v[j] = bin::memorytype(pos);
    }
    assert(pos == bin::section_end(binary, i::wasm::kMemorySectionCode));
  }
  return v;
}

// Export section

490
auto exports(const vec<const byte_t>& binary, const vec<FuncType*>& funcs,
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 517 518 519 520 521 522 523
             const vec<GlobalType*>& globals, const vec<TableType*>& tables,
             const vec<MemoryType*>& memories) -> vec<ExportType*> {
  auto pos = bin::section(binary, i::wasm::kExportSectionCode);
  if (pos == nullptr) return vec<ExportType*>::make();
  size_t size = bin::u32(pos);
  auto exports = vec<ExportType*>::make_uninitialized(size);
  for (uint32_t i = 0; i < size; ++i) {
    auto name = bin::name(pos);
    auto tag = *pos++;
    auto index = bin::u32(pos);
    own<ExternType*> type;
    switch (tag) {
      case i::wasm::kExternalFunction:
        type = funcs[index]->copy();
        break;
      case i::wasm::kExternalTable:
        type = tables[index]->copy();
        break;
      case i::wasm::kExternalMemory:
        type = memories[index]->copy();
        break;
      case i::wasm::kExternalGlobal:
        type = globals[index]->copy();
        break;
      default:
        UNREACHABLE();
    }
    exports[i] = ExportType::make(std::move(name), std::move(type));
  }
  assert(pos == bin::section_end(binary, i::wasm::kExportSectionCode));
  return exports;
}

524
auto imports(const vec<const byte_t>& binary) -> vec<ImportType*> {
525 526 527
  return bin::imports(binary, bin::types(binary));
}

528
auto exports(const vec<const byte_t>& binary) -> vec<ExportType*> {
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 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
  auto types = bin::types(binary);
  auto imports = bin::imports(binary, types);
  auto funcs = bin::funcs(binary, imports, types);
  auto globals = bin::globals(binary, imports);
  auto tables = bin::tables(binary, imports);
  auto memories = bin::memories(binary, imports);
  return bin::exports(binary, funcs, globals, tables, memories);
}

}  // namespace bin
}  // namespace wasm

// BEGIN FILE wasm-v8-lowlevel.cc

namespace v8 {
namespace wasm {

// Foreign pointers

auto foreign_new(v8::Isolate* isolate, void* ptr) -> v8::Local<v8::Value> {
  auto foreign = v8::FromCData(reinterpret_cast<i::Isolate*>(isolate),
                               reinterpret_cast<i::Address>(ptr));
  return v8::Utils::ToLocal(foreign);
}

auto foreign_get(v8::Local<v8::Value> val) -> void* {
  auto foreign = v8::Utils::OpenHandle(*val);
  if (!foreign->IsForeign()) return nullptr;
  auto addr = v8::ToCData<i::Address>(*foreign);
  return reinterpret_cast<void*>(addr);
}

// Types

auto v8_valtype_to_wasm(i::wasm::ValueType v8_valtype) -> ::wasm::ValKind {
  switch (v8_valtype) {
    case i::wasm::kWasmI32:
      return ::wasm::I32;
    case i::wasm::kWasmI64:
      return ::wasm::I64;
    case i::wasm::kWasmF32:
      return ::wasm::F32;
    case i::wasm::kWasmF64:
      return ::wasm::F64;
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
  }
}

579 580 581 582 583 584 585 586 587 588 589 590 591
i::wasm::ValueType wasm_valtype_to_v8(::wasm::ValKind type) {
  switch (type) {
    case ::wasm::I32:
      return i::wasm::kWasmI32;
    case ::wasm::I64:
      return i::wasm::kWasmI64;
    case ::wasm::F32:
      return i::wasm::kWasmF32;
    case ::wasm::F64:
      return i::wasm::kWasmF64;
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
592 593 594 595 596 597 598 599 600 601 602 603 604 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 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  }
}

}  // namespace wasm
}  // namespace v8

/// BEGIN FILE wasm-v8.cc

namespace wasm {

///////////////////////////////////////////////////////////////////////////////
// Auxiliaries

[[noreturn]] void WASM_UNIMPLEMENTED(const char* s) {
  std::cerr << "Wasm API: " << s << " not supported yet!\n";
  exit(1);
}

template <class T>
void ignore(T) {}

template <class C>
struct implement;

template <class C>
auto impl(C* x) -> typename implement<C>::type* {
  return reinterpret_cast<typename implement<C>::type*>(x);
}

template <class C>
auto impl(const C* x) -> const typename implement<C>::type* {
  return reinterpret_cast<const typename implement<C>::type*>(x);
}

template <class C>
auto seal(typename implement<C>::type* x) -> C* {
  return reinterpret_cast<C*>(x);
}

template <class C>
auto seal(const typename implement<C>::type* x) -> const C* {
  return reinterpret_cast<const C*>(x);
}

#ifdef DEBUG
template <class T>
void vec<T>::make_data() {}

template <class T>
void vec<T>::free_data() {}
#endif

///////////////////////////////////////////////////////////////////////////////
// Runtime Environment

// Configuration

struct ConfigImpl {
  ConfigImpl() {}
  ~ConfigImpl() {}
};

template <>
struct implement<Config> {
  using type = ConfigImpl;
};

Config::~Config() { impl(this)->~ConfigImpl(); }

void Config::operator delete(void* p) { ::operator delete(p); }

auto Config::make() -> own<Config*> {
  return own<Config*>(seal<Config>(new (std::nothrow) ConfigImpl()));
}

// Engine

struct EngineImpl {
  static bool created;

  std::unique_ptr<v8::Platform> platform;

  EngineImpl() {
    assert(!created);
    created = true;
  }

  ~EngineImpl() {
    v8::V8::Dispose();
    v8::V8::ShutdownPlatform();
  }
};

bool EngineImpl::created = false;

template <>
struct implement<Engine> {
  using type = EngineImpl;
};

Engine::~Engine() { impl(this)->~EngineImpl(); }

void Engine::operator delete(void* p) { ::operator delete(p); }

auto Engine::make(own<Config*>&& config) -> own<Engine*> {
  i::FLAG_expose_gc = true;
  i::FLAG_experimental_wasm_bigint = true;
  i::FLAG_experimental_wasm_mv = true;
  auto engine = new (std::nothrow) EngineImpl;
  if (!engine) return own<Engine*>();
  engine->platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(engine->platform.get());
  v8::V8::Initialize();
  return make_own(seal<Engine>(engine));
}

// Stores

class StoreImpl {
  friend own<Store*> Store::make(Engine*);

  v8::Isolate::CreateParams create_params_;
  v8::Isolate* isolate_;
  v8::Eternal<v8::Context> context_;

 public:
  StoreImpl() {}

  ~StoreImpl() {
#ifdef DEBUG
    reinterpret_cast<i::Isolate*>(isolate_)->heap()->PreciseCollectAllGarbage(
        i::Heap::kNoGCFlags, i::GarbageCollectionReason::kTesting,
        v8::kGCCallbackFlagForced);
#endif
    context()->Exit();
    isolate_->Exit();
    isolate_->Dispose();
    delete create_params_.array_buffer_allocator;
  }

  auto isolate() const -> v8::Isolate* { return isolate_; }
733 734 735
  i::Isolate* i_isolate() const {
    return reinterpret_cast<i::Isolate*>(isolate_);
  }
736 737 738 739 740

  auto context() const -> v8::Local<v8::Context> {
    return context_.Get(isolate_);
  }

741 742 743
  static auto get(i::Isolate* isolate) -> StoreImpl* {
    return static_cast<StoreImpl*>(
        reinterpret_cast<v8::Isolate*>(isolate)->GetData(0));
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 784 785 786 787 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 816 817 818 819 820 821 822 823 824 825 826 827 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 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 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 941 942 943 944 945 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 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
  }
};

template <>
struct implement<Store> {
  using type = StoreImpl;
};

Store::~Store() { impl(this)->~StoreImpl(); }

void Store::operator delete(void* p) { ::operator delete(p); }

auto Store::make(Engine*) -> own<Store*> {
  auto store = make_own(new (std::nothrow) StoreImpl());
  if (!store) return own<Store*>();

  // Create isolate.
  store->create_params_.array_buffer_allocator =
      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
  auto isolate = v8::Isolate::New(store->create_params_);
  if (!isolate) return own<Store*>();

  {
    v8::Isolate::Scope isolate_scope(isolate);
    v8::HandleScope handle_scope(isolate);

    // Create context.
    auto context = v8::Context::New(isolate);
    if (context.IsEmpty()) return own<Store*>();
    v8::Context::Scope context_scope(context);

    store->isolate_ = isolate;
    store->context_ = v8::Eternal<v8::Context>(isolate, context);
  }

  store->isolate()->Enter();
  store->context()->Enter();
  isolate->SetData(0, store.get());

  return make_own(seal<Store>(store.release()));
}

///////////////////////////////////////////////////////////////////////////////
// Type Representations

// Value Types

struct ValTypeImpl {
  ValKind kind;

  explicit ValTypeImpl(ValKind kind) : kind(kind) {}
};

template <>
struct implement<ValType> {
  using type = ValTypeImpl;
};

ValTypeImpl* valtypes[] = {
    new ValTypeImpl(I32), new ValTypeImpl(I64),    new ValTypeImpl(F32),
    new ValTypeImpl(F64), new ValTypeImpl(ANYREF), new ValTypeImpl(FUNCREF),
};

ValType::~ValType() {}

void ValType::operator delete(void*) {}

auto ValType::make(ValKind k) -> own<ValType*> {
  auto result = seal<ValType>(valtypes[k]);
  return own<ValType*>(result);
}

auto ValType::copy() const -> own<ValType*> { return make(kind()); }

auto ValType::kind() const -> ValKind { return impl(this)->kind; }

// Extern Types

struct ExternTypeImpl {
  ExternKind kind;

  explicit ExternTypeImpl(ExternKind kind) : kind(kind) {}
  virtual ~ExternTypeImpl() {}
};

template <>
struct implement<ExternType> {
  using type = ExternTypeImpl;
};

ExternType::~ExternType() { impl(this)->~ExternTypeImpl(); }

void ExternType::operator delete(void* p) { ::operator delete(p); }

auto ExternType::copy() const -> own<ExternType*> {
  switch (kind()) {
    case EXTERN_FUNC:
      return func()->copy();
    case EXTERN_GLOBAL:
      return global()->copy();
    case EXTERN_TABLE:
      return table()->copy();
    case EXTERN_MEMORY:
      return memory()->copy();
  }
}

auto ExternType::kind() const -> ExternKind { return impl(this)->kind; }

// Function Types

struct FuncTypeImpl : ExternTypeImpl {
  vec<ValType*> params;
  vec<ValType*> results;

  FuncTypeImpl(vec<ValType*>& params, vec<ValType*>& results)
      : ExternTypeImpl(EXTERN_FUNC),
        params(std::move(params)),
        results(std::move(results)) {}

  ~FuncTypeImpl() {}
};

template <>
struct implement<FuncType> {
  using type = FuncTypeImpl;
};

FuncType::~FuncType() {}

auto FuncType::make(vec<ValType*>&& params, vec<ValType*>&& results)
    -> own<FuncType*> {
  return params && results
             ? own<FuncType*>(seal<FuncType>(new (std::nothrow)
                                                 FuncTypeImpl(params, results)))
             : own<FuncType*>();
}

auto FuncType::copy() const -> own<FuncType*> {
  return make(params().copy(), results().copy());
}

auto FuncType::params() const -> const vec<ValType*>& {
  return impl(this)->params;
}

auto FuncType::results() const -> const vec<ValType*>& {
  return impl(this)->results;
}

auto ExternType::func() -> FuncType* {
  return kind() == EXTERN_FUNC
             ? seal<FuncType>(static_cast<FuncTypeImpl*>(impl(this)))
             : nullptr;
}

auto ExternType::func() const -> const FuncType* {
  return kind() == EXTERN_FUNC
             ? seal<FuncType>(static_cast<const FuncTypeImpl*>(impl(this)))
             : nullptr;
}

// Global Types

struct GlobalTypeImpl : ExternTypeImpl {
  own<ValType*> content;
  Mutability mutability;

  GlobalTypeImpl(own<ValType*>& content, Mutability mutability)
      : ExternTypeImpl(EXTERN_GLOBAL),
        content(std::move(content)),
        mutability(mutability) {}

  ~GlobalTypeImpl() {}
};

template <>
struct implement<GlobalType> {
  using type = GlobalTypeImpl;
};

GlobalType::~GlobalType() {}

auto GlobalType::make(own<ValType*>&& content, Mutability mutability)
    -> own<GlobalType*> {
  return content ? own<GlobalType*>(seal<GlobalType>(
                       new (std::nothrow) GlobalTypeImpl(content, mutability)))
                 : own<GlobalType*>();
}

auto GlobalType::copy() const -> own<GlobalType*> {
  return make(content()->copy(), mutability());
}

auto GlobalType::content() const -> const ValType* {
  return impl(this)->content.get();
}

auto GlobalType::mutability() const -> Mutability {
  return impl(this)->mutability;
}

auto ExternType::global() -> GlobalType* {
  return kind() == EXTERN_GLOBAL
             ? seal<GlobalType>(static_cast<GlobalTypeImpl*>(impl(this)))
             : nullptr;
}

auto ExternType::global() const -> const GlobalType* {
  return kind() == EXTERN_GLOBAL
             ? seal<GlobalType>(static_cast<const GlobalTypeImpl*>(impl(this)))
             : nullptr;
}

// Table Types

struct TableTypeImpl : ExternTypeImpl {
  own<ValType*> element;
  Limits limits;

  TableTypeImpl(own<ValType*>& element, Limits limits)
      : ExternTypeImpl(EXTERN_TABLE),
        element(std::move(element)),
        limits(limits) {}

  ~TableTypeImpl() {}
};

template <>
struct implement<TableType> {
  using type = TableTypeImpl;
};

TableType::~TableType() {}

auto TableType::make(own<ValType*>&& element, Limits limits)
    -> own<TableType*> {
  return element ? own<TableType*>(seal<TableType>(
                       new (std::nothrow) TableTypeImpl(element, limits)))
                 : own<TableType*>();
}

auto TableType::copy() const -> own<TableType*> {
  return make(element()->copy(), limits());
}

auto TableType::element() const -> const ValType* {
  return impl(this)->element.get();
}

auto TableType::limits() const -> const Limits& { return impl(this)->limits; }

auto ExternType::table() -> TableType* {
  return kind() == EXTERN_TABLE
             ? seal<TableType>(static_cast<TableTypeImpl*>(impl(this)))
             : nullptr;
}

auto ExternType::table() const -> const TableType* {
  return kind() == EXTERN_TABLE
             ? seal<TableType>(static_cast<const TableTypeImpl*>(impl(this)))
             : nullptr;
}

// Memory Types

struct MemoryTypeImpl : ExternTypeImpl {
  Limits limits;

  explicit MemoryTypeImpl(Limits limits)
      : ExternTypeImpl(EXTERN_MEMORY), limits(limits) {}

  ~MemoryTypeImpl() {}
};

template <>
struct implement<MemoryType> {
  using type = MemoryTypeImpl;
};

MemoryType::~MemoryType() {}

auto MemoryType::make(Limits limits) -> own<MemoryType*> {
  return own<MemoryType*>(
      seal<MemoryType>(new (std::nothrow) MemoryTypeImpl(limits)));
}

auto MemoryType::copy() const -> own<MemoryType*> {
  return MemoryType::make(limits());
}

auto MemoryType::limits() const -> const Limits& { return impl(this)->limits; }

auto ExternType::memory() -> MemoryType* {
  return kind() == EXTERN_MEMORY
             ? seal<MemoryType>(static_cast<MemoryTypeImpl*>(impl(this)))
             : nullptr;
}

auto ExternType::memory() const -> const MemoryType* {
  return kind() == EXTERN_MEMORY
             ? seal<MemoryType>(static_cast<const MemoryTypeImpl*>(impl(this)))
             : nullptr;
}

// Import Types

struct ImportTypeImpl {
  Name module;
  Name name;
  own<ExternType*> type;

  ImportTypeImpl(Name& module, Name& name, own<ExternType*>& type)
      : module(std::move(module)),
        name(std::move(name)),
        type(std::move(type)) {}

  ~ImportTypeImpl() {}
};

template <>
struct implement<ImportType> {
  using type = ImportTypeImpl;
};

ImportType::~ImportType() { impl(this)->~ImportTypeImpl(); }

void ImportType::operator delete(void* p) { ::operator delete(p); }

auto ImportType::make(Name&& module, Name&& name, own<ExternType*>&& type)
    -> own<ImportType*> {
  return module && name && type
             ? own<ImportType*>(seal<ImportType>(
                   new (std::nothrow) ImportTypeImpl(module, name, type)))
             : own<ImportType*>();
}

auto ImportType::copy() const -> own<ImportType*> {
  return make(module().copy(), name().copy(), type()->copy());
}

auto ImportType::module() const -> const Name& { return impl(this)->module; }

auto ImportType::name() const -> const Name& { return impl(this)->name; }

auto ImportType::type() const -> const ExternType* {
  return impl(this)->type.get();
}

// Export Types

struct ExportTypeImpl {
  Name name;
  own<ExternType*> type;

  ExportTypeImpl(Name& name, own<ExternType*>& type)
      : name(std::move(name)), type(std::move(type)) {}

  ~ExportTypeImpl() {}
};

template <>
struct implement<ExportType> {
  using type = ExportTypeImpl;
};

ExportType::~ExportType() { impl(this)->~ExportTypeImpl(); }

void ExportType::operator delete(void* p) { ::operator delete(p); }

auto ExportType::make(Name&& name, own<ExternType*>&& type)
    -> own<ExportType*> {
  return name && type ? own<ExportType*>(seal<ExportType>(
                            new (std::nothrow) ExportTypeImpl(name, type)))
                      : own<ExportType*>();
}

auto ExportType::copy() const -> own<ExportType*> {
  return make(name().copy(), type()->copy());
}

auto ExportType::name() const -> const Name& { return impl(this)->name; }

auto ExportType::type() const -> const ExternType* {
  return impl(this)->type.get();
}

///////////////////////////////////////////////////////////////////////////////
1132
// Conversions of values from and to V8 objects
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

auto val_to_v8(StoreImpl* store, const Val& v) -> v8::Local<v8::Value> {
  auto isolate = store->isolate();
  switch (v.kind()) {
    case I32:
      return v8::Integer::NewFromUnsigned(isolate, v.i32());
    case I64:
      return v8::BigInt::New(isolate, v.i64());
    case F32:
      return v8::Number::New(isolate, v.f32());
    case F64:
      return v8::Number::New(isolate, v.f64());
    case ANYREF:
    case FUNCREF: {
      if (v.ref() == nullptr) {
        return v8::Null(isolate);
      } else {
        WASM_UNIMPLEMENTED("ref value");
      }
    }
    default:
      UNREACHABLE();
  }
}

1158 1159 1160
own<Val> v8_to_val(i::Isolate* isolate, i::Handle<i::Object> value,
                   ValKind kind) {
  switch (kind) {
1161
    case I32:
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
      do {
        if (value->IsSmi()) return Val(i::Smi::ToInt(*value));
        if (value->IsHeapNumber()) {
          return Val(i::DoubleToInt32(i::HeapNumber::cast(*value)->value()));
        }
        value = i::Object::ToInt32(isolate, value).ToHandleChecked();
        // This will loop back at most once.
      } while (true);
      UNREACHABLE();
    case I64:
      if (value->IsBigInt()) return Val(i::BigInt::cast(*value)->AsInt64());
      return Val(
          i::BigInt::FromObject(isolate, value).ToHandleChecked()->AsInt64());
    case F32:
      do {
        if (value->IsSmi()) {
          return Val(static_cast<float32_t>(i::Smi::ToInt(*value)));
        }
        if (value->IsHeapNumber()) {
          return Val(i::DoubleToFloat32(i::HeapNumber::cast(*value)->value()));
        }
        value = i::Object::ToNumber(isolate, value).ToHandleChecked();
        // This will loop back at most once.
      } while (true);
      UNREACHABLE();
1187
    case F64:
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
      do {
        if (value->IsSmi()) {
          return Val(static_cast<float64_t>(i::Smi::ToInt(*value)));
        }
        if (value->IsHeapNumber()) {
          return Val(i::HeapNumber::cast(*value)->value());
        }
        value = i::Object::ToNumber(isolate, value).ToHandleChecked();
        // This will loop back at most once.
      } while (true);
      UNREACHABLE();
1199 1200
    case ANYREF:
    case FUNCREF: {
1201
      if (value->IsNull(isolate)) {
1202 1203 1204 1205 1206 1207 1208 1209
        return Val(nullptr);
      } else {
        WASM_UNIMPLEMENTED("ref value");
      }
    }
  }
}

1210 1211 1212 1213 1214 1215 1216
i::Handle<i::String> VecToString(i::Isolate* isolate,
                                 const vec<byte_t>& chars) {
  return isolate->factory()
      ->NewStringFromUtf8({chars.get(), chars.size()})
      .ToHandleChecked();
}

1217 1218
// References

1219 1220
template <class Ref, class JSType>
class RefImpl {
1221
 public:
1222 1223
  static own<Ref*> make(StoreImpl* store, i::Handle<JSType> obj) {
    RefImpl* self = new (std::nothrow) RefImpl();
1224
    if (!self) return nullptr;
1225 1226
    i::Isolate* isolate = store->i_isolate();
    self->val_ = isolate->global_handles()->Create(*obj);
1227 1228 1229
    return make_own(seal<Ref>(self));
  }

1230 1231 1232 1233 1234 1235 1236 1237
  void Reset() {
    i::GlobalHandles::Destroy(location());
    if (host_data_) {
      if (host_data_->finalizer) {
        host_data_->finalizer(host_data_->info);
      }
      delete host_data_;
    }
1238 1239
  }

1240
  own<Ref*> copy() const { return make(store(), v8_object()); }
1241

1242
  StoreImpl* store() const { return StoreImpl::get(isolate()); }
1243

1244
  i::Isolate* isolate() const { return val_->GetIsolate(); }
1245

1246
  i::Handle<JSType> v8_object() const { return i::Handle<JSType>::cast(val_); }
1247

1248 1249 1250
  void* get_host_info() const {
    if (host_data_ == nullptr) return nullptr;
    return host_data_->info;
1251 1252 1253
  }

  void set_host_info(void* info, void (*finalizer)(void*)) {
1254 1255 1256
    host_data_ = new HostData(location(), info, finalizer);
    i::GlobalHandles::MakeWeak(host_data_->location, host_data_, &v8_finalizer,
                               v8::WeakCallbackType::kParameter);
1257 1258 1259 1260
  }

 private:
  struct HostData {
1261 1262 1263
    HostData(i::Address* location, void* info, void (*finalizer)(void*))
        : location(location), info(info), finalizer(finalizer) {}
    i::Address* location;
1264 1265 1266 1267
    void* info;
    void (*finalizer)(void*);
  };

1268 1269 1270 1271 1272
  RefImpl() {}

  static void v8_finalizer(const v8::WeakCallbackInfo<void>& info) {
    HostData* data = reinterpret_cast<HostData*>(info.GetParameter());
    i::GlobalHandles::Destroy(data->location);
1273 1274 1275
    if (data->finalizer) (*data->finalizer)(data->info);
    delete data;
  }
1276 1277 1278 1279 1280 1281 1282

  i::Address* location() const {
    return reinterpret_cast<i::Address*>(val_.address());
  }

  i::Handle<i::JSReceiver> val_;
  HostData* host_data_ = nullptr;
1283 1284 1285 1286
};

template <>
struct implement<Ref> {
1287
  using type = RefImpl<Ref, i::JSReceiver>;
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
};

Ref::~Ref() {
  impl(this)->Reset();
  delete impl(this);
}

void Ref::operator delete(void* p) {}

auto Ref::copy() const -> own<Ref*> { return impl(this)->copy(); }

auto Ref::get_host_info() const -> void* { return impl(this)->get_host_info(); }

void Ref::set_host_info(void* info, void (*finalizer)(void*)) {
  impl(this)->set_host_info(info, finalizer);
}

///////////////////////////////////////////////////////////////////////////////
// Runtime Objects

// Traps

template <>
struct implement<Trap> {
1312
  using type = RefImpl<Trap, i::JSReceiver>;
1313 1314 1315 1316 1317 1318 1319 1320
};

Trap::~Trap() {}

auto Trap::copy() const -> own<Trap*> { return impl(this)->copy(); }

auto Trap::make(Store* store_abs, const Message& message) -> own<Trap*> {
  auto store = impl(store_abs);
1321 1322 1323 1324 1325 1326
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
  i::Handle<i::String> string = VecToString(isolate, message);
  i::Handle<i::JSReceiver> exception = i::Handle<i::JSReceiver>::cast(
      isolate->factory()->NewError(isolate->error_function(), string));
  return implement<Trap>::type::make(store, exception);
1327 1328 1329 1330
}

auto Trap::message() const -> Message {
  auto isolate = impl(this)->isolate();
1331
  i::HandleScope handle_scope(isolate);
1332

1333 1334 1335 1336 1337 1338 1339 1340
  i::Handle<i::JSMessageObject> message =
      isolate->CreateMessage(impl(this)->v8_object(), nullptr);
  i::Handle<i::String> result = i::MessageHandler::GetMessage(isolate, message);
  result = i::String::Flatten(isolate, result);  // For performance.
  int length = 0;
  std::unique_ptr<char[]> utf8 =
      result->ToCString(i::DISALLOW_NULLS, i::FAST_STRING_TRAVERSAL, &length);
  return vec<byte_t>::adopt(length, utf8.release());
1341 1342 1343 1344 1345 1346
}

// Foreign Objects

template <>
struct implement<Foreign> {
1347
  using type = RefImpl<Foreign, i::JSReceiver>;
1348 1349 1350 1351 1352 1353 1354 1355
};

Foreign::~Foreign() {}

auto Foreign::copy() const -> own<Foreign*> { return impl(this)->copy(); }

auto Foreign::make(Store* store_abs) -> own<Foreign*> {
  auto store = impl(store_abs);
1356 1357
  auto isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
1358

1359 1360
  auto obj = i::Handle<i::JSReceiver>();
  return implement<Foreign>::type::make(store, obj);
1361 1362 1363 1364 1365 1366
}

// Modules

template <>
struct implement<Module> {
1367
  using type = RefImpl<Module, i::WasmModuleObject>;
1368 1369 1370 1371 1372 1373 1374
};

Module::~Module() {}

auto Module::copy() const -> own<Module*> { return impl(this)->copy(); }

auto Module::validate(Store* store_abs, const vec<byte_t>& binary) -> bool {
1375 1376 1377 1378 1379
  i::wasm::ModuleWireBytes bytes(
      {reinterpret_cast<const uint8_t*>(binary.get()), binary.size()});
  i::Isolate* isolate = impl(store_abs)->i_isolate();
  i::wasm::WasmFeatures features = i::wasm::WasmFeaturesFromIsolate(isolate);
  return isolate->wasm_engine()->SyncValidate(isolate, features, bytes);
1380 1381
}

1382 1383 1384 1385 1386 1387
class NopErrorThrower : public i::wasm::ErrorThrower {
 public:
  explicit NopErrorThrower(i::Isolate* isolate)
      : i::wasm::ErrorThrower(isolate, "ignored") {}
  ~NopErrorThrower() { Reset(); }
};
1388

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
auto Module::make(Store* store_abs, const vec<byte_t>& binary) -> own<Module*> {
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope scope(isolate);
  i::wasm::ModuleWireBytes bytes(
      {reinterpret_cast<const uint8_t*>(binary.get()), binary.size()});
  i::wasm::WasmFeatures features = i::wasm::WasmFeaturesFromIsolate(isolate);
  NopErrorThrower thrower(isolate);
  i::Handle<i::WasmModuleObject> module;
  if (!isolate->wasm_engine()
           ->SyncCompile(isolate, features, &thrower, bytes)
           .ToHandle(&module)) {
    return nullptr;
  }
  return implement<Module>::type::make(store, module);
1404 1405 1406
}

auto Module::imports() const -> vec<ImportType*> {
1407 1408 1409
  i::Vector<const uint8_t> wire_bytes =
      impl(this)->v8_object()->native_module()->wire_bytes();
  vec<const byte_t> binary = vec<const byte_t>::adopt(
1410
      wire_bytes.size(), reinterpret_cast<const byte_t*>(wire_bytes.begin()));
1411 1412 1413 1414 1415
  auto imports = wasm::bin::imports(binary);
  binary.release();
  return imports;
}

1416 1417 1418 1419
vec<ExportType*> ExportsImpl(i::Handle<i::WasmModuleObject> module_obj) {
  i::Vector<const uint8_t> wire_bytes =
      module_obj->native_module()->wire_bytes();
  vec<const byte_t> binary = vec<const byte_t>::adopt(
1420
      wire_bytes.size(), reinterpret_cast<const byte_t*>(wire_bytes.begin()));
1421 1422 1423 1424 1425
  auto exports = wasm::bin::exports(binary);
  binary.release();
  return exports;
}

1426 1427 1428 1429
auto Module::exports() const -> vec<ExportType*> {
  return ExportsImpl(impl(this)->v8_object());
}

1430
auto Module::serialize() const -> vec<byte_t> {
1431 1432 1433 1434 1435 1436 1437 1438
  i::wasm::NativeModule* native_module =
      impl(this)->v8_object()->native_module();
  i::Vector<const uint8_t> wire_bytes = native_module->wire_bytes();
  size_t binary_size = wire_bytes.size();
  i::wasm::WasmSerializer serializer(native_module);
  size_t serial_size = serializer.GetSerializedNativeModuleSize();
  size_t size_size = i::wasm::LEBHelper::sizeof_u64v(binary_size);
  vec<byte_t> buffer =
1439
      vec<byte_t>::make_uninitialized(size_size + binary_size + serial_size);
1440
  byte_t* ptr = buffer.get();
1441 1442
  i::wasm::LEBHelper::write_u64v(reinterpret_cast<uint8_t**>(&ptr),
                                 binary_size);
1443
  std::memcpy(ptr, wire_bytes.begin(), binary_size);
1444
  ptr += binary_size;
1445 1446 1447 1448
  if (!serializer.SerializeNativeModule(
          {reinterpret_cast<uint8_t*>(ptr), serial_size})) {
    buffer.reset();
  }
1449 1450 1451 1452 1453
  return std::move(buffer);
}

auto Module::deserialize(Store* store_abs, const vec<byte_t>& serialized)
    -> own<Module*> {
1454 1455 1456 1457 1458 1459 1460 1461
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
  const byte_t* ptr = serialized.get();
  uint64_t binary_size = wasm::bin::u64(ptr);
  ptrdiff_t size_size = ptr - serialized.get();
  size_t serial_size = serialized.size() - size_size - binary_size;
  i::Handle<i::WasmModuleObject> module_obj;
1462
  size_t data_size = static_cast<size_t>(binary_size);
1463 1464
  if (!i::wasm::DeserializeNativeModule(
           isolate,
1465 1466
           {reinterpret_cast<const uint8_t*>(ptr + data_size), serial_size},
           {reinterpret_cast<const uint8_t*>(ptr), data_size})
1467 1468 1469 1470
           .ToHandle(&module_obj)) {
    return nullptr;
  }
  return implement<Module>::type::make(store, module_obj);
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
}

// TODO(v8): do better when V8 can do better.
template <>
struct implement<Shared<Module>> {
  using type = vec<byte_t>;
};

template <>
Shared<Module>::~Shared() {
  impl(this)->~vec();
}

template <>
void Shared<Module>::operator delete(void* p) {
  ::operator delete(p);
}

auto Module::share() const -> own<Shared<Module>*> {
  auto shared = seal<Shared<Module>>(new vec<byte_t>(serialize()));
  return make_own(shared);
}

auto Module::obtain(Store* store, const Shared<Module>* shared)
    -> own<Module*> {
  return Module::deserialize(store, *impl(shared));
}

// Externals

template <>
struct implement<Extern> {
1503
  using type = RefImpl<Extern, i::JSReceiver>;
1504 1505 1506 1507 1508 1509 1510
};

Extern::~Extern() {}

auto Extern::copy() const -> own<Extern*> { return impl(this)->copy(); }

auto Extern::kind() const -> ExternKind {
1511 1512 1513 1514 1515 1516 1517 1518
  i::Handle<i::JSReceiver> obj = impl(this)->v8_object();
  if (i::WasmExportedFunction::IsWasmExportedFunction(*obj)) {
    return wasm::EXTERN_FUNC;
  }
  if (obj->IsWasmGlobalObject()) return wasm::EXTERN_GLOBAL;
  if (obj->IsWasmTableObject()) return wasm::EXTERN_TABLE;
  if (obj->IsWasmMemoryObject()) return wasm::EXTERN_MEMORY;
  UNREACHABLE();
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
}

auto Extern::type() const -> own<ExternType*> {
  switch (kind()) {
    case EXTERN_FUNC:
      return func()->type();
    case EXTERN_GLOBAL:
      return global()->type();
    case EXTERN_TABLE:
      return table()->type();
    case EXTERN_MEMORY:
      return memory()->type();
  }
}

auto Extern::func() -> Func* {
  return kind() == EXTERN_FUNC ? static_cast<Func*>(this) : nullptr;
}

auto Extern::global() -> Global* {
  return kind() == EXTERN_GLOBAL ? static_cast<Global*>(this) : nullptr;
}

auto Extern::table() -> Table* {
  return kind() == EXTERN_TABLE ? static_cast<Table*>(this) : nullptr;
}

auto Extern::memory() -> Memory* {
  return kind() == EXTERN_MEMORY ? static_cast<Memory*>(this) : nullptr;
}

auto Extern::func() const -> const Func* {
  return kind() == EXTERN_FUNC ? static_cast<const Func*>(this) : nullptr;
}

auto Extern::global() const -> const Global* {
  return kind() == EXTERN_GLOBAL ? static_cast<const Global*>(this) : nullptr;
}

auto Extern::table() const -> const Table* {
  return kind() == EXTERN_TABLE ? static_cast<const Table*>(this) : nullptr;
}

auto Extern::memory() const -> const Memory* {
  return kind() == EXTERN_MEMORY ? static_cast<const Memory*>(this) : nullptr;
}

1566
auto extern_to_v8(const Extern* ex) -> i::Handle<i::JSReceiver> {
1567 1568 1569 1570 1571 1572 1573
  return impl(ex)->v8_object();
}

// Function Instances

template <>
struct implement<Func> {
1574
  using type = RefImpl<Func, i::JSFunction>;
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
};

Func::~Func() {}

auto Func::copy() const -> own<Func*> { return impl(this)->copy(); }

struct FuncData {
  Store* store;
  own<FuncType*> type;
  enum Kind { kCallback, kCallbackWithEnv } kind;
  union {
    Func::callback callback;
    Func::callback_with_env callback_with_env;
  };
  void (*finalizer)(void*);
  void* env;

  FuncData(Store* store, const FuncType* type, Kind kind)
      : store(store),
        type(type->copy()),
        kind(kind),
        finalizer(nullptr),
        env(nullptr) {}

  ~FuncData() {
    if (finalizer) (*finalizer)(env);
  }

1603
  static i::Address v8_callback(void* data, i::Address argv);
1604 1605 1606 1607 1608
  static void finalize_func_data(void* data);
};

namespace {

1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
// TODO(jkummerow): Generalize for WasmExportedFunction and WasmCapiFunction.
class SignatureHelper : public i::AllStatic {
 public:
  // Use an invalid type as a marker separating params and results.
  static const i::wasm::ValueType kMarker = i::wasm::kWasmStmt;

  static i::Handle<i::PodArray<i::wasm::ValueType>> Serialize(
      i::Isolate* isolate, FuncType* type) {
    int sig_size =
        static_cast<int>(type->params().size() + type->results().size() + 1);
    i::Handle<i::PodArray<i::wasm::ValueType>> sig =
        i::PodArray<i::wasm::ValueType>::New(isolate, sig_size,
                                             i::AllocationType::kOld);
    int index = 0;
    // TODO(jkummerow): Consider making vec<> range-based for-iterable.
    for (size_t i = 0; i < type->results().size(); i++) {
      sig->set(index++,
               v8::wasm::wasm_valtype_to_v8(type->results()[i]->kind()));
    }
    // {sig->set} needs to take the address of its second parameter,
    // so we can't pass in the static const kMarker directly.
    i::wasm::ValueType marker = kMarker;
    sig->set(index++, marker);
    for (size_t i = 0; i < type->params().size(); i++) {
      sig->set(index++,
               v8::wasm::wasm_valtype_to_v8(type->params()[i]->kind()));
    }
    return sig;
  }

  static own<FuncType*> Deserialize(i::PodArray<i::wasm::ValueType> sig) {
    int result_arity = ResultArity(sig);
    int param_arity = sig->length() - result_arity - 1;
    vec<ValType*> results = vec<ValType*>::make_uninitialized(result_arity);
    vec<ValType*> params = vec<ValType*>::make_uninitialized(param_arity);

    int i = 0;
    for (; i < sig->length(); ++i) {
      results[i] = ValType::make(v8::wasm::v8_valtype_to_wasm(sig->get(i)));
    }
    i++;
    for (; i < param_arity; ++i) {
      params[i] = ValType::make(v8::wasm::v8_valtype_to_wasm(sig->get(i)));
    }
    return FuncType::make(std::move(params), std::move(results));
  }

  static int ResultArity(i::PodArray<i::wasm::ValueType> sig) {
    int count = 0;
    for (; count < sig->length(); count++) {
      if (sig->get(count) == kMarker) return count;
    }
    UNREACHABLE();
  }

  static int ParamArity(i::PodArray<i::wasm::ValueType> sig) {
    return sig->length() - ResultArity(sig) - 1;
  }

  static i::PodArray<i::wasm::ValueType> GetSig(
      i::Handle<i::JSFunction> function) {
    return i::WasmCapiFunction::cast(*function)->GetSerializedSignature();
  }
};

1674 1675
auto make_func(Store* store_abs, FuncData* data) -> own<Func*> {
  auto store = impl(store_abs);
1676 1677
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
1678 1679 1680 1681
  i::Handle<i::WasmCapiFunction> function = i::WasmCapiFunction::New(
      isolate, reinterpret_cast<i::Address>(&FuncData::v8_callback), data,
      SignatureHelper::Serialize(isolate, data->type.get()));
  auto func = implement<Func>::type::make(store, function);
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
  func->set_host_info(data, &FuncData::finalize_func_data);
  return func;
}

}  // namespace

auto Func::make(Store* store, const FuncType* type, Func::callback callback)
    -> own<Func*> {
  auto data = new FuncData(store, type, FuncData::kCallback);
  data->callback = callback;
  return make_func(store, data);
}

auto Func::make(Store* store, const FuncType* type, callback_with_env callback,
                void* env, void (*finalizer)(void*)) -> own<Func*> {
  auto data = new FuncData(store, type, FuncData::kCallbackWithEnv);
  data->callback_with_env = callback;
  data->env = env;
  data->finalizer = finalizer;
  return make_func(store, data);
}

auto Func::type() const -> own<FuncType*> {
1705 1706 1707 1708 1709 1710 1711
  i::Handle<i::JSFunction> func = impl(this)->v8_object();
  if (i::WasmCapiFunction::IsWasmCapiFunction(*func)) {
    return SignatureHelper::Deserialize(SignatureHelper::GetSig(func));
  }
  DCHECK(i::WasmExportedFunction::IsWasmExportedFunction(*func));
  i::Handle<i::WasmExportedFunction> function =
      i::Handle<i::WasmExportedFunction>::cast(func);
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
  i::wasm::FunctionSig* sig =
      function->instance()->module()->functions[function->function_index()].sig;
  uint32_t param_arity = static_cast<uint32_t>(sig->parameter_count());
  uint32_t result_arity = static_cast<uint32_t>(sig->return_count());
  auto params = vec<ValType*>::make_uninitialized(param_arity);
  auto results = vec<ValType*>::make_uninitialized(result_arity);

  for (size_t i = 0; i < params.size(); ++i) {
    auto kind = v8::wasm::v8_valtype_to_wasm(sig->GetParam(i));
    params[i] = ValType::make(kind);
  }
  for (size_t i = 0; i < results.size(); ++i) {
    auto kind = v8::wasm::v8_valtype_to_wasm(sig->GetReturn(i));
    results[i] = ValType::make(kind);
  }
  return FuncType::make(std::move(params), std::move(results));
1728 1729 1730
}

auto Func::param_arity() const -> size_t {
1731 1732 1733 1734 1735 1736 1737
  i::Handle<i::JSFunction> func = impl(this)->v8_object();
  if (i::WasmCapiFunction::IsWasmCapiFunction(*func)) {
    return SignatureHelper::ParamArity(SignatureHelper::GetSig(func));
  }
  DCHECK(i::WasmExportedFunction::IsWasmExportedFunction(*func));
  i::Handle<i::WasmExportedFunction> function =
      i::Handle<i::WasmExportedFunction>::cast(func);
1738 1739 1740
  i::wasm::FunctionSig* sig =
      function->instance()->module()->functions[function->function_index()].sig;
  return sig->parameter_count();
1741 1742 1743
}

auto Func::result_arity() const -> size_t {
1744 1745 1746 1747 1748 1749 1750
  i::Handle<i::JSFunction> func = impl(this)->v8_object();
  if (i::WasmCapiFunction::IsWasmCapiFunction(*func)) {
    return SignatureHelper::ResultArity(SignatureHelper::GetSig(func));
  }
  DCHECK(i::WasmExportedFunction::IsWasmExportedFunction(*func));
  i::Handle<i::WasmExportedFunction> function =
      i::Handle<i::WasmExportedFunction>::cast(func);
1751 1752 1753
  i::wasm::FunctionSig* sig =
      function->instance()->module()->functions[function->function_index()].sig;
  return sig->return_count();
1754 1755 1756 1757 1758 1759
}

auto Func::call(const Val args[], Val results[]) const -> own<Trap*> {
  auto func = impl(this);
  auto store = func->store();
  auto isolate = store->isolate();
1760
  auto i_isolate = store->i_isolate();
1761 1762
  v8::HandleScope handle_scope(isolate);

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
  int num_params;
  int num_results;
  ValKind result_kind;
  i::Handle<i::JSFunction> v8_func = func->v8_object();
  if (i::WasmExportedFunction::IsWasmExportedFunction(*v8_func)) {
    i::WasmExportedFunction wef = i::WasmExportedFunction::cast(*v8_func);
    i::wasm::FunctionSig* sig =
        wef->instance()->module()->functions[wef->function_index()].sig;
    num_params = static_cast<int>(sig->parameter_count());
    num_results = static_cast<int>(sig->return_count());
    if (num_results > 0) {
      result_kind = v8::wasm::v8_valtype_to_wasm(sig->GetReturn(0));
    }
#if DEBUG
    for (int i = 0; i < num_params; i++) {
      DCHECK_EQ(args[i].kind(), v8::wasm::v8_valtype_to_wasm(sig->GetParam(i)));
    }
#endif
  } else {
    DCHECK(i::WasmCapiFunction::IsWasmCapiFunction(*v8_func));
    UNIMPLEMENTED();
  }
1785
  // TODO(rossberg): cache v8_args array per thread.
1786
  auto v8_args = std::unique_ptr<i::Handle<i::Object>[]>(
1787 1788
      new (std::nothrow) i::Handle<i::Object>[num_params]);
  for (int i = 0; i < num_params; ++i) {
1789
    v8_args[i] = v8::Utils::OpenHandle(*val_to_v8(store, args[i]));
1790 1791
  }

1792
  // TODO(jkummerow): Use Execution::TryCall instead of manual TryCatch.
1793
  v8::TryCatch handler(isolate);
1794 1795
  i::MaybeHandle<i::Object> maybe_val = i::Execution::Call(
      i_isolate, func->v8_object(), i_isolate->factory()->undefined_value(),
1796
      num_params, v8_args.get());
1797 1798

  if (handler.HasCaught()) {
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
    i_isolate->OptionalRescheduleException(true);
    i::Handle<i::Object> exception =
        v8::Utils::OpenHandle(*handler.Exception());
    if (!exception->IsJSReceiver()) {
      i::MaybeHandle<i::String> maybe_string =
          i::Object::ToString(i_isolate, exception);
      i::Handle<i::String> string = maybe_string.is_null()
                                        ? i_isolate->factory()->empty_string()
                                        : maybe_string.ToHandleChecked();
      exception =
          i_isolate->factory()->NewError(i_isolate->error_function(), string);
1810
    }
1811 1812
    return implement<Trap>::type::make(
        store, i::Handle<i::JSReceiver>::cast(exception));
1813 1814
  }

1815
  auto val = maybe_val.ToHandleChecked();
1816
  if (num_results == 0) {
1817
    assert(val->IsUndefined(i_isolate));
1818
  } else if (num_results == 1) {
1819
    assert(!val->IsUndefined(i_isolate));
1820
    new (&results[0]) Val(v8_to_val(i_isolate, val, result_kind));
1821 1822 1823 1824 1825 1826
  } else {
    WASM_UNIMPLEMENTED("multiple results");
  }
  return nullptr;
}

1827 1828
i::Address FuncData::v8_callback(void* data, i::Address argv) {
  FuncData* self = reinterpret_cast<FuncData*>(data);
1829

1830 1831
  const vec<ValType*>& param_types = self->type->params();
  const vec<ValType*>& result_types = self->type->results();
1832 1833 1834 1835

  int num_param_types = static_cast<int>(param_types.size());
  int num_result_types = static_cast<int>(result_types.size());

1836
  std::unique_ptr<Val[]> params(new Val[num_param_types]);
1837
  std::unique_ptr<Val[]> results(new Val[num_result_types]);
1838
  i::Address p = argv;
1839
  for (int i = 0; i < num_param_types; ++i) {
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
    switch (param_types[i]->kind()) {
      case I32:
        params[i] = Val(i::ReadUnalignedValue<int32_t>(p));
        p += 4;
        break;
      case I64:
        params[i] = Val(i::ReadUnalignedValue<int64_t>(p));
        p += 8;
        break;
      case F32:
        params[i] = Val(i::ReadUnalignedValue<float32_t>(p));
        p += 4;
        break;
      case F64:
        params[i] = Val(i::ReadUnalignedValue<float64_t>(p));
        p += 8;
        break;
      case ANYREF:
      case FUNCREF: {
        i::Address raw = i::ReadUnalignedValue<i::Address>(p);
        p += sizeof(raw);
        if (raw == i::kNullAddress) {
          params[i] = Val(nullptr);
        } else {
          i::JSReceiver raw_obj = i::JSReceiver::cast(i::Object(raw));
          i::Handle<i::JSReceiver> obj(raw_obj, raw_obj->GetIsolate());
          params[i] = Val(implement<Ref>::type::make(impl(self->store), obj));
        }
        break;
      }
    }
1871 1872 1873 1874
  }

  own<Trap*> trap;
  if (self->kind == kCallbackWithEnv) {
1875
    trap = self->callback_with_env(self->env, params.get(), results.get());
1876
  } else {
1877
    trap = self->callback(params.get(), results.get());
1878 1879 1880
  }

  if (trap) {
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
    i::Isolate* isolate = impl(self->store)->i_isolate();
    isolate->Throw(*impl(trap.get())->v8_object());
    i::Object ex = isolate->pending_exception();
    isolate->clear_pending_exception();
    return ex->ptr();
  }

  p = argv;
  for (int i = 0; i < num_result_types; ++i) {
    switch (result_types[i]->kind()) {
      case I32:
        i::WriteUnalignedValue(p, results[i].i32());
        p += 4;
        break;
      case I64:
        i::WriteUnalignedValue(p, results[i].i64());
        p += 8;
        break;
      case F32:
        i::WriteUnalignedValue(p, results[i].f32());
        p += 4;
        break;
      case F64:
        i::WriteUnalignedValue(p, results[i].f64());
        p += 8;
        break;
      case ANYREF:
      case FUNCREF: {
        if (results[i].ref() == nullptr) {
          i::WriteUnalignedValue(p, i::kNullAddress);
        } else {
          i::WriteUnalignedValue(p, impl(results[i].ref())->v8_object()->ptr());
        }
        p += sizeof(i::Address);
        break;
      }
    }
1918
  }
1919
  return i::kNullAddress;
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
}

void FuncData::finalize_func_data(void* data) {
  delete reinterpret_cast<FuncData*>(data);
}

// Global Instances

template <>
struct implement<Global> {
1930
  using type = RefImpl<Global, i::WasmGlobalObject>;
1931 1932 1933 1934 1935 1936 1937 1938
};

Global::~Global() {}

auto Global::copy() const -> own<Global*> { return impl(this)->copy(); }

auto Global::make(Store* store_abs, const GlobalType* type, const Val& val)
    -> own<Global*> {
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);

  DCHECK_EQ(type->content()->kind(), val.kind());

  i::wasm::ValueType i_type =
      v8::wasm::wasm_valtype_to_v8(type->content()->kind());
  bool is_mutable = (type->mutability() == VAR);
  const int32_t offset = 0;
  i::Handle<i::WasmGlobalObject> obj =
      i::WasmGlobalObject::New(isolate, i::MaybeHandle<i::JSArrayBuffer>(),
                               i::MaybeHandle<i::FixedArray>(), i_type, offset,
                               is_mutable)
          .ToHandleChecked();

  auto global = implement<Global>::type::make(store, obj);
1956 1957 1958 1959 1960 1961
  assert(global);
  global->set(val);
  return global;
}

auto Global::type() const -> own<GlobalType*> {
1962 1963 1964
  i::Handle<i::WasmGlobalObject> v8_global = impl(this)->v8_object();
  ValKind kind = v8::wasm::v8_valtype_to_wasm(v8_global->type());
  Mutability mutability = v8_global->is_mutable() ? VAR : CONST;
1965 1966 1967 1968
  return GlobalType::make(ValType::make(kind), mutability);
}

auto Global::get() const -> Val {
1969
  i::Handle<i::WasmGlobalObject> v8_global = impl(this)->v8_object();
1970 1971
  switch (type()->content()->kind()) {
    case I32:
1972
      return Val(v8_global->GetI32());
1973
    case I64:
1974
      return Val(v8_global->GetI64());
1975
    case F32:
1976
      return Val(v8_global->GetF32());
1977
    case F64:
1978
      return Val(v8_global->GetF64());
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    case ANYREF:
    case FUNCREF:
      WASM_UNIMPLEMENTED("globals of reference type");
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
  }
}

void Global::set(const Val& val) {
1989
  i::Handle<i::WasmGlobalObject> v8_global = impl(this)->v8_object();
1990 1991
  switch (val.kind()) {
    case I32:
1992
      return v8_global->SetI32(val.i32());
1993
    case I64:
1994
      return v8_global->SetI64(val.i64());
1995
    case F32:
1996
      return v8_global->SetF32(val.f32());
1997
    case F64:
1998
      return v8_global->SetF64(val.f64());
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
    case ANYREF:
    case FUNCREF:
      WASM_UNIMPLEMENTED("globals of reference type");
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
  }
}

// Table Instances

template <>
struct implement<Table> {
2012
  using type = RefImpl<Table, i::WasmTableObject>;
2013 2014 2015 2016 2017 2018 2019 2020
};

Table::~Table() {}

auto Table::copy() const -> own<Table*> { return impl(this)->copy(); }

auto Table::make(Store* store_abs, const TableType* type, const Ref* ref)
    -> own<Table*> {
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope scope(isolate);
  auto enabled_features = i::wasm::WasmFeaturesFromFlags();

  // Get "element".
  i::wasm::ValueType i_type;
  switch (type->element()->kind()) {
    case FUNCREF:
      i_type = i::wasm::kWasmAnyFunc;
      break;
    case ANYREF:
      if (enabled_features.anyref) {
        i_type = i::wasm::kWasmAnyRef;
        break;
      }  // Else fall through.
      V8_FALLTHROUGH;
    default:
      UNREACHABLE();  // 'element' must be 'FUNCREF'.
      return nullptr;
  }

  const Limits& limits = type->limits();
  uint32_t minimum = limits.min;
  if (minimum > i::wasm::max_table_init_entries()) return nullptr;
  uint32_t maximum = limits.max;
  bool has_maximum = false;
  if (maximum != Limits(0).max) {
    has_maximum = true;
    if (maximum < minimum) return nullptr;
    if (maximum > i::wasm::max_table_init_entries()) return nullptr;
  }

  i::Handle<i::FixedArray> backing_store;
  i::Handle<i::WasmTableObject> table_obj = i::WasmTableObject::New(
      isolate, i_type, minimum, has_maximum, maximum, &backing_store);

  if (ref) {
    i::Handle<i::JSReceiver> init = impl(ref)->v8_object();
    DCHECK(i::wasm::max_table_init_entries() <= i::kMaxInt);
    for (int i = 0; i < static_cast<int>(minimum); i++) {
      // This doesn't call WasmTableObject::Set because the table has
      // just been created, so it can't be imported by any instances
      // yet that might require updating.
      DCHECK_EQ(table_obj->dispatch_tables()->length(), 0);
      backing_store->set(i, *init);
2067 2068
    }
  }
2069
  return implement<Table>::type::make(store, table_obj);
2070 2071 2072
}

auto Table::type() const -> own<TableType*> {
2073 2074 2075 2076
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
  uint32_t min = table->current_length();
  uint32_t max;
  if (!table->maximum_length()->ToUint32(&max)) max = 0xFFFFFFFFu;
2077 2078 2079 2080 2081
  // TODO(wasm+): support new element types.
  return TableType::make(ValType::make(FUNCREF), Limits(min, max));
}

auto Table::get(size_t index) const -> own<Ref*> {
2082 2083 2084 2085 2086 2087
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
  if (index >= table->current_length()) return own<Ref*>();
  i::Isolate* isolate = table->GetIsolate();
  i::HandleScope handle_scope(isolate);
  i::Handle<i::Object> result =
      i::WasmTableObject::Get(isolate, table, static_cast<uint32_t>(index));
2088 2089 2090
  if (!result->IsJSFunction()) return own<Ref*>();
  DCHECK(i::WasmExportedFunction::IsWasmExportedFunction(*result) ||
         i::WasmCapiFunction::IsWasmCapiFunction(*result));
2091
  // TODO(wasm+): other references
2092 2093
  return implement<Func>::type::make(impl(this)->store(),
                                     i::Handle<i::JSFunction>::cast(result));
2094 2095 2096 2097 2098 2099
}

auto Table::set(size_t index, const Ref* ref) -> bool {
  if (ref && !impl(ref)->v8_object()->IsFunction()) {
    WASM_UNIMPLEMENTED("non-function table elements");
  }
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
  if (index >= table->current_length()) return false;
  i::Isolate* isolate = table->GetIsolate();
  i::HandleScope handle_scope(isolate);
  i::Handle<i::Object> obj =
      ref ? i::Handle<i::Object>::cast(impl(ref)->v8_object())
          : i::Handle<i::Object>::cast(
                i::ReadOnlyRoots(isolate).null_value_handle());
  i::WasmTableObject::Set(isolate, table, static_cast<uint32_t>(index), obj);
  return true;
2110 2111
}

2112
// TODO(jkummerow): Having Table::size_t shadowing "std" size_t is ugly.
2113
auto Table::size() const -> size_t {
2114
  return impl(this)->v8_object()->current_length();
2115 2116 2117
}

auto Table::grow(size_t delta, const Ref* ref) -> bool {
2118
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
2119
  i::Isolate* isolate = table->GetIsolate();
2120 2121 2122 2123 2124 2125 2126
  i::HandleScope scope(isolate);
  i::Handle<i::Object> init_value =
      ref == nullptr
          ? i::Handle<i::Object>::cast(isolate->factory()->null_value())
          : i::Handle<i::Object>::cast(impl(ref)->v8_object());
  int result = i::WasmTableObject::Grow(
      isolate, table, static_cast<uint32_t>(delta), init_value);
2127
  return result >= 0;
2128 2129 2130 2131 2132 2133
}

// Memory Instances

template <>
struct implement<Memory> {
2134
  using type = RefImpl<Memory, i::WasmMemoryObject>;
2135 2136 2137 2138 2139 2140 2141
};

Memory::~Memory() {}

auto Memory::copy() const -> own<Memory*> { return impl(this)->copy(); }

auto Memory::make(Store* store_abs, const MemoryType* type) -> own<Memory*> {
2142 2143 2144
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope scope(isolate);
2145

2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
  const Limits& limits = type->limits();
  uint32_t minimum = limits.min;
  if (minimum > i::wasm::max_mem_pages()) return nullptr;
  uint32_t maximum = limits.max;
  if (maximum != Limits(0).max) {
    if (maximum < minimum) return nullptr;
    if (maximum > i::wasm::kSpecMaxWasmMemoryPages) return nullptr;
  }
  bool is_shared = false;  // TODO(wasm+): Support shared memory.
  i::Handle<i::WasmMemoryObject> memory_obj;
  if (!i::WasmMemoryObject::New(isolate, minimum, maximum, is_shared)
           .ToHandle(&memory_obj)) {
    return own<Memory*>();
  }
  return implement<Memory>::type::make(store, memory_obj);
2161 2162 2163
}

auto Memory::type() const -> own<MemoryType*> {
2164 2165 2166 2167 2168
  i::Handle<i::WasmMemoryObject> memory = impl(this)->v8_object();
  uint32_t min = static_cast<uint32_t>(memory->array_buffer()->byte_length() /
                                       i::wasm::kWasmPageSize);
  uint32_t max =
      memory->has_maximum_pages() ? memory->maximum_pages() : 0xFFFFFFFFu;
2169 2170 2171 2172
  return MemoryType::make(Limits(min, max));
}

auto Memory::data() const -> byte_t* {
2173 2174
  return reinterpret_cast<byte_t*>(
      impl(this)->v8_object()->array_buffer()->backing_store());
2175 2176 2177
}

auto Memory::data_size() const -> size_t {
2178
  return impl(this)->v8_object()->array_buffer()->byte_length();
2179 2180 2181
}

auto Memory::size() const -> pages_t {
2182 2183 2184
  return static_cast<pages_t>(
      impl(this)->v8_object()->array_buffer()->byte_length() /
      i::wasm::kWasmPageSize);
2185 2186 2187
}

auto Memory::grow(pages_t delta) -> bool {
2188 2189 2190 2191 2192
  i::Handle<i::WasmMemoryObject> memory = impl(this)->v8_object();
  i::Isolate* isolate = memory->GetIsolate();
  i::HandleScope handle_scope(isolate);
  int32_t old = i::WasmMemoryObject::Grow(isolate, memory, delta);
  return old != -1;
2193 2194 2195 2196 2197 2198
}

// Module Instances

template <>
struct implement<Instance> {
2199
  using type = RefImpl<Instance, i::WasmInstanceObject>;
2200 2201 2202 2203 2204 2205 2206 2207
};

Instance::~Instance() {}

auto Instance::copy() const -> own<Instance*> { return impl(this)->copy(); }

auto Instance::make(Store* store_abs, const Module* module_abs,
                    const Extern* const imports[]) -> own<Instance*> {
2208 2209 2210 2211
  StoreImpl* store = impl(store_abs);
  const implement<Module>::type* module = impl(module_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
2212

2213
  DCHECK_EQ(module->v8_object()->GetIsolate(), isolate);
2214

2215 2216 2217
  vec<ImportType*> import_types = module_abs->imports();
  i::Handle<i::JSObject> imports_obj =
      isolate->factory()->NewJSObject(isolate->object_function());
2218 2219
  for (size_t i = 0; i < import_types.size(); ++i) {
    auto type = import_types[i];
2220 2221 2222 2223 2224 2225 2226 2227 2228
    i::Handle<i::String> module_str = VecToString(isolate, type->module());
    i::Handle<i::String> name_str = VecToString(isolate, type->name());

    i::Handle<i::JSObject> module_obj;
    i::LookupIterator module_it(isolate, imports_obj, module_str,
                                i::LookupIterator::OWN_SKIP_INTERCEPTOR);
    if (i::JSObject::HasProperty(&module_it).ToChecked()) {
      module_obj = i::Handle<i::JSObject>::cast(
          i::Object::GetProperty(&module_it).ToHandleChecked());
2229
    } else {
2230 2231 2232
      module_obj = isolate->factory()->NewJSObject(isolate->object_function());
      ignore(
          i::Object::SetProperty(isolate, imports_obj, module_str, module_obj));
2233
    }
2234 2235
    ignore(i::Object::SetProperty(isolate, module_obj, name_str,
                                  impl(imports[i])->v8_object()));
2236 2237
  }

2238 2239 2240 2241 2242 2243 2244
  NopErrorThrower thrower(isolate);
  i::Handle<i::WasmInstanceObject> instance_obj =
      isolate->wasm_engine()
          ->SyncInstantiate(isolate, &thrower, module->v8_object(), imports_obj,
                            i::MaybeHandle<i::JSArrayBuffer>())
          .ToHandleChecked();
  return implement<Instance>::type::make(store, instance_obj);
2245 2246 2247
}

auto Instance::exports() const -> vec<Extern*> {
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
  const implement<Instance>::type* instance = impl(this);
  StoreImpl* store = instance->store();
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
  i::Handle<i::WasmInstanceObject> instance_obj = instance->v8_object();
  i::Handle<i::WasmModuleObject> module_obj(instance_obj->module_object(),
                                            isolate);
  i::Handle<i::JSObject> exports_obj(instance_obj->exports_object(), isolate);

  vec<ExportType*> export_types = ExportsImpl(module_obj);
  vec<Extern*> exports = vec<Extern*>::make_uninitialized(export_types.size());
2259 2260 2261 2262
  if (!exports) return vec<Extern*>::invalid();

  for (size_t i = 0; i < export_types.size(); ++i) {
    auto& name = export_types[i]->name();
2263 2264 2265 2266 2267 2268
    i::Handle<i::String> name_str = VecToString(isolate, name);
    i::Handle<i::Object> obj =
        i::Object::GetProperty(isolate, exports_obj, name_str)
            .ToHandleChecked();

    const ExternType* type = export_types[i]->type();
2269 2270
    switch (type->kind()) {
      case EXTERN_FUNC: {
2271 2272 2273
        DCHECK(i::WasmExportedFunction::IsWasmExportedFunction(*obj));
        exports[i].reset(implement<Func>::type::make(
            store, i::Handle<i::WasmExportedFunction>::cast(obj)));
2274 2275
      } break;
      case EXTERN_GLOBAL: {
2276 2277
        exports[i].reset(implement<Global>::type::make(
            store, i::Handle<i::WasmGlobalObject>::cast(obj)));
2278 2279
      } break;
      case EXTERN_TABLE: {
2280 2281
        exports[i].reset(implement<Table>::type::make(
            store, i::Handle<i::WasmTableObject>::cast(obj)));
2282 2283
      } break;
      case EXTERN_MEMORY: {
2284 2285
        exports[i].reset(implement<Memory>::type::make(
            store, i::Handle<i::WasmMemoryObject>::cast(obj)));
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248
      } break;
    }
  }

  return exports;
}

///////////////////////////////////////////////////////////////////////////////

}  // namespace wasm

// BEGIN FILE wasm-c.cc

extern "C" {

///////////////////////////////////////////////////////////////////////////////
// Auxiliaries

// Backing implementation

extern "C++" {

template <class T>
struct borrowed_vec {
  wasm::vec<T> it;
  explicit borrowed_vec(wasm::vec<T>&& v) : it(std::move(v)) {}
  borrowed_vec(borrowed_vec<T>&& that) : it(std::move(that.it)) {}
  ~borrowed_vec() { it.release(); }
};

}  // extern "C++"

#define WASM_DEFINE_OWN(name, Name)                                          \
  struct wasm_##name##_t : Name {};                                          \
                                                                             \
  void wasm_##name##_delete(wasm_##name##_t* x) { delete x; }                \
                                                                             \
  extern "C++" inline auto hide(Name* x)->wasm_##name##_t* {                 \
    return static_cast<wasm_##name##_t*>(x);                                 \
  }                                                                          \
  extern "C++" inline auto hide(const Name* x)->const wasm_##name##_t* {     \
    return static_cast<const wasm_##name##_t*>(x);                           \
  }                                                                          \
  extern "C++" inline auto reveal(wasm_##name##_t* x)->Name* { return x; }   \
  extern "C++" inline auto reveal(const wasm_##name##_t* x)->const Name* {   \
    return x;                                                                \
  }                                                                          \
  extern "C++" inline auto get(wasm::own<Name*>& x)->wasm_##name##_t* {      \
    return hide(x.get());                                                    \
  }                                                                          \
  extern "C++" inline auto get(const wasm::own<Name*>& x)                    \
      ->const wasm_##name##_t* {                                             \
    return hide(x.get());                                                    \
  }                                                                          \
  extern "C++" inline auto release(wasm::own<Name*>&& x)->wasm_##name##_t* { \
    return hide(x.release());                                                \
  }                                                                          \
  extern "C++" inline auto adopt(wasm_##name##_t* x)->wasm::own<Name*> {     \
    return make_own(x);                                                      \
  }

// Vectors

#define WASM_DEFINE_VEC_BASE(name, Name, ptr_or_none)                       \
  extern "C++" inline auto hide(wasm::vec<Name ptr_or_none>& v)             \
      ->wasm_##name##_vec_t* {                                              \
    static_assert(sizeof(wasm_##name##_vec_t) == sizeof(wasm::vec<Name>),   \
                  "C/C++ incompatibility");                                 \
    return reinterpret_cast<wasm_##name##_vec_t*>(&v);                      \
  }                                                                         \
  extern "C++" inline auto hide(const wasm::vec<Name ptr_or_none>& v)       \
      ->const wasm_##name##_vec_t* {                                        \
    static_assert(sizeof(wasm_##name##_vec_t) == sizeof(wasm::vec<Name>),   \
                  "C/C++ incompatibility");                                 \
    return reinterpret_cast<const wasm_##name##_vec_t*>(&v);                \
  }                                                                         \
  extern "C++" inline auto hide(Name ptr_or_none* v)                        \
      ->wasm_##name##_t ptr_or_none* {                                      \
    static_assert(                                                          \
        sizeof(wasm_##name##_t ptr_or_none) == sizeof(Name ptr_or_none),    \
        "C/C++ incompatibility");                                           \
    return reinterpret_cast<wasm_##name##_t ptr_or_none*>(v);               \
  }                                                                         \
  extern "C++" inline auto hide(Name ptr_or_none const* v)                  \
      ->wasm_##name##_t ptr_or_none const* {                                \
    static_assert(                                                          \
        sizeof(wasm_##name##_t ptr_or_none) == sizeof(Name ptr_or_none),    \
        "C/C++ incompatibility");                                           \
    return reinterpret_cast<wasm_##name##_t ptr_or_none const*>(v);         \
  }                                                                         \
  extern "C++" inline auto reveal(wasm_##name##_t ptr_or_none* v)           \
      ->Name ptr_or_none* {                                                 \
    static_assert(                                                          \
        sizeof(wasm_##name##_t ptr_or_none) == sizeof(Name ptr_or_none),    \
        "C/C++ incompatibility");                                           \
    return reinterpret_cast<Name ptr_or_none*>(v);                          \
  }                                                                         \
  extern "C++" inline auto reveal(wasm_##name##_t ptr_or_none const* v)     \
      ->Name ptr_or_none const* {                                           \
    static_assert(                                                          \
        sizeof(wasm_##name##_t ptr_or_none) == sizeof(Name ptr_or_none),    \
        "C/C++ incompatibility");                                           \
    return reinterpret_cast<Name ptr_or_none const*>(v);                    \
  }                                                                         \
  extern "C++" inline auto get(wasm::vec<Name ptr_or_none>& v)              \
      ->wasm_##name##_vec_t {                                               \
    wasm_##name##_vec_t v2 = {v.size(), hide(v.get())};                     \
    return v2;                                                              \
  }                                                                         \
  extern "C++" inline auto get(const wasm::vec<Name ptr_or_none>& v)        \
      ->const wasm_##name##_vec_t {                                         \
    wasm_##name##_vec_t v2 = {                                              \
        v.size(), const_cast<wasm_##name##_t ptr_or_none*>(hide(v.get()))}; \
    return v2;                                                              \
  }                                                                         \
  extern "C++" inline auto release(wasm::vec<Name ptr_or_none>&& v)         \
      ->wasm_##name##_vec_t {                                               \
    wasm_##name##_vec_t v2 = {v.size(), hide(v.release())};                 \
    return v2;                                                              \
  }                                                                         \
  extern "C++" inline auto adopt(wasm_##name##_vec_t* v)                    \
      ->wasm::vec<Name ptr_or_none> {                                       \
    return wasm::vec<Name ptr_or_none>::adopt(v->size, reveal(v->data));    \
  }                                                                         \
  extern "C++" inline auto borrow(const wasm_##name##_vec_t* v)             \
      ->borrowed_vec<Name ptr_or_none> {                                    \
    return borrowed_vec<Name ptr_or_none>(                                  \
        wasm::vec<Name ptr_or_none>::adopt(v->size, reveal(v->data)));      \
  }                                                                         \
                                                                            \
  void wasm_##name##_vec_new_uninitialized(wasm_##name##_vec_t* out,        \
                                           size_t size) {                   \
    *out = release(wasm::vec<Name ptr_or_none>::make_uninitialized(size));  \
  }                                                                         \
  void wasm_##name##_vec_new_empty(wasm_##name##_vec_t* out) {              \
    wasm_##name##_vec_new_uninitialized(out, 0);                            \
  }                                                                         \
                                                                            \
  void wasm_##name##_vec_delete(wasm_##name##_vec_t* v) { adopt(v); }

// Vectors with no ownership management of elements
#define WASM_DEFINE_VEC_PLAIN(name, Name, ptr_or_none)                    \
  WASM_DEFINE_VEC_BASE(name, Name, ptr_or_none)                           \
                                                                          \
  void wasm_##name##_vec_new(wasm_##name##_vec_t* out, size_t size,       \
                             wasm_##name##_t ptr_or_none const data[]) {  \
    auto v2 = wasm::vec<Name ptr_or_none>::make_uninitialized(size);      \
    if (v2.size() != 0) {                                                 \
      memcpy(v2.get(), data, size * sizeof(wasm_##name##_t ptr_or_none)); \
    }                                                                     \
    *out = release(std::move(v2));                                        \
  }                                                                       \
                                                                          \
  void wasm_##name##_vec_copy(wasm_##name##_vec_t* out,                   \
                              wasm_##name##_vec_t* v) {                   \
    wasm_##name##_vec_new(out, v->size, v->data);                         \
  }

// Vectors who own their elements
#define WASM_DEFINE_VEC(name, Name, ptr_or_none)                         \
  WASM_DEFINE_VEC_BASE(name, Name, ptr_or_none)                          \
                                                                         \
  void wasm_##name##_vec_new(wasm_##name##_vec_t* out, size_t size,      \
                             wasm_##name##_t ptr_or_none const data[]) { \
    auto v2 = wasm::vec<Name ptr_or_none>::make_uninitialized(size);     \
    for (size_t i = 0; i < v2.size(); ++i) {                             \
      v2[i] = adopt(data[i]);                                            \
    }                                                                    \
    *out = release(std::move(v2));                                       \
  }                                                                      \
                                                                         \
  void wasm_##name##_vec_copy(wasm_##name##_vec_t* out,                  \
                              wasm_##name##_vec_t* v) {                  \
    auto v2 = wasm::vec<Name ptr_or_none>::make_uninitialized(v->size);  \
    for (size_t i = 0; i < v2.size(); ++i) {                             \
      v2[i] = adopt(wasm_##name##_copy(v->data[i]));                     \
    }                                                                    \
    *out = release(std::move(v2));                                       \
  }

extern "C++" {
template <class T>
inline auto is_empty(T* p) -> bool {
  return !p;
}
}

// Byte vectors

using byte = byte_t;
WASM_DEFINE_VEC_PLAIN(byte, byte, )

///////////////////////////////////////////////////////////////////////////////
// Runtime Environment

// Configuration

WASM_DEFINE_OWN(config, wasm::Config)

wasm_config_t* wasm_config_new() { return release(wasm::Config::make()); }

// Engine

WASM_DEFINE_OWN(engine, wasm::Engine)

wasm_engine_t* wasm_engine_new() { return release(wasm::Engine::make()); }

wasm_engine_t* wasm_engine_new_with_config(wasm_config_t* config) {
  return release(wasm::Engine::make(adopt(config)));
}

// Stores

WASM_DEFINE_OWN(store, wasm::Store)

wasm_store_t* wasm_store_new(wasm_engine_t* engine) {
  return release(wasm::Store::make(engine));
}

///////////////////////////////////////////////////////////////////////////////
// Type Representations

// Type attributes

extern "C++" inline auto hide(wasm::Mutability mutability)
    -> wasm_mutability_t {
  return static_cast<wasm_mutability_t>(mutability);
}

extern "C++" inline auto reveal(wasm_mutability_t mutability)
    -> wasm::Mutability {
  return static_cast<wasm::Mutability>(mutability);
}

extern "C++" inline auto hide(const wasm::Limits& limits)
    -> const wasm_limits_t* {
  return reinterpret_cast<const wasm_limits_t*>(&limits);
}

extern "C++" inline auto reveal(wasm_limits_t limits) -> wasm::Limits {
  return wasm::Limits(limits.min, limits.max);
}

extern "C++" inline auto hide(wasm::ValKind kind) -> wasm_valkind_t {
  return static_cast<wasm_valkind_t>(kind);
}

extern "C++" inline auto reveal(wasm_valkind_t kind) -> wasm::ValKind {
  return static_cast<wasm::ValKind>(kind);
}

extern "C++" inline auto hide(wasm::ExternKind kind) -> wasm_externkind_t {
  return static_cast<wasm_externkind_t>(kind);
}

extern "C++" inline auto reveal(wasm_externkind_t kind) -> wasm::ExternKind {
  return static_cast<wasm::ExternKind>(kind);
}

// Generic

#define WASM_DEFINE_TYPE(name, Name)                        \
  WASM_DEFINE_OWN(name, Name)                               \
  WASM_DEFINE_VEC(name, Name, *)                            \
                                                            \
  wasm_##name##_t* wasm_##name##_copy(wasm_##name##_t* t) { \
    return release(t->copy());                              \
  }

// Value Types

WASM_DEFINE_TYPE(valtype, wasm::ValType)

wasm_valtype_t* wasm_valtype_new(wasm_valkind_t k) {
  return release(wasm::ValType::make(reveal(k)));
}

wasm_valkind_t wasm_valtype_kind(const wasm_valtype_t* t) {
  return hide(t->kind());
}

// Function Types

WASM_DEFINE_TYPE(functype, wasm::FuncType)

wasm_functype_t* wasm_functype_new(wasm_valtype_vec_t* params,
                                   wasm_valtype_vec_t* results) {
  return release(wasm::FuncType::make(adopt(params), adopt(results)));
}

const wasm_valtype_vec_t* wasm_functype_params(const wasm_functype_t* ft) {
  return hide(ft->params());
}

const wasm_valtype_vec_t* wasm_functype_results(const wasm_functype_t* ft) {
  return hide(ft->results());
}

// Global Types

WASM_DEFINE_TYPE(globaltype, wasm::GlobalType)

wasm_globaltype_t* wasm_globaltype_new(wasm_valtype_t* content,
                                       wasm_mutability_t mutability) {
  return release(wasm::GlobalType::make(adopt(content), reveal(mutability)));
}

const wasm_valtype_t* wasm_globaltype_content(const wasm_globaltype_t* gt) {
  return hide(gt->content());
}

wasm_mutability_t wasm_globaltype_mutability(const wasm_globaltype_t* gt) {
  return hide(gt->mutability());
}

// Table Types

WASM_DEFINE_TYPE(tabletype, wasm::TableType)

wasm_tabletype_t* wasm_tabletype_new(wasm_valtype_t* element,
                                     const wasm_limits_t* limits) {
  return release(wasm::TableType::make(adopt(element), reveal(*limits)));
}

const wasm_valtype_t* wasm_tabletype_element(const wasm_tabletype_t* tt) {
  return hide(tt->element());
}

const wasm_limits_t* wasm_tabletype_limits(const wasm_tabletype_t* tt) {
  return hide(tt->limits());
}

// Memory Types

WASM_DEFINE_TYPE(memorytype, wasm::MemoryType)

wasm_memorytype_t* wasm_memorytype_new(const wasm_limits_t* limits) {
  return release(wasm::MemoryType::make(reveal(*limits)));
}

const wasm_limits_t* wasm_memorytype_limits(const wasm_memorytype_t* mt) {
  return hide(mt->limits());
}

// Extern Types

WASM_DEFINE_TYPE(externtype, wasm::ExternType)

wasm_externkind_t wasm_externtype_kind(const wasm_externtype_t* et) {
  return hide(et->kind());
}

wasm_externtype_t* wasm_functype_as_externtype(wasm_functype_t* ft) {
  return hide(static_cast<wasm::ExternType*>(ft));
}
wasm_externtype_t* wasm_globaltype_as_externtype(wasm_globaltype_t* gt) {
  return hide(static_cast<wasm::ExternType*>(gt));
}
wasm_externtype_t* wasm_tabletype_as_externtype(wasm_tabletype_t* tt) {
  return hide(static_cast<wasm::ExternType*>(tt));
}
wasm_externtype_t* wasm_memorytype_as_externtype(wasm_memorytype_t* mt) {
  return hide(static_cast<wasm::ExternType*>(mt));
}

const wasm_externtype_t* wasm_functype_as_externtype_const(
    const wasm_functype_t* ft) {
  return hide(static_cast<const wasm::ExternType*>(ft));
}
const wasm_externtype_t* wasm_globaltype_as_externtype_const(
    const wasm_globaltype_t* gt) {
  return hide(static_cast<const wasm::ExternType*>(gt));
}
const wasm_externtype_t* wasm_tabletype_as_externtype_const(
    const wasm_tabletype_t* tt) {
  return hide(static_cast<const wasm::ExternType*>(tt));
}
const wasm_externtype_t* wasm_memorytype_as_externtype_const(
    const wasm_memorytype_t* mt) {
  return hide(static_cast<const wasm::ExternType*>(mt));
}

wasm_functype_t* wasm_externtype_as_functype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_FUNC
             ? hide(static_cast<wasm::FuncType*>(reveal(et)))
             : nullptr;
}
wasm_globaltype_t* wasm_externtype_as_globaltype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_GLOBAL
             ? hide(static_cast<wasm::GlobalType*>(reveal(et)))
             : nullptr;
}
wasm_tabletype_t* wasm_externtype_as_tabletype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_TABLE
             ? hide(static_cast<wasm::TableType*>(reveal(et)))
             : nullptr;
}
wasm_memorytype_t* wasm_externtype_as_memorytype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_MEMORY
             ? hide(static_cast<wasm::MemoryType*>(reveal(et)))
             : nullptr;
}

const wasm_functype_t* wasm_externtype_as_functype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_FUNC
             ? hide(static_cast<const wasm::FuncType*>(reveal(et)))
             : nullptr;
}
const wasm_globaltype_t* wasm_externtype_as_globaltype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_GLOBAL
             ? hide(static_cast<const wasm::GlobalType*>(reveal(et)))
             : nullptr;
}
const wasm_tabletype_t* wasm_externtype_as_tabletype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_TABLE
             ? hide(static_cast<const wasm::TableType*>(reveal(et)))
             : nullptr;
}
const wasm_memorytype_t* wasm_externtype_as_memorytype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_MEMORY
             ? hide(static_cast<const wasm::MemoryType*>(reveal(et)))
             : nullptr;
}

// Import Types

WASM_DEFINE_TYPE(importtype, wasm::ImportType)

wasm_importtype_t* wasm_importtype_new(wasm_name_t* module, wasm_name_t* name,
                                       wasm_externtype_t* type) {
  return release(
      wasm::ImportType::make(adopt(module), adopt(name), adopt(type)));
}

const wasm_name_t* wasm_importtype_module(const wasm_importtype_t* it) {
  return hide(it->module());
}

const wasm_name_t* wasm_importtype_name(const wasm_importtype_t* it) {
  return hide(it->name());
}

const wasm_externtype_t* wasm_importtype_type(const wasm_importtype_t* it) {
  return hide(it->type());
}

// Export Types

WASM_DEFINE_TYPE(exporttype, wasm::ExportType)

wasm_exporttype_t* wasm_exporttype_new(wasm_name_t* name,
                                       wasm_externtype_t* type) {
  return release(wasm::ExportType::make(adopt(name), adopt(type)));
}

const wasm_name_t* wasm_exporttype_name(const wasm_exporttype_t* et) {
  return hide(et->name());
}

const wasm_externtype_t* wasm_exporttype_type(const wasm_exporttype_t* et) {
  return hide(et->type());
}

///////////////////////////////////////////////////////////////////////////////
// Runtime Values

// References

#define WASM_DEFINE_REF_BASE(name, Name)                             \
  WASM_DEFINE_OWN(name, Name)                                        \
                                                                     \
  wasm_##name##_t* wasm_##name##_copy(const wasm_##name##_t* t) {    \
    return release(t->copy());                                       \
  }                                                                  \
                                                                     \
  void* wasm_##name##_get_host_info(const wasm_##name##_t* r) {      \
    return r->get_host_info();                                       \
  }                                                                  \
  void wasm_##name##_set_host_info(wasm_##name##_t* r, void* info) { \
    r->set_host_info(info);                                          \
  }                                                                  \
  void wasm_##name##_set_host_info_with_finalizer(                   \
      wasm_##name##_t* r, void* info, void (*finalizer)(void*)) {    \
    r->set_host_info(info, finalizer);                               \
  }

#define WASM_DEFINE_REF(name, Name)                                        \
  WASM_DEFINE_REF_BASE(name, Name)                                         \
                                                                           \
  wasm_ref_t* wasm_##name##_as_ref(wasm_##name##_t* r) {                   \
    return hide(static_cast<wasm::Ref*>(reveal(r)));                       \
  }                                                                        \
  wasm_##name##_t* wasm_ref_as_##name(wasm_ref_t* r) {                     \
    return hide(static_cast<Name*>(reveal(r)));                            \
  }                                                                        \
                                                                           \
  const wasm_ref_t* wasm_##name##_as_ref_const(const wasm_##name##_t* r) { \
    return hide(static_cast<const wasm::Ref*>(reveal(r)));                 \
  }                                                                        \
  const wasm_##name##_t* wasm_ref_as_##name##_const(const wasm_ref_t* r) { \
    return hide(static_cast<const Name*>(reveal(r)));                      \
  }

#define WASM_DEFINE_SHARABLE_REF(name, Name) \
  WASM_DEFINE_REF(name, Name)                \
  WASM_DEFINE_OWN(shared_##name, wasm::Shared<Name>)

WASM_DEFINE_REF_BASE(ref, wasm::Ref)

// Values

extern "C++" {

inline auto is_empty(wasm_val_t v) -> bool {
  return !is_ref(reveal(v.kind)) || !v.of.ref;
}

inline auto hide(wasm::Val v) -> wasm_val_t {
  wasm_val_t v2 = {hide(v.kind()), {}};
  switch (v.kind()) {
    case wasm::I32:
      v2.of.i32 = v.i32();
      break;
    case wasm::I64:
      v2.of.i64 = v.i64();
      break;
    case wasm::F32:
      v2.of.f32 = v.f32();
      break;
    case wasm::F64:
      v2.of.f64 = v.f64();
      break;
    case wasm::ANYREF:
    case wasm::FUNCREF:
      v2.of.ref = hide(v.ref());
      break;
    default:
      UNREACHABLE();
  }
  return v2;
}

inline auto release(wasm::Val v) -> wasm_val_t {
  wasm_val_t v2 = {hide(v.kind()), {}};
  switch (v.kind()) {
    case wasm::I32:
      v2.of.i32 = v.i32();
      break;
    case wasm::I64:
      v2.of.i64 = v.i64();
      break;
    case wasm::F32:
      v2.of.f32 = v.f32();
      break;
    case wasm::F64:
      v2.of.f64 = v.f64();
      break;
    case wasm::ANYREF:
    case wasm::FUNCREF:
      v2.of.ref = release(v.release_ref());
      break;
    default:
      UNREACHABLE();
  }
  return v2;
}

inline auto adopt(wasm_val_t v) -> wasm::Val {
  switch (reveal(v.kind)) {
    case wasm::I32:
      return wasm::Val(v.of.i32);
    case wasm::I64:
      return wasm::Val(v.of.i64);
    case wasm::F32:
      return wasm::Val(v.of.f32);
    case wasm::F64:
      return wasm::Val(v.of.f64);
    case wasm::ANYREF:
    case wasm::FUNCREF:
      return wasm::Val(adopt(v.of.ref));
    default:
      UNREACHABLE();
  }
}

struct borrowed_val {
  wasm::Val it;
  explicit borrowed_val(wasm::Val&& v) : it(std::move(v)) {}
  borrowed_val(borrowed_val&& that) : it(std::move(that.it)) {}
  ~borrowed_val() {
    if (it.is_ref()) it.release_ref();
  }
};

inline auto borrow(const wasm_val_t* v) -> borrowed_val {
  wasm::Val v2;
  switch (reveal(v->kind)) {
    case wasm::I32:
      v2 = wasm::Val(v->of.i32);
      break;
    case wasm::I64:
      v2 = wasm::Val(v->of.i64);
      break;
    case wasm::F32:
      v2 = wasm::Val(v->of.f32);
      break;
    case wasm::F64:
      v2 = wasm::Val(v->of.f64);
      break;
    case wasm::ANYREF:
    case wasm::FUNCREF:
      v2 = wasm::Val(adopt(v->of.ref));
      break;
    default:
      UNREACHABLE();
  }
  return borrowed_val(std::move(v2));
}

}  // extern "C++"

WASM_DEFINE_VEC_BASE(val, wasm::Val, )

void wasm_val_vec_new(wasm_val_vec_t* out, size_t size,
                      wasm_val_t const data[]) {
  auto v2 = wasm::vec<wasm::Val>::make_uninitialized(size);
  for (size_t i = 0; i < v2.size(); ++i) {
    v2[i] = adopt(data[i]);
  }
  *out = release(std::move(v2));
}

void wasm_val_vec_copy(wasm_val_vec_t* out, wasm_val_vec_t* v) {
  auto v2 = wasm::vec<wasm::Val>::make_uninitialized(v->size);
  for (size_t i = 0; i < v2.size(); ++i) {
    wasm_val_t val;
    wasm_val_copy(&v->data[i], &val);
    v2[i] = adopt(val);
  }
  *out = release(std::move(v2));
}

void wasm_val_delete(wasm_val_t* v) {
  if (is_ref(reveal(v->kind))) adopt(v->of.ref);
}

void wasm_val_copy(wasm_val_t* out, const wasm_val_t* v) {
  *out = *v;
  if (is_ref(reveal(v->kind))) {
    out->of.ref = release(v->of.ref->copy());
  }
}

///////////////////////////////////////////////////////////////////////////////
// Runtime Objects

// Traps

WASM_DEFINE_REF(trap, wasm::Trap)

wasm_trap_t* wasm_trap_new(wasm_store_t* store, const wasm_message_t* message) {
  auto message_ = borrow(message);
  return release(wasm::Trap::make(store, message_.it));
}

void wasm_trap_message(const wasm_trap_t* trap, wasm_message_t* out) {
  *out = release(reveal(trap)->message());
}

// Foreign Objects

WASM_DEFINE_REF(foreign, wasm::Foreign)

wasm_foreign_t* wasm_foreign_new(wasm_store_t* store) {
  return release(wasm::Foreign::make(store));
}

// Modules

WASM_DEFINE_SHARABLE_REF(module, wasm::Module)

bool wasm_module_validate(wasm_store_t* store, const wasm_byte_vec_t* binary) {
  auto binary_ = borrow(binary);
  return wasm::Module::validate(store, binary_.it);
}

wasm_module_t* wasm_module_new(wasm_store_t* store,
                               const wasm_byte_vec_t* binary) {
  auto binary_ = borrow(binary);
  return release(wasm::Module::make(store, binary_.it));
}

void wasm_module_imports(const wasm_module_t* module,
                         wasm_importtype_vec_t* out) {
  *out = release(reveal(module)->imports());
}

void wasm_module_exports(const wasm_module_t* module,
                         wasm_exporttype_vec_t* out) {
  *out = release(reveal(module)->exports());
}

void wasm_module_serialize(const wasm_module_t* module, wasm_byte_vec_t* out) {
  *out = release(reveal(module)->serialize());
}

wasm_module_t* wasm_module_deserialize(wasm_store_t* store,
                                       const wasm_byte_vec_t* binary) {
  auto binary_ = borrow(binary);
  return release(wasm::Module::deserialize(store, binary_.it));
}

wasm_shared_module_t* wasm_module_share(const wasm_module_t* module) {
  return release(reveal(module)->share());
}

wasm_module_t* wasm_module_obtain(wasm_store_t* store,
                                  const wasm_shared_module_t* shared) {
  return release(wasm::Module::obtain(store, shared));
}

// Function Instances

WASM_DEFINE_REF(func, wasm::Func)

extern "C++" {

auto wasm_callback(void* env, const wasm::Val args[], wasm::Val results[])
    -> wasm::own<wasm::Trap*> {
  auto f = reinterpret_cast<wasm_func_callback_t>(env);
  return adopt(f(hide(args), hide(results)));
}

struct wasm_callback_env_t {
  wasm_func_callback_with_env_t callback;
  void* env;
  void (*finalizer)(void*);
};

auto wasm_callback_with_env(void* env, const wasm::Val args[],
                            wasm::Val results[]) -> wasm::own<wasm::Trap*> {
  auto t = static_cast<wasm_callback_env_t*>(env);
  return adopt(t->callback(t->env, hide(args), hide(results)));
}

void wasm_callback_env_finalizer(void* env) {
  auto t = static_cast<wasm_callback_env_t*>(env);
  if (t->finalizer) t->finalizer(t->env);
  delete t;
}

}  // extern "C++"

wasm_func_t* wasm_func_new(wasm_store_t* store, const wasm_functype_t* type,
                           wasm_func_callback_t callback) {
  return release(wasm::Func::make(store, type, wasm_callback,
                                  reinterpret_cast<void*>(callback)));
}

wasm_func_t* wasm_func_new_with_env(wasm_store_t* store,
                                    const wasm_functype_t* type,
                                    wasm_func_callback_with_env_t callback,
                                    void* env, void (*finalizer)(void*)) {
  auto env2 = new wasm_callback_env_t{callback, env, finalizer};
  return release(wasm::Func::make(store, type, wasm_callback_with_env, env2,
                                  wasm_callback_env_finalizer));
}

wasm_functype_t* wasm_func_type(const wasm_func_t* func) {
  return release(func->type());
}

size_t wasm_func_param_arity(const wasm_func_t* func) {
  return func->param_arity();
}

size_t wasm_func_result_arity(const wasm_func_t* func) {
  return func->result_arity();
}

wasm_trap_t* wasm_func_call(const wasm_func_t* func, const wasm_val_t args[],
                            wasm_val_t results[]) {
  return release(func->call(reveal(args), reveal(results)));
}

// Global Instances

WASM_DEFINE_REF(global, wasm::Global)

wasm_global_t* wasm_global_new(wasm_store_t* store,
                               const wasm_globaltype_t* type,
                               const wasm_val_t* val) {
  auto val_ = borrow(val);
  return release(wasm::Global::make(store, type, val_.it));
}

wasm_globaltype_t* wasm_global_type(const wasm_global_t* global) {
  return release(global->type());
}

void wasm_global_get(const wasm_global_t* global, wasm_val_t* out) {
  *out = release(global->get());
}

void wasm_global_set(wasm_global_t* global, const wasm_val_t* val) {
  auto val_ = borrow(val);
  global->set(val_.it);
}

// Table Instances

WASM_DEFINE_REF(table, wasm::Table)

wasm_table_t* wasm_table_new(wasm_store_t* store, const wasm_tabletype_t* type,
                             wasm_ref_t* ref) {
  return release(wasm::Table::make(store, type, ref));
}

wasm_tabletype_t* wasm_table_type(const wasm_table_t* table) {
  return release(table->type());
}

wasm_ref_t* wasm_table_get(const wasm_table_t* table, wasm_table_size_t index) {
  return release(table->get(index));
}

bool wasm_table_set(wasm_table_t* table, wasm_table_size_t index,
                    wasm_ref_t* ref) {
  return table->set(index, ref);
}

wasm_table_size_t wasm_table_size(const wasm_table_t* table) {
  return table->size();
}

bool wasm_table_grow(wasm_table_t* table, wasm_table_size_t delta,
                     wasm_ref_t* ref) {
  return table->grow(delta, ref);
}

// Memory Instances

WASM_DEFINE_REF(memory, wasm::Memory)

wasm_memory_t* wasm_memory_new(wasm_store_t* store,
                               const wasm_memorytype_t* type) {
  return release(wasm::Memory::make(store, type));
}

wasm_memorytype_t* wasm_memory_type(const wasm_memory_t* memory) {
  return release(memory->type());
}

wasm_byte_t* wasm_memory_data(wasm_memory_t* memory) { return memory->data(); }

size_t wasm_memory_data_size(const wasm_memory_t* memory) {
  return memory->data_size();
}

wasm_memory_pages_t wasm_memory_size(const wasm_memory_t* memory) {
  return memory->size();
}

bool wasm_memory_grow(wasm_memory_t* memory, wasm_memory_pages_t delta) {
  return memory->grow(delta);
}

// Externals

WASM_DEFINE_REF(extern, wasm::Extern)
WASM_DEFINE_VEC(extern, wasm::Extern, *)

wasm_externkind_t wasm_extern_kind(const wasm_extern_t* external) {
  return hide(external->kind());
}
wasm_externtype_t* wasm_extern_type(const wasm_extern_t* external) {
  return release(external->type());
}

wasm_extern_t* wasm_func_as_extern(wasm_func_t* func) {
  return hide(static_cast<wasm::Extern*>(reveal(func)));
}
wasm_extern_t* wasm_global_as_extern(wasm_global_t* global) {
  return hide(static_cast<wasm::Extern*>(reveal(global)));
}
wasm_extern_t* wasm_table_as_extern(wasm_table_t* table) {
  return hide(static_cast<wasm::Extern*>(reveal(table)));
}
wasm_extern_t* wasm_memory_as_extern(wasm_memory_t* memory) {
  return hide(static_cast<wasm::Extern*>(reveal(memory)));
}

const wasm_extern_t* wasm_func_as_extern_const(const wasm_func_t* func) {
  return hide(static_cast<const wasm::Extern*>(reveal(func)));
}
const wasm_extern_t* wasm_global_as_extern_const(const wasm_global_t* global) {
  return hide(static_cast<const wasm::Extern*>(reveal(global)));
}
const wasm_extern_t* wasm_table_as_extern_const(const wasm_table_t* table) {
  return hide(static_cast<const wasm::Extern*>(reveal(table)));
}
const wasm_extern_t* wasm_memory_as_extern_const(const wasm_memory_t* memory) {
  return hide(static_cast<const wasm::Extern*>(reveal(memory)));
}

wasm_func_t* wasm_extern_as_func(wasm_extern_t* external) {
  return hide(external->func());
}
wasm_global_t* wasm_extern_as_global(wasm_extern_t* external) {
  return hide(external->global());
}
wasm_table_t* wasm_extern_as_table(wasm_extern_t* external) {
  return hide(external->table());
}
wasm_memory_t* wasm_extern_as_memory(wasm_extern_t* external) {
  return hide(external->memory());
}

const wasm_func_t* wasm_extern_as_func_const(const wasm_extern_t* external) {
  return hide(external->func());
}
const wasm_global_t* wasm_extern_as_global_const(
    const wasm_extern_t* external) {
  return hide(external->global());
}
const wasm_table_t* wasm_extern_as_table_const(const wasm_extern_t* external) {
  return hide(external->table());
}
const wasm_memory_t* wasm_extern_as_memory_const(
    const wasm_extern_t* external) {
  return hide(external->memory());
}

// Module Instances

WASM_DEFINE_REF(instance, wasm::Instance)

wasm_instance_t* wasm_instance_new(wasm_store_t* store,
                                   const wasm_module_t* module,
                                   const wasm_extern_t* const imports[]) {
  return release(wasm::Instance::make(
      store, module, reinterpret_cast<const wasm::Extern* const*>(imports)));
}

void wasm_instance_exports(const wasm_instance_t* instance,
                           wasm_extern_vec_t* out) {
  *out = release(instance->exports());
}

#undef WASM_DEFINE_OWN
#undef WASM_DEFINE_VEC_BASE
#undef WASM_DEFINE_VEC_PLAIN
#undef WASM_DEFINE_VEC
#undef WASM_DEFINE_TYPE
#undef WASM_DEFINE_REF_BASE
#undef WASM_DEFINE_REF
#undef WASM_DEFINE_SHARABLE_REF

}  // extern "C"