From 2ff1e7874a8d634710217988936023f18fb9bc8d Mon Sep 17 00:00:00 2001 From: Valtameri Sieluna Date: Sun, 19 Jan 2025 04:35:17 +0000 Subject: [PATCH 1/3] Try to enhance no std support --- Cargo.toml | 2 ++ src/function.rs | 4 +++- src/helper.rs | 4 ++-- src/host_function.rs | 5 +++-- src/instance.rs | 1 + src/lib.rs | 38 +++++++++++++++++++++++++------------- src/module.rs | 31 ++++++++++++++----------------- src/runtime.rs | 17 +++++++++++------ src/value.rs | 22 ++++++++++++---------- src/wasi_context.rs | 3 ++- 10 files changed, 75 insertions(+), 52 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6c2aa3b..a4f27bb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] diff --git a/src/function.rs b/src/function.rs index 9dabca4..2419348 100644 --- a/src/function.rs +++ b/src/function.rs @@ -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, diff --git a/src/helper.rs b/src/helper.rs index 71d0781..4698afe 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -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; diff --git a/src/host_function.rs b/src/host_function.rs index 42bc75b..ea78ea9 100644 --- a/src/host_function.rs +++ b/src/host_function.rs @@ -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; diff --git a/src/instance.rs b/src/instance.rs index 2e170a7..b14e94b 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -8,6 +8,7 @@ #![allow(unused_variables)] +use alloc::string::String; use core::{ffi::c_char, marker::PhantomData}; use wamr_sys::{ diff --git a/src/lib.rs b/src/lib.rs index 2383a59..bfcf873 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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"); //! @@ -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 @@ -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)?; //! @@ -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; @@ -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), @@ -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), @@ -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 for RuntimeError { - fn from(e: io::Error) -> Self { +#[cfg(any(test, feature = "std"))] +impl From for RuntimeError { + fn from(e: std::io::Error) -> Self { RuntimeError::WasmFileFSError(e) } } diff --git a/src/module.rs b/src/module.rs index 68cbba5..258d352 100644 --- a/src/module.rs +++ b/src/module.rs @@ -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> { @@ -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 { + #[cfg(any(test, feature = "std"))] + pub fn from_file(runtime: &'runtime Runtime, wasm_file: &std::path::Path) -> Result { + use std::{fs::File, io::Read}; + let name = wasm_file.file_name().unwrap().to_str().unwrap(); let mut wasm_file = File::open(wasm_file)?; @@ -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] diff --git a/src/runtime.rs b/src/runtime.rs index 2109fd0..9319ad0 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -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, @@ -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 + 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 { diff --git a/src/value.rs b/src/value.rs index ce48ae5..3c8c727 100644 --- a/src/value.rs +++ b/src/value.rs @@ -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, @@ -22,23 +24,23 @@ impl WasmValue { vec![] } WasmValue::I32(value) => { - let in_u32_array = unsafe { std::mem::transmute::(value) }; + let in_u32_array = unsafe { core::mem::transmute::(value) }; vec![in_u32_array[0]] } WasmValue::I64(value) => { - let in_u32_array = unsafe { std::mem::transmute::(value) }; + let in_u32_array = unsafe { core::mem::transmute::(value) }; vec![in_u32_array[0], in_u32_array[1]] } WasmValue::F32(value) => { - let in_u32_array = unsafe { std::mem::transmute::(value) }; + let in_u32_array = unsafe { core::mem::transmute::(value) }; vec![in_u32_array[0]] } WasmValue::F64(value) => { - let in_u32_array = unsafe { std::mem::transmute::(value) }; + let in_u32_array = unsafe { core::mem::transmute::(value) }; vec![in_u32_array[0], in_u32_array[1]] } WasmValue::V128(value) => { - let in_u32_array = unsafe { std::mem::transmute::(value) }; + let in_u32_array = unsafe { core::mem::transmute::(value) }; vec![ in_u32_array[0], in_u32_array[1], @@ -51,27 +53,27 @@ impl WasmValue { pub fn decode_to_i32(binary: Vec) -> 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) -> 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) -> 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) -> 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) -> 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) }) } } diff --git a/src/wasi_context.rs b/src/wasi_context.rs index ff2cb6b..3dcf030 100644 --- a/src/wasi_context.rs +++ b/src/wasi_context.rs @@ -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 { From 4bfb513155a7180b98847524b6c8fb71a53dc900 Mon Sep 17 00:00:00 2001 From: Valtameri Sieluna Date: Wed, 22 Jan 2025 15:54:18 +0000 Subject: [PATCH 2/3] Revert sample and simplified the condition --- src/lib.rs | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index bfcf873..256c49c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,6 +64,8 @@ //! The rust code to call the function would be: //! //! ``` +//! use std::path::PathBuf; +//! //! use wamr_rust_sdk::{ //! runtime::Runtime, module::Module, instance::Instance, function::Function, //! value::WasmValue, RuntimeError @@ -72,7 +74,7 @@ //! fn main() -> Result<(), RuntimeError> { //! let runtime = Runtime::new()?; //! -//! let mut d = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); +//! let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); //! d.push("resources/test"); //! d.push("gcd_wasm32_wasi.wasm"); //! @@ -105,13 +107,8 @@ //! 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 std::ffi::c_void; +//! use std::path::PathBuf; //! //! use wamr_rust_sdk::{ //! runtime::Runtime, module::Module, instance::Instance, function::Function, @@ -128,9 +125,10 @@ //! .register_host_function("extra", extra as *mut c_void) //! .build()?; //! -//! -//! 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 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 instance = Instance::new(&runtime, &module, 1024 * 64)?; //! @@ -145,7 +143,7 @@ //! ``` //! -#![cfg_attr(all(not(test), not(feature = "std")), no_std)] +#![cfg_attr(not(feature = "std"), no_std)] #[macro_use] extern crate alloc; @@ -176,7 +174,7 @@ pub enum RuntimeError { /// Runtime initialization error. InitializationFailure, /// file operation error. usually while loading(compilation) a .wasm - #[cfg(any(test, feature = "std"))] + #[cfg(feature = "std")] WasmFileFSError(std::io::Error), /// A compilation error. usually means that the .wasm file is invalid CompilationError(String), @@ -193,7 +191,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"))] + #[cfg(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), @@ -210,14 +208,14 @@ 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"))] + #[cfg(feature = "std")] RuntimeError::WasmFileFSError(e) => Some(e), _ => None, } } } -#[cfg(any(test, feature = "std"))] +#[cfg(feature = "std")] impl From for RuntimeError { fn from(e: std::io::Error) -> Self { RuntimeError::WasmFileFSError(e) From b9f37d6b5dcd3a0482ceaffa9dd5b6d6a11bb046 Mon Sep 17 00:00:00 2001 From: Valtameri Sieluna Date: Fri, 24 Jan 2025 00:49:46 +0200 Subject: [PATCH 3/3] Remove a unused cfg --- src/module.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/module.rs b/src/module.rs index 258d352..98bb000 100644 --- a/src/module.rs +++ b/src/module.rs @@ -38,7 +38,7 @@ 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. - #[cfg(any(test, feature = "std"))] + #[cfg(feature = "std")] pub fn from_file(runtime: &'runtime Runtime, wasm_file: &std::path::Path) -> Result { use std::{fs::File, io::Read};