This document is an early draft, porting the official JS/WebAssembly interface specification to WebIDL and Bikeshed. It should currently not be used as the WebAssembly specification.
This API is, initially, the only API for accessing WebAssembly [WEBASSEMBLY] from the web platform, through a bridge to explicitly construct modules from ECMAScript [ECMASCRIPT].
In future versions, WebAssembly may
be loaded and run directly from an HTML <script type='module'>
tag—and
any other Web API that loads ES6 modules via URL—as part of ES6 Module integration.)
Note: WebAssembly JS API declaration file for TypeScript can be found here which enable autocompletion and make TypeScript compiler happy.
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 four 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.
-
The Global object cache, mapping global addresses to
Global
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 two 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 Type(v) is Number,
-
Let value be ToWebAssemblyValue(v, globaltype.valtype)
-
Let store be the current agent’s associated store.
-
Let (store, globaladdr) be alloc_global(store, globaltype, value).
-
Set the current agent’s associated store to store.
-
If v is a
Global
instance,-
Let globaladdr be v.[[Global]]
-
-
Otherwise,
-
Throw a
LinkError
exception.
-
-
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,
-
Assert: externval is of the form 𝗀𝗅𝗈𝖻𝖺𝗅 globaladdr.
-
Let 𝗀𝗅𝗈𝖻𝖺𝗅 globaladdr be externval.
-
Let global be a new Global object created from globaladdr.
-
Let value be global.
-
-
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 two internal slots:
-
[[Memory]] : a memory address
-
[[BufferObject]] : an
ArrayBuffer
whose Data Block is identified with the above memory address
-
Let map be the current 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 current agent’s associated store.
-
Let (store, memaddr) be alloc_mem(store, memtype). If allocation fails, throw a
RangeError
exception. -
Set the current agent’s associated store to store.
-
Create a memory object from the memory address memaddr and return the result.
grow(delta)
method, when invoked, performs the following steps:
-
Let memory be the Memory instance.
-
Let store be the current 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 current agent’s associated store to store.
-
Perform ! DetachArrayBuffer(memory.[[BufferObject]]).
-
Let block be a Data Block which is identified with the underlying memory of memaddr.
-
Assert: The size of block is the same as size_mem(store, memaddr) * 64 Ki
-
Let buffer be a new
ArrayBuffer
whose [[ArrayBufferData]] is block and [[ArrayBufferByteLength]] is set to the length of block. -
Set memory.[[BufferObject]] to buffer.
-
Return ret.
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 longdelta
); voidset
([EnforceRange] unsigned longdelta
, 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 one internal slots:
-
[[Table]] : a table address
-
[[Values]] : a List whose elements are either null or Exported Functions.
-
Let map be the current 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 current agent’s associated store.
-
Let (store, tableaddr) be alloc_table(store, type).
-
Set the current 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 current 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 current 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 current agent’s associated store.
-
Let store be write_table(store, tableaddr, index, funcaddr).
-
If store is error, throw a
RangeError
exception. -
Set the current agent’s associated store to store.
-
Set values[index] to value.
-
Return undefined.
3.5. Globals
dictionaryGlobalDescriptor
{ required USVStringtype
; unrestricted doublevalue
= 0; booleanmutable
= false; }; [LegacyNamespace=WebAssembly, Constructor(GlobalDescriptordescriptor
), Exposed=(Window,Worker,Worklet)] interfaceGlobal
{ unrestricted double valueOf(); attribute unrestricted double value; };
Global
object represents a single global instance which can be simultaneously referenced by multiple Instance
objects. Each Global
object has one internal slot:
-
[[Global]] : a global address
-
Let map be the current agent's associated Global object cache.
-
If map[globaladdr] exists,
-
Return map[globaladdr].
-
-
Let global be a new
Global
instance with [[Global]] set to globaladdr. -
Set map[globaladdr] to global.
-
Return global.
Global(descriptor)
constructor, when invoked, performs the following steps:
-
Let v be descriptor["value"].
-
Let mutable be descriptor["mutable"].
-
Let type be ToValueType(descriptor["type"]).
-
Let value be ToWebAssemblyValue(v, type).
-
If mutable is true, let globaltype be var type; otherwise, let globaltype be const type.
-
Let store be the current agent’s associated store.
-
Let (store, globaladdr) be alloc_global(store, globaltype, value).
-
Set the current agent’s associated store to store.
-
Create a global object from the global address globaladdr and return the result.
Global
global) performs the following steps:
-
Let store be the current agent’s associated store.
-
Let globaladdr be global.[[Global]].
-
Let globaltype be type_global(store, globaladdr).
-
Let value be read_global(store, globaladdr).
-
Return ToJSValue(value).
value
attribute of Global
, when invoked, performs the following steps:
-
Let global be the
Global
instance. -
Return GetGlobalValue(global).
The setter of the value attribute of Global
, when invoked with a value v, performs the following steps:
-
Let global be the
Global
instance. -
Let store be the current agent’s associated store.
-
Let globaladdr be global.[[Global]].
-
Let globaltype be type_global(store, globaladdr).
-
If globaltype is of the form const type, throw a {{TypeError}.
-
Let value be ToWebAssemblyValue(v, type).
-
Let store be write_global(store, globaladdr, value).
-
If store is error, throw a
RangeError
exception. -
Set the current agent’s associated store to store.
valueOf()
method, when invoked, performs the following steps:
-
Let global be the
Global
instance. -
Return GetGlobalValue(global).
3.6. 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 current agent’s associated store.
-
Let store be the current 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 current 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 current 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 current 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 current 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 current agent’s associated store.
-
Let (store, funcaddr) be alloc_func(store, functype, hostfunc).
-
Set the current agent cluster’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 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.7. Error Objects
WebAssembly defines three Error classes. 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.