--- /dev/null
+import * as assert from '../assert.js';
+import Builder from '../Builder.js';
+
+assert.truthy(WebAssembly.instantiate instanceof Function);
+assert.eq(WebAssembly.instantiate.length, 1);
+
+{
+ const builder = (new Builder())
+ .Type().End()
+ .Function().End()
+ .Export()
+ .Function("foo")
+ .End()
+ .Code()
+ .Function("foo", { params: [], ret: "i32" })
+ .I32Const(1)
+ .End()
+ .End();
+
+ const bin = builder.WebAssembly().get();
+
+ let done = false;
+ async function test() {
+ let {module, instance} = await WebAssembly.instantiate(bin);
+ assert.truthy(module instanceof WebAssembly.Module);
+ assert.truthy(instance instanceof WebAssembly.Instance);
+ assert.eq(instance.exports.foo(20), 1);
+ done = true;
+ }
+
+ test();
+ drainMicrotasks();
+ assert.truthy(done);
+}
+
+{
+ const builder = (new Builder())
+ .Type().End()
+ .Function().End()
+ .Export()
+ .Function("foo")
+ .End()
+ .Code()
+ .Function("foo", { params: [], ret: "i32" })
+ .I32Const(1)
+ .End()
+ .End();
+
+ const bin = builder.WebAssembly().get();
+
+ let done = false;
+ async function test() {
+ try {
+ let {module, instance} = await WebAssembly.instantiate(bin, null);
+ } catch(e) {
+ assert.eq(e.message, "second argument to WebAssembly.instantiate must be undefined or an Object (evaluating 'WebAssembly.instantiate(bin, null)')");
+ }
+ done = true;
+ }
+
+ test();
+ drainMicrotasks();
+ assert.truthy(done);
+}
+
+{
+ const builder = (new Builder())
+ .Type().End()
+ .Function().End()
+ .Export()
+ .Function("foo")
+ .End()
+ .Code()
+ .Function("foo", { params: [], ret: "i32" })
+ .F32Const(1)
+ .End()
+ .End();
+
+ const bin = builder.WebAssembly().get();
+
+ let done = false;
+ async function test() {
+ try {
+ let {module, instance} = await WebAssembly.instantiate(bin);
+ } catch(e) {
+ assert.truthy(e instanceof WebAssembly.CompileError);
+ assert.eq(e.message, "WebAssembly.Module doesn't validate: control flow returns with unexpected type, in function at index 0 (evaluating 'WebAssembly.instantiate(bin)')");
+ }
+ done = true;
+ }
+
+ test();
+ drainMicrotasks();
+ assert.truthy(done);
+}
+
+{
+ const builder = (new Builder())
+ .Type().End()
+ .Import().Memory("imp", "memory", {initial:100}).End()
+ .Function().End()
+ .Export()
+ .Function("foo")
+ .End()
+ .Code()
+ .Function("foo", { params: [], ret: "i32" })
+ .I32Const(1)
+ .End()
+ .End();
+
+ const bin = builder.WebAssembly().get();
+
+ let done = false;
+ async function test() {
+ try {
+ let {module, instance} = await WebAssembly.instantiate(bin, {imp: {memory: 20}});
+ } catch(e) {
+ assert.eq(e.message, "Memory import is not an instance of WebAssembly.Memory (evaluating 'WebAssembly.instantiate(bin, {imp: {memory: 20}})')");
+ }
+ done = true;
+ }
+
+ test();
+ drainMicrotasks();
+ assert.truthy(done);
+}
+
+{
+ const builder = (new Builder())
+ .Type().End()
+ .Import().Memory("imp", "memory", {initial:100}).End()
+ .Function().End()
+ .Export()
+ .Function("foo")
+ .End()
+ .Code()
+ .Function("foo", { params: [], ret: "i32" })
+ .I32Const(1)
+ .End()
+ .End();
+
+ const bin = builder.WebAssembly().get();
+
+ let done = false;
+ async function test() {
+ try {
+ const module = new WebAssembly.Module(bin);
+ let instance = await WebAssembly.instantiate(bin, {imp: {memory: 20}});
+ } catch(e) {
+ assert.eq(e.message, "Memory import is not an instance of WebAssembly.Memory (evaluating 'WebAssembly.instantiate(bin, {imp: {memory: 20}})')");
+ }
+ done = true;
+ }
+
+ test();
+ drainMicrotasks();
+ assert.truthy(done);
+}
+
+{
+ const builder = (new Builder())
+ .Type().End()
+ .Function().End()
+ .Export()
+ .Function("foo")
+ .End()
+ .Code()
+ .Function("foo", { params: [], ret: "i32" })
+ .I32Const(1)
+ .End()
+ .End();
+
+ const bin = builder.WebAssembly().get();
+
+ let done = false;
+ async function test() {
+ let module = new WebAssembly.Module(bin);
+ let instance = await WebAssembly.instantiate(module);
+ assert.truthy(instance instanceof WebAssembly.Instance);
+ assert.eq(instance.exports.foo(20), 1);
+ done = true;
+ }
+
+ test();
+ drainMicrotasks();
+ assert.truthy(done);
+}
+
+{
+ const builder = (new Builder())
+ .Type().End()
+ .Import().Memory("imp", "memory", {initial:100}).End()
+ .Function().End()
+ .Export()
+ .Function("foo")
+ .End()
+ .Code()
+ .Function("foo", { params: [], ret: "i32" })
+ .I32Const(1)
+ .End()
+ .End();
+
+ const bin = builder.WebAssembly().get();
+
+ let done = false;
+ async function test() {
+ try {
+ await WebAssembly.instantiate(25);
+ } catch(e) {
+ // FIXME: Better error message here.
+ assert.eq(e.message, "first argument must be an ArrayBufferView or an ArrayBuffer (evaluating 'WebAssembly.instantiate(25)')");
+ }
+ done = true;
+ }
+
+ test();
+ drainMicrotasks();
+ assert.truthy(done);
+}
#include "JSCInlines.h"
#include "JSPromiseDeferred.h"
#include "JSWebAssemblyHelpers.h"
+#include "ObjectConstructor.h"
#include "WasmPlan.h"
#include "WebAssemblyModuleConstructor.h"
EncodedJSValue JSC_HOST_CALL webAssemblyValidateFunc(ExecState*);
EncodedJSValue JSC_HOST_CALL webAssemblyCompileFunc(ExecState*);
+EncodedJSValue JSC_HOST_CALL webAssemblyInstantiateFunc(ExecState*);
EncodedJSValue JSC_HOST_CALL webAssemblyCompileFunc(ExecState* exec)
{
// FIXME: Make this truly asynchronous:
// https://bugs.webkit.org/show_bug.cgi?id=166016
- JSValue module = WebAssemblyModuleConstructor::createModule(exec, exec->lexicalGlobalObject()->WebAssemblyModuleStructure());
+ JSValue module = WebAssemblyModuleConstructor::createModule(exec, exec->argument(0), exec->lexicalGlobalObject()->WebAssemblyModuleStructure());
if (Exception* exception = catchScope.exception()) {
catchScope.clearException();
promise->reject(exec, exception->value());
return JSValue::encode(promise->promise());
}
+EncodedJSValue JSC_HOST_CALL webAssemblyInstantiateFunc(ExecState* exec)
+{
+ VM& vm = exec->vm();
+ auto catchScope = DECLARE_CATCH_SCOPE(vm);
+
+ // FIXME: Make this API truly asynchronous: https://bugs.webkit.org/show_bug.cgi?id=169187
+
+ JSPromiseDeferred* promise = JSPromiseDeferred::create(exec, exec->lexicalGlobalObject());
+ RETURN_IF_EXCEPTION(catchScope, encodedJSValue());
+
+ auto reject = [&] () {
+ Exception* exception = catchScope.exception();
+ ASSERT(exception);
+ catchScope.clearException();
+ promise->reject(exec, exception->value());
+ return JSValue::encode(promise->promise());
+ };
+
+ JSValue importArgument = exec->argument(1);
+ JSObject* importObject = importArgument.getObject();
+ if (!importArgument.isUndefined() && !importObject) {
+ promise->reject(exec, createTypeError(exec,
+ ASCIILiteral("second argument to WebAssembly.instantiate must be undefined or an Object"), defaultSourceAppender, runtimeTypeForValue(importArgument)));
+ return JSValue::encode(promise->promise());
+ }
+
+ JSValue firstArgument = exec->argument(0);
+ JSValue module;
+ bool firstArgumentIsModule = false;
+ if (firstArgument.inherits(vm, JSWebAssemblyModule::info())) {
+ firstArgumentIsModule = true;
+ module = firstArgument;
+ } else {
+ module = WebAssemblyModuleConstructor::createModule(exec, firstArgument, exec->lexicalGlobalObject()->WebAssemblyModuleStructure());
+ if (catchScope.exception())
+ return reject();
+ }
+
+ JSWebAssemblyInstance* instance = WebAssemblyInstanceConstructor::createInstance(exec, jsCast<JSWebAssemblyModule*>(module), importObject, exec->lexicalGlobalObject()->WebAssemblyInstanceStructure());
+ if (catchScope.exception())
+ return reject();
+
+ if (firstArgumentIsModule)
+ promise->resolve(exec, instance);
+ else {
+ JSObject* result = constructEmptyObject(exec);
+ result->putDirect(vm, Identifier::fromString(&vm, ASCIILiteral("module")), module);
+ result->putDirect(vm, Identifier::fromString(&vm, ASCIILiteral("instance")), instance);
+ promise->resolve(exec, result);
+ }
+
+ return JSValue::encode(promise->promise());
+}
+
EncodedJSValue JSC_HOST_CALL webAssemblyValidateFunc(ExecState* exec)
{
VM& vm = exec->vm();
ASSERT(inherits(vm, info()));
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("validate", webAssemblyValidateFunc, DontEnum, 1);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("compile", webAssemblyCompileFunc, DontEnum, 1);
+ JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("instantiate", webAssemblyInstantiateFunc, DontEnum, 1);
}
JSWebAssembly::JSWebAssembly(VM& vm, Structure* structure)
{
auto& vm = exec->vm();
auto throwScope = DECLARE_THROW_SCOPE(vm);
- auto* globalObject = exec->lexicalGlobalObject();
// If moduleObject is not a WebAssembly.Module instance, a TypeError is thrown.
JSWebAssemblyModule* jsModule = jsDynamicCast<JSWebAssemblyModule*>(vm, exec->argument(0));
if (!jsModule)
return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("first argument to WebAssembly.Instance must be a WebAssembly.Module"), defaultSourceAppender, runtimeTypeForValue(exec->argument(0)))));
- const Wasm::ModuleInformation& moduleInformation = jsModule->moduleInformation();
// If the importObject parameter is not undefined and Type(importObject) is not Object, a TypeError is thrown.
JSValue importArgument = exec->argument(1);
JSObject* importObject = importArgument.getObject();
if (!importArgument.isUndefined() && !importObject)
return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("second argument to WebAssembly.Instance must be undefined or an Object"), defaultSourceAppender, runtimeTypeForValue(importArgument))));
+
+ Structure* instanceStructure = InternalFunction::createSubclassStructure(exec, exec->newTarget(), exec->lexicalGlobalObject()->WebAssemblyInstanceStructure());
+ RETURN_IF_EXCEPTION(throwScope, { });
+
+ throwScope.release();
+ return JSValue::encode(WebAssemblyInstanceConstructor::createInstance(exec, jsModule, importObject, instanceStructure));
+}
+
+JSWebAssemblyInstance* WebAssemblyInstanceConstructor::createInstance(ExecState* exec, JSWebAssemblyModule* jsModule, JSObject* importObject, Structure* instanceStructure)
+{
+ auto& vm = exec->vm();
+ auto throwScope = DECLARE_THROW_SCOPE(vm);
+ auto* globalObject = exec->lexicalGlobalObject();
+
+ const Wasm::ModuleInformation& moduleInformation = jsModule->moduleInformation();
+
+ auto exception = [&] (JSObject* error) {
+ throwException(exec, throwScope, error);
+ return nullptr;
+ };
// If the list of module.imports is not empty and Type(importObject) is not Object, a TypeError is thrown.
if (moduleInformation.imports.size() && !importObject)
- return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("second argument to WebAssembly.Instance must be Object because the WebAssembly.Module has imports"), defaultSourceAppender, runtimeTypeForValue(importArgument))));
+ return exception(createTypeError(exec, ASCIILiteral("can't make WebAssembly.Instance because there is no imports Object and the WebAssembly.Module requires imports")));
Identifier moduleKey = Identifier::fromUid(PrivateName(PrivateName::Description, "WebAssemblyInstance"));
WebAssemblyModuleRecord* moduleRecord = WebAssemblyModuleRecord::create(exec, vm, globalObject->webAssemblyModuleRecordStructure(), moduleKey, moduleInformation);
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
- Structure* instanceStructure = InternalFunction::createSubclassStructure(exec, exec->newTarget(), globalObject->WebAssemblyInstanceStructure());
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
JSWebAssemblyInstance* instance = JSWebAssemblyInstance::create(vm, instanceStructure, jsModule, moduleRecord->getModuleNamespace(exec));
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
// Let funcs, memories and tables be initially-empty lists of callable JavaScript objects, WebAssembly.Memory objects and WebAssembly.Table objects, respectively.
for (auto& import : moduleInformation.imports) {
// 1. Let o be the resultant value of performing Get(importObject, i.module_name).
JSValue importModuleValue = importObject->get(exec, import.module);
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
// 2. If Type(o) is not Object, throw a TypeError.
if (!importModuleValue.isObject())
- return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("import must be an object"), defaultSourceAppender, runtimeTypeForValue(importModuleValue))));
+ return exception(createTypeError(exec, ASCIILiteral("import must be an object"), defaultSourceAppender, runtimeTypeForValue(importModuleValue)));
// 3. Let v be the value of performing Get(o, i.item_name)
JSObject* object = jsCast<JSObject*>(importModuleValue);
JSValue value = object->get(exec, import.field);
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
switch (import.kind) {
case Wasm::ExternalKind::Function: {
// 4. If i is a function import:
// i. If IsCallable(v) is false, throw a WebAssembly.LinkError.
if (!value.isFunction())
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("import function must be callable"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("import function must be callable")));
+
JSCell* cell = value.asCell();
// ii. If v is an Exported Function Exotic Object:
if (WebAssemblyFunction* importedExport = jsDynamicCast<WebAssemblyFunction*>(vm, cell)) {
Wasm::SignatureIndex importedSignatureIndex = importedExport->signatureIndex();
Wasm::SignatureIndex expectedSignatureIndex = moduleInformation.importFunctionSignatureIndices[import.kindIndex];
if (importedSignatureIndex != expectedSignatureIndex)
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("imported function's signature doesn't match the provided WebAssembly function's signature"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("imported function's signature doesn't match the provided WebAssembly function's signature")));
// b. Let closure be v.[[Closure]].
}
// iii. Otherwise:
JSWebAssemblyTable* table = jsDynamicCast<JSWebAssemblyTable*>(vm, value);
// i. If v is not a WebAssembly.Table object, throw a WebAssembly.LinkError.
if (!table)
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Table import is not an instance of WebAssembly.Table"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Table import is not an instance of WebAssembly.Table")));
uint32_t expectedInitial = moduleInformation.tableInformation.initial();
uint32_t actualInitial = table->size();
if (actualInitial < expectedInitial)
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Table import provided an 'initial' that is too small"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Table import provided an 'initial' that is too small")));
if (std::optional<uint32_t> expectedMaximum = moduleInformation.tableInformation.maximum()) {
std::optional<uint32_t> actualMaximum = table->maximum();
- if (!actualMaximum) {
- return JSValue::encode(
- throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Table import does not have a 'maximum' but the module requires that it does"))));
- }
- if (*actualMaximum > *expectedMaximum) {
- return JSValue::encode(
- throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Imported Table's 'maximum' is larger than the module's expected 'maximum'"))));
- }
+ if (!actualMaximum)
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Table import does not have a 'maximum' but the module requires that it does")));
+ if (*actualMaximum > *expectedMaximum)
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Imported Table's 'maximum' is larger than the module's expected 'maximum'")));
}
// ii. Append v to tables.
JSWebAssemblyMemory* memory = jsDynamicCast<JSWebAssemblyMemory*>(vm, value);
// i. If v is not a WebAssembly.Memory object, throw a WebAssembly.LinkError.
if (!memory)
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory import is not an instance of WebAssembly.Memory"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory import is not an instance of WebAssembly.Memory")));
Wasm::PageCount expectedInitial = moduleInformation.memory.initial();
Wasm::PageCount actualInitial = memory->memory().initial();
if (actualInitial < expectedInitial)
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory import provided an 'initial' that is too small"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory import provided an 'initial' that is too small")));
if (Wasm::PageCount expectedMaximum = moduleInformation.memory.maximum()) {
Wasm::PageCount actualMaximum = memory->memory().maximum();
- if (!actualMaximum) {
- return JSValue::encode(
- throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory import did not have a 'maximum' but the module requires that it does"))));
- }
-
- if (actualMaximum > expectedMaximum) {
- return JSValue::encode(
- throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory imports 'maximum' is larger than the module's expected 'maximum'"))));
- }
+ if (!actualMaximum)
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory import did not have a 'maximum' but the module requires that it does")));
+
+ if (actualMaximum > expectedMaximum)
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("Memory imports 'maximum' is larger than the module's expected 'maximum'")));
}
// ii. Append v to memories.
// iii. Append v.[[Memory]] to imports.
instance->setMemory(vm, exec, memory);
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
break;
}
case Wasm::ExternalKind::Global: {
ASSERT(moduleInformation.globals[import.kindIndex].mutability == Wasm::Global::Immutable);
// ii. If the global_type of i is i64 or Type(v) is not Number, throw a WebAssembly.LinkError.
if (moduleInformation.globals[import.kindIndex].type == Wasm::I64)
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("imported global cannot be an i64"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("imported global cannot be an i64")));
if (!value.isNumber())
- return JSValue::encode(throwException(exec, throwScope, createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("imported global must be a number"))));
+ return exception(createJSWebAssemblyLinkError(exec, vm, ASCIILiteral("imported global must be a number")));
// iii. Append ToWebAssemblyValue(v) to imports.
switch (moduleInformation.globals[import.kindIndex].type) {
case Wasm::I32:
else {
memory = Wasm::Memory::create(vm, moduleInformation.memory.initial(), moduleInformation.memory.maximum());
if (!memory)
- return JSValue::encode(throwException(exec, throwScope, createOutOfMemoryError(exec)));
+ return exception(createOutOfMemoryError(exec));
}
instance->setMemory(vm, exec,
JSWebAssemblyMemory::create(vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure(), memory.releaseNonNull()));
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
}
}
}
moduleRecord->link(exec, instance);
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
if (verbose)
moduleRecord->dump();
JSValue startResult = moduleRecord->evaluate(exec);
UNUSED_PARAM(startResult);
- RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
+ RETURN_IF_EXCEPTION(throwScope, nullptr);
- return JSValue::encode(instance);
+ return instance;
}
static EncodedJSValue JSC_HOST_CALL callJSWebAssemblyInstance(ExecState* state)