Commit Graph

44 Commits

Author SHA1 Message Date
Pat Hickey
22433ed726 wiggle: new error configuration for generating a "trappable error" (#5276)
* Add a new "trappable" mode for wiggle to make an error type

start refactoring how errors are generated and configured

put a pin in this - you can now configure a generated error

but i need to go fix Names

Names is no longer a struct, rt is hardcoded to wiggle

rest of fixes to pass tests

its called a trappable error now

don't generate UserErrorConversion trait if empty

mention in macro docs

* undo omitting the user error conversion trait when empty
2022-11-16 10:54:41 -06:00
Andrew Brown
060f12571d wiggle: adapt Wiggle strings for shared use (#5264)
* wiggle: adapt Wiggle strings for shared use

This is an extension of #5229 for the `&str` and `&mut str` types. As
documented there, we are attempting to maintain Rust guarantees for
slices that Wiggle hands out in the presence of WebAssembly shared
memory, in which case multiple threads could be modifying the underlying
data of the slice.

This change changes the API of `GuestPtr` to return an `Option` which is
`None` when attempting to view the WebAssembly data as a string and the
underlying WebAssembly memory is shared. This reuses the
`UnsafeGuestSlice` structure from #5229 to do so and appropriately marks
the region as borrowed in Wiggle's manual borrow checker. Each original
call site in this project's WASI implementations is fixed up to `expect`
that a non-shared memory is used.  (Note that I can find no uses of
`GuestStrMut` in the WASI implementations).

* wiggle: make `GuestStr*` containers wrappers of `GuestSlice*`

This change makes it possible to reuse the underlying logic in
`UnsafeGuestSlice` and the `GuestSlice*` implementations to continue to
expose the `GuestStr` and `GuestStrMut` types. These types now are
simple wrappers of their `GuestSlice*` variant. The UTF-8 validation
that distinguished `GuestStr*` now lives in the `TryFrom`
implementations for each type.
2022-11-14 22:33:24 +00:00
Andrew Brown
7717d8fa55 wiggle: adapt Wiggle guest slices for unsafe shared use (#5229)
* wiggle: adapt Wiggle guest slices for `unsafe` shared use

When multiple threads can concurrently modify a WebAssembly shared
memory, the underlying data for a Wiggle `GuestSlice` and
`GuestSliceMut` could change due to access from other threads. This
breaks Rust guarantees when `&[T]` and `&mut [T]` slices are handed out.
This change modifies `GuestPtr` to make `as_slice` and `as_slice_mut`
return an `Option` which is `None` when the underlying WebAssembly
memory is shared.

But WASI implementations still need access to the underlying WebAssembly
memory, both to read to it and write from it. This change adds new APIs:
- `GuestPtr::to_vec` copies the  bytes from WebAssembly memory (from
  which we can safely take a `&[T]`)
- `GuestPtr::as_unsafe_slice_mut` returns a wrapper `struct` from which
  we can  `unsafe`-ly return a mutable slice (users must accept the
  unsafety of concurrently modifying a `&mut [T]`)

This approach allows us to maintain Wiggle's borrow-checking
infrastructure, which enforces the guarantee that Wiggle will not modify
overlapping regions, e.g. This is important because the underlying
system calls may expect this. Though other threads may modify the same
underlying region, this is impossible to prevent; at least Wiggle will
not be able to do so.

Finally, the changes to Wiggle's API are propagated to all WASI
implementations in Wasmtime. For now, code locations that attempt to get
a guest slice will panic if the underlying memory is shared. Note that
Wiggle is not enabled for shared memory (that will come later in
something like #5054), but when it is, these panics will be clear
indicators of locations that must be re-implemented in a thread-safe
way.

* review: remove double cast

* review: refactor to include more logic in 'UnsafeGuestSlice'

* review: add reference to #4203

* review: link all thread-safe WASI fixups to #5235

* fix: consume 'UnsafeGuestSlice' during conversion to safe versions

* review: remove 'as_slice' and 'as_slice_mut'

* review: use 'as_unsafe_slice_mut' in 'to_vec'

* review: add `UnsafeBorrowResult`
2022-11-10 21:54:52 +00:00
Joe Shaw
7b7eeac1be wiggle: fix compilation with async functions when tracing is off (#5203)
Fixes #5202
2022-11-04 11:43:00 -07:00
Alex Crichton
2afaac5181 Return anyhow::Error from host functions instead of Trap, redesign Trap (#5149)
* Return `anyhow::Error` from host functions instead of `Trap`

This commit refactors how errors are modeled when returned from host
functions and additionally refactors how custom errors work with `Trap`.
At a high level functions in Wasmtime that previously worked with
`Result<T, Trap>` now work with `Result<T>` instead where the error is
`anyhow::Error`. This includes functions such as:

* Host-defined functions in a `Linker<T>`
* `TypedFunc::call`
* Host-related callbacks like call hooks

Errors are now modeled primarily as `anyhow::Error` throughout Wasmtime.
This subsequently removes the need for `Trap` to have the ability to
represent all host-defined errors as it previously did. Consequently the
`From` implementations for any error into a `Trap` have been removed
here and the only embedder-defined way to create a `Trap` is to use
`Trap::new` with a custom string.

After this commit the distinction between a `Trap` and a host error is
the wasm backtrace that it contains. Previously all errors in host
functions would flow through a `Trap` and get a wasm backtrace attached
to them, but now this only happens if a `Trap` itself is created meaning
that arbitrary host-defined errors flowing from a host import to the
other side won't get backtraces attached. Some internals of Wasmtime
itself were updated or preserved to use `Trap::new` to capture a
backtrace where it seemed useful, such as when fuel runs out.

The main motivation for this commit is that it now enables hosts to
thread a concrete error type from a host function all the way through to
where a wasm function was invoked. Previously this could not be done
since the host error was wrapped in a `Trap` that didn't provide the
ability to get at the internals.

A consequence of this commit is that when a host error is returned that
isn't a `Trap` we'll capture a backtrace and then won't have a `Trap` to
attach it to. To avoid losing the contextual information this commit
uses the `Error::context` method to attach the backtrace as contextual
information to ensure that the backtrace is itself not lost.

This is a breaking change for likely all users of Wasmtime, but it's
hoped to be a relatively minor change to workaround. Most use cases can
likely change `-> Result<T, Trap>` to `-> Result<T>` and otherwise
explicit creation of a `Trap` is largely no longer necessary.

* Fix some doc links

* add some tests and make a backtrace type public (#55)

* Trap: avoid a trailing newline in the Display impl

which in turn ends up with three newlines between the end of the
backtrace and the `Caused by` in the anyhow Debug impl

* make BacktraceContext pub, and add tests showing downcasting behavior of anyhow::Error to traps or backtraces

* Remove now-unnecesary `Trap` downcasts in `Linker::module`

* Fix test output expectations

* Remove `Trap::i32_exit`

This commit removes special-handling in the `wasmtime::Trap` type for
the i32 exit code required by WASI. This is now instead modeled as a
specific `I32Exit` error type in the `wasmtime-wasi` crate which is
returned by the `proc_exit` hostcall. Embedders which previously tested
for i32 exits now downcast to the `I32Exit` value.

* Remove the `Trap::new` constructor

This commit removes the ability to create a trap with an arbitrary error
message. The purpose of this commit is to continue the prior trend of
leaning into the `anyhow::Error` type instead of trying to recreate it
with `Trap`. A subsequent simplification to `Trap` after this commit is
that `Trap` will simply be an `enum` of trap codes with no extra
information. This commit is doubly-motivated by the desire to always use
the new `BacktraceContext` type instead of sometimes using that and
sometimes using `Trap`.

Most of the changes here were around updating `Trap::new` calls to
`bail!` calls instead. Tests which assert particular error messages
additionally often needed to use the `:?` formatter instead of the `{}`
formatter because the prior formats the whole `anyhow::Error` and the
latter only formats the top-most error, which now contains the
backtrace.

* Merge `Trap` and `TrapCode`

With prior refactorings there's no more need for `Trap` to be opaque or
otherwise contain a backtrace. This commit parse down `Trap` to simply
an `enum` which was the old `TrapCode`. All various tests and such were
updated to handle this.

The main consequence of this commit is that all errors have a
`BacktraceContext` context attached to them. This unfortunately means
that the backtrace is printed first before the error message or trap
code, but given all the prior simplifications that seems worth it at
this time.

* Rename `BacktraceContext` to `WasmBacktrace`

This feels like a better name given how this has turned out, and
additionally this commit removes having both `WasmBacktrace` and
`BacktraceContext`.

* Soup up documentation for errors and traps

* Fix build of the C API

Co-authored-by: Pat Hickey <pat@moreproductive.org>
2022-11-02 16:29:31 +00:00
Pat Hickey
0290a83502 wiggle: make wasmtime a mandatory dep, get rid of own Trap enum (#5137)
* wiggle: no longer need to guard wasmtime integration behind a feature

this existed so we could use wiggle in lucet, but lucet is long EOL

* replace wiggle::Trap with wiggle::wasmtime_crate::Trap

* wiggle tests: unwrap traps because we cant assert_eq on them

* wasi-common: emit a wasmtime::Trap instead of a wiggle::Trap

formally add a dependency on wasmtime here to make it obvious, though
we do now have a transitive one via wiggle no matter what (and therefore
can get rid of the default-features=false on the wiggle dep)

* wasi-nn: use wasmtime::Trap instead of wiggle::Trap

there's no way the implementation of this func is actually
a good idea, it will panic the host process on any error,
but I'll ask @mtr to fix that

* wiggle test-helpers examples: fixes

* wasi-common cant cross compile to wasm32-unknown-emscripten anymore

this was originally for the WASI polyfill for web targets. Those days
are way behind us now.

* wasmtime wont compile for armv7-unknown-linux-gnueabihf either
2022-10-27 09:28:10 -07:00
Alex Crichton
bcf3544924 Optimize Func::call and its C API (#3319)
* Optimize `Func::call` and its C API

This commit is an alternative to #3298 which achieves effectively the
same goal of optimizing the `Func::call` API as well as its C API
sibling of `wasmtime_func_call`. The strategy taken here is different
than #3298 though where a new API isn't created, rather a small tweak to
an existing API is done. Specifically this commit handles the major
sources of slowness with `Func::call` with:

* Looking up the type of a function, to typecheck the arguments with and
  use to guide how the results should be loaded, no longer hits the
  rwlock in the `Engine` but instead each `Func` contains its own
  `FuncType`. This can be an unnecessary allocation for funcs not used
  with `Func::call`, so this is a downside of this implementation
  relative to #3298. A mitigating factor, though, is that instance
  exports are loaded lazily into the `Store` and in theory not too many
  funcs are active in the store as `Func` objects.

* Temporary storage is amortized with a long-lived `Vec` in the `Store`
  rather than allocating a new vector on each call. This is basically
  the same strategy as #3294 only applied to different types in
  different places. Specifically `wasmtime::Store` now retains a
  `Vec<u128>` for `Func::call`, and the C API retains a `Vec<Val>` for
  calling `Func::call`.

* Finally, an API breaking change is made to `Func::call` and its type
  signature (as well as `Func::call_async`). Instead of returning
  `Box<[Val]>` as it did before this function now takes a
  `results: &mut [Val]` parameter. This allows the caller to manage the
  allocation and we can amortize-remove it in `wasmtime_func_call` by
  using space after the parameters in the `Vec<Val>` we're passing in.
  This change is naturally a breaking change and we'll want to consider
  it carefully, but mitigating factors are that most embeddings are
  likely using `TypedFunc::call` instead and this signature taking a
  mutable slice better aligns with `Func::new` which receives a mutable
  slice for the results.

Overall this change, in the benchmark of "call a nop function from the C
API" is not quite as good as #3298. It's still a bit slower, on the
order of 15ns, because there's lots of capacity checks around vectors
and the type checks are slightly less optimized than before. Overall
though this is still significantly better than today because allocations
and the rwlock to acquire the type information are both avoided. I
personally feel that this change is the best to do because it has less
of an API impact than #3298.

* Rebase issues
2021-09-21 14:07:05 -05:00
Pat Hickey
4fa4a72328 wiggle: expand test suite
sync test: show the dummy executor will trap (rather than panic) when a
future inside it pends.

async test: show that the executor is hooked up to a future that pends
for a trivial amount of time.

this adds tokio to the dev-dependencies of wiggle, it shouldn't end up
increasing the build burden for the project as a whole since its already
a dev-dependency.
2021-07-16 09:32:43 -07:00
Alex Crichton
5140fd251a Update wasm-tools crates (#2989)
* Update wasm-tools crates

This brings in recent updates, notably including more improvements to
wasm-smith which will hopefully help exercise non-trapping wasm more.

* Fix some wat
2021-06-15 22:56:10 -05:00
Alex Crichton
7a1b7cdf92 Implement RFC 11: Redesigning Wasmtime's APIs (#2897)
Implement Wasmtime's new API as designed by RFC 11. This is quite a large commit which has had lots of discussion externally, so for more information it's best to read the RFC thread and the PR thread.
2021-06-03 09:10:53 -05:00
Pat Hickey
228096c840 wiggle: convenient syntax for marking all funcs async 2021-04-14 14:51:24 -07:00
Pat Hickey
e38166ac3f wiggle::async_trait is defined as async_trait::async_trait(?Send)
async methods used by wiggle currently need to Not have the Send
constraint, so rather than make all use sites pass the argument
to the re-exported async_trait macro, define a new macro that
applies the argument.
2021-03-29 10:04:42 -07:00
Pat Hickey
1c4af27f2d delete GuestErrorConversion from docs, tests 2021-03-23 22:20:29 -07:00
Pat Hickey
84df5fa54a use the async keyword as syntax in the macro invocation 2021-03-05 08:58:54 -08:00
Pat Hickey
c4d8e2323a wiggle tests: fixes for new syntax 2021-03-04 18:16:36 -08:00
Pat Hickey
1fe97ea31e rename some wiggle tests to reflect new witx ast names
arrays are now lists
structs are now records
unions are now variants

this ruins some of my union puns, oh well
2021-02-18 15:06:16 -08:00
Alex Crichton
fa98f0bc91 Fix wiggle tests 2021-02-18 14:45:20 -08:00
Pat Hickey
ed44a19e5e wiggle: use bitflags to generate flags
more consistient with the rest of the ecosystem.
2021-01-11 18:20:57 -08:00
Pat Hickey
ec1bfeefb3 fix tests 2021-01-07 11:45:11 -08:00
Tanya L. Crenshaw
b06ed39c1e Fixes #2418: Enhance wiggle to generate its UserErrorConverstion trait with a function that returns Result<abi_err, String> (#2419)
* Enhance wiggle to generate its UserErrorConverstion trait with a function that returns
a Result<abi_err, String>.  This enhancement allows hostcall implementations using wiggle
to return an actionable error to the instance (the abi_err) or to terminate the instance
using the String as fatal error information.

* Enhance wiggle to generate its UserErrorConverstion trait with a function that returns
a Result<abi_err, String>.  This enhancement allows hostcall implementations using wiggle
to return an actionable error to the instance (the abi_err) or to terminate the instance
using the String as fatal error information.

* Enhance the wiggle/wasmtime integration to leverage new work in ab7e9c6.  Hostcall
implementations generated by wiggle now return an Result<abi_error, Trap>.  As a
result, hostcalls experiencing fatal errors may trap, thereby terminating the
wasmtime instance.  This enhancement has been performed for both wasi snapshot1
and wasi snapshot0.

* Update wasi-nn crate to reflect enhancement in issue #2418.

* Update wiggle test-helpers for wiggle enhancement made in issue #2418.

* Address PR feedback; omit verbose return statement.

* Address PR feedback; manually format within a proc macro.

* Address PR feedback; manually format proc macro.

* Restore return statements to wasi.rs.

* Restore return statements in funcs.rs.

* Address PR feedback; omit TODO and fix formatting.

* Ok-wrap error type in assert statement.
2020-11-24 14:06:57 -06:00
Pat Hickey
3509883f2d wiggle: add test of overlapping immutable borrows 2020-11-18 15:02:02 -08:00
Pat Hickey
776f12ae3c tests: exercise array getters 2020-09-03 16:41:10 -07:00
Pat Hickey
335886134c fix test 2020-08-28 17:11:11 -07:00
Pat Hickey
edefbf7c73 fix tests 2020-08-28 15:58:16 -07:00
Andrew Brown
f0e32c5f71 Fix typo (#2114) 2020-08-07 12:19:07 -05:00
Pat Hickey
8264abdef3 structs tests: comprehensive proptest for struct of array 2020-08-04 15:50:32 -07:00
Jakub Konka
5d8271286a Check if named type requires a lifetime and conform if does 2020-08-04 10:53:01 -07:00
Jakub Konka
e500be829b Add test case that replicate the problem 2020-08-04 10:53:01 -07:00
Pat Hickey
de7ff38fea add a second case for multiple error mappings 2020-05-30 14:06:48 -07:00
Pat Hickey
9085fc9f75 error conversion code: update test to actually execute it 2020-05-30 13:50:02 -07:00
Pat Hickey
1d2a1c4744 Merge remote-tracking branch 'origin/master' into pch/wiggle_error_transforms 2020-05-30 13:20:30 -07:00
Katelyn Martin
ae9af212ff wiggle: escape rust keywords, allow witx literals
# Overview

This commit makes changes to the `wiggle::from_witx` procedural in order
to allow for escaping strict and reserved Rust keywords.

Additionally, this commit introduces the ability to use a `witx_literal`
field in the `{..}` object provided as an argument to
`wiggle::from_witx`. This field allows for witx documents to be provided
as inline string literals.

Documentation comments are added to the methods of
`wiggle_generate::names::Names` struct responsible for generating
`proc_macro2::Ident` words.

 ## Keyword Escaping

Today, an interface that includes witx identifiers that conflict with
with Rust syntax will cause the `from_witx` macro to panic at
compilation time.

Here is a small example (adapted from
`/crates/wiggle/tests/keywords.rs`) that demonstrates this issue:

```
;; Attempts to define a module `self`, containing a trait `Self`. Both
;; of these are reserved keywords, and will thus cause a compilation
;; error.
(module $self
    (@interface func (export "betchya_cant_implement_this")
    )
)
```

Building off of code that (as of `master` today)
[demonstrates a strategy][esc] for escaping keywords, we introduce an
internal `escaping` module to `generate/src/config.rs` that contains
code responsible for escaping Rust keywords in a generalized manner.

[esc]: 0dd77d36f8/crates/wiggle/generate/src/names.rs (L106)

Some code related to special cases, such as accounting for
[`errno::2big`][err] while generating names for enum variants, is moved
into this module as well.

[err]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#-errno-enumu16

As mentioned in the document comments of this diff, we do not include
weak keywords like `'static` or `union`. Their semantics do not impact
us in the same way from a code generation perspective.

 ## witx_literal

First, some background. Trait names, type names, and so on use a
camel-cased naming convention.  As such, `Self` is the only keyword that
can potentially conflict with these identifiers. (See the [Rust
Reference][key] for a complete list of strict, reserved, and weak
keywords.)

When writing tests, this meant that many tests had to be outlined into
separate files, as items with the name `$self` could not be defined in
the same namespace. As such, it seemed like a worthwhile feature to
implement while the above work was being developed.

The most important function to note is the `load_document` inherent
method added to `WitxConf`, and that `WitxConf` is now an enum
containing either (a) a collection of paths, identical to its current
functionality, or (b) a single string literal.

Note that a witx document given to `from_witx` using a string literal
provided to `from_witx` cannot include `use (..)` directives, per
the `witx::parse` documentation.
(See: https://docs.rs/witx/0.8.5/witx/fn.parse.html)

Two newtypes, `Paths` and `Literal`, are introduced to facilitate the
parsing of `WitxConf` values. Their public API and trait implementations
has been kept to the minimum required to satisfy compilation in order to
limit the scope of this diff. Additional surface for external consumers
can be added in follow-up commits if deemed necessary in review.
2020-05-30 02:02:38 -04:00
Pat Hickey
9038f91696 wiggle: allow user-configurable error transformations 2020-05-29 12:55:57 -07:00
Pat Hickey
96d6884d33 wiggle: get BorrowChecker from GuestMemory method 2020-05-21 12:37:14 -07:00
Pat Hickey
c30194dfa1 document BorrowChecker, make creation unsafe 2020-05-20 12:51:28 -07:00
Pat Hickey
be1df80c1b wasi test: update explanation of safety 2020-05-20 12:51:28 -07:00
Pat Hickey
52e8300f01 wiggle: automate borrow checking, explicitly passing borrow checker throughout 2020-05-20 12:51:28 -07:00
Pat Hickey
3e97e5f1ae wiggle: revamp error type conversions 2020-04-03 15:27:27 -07:00
Pat Hickey
167a040ea5 GuestErrorType only needs to have a success constructor 2020-04-03 15:26:15 -07:00
Alex Crichton
a628dc315e Shuffle around the wiggle crates (#1414)
* Shuffle around the wiggle crates

This commit reorganizes the wiggle crates slightly by performing the
following transforms:

* The `crates/wiggle` crate, previously named `wiggle`, was moved to
  `crates/wiggle/crates/macro` and is renamed to `wiggle-macro`.

* The `crates/wiggle/crates/runtime` crate, previously named
  `wiggle-runtime`, was moved to `crates/wiggle` and is renamed to
  `wiggle`.

* The new `wiggle` crate depends on `wiggle-macro` and reexports the macro.

The goal here is that consumers only deal with the `wiggle` crate
itself. No more crates depend on `wiggle-runtime` and all dependencies
are entirely on just the `wiggle` crate.

* Remove the `crates/wiggle/crates` directory

Move everything into `crates/wiggle` directly, like `wasi-common`

* Add wiggle-macro to test-all script

* Fixup a test
2020-03-26 18:34:50 -05:00
Pat Hickey
bc1a11435e wiggle: emit a metadata module containing witx document (#1387)
* wiggle: emit a metadata module containing witx document

* wiggle: put metadata module behind a wiggle_metadata feature

* wasi-common: add wiggle_metadata feature and optional witx dep

* refactor according to alex's advice

* wasi-common: make snapshots pub

* wasi-common: i do need a wiggle_metadata feature to be available

* Tweak features and such

* wiggle: fix tests by passing metadata flag to wiggle-runtime

* wiggle: need to move wiggle-runtime to a non-dev dependency

so that the feature resolves for external users of the crates

Co-authored-by: Alex Crichton <alex@alexcrichton.com>
2020-03-25 14:57:44 -05:00
Pat Hickey
0e72edb80e wiggle-generate: always pass GuestPtr by reference
with the prev approach, it would be passed by reference sometimes
(e.g. when used as an Array argument) but by value most of the time.
this was inconsistient.

theres no need to pass the owned version, all operations are &self.
2020-03-20 14:01:41 -07:00
Jakub Konka
5024d7bf09 [wiggle] Impl different formatters for flags (#1299)
* Impl different formatters for flags

Rather than forcing only binary formatting of flags types, how about
we implement all relevant traits (`Binary`, `Octal`, `LowerHex`, and
`UpperHex`) and allow the user to pick the most relevant one for their
use case?

Also, we use at least `Octal` and `LowerHex` in a couple of places
in `wasi-common`.

* fmt::Display for flags now inspired by bitflags

Flags is now by default formatted similarly to how
`bitflags` crate does it, namely, `dsync|append (0x11)`. In case
we're dealing with an empty set, we get `empty (0x0)`. Because of
this, any `Octal`, `LowerHex`, etc., formatters are redundant now.

Furthermore, while here, I've rewritten `EMPTY_FLAGS` and `ALL_FLAGS`
(where the former means `0x0` and the latter is the union of all possible
values) to be `const fn empty()` and `const fn all()` where the latter is
an expanded union of primitive representation values out of a macro.
This is again largely inspired by the `bitflags` crate.

* Test fmt::Display for flags
2020-03-13 12:27:34 -07:00
Jakub Konka
ae0a0240ed Add 'crates/wiggle/' from commit 'cd484e49932d8dd8f1bd1a002e0717ad8bff07fb'
git-subtree-dir: crates/wiggle
git-subtree-mainline: 2ead747f48
git-subtree-split: cd484e4993
2020-03-11 17:30:49 +01:00