Commit Graph

794 Commits

Author SHA1 Message Date
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
Pat Hickey
c32c2e8272 Merge pull request #1793 from katie-martin-fastly/ktm/beep-beep-keywords-to-the-jeep
💖 wiggle: escape rust keywords, allow witx literals
2020-05-30 13:10:59 -07:00
Pat Hickey
614723ab7e Update crates/wiggle/generate/src/names.rs 2020-05-30 13:10:47 -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
Leonardo Yvens
0b3b9c298e impl From<anyhow::Error> for Trap (#1753)
* From<anyhow::Error> for Trap

* Add TrapReason::Error

* wasmtime: Improve Error to Trap conversion

* Remove Trap::message
2020-05-29 15:24:12 -05:00
Pat Hickey
9038f91696 wiggle: allow user-configurable error transformations 2020-05-29 12:55:57 -07:00
Dan Gohman
ce757f12d1 Linker refactoring (#1773)
* Minor code tidying.

* Document that `Linker::iter`'s iteration order is arbitrary.

* Add a few more tests for `wasmtime::Linker`.

* Refactor `Linker::compute_imports`.

 - Extract the error message generation into a separate function.
 - In the error message, sort the candidates.

* Fix a typo in a comment.

* Add `__rtti_base` to the list of allowed but deprecated exports.

* Don't print an Error message when a program exits normally.

* Update comments to reflect the current code.

* Also allow "table" as an exported table, which is used by AssemblyScript.
2020-05-28 13:28:05 -07:00
Dan Gohman
3715e19c67 Reactor support. (#1565)
* Reactor support.

This implements the new WASI ABI described here:

https://github.com/WebAssembly/WASI/blob/master/design/application-abi.md

It adds APIs to `Instance` and `Linker` with support for running
WASI programs, and also simplifies the process of instantiating
WASI API modules.

This currently only includes Rust API support.

* Add comments and fix a typo in a comment.

* Fix a rustdoc warning.

* Tidy an unneeded `mut`.

* Factor out instance initialization with `NewInstance`.

This also separates instantiation from initialization in a manner
similar to https://github.com/bytecodealliance/lucet/pull/506.

* Update fuzzing oracles for the API changes.

* Remove `wasi_linker` and clarify that Commands/Reactors aren't connected to WASI.

* Move Command/Reactor semantics into the Linker.

* C API support.

* Fix fuzzer build.

* Update usage syntax from "::" to "=".

* Remove `NewInstance` and `start()`.

* Elaborate on Commands and Reactors and add a spec link.

* Add more comments.

* Fix wat syntax.

* Fix wat.

* Use the `Debug` formatter to format an anyhow::Error.

* Fix wat.
2020-05-26 10:39:40 -05:00
Pat Hickey
d57fea20ca Merge pull request #1717 from bytecodealliance/pch/wiggle_auto_borrow_checking
Automate borrow checking in wiggle
2020-05-22 09:35:12 -07:00
whitequark
b2e8ed4dc9 cranelift: add i64.[us]{div,rem} libcalls.
These libcalls are useful for 32-bit platforms.
2020-05-22 11:41:56 +00:00
Pat Hickey
bc1f538385 wiggle: fix tests 2020-05-21 15:47:48 -07:00
Pat Hickey
561f9e084a wig: bugfixes (sorry, thought i had tested before committimg) 2020-05-21 14:21:47 -07:00
whitequark
26ee986c2f runtime: handle traps on Windows x32. (#1740) 2020-05-21 15:07:05 -05:00
Alex Crichton
036c8ec8c5 Fix assertion about length/capacity in C API (#1736)
I recently saw some [errors] crop up in wasmtime-go's CI, so let's be
sure to convert to `Box<[T]>` which guarantees the length/capacity of
the vector are equal.

[errors]: https://github.com/bytecodealliance/wasmtime-go/runs/694744570
2020-05-21 15:06:30 -05:00
Pat Hickey
d19a09a4be wig: wiggle now puts BorrowChecker inside GuestMemory 2020-05-21 12:40:39 -07:00
Pat Hickey
9f763375de error name change fixup 2020-05-21 12:38:06 -07:00
Pat Hickey
96d6884d33 wiggle: get BorrowChecker from GuestMemory method 2020-05-21 12:37:14 -07:00
Pat Hickey
3920d8c1f3 code review fix 2020-05-21 12:22:47 -07:00
Pat Hickey
ba82ddcf37 borrow out of handles: change error name and describe behavior in comment 2020-05-21 12:22:19 -07:00
whitequark
e5635f4bc9 winx: do not link directly to ntdll.dll. (#1739)
The documentation for RtlNtStatusToDosError explicitly tells to call
it via GetProcAddress. The documentation for NtQueryInformationFile
does not, but similar considerations apply because there is normally
no import library for ntdll.

The main reason to use GetProcAddress though is because MinGW does
include an import library for ntdll, this import library contains
a definition of setjmp, and because of the way rustc orders linker
arguments, this definition of setjmp conflicts with and gets picked
over the one in msvcrt. Using setjmp from ntdll is undesirable as it
is an undocumented API and it is missing from wine, making it harder
to develop wasmtime using a cross-compiler.

Fixes #1738.
2020-05-21 13:56:20 -05:00
Alex Crichton
68f0d2f6d0 Enable env_logger in the C API (#1737)
This commit ensures that `env_logger` and `RUST_LOG` are configured to
work with the C API.
2020-05-21 11:02:49 -05:00
Pat Hickey
37514b730f wig: alex has convinced me that this BorrowChecker creation is correct 2020-05-20 12:51:28 -07:00
Pat Hickey
b130a64d19 wasi-common fixes 2020-05-20 12:51:28 -07:00
Pat Hickey
04fb4acc6a wasi-common: WIP translating to use automated borrow checking 2020-05-20 12:51:28 -07:00
Pat Hickey
3643f2d164 wig: create a BorrowChecker just to get things compiling. Needs fixing. 2020-05-20 12:51:28 -07:00
Pat Hickey
056a7d0729 wiggle: redo docs for auto borrow checking 2020-05-20 12:51:28 -07:00
Pat Hickey
c30194dfa1 document BorrowChecker, make creation unsafe 2020-05-20 12:51:28 -07:00
Pat Hickey
a4c1079b50 borrow checker: add method to check that its empty 2020-05-20 12:51:28 -07:00
Pat Hickey
d221a3a346 faster path for borrow-checking GuestPtr::{read, write} 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
478cc68082 wiggle: GuestType read and write must borrow 2020-05-20 12:51:28 -07:00
Pat Hickey
73602c6bfe borrow checker: reset index when empty, handle oom 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
Nick Fitzgerald
e229fbc79c Merge pull request #1733 from fitzgen/rename-anyref-to-externref
Rename `anyref` to `externref` across the board
2020-05-20 12:44:49 -07:00
Jakub Konka
348be6f3ed Revert fstatat on *nix and test symlinks in path_filestat calls (#1725)
* Revert fstatat on *nix and test symlinks in path_filestat calls

This commit effectively reverts too eager refactoring on my part which
resulted in incorrect `path_filestat_{get, set_times}` behaviour on
*nix hosts. In the presence of symlinks, neither of the calls would
work properly.

In order to shield ourselves from similar errors in the future, I've
augmented the `path_filestat` test cases with symlink checks as well.

* Pass appropriate flags to fstatat and utimensat

* Fix formatting

* Fix Windows build

* Expand final symlinks if follow is set on Windows

* Fix formatting

* Do not follow symlinks unless specified on Windows

* Update comments and restart CI

* Skip testing volatile atim field
2020-05-20 12:02:24 -07:00
Nick Fitzgerald
f28b3738ee Rename anyref to externref across the board 2020-05-20 11:58:55 -07:00
Chris Fallin
72e6be9342 Rework of MachInst isel, branch fixups and lowering, and block ordering.
This patch includes:

- A complete rework of the way that CLIF blocks and edge blocks are
  lowered into VCode blocks. The new mechanism in `BlockLoweringOrder`
  computes RPO over the CFG, but with a twist: it merges edge blocks intto
  heads or tails of original CLIF blocks wherever possible, and it does
  this without ever actually materializing the full nodes-plus-edges
  graph first. The backend driver lowers blocks in final order so
  there's no need to reshuffle later.

- A new `MachBuffer` that replaces the `MachSection`. This is a special
  version of a code-sink that is far more than a humble `Vec<u8>`. In
  particular, it keeps a record of label definitions and label uses,
  with a machine-pluggable `LabelUse` trait that defines various types
  of fixups (basically internal relocations).

  Importantly, it implements some simple peephole-style branch rewrites
  *inline in the emission pass*, without any separate traversals over
  the code to use fallthroughs, swap taken/not-taken arms, etc. It
  tracks branches at the tail of the buffer and can (i) remove blocks
  that are just unconditional branches (by redirecting the label), (ii)
  understand a conditional/unconditional pair and swap the conditional
  polarity when it's helpful; and (iii) remove branches that branch to
  the fallthrough PC.

  The `MachBuffer` also implements branch-island support. On
  architectures like AArch64, this is needed to allow conditional
  branches within plausibly-attainable ranges (+/- 1MB on AArch64
  specifically). It also does this inline while streaming through the
  emission, without any sort of fixpoint algorithm or later moving of
  code, by simply tracking outstanding references and "deadlines" and
  emitting an island just-in-time when we're in danger of going out of
  range.

- A rework of the instruction selector driver. This is largely following
  the same algorithm as before, but is cleaned up significantly, in
  particular in the API: the machine backend can ask for an input arg
  and get any of three forms (constant, register, producing
  instruction), indicating it needs the register or can merge the
  constant or producing instruction as appropriate. This new driver
  takes special care to emit constants right at use-sites (and at phi
  inputs), minimizing their live-ranges, and also special-cases the
  "pinned register" to avoid superfluous moves.

Overall, on `bz2.wasm`, the results are:

    wasmtime full run (compile + runtime) of bz2:

    baseline:   9774M insns, 9742M cycles, 3.918s
    w/ changes: 7012M insns, 6888M cycles, 2.958s  (24.5% faster, 28.3% fewer insns)

    clif-util wasm compile bz2:

    baseline:   2633M insns, 3278M cycles, 1.034s
    w/ changes: 2366M insns, 2920M cycles, 0.923s  (10.7% faster, 10.1% fewer insns)

    All numbers are averages of two runs on an Ampere eMAG.
2020-05-16 23:08:22 -07:00
Nick Fitzgerald
1a4f3fb2df Update deps and tests for anyref --> externref
* Update to using `wasmparser` 0.55.0
* Update wasmprinter to 0.2.5
* Update `wat` to 1.0.18, and `wast` to 17.0.0
2020-05-14 12:47:37 -07:00
Alex Crichton
1e3a1fa372 Remove stray debugging printlns (#1698)
Forgot to do this earlier!
2020-05-14 10:26:09 -05:00
Alex Crichton
1247f2b4ae Add wasmtime-specific C APIs for tables (#1654)
This commit adds a suite of `wasmtime_funcref_table_*` APIs which mirror
the standard APIs but have a few differences:

* More errors are returned. For example error messages are communicated
  through `wasmtime_error_t` and out-of-bounds vs load of null can be
  differentiated in the `get` API.

* APIs take `wasm_func_t` instead of `wasm_ref_t`. Given the recent
  decision to remove subtyping from the anyref proposal it's not clear
  how the C API for tables will be affected, so for now these APIs are
  all specialized to only funcref tables.

* Growth now allows access to the previous size of the table, if
  desired, which mirrors the `table.grow` instruction.

This was originally motivated by bytecodealliance/wasmtime-go#5 where
the current APIs we have for working with tables don't quite work. We
don't have a great way to take an anyref constructed from a `Func` and
get the `Func` back out, so for now this sidesteps those concerns while
we sort out the anyref story.

It's intended that once the anyref story has settled and the official C
API has updated we'll likely delete these wasmtime-specific APIs or
implement them as trivial wrappers around the official ones.
2020-05-13 16:16:29 -07:00
Dan Gohman
fb0b9e3ae6 Change proc_exit to unwind the stack rather than exiting the host process. (#1646)
* Remove Cranelift's OutOfBounds trap, which is no longer used.

* Change proc_exit to unwind instead of exit the host process.

This implements the semantics in https://github.com/WebAssembly/WASI/pull/235.

Fixes #783.
Fixes #993.

* Fix exit-status tests on Windows.

* Revert the wiggle changes and re-introduce the wasi-common implementations.

* Move `wasi_proc_exit` into the wasmtime-wasi crate.

* Revert the spec_testsuite change.

* Remove the old proc_exit implementations.

* Make `TrapReason` an implementation detail.

* Allow exit status 2 on Windows too.

* Fix a documentation link.

* Really fix a documentation link.
2020-05-13 15:59:43 -07:00
Josh Triplett
08983bf39c Move crates/api to crates/wasmtime (#1693)
The `wasmtime` crate currently lives in `crates/api` for historical
reasons, because we once called it `wasmtime-api` crate. This creates a
stumbling block for new contributors.

As discussed on Zulip, rename the directory to `crates/wasmtime`.
2020-05-13 16:04:31 -05:00
Alex Crichton
962f057c8a Remove no-longer-needed C shims (#1686)
The published version of `libc` now has all that's necessary to natively
read these fields!
2020-05-12 16:01:13 -05:00
SlightlyOutOfPhase
5394b6c72e Update staticvec dependency from 0.8 to 0.9 (#1676)
* Update staticvec dependency from 0.8 to 0.9

* Update lockfile also
2020-05-11 09:22:06 -05:00
whitequark
a1dbeee062 Implement X86CallPCRel4 relocations in the JIT linker.
All calls inside a module are relocated with these.
2020-05-09 03:27:06 -07:00
whitequark
736766397e Remove the last hardcoded instance of I64 pointers, in wasmtime-api. 2020-05-09 03:27:06 -07:00
whitequark
b3a9882466 Add X86-32 support to wasm-runtime trap handler. 2020-05-09 03:27:06 -07:00
Jakub Konka
cbf7cbfa39 Introduce strongly-typed system primitives (#1561)
* Introduce strongly-typed system primitives

This commit does a lot of reshuffling and even some more. It introduces
strongly-typed system primitives which are: `OsFile`, `OsDir`, `Stdio`,
and `OsOther`. Those primitives are separate structs now, each implementing
a subset of `Handle` methods, rather than all being an enumeration of some
supertype such as `OsHandle`. To summarise the structs:

* `OsFile` represents a regular file, and implements fd-ops
  of `Handle` trait
* `OsDir` represents a directory, and primarily implements path-ops, plus
  `readdir` and some common fd-ops such as `fdstat`, etc.
* `Stdio` represents a stdio handle, and implements a subset of fd-ops
  such as `fdstat` _and_ `read_` and `write_vectored` calls
* `OsOther` currently represents anything else and implements a set similar
  to that implemented by `Stdio`

This commit is effectively an experiment and an excercise into better
understanding what's going on for each OS resource/type under-the-hood.
It's meant to give us some intuition in order to move on with the idea
of having strongly-typed handles in WASI both in the syscall impl as well
as at the libc level.

Some more minor changes include making `OsHandle` represent an OS-specific
wrapper for a raw OS handle (Unix fd or Windows handle). Also, since `OsDir`
is tricky across OSes, we also have a supertype of `OsHandle` called
`OsDirHandle` which may store a `DIR*` stream pointer (mainly BSD). Last but not
least, the `Filetype` and `Rights` are now computed when the resource is created,
rather than every time we call `Handle::get_file_type` and `Handle::get_rights`.
Finally, in order to facilitate the latter, I've converted `EntryRights` into
`HandleRights` and pushed them into each `Handle` implementor.

* Do not adjust rights on Stdio

* Clean up testing for TTY and escaping writes

* Implement AsFile for dyn Handle

This cleans up a lot of repeating boilerplate code todo with
dynamic dispatch.

* Delegate definition of OsDir to OS-specific modules

Delegates defining `OsDir` struct to OS-specific modules (BSD, Linux,
Emscripten, Windows). This way, `OsDir` can safely re-use `OsHandle`
for raw OS handle storage, and can store some aux data such as an
initialized stream ptr in case of BSD. As a result, we can safely
get rid of `OsDirHandle` which IMHO was causing unnecessary noise and
overcomplicating the design. On the other hand, delegating definition
of `OsDir` to OS-specific modules isn't super clean in and of itself
either. Perhaps there's a better way of handling this?

* Check if filetype of OS handle matches WASI filetype when creating

It seems prudent to check if the passed in `File` instance is of
type matching that of the requested WASI filetype. In other words,
we'd like to avoid situations where `OsFile` is created from a
pipe.

* Make AsFile fallible

Return `EBADF` in `AsFile` in case a `Handle` cannot be made into
a `std::fs::File`.

* Remove unnecessary as_file conversion

* Remove unnecessary check for TTY for Stdio handle type

* Fix incorrect stdio ctors on Unix

* Split Stdio into three separate types: Stdin, Stdout, Stderr

* Rename PendingEntry::File to PendingEntry::OsHandle to avoid confusion

* Rename OsHandle to RawOsHandle

Also, since `RawOsHandle` on *nix doesn't need interior mutability
wrt the inner raw file descriptor, we can safely swap the `RawFd`
for `File` instance.

* Add docs explaining what OsOther is

* Allow for stdio to be non-character-device (e.g., piped)

* Return error on bad preopen rather than panic
2020-05-07 16:00:14 -07:00
Alex Crichton
57fb1c69c5 Enable the multi-value proposal by default (#1667)
This was merged into the wasm spec upstream in WebAssembly/spec#1145, so
let's follow the spec and enable it by default here as well!
2020-05-06 12:37:29 -05:00