wasmer_runtime_core_fl/backend.rs
1use crate::{
2 error::{CompileResult, RuntimeError},
3 module::ModuleInner,
4 state::ModuleStateMap,
5 typed_func::Wasm,
6 types::{LocalFuncIndex, SigIndex},
7 vm,
8};
9
10use crate::{
11 cache::{Artifact, Error as CacheError},
12 codegen::BreakpointMap,
13 module::ModuleInfo,
14 sys::Memory,
15};
16use std::fmt;
17use std::{any::Any, ptr::NonNull};
18
19use std::collections::HashMap;
20
21pub mod sys {
22 pub use crate::sys::*;
23}
24pub use crate::sig_registry::SigRegistry;
25
26/// The target architecture for code generation.
27#[derive(Copy, Clone, Debug)]
28pub enum Architecture {
29 /// x86-64.
30 X64,
31
32 /// Aarch64 (ARM64).
33 Aarch64,
34}
35
36/// The type of an inline breakpoint.
37#[repr(u8)]
38#[derive(Copy, Clone, Debug)]
39pub enum InlineBreakpointType {
40 /// A middleware invocation breakpoint.
41 Middleware,
42}
43
44/// Information of an inline breakpoint.
45#[derive(Clone, Debug)]
46pub struct InlineBreakpoint {
47 /// Size in bytes taken by this breakpoint's instruction sequence.
48 pub size: usize,
49
50 /// Type of the inline breakpoint.
51 pub ty: InlineBreakpointType,
52}
53
54/// This type cannot be constructed from
55/// outside the runtime crate.
56pub struct Token {
57 _private: (),
58}
59
60impl Token {
61 pub(crate) fn generate() -> Self {
62 Self { _private: () }
63 }
64}
65
66#[derive(Copy, Clone, Debug)]
67pub enum MemoryBoundCheckMode {
68 Default,
69 Enable,
70 Disable,
71}
72
73impl Default for MemoryBoundCheckMode {
74 fn default() -> MemoryBoundCheckMode {
75 MemoryBoundCheckMode::Default
76 }
77}
78
79/// Controls which experimental features will be enabled.
80/// Features usually have a corresponding [WebAssembly proposal][wasm-props].
81///
82/// [wasm-props]: https://github.com/WebAssembly/proposals
83#[derive(Debug, Default)]
84pub struct Features {
85 /// Whether support for the [SIMD proposal][simd-prop] is enabled.
86 ///
87 /// [simd-prop]: https://github.com/webassembly/simd
88 pub simd: bool,
89 /// Whether support for the [threads proposal][threads-prop] is enabled.
90 ///
91 /// [threads-prop]: https://github.com/webassembly/threads
92 pub threads: bool,
93}
94
95/// Use this to point to a compiler config struct provided by the backend.
96/// The backend struct must support runtime reflection with `Any`, which is any
97/// struct that does not contain a non-`'static` reference.
98#[derive(Debug)]
99pub struct BackendCompilerConfig(pub Box<dyn Any + 'static>);
100
101impl BackendCompilerConfig {
102 /// Obtain the backend-specific compiler config struct.
103 pub fn get_specific<T: 'static>(&self) -> Option<&T> {
104 self.0.downcast_ref::<T>()
105 }
106}
107
108/// Configuration data for the compiler
109#[derive(Debug)]
110pub struct CompilerConfig {
111 /// Symbol information generated from emscripten; used for more detailed debug messages
112 pub symbol_map: Option<HashMap<u32, String>>,
113
114 /// How to make the decision whether to emit bounds checks for memory accesses.
115 pub memory_bound_check_mode: MemoryBoundCheckMode,
116
117 /// Whether to generate explicit native stack checks against `stack_lower_bound` in `InternalCtx`.
118 ///
119 /// Usually it's adequate to use hardware memory protection mechanisms such as `mprotect` on Unix to
120 /// prevent stack overflow. But for low-level environments, e.g. the kernel, faults are generally
121 /// not expected and relying on hardware memory protection would add too much complexity.
122 pub enforce_stack_check: bool,
123
124 /// Whether to enable state tracking. Necessary for managed mode.
125 pub track_state: bool,
126
127 /// Whether to enable full preemption checkpoint generation.
128 ///
129 /// This inserts checkpoints at critical locations such as loop backedges and function calls,
130 /// allowing preemptive unwinding/task switching.
131 ///
132 /// When enabled there can be a small amount of runtime performance overhead.
133 pub full_preemption: bool,
134
135 /// Always choose a unique bit representation for NaN.
136 /// Enabling this makes execution deterministic but increases runtime overhead.
137 pub nan_canonicalization: bool,
138
139 /// Turns on verification that is done by default when `debug_assertions` are enabled
140 /// (for example in 'debug' builds). Disabling this flag will make compilation faster
141 /// in debug mode at the cost of not detecting bugs in the compiler.
142 ///
143 /// These verifications are disabled by default in 'release' builds.
144 pub enable_verification: bool,
145
146 pub features: Features,
147
148 // Target info. Presently only supported by LLVM.
149 pub triple: Option<String>,
150 pub cpu_name: Option<String>,
151 pub cpu_features: Option<String>,
152
153 pub backend_specific_config: Option<BackendCompilerConfig>,
154
155 pub generate_debug_info: bool,
156}
157
158impl Default for CompilerConfig {
159 fn default() -> Self {
160 Self {
161 symbol_map: Default::default(),
162 memory_bound_check_mode: Default::default(),
163 enforce_stack_check: Default::default(),
164 track_state: Default::default(),
165 full_preemption: Default::default(),
166 nan_canonicalization: Default::default(),
167 features: Default::default(),
168 triple: Default::default(),
169 cpu_name: Default::default(),
170 cpu_features: Default::default(),
171 backend_specific_config: Default::default(),
172 generate_debug_info: Default::default(),
173
174 // Default verification to 'on' when testing or running in debug mode.
175 // NOTE: cfg(test) probably does nothing when not running `cargo test`
176 // on this crate
177 enable_verification: cfg!(test) || cfg!(debug_assertions),
178 }
179 }
180}
181
182impl CompilerConfig {
183 /// Use this to check if we should be generating debug information.
184 /// This function takes into account the features that runtime-core was
185 /// compiled with in addition to the value of the `generate_debug_info` field.
186 pub(crate) fn should_generate_debug_info(&self) -> bool {
187 cfg!(feature = "generate-debug-information") && self.generate_debug_info
188 }
189}
190
191/// An exception table for a `RunnableModule`.
192#[derive(Clone, Debug, Default, Serialize, Deserialize)]
193pub struct ExceptionTable {
194 /// Mappings from offsets in generated machine code to the corresponding exception code.
195 pub offset_to_code: HashMap<usize, ExceptionCode>,
196}
197
198impl ExceptionTable {
199 pub fn new() -> Self {
200 Self::default()
201 }
202}
203
204/// The code of an exception.
205#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
206pub enum ExceptionCode {
207 /// An `unreachable` opcode was executed.
208 Unreachable = 0,
209 /// Call indirect incorrect signature trap.
210 IncorrectCallIndirectSignature = 1,
211 /// Memory out of bounds trap.
212 MemoryOutOfBounds = 2,
213 /// Call indirect out of bounds trap.
214 CallIndirectOOB = 3,
215 /// An arithmetic exception, e.g. divided by zero.
216 IllegalArithmetic = 4,
217 /// Misaligned atomic access trap.
218 MisalignedAtomicAccess = 5,
219}
220
221impl fmt::Display for ExceptionCode {
222 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223 write!(
224 f,
225 "{}",
226 match self {
227 ExceptionCode::Unreachable => "unreachable",
228 ExceptionCode::IncorrectCallIndirectSignature => {
229 "incorrect `call_indirect` signature"
230 }
231 ExceptionCode::MemoryOutOfBounds => "memory out-of-bounds access",
232 ExceptionCode::CallIndirectOOB => "`call_indirect` out-of-bounds",
233 ExceptionCode::IllegalArithmetic => "illegal arithmetic operation",
234 ExceptionCode::MisalignedAtomicAccess => "misaligned atomic access",
235 }
236 )
237 }
238}
239
240pub trait Compiler {
241 /// Compiles a `Module` from WebAssembly binary format.
242 /// The `CompileToken` parameter ensures that this can only
243 /// be called from inside the runtime.
244 fn compile(
245 &self,
246 wasm: &[u8],
247 comp_conf: CompilerConfig,
248 _: Token,
249 ) -> CompileResult<ModuleInner>;
250
251 unsafe fn from_cache(&self, cache: Artifact, _: Token) -> Result<ModuleInner, CacheError>;
252}
253
254pub trait RunnableModule: Send + Sync {
255 /// This returns a pointer to the function designated by the `local_func_index`
256 /// parameter.
257 fn get_func(
258 &self,
259 info: &ModuleInfo,
260 local_func_index: LocalFuncIndex,
261 ) -> Option<NonNull<vm::Func>>;
262
263 fn get_module_state_map(&self) -> Option<ModuleStateMap> {
264 None
265 }
266
267 fn get_breakpoints(&self) -> Option<BreakpointMap> {
268 None
269 }
270
271 fn get_exception_table(&self) -> Option<&ExceptionTable> {
272 None
273 }
274
275 unsafe fn patch_local_function(&self, _idx: usize, _target_address: usize) -> bool {
276 false
277 }
278
279 /// A wasm trampoline contains the necessary data to dynamically call an exported wasm function.
280 /// Given a particular signature index, we return a trampoline that is matched with that
281 /// signature and an invoke function that can call the trampoline.
282 fn get_trampoline(&self, info: &ModuleInfo, sig_index: SigIndex) -> Option<Wasm>;
283
284 /// Trap an error.
285 unsafe fn do_early_trap(&self, data: RuntimeError) -> !;
286
287 /// Returns the machine code associated with this module.
288 fn get_code(&self) -> Option<&[u8]> {
289 None
290 }
291
292 /// Returns the beginning offsets of all functions, including import trampolines.
293 fn get_offsets(&self) -> Option<Vec<usize>> {
294 None
295 }
296
297 /// Returns the beginning offsets of all local functions.
298 fn get_local_function_offsets(&self) -> Option<Vec<usize>> {
299 None
300 }
301
302 /// Returns the inline breakpoint size corresponding to an Architecture (None in case is not implemented)
303 fn get_inline_breakpoint_size(&self, _arch: Architecture) -> Option<usize> {
304 None
305 }
306
307 /// Attempts to read an inline breakpoint from the code.
308 ///
309 /// Inline breakpoints are detected by special instruction sequences that never
310 /// appear in valid code.
311 fn read_inline_breakpoint(
312 &self,
313 _arch: Architecture,
314 _code: &[u8],
315 ) -> Option<InlineBreakpoint> {
316 None
317 }
318}
319
320pub trait CacheGen: Send + Sync {
321 fn generate_cache(&self) -> Result<(Box<[u8]>, Memory), CacheError>;
322}