Skip to content

Implement auto host function by macro #104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
11 changes: 10 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 9 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

[workspace]
members = ["crates/wamr-sys"]
members = [
"crates/wamr-macros",
"crates/wamr-sys",
]
exclude = [
"examples/wasi-hello",
"resources/test/gcd",
"resources/test/add-extra",
".devcontainer",
".github",
"examples/modules",
"tests/fixtures",
]
resolver = "2"

Expand All @@ -29,6 +29,7 @@ categories = ["api-bindings", "wasm"]
keywords = ["api-bindings", "wasm", "webassembly"]

[dependencies]
wamr-macros = { path = "crates/wamr-macros", version = "1.0.0", optional = true }
wamr-sys = { path = "crates/wamr-sys", version = "1.0.0" }

[target.'cfg( target_os = "espidf" )'.dependencies]
Expand All @@ -39,6 +40,8 @@ bindings_header = "./crates/wamr-sys/wasm-micro-runtime/core/iwasm/include/wasm_
component_dirs = ["./crates/wamr-sys/wasm-micro-runtime/build-scripts/esp-idf"]

[features]
default = ["macros"]
macros = ["wamr-macros"]
custom-section = ["wamr-sys/custom-section"]
dump-call-stack = ["wamr-sys/dump-call-stack"]
esp-idf = ["esp-idf-sys", "wamr-sys/esp-idf"]
Expand Down
45 changes: 29 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ This crate has similar concepts to the
#### WAMR private concepts

- *loading linking* instead of *instantiation linking*. *instantiation linking* is
used in Wasm JS API and Wasm C API. It means that every instance has its own, maybe
variant, imports. But *loading linking* means that all instances share the same *imports*.
used in Wasm JS API and Wasm C API. It means that every instance has its own, maybe
variant, imports. But *loading linking* means that all instances share the same *imports*.

- *RuntimeArg*. Control runtime behavior.
- *running mode*.
Expand All @@ -50,7 +50,22 @@ variant, imports. But *loading linking* means that all instances share the same

### Examples

#### Example: to run a wasm32-wasi .wasm
Under the [`examples`](examples) contains a number of examples showcasing various
capabilities of the `wamr-rust-sdk` crate.

All examples can be executed with:

```sh
cargo run --example $name
```

A good starting point for the examples would be [`examples/basic`](examples/basic.rs).

If you've got an example you'd like to see here, please feel free to open an
issue. Otherwise if you've got an example you'd like to add, please feel free
to make a PR!

#### Quick Start: to run a wasm32-wasi .wasm

*wasm32-wasi* is a most common target for Wasm. It means that the .wasm is compiled with
`cargo build --target wasm32-wasi` or `wasi-sdk/bin/clang --target wasm32-wasi`.
Expand All @@ -65,13 +80,12 @@ use wamr_rust_sdk::{
runtime::Runtime, module::Module, instance::Instance, function::Function,
value::WasmValue, RuntimeError
};
use std::path::PathBuf;

fn main() -> Result<(), RuntimeError> {
let runtime = Runtime::new()?;

let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("resources/test");
let mut d = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests/fixtures");
d.push("gcd_wasm32_wasi.wasm");

let module = Module::from_file(&runtime, d.as_path())?;
Expand All @@ -88,7 +102,7 @@ fn main() -> Result<(), RuntimeError> {
}
```

#### Example: more configuration for runtime.
#### Quick Start: more configuration for runtime.

With more configuration, runtime is capable to run .wasm with variant features, like
- Wasm without WASI requirement. Usually, it means that the .wasm is compiled with `-nostdlib`
Expand All @@ -104,25 +118,25 @@ The rust code to call the *add* function is like this:

```rust
use wamr_rust_sdk::{
runtime::Runtime, module::Module, instance::Instance, function::Function,
value::WasmValue, RuntimeError
function::Function, generate_host_function, instance::Instance, module::Module,
runtime::Runtime, value::WasmValue, RuntimeError
};
use std::path::PathBuf;
use std::ffi::c_void;

extern "C" fn extra() -> i32 {
#[generate_host_function]
fn extra() -> i32 {
100
}

fn main() -> Result<(), RuntimeError> {
let runtime = Runtime::builder()
.use_system_allocator()
.register_host_function("extra", extra as *mut c_void)
.register_host_function(extra)
.build()?;

let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("resources/test");
let mut d = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests/fixtures");
d.push("add_extra_wasm32_wasi.wasm");

let module = Module::from_file(&runtime, d.as_path())?;

let instance = Instance::new(&runtime, &module, 1024 * 64)?;
Expand All @@ -136,4 +150,3 @@ fn main() -> Result<(), RuntimeError> {
Ok(())
}
```

13 changes: 13 additions & 0 deletions crates/wamr-macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "wamr-macros"
version = "1.0.0"
edition = "2021"
license = "Apache-2.0 WITH LLVM-exception"
authors = ["The WAMR Project Developers"]

[lib]
proc-macro = true

[dependencies]
quote = "1"
syn = { version = "2", features = ["full"] }
120 changes: 120 additions & 0 deletions crates/wamr-macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{meta, parse_macro_input, FnArg, ItemFn, LitStr, ReturnType, Type};

#[proc_macro_attribute]
pub fn generate_host_function(args: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as ItemFn);

let mut name_override: Option<LitStr> = None;
let mut signature_override: Option<LitStr> = None;

let args_parser = meta::parser(|meta| {
if meta.path.is_ident("name") {
name_override = Some(meta.value()?.parse()?);
} else if meta.path.is_ident("signature") {
signature_override = Some(meta.value()?.parse()?);
} else {
return Err(meta.error("unsupported generate host function property."));
}
Ok(())
});

parse_macro_input!(args with args_parser);

let function_ident = &input.sig.ident;
let function_vis = &input.vis;
let function_inputs = &input.sig.inputs;
let function_output = &input.sig.output;
let function_block = &input.block;

let function_name = name_override
.map(|n| n.value())
.unwrap_or_else(|| function_ident.to_string());

let signature = signature_override.map(|s| s.value()).unwrap_or_else(|| {
let mut param_signature = String::new();
let mut buffer_flag = false;

for arg in function_inputs.iter() {
if let FnArg::Typed(typed) = arg {
let sig_char = get_signature_for_type(&typed.ty)
.unwrap_or_else(|| panic!("Unsupported parameter type."));

if sig_char == '~' && !buffer_flag {
panic!("`~` must follow `*` (buffer address).");
}

buffer_flag = sig_char == '*';
param_signature.push(sig_char);
}
}

let return_signature = match function_output {
ReturnType::Default => String::new(),
ReturnType::Type(_, ret_type) => get_signature_for_type(ret_type)
.unwrap_or_else(|| panic!("Unsupported return type."))
.to_string(),
};

format!("({}){}", param_signature, return_signature)
});

let c_function_ident = syn::Ident::new(&format!("{}_c", function_ident), function_ident.span());

let expanded = quote! {
#function_vis extern "C" fn #c_function_ident(exec_env: wamr_rust_sdk::sys::wasm_exec_env_t, #function_inputs) #function_output #function_block

#function_vis fn #function_ident() -> wamr_rust_sdk::host_function::HostFunction {
wamr_rust_sdk::host_function::HostFunction::new(
#function_name,
#c_function_ident as *mut core::ffi::c_void,
#signature
)
}
};

TokenStream::from(expanded)
}

fn get_signature_for_type(ty: &Type) -> Option<char> {
match ty {
Type::Path(type_path) => {
let type_name = type_path.path.segments.last()?.ident.to_string();
match type_name.as_str() {
"i32" | "u32" => Some('i'),
"i64" | "u64" => Some('I'),
"f32" => Some('f'),
"f64" => Some('F'),
"usize" => Some('i'),
_ => None,
}
}
Type::Reference(type_ref) => match &*type_ref.elem {
Type::Path(type_path) => {
let type_name = type_path.path.segments.last()?.ident.to_string();
if type_name == "str" {
Some('$')
} else {
None
}
}
_ => None,
},
Type::Ptr(type_ptr) => {
if let Type::Path(type_path) = &*type_ptr.elem {
let type_name = type_path.path.segments.last()?.ident.to_string();
if type_name == "u8" {
Some('*')
} else {
None
}
} else {
None
}
}
_ => None,
}
}
Loading
Loading