Commit Graph

22 Commits

Author SHA1 Message Date
Thomas Pelletier
0bfb4b52eb Give Listener a read-only view of globals (#1404)
* experimental: give listener r/o view of globals

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* experimental: add global support to interpreter

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* exp: replace globals proxy with module interface

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* exp: trim down experimental.InternalModule

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* Replace globals view slice with constantGlobal

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* Fix tests after merge

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* Address PR feedback

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* Rename methods of experimental.Module

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* Run make check

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

* Add WazeroOnlyType to constantGlobal

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>

---------

Signed-off-by: Thomas Pelletier <thomas@pelletier.codes>
2023-04-29 00:07:28 -07:00
Takeshi Yoneda
cd1110c088 Avoids allocation of exports map per instance (#1275)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-03-23 16:37:56 +09:00
Takeshi Yoneda
7466f0e7bd Holds most fields as slice of values, not ptrs in wasm.Module (#1221)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-03-13 12:50:36 +09:00
Takeshi Yoneda
24e4d5dfa0 Generates typeIDs at compilation time (#1218)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-03-10 13:46:08 +09:00
Takeshi Yoneda
b63d4e6dcd Deletes namespace API (#1018)
Formerly, we introduced `wazero.Namespace` to help avoid module name or import conflicts while still sharing the runtime's compilation cache. Now that we've introduced `CompilationCache` `wazero.Namespace` is no longer necessary. By removing it, we reduce the conceptual load on end users as well internal complexity. Since most users don't use namespace, the change isn't very impactful.

Users who are only trying to avoid module name conflict can generate a name like below instead of using multiple runtimes:

```go
moduleName := fmt.Sprintf("%d", atomic.AddUint64(&m.instanceCounter, 1))
module, err := runtime.InstantiateModule(ctx, compiled, config.WithName(moduleName))
```

For `HostModuleBuilder` users, we no longer take `Namespace` as the last parameter of `Instantiate` method: 

```diff
 	// log to the console.
 	_, err := r.NewHostModuleBuilder("env").
 		NewFunctionBuilder().WithFunc(logString).Export("log").
-		Instantiate(ctx, r)
+		Instantiate(ctx)
 	if err != nil {
 		log.Panicln(err)
 	}
```


The following is an example diff a use of namespace can use to keep compilation cache while also ensuring their modules don't conflict:

```diff

 func useMultipleRuntimes(ctx context.Context, cache) {
-	r := wazero.NewRuntime(ctx)
+	cache := wazero.NewCompilationCache()
 
 	for i := 0; i < N; i++ {
-		// Create a new namespace to instantiate modules into.
-		ns := r.NewNamespace(ctx) // Note: this is closed when the Runtime is
+		r := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCompilationCache(cache))
 
 		// Instantiate a new "env" module which exports a stateful function.
 		_, err := r.NewHostModuleBuilder("env").
```

Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-01-10 14:11:46 +09:00
Crypt Keeper
126bd9050d Removes context parameter from instruction-scoped operations (#923)
We originally had a `context.Context` for anything that might be
traced, but it turned out to be only useful for lifecycle and host functions.

For instruction-scoped aspects like memory updates, a context parameter is too
fine-grained and also invisible in practice. For example, most users will use
the compiler engine, and its memory, global or table access will never use go's
context.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-12-14 16:08:07 +09:00
Takeshi Yoneda
8339045657 Ensures listeners only bound to compile time objects (#870)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-11-29 17:25:59 +09:00
Crypt Keeper
329ccca6b1 Switches from gofmt to gofumpt (#848)
This switches to gofumpt and applies changes, as I've noticed working
in dapr (who uses this) that it finds some things that are annoying,
such as inconsistent block formatting in test tables.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-11-09 05:48:24 +01: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
Anuraag Agrawal
633fc41706 experimental: FunctionListenerFactory can decide whether to intercept function start/finish (#505)
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-26 15:28:17 +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
Takeshi Yoneda
e3035b5a76 binary: complete encoder (#463)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-04-14 16:55:53 +09:00
Crypt Keeper
ce1052a097 Isolates testify to one file, so that it is easier to remove (#460)
This starts the process of removing all dependencies from wazero, by
isolating all assertions we use into a single file. This allows us to
port those assertions as we have time, and when twitchy is gone, the
project literally has no dependencies except go!

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-14 10:05:38 +08:00
Crypt Keeper
fb0b311844 Consistently uses LEB128 signed encoding for global constants (#443)
Global constants can be defined in wasm or in ModuleBuilder. In either
case, they end up being decoded and interpreted during instantiation.
This chooses signed encoding to avoid surprises. A more comprehensive
explanation was added to RATIONALE.md, but the motivation was a global
100 coming out negative.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-06 09:50:47 +08:00
Crypt Keeper
f5598c9a8e Fixes global numeric types to have max of signed encoding (#442)
This adjusts towards the exiting code which used int32/64 instead of
uint32/64. The reason is that the spec indicates intepretation as signed
numbers, which affects the maximum value.

See https://www.w3.org/TR/wasm-core-1/#value-types%E2%91%A2

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-06 06:35:31 +08: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
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
91444c7af9 Propagates module name to module engine panic nicer (#374)
Before, if there was an unexpected panic on munmap of a code section,
we'd only see "invalid argument" and have to guess why. This propagates
context and stubs out the finalizer so we can test a better error, like:

"jit: failed to munmap code segment for test.function[0]: invalid argument"

This also attempts to improve troubleshooting time by making all module
instantiation that used empty module name, use the test name instead.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-15 16:17:10 +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
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
Crypt Keeper
cfb11f352a Adds ability to disable mutable globals and improves decode perf (#315)
This adds `RuntimeConfig.WithFeatureMutableGlobal(enabled bool)`, which
allows disabling of mutable globals. When disabled, any attempt to add a
mutable global, either explicitly or implicitly via decoding wasm will
fail.

To support this, there's a new `Features` bitflag that can allow up to
63 feature toggles without passing structs.

While here, I fixed a significant performance problem in decoding
binary:

Before
```
BenchmarkCodecExample/binary.DecodeModule-16         	  184243	      5623 ns/op	    3848 B/op	     184 allocs/op
```

Now
```
BenchmarkCodecExample/binary.DecodeModule-16         	  294084	      3520 ns/op	    2176 B/op	      91 allocs/op

```

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-03 10:31:10 +08:00
Crypt Keeper
c0e6313ab6 Adds Global API and implements for module-defined globals (#310)
Global is a WebAssembly 1.0 (20191205) global exported from an
instantiated module (wazero.Runtime NewModule).

Ex. If the value is not mutable, you can read it once:
```go
offset := module.Global("memory.offset").Get()
```

Globals are allowed by specification to be mutable. However, this can
be disabled by configuration. When in doubt, safe cast to find out if
the value can change.

Ex.
```go
offset := module.Global("memory.offset")
if _, ok := offset.(wasm.MutableGlobal); ok {
	value can change
} else {
	value is constant
}
```

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#globals%E2%91%A0

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-02 17:40:43 +08:00