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

#include "src/api-natives.h"
6
#include "src/api.h"
7
#include "src/asmjs/asm-js.h"
8
#include "src/asmjs/asm-typer.h"
9
#include "src/asmjs/asm-wasm-builder.h"
10 11
#include "src/assert-scope.h"
#include "src/ast/ast.h"
12
#include "src/execution.h"
13 14 15
#include "src/factory.h"
#include "src/handles.h"
#include "src/isolate.h"
16
#include "src/objects-inl.h"
17
#include "src/objects.h"
18
#include "src/parsing/parse-info.h"
19 20 21

#include "src/wasm/module-decoder.h"
#include "src/wasm/wasm-js.h"
22
#include "src/wasm/wasm-limits.h"
23
#include "src/wasm/wasm-module.h"
24
#include "src/wasm/wasm-objects.h"
25 26 27 28 29 30 31 32 33
#include "src/wasm/wasm-result.h"

typedef uint8_t byte;

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

namespace v8 {

namespace {
34 35 36 37 38

#define RANGE_ERROR_MSG                                                        \
  "Wasm compilation exceeds internal limits in this context for the provided " \
  "arguments"

39 40 41 42 43 44 45 46 47 48 49 50 51 52
// TODO(wasm): move brand check to the respective types, and don't throw
// in it, rather, use a provided ErrorThrower, or let caller handle it.
static bool HasBrand(i::Handle<i::Object> value, i::Handle<i::Symbol> sym) {
  if (!value->IsJSObject()) return false;
  i::Handle<i::JSObject> object = i::Handle<i::JSObject>::cast(value);
  Maybe<bool> has_brand = i::JSObject::HasOwnProperty(object, sym);
  return has_brand.FromMaybe(false);
}

static bool BrandCheck(i::Handle<i::Object> value, i::Handle<i::Symbol> sym,
                       ErrorThrower* thrower, const char* msg) {
  return HasBrand(value, sym) ? true : (thrower->TypeError("%s", msg), false);
}

53 54 55 56 57 58 59
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));
}

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
i::MaybeHandle<i::WasmModuleObject> GetFirstArgumentAsModule(
    const v8::FunctionCallbackInfo<v8::Value>& args, ErrorThrower* thrower) {
  v8::Isolate* isolate = args.GetIsolate();
  if (args.Length() < 1) {
    thrower->TypeError("Argument 0 must be a WebAssembly.Module");
    return {};
  }

  Local<Context> context = isolate->GetCurrentContext();
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);
  if (!BrandCheck(Utils::OpenHandle(*args[0]),
                  i::handle(i_context->wasm_module_sym()), thrower,
                  "Argument 0 must be a WebAssembly.Module")) {
    return {};
  }

  Local<Object> module_obj = Local<Object>::Cast(args[0]);
  return i::Handle<i::WasmModuleObject>::cast(
      v8::Utils::OpenHandle(*module_obj));
}

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
bool IsCompilationAllowed(i::Isolate* isolate, ErrorThrower* thrower,
                          v8::Local<v8::Value> source, bool is_async) {
  // Allow caller to do one final check on thrower state, rather than
  // one at each step. No information is lost - failure reason is captured
  // in the thrower state.
  if (thrower->error()) return false;

  AllowWasmCompileCallback callback = isolate->allow_wasm_compile_callback();
  if (callback != nullptr &&
      !callback(reinterpret_cast<v8::Isolate*>(isolate), source, is_async)) {
    thrower->RangeError(RANGE_ERROR_MSG);
    return false;
  }
  return true;
}

bool IsInstantiationAllowed(i::Isolate* isolate, ErrorThrower* thrower,
                            v8::Local<v8::Value> module_or_bytes,
                            i::MaybeHandle<i::JSReceiver> ffi, bool is_async) {
  // Allow caller to do one final check on thrower state, rather than
  // one at each step. No information is lost - failure reason is captured
  // in the thrower state.
  if (thrower->error()) return false;
  v8::MaybeLocal<v8::Value> v8_ffi;
  if (!ffi.is_null()) {
    v8_ffi = v8::Local<v8::Value>::Cast(Utils::ToLocal(ffi.ToHandleChecked()));
  }
  AllowWasmInstantiateCallback callback =
      isolate->allow_wasm_instantiate_callback();
  if (callback != nullptr &&
      !callback(reinterpret_cast<v8::Isolate*>(isolate), module_or_bytes,
                v8_ffi, is_async)) {
    thrower->RangeError(RANGE_ERROR_MSG);
    return false;
  }
  return true;
}

119 120 121 122 123 124
i::wasm::ModuleWireBytes GetFirstArgumentAsBytes(
    const v8::FunctionCallbackInfo<v8::Value>& args, ErrorThrower* thrower) {
  if (args.Length() < 1) {
    thrower->TypeError("Argument 0 must be a buffer source");
    return i::wasm::ModuleWireBytes(nullptr, nullptr);
  }
125

126
  const byte* start = nullptr;
127
  size_t length = 0;
128
  v8::Local<v8::Value> source = args[0];
rossberg's avatar
rossberg committed
129
  if (source->IsArrayBuffer()) {
130
    // A raw array buffer was passed.
rossberg's avatar
rossberg committed
131
    Local<ArrayBuffer> buffer = Local<ArrayBuffer>::Cast(source);
132 133 134
    ArrayBuffer::Contents contents = buffer->GetContents();

    start = reinterpret_cast<const byte*>(contents.Data());
135
    length = contents.ByteLength();
rossberg's avatar
rossberg committed
136
  } else if (source->IsTypedArray()) {
137
    // A TypedArray was passed.
rossberg's avatar
rossberg committed
138
    Local<TypedArray> array = Local<TypedArray>::Cast(source);
139 140 141 142 143 144
    Local<ArrayBuffer> buffer = array->Buffer();

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

    start =
        reinterpret_cast<const byte*>(contents.Data()) + array->ByteOffset();
145
    length = array->ByteLength();
146
  } else {
147
    thrower->TypeError("Argument 0 must be a buffer source");
148
  }
149 150
  DCHECK_IMPLIES(length, start != nullptr);
  if (length == 0) {
151 152
    thrower->CompileError("BufferSource argument is empty");
  }
153 154 155 156 157
  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);
158
  // TODO(titzer): use the handle as well?
159
  return i::wasm::ModuleWireBytes(start, start + length);
160 161
}

162 163 164 165
i::MaybeHandle<i::JSReceiver> GetSecondArgumentAsImports(
    const v8::FunctionCallbackInfo<v8::Value>& args, ErrorThrower* thrower) {
  if (args.Length() < 2) return {};
  if (args[1]->IsUndefined()) return {};
166

167 168 169 170 171 172
  if (!args[1]->IsObject()) {
    thrower->TypeError("Argument 1 must be an object");
    return {};
  }
  Local<Object> obj = Local<Object>::Cast(args[1]);
  return i::Handle<i::JSReceiver>::cast(v8::Utils::OpenHandle(*obj));
173 174
}

175
// WebAssembly.compile(bytes) -> Promise
rossberg's avatar
rossberg committed
176 177
void WebAssemblyCompile(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
178
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
rossberg's avatar
rossberg committed
179
  HandleScope scope(isolate);
180
  ErrorThrower thrower(i_isolate, "WebAssembly.compile()");
rossberg's avatar
rossberg committed
181

182 183 184 185 186 187
  Local<Context> context = isolate->GetCurrentContext();
  v8::Local<v8::Promise::Resolver> resolver;
  if (!v8::Promise::Resolver::New(context).ToLocal(&resolver)) return;
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(resolver->GetPromise());

188
  auto bytes = GetFirstArgumentAsBytes(args, &thrower);
189
  if (!IsCompilationAllowed(i_isolate, &thrower, args[0], true)) {
190
    resolver->Reject(context, Utils::ToLocal(thrower.Reify()));
191
    return;
192
  }
193
  DCHECK(!thrower.error());
194 195
  i::Handle<i::JSPromise> promise = Utils::OpenHandle(*resolver->GetPromise());
  i::wasm::AsyncCompile(i_isolate, promise, bytes);
rossberg's avatar
rossberg committed
196 197
}

198
// WebAssembly.validate(bytes) -> bool
199 200
void WebAssemblyValidate(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
201
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
202
  HandleScope scope(isolate);
203
  ErrorThrower thrower(i_isolate, "WebAssembly.validate()");
204

205
  auto bytes = GetFirstArgumentAsBytes(args, &thrower);
206 207

  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
208 209 210
  if (!thrower.error() &&
      i::wasm::SyncValidate(reinterpret_cast<i::Isolate*>(isolate), &thrower,
                            bytes)) {
211 212
    return_value.Set(v8::True(isolate));
  } else {
213
    if (thrower.wasm_error()) thrower.Reify();  // Clear error.
214 215 216 217
    return_value.Set(v8::False(isolate));
  }
}

218
// new WebAssembly.Module(bytes) -> WebAssembly.Module
rossberg's avatar
rossberg committed
219 220
void WebAssemblyModule(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
221
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
rossberg's avatar
rossberg committed
222
  HandleScope scope(isolate);
223
  ErrorThrower thrower(i_isolate, "WebAssembly.Module()");
rossberg's avatar
rossberg committed
224

225
  auto bytes = GetFirstArgumentAsBytes(args, &thrower);
226
  if (!IsCompilationAllowed(i_isolate, &thrower, args[0], false)) return;
227

228
  DCHECK(!thrower.error());
229 230
  i::MaybeHandle<i::Object> module_obj =
      i::wasm::SyncCompile(i_isolate, &thrower, bytes);
rossberg's avatar
rossberg committed
231 232 233 234 235 236
  if (module_obj.is_null()) return;

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

237
// WebAssembly.Module.imports(module) -> Array<Import>
238 239 240 241 242
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);
  ErrorThrower thrower(i_isolate, "WebAssembly.Module.imports()");
243

244
  auto maybe_module = GetFirstArgumentAsModule(args, &thrower);
245 246 247
  if (thrower.error()) return;
  auto imports = i::wasm::GetImports(i_isolate, maybe_module.ToHandleChecked());
  args.GetReturnValue().Set(Utils::ToLocal(imports));
248 249
}

250
// WebAssembly.Module.exports(module) -> Array<Export>
251 252 253 254 255 256
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);
  ErrorThrower thrower(i_isolate, "WebAssembly.Module.exports()");

257
  auto maybe_module = GetFirstArgumentAsModule(args, &thrower);
258 259 260
  if (thrower.error()) return;
  auto exports = i::wasm::GetExports(i_isolate, maybe_module.ToHandleChecked());
  args.GetReturnValue().Set(Utils::ToLocal(exports));
261
}
262

263
// WebAssembly.Module.customSections(module, name) -> Array<Section>
264 265 266 267 268 269 270
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);
  ErrorThrower thrower(i_isolate, "WebAssembly.Module.customSections()");

271
  auto maybe_module = GetFirstArgumentAsModule(args, &thrower);
272
  if (thrower.error()) return;
273 274 275

  if (args.Length() < 2) {
    thrower.TypeError("Argument 1 must be a string");
276 277 278
    return;
  }

279 280 281 282 283
  i::Handle<i::Object> name = Utils::OpenHandle(*args[1]);
  if (!name->IsString()) {
    thrower.TypeError("Argument 1 must be a string");
    return;
  }
284

285 286 287 288 289
  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));
290 291
}

292
// new WebAssembly.Instance(module, imports) -> WebAssembly.Instance
293
void WebAssemblyInstance(const v8::FunctionCallbackInfo<v8::Value>& args) {
rossberg's avatar
rossberg committed
294 295
  HandleScope scope(args.GetIsolate());
  v8::Isolate* isolate = args.GetIsolate();
296 297
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  ErrorThrower thrower(i_isolate, "WebAssembly.Instance()");
298

299
  auto maybe_module = GetFirstArgumentAsModule(args, &thrower);
300
  if (thrower.error()) return;
301

302
  auto maybe_imports = GetSecondArgumentAsImports(args, &thrower);
303 304 305 306 307
  if (!IsInstantiationAllowed(i_isolate, &thrower, args[0], maybe_imports,
                              false)) {
    return;
  }
  DCHECK(!thrower.error());
308

309 310 311 312 313
  i::MaybeHandle<i::Object> instance_object = i::wasm::SyncInstantiate(
      i_isolate, &thrower, maybe_module.ToHandleChecked(), maybe_imports,
      i::MaybeHandle<i::JSArrayBuffer>());
  if (instance_object.is_null()) return;
  args.GetReturnValue().Set(Utils::ToLocal(instance_object.ToHandleChecked()));
314 315
}

316 317 318
// WebAssembly.instantiate(module, imports) -> WebAssembly.Instance
// WebAssembly.instantiate(bytes, imports) ->
//     {module: WebAssembly.Module, instance: WebAssembly.Instance}
319 320 321
void WebAssemblyInstantiate(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
322
  ErrorThrower thrower(i_isolate, "WebAssembly.instantiate()");
323 324 325

  HandleScope scope(isolate);

326
  Local<Context> context = isolate->GetCurrentContext();
327 328
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);

329 330 331 332 333
  v8::Local<v8::Promise::Resolver> resolver;
  if (!v8::Promise::Resolver::New(context).ToLocal(&resolver)) return;
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(resolver->GetPromise());

334
  if (args.Length() < 1) {
335 336 337
    thrower.TypeError(
        "Argument 0 must be provided and must be either a buffer source or a "
        "WebAssembly.Module object");
338
    resolver->Reject(context, Utils::ToLocal(thrower.Reify()));
339
    return;
340
  }
341

342 343 344 345
  i::Handle<i::Object> first_arg = Utils::OpenHandle(*args[0]);
  if (!first_arg->IsJSObject()) {
    thrower.TypeError(
        "Argument 0 must be a buffer source or a WebAssembly.Module object");
346
    resolver->Reject(context, Utils::ToLocal(thrower.Reify()));
347 348
    return;
  }
349 350 351

  auto maybe_imports = GetSecondArgumentAsImports(args, &thrower);
  if (thrower.error()) {
352
    resolver->Reject(context, Utils::ToLocal(thrower.Reify()));
353 354
    return;
  }
355 356 357 358 359
  if (!IsInstantiationAllowed(i_isolate, &thrower, args[0], maybe_imports,
                              true)) {
    resolver->Reject(context, Utils::ToLocal(thrower.Reify()));
    return;
  }
360 361 362 363 364 365
  i::Handle<i::JSPromise> promise = Utils::OpenHandle(*resolver->GetPromise());
  if (HasBrand(first_arg, i::Handle<i::Symbol>(i_context->wasm_module_sym()))) {
    // WebAssembly.instantiate(module, imports) -> WebAssembly.Instance
    auto module_object = GetFirstArgumentAsModule(args, &thrower);
    i::wasm::AsyncInstantiate(i_isolate, promise,
                              module_object.ToHandleChecked(), maybe_imports);
366
  } else {
367 368 369 370 371
    // WebAssembly.instantiate(bytes, imports) -> {module, instance}
    auto bytes = GetFirstArgumentAsBytes(args, &thrower);
    if (thrower.error()) {
      resolver->Reject(context, Utils::ToLocal(thrower.Reify()));
      return;
372
    }
373 374
    i::wasm::AsyncCompileAndInstantiate(i_isolate, promise, bytes,
                                        maybe_imports);
375
  }
376
}
377 378 379

bool GetIntegerProperty(v8::Isolate* isolate, ErrorThrower* thrower,
                        Local<Context> context, Local<v8::Object> object,
380 381
                        Local<String> property, int* result,
                        int64_t lower_bound, uint64_t upper_bound) {
382 383
  v8::MaybeLocal<v8::Value> maybe = object->Get(context, property);
  v8::Local<v8::Value> value;
384
  if (maybe.ToLocal(&value)) {
385 386
    int64_t number;
    if (!value->IntegerValue(context).To(&number)) return false;
387
    if (number < lower_bound) {
388
      thrower->RangeError("Property value %" PRId64
389
                          " is below the lower bound %" PRIx64,
390 391 392
                          number, lower_bound);
      return false;
    }
393
    if (number > static_cast<int64_t>(upper_bound)) {
394
      thrower->RangeError("Property value %" PRId64
395
                          " is above the upper bound %" PRIu64,
396 397 398
                          number, upper_bound);
      return false;
    }
399
    *result = static_cast<int>(number);
400 401 402 403 404
    return true;
  }
  return false;
}

405
// new WebAssembly.Table(args) -> WebAssembly.Table
406 407
void WebAssemblyTable(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
408
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
409
  HandleScope scope(isolate);
410
  ErrorThrower thrower(i_isolate, "WebAssembly.Module()");
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
  if (args.Length() < 1 || !args[0]->IsObject()) {
    thrower.TypeError("Argument 0 must be a table descriptor");
    return;
  }
  Local<Context> context = isolate->GetCurrentContext();
  Local<v8::Object> descriptor = args[0]->ToObject(context).ToLocalChecked();
  // 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;
    bool equal;
    if (!string->Equals(context, v8_str(isolate, "anyfunc")).To(&equal)) return;
    if (!equal) {
      thrower.TypeError("Descriptor property 'element' must be 'anyfunc'");
      return;
    }
  }
  // The descriptor's 'initial'.
433
  int initial = 0;
434 435
  if (!GetIntegerProperty(isolate, &thrower, context, descriptor,
                          v8_str(isolate, "initial"), &initial, 0,
436
                          i::FLAG_wasm_max_table_size)) {
437 438 439
    return;
  }
  // The descriptor's 'maximum'.
440
  int maximum = -1;
441 442 443
  Local<String> maximum_key = v8_str(isolate, "maximum");
  Maybe<bool> has_maximum = descriptor->Has(context, maximum_key);

444
  if (!has_maximum.IsNothing() && has_maximum.FromJust()) {
445
    if (!GetIntegerProperty(isolate, &thrower, context, descriptor, maximum_key,
446 447
                            &maximum, initial,
                            i::wasm::kSpecMaxWasmTableSize)) {
448 449 450 451
      return;
    }
  }

452
  i::Handle<i::FixedArray> fixed_array;
453 454
  i::Handle<i::JSObject> table_obj =
      i::WasmTableObject::New(i_isolate, initial, maximum, &fixed_array);
455 456 457
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(Utils::ToLocal(table_obj));
}
458

459 460
void WebAssemblyMemory(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
461
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
462
  HandleScope scope(isolate);
463
  ErrorThrower thrower(i_isolate, "WebAssembly.Memory()");
464
  if (args.Length() < 1 || !args[0]->IsObject()) {
465
    thrower.TypeError("Argument 0 must be a memory descriptor");
466 467 468 469 470
    return;
  }
  Local<Context> context = isolate->GetCurrentContext();
  Local<v8::Object> descriptor = args[0]->ToObject(context).ToLocalChecked();
  // The descriptor's 'initial'.
471
  int initial = 0;
472
  if (!GetIntegerProperty(isolate, &thrower, context, descriptor,
473
                          v8_str(isolate, "initial"), &initial, 0,
474
                          i::FLAG_wasm_max_mem_pages)) {
475 476
    return;
  }
477
  // The descriptor's 'maximum'.
478
  int maximum = -1;
479 480 481
  Local<String> maximum_key = v8_str(isolate, "maximum");
  Maybe<bool> has_maximum = descriptor->Has(context, maximum_key);

482
  if (!has_maximum.IsNothing() && has_maximum.FromJust()) {
483
    if (!GetIntegerProperty(isolate, &thrower, context, descriptor, maximum_key,
484 485
                            &maximum, initial,
                            i::wasm::kSpecMaxWasmMemoryPages)) {
486 487 488 489 490
      return;
    }
  }
  size_t size = static_cast<size_t>(i::wasm::WasmModule::kPageSize) *
                static_cast<size_t>(initial);
491 492
  i::Handle<i::JSArrayBuffer> buffer =
      i::wasm::NewArrayBuffer(i_isolate, size, i::FLAG_wasm_guard_pages);
493 494 495 496
  if (buffer.is_null()) {
    thrower.RangeError("could not allocate memory");
    return;
  }
497 498
  i::Handle<i::JSObject> memory_obj =
      i::WasmMemoryObject::New(i_isolate, buffer, maximum);
499
  args.GetReturnValue().Set(Utils::ToLocal(memory_obj));
500
}
501

502 503
void WebAssemblyTableGetLength(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
504
  v8::Isolate* isolate = args.GetIsolate();
505 506 507
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
  ErrorThrower thrower(i_isolate, "WebAssembly.Table.length()");
508 509
  Local<Context> context = isolate->GetCurrentContext();
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);
510 511
  if (!BrandCheck(Utils::OpenHandle(*args.This()),
                  i::Handle<i::Symbol>(i_context->wasm_table_sym()), &thrower,
512 513 514
                  "Receiver is not a WebAssembly.Table")) {
    return;
  }
515 516 517 518
  auto receiver =
      i::Handle<i::WasmTableObject>::cast(Utils::OpenHandle(*args.This()));
  args.GetReturnValue().Set(
      v8::Number::New(isolate, receiver->current_length()));
519
}
520

521
// WebAssembly.Table.grow(num) -> num
522
void WebAssemblyTableGrow(const v8::FunctionCallbackInfo<v8::Value>& args) {
523
  v8::Isolate* isolate = args.GetIsolate();
524 525 526
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  HandleScope scope(isolate);
  ErrorThrower thrower(i_isolate, "WebAssembly.Table.grow()");
527 528
  Local<Context> context = isolate->GetCurrentContext();
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);
529 530
  if (!BrandCheck(Utils::OpenHandle(*args.This()),
                  i::Handle<i::Symbol>(i_context->wasm_table_sym()), &thrower,
531 532 533
                  "Receiver is not a WebAssembly.Table")) {
    return;
  }
534

535 536
  auto receiver =
      i::Handle<i::WasmTableObject>::cast(Utils::OpenHandle(*args.This()));
537
  i::Handle<i::FixedArray> old_array(receiver->functions(), i_isolate);
538 539 540 541 542 543 544
  int old_size = old_array->length();
  int64_t new_size64 = 0;
  if (args.Length() > 0 && !args[0]->IntegerValue(context).To(&new_size64)) {
    return;
  }
  new_size64 += old_size;

545 546
  int64_t max_size64 = receiver->maximum_length();
  if (max_size64 < 0 ||
547 548
      max_size64 > static_cast<int64_t>(i::FLAG_wasm_max_table_size)) {
    max_size64 = i::FLAG_wasm_max_table_size;
549 550 551
  }

  if (new_size64 < old_size || new_size64 > max_size64) {
552 553
    thrower.RangeError(new_size64 < old_size ? "trying to shrink table"
                                             : "maximum table size exceeded");
554 555
    return;
  }
556

557
  int new_size = static_cast<int>(new_size64);
558 559
  i::WasmTableObject::Grow(i_isolate, receiver,
                           static_cast<uint32_t>(new_size - old_size));
560 561 562 563 564 565 566

  if (new_size != old_size) {
    i::Handle<i::FixedArray> new_array =
        i_isolate->factory()->NewFixedArray(new_size);
    for (int i = 0; i < old_size; ++i) new_array->set(i, old_array->get(i));
    i::Object* null = i_isolate->heap()->null_value();
    for (int i = old_size; i < new_size; ++i) new_array->set(i, null);
567
    receiver->set_functions(*new_array);
568 569
  }

570 571 572
  // TODO(gdeepti): use weak links for instances
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(old_size);
573
}
574

575
// WebAssembly.Table.get(num) -> JSFunction
576
void WebAssemblyTableGet(const v8::FunctionCallbackInfo<v8::Value>& args) {
577
  v8::Isolate* isolate = args.GetIsolate();
578
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
579
  HandleScope scope(isolate);
580
  ErrorThrower thrower(i_isolate, "WebAssembly.Table.get()");
581 582
  Local<Context> context = isolate->GetCurrentContext();
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);
583 584
  if (!BrandCheck(Utils::OpenHandle(*args.This()),
                  i::Handle<i::Symbol>(i_context->wasm_table_sym()), &thrower,
585 586 587 588
                  "Receiver is not a WebAssembly.Table")) {
    return;
  }

589 590
  auto receiver =
      i::Handle<i::WasmTableObject>::cast(Utils::OpenHandle(*args.This()));
591
  i::Handle<i::FixedArray> array(receiver->functions(), i_isolate);
592 593 594
  int i = 0;
  if (args.Length() > 0 && !args[0]->Int32Value(context).To(&i)) return;
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
595
  if (i < 0 || i >= array->length()) {
596
    thrower.RangeError("index out of bounds");
597
    return;
598
  }
599

600
  i::Handle<i::Object> value(array->get(i), i_isolate);
601
  return_value.Set(Utils::ToLocal(value));
602
}
603

604
// WebAssembly.Table.set(num, JSFunction)
605
void WebAssemblyTableSet(const v8::FunctionCallbackInfo<v8::Value>& args) {
606
  v8::Isolate* isolate = args.GetIsolate();
607
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
608
  HandleScope scope(isolate);
609
  ErrorThrower thrower(i_isolate, "WebAssembly.Table.set()");
610 611
  Local<Context> context = isolate->GetCurrentContext();
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);
612 613
  if (!BrandCheck(Utils::OpenHandle(*args.This()),
                  i::Handle<i::Symbol>(i_context->wasm_table_sym()), &thrower,
614 615 616
                  "Receiver is not a WebAssembly.Table")) {
    return;
  }
617
  if (args.Length() < 2) {
618
    thrower.TypeError("Argument 1 must be null or a function");
619 620
    return;
  }
621 622 623 624 625
  i::Handle<i::Object> value = Utils::OpenHandle(*args[1]);
  if (!value->IsNull(i_isolate) &&
      (!value->IsJSFunction() ||
       i::Handle<i::JSFunction>::cast(value)->code()->kind() !=
           i::Code::JS_TO_WASM_FUNCTION)) {
626
    thrower.TypeError("Argument 1 must be null or a WebAssembly function");
627 628
    return;
  }
629

630 631
  auto receiver =
      i::Handle<i::WasmTableObject>::cast(Utils::OpenHandle(*args.This()));
632
  i::Handle<i::FixedArray> array(receiver->functions(), i_isolate);
633 634
  int i;
  if (!args[0]->Int32Value(context).To(&i)) return;
635
  if (i < 0 || i >= array->length()) {
636
    thrower.RangeError("index out of bounds");
637 638 639
    return;
  }

640
  i::Handle<i::FixedArray> dispatch_tables(receiver->dispatch_tables(),
641
                                           i_isolate);
642 643 644 645 646 647 648
  if (value->IsNull(i_isolate)) {
    i::wasm::UpdateDispatchTables(i_isolate, dispatch_tables, i,
                                  i::Handle<i::JSFunction>::null());
  } else {
    i::wasm::UpdateDispatchTables(i_isolate, dispatch_tables, i,
                                  i::Handle<i::JSFunction>::cast(value));
  }
649

650
  i::Handle<i::FixedArray>::cast(array)->set(i, *value);
651
}
652

653
// WebAssembly.Memory.grow(num) -> num
654
void WebAssemblyMemoryGrow(const v8::FunctionCallbackInfo<v8::Value>& args) {
655
  v8::Isolate* isolate = args.GetIsolate();
656
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
657
  HandleScope scope(isolate);
658
  ErrorThrower thrower(i_isolate, "WebAssembly.Memory.grow()");
659 660
  Local<Context> context = isolate->GetCurrentContext();
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);
661 662
  if (!BrandCheck(Utils::OpenHandle(*args.This()),
                  i::Handle<i::Symbol>(i_context->wasm_memory_sym()), &thrower,
663 664 665
                  "Receiver is not a WebAssembly.Memory")) {
    return;
  }
666 667
  int64_t delta_size = 0;
  if (args.Length() < 1 || !args[0]->IntegerValue(context).To(&delta_size)) {
668
    thrower.TypeError("Argument 0 required, must be numeric value of pages");
669 670
    return;
  }
671 672 673 674
  i::Handle<i::WasmMemoryObject> receiver =
      i::Handle<i::WasmMemoryObject>::cast(Utils::OpenHandle(*args.This()));
  int64_t max_size64 = receiver->maximum_pages();
  if (max_size64 < 0 ||
675 676
      max_size64 > static_cast<int64_t>(i::FLAG_wasm_max_mem_pages)) {
    max_size64 = i::FLAG_wasm_max_mem_pages;
677 678 679 680 681 682
  }
  i::Handle<i::JSArrayBuffer> old_buffer(receiver->buffer());
  uint32_t old_size =
      old_buffer->byte_length()->Number() / i::wasm::kSpecMaxWasmMemoryPages;
  int64_t new_size64 = old_size + delta_size;
  if (delta_size < 0 || max_size64 < new_size64 || new_size64 < old_size) {
683 684
    thrower.RangeError(new_size64 < old_size ? "trying to shrink memory"
                                             : "maximum memory size exceeded");
685 686 687 688
    return;
  }
  int32_t ret = i::wasm::GrowWebAssemblyMemory(
      i_isolate, receiver, static_cast<uint32_t>(delta_size));
689
  if (ret == -1) {
690
    thrower.RangeError("Unable to grow instance memory.");
691 692 693 694
    return;
  }
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(ret);
695
}
696

697
// WebAssembly.Memory.buffer -> ArrayBuffer
698 699 700
void WebAssemblyMemoryGetBuffer(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
701
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
702
  HandleScope scope(isolate);
703
  ErrorThrower thrower(i_isolate, "WebAssembly.Memory.buffer");
704 705
  Local<Context> context = isolate->GetCurrentContext();
  i::Handle<i::Context> i_context = Utils::OpenHandle(*context);
706 707
  if (!BrandCheck(Utils::OpenHandle(*args.This()),
                  i::Handle<i::Symbol>(i_context->wasm_memory_sym()), &thrower,
708 709 710
                  "Receiver is not a WebAssembly.Memory")) {
    return;
  }
711 712
  i::Handle<i::WasmMemoryObject> receiver =
      i::Handle<i::WasmMemoryObject>::cast(Utils::OpenHandle(*args.This()));
713
  i::Handle<i::Object> buffer(receiver->buffer(), i_isolate);
714 715 716 717
  DCHECK(buffer->IsJSArrayBuffer());
  v8::ReturnValue<v8::Value> return_value = args.GetReturnValue();
  return_value.Set(Utils::ToLocal(buffer));
}
718 719 720 721 722 723 724
}  // namespace

// TODO(titzer): we use the API to create the function template because the
// internal guts are too ugly to replicate here.
static i::Handle<i::FunctionTemplateInfo> NewTemplate(i::Isolate* i_isolate,
                                                      FunctionCallback func) {
  Isolate* isolate = reinterpret_cast<Isolate*>(i_isolate);
725 726 727
  Local<FunctionTemplate> templ = FunctionTemplate::New(isolate, func);
  templ->ReadOnlyPrototype();
  return v8::Utils::OpenHandle(*templ);
728 729 730 731
}

namespace internal {

732
Handle<JSFunction> InstallFunc(Isolate* isolate, Handle<JSObject> object,
733 734
                               const char* str, FunctionCallback func,
                               int length = 0) {
735 736 737 738
  Handle<String> name = v8_str(isolate, str);
  Handle<FunctionTemplateInfo> temp = NewTemplate(isolate, func);
  Handle<JSFunction> function =
      ApiNatives::InstantiateFunction(temp).ToHandleChecked();
739 740
  JSFunction::SetName(function, name, isolate->factory()->empty_string());
  function->shared()->set_length(length);
741
  PropertyAttributes attributes = static_cast<PropertyAttributes>(DONT_ENUM);
742
  JSObject::AddProperty(object, name, function, attributes);
rossberg's avatar
rossberg committed
743
  return function;
744 745
}

746 747 748 749 750 751 752
Handle<JSFunction> InstallGetter(Isolate* isolate, Handle<JSObject> object,
                                 const char* str, FunctionCallback func) {
  Handle<String> name = v8_str(isolate, str);
  Handle<FunctionTemplateInfo> temp = NewTemplate(isolate, func);
  Handle<JSFunction> function =
      ApiNatives::InstantiateFunction(temp).ToHandleChecked();
  v8::PropertyAttribute attributes =
753
      static_cast<v8::PropertyAttribute>(v8::DontEnum);
754 755 756 757 758 759
  Utils::ToLocal(object)->SetAccessorProperty(Utils::ToLocal(name),
                                              Utils::ToLocal(function),
                                              Local<Function>(), attributes);
  return function;
}

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
void WasmJs::Install(Isolate* isolate) {
  Handle<JSGlobalObject> global = isolate->global_object();
  Handle<Context> context(global->native_context(), isolate);
  // TODO(titzer): once FLAG_expose_wasm is gone, this should become a DCHECK.
  if (context->get(Context::WASM_FUNCTION_MAP_INDEX)->IsMap()) return;

  // Install Maps.

  // TODO(titzer): Also make one for strict mode functions?
  Handle<Map> prev_map = Handle<Map>(context->sloppy_function_map(), isolate);

  InstanceType instance_type = prev_map->instance_type();
  int internal_fields = JSObject::GetInternalFieldCount(*prev_map);
  CHECK_EQ(0, internal_fields);
  int pre_allocated =
      prev_map->GetInObjectProperties() - prev_map->unused_property_fields();
  int instance_size = 0;
  int in_object_properties = 0;
  int wasm_internal_fields = internal_fields + 1  // module instance object
      + 1                  // function arity
      + 1;                 // function signature
  JSFunction::CalculateInstanceSizeHelper(instance_type, wasm_internal_fields,
                                          0, &instance_size,
                                          &in_object_properties);

  int unused_property_fields = in_object_properties - pre_allocated;
  Handle<Map> map = Map::CopyInitialMap(
      prev_map, instance_size, in_object_properties, unused_property_fields);

  context->set_wasm_function_map(*map);

  // Install symbols.
792

793 794 795 796 797 798 799 800 801 802 803 804 805 806
  Factory* factory = isolate->factory();
  // Create private symbols.
  Handle<Symbol> module_sym = factory->NewPrivateSymbol();
  context->set_wasm_module_sym(*module_sym);

  Handle<Symbol> instance_sym = factory->NewPrivateSymbol();
  context->set_wasm_instance_sym(*instance_sym);

  Handle<Symbol> table_sym = factory->NewPrivateSymbol();
  context->set_wasm_table_sym(*table_sym);

  Handle<Symbol> memory_sym = factory->NewPrivateSymbol();
  context->set_wasm_memory_sym(*memory_sym);

807 808 809
  // Install the JS API.

  // Setup WebAssembly
810 811 812 813 814
  Handle<String> name = v8_str(isolate, "WebAssembly");
  Handle<JSFunction> cons = factory->NewFunction(name);
  JSFunction::SetInstancePrototype(
      cons, Handle<Object>(context->initial_object_prototype(), isolate));
  cons->shared()->set_instance_class_name(*name);
815
  Handle<JSObject> webassembly = factory->NewJSObject(cons, TENURED);
816
  PropertyAttributes attributes = static_cast<PropertyAttributes>(DONT_ENUM);
817
  JSObject::AddProperty(global, name, webassembly, attributes);
818 819 820 821
  PropertyAttributes ro_attributes =
      static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
  JSObject::AddProperty(webassembly, factory->to_string_tag_symbol(),
                        v8_str(isolate, "WebAssembly"), ro_attributes);
822 823
  InstallFunc(isolate, webassembly, "compile", WebAssemblyCompile, 1);
  InstallFunc(isolate, webassembly, "validate", WebAssemblyValidate, 1);
824 825
  InstallFunc(isolate, webassembly, "instantiate", WebAssemblyInstantiate, 1);

826 827
  // Setup Module
  Handle<JSFunction> module_constructor =
828
      InstallFunc(isolate, webassembly, "Module", WebAssemblyModule, 1);
829 830 831
  context->set_wasm_module_constructor(*module_constructor);
  Handle<JSObject> module_proto =
      factory->NewJSObject(module_constructor, TENURED);
832
  i::Handle<i::Map> module_map = isolate->factory()->NewMap(
833
      i::JS_API_OBJECT_TYPE, i::JSObject::kHeaderSize +
834
                             WasmModuleObject::kFieldCount * i::kPointerSize);
835
  JSFunction::SetInitialMap(module_constructor, module_map, module_proto);
836 837
  InstallFunc(isolate, module_constructor, "imports", WebAssemblyModuleImports,
              1);
838 839
  InstallFunc(isolate, module_constructor, "exports", WebAssemblyModuleExports,
              1);
840 841
  InstallFunc(isolate, module_constructor, "customSections",
              WebAssemblyModuleCustomSections, 2);
842 843 844 845
  JSObject::AddProperty(module_proto, isolate->factory()->constructor_string(),
                        module_constructor, DONT_ENUM);
  JSObject::AddProperty(module_proto, factory->to_string_tag_symbol(),
                        v8_str(isolate, "WebAssembly.Module"), ro_attributes);
846 847 848

  // Setup Instance
  Handle<JSFunction> instance_constructor =
849
      InstallFunc(isolate, webassembly, "Instance", WebAssemblyInstance, 1);
850
  context->set_wasm_instance_constructor(*instance_constructor);
851 852 853
  Handle<JSObject> instance_proto =
      factory->NewJSObject(instance_constructor, TENURED);
  i::Handle<i::Map> instance_map = isolate->factory()->NewMap(
854
      i::JS_API_OBJECT_TYPE, i::JSObject::kHeaderSize +
855 856 857 858 859
                             WasmInstanceObject::kFieldCount * i::kPointerSize);
  JSFunction::SetInitialMap(instance_constructor, instance_map, instance_proto);
  JSObject::AddProperty(instance_proto,
                        isolate->factory()->constructor_string(),
                        instance_constructor, DONT_ENUM);
860 861
  JSObject::AddProperty(instance_proto, factory->to_string_tag_symbol(),
                        v8_str(isolate, "WebAssembly.Instance"), ro_attributes);
862 863 864

  // Setup Table
  Handle<JSFunction> table_constructor =
865
      InstallFunc(isolate, webassembly, "Table", WebAssemblyTable, 1);
866 867 868
  context->set_wasm_table_constructor(*table_constructor);
  Handle<JSObject> table_proto =
      factory->NewJSObject(table_constructor, TENURED);
869
  i::Handle<i::Map> table_map = isolate->factory()->NewMap(
870
      i::JS_API_OBJECT_TYPE, i::JSObject::kHeaderSize +
871
                             WasmTableObject::kFieldCount * i::kPointerSize);
872
  JSFunction::SetInitialMap(table_constructor, table_map, table_proto);
873 874 875
  JSObject::AddProperty(table_proto, isolate->factory()->constructor_string(),
                        table_constructor, DONT_ENUM);
  InstallGetter(isolate, table_proto, "length", WebAssemblyTableGetLength);
876 877 878
  InstallFunc(isolate, table_proto, "grow", WebAssemblyTableGrow, 1);
  InstallFunc(isolate, table_proto, "get", WebAssemblyTableGet, 1);
  InstallFunc(isolate, table_proto, "set", WebAssemblyTableSet, 2);
879 880
  JSObject::AddProperty(table_proto, factory->to_string_tag_symbol(),
                        v8_str(isolate, "WebAssembly.Table"), ro_attributes);
881 882 883

  // Setup Memory
  Handle<JSFunction> memory_constructor =
884
      InstallFunc(isolate, webassembly, "Memory", WebAssemblyMemory, 1);
885 886 887
  context->set_wasm_memory_constructor(*memory_constructor);
  Handle<JSObject> memory_proto =
      factory->NewJSObject(memory_constructor, TENURED);
888
  i::Handle<i::Map> memory_map = isolate->factory()->NewMap(
889
      i::JS_API_OBJECT_TYPE, i::JSObject::kHeaderSize +
890
                             WasmMemoryObject::kFieldCount * i::kPointerSize);
891
  JSFunction::SetInitialMap(memory_constructor, memory_map, memory_proto);
892 893
  JSObject::AddProperty(memory_proto, isolate->factory()->constructor_string(),
                        memory_constructor, DONT_ENUM);
894
  InstallFunc(isolate, memory_proto, "grow", WebAssemblyMemoryGrow, 1);
895
  InstallGetter(isolate, memory_proto, "buffer", WebAssemblyMemoryGetBuffer);
896 897
  JSObject::AddProperty(memory_proto, factory->to_string_tag_symbol(),
                        v8_str(isolate, "WebAssembly.Memory"), ro_attributes);
898 899

  // Setup errors
900
  attributes = static_cast<PropertyAttributes>(DONT_ENUM);
901 902
  Handle<JSFunction> compile_error(
      isolate->native_context()->wasm_compile_error_function());
903
  JSObject::AddProperty(webassembly, isolate->factory()->CompileError_string(),
904
                        compile_error, attributes);
905 906 907 908
  Handle<JSFunction> link_error(
      isolate->native_context()->wasm_link_error_function());
  JSObject::AddProperty(webassembly, isolate->factory()->LinkError_string(),
                        link_error, attributes);
909 910
  Handle<JSFunction> runtime_error(
      isolate->native_context()->wasm_runtime_error_function());
911
  JSObject::AddProperty(webassembly, isolate->factory()->RuntimeError_string(),
912
                        runtime_error, attributes);
913 914
}

915 916 917 918 919 920 921 922 923
bool WasmJs::IsWasmMemoryObject(Isolate* isolate, Handle<Object> value) {
  i::Handle<i::Symbol> symbol(isolate->context()->wasm_memory_sym(), isolate);
  return HasBrand(value, symbol);
}

bool WasmJs::IsWasmTableObject(Isolate* isolate, Handle<Object> value) {
  i::Handle<i::Symbol> symbol(isolate->context()->wasm_table_sym(), isolate);
  return HasBrand(value, symbol);
}
924 925
}  // namespace internal
}  // namespace v8