Commit Graph

92 Commits

Author SHA1 Message Date
Teppei Fukuda
bed4959f6d Adds Zig example (#741)
Signed-off-by: knqyf263 <knqyf263@gmail.com>
2022-08-11 16:31:06 +08:00
Crypt Keeper
fe56fabd63 Removes invalid ignore files (#734)
None of the examples suggest `go build` first anymore.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-08-04 19:57:03 +12:00
Takeshi Yoneda
c50ed2c263 example: adds missing error check (#727)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-07-30 11:34:33 +09:00
Takeshi Yoneda
02c23d55db Disallow direct call of host functions (#723)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-07-30 09:33:20 +08:00
Takeshi Yoneda
ed068597cd ci: adds Go 1.19.0-rc.2 into matrix (#714)
This adds the 1.19.0-rc2. in the testing matrix.

This also formats the Godocs across the codebase, as
Go 1.19 has started auto-formatting Godoc. https://github.com/tetratelabs/wazero/issues/426

Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-07-25 11:14:00 +09:00
Crypt Keeper
0d76b11d66 Adds Emscripten integration (#678)
This adds a toehold integration for emscripten users, so they don't
have to define the memory growth function.

Fixes #601

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-07-18 07:51:48 +08:00
Crypt Keeper
b1f4ced425 Uses Zig 0.10.0-dev for cc, adding the name section (#706)
This manually installs in CI until 0.10.0 is released.

Here's the example wasm trace output from cat.c:
```
--> ._start.command_export()
	--> .__wasm_call_ctors()
		--> .__wasilibc_populate_preopens()
			==> wasi_snapshot_preview1.fd_prestat_get(fd=3,result.prestat=1048568)
			<== ESUCCESS
			--> .dlmalloc(2)
			<-- (1051568)
			==> wasi_snapshot_preview1.fd_prestat_dir_name(fd=3,path=1051568,path_len=1)
			<== ESUCCESS
			--> .dlmalloc(32)
			<-- (1051584)
			--> .memset(32,0,1051584)
			<-- (1051584)
			--> .memcpy(0,0,1051584)
			<-- (1051584)
			--> .free(0)
			<-- ()
			--> .dlmalloc(1)
			<-- (1051632)
			--> .memcpy(1,1051569,1051632)
			<-- (1051632)
			--> .free(1051568)
			<-- ()
			==> wasi_snapshot_preview1.fd_prestat_get(fd=4,result.prestat=1048568)
			<== EBADF
		<-- ()
	<-- ()
	--> ._start()
		--> .__original_main()
			==> wasi_snapshot_preview1.args_sizes_get(result.argc=1048024,result.argv_buf_size=1048028)
			<== ESUCCESS
			--> .dlmalloc(15)
			<-- (1051648)
			--> .dlmalloc(12)
			<-- (1051568)
			--> .memset(12,0,1051568)
			<-- (1051568)
			==> wasi_snapshot_preview1.args_get(argv=1051568,argv_buf=1051648)
			<== ESUCCESS
			==> wasi_snapshot_preview1.fd_fdstat_get(fd=3,result.stat=1048544)
			<== ESUCCESS
			==> wasi_snapshot_preview1.path_open(fd=3,dirflags=1,path=1051654,path_len=8,oflags=0,fs_rights_base=0,fs_rights_inheriting=0,fdflags=0,result.opened_fd=1048572)
			<== ESUCCESS
			==> wasi_snapshot_preview1.fd_read(fd=4,iovs=1048544,iovs_len=1,result.size=1048572)
			<== ESUCCESS
			==> wasi_snapshot_preview1.fd_write(fd=1,iovs=1048544,iovs_len=1,result.size=1048572)
greet filesystem
			<== ESUCCESS
			==> wasi_snapshot_preview1.fd_read(fd=4,iovs=1048544,iovs_len=1,result.size=1048572)
			<== ESUCCESS
			==> wasi_snapshot_preview1.fd_close(fd=4)
			<== ESUCCESS
		<-- (0)
	<-- ()
	--> .__wasm_call_dtors()
		--> .__stdio_exit()
		<-- ()
	<-- ()
<-- ()

```

Special thanks to @Luukdegram for supporting the `--export` linker
argument even if this particular example doesn't use it.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-07-16 15:53:53 +08:00
Crypt Keeper
14d892d310 Removes api.ImportRenamer for a different approach to "env" (#680)
Before, we introduced a type `api.ImportRenamer` to resolve conflicts
where the "env" module was shared between AssemblyScript and
user-defined functions. This API was never used in GitHub, and is
complicated.

AssemblyScript also isn't the only ABI to share the "env" module, as
other web APIs like Emscripten do also. The less complicated approach is
to have packages that need to share "env" use
`ModuleBuilder.ExportFunctions` instead, and use namespaces as needed if
there is overlap.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-07-11 14:57:26 +08:00
Takeshi Yoneda
09a8aa6030 example(wasi): fixes link drifts (#679)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-07-11 07:33:41 +08:00
Crypt Keeper
f0e05fb95b examples: adds rust build and WASI example (#676)
This fixes where our pull requests didn't check the rust source in
examples were valid. It also adds an example of wasi with rust.

This uses cargo-wasi because the default target creates almost 2MB of
wasm for a simple cat program.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-07-08 10:49:50 +08:00
Crypt Keeper
8c2f0928bc Panics caller on exit error (#673)
This changes the AssemblyScript abort handler and WASI proc_exit
implementation to panic the caller which eventually invoked close.

This ensures no code executes afterwards, For example, LLVM inserts
unreachable instructions after calls to exit.

See https://github.com/emscripten-core/emscripten/issues/12322
See #601

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-07-06 16:30:31 +08:00
Anuraag Agrawal
bd1f742cb2 Enable wasm 2.0 support in tinygo examples to allow running with wasm… (#672)
* Enable wasm 2.0 support in tinygo examples to allow running with wasm built with latest

Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
2022-07-05 15:23:38 +09:00
Crypt Keeper
798ff20f81 Removes WithWorkDirFS and "." resolution (#660)
This removes WithWorkDirFS and any other attempts to resolve the current directory (".") in host functions. This is a reaction to reality of compilers who track this inside wasm (not via host functions). One nice side effect is substantially simpler internal implementation of file-systems.

This also allows experimental.WithFS to block file access via passing nil.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-27 13:29:35 +08:00
Crypt Keeper
507ce79080 Adds sys.Walltime and sys.Nanotime for security and determinism (#616)
This adds two clock interfaces: sys.Walltime and sys.Nanotime to
allow implementations to override readings for purposes of security or
determinism.

The default values of both are a fake timestamp, to avoid the sandbox
break we formerly had by returning the real time. This is similar to how
we don't inherit OS Env values.
2022-06-04 15:14:31 +08:00
Crypt Keeper
92ba4929e5 Drops support for the WebAssembly text format (#614)
This drops the text format (%.wat) and renames
InstantiateModuleFromCode to InstantiateModuleFromBinary as it is no
longer ambiguous.

We decided to stop supporting the text format as it isn't typically used
in production, yet costs a lot of work to develop. Given the resources
available and the increased work added with WebAssembly 2.0 and soon
WASI 2, we can't afford to spend the time on it.

The old parser is used only internally and will eventually be moved to
its own repository named watzero, possibly towards archival.

See #59

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-01 19:01:43 +08:00
Crypt Keeper
5fae0fd76b Renames wasi package to wasi_snapshot_preview1 (#610)
The componentized successor to wasi_snapshot_preview1 is not compatible
with the prior imports or even error numbers. Before releasing wazero
1.0 we need to change this package to reflect that WASI 2 is effectively
  a different API.

Fixes #263

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-01 12:21:11 +08:00
Crypt Keeper
adc7e5b170 Adds Runtime.NewNamespace to allow intentional name collisions (#604)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-01 10:03:19 +08:00
Crypt Keeper
7fec94b2e1 experimental: consolidates context patterns (#579)
This consolidates the pattern used for context overrides, notably
replacing clock overrides via experimental.WithTimeNowUnixNano
and making all context keys internal.

This also makes sure experimental example tests are handled the same
way, notably backfilling one for WithFS
2022-05-26 18:22:29 -07:00
Teppei Fukuda
7794530d01 Allow passing fs.FS when calling functions (#571)
Fixes #563 

Signed-off-by: knqyf263 <knqyf263@gmail.com>
Co-authored-by: Adrian Cole <adrian@tetrate.io>
2022-05-20 10:51:17 +09:00
Anuraag Agrawal
b3fc76ed6e Adds assemblyscript host module and example (#569)
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Co-authored-by: Adrian Cole <adrian@tetrate.io>
2022-05-19 13:24:23 -06:00
Crypt Keeper
03bfa31928 Makes all examples and docs use Runtime.Close (#537)
This removes tedium in our examples and docs by using `Runtime.Close`
instead of tracking everything. Internal tests still track too much, but
anyway at least this stops suggesting others should do it.

This also changes our examples to use log.PanicXX so that the line
number goes into the console output.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-05-10 12:08:25 +08:00
Crypt Keeper
8f8c9ee205 Extracts CompileConfig and consolidates code. (#533)
This performs several changes to allow compilation config to be
centralized and scoped properly. The immediate effects are that we can
now process external types during `Runtime.CompileModule` instead of
doing so later during `Runtime.InstantiateModule`. Another nice side
effect is memory size problems can err at a source line instead of
having to be handled in several places.

There are some API effects to this, and to pay for them, some less used
APIs were removed. The "easy APIs" are left alone. For example, the APIs
to compile and instantiate a module from Go or Wasm in one step are left
alone.

Here are the changes, some of which are only for consistency. Rationale
is summarized in each point.
* ModuleBuilder.Build -> ModuleBuilder.Compile
  * The result of this is similar to `CompileModule`, and pairs better
    with `ModuleBuilder.Instantiate` which is like `InstantiateModule`.
* CompiledCode -> CompiledModule
  * We punted on this name, the result is more than just code. This is
    better I think and more consistent as it introduces less terms.
* Adds CompileConfig param to Runtime.CompileModule.
  * This holds existing features and will have future ones, such as
    mapping externtypes to uint64 for wasm that doesn't yet support it.
* Merges Runtime.InstantiateModuleWithConfig with Runtime.InstantiateModule
  * This allows us to explain APIs in terms of implicit or explicit
    compilation and config, vs implicit, kindof implicit, and explicit.
* Removes Runtime.InstantiateModuleFromCodeWithConfig
  * Similar to above, this API only saves the compilation step and also
    difficult to reason with from a name POV.
* RuntimeConfig.WithMemory(CapacityPages|LimitPages) -> CompileConfig.WithMemorySizer
  * This allows all error handling to be attached to the source line
  * This also allows someone to reduce unbounded memory while knowing
    what its minimum is.
* ModuleConfig.With(Import|ImportModule) -> CompileConfig.WithImportRenamer
  * This allows more types of import manipulation, also without
    conflating functions with globals.
* Adds api.ExternType
  * Needed for ImportRenamer and will be needed later for ExportRenamer.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-05-09 11:02:32 +08:00
Crypt Keeper
a47cb700ad examples: switches tinygo example to use slice header (#524)
We get undefined behavior, at least in code that re-slices, unless
capacity is set. This ensures the buffer under the string has a capacity
set to the same length as its size. This also shows more explicitly the
problems in TinyGo (ex some type mismatch you have to ignore until
fixed).

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-05-04 19:14:04 +08:00
Crypt Keeper
18da3f58aa updates to tinygo 0.23 (#522)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-05-03 10:24:54 +08:00
Crypt Keeper
a91140f7f7 Changes RuntimeConfig to an interface and exposes WithWasmCore2 (#518)
WebAssembly Core Working Draft 1 recently came out. Before that, we had
a toe-hold feature bucked called FinishedFeatures. This replaces
`RuntimeConfig.WithFinishedFeatures` with `RuntimeConfig.WithWasmCore2`.
This also adds `WithWasmCore1` for those who want to lock into 1.0
features as opposed to relying on defaults.

This also fixes some design debt where we hadn't finished migrating
public types that require constructor functions (NewXxx) to interfaces.
By using interfaces, we prevent people from accidentally initializing
key configuration directly (via &Xxx), causing nil field refs. This also
helps prevent confusion about how to use the type (ex pointer or not) as
there's only one way (as an interface).

See https://github.com/tetratelabs/wazero/issues/516

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-05-02 10:29:38 +08:00
Crypt Keeper
45ff2fe12f Propagates context to all api interface methods that aren't constant (#502)
This prepares for exposing operations like Memory.Grow while keeping the
ability to trace what did that, by adding a `context.Context` initial
parameter. This adds this to all API methods that mutate or return
mutated data.

Before, we made a change to trace functions and general lifecycle
commands, but we missed this part. Ex. We track functions, but can't
track what closed the module, changed memory or a mutable constant.
Changing to do this now is not only more consistent, but helps us
optimize at least the interpreter to help users identify otherwise
opaque code that can cause harm. This is critical before we add more
functions that can cause harm, such as Memory.Grow.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-25 08:13:18 +08:00
Crypt Keeper
98676fbc64 examples: polishes a few docs (#501)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-24 08:52:12 +08:00
Crypt Keeper
b7b90e7dfd Adds allocation examples in Rust and TinyGo (#475)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
Co-authored-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-04-21 18:22:22 +08:00
Crypt Keeper
cbd22d49d2 Switches TinyGo to build without debug (#492)
We don't currently read DWARF, and are checking in Wasm binaries to
source that include it. This changes the settings to not include that,
so that our git pull performance doesn't degrade over time.

Note: This keeps the name section, so our current panics will be able to
show the source functions same as before.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-21 15:34:05 +09:00
Crypt Keeper
45ccab589b Refactors API to ensure context propagation (#482)
This is an API breaking change that does a few things:

* Stop encouraging practice that can break context propagation:
  * Stops caching `context.Context` in `wazero.RuntimeConfig`
  * Stops caching `context.Context` in `api.Module`

* Fixes context propagation in function calls:
  * Changes `api.Function`'s arg0 from `api.Module` to `context.Context`
  * Adds `context.Context` parameter in instantiation (propagates to
    .start)

* Allows context propagation for heavy operations like compile:
  * Adds `context.Context` as the initial parameter of `CompileModule`

The design we had earlier was a good start, but this is the only way to
ensure coherence when users start correlating or tracing. While adding a
`context.Context` parameter may seem difficult, wazero is a low-level
library and WebAssembly is notoriously difficult to troubleshoot. In
other words, it will be easier to explain to users to pass (even nil) as
the context parameter vs try to figure out things without coherent
context.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-19 16:52:57 +08:00
Crypt Keeper
c4caa1ea9b Changes how examples are tested, and fixes ExitError bug (#468)
Before, we tested the examples/ directory using "ExampleXX", but this is
not ideal because it literally embeds the call to `main` into example
godoc output. This stops doing that for a different infrastructure.

This also makes sure there's a godoc example for both the main package
and wasi, so that people looking at https://pkg.go.dev see something and
also a link to our real examples directory.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-15 15:51:27 +08:00
Crypt Keeper
106f96b066 Adds import-go example (#466)
This shows how to define, export and import functions written in Go.

Fixes #464

Signed-off-by: Adrian Cole <adrian@tetrate.io>
Co-authored-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-04-15 09:31:52 +08:00
Takeshi Yoneda
bd328a3355 Add compilation cache functionality and Close on CompiledCode. (#457)
Thanks to #454, now the compiled binary (code segment) can be reused for
multiple module instances originating from the same source (wasm.Module).

This commit introduces the caching mechanism on engine where it caches
compiled functions keyed on `wasm.Module`. As a result, this allows us to
do the fast module instantiation from the same *CompiledCode.

In order to release the cache properly, this also adds `Close` method 
on CompiledCode.

Here's some bench result for instantiating multiple modules from the same CompiledCode:

```
name                           old time/op    new time/op    delta
Initialization/interpreter-32    2.84ms ± 3%    0.06ms ± 1%  -97.73%  (p=0.008 n=5+5)
Initialization/jit-32            10.7ms ±18%     0.1ms ± 1%  -99.52%  (p=0.008 n=5+5)

name                           old alloc/op   new alloc/op   delta
Initialization/interpreter-32    1.25MB ± 0%    0.15MB ± 0%  -88.41%  (p=0.008 n=5+5)
Initialization/jit-32            4.46MB ± 0%    0.15MB ± 0%  -96.69%  (p=0.008 n=5+5)

name                           old allocs/op  new allocs/op  delta
Initialization/interpreter-32     35.2k ± 0%      0.3k ± 0%  -99.29%  (p=0.008 n=5+5)
Initialization/jit-32             94.1k ± 0%      0.2k ± 0%  -99.74%  (p=0.008 n=5+5)
```


Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-04-14 11:33:10 +09:00
Crypt Keeper
dbf089b897 Fixes godoc links in example tests (#459)
thanks for noticing this @mathetake

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-14 08:38:52 +08:00
Crypt Keeper
958ce19c0b Makes examples runnable and pares down list (#458)
This deduplicates examples, leaving only the most maintained or targeted
ones. Notably, this makes each runnable, avoiding test dependencies.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-13 16:03:50 +08:00
Crypt Keeper
c3ff16d596 Supports functions with multiple results (multi-value) (#446)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-04-13 09:22:39 +08:00
Taction
9040fff0e1 fix typo in host func example (#449)
Signed-off-by: zhangchao <zchao9100@gmail.com>
2022-04-09 19:47:52 +09:00
Crypt Keeper
1527e019e9 Adds ModuleConfig.WithImport and WithImportModule (#444)
Before, complicated wasm could be hard to implement, particularly as it
might have cyclic imports. This change allows users to re-map imports to
untangle any cycles or to break up monolithic modules like "env".

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-06 18:28:37 +08:00
Taction
a05b291836 Close module correctly in host func example (#445)
Signed-off-by: zhangchao <zchao9100@gmail.com>
2022-04-06 19:15:26 +09:00
Crypt Keeper
2664b1eb62 Simplifies API per feedback (#427)
During #425, @neilalexander gave constructive feedback that the API is
both moving fast, and not good enough yet. This attempts to reduce the
incidental complexity at the cost of a little conflation.

### odd presence of `wasm` and `wasi` packages -> `api` package

We had public API packages in wasm and wasi, which helped us avoid
leaking too many internals as public. That these had names that look
like there should be implementations in them cause unnecessary
confusion. This squashes both into one package "api" which has no
package collission with anything.

We've long struggled with the poorly specified and non-uniformly
implemented WASI specification. Trying to bring visibility to its
constraints knowing they are routinely invalid taints our API for no
good reason. This removes all `WASI` commands for a default to invoke
the function `_start` if it exists. In doing so, there's only one path
to start a module.

Moreover, this puts all wasi code in a top-level package "wasi" as it
isn't re-imported by any internal types.

### Reuse of Module for pre and post instantiation to `Binary` -> `Module`

Module is defined by WebAssembly in many phases, from decoded to
instantiated. However, using the same noun in multiple packages is very
confusing. We at one point tried a name "DecodedModule" or
"InstantiatedModule", but this is a fools errand. By deviating slightly
from the spec we can make it unambiguous what a module is.

This make a result of compilation a `Binary`, retaining `Module` for an
instantiated one. In doing so, there's no longer any name conflicts
whatsoever.

### Confusion about config -> `ModuleConfig`

Also caused by splitting wasm into wasm+wasi is configuration. This
conflates both into the same type `ModuleConfig` as it is simpler than
trying to explain a "will never be finished" api of wasi snapshot-01 in
routine use of WebAssembly. In other words, this further moves WASI out
of the foreground as it has been nothing but burden.

```diff
--- a/README.md
+++ b/README.md
@@ -49,8 +49,8 @@ For example, here's how you can allow WebAssembly modules to read
-wm, err := r.InstantiateModule(wazero.WASISnapshotPreview1())
-defer wm.Close()
+wm, err := wasi.InstantiateSnapshotPreview1(r)
+defer wm.Close()

-sysConfig := wazero.NewSysConfig().WithFS(os.DirFS("/work/home"))
-module, err := wazero.StartWASICommandWithConfig(r, compiled, sysConfig)
+config := wazero.ModuleConfig().WithFS(os.DirFS("/work/home"))
+module, err := r.InstantiateModule(binary, config)
 defer module.Close()
 ...
```
2022-04-02 06:42:36 +08:00
Crypt Keeper
3c3df6b836 Updates to latest wabt and pares back to 1.0 (#430)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-01 15:09:37 +08:00
Crypt Keeper
000cbdeb54 wasi: replaces existing filesystem apis with fs.FS (#394)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-24 15:35:17 +08:00
Crypt Keeper
59617a24c8 wasi: renames WASIConfig to SysConfig and makes stdio defaults safer (#396)
This introduces `SysConfig` to replace `WASIConfig` and formalize documentation around system calls.

The only incompatible change planned after this is to switch from wasi.FS to fs.FS

Implementation Notes:

Defaulting to os.Stdin os.Stdout and os.Stderr doesn't make sense for
the same reasons as why we don't propagate ENV or ARGV: it violates
sand-boxing. Moreover, these are worse as they prevent concurrency and
can also lead to console overload if accidentally not overridden.

This also changes default stdin to read EOF as that is safer than reading
from os.DevNull, which can run the host out of file descriptors.

Finally, this removes "WithPreopens" for "WithFS" and "WithWorkDirFS",
to focus on the intended result. Similar Docker, if the WorkDir isn't set, it
defaults to the same as root.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-23 12:58:55 +08:00
Crypt Keeper
9a0f7f6bc6 wasi: moves system resource management to the importing module (#401)
The prior design had a problem, where multiple imports of WASI would end
up having different file descriptors for the same file. Moreover, there
was no means to close any of these when a module importing WASI was
closed.

This moves all existing functionality to a new type SystemContext, which
is owned by the importing module, similar to how it owns its memory.
While this PR doesn't fix some problems such as unclosed files, the code
is now organized in a way it can be, and these issues will be resolved
by #394.

In order to fix scope, `WASISnapshotPreview1WithConfig` had to be
removed.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-22 07:58:31 +08:00
Crypt Keeper
5b35bd9b66 Makes filesystem test simpler and removes use of panic in examples (#395)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-19 20:01:55 +08:00
Crypt Keeper
a8944f6098 Adds StartWASICommandWithConfig to defer configuration (#367)
StartWASICommandWithConfig is like StartWASICommand, except you can override configuration based on the importing
module. For example, you can use this to define different args depending on the importing module.

```go
// Initialize base configuration:
r := wazero.NewRuntime()
config := wazero.NewWASIConfig().WithStdout(buf)
wasi, _ := r.NewHostModule(wazero.WASISnapshotPreview1WithConfig(config))
decoded, _ := r.CompileModule(source)

// Assign configuration only when ready to instantiate.
module, _ := StartWASICommandWithConfig(r, decoded, config.WithArgs("rotate", "angle=90", "dir=cw"))
```

This also changes the config to be immutable since it may be reused many
times. Instead of assigning fields directly, use `WithXXX`.

Finally, this changes the examples to encourage using `.Close()`

Fixes #364

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-14 14:39:53 +08:00
Crypt Keeper
50d9fa58a1 Runtime.NewModule -> InstantiateModule and adds ModuleBuilder (#349)
This reverts `Runtime.NewModule` back to `InstantiateModule` as it calls
more attention to the registration aspect of it, and also makes a chain
of `NewXX` more clear. This is particularly helpful as this change
introduces `ModuleBuilder` which is created by `NewModuleBuilder`.

`ModuleBuilder` is a way to define a WebAssembly 1.0 (20191205) in Go.
The first iteration allows setting the module name and exported
functions. The next PR will add globals.

Ex. Below defines and instantiates a module named "env" with one function:

```go
hello := func() {
	fmt.Fprintln(stdout, "hello!")
}
_, err := r.NewModuleBuilder("env").ExportFunction("hello", hello).InstantiateModule()
```

If the same module may be instantiated multiple times, it is more efficient to separate steps. Ex.

```go
env, err := r.NewModuleBuilder("env").ExportFunction("get_random_string", getRandomString).Build()

_, err := r.InstantiateModule(env.WithName("env.1"))
_, err := r.InstantiateModule(env.WithName("env.2"))
```

Note: Builder methods do not return errors, to allow chaining. Any validation errors are deferred until Build.
Note: Insertion order is not retained. Anything defined by this builder is sorted lexicographically on Build.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-09 10:39:13 +08:00
Crypt Keeper
1e4834612a Removes host-specific types (#347)
This converges host-defined modules with Wasm defined modules by
introducing a custom section for host-defined functions. The net result
are far less types and consistent initialization.

* HostModule is removed for Module
* HostFunction is removed for Function
* ModuleContext is removed for Module

Note: One impact of this is that the low-level API no longer accepts a
go context (context.Context), rather a `wasm.Module` which the function
is called in context of. This meant exposing `wasm.Module.WithContext`
to override the default.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-08 16:43:13 +08:00
Takeshi Yoneda
e8406de84a Simplify host_call example (#314)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-03-03 15:32:48 +09:00
Takeshi Yoneda
490f830096 jit(arm64): restore callee-saved registers on exits from native code (#311)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-03-02 20:51:05 +09:00