1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use crate::module::BareModuleInfo;
use crate::{Engine, FuncType, Trap, ValRaw};
use anyhow::Result;
use std::any::Any;
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use wasmtime_environ::{
AnyfuncIndex, EntityIndex, FunctionInfo, Module, ModuleType, SignatureIndex,
};
use wasmtime_jit::{CodeMemory, ProfilingAgent};
use wasmtime_runtime::{
Imports, InstanceAllocationRequest, InstanceAllocator, InstanceHandle,
OnDemandInstanceAllocator, StorePtr, VMContext, VMFunctionBody, VMOpaqueContext,
VMSharedSignatureIndex, VMTrampoline,
};
struct TrampolineState<F> {
func: F,
#[allow(dead_code)]
code_memory: CodeMemory,
}
unsafe extern "C" fn stub_fn<F>(
vmctx: *mut VMOpaqueContext,
caller_vmctx: *mut VMContext,
values_vec: *mut ValRaw,
values_vec_len: usize,
) where
F: Fn(*mut VMContext, &mut [ValRaw]) -> Result<(), Trap> + 'static,
{
let result = panic::catch_unwind(AssertUnwindSafe(|| {
let vmctx = VMContext::from_opaque(vmctx);
let state = (*vmctx).host_state();
debug_assert!(state.is::<TrampolineState<F>>());
let state = &*(state as *const _ as *const TrampolineState<F>);
let values_vec = std::slice::from_raw_parts_mut(values_vec, values_vec_len);
(state.func)(caller_vmctx, values_vec)
}));
match result {
Ok(Ok(())) => {}
Ok(Err(trap)) => wasmtime_runtime::raise_user_trap(trap.into()),
Err(panic) => wasmtime_runtime::resume_panic(panic),
}
}
#[cfg(compiler)]
fn register_trampolines(profiler: &dyn ProfilingAgent, image: &object::File<'_>) {
use object::{Object as _, ObjectSection, ObjectSymbol, SectionKind, SymbolKind};
let pid = std::process::id();
let tid = pid;
let text_base = match image.sections().find(|s| s.kind() == SectionKind::Text) {
Some(section) => match section.data() {
Ok(data) => data.as_ptr() as usize,
Err(_) => return,
},
None => return,
};
for sym in image.symbols() {
if !sym.is_definition() {
continue;
}
if sym.kind() != SymbolKind::Text {
continue;
}
let address = sym.address();
let size = sym.size();
if address == 0 || size == 0 {
continue;
}
if let Ok(name) = sym.name() {
let addr = text_base + address as usize;
profiler.load_single_trampoline(name, addr as *const u8, size as usize, pid, tid);
}
}
}
#[cfg(compiler)]
pub fn create_function<F>(
ft: &FuncType,
func: F,
engine: &Engine,
) -> Result<(InstanceHandle, VMTrampoline)>
where
F: Fn(*mut VMContext, &mut [ValRaw]) -> Result<(), Trap> + Send + Sync + 'static,
{
let mut obj = engine.compiler().object()?;
let (t1, t2) = engine.compiler().emit_trampoline_obj(
ft.as_wasm_func_type(),
stub_fn::<F> as usize,
&mut obj,
)?;
let obj = wasmtime_jit::mmap_vec_from_obj(obj)?;
let mut code_memory = CodeMemory::new(obj);
let code = code_memory.publish()?;
register_trampolines(engine.config().profiler.as_ref(), &code.obj);
let host_trampoline = code.text[t1.start as usize..][..t1.length as usize].as_ptr();
let wasm_trampoline = &code.text[t2.start as usize..][..t2.length as usize];
let wasm_trampoline = wasm_trampoline as *const [u8] as *mut [VMFunctionBody];
let sig = engine.signatures().register(ft.as_wasm_func_type());
unsafe {
let instance = create_raw_function(
wasm_trampoline,
sig,
Box::new(TrampolineState { func, code_memory }),
)?;
let host_trampoline = std::mem::transmute::<*const u8, VMTrampoline>(host_trampoline);
Ok((instance, host_trampoline))
}
}
pub unsafe fn create_raw_function(
func: *mut [VMFunctionBody],
sig: VMSharedSignatureIndex,
host_state: Box<dyn Any + Send + Sync>,
) -> Result<InstanceHandle> {
let mut module = Module::new();
let sig_id = SignatureIndex::from_u32(u32::max_value() - 1);
module.types.push(ModuleType::Function(sig_id));
let func_id = module.push_escaped_function(sig_id, AnyfuncIndex::from_u32(0));
module.num_escaped_funcs = 1;
module
.exports
.insert(String::new(), EntityIndex::Function(func_id));
let module = Arc::new(module);
let runtime_info = &BareModuleInfo::one_func(
module.clone(),
(*func).as_ptr() as usize,
FunctionInfo::default(),
sig_id,
sig,
)
.into_traitobj();
Ok(
OnDemandInstanceAllocator::default().allocate(InstanceAllocationRequest {
imports: Imports::default(),
host_state,
store: StorePtr::empty(),
runtime_info,
})?,
)
}