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 /// #359: declared parameter widths per *function* (full index, imports
143 /// first): `func_params_i64[f][k]` is true when param `k` of function `f` is
144 /// i64/f64. The AAPCS stack-argument path needs the *declared* widths
145 /// (op-stream inference can't see an unused i64 param that still shifts the
146 /// incoming-stack layout). The source of truth — a per-function driver loop
147 /// (`compile_module` / the CLI loop) indexes it by `func.index` and copies
148 /// the slice into [`current_func_params_i64`] before each `compile_function`.
149 /// Empty → every param assumed i32 (the legacy path; keeps every function
150 /// with <=4 params, or all-i32 params, byte-identical).
151 pub func_params_i64: Vec<Vec<bool>>,
152 /// #359: declared parameter widths of the function CURRENTLY being compiled
153 /// — `current_func_params_i64[k]` is true when param `k` is i64/f64. Set per
154 /// function (a cheap clone of the config) from [`func_params_i64`] by the
155 /// driver loop, because `compile_function` is shared across backends and
156 /// carries no function index. Empty → assume i32.
157 pub current_func_params_i64: Vec<bool>,
158}
159
160impl CompileConfig {
161 /// Resolve the effective safety-bounds setting, honouring the legacy
162 /// `bounds_check` field as a fallback. Used by backends to pick the
163 /// inline-check shape.
164 pub fn effective_safety_bounds(&self) -> SafetyBounds {
165 match (self.safety_bounds, self.bounds_check) {
166 (SafetyBounds::None, true) => SafetyBounds::Software,
167 (s, _) => s,
168 }
169 }
170}
171
172impl Default for CompileConfig {
173 fn default() -> Self {
174 Self {
175 opt_level: 2,
176 target: TargetSpec::cortex_m4(),
177 bounds_check: false,
178 safety_bounds: SafetyBounds::None,
179 hardware: String::new(),
180 no_optimize: false,
181 loom_compat: false,
182 num_imports: 0,
183 func_arg_counts: Vec::new(),
184 type_arg_counts: Vec::new(),
185 relocatable: false,
186 native_pointer_abi: false,
187 linear_memory_bytes: 0,
188 stack_pointer_global: None,
189 func_ret_i64: Vec::new(),
190 type_ret_i64: Vec::new(),
191 func_params_i64: Vec::new(),
192 current_func_params_i64: Vec::new(),
193 }
194 }
195}
196
197/// A relocation entry produced during compilation
198///
199/// Records that a BL instruction at `offset` bytes into the function's code
200/// targets an external symbol (e.g., `__meld_dispatch_import`). The linker
201/// resolves these when combining the Synth object with the Kiln bridge.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum RelocKind {
204 /// R_ARM_THM_CALL — a Thumb BL call site (the default; #167).
205 ThmCall,
206 /// R_ARM_MOVW_ABS_NC — the MOVW half of a symbol-relative address (#237).
207 MovwAbs,
208 /// R_ARM_MOVT_ABS — the MOVT half of a symbol-relative address (#237).
209 MovtAbs,
210 /// R_ARM_ABS32 — a 32-bit absolute address held in a `.text` literal-pool
211 /// word, loaded via `LDR rX, [pc, #off]` (#345). The link-survivable
212 /// replacement for the inline-immediate MOVW/MOVT-ABS pair: `ld`/bfd patches
213 /// the data word at link time (`S + A`, the addend living in the word, REL
214 /// semantics), which survives placement into a large multi-object image —
215 /// whereas an inline-instruction MOVW_ABS immediate can be mangled.
216 Abs32,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct CodeRelocation {
221 /// Byte offset within the function's machine code where the reloc applies
222 pub offset: u32,
223 /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
224 pub symbol: String,
225 /// Which ARM relocation type to emit for this site.
226 pub kind: RelocKind,
227}
228
229/// A single compiled function
230#[derive(Debug, Clone)]
231pub struct CompiledFunction {
232 /// Function name (from WASM export or generated)
233 pub name: String,
234 /// Raw machine code bytes
235 pub code: Vec<u8>,
236 /// Original WASM ops (retained for verification)
237 pub wasm_ops: Vec<WasmOp>,
238 /// Relocations for external symbol references (BL to bridge functions)
239 pub relocations: Vec<CodeRelocation>,
240}
241
242/// Result of compiling a full module
243#[derive(Debug)]
244pub struct CompilationResult {
245 /// Compiled functions
246 pub functions: Vec<CompiledFunction>,
247 /// Complete ELF binary (if backend produces one directly)
248 pub elf: Option<Vec<u8>>,
249 /// Name of the backend that produced this result
250 pub backend_name: String,
251}
252
253/// What a backend can and cannot do
254#[derive(Debug, Clone)]
255pub struct BackendCapabilities {
256 /// Backend produces complete ELF files (external backends like aWsm)
257 pub produces_elf: bool,
258 /// Backend supports per-rule verification (only our custom ARM backend)
259 pub supports_rule_verification: bool,
260 /// Backend supports binary-level verification (all backends via disassembly)
261 pub supports_binary_verification: bool,
262 /// Backend is an external tool (not a library)
263 pub is_external: bool,
264}
265
266/// Trait that every compilation backend implements
267pub trait Backend: Send + Sync {
268 /// Human-readable backend name
269 fn name(&self) -> &str;
270
271 /// What this backend can do
272 fn capabilities(&self) -> BackendCapabilities;
273
274 /// Which targets this backend supports
275 fn supported_targets(&self) -> Vec<TargetSpec>;
276
277 /// Compile an entire decoded WASM module
278 fn compile_module(
279 &self,
280 module: &DecodedModule,
281 config: &CompileConfig,
282 ) -> std::result::Result<CompilationResult, BackendError>;
283
284 /// Compile a single function from WASM ops to machine code
285 fn compile_function(
286 &self,
287 name: &str,
288 ops: &[WasmOp],
289 config: &CompileConfig,
290 ) -> std::result::Result<CompiledFunction, BackendError>;
291
292 /// Check if this backend is available (external tools installed, etc.)
293 fn is_available(&self) -> bool;
294}
295
296/// Registry of available backends
297pub struct BackendRegistry {
298 backends: HashMap<String, Box<dyn Backend>>,
299}
300
301impl BackendRegistry {
302 pub fn new() -> Self {
303 Self {
304 backends: HashMap::new(),
305 }
306 }
307
308 /// Register a backend under its name
309 pub fn register(&mut self, backend: Box<dyn Backend>) {
310 let name = backend.name().to_string();
311 self.backends.insert(name, backend);
312 }
313
314 /// Get a backend by name
315 pub fn get(&self, name: &str) -> Option<&dyn Backend> {
316 self.backends.get(name).map(|b| b.as_ref())
317 }
318
319 /// List all registered backends
320 pub fn list(&self) -> Vec<&dyn Backend> {
321 self.backends.values().map(|b| b.as_ref()).collect()
322 }
323
324 /// List backends that are actually available (installed and working)
325 pub fn available(&self) -> Vec<&dyn Backend> {
326 self.backends
327 .values()
328 .filter(|b| b.is_available())
329 .map(|b| b.as_ref())
330 .collect()
331 }
332}
333
334impl Default for BackendRegistry {
335 fn default() -> Self {
336 Self::new()
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 #[test]
345 fn test_registry_empty() {
346 let reg = BackendRegistry::new();
347 assert!(reg.list().is_empty());
348 assert!(reg.available().is_empty());
349 assert!(reg.get("arm").is_none());
350 }
351
352 #[test]
353 fn test_compile_config_default() {
354 let config = CompileConfig::default();
355 assert_eq!(config.opt_level, 2);
356 assert!(!config.bounds_check);
357 assert_eq!(config.safety_bounds, SafetyBounds::None);
358 assert!(!config.no_optimize);
359 }
360
361 #[test]
362 fn safety_bounds_parse_round_trip() {
363 for s in ["none", "mpu", "software", "mask"] {
364 let sb = SafetyBounds::parse(s).unwrap();
365 assert_eq!(sb.as_str(), s);
366 }
367 assert_eq!(SafetyBounds::parse("pmp").unwrap(), SafetyBounds::Mpu);
368 assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
369 assert!(SafetyBounds::parse("nonsense").is_err());
370 }
371
372 #[test]
373 fn effective_safety_bounds_legacy_promotes_to_software() {
374 let cfg = CompileConfig {
375 bounds_check: true,
376 ..Default::default()
377 };
378 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
379 }
380
381 #[test]
382 fn effective_safety_bounds_new_field_wins() {
383 let cfg = CompileConfig {
384 bounds_check: true,
385 safety_bounds: SafetyBounds::Mpu,
386 ..Default::default()
387 };
388 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
389 }
390}