diff options
author | Casper Beyer <caspervonb@pm.me> | 2020-12-04 02:36:13 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-12-03 19:36:13 +0100 |
commit | de036e1f08dad4c5d0c6641f1942750558e3e787 (patch) | |
tree | 2a99e297c3213e1a86f36f1675a13af9a38a0aea | |
parent | 93d9f51d16711e6ec0763e1189eb1a57a5ba8e3e (diff) |
feat(std/wasi): add support for initializing reactors (#8603)
This adds another entry point to Context called initialize for
spinning up style modules.
Reactors are modules that don't have a main function and
basically run forever in the background.
-rw-r--r-- | std/wasi/snapshot_preview1.ts | 33 | ||||
-rw-r--r-- | std/wasi/snapshot_preview1_test.ts | 42 |
2 files changed, 75 insertions, 0 deletions
diff --git a/std/wasi/snapshot_preview1.ts b/std/wasi/snapshot_preview1.ts index eb296c47d..4c974fe1d 100644 --- a/std/wasi/snapshot_preview1.ts +++ b/std/wasi/snapshot_preview1.ts @@ -1588,4 +1588,37 @@ export default class Context { _start(); } + + /** + * Attempt to initialize instance as a reactor by invoking its _initialize() export. + * + * If instance contains a _start() export, then an exception is thrown. + * + * The instance must also have a WebAssembly.Memory export named "memory" + * which will be used as the address space, if it does not an error will be + * thrown. + */ + initialize(instance: WebAssembly.Instance) { + const { _start, _initialize, memory } = instance.exports; + + if (!(memory instanceof WebAssembly.Memory)) { + throw new TypeError("WebAsembly.instance must provide a memory export"); + } + + this.memory = memory; + + if (typeof _start == "function") { + throw new TypeError( + "WebAssembly.Instance export _start must not be a function", + ); + } + + if (typeof _initialize != "function") { + throw new TypeError( + "WebAsembly.instance export _initialize must be a function", + ); + } + + _initialize(); + } } diff --git a/std/wasi/snapshot_preview1_test.ts b/std/wasi/snapshot_preview1_test.ts index 44877117c..d7e29e195 100644 --- a/std/wasi/snapshot_preview1_test.ts +++ b/std/wasi/snapshot_preview1_test.ts @@ -180,3 +180,45 @@ Deno.test("context_start", function () { "export _start must be a function", ); }); + +Deno.test("context_initialize", function () { + assertThrows( + () => { + const context = new Context({}); + context.initialize({ + exports: { + _initialize() {}, + }, + }); + }, + TypeError, + "must provide a memory export", + ); + + assertThrows( + () => { + const context = new Context({}); + context.initialize({ + exports: { + _start() {}, + memory: new WebAssembly.Memory({ initial: 1 }), + }, + }); + }, + TypeError, + "export _start must not be a function", + ); + + assertThrows( + () => { + const context = new Context({}); + context.initialize({ + exports: { + memory: new WebAssembly.Memory({ initial: 1 }), + }, + }); + }, + TypeError, + "export _initialize must be a function", + ); +}); |