Skip to main content

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    /// R_ARM_ABS32 — a 32-bit absolute address held in a `.text` literal-pool
193    /// word, loaded via `LDR rX, [pc, #off]` (#345). The link-survivable
194    /// replacement for the inline-immediate MOVW/MOVT-ABS pair: `ld`/bfd patches
195    /// the data word at link time (`S + A`, the addend living in the word, REL
196    /// semantics), which survives placement into a large multi-object image —
197    /// whereas an inline-instruction MOVW_ABS immediate can be mangled.
198    Abs32,
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub struct CodeRelocation {
203    /// Byte offset within the function's machine code where the reloc applies
204    pub offset: u32,
205    /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
206    pub symbol: String,
207    /// Which ARM relocation type to emit for this site.
208    pub kind: RelocKind,
209}
210
211/// A single compiled function
212#[derive(Debug, Clone)]
213pub struct CompiledFunction {
214    /// Function name (from WASM export or generated)
215    pub name: String,
216    /// Raw machine code bytes
217    pub code: Vec<u8>,
218    /// Original WASM ops (retained for verification)
219    pub wasm_ops: Vec<WasmOp>,
220    /// Relocations for external symbol references (BL to bridge functions)
221    pub relocations: Vec<CodeRelocation>,
222}
223
224/// Result of compiling a full module
225#[derive(Debug)]
226pub struct CompilationResult {
227    /// Compiled functions
228    pub functions: Vec<CompiledFunction>,
229    /// Complete ELF binary (if backend produces one directly)
230    pub elf: Option<Vec<u8>>,
231    /// Name of the backend that produced this result
232    pub backend_name: String,
233}
234
235/// What a backend can and cannot do
236#[derive(Debug, Clone)]
237pub struct BackendCapabilities {
238    /// Backend produces complete ELF files (external backends like aWsm)
239    pub produces_elf: bool,
240    /// Backend supports per-rule verification (only our custom ARM backend)
241    pub supports_rule_verification: bool,
242    /// Backend supports binary-level verification (all backends via disassembly)
243    pub supports_binary_verification: bool,
244    /// Backend is an external tool (not a library)
245    pub is_external: bool,
246}
247
248/// Trait that every compilation backend implements
249pub trait Backend: Send + Sync {
250    /// Human-readable backend name
251    fn name(&self) -> &str;
252
253    /// What this backend can do
254    fn capabilities(&self) -> BackendCapabilities;
255
256    /// Which targets this backend supports
257    fn supported_targets(&self) -> Vec<TargetSpec>;
258
259    /// Compile an entire decoded WASM module
260    fn compile_module(
261        &self,
262        module: &DecodedModule,
263        config: &CompileConfig,
264    ) -> std::result::Result<CompilationResult, BackendError>;
265
266    /// Compile a single function from WASM ops to machine code
267    fn compile_function(
268        &self,
269        name: &str,
270        ops: &[WasmOp],
271        config: &CompileConfig,
272    ) -> std::result::Result<CompiledFunction, BackendError>;
273
274    /// Check if this backend is available (external tools installed, etc.)
275    fn is_available(&self) -> bool;
276}
277
278/// Registry of available backends
279pub struct BackendRegistry {
280    backends: HashMap<String, Box<dyn Backend>>,
281}
282
283impl BackendRegistry {
284    pub fn new() -> Self {
285        Self {
286            backends: HashMap::new(),
287        }
288    }
289
290    /// Register a backend under its name
291    pub fn register(&mut self, backend: Box<dyn Backend>) {
292        let name = backend.name().to_string();
293        self.backends.insert(name, backend);
294    }
295
296    /// Get a backend by name
297    pub fn get(&self, name: &str) -> Option<&dyn Backend> {
298        self.backends.get(name).map(|b| b.as_ref())
299    }
300
301    /// List all registered backends
302    pub fn list(&self) -> Vec<&dyn Backend> {
303        self.backends.values().map(|b| b.as_ref()).collect()
304    }
305
306    /// List backends that are actually available (installed and working)
307    pub fn available(&self) -> Vec<&dyn Backend> {
308        self.backends
309            .values()
310            .filter(|b| b.is_available())
311            .map(|b| b.as_ref())
312            .collect()
313    }
314}
315
316impl Default for BackendRegistry {
317    fn default() -> Self {
318        Self::new()
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn test_registry_empty() {
328        let reg = BackendRegistry::new();
329        assert!(reg.list().is_empty());
330        assert!(reg.available().is_empty());
331        assert!(reg.get("arm").is_none());
332    }
333
334    #[test]
335    fn test_compile_config_default() {
336        let config = CompileConfig::default();
337        assert_eq!(config.opt_level, 2);
338        assert!(!config.bounds_check);
339        assert_eq!(config.safety_bounds, SafetyBounds::None);
340        assert!(!config.no_optimize);
341    }
342
343    #[test]
344    fn safety_bounds_parse_round_trip() {
345        for s in ["none", "mpu", "software", "mask"] {
346            let sb = SafetyBounds::parse(s).unwrap();
347            assert_eq!(sb.as_str(), s);
348        }
349        assert_eq!(SafetyBounds::parse("pmp").unwrap(), SafetyBounds::Mpu);
350        assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
351        assert!(SafetyBounds::parse("nonsense").is_err());
352    }
353
354    #[test]
355    fn effective_safety_bounds_legacy_promotes_to_software() {
356        let cfg = CompileConfig {
357            bounds_check: true,
358            ..Default::default()
359        };
360        assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
361    }
362
363    #[test]
364    fn effective_safety_bounds_new_field_wins() {
365        let cfg = CompileConfig {
366            bounds_check: true,
367            safety_bounds: SafetyBounds::Mpu,
368            ..Default::default()
369        };
370        assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
371    }
372}