Struct wasmedge_sdk::Vm

source ·
pub struct Vm { /* private fields */ }
Expand description

A Vm defines a virtual environment for managing WebAssembly programs.

Example

The example below presents how to register a module as named module in a Vm instance and run a target wasm function.

// If the version of rust used is less than v1.63, please uncomment the follow attribute.
// #![feature(explicit_generic_args_with_impl_trait)]
#[cfg(not(feature = "async"))]
use wasmedge_sdk::{params, VmBuilder, WasmVal, wat2wasm, ValType, NeverType};

#[cfg_attr(test, test)]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    #[cfg(not(feature = "async"))]
    {
        // create a Vm context
        let vm = VmBuilder::new().build()?;

        // register a wasm module from the given in-memory wasm bytes
        let wasm_bytes = wat2wasm(
            br#"(module
            (export "fib" (func $fib))
            (func $fib (param $n i32) (result i32)
             (if
              (i32.lt_s
               (get_local $n)
               (i32.const 2)
              )
              (return
               (i32.const 1)
              )
             )
             (return
              (i32.add
               (call $fib
                (i32.sub
                 (get_local $n)
                 (i32.const 2)
                )
               )
               (call $fib
                (i32.sub
                 (get_local $n)
                 (i32.const 1)
                )
               )
              )
             )
            )
           )
        "#,
        )?;
        let mut vm = vm.register_module_from_bytes("extern", wasm_bytes)?;

        // run `fib` function in the named module instance
        let returns = vm.run_func(Some("extern"), "fib", params!(10))?;
        assert_eq!(returns.len(), 1);
        assert_eq!(returns[0].to_i32(), 89);
    }

    Ok(())
}

Implementations§

source§

impl Vm

source

pub fn register_module( self, mod_name: Option<&str>, module: Module ) -> WasmEdgeResult<Self>

Registers a wasm module into this vm as a named or active module instance.

Arguments
  • mod_name - The exported name for the registered module. If None, then the module is registered as an active instance.

  • module - The module to be registered.

Error

If fail to register the given module, then an error is returned.

source

pub fn register_module_from_file( self, mod_name: impl AsRef<str>, file: impl AsRef<Path> ) -> WasmEdgeResult<Self>

Registers a wasm module into the vm from a wasm file.

Arguments
  • mod_name - The exported name for the registered module.

  • file - A wasm file or an AOT wasm file.

Error

If fail to register, then an error is returned.

source

pub fn register_module_from_bytes( self, mod_name: impl AsRef<str>, bytes: impl AsRef<[u8]> ) -> WasmEdgeResult<Self>

Registers a wasm module from the given in-memory wasm bytes into this vm.

Arguments
  • mod_name - The exported name for the registered module.

  • bytes - The in-memory wasm bytes.

Error

If fail to register, then an error is returned.

source

pub fn register_import_module<T>( &mut self, import: &ImportObject<T> ) -> WasmEdgeResult<()>where T: ?Sized + Send + Sync + Clone,

Registers an import object into this vm.

Arguments
  • import - The import object to be registered.
Error

If fail to register, then an error is returned.

source

pub fn auto_detect_plugins(self) -> WasmEdgeResult<Self>

Auto detect all plugins in WASMEDGE_PLUGIN_PATH

Error

If fail to register plugin instance, then an error is returned.

source

pub fn run_func( &self, mod_name: Option<&str>, func_name: impl AsRef<str>, args: impl IntoIterator<Item = WasmValue> ) -> WasmEdgeResult<Vec<WasmValue>>

Runs an exported wasm function in a (named or active) module instance.

Arguments
  • mod_name - The exported name of the module instance, which holds the target function. If None, then the active module is used.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run the wasm function, then an error is returned.

source

pub fn run_func_with_timeout( &self, mod_name: Option<&str>, func_name: impl AsRef<str>, args: impl IntoIterator<Item = WasmValue>, timeout: Duration ) -> WasmEdgeResult<Vec<WasmValue>>

Runs an exported wasm function in a (named or active) module instance with a timeout setting

Arguments
  • mod_name - The exported name of the module instance, which holds the target function. If None, then the active module is used.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

  • timeout - The maximum execution time of the function to be run.

Error

If fail to run the wasm function, then an error is returned.

source

pub async fn run_func_async( &self, async_state: &AsyncState, mod_name: Option<&str>, func_name: impl AsRef<str> + Send, args: impl IntoIterator<Item = WasmValue> + Send ) -> WasmEdgeResult<Vec<WasmValue>>

Available on crate feature async and Linux only.

Asynchronously runs an exported wasm function in a (named or active) module instance.

Arguments
  • async_state - The AsyncState to run the wasm function.

  • mod_name - The exported name of the module instance, which holds the target function. If None, then the active module is used.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run the wasm function, then an error is returned.

source

pub async fn run_func_async_with_timeout( &self, async_state: &AsyncState, mod_name: Option<&str>, func_name: impl AsRef<str> + Send, args: impl IntoIterator<Item = WasmValue> + Send, timeout: Duration ) -> WasmEdgeResult<Vec<WasmValue>>

Available on crate feature async and Linux and non-musl only.

Asynchronously runs an exported wasm function in a (named or active) module instance with a timeout setting

Arguments
  • async_state - The AsyncState to run the wasm function.

  • mod_name - The exported name of the module instance, which holds the target function. If None, then the active module is used.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

  • timeout - The maximum execution time of the function to be run.

Error

If fail to run the wasm function, then an error is returned.

source

pub fn run_func_from_module( &mut self, module: Module, func_name: impl AsRef<str>, args: impl IntoIterator<Item = WasmValue> ) -> WasmEdgeResult<Vec<WasmValue>>

Runs an exported wasm function from the given wasm module.

This method is a shortcut of calling register_module and run_func in sequence.

Arguments
  • module - A wasm module.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run, then an error is returned.

source

pub async fn run_func_from_module_async<N, A>( &mut self, async_state: &AsyncState, module: Module, func_name: N, args: A ) -> WasmEdgeResult<Vec<WasmValue>>where N: AsRef<str> + Send, A: IntoIterator<Item = WasmValue> + Send,

Available on crate feature async and Linux only.

Runs an exported wasm function from the given wasm module.

To use this method, turn on the async feature.

Arguments
  • async_state - The AsyncState to run the wasm function.

  • module - A wasm module.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run, then an error is returned.

source

pub fn run_func_from_file( &mut self, file: impl AsRef<Path>, func_name: impl AsRef<str>, args: impl IntoIterator<Item = WasmValue> ) -> WasmEdgeResult<Vec<WasmValue>>

Runs an exported wasm function from the given wasm file.

Arguments
  • file - A wasm file or an AOT wasm file.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run, then an error is returned.

source

pub async fn run_func_from_file_async<P, N, A>( &mut self, async_state: &AsyncState, file: P, func_name: N, args: A ) -> WasmEdgeResult<Vec<WasmValue>>where P: AsRef<Path>, N: AsRef<str> + Send, A: IntoIterator<Item = WasmValue> + Send,

Available on crate feature async and Linux only.

Asynchronously runs an exported wasm function from the given wasm file.

Arguments
  • async_state - The AsyncState to run the wasm function.

  • file - A wasm file or an AOT wasm file.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run, then an error is returned.

source

pub fn run_func_from_bytes( &mut self, bytes: &[u8], func_name: impl AsRef<str>, args: impl IntoIterator<Item = WasmValue> ) -> WasmEdgeResult<Vec<WasmValue>>

Runs an exported wasm function from the given in-memory wasm bytes.

Arguments
  • bytes - The in-memory wasm bytes.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run, then an error is returned.

source

pub async fn run_func_from_bytes_async<N, A>( &mut self, async_state: &AsyncState, bytes: &[u8], func_name: N, args: A ) -> WasmEdgeResult<Vec<WasmValue>>where N: AsRef<str> + Send, A: IntoIterator<Item = WasmValue> + Send,

Available on crate feature async and Linux only.

Runs an exported wasm function from the given in-memory wasm bytes.

Arguments
  • async_state - The AsyncState to run the wasm function.

  • bytes - The in-memory wasm bytes.

  • func_name - The exported name of the target wasm function.

  • args - The arguments to be passed to the target wasm function.

Error

If fail to run, then an error is returned.

source

pub fn statistics(&self) -> Option<&Statistics>

Returns a reference to the internal statistics from this vm.

source

pub fn statistics_mut(&mut self) -> Option<&mut Statistics>

Returns a mutable reference to the internal statistics from this vm.

source

pub fn executor(&self) -> &Executor

Returns a reference to the internal executor from this vm.

source

pub fn executor_mut(&mut self) -> &mut Executor

Returns a mutable reference to the internal executor from this vm.

source

pub fn store(&self) -> &Store

Returns a reference to the internal store from this vm.

source

pub fn store_mut(&mut self) -> &mut Store

Returns a mutable reference to the internal store from this vm.

source

pub fn wasi_module(&self) -> Option<&WasiInstance>

Returns a reference to the [wasi module instance] from this vm.

To retrieve the [wasi module instance], a config with the enabled wasi option should be given when create this vm.

source

pub fn wasi_module_mut(&mut self) -> Option<&mut WasiInstance>

Returns a mutable reference to the [wasi module instance] from this vm.

To retrieve the [wasi module instance], a config with the enabled wasi option should be given when create this vm.

source

pub fn named_module(&self, name: impl AsRef<str>) -> WasmEdgeResult<&Instance>

Returns a reference to the named module instance with the given name from this vm.

Argument
  • name - The exported name of the target module instance.
Error

If fail to get the reference to the target module instance, then an error is returned.

source

pub fn named_module_mut( &mut self, name: impl AsRef<str> ) -> WasmEdgeResult<&mut Instance>

Returns a mutable reference to the named module instance with the given name.

Argument
  • name - The exported name of the target module instance.
Error

If fail to get the mutable reference to the target module instance, then an error is returned.

source

pub fn active_module(&self) -> WasmEdgeResult<&Instance>

Returns a reference to the active module instance from this vm.

Error

If fail to get the reference to the active module instance, then an error is returned.

source

pub fn active_module_mut(&mut self) -> WasmEdgeResult<&mut Instance>

Returns a mutable reference to the active module instance from this vm.

Error

If fail to get the mutable reference to the active module instance, then an error is returned.

source

pub fn contains_module(&self, mod_name: impl AsRef<str>) -> bool

Checks if the vm contains a named module instance.

Argument
  • mod_name - The exported name of the target module instance.
source

pub fn named_instance_count(&self) -> u32

Returns the count of the named module instances this vm holds.

source

pub fn instance_names(&self) -> Vec<String>

Returns the names of all named module instances this vm holds.

Trait Implementations§

source§

impl Clone for Vm

source§

fn clone(&self) -> Vm

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Vm

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Vm

§

impl Send for Vm

§

impl Sync for Vm

§

impl Unpin for Vm

§

impl !UnwindSafe for Vm

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V