Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ cranelift-entity = { version = "0.49", features = ["enable-serde"] }
cranelift-wasm = { version = "0.49", features = ["enable-serde"] }
cranelift-native = "0.49"
wasmtime = { path = "crates/api" }
wasmtime-bindings = { path = "crates/bindings" }
wasmtime-bindings-macro = { path = "crates/bindings/macro" }
wasmtime-debug = { path = "crates/debug" }
wasmtime-environ = { path = "crates/environ" }
wasmtime-interface-types = { path = "crates/interface-types" }
Expand Down
2 changes: 2 additions & 0 deletions crates/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ serde = { "version" = "1.0.94", features = ["derive"] }
pretty_env_logger = "0.3.0"
wasmtime-wast = { path = "../wast" }
wasmtime-wasi = { path = "../wasi" }
wasmtime-bindings = { path = "../bindings" }
wasmtime-bindings-macro = { path = "../bindings/macro" }
rayon = "1.1"
file-per-thread-logger = "0.1.1"

Expand Down
74 changes: 74 additions & 0 deletions crates/api/examples/hello2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! Translation of hello example

use anyhow::{bail, format_err, Result};
use std::cell::Ref;
use std::fs::read;
use wasmtime_api::*;

#[macro_use]
extern crate wasmtime_bindings_macro;

use wasmtime_bindings::*;

#[wasmtime_method(module(callback_mod))]
fn callback() {
println!("Calling back...");
println!("> Hello World!");
}

#[wasmtime_method(module(hello_mod))]
fn hello() {
unimplemented!();
}

fn main() -> Result<()> {
// Initialize.
println!("Initializing...");
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(&engine));

// Load binary.
println!("Loading binary...");
let binary = read("examples/hello.wasm")?;

// Compile.
println!("Compiling module...");
let module = HostRef::new(
Module::new(&store, &binary).map_err(|_| format_err!("> Error compiling module!"))?,
);

// Create external print functions.
println!("Creating callback...");
let hello_func = HostRef::new(wrap_wasmtime_func!(&store; module(callback_mod)));

// Instantiate.
println!("Instantiating module...");
let imports = vec![hello_func.into()];
let instance = HostRef::new(
Instance::new(&store, &module, imports.as_slice())
.map_err(|_| format_err!("> Error instantiating module!"))?,
);

// Extract export.
println!("Extracting export...");
let exports = Ref::map(instance.borrow(), |instance| instance.exports());
if exports.len() == 0 {
bail!("> Error accessing exports!");
}
let run_func = exports[0]
.func()
.ok_or_else(|| format_err!("> Error accessing exports!"))?;

// Call.
println!("Calling export...");
let f = get_wasmtime_func!(run_func; module(hello_mod));
f.call();

// Shut down.
println!("Shutting down...");
drop(store);

// All done.
println!("Done.");
Ok(())
}
80 changes: 80 additions & 0 deletions crates/api/examples/hello3.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
//! Translation of hello example

use anyhow::{format_err, Result};
use std::fs::read;
use wasmtime_api::*;

#[macro_use]
extern crate wasmtime_bindings_macro;

#[wasmtime_trait(module(callback_mod))]
trait Callback {
fn callback(&self);
}

struct CallbackImpl;

impl Callback for CallbackImpl {
fn callback(&self) {
println!("Calling back...");
println!("> Hello World!");
}
}

#[wasmtime_trait(module(hello_mod))]
trait Hello {
fn run(&self);
}

fn main() -> Result<()> {
// Initialize.
println!("Initializing...");
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(&engine));

// Load binary.
println!("Loading binary...");
let binary = read("examples/hello.wasm")?;

// Compile.
println!("Compiling module...");
let module = HostRef::new(
Module::new(&store, &binary).map_err(|_| format_err!("> Error compiling module!"))?,
);

// Create external print functions.
println!("Creating callback...");
let callback_mod = HostRef::new(
wrap_wasmtime_module!(
&store, |_imports| CallbackImpl; module(callback_mod)
)
.map_err(|_| format_err!("> Error compiling callback module!"))?,
);
let callback_instance = Instance::new(&store, &callback_mod, &[])
.map_err(|_| format_err!("> Error instantiating callback module!"))?;
let hello_func = &callback_instance.exports()[0];

// Instantiate.
println!("Instantiating module...");
let imports = vec![hello_func.clone()];
let instance = HostRef::new(
Instance::new(&store, &module, imports.as_slice())
.map_err(|_| format_err!("> Error instantiating module!"))?,
);

// Extract export.
println!("Extracting export...");
let hello = map_to_wasmtime_trait!(instance; module(hello_mod));

// Call.
println!("Calling export...");
hello.run();

// Shut down.
println!("Shutting down...");
drop(store);

// All done.
println!("Done.");
Ok(())
}
76 changes: 76 additions & 0 deletions crates/api/examples/hello4.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//! Translation of hello example

use anyhow::{format_err, Result};
use std::fs::read;
use wasmtime_api::*;

#[macro_use]
extern crate wasmtime_bindings_macro;

struct Callback;

#[wasmtime_impl(module(callback_mod))]
impl Callback {
fn callback(&self) {
println!("Calling back...");
println!("> Hello World!");
}
}

#[wasmtime_trait(module(hello_mod))]
trait Hello {
fn run(&self);
}

fn main() -> Result<()> {
// Initialize.
println!("Initializing...");
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(&engine));

// Load binary.
println!("Loading binary...");
let binary = read("examples/hello.wasm")?;

// Compile.
println!("Compiling module...");
let module = HostRef::new(
Module::new(&store, &binary).map_err(|_| format_err!("> Error compiling module!"))?,
);

// Create external print functions.
println!("Creating callback...");
let callback_mod = HostRef::new(
wrap_wasmtime_module!(
&store, |_imports| Callback; module(callback_mod)
)
.map_err(|_| format_err!("> Error compiling callback module!"))?,
);
let callback_instance = Instance::new(&store, &callback_mod, &[])
.map_err(|_| format_err!("> Error instantiating callback module!"))?;
let hello_func = &callback_instance.exports()[0];

// Instantiate.
println!("Instantiating module...");
let imports = vec![hello_func.clone()];
let instance = HostRef::new(
Instance::new(&store, &module, imports.as_slice())
.map_err(|_| format_err!("> Error instantiating module!"))?,
);

// Extract export.
println!("Extracting export...");
let hello = map_to_wasmtime_trait!(&instance; module(hello_mod));

// Call.
println!("Calling export...");
hello.run();

// Shut down.
println!("Shutting down...");
drop(store);

// All done.
println!("Done.");
Ok(())
}
32 changes: 31 additions & 1 deletion crates/api/src/callable.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::r#ref::HostRef;
use crate::runtime::Store;
use crate::trampoline::generate_func_export;
use crate::trampoline::{generate_func_export, wrap_func_export};
use crate::trap::Trap;
use crate::types::FuncType;
use crate::values::Val;
Expand Down Expand Up @@ -151,3 +151,33 @@ impl WrappedCallable for NativeCallable {
&self.export
}
}

pub struct RawCallable {
instance: InstanceHandle,
export: Export,
}

impl RawCallable {
pub fn new(address: *const u8, signature: ir::Signature, store: &HostRef<Store>) -> Self {
let (instance, export) = wrap_func_export(
address as *const wasmtime_runtime::VMFunctionBody,
signature,
store,
)
.expect("wrapped export");
RawCallable { instance, export }
}
}

impl WrappedCallable for RawCallable {
fn call(&self, _params: &[Val], _results: &mut [Val]) -> Result<(), HostRef<Trap>> {
// TODO similar to WasmtimeFn::call
unimplemented!();
}
fn wasmtime_handle(&self) -> &InstanceHandle {
&self.instance
}
fn wasmtime_export(&self) -> &Export {
&self.export
}
}
19 changes: 18 additions & 1 deletion crates/api/src/externals.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::callable::{Callable, NativeCallable, WasmtimeFn, WrappedCallable};
use crate::callable::{Callable, NativeCallable, RawCallable, WasmtimeFn, WrappedCallable};
use crate::r#ref::{AnyRef, HostRef};
use crate::runtime::Store;
use crate::trampoline::{generate_global_export, generate_memory_export, generate_table_export};
Expand Down Expand Up @@ -135,6 +135,23 @@ impl Func {
}
}

pub fn from_raw(
store: &HostRef<Store>,
address: *const u8,
signature: cranelift_codegen::ir::Signature,
) -> Self {
let callable = RawCallable::new(address, signature.clone(), store);
let ty = FuncType::from_cranelift_signature(signature);
Func::from_wrapped(store, ty, Rc::new(callable))
}

pub fn raw_parts(&self) -> (wasmtime_runtime::InstanceHandle, wasmtime_runtime::Export) {
(
self.callable.wasmtime_handle().clone(),
self.callable.wasmtime_export().clone(),
)
}

pub fn r#type(&self) -> &FuncType {
&self.r#type
}
Expand Down
25 changes: 22 additions & 3 deletions crates/api/src/instance.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::context::Context;
use crate::externals::Extern;
use crate::module::Module;
use crate::module::{Module, ModuleCodeSource};
use crate::r#ref::HostRef;
use crate::runtime::Store;
use crate::trampoline::create_handle_for_trait;
use crate::{HashMap, HashSet};
use alloc::string::{String, ToString};
use alloc::{borrow::ToOwned, boxed::Box, rc::Rc, vec::Vec};
Expand Down Expand Up @@ -70,8 +71,26 @@ impl Instance {
.zip(externs.iter())
.map(|(i, e)| (i.module().to_string(), i.name().to_string(), e.clone()))
.collect::<Vec<_>>();
let (mut instance_handle, contexts) =
instantiate_in_context(module.borrow().binary(), imports, context, exports)?;

let (mut instance_handle, contexts) = match module.borrow().source() {
ModuleCodeSource::Binary(binary) => {
instantiate_in_context(binary, imports, context, exports)?
}
ModuleCodeSource::Factory {
state_builder,
addresses,
} => {
let exports = module
.borrow()
.exports()
.iter()
.map(|e| e.clone())
.zip(addresses.clone().into_iter())
.collect::<Vec<_>>();
let handle = create_handle_for_trait(&**state_builder, &exports, externs, &store)?;
(handle, HashSet::new())
}
};

let exports = {
let module = module.borrow();
Expand Down
3 changes: 2 additions & 1 deletion crates/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod callable;
mod context;
mod externals;
mod instance;
mod r#macro;
mod module;
mod r#ref;
mod runtime;
Expand All @@ -21,7 +22,7 @@ extern crate alloc;
pub use crate::callable::Callable;
pub use crate::externals::*;
pub use crate::instance::Instance;
pub use crate::module::Module;
pub use crate::module::{HandleStateBuilder, Module};
pub use crate::r#ref::{AnyRef, HostInfo, HostRef};
pub use crate::runtime::{Config, Engine, Store};
pub use crate::trap::Trap;
Expand Down
Loading