This API provides a way to access WebAssembly [WEBASSEMBLY] through a bridge to explicitly construct modules from JavaScript [ECMASCRIPT].
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. Notation
This specification depends on the Infra Standard. [INFRA]
The WebAssembly sequence type is equivalent to the list type defined there; values of one are treated as values of the other transparently.
3. Internal storage
3.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 store_init().
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.
3.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. However, this property does not hold for shared objects.
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.
-
The Exported GC Object cache, mapping struct addresses and array addresses to Exported GC Object objects.
-
The Global object cache, mapping global addresses to
Global
objects. -
The Tag object cache, mapping tag addresses to
Tag
objects. -
The Exception object cache, mapping exception addresses to
Exception
objects. -
The Host value cache, mapping host addresses to values.
4. The WebAssembly Namespace
dictionary {
WebAssemblyInstantiatedSource required Module ;
module required Instance ; };
instance dictionary {
WebAssemblyCompileOptions USVString ?;
importedStringConstants sequence <USVString >; }; [Exposed=*]
builtins namespace {
WebAssembly boolean validate (BufferSource ,
bytes optional WebAssemblyCompileOptions );
options Promise <Module >compile (BufferSource ,
bytes optional WebAssemblyCompileOptions );
options Promise <WebAssemblyInstantiatedSource >instantiate (BufferSource ,
bytes optional object ,
importObject optional WebAssemblyCompileOptions );
options Promise <Instance >instantiate (Module ,
moduleObject optional object );
importObject readonly attribute Tag JSTag ; };
-
Let module be module_decode(bytes). If module is error, return error.
-
If module_validate(module) is error, return error.
-
Return module.
-
If validating builtin set names for builtinSetNames is false, return false.
-
For each import of module_imports(module),
-
If importedStringModule is not null and import[0] equals importedStringModule,
-
Let importExternType be import[2]
-
Let stringExternType be
global const (ref extern)
-
If match_externtype(stringExternType, importExternType) is false, return false
-
-
Else,
-
If validating a import for builtin with import and builtinSetNames is false, return false.
-
-
-
Return true.
validate(bytes, options)
method, when invoked, performs the following steps:
-
Let stableBytes be a copy of the bytes held by the buffer bytes.
-
Compile stableBytes as a WebAssembly module and store the results as module.
-
If module is error, return false.
-
Let builtinSetNames be options["builtins"]
-
Let importedStringModule be options["importedStringConstants"]
-
If validating builtins and imported strings for module with builtinSetNames and importedStringModule returns false, return false.
-
Return true.
A Module
object represents a single WebAssembly module. Each Module
object has the following internal slots:
-
[[Module]] : a WebAssembly module
-
[[Bytes]] : the source bytes of [[Module]].
-
[[BuiltinSets]] : an ordered set of names of builtin sets
-
[[ImportedStringModule]] : an optional module specifier string where any string constant can be imported from.
-
Let moduleObject be a new
Module
object. -
Set moduleObject.[[Module]] to module.
-
Set moduleObject.[[Bytes]] to bytes.
-
Set moduleObject.[[BuiltinSets]] to builtinSetNames.
-
Set moduleObject.[[ImportedStringModule]] to importedStringModule.
-
Return moduleObject.
WebAssemblyCompileOptions
options using optional task source taskSource, perform the following steps:
-
Let promise be a new promise.
-
Run the following steps in parallel:
-
Compile the WebAssembly module bytes and store the result as module.
-
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. -
Let builtinSetNames be options["builtins"]
-
Let importedStringModule be options["importedStringConstants"]
-
If validating builtins and imported strings for module with builtinSetNames and importedStringModule is false, reject promise with a
CompileError
exception. -
Otherwise,
-
Construct a WebAssembly module object from module, bytes, builtinSetNames, importedStringModule, and let moduleObject be the result.
-
Resolve promise with moduleObject.
-
-
-
-
Return promise.
compile(bytes, options)
method, when invoked, performs the following steps:
-
Let stableBytes be a copy of the bytes held by the buffer bytes.
-
Asynchronously compile a WebAssembly module from stableBytes using options and return the result.
-
Assert: importedStringModule is not null.
-
Let exportsObject be ! OrdinaryObjectCreate(null).
-
If externtype is of the form func functype,
-
-
For each (moduleName, componentName, externtype) of module_imports(module),
-
If moduleName does not equal importedStringModule, then continue.
-
Let stringConstant be componentName.
-
Let status be ! CreateDataProperty(exportsObject, stringConstant, stringConstant).
-
Assert: status is true.
-
-
Return exportsObject.
-
If module.imports is not empty, and importObject is undefined, throw a
TypeError
exception. -
Let builtinOrStringImports be the ordered map « ».
-
For each builtinSetName of builtinSetNames,
-
Assert: builtinOrStringImports does not contain builtinSetName
-
If builtinSetName does not refer to a builtin set, then continue.
-
Let exportsObject be the result of instantiate a builtin set with builtinSetName
-
Let builtinSetQualifiedName be builtinSetName prefixed with "wasm:"
-
Set builtinOrStringImports[builtinSetQualifiedName] to exportsObject
-
-
If importedStringModule is not null,
-
Let exportsObject be the result of instantiate imported strings with module and importedStringModule
-
Set builtinOrStringImports[importedStringModule] to exportsObject
-
-
Let imports be « ».
-
For each (moduleName, componentName, externtype) of module_imports(module),
-
If builtinOrStringImports contains moduleName,
-
Let o be builtinOrStringImports[moduleName]
-
-
Else,
-
If externtype is of the form func 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.
-
-
Otherwise,
-
Create a host function from v and functype, 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 func funcaddr.
-
Append externfunc to imports.
-
-
If externtype is of the form global mut valtype,
-
If v implements
Global
,-
Let globaladdr be v.[[Global]].
-
-
Otherwise,
-
If valtype is i64 and Type(v) is not BigInt,
-
Throw a
LinkError
exception.
-
-
If valtype is one of i32, f32 or f64 and Type(v) is not Number,
-
Throw a
LinkError
exception.
-
-
If valtype is v128,
-
Throw a
LinkError
exception.
-
-
Let value be ToWebAssemblyValue(v, valtype). If this operation throws a
TypeError
, catch it, and throw aLinkError
exception. -
Let store be the surrounding agent's associated store.
-
Let (store, globaladdr) be global_alloc(store, const valtype, value).
-
Set the surrounding agent's associated store to store.
-
-
Let externglobal be global globaladdr.
-
Append externglobal to imports.
-
-
If externtype is of the form mem memtype,
-
If externtype is of the form table tabletype,
-
If externtype is of the form tag attribute functype,
-
-
Return imports.
Note: This algorithm only verifies the right kind of JavaScript values are passed. The verification of WebAssembly type requirements is deferred to the "instantiate the core of a WebAssembly module" algorithm.
-
Let exportsObject be ! OrdinaryObjectCreate(null).
-
For each (name, externtype) of module_exports(module),
-
Let externval be instance_export(instance, name).
-
Assert: externval is not error.
-
If externtype is of the form func functype,
-
Assert: externval is of the form func funcaddr.
-
Let func 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 global mut globaltype,
-
Assert: externval is of the form global globaladdr.
-
Let global globaladdr be externval.
-
Let global be a new Global object created from globaladdr.
-
Let value be global.
-
-
If externtype is of the form mem memtype,
-
Assert: externval is of the form mem memaddr.
-
Let mem memaddr be externval.
-
Let memory be a new Memory object created from memaddr.
-
Let value be memory.
-
-
If externtype is of the form table tabletype,
-
Assert: externval is of the form table tableaddr.
-
Let table tableaddr be externval.
-
Let table be a new Table object created from tableaddr.
-
Let value be table.
-
-
If externtype is of the form tag attribute functype,
-
Assert: attribute is exception.
-
Assert: externval is of the form tag tagaddr.
-
Let tag tagaddr be externval.
-
Let tag be a new Tag object created from tagaddr.
-
Let value be tag.
-
-
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"
). -
Return exportsObject.
-
Create an exports object from module and instance and let exportsObject be the result.
-
Set instanceObject.[[Instance]] to instance.
-
Set instanceObject.[[Exports]] to exportsObject.
-
Let store be the surrounding agent's associated store.
-
Let result be module_instantiate(store, module, imports).
-
If result 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 (store, instance) be result.
-
Set the surrounding agent's associated store to store.
-
Return instance.
Module
moduleObject and imports importObject, perform the following steps:
-
Let promise be a new promise.
-
Let module be moduleObject.[[Module]].
-
Let builtinSetNames be moduleObject.[[BuiltinSets]].
-
Let importedStringModule be moduleObject.[[ImportedStringModule]].
-
Read the imports of module with imports importObject, builtinSetNames and importedStringModule, and let imports be the result. If this operation throws an exception, catch it, reject promise with the exception, and return promise.
-
Run the following steps in parallel:
-
Queue a task to perform the following steps: Note: Implementation-specific work may be performed here.
-
Instantiate the core of a WebAssembly module module with imports, and let instance be the result. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.
-
Initialize instanceObject from module and instance. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.
-
Resolve promise with instanceObject.
-
-
-
Return promise.
-
Let promise be a new promise.
-
Upon fulfillment of promiseOfModule with value module:
-
Instantiate the WebAssembly module module importing importObject, and let innerPromise be the result.
-
Upon fulfillment of innerPromise with value instance.
-
Let result be the
WebAssemblyInstantiatedSource
value «[ "module
" → module, "instance
" → instance ]». -
Resolve promise with result.
-
-
Upon rejection of innerPromise with reason reason:
-
Reject promise with reason.
-
-
-
Upon rejection of promiseOfModule with reason reason:
-
Reject promise with reason.
-
-
Return promise.
instantiate(bytes, importObject, options)
method, when invoked, performs the following steps:
-
Let stableBytes be a copy of the bytes held by the buffer bytes.
-
Asynchronously compile a WebAssembly module from stableBytes using options and let promiseOfModule be the result.
-
Instantiate promiseOfModule with imports importObject and return the result.
instantiate(moduleObject, importObject)
method, when invoked, performs the following steps:
-
Asynchronously instantiate the WebAssembly module moduleObject importing importObject, and return the result.
Note: A follow-on streaming API is documented in the WebAssembly Web API.
The getter of the JSTag
attribute of the WebAssembly
Namespace, when invoked, performs the following steps:
-
Let JSTagAddr be the result of getting the JavaScript exception tag.
-
Let JSTagObject be the result of creating a Tag object from JSTagAddr.
-
Return JSTagObject.
4.1. Modules
enum {
ImportExportKind ,
"function" ,
"table" ,
"memory" ,
"global" };
"tag" dictionary {
ModuleExportDescriptor required USVString ;
name required ImportExportKind ; // Note: Other fields such as signature may be added in the future. };
kind dictionary {
ModuleImportDescriptor required USVString ;
module required USVString ;
name required ImportExportKind ; }; [
kind LegacyNamespace =WebAssembly , Exposed=*]interface {
Module constructor (BufferSource ,
bytes optional WebAssemblyCompileOptions );
options static sequence <ModuleExportDescriptor >exports (Module );
moduleObject static sequence <ModuleImportDescriptor >imports (Module );
moduleObject static sequence <ArrayBuffer >customSections (Module ,
moduleObject DOMString ); };
sectionName
exports(moduleObject)
method, when invoked, performs the following steps:
-
Let module be moduleObject.[[Module]].
-
Let exports be « ».
-
For each (name, type) of module_exports(module),
-
Let kind be the string value of the extern type type.
-
Append obj to exports.
-
-
Return exports.
imports(moduleObject)
method, when invoked, performs the following steps:
-
Let module be moduleObject.[[Module]].
-
Let builtinSetNames be moduleObject.[[BuiltinSets]].
-
Let importedStringModule be moduleObject.[[ImportedStringModule]].
-
Let imports be « ».
-
For each (moduleName, name, type) of module_imports(module),
-
If find a builtin for (moduleName, name, type) and builtinSetNames is not null, then continue
-
If importedStringModule is not null and moduleName equals importedStringModule, then continue
-
Let kind be the string value of the extern type type.
-
Let obj be «[ "
module
" → moduleName, "name
" → name, "kind
" → kind ]». -
Append obj to imports.
-
-
Return imports.
customSections(moduleObject, sectionName)
method, when invoked, performs the following steps:
-
Let bytes be moduleObject.[[Bytes]].
-
Let customSections be « ».
-
For each custom section customSection of bytes, interpreted according to the module grammar,
-
Let name be the
name
of customSection, decoded as UTF-8. -
Assert: name is not failure (moduleObject.[[Module]] is valid).
-
If name equals sectionName as string values,
-
Append a new
ArrayBuffer
containing a copy of the bytes in bytes for the range matched by this customsec production to customSections.
-
-
-
Return customSections.
Module(bytes, options)
constructor, when invoked, performs the following 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. -
Let builtinSetNames be options["builtins"]
-
Let importedStringModule be options["importedStringConstants"]
-
If validating builtins and imported strings for module with builtinSetNames and importedStringModule returns false, throw a
CompileError
exception. -
Set this.[[Module]] to module.
-
Set this.[[Bytes]] to stableBytes.
-
Set this.[[BuiltinSets]] to builtinSetNames.
-
Set this.[[ImportedStringModule]] to importedStringModule.
Note: Some implementations enforce a size limitation on bytes. Use of this API is discouraged, in favor of asynchronous APIs.
4.2. Instances
[LegacyNamespace =WebAssembly , Exposed=*]interface {
Instance constructor (Module ,
module optional object );
importObject readonly attribute object exports ; };
Instance(module, importObject)
constructor, when invoked, runs the following steps:
-
Let module be module.[[Module]].
-
Let builtinSetNames be module.[[BuiltinSets]].
-
Let importedStringModule be module.[[ImportedStringModule]].
-
Read the imports of module with imports importObject, builtinSetNames, and importedStringModule, and let imports be the result.
-
Instantiate the core of a WebAssembly module module with imports, and let instance be the result.
-
Initialize this from module and instance.
Note: The use of this synchronous API is discouraged, as some implementations sometimes do long-running compilation work when instantiating.
exports
attribute of Instance
returns this.[[Exports]]. 4.3. Memories
dictionary {
MemoryDescriptor required [EnforceRange ]unsigned long ; [
initial EnforceRange ]unsigned long ; }; [
maximum LegacyNamespace =WebAssembly , Exposed=*]interface {
Memory constructor (MemoryDescriptor );
descriptor unsigned long grow ([EnforceRange ]unsigned long );
delta ArrayBuffer toFixedLengthBuffer ();ArrayBuffer toResizableBuffer ();readonly attribute ArrayBuffer buffer ; };
A 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 block be a Data Block which is identified with the underlying memory of memaddr.
-
Let buffer be a new
ArrayBuffer
with the internal slots [[ArrayBufferData]], [[ArrayBufferByteLength]], and [[ArrayBufferDetachKey]]. -
Set buffer.[[ArrayBufferData]] to block.
-
Set buffer.[[ArrayBufferByteLength]] to the length of block.
-
Set buffer.[[ArrayBufferDetachKey]] to "WebAssembly.Memory".
-
Return buffer.
-
Let block be a Data Block which is identified with the underlying memory of memaddr.
-
Let length be the length of block.
-
If maxsize > (65536 × 65536),
-
Throw a
RangeError
exception.
-
-
Let buffer be a new
ArrayBuffer
with the internal slots [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferMaxByteLength]], and [[ArrayBufferDetachKey]]. -
Set buffer.[[ArrayBufferData]] to block.
-
Set buffer.[[ArrayBufferByteLength]] to length.
-
Set buffer.[[ArrayBufferMaxByteLength]] is maxsize.
-
Set buffer.[[ArrayBufferDetachKey]] to "WebAssembly.Memory".
-
Return buffer.
-
Let map be the surrounding agent's associated Memory object cache.
-
Assert: map[memaddr] doesn’t exist.
-
Let buffer be the result of creating a fixed length memory buffer from memaddr.
-
Set memory.[[Memory]] to memaddr.
-
Set memory.[[BufferObject]] to buffer.
-
Set map[memaddr] to memory.
-
Let map be the surrounding agent's associated Memory object cache.
-
If map[memaddr] exists,
-
Return map[memaddr].
-
-
Initialize memory from memaddr.
-
Return memory.
Memory(descriptor)
constructor, when invoked, performs the following steps:
-
Let initial be descriptor["initial"].
-
If descriptor["maximum"] exists, let maximum be descriptor["maximum"]; otherwise, let maximum be empty.
-
If maximum is not empty and maximum < initial, throw a
RangeError
exception. -
Let memtype be { min initial, max maximum }.
-
Let store be the surrounding agent's associated store.
-
Let (store, memaddr) be mem_alloc(store, memtype). If allocation fails, throw a
RangeError
exception. -
Set the surrounding agent's associated store to store.
-
Initialize this from memaddr.
-
Let map be the surrounding agent's associated Memory object cache.
-
Assert: map[memaddr] exists.
-
Let memory be map[memaddr].
-
Let buffer be memory.[[BufferObject]].
-
If IsFixedLengthArrayBuffer(buffer) is true,
-
Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
-
Let buffer be the result of creating a fixed length memory buffer from memaddr.
-
Set memory.[[BufferObject]] to buffer.
-
-
Otherwise,
-
Let block be a Data Block which is identified with the underlying memory of memaddr.
-
Set buffer.[[ArrayBufferData]] to block.
-
Set buffer.[[ArrayBufferByteLength]] to the length of block.
-
-
Let store be the surrounding agent's associated store.
-
Let ret be the mem_size(store, memaddr).
-
Let store be mem_grow(store, memaddr, delta).
-
If store is error, throw a
RangeError
exception. -
Set the surrounding agent's associated store to store.
-
Refresh the memory buffer of memaddr.
-
Return ret.
grow(delta)
method, when invoked, performs the following steps:
-
Let memaddr be this.[[Memory]].
-
Return the result of growing the memory buffer associated with memaddr by delta.
Immediately after a WebAssembly memory.grow instruction executes, perform the following steps:
-
If the top of the stack is not i32.const (−1),
-
Let frame be the current frame.
-
Refresh the memory buffer of memaddr.
-
toFixedLengthBuffer()
method, when invoked, performs the following steps:
-
Let buffer be this.[[BufferObject]].
-
If IsFixedLengthArrayBuffer(buffer) is true, return buffer.
-
Let memaddr be this.[[Memory]].
-
Let fixedBuffer be the result of creating a fixed length memory buffer from memaddr.
-
Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
-
Set this.[[BufferObject]] to fixedBuffer.
-
Return fixedBuffer.
toResizableBuffer()
method, when invoked, performs the following steps:
-
Let buffer be this.[[BufferObject]].
-
If IsFixedLengthArrayBuffer(buffer) is false, return buffer.
-
Let memaddr be this.[[Memory]].
-
Let store be the surrounding agent's associated store.
-
Let memtype be mem_type(store, memaddr).
-
If memtype has a max,
-
Let maxsize be the max value in memtype.
-
-
Otherwise,
-
Let maxsize be 65536 × 65536.
-
-
Let resizableBuffer be the result of creating a resizable memory buffer from memaddr and maxsize.
-
Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
-
Set this.[[BufferObject]] to resizableBuffer.
-
Return resizableBuffer.
ArrayBuffer
objects returned by a Memory
object must have a size that is a multiple of a WebAssembly page size (the constant 65536). For this reason HostResizeArrayBuffer is redefined as follows.
The abstract operation HostResizeArrayBuffer takes arguments buffer (an ArrayBuffer
) and newLength. It performs the following steps when called.
-
If buffer.[[ArrayBufferDetachKey]] is "WebAssembly.Memory",
-
Let map be the surrounding agent's associated Memory object cache.
-
Assert: buffer is the [[BufferObject]] of exactly one value in map.
-
For each memaddr → mem in map,
-
If SameValue(mem.[[BufferObject]], buffer) is true,
-
Assert: buffer.[[ArrayBufferByteLength]] modulo 65536 is 0.
-
Let lengthDelta be newLength - buffer.[[ArrayBufferByteLength]].
-
If lengthDelta < 0 or lengthDelta modulo 65536 is not 0,
-
Throw a
RangeError
exception.
-
-
Let delta be lengthDelta ÷ 65536.
-
Grow the memory buffer associated with memaddr by delta.
-
-
-
Return
handled .
-
-
Otherwise, return
unhandled .
buffer
attribute of Memory
returns this.[[BufferObject]]. 4.4. Tables
enum {
TableKind ,
"externref" , // Note: More values may be added in future iterations, // e.g., typed function references, typed GC references };
"anyfunc" dictionary {
TableDescriptor required TableKind ;
element required [EnforceRange ]unsigned long ; [
initial EnforceRange ]unsigned long ; }; [
maximum LegacyNamespace =WebAssembly , Exposed=*]interface {
Table constructor (TableDescriptor ,
descriptor optional any );
value unsigned long grow ([EnforceRange ]unsigned long ,
delta optional any );
value any get ([EnforceRange ]unsigned long );
index undefined set ([EnforceRange ]unsigned long ,
index optional any );
value readonly attribute unsigned long length ; };
A Table
object represents a single table instance which can be simultaneously referenced by
multiple Instance
objects.
Each Table
object has a [[Table]] internal slot, which is a table address.
-
Let map be the surrounding agent's associated Table object cache.
-
Assert: map[tableaddr] doesn’t exist.
-
Set table.[[Table]] to tableaddr.
-
Set map[tableaddr] to table.
-
Let map be the surrounding agent's associated Table object cache.
-
If map[tableaddr] exists,
-
Return map[tableaddr].
-
-
Initialize table from tableaddr.
-
Return table.
Table(descriptor, value)
constructor, when invoked, performs the following steps:
-
Let elementType be ToValueType(descriptor["element"]).
-
If elementType is not a reftype,
-
Throw a
TypeError
exception.
-
-
Let initial be descriptor["initial"].
-
If descriptor["maximum"] exists, let maximum be descriptor["maximum"]; otherwise, let maximum be empty.
-
If maximum is not empty and maximum < initial, throw a
RangeError
exception. -
If value is missing,
-
Let ref be DefaultValue(elementType).
-
Assert: ref is not error.
-
-
Otherwise,
-
Let ref be ? ToWebAssemblyValue(value, elementType).
-
-
Let type be the table type {min initial, max maximum} elementType.
-
Let store be the surrounding agent's associated store.
-
Let (store, tableaddr) be table_alloc(store, type, ref).
-
Set the surrounding agent's associated store to store.
-
Initialize this from tableaddr.
grow(delta, value)
method, when invoked, performs the following steps:
-
Let tableaddr be this.[[Table]].
-
Let store be the surrounding agent's associated store.
-
Let initialSize be table_size(store, tableaddr).
-
Let (limits, elementType) be table_type(tableaddr).
-
If value is missing,
-
Let ref be DefaultValue(elementType).
-
-
Otherwise,
-
Let ref be ? ToWebAssemblyValue(value, elementType).
-
-
Let result be table_grow(store, tableaddr, delta, ref).
-
If result is error, throw a
RangeError
exception.Note: The above exception can happen due to either insufficient memory or an invalid size parameter.
-
Set the surrounding agent's associated store to result.
-
Return initialSize.
length
attribute of Table
, when invoked, performs the following steps:
-
Let tableaddr be this.[[Table]].
-
Let store be the surrounding agent's associated store.
-
Return table_size(store, tableaddr).
get(index)
method, when invoked, performs the following steps:
-
Let tableaddr be this.[[Table]].
-
Let store be the surrounding agent's associated store.
-
Let (limits, elementType) be table_type(store, tableaddr).
-
If elementType is exnref,
-
Throw a
TypeError
exception.
-
-
Let result be table_read(store, tableaddr, index).
-
If result is error, throw a
RangeError
exception. -
Return ToJSValue(result).
set(index, value)
method, when invoked, performs the following steps:
-
Let tableaddr be this.[[Table]].
-
Let store be the surrounding agent's associated store.
-
Let (limits, elementType) be table_type(store, tableaddr).
-
If elementType is exnref,
-
Throw a
TypeError
exception.
-
-
If value is missing,
-
Let ref be DefaultValue(elementType).
-
-
Otherwise,
-
Let ref be ? ToWebAssemblyValue(value, elementType).
-
-
Let store be the surrounding agent's associated store.
-
Let store be table_write(store, tableaddr, index, ref).
-
If store is error, throw a
RangeError
exception. -
Set the surrounding agent's associated store to store.
4.5. Globals
enum {
ValueType ,
"i32" ,
"i64" ,
"f32" ,
"f64" ,
"v128" ,
"externref" , };
"anyfunc"
Note: this type may be extended with additional cases in future versions of WebAssembly.
dictionary {
GlobalDescriptor required ValueType ;
value boolean =
mutable false ; }; [LegacyNamespace =WebAssembly , Exposed=*]interface {
Global constructor (GlobalDescriptor ,
descriptor optional any );
v any valueOf ();attribute any value ; };
A 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 surrounding agent's associated Global object cache.
-
Assert: map[globaladdr] doesn’t exist.
-
Set global.[[Global]] to globaladdr.
-
Set map[globaladdr] to global.
-
Let map be the surrounding agent's associated Global object cache.
-
If map[globaladdr] exists,
-
Return map[globaladdr].
-
-
Initialize global from globaladdr.
-
Return global.
-
If valuetype equals externref, return ToWebAssemblyValue(undefined, valuetype).
-
Return val_default(valuetype).
Global(descriptor, v)
constructor, when invoked, performs the following steps:
-
Let mutable be descriptor["mutable"].
-
Let valuetype be ToValueType(descriptor["value"]).
-
If valuetype is v128 or exnref,
-
Throw a
TypeError
exception.
-
-
If v is missing,
-
Let value be DefaultValue(valuetype).
-
Assert: value is not error.
-
-
Otherwise,
-
Let value be ToWebAssemblyValue(v, valuetype).
-
-
If mutable is true, let globaltype be var valuetype; otherwise, let globaltype be const valuetype.
-
Let store be the current agent’s associated store.
-
Let (store, globaladdr) be global_alloc(store, globaltype, value).
-
Set the current agent’s associated store to store.
-
Initialize this from globaladdr.
Global
global) performs the following steps:
-
Let store be the current agent’s associated store.
-
Let globaladdr be global.[[Global]].
-
Let globaltype be global_type(store, globaladdr).
-
If globaltype is of the form mut valuetype where valuetype is v128 or exnref, throw a
TypeError
. -
Let value be global_read(store, globaladdr).
-
Return ToJSValue(value).
value
attribute of Global
, when invoked, performs the following steps:
-
Return GetGlobalValue(this).
The setter of the value attribute of Global
, when invoked, performs the following steps:
-
Let store be the current agent’s associated store.
-
Let globaladdr be this.[[Global]].
-
Let mut valuetype be global_type(store, globaladdr).
-
Let value be ToWebAssemblyValue(the given value, valuetype).
-
Let store be global_write(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:
-
Return GetGlobalValue(this).
4.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 surrounding agent's associated store.
-
Let store be the surrounding agent's associated store.
-
Let funcinst be store.funcs[funcaddr].
-
If funcinst is of the form {type functype, hostcode 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.module.
-
Assert: funcaddr is contained in moduleinst.funcaddrs.
-
Let index be the index of moduleinst.funcaddrs where funcaddr is found.
-
-
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 store be the surrounding agent's associated store.
-
Let functype be func_type(store, funcaddr).
-
Let [paramTypes] → [resultTypes] be functype.
-
Let arity be paramTypes’s size.
-
Let name be the name of the WebAssembly function funcaddr.
-
Let function be ! CreateBuiltinFunction(steps, arity, name, « [[FunctionAddress]] », realm).
-
Set function.[[FunctionAddress]] to funcaddr.
-
Set map[funcaddr] to function.
-
Return function.
-
Let store be the surrounding agent's associated store.
-
Let functype be func_type(store, funcaddr).
-
Let [parameters] → [results] be functype.
-
If parameters or results contain v128 or exnref, throw a
TypeError
.Note: the above error is thrown each time the [[Call]] method is invoked.
-
Let args be « ».
-
Let i be 0.
-
For each t of parameters,
-
If argValues’s size > 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 func_invoke(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 ret is THROW ref.exn exnaddr, then
-
Let tagaddr be exn_tag(store, exnaddr).
-
Let payload be exn_read(store, exnaddr).
-
Let jsTagAddr be the result of getting the JavaScript exception tag.
-
If tagaddr is equal to jsTagAddr,
-
Throw the result of retrieving a host value from payload[0].
-
-
Otherwise,
-
Let exception be a new Exception created from exnaddr.
-
Throw exception.
-
-
-
Let outArity be the size of ret.
-
If outArity is 0, return undefined.
-
Otherwise, if outArity is 1, return ToJSValue(ret[0]).
-
Otherwise,
-
Let values be « ».
-
For each r of ret,
-
Return CreateArrayFromList(values).
-
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 [parameters] → [results] be functype.
-
If parameters or results contain v128 or exnref, throw a
TypeError
. -
Let jsArguments be « ».
-
For each arg of arguments,
-
Let resultsSize be results’s size.
-
If resultsSize is 0, return « ».
-
Otherwise, if resultsSize is 1, return « ? ToWebAssemblyValue(ret, results[0]) ».
-
Otherwise,
-
Let method be ? GetMethod(ret,
%Symbol.iterator%
). -
Let values be ? IteratorToList(? GetIteratorFromMethod(ret, method)).
-
Let wasmValues be a new, empty list.
-
If values’s size is not resultsSize, throw a
TypeError
exception. -
For each value and resultType in values and results, paired linearly,
-
Append ToWebAssemblyValue(value, resultType) to wasmValues.
-
-
Return wasmValues.
-
-
Assert: IsCallable(func).
-
Let stored settings be the incumbent settings object.
-
Let hostfunc be a host function which performs the following steps when called with arguments arguments:
-
Let realm be func’s associated Realm.
-
Let relevant settings be realm’s settings object.
-
Prepare to run script with relevant settings.
-
Prepare to run a callback with stored settings.
-
Let result be the result of running a host function from func, functype, and arguments.
-
Clean up after running a callback with stored settings.
-
Clean up after running script with relevant settings.
-
Assert: result.[[Type]] is
throw ornormal . -
Let store be the surrounding agent's associated store.
-
If result.[[Type]] is
throw , then:-
Let v be result.[[Value]].
-
If v implements
Exception
,-
Let address be v.[[Address]].
-
-
Otherwise,
-
Let type be the result of getting the JavaScript exception tag.
-
Let payload be ! ToWebAssemblyValue(v, externref).
-
Let (store, address) be exn_alloc(store, type, « payload »).
-
Set the surrounding agent's associated store to store.
-
-
Execute the WebAssembly instructions (ref.exn address) (throw_ref).
-
-
Otherwise, return result.[[Value]].
-
-
Let (store, funcaddr) be func_alloc(store, functype, hostfunc).
-
Set the surrounding agent's associated store to store.
-
Return funcaddr.
-
Assert: w is not of the form v128.const v128.
-
Assert: w is not of the form ref.exn exnaddr.
-
If w is of the form i64.const u64,
-
If w is of the form i32.const i32,
-
If w is of the form f32.const f32,
-
If w is of the form f64.const f64,
-
If w is of the form ref.null t, return null.
-
If w is of the form ref.i31 u31,
-
If w is of the form ref.struct structaddr, return the result of creating a new Exported GC Object from structaddr and "struct".
-
If w is of the form ref.array arrayaddr, return the result of creating a new Exported GC Object from arrayaddr and "array".
-
If w is of the form ref.func funcaddr, return the result of creating a new Exported Function from funcaddr.
-
If w is of the form ref.host hostaddr, return the result of retrieving a host value from hostaddr.
-
If w is of the form ref.extern ref, return ToJSValue(ref).
Note: Number values which are equal to NaN may have various observable NaN payloads; see NumericToRawBytes for details.
For retrieving a host value from an host address hostaddr, perform the following steps:
-
Let map be the surrounding agent's associated host value cache.
-
Assert: map[hostaddr] exists.
-
Return map[hostaddr].
-
Assert: type is not v128.
-
Assert: type is not exnref.
-
If type is i64,
-
Let i64 be ? ToBigInt64(v).
-
Let u64 be the unsigned integer such that i64 is signed_64(u64).
-
Return i64.const u64.
-
-
If type is i32,
-
If type is f32,
-
If number is NaN,
-
Otherwise,
-
Let f32 be number rounded to the nearest representable value using IEEE 754-2008 round to nearest, ties to even mode. [IEEE-754]
-
-
Return f32.const f32.
-
If type is f64,
-
If type is of the form ref null heaptype,
-
If v is null,
-
Let r be ref.null heaptype.
-
-
Else if match_valtype(type, ref null extern),
-
Let ref be ToWebAssemblyValue(v, ref any).
-
Let r be ref.extern ref.
-
-
Else if v is an Exported Function and match_valtype(type, ref null func),
-
Let funcaddr be the value of v’s [[FunctionAddress]] internal slot.
-
Let r be ref.func funcaddr.
-
-
Else if v is a Number and v is equal to ? ToInt32(v) and ℝ(v) < 230 and ℝ(v) ⩾ -230,
-
Else if v is an Exported GC Object,
-
Let objectaddr be the value of v’s [[ObjectAddress]] internal slot.
-
Let objectkind be the value of v’s [[ObjectKind]] internal slot.
-
If objectkind is "array",
-
Let r be ref.array objectaddr.
-
-
If objectkind is "struct",
-
Let r be ref.struct objectaddr.
-
-
-
Else,
-
Let map be the surrounding agent's associated host value cache.
-
If a host address hostaddr exists such that map[hostaddr] is the same as v,
-
Return ref.host hostaddr.
-
-
Let host address hostaddr be the smallest address such that map[hostaddr] exists is false.
-
Set map[hostaddr] to v.
-
Let r be ref.host hostaddr.
-
-
Let store be the current agent’s associated store.
-
Let actualtype be ref_type(store, r).
-
If match_valtype(actualtype, type) is false,
-
Throw a
TypeError
.
-
-
Return r.
-
-
Assert: This step is not reached.
4.7. Tags
The tag_alloc(store, parameters) algorithm creates a new tag address for parameters in store and returns the updated store and the tag address.
4.7.1. Tag types
dictionary {
TagType required sequence <ValueType >; }; [
parameters LegacyNamespace =WebAssembly ,Exposed =(Window ,Worker ,Worklet )]interface {
Tag constructor (TagType ); };
type
A Tag
value represents an exception tag.
To initialize a Tag object tag from a tag address tagAddress, perform the following steps:
-
Let map be the surrounding agent's associated Tag object cache.
-
Assert: map[tagAddress] doesn’t exist.
-
Set tag.[[Address]] to tagAddress.
-
Set map[tagAddress] to tag.
To create a Tag object from a tag address tagAddress, perform the following steps:
-
Let map be the surrounding agent's associated Tag object cache.
-
If map[tagAddress] exists,
-
Return map[tagAddress].
-
-
Initialize tag from tagAddress.
-
Return tag.
The new Tag(type)
constructor steps are:
-
Let parameters be type["parameters"].
-
Let wasmParameters be «».
-
For each type of parameters,
-
Append ToValueType(type) to wasmParameters.
-
-
Let store be the current agent’s associated store.
-
Let (store, tagAddress) be tag_alloc(store, wasmParameters).
-
Set the current agent’s associated store to store.
-
Initialize this from tagAddress.
4.8. Garbage Collected Objects
A WebAssembly struct or array is made available in JavaScript as an Exported GC Object. An Exported GC Object is an exotic object that wraps a garbage collected WebAssembly reference value. Most JavaScript operations on an Exported GC Object will throw an exception or return undefined.
Note: These operations may be refined in the future to allow richer interactions in JavaScript with WebAssembly structs and arrays.
An Exported GC Object contains an [[ObjectAddress]] internal slot, which holds a object address relative to the surrounding agent's associated store, and an [[ObjectKind]] internal slot, which holds the string value "struct" or "array".
The internal methods of an Exported GC Object use the following implementations.
-
Return null.
-
Return false.
-
Return false.
-
Return false.
-
Return undefined.
-
Return false.
-
Return false.
-
Return undefined.
-
Throw a
TypeError
.
-
Throw a
TypeError
.
-
Let keys be a new empty list.
-
Return keys.
-
Assert: objectkind is either "array" or "struct".
-
Let map be the surrounding agent's associated exported GC object cache.
-
If map[objectaddr] exists,
-
Return map[objectaddr].
-
-
Let object be MakeBasicObject(« [[ObjectAddress]] »).
-
Set object.[[ObjectAddress]] to objectaddr.
-
Set object.[[ObjectKind]] to objectkind.
-
Set object.[[GetPrototypeOf]] as specified in [[GetPrototypeOf]] internal method of an Exported GC Object.
-
Set object.[[SetPrototypeOf]] as specified in [[SetPrototypeOf]] internal method of an Exported GC Object.
-
Set object.[[IsExtensible]] as specified in [[IsExtensible]] internal method of an Exported GC Object.
-
Set object.[[PreventExtensions]] as specified in [[PreventExtensions]] internal method of an Exported GC Object.
-
Set object.[[GetOwnProperty]] as specified in [[GetOwnProperty]] internal method of an Exported GC Object.
-
Set object.[[DefineOwnProperty]] as specified in [[DefineOwnProperty]] internal method of an Exported GC Object.
-
Set object.[[HasProperty]] as specified in [[HasProperty]] internal method of an Exported GC Object.
-
Set object.[[Get]] as specified in [[Get]] internal method of an Exported GC Object.
-
Set object.[[Set]] as specified in [[Set]] internal method of an Exported GC Object.
-
Set object.[[Delete]] as specified in [[Delete]] internal method of an Exported GC Object.
-
Set object.[[OwnPropertyKeys]] as specified in [[OwnPropertyKeys]] internal method of an Exported GC Object.
-
Set map[objectaddr] to object.
-
Return object.
4.9. Exceptions
dictionary {
ExceptionOptions boolean =
traceStack false ; }; [LegacyNamespace =WebAssembly ,Exposed =(Window ,Worker ,Worklet )]interface {
Exception constructor (Tag ,
exceptionTag sequence <any >,
payload optional ExceptionOptions = {});
options any getArg ([EnforceRange ]unsigned long );
index boolean is (Tag );
exceptionTag readonly attribute (DOMString or undefined )stack ; };
An Exception
value represents an exception.
To initialize an Exception object exn from an Exception address exnAddress, perform the following steps:
-
Let map be the surrounding agent's associated Exception object cache.
-
Assert: map[exnAddress] doesn’t exist.
-
Set exn.[[Address]] to exnAddress.
-
Set map[exnAddress] to exn.
-
Let store be the surrounding agent's associated store.
-
Let tagaddr be exn_tag(store, exnAddress).
-
Let payload be exn_read(store, exnAddress).
-
Set exn.[[Type]] to tagaddr.
-
Set exn.[[Payload]] to payload.
-
Set exn.[[Stack]] to undefined.
To create an Exception object from a exception address exnAddress, perform the following steps:
-
Let map be the surrounding agent's associated Exception object cache.
-
If map[exnAddress] exists,
-
Return map[exnAddress].
-
-
Initialize exn from exnAddress.
-
Return exn.
The new Exception(exceptionTag, payload, options)
constructor steps are:
-
Let JSTagAddr be the result of getting the JavaScript exception tag.
-
If exceptionTag.[[Address]] is equal to JSTagAddr,
-
Throw a
TypeError
.
-
-
Let store be the surrounding agent's associated store.
-
Let [types] → [] be tag_type(store, exceptionTag.[[Address]]).
-
If types’s size is not payload’s size,
-
Throw a
TypeError
.
-
-
Let wasmPayload be « ».
-
For each value and resultType of payload and types, paired linearly,
-
Let (store, exceptionAddr) be exn_alloc(store, exceptionTag.[[Address]], wasmPayload)
-
Set the surrounding agent's associated store to store.
-
Initialize this from exceptionAddr.
-
If options["traceStack"] is true,
-
Set this.[[Stack]] to either a
DOMString
representation of the current call stack or undefined.
-
The getArg(index)
method steps are:
-
Let store be the surrounding agent's associated store.
-
Let tagaddr be exn_tag(store, this.[[Address]]).
-
Let payload be exn_read(store, this.[[Address]]).
-
Assert: tagaddr is equal to this.[[Type]].
-
If index ≥ payload’s size,
-
Throw a
RangeError
.
-
-
Let [types] → [] be tag_type(store, tagaddr).
-
If types[index] is v128 or exnref,
-
Throw a
TypeError
.
-
-
Return ToJSValue(payload[index]).
The is(exceptionTag)
method steps are:
-
If this.[[Type]] is not equal to exceptionTag.[[Address]],
-
Return false.
-
-
Return true.
The stack
getter steps are:
-
Return this.[[Stack]].
4.9.1. JavaScript exceptions
The JavaScript exception tag is a tag address associated with the surrounding agent. It is allocated in the agent’s associated store on first use and cached. It always has the tag type « externref » → « ».
To get the JavaScript exception tag, perform the following steps:
-
If the surrounding agent's associated JavaScript exception tag has been initialized,
-
return the surrounding agent's associated JavaScript exception tag
-
-
Let store be the surrounding agent's associated store.
-
Let (store, tagAddress) be tag_alloc(store, « externref » → « »).
-
Set the current agent’s associated store to store.
-
Set the current agent’s associated JavaScript exception tag to tagAddress.
-
return tagAddress.
4.10. Error Objects
WebAssembly defines the following Error classes: CompileError
, LinkError
, and RuntimeError
.
WebAssembly
namespace is created, the following steps must be run:
-
Let namespaceObject be the namespace object.
-
For each error of « "CompileError", "LinkError", "RuntimeError" »,
-
Let constructor be a new object, implementing the NativeError Object Structure, with NativeError set to error.
-
! DefineMethodProperty(namespaceObject, error, constructor, false).
-
Note: This defines CompileError
, LinkError
, and RuntimeError
classes on the WebAssembly
namespace, which are produced by the APIs defined in this specification.
They expose the same interface as native JavaScript errors like TypeError
and RangeError
.
Note: It is not currently possible to define this behavior using Web IDL.
5. Builtins
The JS-API defines sets of builtin functions which can be imported through options
when compiling a module. WebAssembly builtin functions mirror existing JavaScript builtins, but adapt them to be useable directly as WebAssembly functions with minimal overhead.
All builtin functions are grouped into sets. Every builtin set has a name that is used in WebAssemblyCompileOptions
, and a qualified name with a wasm:
prefix that is used during import lookup.
-
Return a list of (name, funcType, steps) for the set with name builtinSetName defined within this section.
-
Assert: validate builtin set names builtinSetNames is true.
-
Let importModuleName be import[0]
-
Let importName be import[1]
-
For each builtinSetName of builtinSetNames,
-
If builtinSetName does not refer to a builtin set, then continue.
-
Let builtinSetQualifiedName be builtinSetName prefixed with "wasm:"
-
If importModuleName equals builtinSetQualifiedName
-
Let builtins be the result of get the builtins for a builtin set builtinSetName
-
For each builtin of builtins
-
Let builtinName be builtin[0]
-
If importName equals builtinName, return (builtinSetName, builtin).
-
-
-
-
Return null.
-
If builtinSetNames contains any duplicates, return false.
-
Return false.
-
Let stored settings be the incumbent settings object.
-
Let hostfunc be a host function which executes steps when called.
-
Let (store, funcaddr) be func_alloc(store, functype, hostfunc).
-
Set the surrounding agent's associated store to store.
-
Return funcaddr.
-
Let builtins be the result of get the builtins for a builtin set builtinSetName
-
Let exportsObject be ! OrdinaryObjectCreate(null).
-
If externtype is of the form func functype,
-
-
For each (name, funcType, steps) of builtins,
-
Let funcaddr be the result fo create a builtin function with funcType and steps
-
Let func be the result of creating a new Exported Function from funcaddr.
-
Let value be func.
-
Let status be ! CreateDataProperty(exportsObject, name, value).
-
Assert: status is true.
-
-
Return exportsObject.
-
Assert: validate builtin set names builtinSetNames is true.
-
Let maybeBuiltin be the result of finding a builtin for import and builtinSetNames
-
If maybeBuiltin is null, return true.
-
Let importExternType be import[2]
-
Let builtinFuncType be maybeBuiltin[0][1]
-
Let builtinExternType be
func |builtinFuncType|
-
Return match_externtype(builtinExternType, importExternType)
5.1. String Builtins
String builtins adapt the interface of the String builtin object. The name for this set is js-string
.
Note: The algorithms in this section refer to JS builtins defined on String. These refer to the actual builtin and do not perform a dynamic lookup on the String object.
5.1.1. Abstract operations
The UnwrapString(v) abstract operation, when invoked, performs the following steps:
-
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Return v
The FromCharCode(v) abstract operation, when invoked, performs the following steps:
-
Assert: v is of type i32.
-
Return ! Call(String.fromCharCode, undefined, « ToJSValue(v) »).
The CharCodeAt(string, index) abstract operation, when invoked, performs the following steps:
-
Assert: index is of type i32.
-
Return ! Call(String.prototype.charCodeAt, string, « ToJSValue(index) »).
5.1.2. cast
The funcType of this builtin is (func (param externref) (result externref))
.
-
Return ? UnwrapString(v)
5.1.3. test
The funcType of this builtin is (func (param externref) (result i32))
.
5.1.4. fromCharCodeArray
The funcType of this builtin is (func (param (ref null (array (mut i16))) i32 i32) (result externref))
.
Note: This function only takes a mutable i16 array defined in its own recursion group.
-
If array is null
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Let length be the number of elements in array.
-
If start > end or end > length
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Let result be the empty string.
-
Let i be start.
-
While i < end:
-
Let charCode be the value of the element stored at index i in array.
-
Let charCodeString be FromCharCode(charCode).
-
Let result be the concatenation of result and charCodeString.
-
Set i to i + 1.
-
-
Return result.
5.1.5. intoCharCodeArray
The funcType of this builtin is (func (param externref (ref null (array (mut i16))) i32) (result i32))
.
Note: This function only takes a mutable i16 array defined in its own recursion group.
-
If array is null
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Let string be ? UnwrapString(string).
-
Let stringLength be the length of string.
-
Let arrayLength be the number of elements in array.
-
If start + stringLength > arrayLength
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Let i be 0.
-
While i < stringLength:
-
Let charCode be CharCodeAt(string, i).
-
Set the element at index start + i in array to ToWebAssemblyValue(charCode).
-
Set i to i + 1.
-
-
Return stringLength.
5.1.6. fromCharCode
The funcType of this builtin is (func (param i32) (result externref))
.
-
Return FromCharCode(v).
5.1.7. fromCodePoint
The funcType of this builtin is (func (param i32) (result externref))
.
-
If v > 0x10ffff
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Return ! Call(String.fromCodePoint, undefined, « ToJSValue(v) »).
5.1.8. charCodeAt
The type of this function is (func (param externref i32) (result i32))
.
-
Let string be ? UnwrapString(string).
-
Let length be the length of string.
-
If index >= length
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Return CharCodeAt(string, index).
5.1.9. codePointAt
The type of this function is (func (param externref i32) (result i32))
.
-
Let string be ? UnwrapString(string).
-
Let length be the length of string.
-
If index >= length
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
Return ! Call(String.prototype.codePointAt, string, « ToJSValue(index) »).
5.1.10. length
The funcType of this builtin is (func (param externref) (result i32))
.
-
Let string be ? UnwrapString(v).
-
Return the length of string.
5.1.11. concat
The funcType of this builtin is (func (param externref externref) (result externref))
.
-
Let first be ? UnwrapString(first).
-
Let second be ? UnwrapString(second).
-
Return ! Call(String.prototype.concat, first, « second »).
5.1.12. substring
The funcType of this builtin is (func (param externref i32 i32) (result externref))
.
-
Let string be ? UnwrapString(string).
-
Let length be the length of string.
-
If start > end or start > length
-
Return the empty string.
-
-
Return ! Call(String.prototype.substring, string, « ToJSValue(start), ToJSValue(end) »).
5.1.13. equals
The funcType of this builtin is (func (param externref externref) (result i32))
.
Note: Explicitly allow null strings to be compared for equality as that is meaningful.
When this builtin is invoked with parameters first and second, the following steps must be run:
-
If first is not null and Type(first) is not String
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
If second is not null and Type(second) is not String
-
Throw a
RuntimeError
exception as if a trap was executed.
-
-
If ! IsStrictlyEqual(first, second) is true
-
Return 1.
-
-
Return 0.
5.1.14. compare
The funcType of this builtin is (func (param externref externref) (result i32))
.
When this builtin is invoked with parameters first and second, the following steps must be run:
-
Let first be ? UnwrapString(first).
-
Let second be ? UnwrapString(second).
-
If ! IsStrictlyEqual(first, second) is true
-
Return 0.
-
-
If ! IsLessThan(first, second, true) is true
-
Return -1.
-
-
Return 1.
6. 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.
6.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.
6.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.
-
a
RangeError
, as specified in theMemory
grow()
andTable
grow()
operations -
returning -1 as the memory.grow instruction
-
UA-specific OOM behavior as described in this section.
See Issue 879 for further discussion.
7. Implementation-defined Limits
The WebAssembly core specification allows an implementation to define limits on the syntactic structure of the module.
While each embedding of WebAssembly may choose to define its own limits, for predictability the standard WebAssembly JavaScript Interface described in this document defines the following exact limits.
An implementation must reject a module that exceeds one of the following limits with a CompileError
.
In practice, an implementation may run out of resources for valid modules below these limits.
- The maximum size of a module is 1,073,741,824 bytes (1 GiB).
- The maximum number of types defined in the types section is 1,000,000.
- The maximum number of recursion groups defined in the types sections is 1,000,000.
- The maximum number of types defined in a recursion group is 1,000,000.
- The maximum depth of a defined subtype hierarchy is 63 (where a type defined with no supertype has depth 0).
- The maximum number of functions defined in a module is 1,000,000.
- The maximum number of imports declared in a module is 100,000.
- The maximum number of exports declared in a module is 100,000.
- The maximum number of globals defined in a module is 1,000,000.
- The maximum number of tags defined in a module is 1,000,000.
- The maximum number of data segments defined in a module is 100,000.
- The maximum number of tables, including declared or imported tables, is 100,000.
- The maximum size of a table is 10,000,000.
- The maximum number of table entries in any table initialization is 10,000,000.
- The maximum number of memories, including defined and imported memories, is 100.
- The maximum number of parameters to any function or block is 1,000.
- The maximum number of return values for any function or block is 1,000.
- The maximum size of a function body, including locals declarations, is 7,654,321 bytes.
- The maximum number of locals declared in a function, including implicitly declared as parameters, is 50,000.
- The maximum number of fields in a struct is 10,000.
- The maximum number of operands to
array.new_fixed
is 10,000.
An implementation must throw a RuntimeError
if one of the following limits is exceeded during runtime:
In practice, an implementation may run out of resources for valid modules below these limits.
- The maximum size of a table is 10,000,000.
- The maximum number of pages of a memory is 65,536.
8. Security and Privacy Considerations
This section is non-normative.
This document defines a host environment for WebAssembly. It enables a WebAssembly instance to import JavaScript objects and functions from an import object, but otherwise provides no access to the embedding environment. Thus a WebAssembly instance is bound to the same constraints as JavaScript.