Commit Graph

31 Commits

Author SHA1 Message Date
Takeshi Yoneda
4aa3c39da2 Removes unnecessary mutex on Table/Memory Instance (#1755)
Signed-off-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
2023-10-05 08:57:09 +09:00
Anuraag Agrawal
714368bcea Remove threads support (#1487)
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
2023-05-22 12:18:36 +10:00
Anuraag Agrawal
bc96257575 Implement WebAssembly threads proposal with interpreter (#1460)
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
2023-05-16 12:22:17 +08:00
Nuno Cruces
4ceef7b245 memory: avoid integer overflow (#1459)
Signed-off-by: Nuno Cruces <ncruces@users.noreply.github.com>
2023-05-12 14:53:00 +08:00
Nuno Cruces
197facf7a9 Close certain api interfaces for external implementation (#1396)
This adds a new type `internalapi.WazeroOnly` which should be embedded on types users are likely to accidentally implement despite docs saying otherwise.

Signed-off-by: Nuno Cruces <ncruces@users.noreply.github.com>
2023-04-28 15:32:32 +08: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
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
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
Anuraag Agrawal
0b4dbfd8d6 Add Memory.WriteString (#820)
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
2022-10-03 10:26:36 +02: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
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
Crypt Keeper
30be6a8e2a wasi: Implements wasi_snapshot_preview1.poll_oneoff for relative clock events (#629)
This implements wasi_snapshot_preview1.poll_oneoff for relative clock events,
and in doing so stubs `Nanosleep` which defaults to noop, but can be configured
to `time.Sleep`.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-17 16:48:35 +08:00
Crypt Keeper
fd3834442b Replaces Memory.IndexByte with stronger documentation on Read (#622)
Memory.IndexByte is unneeded with better understanding of write-through
on Memory.Read. Removing this also helps usher folks into the myriad of
Go utilities that are compatable with []byte.

This also reduces the complexity of WASI which didn't need to re-buffer
random reads (also due to above).

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-05 19:50:01 +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
96bc7c8462 Exposes api.Memory Grow (#535)
This exports an API which allows host-defined functions access to
increase the memory size.

Fixes #483

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-05-09 14:56:50 +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
0561190cb9 Documents Memory.Read as a way to share memory between Go and Wasm (#527)
By testing the side-effects of Memory.Read, we ensure users who control
the underlying memory capacity can use the returned slice for
write-through access to Wasm addressible memory. Notably, this allows a
shared fixed length data structure to exist with a pointer on the Go
side and a memory offset on the Wasm side.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
Co-authored-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-05-06 09:56:40 +08:00
inkeliz
7f1dab1988 Fix bytes capacity on Read (#528)
Before that change it was possible to overwrite content out of specified range.

Signed-off-by: Inkeliz <inkeliz@inkeliz.com>
2022-05-06 06:55:39 +08:00
Crypt Keeper
2c03098dba Adds Runtime.WithCapacityPages to avoid allocations during runtime. (#514)
`Runtime.WithMemoryCapacityPages` is a function that determines memory
capacity in pages (65536 bytes per page). The inputs are the min and
possibly nil max defined by the module, and the default is to return
the min.

Ex. To set capacity to max when exists:
```golang
c.WithMemoryCapacityPages(func(minPages uint32, maxPages *uint32) uint32 {
	if maxPages != nil {
		return *maxPages
	}
	return minPages
})
```

Note: This applies at compile time, ModuleBuilder.Build or Runtime.CompileModule.

Fixes #500

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-29 17:54:48 +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
d238a004a8 Adds Memory.IndexByte and memory grow example (#489)
This adds Memory.IndexByte which allows efficent scanning for a
delimiter, ex NUL(0) in null-terminated strings.

This also adds an ad-hoc test to ensure we can export memory functions
such as grow. While this is implicitly in the spectests, it is easier to
find in the ad-hoc tests.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-20 20:33:15 +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
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
8f461f6f12 Makes memory limit configurable and a compile error (#419)
This allows users to reduce the memory limit per module below 4 Gi. This
is often needed because Wasm routinely leaves off the max, which implies
spec max (4 Gi). This uses Ki Gi etc in error messages because the spec
chooses to, though we can change to make it less awkward.

This also fixes an issue where we instantiated an engine inside config.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-31 08:57:28 +08:00
Takaya Saeki
a9c1ee806e Fix overflow on MemoryInstance.hasSize (#369)
Signed-off-by: Takaya Saeki <takaya@tetrate.io>
2022-03-14 19:50:40 +09:00
Crypt Keeper
f9ba190c36 cleanups before table element init redo (#361)
Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-03-11 16:45:26 +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
759e820f77 Make store's fields private (#319)
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-03-03 17:18:05 +09:00
Crypt Keeper
119144ece8 Stops proliferation of MVP jargon (#295)
MVP was a term used by WebAssembly insiders when ramping up to the 1.0
spec. While these folks still use that term it is confusing and
unnecessary way to qualify a W3C version. Here are some of the problems:

* MVP does not match a W3C published URL
* MVP does not match a git tag on the spec repo
* MVP was a work in progress, so there are text that say "not in MVP"
  which ended up in 1.0 (as MVP became more than it was).
* MVP is jargon to people who don't know that stands for Minimum Viable Product.

This stops this practice and instead uses the W3C 1.0 Draft version
instead: 20191205

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-02-25 09:34:05 +08:00
Crypt Keeper
70118ab158 Adds Memory.ReadByte and WriteByte (#289)
This adds functions to read or write a single byte from memory. This can
eventually be used by wasi `FdPrestatGet`, once implemented, to verify
the tag without also needing read padding. It can also be used by host
functions who want to share flags with other host functions for other
reasons, such as state transitions.

This also carves in benchmarks for future optimizations:

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-02-24 14:02:50 +08:00