c-api.cc 103 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
// 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>

25 26
#include "src/wasm/c-api.h"

27 28 29
#include "third_party/wasm-api/wasm.h"

#include "include/libplatform/libplatform.h"
30
#include "src/api/api-inl.h"
31
#include "src/compiler/wasm-compiler.h"
32 33
#include "src/objects/js-collection-inl.h"
#include "src/objects/managed.h"
34
#include "src/objects/stack-frame-info-inl.h"
35
#include "src/wasm/leb-helper.h"
36
#include "src/wasm/module-instantiate.h"
37
#include "src/wasm/wasm-arguments.h"
38 39
#include "src/wasm/wasm-constants.h"
#include "src/wasm/wasm-objects.h"
40
#include "src/wasm/wasm-result.h"
41 42
#include "src/wasm/wasm-serialization.h"

43 44 45 46
#ifdef WASM_API_DEBUG
#error "WASM_API_DEBUG is unsupported"
#endif

47 48
namespace wasm {

49
namespace {
50

51
auto ReadLebU64(const byte_t** pos) -> uint64_t {
52 53 54 55
  uint64_t n = 0;
  uint64_t shift = 0;
  byte_t b;
  do {
56 57
    b = **pos;
    (*pos)++;
58 59 60 61 62 63
    n += (b & 0x7f) << shift;
    shift += 7;
  } while ((b & 0x80) != 0);
  return n;
}

64
ValKind V8ValueTypeToWasm(i::wasm::ValueType v8_valtype) {
65 66
  switch (v8_valtype.kind()) {
    case i::wasm::ValueType::kI32:
67
      return I32;
68
    case i::wasm::ValueType::kI64:
69
      return I64;
70
    case i::wasm::ValueType::kF32:
71
      return F32;
72
    case i::wasm::ValueType::kF64:
73
      return F64;
74 75
    case i::wasm::ValueType::kRef:
    case i::wasm::ValueType::kOptRef:
76
      switch (v8_valtype.heap_representation()) {
77
        case i::wasm::HeapType::kFunc:
78
          return FUNCREF;
79
        case i::wasm::HeapType::kExtern:
80 81 82 83 84 85 86
          // TODO(7748): Rename this to EXTERNREF if/when third-party API
          // changes.
          return ANYREF;
        default:
          // TODO(wasm+): support new value types
          UNREACHABLE();
      }
87 88 89 90 91 92
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
  }
}

93 94 95
i::wasm::ValueType WasmValKindToV8(ValKind kind) {
  switch (kind) {
    case I32:
96
      return i::wasm::kWasmI32;
97
    case I64:
98
      return i::wasm::kWasmI64;
99
    case F32:
100
      return i::wasm::kWasmF32;
101
    case F64:
102
      return i::wasm::kWasmF64;
103
    case FUNCREF:
104
      return i::wasm::kWasmFuncRef;
105
    case ANYREF:
106
      return i::wasm::kWasmExternRef;
107 108 109
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
110 111 112
  }
}

113 114 115 116
Name GetNameFromWireBytes(const i::wasm::WireBytesRef& ref,
                          const i::Vector<const uint8_t>& wire_bytes) {
  DCHECK_LE(ref.offset(), wire_bytes.length());
  DCHECK_LE(ref.end_offset(), wire_bytes.length());
117
  if (ref.length() == 0) return Name::make();
118 119 120 121
  Name name = Name::make_uninitialized(ref.length());
  std::memcpy(name.get(), wire_bytes.begin() + ref.offset(), ref.length());
  return name;
}
122

123
own<FuncType> FunctionSigToFuncType(const i::wasm::FunctionSig* sig) {
124
  size_t param_count = sig->parameter_count();
125
  ownvec<ValType> params = ownvec<ValType>::make_uninitialized(param_count);
126 127 128 129
  for (size_t i = 0; i < param_count; i++) {
    params[i] = ValType::make(V8ValueTypeToWasm(sig->GetParam(i)));
  }
  size_t return_count = sig->return_count();
130
  ownvec<ValType> results = ownvec<ValType>::make_uninitialized(return_count);
131 132 133 134 135
  for (size_t i = 0; i < return_count; i++) {
    results[i] = ValType::make(V8ValueTypeToWasm(sig->GetReturn(i)));
  }
  return FuncType::make(std::move(params), std::move(results));
}
136

137 138 139
own<ExternType> GetImportExportType(const i::wasm::WasmModule* module,
                                    const i::wasm::ImportExportKindCode kind,
                                    const uint32_t index) {
140 141 142 143 144 145
  switch (kind) {
    case i::wasm::kExternalFunction: {
      return FunctionSigToFuncType(module->functions[index].sig);
    }
    case i::wasm::kExternalTable: {
      const i::wasm::WasmTable& table = module->tables[index];
146
      own<ValType> elem = ValType::make(V8ValueTypeToWasm(table.type));
147 148 149 150 151 152 153 154 155 156 157 158
      Limits limits(table.initial_size,
                    table.has_maximum_size ? table.maximum_size : -1);
      return TableType::make(std::move(elem), limits);
    }
    case i::wasm::kExternalMemory: {
      DCHECK(module->has_memory);
      Limits limits(module->initial_pages,
                    module->has_maximum_pages ? module->maximum_pages : -1);
      return MemoryType::make(limits);
    }
    case i::wasm::kExternalGlobal: {
      const i::wasm::WasmGlobal& global = module->globals[index];
159
      own<ValType> content = ValType::make(V8ValueTypeToWasm(global.type));
160 161 162 163 164 165 166 167 168 169 170 171
      Mutability mutability = global.mutability ? VAR : CONST;
      return GlobalType::make(std::move(content), mutability);
    }
    case i::wasm::kExternalException:
      UNREACHABLE();
      return {};
  }
}

}  // namespace

/// BEGIN FILE wasm-v8.cc
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

///////////////////////////////////////////////////////////////////////////////
// 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);
}

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

// Configuration

struct ConfigImpl {
};

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

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

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

224 225
auto Config::make() -> own<Config> {
  return own<Config>(seal<Config>(new (std::nothrow) ConfigImpl()));
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
}

// 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); }

257
auto Engine::make(own<Config>&& config) -> own<Engine> {
258
  i::FLAG_expose_gc = true;
259
  i::FLAG_experimental_wasm_reftypes = true;
260 261 262
  i::FLAG_experimental_wasm_bigint = true;
  i::FLAG_experimental_wasm_mv = true;
  auto engine = new (std::nothrow) EngineImpl;
263
  if (!engine) return own<Engine>();
264 265 266 267 268 269 270 271
  engine->platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(engine->platform.get());
  v8::V8::Initialize();
  return make_own(seal<Engine>(engine));
}

// Stores

272
StoreImpl::~StoreImpl() {
273
#ifdef DEBUG
274
  reinterpret_cast<i::Isolate*>(isolate_)->heap()->PreciseCollectAllGarbage(
275 276
      i::Heap::kForcedGC, i::GarbageCollectionReason::kTesting,
      v8::kNoGCCallbackFlags);
277
#endif
278 279 280 281
  context()->Exit();
  isolate_->Dispose();
  delete create_params_.array_buffer_allocator;
}
282

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
struct ManagedData {
  ManagedData(void* info, void (*finalizer)(void*))
      : info(info), finalizer(finalizer) {}

  ~ManagedData() {
    if (finalizer) (*finalizer)(info);
  }

  void* info;
  void (*finalizer)(void*);
};

void StoreImpl::SetHostInfo(i::Handle<i::Object> object, void* info,
                            void (*finalizer)(void*)) {
  i::HandleScope scope(i_isolate());
  // Ideally we would specify the total size kept alive by {info} here,
  // but all we get from the embedder is a {void*}, so our best estimate
  // is the size of the metadata.
  size_t estimated_size = sizeof(ManagedData);
  i::Handle<i::Object> wrapper = i::Managed<ManagedData>::FromRawPtr(
      i_isolate(), estimated_size, new ManagedData(info, finalizer));
  int32_t hash = object->GetOrCreateHash(i_isolate()).value();
  i::JSWeakCollection::Set(host_info_map_, object, wrapper, hash);
}

void* StoreImpl::GetHostInfo(i::Handle<i::Object> key) {
  i::Object raw =
      i::EphemeronHashTable::cast(host_info_map_->table()).Lookup(key);
  if (raw.IsTheHole(i_isolate())) return nullptr;
  return i::Managed<ManagedData>::cast(raw).raw()->info;
}

315 316 317 318 319 320 321 322 323
template <>
struct implement<Store> {
  using type = StoreImpl;
};

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

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

324
auto Store::make(Engine*) -> own<Store> {
325
  auto store = make_own(new (std::nothrow) StoreImpl());
326
  if (!store) return own<Store>();
327 328 329 330

  // Create isolate.
  store->create_params_.array_buffer_allocator =
      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
331
  v8::Isolate* isolate = v8::Isolate::New(store->create_params_);
332
  if (!isolate) return own<Store>();
333 334 335 336 337 338
  store->isolate_ = isolate;
  isolate->SetData(0, store.get());
  // We intentionally do not call isolate->Enter() here, because that would
  // prevent embedders from using stores with overlapping but non-nested
  // lifetimes. The consequence is that Isolate::Current() is dysfunctional
  // and hence must not be called by anything reachable via this file.
339 340 341 342 343

  {
    v8::HandleScope handle_scope(isolate);

    // Create context.
344
    v8::Local<v8::Context> context = v8::Context::New(isolate);
345
    if (context.IsEmpty()) return own<Store>();
346
    context->Enter();  // The Exit() call is in ~StoreImpl.
347
    store->context_ = v8::Eternal<v8::Context>(isolate, context);
348 349 350 351 352

    // Create weak map for Refs with host info.
    i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    store->host_info_map_ = i_isolate->global_handles()->Create(
        *i_isolate->factory()->NewJSWeakMap());
353
  }
354 355 356 357
  // We want stack traces for traps.
  constexpr int kStackLimit = 10;
  isolate->SetCaptureStackTraceForUncaughtExceptions(true, kStackLimit,
                                                     v8::StackTrace::kOverview);
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

  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;
};

378 379 380 381
ValTypeImpl* valtype_i32 = new ValTypeImpl(I32);
ValTypeImpl* valtype_i64 = new ValTypeImpl(I64);
ValTypeImpl* valtype_f32 = new ValTypeImpl(F32);
ValTypeImpl* valtype_f64 = new ValTypeImpl(F64);
382
ValTypeImpl* valtype_externref = new ValTypeImpl(ANYREF);
383
ValTypeImpl* valtype_funcref = new ValTypeImpl(FUNCREF);
384

385
ValType::~ValType() = default;
386 387 388

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

389
own<ValType> ValType::make(ValKind k) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
  ValTypeImpl* valtype;
  switch (k) {
    case I32:
      valtype = valtype_i32;
      break;
    case I64:
      valtype = valtype_i64;
      break;
    case F32:
      valtype = valtype_f32;
      break;
    case F64:
      valtype = valtype_f64;
      break;
    case ANYREF:
405
      valtype = valtype_externref;
406 407 408 409 410 411 412 413
      break;
    case FUNCREF:
      valtype = valtype_funcref;
      break;
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
  }
414
  return own<ValType>(seal<ValType>(valtype));
415 416
}

417
auto ValType::copy() const -> own<ValType> { return make(kind()); }
418 419 420 421 422 423 424 425 426

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

// Extern Types

struct ExternTypeImpl {
  ExternKind kind;

  explicit ExternTypeImpl(ExternKind kind) : kind(kind) {}
427
  virtual ~ExternTypeImpl() = default;
428 429 430 431 432 433 434 435 436 437 438
};

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

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

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

439
auto ExternType::copy() const -> own<ExternType> {
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
  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 {
457 458
  ownvec<ValType> params;
  ownvec<ValType> results;
459

460 461
  FuncTypeImpl(ownvec<ValType>& params,   // NOLINT(runtime/references)
               ownvec<ValType>& results)  // NOLINT(runtime/references)
462 463 464 465 466 467 468 469 470 471
      : ExternTypeImpl(EXTERN_FUNC),
        params(std::move(params)),
        results(std::move(results)) {}
};

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

472
FuncType::~FuncType() = default;
473

474 475
auto FuncType::make(ownvec<ValType>&& params, ownvec<ValType>&& results)
    -> own<FuncType> {
476
  return params && results
477 478 479
             ? own<FuncType>(seal<FuncType>(new (std::nothrow)
                                                FuncTypeImpl(params, results)))
             : own<FuncType>();
480 481
}

482 483
auto FuncType::copy() const -> own<FuncType> {
  return make(params().deep_copy(), results().deep_copy());
484 485
}

486
auto FuncType::params() const -> const ownvec<ValType>& {
487 488 489
  return impl(this)->params;
}

490
auto FuncType::results() const -> const ownvec<ValType>& {
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
  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 {
509
  own<ValType> content;
510 511
  Mutability mutability;

512
  GlobalTypeImpl(own<ValType>& content,  // NOLINT(runtime/references)
513
                 Mutability mutability)
514 515 516 517
      : ExternTypeImpl(EXTERN_GLOBAL),
        content(std::move(content)),
        mutability(mutability) {}

518
  ~GlobalTypeImpl() override = default;
519 520 521 522 523 524 525
};

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

526
GlobalType::~GlobalType() = default;
527

528 529 530
auto GlobalType::make(own<ValType>&& content, Mutability mutability)
    -> own<GlobalType> {
  return content ? own<GlobalType>(seal<GlobalType>(
531
                       new (std::nothrow) GlobalTypeImpl(content, mutability)))
532
                 : own<GlobalType>();
533 534
}

535
auto GlobalType::copy() const -> own<GlobalType> {
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
  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 {
562
  own<ValType> element;
563 564
  Limits limits;

565
  TableTypeImpl(own<ValType>& element,  // NOLINT(runtime/references)
566
                Limits limits)
567 568 569 570
      : ExternTypeImpl(EXTERN_TABLE),
        element(std::move(element)),
        limits(limits) {}

571
  ~TableTypeImpl() override = default;
572 573 574 575 576 577 578
};

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

579
TableType::~TableType() = default;
580

581 582
auto TableType::make(own<ValType>&& element, Limits limits) -> own<TableType> {
  return element ? own<TableType>(seal<TableType>(
583
                       new (std::nothrow) TableTypeImpl(element, limits)))
584
                 : own<TableType>();
585 586
}

587
auto TableType::copy() const -> own<TableType> {
588 589 590 591 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
  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) {}

617
  ~MemoryTypeImpl() override = default;
618 619 620 621 622 623 624
};

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

625
MemoryType::~MemoryType() = default;
626

627 628
auto MemoryType::make(Limits limits) -> own<MemoryType> {
  return own<MemoryType>(
629 630 631
      seal<MemoryType>(new (std::nothrow) MemoryTypeImpl(limits)));
}

632
auto MemoryType::copy() const -> own<MemoryType> {
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
  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;
655
  own<ExternType> type;
656

657 658 659
  ImportTypeImpl(Name& module,           // NOLINT(runtime/references)
                 Name& name,             // NOLINT(runtime/references)
                 own<ExternType>& type)  // NOLINT(runtime/references)
660 661 662 663 664 665 666 667 668 669 670 671 672 673
      : module(std::move(module)),
        name(std::move(name)),
        type(std::move(type)) {}
};

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

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

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

674 675
auto ImportType::make(Name&& module, Name&& name, own<ExternType>&& type)
    -> own<ImportType> {
676
  return module && name && type
677
             ? own<ImportType>(seal<ImportType>(
678
                   new (std::nothrow) ImportTypeImpl(module, name, type)))
679
             : own<ImportType>();
680 681
}

682
auto ImportType::copy() const -> own<ImportType> {
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
  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;
698
  own<ExternType> type;
699

700 701
  ExportTypeImpl(Name& name,             // NOLINT(runtime/references)
                 own<ExternType>& type)  // NOLINT(runtime/references)
702 703 704 705 706 707 708 709 710 711 712 713
      : name(std::move(name)), type(std::move(type)) {}
};

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

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

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

714 715
auto ExportType::make(Name&& name, own<ExternType>&& type) -> own<ExportType> {
  return name && type ? own<ExportType>(seal<ExportType>(
716
                            new (std::nothrow) ExportTypeImpl(name, type)))
717
                      : own<ExportType>();
718 719
}

720
auto ExportType::copy() const -> own<ExportType> {
721 722 723 724 725 726 727 728 729
  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();
}

730 731
i::Handle<i::String> VecToString(i::Isolate* isolate,
                                 const vec<byte_t>& chars) {
732 733 734 735
  size_t length = chars.size();
  // Some, but not all, {chars} vectors we get here are null-terminated,
  // so let's be robust to that.
  if (length > 0 && chars[length - 1] == 0) length--;
736
  return isolate->factory()
737
      ->NewStringFromUtf8({chars.get(), length})
738 739 740
      .ToHandleChecked();
}

741 742
// References

743 744
template <class Ref, class JSType>
class RefImpl {
745
 public:
746
  static own<Ref> make(StoreImpl* store, i::Handle<JSType> obj) {
747
    RefImpl* self = new (std::nothrow) RefImpl();
748
    if (!self) return nullptr;
749 750
    i::Isolate* isolate = store->i_isolate();
    self->val_ = isolate->global_handles()->Create(*obj);
751 752 753
    return make_own(seal<Ref>(self));
  }

754
  ~RefImpl() { i::GlobalHandles::Destroy(location()); }
755

756
  own<Ref> copy() const { return make(store(), v8_object()); }
757

758
  StoreImpl* store() const { return StoreImpl::get(isolate()); }
759

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

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

764
  void* get_host_info() const { return store()->GetHostInfo(v8_object()); }
765 766

  void set_host_info(void* info, void (*finalizer)(void*)) {
767
    store()->SetHostInfo(v8_object(), info, finalizer);
768 769 770
  }

 private:
771
  RefImpl() = default;
772 773 774 775 776 777

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

  i::Handle<i::JSReceiver> val_;
778 779 780 781
};

template <>
struct implement<Ref> {
782
  using type = RefImpl<Ref, i::JSReceiver>;
783 784
};

785
Ref::~Ref() { delete impl(this); }
786 787 788

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

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

791 792 793 794 795
auto Ref::same(const Ref* that) const -> bool {
  i::HandleScope handle_scope(impl(this)->isolate());
  return impl(this)->v8_object()->SameValue(*impl(that)->v8_object());
}

796 797 798 799 800 801 802 803 804
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

805 806 807 808 809
// Frames

namespace {

struct FrameImpl {
810
  FrameImpl(own<Instance>&& instance, uint32_t func_index, size_t func_offset,
811 812 813 814 815 816
            size_t module_offset)
      : instance(std::move(instance)),
        func_index(func_index),
        func_offset(func_offset),
        module_offset(module_offset) {}

817
  own<Instance> instance;
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
  uint32_t func_index;
  size_t func_offset;
  size_t module_offset;
};

}  // namespace

template <>
struct implement<Frame> {
  using type = FrameImpl;
};

Frame::~Frame() { impl(this)->~FrameImpl(); }

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

834
own<Frame> Frame::copy() const {
835
  auto self = impl(this);
836
  return own<Frame>(seal<Frame>(
837 838 839 840 841 842 843 844 845 846 847 848
      new (std::nothrow) FrameImpl(self->instance->copy(), self->func_index,
                                   self->func_offset, self->module_offset)));
}

Instance* Frame::instance() const { return impl(this)->instance.get(); }

uint32_t Frame::func_index() const { return impl(this)->func_index; }

size_t Frame::func_offset() const { return impl(this)->func_offset; }

size_t Frame::module_offset() const { return impl(this)->module_offset; }

849 850 851 852
// Traps

template <>
struct implement<Trap> {
853
  using type = RefImpl<Trap, i::JSReceiver>;
854 855
};

856
Trap::~Trap() = default;
857

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

860
auto Trap::make(Store* store_abs, const Message& message) -> own<Trap> {
861
  auto store = impl(store_abs);
862 863 864 865 866 867
  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);
868 869 870 871
}

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

874 875 876 877 878 879 880 881
  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());
882 883
}

884 885
namespace {

886 887
own<Instance> GetInstance(StoreImpl* store,
                          i::Handle<i::WasmInstanceObject> instance);
888

889 890
own<Frame> CreateFrameFromInternal(i::Handle<i::FixedArray> frames, int index,
                                   i::Isolate* isolate, StoreImpl* store) {
891 892 893 894
  i::Handle<i::StackTraceFrame> frame(i::StackTraceFrame::cast(frames->get(0)),
                                      isolate);
  i::Handle<i::WasmInstanceObject> instance =
      i::StackTraceFrame::GetWasmInstance(frame);
895
  uint32_t func_index = i::StackTraceFrame::GetWasmFunctionIndex(frame);
896 897
  size_t func_offset = i::StackTraceFrame::GetFunctionOffset(frame);
  size_t module_offset = i::StackTraceFrame::GetColumnNumber(frame);
898
  return own<Frame>(seal<Frame>(new (std::nothrow) FrameImpl(
899 900 901 902 903
      GetInstance(store, instance), func_index, func_offset, module_offset)));
}

}  // namespace

904
own<Frame> Trap::origin() const {
905 906 907 908 909 910 911
  i::Isolate* isolate = impl(this)->isolate();
  i::HandleScope handle_scope(isolate);

  i::Handle<i::JSMessageObject> message =
      isolate->CreateMessage(impl(this)->v8_object(), nullptr);
  i::Handle<i::FixedArray> frames(i::FixedArray::cast(message->stack_frames()),
                                  isolate);
912 913 914
  if (frames->length() == 0) {
    return own<Frame>();
  }
915 916 917
  return CreateFrameFromInternal(frames, 0, isolate, impl(this)->store());
}

918
ownvec<Frame> Trap::trace() const {
919 920 921 922 923 924 925 926
  i::Isolate* isolate = impl(this)->isolate();
  i::HandleScope handle_scope(isolate);

  i::Handle<i::JSMessageObject> message =
      isolate->CreateMessage(impl(this)->v8_object(), nullptr);
  i::Handle<i::FixedArray> frames(i::FixedArray::cast(message->stack_frames()),
                                  isolate);
  int num_frames = frames->length();
927
  // {num_frames} can be 0; the code below can handle that case.
928
  ownvec<Frame> result = ownvec<Frame>::make_uninitialized(num_frames);
929 930 931 932 933 934 935
  for (int i = 0; i < num_frames; i++) {
    result[i] =
        CreateFrameFromInternal(frames, i, isolate, impl(this)->store());
  }
  return result;
}

936 937 938 939
// Foreign Objects

template <>
struct implement<Foreign> {
940
  using type = RefImpl<Foreign, i::JSReceiver>;
941 942
};

943
Foreign::~Foreign() = default;
944

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

947
auto Foreign::make(Store* store_abs) -> own<Foreign> {
948 949
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
950
  i::HandleScope handle_scope(isolate);
951

952 953
  i::Handle<i::JSObject> obj =
      isolate->factory()->NewJSObject(isolate->object_function());
954
  return implement<Foreign>::type::make(store, obj);
955 956 957 958 959 960
}

// Modules

template <>
struct implement<Module> {
961
  using type = RefImpl<Module, i::WasmModuleObject>;
962 963
};

964
Module::~Module() = default;
965

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

auto Module::validate(Store* store_abs, const vec<byte_t>& binary) -> bool {
969 970 971
  i::wasm::ModuleWireBytes bytes(
      {reinterpret_cast<const uint8_t*>(binary.get()), binary.size()});
  i::Isolate* isolate = impl(store_abs)->i_isolate();
972
  i::wasm::WasmFeatures features = i::wasm::WasmFeatures::FromIsolate(isolate);
973
  return isolate->wasm_engine()->SyncValidate(isolate, features, bytes);
974 975
}

976
auto Module::make(Store* store_abs, const vec<byte_t>& binary) -> own<Module> {
977 978 979 980 981
  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()});
982
  i::wasm::WasmFeatures features = i::wasm::WasmFeatures::FromIsolate(isolate);
983
  i::wasm::ErrorThrower thrower(isolate, "ignored");
984 985 986 987
  i::Handle<i::WasmModuleObject> module;
  if (!isolate->wasm_engine()
           ->SyncCompile(isolate, features, &thrower, bytes)
           .ToHandle(&module)) {
988
    thrower.Reset();  // The API provides no way to expose the error.
989 990 991
    return nullptr;
  }
  return implement<Module>::type::make(store, module);
992 993
}

994
auto Module::imports() const -> ownvec<ImportType> {
995 996 997 998 999 1000
  const i::wasm::NativeModule* native_module =
      impl(this)->v8_object()->native_module();
  const i::wasm::WasmModule* module = native_module->module();
  const i::Vector<const uint8_t> wire_bytes = native_module->wire_bytes();
  const std::vector<i::wasm::WasmImport>& import_table = module->import_table;
  size_t size = import_table.size();
1001
  ownvec<ImportType> imports = ownvec<ImportType>::make_uninitialized(size);
1002 1003 1004 1005
  for (uint32_t i = 0; i < size; i++) {
    const i::wasm::WasmImport& imp = import_table[i];
    Name module_name = GetNameFromWireBytes(imp.module_name, wire_bytes);
    Name name = GetNameFromWireBytes(imp.field_name, wire_bytes);
1006
    own<ExternType> type = GetImportExportType(module, imp.kind, imp.index);
1007 1008 1009
    imports[i] = ImportType::make(std::move(module_name), std::move(name),
                                  std::move(type));
  }
1010 1011 1012
  return imports;
}

1013
ownvec<ExportType> ExportsImpl(i::Handle<i::WasmModuleObject> module_obj) {
1014 1015 1016 1017 1018
  const i::wasm::NativeModule* native_module = module_obj->native_module();
  const i::wasm::WasmModule* module = native_module->module();
  const i::Vector<const uint8_t> wire_bytes = native_module->wire_bytes();
  const std::vector<i::wasm::WasmExport>& export_table = module->export_table;
  size_t size = export_table.size();
1019
  ownvec<ExportType> exports = ownvec<ExportType>::make_uninitialized(size);
1020 1021 1022
  for (uint32_t i = 0; i < size; i++) {
    const i::wasm::WasmExport& exp = export_table[i];
    Name name = GetNameFromWireBytes(exp.name, wire_bytes);
1023
    own<ExternType> type = GetImportExportType(module, exp.kind, exp.index);
1024 1025
    exports[i] = ExportType::make(std::move(name), std::move(type));
  }
1026 1027 1028
  return exports;
}

1029
auto Module::exports() const -> ownvec<ExportType> {
1030 1031 1032
  return ExportsImpl(impl(this)->v8_object());
}

1033
auto Module::serialize() const -> vec<byte_t> {
1034 1035 1036 1037
  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();
1038 1039
  // We can only serialize after top-tier compilation (TurboFan) finished.
  native_module->compilation_state()->WaitForTopTierFinished();
1040 1041 1042 1043
  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 =
1044
      vec<byte_t>::make_uninitialized(size_size + binary_size + serial_size);
1045
  byte_t* ptr = buffer.get();
1046 1047
  i::wasm::LEBHelper::write_u64v(reinterpret_cast<uint8_t**>(&ptr),
                                 binary_size);
1048
  std::memcpy(ptr, wire_bytes.begin(), binary_size);
1049
  ptr += binary_size;
1050 1051 1052 1053
  if (!serializer.SerializeNativeModule(
          {reinterpret_cast<uint8_t*>(ptr), serial_size})) {
    buffer.reset();
  }
1054
  return buffer;
1055 1056 1057
}

auto Module::deserialize(Store* store_abs, const vec<byte_t>& serialized)
1058
    -> own<Module> {
1059 1060 1061 1062
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
  const byte_t* ptr = serialized.get();
1063
  uint64_t binary_size = ReadLebU64(&ptr);
1064 1065 1066
  ptrdiff_t size_size = ptr - serialized.get();
  size_t serial_size = serialized.size() - size_size - binary_size;
  i::Handle<i::WasmModuleObject> module_obj;
1067
  size_t data_size = static_cast<size_t>(binary_size);
1068 1069
  if (!i::wasm::DeserializeNativeModule(
           isolate,
1070
           {reinterpret_cast<const uint8_t*>(ptr + data_size), serial_size},
1071
           {reinterpret_cast<const uint8_t*>(ptr), data_size}, {})
1072 1073 1074 1075
           .ToHandle(&module_obj)) {
    return nullptr;
  }
  return implement<Module>::type::make(store, module_obj);
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
}

// 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);
}

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

1099
auto Module::obtain(Store* store, const Shared<Module>* shared) -> own<Module> {
1100 1101 1102 1103 1104 1105 1106
  return Module::deserialize(store, *impl(shared));
}

// Externals

template <>
struct implement<Extern> {
1107
  using type = RefImpl<Extern, i::JSReceiver>;
1108 1109
};

1110
Extern::~Extern() = default;
1111

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

auto Extern::kind() const -> ExternKind {
1115 1116 1117 1118 1119 1120 1121 1122
  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();
1123 1124
}

1125
auto Extern::type() const -> own<ExternType> {
1126 1127 1128 1129 1130 1131 1132 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 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
  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;
}

1170
auto extern_to_v8(const Extern* ex) -> i::Handle<i::JSReceiver> {
1171 1172 1173 1174 1175 1176 1177
  return impl(ex)->v8_object();
}

// Function Instances

template <>
struct implement<Func> {
1178
  using type = RefImpl<Func, i::JSFunction>;
1179 1180
};

1181
Func::~Func() = default;
1182

1183
auto Func::copy() const -> own<Func> { return impl(this)->copy(); }
1184 1185 1186

struct FuncData {
  Store* store;
1187
  own<FuncType> type;
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
  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);
  }

1207
  static i::Address v8_callback(i::Address host_data_foreign, i::Address argv);
1208 1209 1210 1211
};

namespace {

1212 1213 1214 1215
// TODO(jkummerow): Generalize for WasmExportedFunction and WasmCapiFunction.
class SignatureHelper : public i::AllStatic {
 public:
  // Use an invalid type as a marker separating params and results.
1216
  static constexpr i::wasm::ValueType kMarker = i::wasm::kWasmStmt;
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227

  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++) {
1228
      sig->set(index++, WasmValKindToV8(type->results()[i]->kind()));
1229 1230 1231 1232 1233 1234
    }
    // {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++) {
1235
      sig->set(index++, WasmValKindToV8(type->params()[i]->kind()));
1236 1237 1238 1239
    }
    return sig;
  }

1240
  static own<FuncType> Deserialize(i::PodArray<i::wasm::ValueType> sig) {
1241
    int result_arity = ResultArity(sig);
1242
    int param_arity = sig.length() - result_arity - 1;
1243 1244
    ownvec<ValType> results = ownvec<ValType>::make_uninitialized(result_arity);
    ownvec<ValType> params = ownvec<ValType>::make_uninitialized(param_arity);
1245 1246

    int i = 0;
1247
    for (; i < result_arity; ++i) {
1248
      results[i] = ValType::make(V8ValueTypeToWasm(sig.get(i)));
1249
    }
1250 1251
    i++;  // Skip marker.
    for (int p = 0; i < sig.length(); ++i, ++p) {
1252
      params[p] = ValType::make(V8ValueTypeToWasm(sig.get(i)));
1253 1254 1255 1256 1257 1258
    }
    return FuncType::make(std::move(params), std::move(results));
  }

  static int ResultArity(i::PodArray<i::wasm::ValueType> sig) {
    int count = 0;
1259 1260
    for (; count < sig.length(); count++) {
      if (sig.get(count) == kMarker) return count;
1261 1262 1263 1264 1265
    }
    UNREACHABLE();
  }

  static int ParamArity(i::PodArray<i::wasm::ValueType> sig) {
1266
    return sig.length() - ResultArity(sig) - 1;
1267 1268 1269 1270
  }

  static i::PodArray<i::wasm::ValueType> GetSig(
      i::Handle<i::JSFunction> function) {
1271
    return i::WasmCapiFunction::cast(*function).GetSerializedSignature();
1272 1273 1274
  }
};

1275 1276 1277 1278
// Explicit instantiation makes the linker happy for component builds of
// wasm_api_tests.
constexpr i::wasm::ValueType SignatureHelper::kMarker;

1279
auto make_func(Store* store_abs, FuncData* data) -> own<Func> {
1280
  auto store = impl(store_abs);
1281 1282
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
1283 1284
  i::Handle<i::Managed<FuncData>> embedder_data =
      i::Managed<FuncData>::FromRawPtr(isolate, sizeof(FuncData), data);
1285
  i::Handle<i::WasmCapiFunction> function = i::WasmCapiFunction::New(
1286 1287
      isolate, reinterpret_cast<i::Address>(&FuncData::v8_callback),
      embedder_data, SignatureHelper::Serialize(isolate, data->type.get()));
1288
  auto func = implement<Func>::type::make(store, function);
1289 1290 1291 1292 1293 1294
  return func;
}

}  // namespace

auto Func::make(Store* store, const FuncType* type, Func::callback callback)
1295
    -> own<Func> {
1296 1297 1298 1299 1300 1301
  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,
1302
                void* env, void (*finalizer)(void*)) -> own<Func> {
1303 1304 1305 1306 1307 1308 1309
  auto data = new FuncData(store, type, FuncData::kCallbackWithEnv);
  data->callback_with_env = callback;
  data->env = env;
  data->finalizer = finalizer;
  return make_func(store, data);
}

1310
auto Func::type() const -> own<FuncType> {
1311 1312 1313 1314 1315 1316 1317
  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);
1318 1319
  return FunctionSigToFuncType(
      function->instance().module()->functions[function->function_index()].sig);
1320 1321 1322
}

auto Func::param_arity() const -> size_t {
1323 1324 1325 1326 1327 1328 1329
  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);
1330
  const i::wasm::FunctionSig* sig =
1331
      function->instance().module()->functions[function->function_index()].sig;
1332
  return sig->parameter_count();
1333 1334 1335
}

auto Func::result_arity() const -> size_t {
1336 1337 1338 1339 1340 1341 1342
  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);
1343
  const i::wasm::FunctionSig* sig =
1344
      function->instance().module()->functions[function->function_index()].sig;
1345
  return sig->return_count();
1346 1347
}

1348 1349
namespace {

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
own<Ref> V8RefValueToWasm(StoreImpl* store, i::Handle<i::Object> value) {
  if (value->IsNull(store->i_isolate())) return nullptr;
  return implement<Ref>::type::make(store,
                                    i::Handle<i::JSReceiver>::cast(value));
}

i::Handle<i::Object> WasmRefToV8(i::Isolate* isolate, const Ref* ref) {
  if (ref == nullptr) return i::ReadOnlyRoots(isolate).null_value_handle();
  return impl(ref)->v8_object();
}

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
i::Handle<i::Object> CallTargetForCaching(i::Isolate* isolate,
                                          i::Address real_call_target) {
  if (i::kTaggedSize == i::kInt32Size) {
    return isolate->factory()->NewForeign(real_call_target);
  } else {
    // 64-bit uncompressed platform.
    return i::handle(i::Smi((real_call_target << i::kSmiTagSize) | i::kSmiTag),
                     isolate);
  }
}

i::Address CallTargetFromCache(i::Object cached_call_target) {
  if (i::kTaggedSize == i::kInt32Size) {
    return i::Foreign::cast(cached_call_target).foreign_address();
  } else {
    // 64-bit uncompressed platform.
    return cached_call_target.ptr() >> i::kSmiTagSize;
  }
}

1381 1382
void PrepareFunctionData(i::Isolate* isolate,
                         i::Handle<i::WasmExportedFunctionData> function_data,
1383
                         const i::wasm::FunctionSig* sig) {
1384 1385 1386 1387
  // If the data is already populated, return immediately.
  if (!function_data->c_wrapper_code().IsSmi()) return;
  // Compile wrapper code.
  i::Handle<i::Code> wrapper_code =
1388
      i::compiler::CompileCWasmEntry(isolate, sig);
1389 1390 1391 1392
  function_data->set_c_wrapper_code(*wrapper_code);
  // Compute packed args size.
  function_data->set_packed_args_size(
      i::wasm::CWasmArgumentsPacker::TotalSize(sig));
1393 1394 1395 1396 1397 1398
  // Get call target (function table offset), and wrap it as a cacheable object
  // (pseudo-Smi or Foreign, depending on platform).
  i::Handle<i::Object> call_target = CallTargetForCaching(
      isolate,
      function_data->instance().GetCallTarget(function_data->function_index()));
  function_data->set_wasm_call_target(*call_target);
1399 1400
}

1401
void PushArgs(const i::wasm::FunctionSig* sig, const Val args[],
1402
              i::wasm::CWasmArgumentsPacker* packer, StoreImpl* store) {
1403 1404
  for (size_t i = 0; i < sig->parameter_count(); i++) {
    i::wasm::ValueType type = sig->GetParam(i);
1405 1406
    switch (type.kind()) {
      case i::wasm::ValueType::kI32:
1407 1408
        packer->Push(args[i].i32());
        break;
1409
      case i::wasm::ValueType::kI64:
1410 1411
        packer->Push(args[i].i64());
        break;
1412
      case i::wasm::ValueType::kF32:
1413 1414
        packer->Push(args[i].f32());
        break;
1415
      case i::wasm::ValueType::kF64:
1416 1417
        packer->Push(args[i].f64());
        break;
1418 1419
      case i::wasm::ValueType::kRef:
      case i::wasm::ValueType::kOptRef:
1420
        // TODO(7748): Make sure this works for all heap types.
1421
        packer->Push(WasmRefToV8(store->i_isolate(), args[i].ref())->ptr());
1422
        break;
1423 1424 1425
      case i::wasm::ValueType::kRtt:
      case i::wasm::ValueType::kS128:
        // TODO(7748): Implement.
1426
        UNIMPLEMENTED();
1427 1428 1429 1430 1431 1432
      case i::wasm::ValueType::kI8:
      case i::wasm::ValueType::kI16:
      case i::wasm::ValueType::kStmt:
      case i::wasm::ValueType::kBottom:
        UNREACHABLE();
        break;
1433 1434 1435 1436
    }
  }
}

1437
void PopArgs(const i::wasm::FunctionSig* sig, Val results[],
1438
             i::wasm::CWasmArgumentsPacker* packer, StoreImpl* store) {
1439 1440 1441
  packer->Reset();
  for (size_t i = 0; i < sig->return_count(); i++) {
    i::wasm::ValueType type = sig->GetReturn(i);
1442 1443
    switch (type.kind()) {
      case i::wasm::ValueType::kI32:
1444 1445
        results[i] = Val(packer->Pop<int32_t>());
        break;
1446
      case i::wasm::ValueType::kI64:
1447 1448
        results[i] = Val(packer->Pop<int64_t>());
        break;
1449
      case i::wasm::ValueType::kF32:
1450 1451
        results[i] = Val(packer->Pop<float>());
        break;
1452
      case i::wasm::ValueType::kF64:
1453 1454
        results[i] = Val(packer->Pop<double>());
        break;
1455
      case i::wasm::ValueType::kRef:
1456 1457 1458 1459 1460
      case i::wasm::ValueType::kOptRef: {
        // TODO(7748): Make sure this works for all heap types.
        i::Address raw = packer->Pop<i::Address>();
        i::Handle<i::Object> obj(i::Object(raw), store->i_isolate());
        results[i] = Val(V8RefValueToWasm(store, obj));
1461
        break;
1462 1463 1464 1465
      }
      case i::wasm::ValueType::kRtt:
      case i::wasm::ValueType::kS128:
        // TODO(7748): Implement.
1466
        UNIMPLEMENTED();
1467 1468 1469 1470 1471 1472
      case i::wasm::ValueType::kI8:
      case i::wasm::ValueType::kI16:
      case i::wasm::ValueType::kStmt:
      case i::wasm::ValueType::kBottom:
        UNREACHABLE();
        break;
1473 1474 1475 1476
    }
  }
}

1477 1478
own<Trap> CallWasmCapiFunction(i::WasmCapiFunctionData data, const Val args[],
                               Val results[]) {
1479
  FuncData* func_data = i::Managed<FuncData>::cast(data.embedder_data()).raw();
1480 1481 1482 1483 1484 1485 1486
  if (func_data->kind == FuncData::kCallback) {
    return (func_data->callback)(args, results);
  }
  DCHECK(func_data->kind == FuncData::kCallbackWithEnv);
  return (func_data->callback_with_env)(func_data->env, args, results);
}

1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
i::Handle<i::JSReceiver> GetProperException(
    i::Isolate* isolate, i::Handle<i::Object> maybe_exception) {
  if (maybe_exception->IsJSReceiver()) {
    return i::Handle<i::JSReceiver>::cast(maybe_exception);
  }
  i::MaybeHandle<i::String> maybe_string =
      i::Object::ToString(isolate, maybe_exception);
  i::Handle<i::String> string = isolate->factory()->empty_string();
  if (!maybe_string.ToHandle(&string)) {
    // If converting the {maybe_exception} to string threw another exception,
    // just give up and leave {string} as the empty string.
    isolate->clear_pending_exception();
  }
  // {NewError} cannot fail when its input is a plain String, so we always
  // get an Error object here.
  return i::Handle<i::JSReceiver>::cast(
      isolate->factory()->NewError(isolate->error_function(), string));
}

1506 1507
}  // namespace

1508
auto Func::call(const Val args[], Val results[]) const -> own<Trap> {
1509 1510
  auto func = impl(this);
  auto store = func->store();
1511 1512 1513 1514 1515 1516
  auto isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
  i::Object raw_function_data = func->v8_object()->shared().function_data();

  // WasmCapiFunctions can be called directly.
  if (raw_function_data.IsWasmCapiFunctionData()) {
1517 1518
    return CallWasmCapiFunction(
        i::WasmCapiFunctionData::cast(raw_function_data), args, results);
1519
  }
1520

1521 1522 1523 1524
  DCHECK(raw_function_data.IsWasmExportedFunctionData());
  i::Handle<i::WasmExportedFunctionData> function_data(
      i::WasmExportedFunctionData::cast(raw_function_data), isolate);
  i::Handle<i::WasmInstanceObject> instance(function_data->instance(), isolate);
1525
  int function_index = function_data->function_index();
1526
  // Caching {sig} would give a ~10% reduction in overhead.
1527 1528
  const i::wasm::FunctionSig* sig =
      instance->module()->functions[function_index].sig;
1529 1530 1531 1532
  PrepareFunctionData(isolate, function_data, sig);
  i::Handle<i::Code> wrapper_code = i::Handle<i::Code>(
      i::Code::cast(function_data->c_wrapper_code()), isolate);
  i::Address call_target =
1533
      CallTargetFromCache(function_data->wasm_call_target());
1534 1535

  i::wasm::CWasmArgumentsPacker packer(function_data->packed_args_size());
1536
  PushArgs(sig, args, &packer, store);
1537 1538

  i::Handle<i::Object> object_ref = instance;
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
  if (function_index <
      static_cast<int>(instance->module()->num_imported_functions)) {
    object_ref = i::handle(
        instance->imported_function_refs().get(function_index), isolate);
    if (object_ref->IsTuple2()) {
      i::JSFunction jsfunc =
          i::JSFunction::cast(i::Tuple2::cast(*object_ref).value2());
      i::Object data = jsfunc.shared().function_data();
      if (data.IsWasmCapiFunctionData()) {
        return CallWasmCapiFunction(i::WasmCapiFunctionData::cast(data), args,
                                    results);
      }
      // TODO(jkummerow): Imported and then re-exported JavaScript functions
      // are not supported yet. If we support C-API + JavaScript, we'll need
      // to call those here.
      UNIMPLEMENTED();
    } else {
      // A WasmFunction from another module.
      DCHECK(object_ref->IsWasmInstanceObject());
    }
  }
1560 1561 1562 1563 1564 1565 1566

  i::Execution::CallWasm(isolate, wrapper_code, call_target, object_ref,
                         packer.argv());

  if (isolate->has_pending_exception()) {
    i::Handle<i::Object> exception(isolate->pending_exception(), isolate);
    isolate->clear_pending_exception();
1567 1568
    return implement<Trap>::type::make(store,
                                       GetProperException(isolate, exception));
1569 1570
  }

1571
  PopArgs(sig, results, &packer, store);
1572 1573 1574
  return nullptr;
}

1575 1576 1577
i::Address FuncData::v8_callback(i::Address host_data_foreign,
                                 i::Address argv) {
  FuncData* self =
1578
      i::Managed<FuncData>::cast(i::Object(host_data_foreign)).raw();
1579 1580
  StoreImpl* store = impl(self->store);
  i::Isolate* isolate = store->i_isolate();
1581
  i::HandleScope scope(isolate);
1582

1583 1584
  const ownvec<ValType>& param_types = self->type->params();
  const ownvec<ValType>& result_types = self->type->results();
1585 1586 1587 1588

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

1589
  std::unique_ptr<Val[]> params(new Val[num_param_types]);
1590
  std::unique_ptr<Val[]> results(new Val[num_result_types]);
1591
  i::Address p = argv;
1592
  for (int i = 0; i < num_param_types; ++i) {
1593 1594
    switch (param_types[i]->kind()) {
      case I32:
1595
        params[i] = Val(v8::base::ReadUnalignedValue<int32_t>(p));
1596 1597 1598
        p += 4;
        break;
      case I64:
1599
        params[i] = Val(v8::base::ReadUnalignedValue<int64_t>(p));
1600 1601 1602
        p += 8;
        break;
      case F32:
1603
        params[i] = Val(v8::base::ReadUnalignedValue<float32_t>(p));
1604 1605 1606
        p += 4;
        break;
      case F64:
1607
        params[i] = Val(v8::base::ReadUnalignedValue<float64_t>(p));
1608 1609 1610 1611
        p += 8;
        break;
      case ANYREF:
      case FUNCREF: {
1612
        i::Address raw = v8::base::ReadUnalignedValue<i::Address>(p);
1613
        p += sizeof(raw);
1614 1615
        i::Handle<i::Object> obj(i::Object(raw), isolate);
        params[i] = Val(V8RefValueToWasm(store, obj));
1616 1617 1618
        break;
      }
    }
1619 1620
  }

1621
  own<Trap> trap;
1622
  if (self->kind == kCallbackWithEnv) {
1623
    trap = self->callback_with_env(self->env, params.get(), results.get());
1624
  } else {
1625
    trap = self->callback(params.get(), results.get());
1626 1627 1628
  }

  if (trap) {
1629 1630 1631
    isolate->Throw(*impl(trap.get())->v8_object());
    i::Object ex = isolate->pending_exception();
    isolate->clear_pending_exception();
1632
    return ex.ptr();
1633 1634 1635 1636 1637 1638
  }

  p = argv;
  for (int i = 0; i < num_result_types; ++i) {
    switch (result_types[i]->kind()) {
      case I32:
1639
        v8::base::WriteUnalignedValue(p, results[i].i32());
1640 1641 1642
        p += 4;
        break;
      case I64:
1643
        v8::base::WriteUnalignedValue(p, results[i].i64());
1644 1645 1646
        p += 8;
        break;
      case F32:
1647
        v8::base::WriteUnalignedValue(p, results[i].f32());
1648 1649 1650
        p += 4;
        break;
      case F64:
1651
        v8::base::WriteUnalignedValue(p, results[i].f64());
1652 1653 1654 1655
        p += 8;
        break;
      case ANYREF:
      case FUNCREF: {
1656 1657
        v8::base::WriteUnalignedValue(
            p, WasmRefToV8(isolate, results[i].ref())->ptr());
1658 1659 1660 1661
        p += sizeof(i::Address);
        break;
      }
    }
1662
  }
1663
  return i::kNullAddress;
1664 1665 1666 1667 1668 1669
}

// Global Instances

template <>
struct implement<Global> {
1670
  using type = RefImpl<Global, i::WasmGlobalObject>;
1671 1672
};

1673
Global::~Global() = default;
1674

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

auto Global::make(Store* store_abs, const GlobalType* type, const Val& val)
1678
    -> own<Global> {
1679 1680 1681 1682 1683 1684
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);

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

1685
  i::wasm::ValueType i_type = WasmValKindToV8(type->content()->kind());
1686 1687 1688 1689 1690 1691 1692 1693 1694
  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);
1695 1696 1697 1698 1699
  assert(global);
  global->set(val);
  return global;
}

1700
auto Global::type() const -> own<GlobalType> {
1701
  i::Handle<i::WasmGlobalObject> v8_global = impl(this)->v8_object();
1702
  ValKind kind = V8ValueTypeToWasm(v8_global->type());
1703
  Mutability mutability = v8_global->is_mutable() ? VAR : CONST;
1704 1705 1706 1707
  return GlobalType::make(ValType::make(kind), mutability);
}

auto Global::get() const -> Val {
1708
  i::Handle<i::WasmGlobalObject> v8_global = impl(this)->v8_object();
1709 1710
  switch (v8_global->type().kind()) {
    case i::wasm::ValueType::kI32:
1711
      return Val(v8_global->GetI32());
1712
    case i::wasm::ValueType::kI64:
1713
      return Val(v8_global->GetI64());
1714
    case i::wasm::ValueType::kF32:
1715
      return Val(v8_global->GetF32());
1716
    case i::wasm::ValueType::kF64:
1717
      return Val(v8_global->GetF64());
1718
    case i::wasm::ValueType::kRef:
1719 1720 1721 1722 1723 1724 1725 1726
    case i::wasm::ValueType::kOptRef: {
      // TODO(7748): Make sure this works for all heap types.
      StoreImpl* store = impl(this)->store();
      i::HandleScope scope(store->i_isolate());
      return Val(V8RefValueToWasm(store, v8_global->GetRef()));
    }
    case i::wasm::ValueType::kRtt:
    case i::wasm::ValueType::kS128:
1727
      // TODO(7748): Implement these.
1728 1729 1730 1731 1732
      UNIMPLEMENTED();
    case i::wasm::ValueType::kI8:
    case i::wasm::ValueType::kI16:
    case i::wasm::ValueType::kStmt:
    case i::wasm::ValueType::kBottom:
1733 1734 1735 1736 1737
      UNREACHABLE();
  }
}

void Global::set(const Val& val) {
1738
  i::Handle<i::WasmGlobalObject> v8_global = impl(this)->v8_object();
1739 1740
  switch (val.kind()) {
    case I32:
1741
      return v8_global->SetI32(val.i32());
1742
    case I64:
1743
      return v8_global->SetI64(val.i64());
1744
    case F32:
1745
      return v8_global->SetF32(val.f32());
1746
    case F64:
1747
      return v8_global->SetF64(val.f64());
1748
    case ANYREF:
1749
      return v8_global->SetExternRef(
1750
          WasmRefToV8(impl(this)->store()->i_isolate(), val.ref()));
1751
    case FUNCREF: {
1752 1753 1754
      i::Isolate* isolate = impl(this)->store()->i_isolate();
      bool result =
          v8_global->SetFuncRef(isolate, WasmRefToV8(isolate, val.ref()));
1755 1756 1757 1758
      DCHECK(result);
      USE(result);
      return;
    }
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
    default:
      // TODO(wasm+): support new value types
      UNREACHABLE();
  }
}

// Table Instances

template <>
struct implement<Table> {
1769
  using type = RefImpl<Table, i::WasmTableObject>;
1770 1771
};

1772
Table::~Table() = default;
1773

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

auto Table::make(Store* store_abs, const TableType* type, const Ref* ref)
1777
    -> own<Table> {
1778 1779 1780 1781 1782 1783 1784 1785
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope scope(isolate);

  // Get "element".
  i::wasm::ValueType i_type;
  switch (type->element()->kind()) {
    case FUNCREF:
1786
      i_type = i::wasm::kWasmFuncRef;
1787 1788
      break;
    case ANYREF:
1789
      // See Engine::make().
1790 1791
      DCHECK(i::wasm::WasmFeatures::FromFlags().has_reftypes());
      i_type = i::wasm::kWasmExternRef;
1792
      break;
1793
    default:
1794
      UNREACHABLE();
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
      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.
1820
      DCHECK_EQ(table_obj->dispatch_tables().length(), 0);
1821
      backing_store->set(i, *init);
1822 1823
    }
  }
1824
  return implement<Table>::type::make(store, table_obj);
1825 1826
}

1827
auto Table::type() const -> own<TableType> {
1828 1829 1830
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
  uint32_t min = table->current_length();
  uint32_t max;
1831
  if (!table->maximum_length().ToUint32(&max)) max = 0xFFFFFFFFu;
1832
  ValKind kind;
1833
  switch (table->type().heap_representation()) {
1834
    case i::wasm::HeapType::kFunc:
1835 1836
      kind = FUNCREF;
      break;
1837
    case i::wasm::HeapType::kExtern:
1838 1839 1840 1841 1842 1843
      kind = ANYREF;
      break;
    default:
      UNREACHABLE();
  }
  return TableType::make(ValType::make(kind), Limits(min, max));
1844 1845
}

1846
auto Table::get(size_t index) const -> own<Ref> {
1847
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
1848
  if (index >= static_cast<size_t>(table->current_length())) return own<Ref>();
1849 1850 1851 1852
  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));
1853 1854
  // TODO(jkummerow): If we support both JavaScript and the C-API at the same
  // time, we need to handle Smis and other JS primitives here.
1855 1856
  DCHECK(result->IsNull(isolate) || result->IsJSReceiver());
  return V8RefValueToWasm(impl(this)->store(), result);
1857 1858 1859
}

auto Table::set(size_t index, const Ref* ref) -> bool {
1860
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
1861
  if (index >= static_cast<size_t>(table->current_length())) return false;
1862 1863
  i::Isolate* isolate = table->GetIsolate();
  i::HandleScope handle_scope(isolate);
1864
  i::Handle<i::Object> obj = WasmRefToV8(isolate, ref);
1865 1866
  i::WasmTableObject::Set(isolate, table, static_cast<uint32_t>(index), obj);
  return true;
1867 1868
}

1869
// TODO(jkummerow): Having Table::size_t shadowing "std" size_t is ugly.
1870
auto Table::size() const -> size_t {
1871
  return impl(this)->v8_object()->current_length();
1872 1873 1874
}

auto Table::grow(size_t delta, const Ref* ref) -> bool {
1875
  i::Handle<i::WasmTableObject> table = impl(this)->v8_object();
1876
  i::Isolate* isolate = table->GetIsolate();
1877
  i::HandleScope scope(isolate);
1878
  i::Handle<i::Object> init_value = WasmRefToV8(isolate, ref);
1879 1880
  int result = i::WasmTableObject::Grow(
      isolate, table, static_cast<uint32_t>(delta), init_value);
1881
  return result >= 0;
1882 1883 1884 1885 1886 1887
}

// Memory Instances

template <>
struct implement<Memory> {
1888
  using type = RefImpl<Memory, i::WasmMemoryObject>;
1889 1890
};

1891
Memory::~Memory() = default;
1892

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

1895
auto Memory::make(Store* store_abs, const MemoryType* type) -> own<Memory> {
1896 1897 1898
  StoreImpl* store = impl(store_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope scope(isolate);
1899

1900 1901
  const Limits& limits = type->limits();
  uint32_t minimum = limits.min;
1902 1903
  // The max_initial_mem_pages limit is only spec'ed for JS embeddings,
  // so we'll directly use the maximum pages limit here.
1904
  if (minimum > i::wasm::kSpecMaxMemoryPages) return nullptr;
1905 1906 1907
  uint32_t maximum = limits.max;
  if (maximum != Limits(0).max) {
    if (maximum < minimum) return nullptr;
1908
    if (maximum > i::wasm::kSpecMaxMemoryPages) return nullptr;
1909
  }
1910 1911
  // TODO(wasm+): Support shared memory.
  i::SharedFlag shared = i::SharedFlag::kNotShared;
1912
  i::Handle<i::WasmMemoryObject> memory_obj;
1913
  if (!i::WasmMemoryObject::New(isolate, minimum, maximum, shared)
1914
           .ToHandle(&memory_obj)) {
1915
    return own<Memory>();
1916 1917
  }
  return implement<Memory>::type::make(store, memory_obj);
1918 1919
}

1920
auto Memory::type() const -> own<MemoryType> {
1921
  i::Handle<i::WasmMemoryObject> memory = impl(this)->v8_object();
1922
  uint32_t min = static_cast<uint32_t>(memory->array_buffer().byte_length() /
1923 1924 1925
                                       i::wasm::kWasmPageSize);
  uint32_t max =
      memory->has_maximum_pages() ? memory->maximum_pages() : 0xFFFFFFFFu;
1926 1927 1928 1929
  return MemoryType::make(Limits(min, max));
}

auto Memory::data() const -> byte_t* {
1930
  return reinterpret_cast<byte_t*>(
1931
      impl(this)->v8_object()->array_buffer().backing_store());
1932 1933 1934
}

auto Memory::data_size() const -> size_t {
1935
  return impl(this)->v8_object()->array_buffer().byte_length();
1936 1937 1938
}

auto Memory::size() const -> pages_t {
1939
  return static_cast<pages_t>(
1940
      impl(this)->v8_object()->array_buffer().byte_length() /
1941
      i::wasm::kWasmPageSize);
1942 1943 1944
}

auto Memory::grow(pages_t delta) -> bool {
1945 1946 1947 1948 1949
  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;
1950 1951 1952 1953 1954 1955
}

// Module Instances

template <>
struct implement<Instance> {
1956
  using type = RefImpl<Instance, i::WasmInstanceObject>;
1957 1958
};

1959
Instance::~Instance() = default;
1960

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

1963 1964
own<Instance> Instance::make(Store* store_abs, const Module* module_abs,
                             const Extern* const imports[], own<Trap>* trap) {
1965 1966 1967 1968
  StoreImpl* store = impl(store_abs);
  const implement<Module>::type* module = impl(module_abs);
  i::Isolate* isolate = store->i_isolate();
  i::HandleScope handle_scope(isolate);
1969

1970
  DCHECK_EQ(module->v8_object()->GetIsolate(), isolate);
1971

1972
  if (trap) *trap = nullptr;
1973
  ownvec<ImportType> import_types = module_abs->imports();
1974 1975
  i::Handle<i::JSObject> imports_obj =
      isolate->factory()->NewJSObject(isolate->object_function());
1976
  for (size_t i = 0; i < import_types.size(); ++i) {
1977
    ImportType* type = import_types[i].get();
1978 1979 1980 1981 1982 1983 1984 1985 1986
    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());
1987
    } else {
1988 1989 1990
      module_obj = isolate->factory()->NewJSObject(isolate->object_function());
      ignore(
          i::Object::SetProperty(isolate, imports_obj, module_str, module_obj));
1991
    }
1992 1993
    ignore(i::Object::SetProperty(isolate, module_obj, name_str,
                                  impl(imports[i])->v8_object()));
1994
  }
1995 1996 1997 1998 1999 2000 2001 2002 2003
  i::wasm::ErrorThrower thrower(isolate, "instantiation");
  i::MaybeHandle<i::WasmInstanceObject> instance_obj =
      isolate->wasm_engine()->SyncInstantiate(
          isolate, &thrower, module->v8_object(), imports_obj,
          i::MaybeHandle<i::JSArrayBuffer>());
  if (trap) {
    if (thrower.error()) {
      *trap = implement<Trap>::type::make(
          store, GetProperException(isolate, thrower.Reify()));
2004
      DCHECK(!thrower.error());                   // Reify() called Reset().
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
      DCHECK(!isolate->has_pending_exception());  // Hasn't been thrown yet.
      return own<Instance>();
    } else if (isolate->has_pending_exception()) {
      i::Handle<i::Object> maybe_exception(isolate->pending_exception(),
                                           isolate);
      *trap = implement<Trap>::type::make(
          store, GetProperException(isolate, maybe_exception));
      isolate->clear_pending_exception();
      return own<Instance>();
    }
  } else if (instance_obj.is_null()) {
    // If no {trap} output is specified, silently swallow all errors.
    thrower.Reset();
    isolate->clear_pending_exception();
    return own<Instance>();
  }
  return implement<Instance>::type::make(store, instance_obj.ToHandleChecked());
2022 2023
}

2024 2025
namespace {

2026 2027
own<Instance> GetInstance(StoreImpl* store,
                          i::Handle<i::WasmInstanceObject> instance) {
2028 2029 2030 2031 2032
  return implement<Instance>::type::make(store, instance);
}

}  // namespace

2033
auto Instance::exports() const -> ownvec<Extern> {
2034 2035 2036 2037 2038 2039 2040 2041 2042
  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);

2043 2044 2045 2046
  ownvec<ExportType> export_types = ExportsImpl(module_obj);
  ownvec<Extern> exports =
      ownvec<Extern>::make_uninitialized(export_types.size());
  if (!exports) return ownvec<Extern>::invalid();
2047 2048 2049

  for (size_t i = 0; i < export_types.size(); ++i) {
    auto& name = export_types[i]->name();
2050 2051 2052 2053 2054 2055
    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();
2056 2057
    switch (type->kind()) {
      case EXTERN_FUNC: {
2058
        DCHECK(i::WasmExportedFunction::IsWasmExportedFunction(*obj));
2059 2060
        exports[i] = implement<Func>::type::make(
            store, i::Handle<i::WasmExportedFunction>::cast(obj));
2061 2062
      } break;
      case EXTERN_GLOBAL: {
2063 2064
        exports[i] = implement<Global>::type::make(
            store, i::Handle<i::WasmGlobalObject>::cast(obj));
2065 2066
      } break;
      case EXTERN_TABLE: {
2067 2068
        exports[i] = implement<Table>::type::make(
            store, i::Handle<i::WasmTableObject>::cast(obj));
2069 2070
      } break;
      case EXTERN_MEMORY: {
2071 2072
        exports[i] = implement<Memory>::type::make(
            store, i::Handle<i::WasmMemoryObject>::cast(obj));
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
      } 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++"

2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
#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(Name* x)->wasm_##name##_t* {            \
    return static_cast<wasm_##name##_t*>(x);                                   \
  }                                                                            \
  extern "C++" inline auto hide_##name(const Name* x)                          \
      ->const wasm_##name##_t* {                                               \
    return static_cast<const wasm_##name##_t*>(x);                             \
  }                                                                            \
  extern "C++" inline auto reveal_##name(wasm_##name##_t* x)->Name* {          \
    return x;                                                                  \
  }                                                                            \
  extern "C++" inline auto reveal_##name(const wasm_##name##_t* x)             \
      ->const Name* {                                                          \
    return x;                                                                  \
  }                                                                            \
2124
  extern "C++" inline auto get_##name(wasm::own<Name>& x)->wasm_##name##_t* {  \
2125 2126
    return hide_##name(x.get());                                               \
  }                                                                            \
2127
  extern "C++" inline auto get_##name(const wasm::own<Name>& x)                \
2128 2129 2130
      ->const wasm_##name##_t* {                                               \
    return hide_##name(x.get());                                               \
  }                                                                            \
2131
  extern "C++" inline auto release_##name(wasm::own<Name>&& x)                 \
2132 2133 2134
      ->wasm_##name##_t* {                                                     \
    return hide_##name(x.release());                                           \
  }                                                                            \
2135
  extern "C++" inline auto adopt_##name(wasm_##name##_t* x)->wasm::own<Name> { \
2136
    return make_own(x);                                                        \
2137 2138 2139 2140
  }

// Vectors

2141 2142 2143 2144 2145 2146 2147
#define WASM_DEFINE_VEC_BASE(name, Name, vec, ptr_or_none)                     \
  static_assert(sizeof(wasm_##name##_vec_t) == sizeof(vec<Name>),              \
                "C/C++ incompatibility");                                      \
  static_assert(                                                               \
      sizeof(wasm_##name##_t ptr_or_none) == sizeof(vec<Name>::elem_type),     \
      "C/C++ incompatibility");                                                \
  extern "C++" inline auto hide_##name##_vec(vec<Name>& v)                     \
2148 2149 2150
      ->wasm_##name##_vec_t* {                                                 \
    return reinterpret_cast<wasm_##name##_vec_t*>(&v);                         \
  }                                                                            \
2151
  extern "C++" inline auto hide_##name##_vec(const vec<Name>& v)               \
2152 2153 2154
      ->const wasm_##name##_vec_t* {                                           \
    return reinterpret_cast<const wasm_##name##_vec_t*>(&v);                   \
  }                                                                            \
2155
  extern "C++" inline auto hide_##name##_vec(vec<Name>::elem_type* v)          \
2156 2157 2158
      ->wasm_##name##_t ptr_or_none* {                                         \
    return reinterpret_cast<wasm_##name##_t ptr_or_none*>(v);                  \
  }                                                                            \
2159
  extern "C++" inline auto hide_##name##_vec(const vec<Name>::elem_type* v)    \
2160 2161 2162 2163
      ->wasm_##name##_t ptr_or_none const* {                                   \
    return reinterpret_cast<wasm_##name##_t ptr_or_none const*>(v);            \
  }                                                                            \
  extern "C++" inline auto reveal_##name##_vec(wasm_##name##_t ptr_or_none* v) \
2164 2165
      ->vec<Name>::elem_type* {                                                \
    return reinterpret_cast<vec<Name>::elem_type*>(v);                         \
2166 2167 2168
  }                                                                            \
  extern "C++" inline auto reveal_##name##_vec(                                \
      wasm_##name##_t ptr_or_none const* v)                                    \
2169 2170
      ->const vec<Name>::elem_type* {                                          \
    return reinterpret_cast<const vec<Name>::elem_type*>(v);                   \
2171
  }                                                                            \
2172
  extern "C++" inline auto get_##name##_vec(vec<Name>& v)                      \
2173 2174 2175 2176
      ->wasm_##name##_vec_t {                                                  \
    wasm_##name##_vec_t v2 = {v.size(), hide_##name##_vec(v.get())};           \
    return v2;                                                                 \
  }                                                                            \
2177
  extern "C++" inline auto get_##name##_vec(const vec<Name>& v)                \
2178 2179 2180 2181 2182 2183
      ->const wasm_##name##_vec_t {                                            \
    wasm_##name##_vec_t v2 = {                                                 \
        v.size(),                                                              \
        const_cast<wasm_##name##_t ptr_or_none*>(hide_##name##_vec(v.get()))}; \
    return v2;                                                                 \
  }                                                                            \
2184
  extern "C++" inline auto release_##name##_vec(vec<Name>&& v)                 \
2185 2186 2187 2188 2189
      ->wasm_##name##_vec_t {                                                  \
    wasm_##name##_vec_t v2 = {v.size(), hide_##name##_vec(v.release())};       \
    return v2;                                                                 \
  }                                                                            \
  extern "C++" inline auto adopt_##name##_vec(wasm_##name##_vec_t* v)          \
2190 2191
      ->vec<Name> {                                                            \
    return vec<Name>::adopt(v->size, reveal_##name##_vec(v->data));            \
2192 2193
  }                                                                            \
  extern "C++" inline auto borrow_##name##_vec(const wasm_##name##_vec_t* v)   \
2194 2195 2196
      ->borrowed_vec<vec<Name>::elem_type> {                                   \
    return borrowed_vec<vec<Name>::elem_type>(                                 \
        vec<Name>::adopt(v->size, reveal_##name##_vec(v->data)));              \
2197 2198 2199 2200
  }                                                                            \
                                                                               \
  void wasm_##name##_vec_new_uninitialized(wasm_##name##_vec_t* out,           \
                                           size_t size) {                      \
2201
    *out = release_##name##_vec(vec<Name>::make_uninitialized(size));          \
2202 2203 2204 2205 2206 2207 2208 2209
  }                                                                            \
  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_##name##_vec(v);                                                     \
  }
2210 2211

// Vectors with no ownership management of elements
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
#define WASM_DEFINE_VEC_PLAIN(name, Name)                           \
  WASM_DEFINE_VEC_BASE(name, Name,                                  \
                       wasm::vec, ) /* NOLINT(whitespace/parens) */ \
                                                                    \
  void wasm_##name##_vec_new(wasm_##name##_vec_t* out, size_t size, \
                             const wasm_##name##_t data[]) {        \
    auto v2 = wasm::vec<Name>::make_uninitialized(size);            \
    if (v2.size() != 0) {                                           \
      memcpy(v2.get(), data, size * sizeof(wasm_##name##_t));       \
    }                                                               \
    *out = release_##name##_vec(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);                   \
2228 2229
  }

2230
// Vectors that own their elements
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
#define WASM_DEFINE_VEC_OWN(name, Name)                             \
  WASM_DEFINE_VEC_BASE(name, Name, wasm::ownvec, *)                 \
                                                                    \
  void wasm_##name##_vec_new(wasm_##name##_vec_t* out, size_t size, \
                             wasm_##name##_t* const data[]) {       \
    auto v2 = wasm::ownvec<Name>::make_uninitialized(size);         \
    for (size_t i = 0; i < v2.size(); ++i) {                        \
      v2[i] = adopt_##name(data[i]);                                \
    }                                                               \
    *out = release_##name##_vec(std::move(v2));                     \
  }                                                                 \
                                                                    \
  void wasm_##name##_vec_copy(wasm_##name##_vec_t* out,             \
                              wasm_##name##_vec_t* v) {             \
    auto v2 = wasm::ownvec<Name>::make_uninitialized(v->size);      \
    for (size_t i = 0; i < v2.size(); ++i) {                        \
      v2[i] = adopt_##name(wasm_##name##_copy(v->data[i]));         \
    }                                                               \
    *out = release_##name##_vec(std::move(v2));                     \
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
  }

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

// Byte vectors

using byte = byte_t;
2262
WASM_DEFINE_VEC_PLAIN(byte, byte)
2263 2264 2265 2266 2267 2268 2269 2270

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

// Configuration

WASM_DEFINE_OWN(config, wasm::Config)

2271 2272 2273
wasm_config_t* wasm_config_new() {
  return release_config(wasm::Config::make());
}
2274 2275 2276 2277 2278

// Engine

WASM_DEFINE_OWN(engine, wasm::Engine)

2279 2280 2281
wasm_engine_t* wasm_engine_new() {
  return release_engine(wasm::Engine::make());
}
2282 2283

wasm_engine_t* wasm_engine_new_with_config(wasm_config_t* config) {
2284
  return release_engine(wasm::Engine::make(adopt_config(config)));
2285 2286 2287 2288 2289 2290 2291
}

// Stores

WASM_DEFINE_OWN(store, wasm::Store)

wasm_store_t* wasm_store_new(wasm_engine_t* engine) {
2292
  return release_store(wasm::Store::make(engine));
2293 2294 2295 2296 2297 2298 2299
}

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

// Type attributes

2300
extern "C++" inline auto hide_mutability(wasm::Mutability mutability)
2301 2302 2303 2304
    -> wasm_mutability_t {
  return static_cast<wasm_mutability_t>(mutability);
}

2305
extern "C++" inline auto reveal_mutability(wasm_mutability_t mutability)
2306 2307 2308 2309
    -> wasm::Mutability {
  return static_cast<wasm::Mutability>(mutability);
}

2310
extern "C++" inline auto hide_limits(const wasm::Limits& limits)
2311 2312 2313 2314
    -> const wasm_limits_t* {
  return reinterpret_cast<const wasm_limits_t*>(&limits);
}

2315
extern "C++" inline auto reveal_limits(wasm_limits_t limits) -> wasm::Limits {
2316 2317 2318
  return wasm::Limits(limits.min, limits.max);
}

2319
extern "C++" inline auto hide_valkind(wasm::ValKind kind) -> wasm_valkind_t {
2320 2321 2322
  return static_cast<wasm_valkind_t>(kind);
}

2323
extern "C++" inline auto reveal_valkind(wasm_valkind_t kind) -> wasm::ValKind {
2324 2325 2326
  return static_cast<wasm::ValKind>(kind);
}

2327 2328
extern "C++" inline auto hide_externkind(wasm::ExternKind kind)
    -> wasm_externkind_t {
2329 2330 2331
  return static_cast<wasm_externkind_t>(kind);
}

2332
extern "C++" inline auto reveal_externkind(wasm_externkind_t kind)
2333
    -> wasm::ExternKind {
2334 2335 2336 2337 2338 2339 2340
  return static_cast<wasm::ExternKind>(kind);
}

// Generic

#define WASM_DEFINE_TYPE(name, Name)                        \
  WASM_DEFINE_OWN(name, Name)                               \
2341
  WASM_DEFINE_VEC_OWN(name, Name)                           \
2342 2343
                                                            \
  wasm_##name##_t* wasm_##name##_copy(wasm_##name##_t* t) { \
2344
    return release_##name(t->copy());                       \
2345 2346 2347 2348 2349 2350 2351
  }

// Value Types

WASM_DEFINE_TYPE(valtype, wasm::ValType)

wasm_valtype_t* wasm_valtype_new(wasm_valkind_t k) {
2352
  return release_valtype(wasm::ValType::make(reveal_valkind(k)));
2353 2354 2355
}

wasm_valkind_t wasm_valtype_kind(const wasm_valtype_t* t) {
2356
  return hide_valkind(t->kind());
2357 2358 2359 2360 2361 2362 2363 2364
}

// Function Types

WASM_DEFINE_TYPE(functype, wasm::FuncType)

wasm_functype_t* wasm_functype_new(wasm_valtype_vec_t* params,
                                   wasm_valtype_vec_t* results) {
2365 2366
  return release_functype(wasm::FuncType::make(adopt_valtype_vec(params),
                                               adopt_valtype_vec(results)));
2367 2368 2369
}

const wasm_valtype_vec_t* wasm_functype_params(const wasm_functype_t* ft) {
2370
  return hide_valtype_vec(ft->params());
2371 2372 2373
}

const wasm_valtype_vec_t* wasm_functype_results(const wasm_functype_t* ft) {
2374
  return hide_valtype_vec(ft->results());
2375 2376 2377 2378 2379 2380 2381 2382
}

// Global Types

WASM_DEFINE_TYPE(globaltype, wasm::GlobalType)

wasm_globaltype_t* wasm_globaltype_new(wasm_valtype_t* content,
                                       wasm_mutability_t mutability) {
2383
  return release_globaltype(wasm::GlobalType::make(
2384
      adopt_valtype(content), reveal_mutability(mutability)));
2385 2386 2387
}

const wasm_valtype_t* wasm_globaltype_content(const wasm_globaltype_t* gt) {
2388
  return hide_valtype(gt->content());
2389 2390 2391
}

wasm_mutability_t wasm_globaltype_mutability(const wasm_globaltype_t* gt) {
2392
  return hide_mutability(gt->mutability());
2393 2394 2395 2396 2397 2398 2399 2400
}

// Table Types

WASM_DEFINE_TYPE(tabletype, wasm::TableType)

wasm_tabletype_t* wasm_tabletype_new(wasm_valtype_t* element,
                                     const wasm_limits_t* limits) {
2401 2402
  return release_tabletype(
      wasm::TableType::make(adopt_valtype(element), reveal_limits(*limits)));
2403 2404 2405
}

const wasm_valtype_t* wasm_tabletype_element(const wasm_tabletype_t* tt) {
2406
  return hide_valtype(tt->element());
2407 2408 2409
}

const wasm_limits_t* wasm_tabletype_limits(const wasm_tabletype_t* tt) {
2410
  return hide_limits(tt->limits());
2411 2412 2413 2414 2415 2416 2417
}

// Memory Types

WASM_DEFINE_TYPE(memorytype, wasm::MemoryType)

wasm_memorytype_t* wasm_memorytype_new(const wasm_limits_t* limits) {
2418
  return release_memorytype(wasm::MemoryType::make(reveal_limits(*limits)));
2419 2420 2421
}

const wasm_limits_t* wasm_memorytype_limits(const wasm_memorytype_t* mt) {
2422
  return hide_limits(mt->limits());
2423 2424 2425 2426 2427 2428 2429
}

// Extern Types

WASM_DEFINE_TYPE(externtype, wasm::ExternType)

wasm_externkind_t wasm_externtype_kind(const wasm_externtype_t* et) {
2430
  return hide_externkind(et->kind());
2431 2432 2433
}

wasm_externtype_t* wasm_functype_as_externtype(wasm_functype_t* ft) {
2434
  return hide_externtype(static_cast<wasm::ExternType*>(ft));
2435 2436
}
wasm_externtype_t* wasm_globaltype_as_externtype(wasm_globaltype_t* gt) {
2437
  return hide_externtype(static_cast<wasm::ExternType*>(gt));
2438 2439
}
wasm_externtype_t* wasm_tabletype_as_externtype(wasm_tabletype_t* tt) {
2440
  return hide_externtype(static_cast<wasm::ExternType*>(tt));
2441 2442
}
wasm_externtype_t* wasm_memorytype_as_externtype(wasm_memorytype_t* mt) {
2443
  return hide_externtype(static_cast<wasm::ExternType*>(mt));
2444 2445 2446 2447
}

const wasm_externtype_t* wasm_functype_as_externtype_const(
    const wasm_functype_t* ft) {
2448
  return hide_externtype(static_cast<const wasm::ExternType*>(ft));
2449 2450 2451
}
const wasm_externtype_t* wasm_globaltype_as_externtype_const(
    const wasm_globaltype_t* gt) {
2452
  return hide_externtype(static_cast<const wasm::ExternType*>(gt));
2453 2454 2455
}
const wasm_externtype_t* wasm_tabletype_as_externtype_const(
    const wasm_tabletype_t* tt) {
2456
  return hide_externtype(static_cast<const wasm::ExternType*>(tt));
2457 2458 2459
}
const wasm_externtype_t* wasm_memorytype_as_externtype_const(
    const wasm_memorytype_t* mt) {
2460
  return hide_externtype(static_cast<const wasm::ExternType*>(mt));
2461 2462 2463 2464
}

wasm_functype_t* wasm_externtype_as_functype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_FUNC
2465 2466
             ? hide_functype(
                   static_cast<wasm::FuncType*>(reveal_externtype(et)))
2467 2468 2469 2470
             : nullptr;
}
wasm_globaltype_t* wasm_externtype_as_globaltype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_GLOBAL
2471 2472
             ? hide_globaltype(
                   static_cast<wasm::GlobalType*>(reveal_externtype(et)))
2473 2474 2475 2476
             : nullptr;
}
wasm_tabletype_t* wasm_externtype_as_tabletype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_TABLE
2477 2478
             ? hide_tabletype(
                   static_cast<wasm::TableType*>(reveal_externtype(et)))
2479 2480 2481 2482
             : nullptr;
}
wasm_memorytype_t* wasm_externtype_as_memorytype(wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_MEMORY
2483 2484
             ? hide_memorytype(
                   static_cast<wasm::MemoryType*>(reveal_externtype(et)))
2485 2486 2487 2488 2489 2490
             : nullptr;
}

const wasm_functype_t* wasm_externtype_as_functype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_FUNC
2491 2492
             ? hide_functype(
                   static_cast<const wasm::FuncType*>(reveal_externtype(et)))
2493 2494 2495 2496 2497
             : nullptr;
}
const wasm_globaltype_t* wasm_externtype_as_globaltype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_GLOBAL
2498 2499
             ? hide_globaltype(
                   static_cast<const wasm::GlobalType*>(reveal_externtype(et)))
2500 2501 2502 2503 2504
             : nullptr;
}
const wasm_tabletype_t* wasm_externtype_as_tabletype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_TABLE
2505 2506
             ? hide_tabletype(
                   static_cast<const wasm::TableType*>(reveal_externtype(et)))
2507 2508 2509 2510 2511
             : nullptr;
}
const wasm_memorytype_t* wasm_externtype_as_memorytype_const(
    const wasm_externtype_t* et) {
  return et->kind() == wasm::EXTERN_MEMORY
2512 2513
             ? hide_memorytype(
                   static_cast<const wasm::MemoryType*>(reveal_externtype(et)))
2514 2515 2516 2517 2518 2519 2520 2521 2522
             : 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) {
2523 2524
  return release_importtype(wasm::ImportType::make(
      adopt_byte_vec(module), adopt_byte_vec(name), adopt_externtype(type)));
2525 2526 2527
}

const wasm_name_t* wasm_importtype_module(const wasm_importtype_t* it) {
2528
  return hide_byte_vec(it->module());
2529 2530 2531
}

const wasm_name_t* wasm_importtype_name(const wasm_importtype_t* it) {
2532
  return hide_byte_vec(it->name());
2533 2534 2535
}

const wasm_externtype_t* wasm_importtype_type(const wasm_importtype_t* it) {
2536
  return hide_externtype(it->type());
2537 2538 2539 2540 2541 2542 2543 2544
}

// Export Types

WASM_DEFINE_TYPE(exporttype, wasm::ExportType)

wasm_exporttype_t* wasm_exporttype_new(wasm_name_t* name,
                                       wasm_externtype_t* type) {
2545 2546
  return release_exporttype(
      wasm::ExportType::make(adopt_byte_vec(name), adopt_externtype(type)));
2547 2548 2549
}

const wasm_name_t* wasm_exporttype_name(const wasm_exporttype_t* et) {
2550
  return hide_byte_vec(et->name());
2551 2552 2553
}

const wasm_externtype_t* wasm_exporttype_type(const wasm_exporttype_t* et) {
2554
  return hide_externtype(et->type());
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
}

///////////////////////////////////////////////////////////////////////////////
// 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) {    \
2566
    return release_##name(t->copy());                                \
2567 2568
  }                                                                  \
                                                                     \
2569 2570 2571 2572 2573
  bool wasm_##name##_same(const wasm_##name##_t* t1,                 \
                          const wasm_##name##_t* t2) {               \
    return t1->same(t2);                                             \
  }                                                                  \
                                                                     \
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
  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) {                   \
2589
    return hide_ref(static_cast<wasm::Ref*>(reveal_##name(r)));            \
2590 2591
  }                                                                        \
  wasm_##name##_t* wasm_ref_as_##name(wasm_ref_t* r) {                     \
2592
    return hide_##name(static_cast<Name*>(reveal_ref(r)));                 \
2593 2594 2595
  }                                                                        \
                                                                           \
  const wasm_ref_t* wasm_##name##_as_ref_const(const wasm_##name##_t* r) { \
2596
    return hide_ref(static_cast<const wasm::Ref*>(reveal_##name(r)));      \
2597 2598
  }                                                                        \
  const wasm_##name##_t* wasm_ref_as_##name##_const(const wasm_ref_t* r) { \
2599
    return hide_##name(static_cast<const Name*>(reveal_ref(r)));           \
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
  }

#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 {
2613
  return !is_ref(reveal_valkind(v.kind)) || !v.of.ref;
2614 2615
}

2616 2617
inline auto hide_val(wasm::Val v) -> wasm_val_t {
  wasm_val_t v2 = {hide_valkind(v.kind()), {}};
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
  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:
2633
      v2.of.ref = hide_ref(v.ref());
2634 2635 2636 2637 2638 2639 2640
      break;
    default:
      UNREACHABLE();
  }
  return v2;
}

2641 2642
inline auto release_val(wasm::Val v) -> wasm_val_t {
  wasm_val_t v2 = {hide_valkind(v.kind()), {}};
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
  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:
2658
      v2.of.ref = release_ref(v.release_ref());
2659 2660 2661 2662 2663 2664 2665
      break;
    default:
      UNREACHABLE();
  }
  return v2;
}

2666 2667
inline auto adopt_val(wasm_val_t v) -> wasm::Val {
  switch (reveal_valkind(v.kind)) {
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
    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:
2678
      return wasm::Val(adopt_ref(v.of.ref));
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
    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() {
2689
    if (it.is_ref()) it.release_ref().release();
2690 2691 2692
  }
};

2693
inline auto borrow_val(const wasm_val_t* v) -> borrowed_val {
2694
  wasm::Val v2;
2695
  switch (reveal_valkind(v->kind)) {
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
    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:
2710
      v2 = wasm::Val(adopt_ref(v->of.ref));
2711 2712 2713 2714 2715 2716 2717 2718 2719
      break;
    default:
      UNREACHABLE();
  }
  return borrowed_val(std::move(v2));
}

}  // extern "C++"

2720
WASM_DEFINE_VEC_BASE(val, wasm::Val, wasm::vec, )
2721 2722 2723 2724 2725

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) {
2726
    v2[i] = adopt_val(data[i]);
2727
  }
2728
  *out = release_val_vec(std::move(v2));
2729 2730 2731 2732 2733 2734 2735
}

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);
2736
    v2[i] = adopt_val(val);
2737
  }
2738
  *out = release_val_vec(std::move(v2));
2739 2740 2741
}

void wasm_val_delete(wasm_val_t* v) {
2742 2743
  if (is_ref(reveal_valkind(v->kind))) {
    adopt_ref(v->of.ref);
2744
  }
2745 2746 2747 2748
}

void wasm_val_copy(wasm_val_t* out, const wasm_val_t* v) {
  *out = *v;
2749
  if (is_ref(reveal_valkind(v->kind))) {
2750
    out->of.ref = v->of.ref ? release_ref(v->of.ref->copy()) : nullptr;
2751 2752 2753 2754 2755 2756
  }
}

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

2757 2758 2759
// Frames

WASM_DEFINE_OWN(frame, wasm::Frame)
2760
WASM_DEFINE_VEC_OWN(frame, wasm::Frame)
2761 2762

wasm_frame_t* wasm_frame_copy(const wasm_frame_t* frame) {
2763
  return release_frame(frame->copy());
2764 2765 2766 2767 2768 2769
}

wasm_instance_t* wasm_frame_instance(const wasm_frame_t* frame);
// Defined below along with wasm_instance_t.

uint32_t wasm_frame_func_index(const wasm_frame_t* frame) {
2770
  return reveal_frame(frame)->func_index();
2771 2772 2773
}

size_t wasm_frame_func_offset(const wasm_frame_t* frame) {
2774
  return reveal_frame(frame)->func_offset();
2775 2776 2777
}

size_t wasm_frame_module_offset(const wasm_frame_t* frame) {
2778
  return reveal_frame(frame)->module_offset();
2779 2780
}

2781 2782 2783 2784 2785
// Traps

WASM_DEFINE_REF(trap, wasm::Trap)

wasm_trap_t* wasm_trap_new(wasm_store_t* store, const wasm_message_t* message) {
2786 2787
  auto message_ = borrow_byte_vec(message);
  return release_trap(wasm::Trap::make(store, message_.it));
2788 2789 2790
}

void wasm_trap_message(const wasm_trap_t* trap, wasm_message_t* out) {
2791
  *out = release_byte_vec(reveal_trap(trap)->message());
2792 2793
}

2794
wasm_frame_t* wasm_trap_origin(const wasm_trap_t* trap) {
2795
  return release_frame(reveal_trap(trap)->origin());
2796 2797 2798
}

void wasm_trap_trace(const wasm_trap_t* trap, wasm_frame_vec_t* out) {
2799
  *out = release_frame_vec(reveal_trap(trap)->trace());
2800 2801
}

2802 2803 2804 2805 2806
// Foreign Objects

WASM_DEFINE_REF(foreign, wasm::Foreign)

wasm_foreign_t* wasm_foreign_new(wasm_store_t* store) {
2807
  return release_foreign(wasm::Foreign::make(store));
2808 2809 2810 2811 2812 2813 2814
}

// Modules

WASM_DEFINE_SHARABLE_REF(module, wasm::Module)

bool wasm_module_validate(wasm_store_t* store, const wasm_byte_vec_t* binary) {
2815
  auto binary_ = borrow_byte_vec(binary);
2816 2817 2818 2819 2820
  return wasm::Module::validate(store, binary_.it);
}

wasm_module_t* wasm_module_new(wasm_store_t* store,
                               const wasm_byte_vec_t* binary) {
2821 2822
  auto binary_ = borrow_byte_vec(binary);
  return release_module(wasm::Module::make(store, binary_.it));
2823 2824 2825 2826
}

void wasm_module_imports(const wasm_module_t* module,
                         wasm_importtype_vec_t* out) {
2827
  *out = release_importtype_vec(reveal_module(module)->imports());
2828 2829 2830 2831
}

void wasm_module_exports(const wasm_module_t* module,
                         wasm_exporttype_vec_t* out) {
2832
  *out = release_exporttype_vec(reveal_module(module)->exports());
2833 2834 2835
}

void wasm_module_serialize(const wasm_module_t* module, wasm_byte_vec_t* out) {
2836
  *out = release_byte_vec(reveal_module(module)->serialize());
2837 2838 2839 2840
}

wasm_module_t* wasm_module_deserialize(wasm_store_t* store,
                                       const wasm_byte_vec_t* binary) {
2841 2842
  auto binary_ = borrow_byte_vec(binary);
  return release_module(wasm::Module::deserialize(store, binary_.it));
2843 2844 2845
}

wasm_shared_module_t* wasm_module_share(const wasm_module_t* module) {
2846
  return release_shared_module(reveal_module(module)->share());
2847 2848 2849 2850
}

wasm_module_t* wasm_module_obtain(wasm_store_t* store,
                                  const wasm_shared_module_t* shared) {
2851
  return release_module(wasm::Module::obtain(store, shared));
2852 2853 2854 2855 2856 2857 2858 2859 2860
}

// Function Instances

WASM_DEFINE_REF(func, wasm::Func)

extern "C++" {

auto wasm_callback(void* env, const wasm::Val args[], wasm::Val results[])
2861
    -> wasm::own<wasm::Trap> {
2862
  auto f = reinterpret_cast<wasm_func_callback_t>(env);
2863
  return adopt_trap(f(hide_val_vec(args), hide_val_vec(results)));
2864 2865 2866 2867 2868 2869 2870 2871 2872
}

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[],
2873
                            wasm::Val results[]) -> wasm::own<wasm::Trap> {
2874
  auto t = static_cast<wasm_callback_env_t*>(env);
2875 2876
  return adopt_trap(
      t->callback(t->env, hide_val_vec(args), hide_val_vec(results)));
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888
}

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) {
2889 2890
  return release_func(wasm::Func::make(store, type, wasm_callback,
                                       reinterpret_cast<void*>(callback)));
2891 2892 2893 2894 2895 2896 2897
}

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};
2898 2899
  return release_func(wasm::Func::make(store, type, wasm_callback_with_env,
                                       env2, wasm_callback_env_finalizer));
2900 2901 2902
}

wasm_functype_t* wasm_func_type(const wasm_func_t* func) {
2903
  return release_functype(func->type());
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
}

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[]) {
2916 2917
  return release_trap(
      func->call(reveal_val_vec(args), reveal_val_vec(results)));
2918 2919 2920 2921 2922 2923 2924 2925 2926
}

// 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) {
2927 2928
  auto val_ = borrow_val(val);
  return release_global(wasm::Global::make(store, type, val_.it));
2929 2930 2931
}

wasm_globaltype_t* wasm_global_type(const wasm_global_t* global) {
2932
  return release_globaltype(global->type());
2933 2934 2935
}

void wasm_global_get(const wasm_global_t* global, wasm_val_t* out) {
2936
  *out = release_val(global->get());
2937 2938 2939
}

void wasm_global_set(wasm_global_t* global, const wasm_val_t* val) {
2940
  auto val_ = borrow_val(val);
2941 2942 2943 2944 2945 2946 2947 2948 2949
  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) {
2950
  return release_table(wasm::Table::make(store, type, ref));
2951 2952 2953
}

wasm_tabletype_t* wasm_table_type(const wasm_table_t* table) {
2954
  return release_tabletype(table->type());
2955 2956 2957
}

wasm_ref_t* wasm_table_get(const wasm_table_t* table, wasm_table_size_t index) {
2958
  return release_ref(table->get(index));
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980
}

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) {
2981
  return release_memory(wasm::Memory::make(store, type));
2982 2983 2984
}

wasm_memorytype_t* wasm_memory_type(const wasm_memory_t* memory) {
2985
  return release_memorytype(memory->type());
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
}

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)
3005
WASM_DEFINE_VEC_OWN(extern, wasm::Extern)
3006 3007

wasm_externkind_t wasm_extern_kind(const wasm_extern_t* external) {
3008
  return hide_externkind(external->kind());
3009 3010
}
wasm_externtype_t* wasm_extern_type(const wasm_extern_t* external) {
3011
  return release_externtype(external->type());
3012 3013 3014
}

wasm_extern_t* wasm_func_as_extern(wasm_func_t* func) {
3015
  return hide_extern(static_cast<wasm::Extern*>(reveal_func(func)));
3016 3017
}
wasm_extern_t* wasm_global_as_extern(wasm_global_t* global) {
3018
  return hide_extern(static_cast<wasm::Extern*>(reveal_global(global)));
3019 3020
}
wasm_extern_t* wasm_table_as_extern(wasm_table_t* table) {
3021
  return hide_extern(static_cast<wasm::Extern*>(reveal_table(table)));
3022 3023
}
wasm_extern_t* wasm_memory_as_extern(wasm_memory_t* memory) {
3024
  return hide_extern(static_cast<wasm::Extern*>(reveal_memory(memory)));
3025 3026 3027
}

const wasm_extern_t* wasm_func_as_extern_const(const wasm_func_t* func) {
3028
  return hide_extern(static_cast<const wasm::Extern*>(reveal_func(func)));
3029 3030
}
const wasm_extern_t* wasm_global_as_extern_const(const wasm_global_t* global) {
3031
  return hide_extern(static_cast<const wasm::Extern*>(reveal_global(global)));
3032 3033
}
const wasm_extern_t* wasm_table_as_extern_const(const wasm_table_t* table) {
3034
  return hide_extern(static_cast<const wasm::Extern*>(reveal_table(table)));
3035 3036
}
const wasm_extern_t* wasm_memory_as_extern_const(const wasm_memory_t* memory) {
3037
  return hide_extern(static_cast<const wasm::Extern*>(reveal_memory(memory)));
3038 3039 3040
}

wasm_func_t* wasm_extern_as_func(wasm_extern_t* external) {
3041
  return hide_func(external->func());
3042 3043
}
wasm_global_t* wasm_extern_as_global(wasm_extern_t* external) {
3044
  return hide_global(external->global());
3045 3046
}
wasm_table_t* wasm_extern_as_table(wasm_extern_t* external) {
3047
  return hide_table(external->table());
3048 3049
}
wasm_memory_t* wasm_extern_as_memory(wasm_extern_t* external) {
3050
  return hide_memory(external->memory());
3051 3052 3053
}

const wasm_func_t* wasm_extern_as_func_const(const wasm_extern_t* external) {
3054
  return hide_func(external->func());
3055 3056 3057
}
const wasm_global_t* wasm_extern_as_global_const(
    const wasm_extern_t* external) {
3058
  return hide_global(external->global());
3059 3060
}
const wasm_table_t* wasm_extern_as_table_const(const wasm_extern_t* external) {
3061
  return hide_table(external->table());
3062 3063 3064
}
const wasm_memory_t* wasm_extern_as_memory_const(
    const wasm_extern_t* external) {
3065
  return hide_memory(external->memory());
3066 3067 3068 3069 3070 3071 3072 3073
}

// Module Instances

WASM_DEFINE_REF(instance, wasm::Instance)

wasm_instance_t* wasm_instance_new(wasm_store_t* store,
                                   const wasm_module_t* module,
3074 3075 3076 3077 3078 3079 3080 3081
                                   const wasm_extern_t* const imports[],
                                   wasm_trap_t** trap) {
  wasm::own<wasm::Trap> error;
  wasm_instance_t* instance = release_instance(wasm::Instance::make(
      store, module, reinterpret_cast<const wasm::Extern* const*>(imports),
      &error));
  if (trap) *trap = hide_trap(error.release());
  return instance;
3082 3083 3084 3085
}

void wasm_instance_exports(const wasm_instance_t* instance,
                           wasm_extern_vec_t* out) {
3086
  *out = release_extern_vec(instance->exports());
3087 3088
}

3089
wasm_instance_t* wasm_frame_instance(const wasm_frame_t* frame) {
3090
  return hide_instance(reveal_frame(frame)->instance());
3091 3092
}

3093 3094 3095
#undef WASM_DEFINE_OWN
#undef WASM_DEFINE_VEC_BASE
#undef WASM_DEFINE_VEC_PLAIN
3096
#undef WASM_DEFINE_VEC_OWN
3097 3098 3099 3100 3101 3102
#undef WASM_DEFINE_TYPE
#undef WASM_DEFINE_REF_BASE
#undef WASM_DEFINE_REF
#undef WASM_DEFINE_SHARABLE_REF

}  // extern "C"