wasmer_compiler_cranelift/trampoline/
dynamic_function.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4//! A trampoline generator for calling dynamic host functions from Wasm.
5
6use crate::{
7    CraneliftCallbacks,
8    translator::{compiled_function_unwind_info, signature_to_cranelift_ir},
9};
10use cranelift_codegen::{
11    Context,
12    ir::{self, Function, InstBuilder, StackSlotData, StackSlotKind, UserFuncName},
13    isa::TargetIsa,
14};
15use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
16use std::{cmp, mem};
17use target_lexicon::Architecture;
18use wasmer_compiler::{misc::CompiledKind, types::function::FunctionBody};
19use wasmer_types::{CompileError, FunctionType, VMOffsets};
20
21/// Create a trampoline for invoking a WebAssembly function.
22#[allow(clippy::too_many_arguments)]
23pub fn make_trampoline_dynamic_function(
24    callbacks: &Option<CraneliftCallbacks>,
25    isa: &dyn TargetIsa,
26    arch: Architecture,
27    offsets: &VMOffsets,
28    fn_builder_ctx: &mut FunctionBuilderContext,
29    kind: &CompiledKind,
30    func_type: &FunctionType,
31    module_hash: &Option<String>,
32) -> Result<FunctionBody, CompileError> {
33    let pointer_type = isa.pointer_type();
34    let frontend_config = isa.frontend_config();
35    let signature = signature_to_cranelift_ir(func_type, frontend_config);
36    let mut stub_sig = ir::Signature::new(frontend_config.default_call_conv);
37    // Add the caller `vmctx` parameter.
38    stub_sig.params.push(ir::AbiParam::special(
39        pointer_type,
40        ir::ArgumentPurpose::VMContext,
41    ));
42
43    // Add the `values_vec` parameter.
44    stub_sig.params.push(ir::AbiParam::new(pointer_type));
45
46    // Compute the size of the values vector. The vmctx and caller vmctx are passed separately.
47    let value_size = mem::size_of::<u128>();
48    let values_vec_len =
49        (value_size * cmp::max(signature.params.len() - 1, signature.returns.len())) as u32;
50
51    let mut context = Context::new();
52    context.func = Function::with_name_signature(UserFuncName::user(0, 0), signature.clone());
53
54    let ss = context.func.create_sized_stack_slot(StackSlotData::new(
55        StackSlotKind::ExplicitSlot,
56        values_vec_len,
57        0,
58    ));
59
60    {
61        let mut builder = FunctionBuilder::new(&mut context.func, fn_builder_ctx);
62        let block0 = builder.create_block();
63
64        builder.append_block_params_for_function_params(block0);
65        builder.switch_to_block(block0);
66        builder.seal_block(block0);
67
68        let values_vec_ptr_val = builder.ins().stack_addr(pointer_type, ss, 0);
69        let mflags = ir::MemFlagsData::trusted();
70        // We only get the non-vmctx arguments
71        for i in 1..signature.params.len() {
72            let val = builder.func.dfg.block_params(block0)[i];
73            builder.ins().store(
74                mflags,
75                val,
76                values_vec_ptr_val,
77                ((i - 1) * value_size) as i32,
78            );
79        }
80
81        let block_params = builder.func.dfg.block_params(block0);
82        let vmctx_ptr_val = block_params[0];
83        let callee_args = vec![vmctx_ptr_val, values_vec_ptr_val];
84
85        let new_sig = builder.import_signature(stub_sig);
86
87        let mem_flags = ir::MemFlagsData::trusted();
88        let callee_value = builder.ins().load(
89            pointer_type,
90            mem_flags,
91            vmctx_ptr_val,
92            offsets.vmdynamicfunction_import_context_address() as i32,
93        );
94
95        builder
96            .ins()
97            .call_indirect(new_sig, callee_value, &callee_args);
98
99        let mflags = ir::MemFlagsData::trusted();
100        let mut results = Vec::new();
101        for (i, r) in signature.returns.iter().enumerate() {
102            let load = builder.ins().load(
103                r.value_type,
104                mflags,
105                values_vec_ptr_val,
106                (i * value_size) as i32,
107            );
108            results.push(load);
109        }
110        builder.ins().return_(&results);
111        builder.finalize(frontend_config)
112    }
113
114    if let Some(callbacks) = callbacks.as_ref() {
115        callbacks.preopt_ir(
116            kind,
117            module_hash,
118            context.func.display().to_string().as_bytes(),
119        );
120    }
121
122    let mut code_buf = Vec::new();
123    let mut ctrl_plane = Default::default();
124    let compiled = context
125        .compile(isa, &mut ctrl_plane)
126        .map_err(|error| CompileError::Codegen(error.inner.to_string()))?;
127    code_buf.extend_from_slice(compiled.code_buffer());
128
129    if let Some(callbacks) = callbacks.as_ref() {
130        callbacks.obj_memory_buffer(kind, module_hash, &code_buf);
131        callbacks.asm_memory_buffer(kind, module_hash, arch, &code_buf)?;
132    }
133
134    let unwind_info = compiled_function_unwind_info(isa, &context)?.maybe_into_to_windows_unwind();
135
136    Ok(FunctionBody {
137        body: code_buf,
138        unwind_info,
139    })
140}