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}
138
139impl CompileConfig {
140 /// Resolve the effective safety-bounds setting, honouring the legacy
141 /// `bounds_check` field as a fallback. Used by backends to pick the
142 /// inline-check shape.
143 pub fn effective_safety_bounds(&self) -> SafetyBounds {
144 match (self.safety_bounds, self.bounds_check) {
145 (SafetyBounds::None, true) => SafetyBounds::Software,
146 (s, _) => s,
147 }
148 }
149}
150
151impl Default for CompileConfig {
152 fn default() -> Self {
153 Self {
154 opt_level: 2,
155 target: TargetSpec::cortex_m4(),
156 bounds_check: false,
157 safety_bounds: SafetyBounds::None,
158 hardware: String::new(),
159 no_optimize: false,
160 loom_compat: false,
161 num_imports: 0,
162 func_arg_counts: Vec::new(),
163 type_arg_counts: Vec::new(),
164 relocatable: false,
165 native_pointer_abi: false,
166 linear_memory_bytes: 0,
167 stack_pointer_global: None,
168 }
169 }
170}
171
172/// A relocation entry produced during compilation
173///
174/// Records that a BL instruction at `offset` bytes into the function's code
175/// targets an external symbol (e.g., `__meld_dispatch_import`). The linker
176/// resolves these when combining the Synth object with the Kiln bridge.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub enum RelocKind {
179 /// R_ARM_THM_CALL — a Thumb BL call site (the default; #167).
180 ThmCall,
181 /// R_ARM_MOVW_ABS_NC — the MOVW half of a symbol-relative address (#237).
182 MovwAbs,
183 /// R_ARM_MOVT_ABS — the MOVT half of a symbol-relative address (#237).
184 MovtAbs,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct CodeRelocation {
189 /// Byte offset within the function's machine code where the reloc applies
190 pub offset: u32,
191 /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
192 pub symbol: String,
193 /// Which ARM relocation type to emit for this site.
194 pub kind: RelocKind,
195}
196
197/// A single compiled function
198#[derive(Debug, Clone)]
199pub struct CompiledFunction {
200 /// Function name (from WASM export or generated)
201 pub name: String,
202 /// Raw machine code bytes
203 pub code: Vec<u8>,
204 /// Original WASM ops (retained for verification)
205 pub wasm_ops: Vec<WasmOp>,
206 /// Relocations for external symbol references (BL to bridge functions)
207 pub relocations: Vec<CodeRelocation>,
208}
209
210/// Result of compiling a full module
211#[derive(Debug)]
212pub struct CompilationResult {
213 /// Compiled functions
214 pub functions: Vec<CompiledFunction>,
215 /// Complete ELF binary (if backend produces one directly)
216 pub elf: Option<Vec<u8>>,
217 /// Name of the backend that produced this result
218 pub backend_name: String,
219}
220
221/// What a backend can and cannot do
222#[derive(Debug, Clone)]
223pub struct BackendCapabilities {
224 /// Backend produces complete ELF files (external backends like aWsm)
225 pub produces_elf: bool,
226 /// Backend supports per-rule verification (only our custom ARM backend)
227 pub supports_rule_verification: bool,
228 /// Backend supports binary-level verification (all backends via disassembly)
229 pub supports_binary_verification: bool,
230 /// Backend is an external tool (not a library)
231 pub is_external: bool,
232}
233
234/// Trait that every compilation backend implements
235pub trait Backend: Send + Sync {
236 /// Human-readable backend name
237 fn name(&self) -> &str;
238
239 /// What this backend can do
240 fn capabilities(&self) -> BackendCapabilities;
241
242 /// Which targets this backend supports
243 fn supported_targets(&self) -> Vec<TargetSpec>;
244
245 /// Compile an entire decoded WASM module
246 fn compile_module(
247 &self,
248 module: &DecodedModule,
249 config: &CompileConfig,
250 ) -> std::result::Result<CompilationResult, BackendError>;
251
252 /// Compile a single function from WASM ops to machine code
253 fn compile_function(
254 &self,
255 name: &str,
256 ops: &[WasmOp],
257 config: &CompileConfig,
258 ) -> std::result::Result<CompiledFunction, BackendError>;
259
260 /// Check if this backend is available (external tools installed, etc.)
261 fn is_available(&self) -> bool;
262}
263
264/// Registry of available backends
265pub struct BackendRegistry {
266 backends: HashMap<String, Box<dyn Backend>>,
267}
268
269impl BackendRegistry {
270 pub fn new() -> Self {
271 Self {
272 backends: HashMap::new(),
273 }
274 }
275
276 /// Register a backend under its name
277 pub fn register(&mut self, backend: Box<dyn Backend>) {
278 let name = backend.name().to_string();
279 self.backends.insert(name, backend);
280 }
281
282 /// Get a backend by name
283 pub fn get(&self, name: &str) -> Option<&dyn Backend> {
284 self.backends.get(name).map(|b| b.as_ref())
285 }
286
287 /// List all registered backends
288 pub fn list(&self) -> Vec<&dyn Backend> {
289 self.backends.values().map(|b| b.as_ref()).collect()
290 }
291
292 /// List backends that are actually available (installed and working)
293 pub fn available(&self) -> Vec<&dyn Backend> {
294 self.backends
295 .values()
296 .filter(|b| b.is_available())
297 .map(|b| b.as_ref())
298 .collect()
299 }
300}
301
302impl Default for BackendRegistry {
303 fn default() -> Self {
304 Self::new()
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 #[test]
313 fn test_registry_empty() {
314 let reg = BackendRegistry::new();
315 assert!(reg.list().is_empty());
316 assert!(reg.available().is_empty());
317 assert!(reg.get("arm").is_none());
318 }
319
320 #[test]
321 fn test_compile_config_default() {
322 let config = CompileConfig::default();
323 assert_eq!(config.opt_level, 2);
324 assert!(!config.bounds_check);
325 assert_eq!(config.safety_bounds, SafetyBounds::None);
326 assert!(!config.no_optimize);
327 }
328
329 #[test]
330 fn safety_bounds_parse_round_trip() {
331 for s in ["none", "mpu", "software", "mask"] {
332 let sb = SafetyBounds::parse(s).unwrap();
333 assert_eq!(sb.as_str(), s);
334 }
335 assert_eq!(SafetyBounds::parse("pmp").unwrap(), SafetyBounds::Mpu);
336 assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
337 assert!(SafetyBounds::parse("nonsense").is_err());
338 }
339
340 #[test]
341 fn effective_safety_bounds_legacy_promotes_to_software() {
342 let cfg = CompileConfig {
343 bounds_check: true,
344 ..Default::default()
345 };
346 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
347 }
348
349 #[test]
350 fn effective_safety_bounds_new_field_wins() {
351 let cfg = CompileConfig {
352 bounds_check: true,
353 safety_bounds: SafetyBounds::Mpu,
354 ..Default::default()
355 };
356 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
357 }
358}