Skip to content
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

[Refactor] Update PluginModule and WasiModule in wasmedge-sys #42

Merged
merged 9 commits into from
Jul 28, 2023
6 changes: 3 additions & 3 deletions crates/wasmedge-sys/src/async/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2341,7 +2341,7 @@ impl async_wasi::snapshots::common::memory::Memory for Memory {
mod tests {
use super::*;
use crate::{
r#async::fiber::AsyncState, Config, Executor, ImportObject, Loader, Store, Validator,
r#async::fiber::AsyncState, Config, Executor, Loader, Store, Validator, WasiInstance,
};

#[tokio::test]
Expand All @@ -2368,8 +2368,8 @@ mod tests {
let async_wasi_module = result.unwrap();

// register async_wasi module into the store
let wasi_import = ImportObject::AsyncWasi(async_wasi_module);
let result = executor.register_import_object(&mut store, &wasi_import);
let wasi_import = WasiInstance::AsyncWasi(async_wasi_module);
let result = executor.register_wasi_instance(&mut store, &wasi_import);
assert!(result.is_ok());

let wasm_file = std::env::current_dir()
Expand Down
26 changes: 13 additions & 13 deletions crates/wasmedge-sys/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use super::ffi;
use crate::r#async::fiber::{AsyncState, FiberFuture};
use crate::{
instance::module::InnerInstance, types::WasmEdgeString, utils::check, Config, Engine, FuncRef,
Function, ImportModule, ImportObject, Instance, Module, Statistics, Store, WasmEdgeResult,
Function, ImportModule, Instance, Module, Statistics, Store, WasiInstance, WasmEdgeResult,
WasmValue,
};
use parking_lot::Mutex;
Expand Down Expand Up @@ -57,33 +57,33 @@ impl Executor {
}
}

/// Registers and instantiates a WasmEdge [import object](crate::ImportObject) into a [store](crate::Store).
/// Registers and instantiates the given [WASI instance](crate::WasiInstance) into a [store](crate::Store).
///
/// # Arguments
///
/// * `store` - The target [store](crate::Store), into which the given [import object](crate::ImportObject) is registered.
///
/// * `import` - The WasmEdge [import object](crate::ImportObject) to be registered.
/// * `instance` - The [WASI instance](crate::WasiInstance) to be registered.
///
/// # Error
///
/// If fail to register the given [import object](crate::ImportObject), then an error is returned.
pub fn register_import_object(
/// If fail to register the given [WASI instance](crate::WasiInstance), then an error is returned.
pub fn register_wasi_instance(
&mut self,
store: &Store,
import: &ImportObject,
instance: &WasiInstance,
) -> WasmEdgeResult<()> {
match import {
match instance {
#[cfg(not(feature = "async"))]
ImportObject::Wasi(import) => unsafe {
WasiInstance::Wasi(import) => unsafe {
check(ffi::WasmEdge_ExecutorRegisterImport(
self.inner.0,
store.inner.0,
import.inner.0 as *const _,
))?;
},
#[cfg(all(feature = "async", target_os = "linux"))]
ImportObject::AsyncWasi(import) => unsafe {
WasiInstance::AsyncWasi(import) => unsafe {
check(ffi::WasmEdge_ExecutorRegisterImport(
self.inner.0,
store.inner.0,
Expand Down Expand Up @@ -625,8 +625,8 @@ mod tests {
assert!(result.is_ok());
let async_wasi_module = result.unwrap();

let wasi_import = ImportObject::AsyncWasi(async_wasi_module);
let result = executor.register_import_object(&mut store, &wasi_import);
let wasi_import = WasiInstance::AsyncWasi(async_wasi_module);
let result = executor.register_wasi_instance(&mut store, &wasi_import);
assert!(result.is_ok());

// register async_wasi module into the store
Expand Down Expand Up @@ -706,8 +706,8 @@ mod tests {
let async_wasi_module = result.unwrap();

// register async_wasi module into the store
let wasi_import = ImportObject::AsyncWasi(async_wasi_module);
let result = executor.register_import_object(&mut store, &wasi_import);
let wasi_import = WasiInstance::AsyncWasi(async_wasi_module);
let result = executor.register_wasi_instance(&mut store, &wasi_import);
assert!(result.is_ok());

let ty = FuncType::create([], [])?;
Expand Down
262 changes: 11 additions & 251 deletions crates/wasmedge-sys/src/instance/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,11 @@ impl WasiModule {
}
}

/// Returns the name of the module instance.
pub fn name(&self) -> &str {
"wasi_snapshot_preview1"
}

/// Initializes the WASI host module with the given parameters.
///
/// # Arguments
Expand Down Expand Up @@ -712,251 +717,6 @@ impl WasiModule {
self.inner.0 as *const _
}
}
#[cfg(not(feature = "async"))]
impl AsInstance for WasiModule {
fn get_func(&self, name: impl AsRef<str>) -> WasmEdgeResult<Function> {
let func_name: WasmEdgeString = name.as_ref().into();
let func_ctx = unsafe {
ffi::WasmEdge_ModuleInstanceFindFunction(self.inner.0 as *const _, func_name.as_raw())
};
match func_ctx.is_null() {
true => Err(Box::new(WasmEdgeError::Instance(
InstanceError::NotFoundFunc(name.as_ref().to_string()),
))),
false => Ok(Function {
inner: Arc::new(Mutex::new(InnerFunc(func_ctx))),
registered: true,
}),
}
}

fn get_table(&self, name: impl AsRef<str>) -> WasmEdgeResult<Table> {
let table_name: WasmEdgeString = name.as_ref().into();
let ctx = unsafe {
ffi::WasmEdge_ModuleInstanceFindTable(self.inner.0 as *const _, table_name.as_raw())
};
match ctx.is_null() {
true => Err(Box::new(WasmEdgeError::Instance(
InstanceError::NotFoundTable(name.as_ref().to_string()),
))),
false => Ok(Table {
inner: Arc::new(Mutex::new(InnerTable(ctx))),
registered: true,
}),
}
}

fn get_memory(&self, name: impl AsRef<str>) -> WasmEdgeResult<Memory> {
let mem_name: WasmEdgeString = name.as_ref().into();
let ctx = unsafe {
ffi::WasmEdge_ModuleInstanceFindMemory(self.inner.0 as *const _, mem_name.as_raw())
};
match ctx.is_null() {
true => Err(Box::new(WasmEdgeError::Instance(
InstanceError::NotFoundMem(name.as_ref().to_string()),
))),
false => Ok(Memory {
inner: Arc::new(Mutex::new(InnerMemory(ctx))),
registered: true,
}),
}
}

fn get_global(&self, name: impl AsRef<str>) -> WasmEdgeResult<Global> {
let global_name: WasmEdgeString = name.as_ref().into();
let ctx = unsafe {
ffi::WasmEdge_ModuleInstanceFindGlobal(self.inner.0 as *const _, global_name.as_raw())
};
match ctx.is_null() {
true => Err(Box::new(WasmEdgeError::Instance(
InstanceError::NotFoundGlobal(name.as_ref().to_string()),
))),
false => Ok(Global {
inner: Arc::new(Mutex::new(InnerGlobal(ctx))),
registered: true,
}),
}
}

/// Returns the length of the exported [function instances](crate::Function) in this module instance.
fn func_len(&self) -> u32 {
unsafe { ffi::WasmEdge_ModuleInstanceListFunctionLength(self.inner.0) }
}

/// Returns the names of the exported [function instances](crate::Function) in this module instance.
fn func_names(&self) -> Option<Vec<String>> {
let len_func_names = self.func_len();
match len_func_names > 0 {
true => {
let mut func_names = Vec::with_capacity(len_func_names as usize);
unsafe {
ffi::WasmEdge_ModuleInstanceListFunction(
self.inner.0,
func_names.as_mut_ptr(),
len_func_names,
);
func_names.set_len(len_func_names as usize);
}

let names = func_names
.into_iter()
.map(|x| x.into())
.collect::<Vec<String>>();
Some(names)
}
false => None,
}
}

/// Returns the length of the exported [table instances](crate::Table) in this module instance.
fn table_len(&self) -> u32 {
unsafe { ffi::WasmEdge_ModuleInstanceListTableLength(self.inner.0) }
}

/// Returns the names of the exported [table instances](crate::Table) in this module instance.
fn table_names(&self) -> Option<Vec<String>> {
let len_table_names = self.table_len();
match len_table_names > 0 {
true => {
let mut table_names = Vec::with_capacity(len_table_names as usize);
unsafe {
ffi::WasmEdge_ModuleInstanceListTable(
self.inner.0,
table_names.as_mut_ptr(),
len_table_names,
);
table_names.set_len(len_table_names as usize);
}

let names = table_names
.into_iter()
.map(|x| x.into())
.collect::<Vec<String>>();
Some(names)
}
false => None,
}
}

/// Returns the length of the exported [memory instances](crate::Memory) in this module instance.
fn mem_len(&self) -> u32 {
unsafe { ffi::WasmEdge_ModuleInstanceListMemoryLength(self.inner.0) }
}

/// Returns the names of all exported [memory instances](crate::Memory) in this module instance.
fn mem_names(&self) -> Option<Vec<String>> {
let len_mem_names = self.mem_len();
match len_mem_names > 0 {
true => {
let mut mem_names = Vec::with_capacity(len_mem_names as usize);
unsafe {
ffi::WasmEdge_ModuleInstanceListMemory(
self.inner.0,
mem_names.as_mut_ptr(),
len_mem_names,
);
mem_names.set_len(len_mem_names as usize);
}

let names = mem_names
.into_iter()
.map(|x| x.into())
.collect::<Vec<String>>();
Some(names)
}
false => None,
}
}

/// Returns the length of the exported [global instances](crate::Global) in this module instance.
fn global_len(&self) -> u32 {
unsafe { ffi::WasmEdge_ModuleInstanceListGlobalLength(self.inner.0) }
}

/// Returns the names of the exported [global instances](crate::Global) in this module instance.
fn global_names(&self) -> Option<Vec<String>> {
let len_global_names = self.global_len();
match len_global_names > 0 {
true => {
let mut global_names = Vec::with_capacity(len_global_names as usize);
unsafe {
ffi::WasmEdge_ModuleInstanceListGlobal(
self.inner.0,
global_names.as_mut_ptr(),
len_global_names,
);
global_names.set_len(len_global_names as usize);
}

let names = global_names
.into_iter()
.map(|x| x.into())
.collect::<Vec<String>>();
Some(names)
}
false => None,
}
}
}
#[cfg(not(feature = "async"))]
impl AsImport for WasiModule {
fn name(&self) -> &str {
"wasi_snapshot_preview1"
}

fn add_func(&mut self, name: impl AsRef<str>, func: Function) {
self.funcs.push(func);
let f = self.funcs.last_mut().unwrap();

let func_name: WasmEdgeString = name.into();
unsafe {
ffi::WasmEdge_ModuleInstanceAddFunction(
self.inner.0,
func_name.as_raw(),
f.inner.lock().0,
);
}
}

fn add_table(&mut self, name: impl AsRef<str>, table: Table) {
let table_name: WasmEdgeString = name.as_ref().into();
unsafe {
ffi::WasmEdge_ModuleInstanceAddTable(
self.inner.0,
table_name.as_raw(),
table.inner.lock().0,
);
}

table.inner.lock().0 = std::ptr::null_mut();
}

fn add_memory(&mut self, name: impl AsRef<str>, memory: Memory) {
let mem_name: WasmEdgeString = name.as_ref().into();
unsafe {
ffi::WasmEdge_ModuleInstanceAddMemory(
self.inner.0,
mem_name.as_raw(),
memory.inner.lock().0,
);
}

memory.inner.lock().0 = std::ptr::null_mut();
}

fn add_global(&mut self, name: impl AsRef<str>, global: Global) {
let global_name: WasmEdgeString = name.as_ref().into();
unsafe {
ffi::WasmEdge_ModuleInstanceAddGlobal(
self.inner.0,
global_name.as_raw(),
global.inner.lock().0,
);
}

global.inner.lock().0 = std::ptr::null_mut();
}
}

/// The object to be registered via the the [Executor::register_import_object](crate::Executor::register_import_object) function is required to implement this trait.
pub trait AsImport {
Expand Down Expand Up @@ -1002,22 +762,22 @@ pub trait AsImport {

/// Defines three types of module instances that can be imported into a WasmEdge [Store](crate::Store) instance.
#[derive(Debug, Clone)]
pub enum ImportObject {
pub enum WasiInstance {
/// Defines the import module instance of WasiModule type.
#[cfg(not(feature = "async"))]
Wasi(WasiModule),
/// Defines the import module instance of AsyncWasiModule type.
#[cfg(all(feature = "async", target_os = "linux"))]
AsyncWasi(AsyncWasiModule),
}
impl ImportObject {
impl WasiInstance {
/// Returns the name of the import object.
pub fn name(&self) -> &str {
match self {
#[cfg(not(feature = "async"))]
ImportObject::Wasi(wasi) => wasi.name(),
WasiInstance::Wasi(wasi) => wasi.name(),
#[cfg(all(feature = "async", target_os = "linux"))]
ImportObject::AsyncWasi(async_wasi) => async_wasi.name(),
WasiInstance::AsyncWasi(async_wasi) => async_wasi.name(),
}
}

Expand All @@ -1026,9 +786,9 @@ impl ImportObject {
pub fn as_raw_ptr(&self) -> *const ffi::WasmEdge_ModuleInstanceContext {
match self {
#[cfg(not(feature = "async"))]
ImportObject::Wasi(wasi) => wasi.inner.0,
WasiInstance::Wasi(wasi) => wasi.inner.0,
#[cfg(all(feature = "async", target_os = "linux"))]
ImportObject::AsyncWasi(async_wasi) => async_wasi.inner.0,
WasiInstance::AsyncWasi(async_wasi) => async_wasi.inner.0,
}
}
}
Expand Down
Loading