wasm-js.cc 80.5 KB
Newer Older
1 2 3 4
// Copyright 2015 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.

5 6
#include "src/wasm/wasm-js.h"

7 8
#include <string>

9
#include "src/api-inl.h"
10 11 12
#include "src/api-natives.h"
#include "src/assert-scope.h"
#include "src/ast/ast.h"
13
#include "src/base/overflowing-math.h"
14
#include "src/execution.h"
15
#include "src/handles.h"
16
#include "src/heap/factory.h"
17
#include "src/isolate.h"
18
#include "src/objects-inl.h"
19
#include "src/objects/js-promise-inl.h"
20
#include "src/objects/templates.h"
21
#include "src/parsing/parse-info.h"
22
#include "src/task-utils.h"
23
#include "src/trap-handler/trap-handler.h"
24
#include "src/v8.h"
25
#include "src/wasm/streaming-decoder.h"
26
#include "src/wasm/wasm-engine.h"
27
#include "src/wasm/wasm-limits.h"
28
#include "src/wasm/wasm-memory.h"
29
#include "src/wasm/wasm-objects-inl.h"
30
#include "src/wasm/wasm-serialization.h"
31 32 33 34 35

using v8::internal::wasm::ErrorThrower;

namespace v8 {

36 37
class WasmStreaming::WasmStreamingImpl {
 public:
38
  WasmStreamingImpl(
39
      Isolate* isolate, const char* api_method_name,
40 41 42 43 44 45
      std::shared_ptr<internal::wasm::CompilationResultResolver> resolver)
      : isolate_(isolate), resolver_(std::move(resolver)) {
    i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate_);
    auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
    streaming_decoder_ = i_isolate->wasm_engine()->StartStreamingCompilation(
        i_isolate, enabled_features, handle(i_isolate->context(), i_isolate),
46
        api_method_name, resolver_);
47 48 49
  }

  void OnBytesReceived(const uint8_t* bytes, size_t size) {
50
    streaming_decoder_->OnBytesReceived(i::VectorOf(bytes, size));
51 52
  }
  void Finish() { streaming_decoder_->Finish(); }
53

54 55 56 57 58 59 60 61 62 63 64 65
  void Abort(MaybeLocal<Value> exception) {
    i::HandleScope scope(reinterpret_cast<i::Isolate*>(isolate_));
    streaming_decoder_->Abort();

    // If no exception value is provided, we do not reject the promise. This can
    // happen when streaming compilation gets aborted when no script execution
    // is allowed anymore, e.g. when a browser tab gets refreshed.
    if (exception.IsEmpty()) return;

    resolver_->OnCompilationFailed(
        Utils::OpenHandle(*exception.ToLocalChecked()));
  }
66

67
  bool SetCompiledModuleBytes(const uint8_t* bytes, size_t size) {
68
    if (!i::wasm::IsSupportedVersion({bytes, size})) return false;
69 70 71
    return streaming_decoder_->SetCompiledModuleBytes({bytes, size});
  }

72 73
  void SetClient(std::shared_ptr<Client> client) {
    // There are no other event notifications so just pass client to decoder.
74 75 76 77 78 79
    // Wrap the client with a callback to trigger the callback in a new
    // foreground task.
    i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate_);
    v8::Platform* platform = i::V8::GetCurrentPlatform();
    std::shared_ptr<TaskRunner> foreground_task_runner =
        platform->GetForegroundTaskRunner(isolate_);
80
    streaming_decoder_->SetModuleCompiledCallback(
81 82 83 84 85 86
        [client, i_isolate, foreground_task_runner](
            const std::shared_ptr<i::wasm::NativeModule>& native_module) {
          foreground_task_runner->PostTask(
              i::MakeCancelableTask(i_isolate, [client, native_module] {
                client->OnModuleCompiled(Utils::Convert(native_module));
              }));
87 88 89
        });
  }

90
 private:
91
  Isolate* const isolate_;
92 93
  std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
  std::shared_ptr<internal::wasm::CompilationResultResolver> resolver_;
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
};

WasmStreaming::WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl)
    : impl_(std::move(impl)) {}

// The destructor is defined here because we have a unique_ptr with forward
// declaration.
WasmStreaming::~WasmStreaming() = default;

void WasmStreaming::OnBytesReceived(const uint8_t* bytes, size_t size) {
  impl_->OnBytesReceived(bytes, size);
}

void WasmStreaming::Finish() { impl_->Finish(); }

void WasmStreaming::Abort(MaybeLocal<Value> exception) {
  impl_->Abort(exception);
}

113 114 115 116
bool WasmStreaming::SetCompiledModuleBytes(const uint8_t* bytes, size_t size) {
  return impl_->SetCompiledModuleBytes(bytes, size);
}

117 118 119 120
void WasmStreaming::SetClient(std::shared_ptr<Client> client) {
  impl_->SetClient(client);
}

121 122 123 124 125 126 127 128 129
// static
std::shared_ptr<WasmStreaming> WasmStreaming::Unpack(Isolate* isolate,
                                                     Local<Value> value) {
  i::HandleScope scope(reinterpret_cast<i::Isolate*>(isolate));
  auto managed =
      i::Handle<i::Managed<WasmStreaming>>::cast(Utils::OpenHandle(*value));
  return managed->get();
}

130
namespace {
131

132 133 134 135 136 137 138 139 140
#define ASSIGN(type, var, expr)                      \
  Local<type> var;                                   \
  do {                                               \
    if (!expr.ToLocal(&var)) {                       \
      DCHECK(i_isolate->has_scheduled_exception());  \
      return;                                        \
    } else {                                         \
      DCHECK(!i_isolate->has_scheduled_exception()); \
    }                                                \
141 142
  } while (false)

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
// Like an ErrorThrower, but turns all pending exceptions into scheduled
// exceptions when going out of scope. Use this in API methods.
// Note that pending exceptions are not necessarily created by the ErrorThrower,
// but e.g. by the wasm start function. There might also be a scheduled
// exception, created by another API call (e.g. v8::Object::Get). But there
// should never be both pending and scheduled exceptions.
class ScheduledErrorThrower : public ErrorThrower {
 public:
  ScheduledErrorThrower(i::Isolate* isolate, const char* context)
      : ErrorThrower(isolate, context) {}

  ~ScheduledErrorThrower();
};

ScheduledErrorThrower::~ScheduledErrorThrower() {
  // There should never be both a pending and a scheduled exception.
  DCHECK(!isolate()->has_scheduled_exception() ||
         !isolate()->has_pending_exception());
  // Don't throw another error if there is already a scheduled error.
  if (isolate()->has_scheduled_exception()) {
    Reset();
  } else if (isolate()->has_pending_exception()) {
    Reset();
    isolate()->OptionalRescheduleException(false);
  } else if (error()) {
    isolate()->ScheduleThrow(*Reify());
  }
}

172 173 174 175 176 177 178
i::Handle<i::String> v8_str(i::Isolate* isolate, const char* str) {
  return isolate->factory()->NewStringFromAsciiChecked(str);
}
Local<String> v8_str(Isolate* isolate, const char* str) {
  return Utils::ToLocal(v8_str(reinterpret_cast<i::Isolate*>(isolate), str));
}

179 180 181 182 183 184 185 186 187 188 189 190
#define GET_FIRST_ARGUMENT_AS(Type)                                  \
  i::MaybeHandle<i::Wasm##Type##Object> GetFirstArgumentAs##Type(    \
      const v8::FunctionCallbackInfo<v8::Value>& args,               \
      ErrorThrower* thrower) {                                       \
    i::Handle<i::Object> arg0 = Utils::OpenHandle(*args[0]);         \
    if (!arg0->IsWasm##Type##Object()) {                             \
      thrower->TypeError("Argument 0 must be a WebAssembly." #Type); \
      return {};                                                     \
    }                                                                \
    Local<Object> obj = Local<Object>::Cast(args[0]);                \
    return i::Handle<i::Wasm##Type##Object>::cast(                   \
        v8::Utils::OpenHandle(*obj));                                \
191 192
  }

193 194
GET_FIRST_ARGUMENT_AS(Module)
GET_FIRST_ARGUMENT_AS(Memory)
195
GET_FIRST_ARGUMENT_AS(Table)
196
GET_FIRST_ARGUMENT_AS(Global)
197 198

#undef GET_FIRST_ARGUMENT_AS
199 200

i::wasm::ModuleWireBytes GetFirstArgumentAsBytes(
201 202
    const v8::FunctionCallbackInfo<v8::Value>& args, ErrorThrower* thrower,
    bool* is_shared) {
203
  const uint8_t* start = nullptr;
204
  size_t length = 0;
205
  v8::Local<v8::Value> source = args[0];
rossberg's avatar
rossberg committed
206
  if (source->IsArrayBuffer()) {
207
    // A raw array buffer was passed.
rossberg's avatar
rossberg committed
208
    Local<ArrayBuffer> buffer = Local<ArrayBuffer>::Cast(source);
209 210
    ArrayBuffer::Contents contents = buffer->GetContents();

211
    start = reinterpret_cast<const uint8_t*>(contents.Data());
212
    length = contents.ByteLength();
213
    *is_shared = buffer->IsSharedArrayBuffer();
rossberg's avatar
rossberg committed
214
  } else if (source->IsTypedArray()) {
215
    // A TypedArray was passed.
rossberg's avatar
rossberg committed
216
    Local<TypedArray> array = Local<TypedArray>::Cast(source);
217 218 219 220 221
    Local<ArrayBuffer> buffer = array->Buffer();

    ArrayBuffer::Contents contents = buffer->GetContents();

    start =
222
        reinterpret_cast<const uint8_t*>(contents.Data()) + array->ByteOffset();
223
    length = array->ByteLength();
224
    *is_shared = buffer->IsSharedArrayBuffer();
225
  } else {
226
    thrower->TypeError("Argument 0 must be a buffer source");
227
  }
228 229
  DCHECK_IMPLIES(length, start != nullptr);
  if (length == 0) {
230 231
    thrower->CompileError("BufferSource argument is empty");
  }
232 233 234 235 236 237
  if (length > i::wasm::kV8MaxWasmModuleSize) {
    thrower->RangeError("buffer source exceeds maximum size of %zu (is %zu)",
                        i::wasm::kV8MaxWasmModuleSize, length);
  }
  if (thrower->error()) return i::wasm::ModuleWireBytes(nullptr, nullptr);
  return i::wasm::ModuleWireBytes(start, start + length);
238 239
}

240
i::MaybeHandle<i::JSReceiver> GetValueAsImports(Local<Value> arg,
241 242
                                                ErrorThrower* thrower) {
  if (arg->IsUndefined()) return {};
243

244
  if (!arg->IsObject()) {
245 246 247
    thrower->TypeError("Argument 1 must be an object");
    return {};
  }
248
  Local<Object> obj = Local<Object>::Cast(arg);
249
  return i::Handle<i::JSReceiver>::cast(v8::Utils::OpenHandle(*obj));
250 251
}

252 253 254 255 256 257
namespace {
// This class resolves the result of WebAssembly.compile. It just places the
// compilation result in the supplied {promise}.
class AsyncCompilationResolver : public i::wasm::CompilationResultResolver {
 public:
  AsyncCompilationResolver(i::Isolate* isolate, i::Handle<i::JSPromise> promise)
258 259 260 261
      : promise_(isolate->global_handles()->Create(*promise)) {
    i::GlobalHandles::AnnotateStrongRetainer(promise_.location(),
                                             kGlobalPromiseHandle);
  }
262

263
  ~AsyncCompilationResolver() override {
264
    i::GlobalHandles::Destroy(promise_.location());
265 266 267
  }

  void OnCompilationSucceeded(i::Handle<i::WasmModuleObject> result) override {
268 269
    if (finished_) return;
    finished_ = true;
270 271 272 273 274 275 276
    i::MaybeHandle<i::Object> promise_result =
        i::JSPromise::Resolve(promise_, result);
    CHECK_EQ(promise_result.is_null(),
             promise_->GetIsolate()->has_pending_exception());
  }

  void OnCompilationFailed(i::Handle<i::Object> error_reason) override {
277 278
    if (finished_) return;
    finished_ = true;
279 280 281 282 283 284 285
    i::MaybeHandle<i::Object> promise_result =
        i::JSPromise::Reject(promise_, error_reason);
    CHECK_EQ(promise_result.is_null(),
             promise_->GetIsolate()->has_pending_exception());
  }

 private:
286 287
  static constexpr char kGlobalPromiseHandle[] =
      "AsyncCompilationResolver::promise_";
288
  bool finished_ = false;
289 290 291
  i::Handle<i::JSPromise> promise_;
};

292 293
constexpr char AsyncCompilationResolver::kGlobalPromiseHandle[];

294 295 296 297 298 299 300
// This class resolves the result of WebAssembly.instantiate(module, imports).
// It just places the instantiation result in the supplied {promise}.
class InstantiateModuleResultResolver
    : public i::wasm::InstantiationResultResolver {
 public:
  InstantiateModuleResultResolver(i::Isolate* isolate,
                                  i::Handle<i::JSPromise> promise)
301 302 303 304
      : promise_(isolate->global_handles()->Create(*promise)) {
    i::GlobalHandles::AnnotateStrongRetainer(promise_.location(),
                                             kGlobalPromiseHandle);
  }
305

306
  ~InstantiateModuleResultResolver() override {
307
    i::GlobalHandles::Destroy(promise_.location());
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  }

  void OnInstantiationSucceeded(
      i::Handle<i::WasmInstanceObject> instance) override {
    i::MaybeHandle<i::Object> promise_result =
        i::JSPromise::Resolve(promise_, instance);
    CHECK_EQ(promise_result.is_null(),
             promise_->GetIsolate()->has_pending_exception());
  }

  void OnInstantiationFailed(i::Handle<i::Object> error_reason) override {
    i::MaybeHandle<i::Object> promise_result =
        i::JSPromise::Reject(promise_, error_reason);
    CHECK_EQ(promise_result.is_null(),
             promise_->GetIsolate()->has_pending_exception());
  }

 private:
326 327
  static constexpr char kGlobalPromiseHandle[] =
      "InstantiateModuleResultResolver::promise_";
328 329 330
  i::Handle<i::JSPromise> promise_;
};

331 332
constexpr char InstantiateModuleResultResolver::kGlobalPromiseHandle[];

333 334 335 336 337 338 339 340 341 342 343
// This class resolves the result of WebAssembly.instantiate(bytes, imports).
// For that it creates a new {JSObject} which contains both the provided
// {WasmModuleObject} and the resulting {WebAssemblyInstanceObject} itself.
class InstantiateBytesResultResolver
    : public i::wasm::InstantiationResultResolver {
 public:
  InstantiateBytesResultResolver(i::Isolate* isolate,
                                 i::Handle<i::JSPromise> promise,
                                 i::Handle<i::WasmModuleObject> module)
      : isolate_(isolate),
        promise_(isolate_->global_handles()->Create(*promise)),
344 345 346 347 348 349
        module_(isolate_->global_handles()->Create(*module)) {
    i::GlobalHandles::AnnotateStrongRetainer(promise_.location(),
                                             kGlobalPromiseHandle);
    i::GlobalHandles::AnnotateStrongRetainer(module_.location(),
                                             kGlobalModuleHandle);
  }
350

351
  ~InstantiateBytesResultResolver() override {
352 353
    i::GlobalHandles::Destroy(promise_.location());
    i::GlobalHandles::Destroy(module_.location());
354 355 356 357 358 359 360 361 362 363 364
  }

  void OnInstantiationSucceeded(
      i::Handle<i::WasmInstanceObject> instance) override {
    // The result is a JSObject with 2 fields which contain the
    // WasmInstanceObject and the WasmModuleObject.
    i::Handle<i::JSObject> result =
        isolate_->factory()->NewJSObject(isolate_->object_function());

    i::Handle<i::String> instance_name =
        isolate_->factory()
365
            ->NewStringFromOneByte(i::StaticCharVector("instance"))
366 367 368 369
            .ToHandleChecked();

    i::Handle<i::String> module_name =
        isolate_->factory()
370
            ->NewStringFromOneByte(i::StaticCharVector("module"))
371 372
            .ToHandleChecked();

373 374 375
    i::JSObject::AddProperty(isolate_, result, instance_name, instance,
                             i::NONE);
    i::JSObject::AddProperty(isolate_, result, module_name, module_, i::NONE);
376 377 378 379 380 381 382 383 384 385 386 387 388

    i::MaybeHandle<i::Object> promise_result =
        i::JSPromise::Resolve(promise_, result);
    CHECK_EQ(promise_result.is_null(), isolate_->has_pending_exception());
  }

  void OnInstantiationFailed(i::Handle<i::Object> error_reason) override {
    i::MaybeHandle<i::Object> promise_result =
        i::JSPromise::Reject(promise_, error_reason);
    CHECK_EQ(promise_result.is_null(), isolate_->has_pending_exception());
  }

 private:
389 390 391 392
  static constexpr char kGlobalPromiseHandle[] =
      "InstantiateBytesResultResolver::promise_";
  static constexpr char kGlobalModuleHandle[] =
      "InstantiateBytesResultResolver::module_";
393 394 395 396 397
  i::Isolate* isolate_;
  i::Handle<i::JSPromise> promise_;
  i::Handle<i::WasmModuleObject> module_;
};

398 399 400
constexpr char InstantiateBytesResultResolver::kGlobalPromiseHandle[];
constexpr char InstantiateBytesResultResolver::kGlobalModuleHandle[];

401 402 403 404 405 406 407 408 409 410 411 412 413 414
// This class is the {CompilationResultResolver} for
// WebAssembly.instantiate(bytes, imports). When compilation finishes,
// {AsyncInstantiate} is started on the compilation result.
class AsyncInstantiateCompileResultResolver
    : public i::wasm::CompilationResultResolver {
 public:
  AsyncInstantiateCompileResultResolver(
      i::Isolate* isolate, i::Handle<i::JSPromise> promise,
      i::MaybeHandle<i::JSReceiver> maybe_imports)
      : isolate_(isolate),
        promise_(isolate_->global_handles()->Create(*promise)),
        maybe_imports_(maybe_imports.is_null()
                           ? maybe_imports
                           : isolate_->global_handles()->Create(
415 416 417 418 419 420 421 422
                                 *maybe_imports.ToHandleChecked())) {
    i::GlobalHandles::AnnotateStrongRetainer(promise_.location(),
                                             kGlobalPromiseHandle);
    if (!maybe_imports_.is_null()) {
      i::GlobalHandles::AnnotateStrongRetainer(
          maybe_imports_.ToHandleChecked().location(), kGlobalImportsHandle);
    }
  }
423

424
  ~AsyncInstantiateCompileResultResolver() override {
425
    i::GlobalHandles::Destroy(promise_.location());
426
    if (!maybe_imports_.is_null()) {
427
      i::GlobalHandles::Destroy(maybe_imports_.ToHandleChecked().location());
428 429 430 431
    }
  }

  void OnCompilationSucceeded(i::Handle<i::WasmModuleObject> result) override {
432 433
    if (finished_) return;
    finished_ = true;
434 435 436 437 438 439 440 441
    isolate_->wasm_engine()->AsyncInstantiate(
        isolate_,
        base::make_unique<InstantiateBytesResultResolver>(isolate_, promise_,
                                                          result),
        result, maybe_imports_);
  }

  void OnCompilationFailed(i::Handle<i::Object> error_reason) override {
442 443
    if (finished_) return;
    finished_ = true;
444 445 446 447 448 449
    i::MaybeHandle<i::Object> promise_result =
        i::JSPromise::Reject(promise_, error_reason);
    CHECK_EQ(promise_result.is_null(), isolate_->has_pending_exception());
  }

 private:
450 451 452 453
  static constexpr char kGlobalPromiseHandle[] =
      "AsyncInstantiateCompileResultResolver::promise_";
  static constexpr char kGlobalImportsHandle[] =
      "AsyncInstantiateCompileResultResolver::module_";
454
  bool finished_ = false;
455 456 457 458 459
  i::Isolate* isolate_;
  i::Handle<i::JSPromise> promise_;
  i::MaybeHandle<i::JSReceiver> maybe_imports_;
};

460 461
constexpr char AsyncInstantiateCompileResultResolver::kGlobalPromiseHandle[];
constexpr char AsyncInstantiateCompileResultResolver::kGlobalImportsHandle[];
462 463 464 465 466 467

std::string ToString(const char* name) { return std::string(name); }

std::string ToString(const i::Handle<i::String> name) {
  return std::string("Property '") + name->ToCString().get() + "'";
}
468

469 470 471
// Web IDL: '[EnforceRange] unsigned long'
// Previously called ToNonWrappingUint32 in the draft WebAssembly JS spec.
// https://heycam.github.io/webidl/#EnforceRange
472 473 474
template <typename T>
bool EnforceUint32(T argument_name, Local<v8::Value> v, Local<Context> context,
                   ErrorThrower* thrower, uint32_t* res) {
475 476 477
  double double_number;

  if (!v->NumberValue(context).To(&double_number)) {
478 479
    thrower->TypeError("%s must be convertible to a number",
                       ToString(argument_name).c_str());
480 481 482
    return false;
  }
  if (!std::isfinite(double_number)) {
483 484
    thrower->TypeError("%s must be convertible to a valid number",
                       ToString(argument_name).c_str());
485 486 487
    return false;
  }
  if (double_number < 0) {
488 489
    thrower->TypeError("%s must be non-negative",
                       ToString(argument_name).c_str());
490 491 492
    return false;
  }
  if (double_number > std::numeric_limits<uint32_t>::max()) {
493 494
    thrower->TypeError("%s must be in the unsigned long range",
                       ToString(argument_name).c_str());
495 496 497 498 499 500
    return false;
  }

  *res = static_cast<uint32_t>(double_number);
  return true;
}
501
}  // namespace
502

503
// WebAssembly.compile(bytes) -> Promise
rossberg's avatar
rossberg committed
504 505
void WebAssemblyCompile(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
506
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
507

rossberg's avatar
rossberg committed
508
  HandleScope scope(isolate);
509
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.compile()");
rossberg's avatar
rossberg committed
510

511 512 513 514
  if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
    thrower.CompileError("Wasm code generation disallowed by embedder");
  }

515
  Local<Context> context = isolate->GetCurrentContext();
516 517
  ASSIGN(Promise::Resolver, promise_resolver, Promise::Resolver::New(context));
  Local<Promise> promise = promise_resolver->GetPromise();
518
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
519 520
  return_value.Set(promise);

521
  std::shared_ptr<i::wasm::CompilationResultResolver> resolver(
522
      new AsyncCompilationResolver(i_isolate, Utils::OpenHandle(*promise)));
523

524 525
  bool is_shared = false;
  auto bytes = GetFirstArgumentAsBytes(args, &thrower, &is_shared);
526
  if (thrower.error()) {
527
    resolver->OnCompilationFailed(thrower.Reify());
528
    return;
529
  }
530
  // Asynchronous compilation handles copying wire bytes if necessary.
531 532 533
  auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
  i_isolate->wasm_engine()->AsyncCompile(i_isolate, enabled_features,
                                         std::move(resolver), bytes, is_shared);
rossberg's avatar
rossberg committed
534 535
}

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
void WasmStreamingCallbackForTesting(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);

  HandleScope scope(isolate);
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.compile()");

  std::shared_ptr<v8::WasmStreaming> streaming =
      v8::WasmStreaming::Unpack(args.GetIsolate(), args.Data());

  bool is_shared = false;
  i::wasm::ModuleWireBytes bytes =
      GetFirstArgumentAsBytes(args, &thrower, &is_shared);
  if (thrower.error()) {
    streaming->Abort(Utils::ToLocal(thrower.Reify()));
    return;
  }
  streaming->OnBytesReceived(bytes.start(), bytes.length());
  streaming->Finish();
  CHECK(!thrower.error());
}

void WasmStreamingPromiseFailedCallback(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  std::shared_ptr<v8::WasmStreaming> streaming =
      v8::WasmStreaming::Unpack(args.GetIsolate(), args.Data());
  streaming->Abort(args[0]);
}

566 567 568 569 570 571
// WebAssembly.compileStreaming(Promise<Response>) -> Promise
void WebAssemblyCompileStreaming(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
572 573
  const char* const kAPIMethodName = "WebAssembly.compileStreaming()";
  ScheduledErrorThrower thrower(i_isolate, kAPIMethodName);
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
  Local<Context> context = isolate->GetCurrentContext();

  // Create and assign the return value of this function.
  ASSIGN(Promise::Resolver, result_resolver, Promise::Resolver::New(context));
  Local<Promise> promise = result_resolver->GetPromise();
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(promise);

  // Prepare the CompilationResultResolver for the compilation.
  auto resolver = std::make_shared<AsyncCompilationResolver>(
      i_isolate, Utils::OpenHandle(*promise));

  if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
    thrower.CompileError("Wasm code generation disallowed by embedder");
    resolver->OnCompilationFailed(thrower.Reify());
    return;
  }

  // Allocate the streaming decoder in a Managed so we can pass it to the
  // embedder.
  i::Handle<i::Managed<WasmStreaming>> data =
      i::Managed<WasmStreaming>::Allocate(
          i_isolate, 0,
597 598
          base::make_unique<WasmStreaming::WasmStreamingImpl>(
              isolate, kAPIMethodName, resolver));
599 600 601 602 603 604

  DCHECK_NOT_NULL(i_isolate->wasm_streaming_callback());
  ASSIGN(
      v8::Function, compile_callback,
      v8::Function::New(context, i_isolate->wasm_streaming_callback(),
                        Utils::ToLocal(i::Handle<i::Object>::cast(data)), 1));
605 606 607 608
  ASSIGN(
      v8::Function, reject_callback,
      v8::Function::New(context, WasmStreamingPromiseFailedCallback,
                        Utils::ToLocal(i::Handle<i::Object>::cast(data)), 1));
609 610 611 612 613 614 615 616 617 618 619 620 621

  // The parameter may be of type {Response} or of type {Promise<Response>}.
  // Treat either case of parameter as Promise.resolve(parameter)
  // as per https://www.w3.org/2001/tag/doc/promises-guide#resolve-arguments

  // Ending with:
  //    return Promise.resolve(parameter).then(compile_callback);
  ASSIGN(Promise::Resolver, input_resolver, Promise::Resolver::New(context));
  if (!input_resolver->Resolve(context, args[0]).IsJust()) return;

  // We do not have any use of the result here. The {compile_callback} will
  // start streaming compilation, which will eventually resolve the promise we
  // set as result value.
622 623
  USE(input_resolver->GetPromise()->Then(context, compile_callback,
                                         reject_callback));
624 625
}

626
// WebAssembly.validate(bytes) -> bool
627 628
void WebAssemblyValidate(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
629
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
630
  HandleScope scope(isolate);
631
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.validate()");
632

633 634
  bool is_shared = false;
  auto bytes = GetFirstArgumentAsBytes(args, &thrower, &is_shared);
635 636

  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
637 638

  if (thrower.error()) {
639
    if (thrower.wasm_error()) thrower.Reset();  // Clear error.
640
    return_value.Set(v8::False(isolate));
641 642 643
    return;
  }

644
  auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
645 646 647 648 649 650 651
  bool validated = false;
  if (is_shared) {
    // Make a copy of the wire bytes to avoid concurrent modification.
    std::unique_ptr<uint8_t[]> copy(new uint8_t[bytes.length()]);
    memcpy(copy.get(), bytes.start(), bytes.length());
    i::wasm::ModuleWireBytes bytes_copy(copy.get(),
                                        copy.get() + bytes.length());
652 653
    validated = i_isolate->wasm_engine()->SyncValidate(
        i_isolate, enabled_features, bytes_copy);
654 655
  } else {
    // The wire bytes are not shared, OK to use them directly.
656 657
    validated = i_isolate->wasm_engine()->SyncValidate(i_isolate,
                                                       enabled_features, bytes);
658
  }
659 660

  return_value.Set(Boolean::New(isolate, validated));
661 662
}

663
// new WebAssembly.Module(bytes) -> WebAssembly.Module
rossberg's avatar
rossberg committed
664 665
void WebAssemblyModule(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
666
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
667 668
  if (i_isolate->wasm_module_callback()(args)) return;

rossberg's avatar
rossberg committed
669
  HandleScope scope(isolate);
670
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Module()");
rossberg's avatar
rossberg committed
671

672 673 674 675
  if (!args.IsConstructCall()) {
    thrower.TypeError("WebAssembly.Module must be invoked with 'new'");
    return;
  }
676 677 678 679 680
  if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
    thrower.CompileError("Wasm code generation disallowed by embedder");
    return;
  }

681 682
  bool is_shared = false;
  auto bytes = GetFirstArgumentAsBytes(args, &thrower, &is_shared);
683

684 685 686
  if (thrower.error()) {
    return;
  }
687
  auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
688 689 690 691 692 693 694
  i::MaybeHandle<i::Object> module_obj;
  if (is_shared) {
    // Make a copy of the wire bytes to avoid concurrent modification.
    std::unique_ptr<uint8_t[]> copy(new uint8_t[bytes.length()]);
    memcpy(copy.get(), bytes.start(), bytes.length());
    i::wasm::ModuleWireBytes bytes_copy(copy.get(),
                                        copy.get() + bytes.length());
695 696
    module_obj = i_isolate->wasm_engine()->SyncCompile(
        i_isolate, enabled_features, &thrower, bytes_copy);
697 698
  } else {
    // The wire bytes are not shared, OK to use them directly.
699 700
    module_obj = i_isolate->wasm_engine()->SyncCompile(
        i_isolate, enabled_features, &thrower, bytes);
701 702
  }

rossberg's avatar
rossberg committed
703 704 705 706 707 708
  if (module_obj.is_null()) return;

  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(Utils::ToLocal(module_obj.ToHandleChecked()));
}

709
// WebAssembly.Module.imports(module) -> Array<Import>
710 711 712 713
void WebAssemblyModuleImports(const v8::FunctionCallbackInfo<v8::Value>& args) {
  HandleScope scope(args.GetIsolate());
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
714
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Module.imports()");
715

716
  auto maybe_module = GetFirstArgumentAsModule(args, &thrower);
717 718 719
  if (thrower.error()) return;
  auto imports = i::wasm::GetImports(i_isolate, maybe_module.ToHandleChecked());
  args.GetReturnValue().Set(Utils::ToLocal(imports));
720 721
}

722
// WebAssembly.Module.exports(module) -> Array<Export>
723 724 725 726
void WebAssemblyModuleExports(const v8::FunctionCallbackInfo<v8::Value>& args) {
  HandleScope scope(args.GetIsolate());
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
727
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Module.exports()");
728

729
  auto maybe_module = GetFirstArgumentAsModule(args, &thrower);
730 731 732
  if (thrower.error()) return;
  auto exports = i::wasm::GetExports(i_isolate, maybe_module.ToHandleChecked());
  args.GetReturnValue().Set(Utils::ToLocal(exports));
733
}
734

735
// WebAssembly.Module.customSections(module, name) -> Array<Section>
736 737 738 739 740
void WebAssemblyModuleCustomSections(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  HandleScope scope(args.GetIsolate());
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
741 742
  ScheduledErrorThrower thrower(i_isolate,
                                "WebAssembly.Module.customSections()");
743

744
  auto maybe_module = GetFirstArgumentAsModule(args, &thrower);
745
  if (thrower.error()) return;
746

747 748 749 750 751
  if (args[1]->IsUndefined()) {
    thrower.TypeError("Argument 1 is required");
    return;
  }

752 753 754 755
  i::MaybeHandle<i::Object> maybe_name =
      i::Object::ToString(i_isolate, Utils::OpenHandle(*args[1]));
  i::Handle<i::Object> name;
  if (!maybe_name.ToHandle(&name)) return;
756 757 758 759 760
  auto custom_sections =
      i::wasm::GetCustomSections(i_isolate, maybe_module.ToHandleChecked(),
                                 i::Handle<i::String>::cast(name), &thrower);
  if (thrower.error()) return;
  args.GetReturnValue().Set(Utils::ToLocal(custom_sections));
761 762
}

763 764 765 766 767
MaybeLocal<Value> WebAssemblyInstantiateImpl(Isolate* isolate,
                                             Local<Value> module,
                                             Local<Value> ffi) {
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);

768 769
  i::MaybeHandle<i::Object> instance_object;
  {
770
    ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Instance()");
771 772 773 774 775 776 777 778 779

    // TODO(ahaas): These checks on the module should not be necessary here They
    // are just a workaround for https://crbug.com/837417.
    i::Handle<i::Object> module_obj = Utils::OpenHandle(*module);
    if (!module_obj->IsWasmModuleObject()) {
      thrower.TypeError("Argument 0 must be a WebAssembly.Module object");
      return {};
    }

780 781 782 783
    i::MaybeHandle<i::JSReceiver> maybe_imports =
        GetValueAsImports(ffi, &thrower);
    if (thrower.error()) return {};

784
    instance_object = i_isolate->wasm_engine()->SyncInstantiate(
785 786
        i_isolate, &thrower, i::Handle<i::WasmModuleObject>::cast(module_obj),
        maybe_imports, i::MaybeHandle<i::JSArrayBuffer>());
787
  }
788 789 790

  DCHECK_EQ(instance_object.is_null(), i_isolate->has_scheduled_exception());
  if (instance_object.is_null()) return {};
791 792 793
  return Utils::ToLocal(instance_object.ToHandleChecked());
}

794
// new WebAssembly.Instance(module, imports) -> WebAssembly.Instance
795
void WebAssemblyInstance(const v8::FunctionCallbackInfo<v8::Value>& args) {
796
  Isolate* isolate = args.GetIsolate();
797 798 799
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  i_isolate->CountUsage(
      v8::Isolate::UseCounterFeature::kWebAssemblyInstantiation);
800

rossberg's avatar
rossberg committed
801
  HandleScope scope(args.GetIsolate());
802 803
  if (i_isolate->wasm_instance_callback()(args)) return;

804
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Instance()");
805 806 807 808
  if (!args.IsConstructCall()) {
    thrower.TypeError("WebAssembly.Instance must be invoked with 'new'");
    return;
  }
809

810
  GetFirstArgumentAsModule(args, &thrower);
811
  if (thrower.error()) return;
812

813 814 815
  // If args.Length < 2, this will be undefined - see FunctionCallbackInfo.
  // We'll check for that in WebAssemblyInstantiateImpl.
  Local<Value> data = args[1];
816

817 818 819 820
  Local<Value> instance;
  if (WebAssemblyInstantiateImpl(isolate, args[0], data).ToLocal(&instance)) {
    args.GetReturnValue().Set(instance);
  }
821 822
}

823 824 825 826
void WebAssemblyInstantiateStreaming(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
827 828
  i_isolate->CountUsage(
      v8::Isolate::UseCounterFeature::kWebAssemblyInstantiation);
829

830
  HandleScope scope(isolate);
831
  Local<Context> context = isolate->GetCurrentContext();
832 833
  const char* const kAPIMethodName = "WebAssembly.instantiateStreaming()";
  ScheduledErrorThrower thrower(i_isolate, kAPIMethodName);
834

835 836 837 838 839
  // Create and assign the return value of this function.
  ASSIGN(Promise::Resolver, result_resolver, Promise::Resolver::New(context));
  Local<Promise> promise = result_resolver->GetPromise();
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(promise);
840

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
  // Create an InstantiateResultResolver in case there is an issue with the
  // passed parameters.
  std::unique_ptr<i::wasm::InstantiationResultResolver> resolver(
      new InstantiateModuleResultResolver(i_isolate,
                                          Utils::OpenHandle(*promise)));

  if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
    thrower.CompileError("Wasm code generation disallowed by embedder");
    resolver->OnInstantiationFailed(thrower.Reify());
    return;
  }

  // If args.Length < 2, this will be undefined - see FunctionCallbackInfo.
  Local<Value> ffi = args[1];
  i::MaybeHandle<i::JSReceiver> maybe_imports =
      GetValueAsImports(ffi, &thrower);

  if (thrower.error()) {
    resolver->OnInstantiationFailed(thrower.Reify());
    return;
  }

  // We start compilation now, we have no use for the
  // {InstantiationResultResolver}.
  resolver.reset();

  std::shared_ptr<i::wasm::CompilationResultResolver> compilation_resolver(
      new AsyncInstantiateCompileResultResolver(
          i_isolate, Utils::OpenHandle(*promise), maybe_imports));

  // Allocate the streaming decoder in a Managed so we can pass it to the
  // embedder.
  i::Handle<i::Managed<WasmStreaming>> data =
      i::Managed<WasmStreaming>::Allocate(
          i_isolate, 0,
          base::make_unique<WasmStreaming::WasmStreamingImpl>(
877
              isolate, kAPIMethodName, compilation_resolver));
878 879 880 881 882 883

  DCHECK_NOT_NULL(i_isolate->wasm_streaming_callback());
  ASSIGN(
      v8::Function, compile_callback,
      v8::Function::New(context, i_isolate->wasm_streaming_callback(),
                        Utils::ToLocal(i::Handle<i::Object>::cast(data)), 1));
884 885 886 887
  ASSIGN(
      v8::Function, reject_callback,
      v8::Function::New(context, WasmStreamingPromiseFailedCallback,
                        Utils::ToLocal(i::Handle<i::Object>::cast(data)), 1));
888 889 890 891 892 893 894 895 896 897 898 899 900

  // The parameter may be of type {Response} or of type {Promise<Response>}.
  // Treat either case of parameter as Promise.resolve(parameter)
  // as per https://www.w3.org/2001/tag/doc/promises-guide#resolve-arguments

  // Ending with:
  //    return Promise.resolve(parameter).then(compile_callback);
  ASSIGN(Promise::Resolver, input_resolver, Promise::Resolver::New(context));
  if (!input_resolver->Resolve(context, args[0]).IsJust()) return;

  // We do not have any use of the result here. The {compile_callback} will
  // start streaming compilation, which will eventually resolve the promise we
  // set as result value.
901 902
  USE(input_resolver->GetPromise()->Then(context, compile_callback,
                                         reject_callback));
903 904
}

905 906 907
// WebAssembly.instantiate(module, imports) -> WebAssembly.Instance
// WebAssembly.instantiate(bytes, imports) ->
//     {module: WebAssembly.Module, instance: WebAssembly.Instance}
908 909 910
void WebAssemblyInstantiate(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
911 912
  i_isolate->CountUsage(
      v8::Isolate::UseCounterFeature::kWebAssemblyInstantiation);
913

914
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.instantiate()");
915 916 917

  HandleScope scope(isolate);

918
  Local<Context> context = isolate->GetCurrentContext();
919

920 921
  ASSIGN(Promise::Resolver, promise_resolver, Promise::Resolver::New(context));
  Local<Promise> promise = promise_resolver->GetPromise();
922
  args.GetReturnValue().Set(promise);
923

924 925 926 927
  std::unique_ptr<i::wasm::InstantiationResultResolver> resolver(
      new InstantiateModuleResultResolver(i_isolate,
                                          Utils::OpenHandle(*promise)));

928 929
  Local<Value> first_arg_value = args[0];
  i::Handle<i::Object> first_arg = Utils::OpenHandle(*first_arg_value);
930 931 932
  if (!first_arg->IsJSObject()) {
    thrower.TypeError(
        "Argument 0 must be a buffer source or a WebAssembly.Module object");
933 934 935 936 937 938 939 940 941 942 943
    resolver->OnInstantiationFailed(thrower.Reify());
    return;
  }

  // If args.Length < 2, this will be undefined - see FunctionCallbackInfo.
  Local<Value> ffi = args[1];
  i::MaybeHandle<i::JSReceiver> maybe_imports =
      GetValueAsImports(ffi, &thrower);

  if (thrower.error()) {
    resolver->OnInstantiationFailed(thrower.Reify());
944 945
    return;
  }
946

947
  if (first_arg->IsWasmModuleObject()) {
948 949 950
    i::Handle<i::WasmModuleObject> module_obj =
        i::Handle<i::WasmModuleObject>::cast(first_arg);

951 952 953 954
    i_isolate->wasm_engine()->AsyncInstantiate(i_isolate, std::move(resolver),
                                               module_obj, maybe_imports);
    return;
  }
955

956 957 958 959
  bool is_shared = false;
  auto bytes = GetFirstArgumentAsBytes(args, &thrower, &is_shared);
  if (thrower.error()) {
    resolver->OnInstantiationFailed(thrower.Reify());
960
    return;
961
  }
962

963 964 965 966
  // We start compilation now, we have no use for the
  // {InstantiationResultResolver}.
  resolver.reset();

967
  std::shared_ptr<i::wasm::CompilationResultResolver> compilation_resolver(
968 969 970 971 972 973 974 975
      new AsyncInstantiateCompileResultResolver(
          i_isolate, Utils::OpenHandle(*promise), maybe_imports));

  // The first parameter is a buffer source, we have to check if we are allowed
  // to compile it.
  if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
    thrower.CompileError("Wasm code generation disallowed by embedder");
    compilation_resolver->OnCompilationFailed(thrower.Reify());
976
    return;
977 978 979
  }

  // Asynchronous compilation handles copying wire bytes if necessary.
980 981 982 983
  auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
  i_isolate->wasm_engine()->AsyncCompile(i_isolate, enabled_features,
                                         std::move(compilation_resolver), bytes,
                                         is_shared);
984
}
985 986

bool GetIntegerProperty(v8::Isolate* isolate, ErrorThrower* thrower,
987 988
                        Local<Context> context, v8::Local<v8::Value> value,
                        i::Handle<i::String> property_name, int64_t* result,
989
                        int64_t lower_bound, uint64_t upper_bound) {
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
  uint32_t number;
  if (!EnforceUint32(property_name, value, context, thrower, &number)) {
    return false;
  }
  if (number < lower_bound) {
    thrower->RangeError("Property '%s': value %" PRIu32
                        " is below the lower bound %" PRIx64,
                        property_name->ToCString().get(), number, lower_bound);
    return false;
  }
  if (number > upper_bound) {
    thrower->RangeError("Property '%s': value %" PRIu32
                        " is above the upper bound %" PRIu64,
                        property_name->ToCString().get(), number, upper_bound);
    return false;
  }

  *result = static_cast<int64_t>(number);
  return true;
}

bool GetOptionalIntegerProperty(v8::Isolate* isolate, ErrorThrower* thrower,
                                Local<Context> context,
                                Local<v8::Object> object,
1014 1015 1016
                                Local<String> property, bool* has_property,
                                int64_t* result, int64_t lower_bound,
                                uint64_t upper_bound) {
1017 1018 1019 1020 1021 1022 1023 1024
  v8::Local<v8::Value> value;
  if (!object->Get(context, property).ToLocal(&value)) {
    return false;
  }

  // Web IDL: dictionary presence
  // https://heycam.github.io/webidl/#dfn-present
  if (value->IsUndefined()) {
1025
    if (has_property != nullptr) *has_property = false;
1026 1027
    return true;
  }
1028

1029
  if (has_property != nullptr) *has_property = true;
1030 1031 1032 1033
  i::Handle<i::String> property_name = v8::Utils::OpenHandle(*property);

  return GetIntegerProperty(isolate, thrower, context, value, property_name,
                            result, lower_bound, upper_bound);
1034 1035
}

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
// Fetch 'initial' or 'minimum' property from object. If both are provided,
// 'initial' is used.
// TODO(aseemgarg): change behavior when the following bug is resolved:
// https://github.com/WebAssembly/js-types/issues/6
bool GetInitialOrMinimumProperty(v8::Isolate* isolate, ErrorThrower* thrower,
                                 Local<Context> context,
                                 Local<v8::Object> object, int64_t* result,
                                 int64_t lower_bound, uint64_t upper_bound) {
  bool has_initial = false;
  if (!GetOptionalIntegerProperty(isolate, thrower, context, object,
                                  v8_str(isolate, "initial"), &has_initial,
                                  result, lower_bound, upper_bound)) {
    return false;
  }
  auto enabled_features = i::wasm::WasmFeaturesFromFlags();
  if (!has_initial && enabled_features.type_reflection) {
    if (!GetOptionalIntegerProperty(isolate, thrower, context, object,
                                    v8_str(isolate, "minimum"), &has_initial,
                                    result, lower_bound, upper_bound)) {
      return false;
    }
  }
  if (!has_initial) {
    // TODO(aseemgarg): update error message when the spec issue is resolved.
    thrower->TypeError("Property 'initial' is required");
    return false;
  }
  return true;
}

1066
// new WebAssembly.Table(args) -> WebAssembly.Table
1067 1068
void WebAssemblyTable(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
1069
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1070
  HandleScope scope(isolate);
1071
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Module()");
1072 1073 1074 1075
  if (!args.IsConstructCall()) {
    thrower.TypeError("WebAssembly.Table must be invoked with 'new'");
    return;
  }
1076
  if (!args[0]->IsObject()) {
1077 1078 1079 1080
    thrower.TypeError("Argument 0 must be a table descriptor");
    return;
  }
  Local<Context> context = isolate->GetCurrentContext();
1081
  Local<v8::Object> descriptor = Local<Object>::Cast(args[0]);
1082
  i::wasm::ValueType type;
1083 1084 1085 1086 1087 1088 1089 1090
  // The descriptor's 'element'.
  {
    v8::MaybeLocal<v8::Value> maybe =
        descriptor->Get(context, v8_str(isolate, "element"));
    v8::Local<v8::Value> value;
    if (!maybe.ToLocal(&value)) return;
    v8::Local<v8::String> string;
    if (!value->ToString(context).ToLocal(&string)) return;
1091 1092 1093 1094 1095 1096 1097
    auto enabled_features = i::wasm::WasmFeaturesFromFlags();
    if (string->StringEquals(v8_str(isolate, "anyfunc"))) {
      type = i::wasm::kWasmAnyFunc;
    } else if (enabled_features.anyref &&
               string->StringEquals(v8_str(isolate, "anyref"))) {
      type = i::wasm::kWasmAnyRef;
    } else {
1098 1099 1100 1101
      thrower.TypeError("Descriptor property 'element' must be 'anyfunc'");
      return;
    }
  }
1102

1103
  int64_t initial = 0;
1104 1105 1106
  if (!GetInitialOrMinimumProperty(isolate, &thrower, context, descriptor,
                                   &initial, 0,
                                   i::wasm::max_table_init_entries())) {
1107 1108 1109
    return;
  }
  // The descriptor's 'maximum'.
1110
  int64_t maximum = -1;
1111 1112 1113 1114
  bool has_maximum = true;
  if (!GetOptionalIntegerProperty(
          isolate, &thrower, context, descriptor, v8_str(isolate, "maximum"),
          &has_maximum, &maximum, initial, i::wasm::max_table_init_entries())) {
1115
    return;
1116 1117
  }

1118
  i::Handle<i::FixedArray> fixed_array;
1119 1120 1121
  i::Handle<i::JSObject> table_obj = i::WasmTableObject::New(
      i_isolate, type, static_cast<uint32_t>(initial), has_maximum,
      static_cast<uint32_t>(maximum), &fixed_array);
1122 1123 1124
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(Utils::ToLocal(table_obj));
}
1125

1126 1127
void WebAssemblyMemory(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
1128
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1129
  HandleScope scope(isolate);
1130
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Memory()");
1131 1132 1133 1134
  if (!args.IsConstructCall()) {
    thrower.TypeError("WebAssembly.Memory must be invoked with 'new'");
    return;
  }
1135
  if (!args[0]->IsObject()) {
1136
    thrower.TypeError("Argument 0 must be a memory descriptor");
1137 1138 1139
    return;
  }
  Local<Context> context = isolate->GetCurrentContext();
1140
  Local<v8::Object> descriptor = Local<Object>::Cast(args[0]);
1141

1142
  int64_t initial = 0;
1143 1144
  if (!GetInitialOrMinimumProperty(isolate, &thrower, context, descriptor,
                                   &initial, 0, i::wasm::max_mem_pages())) {
1145 1146
    return;
  }
1147
  // The descriptor's 'maximum'.
1148
  int64_t maximum = -1;
1149
  if (!GetOptionalIntegerProperty(isolate, &thrower, context, descriptor,
1150 1151
                                  v8_str(isolate, "maximum"), nullptr, &maximum,
                                  initial, i::wasm::kSpecMaxWasmMemoryPages)) {
1152
    return;
1153
  }
1154 1155

  bool is_shared_memory = false;
1156 1157
  auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
  if (enabled_features.threads) {
1158 1159
    // Shared property of descriptor
    Local<String> shared_key = v8_str(isolate, "shared");
1160 1161 1162 1163 1164
    v8::MaybeLocal<v8::Value> maybe_value =
        descriptor->Get(context, shared_key);
    v8::Local<v8::Value> value;
    if (maybe_value.ToLocal(&value)) {
      is_shared_memory = value->BooleanValue(isolate);
1165 1166 1167 1168 1169
    }
    // Throw TypeError if shared is true, and the descriptor has no "maximum"
    if (is_shared_memory && maximum == -1) {
      thrower.TypeError(
          "If shared is true, maximum property should be defined.");
1170
      return;
1171 1172 1173
    }
  }

1174 1175 1176 1177 1178
  i::Handle<i::JSObject> memory_obj;
  if (!i::WasmMemoryObject::New(i_isolate, static_cast<uint32_t>(initial),
                                static_cast<uint32_t>(maximum),
                                is_shared_memory)
           .ToHandle(&memory_obj)) {
1179 1180 1181
    thrower.RangeError("could not allocate memory");
    return;
  }
1182 1183 1184 1185
  if (is_shared_memory) {
    i::Handle<i::JSArrayBuffer> buffer(
        i::Handle<i::WasmMemoryObject>::cast(memory_obj)->array_buffer(),
        i_isolate);
1186
    Maybe<bool> result =
1187
        buffer->SetIntegrityLevel(buffer, i::FROZEN, i::kDontThrow);
1188 1189 1190
    if (!result.FromJust()) {
      thrower.TypeError(
          "Status of setting SetIntegrityLevel of buffer is false.");
1191
      return;
1192 1193
    }
  }
1194
  args.GetReturnValue().Set(Utils::ToLocal(memory_obj));
1195
}
1196

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
void WebAssemblyGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Global()");
  if (!args.IsConstructCall()) {
    thrower.TypeError("WebAssembly.Global must be invoked with 'new'");
    return;
  }
  if (!args[0]->IsObject()) {
    thrower.TypeError("Argument 0 must be a global descriptor");
    return;
  }
  Local<Context> context = isolate->GetCurrentContext();
  Local<v8::Object> descriptor = Local<Object>::Cast(args[0]);

  // The descriptor's 'mutable'.
  bool is_mutable = false;
  {
    Local<String> mutable_key = v8_str(isolate, "mutable");
    v8::MaybeLocal<v8::Value> maybe = descriptor->Get(context, mutable_key);
    v8::Local<v8::Value> value;
    if (maybe.ToLocal(&value)) {
1220
      is_mutable = value->BooleanValue(isolate);
1221 1222 1223
    }
  }

1224 1225 1226
  // The descriptor's type, called 'value'. It is called 'value' because this
  // descriptor is planned to be re-used as the global's type for reflection,
  // so calling it 'type' is redundant.
1227 1228 1229
  i::wasm::ValueType type;
  {
    v8::MaybeLocal<v8::Value> maybe =
1230
        descriptor->Get(context, v8_str(isolate, "value"));
1231 1232 1233 1234 1235
    v8::Local<v8::Value> value;
    if (!maybe.ToLocal(&value)) return;
    v8::Local<v8::String> string;
    if (!value->ToString(context).ToLocal(&string)) return;

1236
    auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
1237
    if (string->StringEquals(v8_str(isolate, "i32"))) {
1238
      type = i::wasm::kWasmI32;
1239
    } else if (string->StringEquals(v8_str(isolate, "f32"))) {
1240
      type = i::wasm::kWasmF32;
1241
    } else if (string->StringEquals(v8_str(isolate, "i64"))) {
1242
      type = i::wasm::kWasmI64;
1243
    } else if (string->StringEquals(v8_str(isolate, "f64"))) {
1244
      type = i::wasm::kWasmF64;
1245 1246
    } else if (enabled_features.anyref &&
               string->StringEquals(v8_str(isolate, "anyref"))) {
1247
      type = i::wasm::kWasmAnyRef;
1248 1249
    } else if (enabled_features.anyref &&
               string->StringEquals(v8_str(isolate, "anyfunc"))) {
1250
      type = i::wasm::kWasmAnyFunc;
1251
    } else {
1252 1253 1254
      thrower.TypeError(
          "Descriptor property 'value' must be 'i32', 'i64', 'f32', or "
          "'f64'");
1255 1256 1257 1258
      return;
    }
  }

1259 1260 1261
  const uint32_t offset = 0;
  i::MaybeHandle<i::WasmGlobalObject> maybe_global_obj =
      i::WasmGlobalObject::New(i_isolate, i::MaybeHandle<i::JSArrayBuffer>(),
1262 1263
                               i::MaybeHandle<i::FixedArray>(), type, offset,
                               is_mutable);
1264 1265 1266 1267 1268 1269 1270

  i::Handle<i::WasmGlobalObject> global_obj;
  if (!maybe_global_obj.ToHandle(&global_obj)) {
    thrower.RangeError("could not allocate memory");
    return;
  }

1271 1272 1273 1274 1275 1276
  // Convert value to a WebAssembly value, the default value is 0.
  Local<v8::Value> value = Local<Value>::Cast(args[1]);
  switch (type) {
    case i::wasm::kWasmI32: {
      int32_t i32_value = 0;
      if (!value->IsUndefined()) {
1277 1278 1279 1280
        v8::Local<v8::Int32> int32_value;
        if (!value->ToInt32(context).ToLocal(&int32_value)) return;
        if (!int32_value->Int32Value(context).To(&i32_value)) return;
      }
1281 1282 1283
      global_obj->SetI32(i32_value);
      break;
    }
1284 1285 1286
    case i::wasm::kWasmI64: {
      int64_t i64_value = 0;
      if (!value->IsUndefined()) {
1287 1288 1289 1290 1291 1292
        auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
        if (!enabled_features.bigint) {
          thrower.TypeError("Can't set the value of i64 WebAssembly.Global");
          return;
        }

1293 1294 1295 1296 1297 1298 1299
        v8::Local<v8::BigInt> bigint_value;
        if (!value->ToBigInt(context).ToLocal(&bigint_value)) return;
        i64_value = bigint_value->Int64Value();
      }
      global_obj->SetI64(i64_value);
      break;
    }
1300 1301 1302
    case i::wasm::kWasmF32: {
      float f32_value = 0;
      if (!value->IsUndefined()) {
1303 1304 1305 1306
        double f64_value = 0;
        v8::Local<v8::Number> number_value;
        if (!value->ToNumber(context).ToLocal(&number_value)) return;
        if (!number_value->NumberValue(context).To(&f64_value)) return;
1307
        f32_value = static_cast<float>(f64_value);
1308
      }
1309 1310 1311 1312 1313 1314
      global_obj->SetF32(f32_value);
      break;
    }
    case i::wasm::kWasmF64: {
      double f64_value = 0;
      if (!value->IsUndefined()) {
1315 1316 1317 1318
        v8::Local<v8::Number> number_value;
        if (!value->ToNumber(context).ToLocal(&number_value)) return;
        if (!number_value->NumberValue(context).To(&f64_value)) return;
      }
1319 1320
      global_obj->SetF64(f64_value);
      break;
1321
    }
1322 1323 1324 1325
    case i::wasm::kWasmAnyRef: {
      if (args.Length() < 2) {
        // When no inital value is provided, we have to use the WebAssembly
        // default value 'null', and not the JS default value 'undefined'.
1326
        global_obj->SetAnyRef(i_isolate->factory()->null_value());
1327 1328 1329 1330 1331
        break;
      }
      global_obj->SetAnyRef(Utils::OpenHandle(*value));
      break;
    }
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    case i::wasm::kWasmAnyFunc: {
      if (args.Length() < 2) {
        // When no inital value is provided, we have to use the WebAssembly
        // default value 'null', and not the JS default value 'undefined'.
        global_obj->SetAnyFunc(i_isolate, i_isolate->factory()->null_value());
        break;
      }

      if (!global_obj->SetAnyFunc(i_isolate, Utils::OpenHandle(*value))) {
        thrower.TypeError(
            "The value of anyfunc globals must be null or an "
            "exported function");
      }
      break;
    }
1347 1348
    default:
      UNREACHABLE();
1349 1350 1351 1352
  }

  i::Handle<i::JSObject> global_js_object(global_obj);
  args.GetReturnValue().Set(Utils::ToLocal(global_js_object));
1353 1354
}

1355 1356 1357 1358 1359
// WebAssembly.Exception
void WebAssemblyException(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
1360
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Exception()");
1361 1362 1363
  thrower.TypeError("WebAssembly.Exception cannot be called");
}

1364
constexpr const char* kName_WasmGlobalObject = "WebAssembly.Global";
1365 1366 1367
constexpr const char* kName_WasmMemoryObject = "WebAssembly.Memory";
constexpr const char* kName_WasmInstanceObject = "WebAssembly.Instance";
constexpr const char* kName_WasmTableObject = "WebAssembly.Table";
1368 1369 1370 1371 1372 1373

#define EXTRACT_THIS(var, WasmType)                                  \
  i::Handle<i::WasmType> var;                                        \
  {                                                                  \
    i::Handle<i::Object> this_arg = Utils::OpenHandle(*args.This()); \
    if (!this_arg->Is##WasmType()) {                                 \
1374
      thrower.TypeError("Receiver is not a %s", kName_##WasmType);   \
1375 1376 1377 1378 1379
      return;                                                        \
    }                                                                \
    var = i::Handle<i::WasmType>::cast(this_arg);                    \
  }

1380 1381 1382 1383 1384
void WebAssemblyInstanceGetExports(
  const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
1385
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Instance.exports()");
1386
  EXTRACT_THIS(receiver, WasmInstanceObject);
1387
  i::Handle<i::JSObject> exports_object(receiver->exports_object(), i_isolate);
1388 1389 1390
  args.GetReturnValue().Set(Utils::ToLocal(exports_object));
}

1391 1392
void WebAssemblyTableGetLength(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1393
  v8::Isolate* isolate = args.GetIsolate();
1394 1395
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
1396
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Table.length()");
1397
  EXTRACT_THIS(receiver, WasmTableObject);
1398 1399
  args.GetReturnValue().Set(
      v8::Number::New(isolate, receiver->current_length()));
1400
}
1401

1402
// WebAssembly.Table.grow(num) -> num
1403
void WebAssemblyTableGrow(const v8::FunctionCallbackInfo<v8::Value>& args) {
1404
  v8::Isolate* isolate = args.GetIsolate();
1405 1406
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
1407
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Table.grow()");
1408
  Local<Context> context = isolate->GetCurrentContext();
1409
  EXTRACT_THIS(receiver, WasmTableObject);
1410

1411 1412 1413 1414 1415
  uint32_t grow_by;
  if (!EnforceUint32("Argument 0", args[0], context, &thrower, &grow_by)) {
    return;
  }

1416 1417
  int old_size = i::WasmTableObject::Grow(i_isolate, receiver, grow_by,
                                          i_isolate->factory()->null_value());
1418

1419 1420
  if (old_size < 0) {
    thrower.RangeError("failed to grow table by %u", grow_by);
1421 1422
    return;
  }
1423 1424
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(old_size);
1425
}
1426

1427
// WebAssembly.Table.get(num) -> JSFunction
1428
void WebAssemblyTableGet(const v8::FunctionCallbackInfo<v8::Value>& args) {
1429
  v8::Isolate* isolate = args.GetIsolate();
1430
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1431
  HandleScope scope(isolate);
1432
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Table.get()");
1433
  Local<Context> context = isolate->GetCurrentContext();
1434
  EXTRACT_THIS(receiver, WasmTableObject);
1435 1436 1437 1438 1439

  uint32_t index;
  if (!EnforceUint32("Argument 0", args[0], context, &thrower, &index)) {
    return;
  }
1440 1441
  if (!i::WasmTableObject::IsInBounds(i_isolate, receiver, index)) {
    thrower.RangeError("invalid index %u into function table", index);
1442
    return;
1443
  }
1444

1445 1446 1447
  i::Handle<i::Object> result =
      i::WasmTableObject::Get(i_isolate, receiver, index);

1448
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
1449
  return_value.Set(Utils::ToLocal(result));
1450
}
1451

1452
// WebAssembly.Table.set(num, JSFunction)
1453
void WebAssemblyTableSet(const v8::FunctionCallbackInfo<v8::Value>& args) {
1454
  v8::Isolate* isolate = args.GetIsolate();
1455
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1456
  HandleScope scope(isolate);
1457
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Table.set()");
1458
  Local<Context> context = isolate->GetCurrentContext();
1459
  EXTRACT_THIS(table_object, WasmTableObject);
1460

1461
  // Parameter 0.
1462 1463 1464 1465
  uint32_t index;
  if (!EnforceUint32("Argument 0", args[0], context, &thrower, &index)) {
    return;
  }
1466 1467
  if (!i::WasmTableObject::IsInBounds(i_isolate, table_object, index)) {
    thrower.RangeError("invalid index %u into function table", index);
1468 1469
    return;
  }
1470

1471 1472 1473
  i::Handle<i::Object> element = Utils::OpenHandle(*args[1]);
  if (!i::WasmTableObject::IsValidElement(i_isolate, table_object, element)) {
    thrower.TypeError("Argument 1 must be null or a WebAssembly function");
1474 1475
    return;
  }
1476
  i::WasmTableObject::Set(i_isolate, table_object, index, element);
1477
}
1478

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
// WebAssembly.Table.type(WebAssembly.Table) -> TableType
void WebAssemblyTableGetType(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  HandleScope scope(isolate);
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Table.type()");

  auto maybe_table = GetFirstArgumentAsTable(args, &thrower);
  if (thrower.error()) return;
  i::Handle<i::WasmTableObject> table = maybe_table.ToHandleChecked();
  v8::Local<v8::Object> ret = v8::Object::New(isolate);

  Local<String> element;
  auto enabled_features = i::wasm::WasmFeaturesFromFlags();
  if (table->type() == i::wasm::ValueType::kWasmAnyFunc) {
    element = v8_str(isolate, "anyfunc");
  } else if (enabled_features.anyref &&
             table->type() == i::wasm::ValueType::kWasmAnyRef) {
    element = v8_str(isolate, "anyref");
  } else {
    UNREACHABLE();
  }
  // TODO(aseemgarg): update anyfunc to funcref
  if (!ret->CreateDataProperty(isolate->GetCurrentContext(),
                               v8_str(isolate, "element"), element)
           .IsJust()) {
    return;
  }

  uint32_t curr_size = table->current_length();
  DCHECK_LE(curr_size, std::numeric_limits<uint32_t>::max());
  if (!ret->CreateDataProperty(isolate->GetCurrentContext(),
                               v8_str(isolate, "minimum"),
                               v8::Integer::NewFromUnsigned(
                                   isolate, static_cast<uint32_t>(curr_size)))
           .IsJust()) {
    return;
  }

  if (!table->maximum_length()->IsUndefined()) {
    uint64_t max_size = table->maximum_length()->Number();
    DCHECK_LE(max_size, std::numeric_limits<uint32_t>::max());
    if (!ret->CreateDataProperty(isolate->GetCurrentContext(),
                                 v8_str(isolate, "maximum"),
                                 v8::Integer::NewFromUnsigned(
                                     isolate, static_cast<uint32_t>(max_size)))
             .IsJust()) {
      return;
    }
  }

  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(ret);
}

1534
// WebAssembly.Memory.grow(num) -> num
1535
void WebAssemblyMemoryGrow(const v8::FunctionCallbackInfo<v8::Value>& args) {
1536
  v8::Isolate* isolate = args.GetIsolate();
1537
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1538
  HandleScope scope(isolate);
1539
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Memory.grow()");
1540
  Local<Context> context = isolate->GetCurrentContext();
1541 1542
  EXTRACT_THIS(receiver, WasmMemoryObject);

1543 1544 1545 1546
  uint32_t delta_size;
  if (!EnforceUint32("Argument 0", args[0], context, &thrower, &delta_size)) {
    return;
  }
1547

1548 1549
  uint64_t max_size64 = receiver->maximum_pages();
  if (max_size64 > uint64_t{i::wasm::max_mem_pages()}) {
1550
    max_size64 = i::wasm::max_mem_pages();
1551
  }
1552
  i::Handle<i::JSArrayBuffer> old_buffer(receiver->array_buffer(), i_isolate);
1553 1554 1555 1556 1557 1558 1559 1560

  DCHECK_LE(max_size64, std::numeric_limits<uint32_t>::max());

  uint64_t old_size64 = old_buffer->byte_length() / i::wasm::kWasmPageSize;
  uint64_t new_size64 = old_size64 + static_cast<uint64_t>(delta_size);

  if (new_size64 > max_size64) {
    thrower.RangeError("Maximum memory size exceeded");
1561 1562
    return;
  }
1563 1564

  int32_t ret = i::WasmMemoryObject::Grow(i_isolate, receiver, delta_size);
1565
  if (ret == -1) {
1566
    thrower.RangeError("Unable to grow instance memory.");
1567 1568 1569 1570
    return;
  }
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(ret);
1571
}
1572

1573
// WebAssembly.Memory.buffer -> ArrayBuffer
1574 1575 1576
void WebAssemblyMemoryGetBuffer(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
1577
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1578
  HandleScope scope(isolate);
1579
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Memory.buffer");
1580 1581
  EXTRACT_THIS(receiver, WasmMemoryObject);

1582 1583
  i::Handle<i::Object> buffer_obj(receiver->array_buffer(), i_isolate);
  DCHECK(buffer_obj->IsJSArrayBuffer());
1584 1585
  i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(*buffer_obj),
                                     i_isolate);
1586 1587 1588 1589 1590
  if (buffer->is_shared()) {
    // TODO(gdeepti): More needed here for when cached buffer, and current
    // buffer are out of sync, handle that here when bounds checks, and Grow
    // are handled correctly.
    Maybe<bool> result =
1591
        buffer->SetIntegrityLevel(buffer, i::FROZEN, i::kDontThrow);
1592 1593 1594 1595 1596
    if (!result.FromJust()) {
      thrower.TypeError(
          "Status of setting SetIntegrityLevel of buffer is false.");
    }
  }
1597 1598 1599
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(Utils::ToLocal(buffer));
}
1600

1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
// WebAssembly.Memory.type(WebAssembly.Memory) -> MemoryType
void WebAssemblyMemoryGetType(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  HandleScope scope(isolate);
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Memory.type()");

  auto maybe_memory = GetFirstArgumentAsMemory(args, &thrower);
  if (thrower.error()) return;
  i::Handle<i::WasmMemoryObject> memory = maybe_memory.ToHandleChecked();
  v8::Local<v8::Object> ret = v8::Object::New(isolate);
  i::Handle<i::JSArrayBuffer> buffer(memory->array_buffer(), i_isolate);

  size_t curr_size = buffer->byte_length() / i::wasm::kWasmPageSize;
  DCHECK_LE(curr_size, std::numeric_limits<uint32_t>::max());
  if (!ret->CreateDataProperty(isolate->GetCurrentContext(),
                               v8_str(isolate, "minimum"),
                               v8::Integer::NewFromUnsigned(
                                   isolate, static_cast<uint32_t>(curr_size)))
           .IsJust()) {
    return;
  }

  if (memory->has_maximum_pages()) {
    uint64_t max_size = memory->maximum_pages();
    DCHECK_LE(max_size, std::numeric_limits<uint32_t>::max());
    if (!ret->CreateDataProperty(isolate->GetCurrentContext(),
                                 v8_str(isolate, "maximum"),
                                 v8::Integer::NewFromUnsigned(
                                     isolate, static_cast<uint32_t>(max_size)))
             .IsJust()) {
      return;
    }
  }

  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(ret);
}

1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
void WebAssemblyGlobalGetValueCommon(
    const v8::FunctionCallbackInfo<v8::Value>& args, const char* name) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
  ScheduledErrorThrower thrower(i_isolate, name);
  EXTRACT_THIS(receiver, WasmGlobalObject);

  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();

  switch (receiver->type()) {
    case i::wasm::kWasmI32:
      return_value.Set(receiver->GetI32());
      break;
1654 1655 1656 1657 1658 1659 1660 1661 1662
    case i::wasm::kWasmI64: {
      auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
      if (enabled_features.bigint) {
        Local<BigInt> value = BigInt::New(isolate, receiver->GetI64());

        return_value.Set(value);
      } else {
        thrower.TypeError("Can't get the value of i64 WebAssembly.Global");
      }
1663
      break;
1664
    }
1665 1666 1667 1668 1669 1670
    case i::wasm::kWasmF32:
      return_value.Set(receiver->GetF32());
      break;
    case i::wasm::kWasmF64:
      return_value.Set(receiver->GetF64());
      break;
1671
    case i::wasm::kWasmAnyRef:
1672
    case i::wasm::kWasmAnyFunc:
1673
    case i::wasm::kWasmExceptRef:
1674
      return_value.Set(Utils::ToLocal(receiver->GetRef()));
1675
      break;
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
    default:
      UNREACHABLE();
  }
}

// WebAssembly.Global.valueOf() -> num
void WebAssemblyGlobalValueOf(const v8::FunctionCallbackInfo<v8::Value>& args) {
  return WebAssemblyGlobalGetValueCommon(args, "WebAssembly.Global.valueOf()");
}

// get WebAssembly.Global.value -> num
void WebAssemblyGlobalGetValue(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  return WebAssemblyGlobalGetValueCommon(args, "get WebAssembly.Global.value");
}

// set WebAssembly.Global.value(num)
void WebAssemblyGlobalSetValue(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
  Local<Context> context = isolate->GetCurrentContext();
  ScheduledErrorThrower thrower(i_isolate, "set WebAssembly.Global.value");
  EXTRACT_THIS(receiver, WasmGlobalObject);

1702 1703 1704 1705
  if (!receiver->is_mutable()) {
    thrower.TypeError("Can't set the value of an immutable global.");
    return;
  }
1706
  if (args[0]->IsUndefined()) {
1707
    thrower.TypeError("Argument 0 is required");
1708 1709
    return;
  }
1710

1711 1712 1713 1714 1715 1716 1717
  switch (receiver->type()) {
    case i::wasm::kWasmI32: {
      int32_t i32_value = 0;
      if (!args[0]->Int32Value(context).To(&i32_value)) return;
      receiver->SetI32(i32_value);
      break;
    }
1718 1719 1720 1721 1722 1723 1724 1725 1726
    case i::wasm::kWasmI64: {
      auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
      if (enabled_features.bigint) {
        v8::Local<v8::BigInt> bigint_value;
        if (!args[0]->ToBigInt(context).ToLocal(&bigint_value)) return;
        receiver->SetI64(bigint_value->Int64Value());
      } else {
        thrower.TypeError("Can't set the value of i64 WebAssembly.Global");
      }
1727
      break;
1728
    }
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
    case i::wasm::kWasmF32: {
      double f64_value = 0;
      if (!args[0]->NumberValue(context).To(&f64_value)) return;
      receiver->SetF32(static_cast<float>(f64_value));
      break;
    }
    case i::wasm::kWasmF64: {
      double f64_value = 0;
      if (!args[0]->NumberValue(context).To(&f64_value)) return;
      receiver->SetF64(f64_value);
      break;
    }
1741 1742
    case i::wasm::kWasmAnyRef:
    case i::wasm::kWasmExceptRef: {
1743 1744 1745
      receiver->SetAnyRef(Utils::OpenHandle(*args[0]));
      break;
    }
1746 1747 1748 1749 1750 1751 1752 1753
    case i::wasm::kWasmAnyFunc: {
      if (!receiver->SetAnyFunc(i_isolate, Utils::OpenHandle(*args[0]))) {
        thrower.TypeError(
            "value of an anyfunc reference must be either null or an "
            "exported function");
      }
      break;
    }
1754 1755 1756 1757 1758
    default:
      UNREACHABLE();
  }
}

1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
// WebAssembly.Global.type(WebAssembly.Global) -> GlobalType
void WebAssemblyGlobalGetType(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  HandleScope scope(isolate);
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  ScheduledErrorThrower thrower(i_isolate, "WebAssembly.Global.type()");

  auto maybe_global = GetFirstArgumentAsGlobal(args, &thrower);
  if (thrower.error()) return;
  i::Handle<i::WasmGlobalObject> global = maybe_global.ToHandleChecked();
  v8::Local<v8::Object> ret = v8::Object::New(isolate);

  if (!ret->CreateDataProperty(isolate->GetCurrentContext(),
                               v8_str(isolate, "mutable"),
                               v8::Boolean::New(isolate, global->is_mutable()))
           .IsJust()) {
    return;
  }

  Local<String> type;
  switch (global->type()) {
    case i::wasm::kWasmI32: {
      type = v8_str(isolate, "i32");
      break;
    }
    case i::wasm::kWasmI64: {
      type = v8_str(isolate, "i64");
      break;
    }
    case i::wasm::kWasmF32: {
      type = v8_str(isolate, "f32");
      break;
    }
    case i::wasm::kWasmF64: {
      type = v8_str(isolate, "f64");
      break;
    }
    case i::wasm::kWasmAnyRef: {
      type = v8_str(isolate, "anyref");
      break;
    }
    default:
      UNREACHABLE();
  }
  if (!ret->CreateDataProperty(isolate->GetCurrentContext(),
                               v8_str(isolate, "value"), type)
           .IsJust()) {
    return;
  }

  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(ret);
}

1813 1814 1815 1816
}  // namespace

// TODO(titzer): we use the API to create the function template because the
// internal guts are too ugly to replicate here.
1817 1818
static i::Handle<i::FunctionTemplateInfo> NewFunctionTemplate(
    i::Isolate* i_isolate, FunctionCallback func) {
1819
  Isolate* isolate = reinterpret_cast<Isolate*>(i_isolate);
1820 1821 1822
  Local<FunctionTemplate> templ = FunctionTemplate::New(isolate, func);
  templ->ReadOnlyPrototype();
  return v8::Utils::OpenHandle(*templ);
1823 1824
}

1825 1826 1827 1828 1829 1830 1831
static i::Handle<i::ObjectTemplateInfo> NewObjectTemplate(
    i::Isolate* i_isolate) {
  Isolate* isolate = reinterpret_cast<Isolate*>(i_isolate);
  Local<ObjectTemplate> templ = ObjectTemplate::New(isolate);
  return v8::Utils::OpenHandle(*templ);
}

1832 1833
namespace internal {

1834 1835
Handle<JSFunction> CreateFunc(Isolate* isolate, Handle<String> name,
                              FunctionCallback func) {
1836
  Handle<FunctionTemplateInfo> temp = NewFunctionTemplate(isolate, func);
1837
  Handle<JSFunction> function =
1838
      ApiNatives::InstantiateFunction(temp, name).ToHandleChecked();
1839
  DCHECK(function->shared()->HasSharedName());
1840 1841 1842 1843 1844
  return function;
}

Handle<JSFunction> InstallFunc(Isolate* isolate, Handle<JSObject> object,
                               const char* str, FunctionCallback func,
1845 1846
                               int length = 0,
                               PropertyAttributes attributes = NONE) {
1847 1848
  Handle<String> name = v8_str(isolate, str);
  Handle<JSFunction> function = CreateFunc(isolate, name, func);
1849
  function->shared()->set_length(length);
1850
  JSObject::AddProperty(isolate, object, name, function, attributes);
rossberg's avatar
rossberg committed
1851
  return function;
1852 1853
}

1854 1855 1856 1857 1858 1859 1860
Handle<JSFunction> InstallConstructorFunc(Isolate* isolate,
                                         Handle<JSObject> object,
                                         const char* str,
                                         FunctionCallback func) {
  return InstallFunc(isolate, object, str, func, 1, DONT_ENUM);
}

1861
Handle<String> GetterName(Isolate* isolate, Handle<String> name) {
1862
  return Name::ToFunctionName(isolate, name, isolate->factory()->get_string())
1863 1864 1865
      .ToHandleChecked();
}

1866 1867
void InstallGetter(Isolate* isolate, Handle<JSObject> object, const char* str,
                   FunctionCallback func) {
1868 1869
  Handle<String> name = v8_str(isolate, str);
  Handle<JSFunction> function =
1870 1871
      CreateFunc(isolate, GetterName(isolate, name), func);

1872 1873
  Utils::ToLocal(object)->SetAccessorProperty(Utils::ToLocal(name),
                                              Utils::ToLocal(function),
1874
                                              Local<Function>(), v8::None);
1875 1876
}

1877
Handle<String> SetterName(Isolate* isolate, Handle<String> name) {
1878
  return Name::ToFunctionName(isolate, name, isolate->factory()->set_string())
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
      .ToHandleChecked();
}

void InstallGetterSetter(Isolate* isolate, Handle<JSObject> object,
                         const char* str, FunctionCallback getter,
                         FunctionCallback setter) {
  Handle<String> name = v8_str(isolate, str);
  Handle<JSFunction> getter_func =
      CreateFunc(isolate, GetterName(isolate, name), getter);
  Handle<JSFunction> setter_func =
      CreateFunc(isolate, SetterName(isolate, name), setter);
1890
  setter_func->shared()->set_length(1);
1891

1892
  v8::PropertyAttribute attributes = v8::None;
1893 1894 1895 1896 1897 1898

  Utils::ToLocal(object)->SetAccessorProperty(
      Utils::ToLocal(name), Utils::ToLocal(getter_func),
      Utils::ToLocal(setter_func), attributes);
}

1899 1900 1901 1902 1903 1904
// Assigns a dummy instance template to the given constructor function. Used to
// make sure the implicit receivers for the constructors in this file have an
// instance type different from the internal one, they allocate the resulting
// object explicitly and ignore implicit receiver.
void SetDummyInstanceTemplate(Isolate* isolate, Handle<JSFunction> fun) {
  Handle<ObjectTemplateInfo> instance_template = NewObjectTemplate(isolate);
1905 1906 1907
  FunctionTemplateInfo::SetInstanceTemplate(
      isolate, handle(fun->shared()->get_api_func_data(), isolate),
      instance_template);
1908 1909
}

1910
// static
1911
void WasmJs::Install(Isolate* isolate, bool exposed_on_global_object) {
1912 1913
  Handle<JSGlobalObject> global = isolate->global_object();
  Handle<Context> context(global->native_context(), isolate);
1914
  // Install the JS API once only.
1915
  Object prev = context->get(Context::WASM_MODULE_CONSTRUCTOR_INDEX);
1916 1917 1918 1919
  if (!prev->IsUndefined(isolate)) {
    DCHECK(prev->IsJSFunction());
    return;
  }
1920

1921 1922
  Factory* factory = isolate->factory();

1923
  // Setup WebAssembly
1924
  Handle<String> name = v8_str(isolate, "WebAssembly");
1925 1926 1927
  NewFunctionArgs args = NewFunctionArgs::ForFunctionWithoutCode(
      name, isolate->strict_function_map(), LanguageMode::kStrict);
  Handle<JSFunction> cons = factory->NewFunction(args);
1928
  JSFunction::SetPrototype(cons, isolate->initial_object_prototype());
1929 1930
  Handle<JSObject> webassembly =
      factory->NewJSObject(cons, AllocationType::kOld);
1931

1932 1933
  PropertyAttributes ro_attributes =
      static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
1934 1935
  JSObject::AddProperty(isolate, webassembly, factory->to_string_tag_symbol(),
                        name, ro_attributes);
1936 1937
  InstallFunc(isolate, webassembly, "compile", WebAssemblyCompile, 1);
  InstallFunc(isolate, webassembly, "validate", WebAssemblyValidate, 1);
1938
  InstallFunc(isolate, webassembly, "instantiate", WebAssemblyInstantiate, 1);
1939

1940 1941 1942 1943
  if (FLAG_wasm_test_streaming) {
    isolate->set_wasm_streaming_callback(WasmStreamingCallbackForTesting);
  }

1944
  if (isolate->wasm_streaming_callback() != nullptr) {
1945 1946 1947 1948 1949
    InstallFunc(isolate, webassembly, "compileStreaming",
                WebAssemblyCompileStreaming, 1);
    InstallFunc(isolate, webassembly, "instantiateStreaming",
                WebAssemblyInstantiateStreaming, 1);
  }
1950

1951 1952
  // Expose the API on the global object if configured to do so.
  if (exposed_on_global_object) {
1953
    JSObject::AddProperty(isolate, global, name, webassembly, DONT_ENUM);
1954 1955
  }

1956 1957
  // Setup Module
  Handle<JSFunction> module_constructor =
1958
      InstallConstructorFunc(isolate, webassembly, "Module", WebAssemblyModule);
1959
  context->set_wasm_module_constructor(*module_constructor);
1960
  SetDummyInstanceTemplate(isolate, module_constructor);
1961 1962
  JSFunction::EnsureHasInitialMap(module_constructor);
  Handle<JSObject> module_proto(
1963
      JSObject::cast(module_constructor->instance_prototype()), isolate);
1964 1965
  i::Handle<i::Map> module_map =
      isolate->factory()->NewMap(i::WASM_MODULE_TYPE, WasmModuleObject::kSize);
1966
  JSFunction::SetInitialMap(module_constructor, module_map, module_proto);
1967 1968
  InstallFunc(isolate, module_constructor, "imports", WebAssemblyModuleImports,
              1);
1969 1970
  InstallFunc(isolate, module_constructor, "exports", WebAssemblyModuleExports,
              1);
1971 1972
  InstallFunc(isolate, module_constructor, "customSections",
              WebAssemblyModuleCustomSections, 2);
1973
  JSObject::AddProperty(isolate, module_proto, factory->to_string_tag_symbol(),
1974
                        v8_str(isolate, "WebAssembly.Module"), ro_attributes);
1975 1976

  // Setup Instance
1977 1978
  Handle<JSFunction> instance_constructor = InstallConstructorFunc(
      isolate, webassembly, "Instance", WebAssemblyInstance);
1979
  context->set_wasm_instance_constructor(*instance_constructor);
1980
  SetDummyInstanceTemplate(isolate, instance_constructor);
1981 1982
  JSFunction::EnsureHasInitialMap(instance_constructor);
  Handle<JSObject> instance_proto(
1983
      JSObject::cast(instance_constructor->instance_prototype()), isolate);
1984
  i::Handle<i::Map> instance_map = isolate->factory()->NewMap(
1985
      i::WASM_INSTANCE_TYPE, WasmInstanceObject::kSize);
1986
  JSFunction::SetInitialMap(instance_constructor, instance_map, instance_proto);
1987 1988
  InstallGetter(isolate, instance_proto, "exports",
                WebAssemblyInstanceGetExports);
1989 1990
  JSObject::AddProperty(isolate, instance_proto,
                        factory->to_string_tag_symbol(),
1991
                        v8_str(isolate, "WebAssembly.Instance"), ro_attributes);
1992

1993 1994 1995 1996
  // The context is not set up completely yet. That's why we cannot use
  // {WasmFeaturesFromIsolate} and have to use {WasmFeaturesFromFlags} instead.
  auto enabled_features = i::wasm::WasmFeaturesFromFlags();

1997 1998
  // Setup Table
  Handle<JSFunction> table_constructor =
1999
      InstallConstructorFunc(isolate, webassembly, "Table", WebAssemblyTable);
2000
  context->set_wasm_table_constructor(*table_constructor);
2001
  SetDummyInstanceTemplate(isolate, table_constructor);
2002 2003
  JSFunction::EnsureHasInitialMap(table_constructor);
  Handle<JSObject> table_proto(
2004
      JSObject::cast(table_constructor->instance_prototype()), isolate);
2005 2006
  i::Handle<i::Map> table_map =
      isolate->factory()->NewMap(i::WASM_TABLE_TYPE, WasmTableObject::kSize);
2007
  JSFunction::SetInitialMap(table_constructor, table_map, table_proto);
2008
  InstallGetter(isolate, table_proto, "length", WebAssemblyTableGetLength);
2009 2010 2011
  InstallFunc(isolate, table_proto, "grow", WebAssemblyTableGrow, 1);
  InstallFunc(isolate, table_proto, "get", WebAssemblyTableGet, 1);
  InstallFunc(isolate, table_proto, "set", WebAssemblyTableSet, 2);
2012 2013 2014
  if (enabled_features.type_reflection) {
    InstallFunc(isolate, table_constructor, "type", WebAssemblyTableGetType, 1);
  }
2015
  JSObject::AddProperty(isolate, table_proto, factory->to_string_tag_symbol(),
2016
                        v8_str(isolate, "WebAssembly.Table"), ro_attributes);
2017 2018 2019

  // Setup Memory
  Handle<JSFunction> memory_constructor =
2020
      InstallConstructorFunc(isolate, webassembly, "Memory", WebAssemblyMemory);
2021
  context->set_wasm_memory_constructor(*memory_constructor);
2022
  SetDummyInstanceTemplate(isolate, memory_constructor);
2023 2024
  JSFunction::EnsureHasInitialMap(memory_constructor);
  Handle<JSObject> memory_proto(
2025
      JSObject::cast(memory_constructor->instance_prototype()), isolate);
2026 2027
  i::Handle<i::Map> memory_map =
      isolate->factory()->NewMap(i::WASM_MEMORY_TYPE, WasmMemoryObject::kSize);
2028
  JSFunction::SetInitialMap(memory_constructor, memory_map, memory_proto);
2029
  InstallFunc(isolate, memory_proto, "grow", WebAssemblyMemoryGrow, 1);
2030
  InstallGetter(isolate, memory_proto, "buffer", WebAssemblyMemoryGetBuffer);
2031 2032 2033 2034
  if (enabled_features.type_reflection) {
    InstallFunc(isolate, memory_constructor, "type", WebAssemblyMemoryGetType,
                1);
  }
2035
  JSObject::AddProperty(isolate, memory_proto, factory->to_string_tag_symbol(),
2036
                        v8_str(isolate, "WebAssembly.Memory"), ro_attributes);
2037

2038
  // Setup Global
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
  Handle<JSFunction> global_constructor =
      InstallConstructorFunc(isolate, webassembly, "Global", WebAssemblyGlobal);
  context->set_wasm_global_constructor(*global_constructor);
  SetDummyInstanceTemplate(isolate, global_constructor);
  JSFunction::EnsureHasInitialMap(global_constructor);
  Handle<JSObject> global_proto(
      JSObject::cast(global_constructor->instance_prototype()), isolate);
  i::Handle<i::Map> global_map =
      isolate->factory()->NewMap(i::WASM_GLOBAL_TYPE, WasmGlobalObject::kSize);
  JSFunction::SetInitialMap(global_constructor, global_map, global_proto);
  InstallFunc(isolate, global_proto, "valueOf", WebAssemblyGlobalValueOf, 0);
  InstallGetterSetter(isolate, global_proto, "value", WebAssemblyGlobalGetValue,
                      WebAssemblyGlobalSetValue);
2052 2053 2054 2055
  if (enabled_features.type_reflection) {
    InstallFunc(isolate, global_constructor, "type", WebAssemblyGlobalGetType,
                1);
  }
2056 2057
  JSObject::AddProperty(isolate, global_proto, factory->to_string_tag_symbol(),
                        v8_str(isolate, "WebAssembly.Global"), ro_attributes);
2058

2059 2060
  // Setup Exception
  if (enabled_features.eh) {
2061 2062
    Handle<JSFunction> exception_constructor = InstallConstructorFunc(
        isolate, webassembly, "Exception", WebAssemblyException);
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
    context->set_wasm_exception_constructor(*exception_constructor);
    SetDummyInstanceTemplate(isolate, exception_constructor);
    JSFunction::EnsureHasInitialMap(exception_constructor);
    Handle<JSObject> exception_proto(
        JSObject::cast(exception_constructor->instance_prototype()), isolate);
    i::Handle<i::Map> exception_map = isolate->factory()->NewMap(
        i::WASM_EXCEPTION_TYPE, WasmExceptionObject::kSize);
    JSFunction::SetInitialMap(exception_constructor, exception_map,
                              exception_proto);
  }

2074 2075
  // Setup errors
  Handle<JSFunction> compile_error(
2076
      isolate->native_context()->wasm_compile_error_function(), isolate);
2077 2078
  JSObject::AddProperty(isolate, webassembly,
                        isolate->factory()->CompileError_string(),
2079
                        compile_error, DONT_ENUM);
2080
  Handle<JSFunction> link_error(
2081
      isolate->native_context()->wasm_link_error_function(), isolate);
2082 2083
  JSObject::AddProperty(isolate, webassembly,
                        isolate->factory()->LinkError_string(), link_error,
2084
                        DONT_ENUM);
2085
  Handle<JSFunction> runtime_error(
2086
      isolate->native_context()->wasm_runtime_error_function(), isolate);
2087 2088
  JSObject::AddProperty(isolate, webassembly,
                        isolate->factory()->RuntimeError_string(),
2089
                        runtime_error, DONT_ENUM);
2090
}
2091 2092 2093 2094

#undef ASSIGN
#undef EXTRACT_THIS

2095 2096
}  // namespace internal
}  // namespace v8