synth_core/backend.rs
1//! Backend trait and registry for multi-backend compilation
2//!
3//! Every compiler backend (ARM, aWsm, wasker, w2c2) implements the `Backend`
4//! trait, allowing the CLI and verification framework to treat them uniformly.
5
6use crate::target::TargetSpec;
7use crate::wasm_decoder::DecodedModule;
8use crate::wasm_op::WasmOp;
9use std::collections::HashMap;
10use thiserror::Error;
11
12/// Errors from backend compilation
13#[derive(Debug, Error)]
14pub enum BackendError {
15 #[error("compilation failed: {0}")]
16 CompilationFailed(String),
17
18 #[error("backend not available: {0}")]
19 NotAvailable(String),
20
21 #[error("unsupported configuration: {0}")]
22 UnsupportedConfig(String),
23
24 #[error("external tool error: {0}")]
25 ExternalToolError(String),
26}
27
28/// Memory-bounds safety strategy. Phase 1 of `docs/binary-safety-design.md` §3.1.
29///
30/// - `Mpu`/PMP: rely on hardware (ARM MPU or RV32 PMP) — no inline check.
31/// - `Software`: emit a `CMP/BHS Trap_Handler` (ARM) or `bgeu addr, mem_size, ebreak` (RV32)
32/// before every load/store.
33/// - `Mask`: emit `AND addr, addr, #(mem_size - 1)` — only valid when memory size
34/// is a power of two. Wraps on OOB rather than trapping (fuzz-profile semantics).
35/// - `None`: no bounds enforcement.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum SafetyBounds {
38 /// No bounds check (caller assumes the WASM module is trusted)
39 #[default]
40 None,
41 /// ARM MPU / RV32 PMP — hardware enforcement, no inline guard
42 Mpu,
43 /// Software CMP/BHS (ARM) or BGEU+EBREAK (RV32) per access
44 Software,
45 /// AND-mask, requires power-of-two memory size
46 Mask,
47}
48
49impl SafetyBounds {
50 /// Parse the `--safety-bounds` argument value.
51 pub fn parse(s: &str) -> std::result::Result<Self, String> {
52 match s {
53 "none" => Ok(SafetyBounds::None),
54 "mpu" | "pmp" => Ok(SafetyBounds::Mpu),
55 "software" | "soft" => Ok(SafetyBounds::Software),
56 "mask" | "masking" => Ok(SafetyBounds::Mask),
57 other => Err(format!(
58 "unknown --safety-bounds value '{}'; expected one of: none, mpu, software, mask",
59 other
60 )),
61 }
62 }
63
64 /// String form used in the safety manifest.
65 pub fn as_str(self) -> &'static str {
66 match self {
67 SafetyBounds::None => "none",
68 SafetyBounds::Mpu => "mpu",
69 SafetyBounds::Software => "software",
70 SafetyBounds::Mask => "mask",
71 }
72 }
73}
74
75/// Configuration for a compilation run
76#[derive(Debug, Clone)]
77pub struct CompileConfig {
78 /// Optimization level (0 = none, 1 = fast, 2 = default, 3 = aggressive)
79 pub opt_level: u8,
80 /// Target specification
81 pub target: TargetSpec,
82 /// Legacy: enable software bounds checking for memory operations.
83 /// Deprecated in favor of `safety_bounds`. When set, equivalent to
84 /// `SafetyBounds::Software`. Kept for backwards compatibility with
85 /// callers that haven't migrated yet.
86 pub bounds_check: bool,
87 /// Phase-1 unified safety-bounds knob. If `bounds_check` is `true` and
88 /// this is `None`, the legacy field wins (back-compat). If both are set,
89 /// `safety_bounds` wins.
90 pub safety_bounds: SafetyBounds,
91 /// Hardware profile name (e.g. "nrf52840", "stm32f407")
92 pub hardware: String,
93 /// Skip optimization passes (direct instruction selection)
94 pub no_optimize: bool,
95 /// Use Loom-compatible optimization preset
96 pub loom_compat: bool,
97 /// Number of imported functions (calls to indices below this use Meld dispatch)
98 pub num_imports: u32,
99 /// AAPCS integer-argument count per function, indexed by full WASM function
100 /// index (imports first, then locals). Lets `Call` marshal the right number
101 /// of operand-stack values into R0–R3 (issue #195). Empty = pass no args
102 /// (pre-#195 behaviour).
103 pub func_arg_counts: Vec<u32>,
104 /// AAPCS integer-argument count per function type, indexed by type index.
105 /// Used by `call_indirect` (issue #195).
106 pub type_arg_counts: Vec<u32>,
107 /// Produce relocatable (ET_REL) host-link output. When set, the backend
108 /// uses the direct instruction selector (`select_with_stack`) rather than
109 /// the optimized path: the optimizer materializes an *absolute* linear-
110 /// memory base (0x20000100) and does not preserve caller-saved registers
111 /// across calls, both wrong for a host-linked object where the linmem base
112 /// is supplied via `fp` at runtime and callees follow AAPCS. Imports are
113 /// also emitted as direct `func_N` BLs (resolved to the wasm field name)
114 /// instead of `__meld_dispatch_import`. (#197 — follow-up to #188/#171.)
115 pub relocatable: bool,
116
117 /// #237: emit wasm function-static data as a base-independent `.data`
118 /// section (`__synth_wasm_data`) addressed via MOVW/MOVT symbol relocations,
119 /// so a host-pointer drop-in (linmem base = 0 for native `*ptr` derefs)
120 /// doesn't mis-resolve the statics. Off by default — only the leaves'
121 /// base-relative `[R11+const]` path is used unless explicitly requested.
122 pub native_pointer_abi: bool,
123
124 /// #237: wasm linear-memory minimum size in bytes — the full static-data
125 /// extent (initialized `(data)` segments plus the zero-init/BSS region).
126 /// Under `native_pointer_abi`, a const memory address below this is a wasm
127 /// static → symbol-relative; any address beyond it is a runtime host pointer
128 /// → `[R11=0 + addr]`.
129 pub linear_memory_bytes: u32,
130
131 /// #237: the wasm stack-pointer global as `(index, init_value)`, if the
132 /// module has one. Under `native_pointer_abi` the backend register-promotes
133 /// it: `global.get` materializes `__synth_wasm_data + init` (the real stack
134 /// top) and the init value doubles as the static-data base that separates
135 /// pointer consts (`>= init`) from frame-size scalars (`< init`).
136 pub stack_pointer_global: Option<(u32, i32)>,
137 /// #311: per-function (full index) / per-type "returns i64" — the call
138 /// lowering must tag i64 results as a register pair or the hi half is
139 /// invisible to liveness.
140 pub func_ret_i64: Vec<bool>,
141 pub type_ret_i64: Vec<bool>,
142}
143
144impl CompileConfig {
145 /// Resolve the effective safety-bounds setting, honouring the legacy
146 /// `bounds_check` field as a fallback. Used by backends to pick the
147 /// inline-check shape.
148 pub fn effective_safety_bounds(&self) -> SafetyBounds {
149 match (self.safety_bounds, self.bounds_check) {
150 (SafetyBounds::None, true) => SafetyBounds::Software,
151 (s, _) => s,
152 }
153 }
154}
155
156impl Default for CompileConfig {
157 fn default() -> Self {
158 Self {
159 opt_level: 2,
160 target: TargetSpec::cortex_m4(),
161 bounds_check: false,
162 safety_bounds: SafetyBounds::None,
163 hardware: String::new(),
164 no_optimize: false,
165 loom_compat: false,
166 num_imports: 0,
167 func_arg_counts: Vec::new(),
168 type_arg_counts: Vec::new(),
169 relocatable: false,
170 native_pointer_abi: false,
171 linear_memory_bytes: 0,
172 stack_pointer_global: None,
173 func_ret_i64: Vec::new(),
174 type_ret_i64: Vec::new(),
175 }
176 }
177}
178
179/// A relocation entry produced during compilation
180///
181/// Records that a BL instruction at `offset` bytes into the function's code
182/// targets an external symbol (e.g., `__meld_dispatch_import`). The linker
183/// resolves these when combining the Synth object with the Kiln bridge.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum RelocKind {
186 /// R_ARM_THM_CALL — a Thumb BL call site (the default; #167).
187 ThmCall,
188 /// R_ARM_MOVW_ABS_NC — the MOVW half of a symbol-relative address (#237).
189 MovwAbs,
190 /// R_ARM_MOVT_ABS — the MOVT half of a symbol-relative address (#237).
191 MovtAbs,
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct CodeRelocation {
196 /// Byte offset within the function's machine code where the reloc applies
197 pub offset: u32,
198 /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
199 pub symbol: String,
200 /// Which ARM relocation type to emit for this site.
201 pub kind: RelocKind,
202}
203
204/// A single compiled function
205#[derive(Debug, Clone)]
206pub struct CompiledFunction {
207 /// Function name (from WASM export or generated)
208 pub name: String,
209 /// Raw machine code bytes
210 pub code: Vec<u8>,
211 /// Original WASM ops (retained for verification)
212 pub wasm_ops: Vec<WasmOp>,
213 /// Relocations for external symbol references (BL to bridge functions)
214 pub relocations: Vec<CodeRelocation>,
215}
216
217/// Result of compiling a full module
218#[derive(Debug)]
219pub struct CompilationResult {
220 /// Compiled functions
221 pub functions: Vec<CompiledFunction>,
222 /// Complete ELF binary (if backend produces one directly)
223 pub elf: Option<Vec<u8>>,
224 /// Name of the backend that produced this result
225 pub backend_name: String,
226}
227
228/// What a backend can and cannot do
229#[derive(Debug, Clone)]
230pub struct BackendCapabilities {
231 /// Backend produces complete ELF files (external backends like aWsm)
232 pub produces_elf: bool,
233 /// Backend supports per-rule verification (only our custom ARM backend)
234 pub supports_rule_verification: bool,
235 /// Backend supports binary-level verification (all backends via disassembly)
236 pub supports_binary_verification: bool,
237 /// Backend is an external tool (not a library)
238 pub is_external: bool,
239}
240
241/// Trait that every compilation backend implements
242pub trait Backend: Send + Sync {
243 /// Human-readable backend name
244 fn name(&self) -> &str;
245
246 /// What this backend can do
247 fn capabilities(&self) -> BackendCapabilities;
248
249 /// Which targets this backend supports
250 fn supported_targets(&self) -> Vec<TargetSpec>;
251
252 /// Compile an entire decoded WASM module
253 fn compile_module(
254 &self,
255 module: &DecodedModule,
256 config: &CompileConfig,
257 ) -> std::result::Result<CompilationResult, BackendError>;
258
259 /// Compile a single function from WASM ops to machine code
260 fn compile_function(
261 &self,
262 name: &str,
263 ops: &[WasmOp],
264 config: &CompileConfig,
265 ) -> std::result::Result<CompiledFunction, BackendError>;
266
267 /// Check if this backend is available (external tools installed, etc.)
268 fn is_available(&self) -> bool;
269}
270
271/// Registry of available backends
272pub struct BackendRegistry {
273 backends: HashMap<String, Box<dyn Backend>>,
274}
275
276impl BackendRegistry {
277 pub fn new() -> Self {
278 Self {
279 backends: HashMap::new(),
280 }
281 }
282
283 /// Register a backend under its name
284 pub fn register(&mut self, backend: Box<dyn Backend>) {
285 let name = backend.name().to_string();
286 self.backends.insert(name, backend);
287 }
288
289 /// Get a backend by name
290 pub fn get(&self, name: &str) -> Option<&dyn Backend> {
291 self.backends.get(name).map(|b| b.as_ref())
292 }
293
294 /// List all registered backends
295 pub fn list(&self) -> Vec<&dyn Backend> {
296 self.backends.values().map(|b| b.as_ref()).collect()
297 }
298
299 /// List backends that are actually available (installed and working)
300 pub fn available(&self) -> Vec<&dyn Backend> {
301 self.backends
302 .values()
303 .filter(|b| b.is_available())
304 .map(|b| b.as_ref())
305 .collect()
306 }
307}
308
309impl Default for BackendRegistry {
310 fn default() -> Self {
311 Self::new()
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 #[test]
320 fn test_registry_empty() {
321 let reg = BackendRegistry::new();
322 assert!(reg.list().is_empty());
323 assert!(reg.available().is_empty());
324 assert!(reg.get("arm").is_none());
325 }
326
327 #[test]
328 fn test_compile_config_default() {
329 let config = CompileConfig::default();
330 assert_eq!(config.opt_level, 2);
331 assert!(!config.bounds_check);
332 assert_eq!(config.safety_bounds, SafetyBounds::None);
333 assert!(!config.no_optimize);
334 }
335
336 #[test]
337 fn safety_bounds_parse_round_trip() {
338 for s in ["none", "mpu", "software", "mask"] {
339 let sb = SafetyBounds::parse(s).unwrap();
340 assert_eq!(sb.as_str(), s);
341 }
342 assert_eq!(SafetyBounds::parse("pmp").unwrap(), SafetyBounds::Mpu);
343 assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
344 assert!(SafetyBounds::parse("nonsense").is_err());
345 }
346
347 #[test]
348 fn effective_safety_bounds_legacy_promotes_to_software() {
349 let cfg = CompileConfig {
350 bounds_check: true,
351 ..Default::default()
352 };
353 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
354 }
355
356 #[test]
357 fn effective_safety_bounds_new_field_wins() {
358 let cfg = CompileConfig {
359 bounds_check: true,
360 safety_bounds: SafetyBounds::Mpu,
361 ..Default::default()
362 };
363 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
364 }
365}