WebAssembly JavaScript Interface

W3C Recommendation,

This version:
https://www.w3.org/TR/2019/REC-wasm-js-api-1-20191205/
Latest published version:
https://www.w3.org/TR/wasm-js-api-1/
Editor's Draft:
https://webassembly.github.io/spec/js-api/
Previous Versions:
https://www.w3.org/TR/2019/PR-wasm-js-api-1-20191001/
Issue Tracking:
Inline In Spec
GitHub Issues
Editor:
Daniel Ehrenberg (Igalia)

Please check the errata for any errors or issues reported since publication.


Abstract

This document provides an explicit JavaScript API for interacting with WebAssembly.

Part of a collection of related documents: the Core WebAssembly Specification, the WebAssembly JS Interface, and the WebAssembly Web API.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document was produced by the WebAssembly Working Group as a Proposed Recommendation.

Technical comments are welcomed by the Working Group to improve future versions of WebAssembly. GitHub Issues are preferred for discussion of this specification. When filing an issue, please put the text “wasm-js-api” in the title, preferably like this: “[wasm-js-api] …summary of comment…”. All issues and comments are archived.

This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 March 2019 W3C Process Document.

Since Candidate Recommendation, the normaitve reference to IEE754 was changed to 754-2019.

According to the Web Platform Tests, which provide an implementation report, this specification has at least two implementations of each feature.

This API privides 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. 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 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.

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. However, this property does not hold for shared objects.

Each agent is associated with the following ordered maps:

3. The WebAssembly Namespace

dictionary WebAssemblyInstantiatedSource {
    required Module module;
    required Instance instance;
};

[Exposed=(Window,Worker,Worklet)]
namespace WebAssembly {
    boolean validate(BufferSource bytes);
    Promise<Module> compile(BufferSource bytes);

    Promise<WebAssemblyInstantiatedSource> instantiate(
        BufferSource bytes, optional object importObject);

    Promise<Instance> instantiate(
        Module moduleObject, optional object importObject);
};
To compile a WebAssembly module from source bytes bytes, perform the following steps:
  1. Let module be module_decode(bytes). If module is error, return error.

  2. If module_validate(module) is error, return error.

  3. Return module.

The validate(bytes) method, when invoked, performs the following steps:
  1. Let stableBytes be a copy of the bytes held by the buffer bytes.

  2. Compile stableBytes as a WebAssembly module and store the results as module.

  3. If module is error, return false.

  4. Return true.

A Module object represents a single WebAssembly module. Each Module object has the following internal slots:
To construct a WebAssembly module object from a module module and source bytes bytes, perform the following steps:
  1. Let moduleObject be a new Module object.

  2. Set moduleObject.[[Module]] to module.

  3. Set moduleObject.[[Bytes]] to bytes.

  4. Return moduleObject.

To asynchronously compile a WebAssembly module from source bytes bytes, using optional task source taskSource, perform the following steps:
  1. Let promise be a new promise.

  2. Run the following steps in parallel:

    1. Compile the WebAssembly module bytes and store the result as module.

    2. Queue a task to perform the following steps. If taskSource was provided, queue the task on that task source.

      1. If module is error, reject promise with a CompileError exception.

      2. Otherwise,

        1. Construct a WebAssembly module object from module and bytes, and let moduleObject be the result.

        2. Resolve promise with moduleObject.

  3. Return promise.

The compile(bytes) method, when invoked, performs the following steps:
  1. Let stableBytes be a copy of the bytes held by the buffer bytes.

  2. Asynchronously compile a WebAssembly module from stableBytes and return the result.

To read the imports from a WebAssembly module module from imports object importObject, perform the following steps:
  1. If module.𝗂𝗆𝗉𝗈𝗋𝗍𝗌 is not an empty list, and importObject is undefined, throw a TypeError exception.

  2. Let imports be an empty list of external values.

  3. For each (moduleName, componentName, externtype) in module_imports(module), do

    1. Let o be ? Get(importObject, moduleName).

    2. If Type(o) is not Object, throw a TypeError exception.

    3. Let v be ? Get(o, componentName)

    4. If externtype is of the form 𝖿𝗎𝗇𝖼 functype,

      1. If IsCallable(v) is false, throw a LinkError exception.

      2. If v has a [[FunctionAddress]] internal slot, and therefore is an Exported Function,

        1. Let funcaddr be the value of v’s [[FunctionAddress]] internal slot.

        Note: The signature is checked by module_instantiate invoked below.

      3. Otherwise,

        1. Create a host function from v and functype, and let funcaddr be the result.

        2. Let index be the number of external functions in imports. This value index is known as the index of the host function funcaddr.

      4. Let externfunc be the external value 𝖿𝗎𝗇𝖼 funcaddr.

      5. Append externfunc to imports.

    5. If externtype is of the form 𝗀𝗅𝗈𝖻𝖺𝗅 mut valtype,

      1. If Type(v) is Number,

        1. If valtype is 𝗂𝟨𝟦, throw a LinkError exception.

        2. Let value be ToWebAssemblyValue(v, valtype)

        3. Let store be the surrounding agent's associated store.

        4. Let (store, globaladdr) be global_alloc(store, const valtype, value).

        5. Set the surrounding agent's associated store to store.

      2. If v is a Global instance,

        1. Let globaladdr be v.[[Global]]

      3. Otherwise,

        1. Throw a LinkError exception.

      4. Let externglobal be 𝗀𝗅𝗈𝖻𝖺𝗅 globaladdr.

      5. Append externglobal to imports.

    6. If externtype is of the form 𝗆𝖾𝗆 memtype,

      1. If v is not a Memory object, throw a LinkError exception.

      2. Note: module_instantiate invoked below will check the imported Memory's size against the importing module’s requirements.

      3. Let externmem be the external value 𝗆𝖾𝗆 v.[[Memory]].

      4. Append externmem to imports.

    7. Otherwise, externtype is of the form 𝗍𝖺𝖻𝗅𝖾 tabletype,

      1. If v is not a Table instance, throw a LinkError exception.

      2. Note: The table’s length, etc. is checked by module_instantiate invoked below.

      3. Let tableaddr be v.[[Table]]

      4. Let externtable be the external value 𝗍𝖺𝖻𝗅𝖾 tableaddr.

      5. Append externtable to imports.

  4. Return imports.

To create an exports object from a WebAssembly module module and instance instance, perform the following steps:
  1. Let exportsObject be ! ObjectCreate(null).

  2. For each pair (name, externtype) in module_exports(module),

    1. Let externval be instance_export(instance, name).

    2. Assert: externval is not error.

    3. If externtype is of the form 𝖿𝗎𝗇𝖼 functype,

      1. Assert: externval is of the form 𝖿𝗎𝗇𝖼 funcaddr.

      2. Let 𝖿𝗎𝗇𝖼 funcaddr be externval.

      3. Let func be the result of creating a new Exported Function from funcaddr.

      4. Let value be func.

    4. If externtype is of the form 𝗀𝗅𝗈𝖻𝖺𝗅 globaltype,

      1. Assert: externval is of the form 𝗀𝗅𝗈𝖻𝖺𝗅 globaladdr.

      2. Let 𝗀𝗅𝗈𝖻𝖺𝗅 globaladdr be externval.

      3. Let global be a new Global object created from globaladdr.

      4. Let value be global.

    5. If externtype is of the form 𝗆𝖾𝗆 memtype,

      1. Assert: externval is of the form 𝗆𝖾𝗆 memaddr.

      2. Let 𝗆𝖾𝗆 memaddr be externval.

      3. Let memory be a new Memory object created from memaddr.

      4. Let value be memory.

    6. Otherwise, externtype is of the form 𝗍𝖺𝖻𝗅𝖾 tabletype,

      1. Assert: externval is of the form 𝗍𝖺𝖻𝗅𝖾 tableaddr.

      2. Let 𝗍𝖺𝖻𝗅𝖾 tableaddr be externval.

      3. Let table be a new Table object created from tableaddr.

      4. Let value be table.

    7. Let status be ! CreateDataProperty(exportsObject, name, value).

    8. 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.

  3. Perform ! SetIntegrityLevel(exportsObject, "frozen").

  4. Return exportsObject.

To initialize an instance object instanceObject from a WebAssembly module module and instance instance, perform the following steps:
  1. Create an exports object from module and instance and let exportsObject be the result.

  2. Set instanceObject.[[Instance]] to instance.

  3. Set instanceObject.[[Exports]] to exportsObject.

To instantiate the core of a WebAssembly module from a module module and imports imports, perform the following steps:
  1. Let store be the surrounding agent's associated store.

  2. Let result be module_instantiate(store, module, imports).

  3. 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.

  4. Let (store, instance) be result.

  5. Set the surrounding agent's associated store to store.

  6. Return instance.

To asynchronously instantiate a WebAssembly module from a Module moduleObject and imports importObject, perform the following steps:
  1. Let promise be a new promise.

  2. Let module be moduleObject.[[Module]].

  3. Read the imports of module with imports importObject, and let imports be the result. If this operation throws an exception, catch it, reject promise with the exception, and return promise.

  4. Queue a task to perform the following steps:

    1. 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.

    2. Let instanceObject be a new Instance.

    3. Initialize instanceObject from module and instance. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.

    4. Resolve promise with instanceObject.

  5. Return promise.

To instantiate a WebAssembly module from a Module moduleObject and imports importObject, perform the following steps:
  1. Let module be moduleObject.[[Module]].

  2. Read the imports of module with imports importObject, and let imports be the result.

  3. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.

  4. Let instanceObject be a new Instance.

  5. Initialize instanceObject from module and instance.

  6. Return instanceObject.

To instantiate a promise of a module promiseOfModule with imports importObject, perform the following steps:
  1. Let promise be a new promise

  2. Upon fulfillment of promiseOfModule with value module:

    1. 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.

    2. Let result be a WebAssemblyInstantiatedSource dictionary with module set to module and instance set to instance.

    3. Resolve promise with result.

  3. Upon rejection of promiseOfModule with reason reason:

    1. Reject promise with reason.

  4. 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.

The instantiate(bytes, importObject) method, when invoked, performs the following steps:
  1. Let stableBytes be a copy of the bytes held by the buffer bytes.

  2. Asynchronously compile a WebAssembly module from stableBytes and let promiseOfModule be the result.

  3. Instantiate promiseOfModule with imports importObject and return the result.

The instantiate(moduleObject, importObject) method, when invoked, performs the following steps:
  1. 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.

3.1. Modules

enum ImportExportKind {
  "function",
  "table",
  "memory",
  "global"
};

dictionary ModuleExportDescriptor {
  required USVString name;
  required ImportExportKind kind;
  // Note: Other fields such as signature may be added in the future.
};

dictionary ModuleImportDescriptor {
  required USVString module;
  required USVString name;
  required ImportExportKind kind;
};

[LegacyNamespace=WebAssembly, Constructor(BufferSource bytes), Exposed=(Window,Worker,Worklet)]
interface Module {
  static sequence<ModuleExportDescriptor> exports(Module moduleObject);
  static sequence<ModuleImportDescriptor> imports(Module moduleObject);
  static sequence<ArrayBuffer> customSections(Module moduleObject, DOMString sectionName);
};
The string value of the extern type type is
The exports(moduleObject) method, when invoked, performs the following steps:
  1. Let module be moduleObject.[[Module]].

  2. Let exports be an empty list.

  3. For each (name, type) in module_exports(module)

    1. Let kind be the string value of the extern type type.

    2. Let obj be a new ModuleExportDescriptor dictionary with name name and kind kind.

    3. Append obj to the end of exports.

  4. Return exports.

The imports(moduleObject) method, when invoked, performs the following steps:
  1. Let module be moduleObject.[[Module]].

  2. Let imports be an empty list.

  3. For each (moduleName, name, type) in module_imports(module),

    1. Let kind be the string value of the extern type type.

    2. Let obj be a new ModuleImportDescriptor dictionary with module moduleName, name name and kind kind.

    3. Append obj to the end of imports.

  4. Return imports.

The customSections(moduleObject, sectionName) method, when invoked, performs the following steps:
  1. Let bytes be moduleObject.[[Bytes]].

  2. Let customSections be an empty list of ArrayBuffers.

  3. For each custom section customSection in bytes, interpreted according to the module grammar,

    1. Let name be the name of customSection, decoded as UTF-8.

    2. Assert: name is not failure (moduleObject.[[Module]] is valid).

    3. If name equals sectionName as string values,

      1. Append a new ArrayBuffer containing a copy of the bytes in bytes for the range matched by this customsec production.

  4. Return customSections.

The Module(bytes) constructor, when invoked, performs the follwing steps:
  1. Let stableBytes be a copy of the bytes held by the buffer bytes.

  2. Compile the WebAssembly module stableBytes and store the result as module.

  3. If module is error, throw a CompileError exception.

  4. Set this.[[Module]] to module.

  5. Set this.[[Bytes]] to stableBytes.

3.2. Instances

[LegacyNamespace=WebAssembly, Constructor(Module module, optional object importObject), Exposed=(Window,Worker,Worklet)]
interface Instance {
  readonly attribute object exports;
};
The Instance(module, importObject) constructor, when invoked, runs the following steps:
  1. Let module be module.[[Module]].

  2. Read the imports of module with imports importObject, and let imports be the result.

  3. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.

  4. Initialize this from module and instance.

The getter of the exports attribute of Instance returns this.[[Exports]].

3.3. Memories

dictionary MemoryDescriptor {
  required [EnforceRange] unsigned long initial;
  [EnforceRange] unsigned long maximum;
};

[LegacyNamespace=WebAssembly, Constructor(MemoryDescriptor descriptor), Exposed=(Window,Worker,Worklet)]
interface Memory {
  unsigned long grow([EnforceRange] unsigned long delta);
  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:
To create a memory buffer from a memory address memaddr, perform the following steps:
  1. Let block be a Data Block which is identified with the underlying memory of memaddr.

  2. Let buffer be a new ArrayBuffer whose [[ArrayBufferData]] is block and [[ArrayBufferByteLength]] is set to the length of block.

  3. Set buffer.[[ArrayBufferDetachKey]] to "WebAssembly.Memory".

  4. Return buffer.

To initialize a memory object memory from a memory address memaddr, perform the following steps:
  1. Let map be the surrounding agent's associated Memory object cache.

  2. Assert: map[memaddr] doesn’t exist.

  3. Let buffer be a the result of creating a memory buffer from memaddr.

  4. Set memory.[[Memory]] to memaddr.

  5. Set memory.[[BufferObject]] to buffer.

  6. Set map[memaddr] to memory.

To create a memory object from a memory address memaddr, perform the following steps:
  1. Let map be the surrounding agent's associated Memory object cache.

  2. If map[memaddr] exists,

    1. Return map[memaddr].

  3. Let memory be a new Memory.

  4. Initialize memory from memaddr.

  5. Return memory.

The Memory(descriptor) constructor, when invoked, performs the following steps:
  1. let initial be descriptor["initial"].

  2. If descriptor["maximum"] is present, let maximum be descriptor["maximum"]; otherwise, let maximum be empty.

  3. If maximum is not empty and maximum < initial, throw a RangeError exception.

  4. Let memtype be { min initial, max maximum }

  5. Let store be the surrounding agent's associated store.

  6. Let (store, memaddr) be mem_alloc(store, memtype). If allocation fails, throw a RangeError exception.

  7. Set the surrounding agent's associated store to store.

  8. Initialize this from memaddr.

To reset the Memory buffer of memaddr, perform the following steps:
  1. Let map be the surrounding agent's associated Memory object cache.

  2. Assert: map[memaddr] exists.

  3. Let memory be map[memaddr].

  4. Perform ! DetachArrayBuffer(memory.[[BufferObject]], "WebAssembly.Memory").

  5. Let buffer be a the result of creating a memory buffer from memaddr.

  6. Set memory.[[BufferObject]] to buffer.

The grow(delta) method, when invoked, performs the following steps:
  1. Let store be the surrounding agent's associated store.

  2. Let memaddr be this.[[Memory]].

  3. Let ret be the mem_size(store, memaddr).

  4. Let store be mem_grow(store, memaddr, delta).

  5. If store is error, throw a RangeError exception.

  6. Set the surrounding agent's associated store to store.

  7. Reset the memory buffer of memaddr.

  8. Return ret.

Immediately after a WebAssembly memory.grow instruction executes, perform the following steps:

  1. If the top of the stack is not 𝗂𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 (−1), then:

    1. Let frame be the current frame.

    2. Assert: due to validation, frame.𝗆𝗈𝖽𝗎𝗅𝖾.𝗆𝖾𝗆𝖺𝖽𝖽𝗋𝗌[0] exists.

    3. Let memaddr be the memory address frame.𝗆𝗈𝖽𝗎𝗅𝖾.𝗆𝖾𝗆𝖺𝖽𝖽𝗋𝗌[0].

    4. Reset the memory buffer of memaddr.

The getter of the buffer attribute of Memory returns this.[[BufferObject]].

3.4. Tables

enum TableKind {
  "anyfunc",
  // Note: More values may be added in future iterations,
  // e.g., typed function references, typed GC references
};

dictionary TableDescriptor {
  required TableKind element;
  required [EnforceRange] unsigned long initial;
  [EnforceRange] unsigned long maximum;
};

[LegacyNamespace=WebAssembly, Constructor(TableDescriptor descriptor), Exposed=(Window,Worker,Worklet)]
interface Table {
  unsigned long grow([EnforceRange] unsigned long delta);
  Function? get([EnforceRange] unsigned long index);
  void set([EnforceRange] unsigned long index, Function? 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 the following internal slots:
To initialize a table object table from a table address tableaddr, perform the following steps:
  1. Let map be the surrounding agent's associated Table object cache.

  2. Assert: map[tableaddr] doesn’t exist.

  3. Let store be the surrounding agent's associated store.

  4. Let values be a list whose length is table_size(store, tableaddr) where each element is null.

  5. Set table.[[Table]] to tableaddr.

  6. Set table.[[Values]] to values.

  7. Set map[tableaddr] to table.

To create a table object from a table address tableaddr, perform the following steps:
  1. Let map be the surrounding agent's associated Table object cache.

  2. If map[tableaddr] exists,

    1. Return map[tableaddr].

  3. Let table be a new Table.

  4. Initialize table from tableaddr.

  5. Return table.

The Table(descriptor) constructor, when invoked, performs the following steps:
  1. let initial be descriptor["initial"].

  2. If descriptor["maximum"] is present, let maximum be descriptor["maximum"]; otherwise, let maximum be empty.

  3. If maximum is not empty and maximum < initial, throw a RangeError exception.

  4. Let type be the table type {𝗆𝗂𝗇 n, 𝗆𝖺𝗑 maximum} 𝖺𝗇𝗒𝖿𝗎𝗇𝖼.

  5. Let store be the surrounding agent's associated store.

  6. Let (store, tableaddr) be table_alloc(store, type).

  7. Set the surrounding agent's associated store to store.

  8. Initialize this from tableaddr.

The grow(delta) method, when invoked, performs the following steps:
  1. Let tableaddr be this.[[Table]].

  2. Let initialSize be the length of this.[[Values]].

  3. Let store be the surrounding agent's associated store.

  4. Let result be table_grow(store, tableaddr, delta).

  5. If result is error, throw a RangeError exception.

    Note: The above exception may happen due to either insufficient memory or an invalid size parameter.

  6. Set the surrounding agent's associated store to result.

  7. Append null to this.[[Values]] delta times.

  8. Return initialSize.

The getter of the length attribute of Table returns the length of this.[[Values]].
The get(index) method, when invoked, performs the following steps:
  1. Let values be this.[[Values]].

  2. Let size be the length of values.

  3. If indexsize, throw a RangeError exception.

  4. Return values[index].

The set(index, value) method, when invoked, performs the following steps:
  1. Let tableaddr be this.[[Table]].

  2. Let values be this.[[Values]].

  3. If value is null, let funcaddr be an empty function element.

  4. Otherwise,

    1. If value does not have a [[FunctionAddress]] internal slot, throw a TypeError exception.

    2. Let funcaddr be value.[[FunctionAddress]].

  5. Let store be the surrounding agent's associated store.

  6. Let store be table_write(store, tableaddr, index, funcaddr).

  7. If store is error, throw a RangeError exception.

  8. Set the surrounding agent's associated store to store.

  9. Set values[index] to value.

  10. Return undefined.

3.5. Globals

enum ValueType {
  "i32",
  "i64",
  "f32",
  "f64"
};

Note: this type may be extended with additional cases in future versions of WebAssembly.

dictionary GlobalDescriptor {
  required ValueType value;
  boolean mutable = false;
};

[LegacyNamespace=WebAssembly, Constructor(GlobalDescriptor descriptor, optional any v), Exposed=(Window,Worker,Worklet)]
interface Global {
  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:
To initialize a global object global from a global address globaladdr, perform the following steps:
  1. Let map be the surrounding agent's associated Global object cache.

  2. Assert: map[globaladdr] doesn’t exist.

  3. Set global.[[Global]] to globaladdr.

  4. Set map[globaladdr] to global.

To create a global object from a global address globaladdr, perform the following steps:
  1. Let map be the current agent's associated Global object cache.

  2. If map[globaladdr] exists,

    1. Return map[globaladdr].

  3. Let global be a new Global.

  4. Initialize global from globaladdr.

  5. Return global.

The algorithm ToValueType(s) performs the following steps:
  1. If s equals "i32", return 𝗂𝟥𝟤.

  2. If s equals "i64", return 𝗂𝟨𝟦.

  3. If s equals "f32", return 𝖿𝟥𝟤.

  4. If s equals "f64", return 𝖿𝟨𝟦.

The algorithm DefaultValue(valuetype) performs the following steps:
  1. If valuetype equals 𝗂𝟥𝟤, return 𝗂𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 0.

  2. If valuetype equals 𝗂𝟨𝟦, return 𝗂𝟨𝟦.𝖼𝗈𝗇𝗌𝗍 0.

  3. If valuetype equals 𝖿𝟥𝟤, return 𝖿𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 0.

  4. If valuetype equals 𝖿𝟨𝟦, return 𝖿𝟨𝟦.𝖼𝗈𝗇𝗌𝗍 0.

  5. Assert: This step is not reached.

The Global(descriptor, v) constructor, when invoked, performs the following steps:
  1. Let mutable be descriptor["mutable"].

  2. Let valuetype be ToValueType(descriptor["value"]).

  3. If v is undefined,

    1. let value be DefaultValue(valuetype).

  4. Otherwise,

    1. If valuetype is 𝗂𝟨𝟦, throw a TypeError exception.

    2. Let value be ToWebAssemblyValue(v, valuetype).

  5. If mutable is true, let globaltype be var valuetype; otherwise, let globaltype be const valuetype.

  6. Let store be the current agent’s associated store.

  7. Let (store, globaladdr) be global_alloc(store, globaltype, value).

  8. Set the current agent’s associated store to store.

  9. Initialize this from globaladdr.

The algorithm GetGlobalValue(Global global) performs the following steps:
  1. Let store be the current agent’s associated store.

  2. Let globaladdr be global.[[Global]].

  3. Let globaltype be global_type(store, globaladdr).

  4. If globaltype is of the form mut 𝗂𝟨𝟦, throw a TypeError.

  5. Let value be global_read(store, globaladdr).

  6. Return ToJSValue(value).

The getter of the value attribute of Global, when invoked, performs the following steps:
  1. Return GetGlobalValue(this).

The setter of the value attribute of Global, when invoked, performs the following steps:

  1. Let store be the current agent’s associated store.

  2. Let globaladdr be this.[[Global]].

  3. Let globaltype be global_type(store, globaladdr), where globaltype is of the form mut valuetype.

  4. If mut is const, throw a TypeError.

  5. If valuetype is 𝗂𝟨𝟦, throw a TypeError.

  6. Let value be ToWebAssemblyValue(the given value, valuetype).

  7. Let store be global_write(store, globaladdr, value).

  8. If store is error, throw a RangeError exception.

  9. Set the current agent’s associated store to store.

The valueOf() method, when invoked, performs the following steps:
  1. Return GetGlobalValue(this).

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 surrounding agent's associated store.

The name of the WebAssembly function funcaddr is found by performing the following steps:
  1. Let store be the surrounding agent's associated store.

  2. Let funcinst be store.𝖿𝗎𝗇𝖼𝗌[funcaddr].

  3. If funcinst is of the form {𝗍𝗒𝗉𝖾 functype, 𝗁𝗈𝗌𝗍𝖼𝗈𝖽𝖾 hostfunc},

    1. Assert: hostfunc is a JavaScript object and IsCallable(hostfunc) is true.

    2. Let index be the index of the host function funcaddr.

  4. Otherwise,

    1. Let moduleinst be funcinst.𝗆𝗈𝖽𝗎𝗅𝖾.

    2. Assert: funcaddr is contained in moduleinst.𝖿𝗎𝗇𝖼𝖺𝖽𝖽𝗋𝗌.

    3. Let index be the index of moduleinst.𝖿𝗎𝗇𝖼𝖺𝖽𝖽𝗋𝗌 where funcaddr is found.

  5. Return ! ToString(index).

To create a new Exported Function from a WebAssembly function address funcaddr, perform the following steps:
  1. Let map be the surrounding agent's associated Exported Function cache.

  2. If map[funcaddr] exists,

    1. Return map[funcaddr].

  3. Let steps be "call the Exported Function funcaddr with arguments."

  4. Let realm be the current Realm.

  5. Let function be CreateBuiltinFunction(realm, steps, %FunctionPrototype%, « [[FunctionAddress]] »).

  6. Set function.[[FunctionAddress]] to funcaddr.

  7. Let store be the surrounding agent's associated store.

  8. Let functype be func_type(store, funcaddr).

  9. Let [paramTypes] → [resultTypes] be functype.

  10. Let arity be the length of paramTypes.

  11. Perform ! SetFunctionLength(function, arity).

  12. Let name be the name of the WebAssembly function funcaddr.

  13. Perform ! SetFunctionName(function, name).

  14. Set map[funcaddr] to function.

  15. Return function.

To call an Exported Function with function address funcaddr and a list of JavaScript arguments argValues, perform the following steps:
  1. Let store be the surrounding agent's associated store.

  2. Let functype be func_type(store, funcaddr).

  3. Let [parameters] → [results] be functype.

  4. If parameters or results contains an 𝗂𝟨𝟦, throw a TypeError.

    Note: the above error is thrown each time the [[Call]] method is invoked.

  5. Let args be an empty list of WebAssembly values.

  6. Let i be 0.

  7. For each type t of parameters,

    1. If the length of argValues > i, let arg be argValues[i].

    2. Otherwise, let arg be undefined.

    3. Append ToWebAssemblyValue(arg, t) to args.

    4. Set i to i + 1.

  8. Let argsSeq be a WebAssembly sequence containing the elements of args.

  9. Let (store, ret) be the result of func_invoke(store, funcaddr, argsSeq).

  10. Set the surrounding agent's associated store to store.

  11. If ret is error, throw an exception. This exception should be a WebAssembly RuntimeError exception, unless otherwise indicated by the WebAssembly error mapping.

  12. If ret is empty, return undefined.

  13. 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.

To run a host function from the JavaScript object func and type functype, perform the following steps:
  1. Let [parameters] → [results] be functype.

  2. Assert: results’s size is at most one.

  3. If either parameters or results contains 𝗂𝟨𝟦, throw a TypeError.

  4. Let arguments be a list of the arguments of the invocation of this function.

  5. Let jsArguments be an empty list.

  6. For each arg in arguments,

    1. Append ! ToJSValue(arg) to jsArguments.

  7. Let ret be ? Call(func, undefined, jsArguments).

  8. If results is empty, return undefined.

  9. Otherwise, return ? ToWebAssemblyValue(ret, results[0]).

To create a host function from the JavaScript object func and type functype, perform the following steps:
  1. Let hostfunc be a host function which performs the following steps when called:

    1. Let result be the result of running a host function from func and functype.

    2. Assert: result.[[Type]] is throw or return.

    3. If result.[[Type]] is throw, then trigger a WebAssembly trap, and propagate result.[[Value]] to the enclosing JavaScript.

    4. Otherwise, return result.[[Value]].

  2. Let store be the surrounding agent's associated store.

  3. Let (store, funcaddr) be func_alloc(store, functype, hostfunc).

  4. Set the surrounding agent's associated store to store.

  5. Return funcaddr

The algorithm ToJSValue(w) coerces a WebAssembly value to a JavaScript value performs the following steps:
  1. Assert: w is not of the form 𝗂𝟨𝟦.𝖼𝗈𝗇𝗌𝗍 i64.

  2. If w is of the form 𝗂𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 i32, return the Number value for signed_32(i32).

  3. If w is of the form 𝖿𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 f32, return the Number value for f32.

  4. If w is of the form 𝖿𝟨𝟦.𝖼𝗈𝗇𝗌𝗍 f64, return the Number value for f64.

Note: Number values which are equal to NaN may have various observable NaN payloads; see NumberToRawBytes for details.

The algorithm ToWebAssemblyValue(v, type) coerce a JavaScript value to a WebAssembly value performs the following steps:
  1. Assert: type is not 𝗂𝟨𝟦.

  2. If type is 𝗂𝟥𝟤,

    1. Let i32 be ? ToInt32(v).

    2. Return 𝗂𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 i32.

  3. If type is 𝖿𝟥𝟤,

    1. Let f32 be ? ToNumber(v) rounded to the nearest representable value using IEEE 754-2019 round to nearest, ties to even mode.

    2. Return 𝖿𝟥𝟤.𝖼𝗈𝗇𝗌𝗍 f32.

  4. If type is 𝖿𝟨𝟦,

    1. Let f64 be ? ToNumber(v).

    2. Return 𝖿𝟨𝟦.𝖼𝗈𝗇𝗌𝗍 f64.

3.7. Error Objects

WebAssembly defines the following Error classes: CompileError, LinkError, and RuntimeError. WebAssembly errors have the following custom bindings:

[LegacyNamespace=WebAssembly]
interface CompileError { };

[LegacyNamespace=WebAssembly]
interface LinkError { };

[LegacyNamespace=WebAssembly]
interface RuntimeError { };

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.

A failed allocation of a large table or memory may either result in In a future revision, we may reconsider more reliable and recoverable errors for allocations of large amounts of memory.

See Issue 879 for further discussion.

5. 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 these limits with a CompileError. In practice, an implementation may run out of resources for valid modules below these limits.

6. 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 bounds to the same constraints as JavaScript.

Changes

Changes since the previous Working Draft:

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[ECMASCRIPT]
ECMAScript Language Specification. URL: https://tc39.github.io/ecma262/
[ENCODING]
Anne van Kesteren. Encoding Standard. Living Standard. URL: https://encoding.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/
[PROMISES-GUIDE]
Domenic Denicola. Writing Promise-Using Specifications. 9 November 2018. TAG Finding. URL: https://www.w3.org/2001/tag/doc/promises-guide
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WEBASSEMBLY]
WebAssembly Core Specification. Draft. URL: https://webassembly.github.io/spec/core/
[WebIDL]
Boris Zbarsky. Web IDL. 15 December 2016. ED. URL: https://heycam.github.io/webidl/

IDL Index

dictionary WebAssemblyInstantiatedSource {
    required Module module;
    required Instance instance;
};

[Exposed=(Window,Worker,Worklet)]
namespace WebAssembly {
    boolean validate(BufferSource bytes);
    Promise<Module> compile(BufferSource bytes);

    Promise<WebAssemblyInstantiatedSource> instantiate(
        BufferSource bytes, optional object importObject);

    Promise<Instance> instantiate(
        Module moduleObject, optional object importObject);
};

enum ImportExportKind {
  "function",
  "table",
  "memory",
  "global"
};

dictionary ModuleExportDescriptor {
  required USVString name;
  required ImportExportKind kind;
  // Note: Other fields such as signature may be added in the future.
};

dictionary ModuleImportDescriptor {
  required USVString module;
  required USVString name;
  required ImportExportKind kind;
};

[LegacyNamespace=WebAssembly, Constructor(BufferSource bytes), Exposed=(Window,Worker,Worklet)]
interface Module {
  static sequence<ModuleExportDescriptor> exports(Module moduleObject);
  static sequence<ModuleImportDescriptor> imports(Module moduleObject);
  static sequence<ArrayBuffer> customSections(Module moduleObject, DOMString sectionName);
};

[LegacyNamespace=WebAssembly, Constructor(Module module, optional object importObject), Exposed=(Window,Worker,Worklet)]
interface Instance {
  readonly attribute object exports;
};

dictionary MemoryDescriptor {
  required [EnforceRange] unsigned long initial;
  [EnforceRange] unsigned long maximum;
};

[LegacyNamespace=WebAssembly, Constructor(MemoryDescriptor descriptor), Exposed=(Window,Worker,Worklet)]
interface Memory {
  unsigned long grow([EnforceRange] unsigned long delta);
  readonly attribute ArrayBuffer buffer;
};

enum TableKind {
  "anyfunc",
  // Note: More values may be added in future iterations,
  // e.g., typed function references, typed GC references
};

dictionary TableDescriptor {
  required TableKind element;
  required [EnforceRange] unsigned long initial;
  [EnforceRange] unsigned long maximum;
};

[LegacyNamespace=WebAssembly, Constructor(TableDescriptor descriptor), Exposed=(Window,Worker,Worklet)]
interface Table {
  unsigned long grow([EnforceRange] unsigned long delta);
  Function? get([EnforceRange] unsigned long index);
  void set([EnforceRange] unsigned long index, Function? value);
  readonly attribute unsigned long length;
};

enum ValueType {
  "i32",
  "i64",
  "f32",
  "f64"
};

dictionary GlobalDescriptor {
  required ValueType value;
  boolean mutable = false;
};

[LegacyNamespace=WebAssembly, Constructor(GlobalDescriptor descriptor, optional any v), Exposed=(Window,Worker,Worklet)]
interface Global {
  any valueOf();
  attribute any value;
};

[LegacyNamespace=WebAssembly]
interface CompileError { };

[LegacyNamespace=WebAssembly]
interface LinkError { };

[LegacyNamespace=WebAssembly]
interface RuntimeError { };

Issues Index

A failed allocation of a large table or memory may either result in In a future revision, we may reconsider more reliable and recoverable errors for allocations of large amounts of memory.

See Issue 879 for further discussion.