2 * Copyright (C) 2016 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "WebAssemblyInstanceConstructor.h"
29 #if ENABLE(WEBASSEMBLY)
31 #include "FunctionPrototype.h"
32 #include "JSCInlines.h"
33 #include "JSModuleEnvironment.h"
34 #include "JSModuleNamespaceObject.h"
35 #include "JSWebAssemblyInstance.h"
36 #include "JSWebAssemblyMemory.h"
37 #include "JSWebAssemblyModule.h"
38 #include "WebAssemblyFunction.h"
39 #include "WebAssemblyInstancePrototype.h"
40 #include "WebAssemblyModuleRecord.h"
42 #include "WebAssemblyInstanceConstructor.lut.h"
46 static const bool verbose = false;
48 const ClassInfo WebAssemblyInstanceConstructor::s_info = { "Function", &Base::s_info, &constructorTableWebAssemblyInstance, CREATE_METHOD_TABLE(WebAssemblyInstanceConstructor) };
50 /* Source for WebAssemblyInstanceConstructor.lut.h
51 @begin constructorTableWebAssemblyInstance
55 static EncodedJSValue JSC_HOST_CALL constructJSWebAssemblyInstance(ExecState* exec)
57 auto& vm = exec->vm();
58 auto throwScope = DECLARE_THROW_SCOPE(vm);
59 auto* globalObject = exec->lexicalGlobalObject();
61 // If moduleObject is not a WebAssembly.Module instance, a TypeError is thrown.
62 JSWebAssemblyModule* jsModule = jsDynamicCast<JSWebAssemblyModule*>(exec->argument(0));
64 return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("first argument to WebAssembly.Instance must be a WebAssembly.Module"), defaultSourceAppender, runtimeTypeForValue(exec->argument(0)))));
65 const Wasm::ModuleInformation& moduleInformation = jsModule->moduleInformation();
67 // If the importObject parameter is not undefined and Type(importObject) is not Object, a TypeError is thrown.
68 JSValue importArgument = exec->argument(1);
69 JSObject* importObject = importArgument.getObject();
70 if (!importArgument.isUndefined() && !importObject)
71 return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("second argument to WebAssembly.Instance must be undefined or an Object"), defaultSourceAppender, runtimeTypeForValue(importArgument))));
73 // If the list of module.imports is not empty and Type(importObject) is not Object, a TypeError is thrown.
74 if (moduleInformation.imports.size() && !importObject)
75 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))));
77 Identifier moduleKey = Identifier::fromUid(PrivateName(PrivateName::Description, "WebAssemblyInstance"));
78 WebAssemblyModuleRecord* moduleRecord = WebAssemblyModuleRecord::create(exec, vm, globalObject->webAssemblyModuleRecordStructure(), moduleKey, moduleInformation);
79 RETURN_IF_EXCEPTION(throwScope, { });
81 Structure* instanceStructure = InternalFunction::createSubclassStructure(exec, exec->newTarget(), globalObject->WebAssemblyInstanceStructure());
82 RETURN_IF_EXCEPTION(throwScope, { });
84 JSWebAssemblyInstance* instance = JSWebAssemblyInstance::create(vm, instanceStructure, jsModule, moduleRecord->getModuleNamespace(exec), moduleInformation.imports.size());
85 RETURN_IF_EXCEPTION(throwScope, { });
87 // Let funcs, memories and tables be initially-empty lists of callable JavaScript objects, WebAssembly.Memory objects and WebAssembly.Table objects, respectively.
88 // Let imports be an initially-empty list of external values.
89 unsigned numImportFunctions = 0;
91 // FIXME implement Table https://bugs.webkit.org/show_bug.cgi?id=164135
92 // FIXME implement Global https://bugs.webkit.org/show_bug.cgi?id=164133
94 bool hasMemoryImport = false;
95 // For each import i in module.imports:
96 for (auto& import : moduleInformation.imports) {
97 // 1. Let o be the resultant value of performing Get(importObject, i.module_name).
98 JSValue importModuleValue = importObject->get(exec, import.module);
99 RETURN_IF_EXCEPTION(throwScope, { });
100 // 2. If Type(o) is not Object, throw a TypeError.
101 if (!importModuleValue.isObject())
102 return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("import must be an object"), defaultSourceAppender, runtimeTypeForValue(importModuleValue))));
104 // 3. Let v be the value of performing Get(o, i.item_name)
105 JSObject* object = jsCast<JSObject*>(importModuleValue);
106 JSValue value = object->get(exec, import.field);
107 RETURN_IF_EXCEPTION(throwScope, { });
109 switch (import.kind) {
110 case Wasm::External::Function: {
111 // 4. If i is a function import:
112 // i. If IsCallable(v) is false, throw a TypeError.
113 if (!value.isFunction())
114 return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("import function must be callable"), defaultSourceAppender, runtimeTypeForValue(value))));
115 JSCell* cell = value.asCell();
116 // ii. If v is an Exported Function Exotic Object:
117 if (WebAssemblyFunction* importedExports = jsDynamicCast<WebAssemblyFunction*>(object)) {
118 // FIXME handle Function Exotic Object properly. https://bugs.webkit.org/show_bug.cgi?id=165282
119 // a. If the signature of v does not match the signature of i, throw a TypeError.
120 // b. Let closure be v.[[Closure]].
121 RELEASE_ASSERT_NOT_REACHED();
122 UNUSED_PARAM(importedExports);
126 // a. Let closure be a new host function of the given signature which calls v by coercing WebAssembly arguments to JavaScript arguments via ToJSValue and returns the result, if any, by coercing via ToWebAssemblyValue.
127 // Note: done as part of Plan compilation.
128 // iv. Append v to funcs.
129 instance->setImportFunction(vm, cell, numImportFunctions++);
130 // v. Append closure to imports.
133 case Wasm::External::Table: {
134 // 7. Otherwise (i is a table import):
135 // FIXME implement Table https://bugs.webkit.org/show_bug.cgi?id=164135
136 // i. If v is not a WebAssembly.Table object, throw a TypeError.
137 // ii. Append v to tables.
138 // iii. Append v.[[Table]] to imports.
139 RELEASE_ASSERT_NOT_REACHED();
142 case Wasm::External::Memory: {
143 // 6. If i is a memory import:
144 RELEASE_ASSERT(!hasMemoryImport); // This should be guaranteed by a validation failure.
145 RELEASE_ASSERT(moduleInformation.memory);
146 hasMemoryImport = true;
147 JSWebAssemblyMemory* memory = jsDynamicCast<JSWebAssemblyMemory*>(value);
148 // i. If v is not a WebAssembly.Memory object, throw a TypeError.
150 return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("Memory import is not an instance of WebAssembly.Memory"))));
152 Wasm::PageCount expectedInitial = moduleInformation.memory.initial();
153 Wasm::PageCount actualInitial = memory->memory()->initial();
154 if (actualInitial < expectedInitial)
155 return JSValue::encode(throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("Memory import provided an 'initial' that is too small"))));
157 if (Wasm::PageCount expectedMaximum = moduleInformation.memory.maximum()) {
158 Wasm::PageCount actualMaximum = memory->memory()->maximum();
159 if (!actualMaximum) {
160 return JSValue::encode(
161 throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("Memory import did not have a 'maximum' but the module requires that it does"))));
164 if (actualMaximum > expectedMaximum) {
165 return JSValue::encode(
166 throwException(exec, throwScope, createTypeError(exec, ASCIILiteral("Memory imports 'maximum' is larger than the module's expected 'maximum"))));
169 // ii. Append v to memories.
170 // iii. Append v.[[Memory]] to imports.
171 instance->setMemory(vm, memory);
174 case Wasm::External::Global: {
175 // 5. If i is a global import:
176 // FIXME implement Global https://bugs.webkit.org/show_bug.cgi?id=164133
177 // i. If i is not an immutable global, throw a TypeError.
178 // ii. If Type(v) is not Number, throw a TypeError.
179 // iii. Append ToWebAssemblyValue(v) to imports.
180 RELEASE_ASSERT_NOT_REACHED();
187 if (!!moduleInformation.memory && moduleInformation.memory.isImport()) {
188 // We should either have an import or we should have thrown an exception.
189 RELEASE_ASSERT(hasMemoryImport);
192 if (moduleInformation.memory && !hasMemoryImport) {
193 RELEASE_ASSERT(!moduleInformation.memory.isImport());
194 // We create a memory when it's a memory definition.
195 std::unique_ptr<Wasm::Memory> memory = std::make_unique<Wasm::Memory>(moduleInformation.memory.initial(), moduleInformation.memory.maximum());
196 instance->setMemory(vm,
197 JSWebAssemblyMemory::create(vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure(), WTFMove(memory)));
201 moduleRecord->link(exec, instance);
202 RETURN_IF_EXCEPTION(throwScope, { });
204 moduleRecord->dump();
205 JSValue startResult = moduleRecord->evaluate(exec);
206 UNUSED_PARAM(startResult);
207 RETURN_IF_EXCEPTION(throwScope, { });
209 return JSValue::encode(instance);
212 static EncodedJSValue JSC_HOST_CALL callJSWebAssemblyInstance(ExecState* state)
214 VM& vm = state->vm();
215 auto scope = DECLARE_THROW_SCOPE(vm);
216 return JSValue::encode(throwConstructorCannotBeCalledAsFunctionTypeError(state, scope, "WebAssembly.Instance"));
219 WebAssemblyInstanceConstructor* WebAssemblyInstanceConstructor::create(VM& vm, Structure* structure, WebAssemblyInstancePrototype* thisPrototype)
221 auto* constructor = new (NotNull, allocateCell<WebAssemblyInstanceConstructor>(vm.heap)) WebAssemblyInstanceConstructor(vm, structure);
222 constructor->finishCreation(vm, thisPrototype);
226 Structure* WebAssemblyInstanceConstructor::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
228 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
231 void WebAssemblyInstanceConstructor::finishCreation(VM& vm, WebAssemblyInstancePrototype* prototype)
233 Base::finishCreation(vm, ASCIILiteral("Instance"));
234 putDirectWithoutTransition(vm, vm.propertyNames->prototype, prototype, DontEnum | DontDelete | ReadOnly);
235 putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(1), ReadOnly | DontEnum | DontDelete);
238 WebAssemblyInstanceConstructor::WebAssemblyInstanceConstructor(VM& vm, Structure* structure)
239 : Base(vm, structure)
243 ConstructType WebAssemblyInstanceConstructor::getConstructData(JSCell*, ConstructData& constructData)
245 constructData.native.function = constructJSWebAssemblyInstance;
246 return ConstructType::Host;
249 CallType WebAssemblyInstanceConstructor::getCallData(JSCell*, CallData& callData)
251 callData.native.function = callJSWebAssemblyInstance;
252 return CallType::Host;
255 void WebAssemblyInstanceConstructor::visitChildren(JSCell* cell, SlotVisitor& visitor)
257 auto* thisObject = jsCast<WebAssemblyInstanceConstructor*>(cell);
258 ASSERT_GC_OBJECT_INHERITS(thisObject, info());
259 Base::visitChildren(thisObject, visitor);
264 #endif // ENABLE(WEBASSEMBLY)