diff --git a/.github/workflows/js.yaml b/.github/workflows/js.yaml new file mode 100644 index 00000000000..d05e21ce80f --- /dev/null +++ b/.github/workflows/js.yaml @@ -0,0 +1,31 @@ +on: + push: + branches: + - 'master' + - 'staging' + - 'trying' + tags: + # this is _not_ a regex, see: https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet + - '[0-9]+.[0-9]+.[0-9]+*' + +name: wasmer-js tests + +env: + RUST_BACKTRACE: 1 + +jobs: + wasmer-js: + name: wasmer-js + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + profile: minimal + override: true + - name: Install wasm-pack + run: | + curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + - name: Test wasmer-js + run: make test-js diff --git a/Cargo.lock b/Cargo.lock index 33cb9b527ed..c104b1571b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -349,6 +349,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "console_error_panic_hook" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8d976903543e0c48546a91908f21588a680a8c8f984df9a5d69feccb2b2a211" +dependencies = [ + "cfg-if 0.1.10", + "wasm-bindgen", +] + [[package]] name = "constant_time_eq" version = "0.1.5" @@ -1755,6 +1765,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "scoped-tls" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" + [[package]] name = "scopeguard" version = "1.1.0" @@ -2300,6 +2316,18 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fba7978c679d53ce2d0ac80c8c175840feb849a161664365d1287b41f2e67f1" +dependencies = [ + "cfg-if 1.0.0", + "js-sys", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.74" @@ -2329,6 +2357,30 @@ version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" +[[package]] +name = "wasm-bindgen-test" +version = "0.3.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cab416a9b970464c2882ed92d55b0c33046b08e0bdc9d59b3b718acd4e1bae8" +dependencies = [ + "console_error_panic_hook", + "js-sys", + "scoped-tls", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test-macro", +] + +[[package]] +name = "wasm-bindgen-test-macro" +version = "0.3.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd4543fc6cf3541ef0d98bf720104cc6bd856d7eba449fd2aa365ef4fed0e782" +dependencies = [ + "proc-macro2", + "quote", +] + [[package]] name = "wasm-encoder" version = "0.4.1" @@ -2356,13 +2408,16 @@ version = "2.0.0" dependencies = [ "anyhow", "cfg-if 1.0.0", + "hashbrown", "indexmap", - "libc", + "js-sys", "loupe", "more-asserts", "target-lexicon 0.12.0", "tempfile", "thiserror", + "wasm-bindgen", + "wasm-bindgen-test", "wasmer-compiler", "wasmer-compiler-cranelift", "wasmer-compiler-llvm", @@ -2373,6 +2428,7 @@ dependencies = [ "wasmer-engine-universal", "wasmer-types", "wasmer-vm", + "wasmparser", "wat", "winapi", ] diff --git a/Makefile b/Makefile index b21caf3adf5..f0d1a1fb813 100644 --- a/Makefile +++ b/Makefile @@ -500,6 +500,10 @@ test-packages: cargo test --manifest-path lib/compiler-singlepass/Cargo.toml --release --no-default-features --features=std cargo test --manifest-path lib/cli/Cargo.toml $(compiler_features) --release +test-js: + cd lib/api && wasm-pack test --node -- --no-default-features --features js-default,wat + + ##### # # Testing compilers. diff --git a/lib/README.md b/lib/README.md index 19e0f447f1e..f4f7fdb3baa 100644 --- a/lib/README.md +++ b/lib/README.md @@ -7,6 +7,8 @@ composed of a set of crates. We can group them as follows: programatically through the `wasmer` crate, * `c-api` — The public C API exposes everything a C user needs to use Wasmer programatically, +* `js-api` — The public JavaScript API exposes everything a user needs to run Wasmer + in a client like a browser or on a server like NodeJS or Deno, * `cache` — The traits and types to cache compiled WebAssembly modules, * `cli` — The Wasmer CLI itself, diff --git a/lib/api/Cargo.toml b/lib/api/Cargo.toml index 4868f5ccd6d..ec2fe37c21e 100644 --- a/lib/api/Cargo.toml +++ b/lib/api/Cargo.toml @@ -10,96 +10,146 @@ license = "MIT" readme = "README.md" edition = "2018" +##### +# This crate comes in 2 major flavors: +# +# - `sys`, where `wasmer` will be compiled to a native executable +# which provides compilers, engines, a full VM etc. +# - `js`, where `wasmer` will be compiled to WebAssembly to run in a +# JavaScript host. +##### + +# Shared dependencies. [dependencies] +# - Mandatory shared dependencies. +indexmap = { version = "1.6", features = ["serde-1"] } +cfg-if = "1.0" +thiserror = "1.0" +more-asserts = "0.2" +# - Optional shared dependencies. +wat = { version = "1.0", optional = true } + +# Dependencies and Development Dependencies for `sys`. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# - Mandatory dependencies for `sys`. wasmer-vm = { path = "../vm", version = "2.0.0" } -wasmer-compiler-singlepass = { path = "../compiler-singlepass", version = "2.0.0", optional = true } -wasmer-compiler-cranelift = { path = "../compiler-cranelift", version = "2.0.0", optional = true } -wasmer-compiler-llvm = { path = "../compiler-llvm", version = "2.0.0", optional = true } wasmer-compiler = { path = "../compiler", version = "2.0.0" } wasmer-derive = { path = "../derive", version = "2.0.0" } wasmer-engine = { path = "../engine", version = "2.0.0" } -wasmer-engine-universal = { path = "../engine-universal", version = "2.0.0", optional = true } -wasmer-engine-dylib = { path = "../engine-dylib", version = "2.0.0", optional = true } wasmer-types = { path = "../types", version = "2.0.0" } -indexmap = { version = "1.6", features = ["serde-1"] } -cfg-if = "1.0" -wat = { version = "1.0", optional = true } -thiserror = "1.0" -more-asserts = "0.2" target-lexicon = { version = "0.12", default-features = false } loupe = "0.1" - -[target.'cfg(target_os = "windows")'.dependencies] +# - Optional dependencies for `sys`. +wasmer-compiler-singlepass = { path = "../compiler-singlepass", version = "2.0.0", optional = true } +wasmer-compiler-cranelift = { path = "../compiler-cranelift", version = "2.0.0", optional = true } +wasmer-compiler-llvm = { path = "../compiler-llvm", version = "2.0.0", optional = true } +wasmer-engine-universal = { path = "../engine-universal", version = "2.0.0", optional = true } +wasmer-engine-dylib = { path = "../engine-dylib", version = "2.0.0", optional = true } +# - Mandatory dependencies for `sys` on Windows. +[target.'cfg(all(not(target_arch = "wasm32"), target_os = "windows"))'.dependencies] winapi = "0.3" - -[dev-dependencies] -# for the binary wasmer.rs -libc = { version = "^0.2", default-features = false } +# - Development Dependencies for `sys`. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] wat = "1.0" tempfile = "3.1" anyhow = "1.0" +# Dependencies and Develoment Dependencies for `js`. +[target.'cfg(target_arch = "wasm32")'.dependencies] +# - Mandatory dependencies for `js`. +wasmer-types = { path = "../types", version = "2.0.0", default-features = false, features = ["std"] } +wasm-bindgen = "0.2.74" +js-sys = "0.3.51" +wasmer-derive = { path = "../derive", version = "2.0.0" } +# - Optional dependencies for `js`. +wasmparser = { version = "0.78", default-features = false, optional = true } +hashbrown = { version = "0.9", optional = true } +# - Development Dependencies for `js`. +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] +wat = "1.0" +anyhow = "1.0" +wasm-bindgen-test = "0.3.0" + +# Specific to `js`. +# +# `wasm-opt` is on by default in for the release profile, but it can be +# disabled by setting it to `false` +[package.metadata.wasm-pack.profile.release] +wasm-opt = false + [badges] maintenance = { status = "actively-developed" } [features] -default = ["wat", "default-cranelift", "default-universal"] +default = ["sys-default"] +std = [] +core = ["hashbrown"] + +# Features for `sys`. +sys = [] +sys-default = ["sys", "wat", "default-cranelift", "default-universal"] +# - Compilers. compiler = [ + "sys", "wasmer-compiler/translator", "wasmer-engine-universal/compiler", "wasmer-engine-dylib/compiler", ] -engine = [] -universal = [ - "wasmer-engine-universal", - "engine" -] -dylib = [ - "wasmer-engine-dylib", - "engine" -] -singlepass = [ - "wasmer-compiler-singlepass", - "compiler", -] -cranelift = [ - "wasmer-compiler-cranelift", - "compiler", -] -llvm = [ - "wasmer-compiler-llvm", - "compiler", -] - -default-singlepass = [ - "singlepass", - "default-compiler" -] -default-cranelift = [ - "cranelift", - "default-compiler" -] -default-llvm = [ - "llvm", - "default-compiler" -] -default-universal = [ - "universal", - "default-engine" -] -default-dylib = [ - "dylib", - "default-engine" -] - + singlepass = [ + "compiler", + "wasmer-compiler-singlepass", + ] + cranelift = [ + "compiler", + "wasmer-compiler-cranelift", + ] + llvm = [ + "compiler", + "wasmer-compiler-llvm", + ] default-compiler = [] + default-singlepass = [ + "default-compiler", + "singlepass", + ] + default-cranelift = [ + "default-compiler", + "cranelift", + ] + default-llvm = [ + "default-compiler", + "llvm", + ] +# - Engines. +engine = ["sys"] + universal = [ + "engine", + "wasmer-engine-universal", + ] + dylib = [ + "engine", + "wasmer-engine-dylib", + ] default-engine = [] - -# experimental / in-development features + default-universal = [ + "default-engine", + "universal", + ] + default-dylib = [ + "default-engine", + "dylib", + ] +# - Experimental / in-development features experimental-reference-types-extern-ref = [ + "sys", "wasmer-types/experimental-reference-types-extern-ref", ] - -# Deprecated features. +# - Deprecated features. jit = ["universal"] native = ["dylib"] + +# Features for `js`. +js = [] +js-default = ["js", "std", "wasm-types-polyfill"] + +wasm-types-polyfill = ["js", "wasmparser"] diff --git a/lib/api/README.md b/lib/api/README.md index 7ef67360b74..c0145bc881d 100644 --- a/lib/api/README.md +++ b/lib/api/README.md @@ -1,14 +1,17 @@ # `wasmer` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) [![crates.io](https://img.shields.io/crates/v/wasmer.svg)](https://crates.io/crates/wasmer) [`Wasmer`](https://wasmer.io/) is the most popular -[WebAssembly](https://webassembly.org/) runtime for Rust (...and also -the fastest). It supports JIT (Just in Time) and AOT (Ahead of time) -compilation as well as pluggable compilers suited to your needs. +[WebAssembly](https://webassembly.org/) runtime for Rust. It supports +JIT (Just In Time) and AOT (Ahead Of Time) compilation as well as +pluggable compilers suited to your needs. It's designed to be safe and secure, and runnable in any kind of environment. ## Usage +Here is a small example of using Wasmer to run a WebAssembly module +written with its WAT format (textual format): + ```rust use wasmer::{Store, Module, Instance, Value, imports}; @@ -36,36 +39,70 @@ fn main() -> anyhow::Result<()> { } ``` +[Discover the full collection of examples](https://github.com/wasmerio/wasmer/tree/master/examples). + ## Features Wasmer is not only fast, but also designed to be *highly customizable*: -* **Pluggable Engines**: do you have a fancy `dlopen` implementation? This is for you! -* **Pluggable Compilers**: you want to emit code with DynASM or other compiler? We got you! -* **Headless mode**: that means that no compilers will be required - to run a `serialized` Module (via `Module::deserialize()`). -* **Cross-compilation**: You can pre-compile a module and serialize it - to then run it in other platform (via `Module::serialize()`). - -## Config flags - -Wasmer has the following configuration flags: -* `wat` (enabled by default): It allows to read WebAssembly files in their text format. - *This feature is normally used only in development environments* -* Compilers (mutually exclusive): - - `singlepass`: it will use `wasmer-compiler-singlepass` as the default - compiler (ideal for **blockchains**). - - `cranelift`: it will use `wasmer-compiler-cranelift` as the default - compiler (ideal for **development**). - - `llvm`: it will use `wasmer-compiler-llvm` as the default - compiler (ideal for **production**). - -Wasmer ships by default with the `cranelift` compiler as its great for development proposes. -However, we strongly encourage to use the `llvm` backend in production as it performs -about 50% faster, achieving near-native speeds. - -> Note: if you want to use multiple compilers at the same time, it's also possible! -> You will need to import them directly via each of the compiler crates. + +* **Pluggable engines** — An engine is responsible to drive the + compilation process and to store the generated executable code + somewhere, either: + * in-memory (with [`wasmer-engine-universal`]), + * in a native shared object file (with [`wasmer-engine-dylib`], + `.dylib`, `.so`, `.dll`), then load it with `dlopen`, + * in a native static object file (with [`wasmer-engine-staticlib`]), + in addition to emitting a C header file, which both can be linked + against a sandboxed WebAssembly runtime environment for the + compiled module with no need for runtime compilation. + +* **Pluggable compilers** — A compiler is used by an engine to + transform WebAssembly into executable code: + * [`wasmer-compiler-singlepass`] provides a fast compilation-time + but an unoptimized runtime speed, + * [`wasmer-compiler-cranelift`] provides the right balance between + compilation-time and runtime performance, useful for development, + * [`wasmer-compiler-llvm`] provides a deeply optimized executable + code with the fastest runtime speed, ideal for production. + +* **Headless mode** — Once a WebAssembly module has been compiled, it + is possible to serialize it in a file for example, and later execute + it with Wasmer with headless mode turned on. Headless Wasmer has no + compiler, which makes it more portable and faster to load. It's + ideal for constrainted environments. + +* **Cross-compilation** — Most compilers support cross-compilation. It + means it possible to pre-compile a WebAssembly module targetting a + different architecture or platform and serialize it, to then run it + on the targetted architecture and platform later. + +* **Run Wasmer in a JavaScript environment** — With the `js` Cargo + feature, it is possible to compile a Rust program using Wasmer to + WebAssembly. In this context, the resulting WebAssembly module will + expect to run in a JavaScript environment, like a browser, Node.js, + Deno and so on. In this specific scenario, there is no engines or + compilers available, it's the one available in the JavaScript + environment that will be used. + +Wasmer ships by default with the Cranelift compiler as its great for +development purposes. However, we strongly encourage to use the LLVM +compiler in production as it performs about 50% faster, achieving +near-native speeds. + +Note: if one wants to use multiple compilers at the same time, it's +also possible! One will need to import them directly via each of the +compiler crates. + +Read [the documentation to learn +more](https://wasmerio.github.io/wasmer/crates/doc/wasmer/). --- Made with ❤️ by the Wasmer team, for the community + +[`wasmer-engine-universal`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-universal +[`wasmer-engine-dylib`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-dylib +[`wasmer-engine-staticlib`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-staticlib +[`wasmer-compiler-singlepass`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-singlepass +[`wasmer-compiler-cranelift`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-cranelift +[`wasmer-compiler-llvm`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-llvm diff --git a/lib/api/src/js/cell.rs b/lib/api/src/js/cell.rs new file mode 100644 index 00000000000..b8c41507928 --- /dev/null +++ b/lib/api/src/js/cell.rs @@ -0,0 +1,140 @@ +use core::cmp::Ordering; +use core::fmt::{self, Debug}; +use std::marker::PhantomData; + +use js_sys::Uint8Array; + +/// A mutable Wasm-memory location. +pub struct WasmCell<'a, T: ?Sized> { + pub(crate) memory: Uint8Array, + #[allow(dead_code)] + phantom: &'a PhantomData, +} + +unsafe impl Send for WasmCell<'_, T> where T: Send {} + +unsafe impl Sync for WasmCell<'_, T> {} + +impl<'a, T: Copy> Clone for WasmCell<'a, T> { + #[inline] + fn clone(&self) -> WasmCell<'a, T> { + WasmCell { + memory: self.memory.clone(), + phantom: &PhantomData, + } + } +} + +impl PartialEq for WasmCell<'_, T> { + #[inline] + fn eq(&self, other: &WasmCell) -> bool { + self.get() == other.get() + } +} + +impl Eq for WasmCell<'_, T> {} + +impl PartialOrd for WasmCell<'_, T> { + #[inline] + fn partial_cmp(&self, other: &WasmCell) -> Option { + self.get().partial_cmp(&other.get()) + } + + #[inline] + fn lt(&self, other: &WasmCell) -> bool { + self.get() < other.get() + } + + #[inline] + fn le(&self, other: &WasmCell) -> bool { + self.get() <= other.get() + } + + #[inline] + fn gt(&self, other: &WasmCell) -> bool { + self.get() > other.get() + } + + #[inline] + fn ge(&self, other: &WasmCell) -> bool { + self.get() >= other.get() + } +} + +impl Ord for WasmCell<'_, T> { + #[inline] + fn cmp(&self, other: &WasmCell) -> Ordering { + self.get().cmp(&other.get()) + } +} + +impl<'a, T> WasmCell<'a, T> { + /// Creates a new `WasmCell` containing the given value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// use wasmer::WasmCell; + /// + /// let cell = Cell::new(5); + /// let wasm_cell = WasmCell::new(&cell); + /// ``` + #[inline] + pub const fn new(memory: Uint8Array) -> WasmCell<'a, T> { + WasmCell { + memory, + phantom: &PhantomData, + } + } +} + +impl<'a, T: Copy> WasmCell<'a, T> { + /// Returns a copy of the contained value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// use wasmer::WasmCell; + /// + /// let cell = Cell::new(5); + /// let wasm_cell = WasmCell::new(&cell); + /// let five = wasm_cell.get(); + /// ``` + #[inline] + pub fn get(&self) -> T { + let vec = self.memory.to_vec(); + unsafe { *(vec.as_ptr() as *const T) } + } +} + +impl Debug for WasmCell<'_, T> { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "WasmCell({:?})", self.get()) + } +} + +impl WasmCell<'_, T> { + /// Sets the contained value. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// use wasmer::WasmCell; + /// + /// let cell = Cell::new(5); + /// let wasm_cell = WasmCell::new(&cell); + /// wasm_cell.set(10); + /// assert_eq!(cell.get(), 10); + /// ``` + #[inline] + pub fn set(&self, val: T) { + let size = std::mem::size_of::(); + let ptr = &val as *const T as *const u8; + let slice = unsafe { std::slice::from_raw_parts(ptr, size) }; + self.memory.copy_from(slice); + } +} diff --git a/lib/api/src/js/env.rs b/lib/api/src/js/env.rs new file mode 100644 index 00000000000..30db0fb3c83 --- /dev/null +++ b/lib/api/src/js/env.rs @@ -0,0 +1,219 @@ +use crate::js::{ExportError, Instance}; +use thiserror::Error; + +/// An error while initializing the user supplied host env with the `WasmerEnv` trait. +#[derive(Error, Debug)] +#[error("Host env initialization error: {0}")] +pub enum HostEnvInitError { + /// An error occurred when accessing an export + Export(ExportError), +} + +impl From for HostEnvInitError { + fn from(other: ExportError) -> Self { + Self::Export(other) + } +} + +/// Trait for initializing the environments passed to host functions after +/// instantiation but before execution. +/// +/// This is useful for filling an environment with data that can only be accesed +/// after instantiation. For example, exported items such as memories and +/// functions which don't exist prior to instantiation can be accessed here so +/// that host functions can use them. +/// +/// # Examples +/// +/// This trait can be derived like so: +/// +/// ``` +/// use wasmer::{WasmerEnv, LazyInit, Memory, NativeFunc}; +/// +/// #[derive(WasmerEnv, Clone)] +/// pub struct MyEnvWithNoInstanceData { +/// non_instance_data: u8, +/// } +/// +/// #[derive(WasmerEnv, Clone)] +/// pub struct MyEnvWithInstanceData { +/// non_instance_data: u8, +/// #[wasmer(export)] +/// memory: LazyInit, +/// #[wasmer(export(name = "real_name"))] +/// func: LazyInit>, +/// #[wasmer(export(optional = true, alias = "memory2", alias = "_memory2"))] +/// optional_memory: LazyInit, +/// } +/// ``` +/// +/// When deriving `WasmerEnv`, you must wrap your types to be initialized in +/// [`LazyInit`]. The derive macro will also generate helper methods of the form +/// `_ref` and `_ref_unchecked` for easy access to the +/// data. +/// +/// The valid arguments to `export` are: +/// - `name = "string"`: specify the name of this item in the Wasm module. If this is not specified, it will default to the name of the field. +/// - `optional = true`: specify whether this export is optional. Defaults to +/// `false`. Being optional means that if the export can't be found, the +/// [`LazyInit`] will be left uninitialized. +/// - `alias = "string"`: specify additional names to look for in the Wasm module. +/// `alias` may be specified multiple times to search for multiple aliases. +/// ------- +/// +/// This trait may also be implemented manually: +/// ``` +/// # use wasmer::{WasmerEnv, LazyInit, Memory, Instance, HostEnvInitError}; +/// #[derive(Clone)] +/// pub struct MyEnv { +/// memory: LazyInit, +/// } +/// +/// impl WasmerEnv for MyEnv { +/// fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> { +/// let memory: Memory = instance.exports.get_with_generics_weak("memory").unwrap(); +/// self.memory.initialize(memory.clone()); +/// Ok(()) +/// } +/// } +/// ``` +pub trait WasmerEnv { + /// The function that Wasmer will call on your type to let it finish + /// setting up the environment with data from the `Instance`. + /// + /// This function is called after `Instance` is created but before it is + /// returned to the user via `Instance::new`. + fn init_with_instance(&mut self, _instance: &Instance) -> Result<(), HostEnvInitError> { + Ok(()) + } +} + +impl WasmerEnv for u8 {} +impl WasmerEnv for i8 {} +impl WasmerEnv for u16 {} +impl WasmerEnv for i16 {} +impl WasmerEnv for u32 {} +impl WasmerEnv for i32 {} +impl WasmerEnv for u64 {} +impl WasmerEnv for i64 {} +impl WasmerEnv for u128 {} +impl WasmerEnv for i128 {} +impl WasmerEnv for f32 {} +impl WasmerEnv for f64 {} +impl WasmerEnv for usize {} +impl WasmerEnv for isize {} +impl WasmerEnv for char {} +impl WasmerEnv for bool {} +impl WasmerEnv for String {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicBool {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicI8 {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicU8 {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicI16 {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicU16 {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicI32 {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicU32 {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicI64 {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicUsize {} +impl<'a> WasmerEnv for &'a ::std::sync::atomic::AtomicIsize {} +impl WasmerEnv for Box { + fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> { + (&mut **self).init_with_instance(instance) + } +} + +impl WasmerEnv for ::std::sync::Arc<::std::sync::Mutex> { + fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> { + let mut guard = self.lock().unwrap(); + guard.init_with_instance(instance) + } +} + +/// Lazily init an item +pub struct LazyInit { + /// The data to be initialized + data: std::mem::MaybeUninit, + /// Whether or not the data has been initialized + initialized: bool, +} + +impl LazyInit { + /// Creates an unitialized value. + pub fn new() -> Self { + Self { + data: std::mem::MaybeUninit::uninit(), + initialized: false, + } + } + + /// # Safety + /// - The data must be initialized first + pub unsafe fn get_unchecked(&self) -> &T { + &*self.data.as_ptr() + } + + /// Get the inner data. + pub fn get_ref(&self) -> Option<&T> { + if !self.initialized { + None + } else { + Some(unsafe { self.get_unchecked() }) + } + } + + /// Sets a value and marks the data as initialized. + pub fn initialize(&mut self, value: T) -> bool { + if self.initialized { + return false; + } + unsafe { + self.data.as_mut_ptr().write(value); + } + self.initialized = true; + true + } +} + +impl std::fmt::Debug for LazyInit { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.debug_struct("LazyInit") + .field("data", &self.get_ref()) + .finish() + } +} + +impl Clone for LazyInit { + fn clone(&self) -> Self { + if let Some(inner) = self.get_ref() { + Self { + data: std::mem::MaybeUninit::new(inner.clone()), + initialized: true, + } + } else { + Self { + data: std::mem::MaybeUninit::uninit(), + initialized: false, + } + } + } +} + +impl Drop for LazyInit { + fn drop(&mut self) { + if self.initialized { + unsafe { + let ptr = self.data.as_mut_ptr(); + std::ptr::drop_in_place(ptr); + }; + } + } +} + +impl Default for LazyInit { + fn default() -> Self { + Self::new() + } +} + +unsafe impl Send for LazyInit {} +// I thought we could opt out of sync..., look into this +// unsafe impl !Sync for InitWithInstance {} diff --git a/lib/api/src/js/error.rs b/lib/api/src/js/error.rs new file mode 100644 index 00000000000..205cf2de946 --- /dev/null +++ b/lib/api/src/js/error.rs @@ -0,0 +1,89 @@ +use crate::js::lib::std::string::String; +#[cfg(feature = "std")] +use thiserror::Error; + +// Compilation Errors +// +// If `std` feature is enable, we can't use `thiserror` until +// https://github.com/dtolnay/thiserror/pull/64 is merged. + +/// The WebAssembly.CompileError object indicates an error during +/// WebAssembly decoding or validation. +/// +/// This is based on the [Wasm Compile Error][compile-error] API. +/// +/// [compiler-error]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError +#[derive(Debug)] +#[cfg_attr(feature = "std", derive(Error))] +pub enum CompileError { + /// A Wasm translation error occured. + #[cfg_attr(feature = "std", error("WebAssembly translation error: {0}"))] + Wasm(WasmError), + + /// A compilation error occured. + #[cfg_attr(feature = "std", error("Compilation error: {0}"))] + Codegen(String), + + /// The module did not pass validation. + #[cfg_attr(feature = "std", error("Validation error: {0}"))] + Validate(String), + + /// The compiler doesn't support a Wasm feature + #[cfg_attr(feature = "std", error("Feature {0} is not yet supported"))] + UnsupportedFeature(String), + + /// The compiler cannot compile for the given target. + /// This can refer to the OS, the chipset or any other aspect of the target system. + #[cfg_attr(feature = "std", error("The target {0} is not yet supported (see https://docs.wasmer.io/ecosystem/wasmer/wasmer-features)"))] + UnsupportedTarget(String), + + /// Insufficient resources available for execution. + #[cfg_attr(feature = "std", error("Insufficient resources: {0}"))] + Resource(String), +} + +#[cfg(feature = "core")] +impl std::fmt::Display for CompileError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "CompileError") + } +} + +impl From for CompileError { + fn from(original: WasmError) -> Self { + Self::Wasm(original) + } +} + +/// A WebAssembly translation error. +/// +/// When a WebAssembly function can't be translated, one of these error codes will be returned +/// to describe the failure. +#[derive(Debug)] +#[cfg_attr(feature = "std", derive(Error))] +pub enum WasmError { + /// The input WebAssembly code is invalid. + /// + /// This error code is used by a WebAssembly translator when it encounters invalid WebAssembly + /// code. This should never happen for validated WebAssembly code. + #[cfg_attr( + feature = "std", + error("Invalid input WebAssembly code at offset {offset}: {message}") + )] + InvalidWebAssembly { + /// A string describing the validation error. + message: String, + /// The bytecode offset where the error occurred. + offset: usize, + }, + + /// A feature used by the WebAssembly code is not supported by the embedding environment. + /// + /// Embedding environments may have their own limitations and feature restrictions. + #[cfg_attr(feature = "std", error("Unsupported feature: {0}"))] + Unsupported(String), + + /// A generic error. + #[cfg_attr(feature = "std", error("{0}"))] + Generic(String), +} diff --git a/lib/api/src/js/export.rs b/lib/api/src/js/export.rs new file mode 100644 index 00000000000..06f72ed3e84 --- /dev/null +++ b/lib/api/src/js/export.rs @@ -0,0 +1,162 @@ +use crate::js::instance::Instance; +use crate::js::wasm_bindgen_polyfill::Global; +use crate::js::HostEnvInitError; +use crate::js::WasmerEnv; +use js_sys::Function; +use js_sys::WebAssembly::{Memory, Table}; +use std::cell::RefCell; +use std::fmt; +use std::sync::Arc; +use wasm_bindgen::{JsCast, JsValue}; +use wasmer_types::{ExternType, FunctionType, GlobalType, MemoryType, TableType}; + +#[derive(Clone, Debug, PartialEq)] +pub struct VMMemory { + pub(crate) memory: Memory, + pub(crate) ty: MemoryType, +} + +impl VMMemory { + pub(crate) fn new(memory: Memory, ty: MemoryType) -> Self { + Self { memory, ty } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct VMGlobal { + pub(crate) global: Global, + pub(crate) ty: GlobalType, +} + +impl VMGlobal { + pub(crate) fn new(global: Global, ty: GlobalType) -> Self { + Self { global, ty } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct VMTable { + pub(crate) table: Table, + pub(crate) ty: TableType, +} + +impl VMTable { + pub(crate) fn new(table: Table, ty: TableType) -> Self { + Self { table, ty } + } +} + +#[derive(Clone)] +pub struct VMFunction { + pub(crate) function: Function, + pub(crate) ty: FunctionType, + pub(crate) environment: Option>>>, +} + +impl VMFunction { + pub(crate) fn new( + function: Function, + ty: FunctionType, + environment: Option>, + ) -> Self { + Self { + function, + ty, + environment: environment.map(|env| Arc::new(RefCell::new(env))), + } + } + + pub(crate) fn init_envs(&self, instance: &Instance) -> Result<(), HostEnvInitError> { + if let Some(env) = &self.environment { + let mut borrowed_env = env.borrow_mut(); + borrowed_env.init_with_instance(instance)?; + } + Ok(()) + } +} + +impl PartialEq for VMFunction { + fn eq(&self, other: &Self) -> bool { + self.function == other.function + } +} + +impl fmt::Debug for VMFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("VMFunction") + .field("function", &self.function) + .finish() + } +} + +/// The value of an export passed from one instance to another. +#[derive(Debug, Clone)] +pub enum Export { + /// A function export value. + Function(VMFunction), + + /// A table export value. + Table(VMTable), + + /// A memory export value. + Memory(VMMemory), + + /// A global export value. + Global(VMGlobal), +} + +impl Export { + pub fn as_jsvalue(&self) -> &JsValue { + match self { + Export::Memory(js_wasm_memory) => js_wasm_memory.memory.as_ref(), + Export::Function(js_func) => js_func.function.as_ref(), + Export::Table(js_wasm_table) => js_wasm_table.table.as_ref(), + Export::Global(js_wasm_global) => js_wasm_global.global.as_ref(), + } + } +} + +impl From<(JsValue, ExternType)> for Export { + fn from((val, extern_type): (JsValue, ExternType)) -> Export { + match extern_type { + ExternType::Memory(memory_type) => { + if val.is_instance_of::() { + return Export::Memory(VMMemory::new( + val.unchecked_into::(), + memory_type, + )); + } else { + panic!("Extern type doesn't match js value type"); + } + } + ExternType::Global(global_type) => { + if val.is_instance_of::() { + return Export::Global(VMGlobal::new( + val.unchecked_into::(), + global_type, + )); + } else { + panic!("Extern type doesn't match js value type"); + } + } + ExternType::Function(function_type) => { + if val.is_instance_of::() { + return Export::Function(VMFunction::new( + val.unchecked_into::(), + function_type, + None, + )); + } else { + panic!("Extern type doesn't match js value type"); + } + } + ExternType::Table(table_type) => { + if val.is_instance_of::() { + return Export::Table(VMTable::new(val.unchecked_into::
(), table_type)); + } else { + panic!("Extern type doesn't match js value type"); + } + } + } + } +} diff --git a/lib/api/src/js/exports.rs b/lib/api/src/js/exports.rs new file mode 100644 index 00000000000..98cca5f9d62 --- /dev/null +++ b/lib/api/src/js/exports.rs @@ -0,0 +1,324 @@ +use crate::js::export::Export; +use crate::js::externals::{Extern, Function, Global, Memory, Table}; +use crate::js::import_object::LikeNamespace; +use crate::js::native::NativeFunc; +use crate::js::WasmTypeList; +use indexmap::IndexMap; +use std::fmt; +use std::iter::{ExactSizeIterator, FromIterator}; +use std::sync::Arc; +use thiserror::Error; + +/// The `ExportError` can happen when trying to get a specific +/// export [`Extern`] from the [`Instance`] exports. +/// +/// [`Instance`]: crate::js::Instance +/// +/// # Examples +/// +/// ## Incompatible export type +/// +/// ```should_panic +/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; +/// # let store = Store::default(); +/// # let wasm_bytes = wat2wasm(r#" +/// # (module +/// # (global $one (export "glob") f32 (f32.const 1))) +/// # "#.as_bytes()).unwrap(); +/// # let module = Module::new(&store, wasm_bytes).unwrap(); +/// # let import_object = imports! {}; +/// # let instance = Instance::new(&module, &import_object).unwrap(); +/// # +/// // This results with an error: `ExportError::IncompatibleType`. +/// let export = instance.exports.get_function("glob").unwrap(); +/// ``` +/// +/// ## Missing export +/// +/// ```should_panic +/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; +/// # let store = Store::default(); +/// # let wasm_bytes = wat2wasm("(module)".as_bytes()).unwrap(); +/// # let module = Module::new(&store, wasm_bytes).unwrap(); +/// # let import_object = imports! {}; +/// # let instance = Instance::new(&module, &import_object).unwrap(); +/// # +/// // This results with an error: `ExportError::Missing`. +/// let export = instance.exports.get_function("unknown").unwrap(); +/// ``` +#[derive(Error, Debug)] +pub enum ExportError { + /// An error than occurs when the exported type and the expected type + /// are incompatible. + #[error("Incompatible Export Type")] + IncompatibleType, + /// This error arises when an export is missing + #[error("Missing export {0}")] + Missing(String), +} + +/// Exports is a special kind of map that allows easily unwrapping +/// the types of instances. +/// +/// TODO: add examples of using exports +#[derive(Clone, Default)] +pub struct Exports { + map: Arc>, +} + +impl Exports { + /// Creates a new `Exports`. + pub fn new() -> Self { + Default::default() + } + + /// Creates a new `Exports` with capacity `n`. + pub fn with_capacity(n: usize) -> Self { + Self { + map: Arc::new(IndexMap::with_capacity(n)), + } + } + + /// Return the number of exports in the `Exports` map. + pub fn len(&self) -> usize { + self.map.len() + } + + /// Return whether or not there are no exports + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Insert a new export into this `Exports` map. + pub fn insert(&mut self, name: S, value: E) + where + S: Into, + E: Into, + { + Arc::get_mut(&mut self.map) + .unwrap() + .insert(name.into(), value.into()); + } + + /// Get an export given a `name`. + /// + /// The `get` method is specifically made for usage inside of + /// Rust APIs, as we can detect what's the desired type easily. + /// + /// If you want to get an export dynamically with type checking + /// please use the following functions: `get_func`, `get_memory`, + /// `get_table` or `get_global` instead. + /// + /// If you want to get an export dynamically handling manually + /// type checking manually, please use `get_extern`. + pub fn get<'a, T: Exportable<'a>>(&'a self, name: &str) -> Result<&'a T, ExportError> { + match self.map.get(name) { + None => Err(ExportError::Missing(name.to_string())), + Some(extern_) => T::get_self_from_extern(extern_), + } + } + + /// Get an export as a `Global`. + pub fn get_global(&self, name: &str) -> Result<&Global, ExportError> { + self.get(name) + } + + /// Get an export as a `Memory`. + pub fn get_memory(&self, name: &str) -> Result<&Memory, ExportError> { + self.get(name) + } + + /// Get an export as a `Table`. + pub fn get_table(&self, name: &str) -> Result<&Table, ExportError> { + self.get(name) + } + + /// Get an export as a `Func`. + pub fn get_function(&self, name: &str) -> Result<&Function, ExportError> { + self.get(name) + } + + /// Get an export as a `NativeFunc`. + pub fn get_native_function( + &self, + name: &str, + ) -> Result, ExportError> + where + Args: WasmTypeList, + Rets: WasmTypeList, + { + self.get_function(name)? + .native() + .map_err(|_| ExportError::IncompatibleType) + } + + /// Hack to get this working with nativefunc too + pub fn get_with_generics<'a, T, Args, Rets>(&'a self, name: &str) -> Result + where + Args: WasmTypeList, + Rets: WasmTypeList, + T: ExportableWithGenerics<'a, Args, Rets>, + { + match self.map.get(name) { + None => Err(ExportError::Missing(name.to_string())), + Some(extern_) => T::get_self_from_extern_with_generics(extern_), + } + } + + /// Like `get_with_generics` but with a WeakReference to the `InstanceRef` internally. + /// This is useful for passing data into `WasmerEnv`, for example. + pub fn get_with_generics_weak<'a, T, Args, Rets>(&'a self, name: &str) -> Result + where + Args: WasmTypeList, + Rets: WasmTypeList, + T: ExportableWithGenerics<'a, Args, Rets>, + { + let out: T = self.get_with_generics(name)?; + Ok(out) + } + + /// Get an export as an `Extern`. + pub fn get_extern(&self, name: &str) -> Option<&Extern> { + self.map.get(name) + } + + /// Returns true if the `Exports` contains the given export name. + pub fn contains(&self, name: S) -> bool + where + S: Into, + { + self.map.contains_key(&name.into()) + } + + /// Get an iterator over the exports. + pub fn iter(&self) -> ExportsIterator> { + ExportsIterator { + iter: self.map.iter(), + } + } +} + +impl fmt::Debug for Exports { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_set().entries(self.iter()).finish() + } +} + +/// An iterator over exports. +pub struct ExportsIterator<'a, I> +where + I: Iterator + Sized, +{ + iter: I, +} + +impl<'a, I> Iterator for ExportsIterator<'a, I> +where + I: Iterator + Sized, +{ + type Item = (&'a String, &'a Extern); + + fn next(&mut self) -> Option { + self.iter.next() + } +} + +impl<'a, I> ExactSizeIterator for ExportsIterator<'a, I> +where + I: Iterator + ExactSizeIterator + Sized, +{ + fn len(&self) -> usize { + self.iter.len() + } +} + +impl<'a, I> ExportsIterator<'a, I> +where + I: Iterator + Sized, +{ + /// Get only the functions. + pub fn functions(self) -> impl Iterator + Sized { + self.iter.filter_map(|(name, export)| match export { + Extern::Function(function) => Some((name, function)), + _ => None, + }) + } + + /// Get only the memories. + pub fn memories(self) -> impl Iterator + Sized { + self.iter.filter_map(|(name, export)| match export { + Extern::Memory(memory) => Some((name, memory)), + _ => None, + }) + } + + /// Get only the globals. + pub fn globals(self) -> impl Iterator + Sized { + self.iter.filter_map(|(name, export)| match export { + Extern::Global(global) => Some((name, global)), + _ => None, + }) + } + + /// Get only the tables. + pub fn tables(self) -> impl Iterator + Sized { + self.iter.filter_map(|(name, export)| match export { + Extern::Table(table) => Some((name, table)), + _ => None, + }) + } +} + +impl FromIterator<(String, Extern)> for Exports { + fn from_iter>(iter: I) -> Self { + Self { + map: Arc::new(IndexMap::from_iter(iter)), + } + } +} + +impl LikeNamespace for Exports { + fn get_namespace_export(&self, name: &str) -> Option { + self.map.get(name).map(|is_export| is_export.to_export()) + } + + fn get_namespace_exports(&self) -> Vec<(String, Export)> { + self.map + .iter() + .map(|(k, v)| (k.clone(), v.to_export())) + .collect() + } +} + +/// This trait is used to mark types as gettable from an [`Instance`]. +/// +/// [`Instance`]: crate::js::Instance +pub trait Exportable<'a>: Sized { + /// This function is used when providedd the [`Extern`] as exportable, so it + /// can be used while instantiating the [`Module`]. + /// + /// [`Module`]: crate::js::Module + fn to_export(&self) -> Export; + + /// Implementation of how to get the export corresponding to the implementing type + /// from an [`Instance`] by name. + /// + /// [`Instance`]: crate::js::Instance + fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError>; +} + +/// A trait for accessing exports (like [`Exportable`]) but it takes generic +/// `Args` and `Rets` parameters so that `NativeFunc` can be accessed directly +/// as well. +pub trait ExportableWithGenerics<'a, Args: WasmTypeList, Rets: WasmTypeList>: Sized { + /// Get an export with the given generics. + fn get_self_from_extern_with_generics(_extern: &'a Extern) -> Result; +} + +/// We implement it for all concrete [`Exportable`] types (that are `Clone`) +/// with empty `Args` and `Rets`. +impl<'a, T: Exportable<'a> + Clone + 'static> ExportableWithGenerics<'a, (), ()> for T { + fn get_self_from_extern_with_generics(_extern: &'a Extern) -> Result { + T::get_self_from_extern(_extern).map(|i| i.clone()) + } +} diff --git a/lib/api/src/js/externals/function.rs b/lib/api/src/js/externals/function.rs new file mode 100644 index 00000000000..d9ccea88be4 --- /dev/null +++ b/lib/api/src/js/externals/function.rs @@ -0,0 +1,1400 @@ +use crate::js::exports::{ExportError, Exportable}; +use crate::js::externals::Extern; +use crate::js::store::Store; +use crate::js::types::{param_from_js, AsJs /* ValFuncRef */, Val}; +use crate::js::FunctionType; +use crate::js::NativeFunc; +use crate::js::RuntimeError; +use crate::js::WasmerEnv; +pub use inner::{FromToNativeWasmType, HostFunction, WasmTypeList, WithEnv, WithoutEnv}; +use js_sys::{Array, Function as JSFunction}; +use std::iter::FromIterator; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; + +use crate::js::export::{Export, VMFunction}; +use std::fmt; + +#[repr(C)] +pub struct VMFunctionBody(u8); + +#[inline] +fn result_to_js(val: &Val) -> JsValue { + match val { + Val::I32(i) => JsValue::from_f64(*i as _), + Val::I64(i) => JsValue::from_f64(*i as _), + Val::F32(f) => JsValue::from_f64(*f as _), + Val::F64(f) => JsValue::from_f64(*f), + val => unimplemented!( + "The value `{:?}` is not yet supported in the JS Function API", + val + ), + } +} + +#[inline] +fn results_to_js_array(values: &[Val]) -> Array { + Array::from_iter(values.iter().map(result_to_js)) +} + +/// A WebAssembly `function` instance. +/// +/// A function instance is the runtime representation of a function. +/// It effectively is a closure of the original function (defined in either +/// the host or the WebAssembly module) over the runtime `Instance` of its +/// originating `Module`. +/// +/// The module instance is used to resolve references to other definitions +/// during execution of the function. +/// +/// Spec: +/// +/// # Panics +/// - Closures (functions with captured environments) are not currently supported +/// with native functions. Attempting to create a native `Function` with one will +/// result in a panic. +/// [Closures as host functions tracking issue](https://github.com/wasmerio/wasmer/issues/1840) +#[derive(Clone, PartialEq)] +pub struct Function { + pub(crate) store: Store, + pub(crate) exported: VMFunction, +} + +impl WasmerEnv for WithoutEnv {} + +impl Function { + /// Creates a new host `Function` (dynamic) with the provided signature. + /// + /// If you know the signature of the host function at compile time, + /// consider using [`Function::new_native`] for less runtime overhead. + /// + /// # Examples + /// + /// ``` + /// # use wasmer::{Function, FunctionType, Type, Store, Value}; + /// # let store = Store::default(); + /// # + /// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]); + /// + /// let f = Function::new(&store, &signature, |args| { + /// let sum = args[0].unwrap_i32() + args[1].unwrap_i32(); + /// Ok(vec![Value::I32(sum)]) + /// }); + /// ``` + /// + /// With constant signature: + /// + /// ``` + /// # use wasmer::{Function, FunctionType, Type, Store, Value}; + /// # let store = Store::default(); + /// # + /// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]); + /// + /// let f = Function::new(&store, I32_I32_TO_I32, |args| { + /// let sum = args[0].unwrap_i32() + args[1].unwrap_i32(); + /// Ok(vec![Value::I32(sum)]) + /// }); + /// ``` + #[allow(clippy::cast_ptr_alignment)] + pub fn new(store: &Store, ty: FT, func: F) -> Self + where + FT: Into, + F: Fn(&[Val]) -> Result, RuntimeError> + 'static + Send + Sync, + { + let ty = ty.into(); + let new_ty = ty.clone(); + + let wrapped_func: JsValue = match ty.results().len() { + 0 => Closure::wrap(Box::new(move |args: &Array| { + let wasm_arguments = new_ty + .params() + .iter() + .enumerate() + .map(|(i, param)| param_from_js(param, &args.get(i as u32))) + .collect::>(); + let _results = func(&wasm_arguments)?; + Ok(()) + }) + as Box Result<(), JsValue>>) + .into_js_value(), + 1 => Closure::wrap(Box::new(move |args: &Array| { + let wasm_arguments = new_ty + .params() + .iter() + .enumerate() + .map(|(i, param)| param_from_js(param, &args.get(i as u32))) + .collect::>(); + let results = func(&wasm_arguments)?; + return Ok(result_to_js(&results[0])); + }) + as Box Result>) + .into_js_value(), + _n => Closure::wrap(Box::new(move |args: &Array| { + let wasm_arguments = new_ty + .params() + .iter() + .enumerate() + .map(|(i, param)| param_from_js(param, &args.get(i as u32))) + .collect::>(); + let results = func(&wasm_arguments)?; + return Ok(results_to_js_array(&results)); + }) + as Box Result>) + .into_js_value(), + }; + + let dyn_func = + JSFunction::new_with_args("f", "return f(Array.prototype.slice.call(arguments, 1))"); + let binded_func = dyn_func.bind1(&JsValue::UNDEFINED, &wrapped_func); + Self { + store: store.clone(), + exported: VMFunction::new(binded_func, ty, None), + } + } + + /// Creates a new host `Function` (dynamic) with the provided signature and environment. + /// + /// If you know the signature of the host function at compile time, + /// consider using [`Function::new_native_with_env`] for less runtime + /// overhead. + /// + /// # Examples + /// + /// ``` + /// # use wasmer::{Function, FunctionType, Type, Store, Value, WasmerEnv}; + /// # let store = Store::default(); + /// # + /// #[derive(WasmerEnv, Clone)] + /// struct Env { + /// multiplier: i32, + /// }; + /// let env = Env { multiplier: 2 }; + /// + /// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]); + /// + /// let f = Function::new_with_env(&store, &signature, env, |env, args| { + /// let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32()); + /// Ok(vec![Value::I32(result)]) + /// }); + /// ``` + /// + /// With constant signature: + /// + /// ``` + /// # use wasmer::{Function, FunctionType, Type, Store, Value, WasmerEnv}; + /// # let store = Store::default(); + /// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]); + /// + /// #[derive(WasmerEnv, Clone)] + /// struct Env { + /// multiplier: i32, + /// }; + /// let env = Env { multiplier: 2 }; + /// + /// let f = Function::new_with_env(&store, I32_I32_TO_I32, env, |env, args| { + /// let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32()); + /// Ok(vec![Value::I32(result)]) + /// }); + /// ``` + #[allow(clippy::cast_ptr_alignment)] + pub fn new_with_env(store: &Store, ty: FT, env: Env, func: F) -> Self + where + FT: Into, + F: Fn(&Env, &[Val]) -> Result, RuntimeError> + 'static + Send + Sync, + Env: Sized + WasmerEnv + 'static, + { + let ty = ty.into(); + let new_ty = ty.clone(); + + let wrapped_func: JsValue = match ty.results().len() { + 0 => Closure::wrap(Box::new(move |args: &Array| { + let wasm_arguments = new_ty + .params() + .iter() + .enumerate() + .map(|(i, param)| param_from_js(param, &args.get(i as u32 + 1))) + .collect::>(); + let env_ptr = args.get(0).as_f64().unwrap() as usize; + let env: &Env = unsafe { &*(env_ptr as *const u8 as *const Env) }; + let _results = func(env, &wasm_arguments)?; + Ok(()) + }) + as Box Result<(), JsValue>>) + .into_js_value(), + 1 => Closure::wrap(Box::new(move |args: &Array| { + let wasm_arguments = new_ty + .params() + .iter() + .enumerate() + .map(|(i, param)| param_from_js(param, &args.get(i as u32 + 1))) + .collect::>(); + let env_ptr = args.get(0).as_f64().unwrap() as usize; + let env: &Env = unsafe { &*(env_ptr as *const u8 as *const Env) }; + let results = func(env, &wasm_arguments)?; + return Ok(result_to_js(&results[0])); + }) + as Box Result>) + .into_js_value(), + _n => Closure::wrap(Box::new(move |args: &Array| { + let wasm_arguments = new_ty + .params() + .iter() + .enumerate() + .map(|(i, param)| param_from_js(param, &args.get(i as u32 + 1))) + .collect::>(); + let env_ptr = args.get(0).as_f64().unwrap() as usize; + let env: &Env = unsafe { &*(env_ptr as *const u8 as *const Env) }; + let results = func(env, &wasm_arguments)?; + return Ok(results_to_js_array(&results)); + }) + as Box Result>) + .into_js_value(), + }; + + let dyn_func = + JSFunction::new_with_args("f", "return f(Array.prototype.slice.call(arguments, 1))"); + + let environment = Box::new(env); + let binded_func = dyn_func.bind2( + &JsValue::UNDEFINED, + &wrapped_func, + &JsValue::from_f64(&*environment as *const Env as *const u8 as usize as f64), + ); + Self { + store: store.clone(), + exported: VMFunction::new(binded_func, ty, Some(environment)), + } + } + + /// Creates a new host `Function` from a native function. + /// + /// The function signature is automatically retrieved using the + /// Rust typing system. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Store, Function}; + /// # let store = Store::default(); + /// # + /// fn sum(a: i32, b: i32) -> i32 { + /// a + b + /// } + /// + /// let f = Function::new_native(&store, sum); + /// ``` + pub fn new_native(store: &Store, func: F) -> Self + where + F: HostFunction, + Args: WasmTypeList, + Rets: WasmTypeList, + Env: Sized + 'static, + { + if std::mem::size_of::() != 0 { + Self::closures_unsupported_panic(); + } + let function = inner::Function::::new(func); + let address = function.address() as usize as u32; + + let ft = wasm_bindgen::function_table(); + let as_table = ft.unchecked_ref::(); + let func = as_table.get(address).unwrap(); + let binded_func = func.bind1(&JsValue::UNDEFINED, &JsValue::UNDEFINED); + let ty = function.ty(); + Self { + store: store.clone(), + exported: VMFunction::new(binded_func, ty, None), + } + } + + /// Creates a new host `Function` from a native function and a provided environment. + /// + /// The function signature is automatically retrieved using the + /// Rust typing system. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Store, Function, WasmerEnv}; + /// # let store = Store::default(); + /// # + /// #[derive(WasmerEnv, Clone)] + /// struct Env { + /// multiplier: i32, + /// }; + /// let env = Env { multiplier: 2 }; + /// + /// fn sum_and_multiply(env: &Env, a: i32, b: i32) -> i32 { + /// (a + b) * env.multiplier + /// } + /// + /// let f = Function::new_native_with_env(&store, env, sum_and_multiply); + /// ``` + pub fn new_native_with_env(store: &Store, env: Env, func: F) -> Self + where + F: HostFunction, + Args: WasmTypeList, + Rets: WasmTypeList, + Env: Sized + WasmerEnv + 'static, + { + if std::mem::size_of::() != 0 { + Self::closures_unsupported_panic(); + } + let function = inner::Function::::new(func); + let address = function.address() as usize as u32; + + let ft = wasm_bindgen::function_table(); + let as_table = ft.unchecked_ref::(); + let func = as_table.get(address).unwrap(); + let ty = function.ty(); + let environment = Box::new(env); + let binded_func = func.bind1( + &JsValue::UNDEFINED, + &JsValue::from_f64(&*environment as *const Env as *const u8 as usize as f64), + ); + // panic!("Function env {:?}", environment.type_id()); + Self { + store: store.clone(), + exported: VMFunction::new(binded_func, ty, Some(environment)), + } + } + + /// Returns the [`FunctionType`] of the `Function`. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Function, Store, Type}; + /// # let store = Store::default(); + /// # + /// fn sum(a: i32, b: i32) -> i32 { + /// a + b + /// } + /// + /// let f = Function::new_native(&store, sum); + /// + /// assert_eq!(f.ty().params(), vec![Type::I32, Type::I32]); + /// assert_eq!(f.ty().results(), vec![Type::I32]); + /// ``` + pub fn ty(&self) -> &FunctionType { + &self.exported.ty + } + + /// Returns the [`Store`] where the `Function` belongs. + pub fn store(&self) -> &Store { + &self.store + } + + /// Returns the number of parameters that this function takes. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Function, Store, Type}; + /// # let store = Store::default(); + /// # + /// fn sum(a: i32, b: i32) -> i32 { + /// a + b + /// } + /// + /// let f = Function::new_native(&store, sum); + /// + /// assert_eq!(f.param_arity(), 2); + /// ``` + pub fn param_arity(&self) -> usize { + self.ty().params().len() + } + + /// Returns the number of results this function produces. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Function, Store, Type}; + /// # let store = Store::default(); + /// # + /// fn sum(a: i32, b: i32) -> i32 { + /// a + b + /// } + /// + /// let f = Function::new_native(&store, sum); + /// + /// assert_eq!(f.result_arity(), 1); + /// ``` + pub fn result_arity(&self) -> usize { + self.ty().results().len() + } + + /// Call the `Function` function. + /// + /// Depending on where the Function is defined, it will call it. + /// 1. If the function is defined inside a WebAssembly, it will call the trampoline + /// for the function signature. + /// 2. If the function is defined in the host (in a native way), it will + /// call the trampoline. + /// + /// # Examples + /// + /// ``` + /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; + /// # let store = Store::default(); + /// # let wasm_bytes = wat2wasm(r#" + /// # (module + /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) + /// # local.get $x + /// # local.get $y + /// # i32.add + /// # )) + /// # "#.as_bytes()).unwrap(); + /// # let module = Module::new(&store, wasm_bytes).unwrap(); + /// # let import_object = imports! {}; + /// # let instance = Instance::new(&module, &import_object).unwrap(); + /// # + /// let sum = instance.exports.get_function("sum").unwrap(); + /// + /// assert_eq!(sum.call(&[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]); + /// ``` + pub fn call(&self, params: &[Val]) -> Result, RuntimeError> { + let arr = js_sys::Array::new_with_length(params.len() as u32); + for (i, param) in params.iter().enumerate() { + let js_value = param.as_jsvalue(); + arr.set(i as u32, js_value); + } + let result = + js_sys::Reflect::apply(&self.exported.function, &wasm_bindgen::JsValue::NULL, &arr)?; + + let result_types = self.exported.ty.results(); + match result_types.len() { + 0 => Ok(Box::new([])), + 1 => { + let value = param_from_js(&result_types[0], &result); + Ok(vec![value].into_boxed_slice()) + } + _n => { + let result_array: Array = result.into(); + Ok(result_array + .iter() + .enumerate() + .map(|(i, js_val)| param_from_js(&result_types[i], &js_val)) + .collect::>() + .into_boxed_slice()) + } + } + } + + pub(crate) fn from_vm_export(store: &Store, wasmer_export: VMFunction) -> Self { + Self { + store: store.clone(), + exported: wasmer_export, + } + } + + /// Transform this WebAssembly function into a function with the + /// native ABI. See [`NativeFunc`] to learn more. + /// + /// # Examples + /// + /// ``` + /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; + /// # let store = Store::default(); + /// # let wasm_bytes = wat2wasm(r#" + /// # (module + /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) + /// # local.get $x + /// # local.get $y + /// # i32.add + /// # )) + /// # "#.as_bytes()).unwrap(); + /// # let module = Module::new(&store, wasm_bytes).unwrap(); + /// # let import_object = imports! {}; + /// # let instance = Instance::new(&module, &import_object).unwrap(); + /// # + /// let sum = instance.exports.get_function("sum").unwrap(); + /// let sum_native = sum.native::<(i32, i32), i32>().unwrap(); + /// + /// assert_eq!(sum_native.call(1, 2).unwrap(), 3); + /// ``` + /// + /// # Errors + /// + /// If the `Args` generic parameter does not match the exported function + /// an error will be raised: + /// + /// ```should_panic + /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; + /// # let store = Store::default(); + /// # let wasm_bytes = wat2wasm(r#" + /// # (module + /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) + /// # local.get $x + /// # local.get $y + /// # i32.add + /// # )) + /// # "#.as_bytes()).unwrap(); + /// # let module = Module::new(&store, wasm_bytes).unwrap(); + /// # let import_object = imports! {}; + /// # let instance = Instance::new(&module, &import_object).unwrap(); + /// # + /// let sum = instance.exports.get_function("sum").unwrap(); + /// + /// // This results in an error: `RuntimeError` + /// let sum_native = sum.native::<(i64, i64), i32>().unwrap(); + /// ``` + /// + /// If the `Rets` generic parameter does not match the exported function + /// an error will be raised: + /// + /// ```should_panic + /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; + /// # let store = Store::default(); + /// # let wasm_bytes = wat2wasm(r#" + /// # (module + /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) + /// # local.get $x + /// # local.get $y + /// # i32.add + /// # )) + /// # "#.as_bytes()).unwrap(); + /// # let module = Module::new(&store, wasm_bytes).unwrap(); + /// # let import_object = imports! {}; + /// # let instance = Instance::new(&module, &import_object).unwrap(); + /// # + /// let sum = instance.exports.get_function("sum").unwrap(); + /// + /// // This results in an error: `RuntimeError` + /// let sum_native = sum.native::<(i32, i32), i64>().unwrap(); + /// ``` + pub fn native(&self) -> Result, RuntimeError> + where + Args: WasmTypeList, + Rets: WasmTypeList, + { + // type check + { + let expected = self.exported.ty.params(); + let given = Args::wasm_types(); + + if expected != given { + return Err(RuntimeError::new(format!( + "given types (`{:?}`) for the function arguments don't match the actual types (`{:?}`)", + given, + expected, + ))); + } + } + + { + let expected = self.exported.ty.results(); + let given = Rets::wasm_types(); + + if expected != given { + // todo: error result types don't match + return Err(RuntimeError::new(format!( + "given types (`{:?}`) for the function results don't match the actual types (`{:?}`)", + given, + expected, + ))); + } + } + + Ok(NativeFunc::new(self.store.clone(), self.exported.clone())) + } + + #[track_caller] + fn closures_unsupported_panic() -> ! { + unimplemented!("Closures (functions with captured environments) are currently unsupported with native functions. See: https://github.com/wasmerio/wasmer/issues/1840") + } +} + +impl<'a> Exportable<'a> for Function { + fn to_export(&self) -> Export { + Export::Function(self.exported.clone()) + } + + fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { + match _extern { + Extern::Function(func) => Ok(func), + _ => Err(ExportError::IncompatibleType), + } + } +} + +impl fmt::Debug for Function { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("Function") + .field("ty", &self.ty()) + .finish() + } +} + +// This is needed for reference types +impl wasmer_types::WasmValueType for Function { + /// Write the value. + unsafe fn write_value_to(&self, _p: *mut i128) { + unimplemented!(); + } + + /// Read the value. + unsafe fn read_value_from(_store: &dyn std::any::Any, _p: *const i128) -> Self { + unimplemented!(); + } +} + +/// This private inner module contains the low-level implementation +/// for `Function` and its siblings. +mod inner { + use super::VMFunctionBody; + use std::array::TryFromSliceError; + use std::convert::{Infallible, TryInto}; + use std::error::Error; + use std::marker::PhantomData; + use std::panic::{self, AssertUnwindSafe}; + + #[cfg(feature = "experimental-reference-types-extern-ref")] + pub use wasmer_types::{ExternRef, VMExternRef}; + use wasmer_types::{FunctionType, NativeWasmType, Type}; + // use wasmer::{raise_user_trap, resume_panic}; + + /// A trait to convert a Rust value to a `WasmNativeType` value, + /// or to convert `WasmNativeType` value to a Rust value. + /// + /// This trait should ideally be split into two traits: + /// `FromNativeWasmType` and `ToNativeWasmType` but it creates a + /// non-negligible complexity in the `WasmTypeList` + /// implementation. + pub unsafe trait FromToNativeWasmType + where + Self: Sized, + { + /// Native Wasm type. + type Native: NativeWasmType; + + /// Convert a value of kind `Self::Native` to `Self`. + /// + /// # Panics + /// + /// This method panics if `native` cannot fit in the `Self` + /// type`. + fn from_native(native: Self::Native) -> Self; + + /// Convert self to `Self::Native`. + /// + /// # Panics + /// + /// This method panics if `self` cannot fit in the + /// `Self::Native` type. + fn to_native(self) -> Self::Native; + } + + macro_rules! from_to_native_wasm_type { + ( $( $type:ty => $native_type:ty ),* ) => { + $( + #[allow(clippy::use_self)] + unsafe impl FromToNativeWasmType for $type { + type Native = $native_type; + + #[inline] + fn from_native(native: Self::Native) -> Self { + native as Self + } + + #[inline] + fn to_native(self) -> Self::Native { + self as Self::Native + } + } + )* + }; + } + + macro_rules! from_to_native_wasm_type_same_size { + ( $( $type:ty => $native_type:ty ),* ) => { + $( + #[allow(clippy::use_self)] + unsafe impl FromToNativeWasmType for $type { + type Native = $native_type; + + #[inline] + fn from_native(native: Self::Native) -> Self { + Self::from_ne_bytes(Self::Native::to_ne_bytes(native)) + } + + #[inline] + fn to_native(self) -> Self::Native { + Self::Native::from_ne_bytes(Self::to_ne_bytes(self)) + } + } + )* + }; + } + + from_to_native_wasm_type!( + i8 => i32, + u8 => i32, + i16 => i32, + u16 => i32 + ); + + from_to_native_wasm_type_same_size!( + i32 => i32, + u32 => i32, + i64 => i64, + u64 => i64, + f32 => f32, + f64 => f64 + ); + + #[cfg(feature = "experimental-reference-types-extern-ref")] + unsafe impl FromToNativeWasmType for ExternRef { + type Native = VMExternRef; + + fn to_native(self) -> Self::Native { + self.into() + } + fn from_native(n: Self::Native) -> Self { + n.into() + } + } + + #[cfg(test)] + mod test_from_to_native_wasm_type { + use super::*; + + #[test] + fn test_to_native() { + assert_eq!(7i8.to_native(), 7i32); + assert_eq!(7u8.to_native(), 7i32); + assert_eq!(7i16.to_native(), 7i32); + assert_eq!(7u16.to_native(), 7i32); + assert_eq!(u32::MAX.to_native(), -1); + } + + #[test] + fn test_to_native_same_size() { + assert_eq!(7i32.to_native(), 7i32); + assert_eq!(7u32.to_native(), 7i32); + assert_eq!(7i64.to_native(), 7i64); + assert_eq!(7u64.to_native(), 7i64); + assert_eq!(7f32.to_native(), 7f32); + assert_eq!(7f64.to_native(), 7f64); + } + } + + /// The `WasmTypeList` trait represents a tuple (list) of Wasm + /// typed values. It is used to get low-level representation of + /// such a tuple. + pub trait WasmTypeList + where + Self: Sized, + { + /// The C type (a struct) that can hold/represent all the + /// represented values. + type CStruct; + + /// The array type that can hold all the represented values. + /// + /// Note that all values are stored in their binary form. + type Array: AsMut<[i128]>; + + /// The size of the array + fn size() -> u32; + + /// Constructs `Self` based on an array of values. + fn from_array(array: Self::Array) -> Self; + + /// Constructs `Self` based on a slice of values. + /// + /// `from_slice` returns a `Result` because it is possible + /// that the slice doesn't have the same size than + /// `Self::Array`, in which circumstance an error of kind + /// `TryFromSliceError` will be returned. + fn from_slice(slice: &[i128]) -> Result; + + /// Builds and returns an array of type `Array` from a tuple + /// (list) of values. + fn into_array(self) -> Self::Array; + + /// Allocates and return an empty array of type `Array` that + /// will hold a tuple (list) of values, usually to hold the + /// returned values of a WebAssembly function call. + fn empty_array() -> Self::Array; + + /// Builds a tuple (list) of values from a C struct of type + /// `CStruct`. + fn from_c_struct(c_struct: Self::CStruct) -> Self; + + /// Builds and returns a C struct of type `CStruct` from a + /// tuple (list) of values. + fn into_c_struct(self) -> Self::CStruct; + + /// Get the Wasm types for the tuple (list) of currently + /// represented values. + fn wasm_types() -> &'static [Type]; + } + + /// The `IntoResult` trait turns a `WasmTypeList` into a + /// `Result`. + /// + /// It is mostly used to turn result values of a Wasm function + /// call into a `Result`. + pub trait IntoResult + where + T: WasmTypeList, + { + /// The error type for this trait. + type Error: Error + Sync + Send + 'static; + + /// Transforms `Self` into a `Result`. + fn into_result(self) -> Result; + } + + impl IntoResult for T + where + T: WasmTypeList, + { + // `T` is not a `Result`, it's already a value, so no error + // can be built. + type Error = Infallible; + + fn into_result(self) -> Result { + Ok(self) + } + } + + impl IntoResult for Result + where + T: WasmTypeList, + E: Error + Sync + Send + 'static, + { + type Error = E; + + fn into_result(self) -> Self { + self + } + } + + #[cfg(test)] + mod test_into_result { + use super::*; + use std::convert::Infallible; + + #[test] + fn test_into_result_over_t() { + let x: i32 = 42; + let result_of_x: Result = x.into_result(); + + assert_eq!(result_of_x.unwrap(), x); + } + + #[test] + fn test_into_result_over_result() { + { + let x: Result = Ok(42); + let result_of_x: Result = x.into_result(); + + assert_eq!(result_of_x, x); + } + + { + use std::{error, fmt}; + + #[derive(Debug, PartialEq)] + struct E; + + impl fmt::Display for E { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "E") + } + } + + impl error::Error for E {} + + let x: Result = Err(E); + let result_of_x: Result = x.into_result(); + + assert_eq!(result_of_x.unwrap_err(), E); + } + } + } + + /// The `HostFunction` trait represents the set of functions that + /// can be used as host function. To uphold this statement, it is + /// necessary for a function to be transformed into a pointer to + /// `VMFunctionBody`. + pub trait HostFunction + where + Args: WasmTypeList, + Rets: WasmTypeList, + Kind: HostFunctionKind, + T: Sized, + Self: Sized, + { + /// Get the pointer to the function body. + fn function_body_ptr(self) -> *const VMFunctionBody; + } + + /// Empty trait to specify the kind of `HostFunction`: With or + /// without an environment. + /// + /// This trait is never aimed to be used by a user. It is used by + /// the trait system to automatically generate the appropriate + /// host functions. + #[doc(hidden)] + pub trait HostFunctionKind {} + + /// An empty struct to help Rust typing to determine + /// when a `HostFunction` does have an environment. + pub struct WithEnv; + + impl HostFunctionKind for WithEnv {} + + /// An empty struct to help Rust typing to determine + /// when a `HostFunction` does not have an environment. + #[derive(Clone)] + pub struct WithoutEnv; + + impl HostFunctionKind for WithoutEnv {} + + /// Represents a low-level Wasm static host function. See + /// `super::Function::new` and `super::Function::new_env` to learn + /// more. + #[derive(Clone, Debug, Hash, PartialEq, Eq)] + pub struct Function { + address: *const VMFunctionBody, + _phantom: PhantomData<(Args, Rets)>, + } + + unsafe impl Send for Function {} + + impl Function + where + Args: WasmTypeList, + Rets: WasmTypeList, + { + /// Creates a new `Function`. + pub fn new(function: F) -> Self + where + F: HostFunction, + T: HostFunctionKind, + E: Sized, + { + Self { + address: function.function_body_ptr(), + _phantom: PhantomData, + } + } + + /// Get the function type of this `Function`. + pub fn ty(&self) -> FunctionType { + FunctionType::new(Args::wasm_types(), Rets::wasm_types()) + } + + /// Get the address of this `Function`. + pub fn address(&self) -> *const VMFunctionBody { + self.address + } + } + + macro_rules! impl_host_function { + ( [$c_struct_representation:ident] + $c_struct_name:ident, + $( $x:ident ),* ) => { + + /// A structure with a C-compatible representation that can hold a set of Wasm values. + /// This type is used by `WasmTypeList::CStruct`. + #[repr($c_struct_representation)] + pub struct $c_struct_name< $( $x ),* > ( $( <$x as FromToNativeWasmType>::Native ),* ) + where + $( $x: FromToNativeWasmType ),*; + + // Implement `WasmTypeList` for a specific tuple. + #[allow(unused_parens, dead_code)] + impl< $( $x ),* > + WasmTypeList + for + ( $( $x ),* ) + where + $( $x: FromToNativeWasmType ),* + { + type CStruct = $c_struct_name< $( $x ),* >; + + type Array = [i128; count_idents!( $( $x ),* )]; + + fn size() -> u32 { + count_idents!( $( $x ),* ) as _ + } + + fn from_array(array: Self::Array) -> Self { + // Unpack items of the array. + #[allow(non_snake_case)] + let [ $( $x ),* ] = array; + + // Build the tuple. + ( + $( + FromToNativeWasmType::from_native(NativeWasmType::from_binary($x)) + ),* + ) + } + + fn from_slice(slice: &[i128]) -> Result { + Ok(Self::from_array(slice.try_into()?)) + } + + fn into_array(self) -> Self::Array { + // Unpack items of the tuple. + #[allow(non_snake_case)] + let ( $( $x ),* ) = self; + + // Build the array. + [ + $( + FromToNativeWasmType::to_native($x).to_binary() + ),* + ] + } + + fn empty_array() -> Self::Array { + // Build an array initialized with `0`. + [0; count_idents!( $( $x ),* )] + } + + fn from_c_struct(c_struct: Self::CStruct) -> Self { + // Unpack items of the C structure. + #[allow(non_snake_case)] + let $c_struct_name( $( $x ),* ) = c_struct; + + ( + $( + FromToNativeWasmType::from_native($x) + ),* + ) + } + + #[allow(unused_parens, non_snake_case)] + fn into_c_struct(self) -> Self::CStruct { + // Unpack items of the tuple. + let ( $( $x ),* ) = self; + + // Build the C structure. + $c_struct_name( + $( + FromToNativeWasmType::to_native($x) + ),* + ) + } + + fn wasm_types() -> &'static [Type] { + &[ + $( + $x::Native::WASM_TYPE + ),* + ] + } + } + + // Implement `HostFunction` for a function that has the same arity than the tuple. + // This specific function has no environment. + #[allow(unused_parens)] + impl< $( $x, )* Rets, RetsAsResult, Func > + HostFunction<( $( $x ),* ), Rets, WithoutEnv, ()> + for + Func + where + $( $x: FromToNativeWasmType, )* + Rets: WasmTypeList, + RetsAsResult: IntoResult, + Func: Fn($( $x , )*) -> RetsAsResult + 'static + Send, + { + #[allow(non_snake_case)] + fn function_body_ptr(self) -> *const VMFunctionBody { + /// This is a function that wraps the real host + /// function. Its address will be used inside the + /// runtime. + extern fn func_wrapper<$( $x, )* Rets, RetsAsResult, Func>( _: usize, $( $x: $x::Native, )* ) -> Rets::CStruct + where + $( $x: FromToNativeWasmType, )* + Rets: WasmTypeList, + RetsAsResult: IntoResult, + Func: Fn( $( $x ),* ) -> RetsAsResult + 'static + { + let func: &Func = unsafe { &*(&() as *const () as *const Func) }; + let result = panic::catch_unwind(AssertUnwindSafe(|| { + func( $( FromToNativeWasmType::from_native($x) ),* ).into_result() + })); + match result { + Ok(Ok(result)) => return result.into_c_struct(), + _ => unimplemented!(), + // Ok(Err(trap)) => unsafe { raise_user_trap(Box::new(trap)) }, + // Err(panic) => unsafe { resume_panic(panic) }, + } + } + + func_wrapper::< $( $x, )* Rets, RetsAsResult, Self > as *const VMFunctionBody + } + } + + // Implement `HostFunction` for a function that has the same arity than the tuple. + // This specific function has an environment. + #[allow(unused_parens)] + impl< $( $x, )* Rets, RetsAsResult, Env, Func > + HostFunction<( $( $x ),* ), Rets, WithEnv, Env> + for + Func + where + $( $x: FromToNativeWasmType, )* + Rets: WasmTypeList, + RetsAsResult: IntoResult, + Env: Sized, + Func: Fn(&Env, $( $x , )*) -> RetsAsResult + Send + 'static, + { + #[allow(non_snake_case)] + fn function_body_ptr(self) -> *const VMFunctionBody { + /// This is a function that wraps the real host + /// function. Its address will be used inside the + /// runtime. + extern fn func_wrapper<$( $x, )* Rets, RetsAsResult, Env, Func>( ptr: usize, $( $x: $x::Native, )* ) -> Rets::CStruct + where + $( $x: FromToNativeWasmType, )* + Rets: WasmTypeList, + RetsAsResult: IntoResult, + Env: Sized, + Func: Fn(&Env, $( $x ),* ) -> RetsAsResult + 'static + { + let env: &Env = unsafe { &*(ptr as *const u8 as *const Env) }; + let func: &Func = unsafe { &*(&() as *const () as *const Func) }; + + let result = panic::catch_unwind(AssertUnwindSafe(|| { + func(env, $( FromToNativeWasmType::from_native($x) ),* ).into_result() + })); + match result { + Ok(Ok(result)) => return result.into_c_struct(), + _ => unimplemented!(), + // Ok(Err(trap)) => unsafe { raise_user_trap(Box::new(trap)) }, + // Err(panic) => unsafe { resume_panic(panic) }, + } + } + + func_wrapper::< $( $x, )* Rets, RetsAsResult, Env, Self > as *const VMFunctionBody + } + } + }; + } + + // Black-magic to count the number of identifiers at compile-time. + macro_rules! count_idents { + ( $($idents:ident),* ) => { + { + #[allow(dead_code, non_camel_case_types)] + enum Idents { $( $idents, )* __CountIdentsLast } + const COUNT: usize = Idents::__CountIdentsLast as usize; + COUNT + } + }; + } + + // Here we go! Let's generate all the C struct, `WasmTypeList` + // implementations and `HostFunction` implementations. + impl_host_function!([C] S0,); + impl_host_function!([transparent] S1, A1); + impl_host_function!([C] S2, A1, A2); + impl_host_function!([C] S3, A1, A2, A3); + impl_host_function!([C] S4, A1, A2, A3, A4); + impl_host_function!([C] S5, A1, A2, A3, A4, A5); + impl_host_function!([C] S6, A1, A2, A3, A4, A5, A6); + impl_host_function!([C] S7, A1, A2, A3, A4, A5, A6, A7); + impl_host_function!([C] S8, A1, A2, A3, A4, A5, A6, A7, A8); + impl_host_function!([C] S9, A1, A2, A3, A4, A5, A6, A7, A8, A9); + impl_host_function!([C] S10, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); + impl_host_function!([C] S11, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11); + impl_host_function!([C] S12, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12); + impl_host_function!([C] S13, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13); + impl_host_function!([C] S14, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14); + impl_host_function!([C] S15, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15); + impl_host_function!([C] S16, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16); + impl_host_function!([C] S17, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17); + impl_host_function!([C] S18, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18); + impl_host_function!([C] S19, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19); + impl_host_function!([C] S20, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20); + impl_host_function!([C] S21, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21); + impl_host_function!([C] S22, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22); + impl_host_function!([C] S23, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23); + impl_host_function!([C] S24, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, A24); + impl_host_function!([C] S25, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, A24, A25); + impl_host_function!([C] S26, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, A24, A25, A26); + + // Implement `WasmTypeList` on `Infallible`, which means that + // `Infallible` can be used as a returned type of a host function + // to express that it doesn't return, or to express that it cannot + // fail (with `Result<_, Infallible>`). + impl WasmTypeList for Infallible { + type CStruct = Self; + type Array = [i128; 0]; + + fn size() -> u32 { + 0 + } + + fn from_array(_: Self::Array) -> Self { + unreachable!() + } + + fn from_slice(_: &[i128]) -> Result { + unreachable!() + } + + fn into_array(self) -> Self::Array { + [] + } + + fn empty_array() -> Self::Array { + unreachable!() + } + + fn from_c_struct(_: Self::CStruct) -> Self { + unreachable!() + } + + fn into_c_struct(self) -> Self::CStruct { + unreachable!() + } + + fn wasm_types() -> &'static [Type] { + &[] + } + } + + #[cfg(test)] + mod test_wasm_type_list { + use super::*; + use wasmer_types::Type; + + #[test] + fn test_from_array() { + assert_eq!(<()>::from_array([]), ()); + assert_eq!(::from_array([1]), (1i32)); + assert_eq!(<(i32, i64)>::from_array([1, 2]), (1i32, 2i64)); + assert_eq!( + <(i32, i64, f32, f64)>::from_array([ + 1, + 2, + (3.1f32).to_bits().into(), + (4.2f64).to_bits().into() + ]), + (1, 2, 3.1f32, 4.2f64) + ); + } + + #[test] + fn test_into_array() { + assert_eq!(().into_array(), []); + assert_eq!((1).into_array(), [1]); + assert_eq!((1i32, 2i64).into_array(), [1, 2]); + assert_eq!( + (1i32, 2i32, 3.1f32, 4.2f64).into_array(), + [1, 2, (3.1f32).to_bits().into(), (4.2f64).to_bits().into()] + ); + } + + #[test] + fn test_empty_array() { + assert_eq!(<()>::empty_array().len(), 0); + assert_eq!(::empty_array().len(), 1); + assert_eq!(<(i32, i64)>::empty_array().len(), 2); + } + + #[test] + fn test_from_c_struct() { + assert_eq!(<()>::from_c_struct(S0()), ()); + assert_eq!(::from_c_struct(S1(1)), (1i32)); + assert_eq!(<(i32, i64)>::from_c_struct(S2(1, 2)), (1i32, 2i64)); + assert_eq!( + <(i32, i64, f32, f64)>::from_c_struct(S4(1, 2, 3.1, 4.2)), + (1i32, 2i64, 3.1f32, 4.2f64) + ); + } + + #[test] + fn test_wasm_types_for_uni_values() { + assert_eq!(::wasm_types(), [Type::I32]); + assert_eq!(::wasm_types(), [Type::I64]); + assert_eq!(::wasm_types(), [Type::F32]); + assert_eq!(::wasm_types(), [Type::F64]); + } + + #[test] + fn test_wasm_types_for_multi_values() { + assert_eq!(<(i32, i32)>::wasm_types(), [Type::I32, Type::I32]); + assert_eq!(<(i64, i64)>::wasm_types(), [Type::I64, Type::I64]); + assert_eq!(<(f32, f32)>::wasm_types(), [Type::F32, Type::F32]); + assert_eq!(<(f64, f64)>::wasm_types(), [Type::F64, Type::F64]); + + assert_eq!( + <(i32, i64, f32, f64)>::wasm_types(), + [Type::I32, Type::I64, Type::F32, Type::F64] + ); + } + } + + #[allow(non_snake_case)] + #[cfg(test)] + mod test_function { + use super::*; + use wasmer_types::Type; + + fn func() {} + fn func__i32() -> i32 { + 0 + } + fn func_i32(_a: i32) {} + fn func_i32__i32(a: i32) -> i32 { + a * 2 + } + fn func_i32_i32__i32(a: i32, b: i32) -> i32 { + a + b + } + fn func_i32_i32__i32_i32(a: i32, b: i32) -> (i32, i32) { + (a, b) + } + fn func_f32_i32__i32_f32(a: f32, b: i32) -> (i32, f32) { + (b, a) + } + + #[test] + fn test_function_types() { + assert_eq!(Function::new(func).ty(), FunctionType::new(vec![], vec![])); + assert_eq!( + Function::new(func__i32).ty(), + FunctionType::new(vec![], vec![Type::I32]) + ); + assert_eq!( + Function::new(func_i32).ty(), + FunctionType::new(vec![Type::I32], vec![]) + ); + assert_eq!( + Function::new(func_i32__i32).ty(), + FunctionType::new(vec![Type::I32], vec![Type::I32]) + ); + assert_eq!( + Function::new(func_i32_i32__i32).ty(), + FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]) + ); + assert_eq!( + Function::new(func_i32_i32__i32_i32).ty(), + FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32, Type::I32]) + ); + assert_eq!( + Function::new(func_f32_i32__i32_f32).ty(), + FunctionType::new(vec![Type::F32, Type::I32], vec![Type::I32, Type::F32]) + ); + } + + #[test] + fn test_function_pointer() { + let f = Function::new(func_i32__i32); + let function = unsafe { std::mem::transmute::<_, fn(usize, i32) -> i32>(f.address) }; + assert_eq!(function(0, 3), 6); + } + } +} diff --git a/lib/api/src/js/externals/global.rs b/lib/api/src/js/externals/global.rs new file mode 100644 index 00000000000..431547129a2 --- /dev/null +++ b/lib/api/src/js/externals/global.rs @@ -0,0 +1,242 @@ +use crate::js::export::Export; +use crate::js::export::VMGlobal; +use crate::js::exports::{ExportError, Exportable}; +use crate::js::externals::Extern; +use crate::js::store::Store; +use crate::js::types::{Val, ValType}; +use crate::js::wasm_bindgen_polyfill::Global as JSGlobal; +use crate::js::GlobalType; +use crate::js::Mutability; +use crate::js::RuntimeError; +use wasm_bindgen::JsValue; + +/// A WebAssembly `global` instance. +/// +/// A global instance is the runtime representation of a global variable. +/// It consists of an individual value and a flag indicating whether it is mutable. +/// +/// Spec: +#[derive(Debug, Clone, PartialEq)] +pub struct Global { + store: Store, + vm_global: VMGlobal, +} + +impl Global { + /// Create a new `Global` with the initial value [`Val`]. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Global, Mutability, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new(&store, Value::I32(1)); + /// + /// assert_eq!(g.get(), Value::I32(1)); + /// assert_eq!(g.ty().mutability, Mutability::Const); + /// ``` + pub fn new(store: &Store, val: Val) -> Self { + Self::from_value(store, val, Mutability::Const).unwrap() + } + + /// Create a mutable `Global` with the initial value [`Val`]. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Global, Mutability, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new_mut(&store, Value::I32(1)); + /// + /// assert_eq!(g.get(), Value::I32(1)); + /// assert_eq!(g.ty().mutability, Mutability::Var); + /// ``` + pub fn new_mut(store: &Store, val: Val) -> Self { + Self::from_value(store, val, Mutability::Var).unwrap() + } + + /// Create a `Global` with the initial value [`Val`] and the provided [`Mutability`]. + fn from_value(store: &Store, val: Val, mutability: Mutability) -> Result { + let global_ty = GlobalType { + mutability, + ty: val.ty(), + }; + let descriptor = js_sys::Object::new(); + let (type_str, value) = match val { + Val::I32(i) => ("i32", JsValue::from_f64(i as _)), + Val::I64(i) => ("i64", JsValue::from_f64(i as _)), + Val::F32(f) => ("f32", JsValue::from_f64(f as _)), + Val::F64(f) => ("f64", JsValue::from_f64(f)), + _ => unimplemented!("The type is not yet supported in the JS Global API"), + }; + // This is the value type as string, even though is incorrectly called "value" + // in the JS API. + js_sys::Reflect::set(&descriptor, &"value".into(), &type_str.into())?; + js_sys::Reflect::set( + &descriptor, + &"mutable".into(), + &mutability.is_mutable().into(), + )?; + + let js_global = JSGlobal::new(&descriptor, &value).unwrap(); + let global = VMGlobal::new(js_global, global_ty); + + Ok(Self { + store: store.clone(), + vm_global: global, + }) + } + + /// Returns the [`GlobalType`] of the `Global`. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Global, Mutability, Store, Type, Value, GlobalType}; + /// # let store = Store::default(); + /// # + /// let c = Global::new(&store, Value::I32(1)); + /// let v = Global::new_mut(&store, Value::I64(1)); + /// + /// assert_eq!(c.ty(), &GlobalType::new(Type::I32, Mutability::Const)); + /// assert_eq!(v.ty(), &GlobalType::new(Type::I64, Mutability::Var)); + /// ``` + pub fn ty(&self) -> &GlobalType { + &self.vm_global.ty + } + + /// Returns the [`Store`] where the `Global` belongs. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Global, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new(&store, Value::I32(1)); + /// + /// assert_eq!(g.store(), &store); + /// ``` + pub fn store(&self) -> &Store { + &self.store + } + + /// Retrieves the current value [`Val`] that the Global has. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Global, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new(&store, Value::I32(1)); + /// + /// assert_eq!(g.get(), Value::I32(1)); + /// ``` + pub fn get(&self) -> Val { + match self.vm_global.ty.ty { + ValType::I32 => Val::I32(self.vm_global.global.value().as_f64().unwrap() as _), + ValType::I64 => Val::I64(self.vm_global.global.value().as_f64().unwrap() as _), + ValType::F32 => Val::F32(self.vm_global.global.value().as_f64().unwrap() as _), + ValType::F64 => Val::F64(self.vm_global.global.value().as_f64().unwrap()), + _ => unimplemented!("The type is not yet supported in the JS Global API"), + } + } + + /// Sets a custom value [`Val`] to the runtime Global. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Global, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new_mut(&store, Value::I32(1)); + /// + /// assert_eq!(g.get(), Value::I32(1)); + /// + /// g.set(Value::I32(2)); + /// + /// assert_eq!(g.get(), Value::I32(2)); + /// ``` + /// + /// # Errors + /// + /// Trying to mutate a immutable global will raise an error: + /// + /// ```should_panic + /// # use wasmer::{Global, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new(&store, Value::I32(1)); + /// + /// g.set(Value::I32(2)).unwrap(); + /// ``` + /// + /// Trying to set a value of a incompatible type will raise an error: + /// + /// ```should_panic + /// # use wasmer::{Global, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new(&store, Value::I32(1)); + /// + /// // This results in an error: `RuntimeError`. + /// g.set(Value::I64(2)).unwrap(); + /// ``` + pub fn set(&self, val: Val) -> Result<(), RuntimeError> { + if self.vm_global.ty.mutability == Mutability::Const { + return Err(RuntimeError::new("The global is immutable".to_owned())); + } + if val.ty() != self.vm_global.ty.ty { + return Err(RuntimeError::new("The types don't match".to_owned())); + } + let new_value = match val { + Val::I32(i) => JsValue::from_f64(i as _), + Val::I64(i) => JsValue::from_f64(i as _), + Val::F32(f) => JsValue::from_f64(f as _), + Val::F64(f) => JsValue::from_f64(f), + _ => unimplemented!("The type is not yet supported in the JS Global API"), + }; + self.vm_global.global.set_value(&new_value); + Ok(()) + } + + pub(crate) fn from_vm_export(store: &Store, vm_global: VMGlobal) -> Self { + Self { + store: store.clone(), + vm_global, + } + } + + /// Returns whether or not these two globals refer to the same data. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Global, Store, Value}; + /// # let store = Store::default(); + /// # + /// let g = Global::new(&store, Value::I32(1)); + /// + /// assert!(g.same(&g)); + /// ``` + pub fn same(&self, other: &Self) -> bool { + self.vm_global == other.vm_global + } +} + +impl<'a> Exportable<'a> for Global { + fn to_export(&self) -> Export { + Export::Global(self.vm_global.clone()) + } + + fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { + match _extern { + Extern::Global(global) => Ok(global), + _ => Err(ExportError::IncompatibleType), + } + } +} diff --git a/lib/api/src/js/externals/memory.rs b/lib/api/src/js/externals/memory.rs new file mode 100644 index 00000000000..4dc868d1fbf --- /dev/null +++ b/lib/api/src/js/externals/memory.rs @@ -0,0 +1,331 @@ +use crate::js::export::{Export, VMMemory}; +use crate::js::exports::{ExportError, Exportable}; +use crate::js::externals::Extern; +use crate::js::store::Store; +use crate::js::{MemoryType, MemoryView}; +use std::convert::TryInto; +use thiserror::Error; + +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasmer_types::{Bytes, Pages, ValueType}; + +/// Error type describing things that can go wrong when operating on Wasm Memories. +#[derive(Error, Debug, Clone, PartialEq, Hash)] +pub enum MemoryError { + /// The operation would cause the size of the memory to exceed the maximum or would cause + /// an overflow leading to unindexable memory. + #[error("The memory could not grow: current size {} pages, requested increase: {} pages", current.0, attempted_delta.0)] + CouldNotGrow { + /// The current size in pages. + current: Pages, + /// The attempted amount to grow by in pages. + attempted_delta: Pages, + }, + /// A user defined error value, used for error cases not listed above. + #[error("A user-defined error occurred: {0}")] + Generic(String), +} + +#[wasm_bindgen] +extern "C" { + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) + #[wasm_bindgen(js_namespace = WebAssembly, extends = js_sys::Object, typescript_type = "WebAssembly.Memory")] + #[derive(Clone, Debug, PartialEq, Eq)] + pub type JSMemory; + + /// The `grow()` protoype method of the `Memory` object increases the + /// size of the memory instance by a specified number of WebAssembly + /// pages. + /// + /// Takes the number of pages to grow (64KiB in size) and returns the + /// previous size of memory, in pages. + /// + /// # Reimplementation + /// + /// We re-implement `WebAssembly.Memory.grow` because it is + /// different from what `wasm-bindgen` declares. It marks the function + /// as `catch`, which means it can throw an exception. + /// + /// See [the opened patch](https://github.com/rustwasm/wasm-bindgen/pull/2599). + /// + /// # Exceptions + /// + /// A `RangeError` is thrown if adding pages would exceed the maximum + /// memory. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/grow) + #[wasm_bindgen(catch, method, js_namespace = WebAssembly)] + pub fn grow(this: &JSMemory, pages: u32) -> Result; +} + +/// A WebAssembly `memory` instance. +/// +/// A memory instance is the runtime representation of a linear memory. +/// It consists of a vector of bytes and an optional maximum size. +/// +/// The length of the vector always is a multiple of the WebAssembly +/// page size, which is defined to be the constant 65536 – abbreviated 64Ki. +/// Like in a memory type, the maximum size in a memory instance is +/// given in units of this page size. +/// +/// A memory created by the host or in WebAssembly code will be accessible and +/// mutable from both host and WebAssembly. +/// +/// Spec: +#[derive(Debug, Clone, PartialEq)] +pub struct Memory { + store: Store, + vm_memory: VMMemory, +} + +impl Memory { + /// Creates a new host `Memory` from the provided [`MemoryType`]. + /// + /// This function will construct the `Memory` using the store + /// [`BaseTunables`][crate::js::tunables::BaseTunables]. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; + /// # let store = Store::default(); + /// # + /// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); + /// ``` + pub fn new(store: &Store, ty: MemoryType) -> Result { + let descriptor = js_sys::Object::new(); + js_sys::Reflect::set(&descriptor, &"initial".into(), &ty.minimum.0.into()).unwrap(); + if let Some(max) = ty.maximum { + js_sys::Reflect::set(&descriptor, &"maximum".into(), &max.0.into()).unwrap(); + } + js_sys::Reflect::set(&descriptor, &"shared".into(), &ty.shared.into()).unwrap(); + + let js_memory = js_sys::WebAssembly::Memory::new(&descriptor) + .map_err(|_e| MemoryError::Generic("Error while creating the memory".to_owned()))?; + + let memory = VMMemory::new(js_memory, ty); + Ok(Self { + store: store.clone(), + vm_memory: memory, + }) + } + + /// Returns the [`MemoryType`] of the `Memory`. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; + /// # let store = Store::default(); + /// # + /// let mt = MemoryType::new(1, None, false); + /// let m = Memory::new(&store, mt).unwrap(); + /// + /// assert_eq!(m.ty(), mt); + /// ``` + pub fn ty(&self) -> MemoryType { + let mut ty = self.vm_memory.ty.clone(); + ty.minimum = self.size(); + ty + } + + /// Returns the [`Store`] where the `Memory` belongs. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; + /// # let store = Store::default(); + /// # + /// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); + /// + /// assert_eq!(m.store(), &store); + /// ``` + pub fn store(&self) -> &Store { + &self.store + } + + /// Retrieve a slice of the memory contents. + /// + /// # Safety + /// + /// Until the returned slice is dropped, it is undefined behaviour to + /// modify the memory contents in any way including by calling a wasm + /// function that writes to the memory or by resizing the memory. + pub unsafe fn data_unchecked(&self) -> &[u8] { + unimplemented!("direct data pointer access is not possible in JavaScript"); + } + + /// Retrieve a mutable slice of the memory contents. + /// + /// # Safety + /// + /// This method provides interior mutability without an UnsafeCell. Until + /// the returned value is dropped, it is undefined behaviour to read or + /// write to the pointed-to memory in any way except through this slice, + /// including by calling a wasm function that reads the memory contents or + /// by resizing this Memory. + #[allow(clippy::mut_from_ref)] + pub unsafe fn data_unchecked_mut(&self) -> &mut [u8] { + unimplemented!("direct data pointer access is not possible in JavaScript"); + } + + /// Returns the pointer to the raw bytes of the `Memory`. + pub fn data_ptr(&self) -> *mut u8 { + unimplemented!("direct data pointer access is not possible in JavaScript"); + } + + /// Returns the size (in bytes) of the `Memory`. + pub fn data_size(&self) -> u64 { + js_sys::Reflect::get(&self.vm_memory.memory.buffer(), &"byteLength".into()) + .unwrap() + .as_f64() + .unwrap() as _ + } + + /// Returns the size (in [`Pages`]) of the `Memory`. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; + /// # let store = Store::default(); + /// # + /// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); + /// + /// assert_eq!(m.size(), Pages(1)); + /// ``` + pub fn size(&self) -> Pages { + let bytes = js_sys::Reflect::get(&self.vm_memory.memory.buffer(), &"byteLength".into()) + .unwrap() + .as_f64() + .unwrap() as u64; + Bytes(bytes as usize).try_into().unwrap() + } + + /// Grow memory by the specified amount of WebAssembly [`Pages`] and return + /// the previous memory size. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; + /// # let store = Store::default(); + /// # + /// let m = Memory::new(&store, MemoryType::new(1, Some(3), false)).unwrap(); + /// let p = m.grow(2).unwrap(); + /// + /// assert_eq!(p, Pages(1)); + /// assert_eq!(m.size(), Pages(3)); + /// ``` + /// + /// # Errors + /// + /// Returns an error if memory can't be grown by the specified amount + /// of pages. + /// + /// ```should_panic + /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; + /// # let store = Store::default(); + /// # + /// let m = Memory::new(&store, MemoryType::new(1, Some(1), false)).unwrap(); + /// + /// // This results in an error: `MemoryError::CouldNotGrow`. + /// let s = m.grow(1).unwrap(); + /// ``` + pub fn grow(&self, delta: IntoPages) -> Result + where + IntoPages: Into, + { + let pages = delta.into(); + let js_memory = self.vm_memory.memory.clone().unchecked_into::(); + let new_pages = js_memory.grow(pages.0).map_err(|err| { + if err.is_instance_of::() { + MemoryError::CouldNotGrow { + current: self.size(), + attempted_delta: pages, + } + } else { + MemoryError::Generic(err.as_string().unwrap()) + } + })?; + Ok(Pages(new_pages)) + } + + /// Return a "view" of the currently accessible memory. By + /// default, the view is unsynchronized, using regular memory + /// accesses. You can force a memory view to use atomic accesses + /// by calling the [`MemoryView::atomically`] method. + /// + /// # Notes: + /// + /// This method is safe (as in, it won't cause the host to crash or have UB), + /// but it doesn't obey rust's rules involving data races, especially concurrent ones. + /// Therefore, if this memory is shared between multiple threads, a single memory + /// location can be mutated concurrently without synchronization. + /// + /// # Usage: + /// + /// ``` + /// # use wasmer::{Memory, MemoryView}; + /// # use std::{cell::Cell, sync::atomic::Ordering}; + /// # fn view_memory(memory: Memory) { + /// // Without synchronization. + /// let view: MemoryView = memory.view(); + /// for byte in view[0x1000 .. 0x1010].iter().map(Cell::get) { + /// println!("byte: {}", byte); + /// } + /// + /// // With synchronization. + /// let atomic_view = view.atomically(); + /// for byte in atomic_view[0x1000 .. 0x1010].iter().map(|atom| atom.load(Ordering::SeqCst)) { + /// println!("byte: {}", byte); + /// } + /// # } + /// ``` + pub fn view(&self) -> MemoryView { + unimplemented!("The view function is not yet implemented in Wasmer Javascript"); + } + + /// example view + pub fn uint8view(&self) -> js_sys::Uint8Array { + js_sys::Uint8Array::new(&self.vm_memory.memory.buffer()) + } + + pub(crate) fn from_vm_export(store: &Store, vm_memory: VMMemory) -> Self { + Self { + store: store.clone(), + vm_memory, + } + } + + /// Returns whether or not these two memories refer to the same data. + /// + /// # Example + /// + /// ``` + /// # use wasmer::{Memory, MemoryType, Store, Value}; + /// # let store = Store::default(); + /// # + /// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); + /// + /// assert!(m.same(&m)); + /// ``` + pub fn same(&self, other: &Self) -> bool { + self.vm_memory == other.vm_memory + } +} + +impl<'a> Exportable<'a> for Memory { + fn to_export(&self) -> Export { + Export::Memory(self.vm_memory.clone()) + } + + fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { + match _extern { + Extern::Memory(memory) => Ok(memory), + _ => Err(ExportError::IncompatibleType), + } + } +} diff --git a/lib/api/src/js/externals/mod.rs b/lib/api/src/js/externals/mod.rs new file mode 100644 index 00000000000..ebcb2b9e049 --- /dev/null +++ b/lib/api/src/js/externals/mod.rs @@ -0,0 +1,113 @@ +pub(crate) mod function; +mod global; +mod memory; +mod table; + +pub use self::function::{ + FromToNativeWasmType, Function, HostFunction, WasmTypeList, WithEnv, WithoutEnv, +}; + +pub use self::global::Global; +pub use self::memory::{Memory, MemoryError}; +pub use self::table::Table; + +use crate::js::export::Export; +use crate::js::exports::{ExportError, Exportable}; +use crate::js::store::{Store, StoreObject}; +use crate::js::ExternType; +use std::fmt; + +/// An `Extern` is the runtime representation of an entity that +/// can be imported or exported. +/// +/// Spec: +#[derive(Clone)] +pub enum Extern { + /// A external [`Function`]. + Function(Function), + /// A external [`Global`]. + Global(Global), + /// A external [`Table`]. + Table(Table), + /// A external [`Memory`]. + Memory(Memory), +} + +impl Extern { + /// Return the underlying type of the inner `Extern`. + pub fn ty(&self) -> ExternType { + match self { + Self::Function(ft) => ExternType::Function(ft.ty().clone()), + Self::Memory(ft) => ExternType::Memory(ft.ty()), + Self::Table(tt) => ExternType::Table(*tt.ty()), + Self::Global(gt) => ExternType::Global(*gt.ty()), + } + } + + /// Create an `Extern` from an `wasmer_engine::Export`. + pub fn from_vm_export(store: &Store, export: Export) -> Self { + match export { + Export::Function(f) => Self::Function(Function::from_vm_export(store, f)), + Export::Memory(m) => Self::Memory(Memory::from_vm_export(store, m)), + Export::Global(g) => Self::Global(Global::from_vm_export(store, g)), + Export::Table(t) => Self::Table(Table::from_vm_export(store, t)), + } + } +} + +impl<'a> Exportable<'a> for Extern { + fn to_export(&self) -> Export { + match self { + Self::Function(f) => f.to_export(), + Self::Global(g) => g.to_export(), + Self::Memory(m) => m.to_export(), + Self::Table(t) => t.to_export(), + } + } + + fn get_self_from_extern(_extern: &'a Self) -> Result<&'a Self, ExportError> { + // Since this is already an extern, we can just return it. + Ok(_extern) + } +} + +impl StoreObject for Extern {} + +impl fmt::Debug for Extern { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "{}", + match self { + Self::Function(_) => "Function(...)", + Self::Global(_) => "Global(...)", + Self::Memory(_) => "Memory(...)", + Self::Table(_) => "Table(...)", + } + ) + } +} + +impl From for Extern { + fn from(r: Function) -> Self { + Self::Function(r) + } +} + +impl From for Extern { + fn from(r: Global) -> Self { + Self::Global(r) + } +} + +impl From for Extern { + fn from(r: Memory) -> Self { + Self::Memory(r) + } +} + +impl From
for Extern { + fn from(r: Table) -> Self { + Self::Table(r) + } +} diff --git a/lib/api/src/js/externals/table.rs b/lib/api/src/js/externals/table.rs new file mode 100644 index 00000000000..cc7608fee9b --- /dev/null +++ b/lib/api/src/js/externals/table.rs @@ -0,0 +1,167 @@ +use crate::js::export::VMFunction; +use crate::js::export::{Export, VMTable}; +use crate::js::exports::{ExportError, Exportable}; +use crate::js::externals::{Extern, Function as WasmerFunction}; +use crate::js::store::Store; +use crate::js::types::Val; +use crate::js::RuntimeError; +use crate::js::TableType; +use js_sys::Function; +use wasmer_types::FunctionType; + +/// A WebAssembly `table` instance. +/// +/// The `Table` struct is an array-like structure representing a WebAssembly Table, +/// which stores function references. +/// +/// A table created by the host or in WebAssembly code will be accessible and +/// mutable from both host and WebAssembly. +/// +/// Spec: +#[derive(Debug, Clone, PartialEq)] +pub struct Table { + store: Store, + vm_table: VMTable, +} + +fn set_table_item(table: &VMTable, item_index: u32, item: &Function) -> Result<(), RuntimeError> { + table.table.set(item_index, item).map_err(|e| e.into()) +} + +fn get_function(val: Val) -> Result { + match val { + Val::FuncRef(func) => Ok(func.as_ref().unwrap().exported.function.clone().into()), + // Only funcrefs is supported by the spec atm + _ => unimplemented!(), + } +} + +impl Table { + /// Creates a new `Table` with the provided [`TableType`] definition. + /// + /// All the elements in the table will be set to the `init` value. + /// + /// This function will construct the `Table` using the store + /// [`BaseTunables`][crate::js::tunables::BaseTunables]. + pub fn new(store: &Store, ty: TableType, init: Val) -> Result { + let descriptor = js_sys::Object::new(); + js_sys::Reflect::set(&descriptor, &"initial".into(), &ty.minimum.into())?; + if let Some(max) = ty.maximum { + js_sys::Reflect::set(&descriptor, &"maximum".into(), &max.into())?; + } + js_sys::Reflect::set(&descriptor, &"element".into(), &"anyfunc".into())?; + + let js_table = js_sys::WebAssembly::Table::new(&descriptor)?; + let table = VMTable::new(js_table, ty); + + let num_elements = table.table.length(); + let func = get_function(init)?; + for i in 0..num_elements { + set_table_item(&table, i, &func)?; + } + + Ok(Self { + store: store.clone(), + vm_table: table, + }) + } + + /// Returns the [`TableType`] of the `Table`. + pub fn ty(&self) -> &TableType { + &self.vm_table.ty + } + + /// Returns the [`Store`] where the `Table` belongs. + pub fn store(&self) -> &Store { + &self.store + } + + /// Retrieves an element of the table at the provided `index`. + pub fn get(&self, index: u32) -> Option { + let func = self.vm_table.table.get(index).ok()?; + let ty = FunctionType::new(vec![], vec![]); + Some(Val::FuncRef(Some(WasmerFunction::from_vm_export( + &self.store, + VMFunction::new(func, ty, None), + )))) + } + + /// Sets an element `val` in the Table at the provided `index`. + pub fn set(&self, index: u32, val: Val) -> Result<(), RuntimeError> { + let func = get_function(val)?; + set_table_item(&self.vm_table, index, &func)?; + Ok(()) + } + + /// Retrieves the size of the `Table` (in elements) + pub fn size(&self) -> u32 { + self.vm_table.table.length() + } + + /// Grows the size of the `Table` by `delta`, initializating + /// the elements with the provided `init` value. + /// + /// It returns the previous size of the `Table` in case is able + /// to grow the Table successfully. + /// + /// # Errors + /// + /// Returns an error if the `delta` is out of bounds for the table. + pub fn grow(&self, _delta: u32, _init: Val) -> Result { + unimplemented!(); + } + + /// Copies the `len` elements of `src_table` starting at `src_index` + /// to the destination table `dst_table` at index `dst_index`. + /// + /// # Errors + /// + /// Returns an error if the range is out of bounds of either the source or + /// destination tables. + pub fn copy( + _dst_table: &Self, + _dst_index: u32, + _src_table: &Self, + _src_index: u32, + _len: u32, + ) -> Result<(), RuntimeError> { + unimplemented!("Table.copy is not natively supported in Javascript"); + } + + pub(crate) fn from_vm_export(store: &Store, vm_table: VMTable) -> Self { + Self { + store: store.clone(), + vm_table, + } + } + + /// Returns whether or not these two tables refer to the same data. + pub fn same(&self, other: &Self) -> bool { + self.vm_table == other.vm_table + } + + /// Get access to the backing VM value for this extern. This function is for + /// tests it should not be called by users of the Wasmer API. + /// + /// # Safety + /// This function is unsafe to call outside of tests for the wasmer crate + /// because there is no stability guarantee for the returned type and we may + /// make breaking changes to it at any time or remove this method. + #[doc(hidden)] + pub unsafe fn get_vm_table(&self) -> &VMTable { + &self.vm_table + } +} + +impl<'a> Exportable<'a> for Table { + fn to_export(&self) -> Export { + Export::Table(self.vm_table.clone()) + } + + fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { + match _extern { + Extern::Table(table) => Ok(table), + _ => Err(ExportError::IncompatibleType), + } + } +} diff --git a/lib/api/src/js/import_object.rs b/lib/api/src/js/import_object.rs new file mode 100644 index 00000000000..63bb41d50f6 --- /dev/null +++ b/lib/api/src/js/import_object.rs @@ -0,0 +1,412 @@ +//! The import module contains the implementation data structures and helper functions used to +//! manipulate and access a wasm module's imports including memories, tables, globals, and +//! functions. +use crate::js::export::Export; +use crate::js::resolver::NamedResolver; +use std::borrow::{Borrow, BorrowMut}; +use std::collections::VecDeque; +use std::collections::{hash_map::Entry, HashMap}; +use std::fmt; +use std::sync::{Arc, Mutex}; + +/// The `LikeNamespace` trait represents objects that act as a namespace for imports. +/// For example, an `Instance` or `Namespace` could be +/// considered namespaces that could provide imports to an instance. +pub trait LikeNamespace { + /// Gets an export by name. + fn get_namespace_export(&self, name: &str) -> Option; + /// Gets all exports in the namespace. + fn get_namespace_exports(&self) -> Vec<(String, Export)>; +} + +/// All of the import data used when instantiating. +/// +/// It's suggested that you use the [`imports!`] macro +/// instead of creating an `ImportObject` by hand. +/// +/// [`imports!`]: macro.imports.html +/// +/// # Usage: +/// ```ignore +/// use wasmer::{Exports, ImportObject, Function}; +/// +/// let mut import_object = ImportObject::new(); +/// let mut env = Exports::new(); +/// +/// env.insert("foo", Function::new_native(foo)); +/// import_object.register("env", env); +/// +/// fn foo(n: i32) -> i32 { +/// n +/// } +/// ``` +#[derive(Clone, Default)] +pub struct ImportObject { + map: Arc>>>, +} + +impl ImportObject { + /// Create a new `ImportObject`. + pub fn new() -> Self { + Default::default() + } + + /// Gets an export given a module and a name + /// + /// # Usage + /// ```ignore + /// # use wasmer::{ImportObject, Instance, Namespace}; + /// let mut import_object = ImportObject::new(); + /// import_object.get_export("module", "name"); + /// ``` + pub fn get_export(&self, module: &str, name: &str) -> Option { + let guard = self.map.lock().unwrap(); + let map_ref = guard.borrow(); + if map_ref.contains_key(module) { + let namespace = map_ref[module].as_ref(); + return namespace.get_namespace_export(name); + } + None + } + + /// Returns true if the ImportObject contains namespace with the provided name. + pub fn contains_namespace(&self, name: &str) -> bool { + self.map.lock().unwrap().borrow().contains_key(name) + } + + /// Register anything that implements `LikeNamespace` as a namespace. + /// + /// # Usage: + /// ```ignore + /// # use wasmer::{ImportObject, Instance, Namespace}; + /// let mut import_object = ImportObject::new(); + /// + /// import_object.register("namespace0", instance); + /// import_object.register("namespace1", namespace); + /// // ... + /// ``` + pub fn register(&mut self, name: S, namespace: N) -> Option> + where + S: Into, + N: LikeNamespace + 'static, + { + let mut guard = self.map.lock().unwrap(); + let map = guard.borrow_mut(); + + match map.entry(name.into()) { + Entry::Vacant(empty) => { + empty.insert(Box::new(namespace)); + None + } + Entry::Occupied(mut occupied) => Some(occupied.insert(Box::new(namespace))), + } + } + + fn get_objects(&self) -> VecDeque<((String, String), Export)> { + let mut out = VecDeque::new(); + let guard = self.map.lock().unwrap(); + let map = guard.borrow(); + for (name, ns) in map.iter() { + for (id, exp) in ns.get_namespace_exports() { + out.push_back(((name.clone(), id), exp)); + } + } + out + } +} + +impl NamedResolver for ImportObject { + fn resolve_by_name(&self, module: &str, name: &str) -> Option { + self.get_export(module, name) + } +} + +/// Iterator for an `ImportObject`'s exports. +pub struct ImportObjectIterator { + elements: VecDeque<((String, String), Export)>, +} + +impl Iterator for ImportObjectIterator { + type Item = ((String, String), Export); + fn next(&mut self) -> Option { + self.elements.pop_front() + } +} + +impl IntoIterator for ImportObject { + type IntoIter = ImportObjectIterator; + type Item = ((String, String), Export); + + fn into_iter(self) -> Self::IntoIter { + ImportObjectIterator { + elements: self.get_objects(), + } + } +} + +impl fmt::Debug for ImportObject { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + enum SecretMap { + Empty, + Some(usize), + } + + impl SecretMap { + fn new(len: usize) -> Self { + if len == 0 { + Self::Empty + } else { + Self::Some(len) + } + } + } + + impl fmt::Debug for SecretMap { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Empty => write!(f, "(empty)"), + Self::Some(len) => write!(f, "(... {} item(s) ...)", len), + } + } + } + + f.debug_struct("ImportObject") + .field( + "map", + &SecretMap::new(self.map.lock().unwrap().borrow().len()), + ) + .finish() + } +} + +// The import! macro for ImportObject + +/// Generate an [`ImportObject`] easily with the `imports!` macro. +/// +/// [`ImportObject`]: struct.ImportObject.html +/// +/// # Usage +/// +/// ``` +/// # use wasmer::{Function, Store}; +/// # let store = Store::default(); +/// use wasmer::imports; +/// +/// let import_object = imports! { +/// "env" => { +/// "foo" => Function::new_native(&store, foo) +/// }, +/// }; +/// +/// fn foo(n: i32) -> i32 { +/// n +/// } +/// ``` +#[macro_export] +macro_rules! imports { + ( $( $ns_name:expr => $ns:tt ),* $(,)? ) => { + { + let mut import_object = $crate::ImportObject::new(); + + $({ + let namespace = $crate::import_namespace!($ns); + + import_object.register($ns_name, namespace); + })* + + import_object + } + }; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! namespace { + ($( $import_name:expr => $import_item:expr ),* $(,)? ) => { + $crate::import_namespace!( { $( $import_name => $import_item, )* } ) + }; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! import_namespace { + ( { $( $import_name:expr => $import_item:expr ),* $(,)? } ) => {{ + let mut namespace = $crate::Exports::new(); + + $( + namespace.insert($import_name, $import_item); + )* + + namespace + }}; + + ( $namespace:ident ) => { + $namespace + }; +} + +#[cfg(test)] +mod test { + use super::*; + use crate::js::ChainableNamedResolver; + use crate::js::Type; + use crate::js::{Global, Store, Val}; + use wasm_bindgen_test::*; + + #[wasm_bindgen_test] + fn chaining_works() { + let store = Store::default(); + let g = Global::new(&store, Val::I32(0)); + + let imports1 = imports! { + "dog" => { + "happy" => g.clone() + } + }; + + let imports2 = imports! { + "dog" => { + "small" => g.clone() + }, + "cat" => { + "small" => g.clone() + } + }; + + let resolver = imports1.chain_front(imports2); + + let small_cat_export = resolver.resolve_by_name("cat", "small"); + assert!(small_cat_export.is_some()); + + let happy = resolver.resolve_by_name("dog", "happy"); + let small = resolver.resolve_by_name("dog", "small"); + assert!(happy.is_some()); + assert!(small.is_some()); + } + + #[wasm_bindgen_test] + fn extending_conflict_overwrites() { + let store = Store::default(); + let g1 = Global::new(&store, Val::I32(0)); + let g2 = Global::new(&store, Val::F32(0.)); + + let imports1 = imports! { + "dog" => { + "happy" => g1, + }, + }; + + let imports2 = imports! { + "dog" => { + "happy" => g2, + }, + }; + + let resolver = imports1.chain_front(imports2); + let happy_dog_entry = resolver.resolve_by_name("dog", "happy").unwrap(); + + assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { + happy_dog_global.ty.ty == Type::F32 + } else { + false + }); + + // now test it in reverse + let store = Store::default(); + let g1 = Global::new(&store, Val::I32(0)); + let g2 = Global::new(&store, Val::F32(0.)); + + let imports1 = imports! { + "dog" => { + "happy" => g1, + }, + }; + + let imports2 = imports! { + "dog" => { + "happy" => g2, + }, + }; + + let resolver = imports1.chain_back(imports2); + let happy_dog_entry = resolver.resolve_by_name("dog", "happy").unwrap(); + + assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { + happy_dog_global.ty.ty == Type::I32 + } else { + false + }); + } + + #[wasm_bindgen_test] + fn namespace() { + let store = Store::default(); + let g1 = Global::new(&store, Val::I32(0)); + let namespace = namespace! { + "happy" => g1 + }; + let imports1 = imports! { + "dog" => namespace + }; + + let happy_dog_entry = imports1.resolve_by_name("dog", "happy").unwrap(); + + assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { + happy_dog_global.ty.ty == Type::I32 + } else { + false + }); + } + + #[wasm_bindgen_test] + fn imports_macro_allows_trailing_comma_and_none() { + use crate::js::Function; + + let store = Default::default(); + + fn func(arg: i32) -> i32 { + arg + 1 + } + + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func), + }, + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func), + } + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func), + }, + "abc" => { + "def" => Function::new_native(&store, func), + } + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func) + }, + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func) + } + }; + let _ = imports! { + "env" => { + "func1" => Function::new_native(&store, func), + "func2" => Function::new_native(&store, func) + } + }; + let _ = imports! { + "env" => { + "func1" => Function::new_native(&store, func), + "func2" => Function::new_native(&store, func), + } + }; + } +} diff --git a/lib/api/src/js/instance.rs b/lib/api/src/js/instance.rs new file mode 100644 index 00000000000..c7e155adc33 --- /dev/null +++ b/lib/api/src/js/instance.rs @@ -0,0 +1,142 @@ +use crate::js::env::HostEnvInitError; +use crate::js::export::Export; +use crate::js::exports::Exports; +use crate::js::externals::Extern; +use crate::js::module::Module; +use crate::js::resolver::Resolver; +use crate::js::store::Store; +use crate::js::trap::RuntimeError; +use js_sys::WebAssembly; +use std::fmt; +#[cfg(feature = "std")] +use thiserror::Error; + +/// A WebAssembly Instance is a stateful, executable +/// instance of a WebAssembly [`Module`]. +/// +/// Instance objects contain all the exported WebAssembly +/// functions, memories, tables and globals that allow +/// interacting with WebAssembly. +/// +/// Spec: +#[derive(Clone)] +pub struct Instance { + instance: WebAssembly::Instance, + module: Module, + /// The exports for an instance. + pub exports: Exports, +} + +/// An error while instantiating a module. +/// +/// This is not a common WebAssembly error, however +/// we need to differentiate from a `LinkError` (an error +/// that happens while linking, on instantiation), a +/// Trap that occurs when calling the WebAssembly module +/// start function, and an error when initializing the user's +/// host environments. +#[derive(Debug)] +#[cfg_attr(feature = "std", derive(Error))] +pub enum InstantiationError { + /// A linking ocurred during instantiation. + #[cfg_attr(feature = "std", error("Link error: {0}"))] + Link(String), + + /// A runtime error occured while invoking the start function + #[cfg_attr(feature = "std", error(transparent))] + Start(RuntimeError), + + /// Error occurred when initializing the host environment. + #[cfg_attr(feature = "std", error(transparent))] + HostEnvInitialization(HostEnvInitError), +} + +#[cfg(feature = "core")] +impl std::fmt::Display for InstantiationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "InstantiationError") + } +} + +impl Instance { + /// Creates a new `Instance` from a WebAssembly [`Module`] and a + /// set of imports resolved by the [`Resolver`]. + /// + /// The resolver can be anything that implements the [`Resolver`] trait, + /// so you can plug custom resolution for the imports, if you wish not + /// to use [`ImportObject`]. + /// + /// The [`ImportObject`] is the easiest way to provide imports to the instance. + /// + /// [`ImportObject`]: crate::js::ImportObject + /// + /// ``` + /// # use wasmer::{imports, Store, Module, Global, Value, Instance}; + /// # fn main() -> anyhow::Result<()> { + /// let store = Store::default(); + /// let module = Module::new(&store, "(module)")?; + /// let imports = imports!{ + /// "host" => { + /// "var" => Global::new(&store, Value::I32(2)) + /// } + /// }; + /// let instance = Instance::new(&module, &imports)?; + /// # Ok(()) + /// # } + /// ``` + /// + /// ## Errors + /// + /// The function can return [`InstantiationError`]s. + /// + /// Those are, as defined by the spec: + /// * Link errors that happen when plugging the imports into the instance + /// * Runtime errors that happen when running the module `start` function. + pub fn new(module: &Module, resolver: &dyn Resolver) -> Result { + let store = module.store(); + let (instance, functions) = module + .instantiate(resolver) + .map_err(|e| InstantiationError::Start(e))?; + let instance_exports = instance.exports(); + let exports = module + .exports() + .map(|export_type| { + let name = export_type.name(); + let extern_type = export_type.ty().clone(); + let js_export = js_sys::Reflect::get(&instance_exports, &name.into()).unwrap(); + let export: Export = (js_export, extern_type).into(); + let extern_ = Extern::from_vm_export(store, export); + (name.to_string(), extern_) + }) + .collect::(); + + let self_instance = Self { + module: module.clone(), + instance, + exports, + }; + for func in functions { + func.init_envs(&self_instance) + .map_err(|e| InstantiationError::HostEnvInitialization(e))?; + } + Ok(self_instance) + } + + /// Gets the [`Module`] associated with this instance. + pub fn module(&self) -> &Module { + &self.module + } + + /// Returns the [`Store`] where the `Instance` belongs. + pub fn store(&self) -> &Store { + self.module.store() + } +} + +impl fmt::Debug for Instance { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Instance") + .field("exports", &self.exports) + .finish() + } +} diff --git a/lib/api/src/js/mod.rs b/lib/api/src/js/mod.rs new file mode 100644 index 00000000000..b27d2756c3c --- /dev/null +++ b/lib/api/src/js/mod.rs @@ -0,0 +1,85 @@ +#[cfg(all(feature = "std", feature = "core"))] +compile_error!( + "The `std` and `core` features are both enabled, which is an error. Please enable only once." +); + +#[cfg(all(not(feature = "std"), not(feature = "core")))] +compile_error!("Both the `std` and `core` features are disabled. Please enable one of them."); + +#[cfg(feature = "core")] +extern crate alloc; + +mod lib { + #[cfg(feature = "core")] + pub mod std { + pub use alloc::{borrow, boxed, str, string, sync, vec}; + pub use core::fmt; + pub use hashbrown as collections; + } + + #[cfg(feature = "std")] + pub mod std { + pub use std::{borrow, boxed, collections, fmt, str, string, sync, vec}; + } +} + +mod cell; +mod env; +mod error; +mod export; +mod exports; +mod externals; +mod import_object; +mod instance; +mod module; +#[cfg(feature = "wasm-types-polyfill")] +mod module_info_polyfill; +mod native; +mod ptr; +mod resolver; +mod store; +mod trap; +mod types; +mod utils; +mod wasm_bindgen_polyfill; + +/// Implement [`WasmerEnv`] for your type with `#[derive(WasmerEnv)]`. +/// +/// See the [`WasmerEnv`] trait for more information. +pub use wasmer_derive::WasmerEnv; + +pub use crate::js::cell::WasmCell; +pub use crate::js::env::{HostEnvInitError, LazyInit, WasmerEnv}; +pub use crate::js::exports::{ExportError, Exportable, Exports, ExportsIterator}; +pub use crate::js::externals::{ + Extern, FromToNativeWasmType, Function, Global, HostFunction, Memory, MemoryError, Table, + WasmTypeList, +}; +pub use crate::js::import_object::{ImportObject, ImportObjectIterator, LikeNamespace}; +pub use crate::js::instance::{Instance, InstantiationError}; +pub use crate::js::module::{Module, ModuleTypeHints}; +pub use crate::js::native::NativeFunc; +pub use crate::js::ptr::{Array, Item, WasmPtr}; +pub use crate::js::resolver::{ + ChainableNamedResolver, NamedResolver, NamedResolverChain, Resolver, +}; +pub use crate::js::trap::RuntimeError; + +pub use crate::js::store::{Store, StoreObject}; +pub use crate::js::types::{ + ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, + TableType, Val, ValType, +}; +pub use crate::js::types::{Val as Value, ValType as Type}; +pub use crate::js::utils::is_wasm; + +pub use wasmer_types::{ + Atomically, Bytes, ExportIndex, GlobalInit, LocalFunctionIndex, MemoryView, Pages, ValueType, + WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE, +}; + +#[cfg(feature = "wat")] +pub use wat::parse_bytes as wat2wasm; + +/// Version number of this crate. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/lib/api/src/js/module.rs b/lib/api/src/js/module.rs new file mode 100644 index 00000000000..fb02c27b9a2 --- /dev/null +++ b/lib/api/src/js/module.rs @@ -0,0 +1,519 @@ +use crate::js::export::{Export, VMFunction}; +use crate::js::resolver::Resolver; +use crate::js::store::Store; +use crate::js::types::{ExportType, ImportType}; +// use crate::js::InstantiationError; +use crate::js::error::CompileError; +#[cfg(feature = "wat")] +use crate::js::error::WasmError; +use crate::js::RuntimeError; +use js_sys::{Reflect, Uint8Array, WebAssembly}; +use std::fmt; +use std::io; +use std::path::Path; +#[cfg(feature = "std")] +use thiserror::Error; +use wasm_bindgen::JsValue; +use wasmer_types::{ + ExportsIterator, ExternType, FunctionType, GlobalType, ImportsIterator, MemoryType, Mutability, + Pages, TableType, Type, +}; + +#[derive(Debug)] +#[cfg_attr(feature = "std", derive(Error))] +pub enum IoCompileError { + /// An IO error + #[cfg_attr(feature = "std", error(transparent))] + Io(io::Error), + /// A compilation error + #[cfg_attr(feature = "std", error(transparent))] + Compile(CompileError), +} + +/// WebAssembly in the browser doesn't yet output the descriptor/types +/// corresponding to each extern (import and export). +/// +/// This should be fixed once the JS-Types Wasm proposal is adopted +/// by the browsers: +/// https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md +/// +/// Until that happens, we annotate the module with the expected +/// types so we can built on top of them at runtime. +#[derive(Clone)] +pub struct ModuleTypeHints { + /// The type hints for the imported types + pub imports: Vec, + /// The type hints for the exported types + pub exports: Vec, +} + +/// A WebAssembly Module contains stateless WebAssembly +/// code that has already been compiled and can be instantiated +/// multiple times. +/// +/// ## Cloning a module +/// +/// Cloning a module is cheap: it does a shallow copy of the compiled +/// contents rather than a deep copy. +#[derive(Clone)] +pub struct Module { + store: Store, + module: WebAssembly::Module, + name: Option, + // WebAssembly type hints + type_hints: Option, +} + +impl Module { + /// Creates a new WebAssembly Module given the configuration + /// in the store. + /// + /// If the provided bytes are not WebAssembly-like (start with `b"\0asm"`), + /// and the "wat" feature is enabled for this crate, this function will try to + /// to convert the bytes assuming they correspond to the WebAssembly text + /// format. + /// + /// ## Security + /// + /// Before the code is compiled, it will be validated using the store + /// features. + /// + /// ## Errors + /// + /// Creating a WebAssembly module from bytecode can result in a + /// [`CompileError`] since this operation requires to transorm the Wasm + /// bytecode into code the machine can easily execute. + /// + /// ## Example + /// + /// Reading from a WAT file. + /// + /// ``` + /// use wasmer::*; + /// # fn main() -> anyhow::Result<()> { + /// # let store = Store::default(); + /// let wat = "(module)"; + /// let module = Module::new(&store, wat)?; + /// # Ok(()) + /// # } + /// ``` + /// + /// Reading from bytes: + /// + /// ``` + /// use wasmer::*; + /// # fn main() -> anyhow::Result<()> { + /// # let store = Store::default(); + /// // The following is the same as: + /// // (module + /// // (type $t0 (func (param i32) (result i32))) + /// // (func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32) + /// // get_local $p0 + /// // i32.const 1 + /// // i32.add) + /// // ) + /// let bytes: Vec = vec![ + /// 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, + /// 0x01, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x0b, 0x01, 0x07, + /// 0x61, 0x64, 0x64, 0x5f, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x0a, 0x09, 0x01, + /// 0x07, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x0b, 0x00, 0x1a, 0x04, 0x6e, + /// 0x61, 0x6d, 0x65, 0x01, 0x0a, 0x01, 0x00, 0x07, 0x61, 0x64, 0x64, 0x5f, + /// 0x6f, 0x6e, 0x65, 0x02, 0x07, 0x01, 0x00, 0x01, 0x00, 0x02, 0x70, 0x30, + /// ]; + /// let module = Module::new(&store, bytes)?; + /// # Ok(()) + /// # } + /// ``` + #[allow(unreachable_code)] + pub fn new(store: &Store, bytes: impl AsRef<[u8]>) -> Result { + #[cfg(feature = "wat")] + let bytes = wat::parse_bytes(bytes.as_ref()).map_err(|e| { + CompileError::Wasm(WasmError::Generic(format!( + "Error when converting wat: {}", + e + ))) + })?; + Self::from_binary(store, bytes.as_ref()) + } + + /// Creates a new WebAssembly module from a file path. + pub fn from_file(_store: &Store, _file: impl AsRef) -> Result { + unimplemented!(); + } + + /// Creates a new WebAssembly module from a binary. + /// + /// Opposed to [`Module::new`], this function is not compatible with + /// the WebAssembly text format (if the "wat" feature is enabled for + /// this crate). + pub fn from_binary(store: &Store, binary: &[u8]) -> Result { + // + // Self::validate(store, binary)?; + unsafe { Self::from_binary_unchecked(store, binary) } + } + + /// Creates a new WebAssembly module skipping any kind of validation. + /// + /// # Safety + /// + /// This is safe since the JS vm should be safe already. + /// We maintain the `unsafe` to preserve the same API as Wasmer + pub unsafe fn from_binary_unchecked( + store: &Store, + binary: &[u8], + ) -> Result { + let js_bytes = Uint8Array::view(binary); + let module = WebAssembly::Module::new(&js_bytes.into()).unwrap(); + + // The module is now validated, so we can safely parse it's types + #[cfg(feature = "wasm-types-polyfill")] + let (type_hints, name) = { + let info = crate::js::module_info_polyfill::translate_module(binary).unwrap(); + + ( + Some(ModuleTypeHints { + imports: info + .info + .imports() + .map(|import| import.ty().clone()) + .collect::>(), + exports: info + .info + .exports() + .map(|export| export.ty().clone()) + .collect::>(), + }), + info.info.name, + ) + }; + #[cfg(not(feature = "wasm-types-polyfill"))] + let (type_hints, name) = (None, None); + + Ok(Self { + store: store.clone(), + module, + type_hints, + name, + }) + } + + /// Validates a new WebAssembly Module given the configuration + /// in the Store. + /// + /// This validation is normally pretty fast and checks the enabled + /// WebAssembly features in the Store Engine to assure deterministic + /// validation of the Module. + pub fn validate(_store: &Store, binary: &[u8]) -> Result<(), CompileError> { + let js_bytes = unsafe { Uint8Array::view(binary) }; + match WebAssembly::validate(&js_bytes.into()) { + Ok(true) => Ok(()), + _ => Err(CompileError::Validate("Invalid Wasm file".to_owned())), + } + } + + pub(crate) fn instantiate( + &self, + resolver: &dyn Resolver, + ) -> Result<(WebAssembly::Instance, Vec), RuntimeError> { + let imports = js_sys::Object::new(); + let mut functions: Vec = vec![]; + for (i, import_type) in self.imports().enumerate() { + let resolved_import = + resolver.resolve(i as u32, import_type.module(), import_type.name()); + if let Some(import) = resolved_import { + let val = js_sys::Reflect::get(&imports, &import_type.module().into())?; + if !val.is_undefined() { + // If the namespace is already set + js_sys::Reflect::set(&val, &import_type.name().into(), import.as_jsvalue())?; + } else { + // If the namespace doesn't exist + let import_namespace = js_sys::Object::new(); + js_sys::Reflect::set( + &import_namespace, + &import_type.name().into(), + import.as_jsvalue(), + )?; + js_sys::Reflect::set( + &imports, + &import_type.module().into(), + &import_namespace.into(), + )?; + } + if let Export::Function(func) = import { + functions.push(func); + } + } + // in case the import is not found, the JS Wasm VM will handle + // the error for us, so we don't need to handle it + } + Ok(( + WebAssembly::Instance::new(&self.module, &imports) + .map_err(|e: JsValue| -> RuntimeError { e.into() })?, + functions, + )) + } + + /// Returns the name of the current module. + /// + /// This name is normally set in the WebAssembly bytecode by some + /// compilers, but can be also overwritten using the [`Module::set_name`] method. + /// + /// # Example + /// + /// ``` + /// # use wasmer::*; + /// # fn main() -> anyhow::Result<()> { + /// # let store = Store::default(); + /// let wat = "(module $moduleName)"; + /// let module = Module::new(&store, wat)?; + /// assert_eq!(module.name(), Some("moduleName")); + /// # Ok(()) + /// # } + /// ``` + pub fn name(&self) -> Option<&str> { + self.name.as_ref().map(|s| s.as_ref()) + // self.artifact.module_ref().name.as_deref() + } + + /// Sets the name of the current module. + /// This is normally useful for stacktraces and debugging. + /// + /// It will return `true` if the module name was changed successfully, + /// and return `false` otherwise (in case the module is already + /// instantiated). + /// + /// # Example + /// + /// ``` + /// # use wasmer::*; + /// # fn main() -> anyhow::Result<()> { + /// # let store = Store::default(); + /// let wat = "(module)"; + /// let mut module = Module::new(&store, wat)?; + /// assert_eq!(module.name(), None); + /// module.set_name("foo"); + /// assert_eq!(module.name(), Some("foo")); + /// # Ok(()) + /// # } + /// ``` + pub fn set_name(&mut self, name: &str) -> bool { + self.name = Some(name.to_string()); + true + // match Reflect::set(self.module.as_ref(), &"wasmer_name".into(), &name.into()) { + // Ok(_) => true, + // _ => false + // } + // Arc::get_mut(&mut self.artifact) + // .and_then(|artifact| artifact.module_mut()) + // .map(|mut module_info| { + // module_info.info.name = Some(name.to_string()); + // true + // }) + // .unwrap_or(false) + } + + /// Returns an iterator over the imported types in the Module. + /// + /// The order of the imports is guaranteed to be the same as in the + /// WebAssembly bytecode. + /// + /// # Example + /// + /// ``` + /// # use wasmer::*; + /// # fn main() -> anyhow::Result<()> { + /// # let store = Store::default(); + /// let wat = r#"(module + /// (import "host" "func1" (func)) + /// (import "host" "func2" (func)) + /// )"#; + /// let module = Module::new(&store, wat)?; + /// for import in module.imports() { + /// assert_eq!(import.module(), "host"); + /// assert!(import.name().contains("func")); + /// import.ty(); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn imports<'a>(&'a self) -> ImportsIterator + 'a> { + let imports = WebAssembly::Module::imports(&self.module); + let iter = imports + .iter() + .map(move |val| { + let module = Reflect::get(val.as_ref(), &"module".into()) + .unwrap() + .as_string() + .unwrap(); + let field = Reflect::get(val.as_ref(), &"name".into()) + .unwrap() + .as_string() + .unwrap(); + let kind = Reflect::get(val.as_ref(), &"kind".into()) + .unwrap() + .as_string() + .unwrap(); + let extern_type = match kind.as_str() { + "function" => { + let func_type = FunctionType::new(vec![], vec![]); + ExternType::Function(func_type) + } + "global" => { + let global_type = GlobalType::new(Type::I32, Mutability::Const); + ExternType::Global(global_type) + } + "memory" => { + let memory_type = MemoryType::new(Pages(1), None, false); + ExternType::Memory(memory_type) + } + "table" => { + let table_type = TableType::new(Type::FuncRef, 1, None); + ExternType::Table(table_type) + } + _ => unimplemented!(), + }; + ImportType::new(&module, &field, extern_type) + }) + .collect::>() + .into_iter(); + ImportsIterator::new(iter, imports.length() as usize) + } + + /// Set the type hints for this module. + /// + /// Returns an error if the hints doesn't match the shape of + /// import or export types of the module. + pub fn set_type_hints(&mut self, type_hints: ModuleTypeHints) -> Result<(), String> { + let exports = WebAssembly::Module::exports(&self.module); + // Check exports + if exports.length() as usize != type_hints.exports.len() { + return Err("The exports length must match the type hints lenght".to_owned()); + } + for (i, val) in exports.iter().enumerate() { + let kind = Reflect::get(val.as_ref(), &"kind".into()) + .unwrap() + .as_string() + .unwrap(); + // It is safe to unwrap as we have already checked for the exports length + let type_hint = type_hints.exports.get(i).unwrap(); + let expected_kind = match type_hint { + ExternType::Function(_) => "function", + ExternType::Global(_) => "global", + ExternType::Memory(_) => "memory", + ExternType::Table(_) => "table", + }; + if expected_kind != kind.as_str() { + return Err(format!("The provided type hint for the export {} is {} which doesn't match the expected kind: {}", i, kind.as_str(), expected_kind)); + } + } + self.type_hints = Some(type_hints); + Ok(()) + } + + /// Returns an iterator over the exported types in the Module. + /// + /// The order of the exports is guaranteed to be the same as in the + /// WebAssembly bytecode. + /// + /// # Example + /// + /// ``` + /// # use wasmer::*; + /// # fn main() -> anyhow::Result<()> { + /// # let store = Store::default(); + /// let wat = r#"(module + /// (func (export "namedfunc")) + /// (memory (export "namedmemory") 1) + /// )"#; + /// let module = Module::new(&store, wat)?; + /// for export_ in module.exports() { + /// assert!(export_.name().contains("named")); + /// export_.ty(); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn exports<'a>(&'a self) -> ExportsIterator + 'a> { + let exports = WebAssembly::Module::exports(&self.module); + let iter = exports + .iter() + .enumerate() + .map(move |(i, val)| { + let field = Reflect::get(val.as_ref(), &"name".into()) + .unwrap() + .as_string() + .unwrap(); + let kind = Reflect::get(val.as_ref(), &"kind".into()) + .unwrap() + .as_string() + .unwrap(); + let type_hint = self + .type_hints + .as_ref() + .map(|hints| hints.exports.get(i).unwrap().clone()); + let extern_type = if let Some(hint) = type_hint { + hint + } else { + // The default types + match kind.as_str() { + "function" => { + let func_type = FunctionType::new(vec![], vec![]); + ExternType::Function(func_type) + } + "global" => { + let global_type = GlobalType::new(Type::I32, Mutability::Const); + ExternType::Global(global_type) + } + "memory" => { + let memory_type = MemoryType::new(Pages(1), None, false); + ExternType::Memory(memory_type) + } + "table" => { + let table_type = TableType::new(Type::FuncRef, 1, None); + ExternType::Table(table_type) + } + _ => unimplemented!(), + } + }; + ExportType::new(&field, extern_type) + }) + .collect::>() + .into_iter(); + ExportsIterator::new(iter, exports.length() as usize) + } + + // /// Get the custom sections of the module given a `name`. + // /// + // /// # Important + // /// + // /// Following the WebAssembly spec, one name can have multiple + // /// custom sections. That's why an iterator (rather than one element) + // /// is returned. + // pub fn custom_sections<'a>(&'a self, name: &'a str) -> impl Iterator> + 'a { + // unimplemented!(); + // } + + /// Returns the [`Store`] where the `Instance` belongs. + pub fn store(&self) -> &Store { + &self.store + } +} + +impl fmt::Debug for Module { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Module") + .field("name", &self.name()) + .finish() + } +} + +impl From for Module { + fn from(module: WebAssembly::Module) -> Module { + Module { + store: Store::default(), + module, + name: None, + type_hints: None, + } + } +} diff --git a/lib/api/src/js/module_info_polyfill.rs b/lib/api/src/js/module_info_polyfill.rs new file mode 100644 index 00000000000..733daebb052 --- /dev/null +++ b/lib/api/src/js/module_info_polyfill.rs @@ -0,0 +1,600 @@ +//! Polyfill skeleton that traverses the whole WebAssembly module and +//! creates the corresponding import and export types. +//! +//! This shall not be needed once the JS type reflection API is available +//! for the Wasm imports and exports. +//! +//! https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md +use core::convert::TryFrom; +use std::vec::Vec; +use wasmer_types::entity::EntityRef; +use wasmer_types::{ + ExportIndex, FunctionIndex, FunctionType, GlobalIndex, GlobalType, ImportIndex, MemoryIndex, + MemoryType, ModuleInfo, Pages, SignatureIndex, TableIndex, TableType, Type, +}; + +use wasmparser::{ + self, BinaryReaderError, Export, ExportSectionReader, ExternalKind, FuncType as WPFunctionType, + FunctionSectionReader, GlobalSectionReader, GlobalType as WPGlobalType, ImportSectionEntryType, + ImportSectionReader, MemorySectionReader, MemoryType as WPMemoryType, NameSectionReader, + Parser, Payload, TableSectionReader, TypeDef, TypeSectionReader, +}; + +pub type WasmResult = Result; + +#[derive(Default)] +pub struct ModuleInfoPolyfill { + pub(crate) info: ModuleInfo, +} + +impl ModuleInfoPolyfill { + pub(crate) fn declare_export(&mut self, export: ExportIndex, name: &str) -> WasmResult<()> { + self.info.exports.insert(String::from(name), export); + Ok(()) + } + + pub(crate) fn declare_import( + &mut self, + import: ImportIndex, + module: &str, + field: &str, + ) -> WasmResult<()> { + self.info.imports.insert( + ( + String::from(module), + String::from(field), + self.info.imports.len() as u32, + ), + import, + ); + Ok(()) + } + + pub(crate) fn reserve_signatures(&mut self, num: u32) -> WasmResult<()> { + self.info + .signatures + .reserve_exact(usize::try_from(num).unwrap()); + Ok(()) + } + + pub(crate) fn declare_signature(&mut self, sig: FunctionType) -> WasmResult<()> { + self.info.signatures.push(sig); + Ok(()) + } + + pub(crate) fn declare_func_import( + &mut self, + sig_index: SignatureIndex, + module: &str, + field: &str, + ) -> WasmResult<()> { + debug_assert_eq!( + self.info.functions.len(), + self.info.num_imported_functions, + "Imported functions must be declared first" + ); + self.declare_import( + ImportIndex::Function(FunctionIndex::from_u32( + self.info.num_imported_functions as _, + )), + module, + field, + )?; + self.info.functions.push(sig_index); + self.info.num_imported_functions += 1; + Ok(()) + } + + pub(crate) fn declare_table_import( + &mut self, + table: TableType, + module: &str, + field: &str, + ) -> WasmResult<()> { + debug_assert_eq!( + self.info.tables.len(), + self.info.num_imported_tables, + "Imported tables must be declared first" + ); + self.declare_import( + ImportIndex::Table(TableIndex::from_u32(self.info.num_imported_tables as _)), + module, + field, + )?; + self.info.tables.push(table); + self.info.num_imported_tables += 1; + Ok(()) + } + + pub(crate) fn declare_memory_import( + &mut self, + memory: MemoryType, + module: &str, + field: &str, + ) -> WasmResult<()> { + debug_assert_eq!( + self.info.memories.len(), + self.info.num_imported_memories, + "Imported memories must be declared first" + ); + self.declare_import( + ImportIndex::Memory(MemoryIndex::from_u32(self.info.num_imported_memories as _)), + module, + field, + )?; + self.info.memories.push(memory); + self.info.num_imported_memories += 1; + Ok(()) + } + + pub(crate) fn declare_global_import( + &mut self, + global: GlobalType, + module: &str, + field: &str, + ) -> WasmResult<()> { + debug_assert_eq!( + self.info.globals.len(), + self.info.num_imported_globals, + "Imported globals must be declared first" + ); + self.declare_import( + ImportIndex::Global(GlobalIndex::from_u32(self.info.num_imported_globals as _)), + module, + field, + )?; + self.info.globals.push(global); + self.info.num_imported_globals += 1; + Ok(()) + } + + pub(crate) fn reserve_func_types(&mut self, num: u32) -> WasmResult<()> { + self.info + .functions + .reserve_exact(usize::try_from(num).unwrap()); + Ok(()) + } + + pub(crate) fn declare_func_type(&mut self, sig_index: SignatureIndex) -> WasmResult<()> { + self.info.functions.push(sig_index); + Ok(()) + } + + pub(crate) fn reserve_tables(&mut self, num: u32) -> WasmResult<()> { + self.info + .tables + .reserve_exact(usize::try_from(num).unwrap()); + Ok(()) + } + + pub(crate) fn declare_table(&mut self, table: TableType) -> WasmResult<()> { + self.info.tables.push(table); + Ok(()) + } + + pub(crate) fn reserve_memories(&mut self, num: u32) -> WasmResult<()> { + self.info + .memories + .reserve_exact(usize::try_from(num).unwrap()); + Ok(()) + } + + pub(crate) fn declare_memory(&mut self, memory: MemoryType) -> WasmResult<()> { + self.info.memories.push(memory); + Ok(()) + } + + pub(crate) fn reserve_globals(&mut self, num: u32) -> WasmResult<()> { + self.info + .globals + .reserve_exact(usize::try_from(num).unwrap()); + Ok(()) + } + + pub(crate) fn declare_global(&mut self, global: GlobalType) -> WasmResult<()> { + self.info.globals.push(global); + Ok(()) + } + + pub(crate) fn reserve_exports(&mut self, num: u32) -> WasmResult<()> { + self.info.exports.reserve(usize::try_from(num).unwrap()); + Ok(()) + } + + pub(crate) fn reserve_imports(&mut self, num: u32) -> WasmResult<()> { + self.info.imports.reserve(usize::try_from(num).unwrap()); + Ok(()) + } + + pub(crate) fn declare_func_export( + &mut self, + func_index: FunctionIndex, + name: &str, + ) -> WasmResult<()> { + self.declare_export(ExportIndex::Function(func_index), name) + } + + pub(crate) fn declare_table_export( + &mut self, + table_index: TableIndex, + name: &str, + ) -> WasmResult<()> { + self.declare_export(ExportIndex::Table(table_index), name) + } + + pub(crate) fn declare_memory_export( + &mut self, + memory_index: MemoryIndex, + name: &str, + ) -> WasmResult<()> { + self.declare_export(ExportIndex::Memory(memory_index), name) + } + + pub(crate) fn declare_global_export( + &mut self, + global_index: GlobalIndex, + name: &str, + ) -> WasmResult<()> { + self.declare_export(ExportIndex::Global(global_index), name) + } + + pub(crate) fn declare_module_name(&mut self, name: &str) -> WasmResult<()> { + self.info.name = Some(name.to_string()); + Ok(()) + } +} + +fn transform_err(err: BinaryReaderError) -> String { + err.message().into() +} + +/// Translate a sequence of bytes forming a valid Wasm binary into a +/// parsed ModuleInfo `ModuleInfoPolyfill`. +pub fn translate_module<'data>(data: &'data [u8]) -> WasmResult { + let mut module_info: ModuleInfoPolyfill = Default::default(); + + for payload in Parser::new(0).parse_all(data) { + match payload.map_err(transform_err)? { + Payload::TypeSection(types) => { + parse_type_section(types, &mut module_info)?; + } + + Payload::ImportSection(imports) => { + parse_import_section(imports, &mut module_info)?; + } + + Payload::FunctionSection(functions) => { + parse_function_section(functions, &mut module_info)?; + } + + Payload::TableSection(tables) => { + parse_table_section(tables, &mut module_info)?; + } + + Payload::MemorySection(memories) => { + parse_memory_section(memories, &mut module_info)?; + } + + Payload::GlobalSection(globals) => { + parse_global_section(globals, &mut module_info)?; + } + + Payload::ExportSection(exports) => { + parse_export_section(exports, &mut module_info)?; + } + + Payload::CustomSection { + name: "name", + data, + data_offset, + .. + } => parse_name_section( + NameSectionReader::new(data, data_offset).map_err(transform_err)?, + &mut module_info, + )?, + + _ => {} + } + } + + Ok(module_info) +} + +/// Helper function translating wasmparser types to Wasm Type. +pub fn wptype_to_type(ty: wasmparser::Type) -> WasmResult { + match ty { + wasmparser::Type::I32 => Ok(Type::I32), + wasmparser::Type::I64 => Ok(Type::I64), + wasmparser::Type::F32 => Ok(Type::F32), + wasmparser::Type::F64 => Ok(Type::F64), + wasmparser::Type::V128 => Ok(Type::V128), + wasmparser::Type::ExternRef => Ok(Type::ExternRef), + wasmparser::Type::FuncRef => Ok(Type::FuncRef), + ty => Err(format!("wptype_to_type: wasmparser type {:?}", ty)), + } +} + +/// Parses the Type section of the wasm module. +pub fn parse_type_section( + types: TypeSectionReader, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + let count = types.get_count(); + module_info.reserve_signatures(count)?; + + for entry in types { + if let Ok(TypeDef::Func(WPFunctionType { params, returns })) = entry { + let sig_params: Vec = params + .iter() + .map(|ty| { + wptype_to_type(*ty) + .expect("only numeric types are supported in function signatures") + }) + .collect(); + let sig_returns: Vec = returns + .iter() + .map(|ty| { + wptype_to_type(*ty) + .expect("only numeric types are supported in function signatures") + }) + .collect(); + let sig = FunctionType::new(sig_params, sig_returns); + module_info.declare_signature(sig)?; + } else { + unimplemented!("module linking not implemented yet") + } + } + + Ok(()) +} + +/// Parses the Import section of the wasm module. +pub fn parse_import_section<'data>( + imports: ImportSectionReader<'data>, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + module_info.reserve_imports(imports.get_count())?; + + for entry in imports { + let import = entry.map_err(transform_err)?; + let module_name = import.module; + let field_name = import.field; + + match import.ty { + ImportSectionEntryType::Function(sig) => { + module_info.declare_func_import( + SignatureIndex::from_u32(sig), + module_name, + field_name.unwrap_or_default(), + )?; + } + ImportSectionEntryType::Module(_) + | ImportSectionEntryType::Instance(_) + | ImportSectionEntryType::Event(_) => { + unimplemented!("module linking not implemented yet") + } + ImportSectionEntryType::Memory(WPMemoryType::M32 { + limits: ref memlimits, + shared, + }) => { + module_info.declare_memory_import( + MemoryType { + minimum: Pages(memlimits.initial), + maximum: memlimits.maximum.map(Pages), + shared, + }, + module_name, + field_name.unwrap_or_default(), + )?; + } + ImportSectionEntryType::Memory(WPMemoryType::M64 { .. }) => { + unimplemented!("64bit memory not implemented yet") + } + ImportSectionEntryType::Global(ref ty) => { + module_info.declare_global_import( + GlobalType { + ty: wptype_to_type(ty.content_type).unwrap(), + mutability: ty.mutable.into(), + }, + module_name, + field_name.unwrap_or_default(), + )?; + } + ImportSectionEntryType::Table(ref tab) => { + module_info.declare_table_import( + TableType { + ty: wptype_to_type(tab.element_type).unwrap(), + minimum: tab.limits.initial, + maximum: tab.limits.maximum, + }, + module_name, + field_name.unwrap_or_default(), + )?; + } + } + } + Ok(()) +} + +/// Parses the Function section of the wasm module. +pub fn parse_function_section( + functions: FunctionSectionReader, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + let num_functions = functions.get_count(); + module_info.reserve_func_types(num_functions)?; + + for entry in functions { + let sigindex = entry.map_err(transform_err)?; + module_info.declare_func_type(SignatureIndex::from_u32(sigindex))?; + } + + Ok(()) +} + +/// Parses the Table section of the wasm module. +pub fn parse_table_section( + tables: TableSectionReader, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + module_info.reserve_tables(tables.get_count())?; + + for entry in tables { + let table = entry.map_err(transform_err)?; + module_info.declare_table(TableType { + ty: wptype_to_type(table.element_type).unwrap(), + minimum: table.limits.initial, + maximum: table.limits.maximum, + })?; + } + + Ok(()) +} + +/// Parses the Memory section of the wasm module. +pub fn parse_memory_section( + memories: MemorySectionReader, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + module_info.reserve_memories(memories.get_count())?; + + for entry in memories { + let memory = entry.map_err(transform_err)?; + match memory { + WPMemoryType::M32 { limits, shared } => { + module_info.declare_memory(MemoryType { + minimum: Pages(limits.initial), + maximum: limits.maximum.map(Pages), + shared, + })?; + } + WPMemoryType::M64 { .. } => unimplemented!("64bit memory not implemented yet"), + } + } + + Ok(()) +} + +/// Parses the Global section of the wasm module. +pub fn parse_global_section( + globals: GlobalSectionReader, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + module_info.reserve_globals(globals.get_count())?; + + for entry in globals { + let WPGlobalType { + content_type, + mutable, + } = entry.map_err(transform_err)?.ty; + let global = GlobalType { + ty: wptype_to_type(content_type).unwrap(), + mutability: mutable.into(), + }; + module_info.declare_global(global)?; + } + + Ok(()) +} + +/// Parses the Export section of the wasm module. +pub fn parse_export_section<'data>( + exports: ExportSectionReader<'data>, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + module_info.reserve_exports(exports.get_count())?; + + for entry in exports { + let Export { + field, + ref kind, + index, + } = entry.map_err(transform_err)?; + + // The input has already been validated, so we should be able to + // assume valid UTF-8 and use `from_utf8_unchecked` if performance + // becomes a concern here. + let index = index as usize; + match *kind { + ExternalKind::Function => { + module_info.declare_func_export(FunctionIndex::new(index), field)? + } + ExternalKind::Table => { + module_info.declare_table_export(TableIndex::new(index), field)? + } + ExternalKind::Memory => { + module_info.declare_memory_export(MemoryIndex::new(index), field)? + } + ExternalKind::Global => { + module_info.declare_global_export(GlobalIndex::new(index), field)? + } + ExternalKind::Type + | ExternalKind::Module + | ExternalKind::Instance + | ExternalKind::Event => { + unimplemented!("module linking not implemented yet") + } + } + } + Ok(()) +} + +// /// Parses the Start section of the wasm module. +// pub fn parse_start_section(index: u32, module_info: &mut ModuleInfoPolyfill) -> WasmResult<()> { +// module_info.declare_start_function(FunctionIndex::from_u32(index))?; +// Ok(()) +// } + +/// Parses the Name section of the wasm module. +pub fn parse_name_section<'data>( + mut names: NameSectionReader<'data>, + module_info: &mut ModuleInfoPolyfill, +) -> WasmResult<()> { + while let Ok(subsection) = names.read() { + match subsection { + wasmparser::Name::Function(_function_subsection) => { + // if let Some(function_names) = function_subsection + // .get_map() + // .ok() + // .and_then(parse_function_name_subsection) + // { + // for (index, name) in function_names { + // module_info.declare_function_name(index, name)?; + // } + // } + } + wasmparser::Name::Module(module) => { + if let Ok(name) = module.get_name() { + module_info.declare_module_name(name)?; + } + } + wasmparser::Name::Local(_) => {} + wasmparser::Name::Unknown { .. } => {} + }; + } + Ok(()) +} + +// fn parse_function_name_subsection( +// mut naming_reader: NamingReader<'_>, +// ) -> Option> { +// let mut function_names = HashMap::new(); +// for _ in 0..naming_reader.get_count() { +// let Naming { index, name } = naming_reader.read().ok()?; +// if index == std::u32::MAX { +// // We reserve `u32::MAX` for our own use. +// return None; +// } + +// if function_names +// .insert(FunctionIndex::from_u32(index), name) +// .is_some() +// { +// // If the function index has been previously seen, then we +// // break out of the loop and early return `None`, because these +// // should be unique. +// return None; +// } +// } +// Some(function_names) +// } diff --git a/lib/api/src/js/native.rs b/lib/api/src/js/native.rs new file mode 100644 index 00000000000..6cbd4c53894 --- /dev/null +++ b/lib/api/src/js/native.rs @@ -0,0 +1,149 @@ +//! Native Functions. +//! +//! This module creates the helper `NativeFunc` that let us call WebAssembly +//! functions with the native ABI, that is: +//! +//! ```ignore +//! let add_one = instance.exports.get_function("function_name")?; +//! let add_one_native: NativeFunc = add_one.native().unwrap(); +//! ``` +use std::marker::PhantomData; + +use crate::js::{FromToNativeWasmType, Function, RuntimeError, Store, WasmTypeList}; +// use std::panic::{catch_unwind, AssertUnwindSafe}; +use crate::js::export::VMFunction; +use crate::js::types::param_from_js; +use js_sys::Array; +use std::iter::FromIterator; +use wasm_bindgen::JsValue; +use wasmer_types::NativeWasmType; + +/// A WebAssembly function that can be called natively +/// (using the Native ABI). +#[derive(Clone)] +pub struct NativeFunc { + store: Store, + exported: VMFunction, + _phantom: PhantomData<(Args, Rets)>, +} + +unsafe impl Send for NativeFunc {} + +impl NativeFunc +where + Args: WasmTypeList, + Rets: WasmTypeList, +{ + pub(crate) fn new(store: Store, exported: VMFunction) -> Self { + Self { + store, + exported, + _phantom: PhantomData, + } + } +} + +impl From<&NativeFunc> for VMFunction +where + Args: WasmTypeList, + Rets: WasmTypeList, +{ + fn from(other: &NativeFunc) -> Self { + other.exported.clone() + } +} + +impl From> for Function +where + Args: WasmTypeList, + Rets: WasmTypeList, +{ + fn from(other: NativeFunc) -> Self { + Self { + store: other.store, + exported: other.exported, + } + } +} + +macro_rules! impl_native_traits { + ( $( $x:ident ),* ) => { + #[allow(unused_parens, non_snake_case)] + impl<$( $x , )* Rets> NativeFunc<( $( $x ),* ), Rets> + where + $( $x: FromToNativeWasmType, )* + Rets: WasmTypeList, + { + /// Call the typed func and return results. + pub fn call(&self, $( $x: $x, )* ) -> Result { + let params_list: Vec = vec![ $( JsValue::from_f64($x.to_native().to_binary() as f64) ),* ]; + let results = self.exported.function.apply( + &JsValue::UNDEFINED, + &Array::from_iter(params_list.iter()) + )?; + let mut rets_list_array = Rets::empty_array(); + let mut_rets = rets_list_array.as_mut() as *mut [i128] as *mut i128; + match Rets::size() { + 0 => {}, + 1 => unsafe { + let ty = Rets::wasm_types()[0]; + let val = param_from_js(&ty, &results); + val.write_value_to(mut_rets); + } + _n => { + let results: Array = results.into(); + for (i, ret_type) in Rets::wasm_types().iter().enumerate() { + let ret = results.get(i as u32); + unsafe { + let val = param_from_js(&ret_type, &ret); + val.write_value_to(mut_rets.add(i)); + } + } + } + } + Ok(Rets::from_array(rets_list_array)) + } + + } + + #[allow(unused_parens)] + impl<'a, $( $x, )* Rets> crate::js::exports::ExportableWithGenerics<'a, ($( $x ),*), Rets> for NativeFunc<( $( $x ),* ), Rets> + where + $( $x: FromToNativeWasmType, )* + Rets: WasmTypeList, + { + fn get_self_from_extern_with_generics(_extern: &crate::js::externals::Extern) -> Result { + use crate::js::exports::Exportable; + crate::js::Function::get_self_from_extern(_extern)?.native().map_err(|_| crate::js::exports::ExportError::IncompatibleType) + } + } + }; +} + +impl_native_traits!(); +impl_native_traits!(A1); +impl_native_traits!(A1, A2); +impl_native_traits!(A1, A2, A3); +impl_native_traits!(A1, A2, A3, A4); +impl_native_traits!(A1, A2, A3, A4, A5); +impl_native_traits!(A1, A2, A3, A4, A5, A6); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16); +impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17); +impl_native_traits!( + A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18 +); +impl_native_traits!( + A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19 +); +impl_native_traits!( + A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20 +); diff --git a/lib/api/src/js/ptr.rs b/lib/api/src/js/ptr.rs new file mode 100644 index 00000000000..e5c0c471b90 --- /dev/null +++ b/lib/api/src/js/ptr.rs @@ -0,0 +1,351 @@ +//! Types for a reusable pointer abstraction for accessing Wasm linear memory. +//! +//! This abstraction is safe: it ensures the memory is in bounds and that the pointer +//! is aligned (avoiding undefined behavior). +//! +//! Therefore, you should use this abstraction whenever possible to avoid memory +//! related bugs when implementing an ABI. + +use crate::js::cell::WasmCell; +use crate::js::{externals::Memory, FromToNativeWasmType}; +use std::{fmt, marker::PhantomData, mem}; +use wasmer_types::ValueType; + +/// The `Array` marker type. This type can be used like `WasmPtr` +/// to get access to methods +pub struct Array; +/// The `Item` marker type. This is the default and does not usually need to be +/// specified. +pub struct Item; + +/// A zero-cost type that represents a pointer to something in Wasm linear +/// memory. +/// +/// This type can be used directly in the host function arguments: +/// ``` +/// # use wasmer::Memory; +/// # use wasmer::WasmPtr; +/// pub fn host_import(memory: Memory, ptr: WasmPtr) { +/// let derefed_ptr = ptr.deref(&memory).expect("pointer in bounds"); +/// let inner_val: u32 = derefed_ptr.get(); +/// println!("Got {} from Wasm memory address 0x{:X}", inner_val, ptr.offset()); +/// // update the value being pointed to +/// derefed_ptr.set(inner_val + 1); +/// } +/// ``` +/// +/// This type can also be used with primitive-filled structs, but be careful of +/// guarantees required by `ValueType`. +/// ``` +/// # use wasmer::Memory; +/// # use wasmer::WasmPtr; +/// # use wasmer::ValueType; +/// +/// #[derive(Copy, Clone, Debug)] +/// #[repr(C)] +/// struct V3 { +/// x: f32, +/// y: f32, +/// z: f32 +/// } +/// // This is safe as the 12 bytes represented by this struct +/// // are valid for all bit combinations. +/// unsafe impl ValueType for V3 { +/// } +/// +/// fn update_vector_3(memory: Memory, ptr: WasmPtr) { +/// let derefed_ptr = ptr.deref(&memory).expect("pointer in bounds"); +/// let mut inner_val: V3 = derefed_ptr.get(); +/// println!("Got {:?} from Wasm memory address 0x{:X}", inner_val, ptr.offset()); +/// // update the value being pointed to +/// inner_val.x = 10.4; +/// derefed_ptr.set(inner_val); +/// } +/// ``` +#[repr(transparent)] +pub struct WasmPtr { + offset: u32, + _phantom: PhantomData<(T, Ty)>, +} + +/// Methods relevant to all types of `WasmPtr`. +impl WasmPtr { + /// Create a new `WasmPtr` at the given offset. + #[inline] + pub fn new(offset: u32) -> Self { + Self { + offset, + _phantom: PhantomData, + } + } + + /// Get the offset into Wasm linear memory for this `WasmPtr`. + #[inline] + pub fn offset(self) -> u32 { + self.offset + } +} + +/// Methods for `WasmPtr`s to data that can be dereferenced, namely to types +/// that implement [`ValueType`], meaning that they're valid for all possible +/// bit patterns. +impl WasmPtr { + /// Dereference the `WasmPtr` getting access to a `&Cell` allowing for + /// reading and mutating of the inner value. + /// + /// This method is unsound if used with unsynchronized shared memory. + /// If you're unsure what that means, it likely does not apply to you. + /// This invariant will be enforced in the future. + #[inline] + pub fn deref<'a>(self, memory: &'a Memory) -> Option> { + let total_len = (self.offset as usize) + mem::size_of::(); + if total_len > memory.size().bytes().0 || mem::size_of::() == 0 { + return None; + } + let subarray = memory.uint8view().subarray(self.offset, total_len as u32); + Some(WasmCell::new(subarray)) + } +} + +/// Methods for `WasmPtr`s to arrays of data that can be dereferenced, namely to +/// types that implement [`ValueType`], meaning that they're valid for all +/// possible bit patterns. +impl WasmPtr { + /// Dereference the `WasmPtr` getting access to a `&[Cell]` allowing for + /// reading and mutating of the inner values. + /// + /// This method is unsound if used with unsynchronized shared memory. + /// If you're unsure what that means, it likely does not apply to you. + /// This invariant will be enforced in the future. + #[inline] + pub fn deref(self, memory: &Memory, index: u32, length: u32) -> Option>> { + // gets the size of the item in the array with padding added such that + // for any index, we will always result an aligned memory access + let item_size = mem::size_of::() as u32; + let slice_full_len = index + length; + let memory_size = memory.size().bytes().0 as u32; + + if self.offset + (item_size * slice_full_len) > memory_size + || self.offset >= memory_size + || item_size == 0 + { + return None; + } + + Some( + (0..length) + .map(|i| { + let subarray = memory.uint8view().subarray( + self.offset + i * item_size, + self.offset + (i + 1) * item_size, + ); + WasmCell::new(subarray) + }) + .collect::>(), + ) + } + + /// Get a UTF-8 string from the `WasmPtr` with the given length. + /// + /// Note that . The + /// underlying data can be mutated if the Wasm is allowed to execute or + /// an aliasing `WasmPtr` is used to mutate memory. + /// + /// # Safety + /// This method returns a reference to Wasm linear memory. The underlying + /// data can be mutated if the Wasm is allowed to execute or an aliasing + /// `WasmPtr` is used to mutate memory. + /// + /// `str` has invariants that must not be broken by mutating Wasm memory. + /// Thus the caller must ensure that the backing memory is not modified + /// while the reference is held. + /// + /// Additionally, if `memory` is dynamic, the caller must also ensure that `memory` + /// is not grown while the reference is held. + pub unsafe fn get_utf8_str<'a>( + self, + memory: &'a Memory, + str_len: u32, + ) -> Option> { + self.get_utf8_string(memory, str_len) + .map(std::borrow::Cow::from) + } + + /// Get a UTF-8 `String` from the `WasmPtr` with the given length. + /// + /// an aliasing `WasmPtr` is used to mutate memory. + pub fn get_utf8_string(self, memory: &Memory, str_len: u32) -> Option { + let memory_size = memory.size().bytes().0; + if self.offset as usize + str_len as usize > memory.size().bytes().0 + || self.offset as usize >= memory_size + { + return None; + } + + let view = memory.uint8view(); + // let subarray_as_vec = view.subarray(self.offset, str_len + 1).to_vec(); + + let mut subarray_as_vec: Vec = Vec::with_capacity(str_len as usize); + let base = self.offset; + for i in 0..(str_len) { + let byte = view.get_index(base + i); + subarray_as_vec.push(byte); + } + + String::from_utf8(subarray_as_vec).ok() + } +} + +unsafe impl FromToNativeWasmType for WasmPtr { + type Native = i32; + + fn to_native(self) -> Self::Native { + self.offset as i32 + } + fn from_native(n: Self::Native) -> Self { + Self { + offset: n as u32, + _phantom: PhantomData, + } + } +} + +unsafe impl ValueType for WasmPtr {} + +impl Clone for WasmPtr { + fn clone(&self) -> Self { + Self { + offset: self.offset, + _phantom: PhantomData, + } + } +} + +impl Copy for WasmPtr {} + +impl PartialEq for WasmPtr { + fn eq(&self, other: &Self) -> bool { + self.offset == other.offset + } +} + +impl Eq for WasmPtr {} + +impl fmt::Debug for WasmPtr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "WasmPtr(offset: {}, pointer: {:#x}, align: {})", + self.offset, + self.offset, + mem::align_of::() + ) + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::js::{Memory, MemoryType, Store}; + use wasm_bindgen_test::*; + + /// Ensure that memory accesses work on the edges of memory and that out of + /// bounds errors are caught with both `deref` and `deref_mut`. + #[wasm_bindgen_test] + fn wasm_ptr_is_functional() { + let store = Store::default(); + let memory_descriptor = MemoryType::new(1, Some(1), false); + let memory = Memory::new(&store, memory_descriptor).unwrap(); + + let start_wasm_ptr: WasmPtr = WasmPtr::new(2); + let val = start_wasm_ptr.deref(&memory).unwrap(); + assert_eq!(val.memory.to_vec(), vec![0; 8]); + + val.set(1200); + + assert_eq!(val.memory.to_vec(), vec![176, 4, 0, 0, 0, 0, 0, 0]); + // Let's make sure the main memory is changed + assert_eq!( + memory.uint8view().subarray(0, 10).to_vec(), + vec![0, 0, 176, 4, 0, 0, 0, 0, 0, 0] + ); + + val.memory.copy_from(&[10, 0, 0, 0, 0, 0, 0, 0]); + + let value = val.get(); + assert_eq!(value, 10); + } + + /// Ensure that memory accesses work on the edges of memory and that out of + /// bounds errors are caught with both `deref` and `deref_mut`. + #[wasm_bindgen_test] + fn wasm_ptr_memory_bounds_checks_hold() { + // create a memory + let store = Store::default(); + let memory_descriptor = MemoryType::new(1, Some(1), false); + let memory = Memory::new(&store, memory_descriptor).unwrap(); + + // test that basic access works and that len = 0 works, but oob does not + let start_wasm_ptr: WasmPtr = WasmPtr::new(0); + let start_wasm_ptr_array: WasmPtr = WasmPtr::new(0); + + assert!(start_wasm_ptr.deref(&memory).is_some()); + assert!(start_wasm_ptr_array.deref(&memory, 0, 0).is_some()); + assert!(unsafe { start_wasm_ptr_array.get_utf8_str(&memory, 0).is_some() }); + assert!(start_wasm_ptr_array.get_utf8_string(&memory, 0).is_some()); + assert!(start_wasm_ptr_array.deref(&memory, 0, 1).is_some()); + + // test that accessing the last valid memory address works correctly and OOB is caught + let last_valid_address_for_u8 = (memory.size().bytes().0 - 1) as u32; + let end_wasm_ptr: WasmPtr = WasmPtr::new(last_valid_address_for_u8); + assert!(end_wasm_ptr.deref(&memory).is_some()); + + let end_wasm_ptr_array: WasmPtr = WasmPtr::new(last_valid_address_for_u8); + + assert!(end_wasm_ptr_array.deref(&memory, 0, 1).is_some()); + let invalid_idx_len_combos: [(u32, u32); 3] = + [(last_valid_address_for_u8 + 1, 0), (0, 2), (1, 1)]; + for &(idx, len) in invalid_idx_len_combos.iter() { + assert!(end_wasm_ptr_array.deref(&memory, idx, len).is_none()); + } + assert!(unsafe { end_wasm_ptr_array.get_utf8_str(&memory, 2).is_none() }); + assert!(end_wasm_ptr_array.get_utf8_string(&memory, 2).is_none()); + + // test that accesing the last valid memory address for a u32 is valid + // (same as above test but with more edge cases to assert on) + let last_valid_address_for_u32 = (memory.size().bytes().0 - 4) as u32; + let end_wasm_ptr: WasmPtr = WasmPtr::new(last_valid_address_for_u32); + assert!(end_wasm_ptr.deref(&memory).is_some()); + assert!(end_wasm_ptr.deref(&memory).is_some()); + + let end_wasm_ptr_oob_array: [WasmPtr; 4] = [ + WasmPtr::new(last_valid_address_for_u32 + 1), + WasmPtr::new(last_valid_address_for_u32 + 2), + WasmPtr::new(last_valid_address_for_u32 + 3), + WasmPtr::new(last_valid_address_for_u32 + 4), + ]; + for oob_end_ptr in end_wasm_ptr_oob_array.iter() { + assert!(oob_end_ptr.deref(&memory).is_none()); + } + let end_wasm_ptr_array: WasmPtr = WasmPtr::new(last_valid_address_for_u32); + assert!(end_wasm_ptr_array.deref(&memory, 0, 1).is_some()); + + let invalid_idx_len_combos: [(u32, u32); 3] = + [(last_valid_address_for_u32 + 1, 0), (0, 2), (1, 1)]; + for &(idx, len) in invalid_idx_len_combos.iter() { + assert!(end_wasm_ptr_array.deref(&memory, idx, len).is_none()); + } + + let end_wasm_ptr_array_oob_array: [WasmPtr; 4] = [ + WasmPtr::new(last_valid_address_for_u32 + 1), + WasmPtr::new(last_valid_address_for_u32 + 2), + WasmPtr::new(last_valid_address_for_u32 + 3), + WasmPtr::new(last_valid_address_for_u32 + 4), + ]; + + for oob_end_array_ptr in end_wasm_ptr_array_oob_array.iter() { + assert!(oob_end_array_ptr.deref(&memory, 0, 1).is_none()); + assert!(oob_end_array_ptr.deref(&memory, 1, 0).is_none()); + } + } +} diff --git a/lib/api/src/js/resolver.rs b/lib/api/src/js/resolver.rs new file mode 100644 index 00000000000..6f373eac145 --- /dev/null +++ b/lib/api/src/js/resolver.rs @@ -0,0 +1,165 @@ +use crate::js::export::Export; + +/// Import resolver connects imports with available exported values. +pub trait Resolver { + /// Resolves an import a WebAssembly module to an export it's hooked up to. + /// + /// The `index` provided is the index of the import in the wasm module + /// that's being resolved. For example 1 means that it's the second import + /// listed in the wasm module. + /// + /// The `module` and `field` arguments provided are the module/field names + /// listed on the import itself. + /// + /// # Notes: + /// + /// The index is useful because some WebAssembly modules may rely on that + /// for resolving ambiguity in their imports. Such as: + /// ```ignore + /// (module + /// (import "" "" (func)) + /// (import "" "" (func (param i32) (result i32))) + /// ) + /// ``` + fn resolve(&self, _index: u32, module: &str, field: &str) -> Option; +} + +/// Import resolver connects imports with available exported values. +/// +/// This is a specific subtrait for [`Resolver`] for those users who don't +/// care about the `index`, but only about the `module` and `field` for +/// the resolution. +pub trait NamedResolver { + /// Resolves an import a WebAssembly module to an export it's hooked up to. + /// + /// It receives the `module` and `field` names and return the [`Export`] in + /// case it's found. + fn resolve_by_name(&self, module: &str, field: &str) -> Option; +} + +// All NamedResolvers should extend `Resolver`. +impl Resolver for T { + /// By default this method will be calling [`NamedResolver::resolve_by_name`], + /// dismissing the provided `index`. + fn resolve(&self, _index: u32, module: &str, field: &str) -> Option { + self.resolve_by_name(module, field) + } +} + +impl NamedResolver for &T { + fn resolve_by_name(&self, module: &str, field: &str) -> Option { + (**self).resolve_by_name(module, field) + } +} + +impl NamedResolver for Box { + fn resolve_by_name(&self, module: &str, field: &str) -> Option { + (**self).resolve_by_name(module, field) + } +} + +impl NamedResolver for () { + /// Always returns `None`. + fn resolve_by_name(&self, _module: &str, _field: &str) -> Option { + None + } +} + +/// `Resolver` implementation that always resolves to `None`. Equivalent to `()`. +pub struct NullResolver {} + +impl Resolver for NullResolver { + fn resolve(&self, _idx: u32, _module: &str, _field: &str) -> Option { + None + } +} + +/// A [`Resolver`] that links two resolvers together in a chain. +pub struct NamedResolverChain { + a: A, + b: B, +} + +/// A trait for chaining resolvers together. +/// +/// ``` +/// # use wasmer_engine::{ChainableNamedResolver, NamedResolver}; +/// # fn chainable_test(imports1: A, imports2: B) +/// # where A: NamedResolver + Sized, +/// # B: NamedResolver + Sized, +/// # { +/// // override duplicates with imports from `imports2` +/// imports1.chain_front(imports2); +/// # } +/// ``` +pub trait ChainableNamedResolver: NamedResolver + Sized { + /// Chain a resolver in front of the current resolver. + /// + /// This will cause the second resolver to override the first. + /// + /// ``` + /// # use wasmer_engine::{ChainableNamedResolver, NamedResolver}; + /// # fn chainable_test(imports1: A, imports2: B) + /// # where A: NamedResolver + Sized, + /// # B: NamedResolver + Sized, + /// # { + /// // override duplicates with imports from `imports2` + /// imports1.chain_front(imports2); + /// # } + /// ``` + fn chain_front(self, other: U) -> NamedResolverChain + where + U: NamedResolver, + { + NamedResolverChain { a: other, b: self } + } + + /// Chain a resolver behind the current resolver. + /// + /// This will cause the first resolver to override the second. + /// + /// ``` + /// # use wasmer_engine::{ChainableNamedResolver, NamedResolver}; + /// # fn chainable_test(imports1: A, imports2: B) + /// # where A: NamedResolver + Sized, + /// # B: NamedResolver + Sized, + /// # { + /// // override duplicates with imports from `imports1` + /// imports1.chain_back(imports2); + /// # } + /// ``` + fn chain_back(self, other: U) -> NamedResolverChain + where + U: NamedResolver, + { + NamedResolverChain { a: self, b: other } + } +} + +// We give these chain methods to all types implementing NamedResolver +impl ChainableNamedResolver for T {} + +impl NamedResolver for NamedResolverChain +where + A: NamedResolver, + B: NamedResolver, +{ + fn resolve_by_name(&self, module: &str, field: &str) -> Option { + self.a + .resolve_by_name(module, field) + .or_else(|| self.b.resolve_by_name(module, field)) + } +} + +impl Clone for NamedResolverChain +where + A: NamedResolver + Clone, + B: NamedResolver + Clone, +{ + fn clone(&self) -> Self { + Self { + a: self.a.clone(), + b: self.b.clone(), + } + } +} diff --git a/lib/api/src/js/store.rs b/lib/api/src/js/store.rs new file mode 100644 index 00000000000..88c8b068f78 --- /dev/null +++ b/lib/api/src/js/store.rs @@ -0,0 +1,59 @@ +use std::fmt; + +/// The store represents all global state that can be manipulated by +/// WebAssembly programs. It consists of the runtime representation +/// of all instances of functions, tables, memories, and globals that +/// have been allocated during the lifetime of the abstract machine. +/// +/// The `Store` holds the engine (that is —amongst many things— used to compile +/// the Wasm bytes into a valid module artifact), in addition to the +/// [`Tunables`] (that are used to create the memories, tables and globals). +/// +/// Spec: +#[derive(Clone)] +pub struct Store; + +impl Store { + /// Creates a new `Store`. + pub fn new() -> Self { + Self + } + + /// Checks whether two stores are identical. A store is considered + /// equal to another store if both have the same engine. The + /// tunables are excluded from the logic. + pub fn same(_a: &Self, _b: &Self) -> bool { + true + } +} + +impl PartialEq for Store { + fn eq(&self, other: &Self) -> bool { + Self::same(self, other) + } +} + +// This is required to be able to set the trap_handler in the +// Store. +unsafe impl Send for Store {} +unsafe impl Sync for Store {} + +impl Default for Store { + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for Store { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Store").finish() + } +} + +/// A trait represinting any object that lives in the `Store`. +pub trait StoreObject { + /// Return true if the object `Store` is the same as the provided `Store`. + fn comes_from_same_store(&self, _store: &Store) -> bool { + true + } +} diff --git a/lib/api/src/js/trap.rs b/lib/api/src/js/trap.rs new file mode 100644 index 00000000000..732e57382ff --- /dev/null +++ b/lib/api/src/js/trap.rs @@ -0,0 +1,163 @@ +// use super::frame_info::{FrameInfo, GlobalFrameInfo, FRAME_INFO}; +use std::error::Error; +use std::fmt; +use std::sync::Arc; +use wasm_bindgen::convert::FromWasmAbi; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsValue; + +/// A struct representing an aborted instruction execution, with a message +/// indicating the cause. +#[wasm_bindgen] +#[derive(Clone)] +pub struct WasmerRuntimeError { + inner: Arc, +} + +/// This type is the same as `WasmerRuntimeError`. +/// +/// We use the `WasmerRuntimeError` name to not collide with the +/// `RuntimeError` in JS. +pub type RuntimeError = WasmerRuntimeError; + +impl PartialEq for RuntimeError { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.inner, &other.inner) + } +} + +/// The source of the `RuntimeError`. +#[derive(Debug)] +enum RuntimeErrorSource { + Generic(String), + User(Box), + Js(JsValue), +} + +impl fmt::Display for RuntimeErrorSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Generic(s) => write!(f, "{}", s), + Self::User(s) => write!(f, "{}", s), + Self::Js(s) => write!(f, "{}", s.as_string().unwrap_or("".to_string())), + } + } +} + +impl RuntimeError { + /// Creates a new generic `RuntimeError` with the given `message`. + /// + /// # Example + /// ``` + /// let trap = wasmer_engine::RuntimeError::new("unexpected error"); + /// assert_eq!("unexpected error", trap.message()); + /// ``` + pub fn new>(message: I) -> Self { + RuntimeError { + inner: Arc::new(RuntimeErrorSource::Generic(message.into())), + } + } + + /// Creates a new user `RuntimeError` with the given `error`. + pub fn user(error: impl Error + Send + Sync + 'static) -> Self { + RuntimeError { + inner: Arc::new(RuntimeErrorSource::User(Box::new(error))), + } + } + + /// Raises a custom user Error + pub fn raise(error: Box) -> ! { + let error = if error.is::() { + *error.downcast::().unwrap() + } else { + RuntimeError { + inner: Arc::new(RuntimeErrorSource::User(error)), + } + }; + let js_error: JsValue = error.into(); + wasm_bindgen::throw_val(js_error) + } + + /// Returns a reference the `message` stored in `Trap`. + pub fn message(&self) -> String { + format!("{}", self.inner) + } + + /// Attempts to downcast the `RuntimeError` to a concrete type. + pub fn downcast(self) -> Result { + match Arc::try_unwrap(self.inner) { + // We only try to downcast user errors + Ok(RuntimeErrorSource::User(err)) if err.is::() => Ok(*err.downcast::().unwrap()), + Ok(inner) => Err(Self { + inner: Arc::new(inner), + }), + Err(inner) => Err(Self { inner }), + } + } + + /// Returns true if the `RuntimeError` is the same as T + pub fn is(&self) -> bool { + match self.inner.as_ref() { + RuntimeErrorSource::User(err) => err.is::(), + _ => false, + } + } +} + +impl fmt::Debug for RuntimeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RuntimeError") + .field("source", &self.inner) + .finish() + } +} + +impl fmt::Display for RuntimeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "RuntimeError: {}", self.message())?; + Ok(()) + } +} + +impl std::error::Error for RuntimeError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self.inner.as_ref() { + RuntimeErrorSource::User(err) => Some(&**err), + _ => None, + } + } +} + +pub fn generic_of_jsval>( + js: JsValue, + classname: &str, +) -> Result { + use js_sys::{Object, Reflect}; + let ctor_name = Object::get_prototype_of(&js).constructor().name(); + if ctor_name == classname { + let ptr = Reflect::get(&js, &JsValue::from_str("ptr"))?; + match ptr.as_f64() { + Some(ptr_f64) => { + let foo = unsafe { T::from_abi(ptr_f64 as u32) }; + Ok(foo) + } + None => { + // We simply relay the js value + Err(js) + } + } + } else { + Err(js) + } +} + +impl From for RuntimeError { + fn from(original: JsValue) -> Self { + // We try to downcast the error and see if it's + // an instance of RuntimeError instead, so we don't need + // to re-wrap it. + generic_of_jsval(original, "WasmerRuntimeError").unwrap_or_else(|js| RuntimeError { + inner: Arc::new(RuntimeErrorSource::Js(js)), + }) + } +} diff --git a/lib/api/src/js/types.rs b/lib/api/src/js/types.rs new file mode 100644 index 00000000000..8b9723987f8 --- /dev/null +++ b/lib/api/src/js/types.rs @@ -0,0 +1,52 @@ +use crate::js::externals::Function; +// use crate::js::store::{Store, StoreObject}; +// use crate::js::RuntimeError; +use wasm_bindgen::JsValue; +use wasmer_types::Value; +pub use wasmer_types::{ + ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, + TableType, Type as ValType, +}; + +/// WebAssembly computations manipulate values of basic value types: +/// * Integers (32 or 64 bit width) +/// * Floating-point (32 or 64 bit width) +/// * Vectors (128 bits, with 32 or 64 bit lanes) +/// +/// Spec: +// pub type Val = (); +pub type Val = Value; + +pub trait AsJs { + fn as_jsvalue(&self) -> JsValue; +} + +#[inline] +pub fn param_from_js(ty: &ValType, js_val: &JsValue) -> Val { + match ty { + ValType::I32 => Val::I32(js_val.as_f64().unwrap() as _), + ValType::I64 => Val::I64(js_val.as_f64().unwrap() as _), + ValType::F32 => Val::F32(js_val.as_f64().unwrap() as _), + ValType::F64 => Val::F64(js_val.as_f64().unwrap()), + t => unimplemented!( + "The type `{:?}` is not yet supported in the JS Function API", + t + ), + } +} + +impl AsJs for Val { + fn as_jsvalue(&self) -> JsValue { + match self { + Self::I32(i) => JsValue::from_f64(*i as f64), + Self::I64(i) => JsValue::from_f64(*i as f64), + Self::F32(f) => JsValue::from_f64(*f as f64), + Self::F64(f) => JsValue::from_f64(*f), + Self::FuncRef(func) => func.as_ref().unwrap().exported.function.clone().into(), + v => unimplemented!( + "The value `{:?}` is not yet supported in the JS Function API", + v + ), + } + } +} diff --git a/lib/api/src/utils.rs b/lib/api/src/js/utils.rs similarity index 100% rename from lib/api/src/utils.rs rename to lib/api/src/js/utils.rs diff --git a/lib/api/src/js/wasm_bindgen_polyfill.rs b/lib/api/src/js/wasm_bindgen_polyfill.rs new file mode 100644 index 00000000000..1b5dad63a12 --- /dev/null +++ b/lib/api/src/js/wasm_bindgen_polyfill.rs @@ -0,0 +1,31 @@ +use js_sys::Object; +use wasm_bindgen::prelude::*; + +// WebAssembly.Global +#[wasm_bindgen] +extern "C" { + /// The `WebAssembly.Global()` constructor creates a new `Global` object + /// of the given type and value. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global) + #[wasm_bindgen(js_namespace = WebAssembly, extends = Object, typescript_type = "WebAssembly.Global")] + #[derive(Clone, Debug, PartialEq, Eq)] + pub type Global; + + /// The `WebAssembly.Global()` constructor creates a new `Global` object + /// of the given type and value. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global) + #[wasm_bindgen(constructor, js_namespace = WebAssembly, catch)] + pub fn new(global_descriptor: &Object, value: &JsValue) -> Result; + + /// The value prototype property of the `WebAssembly.Global` object + /// returns the value of the global. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global) + #[wasm_bindgen(method, getter, structural, js_namespace = WebAssembly)] + pub fn value(this: &Global) -> JsValue; + + #[wasm_bindgen(method, setter = value, structural, js_namespace = WebAssembly)] + pub fn set_value(this: &Global, value: &JsValue); +} diff --git a/lib/api/src/lib.rs b/lib/api/src/lib.rs index b92cdc77563..49d535beb03 100644 --- a/lib/api/src/lib.rs +++ b/lib/api/src/lib.rs @@ -26,19 +26,29 @@ clippy::use_self ) )] +#![cfg_attr(feature = "js", crate_type = "cdylib")] +#![cfg_attr(feature = "js", crate_type = "rlib")] -//! This crate contains the `wasmer` API. The `wasmer` API facilitates the efficient, -//! sandboxed execution of [WebAssembly (Wasm)][wasm] modules. +//! [`Wasmer`](https://wasmer.io/) is the most popular +//! [WebAssembly](https://webassembly.org/) runtime for Rust. It supports +//! JIT (Just In Time) and AOT (Ahead Of Time) compilation as well as +//! pluggable compilers suited to your needs. //! -//! Here's an example of the `wasmer` API in action: -//! ``` +//! It's designed to be safe and secure, and runnable in any kind of environment. +//! +//! # Usage +//! +//! Here is a small example of using Wasmer to run a WebAssembly module +//! written with its WAT format (textual format): +//! +//! ```rust //! use wasmer::{Store, Module, Instance, Value, imports}; //! //! fn main() -> anyhow::Result<()> { //! let module_wat = r#" //! (module -//! (type $t0 (func (param i32) (result i32))) -//! (func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32) +//! (type $t0 (func (param i32) (result i32))) +//! (func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32) //! get_local $p0 //! i32.const 1 //! i32.add)) @@ -58,14 +68,63 @@ //! } //! ``` //! -//! For more examples of using the `wasmer` API, check out the -//! [wasmer examples][wasmer-examples]. -//! -//! --------- +//! [Discover the full collection of examples](https://github.com/wasmerio/wasmer/tree/master/examples). +//! +//! # Overview of the Features +//! +//! Wasmer is not only fast, but also designed to be *highly customizable*: +//! +//! * **Pluggable engines** — An engine is responsible to drive the +//! compilation process and to store the generated executable code +//! somewhere, either: +//! * in-memory (with [`wasmer-engine-universal`]), +//! * in a native shared object file (with [`wasmer-engine-dylib`], +//! `.dylib`, `.so`, `.dll`), then load it with `dlopen`, +//! * in a native static object file (with [`wasmer-engine-staticlib`]), +//! in addition to emitting a C header file, which both can be linked +//! against a sandboxed WebAssembly runtime environment for the +//! compiled module with no need for runtime compilation. +//! +//! * **Pluggable compilers** — A compiler is used by an engine to +//! transform WebAssembly into executable code: +//! * [`wasmer-compiler-singlepass`] provides a fast compilation-time +//! but an unoptimized runtime speed, +//! * [`wasmer-compiler-cranelift`] provides the right balance between +//! compilation-time and runtime performance, useful for development, +//! * [`wasmer-compiler-llvm`] provides a deeply optimized executable +//! code with the fastest runtime speed, ideal for production. +//! +//! * **Headless mode** — Once a WebAssembly module has been compiled, it +//! is possible to serialize it in a file for example, and later execute +//! it with Wasmer with headless mode turned on. Headless Wasmer has no +//! compiler, which makes it more portable and faster to load. It's +//! ideal for constrainted environments. +//! +//! * **Cross-compilation** — Most compilers support cross-compilation. It +//! means it possible to pre-compile a WebAssembly module targetting a +//! different architecture or platform and serialize it, to then run it +//! on the targetted architecture and platform later. +//! +//! * **Run Wasmer in a JavaScript environment** — With the `js` Cargo +//! feature, it is possible to compile a Rust program using Wasmer to +//! WebAssembly. In this context, the resulting WebAssembly module will +//! expect to run in a JavaScript environment, like a browser, Node.js, +//! Deno and so on. In this specific scenario, there is no engines or +//! compilers available, it's the one available in the JavaScript +//! environment that will be used. +//! +//! Wasmer ships by default with the Cranelift compiler as its great for +//! development purposes. However, we strongly encourage to use the LLVM +//! compiler in production as it performs about 50% faster, achieving +//! near-native speeds. +//! +//! Note: if one wants to use multiple compilers at the same time, it's +//! also possible! One will need to import them directly via each of the +//! compiler crates. //! //! # Table of Contents //! -//! - [Wasm Primitives](#wasm-primitives) +//! - [WebAssembly Primitives](#webassembly-primitives) //! - [Externs](#externs) //! - [Functions](#functions) //! - [Memories](#memories) @@ -74,10 +133,12 @@ //! - [Project Layout](#project-layout) //! - [Engines](#engines) //! - [Compilers](#compilers) -//! - [Features](#features) +//! - [Cargo Features](#cargo-features) +//! - [Using Wasmer in a JavaScript environment](#using-wasmer-in-a-javascript-environment) +//! //! +//! # WebAssembly Primitives //! -//! # Wasm Primitives //! In order to make use of the power of the `wasmer` API, it's important //! to understand the primitives around which the API is built. //! @@ -88,6 +149,7 @@ //! referred to as "externs". //! //! ## Externs +//! //! An [`Extern`] is a type that can be imported or exported from a Wasm //! module. //! @@ -125,9 +187,10 @@ //! These are the primary types that the `wasmer` API uses. //! //! ### Functions +//! //! There are 2 types of functions in `wasmer`: -//! 1. Wasm functions -//! 2. Host functions +//! 1. Wasm functions, +//! 2. Host functions. //! //! A Wasm function is a function defined in a WebAssembly module that can //! only perform computation without side effects and call other functions. @@ -148,7 +211,7 @@ //! give them access to the outside world with [`imports`]. //! //! If you're looking for a sandboxed, POSIX-like environment to execute Wasm -//! in, check out the [`wasmer-wasi`][wasmer-wasi] crate for our implementation of WASI, +//! in, check out the [`wasmer-wasi`] crate for our implementation of WASI, //! the WebAssembly System Interface. //! //! In the `wasmer` API we support functions which take their arguments and @@ -156,6 +219,7 @@ //! take their arguments and return their results statically, [`NativeFunc`]. //! //! ### Memories +//! //! Memories store data. //! //! In most Wasm programs, nearly all data will live in a [`Memory`]. @@ -164,14 +228,15 @@ //! interesting programs. //! //! ### Globals +//! //! A [`Global`] is a type that may be either mutable or immutable, and //! contains one of the core Wasm types defined in [`Value`]. //! //! ### Tables -//! A [`Table`] is an indexed list of items. //! +//! A [`Table`] is an indexed list of items. //! -//! ## Project Layout +//! # Project Layout //! //! The Wasmer project is divided into a number of crates, below is a dependency //! graph with transitive dependencies removed. @@ -183,202 +248,226 @@ //! While this crate is the top level API, we also publish crates built //! on top of this API that you may be interested in using, including: //! -//! - [wasmer-cache][] for caching compiled Wasm modules. -//! - [wasmer-emscripten][] for running Wasm modules compiled to the -//! Emscripten ABI. -//! - [wasmer-wasi][] for running Wasm modules compiled to the WASI ABI. -//! -//! -------- +//! - [`wasmer-cache`] for caching compiled Wasm modules, +//! - [`wasmer-emscripten`] for running Wasm modules compiled to the +//! Emscripten ABI, +//! - [`wasmer-wasi`] for running Wasm modules compiled to the WASI ABI. //! //! The Wasmer project has two major abstractions: -//! 1. [Engines][wasmer-engine] -//! 2. [Compilers][wasmer-compiler] +//! 1. [Engines][wasmer-engine], +//! 2. [Compilers][wasmer-compiler]. //! //! These two abstractions have multiple options that can be enabled //! with features. //! -//! ### Engines +//! ## Engines //! //! An engine is a system that uses a compiler to make a WebAssembly //! module executable. //! -//! ### Compilers +//! ## Compilers //! //! A compiler is a system that handles the details of making a Wasm //! module executable. For example, by generating native machine code //! for each Wasm function. //! +//! # Cargo Features //! -//! ## Features +//! This crate comes in 2 flavors: //! -//! This crate's features can be broken down into 2 kinds, features that -//! enable new functionality and features that set defaults. +//! 1. `sys` +#![cfg_attr(feature = "sys", doc = "(enabled),")] +#![cfg_attr(not(feature = "sys"), doc = "(disabled),")] +//! where `wasmer` will be compiled to a native executable +//! which provides compilers, engines, a full VM etc. +//! 2. `js` +#![cfg_attr(feature = "js", doc = "(enabled),")] +#![cfg_attr(not(feature = "js"), doc = "(disabled),")] +//! where `wasmer` will be compiled to WebAssembly to run in a +//! JavaScript host (see [Using Wasmer in a JavaScript +//! environment](#using-wasmer-in-a-javascript-environment)). +//! +//! Consequently, we can group the features by the `sys` or `js` +//! features. +//! +#![cfg_attr( + feature = "sys", + doc = "## Features for the `sys` feature group (enabled)" +)] +#![cfg_attr( + not(feature = "sys"), + doc = "## Features for the `sys` feature group (disabled)" +)] +//! +//! The default features can be enabled with the `sys-default` feature. +//! +//! The features for the `sys` feature group can be broken down into 2 +//! kinds: features that enable new functionality and features that +//! set defaults. //! //! The features that enable new functionality are: -//! - `universal` - enable the Universal engine. (See [wasmer-universal][]) -//! - `native` - enable the native engine. (See [wasmer-native][]) -//! - `cranelift` - enable Wasmer's Cranelift compiler. (See [wasmer-cranelift][]) -//! - `llvm` - enable Wasmer's LLVM compiler. (See [wasmer-llvm][]) -//! - `singlepass` - enable Wasmer's Singlepass compiler. (See [wasmer-singlepass][]) -//! - `wat` - enable `wasmer` to parse the WebAssembly text format. +//! - `cranelift` +#![cfg_attr(feature = "cranelift", doc = "(enabled),")] +#![cfg_attr(not(feature = "cranelift"), doc = "(disabled),")] +//! enables Wasmer's [Cranelift compiler][wasmer-compiler-cranelift], +//! - `llvm` +#![cfg_attr(feature = "llvm", doc = "(enabled),")] +#![cfg_attr(not(feature = "llvm"), doc = "(disabled),")] +//! enables Wasmer's [LLVM compiler][wasmer-compiler-lvm], +//! - `singlepass` +#![cfg_attr(feature = "singlepass", doc = "(enabled),")] +#![cfg_attr(not(feature = "singlepass"), doc = "(disabled),")] +//! enables Wasmer's [Singlepass compiler][wasmer-compiler-singlepass], +//! - `wat` +#![cfg_attr(feature = "wat", doc = "(enabled),")] +#![cfg_attr(not(feature = "wat"), doc = "(disabled),")] +//! enables `wasmer` to parse the WebAssembly text format, +//! - `universal` +#![cfg_attr(feature = "universal", doc = "(enabled),")] +#![cfg_attr(not(feature = "universal"), doc = "(disabled),")] +//! enables [the Universal engine][`wasmer-engine-universal`], +//! - `dylib` +#![cfg_attr(feature = "dylib", doc = "(enabled),")] +#![cfg_attr(not(feature = "dylib"), doc = "(disabled),")] +//! enables [the Dylib engine][`wasmer-engine-dylib`]. //! //! The features that set defaults come in sets that are mutually exclusive. //! //! The first set is the default compiler set: -//! - `default-cranelift` - set Wasmer's Cranelift compiler as the default. -//! - `default-llvm` - set Wasmer's LLVM compiler as the default. -//! - `default-singlepass` - set Wasmer's Singlepass compiler as the default. +//! - `default-cranelift` +#![cfg_attr(feature = "default-cranelift", doc = "(enabled),")] +#![cfg_attr(not(feature = "default-cranelift"), doc = "(disabled),")] +//! set Wasmer's Cranelift compiler as the default, +//! - `default-llvm` +#![cfg_attr(feature = "default-llvm", doc = "(enabled),")] +#![cfg_attr(not(feature = "default-llvm"), doc = "(disabled),")] +//! set Wasmer's LLVM compiler as the default, +//! - `default-singlepass` +#![cfg_attr(feature = "default-singlepass", doc = "(enabled),")] +#![cfg_attr(not(feature = "default-singlepass"), doc = "(disabled),")] +//! set Wasmer's Singlepass compiler as the default. //! //! The next set is the default engine set: -//! - `default-universal` - set the Universal engine as the default. -//! - `default-native` - set the native engine as the default. +//! - `default-universal` +#![cfg_attr(feature = "default-universal", doc = "(enabled),")] +#![cfg_attr(not(feature = "default-universal"), doc = "(disabled),")] +//! set the Universal engine as the default, +//! - `default-dylib` +#![cfg_attr(feature = "default-dylib", doc = "(enabled),")] +#![cfg_attr(not(feature = "default-dylib"), doc = "(disabled),")] +//! set the Dylib engine as the default. +//! +#![cfg_attr( + feature = "js", + doc = "## Features for the `js` feature group (enabled)" +)] +#![cfg_attr( + not(feature = "js"), + doc = "## Features for the `js` feature group (disabled)" +)] //! -//! -------- +//! The default features can be enabled with the `js-default` feature. +//! +//! Here are the detailed list of features: +//! +//! - `wasm-types-polyfill` +#![cfg_attr(feature = "wasm-types-polyfill", doc = "(enabled),")] +#![cfg_attr(not(feature = "wasm-types-polyfill"), doc = "(disabled),")] +//! parses the Wasm file, allowing to do type reflection of the +//! inner Wasm types. It adds 100kb to the Wasm bundle (28kb +//! gzipped). It is possible to disable it and to use +//! `Module::set_type_hints` manually instead for a lightweight +//! alternative. This is needed until the [Wasm JS introspection API +//! proposal](https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md) +//! is adopted by browsers, +//! - `wat` +#![cfg_attr(feature = "wat", doc = "(enabled),")] +#![cfg_attr(not(feature = "wat"), doc = "(disabled),")] +//! allows to read a Wasm file in its text format. This feature is +//! normally used only in development environments. It will add +//! around 650kb to the Wasm bundle (120Kb gzipped). +//! +//! # Using Wasmer in a JavaScript environment +//! +//! Imagine a Rust program that uses this `wasmer` crate to execute a +//! WebAssembly module. It is possible to compile this Rust progam to +//! WebAssembly by turning on the `js` Cargo feature of this `wasmer` +//! crate. +//! +//! Here is a small example illustrating such a Rust program, and how +//! to compile it with [`wasm-pack`] and [`wasm-bindgen`]: +//! +//! ```ignore +//! #[wasm_bindgen] +//! pub extern fn do_add_one_in_wasmer() -> i32 { +//! let module_wat = r#" +//! (module +//! (type $t0 (func (param i32) (result i32))) +//! (func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32) +//! get_local $p0 +//! i32.const 1 +//! i32.add)) +//! "#; +//! let store = Store::default(); +//! let module = Module::new(&store, &module_wat).unwrap(); +//! // The module doesn't import anything, so we create an empty import object. +//! let import_object = imports! {}; +//! let instance = Instance::new(&module, &import_object).unwrap(); +//! +//! let add_one = instance.exports.get_function("add_one").unwrap(); +//! let result = add_one.call(&[Value::I32(42)]).unwrap(); +//! assert_eq!(result[0], Value::I32(43)); //! -//! By default the `wat`, `default-cranelift`, and `default-universal` features -//! are enabled. +//! result[0].unwrap_i32() +//! } +//! ``` //! +//! Note that it's the same code as above with the former example. The +//! API is the same! //! +//! Then, compile with `wasm-pack build`. Take care of using the `js` +//! or `js-default` Cargo features. //! //! [wasm]: https://webassembly.org/ //! [wasmer-examples]: https://github.com/wasmerio/wasmer/tree/master/examples -//! [wasmer-cache]: https://docs.rs/wasmer-cache/*/wasmer_cache/ -//! [wasmer-compiler]: https://docs.rs/wasmer-compiler/*/wasmer_compiler/ -//! [wasmer-cranelift]: https://docs.rs/wasmer-compiler-cranelift/*/wasmer_compiler_cranelift/ -//! [wasmer-emscripten]: https://docs.rs/wasmer-emscripten/*/wasmer_emscripten/ -//! [wasmer-engine]: https://docs.rs/wasmer-engine/*/wasmer_engine/ -//! [wasmer-universal]: https://docs.rs/wasmer-engine-universal/*/wasmer_engine_universal/ -//! [wasmer-native]: https://docs.rs/wasmer-engine-dylib/*/wasmer_engine_dylib/ -//! [wasmer-singlepass]: https://docs.rs/wasmer-compiler-singlepass/*/wasmer_compiler_singlepass/ -//! [wasmer-llvm]: https://docs.rs/wasmer-compiler-llvm/*/wasmer_compiler_llvm/ -//! [wasmer-wasi]: https://docs.rs/wasmer-wasi/*/wasmer_wasi/ +//! [`wasmer-cache`]: https://docs.rs/wasmer-cache/ +//! [wasmer-compiler]: https://docs.rs/wasmer-compiler/ +//! [`wasmer-emscripten`]: https://docs.rs/wasmer-emscripten/ +//! [wasmer-engine]: https://docs.rs/wasmer-engine/ +//! [`wasmer-engine-universal`]: https://docs.rs/wasmer-engine-universal/ +//! [`wasmer-engine-dylib`]: https://docs.rs/wasmer-engine-dylib/ +//! [`wasmer-engine-staticlib`]: https://docs.rs/wasmer-engine-staticlib/ +//! [`wasmer-compiler-singlepass`]: https://docs.rs/wasmer-compiler-singlepass/ +//! [`wasmer-compiler-llvm`]: https://docs.rs/wasmer-compiler-llvm/ +//! [`wasmer-compiler-cranelift`]: https://docs.rs/wasmer-compiler-cranelift/ +//! [`wasmer-wasi`]: https://docs.rs/wasmer-wasi/ +//! [`wasm-pack`]: https://github.com/rustwasm/wasm-pack/ +//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen -mod cell; -mod env; -mod exports; -mod externals; -mod import_object; -mod instance; -mod module; -mod native; -mod ptr; -mod store; -mod tunables; -mod types; -mod utils; +#[cfg(all(not(feature = "sys"), not(feature = "js")))] +compile_error!("At least the `sys` or the `js` feature must be enabled. Please, pick one."); -/// Implement [`WasmerEnv`] for your type with `#[derive(WasmerEnv)]`. -/// -/// See the [`WasmerEnv`] trait for more information. -pub use wasmer_derive::WasmerEnv; - -#[doc(hidden)] -pub mod internals { - //! We use the internals module for exporting types that are only - //! intended to use in internal crates such as the compatibility crate - //! `wasmer-vm`. Please don't use any of this types directly, as - //! they might change frequently or be removed in the future. - - pub use crate::externals::{WithEnv, WithoutEnv}; -} - -pub use crate::cell::WasmCell; -pub use crate::env::{HostEnvInitError, LazyInit, WasmerEnv}; -pub use crate::exports::{ExportError, Exportable, Exports, ExportsIterator}; -pub use crate::externals::{ - Extern, FromToNativeWasmType, Function, Global, HostFunction, Memory, Table, WasmTypeList, -}; -pub use crate::import_object::{ImportObject, ImportObjectIterator, LikeNamespace}; -pub use crate::instance::{Instance, InstantiationError}; -pub use crate::module::Module; -pub use crate::native::NativeFunc; -pub use crate::ptr::{Array, Item, WasmPtr}; -pub use crate::store::{Store, StoreObject}; -pub use crate::tunables::BaseTunables; -pub use crate::types::{ - ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, - TableType, Val, ValType, -}; -pub use crate::types::{Val as Value, ValType as Type}; -pub use crate::utils::is_wasm; -pub use target_lexicon::{Architecture, CallingConvention, OperatingSystem, Triple, HOST}; -#[cfg(feature = "compiler")] -pub use wasmer_compiler::{ - wasmparser, CompilerConfig, FunctionMiddleware, MiddlewareError, MiddlewareReaderState, - ModuleMiddleware, -}; -pub use wasmer_compiler::{ - CompileError, CpuFeature, Features, ParseCpuFeatureError, Target, WasmError, WasmResult, -}; -pub use wasmer_engine::{ - ChainableNamedResolver, DeserializeError, Engine, Export, FrameInfo, LinkError, NamedResolver, - NamedResolverChain, Resolver, RuntimeError, SerializeError, Tunables, -}; -#[cfg(feature = "experimental-reference-types-extern-ref")] -pub use wasmer_types::ExternRef; -pub use wasmer_types::{ - Atomically, Bytes, ExportIndex, GlobalInit, LocalFunctionIndex, MemoryView, Pages, ValueType, - WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE, -}; - -// TODO: should those be moved into wasmer::vm as well? -pub use wasmer_vm::{raise_user_trap, MemoryError}; -pub mod vm { - //! The vm module re-exports wasmer-vm types. - - pub use wasmer_vm::{ - Memory, MemoryError, MemoryStyle, Table, TableStyle, VMExtern, VMMemoryDefinition, - VMTableDefinition, - }; -} - -#[cfg(feature = "wat")] -pub use wat::parse_bytes as wat2wasm; - -// The compilers are mutually exclusive -#[cfg(any( - all( - feature = "default-llvm", - any(feature = "default-cranelift", feature = "default-singlepass") - ), - all(feature = "default-cranelift", feature = "default-singlepass") -))] +#[cfg(all(feature = "sys", feature = "js"))] compile_error!( - r#"The `default-singlepass`, `default-cranelift` and `default-llvm` features are mutually exclusive. -If you wish to use more than one compiler, you can simply create the own store. Eg.: - -``` -use wasmer::{Store, Universal, Singlepass}; - -let engine = Universal::new(Singlepass::default()).engine(); -let store = Store::new(&engine); -```"# + "Cannot have both `sys` and `js` features enabled at the same time. Please, pick one." ); -#[cfg(feature = "singlepass")] -pub use wasmer_compiler_singlepass::Singlepass; - -#[cfg(feature = "cranelift")] -pub use wasmer_compiler_cranelift::{Cranelift, CraneliftOptLevel}; +#[cfg(all(feature = "sys", target_arch = "wasm32"))] +compile_error!("The `sys` feature must be enabled only for non-`wasm32` target."); -#[cfg(feature = "llvm")] -pub use wasmer_compiler_llvm::{LLVMOptLevel, LLVM}; - -#[cfg(feature = "universal")] -pub use wasmer_engine_universal::{Universal, UniversalArtifact, UniversalEngine}; +#[cfg(all(feature = "js", not(target_arch = "wasm32")))] +compile_error!( + "The `js` feature must be enabled only for the `wasm32` target (either `wasm32-unknown-unknown` or `wasm32-wasi`)." +); -#[cfg(feature = "dylib")] -pub use wasmer_engine_dylib::{Dylib, DylibArtifact, DylibEngine}; +#[cfg(feature = "sys")] +mod sys; -/// Version number of this crate. -pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +#[cfg(feature = "sys")] +pub use sys::*; -/// The Deprecated JIT Engine (please use `Universal` instead) -#[cfg(feature = "jit")] -#[deprecated(since = "2.0.0", note = "Please use the `universal` feature instead")] -pub type JIT = Universal; +#[cfg(feature = "js")] +mod js; -/// The Deprecated Native Engine (please use `Dylib` instead) -#[cfg(feature = "native")] -#[deprecated(since = "2.0.0", note = "Please use the `native` feature instead")] -pub type Native = Dylib; +#[cfg(feature = "js")] +pub use js::*; diff --git a/lib/api/src/cell.rs b/lib/api/src/sys/cell.rs similarity index 97% rename from lib/api/src/cell.rs rename to lib/api/src/sys/cell.rs index 91e06ffe54b..c7d6bc4dffe 100644 --- a/lib/api/src/cell.rs +++ b/lib/api/src/sys/cell.rs @@ -2,7 +2,6 @@ pub use std::cell::Cell; use core::cmp::Ordering; use core::fmt::{self, Debug}; -use std::fmt::Pointer; /// A mutable Wasm-memory location. #[repr(transparent)] @@ -121,10 +120,10 @@ impl<'a, T: Copy> WasmCell<'a, T> { } } -impl Debug for WasmCell<'_, T> { +impl Debug for WasmCell<'_, T> { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.inner.fmt(f) + write!(f, "WasmCell({:?})", self.inner.get()) } } diff --git a/lib/api/src/env.rs b/lib/api/src/sys/env.rs similarity index 99% rename from lib/api/src/env.rs rename to lib/api/src/sys/env.rs index d8078414579..4a5491d7235 100644 --- a/lib/api/src/env.rs +++ b/lib/api/src/sys/env.rs @@ -1,4 +1,4 @@ -use crate::{ExportError, Instance}; +use crate::sys::{ExportError, Instance}; use thiserror::Error; /// An error while initializing the user supplied host env with the `WasmerEnv` trait. diff --git a/lib/api/src/exports.rs b/lib/api/src/sys/exports.rs similarity index 98% rename from lib/api/src/exports.rs rename to lib/api/src/sys/exports.rs index 899f494a33e..6978a60428f 100644 --- a/lib/api/src/exports.rs +++ b/lib/api/src/sys/exports.rs @@ -1,7 +1,7 @@ -use crate::externals::{Extern, Function, Global, Memory, Table}; -use crate::import_object::LikeNamespace; -use crate::native::NativeFunc; -use crate::WasmTypeList; +use crate::sys::externals::{Extern, Function, Global, Memory, Table}; +use crate::sys::import_object::LikeNamespace; +use crate::sys::native::NativeFunc; +use crate::sys::WasmTypeList; use indexmap::IndexMap; use loupe::MemoryUsage; use std::fmt; diff --git a/lib/api/src/externals/function.rs b/lib/api/src/sys/externals/function.rs similarity index 99% rename from lib/api/src/externals/function.rs rename to lib/api/src/sys/externals/function.rs index 26061482f33..babb2311a37 100644 --- a/lib/api/src/externals/function.rs +++ b/lib/api/src/sys/externals/function.rs @@ -1,11 +1,11 @@ -use crate::exports::{ExportError, Exportable}; -use crate::externals::Extern; -use crate::store::Store; -use crate::types::{Val, ValFuncRef}; -use crate::FunctionType; -use crate::NativeFunc; -use crate::RuntimeError; -use crate::WasmerEnv; +use crate::sys::exports::{ExportError, Exportable}; +use crate::sys::externals::Extern; +use crate::sys::store::Store; +use crate::sys::types::{Val, ValFuncRef}; +use crate::sys::FunctionType; +use crate::sys::NativeFunc; +use crate::sys::RuntimeError; +use crate::sys::WasmerEnv; pub use inner::{FromToNativeWasmType, HostFunction, WasmTypeList, WithEnv, WithoutEnv}; use loupe::MemoryUsage; diff --git a/lib/api/src/externals/global.rs b/lib/api/src/sys/externals/global.rs similarity index 96% rename from lib/api/src/externals/global.rs rename to lib/api/src/sys/externals/global.rs index 788c649bf48..776153af5c0 100644 --- a/lib/api/src/externals/global.rs +++ b/lib/api/src/sys/externals/global.rs @@ -1,10 +1,10 @@ -use crate::exports::{ExportError, Exportable}; -use crate::externals::Extern; -use crate::store::{Store, StoreObject}; -use crate::types::Val; -use crate::GlobalType; -use crate::Mutability; -use crate::RuntimeError; +use crate::sys::exports::{ExportError, Exportable}; +use crate::sys::externals::Extern; +use crate::sys::store::{Store, StoreObject}; +use crate::sys::types::Val; +use crate::sys::GlobalType; +use crate::sys::Mutability; +use crate::sys::RuntimeError; use loupe::MemoryUsage; use std::fmt; use std::sync::Arc; diff --git a/lib/api/src/externals/memory.rs b/lib/api/src/sys/externals/memory.rs similarity index 97% rename from lib/api/src/externals/memory.rs rename to lib/api/src/sys/externals/memory.rs index 0f02f8ccec3..b5b6ba5cc7e 100644 --- a/lib/api/src/externals/memory.rs +++ b/lib/api/src/sys/externals/memory.rs @@ -1,7 +1,7 @@ -use crate::exports::{ExportError, Exportable}; -use crate::externals::Extern; -use crate::store::Store; -use crate::{MemoryType, MemoryView}; +use crate::sys::exports::{ExportError, Exportable}; +use crate::sys::externals::Extern; +use crate::sys::store::Store; +use crate::sys::{MemoryType, MemoryView}; use loupe::MemoryUsage; use std::convert::TryInto; use std::slice; @@ -34,7 +34,7 @@ impl Memory { /// Creates a new host `Memory` from the provided [`MemoryType`]. /// /// This function will construct the `Memory` using the store - /// [`BaseTunables`][crate::tunables::BaseTunables]. + /// [`BaseTunables`][crate::sys::BaseTunables]. /// /// # Example /// diff --git a/lib/api/src/externals/mod.rs b/lib/api/src/sys/externals/mod.rs similarity index 96% rename from lib/api/src/externals/mod.rs rename to lib/api/src/sys/externals/mod.rs index 79859c92d9e..029e4e4206b 100644 --- a/lib/api/src/externals/mod.rs +++ b/lib/api/src/sys/externals/mod.rs @@ -11,9 +11,9 @@ pub use self::global::Global; pub use self::memory::Memory; pub use self::table::Table; -use crate::exports::{ExportError, Exportable}; -use crate::store::{Store, StoreObject}; -use crate::ExternType; +use crate::sys::exports::{ExportError, Exportable}; +use crate::sys::store::{Store, StoreObject}; +use crate::sys::ExternType; use loupe::MemoryUsage; use std::fmt; use wasmer_engine::Export; diff --git a/lib/api/src/externals/table.rs b/lib/api/src/sys/externals/table.rs similarity index 95% rename from lib/api/src/externals/table.rs rename to lib/api/src/sys/externals/table.rs index b006927b1f6..fd981ac4be4 100644 --- a/lib/api/src/externals/table.rs +++ b/lib/api/src/sys/externals/table.rs @@ -1,9 +1,9 @@ -use crate::exports::{ExportError, Exportable}; -use crate::externals::Extern; -use crate::store::Store; -use crate::types::{Val, ValFuncRef}; -use crate::RuntimeError; -use crate::TableType; +use crate::sys::exports::{ExportError, Exportable}; +use crate::sys::externals::Extern; +use crate::sys::store::Store; +use crate::sys::types::{Val, ValFuncRef}; +use crate::sys::RuntimeError; +use crate::sys::TableType; use loupe::MemoryUsage; use std::sync::Arc; use wasmer_engine::Export; @@ -38,7 +38,7 @@ impl Table { /// All the elements in the table will be set to the `init` value. /// /// This function will construct the `Table` using the store - /// [`BaseTunables`][crate::tunables::BaseTunables]. + /// [`BaseTunables`][crate::sys::BaseTunables]. pub fn new(store: &Store, ty: TableType, init: Val) -> Result { let item = init.into_table_reference(store)?; let tunables = store.tunables(); diff --git a/lib/api/src/import_object.rs b/lib/api/src/sys/import_object.rs similarity index 99% rename from lib/api/src/import_object.rs rename to lib/api/src/sys/import_object.rs index ab4b61d36fd..e8491c684ce 100644 --- a/lib/api/src/import_object.rs +++ b/lib/api/src/sys/import_object.rs @@ -247,7 +247,7 @@ macro_rules! import_namespace { #[cfg(test)] mod test { use super::*; - use crate::{Global, Store, Val}; + use crate::sys::{Global, Store, Val}; use wasmer_engine::ChainableNamedResolver; use wasmer_types::Type; @@ -358,7 +358,7 @@ mod test { #[test] fn imports_macro_allows_trailing_comma_and_none() { - use crate::Function; + use crate::sys::Function; let store = Default::default(); diff --git a/lib/api/src/instance.rs b/lib/api/src/sys/instance.rs similarity index 96% rename from lib/api/src/instance.rs rename to lib/api/src/sys/instance.rs index 592fd2eeca9..86fe1f64738 100644 --- a/lib/api/src/instance.rs +++ b/lib/api/src/sys/instance.rs @@ -1,8 +1,8 @@ -use crate::exports::Exports; -use crate::externals::Extern; -use crate::module::Module; -use crate::store::Store; -use crate::{HostEnvInitError, LinkError, RuntimeError}; +use crate::sys::exports::Exports; +use crate::sys::externals::Extern; +use crate::sys::module::Module; +use crate::sys::store::Store; +use crate::sys::{HostEnvInitError, LinkError, RuntimeError}; use loupe::MemoryUsage; use std::fmt; use std::sync::{Arc, Mutex}; diff --git a/lib/api/src/sys/mod.rs b/lib/api/src/sys/mod.rs new file mode 100644 index 00000000000..157a26a4a64 --- /dev/null +++ b/lib/api/src/sys/mod.rs @@ -0,0 +1,129 @@ +mod cell; +mod env; +mod exports; +mod externals; +mod import_object; +mod instance; +mod module; +mod native; +mod ptr; +mod store; +mod tunables; +mod types; +mod utils; + +/// Implement [`WasmerEnv`] for your type with `#[derive(WasmerEnv)]`. +/// +/// See the [`WasmerEnv`] trait for more information. +pub use wasmer_derive::WasmerEnv; + +#[doc(hidden)] +pub mod internals { + //! We use the internals module for exporting types that are only + //! intended to use in internal crates such as the compatibility crate + //! `wasmer-vm`. Please don't use any of this types directly, as + //! they might change frequently or be removed in the future. + + pub use crate::sys::externals::{WithEnv, WithoutEnv}; +} + +pub use crate::sys::cell::WasmCell; +pub use crate::sys::env::{HostEnvInitError, LazyInit, WasmerEnv}; +pub use crate::sys::exports::{ExportError, Exportable, Exports, ExportsIterator}; +pub use crate::sys::externals::{ + Extern, FromToNativeWasmType, Function, Global, HostFunction, Memory, Table, WasmTypeList, +}; +pub use crate::sys::import_object::{ImportObject, ImportObjectIterator, LikeNamespace}; +pub use crate::sys::instance::{Instance, InstantiationError}; +pub use crate::sys::module::Module; +pub use crate::sys::native::NativeFunc; +pub use crate::sys::ptr::{Array, Item, WasmPtr}; +pub use crate::sys::store::{Store, StoreObject}; +pub use crate::sys::tunables::BaseTunables; +pub use crate::sys::types::{ + ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, + TableType, Val, ValType, +}; +pub use crate::sys::types::{Val as Value, ValType as Type}; +pub use crate::sys::utils::is_wasm; +pub use target_lexicon::{Architecture, CallingConvention, OperatingSystem, Triple, HOST}; +#[cfg(feature = "compiler")] +pub use wasmer_compiler::{ + wasmparser, CompilerConfig, FunctionMiddleware, MiddlewareError, MiddlewareReaderState, + ModuleMiddleware, +}; +pub use wasmer_compiler::{ + CompileError, CpuFeature, Features, ParseCpuFeatureError, Target, WasmError, WasmResult, +}; +pub use wasmer_engine::{ + ChainableNamedResolver, DeserializeError, Engine, Export, FrameInfo, LinkError, NamedResolver, + NamedResolverChain, Resolver, RuntimeError, SerializeError, Tunables, +}; +#[cfg(feature = "experimental-reference-types-extern-ref")] +pub use wasmer_types::ExternRef; +pub use wasmer_types::{ + Atomically, Bytes, ExportIndex, GlobalInit, LocalFunctionIndex, MemoryView, Pages, ValueType, + WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE, +}; + +// TODO: should those be moved into wasmer::vm as well? +pub use wasmer_vm::{raise_user_trap, MemoryError}; +pub mod vm { + //! The `vm` module re-exports wasmer-vm types. + + pub use wasmer_vm::{ + Memory, MemoryError, MemoryStyle, Table, TableStyle, VMExtern, VMMemoryDefinition, + VMTableDefinition, + }; +} + +#[cfg(feature = "wat")] +pub use wat::parse_bytes as wat2wasm; + +// The compilers are mutually exclusive +#[cfg(any( + all( + feature = "default-llvm", + any(feature = "default-cranelift", feature = "default-singlepass") + ), + all(feature = "default-cranelift", feature = "default-singlepass") +))] +compile_error!( + r#"The `default-singlepass`, `default-cranelift` and `default-llvm` features are mutually exclusive. +If you wish to use more than one compiler, you can simply create the own store. Eg.: + +``` +use wasmer::{Store, Universal, Singlepass}; + +let engine = Universal::new(Singlepass::default()).engine(); +let store = Store::new(&engine); +```"# +); + +#[cfg(feature = "singlepass")] +pub use wasmer_compiler_singlepass::Singlepass; + +#[cfg(feature = "cranelift")] +pub use wasmer_compiler_cranelift::{Cranelift, CraneliftOptLevel}; + +#[cfg(feature = "llvm")] +pub use wasmer_compiler_llvm::{LLVMOptLevel, LLVM}; + +#[cfg(feature = "universal")] +pub use wasmer_engine_universal::{Universal, UniversalArtifact, UniversalEngine}; + +#[cfg(feature = "dylib")] +pub use wasmer_engine_dylib::{Dylib, DylibArtifact, DylibEngine}; + +/// Version number of this crate. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// The Deprecated JIT Engine (please use `Universal` instead) +#[cfg(feature = "jit")] +#[deprecated(since = "2.0.0", note = "Please use the `universal` feature instead")] +pub type JIT = Universal; + +/// The Deprecated Native Engine (please use `Dylib` instead) +#[cfg(feature = "native")] +#[deprecated(since = "2.0.0", note = "Please use the `native` feature instead")] +pub type Native = Dylib; diff --git a/lib/api/src/module.rs b/lib/api/src/sys/module.rs similarity index 98% rename from lib/api/src/module.rs rename to lib/api/src/sys/module.rs index 6d936a5f3d8..27df4fd6f31 100644 --- a/lib/api/src/module.rs +++ b/lib/api/src/sys/module.rs @@ -1,6 +1,6 @@ -use crate::store::Store; -use crate::types::{ExportType, ImportType}; -use crate::InstantiationError; +use crate::sys::store::Store; +use crate::sys::types::{ExportType, ImportType}; +use crate::sys::InstantiationError; use loupe::MemoryUsage; use std::fmt; use std::io; @@ -11,7 +11,8 @@ use wasmer_compiler::CompileError; #[cfg(feature = "wat")] use wasmer_compiler::WasmError; use wasmer_engine::{Artifact, DeserializeError, Resolver, SerializeError}; -use wasmer_vm::{ExportsIterator, ImportsIterator, InstanceHandle, ModuleInfo}; +use wasmer_types::{ExportsIterator, ImportsIterator, ModuleInfo}; +use wasmer_vm::InstanceHandle; #[derive(Error, Debug)] pub enum IoCompileError { diff --git a/lib/api/src/native.rs b/lib/api/src/sys/native.rs similarity index 95% rename from lib/api/src/native.rs rename to lib/api/src/sys/native.rs index a350c6f090b..7c3f8705be9 100644 --- a/lib/api/src/native.rs +++ b/lib/api/src/sys/native.rs @@ -9,8 +9,8 @@ //! ``` use std::marker::PhantomData; -use crate::externals::function::{DynamicFunction, VMDynamicFunction}; -use crate::{FromToNativeWasmType, Function, RuntimeError, Store, WasmTypeList}; +use crate::sys::externals::function::{DynamicFunction, VMDynamicFunction}; +use crate::sys::{FromToNativeWasmType, Function, RuntimeError, Store, WasmTypeList}; use std::panic::{catch_unwind, AssertUnwindSafe}; use wasmer_engine::ExportFunction; use wasmer_types::NativeWasmType; @@ -223,14 +223,14 @@ macro_rules! impl_native_traits { } #[allow(unused_parens)] - impl<'a, $( $x, )* Rets> crate::exports::ExportableWithGenerics<'a, ($( $x ),*), Rets> for NativeFunc<( $( $x ),* ), Rets> + impl<'a, $( $x, )* Rets> crate::sys::exports::ExportableWithGenerics<'a, ($( $x ),*), Rets> for NativeFunc<( $( $x ),* ), Rets> where $( $x: FromToNativeWasmType, )* Rets: WasmTypeList, { - fn get_self_from_extern_with_generics(_extern: &crate::externals::Extern) -> Result { - use crate::exports::Exportable; - crate::Function::get_self_from_extern(_extern)?.native().map_err(|_| crate::exports::ExportError::IncompatibleType) + fn get_self_from_extern_with_generics(_extern: &crate::sys::externals::Extern) -> Result { + use crate::sys::exports::Exportable; + crate::Function::get_self_from_extern(_extern)?.native().map_err(|_| crate::sys::exports::ExportError::IncompatibleType) } fn into_weak_instance_ref(&mut self) { diff --git a/lib/api/src/ptr.rs b/lib/api/src/sys/ptr.rs similarity index 97% rename from lib/api/src/ptr.rs rename to lib/api/src/sys/ptr.rs index 6830713da0f..33be4844f9c 100644 --- a/lib/api/src/ptr.rs +++ b/lib/api/src/sys/ptr.rs @@ -6,8 +6,8 @@ //! Therefore, you should use this abstraction whenever possible to avoid memory //! related bugs when implementing an ABI. -use crate::cell::WasmCell; -use crate::{externals::Memory, FromToNativeWasmType}; +use crate::sys::cell::WasmCell; +use crate::sys::{externals::Memory, FromToNativeWasmType}; use std::{cell::Cell, fmt, marker::PhantomData, mem}; use wasmer_types::ValueType; @@ -281,14 +281,20 @@ impl Eq for WasmPtr {} impl fmt::Debug for WasmPtr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "WasmPtr({:#x})", self.offset) + write!( + f, + "WasmPtr(offset: {}, pointer: {:#x}, align: {})", + self.offset, + self.offset, + mem::align_of::() + ) } } #[cfg(test)] mod test { use super::*; - use crate::{Memory, MemoryType, Store}; + use crate::sys::{Memory, MemoryType, Store}; /// Ensure that memory accesses work on the edges of memory and that out of /// bounds errors are caught with `deref` diff --git a/lib/api/src/store.rs b/lib/api/src/sys/store.rs similarity index 99% rename from lib/api/src/store.rs rename to lib/api/src/sys/store.rs index d78f63e1381..8709ee9cc83 100644 --- a/lib/api/src/store.rs +++ b/lib/api/src/sys/store.rs @@ -1,4 +1,4 @@ -use crate::tunables::BaseTunables; +use crate::sys::tunables::BaseTunables; use loupe::MemoryUsage; use std::any::Any; use std::fmt; diff --git a/lib/api/src/tunables.rs b/lib/api/src/sys/tunables.rs similarity index 99% rename from lib/api/src/tunables.rs rename to lib/api/src/sys/tunables.rs index d714ffd602b..39a86ef6fd1 100644 --- a/lib/api/src/tunables.rs +++ b/lib/api/src/sys/tunables.rs @@ -1,4 +1,4 @@ -use crate::{MemoryType, Pages, TableType}; +use crate::sys::{MemoryType, Pages, TableType}; use loupe::MemoryUsage; use std::cmp::min; use std::ptr::NonNull; diff --git a/lib/api/src/types.rs b/lib/api/src/sys/types.rs similarity index 97% rename from lib/api/src/types.rs rename to lib/api/src/sys/types.rs index 70c7a196173..ef291e9889b 100644 --- a/lib/api/src/types.rs +++ b/lib/api/src/sys/types.rs @@ -1,6 +1,6 @@ -use crate::externals::Function; -use crate::store::{Store, StoreObject}; -use crate::RuntimeError; +use crate::sys::externals::Function; +use crate::sys::store::{Store, StoreObject}; +use crate::sys::RuntimeError; use wasmer_types::Value; pub use wasmer_types::{ ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, diff --git a/lib/api/src/sys/utils.rs b/lib/api/src/sys/utils.rs new file mode 100644 index 00000000000..b3f067f3334 --- /dev/null +++ b/lib/api/src/sys/utils.rs @@ -0,0 +1,4 @@ +/// Check if the provided bytes are wasm-like +pub fn is_wasm(bytes: impl AsRef<[u8]>) -> bool { + bytes.as_ref().starts_with(b"\0asm") +} diff --git a/lib/api/tests/export.rs b/lib/api/tests/export.rs deleted file mode 100644 index b65d2487bb2..00000000000 --- a/lib/api/tests/export.rs +++ /dev/null @@ -1,334 +0,0 @@ -use anyhow::Result; -use wasmer::*; -use wasmer_vm::WeakOrStrongInstanceRef; - -const MEM_WAT: &str = " - (module - (func $host_fn (import \"env\" \"host_fn\") (param) (result)) - (func (export \"call_host_fn\") (param) (result) - (call $host_fn)) - - (memory $mem 0) - (export \"memory\" (memory $mem)) - ) -"; - -const GLOBAL_WAT: &str = " - (module - (func $host_fn (import \"env\" \"host_fn\") (param) (result)) - (func (export \"call_host_fn\") (param) (result) - (call $host_fn)) - - (global $global i32 (i32.const 11)) - (export \"global\" (global $global)) - ) -"; - -const TABLE_WAT: &str = " - (module - (func $host_fn (import \"env\" \"host_fn\") (param) (result)) - (func (export \"call_host_fn\") (param) (result) - (call $host_fn)) - - (table $table 4 4 funcref) - (export \"table\" (table $table)) - ) -"; - -const FUNCTION_WAT: &str = " - (module - (func $host_fn (import \"env\" \"host_fn\") (param) (result)) - (func (export \"call_host_fn\") (param) (result) - (call $host_fn)) - ) -"; - -fn is_memory_instance_ref_strong(memory: &Memory) -> Option { - // This is safe because we're calling it from a test to test the internals - unsafe { - memory - .get_vm_memory() - .instance_ref - .as_ref() - .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) - } -} - -fn is_table_instance_ref_strong(table: &Table) -> Option { - // This is safe because we're calling it from a test to test the internals - unsafe { - table - .get_vm_table() - .instance_ref - .as_ref() - .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) - } -} - -fn is_global_instance_ref_strong(global: &Global) -> Option { - // This is safe because we're calling it from a test to test the internals - unsafe { - global - .get_vm_global() - .instance_ref - .as_ref() - .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) - } -} - -fn is_function_instance_ref_strong(f: &Function) -> Option { - // This is safe because we're calling it from a test to test the internals - unsafe { - f.get_vm_function() - .instance_ref - .as_ref() - .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) - } -} - -fn is_native_function_instance_ref_strong(f: &NativeFunc) -> Option -where - Args: WasmTypeList, - Rets: WasmTypeList, -{ - // This is safe because we're calling it from a test to test the internals - unsafe { - f.get_vm_function() - .instance_ref - .as_ref() - .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) - } -} - -#[test] -fn strong_weak_behavior_works_memory() -> Result<()> { - #[derive(Clone, Debug, WasmerEnv, Default)] - struct MemEnv { - #[wasmer(export)] - memory: LazyInit, - } - - let host_fn = |env: &MemEnv| { - let mem = env.memory_ref().unwrap(); - assert_eq!(is_memory_instance_ref_strong(&mem), Some(false)); - let mem_clone = mem.clone(); - assert_eq!(is_memory_instance_ref_strong(&mem_clone), Some(true)); - assert_eq!(is_memory_instance_ref_strong(&mem), Some(false)); - }; - - let f: NativeFunc<(), ()> = { - let store = Store::default(); - let module = Module::new(&store, MEM_WAT)?; - let env = MemEnv::default(); - - let instance = Instance::new( - &module, - &imports! { - "env" => { - "host_fn" => Function::new_native_with_env(&store, env, host_fn) - } - }, - )?; - - { - let mem = instance.exports.get_memory("memory")?; - assert_eq!(is_memory_instance_ref_strong(&mem), Some(true)); - } - - let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; - f.call()?; - f - }; - f.call()?; - - Ok(()) -} - -#[test] -fn strong_weak_behavior_works_global() -> Result<()> { - #[derive(Clone, Debug, WasmerEnv, Default)] - struct GlobalEnv { - #[wasmer(export)] - global: LazyInit, - } - - let host_fn = |env: &GlobalEnv| { - let global = env.global_ref().unwrap(); - assert_eq!(is_global_instance_ref_strong(&global), Some(false)); - let global_clone = global.clone(); - assert_eq!(is_global_instance_ref_strong(&global_clone), Some(true)); - assert_eq!(is_global_instance_ref_strong(&global), Some(false)); - }; - - let f: NativeFunc<(), ()> = { - let store = Store::default(); - let module = Module::new(&store, GLOBAL_WAT)?; - let env = GlobalEnv::default(); - - let instance = Instance::new( - &module, - &imports! { - "env" => { - "host_fn" => Function::new_native_with_env(&store, env, host_fn) - } - }, - )?; - - { - let global = instance.exports.get_global("global")?; - assert_eq!(is_global_instance_ref_strong(&global), Some(true)); - } - - let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; - f.call()?; - f - }; - f.call()?; - - Ok(()) -} - -#[test] -fn strong_weak_behavior_works_table() -> Result<()> { - #[derive(Clone, WasmerEnv, Default)] - struct TableEnv { - #[wasmer(export)] - table: LazyInit
, - } - - let host_fn = |env: &TableEnv| { - let table = env.table_ref().unwrap(); - assert_eq!(is_table_instance_ref_strong(&table), Some(false)); - let table_clone = table.clone(); - assert_eq!(is_table_instance_ref_strong(&table_clone), Some(true)); - assert_eq!(is_table_instance_ref_strong(&table), Some(false)); - }; - - let f: NativeFunc<(), ()> = { - let store = Store::default(); - let module = Module::new(&store, TABLE_WAT)?; - let env = TableEnv::default(); - - let instance = Instance::new( - &module, - &imports! { - "env" => { - "host_fn" => Function::new_native_with_env(&store, env, host_fn) - } - }, - )?; - - { - let table = instance.exports.get_table("table")?; - assert_eq!(is_table_instance_ref_strong(&table), Some(true)); - } - - let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; - f.call()?; - f - }; - f.call()?; - - Ok(()) -} - -#[test] -fn strong_weak_behavior_works_function() -> Result<()> { - #[derive(Clone, WasmerEnv, Default)] - struct FunctionEnv { - #[wasmer(export)] - call_host_fn: LazyInit, - } - - let host_fn = |env: &FunctionEnv| { - let function = env.call_host_fn_ref().unwrap(); - assert_eq!(is_function_instance_ref_strong(&function), Some(false)); - let function_clone = function.clone(); - assert_eq!(is_function_instance_ref_strong(&function_clone), Some(true)); - assert_eq!(is_function_instance_ref_strong(&function), Some(false)); - }; - - let f: NativeFunc<(), ()> = { - let store = Store::default(); - let module = Module::new(&store, FUNCTION_WAT)?; - let env = FunctionEnv::default(); - - let instance = Instance::new( - &module, - &imports! { - "env" => { - "host_fn" => Function::new_native_with_env(&store, env, host_fn) - } - }, - )?; - - { - let function = instance.exports.get_function("call_host_fn")?; - assert_eq!(is_function_instance_ref_strong(&function), Some(true)); - } - - let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; - f.call()?; - f - }; - f.call()?; - - Ok(()) -} - -#[test] -fn strong_weak_behavior_works_native_function() -> Result<()> { - #[derive(Clone, WasmerEnv, Default)] - struct FunctionEnv { - #[wasmer(export)] - call_host_fn: LazyInit>, - } - - let host_fn = |env: &FunctionEnv| { - let function = env.call_host_fn_ref().unwrap(); - assert_eq!( - is_native_function_instance_ref_strong(&function), - Some(false) - ); - let function_clone = function.clone(); - assert_eq!( - is_native_function_instance_ref_strong(&function_clone), - Some(true) - ); - assert_eq!( - is_native_function_instance_ref_strong(&function), - Some(false) - ); - }; - - let f: NativeFunc<(), ()> = { - let store = Store::default(); - let module = Module::new(&store, FUNCTION_WAT)?; - let env = FunctionEnv::default(); - - let instance = Instance::new( - &module, - &imports! { - "env" => { - "host_fn" => Function::new_native_with_env(&store, env, host_fn) - } - }, - )?; - - { - let function: NativeFunc<(), ()> = - instance.exports.get_native_function("call_host_fn")?; - assert_eq!( - is_native_function_instance_ref_strong(&function), - Some(true) - ); - } - - let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; - f.call()?; - f - }; - f.call()?; - - Ok(()) -} diff --git a/lib/api/tests/externals.rs b/lib/api/tests/externals.rs deleted file mode 100644 index dff570d2ef2..00000000000 --- a/lib/api/tests/externals.rs +++ /dev/null @@ -1,458 +0,0 @@ -use anyhow::Result; -use wasmer::*; - -#[test] -fn global_new() -> Result<()> { - let store = Store::default(); - let global = Global::new(&store, Value::I32(10)); - assert_eq!( - *global.ty(), - GlobalType { - ty: Type::I32, - mutability: Mutability::Const - } - ); - - let global_mut = Global::new_mut(&store, Value::I32(10)); - assert_eq!( - *global_mut.ty(), - GlobalType { - ty: Type::I32, - mutability: Mutability::Var - } - ); - - Ok(()) -} - -#[test] -fn global_get() -> Result<()> { - let store = Store::default(); - let global_i32 = Global::new(&store, Value::I32(10)); - assert_eq!(global_i32.get(), Value::I32(10)); - let global_i64 = Global::new(&store, Value::I64(20)); - assert_eq!(global_i64.get(), Value::I64(20)); - let global_f32 = Global::new(&store, Value::F32(10.0)); - assert_eq!(global_f32.get(), Value::F32(10.0)); - let global_f64 = Global::new(&store, Value::F64(20.0)); - assert_eq!(global_f64.get(), Value::F64(20.0)); - - Ok(()) -} - -#[test] -fn global_set() -> Result<()> { - let store = Store::default(); - let global_i32 = Global::new(&store, Value::I32(10)); - // Set on a constant should error - assert!(global_i32.set(Value::I32(20)).is_err()); - - let global_i32_mut = Global::new_mut(&store, Value::I32(10)); - // Set on different type should error - assert!(global_i32_mut.set(Value::I64(20)).is_err()); - - // Set on same type should succeed - global_i32_mut.set(Value::I32(20))?; - assert_eq!(global_i32_mut.get(), Value::I32(20)); - - Ok(()) -} - -#[test] -fn table_new() -> Result<()> { - let store = Store::default(); - let table_type = TableType { - ty: Type::FuncRef, - minimum: 0, - maximum: None, - }; - let f = Function::new_native(&store, || {}); - let table = Table::new(&store, table_type, Value::FuncRef(Some(f)))?; - assert_eq!(*table.ty(), table_type); - - // Anyrefs not yet supported - // let table_type = TableType { - // ty: Type::ExternRef, - // minimum: 0, - // maximum: None, - // }; - // let table = Table::new(&store, table_type, Value::ExternRef(ExternRef::Null))?; - // assert_eq!(*table.ty(), table_type); - - Ok(()) -} - -#[test] -#[ignore] -fn table_get() -> Result<()> { - let store = Store::default(); - let table_type = TableType { - ty: Type::FuncRef, - minimum: 0, - maximum: Some(1), - }; - let f = Function::new_native(&store, |num: i32| num + 1); - let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; - assert_eq!(*table.ty(), table_type); - let _elem = table.get(0).unwrap(); - // assert_eq!(elem.funcref().unwrap(), f); - Ok(()) -} - -#[test] -#[ignore] -fn table_set() -> Result<()> { - // Table set not yet tested - Ok(()) -} - -#[test] -fn table_grow() -> Result<()> { - let store = Store::default(); - let table_type = TableType { - ty: Type::FuncRef, - minimum: 0, - maximum: Some(10), - }; - let f = Function::new_native(&store, |num: i32| num + 1); - let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; - // Growing to a bigger maximum should return None - let old_len = table.grow(12, Value::FuncRef(Some(f.clone()))); - assert!(old_len.is_err()); - - // Growing to a bigger maximum should return None - let old_len = table.grow(5, Value::FuncRef(Some(f.clone())))?; - assert_eq!(old_len, 0); - - Ok(()) -} - -#[test] -#[ignore] -fn table_copy() -> Result<()> { - // TODO: table copy test not yet implemented - Ok(()) -} - -#[test] -fn memory_new() -> Result<()> { - let store = Store::default(); - let memory_type = MemoryType { - shared: false, - minimum: Pages(0), - maximum: Some(Pages(10)), - }; - let memory = Memory::new(&store, memory_type)?; - assert_eq!(memory.size(), Pages(0)); - assert_eq!(memory.ty(), memory_type); - Ok(()) -} - -#[test] -fn memory_grow() -> Result<()> { - let store = Store::default(); - - let desc = MemoryType::new(Pages(10), Some(Pages(16)), false); - let memory = Memory::new(&store, desc)?; - assert_eq!(memory.size(), Pages(10)); - - let result = memory.grow(Pages(2)).unwrap(); - assert_eq!(result, Pages(10)); - assert_eq!(memory.size(), Pages(12)); - - let result = memory.grow(Pages(10)); - assert_eq!( - result, - Err(MemoryError::CouldNotGrow { - current: 12.into(), - attempted_delta: 10.into() - }) - ); - - let bad_desc = MemoryType::new(Pages(15), Some(Pages(10)), false); - let bad_result = Memory::new(&store, bad_desc); - - assert!(matches!(bad_result, Err(MemoryError::InvalidMemory { .. }))); - - Ok(()) -} - -#[test] -fn function_new() -> Result<()> { - let store = Store::default(); - let function = Function::new_native(&store, || {}); - assert_eq!(function.ty().clone(), FunctionType::new(vec![], vec![])); - let function = Function::new_native(&store, |_a: i32| {}); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![Type::I32], vec![]) - ); - let function = Function::new_native(&store, |_a: i32, _b: i64, _c: f32, _d: f64| {}); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) - ); - let function = Function::new_native(&store, || -> i32 { 1 }); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![], vec![Type::I32]) - ); - let function = Function::new_native(&store, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) - ); - Ok(()) -} - -#[test] -fn function_new_env() -> Result<()> { - let store = Store::default(); - #[derive(Clone, WasmerEnv)] - struct MyEnv {} - - let my_env = MyEnv {}; - let function = Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv| {}); - assert_eq!(function.ty().clone(), FunctionType::new(vec![], vec![])); - let function = - Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv, _a: i32| {}); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![Type::I32], vec![]) - ); - let function = Function::new_native_with_env( - &store, - my_env.clone(), - |_env: &MyEnv, _a: i32, _b: i64, _c: f32, _d: f64| {}, - ); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) - ); - let function = - Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv| -> i32 { 1 }); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![], vec![Type::I32]) - ); - let function = Function::new_native_with_env( - &store, - my_env.clone(), - |_env: &MyEnv| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, - ); - assert_eq!( - function.ty().clone(), - FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) - ); - Ok(()) -} - -#[test] -fn function_new_dynamic() -> Result<()> { - let store = Store::default(); - - // Using &FunctionType signature - let function_type = FunctionType::new(vec![], vec![]); - let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![Type::I32], vec![]); - let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); - let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![], vec![Type::I32]); - let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); - let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); - assert_eq!(function.ty().clone(), function_type); - - // Using array signature - let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); - let function = Function::new(&store, function_type, |_values: &[Value]| unimplemented!()); - assert_eq!(function.ty().params(), [Type::V128]); - assert_eq!(function.ty().results(), [Type::I32, Type::F32, Type::F64]); - - Ok(()) -} - -#[test] -fn function_new_dynamic_env() -> Result<()> { - let store = Store::default(); - #[derive(Clone, WasmerEnv)] - struct MyEnv {} - let my_env = MyEnv {}; - - // Using &FunctionType signature - let function_type = FunctionType::new(vec![], vec![]); - let function = Function::new_with_env( - &store, - &function_type, - my_env.clone(), - |_env: &MyEnv, _values: &[Value]| unimplemented!(), - ); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![Type::I32], vec![]); - let function = Function::new_with_env( - &store, - &function_type, - my_env.clone(), - |_env: &MyEnv, _values: &[Value]| unimplemented!(), - ); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); - let function = Function::new_with_env( - &store, - &function_type, - my_env.clone(), - |_env: &MyEnv, _values: &[Value]| unimplemented!(), - ); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![], vec![Type::I32]); - let function = Function::new_with_env( - &store, - &function_type, - my_env.clone(), - |_env: &MyEnv, _values: &[Value]| unimplemented!(), - ); - assert_eq!(function.ty().clone(), function_type); - let function_type = FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); - let function = Function::new_with_env( - &store, - &function_type, - my_env.clone(), - |_env: &MyEnv, _values: &[Value]| unimplemented!(), - ); - assert_eq!(function.ty().clone(), function_type); - - // Using array signature - let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); - let function = Function::new_with_env( - &store, - function_type, - my_env.clone(), - |_env: &MyEnv, _values: &[Value]| unimplemented!(), - ); - assert_eq!(function.ty().params(), [Type::V128]); - assert_eq!(function.ty().results(), [Type::I32, Type::F32, Type::F64]); - - Ok(()) -} - -#[test] -fn native_function_works() -> Result<()> { - let store = Store::default(); - let function = Function::new_native(&store, || {}); - let native_function: NativeFunc<(), ()> = function.native().unwrap(); - let result = native_function.call(); - assert!(result.is_ok()); - - let function = Function::new_native(&store, |a: i32| -> i32 { a + 1 }); - let native_function: NativeFunc = function.native().unwrap(); - assert_eq!(native_function.call(3).unwrap(), 4); - - fn rust_abi(a: i32, b: i64, c: f32, d: f64) -> u64 { - (a as u64 * 1000) + (b as u64 * 100) + (c as u64 * 10) + (d as u64) - } - let function = Function::new_native(&store, rust_abi); - let native_function: NativeFunc<(i32, i64, f32, f64), u64> = function.native().unwrap(); - assert_eq!(native_function.call(8, 4, 1.5, 5.).unwrap(), 8415); - - let function = Function::new_native(&store, || -> i32 { 1 }); - let native_function: NativeFunc<(), i32> = function.native().unwrap(); - assert_eq!(native_function.call().unwrap(), 1); - - let function = Function::new_native(&store, |_a: i32| {}); - let native_function: NativeFunc = function.native().unwrap(); - assert!(native_function.call(4).is_ok()); - - let function = Function::new_native(&store, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); - let native_function: NativeFunc<(), (i32, i64, f32, f64)> = function.native().unwrap(); - assert_eq!(native_function.call().unwrap(), (1, 2, 3.0, 4.0)); - - Ok(()) -} - -#[test] -fn function_outlives_instance() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (type $sum_t (func (param i32 i32) (result i32))) - (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add) - (export "sum" (func $sum_f))) -"#; - - let f = { - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - let f: NativeFunc<(i32, i32), i32> = instance.exports.get_native_function("sum")?; - - assert_eq!(f.call(4, 5)?, 9); - f - }; - - assert_eq!(f.call(4, 5)?, 9); - - Ok(()) -} - -#[test] -fn weak_instance_ref_externs_after_instance() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (memory (export "mem") 1) - (type $sum_t (func (param i32 i32) (result i32))) - (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add) - (export "sum" (func $sum_f))) -"#; - - let f = { - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - let f: NativeFunc<(i32, i32), i32> = instance.exports.get_with_generics_weak("sum")?; - - assert_eq!(f.call(4, 5)?, 9); - f - }; - - assert_eq!(f.call(4, 5)?, 9); - - Ok(()) -} - -#[test] -fn manually_generate_wasmer_env() -> Result<()> { - let store = Store::default(); - #[derive(WasmerEnv, Clone)] - struct MyEnv { - val: u32, - memory: LazyInit, - } - - fn host_function(env: &mut MyEnv, arg1: u32, arg2: u32) -> u32 { - env.val + arg1 + arg2 - } - - let mut env = MyEnv { - val: 5, - memory: LazyInit::new(), - }; - - let result = host_function(&mut env, 7, 9); - assert_eq!(result, 21); - - let memory = Memory::new(&store, MemoryType::new(0, None, false))?; - env.memory.initialize(memory); - - let result = host_function(&mut env, 1, 2); - assert_eq!(result, 8); - - Ok(()) -} diff --git a/lib/api/tests/instance.rs b/lib/api/tests/instance.rs deleted file mode 100644 index 69733877424..00000000000 --- a/lib/api/tests/instance.rs +++ /dev/null @@ -1,39 +0,0 @@ -use anyhow::Result; -use wasmer::*; - -#[test] -fn exports_work_after_multiple_instances_have_been_freed() -> Result<()> { - let store = Store::default(); - let module = Module::new( - &store, - " - (module - (type $sum_t (func (param i32 i32) (result i32))) - (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add) - (export \"sum\" (func $sum_f))) -", - )?; - - let import_object = ImportObject::new(); - let instance = Instance::new(&module, &import_object)?; - let instance2 = instance.clone(); - let instance3 = instance.clone(); - - // The function is cloned to “break” the connection with `instance`. - let sum = instance.exports.get_function("sum")?.clone(); - - drop(instance); - drop(instance2); - drop(instance3); - - // All instances have been dropped, but `sum` continues to work! - assert_eq!( - sum.call(&[Value::I32(1), Value::I32(2)])?.into_vec(), - vec![Value::I32(3)], - ); - - Ok(()) -} diff --git a/lib/api/tests/js_externals.rs b/lib/api/tests/js_externals.rs new file mode 100644 index 00000000000..5be196078e6 --- /dev/null +++ b/lib/api/tests/js_externals.rs @@ -0,0 +1,425 @@ +#[cfg(feature = "js")] +mod js { + use wasm_bindgen_test::*; + use wasmer::*; + + #[wasm_bindgen_test] + fn global_new() { + let store = Store::default(); + let global = Global::new(&store, Value::I32(10)); + assert_eq!( + *global.ty(), + GlobalType { + ty: Type::I32, + mutability: Mutability::Const + } + ); + + let global_mut = Global::new_mut(&store, Value::I32(10)); + assert_eq!( + *global_mut.ty(), + GlobalType { + ty: Type::I32, + mutability: Mutability::Var + } + ); + } + + #[wasm_bindgen_test] + fn global_get() { + let store = Store::default(); + let global_i32 = Global::new(&store, Value::I32(10)); + assert_eq!(global_i32.get(), Value::I32(10)); + // 64-bit values are not yet fully supported in some versions of Node + // Commenting this tests for now: + + // let global_i64 = Global::new(&store, Value::I64(20)); + // assert_eq!(global_i64.get(), Value::I64(20)); + let global_f32 = Global::new(&store, Value::F32(10.0)); + assert_eq!(global_f32.get(), Value::F32(10.0)); + // let global_f64 = Global::new(&store, Value::F64(20.0)); + // assert_eq!(global_f64.get(), Value::F64(20.0)); + } + + #[wasm_bindgen_test] + fn global_set() { + let store = Store::default(); + let global_i32 = Global::new(&store, Value::I32(10)); + // Set on a constant should error + assert!(global_i32.set(Value::I32(20)).is_err()); + + let global_i32_mut = Global::new_mut(&store, Value::I32(10)); + // Set on different type should error + assert!(global_i32_mut.set(Value::I64(20)).is_err()); + + // Set on same type should succeed + global_i32_mut.set(Value::I32(20)).unwrap(); + assert_eq!(global_i32_mut.get(), Value::I32(20)); + } + + #[wasm_bindgen_test] + fn table_new() { + let store = Store::default(); + let table_type = TableType { + ty: Type::FuncRef, + minimum: 0, + maximum: None, + }; + let f = Function::new_native(&store, || {}); + let table = Table::new(&store, table_type, Value::FuncRef(Some(f))).unwrap(); + assert_eq!(*table.ty(), table_type); + + // table.get() + // Anyrefs not yet supported + // let table_type = TableType { + // ty: Type::ExternRef, + // minimum: 0, + // maximum: None, + // }; + // let table = Table::new(&store, table_type, Value::ExternRef(ExternRef::Null))?; + // assert_eq!(*table.ty(), table_type); + } + + // Tables are not yet fully supported in Wasm + // Commenting this tests for now + + // #[test] + // #[ignore] + // fn table_get() -> Result<()> { + // let store = Store::default(); + // let table_type = TableType { + // ty: Type::FuncRef, + // minimum: 0, + // maximum: Some(1), + // }; + // let f = Function::new_native(&store, |num: i32| num + 1); + // let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; + // assert_eq!(*table.ty(), table_type); + // let _elem = table.get(0).unwrap(); + // // assert_eq!(elem.funcref().unwrap(), f); + // Ok(()) + // } + + // #[test] + // #[ignore] + // fn table_set() -> Result<()> { + // // Table set not yet tested + // Ok(()) + // } + + // #[test] + // fn table_grow() -> Result<()> { + // let store = Store::default(); + // let table_type = TableType { + // ty: Type::FuncRef, + // minimum: 0, + // maximum: Some(10), + // }; + // let f = Function::new_native(&store, |num: i32| num + 1); + // let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; + // // Growing to a bigger maximum should return None + // let old_len = table.grow(12, Value::FuncRef(Some(f.clone()))); + // assert!(old_len.is_err()); + + // // Growing to a bigger maximum should return None + // let old_len = table.grow(5, Value::FuncRef(Some(f.clone())))?; + // assert_eq!(old_len, 0); + + // Ok(()) + // } + + // #[test] + // #[ignore] + // fn table_copy() -> Result<()> { + // // TODO: table copy test not yet implemented + // Ok(()) + // } + + #[wasm_bindgen_test] + fn memory_new() { + let store = Store::default(); + let memory_type = MemoryType { + shared: false, + minimum: Pages(0), + maximum: Some(Pages(10)), + }; + let memory = Memory::new(&store, memory_type).unwrap(); + assert_eq!(memory.size(), Pages(0)); + assert_eq!(memory.ty(), memory_type); + } + + #[wasm_bindgen_test] + fn memory_grow() { + let store = Store::default(); + + let desc = MemoryType::new(Pages(10), Some(Pages(16)), false); + let memory = Memory::new(&store, desc).unwrap(); + assert_eq!(memory.size(), Pages(10)); + + let result = memory.grow(Pages(2)).unwrap(); + assert_eq!(result, Pages(10)); + assert_eq!(memory.size(), Pages(12)); + + let result = memory.grow(Pages(10)); + assert!(result.is_err()); + assert_eq!( + result, + Err(MemoryError::CouldNotGrow { + current: 12.into(), + attempted_delta: 10.into() + }) + ); + } + + #[wasm_bindgen_test] + fn function_new() { + let store = Store::default(); + let function = Function::new_native(&store, || {}); + assert_eq!(function.ty().clone(), FunctionType::new(vec![], vec![])); + let function = Function::new_native(&store, |_a: i32| {}); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32], vec![]) + ); + let function = Function::new_native(&store, |_a: i32, _b: i64, _c: f32, _d: f64| {}); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) + ); + let function = Function::new_native(&store, || -> i32 { 1 }); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32]) + ); + let function = + Function::new_native(&store, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) + ); + } + + #[wasm_bindgen_test] + fn function_new_env() { + let store = Store::default(); + #[derive(Clone, WasmerEnv)] + struct MyEnv {} + + let my_env = MyEnv {}; + let function = Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv| {}); + assert_eq!(function.ty().clone(), FunctionType::new(vec![], vec![])); + let function = + Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv, _a: i32| {}); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32], vec![]) + ); + let function = Function::new_native_with_env( + &store, + my_env.clone(), + |_env: &MyEnv, _a: i32, _b: i64, _c: f32, _d: f64| {}, + ); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) + ); + let function = + Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv| -> i32 { 1 }); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32]) + ); + let function = Function::new_native_with_env( + &store, + my_env.clone(), + |_env: &MyEnv| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, + ); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) + ); + } + + #[wasm_bindgen_test] + fn function_new_dynamic() { + let store = Store::default(); + + // Using &FunctionType signature + let function_type = FunctionType::new(vec![], vec![]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![Type::I32], vec![]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![], vec![Type::I32]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + + // Using array signature + let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); + let function = Function::new(&store, function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().params(), [Type::V128]); + assert_eq!(function.ty().results(), [Type::I32, Type::F32, Type::F64]); + } + + #[wasm_bindgen_test] + fn function_new_dynamic_env() { + let store = Store::default(); + #[derive(Clone, WasmerEnv)] + struct MyEnv {} + let my_env = MyEnv {}; + + // Using &FunctionType signature + let function_type = FunctionType::new(vec![], vec![]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![Type::I32], vec![]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![], vec![Type::I32]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + + // Using array signature + let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); + let function = Function::new_with_env( + &store, + function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().params(), [Type::V128]); + assert_eq!(function.ty().results(), [Type::I32, Type::F32, Type::F64]); + } + + #[wasm_bindgen_test] + fn native_function_works() { + let store = Store::default(); + let function = Function::new_native(&store, || {}); + let native_function: NativeFunc<(), ()> = function.native().unwrap(); + let result = native_function.call(); + assert!(result.is_ok()); + + let function = Function::new_native(&store, |a: i32| -> i32 { a + 1 }); + let native_function: NativeFunc = function.native().unwrap(); + assert_eq!(native_function.call(3).unwrap(), 4); + + // fn rust_abi(a: i32, b: i64, c: f32, d: f64) -> u64 { + // (a as u64 * 1000) + (b as u64 * 100) + (c as u64 * 10) + (d as u64) + // } + // let function = Function::new_native(&store, rust_abi); + // let native_function: NativeFunc<(i32, i64, f32, f64), u64> = function.native().unwrap(); + // assert_eq!(native_function.call(8, 4, 1.5, 5.).unwrap(), 8415); + + let function = Function::new_native(&store, || -> i32 { 1 }); + let native_function: NativeFunc<(), i32> = function.native().unwrap(); + assert_eq!(native_function.call().unwrap(), 1); + + let function = Function::new_native(&store, |_a: i32| {}); + let native_function: NativeFunc = function.native().unwrap(); + assert!(native_function.call(4).is_ok()); + + // let function = Function::new_native(&store, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); + // let native_function: NativeFunc<(), (i32, i64, f32, f64)> = function.native().unwrap(); + // assert_eq!(native_function.call().unwrap(), (1, 2, 3.0, 4.0)); + } + + #[wasm_bindgen_test] + fn function_outlives_instance() { + let store = Store::default(); + let wat = r#"(module + (type $sum_t (func (param i32 i32) (result i32))) + (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) + local.get $x + local.get $y + i32.add) + (export "sum" (func $sum_f))) +"#; + + let f = { + let module = Module::new(&store, wat).unwrap(); + let instance = Instance::new(&module, &imports! {}).unwrap(); + let f = instance.exports.get_function("sum").unwrap(); + + assert_eq!( + f.call(&[Val::I32(4), Val::I32(5)]).unwrap(), + vec![Val::I32(9)].into_boxed_slice() + ); + f.clone() + }; + + assert_eq!( + f.call(&[Val::I32(4), Val::I32(5)]).unwrap(), + vec![Val::I32(9)].into_boxed_slice() + ); + } + + #[wasm_bindgen_test] + fn manually_generate_wasmer_env() { + let store = Store::default(); + #[derive(WasmerEnv, Clone)] + struct MyEnv { + val: u32, + memory: LazyInit, + } + + fn host_function(env: &mut MyEnv, arg1: u32, arg2: u32) -> u32 { + env.val + arg1 + arg2 + } + + let mut env = MyEnv { + val: 5, + memory: LazyInit::new(), + }; + + let result = host_function(&mut env, 7, 9); + assert_eq!(result, 21); + + let memory = Memory::new(&store, MemoryType::new(0, None, false)).unwrap(); + env.memory.initialize(memory); + + let result = host_function(&mut env, 1, 2); + assert_eq!(result, 8); + } +} diff --git a/lib/api/tests/js_instance.rs b/lib/api/tests/js_instance.rs new file mode 100644 index 00000000000..374f0094140 --- /dev/null +++ b/lib/api/tests/js_instance.rs @@ -0,0 +1,735 @@ +#[cfg(feature = "js")] +mod js { + use anyhow::Result; + use wasm_bindgen_test::*; + use wasmer::*; + + #[wasm_bindgen_test] + fn test_exported_memory() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (memory (export "mem") 1) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![], + exports: vec![ExternType::Memory(MemoryType::new(Pages(1), None, false))], + }) + .unwrap(); + + let import_object = imports! {}; + let instance = Instance::new(&module, &import_object).unwrap(); + + let memory = instance.exports.get_memory("mem").unwrap(); + assert_eq!(memory.ty(), MemoryType::new(Pages(1), None, false)); + assert_eq!(memory.size(), Pages(1)); + assert_eq!(memory.data_size(), 65536); + + memory.grow(Pages(1)).unwrap(); + assert_eq!(memory.ty(), MemoryType::new(Pages(2), None, false)); + assert_eq!(memory.size(), Pages(2)); + assert_eq!(memory.data_size(), 65536 * 2); + } + + #[wasm_bindgen_test] + fn test_exported_function() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (func (export "get_magic") (result i32) + (i32.const 42) + ) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![], + exports: vec![ExternType::Function(FunctionType::new( + vec![], + vec![Type::I32], + ))], + }) + .unwrap(); + + let import_object = imports! {}; + let instance = Instance::new(&module, &import_object).unwrap(); + + let get_magic = instance.exports.get_function("get_magic").unwrap(); + assert_eq!( + get_magic.ty().clone(), + FunctionType::new(vec![], vec![Type::I32]) + ); + + let expected = vec![Val::I32(42)].into_boxed_slice(); + assert_eq!(get_magic.call(&[]), Ok(expected)); + } + + #[wasm_bindgen_test] + fn test_imported_function_dynamic() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (func $imported (import "env" "imported") (param i32) (result i32)) + (func (export "exported") (param i32) (result i32) + (call $imported (local.get 0)) + ) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + exports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + }) + .unwrap(); + + let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); + let imported = Function::new(&store, &imported_signature, |args| { + println!("Calling `imported`..."); + let result = args[0].unwrap_i32() * 2; + println!("Result of `imported`: {:?}", result); + Ok(vec![Value::I32(result)]) + }); + + let import_object = imports! { + "env" => { + "imported" => imported, + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let exported = instance.exports.get_function("exported").unwrap(); + + let expected = vec![Val::I32(6)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(3)]), Ok(expected)); + } + + // We comment it for now because in old versions of Node, only single return values are supported + + // #[wasm_bindgen_test] + // fn test_imported_function_dynamic_multivalue() { + // let store = Store::default(); + // let mut module = Module::new( + // &store, + // br#" + // (module + // (func $multivalue (import "env" "multivalue") (param i32 i32) (result i32 i32)) + // (func (export "multivalue") (param i32 i32) (result i32 i32) + // (call $multivalue (local.get 0) (local.get 1)) + // ) + // ) + // "#, + // ) + // .unwrap(); + // module.set_type_hints(ModuleTypeHints { + // imports: vec![ + // ExternType::Function(FunctionType::new( + // vec![Type::I32, Type::I32], + // vec![Type::I32, Type::I32], + // )), + // ], + // exports: vec![ + // ExternType::Function(FunctionType::new( + // vec![Type::I32, Type::I32], + // vec![Type::I32, Type::I32], + // )), + // ], + // }); + + // let multivalue_signature = + // FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32, Type::I32]); + // let multivalue = Function::new(&store, &multivalue_signature, |args| { + // println!("Calling `imported`..."); + // // let result = args[0].unwrap_i32() * ; + // // println!("Result of `imported`: {:?}", result); + // Ok(vec![args[1].clone(), args[0].clone()]) + // }); + + // let import_object = imports! { + // "env" => { + // "multivalue" => multivalue, + // } + // }; + // let instance = Instance::new(&module, &import_object).unwrap(); + + // let exported_multivalue = instance + // .exports + // .get_function("multivalue") + // .unwrap(); + + // let expected = vec![Val::I32(2), Val::I32(3)].into_boxed_slice(); + // assert_eq!( + // exported_multivalue.call(&[Val::I32(3), Val::I32(2)]), + // Ok(expected) + // ); + // } + + #[wasm_bindgen_test] + fn test_imported_function_dynamic_with_env() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (func $imported (import "env" "imported") (param i32) (result i32)) + (func (export "exported") (param i32) (result i32) + (call $imported (local.get 0)) + ) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + exports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + }) + .unwrap(); + + #[derive(WasmerEnv, Clone)] + struct Env { + multiplier: i32, + } + + let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); + let imported = Function::new_with_env( + &store, + &imported_signature, + Env { multiplier: 3 }, + |env, args| { + println!("Calling `imported`..."); + let result = args[0].unwrap_i32() * env.multiplier; + println!("Result of `imported`: {:?}", result); + Ok(vec![Value::I32(result)]) + }, + ); + + let import_object = imports! { + "env" => { + "imported" => imported, + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let exported = instance.exports.get_function("exported").unwrap(); + + let expected = vec![Val::I32(9)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(3)]), Ok(expected)); + } + + #[wasm_bindgen_test] + fn test_imported_function_native() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (func $imported (import "env" "imported") (param i32) (result i32)) + (func (export "exported") (param i32) (result i32) + (call $imported (local.get 0)) + ) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + exports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + }) + .unwrap(); + + fn imported_fn(arg: u32) -> u32 { + return arg + 1; + } + + let imported = Function::new_native(&store, imported_fn); + + let import_object = imports! { + "env" => { + "imported" => imported, + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let exported = instance.exports.get_function("exported").unwrap(); + + let expected = vec![Val::I32(5)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(4)]), Ok(expected)); + } + + #[wasm_bindgen_test] + fn test_imported_function_native_with_env() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (func $imported (import "env" "imported") (param i32) (result i32)) + (func (export "exported") (param i32) (result i32) + (call $imported (local.get 0)) + ) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + exports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + }) + .unwrap(); + + #[derive(WasmerEnv, Clone)] + struct Env { + multiplier: u32, + } + + fn imported_fn(env: &Env, arg: u32) -> u32 { + return env.multiplier * arg; + } + + let imported = Function::new_native_with_env(&store, Env { multiplier: 3 }, imported_fn); + + let import_object = imports! { + "env" => { + "imported" => imported, + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let exported = instance.exports.get_function("exported").unwrap(); + + let expected = vec![Val::I32(12)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(4)]), Ok(expected)); + } + + #[wasm_bindgen_test] + fn test_imported_function_native_with_wasmer_env() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (func $imported (import "env" "imported") (param i32) (result i32)) + (func (export "exported") (param i32) (result i32) + (call $imported (local.get 0)) + ) + (memory (export "memory") 1) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + exports: vec![ + ExternType::Function(FunctionType::new(vec![Type::I32], vec![Type::I32])), + ExternType::Memory(MemoryType::new(Pages(1), None, false)), + ], + }) + .unwrap(); + + #[derive(WasmerEnv, Clone)] + struct Env { + multiplier: u32, + #[wasmer(export)] + memory: LazyInit, + } + + fn imported_fn(env: &Env, arg: u32) -> u32 { + let memory = env.memory_ref().unwrap(); + let memory_val = memory.uint8view().get_index(0); + return (memory_val as u32) * env.multiplier * arg; + } + + let imported = Function::new_native_with_env( + &store, + Env { + multiplier: 3, + memory: LazyInit::new(), + }, + imported_fn, + ); + + let import_object = imports! { + "env" => { + "imported" => imported, + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let memory = instance.exports.get_memory("memory").unwrap(); + assert_eq!(memory.data_size(), 65536); + let memory_val = memory.uint8view().get_index(0); + assert_eq!(memory_val, 0); + + memory.uint8view().set_index(0, 2); + let memory_val = memory.uint8view().get_index(0); + assert_eq!(memory_val, 2); + + let exported = instance.exports.get_function("exported").unwrap(); + + // It works with the provided memory + let expected = vec![Val::I32(24)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(4)]), Ok(expected)); + + // It works if we update the memory + memory.uint8view().set_index(0, 3); + let expected = vec![Val::I32(36)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(4)]), Ok(expected)); + } + + #[wasm_bindgen_test] + fn test_imported_function_with_wasmer_env() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (func $imported (import "env" "imported") (param i32) (result i32)) + (func (export "exported") (param i32) (result i32) + (call $imported (local.get 0)) + ) + (memory (export "memory") 1) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![ExternType::Function(FunctionType::new( + vec![Type::I32], + vec![Type::I32], + ))], + exports: vec![ + ExternType::Function(FunctionType::new(vec![Type::I32], vec![Type::I32])), + ExternType::Memory(MemoryType::new(Pages(1), None, false)), + ], + }) + .unwrap(); + + #[derive(WasmerEnv, Clone)] + struct Env { + multiplier: u32, + #[wasmer(export)] + memory: LazyInit, + } + + fn imported_fn(env: &Env, args: &[Val]) -> Result, RuntimeError> { + let memory = env.memory_ref().unwrap(); + let memory_val = memory.uint8view().get_index(0); + let value = (memory_val as u32) * env.multiplier * args[0].unwrap_i32() as u32; + return Ok(vec![Val::I32(value as _)]); + } + + let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); + let imported = Function::new_with_env( + &store, + imported_signature, + Env { + multiplier: 3, + memory: LazyInit::new(), + }, + imported_fn, + ); + + let import_object = imports! { + "env" => { + "imported" => imported, + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let memory = instance.exports.get_memory("memory").unwrap(); + assert_eq!(memory.data_size(), 65536); + let memory_val = memory.uint8view().get_index(0); + assert_eq!(memory_val, 0); + + memory.uint8view().set_index(0, 2); + let memory_val = memory.uint8view().get_index(0); + assert_eq!(memory_val, 2); + + let exported = instance.exports.get_function("exported").unwrap(); + + // It works with the provided memory + let expected = vec![Val::I32(24)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(4)]), Ok(expected)); + + // It works if we update the memory + memory.uint8view().set_index(0, 3); + let expected = vec![Val::I32(36)].into_boxed_slice(); + assert_eq!(exported.call(&[Val::I32(4)]), Ok(expected)); + } + + #[wasm_bindgen_test] + fn test_imported_exported_global() { + let store = Store::default(); + let mut module = Module::new( + &store, + br#" + (module + (global $mut_i32_import (import "" "global") (mut i32)) + (func (export "getGlobal") (result i32) (global.get $mut_i32_import)) + (func (export "incGlobal") (global.set $mut_i32_import ( + i32.add (i32.const 1) (global.get $mut_i32_import) + ))) + ) + "#, + ) + .unwrap(); + module + .set_type_hints(ModuleTypeHints { + imports: vec![ExternType::Global(GlobalType::new( + ValType::I32, + Mutability::Var, + ))], + exports: vec![ + ExternType::Function(FunctionType::new(vec![], vec![Type::I32])), + ExternType::Function(FunctionType::new(vec![], vec![])), + ], + }) + .unwrap(); + let global = Global::new_mut(&store, Value::I32(0)); + let import_object = imports! { + "" => { + "global" => global.clone() + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let get_global = instance.exports.get_function("getGlobal").unwrap(); + assert_eq!( + get_global.call(&[]), + Ok(vec![Val::I32(0)].into_boxed_slice()) + ); + + global.set(Value::I32(42)).unwrap(); + assert_eq!( + get_global.call(&[]), + Ok(vec![Val::I32(42)].into_boxed_slice()) + ); + + let inc_global = instance.exports.get_function("incGlobal").unwrap(); + inc_global.call(&[]).unwrap(); + assert_eq!( + get_global.call(&[]), + Ok(vec![Val::I32(43)].into_boxed_slice()) + ); + assert_eq!(global.get(), Val::I32(43)); + } + + #[wasm_bindgen_test] + fn test_native_function() { + let store = Store::default(); + let module = Module::new( + &store, + br#"(module + (func $add (import "env" "sum") (param i32 i32) (result i32)) + (func (export "add_one") (param i32) (result i32) + (call $add (local.get 0) (i32.const 1)) + ) + )"#, + ) + .unwrap(); + + fn sum(a: i32, b: i32) -> i32 { + a + b + } + + let import_object = imports! { + "env" => { + "sum" => Function::new_native(&store, sum), + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let add_one: NativeFunc = + instance.exports.get_native_function("add_one").unwrap(); + assert_eq!(add_one.call(1), Ok(2)); + } + + #[wasm_bindgen_test] + fn test_panic() { + let store = Store::default(); + let module = Module::new( + &store, + br#" +(module + (type $run_t (func (param i32 i32) (result i32))) + (type $early_exit_t (func (param) (result))) + (import "env" "early_exit" (func $early_exit (type $early_exit_t))) + (func $run (type $run_t) (param $x i32) (param $y i32) (result i32) + (call $early_exit) + (i32.add + local.get $x + local.get $y)) + (export "run" (func $run))) +"#, + ) + .unwrap(); + + fn early_exit() { + panic!("Do panic") + } + + let import_object = imports! { + "env" => { + "early_exit" => Function::new_native(&store, early_exit), + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + let run_func: NativeFunc<(i32, i32), i32> = + instance.exports.get_native_function("run").unwrap(); + + assert!(run_func.call(1, 7).is_err(), "Expected early termination",); + let run_func = instance.exports.get_function("run").unwrap(); + + assert!( + run_func.call(&[Val::I32(1), Val::I32(7)]).is_err(), + "Expected early termination", + ); + } + + #[wasm_bindgen_test] + fn test_custom_error() { + let store = Store::default(); + let module = Module::new( + &store, + br#" +(module + (type $run_t (func (param i32 i32) (result i32))) + (type $early_exit_t (func (param) (result))) + (import "env" "early_exit" (func $early_exit (type $early_exit_t))) + (func $run (type $run_t) (param $x i32) (param $y i32) (result i32) + (call $early_exit) + (i32.add + local.get $x + local.get $y)) + (export "run" (func $run))) +"#, + ) + .unwrap(); + + use std::fmt; + + #[derive(Debug, Clone, Copy)] + struct ExitCode(u32); + + impl fmt::Display for ExitCode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } + } + + impl std::error::Error for ExitCode {} + + fn early_exit() { + RuntimeError::raise(Box::new(ExitCode(1))); + } + + let import_object = imports! { + "env" => { + "early_exit" => Function::new_native(&store, early_exit), + } + }; + let instance = Instance::new(&module, &import_object).unwrap(); + + fn test_result(result: Result) { + match result { + Ok(result) => { + assert!( + false, + "Expected early termination with `ExitCode`, found: {:?}", + result + ); + } + Err(e) => { + match e.downcast::() { + // We found the exit code used to terminate execution. + Ok(exit_code) => { + assert_eq!(exit_code.0, 1); + } + Err(e) => { + assert!(false, "Unknown error `{:?}` found. expected `ErrorCode`", e); + } + } + } + } + } + + let run_func: NativeFunc<(i32, i32), i32> = + instance.exports.get_native_function("run").unwrap(); + test_result(run_func.call(1, 7)); + + let run_func = instance.exports.get_function("run").unwrap(); + test_result(run_func.call(&[Val::I32(1), Val::I32(7)])); + } + + #[wasm_bindgen_test] + fn test_start_function_fails() { + let store = Store::default(); + let module = Module::new( + &store, + br#" + (module + (func $start_function + (i32.div_u + (i32.const 1) + (i32.const 0) + ) + drop + ) + (start $start_function) + ) + "#, + ) + .unwrap(); + + let import_object = imports! {}; + let result = Instance::new(&module, &import_object); + let err = result.unwrap_err(); + assert!(format!("{:?}", err).contains("zero")) + } +} diff --git a/lib/api/tests/js_module.rs b/lib/api/tests/js_module.rs new file mode 100644 index 00000000000..f245e222806 --- /dev/null +++ b/lib/api/tests/js_module.rs @@ -0,0 +1,294 @@ +#[cfg(feature = "js")] +mod js { + use js_sys::{Uint8Array, WebAssembly}; + use wasm_bindgen_test::*; + use wasmer::*; + + #[wasm_bindgen_test] + fn module_get_name() { + let store = Store::default(); + let wat = r#"(module)"#; + let module = Module::new(&store, wat).unwrap(); + assert_eq!(module.name(), None); + } + + #[wasm_bindgen_test] + fn module_set_name() { + let store = Store::default(); + let wat = r#"(module $name)"#; + let mut module = Module::new(&store, wat).unwrap(); + + #[cfg(feature = "wasm-types-polyfill")] + assert_eq!(module.name(), Some("name")); + + module.set_name("new_name"); + assert_eq!(module.name(), Some("new_name")); + } + + #[wasm_bindgen_test] + fn module_from_jsmodule() { + let wat = br#"(module $name)"#; + let binary = wat2wasm(wat).unwrap(); + let js_bytes = unsafe { Uint8Array::view(&binary) }; + let js_module = WebAssembly::Module::new(&js_bytes.into()).unwrap(); + let module: Module = js_module.into(); + assert_eq!(module.store(), &Store::default()); + } + + #[wasm_bindgen_test] + fn imports() { + let store = Store::default(); + let wat = r#"(module + (import "host" "func" (func)) + (import "host" "memory" (memory 1)) + (import "host" "table" (table 1 anyfunc)) + (import "host" "global" (global i32)) +)"#; + let module = Module::new(&store, wat).unwrap(); + assert_eq!( + module.imports().collect::>(), + vec![ + ImportType::new( + "host", + "func", + ExternType::Function(FunctionType::new(vec![], vec![])) + ), + ImportType::new( + "host", + "memory", + ExternType::Memory(MemoryType::new(Pages(1), None, false)) + ), + ImportType::new( + "host", + "table", + ExternType::Table(TableType::new(Type::FuncRef, 1, None)) + ), + ImportType::new( + "host", + "global", + ExternType::Global(GlobalType::new(Type::I32, Mutability::Const)) + ) + ] + ); + + // Now we test the iterators + assert_eq!( + module.imports().functions().collect::>(), + vec![ImportType::new( + "host", + "func", + FunctionType::new(vec![], vec![]) + ),] + ); + assert_eq!( + module.imports().memories().collect::>(), + vec![ImportType::new( + "host", + "memory", + MemoryType::new(Pages(1), None, false) + ),] + ); + assert_eq!( + module.imports().tables().collect::>(), + vec![ImportType::new( + "host", + "table", + TableType::new(Type::FuncRef, 1, None) + ),] + ); + assert_eq!( + module.imports().globals().collect::>(), + vec![ImportType::new( + "host", + "global", + GlobalType::new(Type::I32, Mutability::Const) + ),] + ); + } + + #[wasm_bindgen_test] + fn exports() { + let store = Store::default(); + let wat = r#"(module + (func (export "func") nop) + (memory (export "memory") 2) + (table (export "table") 2 funcref) + (global (export "global") i32 (i32.const 0)) +)"#; + let mut module = Module::new(&store, wat).unwrap(); + module + .set_type_hints(ModuleTypeHints { + exports: vec![ + ExternType::Function(FunctionType::new(vec![], vec![])), + ExternType::Memory(MemoryType::new(Pages(2), None, false)), + ExternType::Table(TableType::new(Type::FuncRef, 2, None)), + ExternType::Global(GlobalType::new(Type::I32, Mutability::Const)), + ], + imports: vec![], + }) + .unwrap(); + assert_eq!( + module.exports().collect::>(), + vec![ + ExportType::new( + "func", + ExternType::Function(FunctionType::new(vec![], vec![])) + ), + ExportType::new( + "memory", + ExternType::Memory(MemoryType::new(Pages(2), None, false)) + ), + ExportType::new( + "table", + ExternType::Table(TableType::new(Type::FuncRef, 2, None)) + ), + ExportType::new( + "global", + ExternType::Global(GlobalType::new(Type::I32, Mutability::Const)) + ) + ] + ); + + // Now we test the iterators + assert_eq!( + module.exports().functions().collect::>(), + vec![ExportType::new("func", FunctionType::new(vec![], vec![])),] + ); + assert_eq!( + module.exports().memories().collect::>(), + vec![ExportType::new( + "memory", + MemoryType::new(Pages(2), None, false) + ),] + ); + assert_eq!( + module.exports().tables().collect::>(), + vec![ExportType::new( + "table", + TableType::new(Type::FuncRef, 2, None) + ),] + ); + assert_eq!( + module.exports().globals().collect::>(), + vec![ExportType::new( + "global", + GlobalType::new(Type::I32, Mutability::Const) + ),] + ); + } + + // Test commented because it doesn't work in old versions of Node + // which makes the CI to fail. + + // #[wasm_bindgen_test] + // fn calling_host_functions_with_negative_values_works() { + // let store = Store::default(); + // let wat = r#"(module + // (import "host" "host_func1" (func (param i64))) + // (import "host" "host_func2" (func (param i32))) + // (import "host" "host_func3" (func (param i64))) + // (import "host" "host_func4" (func (param i32))) + // (import "host" "host_func5" (func (param i32))) + // (import "host" "host_func6" (func (param i32))) + // (import "host" "host_func7" (func (param i32))) + // (import "host" "host_func8" (func (param i32))) + + // (func (export "call_host_func1") + // (call 0 (i64.const -1))) + // (func (export "call_host_func2") + // (call 1 (i32.const -1))) + // (func (export "call_host_func3") + // (call 2 (i64.const -1))) + // (func (export "call_host_func4") + // (call 3 (i32.const -1))) + // (func (export "call_host_func5") + // (call 4 (i32.const -1))) + // (func (export "call_host_func6") + // (call 5 (i32.const -1))) + // (func (export "call_host_func7") + // (call 6 (i32.const -1))) + // (func (export "call_host_func8") + // (call 7 (i32.const -1))) + // )"#; + // let module = Module::new(&store, wat).unwrap(); + // let imports = imports! { + // "host" => { + // "host_func1" => Function::new_native(&store, |p: u64| { + // println!("host_func1: Found number {}", p); + // assert_eq!(p, u64::max_value()); + // }), + // "host_func2" => Function::new_native(&store, |p: u32| { + // println!("host_func2: Found number {}", p); + // assert_eq!(p, u32::max_value()); + // }), + // "host_func3" => Function::new_native(&store, |p: i64| { + // println!("host_func3: Found number {}", p); + // assert_eq!(p, -1); + // }), + // "host_func4" => Function::new_native(&store, |p: i32| { + // println!("host_func4: Found number {}", p); + // assert_eq!(p, -1); + // }), + // "host_func5" => Function::new_native(&store, |p: i16| { + // println!("host_func5: Found number {}", p); + // assert_eq!(p, -1); + // }), + // "host_func6" => Function::new_native(&store, |p: u16| { + // println!("host_func6: Found number {}", p); + // assert_eq!(p, u16::max_value()); + // }), + // "host_func7" => Function::new_native(&store, |p: i8| { + // println!("host_func7: Found number {}", p); + // assert_eq!(p, -1); + // }), + // "host_func8" => Function::new_native(&store, |p: u8| { + // println!("host_func8: Found number {}", p); + // assert_eq!(p, u8::max_value()); + // }), + // } + // }; + // let instance = Instance::new(&module, &imports).unwrap(); + + // let f1: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func1") + // .unwrap(); + // let f2: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func2") + // .unwrap(); + // let f3: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func3") + // .unwrap(); + // let f4: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func4") + // .unwrap(); + // let f5: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func5") + // .unwrap(); + // let f6: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func6") + // .unwrap(); + // let f7: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func7") + // .unwrap(); + // let f8: NativeFunc<(), ()> = instance + // .exports + // .get_native_function("call_host_func8") + // .unwrap(); + + // f1.call().unwrap(); + // f2.call().unwrap(); + // f3.call().unwrap(); + // f4.call().unwrap(); + // f5.call().unwrap(); + // f6.call().unwrap(); + // f7.call().unwrap(); + // f8.call().unwrap(); + // } +} diff --git a/lib/api/tests/module.rs b/lib/api/tests/module.rs deleted file mode 100644 index 64708d2ae54..00000000000 --- a/lib/api/tests/module.rs +++ /dev/null @@ -1,248 +0,0 @@ -use anyhow::Result; -use wasmer::*; - -#[test] -fn module_get_name() -> Result<()> { - let store = Store::default(); - let wat = r#"(module)"#; - let module = Module::new(&store, wat)?; - assert_eq!(module.name(), None); - - Ok(()) -} - -#[test] -fn module_set_name() -> Result<()> { - let store = Store::default(); - let wat = r#"(module $name)"#; - let mut module = Module::new(&store, wat)?; - assert_eq!(module.name(), Some("name")); - - module.set_name("new_name"); - assert_eq!(module.name(), Some("new_name")); - - Ok(()) -} - -#[test] -fn imports() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (import "host" "func" (func)) - (import "host" "memory" (memory 1)) - (import "host" "table" (table 1 anyfunc)) - (import "host" "global" (global i32)) -)"#; - let module = Module::new(&store, wat)?; - assert_eq!( - module.imports().collect::>(), - vec![ - ImportType::new( - "host", - "func", - ExternType::Function(FunctionType::new(vec![], vec![])) - ), - ImportType::new( - "host", - "memory", - ExternType::Memory(MemoryType::new(Pages(1), None, false)) - ), - ImportType::new( - "host", - "table", - ExternType::Table(TableType::new(Type::FuncRef, 1, None)) - ), - ImportType::new( - "host", - "global", - ExternType::Global(GlobalType::new(Type::I32, Mutability::Const)) - ) - ] - ); - - // Now we test the iterators - assert_eq!( - module.imports().functions().collect::>(), - vec![ImportType::new( - "host", - "func", - FunctionType::new(vec![], vec![]) - ),] - ); - assert_eq!( - module.imports().memories().collect::>(), - vec![ImportType::new( - "host", - "memory", - MemoryType::new(Pages(1), None, false) - ),] - ); - assert_eq!( - module.imports().tables().collect::>(), - vec![ImportType::new( - "host", - "table", - TableType::new(Type::FuncRef, 1, None) - ),] - ); - assert_eq!( - module.imports().globals().collect::>(), - vec![ImportType::new( - "host", - "global", - GlobalType::new(Type::I32, Mutability::Const) - ),] - ); - Ok(()) -} - -#[test] -fn exports() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (func (export "func") nop) - (memory (export "memory") 1) - (table (export "table") 1 funcref) - (global (export "global") i32 (i32.const 0)) -)"#; - let module = Module::new(&store, wat)?; - assert_eq!( - module.exports().collect::>(), - vec![ - ExportType::new( - "func", - ExternType::Function(FunctionType::new(vec![], vec![])) - ), - ExportType::new( - "memory", - ExternType::Memory(MemoryType::new(Pages(1), None, false)) - ), - ExportType::new( - "table", - ExternType::Table(TableType::new(Type::FuncRef, 1, None)) - ), - ExportType::new( - "global", - ExternType::Global(GlobalType::new(Type::I32, Mutability::Const)) - ) - ] - ); - - // Now we test the iterators - assert_eq!( - module.exports().functions().collect::>(), - vec![ExportType::new("func", FunctionType::new(vec![], vec![])),] - ); - assert_eq!( - module.exports().memories().collect::>(), - vec![ExportType::new( - "memory", - MemoryType::new(Pages(1), None, false) - ),] - ); - assert_eq!( - module.exports().tables().collect::>(), - vec![ExportType::new( - "table", - TableType::new(Type::FuncRef, 1, None) - ),] - ); - assert_eq!( - module.exports().globals().collect::>(), - vec![ExportType::new( - "global", - GlobalType::new(Type::I32, Mutability::Const) - ),] - ); - Ok(()) -} - -#[test] -fn calling_host_functions_with_negative_values_works() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (import "host" "host_func1" (func (param i64))) - (import "host" "host_func2" (func (param i32))) - (import "host" "host_func3" (func (param i64))) - (import "host" "host_func4" (func (param i32))) - (import "host" "host_func5" (func (param i32))) - (import "host" "host_func6" (func (param i32))) - (import "host" "host_func7" (func (param i32))) - (import "host" "host_func8" (func (param i32))) - - (func (export "call_host_func1") - (call 0 (i64.const -1))) - (func (export "call_host_func2") - (call 1 (i32.const -1))) - (func (export "call_host_func3") - (call 2 (i64.const -1))) - (func (export "call_host_func4") - (call 3 (i32.const -1))) - (func (export "call_host_func5") - (call 4 (i32.const -1))) - (func (export "call_host_func6") - (call 5 (i32.const -1))) - (func (export "call_host_func7") - (call 6 (i32.const -1))) - (func (export "call_host_func8") - (call 7 (i32.const -1))) -)"#; - let module = Module::new(&store, wat)?; - let imports = imports! { - "host" => { - "host_func1" => Function::new_native(&store, |p: u64| { - println!("host_func1: Found number {}", p); - assert_eq!(p, u64::max_value()); - }), - "host_func2" => Function::new_native(&store, |p: u32| { - println!("host_func2: Found number {}", p); - assert_eq!(p, u32::max_value()); - }), - "host_func3" => Function::new_native(&store, |p: i64| { - println!("host_func3: Found number {}", p); - assert_eq!(p, -1); - }), - "host_func4" => Function::new_native(&store, |p: i32| { - println!("host_func4: Found number {}", p); - assert_eq!(p, -1); - }), - "host_func5" => Function::new_native(&store, |p: i16| { - println!("host_func5: Found number {}", p); - assert_eq!(p, -1); - }), - "host_func6" => Function::new_native(&store, |p: u16| { - println!("host_func6: Found number {}", p); - assert_eq!(p, u16::max_value()); - }), - "host_func7" => Function::new_native(&store, |p: i8| { - println!("host_func7: Found number {}", p); - assert_eq!(p, -1); - }), - "host_func8" => Function::new_native(&store, |p: u8| { - println!("host_func8: Found number {}", p); - assert_eq!(p, u8::max_value()); - }), - } - }; - let instance = Instance::new(&module, &imports)?; - - let f1: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func1")?; - let f2: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func2")?; - let f3: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func3")?; - let f4: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func4")?; - let f5: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func5")?; - let f6: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func6")?; - let f7: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func7")?; - let f8: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func8")?; - - f1.call()?; - f2.call()?; - f3.call()?; - f4.call()?; - f5.call()?; - f6.call()?; - f7.call()?; - f8.call()?; - - Ok(()) -} diff --git a/lib/api/tests/reference_types.rs b/lib/api/tests/reference_types.rs deleted file mode 100644 index 8a1aaa6e033..00000000000 --- a/lib/api/tests/reference_types.rs +++ /dev/null @@ -1,497 +0,0 @@ -use anyhow::Result; -use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use wasmer::*; - -#[test] -fn func_ref_passed_and_returned() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (import "env" "func_ref_identity" (func (param funcref) (result funcref))) - (type $ret_i32_ty (func (result i32))) - (table $table (export "table") 2 2 funcref) - - (func (export "run") (param) (result funcref) - (call 0 (ref.null func))) - (func (export "call_set_value") (param $fr funcref) (result i32) - (table.set $table (i32.const 0) (local.get $fr)) - (call_indirect $table (type $ret_i32_ty) (i32.const 0))) -)"#; - let module = Module::new(&store, wat)?; - let imports = imports! { - "env" => { - "func_ref_identity" => Function::new(&store, FunctionType::new([Type::FuncRef], [Type::FuncRef]), |values| -> Result, _> { - Ok(vec![values[0].clone()]) - }) - }, - }; - - let instance = Instance::new(&module, &imports)?; - - let f: &Function = instance.exports.get_function("run")?; - let results = f.call(&[]).unwrap(); - if let Value::FuncRef(fr) = &results[0] { - assert!(fr.is_none()); - } else { - panic!("funcref not found!"); - } - - #[derive(Clone, Debug, WasmerEnv)] - pub struct Env(Arc); - let env = Env(Arc::new(AtomicBool::new(false))); - - let func_to_call = Function::new_native_with_env(&store, env.clone(), |env: &Env| -> i32 { - env.0.store(true, Ordering::SeqCst); - 343 - }); - let call_set_value: &Function = instance.exports.get_function("call_set_value")?; - let results: Box<[Value]> = call_set_value.call(&[Value::FuncRef(Some(func_to_call))])?; - assert!(env.0.load(Ordering::SeqCst)); - assert_eq!(&*results, &[Value::I32(343)]); - - Ok(()) -} - -#[test] -fn func_ref_passed_and_called() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (func $func_ref_call (import "env" "func_ref_call") (param funcref) (result i32)) - (type $ret_i32_ty (func (result i32))) - (table $table (export "table") 2 2 funcref) - - (func $product (param $x i32) (param $y i32) (result i32) - (i32.mul (local.get $x) (local.get $y))) - ;; TODO: figure out exactly why this statement is needed - (elem declare func $product) - (func (export "call_set_value") (param $fr funcref) (result i32) - (table.set $table (i32.const 0) (local.get $fr)) - (call_indirect $table (type $ret_i32_ty) (i32.const 0))) - (func (export "call_func") (param $fr funcref) (result i32) - (call $func_ref_call (local.get $fr))) - (func (export "call_host_func_with_wasm_func") (result i32) - (call $func_ref_call (ref.func $product))) -)"#; - let module = Module::new(&store, wat)?; - - fn func_ref_call(values: &[Value]) -> Result, RuntimeError> { - // TODO: look into `Box<[Value]>` being returned breakage - let f = values[0].unwrap_funcref().as_ref().unwrap(); - let f: NativeFunc<(i32, i32), i32> = f.native()?; - Ok(vec![Value::I32(f.call(7, 9)?)]) - } - - let imports = imports! { - "env" => { - "func_ref_call" => Function::new( - &store, - FunctionType::new([Type::FuncRef], [Type::I32]), - func_ref_call - ), - // TODO(reftypes): this should work - /* - "func_ref_call_native" => Function::new_native(&store, |f: Function| -> Result { - let f: NativeFunc::<(i32, i32), i32> = f.native()?; - f.call(7, 9) - }) - */ - }, - }; - - let instance = Instance::new(&module, &imports)?; - { - fn sum(a: i32, b: i32) -> i32 { - a + b - } - let sum_func = Function::new_native(&store, sum); - - let call_func: &Function = instance.exports.get_function("call_func")?; - let result = call_func.call(&[Value::FuncRef(Some(sum_func))])?; - assert_eq!(result[0].unwrap_i32(), 16); - } - - { - let f: NativeFunc<(), i32> = instance - .exports - .get_native_function("call_host_func_with_wasm_func")?; - let result = f.call()?; - assert_eq!(result, 63); - } - - Ok(()) -} - -#[cfg(feature = "experimental-reference-types-extern-ref")] -#[test] -fn extern_ref_passed_and_returned() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (func $extern_ref_identity (import "env" "extern_ref_identity") (param externref) (result externref)) - (func $extern_ref_identity_native (import "env" "extern_ref_identity_native") (param externref) (result externref)) - (func $get_new_extern_ref (import "env" "get_new_extern_ref") (result externref)) - (func $get_new_extern_ref_native (import "env" "get_new_extern_ref_native") (result externref)) - - (func (export "run") (param) (result externref) - (call $extern_ref_identity (ref.null extern))) - (func (export "run_native") (param) (result externref) - (call $extern_ref_identity_native (ref.null extern))) - (func (export "get_hashmap") (param) (result externref) - (call $get_new_extern_ref)) - (func (export "get_hashmap_native") (param) (result externref) - (call $get_new_extern_ref_native)) -)"#; - let module = Module::new(&store, wat)?; - let imports = imports! { - "env" => { - "extern_ref_identity" => Function::new(&store, FunctionType::new([Type::ExternRef], [Type::ExternRef]), |values| -> Result, _> { - Ok(vec![values[0].clone()]) - }), - "extern_ref_identity_native" => Function::new_native(&store, |er: ExternRef| -> ExternRef { - er - }), - "get_new_extern_ref" => Function::new(&store, FunctionType::new([], [Type::ExternRef]), |_| -> Result, _> { - let inner = - [("hello".to_string(), "world".to_string()), - ("color".to_string(), "orange".to_string())] - .iter() - .cloned() - .collect::>(); - let new_extern_ref = ExternRef::new(inner); - Ok(vec![Value::ExternRef(new_extern_ref)]) - }), - "get_new_extern_ref_native" => Function::new_native(&store, || -> ExternRef { - let inner = - [("hello".to_string(), "world".to_string()), - ("color".to_string(), "orange".to_string())] - .iter() - .cloned() - .collect::>(); - ExternRef::new(inner) - }) - }, - }; - - let instance = Instance::new(&module, &imports)?; - for run in &["run", "run_native"] { - let f: &Function = instance.exports.get_function(run)?; - let results = f.call(&[]).unwrap(); - if let Value::ExternRef(er) = &results[0] { - assert!(er.is_null()); - } else { - panic!("result is not an extern ref!"); - } - - let f: NativeFunc<(), ExternRef> = instance.exports.get_native_function(run)?; - let result: ExternRef = f.call()?; - assert!(result.is_null()); - } - - for get_hashmap in &["get_hashmap", "get_hashmap_native"] { - let f: &Function = instance.exports.get_function(get_hashmap)?; - let results = f.call(&[]).unwrap(); - if let Value::ExternRef(er) = &results[0] { - let inner: &HashMap = er.downcast().unwrap(); - assert_eq!(inner["hello"], "world"); - assert_eq!(inner["color"], "orange"); - } else { - panic!("result is not an extern ref!"); - } - - let f: NativeFunc<(), ExternRef> = instance.exports.get_native_function(get_hashmap)?; - - let result: ExternRef = f.call()?; - let inner: &HashMap = result.downcast().unwrap(); - assert_eq!(inner["hello"], "world"); - assert_eq!(inner["color"], "orange"); - } - - Ok(()) -} - -#[cfg(feature = "experimental-reference-types-extern-ref")] -#[test] -// TODO(reftypes): reenable this test -#[ignore] -fn extern_ref_ref_counting_basic() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (func (export "drop") (param $er externref) (result) - (drop (local.get $er))) -)"#; - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - let f: NativeFunc = instance.exports.get_native_function("drop")?; - - let er = ExternRef::new(3u32); - f.call(er.clone())?; - - assert_eq!(er.downcast::().unwrap(), &3); - assert_eq!(er.strong_count(), 1); - - Ok(()) -} - -#[cfg(feature = "experimental-reference-types-extern-ref")] -#[test] -fn refs_in_globals() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (global $er_global (export "er_global") (mut externref) (ref.null extern)) - (global $fr_global (export "fr_global") (mut funcref) (ref.null func)) - (global $fr_immutable_global (export "fr_immutable_global") funcref (ref.func $hello)) - (func $hello (param) (result i32) - (i32.const 73)) -)"#; - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - { - let er_global: &Global = instance.exports.get_global("er_global")?; - - if let Value::ExternRef(er) = er_global.get() { - assert!(er.is_null()); - } else { - panic!("Did not find extern ref in the global"); - } - - er_global.set(Val::ExternRef(ExternRef::new(3u32)))?; - - if let Value::ExternRef(er) = er_global.get() { - assert_eq!(er.downcast::().unwrap(), &3); - assert_eq!(er.strong_count(), 1); - } else { - panic!("Did not find extern ref in the global"); - } - } - - { - let fr_global: &Global = instance.exports.get_global("fr_immutable_global")?; - - if let Value::FuncRef(Some(f)) = fr_global.get() { - let native_func: NativeFunc<(), u32> = f.native()?; - assert_eq!(native_func.call()?, 73); - } else { - panic!("Did not find non-null func ref in the global"); - } - } - - { - let fr_global: &Global = instance.exports.get_global("fr_global")?; - - if let Value::FuncRef(None) = fr_global.get() { - } else { - panic!("Did not find a null func ref in the global"); - } - - let f = Function::new_native(&store, |arg1: i32, arg2: i32| -> i32 { arg1 + arg2 }); - - fr_global.set(Val::FuncRef(Some(f)))?; - - if let Value::FuncRef(Some(f)) = fr_global.get() { - let native: NativeFunc<(i32, i32), i32> = f.native()?; - assert_eq!(native.call(5, 7)?, 12); - } else { - panic!("Did not find extern ref in the global"); - } - } - - Ok(()) -} - -#[cfg(feature = "experimental-reference-types-extern-ref")] -#[test] -fn extern_ref_ref_counting_table_basic() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (global $global (export "global") (mut externref) (ref.null extern)) - (table $table (export "table") 4 4 externref) - (func $insert (param $er externref) (param $idx i32) - (table.set $table (local.get $idx) (local.get $er))) - (func $intermediate (param $er externref) (param $idx i32) - (call $insert (local.get $er) (local.get $idx))) - (func $insert_into_table (export "insert_into_table") (param $er externref) (param $idx i32) (result externref) - (call $intermediate (local.get $er) (local.get $idx)) - (local.get $er)) -)"#; - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - - let f: NativeFunc<(ExternRef, i32), ExternRef> = - instance.exports.get_native_function("insert_into_table")?; - - let er = ExternRef::new(3usize); - - let er = f.call(er, 1)?; - assert_eq!(er.strong_count(), 2); - - let table: &Table = instance.exports.get_table("table")?; - - { - let er2 = table.get(1).unwrap().externref().unwrap(); - assert_eq!(er2.strong_count(), 3); - } - - assert_eq!(er.strong_count(), 2); - table.set(1, Val::ExternRef(ExternRef::null()))?; - - assert_eq!(er.strong_count(), 1); - - Ok(()) -} - -#[cfg(feature = "experimental-reference-types-extern-ref")] -#[test] -// TODO(reftypes): reenable this test -#[ignore] -fn extern_ref_ref_counting_global_basic() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (global $global (export "global") (mut externref) (ref.null extern)) - (func $get_from_global (export "get_from_global") (result externref) - (drop (global.get $global)) - (global.get $global)) -)"#; - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - - let global: &Global = instance.exports.get_global("global")?; - { - let er = ExternRef::new(3usize); - global.set(Val::ExternRef(er.clone()))?; - assert_eq!(er.strong_count(), 2); - } - let get_from_global: NativeFunc<(), ExternRef> = - instance.exports.get_native_function("get_from_global")?; - - let er = get_from_global.call()?; - assert_eq!(er.strong_count(), 2); - global.set(Val::ExternRef(ExternRef::null()))?; - assert_eq!(er.strong_count(), 1); - - Ok(()) -} - -#[cfg(feature = "experimental-reference-types-extern-ref")] -#[test] -// TODO(reftypes): reenable this test -#[ignore] -fn extern_ref_ref_counting_traps() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (func $pass_er (export "pass_extern_ref") (param externref) - (local.get 0) - (unreachable)) -)"#; - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - - let pass_extern_ref: NativeFunc = - instance.exports.get_native_function("pass_extern_ref")?; - - let er = ExternRef::new(3usize); - assert_eq!(er.strong_count(), 1); - - let result = pass_extern_ref.call(er.clone()); - assert!(result.is_err()); - assert_eq!(er.strong_count(), 1); - - Ok(()) -} - -#[cfg(feature = "experimental-reference-types-extern-ref")] -#[test] -fn extern_ref_ref_counting_table_instructions() -> Result<()> { - let store = Store::default(); - let wat = r#"(module - (table $table1 (export "table1") 2 12 externref) - (table $table2 (export "table2") 6 12 externref) - (func $grow_table_with_ref (export "grow_table_with_ref") (param $er externref) (param $size i32) (result i32) - (table.grow $table1 (local.get $er) (local.get $size))) - (func $fill_table_with_ref (export "fill_table_with_ref") (param $er externref) (param $start i32) (param $end i32) - (table.fill $table1 (local.get $start) (local.get $er) (local.get $end))) - (func $copy_into_table2 (export "copy_into_table2") - (table.copy $table2 $table1 (i32.const 0) (i32.const 0) (i32.const 4))) -)"#; - let module = Module::new(&store, wat)?; - let instance = Instance::new(&module, &imports! {})?; - - let grow_table_with_ref: NativeFunc<(ExternRef, i32), i32> = instance - .exports - .get_native_function("grow_table_with_ref")?; - let fill_table_with_ref: NativeFunc<(ExternRef, i32, i32), ()> = instance - .exports - .get_native_function("fill_table_with_ref")?; - let copy_into_table2: NativeFunc<(), ()> = - instance.exports.get_native_function("copy_into_table2")?; - let table1: &Table = instance.exports.get_table("table1")?; - let table2: &Table = instance.exports.get_table("table2")?; - - let er1 = ExternRef::new(3usize); - let er2 = ExternRef::new(5usize); - let er3 = ExternRef::new(7usize); - { - let result = grow_table_with_ref.call(er1.clone(), 0)?; - assert_eq!(result, 2); - assert_eq!(er1.strong_count(), 1); - - let result = grow_table_with_ref.call(er1.clone(), 10_000)?; - assert_eq!(result, -1); - assert_eq!(er1.strong_count(), 1); - - let result = grow_table_with_ref.call(er1.clone(), 8)?; - assert_eq!(result, 2); - assert_eq!(er1.strong_count(), 9); - - for i in 2..10 { - let e = table1.get(i).unwrap().unwrap_externref(); - assert_eq!(*e.downcast::().unwrap(), 3); - assert_eq!(&e, &er1); - } - assert_eq!(er1.strong_count(), 9); - } - - { - fill_table_with_ref.call(er2.clone(), 0, 2)?; - assert_eq!(er2.strong_count(), 3); - } - - { - table2.set(0, Val::ExternRef(er3.clone()))?; - table2.set(1, Val::ExternRef(er3.clone()))?; - table2.set(2, Val::ExternRef(er3.clone()))?; - table2.set(3, Val::ExternRef(er3.clone()))?; - table2.set(4, Val::ExternRef(er3.clone()))?; - assert_eq!(er3.strong_count(), 6); - } - - { - copy_into_table2.call()?; - assert_eq!(er3.strong_count(), 2); - assert_eq!(er2.strong_count(), 5); - assert_eq!(er1.strong_count(), 11); - for i in 1..5 { - let e = table2.get(i).unwrap().unwrap_externref(); - let value = e.downcast::().unwrap(); - match i { - 0 | 1 => assert_eq!(*value, 5), - 4 => assert_eq!(*value, 7), - _ => assert_eq!(*value, 3), - } - } - } - - { - for i in 0..table1.size() { - table1.set(i, Val::ExternRef(ExternRef::null()))?; - } - for i in 0..table2.size() { - table2.set(i, Val::ExternRef(ExternRef::null()))?; - } - } - - assert_eq!(er1.strong_count(), 1); - assert_eq!(er2.strong_count(), 1); - assert_eq!(er3.strong_count(), 1); - - Ok(()) -} diff --git a/lib/api/tests/sys/export.rs b/lib/api/tests/sys/export.rs new file mode 100644 index 00000000000..9975a8580ee --- /dev/null +++ b/lib/api/tests/sys/export.rs @@ -0,0 +1,339 @@ +#[cfg(feature = "sys")] +mod sys { + use anyhow::Result; + use wasmer::*; + use wasmer_vm::WeakOrStrongInstanceRef; + + const MEM_WAT: &str = " + (module + (func $host_fn (import \"env\" \"host_fn\") (param) (result)) + (func (export \"call_host_fn\") (param) (result) + (call $host_fn)) + + (memory $mem 0) + (export \"memory\" (memory $mem)) + ) +"; + + const GLOBAL_WAT: &str = " + (module + (func $host_fn (import \"env\" \"host_fn\") (param) (result)) + (func (export \"call_host_fn\") (param) (result) + (call $host_fn)) + + (global $global i32 (i32.const 11)) + (export \"global\" (global $global)) + ) +"; + + const TABLE_WAT: &str = " + (module + (func $host_fn (import \"env\" \"host_fn\") (param) (result)) + (func (export \"call_host_fn\") (param) (result) + (call $host_fn)) + + (table $table 4 4 funcref) + (export \"table\" (table $table)) + ) +"; + + const FUNCTION_WAT: &str = " + (module + (func $host_fn (import \"env\" \"host_fn\") (param) (result)) + (func (export \"call_host_fn\") (param) (result) + (call $host_fn)) + ) +"; + + fn is_memory_instance_ref_strong(memory: &Memory) -> Option { + // This is safe because we're calling it from a test to test the internals + unsafe { + memory + .get_vm_memory() + .instance_ref + .as_ref() + .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) + } + } + + fn is_table_instance_ref_strong(table: &Table) -> Option { + // This is safe because we're calling it from a test to test the internals + unsafe { + table + .get_vm_table() + .instance_ref + .as_ref() + .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) + } + } + + fn is_global_instance_ref_strong(global: &Global) -> Option { + // This is safe because we're calling it from a test to test the internals + unsafe { + global + .get_vm_global() + .instance_ref + .as_ref() + .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) + } + } + + fn is_function_instance_ref_strong(f: &Function) -> Option { + // This is safe because we're calling it from a test to test the internals + unsafe { + f.get_vm_function() + .instance_ref + .as_ref() + .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) + } + } + + fn is_native_function_instance_ref_strong( + f: &NativeFunc, + ) -> Option + where + Args: WasmTypeList, + Rets: WasmTypeList, + { + // This is safe because we're calling it from a test to test the internals + unsafe { + f.get_vm_function() + .instance_ref + .as_ref() + .map(|v| matches!(v, WeakOrStrongInstanceRef::Strong(_))) + } + } + + #[test] + fn strong_weak_behavior_works_memory() -> Result<()> { + #[derive(Clone, Debug, WasmerEnv, Default)] + struct MemEnv { + #[wasmer(export)] + memory: LazyInit, + } + + let host_fn = |env: &MemEnv| { + let mem = env.memory_ref().unwrap(); + assert_eq!(is_memory_instance_ref_strong(&mem), Some(false)); + let mem_clone = mem.clone(); + assert_eq!(is_memory_instance_ref_strong(&mem_clone), Some(true)); + assert_eq!(is_memory_instance_ref_strong(&mem), Some(false)); + }; + + let f: NativeFunc<(), ()> = { + let store = Store::default(); + let module = Module::new(&store, MEM_WAT)?; + let env = MemEnv::default(); + + let instance = Instance::new( + &module, + &imports! { + "env" => { + "host_fn" => Function::new_native_with_env(&store, env, host_fn) + } + }, + )?; + + { + let mem = instance.exports.get_memory("memory")?; + assert_eq!(is_memory_instance_ref_strong(&mem), Some(true)); + } + + let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; + f.call()?; + f + }; + f.call()?; + + Ok(()) + } + + #[test] + fn strong_weak_behavior_works_global() -> Result<()> { + #[derive(Clone, Debug, WasmerEnv, Default)] + struct GlobalEnv { + #[wasmer(export)] + global: LazyInit, + } + + let host_fn = |env: &GlobalEnv| { + let global = env.global_ref().unwrap(); + assert_eq!(is_global_instance_ref_strong(&global), Some(false)); + let global_clone = global.clone(); + assert_eq!(is_global_instance_ref_strong(&global_clone), Some(true)); + assert_eq!(is_global_instance_ref_strong(&global), Some(false)); + }; + + let f: NativeFunc<(), ()> = { + let store = Store::default(); + let module = Module::new(&store, GLOBAL_WAT)?; + let env = GlobalEnv::default(); + + let instance = Instance::new( + &module, + &imports! { + "env" => { + "host_fn" => Function::new_native_with_env(&store, env, host_fn) + } + }, + )?; + + { + let global = instance.exports.get_global("global")?; + assert_eq!(is_global_instance_ref_strong(&global), Some(true)); + } + + let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; + f.call()?; + f + }; + f.call()?; + + Ok(()) + } + + #[test] + fn strong_weak_behavior_works_table() -> Result<()> { + #[derive(Clone, WasmerEnv, Default)] + struct TableEnv { + #[wasmer(export)] + table: LazyInit
, + } + + let host_fn = |env: &TableEnv| { + let table = env.table_ref().unwrap(); + assert_eq!(is_table_instance_ref_strong(&table), Some(false)); + let table_clone = table.clone(); + assert_eq!(is_table_instance_ref_strong(&table_clone), Some(true)); + assert_eq!(is_table_instance_ref_strong(&table), Some(false)); + }; + + let f: NativeFunc<(), ()> = { + let store = Store::default(); + let module = Module::new(&store, TABLE_WAT)?; + let env = TableEnv::default(); + + let instance = Instance::new( + &module, + &imports! { + "env" => { + "host_fn" => Function::new_native_with_env(&store, env, host_fn) + } + }, + )?; + + { + let table = instance.exports.get_table("table")?; + assert_eq!(is_table_instance_ref_strong(&table), Some(true)); + } + + let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; + f.call()?; + f + }; + f.call()?; + + Ok(()) + } + + #[test] + fn strong_weak_behavior_works_function() -> Result<()> { + #[derive(Clone, WasmerEnv, Default)] + struct FunctionEnv { + #[wasmer(export)] + call_host_fn: LazyInit, + } + + let host_fn = |env: &FunctionEnv| { + let function = env.call_host_fn_ref().unwrap(); + assert_eq!(is_function_instance_ref_strong(&function), Some(false)); + let function_clone = function.clone(); + assert_eq!(is_function_instance_ref_strong(&function_clone), Some(true)); + assert_eq!(is_function_instance_ref_strong(&function), Some(false)); + }; + + let f: NativeFunc<(), ()> = { + let store = Store::default(); + let module = Module::new(&store, FUNCTION_WAT)?; + let env = FunctionEnv::default(); + + let instance = Instance::new( + &module, + &imports! { + "env" => { + "host_fn" => Function::new_native_with_env(&store, env, host_fn) + } + }, + )?; + + { + let function = instance.exports.get_function("call_host_fn")?; + assert_eq!(is_function_instance_ref_strong(&function), Some(true)); + } + + let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; + f.call()?; + f + }; + f.call()?; + + Ok(()) + } + + #[test] + fn strong_weak_behavior_works_native_function() -> Result<()> { + #[derive(Clone, WasmerEnv, Default)] + struct FunctionEnv { + #[wasmer(export)] + call_host_fn: LazyInit>, + } + + let host_fn = |env: &FunctionEnv| { + let function = env.call_host_fn_ref().unwrap(); + assert_eq!( + is_native_function_instance_ref_strong(&function), + Some(false) + ); + let function_clone = function.clone(); + assert_eq!( + is_native_function_instance_ref_strong(&function_clone), + Some(true) + ); + assert_eq!( + is_native_function_instance_ref_strong(&function), + Some(false) + ); + }; + + let f: NativeFunc<(), ()> = { + let store = Store::default(); + let module = Module::new(&store, FUNCTION_WAT)?; + let env = FunctionEnv::default(); + + let instance = Instance::new( + &module, + &imports! { + "env" => { + "host_fn" => Function::new_native_with_env(&store, env, host_fn) + } + }, + )?; + + { + let function: NativeFunc<(), ()> = + instance.exports.get_native_function("call_host_fn")?; + assert_eq!( + is_native_function_instance_ref_strong(&function), + Some(true) + ); + } + + let f: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_fn")?; + f.call()?; + f + }; + f.call()?; + + Ok(()) + } +} diff --git a/lib/api/tests/sys/externals.rs b/lib/api/tests/sys/externals.rs new file mode 100644 index 00000000000..56002390403 --- /dev/null +++ b/lib/api/tests/sys/externals.rs @@ -0,0 +1,467 @@ +#[cfg(feature = "sys")] +mod sys { + use anyhow::Result; + use wasmer::*; + + #[test] + fn global_new() -> Result<()> { + let store = Store::default(); + let global = Global::new(&store, Value::I32(10)); + assert_eq!( + *global.ty(), + GlobalType { + ty: Type::I32, + mutability: Mutability::Const + } + ); + + let global_mut = Global::new_mut(&store, Value::I32(10)); + assert_eq!( + *global_mut.ty(), + GlobalType { + ty: Type::I32, + mutability: Mutability::Var + } + ); + + Ok(()) + } + + #[test] + fn global_get() -> Result<()> { + let store = Store::default(); + let global_i32 = Global::new(&store, Value::I32(10)); + assert_eq!(global_i32.get(), Value::I32(10)); + let global_i64 = Global::new(&store, Value::I64(20)); + assert_eq!(global_i64.get(), Value::I64(20)); + let global_f32 = Global::new(&store, Value::F32(10.0)); + assert_eq!(global_f32.get(), Value::F32(10.0)); + let global_f64 = Global::new(&store, Value::F64(20.0)); + assert_eq!(global_f64.get(), Value::F64(20.0)); + + Ok(()) + } + + #[test] + fn global_set() -> Result<()> { + let store = Store::default(); + let global_i32 = Global::new(&store, Value::I32(10)); + // Set on a constant should error + assert!(global_i32.set(Value::I32(20)).is_err()); + + let global_i32_mut = Global::new_mut(&store, Value::I32(10)); + // Set on different type should error + assert!(global_i32_mut.set(Value::I64(20)).is_err()); + + // Set on same type should succeed + global_i32_mut.set(Value::I32(20))?; + assert_eq!(global_i32_mut.get(), Value::I32(20)); + + Ok(()) + } + + #[test] + fn table_new() -> Result<()> { + let store = Store::default(); + let table_type = TableType { + ty: Type::FuncRef, + minimum: 0, + maximum: None, + }; + let f = Function::new_native(&store, || {}); + let table = Table::new(&store, table_type, Value::FuncRef(Some(f)))?; + assert_eq!(*table.ty(), table_type); + + // Anyrefs not yet supported + // let table_type = TableType { + // ty: Type::ExternRef, + // minimum: 0, + // maximum: None, + // }; + // let table = Table::new(&store, table_type, Value::ExternRef(ExternRef::Null))?; + // assert_eq!(*table.ty(), table_type); + + Ok(()) + } + + #[test] + #[ignore] + fn table_get() -> Result<()> { + let store = Store::default(); + let table_type = TableType { + ty: Type::FuncRef, + minimum: 0, + maximum: Some(1), + }; + let f = Function::new_native(&store, |num: i32| num + 1); + let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; + assert_eq!(*table.ty(), table_type); + let _elem = table.get(0).unwrap(); + // assert_eq!(elem.funcref().unwrap(), f); + Ok(()) + } + + #[test] + #[ignore] + fn table_set() -> Result<()> { + // Table set not yet tested + Ok(()) + } + + #[test] + fn table_grow() -> Result<()> { + let store = Store::default(); + let table_type = TableType { + ty: Type::FuncRef, + minimum: 0, + maximum: Some(10), + }; + let f = Function::new_native(&store, |num: i32| num + 1); + let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; + // Growing to a bigger maximum should return None + let old_len = table.grow(12, Value::FuncRef(Some(f.clone()))); + assert!(old_len.is_err()); + + // Growing to a bigger maximum should return None + let old_len = table.grow(5, Value::FuncRef(Some(f.clone())))?; + assert_eq!(old_len, 0); + + Ok(()) + } + + #[test] + #[ignore] + fn table_copy() -> Result<()> { + // TODO: table copy test not yet implemented + Ok(()) + } + + #[test] + fn memory_new() -> Result<()> { + let store = Store::default(); + let memory_type = MemoryType { + shared: false, + minimum: Pages(0), + maximum: Some(Pages(10)), + }; + let memory = Memory::new(&store, memory_type)?; + assert_eq!(memory.size(), Pages(0)); + assert_eq!(memory.ty(), memory_type); + Ok(()) + } + + #[test] + fn memory_grow() -> Result<()> { + let store = Store::default(); + + let desc = MemoryType::new(Pages(10), Some(Pages(16)), false); + let memory = Memory::new(&store, desc)?; + assert_eq!(memory.size(), Pages(10)); + + let result = memory.grow(Pages(2)).unwrap(); + assert_eq!(result, Pages(10)); + assert_eq!(memory.size(), Pages(12)); + + let result = memory.grow(Pages(10)); + assert_eq!( + result, + Err(MemoryError::CouldNotGrow { + current: 12.into(), + attempted_delta: 10.into() + }) + ); + + let bad_desc = MemoryType::new(Pages(15), Some(Pages(10)), false); + let bad_result = Memory::new(&store, bad_desc); + + assert!(matches!(bad_result, Err(MemoryError::InvalidMemory { .. }))); + + Ok(()) + } + + #[test] + fn function_new() -> Result<()> { + let store = Store::default(); + let function = Function::new_native(&store, || {}); + assert_eq!(function.ty().clone(), FunctionType::new(vec![], vec![])); + let function = Function::new_native(&store, |_a: i32| {}); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32], vec![]) + ); + let function = Function::new_native(&store, |_a: i32, _b: i64, _c: f32, _d: f64| {}); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) + ); + let function = Function::new_native(&store, || -> i32 { 1 }); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32]) + ); + let function = + Function::new_native(&store, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) + ); + Ok(()) + } + + #[test] + fn function_new_env() -> Result<()> { + let store = Store::default(); + #[derive(Clone, WasmerEnv)] + struct MyEnv {} + + let my_env = MyEnv {}; + let function = Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv| {}); + assert_eq!(function.ty().clone(), FunctionType::new(vec![], vec![])); + let function = + Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv, _a: i32| {}); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32], vec![]) + ); + let function = Function::new_native_with_env( + &store, + my_env.clone(), + |_env: &MyEnv, _a: i32, _b: i64, _c: f32, _d: f64| {}, + ); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) + ); + let function = + Function::new_native_with_env(&store, my_env.clone(), |_env: &MyEnv| -> i32 { 1 }); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32]) + ); + let function = Function::new_native_with_env( + &store, + my_env.clone(), + |_env: &MyEnv| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, + ); + assert_eq!( + function.ty().clone(), + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) + ); + Ok(()) + } + + #[test] + fn function_new_dynamic() -> Result<()> { + let store = Store::default(); + + // Using &FunctionType signature + let function_type = FunctionType::new(vec![], vec![]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![Type::I32], vec![]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![], vec![Type::I32]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); + let function = Function::new(&store, &function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().clone(), function_type); + + // Using array signature + let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); + let function = Function::new(&store, function_type, |_values: &[Value]| unimplemented!()); + assert_eq!(function.ty().params(), [Type::V128]); + assert_eq!(function.ty().results(), [Type::I32, Type::F32, Type::F64]); + + Ok(()) + } + + #[test] + fn function_new_dynamic_env() -> Result<()> { + let store = Store::default(); + #[derive(Clone, WasmerEnv)] + struct MyEnv {} + let my_env = MyEnv {}; + + // Using &FunctionType signature + let function_type = FunctionType::new(vec![], vec![]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![Type::I32], vec![]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = FunctionType::new(vec![], vec![Type::I32]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + let function_type = + FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); + let function = Function::new_with_env( + &store, + &function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().clone(), function_type); + + // Using array signature + let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); + let function = Function::new_with_env( + &store, + function_type, + my_env.clone(), + |_env: &MyEnv, _values: &[Value]| unimplemented!(), + ); + assert_eq!(function.ty().params(), [Type::V128]); + assert_eq!(function.ty().results(), [Type::I32, Type::F32, Type::F64]); + + Ok(()) + } + + #[test] + fn native_function_works() -> Result<()> { + let store = Store::default(); + let function = Function::new_native(&store, || {}); + let native_function: NativeFunc<(), ()> = function.native().unwrap(); + let result = native_function.call(); + assert!(result.is_ok()); + + let function = Function::new_native(&store, |a: i32| -> i32 { a + 1 }); + let native_function: NativeFunc = function.native().unwrap(); + assert_eq!(native_function.call(3).unwrap(), 4); + + fn rust_abi(a: i32, b: i64, c: f32, d: f64) -> u64 { + (a as u64 * 1000) + (b as u64 * 100) + (c as u64 * 10) + (d as u64) + } + let function = Function::new_native(&store, rust_abi); + let native_function: NativeFunc<(i32, i64, f32, f64), u64> = function.native().unwrap(); + assert_eq!(native_function.call(8, 4, 1.5, 5.).unwrap(), 8415); + + let function = Function::new_native(&store, || -> i32 { 1 }); + let native_function: NativeFunc<(), i32> = function.native().unwrap(); + assert_eq!(native_function.call().unwrap(), 1); + + let function = Function::new_native(&store, |_a: i32| {}); + let native_function: NativeFunc = function.native().unwrap(); + assert!(native_function.call(4).is_ok()); + + let function = + Function::new_native(&store, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); + let native_function: NativeFunc<(), (i32, i64, f32, f64)> = function.native().unwrap(); + assert_eq!(native_function.call().unwrap(), (1, 2, 3.0, 4.0)); + + Ok(()) + } + + #[test] + fn function_outlives_instance() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (type $sum_t (func (param i32 i32) (result i32))) + (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) + local.get $x + local.get $y + i32.add) + (export "sum" (func $sum_f))) +"#; + + let f = { + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + let f: NativeFunc<(i32, i32), i32> = instance.exports.get_native_function("sum")?; + + assert_eq!(f.call(4, 5)?, 9); + f + }; + + assert_eq!(f.call(4, 5)?, 9); + + Ok(()) + } + + #[test] + fn weak_instance_ref_externs_after_instance() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (memory (export "mem") 1) + (type $sum_t (func (param i32 i32) (result i32))) + (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) + local.get $x + local.get $y + i32.add) + (export "sum" (func $sum_f))) +"#; + + let f = { + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + let f: NativeFunc<(i32, i32), i32> = instance.exports.get_with_generics_weak("sum")?; + + assert_eq!(f.call(4, 5)?, 9); + f + }; + + assert_eq!(f.call(4, 5)?, 9); + + Ok(()) + } + + #[test] + fn manually_generate_wasmer_env() -> Result<()> { + let store = Store::default(); + #[derive(WasmerEnv, Clone)] + struct MyEnv { + val: u32, + memory: LazyInit, + } + + fn host_function(env: &mut MyEnv, arg1: u32, arg2: u32) -> u32 { + env.val + arg1 + arg2 + } + + let mut env = MyEnv { + val: 5, + memory: LazyInit::new(), + }; + + let result = host_function(&mut env, 7, 9); + assert_eq!(result, 21); + + let memory = Memory::new(&store, MemoryType::new(0, None, false))?; + env.memory.initialize(memory); + + let result = host_function(&mut env, 1, 2); + assert_eq!(result, 8); + + Ok(()) + } +} diff --git a/lib/api/tests/sys/instance.rs b/lib/api/tests/sys/instance.rs new file mode 100644 index 00000000000..4afbba187e2 --- /dev/null +++ b/lib/api/tests/sys/instance.rs @@ -0,0 +1,42 @@ +#[cfg(feature = "sys")] +mod sys { + use anyhow::Result; + use wasmer::*; + + #[test] + fn exports_work_after_multiple_instances_have_been_freed() -> Result<()> { + let store = Store::default(); + let module = Module::new( + &store, + " + (module + (type $sum_t (func (param i32 i32) (result i32))) + (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) + local.get $x + local.get $y + i32.add) + (export \"sum\" (func $sum_f))) +", + )?; + + let import_object = ImportObject::new(); + let instance = Instance::new(&module, &import_object)?; + let instance2 = instance.clone(); + let instance3 = instance.clone(); + + // The function is cloned to “break” the connection with `instance`. + let sum = instance.exports.get_function("sum")?.clone(); + + drop(instance); + drop(instance2); + drop(instance3); + + // All instances have been dropped, but `sum` continues to work! + assert_eq!( + sum.call(&[Value::I32(1), Value::I32(2)])?.into_vec(), + vec![Value::I32(3)], + ); + + Ok(()) + } +} diff --git a/lib/api/tests/sys/module.rs b/lib/api/tests/sys/module.rs new file mode 100644 index 00000000000..2214b289ece --- /dev/null +++ b/lib/api/tests/sys/module.rs @@ -0,0 +1,251 @@ +#[cfg(feature = "sys")] +mod sys { + use anyhow::Result; + use wasmer::*; + + #[test] + fn module_get_name() -> Result<()> { + let store = Store::default(); + let wat = r#"(module)"#; + let module = Module::new(&store, wat)?; + assert_eq!(module.name(), None); + + Ok(()) + } + + #[test] + fn module_set_name() -> Result<()> { + let store = Store::default(); + let wat = r#"(module $name)"#; + let mut module = Module::new(&store, wat)?; + assert_eq!(module.name(), Some("name")); + + module.set_name("new_name"); + assert_eq!(module.name(), Some("new_name")); + + Ok(()) + } + + #[test] + fn imports() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (import "host" "func" (func)) + (import "host" "memory" (memory 1)) + (import "host" "table" (table 1 anyfunc)) + (import "host" "global" (global i32)) +)"#; + let module = Module::new(&store, wat)?; + assert_eq!( + module.imports().collect::>(), + vec![ + ImportType::new( + "host", + "func", + ExternType::Function(FunctionType::new(vec![], vec![])) + ), + ImportType::new( + "host", + "memory", + ExternType::Memory(MemoryType::new(Pages(1), None, false)) + ), + ImportType::new( + "host", + "table", + ExternType::Table(TableType::new(Type::FuncRef, 1, None)) + ), + ImportType::new( + "host", + "global", + ExternType::Global(GlobalType::new(Type::I32, Mutability::Const)) + ) + ] + ); + + // Now we test the iterators + assert_eq!( + module.imports().functions().collect::>(), + vec![ImportType::new( + "host", + "func", + FunctionType::new(vec![], vec![]) + ),] + ); + assert_eq!( + module.imports().memories().collect::>(), + vec![ImportType::new( + "host", + "memory", + MemoryType::new(Pages(1), None, false) + ),] + ); + assert_eq!( + module.imports().tables().collect::>(), + vec![ImportType::new( + "host", + "table", + TableType::new(Type::FuncRef, 1, None) + ),] + ); + assert_eq!( + module.imports().globals().collect::>(), + vec![ImportType::new( + "host", + "global", + GlobalType::new(Type::I32, Mutability::Const) + ),] + ); + Ok(()) + } + + #[test] + fn exports() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (func (export "func") nop) + (memory (export "memory") 1) + (table (export "table") 1 funcref) + (global (export "global") i32 (i32.const 0)) +)"#; + let module = Module::new(&store, wat)?; + assert_eq!( + module.exports().collect::>(), + vec![ + ExportType::new( + "func", + ExternType::Function(FunctionType::new(vec![], vec![])) + ), + ExportType::new( + "memory", + ExternType::Memory(MemoryType::new(Pages(1), None, false)) + ), + ExportType::new( + "table", + ExternType::Table(TableType::new(Type::FuncRef, 1, None)) + ), + ExportType::new( + "global", + ExternType::Global(GlobalType::new(Type::I32, Mutability::Const)) + ) + ] + ); + + // Now we test the iterators + assert_eq!( + module.exports().functions().collect::>(), + vec![ExportType::new("func", FunctionType::new(vec![], vec![])),] + ); + assert_eq!( + module.exports().memories().collect::>(), + vec![ExportType::new( + "memory", + MemoryType::new(Pages(1), None, false) + ),] + ); + assert_eq!( + module.exports().tables().collect::>(), + vec![ExportType::new( + "table", + TableType::new(Type::FuncRef, 1, None) + ),] + ); + assert_eq!( + module.exports().globals().collect::>(), + vec![ExportType::new( + "global", + GlobalType::new(Type::I32, Mutability::Const) + ),] + ); + Ok(()) + } + + #[test] + fn calling_host_functions_with_negative_values_works() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (import "host" "host_func1" (func (param i64))) + (import "host" "host_func2" (func (param i32))) + (import "host" "host_func3" (func (param i64))) + (import "host" "host_func4" (func (param i32))) + (import "host" "host_func5" (func (param i32))) + (import "host" "host_func6" (func (param i32))) + (import "host" "host_func7" (func (param i32))) + (import "host" "host_func8" (func (param i32))) + + (func (export "call_host_func1") + (call 0 (i64.const -1))) + (func (export "call_host_func2") + (call 1 (i32.const -1))) + (func (export "call_host_func3") + (call 2 (i64.const -1))) + (func (export "call_host_func4") + (call 3 (i32.const -1))) + (func (export "call_host_func5") + (call 4 (i32.const -1))) + (func (export "call_host_func6") + (call 5 (i32.const -1))) + (func (export "call_host_func7") + (call 6 (i32.const -1))) + (func (export "call_host_func8") + (call 7 (i32.const -1))) +)"#; + let module = Module::new(&store, wat)?; + let imports = imports! { + "host" => { + "host_func1" => Function::new_native(&store, |p: u64| { + println!("host_func1: Found number {}", p); + assert_eq!(p, u64::max_value()); + }), + "host_func2" => Function::new_native(&store, |p: u32| { + println!("host_func2: Found number {}", p); + assert_eq!(p, u32::max_value()); + }), + "host_func3" => Function::new_native(&store, |p: i64| { + println!("host_func3: Found number {}", p); + assert_eq!(p, -1); + }), + "host_func4" => Function::new_native(&store, |p: i32| { + println!("host_func4: Found number {}", p); + assert_eq!(p, -1); + }), + "host_func5" => Function::new_native(&store, |p: i16| { + println!("host_func5: Found number {}", p); + assert_eq!(p, -1); + }), + "host_func6" => Function::new_native(&store, |p: u16| { + println!("host_func6: Found number {}", p); + assert_eq!(p, u16::max_value()); + }), + "host_func7" => Function::new_native(&store, |p: i8| { + println!("host_func7: Found number {}", p); + assert_eq!(p, -1); + }), + "host_func8" => Function::new_native(&store, |p: u8| { + println!("host_func8: Found number {}", p); + assert_eq!(p, u8::max_value()); + }), + } + }; + let instance = Instance::new(&module, &imports)?; + + let f1: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func1")?; + let f2: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func2")?; + let f3: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func3")?; + let f4: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func4")?; + let f5: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func5")?; + let f6: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func6")?; + let f7: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func7")?; + let f8: NativeFunc<(), ()> = instance.exports.get_native_function("call_host_func8")?; + + f1.call()?; + f2.call()?; + f3.call()?; + f4.call()?; + f5.call()?; + f6.call()?; + f7.call()?; + f8.call()?; + + Ok(()) + } +} diff --git a/lib/api/tests/sys/reference_types.rs b/lib/api/tests/sys/reference_types.rs new file mode 100644 index 00000000000..989f60fcbea --- /dev/null +++ b/lib/api/tests/sys/reference_types.rs @@ -0,0 +1,500 @@ +#[cfg(feature = "sys")] +mod sys { + use anyhow::Result; + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + use wasmer::*; + + #[test] + fn func_ref_passed_and_returned() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (import "env" "func_ref_identity" (func (param funcref) (result funcref))) + (type $ret_i32_ty (func (result i32))) + (table $table (export "table") 2 2 funcref) + + (func (export "run") (param) (result funcref) + (call 0 (ref.null func))) + (func (export "call_set_value") (param $fr funcref) (result i32) + (table.set $table (i32.const 0) (local.get $fr)) + (call_indirect $table (type $ret_i32_ty) (i32.const 0))) +)"#; + let module = Module::new(&store, wat)?; + let imports = imports! { + "env" => { + "func_ref_identity" => Function::new(&store, FunctionType::new([Type::FuncRef], [Type::FuncRef]), |values| -> Result, _> { + Ok(vec![values[0].clone()]) + }) + }, + }; + + let instance = Instance::new(&module, &imports)?; + + let f: &Function = instance.exports.get_function("run")?; + let results = f.call(&[]).unwrap(); + if let Value::FuncRef(fr) = &results[0] { + assert!(fr.is_none()); + } else { + panic!("funcref not found!"); + } + + #[derive(Clone, Debug, WasmerEnv)] + pub struct Env(Arc); + let env = Env(Arc::new(AtomicBool::new(false))); + + let func_to_call = Function::new_native_with_env(&store, env.clone(), |env: &Env| -> i32 { + env.0.store(true, Ordering::SeqCst); + 343 + }); + let call_set_value: &Function = instance.exports.get_function("call_set_value")?; + let results: Box<[Value]> = call_set_value.call(&[Value::FuncRef(Some(func_to_call))])?; + assert!(env.0.load(Ordering::SeqCst)); + assert_eq!(&*results, &[Value::I32(343)]); + + Ok(()) + } + + #[test] + fn func_ref_passed_and_called() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (func $func_ref_call (import "env" "func_ref_call") (param funcref) (result i32)) + (type $ret_i32_ty (func (result i32))) + (table $table (export "table") 2 2 funcref) + + (func $product (param $x i32) (param $y i32) (result i32) + (i32.mul (local.get $x) (local.get $y))) + ;; TODO: figure out exactly why this statement is needed + (elem declare func $product) + (func (export "call_set_value") (param $fr funcref) (result i32) + (table.set $table (i32.const 0) (local.get $fr)) + (call_indirect $table (type $ret_i32_ty) (i32.const 0))) + (func (export "call_func") (param $fr funcref) (result i32) + (call $func_ref_call (local.get $fr))) + (func (export "call_host_func_with_wasm_func") (result i32) + (call $func_ref_call (ref.func $product))) +)"#; + let module = Module::new(&store, wat)?; + + fn func_ref_call(values: &[Value]) -> Result, RuntimeError> { + // TODO: look into `Box<[Value]>` being returned breakage + let f = values[0].unwrap_funcref().as_ref().unwrap(); + let f: NativeFunc<(i32, i32), i32> = f.native()?; + Ok(vec![Value::I32(f.call(7, 9)?)]) + } + + let imports = imports! { + "env" => { + "func_ref_call" => Function::new( + &store, + FunctionType::new([Type::FuncRef], [Type::I32]), + func_ref_call + ), + // TODO(reftypes): this should work + /* + "func_ref_call_native" => Function::new_native(&store, |f: Function| -> Result { + let f: NativeFunc::<(i32, i32), i32> = f.native()?; + f.call(7, 9) + }) + */ + }, + }; + + let instance = Instance::new(&module, &imports)?; + { + fn sum(a: i32, b: i32) -> i32 { + a + b + } + let sum_func = Function::new_native(&store, sum); + + let call_func: &Function = instance.exports.get_function("call_func")?; + let result = call_func.call(&[Value::FuncRef(Some(sum_func))])?; + assert_eq!(result[0].unwrap_i32(), 16); + } + + { + let f: NativeFunc<(), i32> = instance + .exports + .get_native_function("call_host_func_with_wasm_func")?; + let result = f.call()?; + assert_eq!(result, 63); + } + + Ok(()) + } + + #[cfg(feature = "experimental-reference-types-extern-ref")] + #[test] + fn extern_ref_passed_and_returned() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (func $extern_ref_identity (import "env" "extern_ref_identity") (param externref) (result externref)) + (func $extern_ref_identity_native (import "env" "extern_ref_identity_native") (param externref) (result externref)) + (func $get_new_extern_ref (import "env" "get_new_extern_ref") (result externref)) + (func $get_new_extern_ref_native (import "env" "get_new_extern_ref_native") (result externref)) + + (func (export "run") (param) (result externref) + (call $extern_ref_identity (ref.null extern))) + (func (export "run_native") (param) (result externref) + (call $extern_ref_identity_native (ref.null extern))) + (func (export "get_hashmap") (param) (result externref) + (call $get_new_extern_ref)) + (func (export "get_hashmap_native") (param) (result externref) + (call $get_new_extern_ref_native)) +)"#; + let module = Module::new(&store, wat)?; + let imports = imports! { + "env" => { + "extern_ref_identity" => Function::new(&store, FunctionType::new([Type::ExternRef], [Type::ExternRef]), |values| -> Result, _> { + Ok(vec![values[0].clone()]) + }), + "extern_ref_identity_native" => Function::new_native(&store, |er: ExternRef| -> ExternRef { + er + }), + "get_new_extern_ref" => Function::new(&store, FunctionType::new([], [Type::ExternRef]), |_| -> Result, _> { + let inner = + [("hello".to_string(), "world".to_string()), + ("color".to_string(), "orange".to_string())] + .iter() + .cloned() + .collect::>(); + let new_extern_ref = ExternRef::new(inner); + Ok(vec![Value::ExternRef(new_extern_ref)]) + }), + "get_new_extern_ref_native" => Function::new_native(&store, || -> ExternRef { + let inner = + [("hello".to_string(), "world".to_string()), + ("color".to_string(), "orange".to_string())] + .iter() + .cloned() + .collect::>(); + ExternRef::new(inner) + }) + }, + }; + + let instance = Instance::new(&module, &imports)?; + for run in &["run", "run_native"] { + let f: &Function = instance.exports.get_function(run)?; + let results = f.call(&[]).unwrap(); + if let Value::ExternRef(er) = &results[0] { + assert!(er.is_null()); + } else { + panic!("result is not an extern ref!"); + } + + let f: NativeFunc<(), ExternRef> = instance.exports.get_native_function(run)?; + let result: ExternRef = f.call()?; + assert!(result.is_null()); + } + + for get_hashmap in &["get_hashmap", "get_hashmap_native"] { + let f: &Function = instance.exports.get_function(get_hashmap)?; + let results = f.call(&[]).unwrap(); + if let Value::ExternRef(er) = &results[0] { + let inner: &HashMap = er.downcast().unwrap(); + assert_eq!(inner["hello"], "world"); + assert_eq!(inner["color"], "orange"); + } else { + panic!("result is not an extern ref!"); + } + + let f: NativeFunc<(), ExternRef> = instance.exports.get_native_function(get_hashmap)?; + + let result: ExternRef = f.call()?; + let inner: &HashMap = result.downcast().unwrap(); + assert_eq!(inner["hello"], "world"); + assert_eq!(inner["color"], "orange"); + } + + Ok(()) + } + + #[cfg(feature = "experimental-reference-types-extern-ref")] + #[test] + // TODO(reftypes): reenable this test + #[ignore] + fn extern_ref_ref_counting_basic() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (func (export "drop") (param $er externref) (result) + (drop (local.get $er))) +)"#; + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + let f: NativeFunc = instance.exports.get_native_function("drop")?; + + let er = ExternRef::new(3u32); + f.call(er.clone())?; + + assert_eq!(er.downcast::().unwrap(), &3); + assert_eq!(er.strong_count(), 1); + + Ok(()) + } + + #[cfg(feature = "experimental-reference-types-extern-ref")] + #[test] + fn refs_in_globals() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (global $er_global (export "er_global") (mut externref) (ref.null extern)) + (global $fr_global (export "fr_global") (mut funcref) (ref.null func)) + (global $fr_immutable_global (export "fr_immutable_global") funcref (ref.func $hello)) + (func $hello (param) (result i32) + (i32.const 73)) +)"#; + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + { + let er_global: &Global = instance.exports.get_global("er_global")?; + + if let Value::ExternRef(er) = er_global.get() { + assert!(er.is_null()); + } else { + panic!("Did not find extern ref in the global"); + } + + er_global.set(Val::ExternRef(ExternRef::new(3u32)))?; + + if let Value::ExternRef(er) = er_global.get() { + assert_eq!(er.downcast::().unwrap(), &3); + assert_eq!(er.strong_count(), 1); + } else { + panic!("Did not find extern ref in the global"); + } + } + + { + let fr_global: &Global = instance.exports.get_global("fr_immutable_global")?; + + if let Value::FuncRef(Some(f)) = fr_global.get() { + let native_func: NativeFunc<(), u32> = f.native()?; + assert_eq!(native_func.call()?, 73); + } else { + panic!("Did not find non-null func ref in the global"); + } + } + + { + let fr_global: &Global = instance.exports.get_global("fr_global")?; + + if let Value::FuncRef(None) = fr_global.get() { + } else { + panic!("Did not find a null func ref in the global"); + } + + let f = Function::new_native(&store, |arg1: i32, arg2: i32| -> i32 { arg1 + arg2 }); + + fr_global.set(Val::FuncRef(Some(f)))?; + + if let Value::FuncRef(Some(f)) = fr_global.get() { + let native: NativeFunc<(i32, i32), i32> = f.native()?; + assert_eq!(native.call(5, 7)?, 12); + } else { + panic!("Did not find extern ref in the global"); + } + } + + Ok(()) + } + + #[cfg(feature = "experimental-reference-types-extern-ref")] + #[test] + fn extern_ref_ref_counting_table_basic() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (global $global (export "global") (mut externref) (ref.null extern)) + (table $table (export "table") 4 4 externref) + (func $insert (param $er externref) (param $idx i32) + (table.set $table (local.get $idx) (local.get $er))) + (func $intermediate (param $er externref) (param $idx i32) + (call $insert (local.get $er) (local.get $idx))) + (func $insert_into_table (export "insert_into_table") (param $er externref) (param $idx i32) (result externref) + (call $intermediate (local.get $er) (local.get $idx)) + (local.get $er)) +)"#; + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + + let f: NativeFunc<(ExternRef, i32), ExternRef> = + instance.exports.get_native_function("insert_into_table")?; + + let er = ExternRef::new(3usize); + + let er = f.call(er, 1)?; + assert_eq!(er.strong_count(), 2); + + let table: &Table = instance.exports.get_table("table")?; + + { + let er2 = table.get(1).unwrap().externref().unwrap(); + assert_eq!(er2.strong_count(), 3); + } + + assert_eq!(er.strong_count(), 2); + table.set(1, Val::ExternRef(ExternRef::null()))?; + + assert_eq!(er.strong_count(), 1); + + Ok(()) + } + + #[cfg(feature = "experimental-reference-types-extern-ref")] + #[test] + // TODO(reftypes): reenable this test + #[ignore] + fn extern_ref_ref_counting_global_basic() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (global $global (export "global") (mut externref) (ref.null extern)) + (func $get_from_global (export "get_from_global") (result externref) + (drop (global.get $global)) + (global.get $global)) +)"#; + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + + let global: &Global = instance.exports.get_global("global")?; + { + let er = ExternRef::new(3usize); + global.set(Val::ExternRef(er.clone()))?; + assert_eq!(er.strong_count(), 2); + } + let get_from_global: NativeFunc<(), ExternRef> = + instance.exports.get_native_function("get_from_global")?; + + let er = get_from_global.call()?; + assert_eq!(er.strong_count(), 2); + global.set(Val::ExternRef(ExternRef::null()))?; + assert_eq!(er.strong_count(), 1); + + Ok(()) + } + + #[cfg(feature = "experimental-reference-types-extern-ref")] + #[test] + // TODO(reftypes): reenable this test + #[ignore] + fn extern_ref_ref_counting_traps() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (func $pass_er (export "pass_extern_ref") (param externref) + (local.get 0) + (unreachable)) +)"#; + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + + let pass_extern_ref: NativeFunc = + instance.exports.get_native_function("pass_extern_ref")?; + + let er = ExternRef::new(3usize); + assert_eq!(er.strong_count(), 1); + + let result = pass_extern_ref.call(er.clone()); + assert!(result.is_err()); + assert_eq!(er.strong_count(), 1); + + Ok(()) + } + + #[cfg(feature = "experimental-reference-types-extern-ref")] + #[test] + fn extern_ref_ref_counting_table_instructions() -> Result<()> { + let store = Store::default(); + let wat = r#"(module + (table $table1 (export "table1") 2 12 externref) + (table $table2 (export "table2") 6 12 externref) + (func $grow_table_with_ref (export "grow_table_with_ref") (param $er externref) (param $size i32) (result i32) + (table.grow $table1 (local.get $er) (local.get $size))) + (func $fill_table_with_ref (export "fill_table_with_ref") (param $er externref) (param $start i32) (param $end i32) + (table.fill $table1 (local.get $start) (local.get $er) (local.get $end))) + (func $copy_into_table2 (export "copy_into_table2") + (table.copy $table2 $table1 (i32.const 0) (i32.const 0) (i32.const 4))) +)"#; + let module = Module::new(&store, wat)?; + let instance = Instance::new(&module, &imports! {})?; + + let grow_table_with_ref: NativeFunc<(ExternRef, i32), i32> = instance + .exports + .get_native_function("grow_table_with_ref")?; + let fill_table_with_ref: NativeFunc<(ExternRef, i32, i32), ()> = instance + .exports + .get_native_function("fill_table_with_ref")?; + let copy_into_table2: NativeFunc<(), ()> = + instance.exports.get_native_function("copy_into_table2")?; + let table1: &Table = instance.exports.get_table("table1")?; + let table2: &Table = instance.exports.get_table("table2")?; + + let er1 = ExternRef::new(3usize); + let er2 = ExternRef::new(5usize); + let er3 = ExternRef::new(7usize); + { + let result = grow_table_with_ref.call(er1.clone(), 0)?; + assert_eq!(result, 2); + assert_eq!(er1.strong_count(), 1); + + let result = grow_table_with_ref.call(er1.clone(), 10_000)?; + assert_eq!(result, -1); + assert_eq!(er1.strong_count(), 1); + + let result = grow_table_with_ref.call(er1.clone(), 8)?; + assert_eq!(result, 2); + assert_eq!(er1.strong_count(), 9); + + for i in 2..10 { + let e = table1.get(i).unwrap().unwrap_externref(); + assert_eq!(*e.downcast::().unwrap(), 3); + assert_eq!(&e, &er1); + } + assert_eq!(er1.strong_count(), 9); + } + + { + fill_table_with_ref.call(er2.clone(), 0, 2)?; + assert_eq!(er2.strong_count(), 3); + } + + { + table2.set(0, Val::ExternRef(er3.clone()))?; + table2.set(1, Val::ExternRef(er3.clone()))?; + table2.set(2, Val::ExternRef(er3.clone()))?; + table2.set(3, Val::ExternRef(er3.clone()))?; + table2.set(4, Val::ExternRef(er3.clone()))?; + assert_eq!(er3.strong_count(), 6); + } + + { + copy_into_table2.call()?; + assert_eq!(er3.strong_count(), 2); + assert_eq!(er2.strong_count(), 5); + assert_eq!(er1.strong_count(), 11); + for i in 1..5 { + let e = table2.get(i).unwrap().unwrap_externref(); + let value = e.downcast::().unwrap(); + match i { + 0 | 1 => assert_eq!(*value, 5), + 4 => assert_eq!(*value, 7), + _ => assert_eq!(*value, 3), + } + } + } + + { + for i in 0..table1.size() { + table1.set(i, Val::ExternRef(ExternRef::null()))?; + } + for i in 0..table2.size() { + table2.set(i, Val::ExternRef(ExternRef::null()))?; + } + } + + assert_eq!(er1.strong_count(), 1); + assert_eq!(er2.strong_count(), 1); + assert_eq!(er3.strong_count(), 1); + + Ok(()) + } +} diff --git a/lib/cache/Cargo.toml b/lib/cache/Cargo.toml index 396ff756ea1..c729a736daa 100644 --- a/lib/cache/Cargo.toml +++ b/lib/cache/Cargo.toml @@ -11,7 +11,7 @@ readme = "README.md" edition = "2018" [dependencies] -wasmer = { path = "../api", version = "2.0.0", default-features = false } +wasmer = { path = "../api", version = "2.0.0", default-features = false, features = ["sys"] } hex = "0.4" thiserror = "1" blake3 = "0.3" diff --git a/lib/cli/src/c_gen/staticlib_header.rs b/lib/cli/src/c_gen/staticlib_header.rs index 2fd5d78ab0f..82933d003cf 100644 --- a/lib/cli/src/c_gen/staticlib_header.rs +++ b/lib/cli/src/c_gen/staticlib_header.rs @@ -2,7 +2,7 @@ use super::{generate_c, CStatement, CType}; use wasmer_compiler::{Symbol, SymbolRegistry}; -use wasmer_vm::ModuleInfo; +use wasmer_types::ModuleInfo; /// Helper functions to simplify the usage of the Staticlib engine. const HELPER_FUNCTIONS: &str = r#" diff --git a/lib/compiler-cranelift/src/func_environ.rs b/lib/compiler-cranelift/src/func_environ.rs index 56e451f4c1b..25b9bb68df1 100644 --- a/lib/compiler-cranelift/src/func_environ.rs +++ b/lib/compiler-cranelift/src/func_environ.rs @@ -18,12 +18,12 @@ use wasmer_compiler::{WasmError, WasmResult}; use wasmer_types::entity::EntityRef; use wasmer_types::entity::PrimaryMap; use wasmer_types::{ - FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, MemoryIndex, SignatureIndex, - TableIndex, Type as WasmerType, + FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, + SignatureIndex, TableIndex, Type as WasmerType, }; use wasmer_vm::VMBuiltinFunctionIndex; use wasmer_vm::VMOffsets; -use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle}; +use wasmer_vm::{MemoryStyle, TableStyle}; /// Compute an `ir::ExternalName` for a given wasm function index. pub fn get_function_name(func_index: FunctionIndex) -> ir::ExternalName { diff --git a/lib/compiler-cranelift/src/sink.rs b/lib/compiler-cranelift/src/sink.rs index 8a0459d2e22..dfc803002d0 100644 --- a/lib/compiler-cranelift/src/sink.rs +++ b/lib/compiler-cranelift/src/sink.rs @@ -6,8 +6,8 @@ use cranelift_codegen::ir::{self, ExternalName}; use cranelift_entity::EntityRef as CraneliftEntityRef; use wasmer_compiler::{JumpTable, Relocation, RelocationTarget, TrapInformation}; use wasmer_types::entity::EntityRef; -use wasmer_types::{FunctionIndex, LocalFunctionIndex}; -use wasmer_vm::{ModuleInfo, TrapCode}; +use wasmer_types::{FunctionIndex, LocalFunctionIndex, ModuleInfo}; +use wasmer_vm::TrapCode; /// Implementation of a relocation sink that just saves all the information for later pub(crate) struct RelocSink<'a> { diff --git a/lib/compiler-llvm/src/translator/code.rs b/lib/compiler-llvm/src/translator/code.rs index 24503fb02ce..e7469799d6a 100644 --- a/lib/compiler-llvm/src/translator/code.rs +++ b/lib/compiler-llvm/src/translator/code.rs @@ -31,10 +31,10 @@ use wasmer_compiler::{ }; use wasmer_types::entity::PrimaryMap; use wasmer_types::{ - FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, MemoryIndex, SignatureIndex, - TableIndex, Type, + FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, + SignatureIndex, TableIndex, Type, }; -use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle, VMOffsets}; +use wasmer_vm::{MemoryStyle, TableStyle, VMOffsets}; const FUNCTION_SECTION: &str = "__TEXT,wasmer_function"; diff --git a/lib/compiler-llvm/src/translator/intrinsics.rs b/lib/compiler-llvm/src/translator/intrinsics.rs index ee6753683dd..8f92f4042f7 100644 --- a/lib/compiler-llvm/src/translator/intrinsics.rs +++ b/lib/compiler-llvm/src/translator/intrinsics.rs @@ -26,9 +26,8 @@ use wasmer_compiler::CompileError; use wasmer_types::entity::{EntityRef, PrimaryMap}; use wasmer_types::{ FunctionIndex, FunctionType as FuncType, GlobalIndex, LocalFunctionIndex, MemoryIndex, - Mutability, SignatureIndex, TableIndex, Type, + ModuleInfo as WasmerCompilerModule, Mutability, SignatureIndex, TableIndex, Type, }; -use wasmer_vm::ModuleInfo as WasmerCompilerModule; use wasmer_vm::{MemoryStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets}; pub fn type_to_llvm_ptr<'ctx>( diff --git a/lib/compiler-singlepass/src/codegen_x64.rs b/lib/compiler-singlepass/src/codegen_x64.rs index 953bda078dd..bd02ddc2a4a 100644 --- a/lib/compiler-singlepass/src/codegen_x64.rs +++ b/lib/compiler-singlepass/src/codegen_x64.rs @@ -17,10 +17,10 @@ use wasmer_types::{ FunctionType, }; use wasmer_types::{ - FunctionIndex, GlobalIndex, LocalFunctionIndex, LocalMemoryIndex, MemoryIndex, SignatureIndex, - TableIndex, Type, + FunctionIndex, GlobalIndex, LocalFunctionIndex, LocalMemoryIndex, MemoryIndex, ModuleInfo, + SignatureIndex, TableIndex, Type, }; -use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets}; +use wasmer_vm::{MemoryStyle, TableStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets}; /// The singlepass per-function code generator. pub struct FuncGen<'a> { diff --git a/lib/compiler-singlepass/src/compiler.rs b/lib/compiler-singlepass/src/compiler.rs index 13d82c2b2eb..ea818264ba6 100644 --- a/lib/compiler-singlepass/src/compiler.rs +++ b/lib/compiler-singlepass/src/compiler.rs @@ -11,16 +11,17 @@ use loupe::MemoryUsage; #[cfg(feature = "rayon")] use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use std::sync::Arc; -use wasmer_compiler::TrapInformation; use wasmer_compiler::{ - Architecture, CompileModuleInfo, CompilerConfig, FunctionBinaryReader, MiddlewareBinaryReader, - ModuleMiddleware, ModuleMiddlewareChain, ModuleTranslationState, OperatingSystem, Target, + Architecture, Compilation, CompileError, CompileModuleInfo, CompiledFunction, Compiler, + CompilerConfig, FunctionBinaryReader, FunctionBody, FunctionBodyData, MiddlewareBinaryReader, + ModuleMiddleware, ModuleMiddlewareChain, ModuleTranslationState, OperatingSystem, SectionIndex, + Target, TrapInformation, }; -use wasmer_compiler::{Compilation, CompileError, CompiledFunction, Compiler, SectionIndex}; -use wasmer_compiler::{FunctionBody, FunctionBodyData}; use wasmer_types::entity::{EntityRef, PrimaryMap}; -use wasmer_types::{FunctionIndex, FunctionType, LocalFunctionIndex, MemoryIndex, TableIndex}; -use wasmer_vm::{ModuleInfo, TrapCode, VMOffsets}; +use wasmer_types::{ + FunctionIndex, FunctionType, LocalFunctionIndex, MemoryIndex, ModuleInfo, TableIndex, +}; +use wasmer_vm::{TrapCode, VMOffsets}; /// A compiler that compiles a WebAssembly module with Singlepass. /// It does the compilation in one pass diff --git a/lib/compiler/src/module.rs b/lib/compiler/src/module.rs index 347003fb61c..6e9c5ce279c 100644 --- a/lib/compiler/src/module.rs +++ b/lib/compiler/src/module.rs @@ -5,8 +5,8 @@ use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize}; #[cfg(feature = "enable-serde")] use serde::{Deserialize, Serialize}; use wasmer_types::entity::PrimaryMap; -use wasmer_types::{Features, MemoryIndex, TableIndex}; -use wasmer_vm::{MemoryStyle, ModuleInfo, TableStyle}; +use wasmer_types::{Features, MemoryIndex, ModuleInfo, TableIndex}; +use wasmer_vm::{MemoryStyle, TableStyle}; /// The required info for compiling a module. /// diff --git a/lib/compiler/src/translator/environ.rs b/lib/compiler/src/translator/environ.rs index 5b22dd73ddf..560f1be128c 100644 --- a/lib/compiler/src/translator/environ.rs +++ b/lib/compiler/src/translator/environ.rs @@ -15,10 +15,9 @@ use wasmer_types::FunctionType; use wasmer_types::{ CustomSectionIndex, DataIndex, DataInitializer, DataInitializerLocation, ElemIndex, ExportIndex, FunctionIndex, GlobalIndex, GlobalInit, GlobalType, ImportIndex, - LocalFunctionIndex, MemoryIndex, MemoryType, SignatureIndex, TableIndex, TableInitializer, - TableType, + LocalFunctionIndex, MemoryIndex, MemoryType, ModuleInfo, SignatureIndex, TableIndex, + TableInitializer, TableType, }; -use wasmer_vm::ModuleInfo; /// Contains function data: bytecode and its offset in the module. #[derive(Hash)] diff --git a/lib/compiler/src/translator/middleware.rs b/lib/compiler/src/translator/middleware.rs index 75d76c4033f..957cf93264b 100644 --- a/lib/compiler/src/translator/middleware.rs +++ b/lib/compiler/src/translator/middleware.rs @@ -6,8 +6,7 @@ use smallvec::SmallVec; use std::collections::VecDeque; use std::fmt::Debug; use std::ops::Deref; -use wasmer_types::LocalFunctionIndex; -use wasmer_vm::ModuleInfo; +use wasmer_types::{LocalFunctionIndex, ModuleInfo}; use wasmparser::{BinaryReader, Operator, Range, Type}; use crate::error::{MiddlewareError, WasmResult}; diff --git a/lib/derive/Cargo.toml b/lib/derive/Cargo.toml index 06b2e8cfc66..52a4154d430 100644 --- a/lib/derive/Cargo.toml +++ b/lib/derive/Cargo.toml @@ -18,4 +18,4 @@ proc-macro-error = "1.0.0" [dev-dependencies] wasmer = { path = "../api", version = "2.0.0" } -compiletest_rs = "0.6" +compiletest_rs = "0.6" \ No newline at end of file diff --git a/lib/emscripten/Cargo.toml b/lib/emscripten/Cargo.toml index a4cdf7add1d..2b9cb4cad97 100644 --- a/lib/emscripten/Cargo.toml +++ b/lib/emscripten/Cargo.toml @@ -16,7 +16,7 @@ lazy_static = "1.4" libc = "^0.2" log = "0.4" time = "0.1" -wasmer = { path = "../api", version = "2.0.0", default-features = false } +wasmer = { path = "../api", version = "2.0.0", default-features = false, features = ["sys"] } [target.'cfg(windows)'.dependencies] getrandom = "0.2" diff --git a/lib/engine-dylib/src/artifact.rs b/lib/engine-dylib/src/artifact.rs index e15220c8921..d4230e84bd4 100644 --- a/lib/engine-dylib/src/artifact.rs +++ b/lib/engine-dylib/src/artifact.rs @@ -36,11 +36,11 @@ use wasmer_types::entity::{BoxedSlice, PrimaryMap}; #[cfg(feature = "compiler")] use wasmer_types::DataInitializer; use wasmer_types::{ - FunctionIndex, LocalFunctionIndex, MemoryIndex, OwnedDataInitializer, SignatureIndex, - TableIndex, + FunctionIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, OwnedDataInitializer, + SignatureIndex, TableIndex, }; use wasmer_vm::{ - FuncDataRegistry, FunctionBodyPtr, MemoryStyle, ModuleInfo, TableStyle, VMFunctionBody, + FuncDataRegistry, FunctionBodyPtr, MemoryStyle, TableStyle, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline, }; diff --git a/lib/engine-staticlib/src/artifact.rs b/lib/engine-staticlib/src/artifact.rs index 0a7d03350b9..f10c18e3e84 100644 --- a/lib/engine-staticlib/src/artifact.rs +++ b/lib/engine-staticlib/src/artifact.rs @@ -24,11 +24,11 @@ use wasmer_types::entity::{BoxedSlice, PrimaryMap}; #[cfg(feature = "compiler")] use wasmer_types::DataInitializer; use wasmer_types::{ - FunctionIndex, LocalFunctionIndex, MemoryIndex, OwnedDataInitializer, SignatureIndex, - TableIndex, + FunctionIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, OwnedDataInitializer, + SignatureIndex, TableIndex, }; use wasmer_vm::{ - FuncDataRegistry, FunctionBodyPtr, MemoryStyle, ModuleInfo, TableStyle, VMSharedSignatureIndex, + FuncDataRegistry, FunctionBodyPtr, MemoryStyle, TableStyle, VMSharedSignatureIndex, VMTrampoline, }; diff --git a/lib/engine-universal/src/artifact.rs b/lib/engine-universal/src/artifact.rs index d4784a958c2..de6e6cc24fb 100644 --- a/lib/engine-universal/src/artifact.rs +++ b/lib/engine-universal/src/artifact.rs @@ -19,11 +19,11 @@ use wasmer_engine::{ use wasmer_engine::{Engine, Tunables}; use wasmer_types::entity::{BoxedSlice, PrimaryMap}; use wasmer_types::{ - FunctionIndex, LocalFunctionIndex, MemoryIndex, OwnedDataInitializer, SignatureIndex, - TableIndex, + FunctionIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, OwnedDataInitializer, + SignatureIndex, TableIndex, }; use wasmer_vm::{ - FuncDataRegistry, FunctionBodyPtr, MemoryStyle, ModuleInfo, TableStyle, VMSharedSignatureIndex, + FuncDataRegistry, FunctionBodyPtr, MemoryStyle, TableStyle, VMSharedSignatureIndex, VMTrampoline, }; diff --git a/lib/engine-universal/src/engine.rs b/lib/engine-universal/src/engine.rs index 205f833ce1a..ecc34931212 100644 --- a/lib/engine-universal/src/engine.rs +++ b/lib/engine-universal/src/engine.rs @@ -10,11 +10,12 @@ use wasmer_compiler::{ }; use wasmer_engine::{Artifact, DeserializeError, Engine, EngineId, FunctionExtent, Tunables}; use wasmer_types::entity::PrimaryMap; -use wasmer_types::Features; -use wasmer_types::{FunctionIndex, FunctionType, LocalFunctionIndex, SignatureIndex}; +use wasmer_types::{ + Features, FunctionIndex, FunctionType, LocalFunctionIndex, ModuleInfo, SignatureIndex, +}; use wasmer_vm::{ - FuncDataRegistry, FunctionBodyPtr, ModuleInfo, SectionBodyPtr, SignatureRegistry, - VMCallerCheckedAnyfunc, VMFuncRef, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline, + FuncDataRegistry, FunctionBodyPtr, SectionBodyPtr, SignatureRegistry, VMCallerCheckedAnyfunc, + VMFuncRef, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline, }; /// A WebAssembly `Universal` Engine. diff --git a/lib/engine-universal/src/link.rs b/lib/engine-universal/src/link.rs index 94447f88da9..e900fc78e5a 100644 --- a/lib/engine-universal/src/link.rs +++ b/lib/engine-universal/src/link.rs @@ -7,8 +7,7 @@ use wasmer_compiler::{ }; use wasmer_engine::FunctionExtent; use wasmer_types::entity::{EntityRef, PrimaryMap}; -use wasmer_types::LocalFunctionIndex; -use wasmer_vm::ModuleInfo; +use wasmer_types::{LocalFunctionIndex, ModuleInfo}; use wasmer_vm::SectionBodyPtr; fn apply_relocation( diff --git a/lib/engine/src/artifact.rs b/lib/engine/src/artifact.rs index 00146067c3d..0f1058602e1 100644 --- a/lib/engine/src/artifact.rs +++ b/lib/engine/src/artifact.rs @@ -9,12 +9,12 @@ use std::sync::Arc; use wasmer_compiler::Features; use wasmer_types::entity::{BoxedSlice, PrimaryMap}; use wasmer_types::{ - DataInitializer, FunctionIndex, LocalFunctionIndex, MemoryIndex, OwnedDataInitializer, - SignatureIndex, TableIndex, + DataInitializer, FunctionIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, + OwnedDataInitializer, SignatureIndex, TableIndex, }; use wasmer_vm::{ - FuncDataRegistry, FunctionBodyPtr, InstanceAllocator, InstanceHandle, MemoryStyle, ModuleInfo, - TableStyle, TrapHandler, VMSharedSignatureIndex, VMTrampoline, + FuncDataRegistry, FunctionBodyPtr, InstanceAllocator, InstanceHandle, MemoryStyle, TableStyle, + TrapHandler, VMSharedSignatureIndex, VMTrampoline, }; /// An `Artifact` is the product that the `Engine` diff --git a/lib/engine/src/resolver.rs b/lib/engine/src/resolver.rs index c3f0ab3b5d0..bcbd4beaeda 100644 --- a/lib/engine/src/resolver.rs +++ b/lib/engine/src/resolver.rs @@ -4,12 +4,12 @@ use crate::{Export, ExportFunctionMetadata, ImportError, LinkError}; use more_asserts::assert_ge; use wasmer_types::entity::{BoxedSlice, EntityRef, PrimaryMap}; -use wasmer_types::{ExternType, FunctionIndex, ImportIndex, MemoryIndex, TableIndex}; +use wasmer_types::{ExternType, FunctionIndex, ImportIndex, MemoryIndex, ModuleInfo, TableIndex}; use wasmer_vm::{ - FunctionBodyPtr, ImportFunctionEnv, Imports, MemoryStyle, ModuleInfo, TableStyle, - VMFunctionBody, VMFunctionEnvironment, VMFunctionImport, VMFunctionKind, VMGlobalImport, - VMMemoryImport, VMTableImport, + FunctionBodyPtr, ImportFunctionEnv, Imports, MemoryStyle, TableStyle, VMFunctionBody, + VMFunctionEnvironment, VMFunctionImport, VMFunctionKind, VMGlobalImport, VMMemoryImport, + VMTableImport, }; /// Import resolver connects imports with available exported values. diff --git a/lib/engine/src/trap/frame_info.rs b/lib/engine/src/trap/frame_info.rs index 08a29b2af34..9b7e4df95c5 100644 --- a/lib/engine/src/trap/frame_info.rs +++ b/lib/engine/src/trap/frame_info.rs @@ -5,7 +5,8 @@ //! //! # Example //! ```ignore -//! use wasmer_vm::{ModuleInfo, FRAME_INFO}; +//! use wasmer_vm::{FRAME_INFO}; +//! use wasmer_types::ModuleInfo; //! //! let module: ModuleInfo = ...; //! FRAME_INFO.register(module, compiled_functions); @@ -16,8 +17,8 @@ use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation}; use wasmer_types::entity::{BoxedSlice, EntityRef, PrimaryMap}; -use wasmer_types::LocalFunctionIndex; -use wasmer_vm::{FunctionBodyPtr, ModuleInfo}; +use wasmer_types::{LocalFunctionIndex, ModuleInfo}; +use wasmer_vm::FunctionBodyPtr; lazy_static::lazy_static! { /// This is a global cache of backtrace frame information for all active diff --git a/lib/engine/src/tunables.rs b/lib/engine/src/tunables.rs index adad964c697..239bd7676f6 100644 --- a/lib/engine/src/tunables.rs +++ b/lib/engine/src/tunables.rs @@ -5,10 +5,10 @@ use std::sync::Arc; use wasmer_types::entity::{EntityRef, PrimaryMap}; use wasmer_types::{ GlobalType, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, MemoryType, - TableIndex, TableType, + ModuleInfo, TableIndex, TableType, }; use wasmer_vm::MemoryError; -use wasmer_vm::{Global, Memory, ModuleInfo, Table}; +use wasmer_vm::{Global, Memory, Table}; use wasmer_vm::{MemoryStyle, TableStyle}; use wasmer_vm::{VMMemoryDefinition, VMTableDefinition}; diff --git a/lib/middlewares/src/metering.rs b/lib/middlewares/src/metering.rs index 18be778b06f..3d009aab1ba 100644 --- a/lib/middlewares/src/metering.rs +++ b/lib/middlewares/src/metering.rs @@ -18,8 +18,7 @@ use wasmer::{ ExportIndex, FunctionMiddleware, GlobalInit, GlobalType, Instance, LocalFunctionIndex, MiddlewareError, MiddlewareReaderState, ModuleMiddleware, Mutability, Type, }; -use wasmer_types::GlobalIndex; -use wasmer_vm::ModuleInfo; +use wasmer_types::{GlobalIndex, ModuleInfo}; #[derive(Clone, MemoryUsage)] struct MeteringGlobalIndexes(GlobalIndex, GlobalIndex); diff --git a/lib/types/Cargo.toml b/lib/types/Cargo.toml index 118afc44258..11c5d3b5411 100644 --- a/lib/types/Cargo.toml +++ b/lib/types/Cargo.toml @@ -11,18 +11,18 @@ readme = "README.md" edition = "2018" [dependencies] -serde = { version = "1.0", features = ["derive"], optional = true, default-features = false } +serde = { version = "1.0", features = ["derive", "rc"], optional = true, default-features = false } thiserror = "1.0" indexmap = { version = "1.6", features = ["serde-1"] } rkyv = { version = "0.6.1", optional = true } -loupe = "0.1" +loupe = { version = "0.1", features = ["enable-indexmap"] } [features] default = ["std", "enable-serde", "enable-rkyv"] -std = ["serde/std"] +std = [] core = [] enable-rkyv = ["rkyv"] -enable-serde = ["serde"] +enable-serde = ["serde", "serde/std"] # experimental / in-development features experimental-reference-types-extern-ref = [] diff --git a/lib/types/src/initializers.rs b/lib/types/src/initializers.rs index 1809eddd0bb..a37a23011c0 100644 --- a/lib/types/src/initializers.rs +++ b/lib/types/src/initializers.rs @@ -8,11 +8,12 @@ use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize}; use serde::{Deserialize, Serialize}; /// A WebAssembly table initializer. -#[derive(Clone, Debug, Hash, Serialize, Deserialize, MemoryUsage, PartialEq, Eq)] +#[derive(Clone, Debug, Hash, MemoryUsage, PartialEq, Eq)] #[cfg_attr( feature = "enable-rkyv", derive(RkyvSerialize, RkyvDeserialize, Archive) )] +#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] pub struct TableInitializer { /// The index of a table to initialize. pub table_index: TableIndex, diff --git a/lib/types/src/lib.rs b/lib/types/src/lib.rs index a471abecc08..88dbd26e5eb 100644 --- a/lib/types/src/lib.rs +++ b/lib/types/src/lib.rs @@ -61,6 +61,7 @@ mod features; mod indexes; mod initializers; mod memory_view; +mod module; mod native; mod types; mod units; @@ -79,6 +80,7 @@ pub use crate::initializers::{ DataInitializer, DataInitializerLocation, OwnedDataInitializer, TableInitializer, }; pub use crate::memory_view::{Atomically, MemoryView}; +pub use crate::module::{ExportsIterator, ImportsIterator, ModuleInfo}; pub use crate::native::{NativeWasmType, ValueType}; pub use crate::units::{ Bytes, PageCountOutOfRange, Pages, WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE, diff --git a/lib/vm/src/module.rs b/lib/types/src/module.rs similarity index 94% rename from lib/vm/src/module.rs rename to lib/types/src/module.rs index e2f1e358118..a4a02ed7d3c 100644 --- a/lib/vm/src/module.rs +++ b/lib/types/src/module.rs @@ -4,6 +4,15 @@ //! Data structure for representing WebAssembly modules in a //! `wasmer::Module`. +use crate::entity::{EntityRef, PrimaryMap}; +#[cfg(feature = "enable-rkyv")] +use crate::ArchivableIndexMap; +use crate::{ + CustomSectionIndex, DataIndex, ElemIndex, ExportIndex, ExportType, ExternType, FunctionIndex, + FunctionType, GlobalIndex, GlobalInit, GlobalType, ImportIndex, ImportType, LocalFunctionIndex, + LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, MemoryType, SignatureIndex, + TableIndex, TableInitializer, TableType, +}; use indexmap::IndexMap; use loupe::MemoryUsage; #[cfg(feature = "enable-rkyv")] @@ -11,6 +20,7 @@ use rkyv::{ de::SharedDeserializer, ser::Serializer, ser::SharedSerializer, Archive, Archived, Deserialize as RkyvDeserialize, Fallible, Serialize as RkyvSerialize, }; +#[cfg(feature = "enable-serde")] use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt; @@ -19,15 +29,6 @@ use std::iter::ExactSizeIterator; use std::mem::MaybeUninit; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Arc; -use wasmer_types::entity::{EntityRef, PrimaryMap}; -#[cfg(feature = "enable-rkyv")] -use wasmer_types::ArchivableIndexMap; -use wasmer_types::{ - CustomSectionIndex, DataIndex, ElemIndex, ExportIndex, ExportType, ExternType, FunctionIndex, - FunctionType, GlobalIndex, GlobalInit, GlobalType, ImportIndex, ImportType, LocalFunctionIndex, - LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, MemoryType, SignatureIndex, - TableIndex, TableInitializer, TableType, -}; #[derive(Debug, Clone, MemoryUsage)] #[cfg_attr( @@ -55,7 +56,8 @@ impl Default for ModuleId { /// A translated WebAssembly module, excluding the function bodies and /// memory initializers. -#[derive(Debug, Clone, Serialize, Deserialize, MemoryUsage)] +#[derive(Debug, Clone, Default, MemoryUsage)] +#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] pub struct ModuleInfo { /// A unique identifier (within this process) for this module. /// @@ -63,7 +65,7 @@ pub struct ModuleInfo { /// should be computed by the process. /// It's not skipped in rkyv, but that is okay, because even though it's skipped in bincode/serde /// it's still deserialized back as a garbage number, and later override from computed by the process - #[serde(skip_serializing, skip_deserializing)] + #[cfg_attr(feature = "enable-serde", serde(skip_serializing, skip_deserializing))] pub id: ModuleId, /// The name of this wasm module, often found in the wasm file. @@ -280,29 +282,7 @@ impl Eq for ModuleInfo {} impl ModuleInfo { /// Allocates the module data structures. pub fn new() -> Self { - Self { - id: ModuleId::default(), - name: None, - imports: IndexMap::new(), - exports: IndexMap::new(), - start_function: None, - table_initializers: Vec::new(), - passive_elements: HashMap::new(), - passive_data: HashMap::new(), - global_initializers: PrimaryMap::new(), - function_names: HashMap::new(), - signatures: PrimaryMap::new(), - functions: PrimaryMap::new(), - tables: PrimaryMap::new(), - memories: PrimaryMap::new(), - globals: PrimaryMap::new(), - num_imported_functions: 0, - num_imported_tables: 0, - num_imported_memories: 0, - num_imported_globals: 0, - custom_sections: IndexMap::new(), - custom_sections_data: PrimaryMap::new(), - } + Default::default() } /// Get the given passive element, if it exists. @@ -349,13 +329,10 @@ impl ModuleInfo { }; ExportType::new(name, extern_type) }); - ExportsIterator { - iter, - size: self.exports.len(), - } + ExportsIterator::new(iter, self.exports.len()) } - /// Get the export types of the module + /// Get the import types of the module pub fn imports<'a>(&'a self) -> ImportsIterator + 'a> { let iter = self .imports @@ -382,10 +359,7 @@ impl ModuleInfo { }; ImportType::new(module, field, extern_type) }); - ImportsIterator { - iter, - size: self.imports.len(), - } + ImportsIterator::new(iter, self.imports.len()) } /// Get the custom sections of the module given a `name`. @@ -508,6 +482,13 @@ pub struct ExportsIterator + Sized> { size: usize, } +impl + Sized> ExportsIterator { + /// Create a new `ExportsIterator` for a given iterator and size + pub fn new(iter: I, size: usize) -> Self { + Self { iter, size } + } +} + impl + Sized> ExactSizeIterator for ExportsIterator { // We can easily calculate the remaining number of iterations. fn len(&self) -> usize { @@ -560,6 +541,13 @@ pub struct ImportsIterator + Sized> { size: usize, } +impl + Sized> ImportsIterator { + /// Create a new `ImportsIterator` for a given iterator and size + pub fn new(iter: I, size: usize) -> Self { + Self { iter, size } + } +} + impl + Sized> ExactSizeIterator for ImportsIterator { // We can easily calculate the remaining number of iterations. fn len(&self) -> usize { diff --git a/lib/vm/src/instance/allocator.rs b/lib/vm/src/instance/allocator.rs index fa2618facc2..f49b42a14b5 100644 --- a/lib/vm/src/instance/allocator.rs +++ b/lib/vm/src/instance/allocator.rs @@ -1,12 +1,12 @@ use super::{Instance, InstanceRef}; use crate::vmcontext::{VMMemoryDefinition, VMTableDefinition}; -use crate::{ModuleInfo, VMOffsets}; +use crate::VMOffsets; use std::alloc::{self, Layout}; use std::convert::TryFrom; use std::mem; use std::ptr::{self, NonNull}; use wasmer_types::entity::EntityRef; -use wasmer_types::{LocalMemoryIndex, LocalTableIndex}; +use wasmer_types::{LocalMemoryIndex, LocalTableIndex, ModuleInfo}; /// This is an intermediate type that manages the raw allocation and /// metadata when creating an [`Instance`]. diff --git a/lib/vm/src/instance/mod.rs b/lib/vm/src/instance/mod.rs index 366339f9fdf..ac827ee4d97 100644 --- a/lib/vm/src/instance/mod.rs +++ b/lib/vm/src/instance/mod.rs @@ -26,7 +26,7 @@ use crate::vmcontext::{ VMMemoryDefinition, VMMemoryImport, VMSharedSignatureIndex, VMTableDefinition, VMTableImport, VMTrampoline, }; -use crate::{FunctionBodyPtr, ModuleInfo, VMOffsets}; +use crate::{FunctionBodyPtr, VMOffsets}; use crate::{VMFunction, VMGlobal, VMMemory, VMTable}; use loupe::{MemoryUsage, MemoryUsageTracker}; use memoffset::offset_of; @@ -44,8 +44,8 @@ use std::sync::Arc; use wasmer_types::entity::{packed_option::ReservedValue, BoxedSlice, EntityRef, PrimaryMap}; use wasmer_types::{ DataIndex, DataInitializer, ElemIndex, ExportIndex, FunctionIndex, GlobalIndex, GlobalInit, - LocalFunctionIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, Pages, - SignatureIndex, TableIndex, TableInitializer, + LocalFunctionIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, + ModuleInfo, Pages, SignatureIndex, TableIndex, TableInitializer, }; /// The function pointer to call with data and an [`Instance`] pointer to diff --git a/lib/vm/src/lib.rs b/lib/vm/src/lib.rs index 87d51529a45..ecf4fd71ff6 100644 --- a/lib/vm/src/lib.rs +++ b/lib/vm/src/lib.rs @@ -28,7 +28,6 @@ mod imports; mod instance; mod memory; mod mmap; -mod module; mod probestack; mod sig_registry; mod table; @@ -48,7 +47,6 @@ pub use crate::instance::{ }; pub use crate::memory::{LinearMemory, Memory, MemoryError, MemoryStyle}; pub use crate::mmap::Mmap; -pub use crate::module::{ExportsIterator, ImportsIterator, ModuleInfo}; pub use crate::probestack::PROBESTACK; pub use crate::sig_registry::SignatureRegistry; pub use crate::table::{LinearTable, Table, TableElement, TableStyle}; @@ -62,6 +60,11 @@ pub use crate::vmcontext::{ pub use crate::vmoffsets::{TargetSharedSignatureIndex, VMOffsets}; use loupe::MemoryUsage; pub use wasmer_types::VMExternRef; +#[deprecated( + since = "2.1.0", + note = "ModuleInfo, ExportsIterator, ImportsIterator should be imported from wasmer_types." +)] +pub use wasmer_types::{ExportsIterator, ImportsIterator, ModuleInfo}; /// Version number of this crate. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/lib/vm/src/vmcontext.rs b/lib/vm/src/vmcontext.rs index ec7d6ca06bf..e969df11218 100644 --- a/lib/vm/src/vmcontext.rs +++ b/lib/vm/src/vmcontext.rs @@ -81,9 +81,10 @@ pub struct VMFunctionImport { #[cfg(test)] mod test_vmfunction_import { use super::VMFunctionImport; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmfunction_import_offsets() { @@ -143,9 +144,10 @@ impl Clone for VMDynamicFunctionContext { #[cfg(test)] mod test_vmdynamicfunction_import_context { use super::VMDynamicFunctionContext; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmdynamicfunction_import_context_offsets() { @@ -219,9 +221,10 @@ pub struct VMTableImport { #[cfg(test)] mod test_vmtable_import { use super::VMTableImport; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmtable_import_offsets() { @@ -257,9 +260,10 @@ pub struct VMMemoryImport { #[cfg(test)] mod test_vmmemory_import { use super::VMMemoryImport; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmmemory_import_offsets() { @@ -307,9 +311,10 @@ unsafe impl Sync for VMGlobalImport {} #[cfg(test)] mod test_vmglobal_import { use super::VMGlobalImport; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmglobal_import_offsets() { @@ -432,9 +437,10 @@ impl VMMemoryDefinition { #[cfg(test)] mod test_vmmemory_definition { use super::VMMemoryDefinition; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmmemory_definition_offsets() { @@ -486,9 +492,10 @@ impl MemoryUsage for VMTableDefinition { #[cfg(test)] mod test_vmtable_definition { use super::VMTableDefinition; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmtable_definition_offsets() { @@ -559,9 +566,10 @@ pub struct VMGlobalDefinition { #[cfg(test)] mod test_vmglobal_definition { use super::VMGlobalDefinition; - use crate::{ModuleInfo, VMFuncRef, VMOffsets}; + use crate::{VMFuncRef, VMOffsets}; use more_asserts::assert_ge; use std::mem::{align_of, size_of}; + use wasmer_types::ModuleInfo; #[test] fn check_vmglobal_definition_alignment() { @@ -796,9 +804,9 @@ pub struct VMSharedSignatureIndex(u32); #[cfg(test)] mod test_vmshared_signature_index { use super::VMSharedSignatureIndex; - use crate::module::ModuleInfo; use crate::vmoffsets::{TargetSharedSignatureIndex, VMOffsets}; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmshared_signature_index() { @@ -850,9 +858,10 @@ pub struct VMCallerCheckedAnyfunc { #[cfg(test)] mod test_vmcaller_checked_anyfunc { use super::VMCallerCheckedAnyfunc; - use crate::{ModuleInfo, VMOffsets}; + use crate::VMOffsets; use memoffset::offset_of; use std::mem::size_of; + use wasmer_types::ModuleInfo; #[test] fn check_vmcaller_checked_anyfunc_offsets() { diff --git a/lib/vm/src/vmoffsets.rs b/lib/vm/src/vmoffsets.rs index 7d849e88e25..2a1df9cf66f 100644 --- a/lib/vm/src/vmoffsets.rs +++ b/lib/vm/src/vmoffsets.rs @@ -6,14 +6,13 @@ #![deny(broken_intra_doc_links)] -use crate::module::ModuleInfo; use crate::VMBuiltinFunctionIndex; use loupe::MemoryUsage; use more_asserts::assert_lt; use std::convert::TryFrom; use wasmer_types::{ FunctionIndex, GlobalIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, - SignatureIndex, TableIndex, + ModuleInfo, SignatureIndex, TableIndex, }; #[cfg(target_pointer_width = "32")] diff --git a/lib/wasi/Cargo.toml b/lib/wasi/Cargo.toml index 7e9313402aa..be2dac2c867 100644 --- a/lib/wasi/Cargo.toml +++ b/lib/wasi/Cargo.toml @@ -20,7 +20,7 @@ getrandom = "0.2" typetag = "0.1" serde = { version = "1.0", features = ["derive"] } wasmer-wasi-types = { path = "../wasi-types", version = "2.0.0" } -wasmer = { path = "../api", version = "2.0.0", default-features = false } +wasmer = { path = "../api", version = "2.0.0", default-features = false, features = ["sys"] } [target.'cfg(windows)'.dependencies] winapi = "0.3" diff --git a/lib/wasi/src/syscalls/mod.rs b/lib/wasi/src/syscalls/mod.rs index 074613a9c8b..e172ca5782e 100644 --- a/lib/wasi/src/syscalls/mod.rs +++ b/lib/wasi/src/syscalls/mod.rs @@ -116,10 +116,11 @@ fn write_buffer_array( let mut current_buffer_offset = 0; for ((i, sub_buffer), ptr) in from.iter().enumerate().zip(ptrs.iter()) { - ptr.set(WasmPtr::new(buffer.offset() + current_buffer_offset)); + debug!("ptr: {:?}, subbuffer: {:?}", ptr, sub_buffer); + let new_ptr = WasmPtr::new(buffer.offset() + current_buffer_offset); + ptr.set(new_ptr); - let cells = - wasi_try!(buffer.deref(memory, current_buffer_offset, sub_buffer.len() as u32 + 1)); + let cells = wasi_try!(new_ptr.deref(memory, 0, sub_buffer.len() as u32 + 1)); for (cell, &byte) in cells.iter().zip(sub_buffer.iter().chain([0].iter())) { cell.set(byte); @@ -268,8 +269,12 @@ pub fn environ_get( environ: WasmPtr, Array>, environ_buf: WasmPtr, ) -> __wasi_errno_t { - debug!("wasi::environ_get"); + debug!( + "wasi::environ_get. Environ: {:?}, environ_buf: {:?}", + environ, environ_buf + ); let (memory, mut state) = env.get_memory_and_wasi_state(0); + debug!(" -> State envs: {:?}", state.envs); write_buffer_array(memory, &*state.envs, environ, environ_buf) } @@ -757,6 +762,7 @@ pub fn fd_prestat_dir_name( // check inode-val.is_preopened? + debug!("=> inode: {:?}", inode_val); match inode_val.kind { Kind::Dir { .. } | Kind::Root { .. } => { // TODO: verify this: null termination, etc @@ -769,11 +775,10 @@ pub fn fd_prestat_dir_name( path_chars[i].set(0); debug!( - "=> result: \"{}\"", - ::std::str::from_utf8(unsafe { - &*(&path_chars[..] as *const [_] as *const [u8]) - }) - .unwrap() + "=> result: \"{}\" (written: {}, {})", + unsafe { path.get_utf8_str(memory, path_len).unwrap() }, + i, + path_chars[0].get(), ); __WASI_ESUCCESS diff --git a/tests/lib/engine-dummy/src/artifact.rs b/tests/lib/engine-dummy/src/artifact.rs index a5a993c401f..72fc3d4552e 100644 --- a/tests/lib/engine-dummy/src/artifact.rs +++ b/tests/lib/engine-dummy/src/artifact.rs @@ -12,12 +12,12 @@ use wasmer_compiler::ModuleEnvironment; use wasmer_engine::{Artifact, DeserializeError, Engine as _, SerializeError, Tunables}; use wasmer_types::entity::{BoxedSlice, PrimaryMap}; use wasmer_types::{ - Features, FunctionIndex, LocalFunctionIndex, MemoryIndex, OwnedDataInitializer, SignatureIndex, - TableIndex, + Features, FunctionIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, OwnedDataInitializer, + SignatureIndex, TableIndex, }; use wasmer_vm::{ - FuncDataRegistry, FunctionBodyPtr, MemoryStyle, ModuleInfo, TableStyle, VMContext, - VMFunctionBody, VMSharedSignatureIndex, VMTrampoline, + FuncDataRegistry, FunctionBodyPtr, MemoryStyle, TableStyle, VMContext, VMFunctionBody, + VMSharedSignatureIndex, VMTrampoline, }; /// Serializable struct for the artifact