Skip to main content

logicaffeine_forge/
patch.rs

1//! Relocation patchers — pure byte math, compiled (and unit-tested) on EVERY
2//! host so the x86-64 patchers are exercised on an arm64 dev machine and vice
3//! versa. Each function rewrites one relocation site in a staging buffer given
4//! the site's final runtime address and its target's address.
5
6use crate::stencil_model::RelocKind;
7
8/// Patch errors carry enough context to identify the failing site.
9#[derive(Debug, PartialEq, Eq)]
10pub enum PatchError {
11    /// Branch/load displacement does not fit the encoding.
12    OutOfRange {
13        /// Relocation kind name.
14        kind: &'static str,
15        /// Address of the patch site.
16        site: u64,
17        /// Address the site must reach.
18        target: u64,
19    },
20    /// arm64 targets must be 4-byte aligned for branches.
21    Misaligned {
22        /// Relocation kind name.
23        kind: &'static str,
24        /// The misaligned target address.
25        target: u64,
26    },
27    /// The value is not aligned for the access size encoded at the site.
28    BadScale {
29        /// Relocation kind name.
30        kind: &'static str,
31        /// The target address.
32        target: u64,
33        /// Access-size shift encoded at the site.
34        scale: u8,
35    },
36}
37
38impl std::fmt::Display for PatchError {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            PatchError::OutOfRange { kind, site, target } => {
42                write!(
43                    f,
44                    "{kind}: target {target:#x} out of range of site {site:#x}"
45                )
46            }
47            PatchError::Misaligned { kind, target } => {
48                write!(f, "{kind}: target {target:#x} is not 4-byte aligned")
49            }
50            PatchError::BadScale {
51                kind,
52                target,
53                scale,
54            } => {
55                write!(
56                    f,
57                    "{kind}: target {target:#x} not aligned for scale {scale}"
58                )
59            }
60        }
61    }
62}
63
64impl std::error::Error for PatchError {}
65
66fn read_u32(buf: &[u8], off: usize) -> u32 {
67    u32::from_le_bytes([buf[off], buf[off + 1], buf[off + 2], buf[off + 3]])
68}
69
70fn write_u32(buf: &mut [u8], off: usize, v: u32) {
71    buf[off..off + 4].copy_from_slice(&v.to_le_bytes());
72}
73
74/// aarch64 `b`/`bl` imm26: PC-relative, ±128 MiB, 4-byte units. Preserves the
75/// opcode bits, rewriting only the immediate.
76pub fn patch_aarch64_branch26(
77    buf: &mut [u8],
78    off: usize,
79    site_addr: u64,
80    target: u64,
81) -> Result<(), PatchError> {
82    if target % 4 != 0 {
83        return Err(PatchError::Misaligned {
84            kind: "branch26",
85            target,
86        });
87    }
88    let delta = (target as i64).wrapping_sub(site_addr as i64);
89    if !(-(1 << 27)..(1 << 27)).contains(&delta) {
90        return Err(PatchError::OutOfRange {
91            kind: "branch26",
92            site: site_addr,
93            target,
94        });
95    }
96    let imm26 = ((delta >> 2) as u32) & 0x03FF_FFFF;
97    let insn = read_u32(buf, off);
98    write_u32(buf, off, (insn & 0xFC00_0000) | imm26);
99    Ok(())
100}
101
102/// aarch64 `adrp` hi21: the PAGE delta (4 KiB pages), split immlo\[30:29\] /
103/// immhi\[23:5\]. Range ±4 GiB.
104pub fn patch_aarch64_page21(
105    buf: &mut [u8],
106    off: usize,
107    site_addr: u64,
108    target: u64,
109) -> Result<(), PatchError> {
110    let page_delta = ((target as i64) >> 12).wrapping_sub((site_addr as i64) >> 12);
111    if !(-(1 << 20)..(1 << 20)).contains(&page_delta) {
112        return Err(PatchError::OutOfRange {
113            kind: "page21",
114            site: site_addr,
115            target,
116        });
117    }
118    let imm = page_delta as u32;
119    let immlo = imm & 0b11;
120    let immhi = (imm >> 2) & 0x7FFFF;
121    let insn = read_u32(buf, off);
122    let cleared = insn & !((0b11 << 29) | (0x7FFFF << 5));
123    write_u32(buf, off, cleared | (immlo << 29) | (immhi << 5));
124    Ok(())
125}
126
127/// aarch64 `add`/`ldr` lo12: the low 12 bits of the target, shifted right by
128/// the access-size scale for loads/stores.
129pub fn patch_aarch64_pageoff12(
130    buf: &mut [u8],
131    off: usize,
132    target: u64,
133    scale: u8,
134) -> Result<(), PatchError> {
135    let lo12 = (target & 0xFFF) as u32;
136    if scale > 0 && lo12 & ((1 << scale) - 1) != 0 {
137        return Err(PatchError::BadScale {
138            kind: "pageoff12",
139            target,
140            scale,
141        });
142    }
143    let imm12 = lo12 >> scale;
144    let insn = read_u32(buf, off);
145    let cleared = insn & !(0xFFF << 10);
146    write_u32(buf, off, cleared | (imm12 << 10));
147    Ok(())
148}
149
150/// x86-64 rip-relative disp32 (`jmp`/`call`/`lea`/`mov`):
151/// `disp = target + addend − field_address`, with the rip-after-displacement
152/// distance already NORMALIZED into the addend at extraction time (ELF bakes
153/// it in natively; build.rs adjusts Mach-O and COFF to match).
154pub fn patch_x64_rel32(
155    buf: &mut [u8],
156    off: usize,
157    site_addr: u64,
158    target: u64,
159    addend: i64,
160) -> Result<(), PatchError> {
161    let delta = (target as i64)
162        .wrapping_add(addend)
163        .wrapping_sub(site_addr as i64);
164    let disp = i32::try_from(delta).map_err(|_| PatchError::OutOfRange {
165        kind: "rel32",
166        site: site_addr,
167        target,
168    })?;
169    buf[off..off + 4].copy_from_slice(&disp.to_le_bytes());
170    Ok(())
171}
172
173/// 8-byte absolute address, little-endian.
174pub fn patch_abs64(buf: &mut [u8], off: usize, target: u64, addend: i64) {
175    let v = (target as i64).wrapping_add(addend) as u64;
176    buf[off..off + 8].copy_from_slice(&v.to_le_bytes());
177}
178
179/// Whether this reloc kind resolves through a pointer slot (GOT/IAT/refptr) —
180/// the buffer layout must provide one and point the site at it.
181pub fn is_indirect(kind: RelocKind) -> bool {
182    matches!(
183        kind,
184        RelocKind::GotPage21 | RelocKind::GotPageOff12 | RelocKind::GotRel32
185    )
186}
187
188#[cfg(test)]
189#[path = "../../logicaffeine_tests/unit/logicaffeine_forge/patch/tests.rs"]
190mod tests;