Commit Graph

57 Commits

Author SHA1 Message Date
Takeshi Yoneda
69c78f9b77 Prevents direct use of host functions via ExportedFunction (#2259)
Signed-off-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
2024-06-20 09:35:22 -07:00
Takeshi Yoneda
a3d0d967ab Cleanups ctxkey package (#2184)
Signed-off-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
2024-04-15 14:55:14 +09:00
Nuno Cruces
c6a907bb9d experimental: cleanup context keys (#2175)
Signed-off-by: Nuno Cruces <ncruces@users.noreply.github.com>
2024-04-06 21:04:55 +09:00
Takeshi Yoneda
a6ef3c7524 Changes ModuleID for listener existence per function (#1742)
Signed-off-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
2023-10-02 10:12:59 +09:00
Nuno Cruces
1bd9a3c17b Use atomic.Uint64. (#1620)
Signed-off-by: Nuno Cruces <ncruces@users.noreply.github.com>
2023-08-09 14:09:54 +01:00
Crypt Keeper
0300f4b3c1 experimental: adds close notification hook (#1574)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-07-11 09:27:43 +08:00
Crypt Keeper
326c267726 Exposes Module.IsClosed to prevent calling functions when closed (#1573)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
Co-authored-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-07-10 15:32:51 +08:00
Crypt Keeper
2b35d93612 explicitly documents ModuleConfig defaults to _start (#1568)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-07-07 14:17:55 +08:00
Edoardo Vacchi
97d0d70b73 wasi: add support for sockets (#1493)
Some checks failed
Release CLI / Pre-release build (push) Has been cancelled
Release CLI / Pre-release test (macos-12) (push) Has been cancelled
Release CLI / Pre-release test (ubuntu-22.04) (push) Has been cancelled
Release CLI / Pre-release test (windows-2022) (push) Has been cancelled
Release CLI / Release (push) Has been cancelled
Signed-off-by: Edoardo Vacchi <evacchi@users.noreply.github.com>
Signed-off-by: Adrian Cole <adrian@tetrate.io>
Co-authored-by: Crypt Keeper <64215+codefromthecrypt@users.noreply.github.com>
Co-authored-by: Achille <achille.roussel@gmail.com>
Co-authored-by: Adrian Cole <adrian@tetrate.io>
2023-06-02 20:45:42 +08:00
Takeshi Yoneda
80452a94c3 Bulk lazy initialization of FunctionDefinitions (#1425)
Signed-off-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
Co-authored-by: Edoardo Vacchi <evacchi@users.noreply.github.com>
2023-05-12 08:02:40 +10:00
Achille
daad2fdb66 experimental: add FunctionListener and FunctionListenerFactory implementations (#1444)
Signed-off-by: Achille Roussel <achille.roussel@gmail.com>
2023-05-09 17:03:08 +08:00
Crypt Keeper
999176e279 godoc: moves sealed type notes to the top and backfills where missing (#1397)
wazero uses interfaces even when they aren't intended to be implemented
by users. We relied on documentation, to suggest what is implementable,
and in some cases documented correctly types that weren't for
implementation.

However, we didn't add that boilerplate to all types, and we also forgot
to recently when it was discussed a week or two ago. This finishes the
job by boilerplating all types that aren't for implementation. This also
orders to the top when it already existed.

Later, we can choose to enforce by type as well, we didn't know how to
do that before. Basically before we just casted to our internal types,
which would stop accidental implementation for things except people
using the types for wrapping purposes.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-04-24 18:44:11 +08:00
Takeshi Yoneda
d33ecd0e3a cache: fixes consistency with CloseOnContextDone and listeners (#1381)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-04-19 15:00:46 +09:00
Crypt Keeper
df0faa5d16 emscripten: adds experimental InstantiateForModule for invoke exports (#1372)
This adds emscripten.InstantiateForModule into the experimental package.
This builds dynamic invoke exports in the same order and only matching
those needed by the importing modules.

Finally, this removes special casing of function type IDs by deferring
resolution of them only in Emscripten.

Fixes #1364

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-04-18 09:13:50 +02:00
Takeshi Yoneda
a4226906cf Deletes wasm.CallCtx (#1280)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-03-24 17:00:43 -07:00
Crypt Keeper
22f8d9da69 fixes nil panic on close (#1286)
Some checks failed
Release CLI / Pre-release build (push) Has been cancelled
Release CLI / Pre-release test (macos-12) (push) Has been cancelled
Release CLI / Pre-release test (ubuntu-22.04) (push) Has been cancelled
Release CLI / Pre-release test (windows-2022) (push) Has been cancelled
Release CLI / Release (push) Has been cancelled
The last PR over-solved the WASI close problem as it special cased both
"_start", used by WASI, and the start section (wasm level) which isn't
used by WASI. In the latter case, we ended up returning nil for both the
module *and* the error result. We should never do that.. If we coerce
exit error zero to nil, we have to return a non-nil module, even if it
is unusable as otherwise code like `defer mod.Close(ctx)` will panic.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-03-24 18:46:43 +01:00
Crypt Keeper
451c792ee8 Avoids returning ExitError on exit code zero, and optimizes for no allocations (#1284)
Fixes #1283

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-03-24 16:42:30 +01:00
Crypt Keeper
53bb95eeaa Allow ModuleConfig.WithName("") to clear the module name (#1277)
We currently allow clearing other config with nil, such as FSConfig.
However, we missed a spot as internally we couldn't differentiate
between name never set, or explicitly set to empty. Now, when someone
sets the module name to empty, the name in the binary section is
ignored.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-03-23 16:53:14 +09:00
Takeshi Yoneda
cd05a22df2 Reduces allocations during instantiation (#1267)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-03-22 18:55:58 +09:00
Takeshi Yoneda
8ab1615b53 Forbids empty name module imports (#1244)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
Co-authored-by: Crypt Keeper <64215+codefromthecrypt@users.noreply.github.com>
2023-03-16 12:22:37 +09:00
Takeshi Yoneda
e42987a17a Holds memory/func defs, and validated elements as values in wasm.Module (#1224)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-03-13 14:52:01 +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
9c07b2793d Allows to set the version of CLI (#1176)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-02-28 18:09:41 +09:00
Dmitry Volodin
7122c9b7ef Removes redundant Magic validation in runtime (#1137)
Signed-off-by: Dmitry Volodin <dmvolod@gmail.com>
2023-02-20 15:31:33 +09:00
Crypt Keeper
b758344212 API BREAK: renames InstantiateModuleFromBinary to Instantiate (#1129)
This renames `InstantiateModuleFromBinary` to `Instantiate` to both make
first time use simpler to write and also de-complicate adding a
`WithConfig` variant as requested in #1105

End users in simple case need to change their signature like so.
```diff
-       mod, err := r.InstantiateModuleFromBinary(ctx, addWasm)
+       mod, err := r.Instantiate(ctx, addWasm)
```

In practice, many will not need to change their signature because they
had to use the `InstantiateModule` function in order to assign
configuration such as the module name, filesystem or use a real clock.
Instead, they had to use the more complicated chain of `CompileModule`
and `InstantiateModule` even when only assigning config. Users in this
situation can opt into the more simplified syntax below:

```go
mod, err := r.InstantiateWithConfig(ctx, addWasm,
	wazero.NewModuleConfig().WithName("adder"))
```



```diff
-       mod, err := r.InstantiateModuleFromBinary(ctx, addWasm)
+       mod, err := r.Instantiate(ctx, addWasm)
```

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2023-02-15 14:52:17 -10:00
Takeshi Yoneda
92e0a488b6 Support context Cancelation/Timeout in function executions (#1108)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-02-10 09:39:04 +09:00
Edoardo Vacchi
39983c4080 fix: should not panic when a module is instantiated with a closed runtime (#1089)
fixes #1088

Signed-off-by: Edoardo Vacchi <evacchi@users.noreply.github.com>
2023-02-08 10:45:52 -05:00
Edoardo Vacchi
d07c40f5d6 CompiledModule: export Custom Sections (#1048)
Signed-off-by: Edoardo Vacchi <evacchi@users.noreply.github.com>
Co-authored-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
2023-01-19 21:39:43 +09:00
Takeshi Yoneda
803e6ba61e Separate interpreter and engine per wazero.cache impl (#1022)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-01-11 11:59:28 +09:00
Takeshi Yoneda
e216466331 Fixes race on engine creation with Cache API (#1021)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2023-01-11 09:46:55 +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
Takeshi Yoneda
35500f9b85 Introduces Cache API (#1016)
This introduces the new API wazero.Cache interface which can be passed to wazero.RuntimeConfig. 
Users can configure this to share the underlying compilation cache across multiple wazero.Runtime. 
And along the way, this deletes the experimental file cache API as it's replaced by this new API.

Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
Co-authored-by: Crypt Keeper <64215+codefromthecrypt@users.noreply.github.com>
2023-01-10 09:32:42 +09:00
Crypt Keeper
5f7467b3e0 Enables debug info (a.k.a. DWARF) by default (#924)
This makes DWARF enabled by default, with an opt-out flag. This didn't
need to be experimental as the feature was requested for a long time and
there's no API impact to using it.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-12-15 14:03:20 +09:00
Takeshi Yoneda
6c4dd1cfd9 Adds support for DWARF based stack traces (#881)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-12-05 14:59:45 +09:00
Takeshi Yoneda
40e698e068 binary: adds custom section decoder (#877)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-12-01 20:08:40 +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
Takeshi Yoneda
84d733eb0a compiler: adds support for FunctionListeners (#869)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-11-29 15:15:49 +09:00
Crypt Keeper
d108ce4c43 Restores ability to define host functions w/o context via reflection (#832)
This restores the ability to leave out the initial context parameter
when defining functions with reflection. This is important because some
projects are porting from a different library to wazero, and all the
alternatives are not contextualized.

For example, this project is porting envoy host functions, and the
original definitions (in mosn) don't have a context parameter. By being
lenient, they can migrate easier.

See 6b813482b6/pkg/proxywasm/wazero/imports_v1.go

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-10-28 12:44:12 -07:00
Crypt Keeper
be33572289 Adds HostFunctionBuilder to enable high performance host functions (#828)
This PR follows @hafeidejiangyou advice to not only enable end users to
avoid reflection when calling host functions, but also use that approach
ourselves internally. The performance results are staggering and will be
noticable in high performance applications.

Before
```
BenchmarkHostCall/Call
BenchmarkHostCall/Call-16            	 1000000	      1050 ns/op
Benchmark_EnvironGet/environGet
Benchmark_EnvironGet/environGet-16         	  525492	      2224 ns/op
```

Now
```
BenchmarkHostCall/Call
BenchmarkHostCall/Call-16            	14807203	        83.22 ns/op
Benchmark_EnvironGet/environGet
Benchmark_EnvironGet/environGet-16         	  951690	      1054 ns/op
```

To accomplish this, this PR consolidates code around host function
definition and enables a fast path for functions where the user takes
responsibility for defining its WebAssembly mappings. Existing users
will need to change their code a bit, as signatures have changed.

For example, we are now more strict that all host functions require a
context parameter zero. Also, we've replaced
`HostModuleBuilder.ExportFunction` and `ExportFunctions` with a new type
`HostFunctionBuilder` that consolidates the responsibility and the
documentation.

```diff
 ctx := context.Background()
-hello := func() {
+hello := func(context.Context) {
         fmt.Fprintln(stdout, "hello!")
 }
-_, err := r.NewHostModuleBuilder("env").ExportFunction("hello", hello).Instantiate(ctx, r)
+_, err := r.NewHostModuleBuilder("env").
+        NewFunctionBuilder().WithFunc(hello).Export("hello").
+        Instantiate(ctx, r)
```

Power users can now use `HostFunctionBuilder` to define functions that
won't use reflection. There are two choices of interfaces to use
depending on if that function needs access to the calling module or not:
`api.GoFunction` and `api.GoModuleFunction`. Here's an example defining
one.

```go
builder.WithGoFunction(api.GoFunc(func(ctx context.Context, params []uint64) []uint64 {
	x, y := uint32(params[0]), uint32(params[1])
	sum := x + y
	return []uint64{sum}
}, []api.ValueType{api.ValueTypeI32, api.ValueTypeI32}, []api.ValueType{api.ValueTypeI32})
```
As you'll notice and as documented, this approach is more verbose and
not for everyone. If you aren't making a low-level library, you are
likely able to afford the 1us penalty for the convenience of reflection.
However, we are happy to enable this option for foundational libraries
and those with high performance requirements (like ourselves)!

Fixes #825

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-10-28 07:51:08 -07:00
Crypt Keeper
1cbb496c26 Stops using "ex." to abbreviate "for example" (#827)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-10-24 11:51:48 +09:00
Crypt Keeper
9a623c4f88 Adds MemoryDefinition to CompiledModule and Memory (#817)
It is more often the case that projects are enabling a freestanding
target, and that may or may not have an exporting memory depending on
how that's interpreted. This adds the ability to inspect memories
similar to how you can already inspect compiled code prior to
instantiation. For example, you can enforce an ABI constraint that
"memory" must be exported even if WASI is not in use.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-09-29 13:37:52 +08:00
Crypt Keeper
761347db1e Replaces MemorySizer and CompileConfig with RuntimeConfig (#815)
We formerly introduced `MemorySizer` as a way to control capacity independently of size. This was the first and only feature in `CompileConfig`. While possibly used privately, `MemorySizer` has never been used in public GitHub code.

These APIs interfere with how we do caching of compiled modules. Notably, they can change the min or max defined in wasm, which invalidates some constants. This has also had a bad experience, forcing everyone to boilerplate`wazero.NewCompileConfig()` despite that API never being used in open source.

This addresses the use cases in a different way, by moving configuration to `RuntimeConfig` instead. This allows us to remove `MemorySizer` and `CompileConfig`, and the problems with them, yet still retaining functionality in case someone uses it.

* `RuntimeConfig.WithMemoryLimitPages(uint32)`: Prevents memory from growing to 4GB (spec limit) per instance.
  * This works regardless of whether the wasm encodes max or not. If there is no max, it becomes effectively this value.
* `RuntimeConfig.WithMemoryCapacityFromMax(bool)`: Prevents reallocations (when growing).
  * Wasm that never sets max will grow from min to the limit above.

Note: Those who want to change their wasm (ex insert a max where there was none), have to do that externally, ex via compiler settings or post-build transformations such as [wabin](https://github.com/tetratelabs/wabin)

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-09-29 08:03:03 +08:00
Crypt Keeper
429334cf98 Renames ModuleBuilder to HostModuleBuilder and drops memory and globals (#812)
We at one point considered making `ModuleBuilder` create complete
WebAssembly binaries. However, we recently spun out
[wabin](https://github.com/tetratelabs/wabin), which allows this.

Meanwhile, the features in `ModuleBuilder` were confusing and misused.
For example, the only two cases memory was exported on GitHub were done
by accident. This is because host functions act on the guest's memory,
not their own.

Hence, this removes memory and globals from host side definitions, and
renames the type to HostModuleBuilder to clarify this is not ever going
to be used to construct normal Wasm binaries.

Most importantly, this simplifies the API and reduces a lot of code. It
is important to make changes like this, particularly deleting any
experimental things that didn't end up useful.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
Co-authored-by: Anuraag Agrawal <anuraaga@gmail.com>
2022-09-28 14:42:14 +08:00
Crypt Keeper
b01effc8a9 Top-levels CoreFeatures and defaults to 2.0 (#800)
While compilers should be conservative when targeting WebAssembly Core
features, runtimes should be lenient as otherwise people need to
constantly turn on all features. Currently, most examples have to turn
on 2.0 features because compilers such as AssemblyScript and TinyGo use
them by default. This matches the policy with the reality, and should
make first time use easier.

This top-levels an internal type as `api.CoreFeatures` and defaults to
2.0 as opposed to 1.0, our previous default. This is less cluttered than
the excess of `WithXXX` methods we had prior to implementing all
planned WebAssembly Core Specification 1.0 features.

Finally, this backfills rationale as flat config types were a distinct
decision even if feature set selection muddied the topic.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-09-06 15:14:36 +08:00
Crypt Keeper
57a705e594 Disallows nil context and fixes linters (#754)
staticcheck linters broke until recent golangci-lint. Now, normal
behaviour of enforcing no nil context works again. Ex.
```
assemblyscript/assemblyscript_example_test.go:16:25: SA1012: do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use (staticcheck)
	r := wazero.NewRuntime(nil)
```

Since default lint already checks for nil context, this removes our
permission of nil context args. The original reason we permitted nil is
no longer valid: we once allowed context to be stashed in config, and
removed that as it caused bugs. We forgot to undo allowing nil
explicitly.

Note: this doesn't particularly check in our code for nil context,
similar as we don't particularly check in our code for nil anything
else. End users should use linters as none of our parameters should be
nil anyway.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-08-19 14:52:50 +08:00
Anuraag Agrawal
b93fd89637 Accept nil ctx in NewRuntime (#752)
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
2022-08-19 12:35:15 +09:00
Takeshi Yoneda
3b32c2028b Externalize compilation cache by compilers (#747)
This adds the experimental support of the file system compilation cache.
Notably, experimental.WithCompilationCacheDirName allows users to configure
where the compiler writes the cache into.

Versioning/validation of binary compatibility has been done via the release tag
(which will be created from the end of this month). More specifically, the cache
file starts with a header with the hardcoded wazero version.


Fixes #618

Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
Co-authored-by: Crypt Keeper <64215+codefromthecrypt@users.noreply.github.com>
2022-08-18 19:37:11 +09:00
Takeshi Yoneda
076d3245e3 Pass context into NewRuntime (#748)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-08-18 14:47:49 +09:00
Crypt Keeper
939403c10b Makes it possible to implement FunctionListener and Factory (#716)
This simplifies FunctionListener definition by making it possible to
implement both interfaces without intermediate state. Passing the
function definition to the before/after callbacks is the key.

This also continues efforts towards Go 1.19 doc formatting.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-07-25 12:53:41 +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