Skip to main content

logicaffeine_forge/
buffer.rs

1//! The copy-and-patch assembler: glue stencils into executable code.
2//!
3//! [`JitBuffer`] collects stencil instances with their hole values, then
4//! `finish()` lays everything out — stencil code, an 8-byte-aligned literal
5//! pool for constant holes, and pointer slots for GOT-indirect sites — maps a
6//! page (learning the final base address), patches every relocation against
7//! that base, writes ONCE, and seals. No mutable window ever escapes; W^X
8//! toggling stays confined to the constructing thread.
9//!
10//! Layout:
11//! ```text
12//! [piece 0][piece 1]…[piece N]  [pointer slots…]  [value slots…]
13//!  ^code, 16-byte aligned        ^8-byte aligned GOT-style slots
14//! ```
15
16use crate::patch;
17use crate::stencil_model::{HoleId, RelocKind, Stencil};
18use crate::{JitError, JitPage};
19
20/// A placed stencil instance, identifying a continuation target.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct Label(usize);
23
24/// What to plug into a stencil's holes, by hole id.
25#[derive(Clone, Copy, Debug)]
26pub enum HoleValue {
27    /// Continuation hole N jumps to this piece.
28    Cont(u8, Label),
29    /// Constant hole N reads this value.
30    Const(u8, i64),
31}
32
33/// Assembly errors.
34#[derive(Debug)]
35pub enum BufferError {
36    /// A hole had no value supplied.
37    MissingHoleValue {
38        /// The stencil whose hole went unfilled.
39        stencil: &'static str,
40        /// The unfilled hole.
41        hole: HoleId,
42    },
43    /// A label referenced a piece that does not exist.
44    UnresolvedLabel(Label),
45    /// A relocation could not be patched.
46    Patch(patch::PatchError),
47    /// The page could not be created.
48    Jit(JitError),
49    /// The buffer has no pieces.
50    Empty,
51}
52
53impl std::fmt::Display for BufferError {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        match self {
56            BufferError::MissingHoleValue { stencil, hole } => {
57                write!(f, "stencil '{stencil}': no value for hole {hole:?}")
58            }
59            BufferError::UnresolvedLabel(l) => write!(f, "unresolved label {l:?}"),
60            BufferError::Patch(e) => write!(f, "patch failed: {e}"),
61            BufferError::Jit(e) => write!(f, "page failed: {e}"),
62            BufferError::Empty => write!(f, "empty JitBuffer"),
63        }
64    }
65}
66
67impl std::error::Error for BufferError {}
68
69struct Piece {
70    stencil: &'static Stencil,
71    holes: Vec<HoleValue>,
72}
73
74/// The staged assembly.
75#[derive(Default)]
76pub struct JitBuffer {
77    pieces: Vec<Piece>,
78    patch_marks: Vec<(usize, u8)>,
79}
80
81/// A finished, executable chain.
82#[derive(Debug)]
83pub struct JitChain {
84    page: JitPage,
85    pieces: usize,
86    /// Literal-pool offsets awaiting the post-finish self-entry patch.
87    patch_slots: Vec<usize>,
88}
89
90impl JitChain {
91    /// Wrap a finished, self-contained block of machine code (no stencil
92    /// pieces, no post-seal patch slots) as a runnable chain. The contiguous
93    /// register-allocated region backend (`compile_region_regalloc`) emits its
94    /// whole function as one such block, then runs it through the SAME
95    /// `run_with_frame` ABI as a stencil chain.
96    ///
97    /// `pieces` is the logical op count (diagnostics only); the executable is
98    /// one contiguous function regardless.
99    pub fn from_code(code: &[u8], pieces: usize) -> Result<JitChain, crate::JitError> {
100        let page = JitPage::new(code)?;
101        Ok(JitChain {
102            page,
103            pieces,
104            patch_slots: Vec::new(),
105        })
106    }
107
108    /// Write `value` into every marked literal-pool slot (the self-call
109    /// entry address, known only after layout). Errs on targets without
110    /// post-seal patching (Apple Silicon MAP_JIT) — callers fall back to
111    /// the table-indirect call.
112    pub fn patch_marked(&self, value: u64) -> Result<(), crate::JitError> {
113        for &slot in &self.patch_slots {
114            self.page.patch_word(slot, value)?;
115        }
116        Ok(())
117    }
118
119    /// Whether any slots await the self-entry patch.
120    pub fn has_patch_marks(&self) -> bool {
121        !self.patch_slots.is_empty()
122    }
123
124    /// The CPS entry point: `fn(base, sp) -> i64` — `base` is the frame (the
125    /// compiled function's register slots), `sp` the operand-stack top.
126    ///
127    /// # Safety
128    /// `base` must point at a frame at least as large as every patched slot
129    /// index; `sp` must point into an operand stack with capacity for the
130    /// chain's pushes; the page must outlive every call.
131    pub unsafe fn entry(
132        &self,
133    ) -> unsafe extern "C" fn(
134        *mut i64,
135        *mut i64,
136        i64,
137        i64,
138        i64,
139        i64,
140        f64,
141        f64,
142        f64,
143        f64,
144        f64,
145        f64,
146    ) -> i64 {
147        std::mem::transmute::<
148            *const u8,
149            unsafe extern "C" fn(
150                *mut i64,
151                *mut i64,
152                i64,
153                i64,
154                i64,
155                i64,
156                f64,
157                f64,
158                f64,
159                f64,
160                f64,
161                f64,
162            ) -> i64,
163        >(self.page.as_ptr())
164    }
165
166    /// Run the chain with an empty frame and a fresh operand stack.
167    pub fn run(&self) -> i64 {
168        let mut frame = vec![0i64; 64];
169        self.run_with_frame(&mut frame)
170    }
171
172    /// Run the chain over the given frame (slot 0 = VM register 0, …), with a
173    /// fresh operand stack. The frame is read AND written by slot stencils.
174    ///
175    /// `LOGOS_JIT_CANARY=1` guards the operand stack with a sentinel canary
176    /// past its end: any stencil that pushes beyond the 256-slot stack (a
177    /// pc/sp miscompile) trips it loudly at the source instead of silently
178    /// corrupting adjacent memory. It is env-gated rather than always-on
179    /// because this runs per chain — millions of times for hot recursion —
180    /// so the default (and every release build) pays nothing.
181    pub fn run_with_frame(&self, frame: &mut [i64]) -> i64 {
182        const STACK: usize = 256;
183        const CANARY: usize = 64;
184        const SENTINEL: i64 = 0x5151_5151_5151_5151u64 as i64;
185        if jit_canary_enabled() {
186            let mut stack = vec![0i64; STACK + CANARY];
187            for c in &mut stack[STACK..] {
188                *c = SENTINEL;
189            }
190            let r = unsafe {
191                (self.entry())(
192                    frame.as_mut_ptr(),
193                    stack.as_mut_ptr(),
194                    0,
195                    0,
196                    0,
197                    0,
198                    0.0,
199                    0.0,
200                    0.0,
201                    0.0,
202                    0.0,
203                    0.0,
204                )
205            };
206            for (k, c) in stack[STACK..].iter().enumerate() {
207                assert_eq!(
208                    *c,
209                    SENTINEL,
210                    "OPERAND STACK OVERFLOW: canary slot {k} (stack base + {}) clobbered",
211                    STACK + k
212                );
213            }
214            return r;
215        }
216        let mut stack = vec![0i64; STACK];
217        // Threaded registers enter zeroed; a pinned chain's prologue
218        // reloads them from the frame before any use.
219        unsafe {
220            (self.entry())(
221                frame.as_mut_ptr(),
222                stack.as_mut_ptr(),
223                0,
224                0,
225                0,
226                0,
227                0.0,
228                0.0,
229                0.0,
230                0.0,
231                0.0,
232                0.0,
233            )
234        }
235    }
236
237    /// The mapped code+pool bytes (diagnostics/tests).
238    pub fn bytes(&self) -> &[u8] {
239        unsafe { std::slice::from_raw_parts(self.page.as_ptr(), self.page.len()) }
240    }
241
242    /// The runtime base address (diagnostics/tests).
243    pub fn base(&self) -> u64 {
244        self.page.as_ptr() as u64
245    }
246
247    /// How many stencil pieces were glued (diagnostics/tests — the
248    /// tail-jump economics of a lowering).
249    pub fn piece_count(&self) -> usize {
250        self.pieces
251    }
252}
253
254/// Whether `LOGOS_JIT_CANARY=1` armed the operand-stack / region-frame
255/// sentinel guards (read once; the per-chain path stays branch-cheap).
256pub fn jit_canary_enabled() -> bool {
257    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
258    *ON.get_or_init(|| std::env::var("LOGOS_JIT_CANARY").is_ok_and(|v| v == "1"))
259}
260
261const PIECE_ALIGN: usize = 16;
262const SLOT_SIZE: usize = 8;
263
264fn align_up(v: usize, a: usize) -> usize {
265    v.div_ceil(a) * a
266}
267
268impl JitBuffer {
269    /// An empty buffer.
270    pub fn new() -> Self {
271        JitBuffer::default()
272    }
273
274    /// Append a stencil instance; the returned [`Label`] is its address for
275    /// continuation holes (including back-edges to earlier pieces).
276    /// Mark hole `n` of the LAST pushed piece for post-finish patching
277    /// (the self-call entry slot).
278    pub fn mark_patch_hole(&mut self, hole_n: u8) {
279        let pi = self.pieces.len().checked_sub(1).expect("mark after a push");
280        self.patch_marks.push((pi, hole_n));
281    }
282
283    /// How many stencil pieces have been pushed so far (the index the next
284    /// `push_stencil` will occupy). Used to assert PASS-1/PASS-2 agreement.
285    pub fn pieces_pushed(&self) -> usize {
286        self.pieces.len()
287    }
288
289    pub fn push_stencil(&mut self, stencil: &'static Stencil, holes: &[HoleValue]) -> Label {
290        self.pieces.push(Piece {
291            stencil,
292            holes: holes.to_vec(),
293        });
294        Label(self.pieces.len() - 1)
295    }
296
297    /// The label of the piece at `index` — usable for FORWARD references
298    /// (validated when `finish` runs).
299    pub fn label(&self, index: usize) -> Label {
300        Label(index)
301    }
302
303    /// Lay out, map, patch against the final base, write once, seal.
304    pub fn finish(self) -> Result<JitChain, BufferError> {
305        if self.pieces.is_empty() {
306            return Err(BufferError::Empty);
307        }
308
309        // Piece offsets.
310        let mut piece_off: Vec<usize> = Vec::with_capacity(self.pieces.len());
311        let mut cursor = 0usize;
312        for piece in &self.pieces {
313            cursor = align_up(cursor, PIECE_ALIGN);
314            piece_off.push(cursor);
315            cursor += piece.stencil.code.len();
316        }
317
318        // Slot assignment: one VALUE slot per Const hole instance; one POINTER
319        // slot per (piece, hole) among indirect relocs — SHARED by every
320        // indirect reloc of that hole. An arm64 GOT load is an ADRP+LDR PAIR
321        // (two relocs, one hole): the ADRP contributes the 4 KiB page and the
322        // LDR the low 12 bits, so both MUST resolve to the same slot or the
323        // composed address breaks as soon as the pool straddles a page
324        // boundary.
325        let mut value_slot: Vec<Vec<Option<usize>>> = Vec::new(); // [piece][hole-n] -> slot off
326        let mut pointer_slot: std::collections::HashMap<(usize, HoleId), usize> =
327            std::collections::HashMap::new();
328        let mut slot_cursor = align_up(cursor, SLOT_SIZE);
329
330        for (pi, piece) in self.pieces.iter().enumerate() {
331            let mut per_hole: Vec<Option<usize>> = vec![None; 9];
332            for hv in &piece.holes {
333                if let HoleValue::Const(n, _) = hv {
334                    if per_hole[*n as usize].is_none() {
335                        per_hole[*n as usize] = Some(slot_cursor);
336                        slot_cursor += SLOT_SIZE;
337                    }
338                }
339            }
340            value_slot.push(per_hole);
341            for reloc in piece.stencil.relocs.iter() {
342                if patch::is_indirect(reloc.kind) {
343                    pointer_slot.entry((pi, reloc.target)).or_insert_with(|| {
344                        let s = slot_cursor;
345                        slot_cursor += SLOT_SIZE;
346                        s
347                    });
348                }
349            }
350        }
351        let total_len = slot_cursor;
352
353        // Resolve a hole on a piece to (target address fn of base, is_const_value).
354        let find_hole = |piece: &Piece, hole: HoleId| -> Result<HoleValue, BufferError> {
355            for hv in &piece.holes {
356                match (hv, hole) {
357                    (HoleValue::Cont(n, _), HoleId::Cont(m)) if *n == m => return Ok(*hv),
358                    (HoleValue::Const(n, _), HoleId::ConstI64(m)) if *n == m => return Ok(*hv),
359                    _ => {}
360                }
361            }
362            Err(BufferError::MissingHoleValue {
363                stencil: piece.stencil.name,
364                hole,
365            })
366        };
367
368        // Validate labels up front.
369        for piece in &self.pieces {
370            for hv in &piece.holes {
371                if let HoleValue::Cont(_, Label(t)) = hv {
372                    if *t >= self.pieces.len() {
373                        return Err(BufferError::UnresolvedLabel(Label(*t)));
374                    }
375                }
376            }
377        }
378
379        let pieces = self.pieces;
380        let patch_marks = self.patch_marks;
381        let mut patch_err: Option<BufferError> = None;
382        let page = JitPage::with_layout(total_len, |base| {
383            let mut buf = vec![0u8; total_len];
384
385            // Copy stencil code.
386            for (pi, piece) in pieces.iter().enumerate() {
387                let off = piece_off[pi];
388                buf[off..off + piece.stencil.code.len()].copy_from_slice(piece.stencil.code);
389            }
390
391            let mut do_patch = || -> Result<(), BufferError> {
392                // Fill value slots.
393                for (pi, piece) in pieces.iter().enumerate() {
394                    for hv in &piece.holes {
395                        if let HoleValue::Const(n, v) = hv {
396                            if let Some(slot) = value_slot[pi][*n as usize] {
397                                buf[slot..slot + 8].copy_from_slice(&v.to_le_bytes());
398                            }
399                        }
400                    }
401                }
402                // Fill pointer slots (one per (piece, hole)).
403                for (&(pi, hole), &slot) in &pointer_slot {
404                    let piece = &pieces[pi];
405                    let content: u64 = match find_hole(piece, hole)? {
406                        HoleValue::Cont(_, Label(t)) => base + piece_off[t] as u64,
407                        HoleValue::Const(n, _) => {
408                            let vslot =
409                                value_slot[pi][n as usize].expect("const hole has a value slot");
410                            base + vslot as u64
411                        }
412                    };
413                    buf[slot..slot + 8].copy_from_slice(&content.to_le_bytes());
414                }
415
416                // Patch every relocation site.
417                for (pi, piece) in pieces.iter().enumerate() {
418                    for reloc in piece.stencil.relocs.iter() {
419                        let site_off = piece_off[pi] + reloc.offset as usize;
420                        let site_addr = base + site_off as u64;
421                        // The address the SITE refers to: a pointer slot for
422                        // indirect kinds, else the direct target.
423                        let target_addr: u64 = if patch::is_indirect(reloc.kind) {
424                            base + pointer_slot[&(pi, reloc.target)] as u64
425                        } else {
426                            match find_hole(piece, reloc.target)? {
427                                HoleValue::Cont(_, Label(t)) => base + piece_off[t] as u64,
428                                HoleValue::Const(n, _) => {
429                                    let vslot = value_slot[pi][n as usize]
430                                        .expect("const hole has a value slot");
431                                    base + vslot as u64
432                                }
433                            }
434                        };
435                        let r = match reloc.kind {
436                            RelocKind::Branch26 => patch::patch_aarch64_branch26(
437                                &mut buf,
438                                site_off,
439                                site_addr,
440                                target_addr,
441                            ),
442                            RelocKind::Page21 | RelocKind::GotPage21 => {
443                                patch::patch_aarch64_page21(
444                                    &mut buf,
445                                    site_off,
446                                    site_addr,
447                                    target_addr,
448                                )
449                            }
450                            RelocKind::PageOff12 { scale } => patch::patch_aarch64_pageoff12(
451                                &mut buf,
452                                site_off,
453                                target_addr,
454                                scale,
455                            ),
456                            RelocKind::GotPageOff12 => {
457                                patch::patch_aarch64_pageoff12(&mut buf, site_off, target_addr, 3)
458                            }
459                            RelocKind::Rel32 | RelocKind::GotRel32 => patch::patch_x64_rel32(
460                                &mut buf,
461                                site_off,
462                                site_addr,
463                                target_addr,
464                                reloc.addend,
465                            ),
466                            RelocKind::Abs64 => {
467                                patch::patch_abs64(&mut buf, site_off, target_addr, reloc.addend);
468                                Ok(())
469                            }
470                        };
471                        r.map_err(BufferError::Patch)?;
472                    }
473                }
474                Ok(())
475            };
476            if let Err(e) = do_patch() {
477                patch_err = Some(e);
478            }
479            buf
480        })
481        .map_err(BufferError::Jit)?;
482
483        if let Some(e) = patch_err {
484            return Err(e);
485        }
486        let patch_slots: Vec<usize> = patch_marks
487            .iter()
488            .map(|&(pi, n)| value_slot[pi][n as usize].expect("marked hole has a const value slot"))
489            .collect();
490        Ok(JitChain {
491            page,
492            pieces: pieces.len(),
493            patch_slots,
494        })
495    }
496}