This API privides a way to access WebAssembly [WEBASSEMBLY] through a bridge to explicitly construct modules from JavaScript [ECMASCRIPT].
See the Issues Index for complete list of issues.
1. Sample API Usage
This section is non-normative.
Given demo.wat
(encoded to demo.wasm
):
(module (import "js" "import1" (func $i1)) (import "js" "import2" (func $i2)) (func $main (call $i1)) (start $main) (func (export "f") (call $i2)) )
and the following JavaScript, run in a browser:
var importObj = {js: { import1: () => console.log("hello,"), import2: () => console.log("world!") }}; fetch('demo.wasm').then(response => response.arrayBuffer() ).then(buffer => WebAssembly.instantiate(buffer, importObj) ).then(({module, instance}) => instance.exports.f() );
2. Internal storage
2.1. Interaction of the WebAssembly Store with JavaScript
Note: WebAssembly semantics are defined in terms of an abstract store, representing the state of the WebAssembly abstract machine. WebAssembly operations take a store and return an updated store.
Each agent has an associated store. When a new agent is created, its associated store is set to the result of init_store().
Note: In this specification, no WebAssembly-related objects, memory or addresses can be shared among agents in an agent cluster. In a future version of WebAssembly, this may change.
Elements of the WebAssembly store may be identified with JavaScript values. In particular, each WebAssembly memory instance with a corresponding Memory
object is identified with a JavaScript Data Block; modifications to this Data Block are identified to updating the agent’s store to a store which reflects those changes, and vice versa.
2.2. WebAssembly JS Object Caches
Note: There are several WebAssembly objects that may have a corresponding JavaScript object. The correspondence is stored in a per-agent mapping from WebAssembly addresses to JavaScript objects. This mapping is used to ensure that, for a given agent, there exists at most one JavaScript object for a particular WebAssembly address.
Each agent is associated with the following ordered maps:
-
The Memory object cache, mapping memory addresses to
Memory
objects. -
The Table object cache, mapping table addresses to
Table
objects. -
The Exported Function cache, mapping function addresses to Exported Function objects.
3. The WebAssembly Namespace
dictionaryWebAssemblyInstantiatedSource
{ required Modulemodule
; required Instanceinstance
; }; [Exposed=(Window,Worker,Worklet)] namespaceWebAssembly
{ boolean validate(BufferSourcebytes
); Promise<Module> compile(BufferSourcebytes
); Promise<WebAssemblyInstantiatedSource> instantiate( BufferSourcebytes
, optional objectimportObject
); Promise<Instance> instantiate( ModulemoduleObject
, optional objectimportObject
); };
BufferSource
bytes, perform the following steps:
-
Let module be decode_module(bytes). If module is error, return error.
-
If validate_module(module) is error, return error.
-
Return module.
validate(bytes)
method, when invoked, performs the following steps:
Module
object represents a single WebAssembly module. Each Module
object has the following internal slots:
-
[[Module]] : a WebAssembly module
-
[[Bytes]] : an
ArrayBuffer
which is source bytes of [[Module]].
-
Let moduleObject be a new
Module
object. -
Set moduleObject.[[Module]] to module.
-
Set moduleObject.[[Bytes]] to bytes.
-
Return moduleObject.
BufferSource
bytes, with the promise promise, using optional task source taskSource, perform the following steps:
-
In parallel, compile the WebAssembly module bytes and store the result as module.
-
When the above operation completes, queue a task to perform the following steps. If taskSource was provided, queue the task on that task source.
-
If module is error, reject promise with a
CompileError
exception. -
Otherwise,
-
Construct a WebAssembly module object from module and bytes, and let moduleObject be the result.
-
Resolve promise with moduleObject.
-
-
compile(bytes)
method, when invoked, performs the following steps:
-
Let stableBytes be a copy of the bytes held by the buffer bytes.
-
Let promise be a new promise.
-
Asynchronously compile a WebAssembly module from stableBytes with promise.
-
Return promise.
Module
moduleObject and imports importObject, perform the following steps:
-
Let module be moduleObject.[[Module]].
-
If module.𝗂𝗆𝗉𝗈𝗋𝗍𝗌 is not an empty list, and importObject is undefined, throw a
TypeError
exception. -
Let imports be an empty list of external values.
-
For each (moduleName, componentName, externtype) in module_imports(module), do
-
Let o be ? Get(importObject, moduleName).
-
Let v be ? Get(o, componentName)
-
If externtype is of the form 𝖿𝗎𝗇𝖼 functype,
-
If IsCallable(v) is false, throw a
LinkError
exception. -
If v has a [[FunctionAddress]] internal slot, and therefore is an Exported Function,
-
Let funcaddr be the value of v’s [[FunctionAddress]] internal slot.
Note: The signature is checked by instantiate_module invoked below.
-
-
Otherwise,
-
Create a host function from v and let funcaddr be the result.
-
Let index be the number of external functions in imports. This value index is known as the index of the host function funcaddr.
-
-
Let externfunc be the external value 𝖿𝗎𝗇𝖼 funcaddr.
-
Append externfunc to imports.
-
-
If externtype is of the form 𝗀𝗅𝗈𝖻𝖺𝗅 globaltype,
-
If globaltype is 𝗂𝟨𝟦 or Type(v) is not Number, throw a
LinkError
exception. -
Let value be ToWebAssemblyValue(v, globaltype.valtype)
-
Assert: globaltype.mut is 𝖼𝗈𝗇𝗌𝗍, as verified by WebAssembly validation.
-
Let store be the surrounding agent's associated store.
-
Let (store, globaladdr) be alloc_global(store, globaltype, value).
-
Set the surrounding agent's associated store to store.
-
Let externglobal be 𝗀𝗅𝗈𝖻𝖺𝗅 globaladdr.
-
Append externglobal to imports.
-
-
If externtype is of the form 𝗆𝖾𝗆 memtype,
Note: instantiate_module invoked below will check the imported
Memory
's size against the importing module’s requirements.-
Let externmem be the external value 𝗆𝖾𝗆 v.[[Memory]].
-
Append externmem to imports.
-
-
Otherwise, externtype is of the form 𝗍𝖺𝖻𝗅𝖾 tabletype,
Note: The table’s length, etc. is checked by instantiate_module invoked below.
-
Let tableaddr be v.[[Table]]
-
Let externtable be the external value 𝗍𝖺𝖻𝗅𝖾 tableaddr.
-
Append externtable to imports.
-
-
-
Let (store, instance) be instantiate_module(store, module, imports).
-
If instance is error, throw an appropriate exception type:
-
A
LinkError
exception for most cases which occur during linking. -
If the error came when running the start function, throw a
RuntimeError
for most errors which occur from WebAssembly, or the error object propagated from inner ECMAScript code. -
Another error type if appropriate, for example an out-of-memory exception, as documented in the WebAssembly error mapping.
-
-
Let exportsObject be ! ObjectCreate(null).
-
For each pair (name, externtype) in module_exports(module),
-
Let externval be get_export(instance, name).
-
Assert: externval is not error.
-
If externtype is of the form 𝖿𝗎𝗇𝖼 functype,
-
Assert: externval is of the form 𝖿𝗎𝗇𝖼 funcaddr.
-
Let 𝖿𝗎𝗇𝖼 funcaddr be externval.
-
Let func be the result of creating a new Exported Function from funcaddr.
-
Let value be func.
-
-
If externtype is of the form 𝗀𝗅𝗈𝖻𝖺𝗅 globaltype,
-
If externtype is of the form 𝗆𝖾𝗆 memtype,
-
Assert: externval is of the form 𝗆𝖾𝗆 memaddr.
-
Let 𝗆𝖾𝗆 memaddr be externval.
-
Let memory be a new Memory object created from memaddr.
-
Let value be memory.
-
-
Otherwise, externtype is of the form 𝗍𝖺𝖻𝗅𝖾 tabletype,
-
Assert: externval is of the form 𝗍𝖺𝖻𝗅𝖾 tableaddr.
-
Let 𝗍𝖺𝖻𝗅𝖾 tableaddr be externval.
-
Let table be a new Table object created from tableaddr.
-
Let value be table.
-
-
Let status be ! CreateDataProperty(exportsObject, name, value).
-
Assert: status is true.
Note: the validity and uniqueness checks performed during WebAssembly module validation ensure that each property name is valid and no properties are defined twice.
-
-
Perform ! SetIntegrityLevel(exportsObject,
"frozen"
). -
Let instanceObject be a new
Instance
object whose internal [[Instance]] slot is set to instance and the [[Exports]] slot to exportsObject. -
Return instanceObject.
-
Let promise be a new promise
-
Upon fulfillment of promiseOfModule with value module:
-
Instantiate the WebAssembly module module importing importObject, and let instance be the result. If this throws an exception, catch it, reject promise with the exception, and abort these substeps.
-
Let result be a
WebAssemblyInstantiatedSource
dictionary withmodule
set to module andinstance
set to instance. -
Resolve promise with result.
-
-
Upon rejection of promiseOfModule with reason reason:
-
Reject promise with reason.
-
-
Return promise.
Note: It would be valid to perform certain parts of the instantiation in parallel, but several parts need to happen in the event loop, including JavaScript operations to access the importObject and execution of the start function.
instantiate(bytes, importObject)
method, when invoked, performs the following steps:
-
Let stableBytes be a copy of the bytes held by the buffer bytes.
-
Let promiseOfModule be a new promise.
-
Asynchronously compile a WebAssembly module from stableBytes with promiseOfModule.
-
Instantiate promiseOfModule with imports importObject and return the result.
instantiate(moduleObject, importObject)
method, when invoked, performs the following steps:
-
Let promise be a new promise.
-
Queue a task to perform the following steps:
-
Instantiate the WebAssembly module module importing importObject, and let instance be the result. If this throws an exception, catch it, and reject promise with the exception.
-
Resolve promise with instance.
-
-
Return promise
Note: A follow-on streaming API is documented in the WebAssembly Web API.
3.1. Modules
enumImportExportKind
{"function"
,"table"
,"memory"
,"global"
}; dictionaryModuleExportDescriptor
{ required USVStringname
; required ImportExportKindkind
; // Note: Other fields such as signature may be added in the future. }; dictionaryModuleImportDescriptor
{ required USVStringmodule
; required USVStringname
; required ImportExportKindkind
; }; [LegacyNamespace=WebAssembly, Constructor(BufferSourcebytes
), Exposed=(Window,Worker,Worklet)] interfaceModule
{ static sequence<ModuleExportDescriptor>exports
(Modulemodule
); static sequence<ModuleImportDescriptor>imports
(Modulemodule
); static sequence<ArrayBuffer>customSections
(Modulemodule
, USVStringsectionName
); };
exports(moduleObject)
method, when invoked, performs the following steps:
-
Let module be moduleObject.[[Module]].
-
Let exports be an empty list.
-
For each (name, type) in module_exports(module)
-
Let kind be the string value of the extern type type.
-
Let obj be a new
ModuleExportDescriptor
dictionary withname
name andkind
kind. -
Append obj to the end of exports.
-
-
Return exports.
imports(moduleObject)
method, when invoked, performs the following steps:
-
Let module be moduleObject.[[Module]].
-
Let imports be an empty list.
-
For each (moduleName, name, type) in module_imports(module),
-
Let kind be the string value of the extern type type.
-
Let obj be a new
ModuleImportDescriptor
dictionary withmodule
moduleName,name
name andkind
kind. -
Append obj to the end of imports.
-
-
Return imports.
customSections(moduleObject, sectionName)
method, when invoked, performs the following steps:
-
Let bytes be moduleObject.[[Bytes]].
-
Let customSections be an empty list of
ArrayBuffer
s. -
For each custom section customSection in the binary format of bytes,
-
Let name be the
name
of the custom section, decoded as UTF-8. -
Assert: name is not failure (moduleObject.[[Module]] is valid).
-
If name equals secondName as string values,
-
Append a new
ArrayBuffer
containing a copy of the bytes held by the buffer bytes for the range matched by this customsec production.
-
-
-
Return customSections.
Module(bytes)
constructor, when invoked, performs the follwing steps:
-
Let stableBytes be a copy of the bytes held by the buffer bytes.
-
Compile the WebAssembly module stableBytes and store the result as module.
-
If module is error, throw a
CompileError
exception. -
Construct a WebAssembly module object from module and bytes, and return the result.
3.2. Instances
[LegacyNamespace=WebAssembly, Constructor(Modulemodule
, optional objectimportObject
), Exposed=(Window,Worker,Worklet)] interfaceInstance
{ readonly attribute object exports; };
Instance(module, importObject)
constructor, when invoked, instantiates the WebAssembly module module importing importObject and returns the result. exports
attribute of Instance
returns the receiver’s [[Exports]] internal slot. 3.3. Memories
dictionaryMemoryDescriptor
{ required [EnforceRange] unsigned longinitial
; [EnforceRange] unsigned longmaximum
; }; [LegacyNamespace=WebAssembly, Constructor(MemoryDescriptordescriptor
), Exposed=(Window,Worker,Worklet)] interfaceMemory
{ unsigned long grow([EnforceRange] unsigned longdelta
); readonly attribute ArrayBufferbuffer
; };
Memory
object represents a single memory instance which can be simultaneously referenced by multiple Instance
objects. Each Memory
object has the following internal slots:
-
[[Memory]] : a memory address
-
[[BufferObject]] : an
ArrayBuffer
whose Data Block is identified with the above memory address
-
Let map be the surrounding agent's associated Memory object cache.
-
If map[memaddr] exists,
-
Return map[memaddr].
-
-
Let block be a Data Block which is identified with the underlying memory of memaddr
-
Let buffer be a new
ArrayBuffer
whose [[ArrayBufferData]] is block and [[ArrayBufferByteLength]] is set to the length of block. -
Let memory be a new
Memory
instance with [[Memory]] set to memaddr and [[BufferObject]] set to buffer. -
Set map[memaddr] to memory.
-
Return memory.
Any attempts to detach buffer, other than the detachment performed by grow(delta)
, will throw a TypeError
exception. Specifying this behavior requires changes to the ECMAScript specification.
Memory(descriptor)
constructor, when invoked, performs the following steps:
-
If descriptor["initial"] is present, let initial be descriptor["initial"]; otherwise, let initial be 0.
-
If descriptor["maximum"] is present, let maximum be descriptor["maximum"]; otherwise, let maximum be empty.
-
Let memtype be { min initial, max maximum }
-
Let store be the surrounding agent's associated store.
-
Let (store, memaddr) be alloc_mem(store, memtype). If allocation fails, throw a
RangeError
exception. -
Set the surrounding agent's associated store to store.
-
Create a memory object from the memory address memaddr and return the result.
-
Let map be the surrounding agent's associated Memory object cache.
-
Assert: map[memaddr] exists
-
Let memory be map[memaddr].
-
Perform ! DetachArrayBuffer(memory.[[BufferObject]]).
-
Let block be a Data Block which is identified with the underlying memory of memaddr.
-
Let buffer be a new
ArrayBuffer
whose [[ArrayBufferData]] is block and [[ArrayBufferByteLength]] is set to the length of block. -
Set memory.[[BufferObject]] to buffer.
grow(delta)
method, when invoked, performs the following steps:
-
Let memory be the Memory instance.
-
Let store be the surrounding agent's associated store.
-
Let memaddr be memory.[[Memory]].
-
Let ret be the size_mem(store, memaddr).
-
Let store be grow_mem(store, memaddr, delta).
-
If store is error, throw a
RangeError
exception. -
Set the surrounding agent's associated store to store.
-
Reset the memory buffer of memaddr.
-
Return ret.
Immediately after a WebAssembly grow_memory instruction executes, perform the following steps:
-
If the top of the stack is not 𝗂𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 (−1), then:
-
Let frame be the current frame.
-
Reset the memory buffer of memaddr.
-
3.4. Tables
enumTableKind
{"anyfunc"
, // Note: More values may be added in future iterations, // e.g., typed function references, typed GC references }; dictionaryTableDescriptor
{ required TableKindelement
; required [EnforceRange] unsigned longinitial
; [EnforceRange] unsigned longmaximum
; }; [LegacyNamespace=WebAssembly, Constructor(TableDescriptordescriptor
), Exposed=(Window,Worker,Worklet)] interfaceTable
{ unsigned longgrow
([EnforceRange] unsigned longdelta
); Function? get([EnforceRange] unsigned longindex
); void set([EnforceRange] unsigned longindex
, Function?value
); readonly attribute unsigned long length; };
Table
object represents a single table instance which can be simultaneously referenced by multiple Instance
objects. Each Table
object has the following internal slots:
-
[[Table]] : a table address
-
[[Values]] : a List whose elements are either null or Exported Functions.
-
Let map be the surrounding agent's associated Table object cache.
-
If map[tableaddr] exists,
-
Return map[tableaddr].
-
-
Let values be a list whose length is size_table(store, tableaddr) where each element is null.
-
Let table be a new
Table
instance with [[Table]] set to tableaddr and [[Values]] set to values. -
Set map[tableaddr] to table.
-
Return table.
Table(descriptor)
constructor, when invoked, performs the following steps:
-
If descriptor["initial"] is present, let n be descriptor["initial"]; otherwise, let n be 0.
-
If descriptor["maximum"] is present, let m be descriptor["maximum"]; otherwise, let m be empty.
-
If m is not empty and m < n, throw a
RangeError
exception. -
Let type be the table type {𝗆𝗂𝗇 n, 𝗆𝖺𝗑 m} 𝖺𝗇𝗒𝖿𝗎𝗇𝖼.
-
Let store be the surrounding agent's associated store.
-
Let (store, tableaddr) be alloc_table(store, type).
-
Set the surrounding agent's associated store to store.
-
Create a table object from the table address tableaddr and return the result.
grow(d)
method, when invoked, performs the following steps:
-
Let tableaddr be the Table instance’s [[Table]] internal slot.
-
Let initialSize be the length of the Table instance’s [[Values]] internal slot.
-
Let store be the surrounding agent's associated store.
-
Let result be grow_table(store, tableaddr, d).
-
If result is error, throw a
RangeError
exception.Note: The above exception may happen due to either insufficient memory or an invalid size parameter.
-
Set the surrounding agent's associated store to store.
-
Append null to the Table instance’s [[Values]] internal slot d times.
-
Return initialSize.
length
attribute of Table
returns the length of the table’s [[Values]] internal slot. get(index)
method, when invoked, performs the following steps:
-
Let values be the Table instance’s [[Values]] internal slot.
-
Let size be the length of values.
-
If index ≥ size, throw a
RangeError
exception. -
Return values[index].
set(index, value)
method, when invoked, performs the following steps:
-
Let tableaddr be the Table instance’s [[Table]] internal slot.
-
Let values be the Table instance’s [[Values]] internal slot.
-
If value is null, let funcaddr be an empty function element.
-
Otherwise,
-
If value does not have a [[FunctionAddress]] internal slot, throw a
TypeError
exception. -
Let funcaddr be value.[[FunctionAddress]].
-
-
Let store be the surrounding agent's associated store.
-
Let store be write_table(store, tableaddr, index, funcaddr).
-
If store is error, throw a
RangeError
exception. -
Set the surrounding agent's associated store to store.
-
Set values[index] to value.
-
Return undefined.
3.5. Exported Functions
A WebAssembly function is made available in JavaScript as an Exported Function. Exported Functions are Built-in Function Objects which are not constructors, and which have a [[FunctionAddress]] internal slot. This slot holds a function address relative to the surrounding agent's associated store.
-
Let store be the surrounding agent's associated store.
-
Let funcinst be store.𝖿𝗎𝗇𝖼𝗌[funcaddr].
-
If funcinst is of the form {𝗍𝗒𝗉𝖾 functype, 𝗁𝗈𝗌𝗍𝖼𝗈𝖽𝖾 hostfunc},
-
Assert: hostfunc is a JavaScript object and IsCallable(hostfunc) is true.
-
Let index be the index of the host function funcaddr.
-
-
Otherwise,
-
Let moduleinst be funcinst.𝗆𝗈𝖽𝗎𝗅𝖾.
-
Assert: funcaddr is contained in moduleinst.𝖿𝗎𝗇𝖼𝖺𝖽𝖽𝗋𝗌.
-
Let index be the index of moduleinst.𝖿𝗎𝗇𝖼𝖺𝖽𝖽𝗋𝗌 where funcaddr is found.
-
-
Return ! ToString(index).
-
Let map be the surrounding agent's associated Exported Function cache.
-
If map[funcaddr] exists,
-
Return map[funcaddr].
-
-
Let steps be "call the Exported Function funcaddr with arguments."
-
Let realm be the current Realm.
-
Let function be CreateBuiltinFunction(realm, steps, %FunctionPrototype%, « [[FunctionAddress]]).
-
Set function.[[FunctionAddress]] to funcaddr.
-
Let store be the surrounding agent's associated store.
-
Let functype be type_func(store, funcaddr).
-
Let [arguments] → [results] be functype.
-
Let arity be the length of arguments.
-
Perform ! DefinePropertyOrThrow(function,
"length"
, PropertyDescriptor {[[Value]]: arity, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true}). -
Let name be the name of the WebAssembly function funcaddr.
-
Perform ! SetFunctionName(function, name).
-
Set map[funcaddr] to function.
-
Return function.
-
Let store be the surrounding agent's associated store.
-
Let functype be type_func(store, funcaddr).
-
Let [parameters] → [results] be functype.
-
If parameters or results contains an 𝗂𝟨𝟦, throw a
TypeError
.Note: the above error is thrown each time the [[Call]] method is invoked.
-
Let args be an empty list of WebAssembly values.
-
Let i be 0.
-
For each type t of parameters,
-
If the length of argValues > i, let arg be argValues[i].
-
Otherwise, let arg be undefined.
-
Append ToWebAssemblyValue(arg, t) to args.
-
Set i to i + 1.
-
-
Let (store, ret) be the result of invoke_func(store, funcaddr, args).
-
Set the surrounding agent's associated store to store.
-
If ret is error, throw an exception. This exception should be a WebAssembly
RuntimeError
exception, unless otherwise indicated by the WebAssembly error mapping. -
If outArity is 0, return undefined.
-
Otherwise, return ToJSValue(v), where v is the singular element of ret.
Note: Calling an Exported Function executes in the [[Realm]] of the callee Exported Function, as per the definition of built-in function objects.
Note: Exported Functions do not have a [[Construct]] method and thus it is not possible to call one with the new
operator.
-
Let hostfunc be a host function which performs the following steps when called:
-
If the signature contains an 𝗂𝟨𝟦 (as argument or result), the host function throws a
TypeError
when called. -
Let arguments be a list of the arguments of the invocation of this function.
-
Let jsArguments be an empty list.
-
For each arg in arguments,
-
Let ret be ? Call(func, undefined, jsArguments). If an exception is thrown, trigger a WebAssembly trap, and propagate the exception to the enclosing JavaScript.
-
Let [parameters] → [results] be functype.
-
If results is empty, return undefined.
-
Otherwise, return ToWebAssemblyValue(ret, results[0]).
-
-
Let store be the surrounding agent's associated store.
-
Let (store, funcaddr) be alloc_func(store, functype, hostfunc).
-
Set the surrounding agent's associated store to store.
-
Return funcaddr
Assert: w is not of the form 𝗂𝟨𝟦.𝖼𝗈𝗇𝗌𝗍 i64.
-
If w is of the form 𝗂𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 i32, return the Number value for signed_32(i32).
-
If w is of the form 𝖿𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 f32, return the Number value for f32.
-
If w is of the form 𝖿𝟨𝟦.𝖼𝗈𝗇𝗌𝗍 f64, return the Number value for f64.
Note: Implementations may optionally replace the NaN payload with any other NaN payload at this point in the f32 or f64 cases; such a change would not be observable through NumberToRawBytes.
Assert: type is not 𝗂𝟨𝟦.
3.6. Error Objects
WebAssembly defines the following Error classes: CompileError
, LinkError
, and RuntimeError
. WebAssembly errors have the following custom bindings:
-
Unlike normal interface types, the interface prototype object for these exception classes must have as its [[Prototype]] the intrinsic object %ErrorPrototype%.
-
The constructor and properties of WebAssembly errors is as specified for
NativeError
. -
If an implementation gives native Error objects special powers or nonstandard properties (such as a stack property), it should also expose those on these exception instances.
[LegacyNamespace=WebAssembly] interfaceCompileError
{ }; [LegacyNamespace=WebAssembly] interfaceLinkError
{ }; [LegacyNamespace=WebAssembly] interfaceRuntimeError
{ };
4. Error Condition Mappings to JavaScript
Running WebAssembly programs encounter certain events which halt execution of the WebAssembly code. WebAssembly code (currently) has no way to catch these conditions and thus an exception will necessarily propagate to the enclosing non-WebAssembly caller (whether it is a browser, JavaScript or another runtime system) where it is handled like a normal JavaScript exception.
If WebAssembly calls JavaScript via import and the JavaScript throws an exception, the exception is propagated through the WebAssembly activation to the enclosing caller.
Because JavaScript exceptions can be handled, and JavaScript can continue to call WebAssembly exports after a trap has been handled, traps do not, in general, prevent future execution.
4.1. Stack Overflow
Whenever a stack overflow occurs in WebAssembly code, the same class of exception is thrown as for a stack overflow in JavaScript. The particular exception here is implementation-defined in both cases.
Note: ECMAScript doesn’t specify any sort of behavior on stack overflow; implementations have been observed to throw RangeError
, InternalError or Error. Any is valid here.
4.2. Out of Memory
Whenever validation, compilation or instantiation run out of memory, the same class of exception is thrown as for out of memory conditions in JavaScript. The particular exception here is implementation-defined in both cases.
Note: ECMAScript doesn’t specify any sort of behavior on out-of-memory conditions; implementations have been observed to throw OOMError and to crash. Either is valid here.
5. Integration with ECMAScript modules
WebAssembly modules can be used in a module graph with ECMAScript modules.
WebAssembly Module Records are a subclass of Circular Module Records which contain WebAssembly code. WebAssembly Module Records has one additional internal slot:
-
[[WebAssemblyModule]] : a WebAssembly
Module
object
ArrayBuffer
body, a Realm realm and object hostDefined, perform the following steps.
-
Compile the WebAssembly module stableBytes and store the result as module.
-
If module is error, throw a
CompileError
exception. -
Construct a WebAssembly module object from module and bytes, and let module be the result.
-
Let requestedModules be a set.
-
For each (moduleName, name, type) in module_imports(module.[[Module]]),
-
Append moduleName to requestedModules.
-
-
Return { [[Realm]]: realm, [[Environment]]: undefined, [[Namespace]]: undefined, [[Status]]: "uninstantiated", [[EvaluationError]]: undefined, [[HostDefined]]: hostDefined, [[WebAssemblyModule]]: module, [[RequestedModules]]: requestedModules, [[DFSIndex]]: undefined, [[DFSAncestorIndex]]: undefined }.
-
Let module be record’s [[WebAssemblyModule]] internal slot.
-
Let exports be an empty list.
-
For each (name, type) in module_exports(module.[[Module]])
-
Append name to the end of exports.
-
-
Return exports.
WebAssembly Module Records have the following methods:
5.1. GetExportedNames ( exportStarSet ) Concrete Method
-
Let record be this WebAssembly Module Record.
-
Return the export name list of record.
5.2. ResolveExport ( exportName, resolveSet ) Concrete Method
-
Let record be this WebAssembly Module Record.
-
If the export name list of record contains exportName, return { [[Module]]: record, [[BindingName]]: exportName }.
-
Otherwise, return null.
5.3. ModuleDeclarationEnvironmentSetup ( ) Concrete Method
-
Let record be this WebAssembly Module Record.
-
Let env be NewModuleEnvironment(null).
-
Set record.[[Environment]] to env.
-
Let envRec be env’s EnvironmentRecord.
-
For each name in the export name list of record,
-
Perform ! envRec.CreateImmutableBinding(name, true).
-
5.4. ModuleExecution ( ) Concrete Method
-
Let record be this WebAssembly Module Record.
-
Let module be record.[[WebAssemblyModule]].
-
Let imports be a new, empty map.
-
For each (importedModuleName, name, type) in module_imports(module.[[Module]]),
-
If imports[importedModuleName] does not exist, set imports[importedModuleName] to a new, empty map.
-
Let importedModule be ! HostResolveImportedModule(module, importedModuleName).
-
NOTE: The above call cannot fail because imported module requests are a subset of module.[[RequestedModules]], and these have been resolved earlier in this algorithm.
-
Let value be ? importedModule.[[Environment]].GetBindingValue(name, true).
-
Set imports[moduleName][name] to value.
-
-
Let importsObject be a new Object.
-
For each key → value of imports,
-
Let moduleImportsObject be a new Object.
-
For each importedName → importedValue of imports,
-
Perform ! CreateDataPropertyOrThrow(moduleImportsObject, importedName, importedValuealue).
-
-
Perform ! CreateDataPropertyOrThrow(importsObject, key, moduleImportsObject).
-
-
Instantiate a WebAssembly module module with imports importsObject and let instance be the result.
-
Let envRec be the EnvironmentRecord of record.[[Environment]].
-
For each name in the export name list of record,
-
Perform ! envRec.InitializeBinding(name, ! Get(instance.[[Exports]], name)).
-
Note: Instantiating the WebAssembly module may yield to the task queue and is not guaranteed to be synchronous.
5.5. Modifications to HTML
The fetch a single module script algorithm, in Step 9, would switch off of the mimetype. If the response has a JavaScript mimetype, continue the algorithm. If it has a non-wasm mimetype, abort the algorithm. If it has an application/wasm
mimetype, perform the following steps:
-
Let source be response’s body as an
ArrayBuffer
-
Create a module script, but with step 7 replacing ParseModule with the parse a WebAssembly Module algorithm.
-
Set moduleMap[url] to to module
TODO: Write this up as a PR against the HTML spec.