wasmtime/runtime/
trampoline.rs

1//! Utility module to create trampolines in/out WebAssembly module.
2
3mod func;
4mod global;
5mod memory;
6mod table;
7
8pub use self::func::*;
9pub use self::global::*;
10pub(crate) use memory::MemoryCreatorProxy;
11
12use self::memory::create_memory;
13use self::table::create_table;
14use crate::prelude::*;
15use crate::runtime::vm::{
16    Imports, InstanceAllocationRequest, InstanceAllocator, ModuleRuntimeInfo,
17    OnDemandInstanceAllocator, SharedMemory, StorePtr, VMFunctionImport,
18};
19use crate::store::{InstanceId, StoreOpaque};
20use crate::{MemoryType, TableType};
21use alloc::sync::Arc;
22use core::any::Any;
23use wasmtime_environ::{MemoryIndex, Module, TableIndex, VMSharedTypeIndex};
24
25fn create_handle(
26    module: Module,
27    store: &mut StoreOpaque,
28    host_state: Box<dyn Any + Send + Sync>,
29    func_imports: &[VMFunctionImport],
30    one_signature: Option<VMSharedTypeIndex>,
31) -> Result<InstanceId> {
32    let mut imports = Imports::default();
33    imports.functions = func_imports;
34
35    unsafe {
36        let config = store.engine().config();
37        // Use the on-demand allocator when creating handles associated with host objects
38        // The configured instance allocator should only be used when creating module instances
39        // as we don't want host objects to count towards instance limits.
40        let module = Arc::new(module);
41        let runtime_info = &ModuleRuntimeInfo::bare_maybe_imported_func(module, one_signature);
42        let allocator = OnDemandInstanceAllocator::new(config.mem_creator.clone(), 0, false);
43        let handle = allocator.allocate_module(InstanceAllocationRequest {
44            imports,
45            host_state,
46            store: StorePtr::new(store.traitobj()),
47            runtime_info,
48            wmemcheck: false,
49            pkey: None,
50            tunables: store.engine().tunables(),
51        })?;
52
53        Ok(store.add_dummy_instance(handle))
54    }
55}
56
57pub fn generate_memory_export(
58    store: &mut StoreOpaque,
59    m: &MemoryType,
60    preallocation: Option<&SharedMemory>,
61) -> Result<crate::runtime::vm::ExportMemory> {
62    let instance = create_memory(store, m, preallocation)?;
63    Ok(store
64        .instance_mut(instance)
65        .get_exported_memory(MemoryIndex::from_u32(0)))
66}
67
68pub fn generate_table_export(
69    store: &mut StoreOpaque,
70    t: &TableType,
71) -> Result<crate::runtime::vm::ExportTable> {
72    let instance = create_table(store, t)?;
73    Ok(store
74        .instance_mut(instance)
75        .get_exported_table(TableIndex::from_u32(0)))
76}