Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -39,6 +39,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 = ["std"]
std = ["wamr-sys/std"]
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
4 changes: 3 additions & 1 deletion src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
//! an exported wasm function.
//! get one via `Function::find_export_func()`

use std::{ffi::CString, marker::PhantomData};
use alloc::{ffi::CString, vec::Vec};
use core::marker::PhantomData;

use wamr_sys::{
wasm_exec_env_t, wasm_func_get_result_count, wasm_func_get_result_types, wasm_function_inst_t,
wasm_runtime_call_wasm, wasm_runtime_get_exception, wasm_runtime_get_exec_env_singleton,
Expand Down
4 changes: 2 additions & 2 deletions src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/

use std::ffi::{c_char, CStr};
use std::string::String;
use alloc::{string::{String, ToString}, vec::Vec};
use core::ffi::{c_char, CStr};

pub const DEFAULT_ERROR_BUF_SIZE: usize = 128;

Expand Down
5 changes: 3 additions & 2 deletions src/host_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
*/

/// This is a wrapper of a host defined(Rust) function.
use std::ffi::{c_void, CString};
use std::ptr;

use alloc::{ffi::CString, vec::Vec};
use core::{ffi::c_void, ptr};

use wamr_sys::NativeSymbol;

Expand Down
1 change: 1 addition & 0 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#![allow(unused_variables)]

use alloc::string::String;
use core::{ffi::c_char, marker::PhantomData};

use wamr_sys::{
Expand Down
38 changes: 25 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,11 @@
//! 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"));
//! let mut d = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! d.push("resources/test");
//! d.push("gcd_wasm32_wasi.wasm");
//!
Expand Down Expand Up @@ -106,12 +105,18 @@
//! The rust code to call the *add* function is like this:
//!
//! ```
//! #![no_std]
//!
//! #[macro_use]
//! extern crate alloc;
//!
//! use alloc::vec::Vec;
//! use core::ffi::c_void;
//!
//! use wamr_rust_sdk::{
//! runtime::Runtime, module::Module, instance::Instance, function::Function,
//! value::WasmValue, RuntimeError
//! };
//! use std::path::PathBuf;
//! use std::ffi::c_void;
//!
//! extern "C" fn extra() -> i32 {
//! 100
Expand All @@ -123,10 +128,9 @@
//! .register_host_function("extra", extra as *mut c_void)
//! .build()?;
//!
//! let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! d.push("resources/test");
//! d.push("add_extra_wasm32_wasi.wasm");
//! let module = Module::from_file(&runtime, d.as_path())?;
//!
//! let bytes = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/test/add_extra_wasm32_wasi.wasm"));
//! let module = Module::from_vec(&runtime, Vec::from(bytes), "add_extra")?;
//!
//! let instance = Instance::new(&runtime, &module, 1024 * 64)?;
//!
Expand All @@ -141,9 +145,13 @@
//! ```
//!

use std::error;
use std::fmt;
use std::io;
#![cfg_attr(all(not(test), not(feature = "std")), no_std)]

#[macro_use]
extern crate alloc;

use alloc::string::String;
use core::{error, fmt};
pub use wamr_sys as sys;

pub mod function;
Expand All @@ -168,6 +176,7 @@ pub enum RuntimeError {
/// Runtime initialization error.
InitializationFailure,
/// file operation error. usually while loading(compilation) a .wasm
#[cfg(any(test, feature = "std"))]
WasmFileFSError(std::io::Error),
/// A compilation error. usually means that the .wasm file is invalid
CompilationError(String),
Expand All @@ -184,6 +193,7 @@ impl fmt::Display for RuntimeError {
match self {
RuntimeError::NotImplemented => write!(f, "Not implemented"),
RuntimeError::InitializationFailure => write!(f, "Runtime initialization failure"),
#[cfg(any(test, feature = "std"))]
RuntimeError::WasmFileFSError(e) => write!(f, "Wasm file operation error: {}", e),
RuntimeError::CompilationError(e) => write!(f, "Wasm compilation error: {}", e),
RuntimeError::InstantiationFailure(e) => write!(f, "Wasm instantiation failure: {}", e),
Expand All @@ -200,14 +210,16 @@ impl fmt::Display for RuntimeError {
impl error::Error for RuntimeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
#[cfg(any(test, feature = "std"))]
RuntimeError::WasmFileFSError(e) => Some(e),
_ => None,
}
}
}

impl From<io::Error> for RuntimeError {
fn from(e: io::Error) -> Self {
#[cfg(any(test, feature = "std"))]
impl From<std::io::Error> for RuntimeError {
fn from(e: std::io::Error) -> Self {
RuntimeError::WasmFileFSError(e)
}
}
31 changes: 14 additions & 17 deletions src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,22 @@
*/

//! .wasm compiled, in-memory representation
//! get one via `Module::from_file()` or `Module::from_buf()`
//! get one via `Module::from_file()` or `Module::from_vec()`

use alloc::{ffi::CString, string::String, vec::Vec};
use core::{ffi::c_char, marker::PhantomData, ptr};

use crate::{
helper::error_buf_to_string, helper::DEFAULT_ERROR_BUF_SIZE, runtime::Runtime,
wasi_context::WasiCtx, RuntimeError,
};
use core::marker::PhantomData;
use std::{
ffi::{c_char, CString},
fs::File,
io::Read,
path::Path,
ptr,
string::String,
vec::Vec,
};
use wamr_sys::{
wasm_module_t, wasm_runtime_load, wasm_runtime_set_module_name,
wasm_runtime_set_wasi_addr_pool, wasm_runtime_set_wasi_args,
wasm_runtime_set_wasi_ns_lookup_pool, wasm_runtime_unload,
};

use crate::{
helper::error_buf_to_string, helper::DEFAULT_ERROR_BUF_SIZE, runtime::Runtime,
wasi_context::WasiCtx, RuntimeError,
};

#[allow(dead_code)]
#[derive(Debug)]
pub struct Module<'runtime> {
Expand All @@ -44,7 +38,10 @@ impl<'runtime> Module<'runtime> {
///
/// If the file does not exist or the file cannot be read, an `RuntimeError::WasmFileFSError` will be returned.
/// If the wasm file is not a valid wasm file, an `RuntimeError::CompilationError` will be returned.
pub fn from_file(runtime: &'runtime Runtime, wasm_file: &Path) -> Result<Self, RuntimeError> {
#[cfg(any(test, feature = "std"))]
pub fn from_file(runtime: &'runtime Runtime, wasm_file: &std::path::Path) -> Result<Self, RuntimeError> {
use std::{fs::File, io::Read};

let name = wasm_file.file_name().unwrap().to_str().unwrap();
let mut wasm_file = File::open(wasm_file)?;

Expand Down Expand Up @@ -202,7 +199,7 @@ impl Drop for Module<'_> {
mod tests {
use super::*;
use crate::{helper::cstr_to_string, runtime::Runtime, wasi_context::WasiCtxBuilder};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use wamr_sys::wasm_runtime_get_module_name;

#[test]
Expand Down
17 changes: 11 additions & 6 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
//! Every process should have only one instance of this runtime by call
//! `Runtime::new()` or `Runtime::builder().build()` once.

use std::ffi::c_void;
use alloc::vec::Vec;
use core::ffi::c_void;

use wamr_sys::{
mem_alloc_type_t_Alloc_With_Pool, mem_alloc_type_t_Alloc_With_System_Allocator,
Expand Down Expand Up @@ -68,15 +69,19 @@ pub struct RuntimeBuilder {
/// Can't build() until config allocator mode
impl Default for RuntimeBuilder {
fn default() -> Self {
let args = RuntimeInitArgs::default();
RuntimeBuilder {
args,
host_functions: HostFunctionList::new("host"),
}
Self::new("host")
}
}

impl RuntimeBuilder {
/// create a named module runtime builder
Copy link
Contributor Author

@Sieluna Sieluna Jan 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A new entrance for builder, make import module with variant names easier.

pub fn new(name: &str) -> Self {
Self {
args: RuntimeInitArgs::default(),
host_functions: HostFunctionList::new(name),
}
}

/// system allocator mode
/// allocate memory from system allocator for runtime consumed memory
pub fn use_system_allocator(mut self) -> RuntimeBuilder {
Expand Down
22 changes: 12 additions & 10 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

//! a wasm value. Always used as function parameters and results

use alloc::vec::Vec;

#[derive(Debug, PartialEq)]
pub enum WasmValue {
Void,
Expand All @@ -22,23 +24,23 @@ impl WasmValue {
vec![]
}
WasmValue::I32(value) => {
let in_u32_array = unsafe { std::mem::transmute::<i32, [u32; 1]>(value) };
let in_u32_array = unsafe { core::mem::transmute::<i32, [u32; 1]>(value) };
vec![in_u32_array[0]]
}
WasmValue::I64(value) => {
let in_u32_array = unsafe { std::mem::transmute::<i64, [u32; 2]>(value) };
let in_u32_array = unsafe { core::mem::transmute::<i64, [u32; 2]>(value) };
vec![in_u32_array[0], in_u32_array[1]]
}
WasmValue::F32(value) => {
let in_u32_array = unsafe { std::mem::transmute::<f32, [u32; 1]>(value) };
let in_u32_array = unsafe { core::mem::transmute::<f32, [u32; 1]>(value) };
vec![in_u32_array[0]]
}
WasmValue::F64(value) => {
let in_u32_array = unsafe { std::mem::transmute::<f64, [u32; 2]>(value) };
let in_u32_array = unsafe { core::mem::transmute::<f64, [u32; 2]>(value) };
vec![in_u32_array[0], in_u32_array[1]]
}
WasmValue::V128(value) => {
let in_u32_array = unsafe { std::mem::transmute::<i128, [u32; 4]>(value) };
let in_u32_array = unsafe { core::mem::transmute::<i128, [u32; 4]>(value) };
vec![
in_u32_array[0],
in_u32_array[1],
Expand All @@ -51,27 +53,27 @@ impl WasmValue {

pub fn decode_to_i32(binary: Vec<u32>) -> WasmValue {
let binary: [u32; 1] = [binary[0]];
WasmValue::I32(unsafe { std::mem::transmute::<[u32; 1], i32>(binary) })
WasmValue::I32(unsafe { core::mem::transmute::<[u32; 1], i32>(binary) })
}

pub fn decode_to_f32(binary: Vec<u32>) -> WasmValue {
let binary: [u32; 1] = [binary[0]];
WasmValue::F32(unsafe { std::mem::transmute::<[u32; 1], f32>(binary) })
WasmValue::F32(unsafe { core::mem::transmute::<[u32; 1], f32>(binary) })
}

pub fn decode_to_i64(binary: Vec<u32>) -> WasmValue {
let binary: [u32; 2] = [binary[0], binary[1]];
WasmValue::I64(unsafe { std::mem::transmute::<[u32; 2], i64>(binary) })
WasmValue::I64(unsafe { core::mem::transmute::<[u32; 2], i64>(binary) })
}

pub fn decode_to_f64(binary: Vec<u32>) -> WasmValue {
let binary: [u32; 2] = [binary[0], binary[1]];
WasmValue::F64(unsafe { std::mem::transmute::<[u32; 2], f64>(binary) })
WasmValue::F64(unsafe { core::mem::transmute::<[u32; 2], f64>(binary) })
}

pub fn decode_to_v128(binary: Vec<u32>) -> WasmValue {
let binary: [u32; 4] = [binary[0], binary[1], binary[2], binary[3]];
WasmValue::V128(unsafe { std::mem::transmute::<[u32; 4], i128>(binary) })
WasmValue::V128(unsafe { core::mem::transmute::<[u32; 4], i128>(binary) })
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/wasi_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

//! prepare wasi context

use std::{ffi::c_char, ffi::CString, vec::Vec};
use alloc::{ffi::CString, vec::Vec};
use core::ffi::c_char;

#[derive(Debug, Default)]
struct PreOpen {
Expand Down
Loading