Skip to main content

logicaffeine_forge/
lib.rs

1// The copy-and-patch JIT extracts stencils from rustc's tail-call codegen, which
2// only holds under the x86_64 System V ABI (Linux + macOS). On Windows x64 (MS
3// ABI) and aarch64, rustc emits a plain `call` at continuation sites, so the
4// stencil chain would grow the stack — those targets run the bytecode VM instead
5// (this crate compiles to nothing there, exactly like wasm32).
6#![cfg(all(target_arch = "x86_64", not(target_os = "windows")))]
7#![doc = include_str!("../README.md")]
8
9use std::fmt;
10use std::mem;
11
12pub mod buffer;
13pub mod jit;
14pub mod patch;
15#[cfg(target_arch = "x86_64")]
16pub mod regalloc;
17pub mod segv_trace;
18mod stencil_model;
19pub mod vectorize;
20#[cfg(target_arch = "x86_64")]
21pub mod x64asm;
22pub use stencil_model::{HoleId, Reloc, RelocKind, Stencil};
23
24// Build-time-extracted stencils (machine code of the Rust functions in
25// `stencils/int_stencils.rs`). See build.rs.
26include!(concat!(env!("OUT_DIR"), "/stencils.rs"));
27
28/// Executable-memory errors.
29#[derive(Debug)]
30pub enum JitError {
31    /// `JitPage::new` was given no code.
32    EmptyCode,
33    /// The executable mapping could not be created.
34    Map(std::io::Error),
35    /// The mapping could not be flipped to read+execute.
36    Protect(std::io::Error),
37}
38
39impl fmt::Display for JitError {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match self {
42            JitError::EmptyCode => write!(f, "JitPage: empty code"),
43            JitError::Map(e) => write!(f, "executable mapping failed: {e}"),
44            JitError::Protect(e) => write!(f, "marking page executable failed: {e}"),
45        }
46    }
47}
48
49impl std::error::Error for JitError {}
50
51/// A page-aligned block of executable memory holding JIT-compiled machine code.
52#[derive(Debug)]
53pub struct JitPage {
54    ptr: *mut u8,
55    /// Bytes of machine code written.
56    code_len: usize,
57    /// Bytes actually mapped (code_len rounded up to the page size) — the
58    /// length that must be passed back when unmapping.
59    alloc_len: usize,
60}
61
62// SAFETY: the page's code is written and sealed inside `new` before the value
63// exists; afterwards JitPage is an immutable handle to read/execute-only
64// memory, which is safe to use AND share across threads (no interior
65// mutability — execution only reads the mapping).
66unsafe impl Send for JitPage {}
67unsafe impl Sync for JitPage {}
68
69impl JitPage {
70    /// Allocate an executable page, copy `code` into it, and make it runnable.
71    pub fn new(code: &[u8]) -> Result<JitPage, JitError> {
72        if code.is_empty() {
73            return Err(JitError::EmptyCode);
74        }
75        let page = page_size();
76        let alloc_len = code.len().div_ceil(page) * page;
77        let ptr = map_executable(alloc_len)?;
78        debug_assert_eq!(
79            ptr as usize % page,
80            0,
81            "executable mapping is not page-aligned"
82        );
83        unsafe {
84            write_code(ptr, code)?;
85        }
86        Ok(JitPage {
87            ptr,
88            code_len: code.len(),
89            alloc_len,
90        })
91    }
92
93    /// Patch one 8-byte LITERAL-POOL word after sealing (the self-call
94    /// entry: a chain's own base address becomes known only after layout).
95    /// Data-only — the word lives in the pool, never decoded as code — so
96    /// no instruction-cache concerns; the brief RW window happens on the
97    /// compiling thread before the chain ever runs.
98    #[cfg(all(unix, not(all(target_os = "macos", target_arch = "aarch64"))))]
99    pub fn patch_word(&self, offset: usize, value: u64) -> Result<(), JitError> {
100        assert!(offset + 8 <= self.code_len, "patch outside the mapping");
101        let page = page_size();
102        let start = (self.ptr as usize + offset) & !(page - 1);
103        let end = self.ptr as usize + offset + 8;
104        let len = end - start;
105        unsafe {
106            let rc = libc::mprotect(
107                start as *mut libc::c_void,
108                len,
109                libc::PROT_READ | libc::PROT_WRITE,
110            );
111            if rc != 0 {
112                return Err(JitError::Protect(std::io::Error::last_os_error()));
113            }
114            std::ptr::write_unaligned(self.ptr.add(offset) as *mut u64, value);
115            let rc = libc::mprotect(
116                start as *mut libc::c_void,
117                len,
118                libc::PROT_READ | libc::PROT_EXEC,
119            );
120            if rc != 0 {
121                return Err(JitError::Protect(std::io::Error::last_os_error()));
122            }
123        }
124        Ok(())
125    }
126
127    /// Self-entry patching is unsupported on MAP_JIT targets (Apple
128    /// Silicon) — callers fall back to the table-indirect call stencil.
129    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
130    pub fn patch_word(&self, _offset: usize, _value: u64) -> Result<(), JitError> {
131        Err(JitError::EmptyCode)
132    }
133
134    /// Two-phase construction for PATCHED code: maps first (so the final base
135    /// address is known), lets `fill` produce the bytes against that base,
136    /// then writes and seals. `fill` must return exactly `len` bytes.
137    pub fn with_layout(len: usize, fill: impl FnOnce(u64) -> Vec<u8>) -> Result<JitPage, JitError> {
138        if len == 0 {
139            return Err(JitError::EmptyCode);
140        }
141        let page = page_size();
142        let alloc_len = len.div_ceil(page) * page;
143        let ptr = map_executable(alloc_len)?;
144        let code = fill(ptr as u64);
145        debug_assert_eq!(code.len(), len, "fill returned a different length");
146        unsafe {
147            write_code(ptr, &code)?;
148        }
149        Ok(JitPage {
150            ptr,
151            code_len: len,
152            alloc_len,
153        })
154    }
155
156    /// Reinterpret the page as an `extern "C" fn(i64, i64) -> i64`.
157    ///
158    /// # Safety
159    /// The caller must guarantee the page actually contains valid machine code
160    /// implementing this exact signature, and must not call the pointer after
161    /// the `JitPage` is dropped.
162    pub unsafe fn as_fn_i64_i64(&self) -> extern "C" fn(i64, i64) -> i64 {
163        mem::transmute::<*mut u8, extern "C" fn(i64, i64) -> i64>(self.ptr)
164    }
165
166    /// Raw pointer to the executable code (for patching / inspection).
167    pub fn as_ptr(&self) -> *const u8 {
168        self.ptr
169    }
170
171    /// Length of the machine code in bytes (the mapping itself is
172    /// [`JitPage::alloc_len`] bytes).
173    pub fn len(&self) -> usize {
174        self.code_len
175    }
176
177    /// Bytes actually mapped (page-size multiple).
178    pub fn alloc_len(&self) -> usize {
179        self.alloc_len
180    }
181
182    /// Whether the page is empty (always false; `new` rejects empty code).
183    pub fn is_empty(&self) -> bool {
184        self.code_len == 0
185    }
186}
187
188impl Drop for JitPage {
189    fn drop(&mut self) {
190        unsafe {
191            #[cfg(unix)]
192            {
193                let rc = libc::munmap(self.ptr as *mut libc::c_void, self.alloc_len);
194                debug_assert_eq!(rc, 0, "munmap failed for a JitPage mapping");
195            }
196            #[cfg(windows)]
197            {
198                let rc = windows_sys::Win32::System::Memory::VirtualFree(
199                    self.ptr as *mut core::ffi::c_void,
200                    0,
201                    windows_sys::Win32::System::Memory::MEM_RELEASE,
202                );
203                debug_assert_ne!(rc, 0, "VirtualFree failed for a JitPage mapping");
204            }
205        }
206    }
207}
208
209/// The system page size (Apple Silicon uses 16 KiB; most x86-64 systems 4 KiB).
210fn page_size() -> usize {
211    #[cfg(unix)]
212    unsafe {
213        let sz = libc::sysconf(libc::_SC_PAGESIZE);
214        if sz > 0 {
215            sz as usize
216        } else {
217            4096
218        }
219    }
220    #[cfg(windows)]
221    unsafe {
222        let mut info = mem::zeroed::<windows_sys::Win32::System::SystemInformation::SYSTEM_INFO>();
223        windows_sys::Win32::System::SystemInformation::GetSystemInfo(&mut info);
224        info.dwPageSize as usize
225    }
226}
227
228// ---------------------------------------------------------------------------
229// macOS / Apple Silicon: MAP_JIT + write-protect toggling.
230// ---------------------------------------------------------------------------
231
232#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
233mod sys {
234    /// `MAP_JIT` is required for executable allocations under the hardened
235    /// runtime on Apple Silicon.
236    pub const MAP_JIT: libc::c_int = 0x800;
237
238    extern "C" {
239        /// Toggle the calling thread's JIT region between writable (`0`) and
240        /// executable (`1`). PER-THREAD state — confined to `JitPage::new`.
241        pub fn pthread_jit_write_protect_np(enabled: libc::c_int);
242        /// Flush the instruction cache for a region after writing code into it.
243        pub fn sys_icache_invalidate(start: *mut libc::c_void, len: libc::size_t);
244    }
245}
246
247#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
248fn map_executable(len: usize) -> Result<*mut u8, JitError> {
249    let ptr = unsafe {
250        libc::mmap(
251            std::ptr::null_mut(),
252            len,
253            libc::PROT_READ | libc::PROT_WRITE | libc::PROT_EXEC,
254            libc::MAP_PRIVATE | libc::MAP_ANON | sys::MAP_JIT,
255            -1,
256            0,
257        )
258    };
259    if ptr == libc::MAP_FAILED {
260        return Err(JitError::Map(std::io::Error::last_os_error()));
261    }
262    Ok(ptr as *mut u8)
263}
264
265#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
266unsafe fn write_code(dst: *mut u8, code: &[u8]) -> Result<(), JitError> {
267    // Make the JIT region writable for THIS thread, copy, then re-protect.
268    sys::pthread_jit_write_protect_np(0);
269    std::ptr::copy_nonoverlapping(code.as_ptr(), dst, code.len());
270    sys::pthread_jit_write_protect_np(1);
271    // ARM requires an explicit I-cache flush of freshly written code.
272    sys::sys_icache_invalidate(dst as *mut libc::c_void, code.len());
273    Ok(())
274}
275
276// ---------------------------------------------------------------------------
277// Other Unix (Linux, Intel macOS): mmap RW, then mprotect to RX.
278// ---------------------------------------------------------------------------
279
280#[cfg(all(unix, not(all(target_os = "macos", target_arch = "aarch64"))))]
281fn map_executable(len: usize) -> Result<*mut u8, JitError> {
282    let ptr = unsafe {
283        libc::mmap(
284            std::ptr::null_mut(),
285            len,
286            libc::PROT_READ | libc::PROT_WRITE,
287            libc::MAP_PRIVATE | libc::MAP_ANON,
288            -1,
289            0,
290        )
291    };
292    if ptr == libc::MAP_FAILED {
293        return Err(JitError::Map(std::io::Error::last_os_error()));
294    }
295    Ok(ptr as *mut u8)
296}
297
298#[cfg(all(unix, not(all(target_os = "macos", target_arch = "aarch64"))))]
299unsafe fn write_code(dst: *mut u8, code: &[u8]) -> Result<(), JitError> {
300    std::ptr::copy_nonoverlapping(code.as_ptr(), dst, code.len());
301    let rc = libc::mprotect(
302        dst as *mut libc::c_void,
303        code.len(),
304        libc::PROT_READ | libc::PROT_EXEC,
305    );
306    if rc != 0 {
307        return Err(JitError::Protect(std::io::Error::last_os_error()));
308    }
309    // `mprotect` does NOT flush the instruction cache on ARM.
310    #[cfg(target_arch = "aarch64")]
311    flush_icache_aarch64(dst, code.len());
312    Ok(())
313}
314
315/// aarch64 I-cache flush (Linux): clean D-cache to the point of unification,
316/// invalidate I-cache, then synchronize. 64-byte lines is a safe lower bound.
317#[cfg(all(unix, target_arch = "aarch64", not(target_os = "macos")))]
318unsafe fn flush_icache_aarch64(start: *mut u8, len: usize) {
319    const LINE: usize = 64;
320    let begin = start as usize & !(LINE - 1);
321    let end = start as usize + len;
322    let mut addr = begin;
323    while addr < end {
324        core::arch::asm!("dc cvau, {0}", in(reg) addr, options(nostack, preserves_flags));
325        addr += LINE;
326    }
327    core::arch::asm!("dsb ish", options(nostack, preserves_flags));
328    let mut addr = begin;
329    while addr < end {
330        core::arch::asm!("ic ivau, {0}", in(reg) addr, options(nostack, preserves_flags));
331        addr += LINE;
332    }
333    core::arch::asm!("dsb ish", "isb", options(nostack, preserves_flags));
334}
335
336// ---------------------------------------------------------------------------
337// Windows: VirtualAlloc RW → copy → VirtualProtect RX → FlushInstructionCache.
338// ---------------------------------------------------------------------------
339
340#[cfg(windows)]
341fn map_executable(len: usize) -> Result<*mut u8, JitError> {
342    use windows_sys::Win32::System::Memory::{
343        VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE,
344    };
345    let ptr = unsafe {
346        VirtualAlloc(
347            std::ptr::null(),
348            len,
349            MEM_COMMIT | MEM_RESERVE,
350            PAGE_READWRITE,
351        )
352    };
353    if ptr.is_null() {
354        return Err(JitError::Map(std::io::Error::last_os_error()));
355    }
356    Ok(ptr as *mut u8)
357}
358
359#[cfg(windows)]
360unsafe fn write_code(dst: *mut u8, code: &[u8]) -> Result<(), JitError> {
361    use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
362    use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READ};
363    use windows_sys::Win32::System::Threading::GetCurrentProcess;
364
365    std::ptr::copy_nonoverlapping(code.as_ptr(), dst, code.len());
366    let mut old = 0u32;
367    let rc = VirtualProtect(
368        dst as *const core::ffi::c_void,
369        code.len(),
370        PAGE_EXECUTE_READ,
371        &mut old,
372    );
373    if rc == 0 {
374        return Err(JitError::Protect(std::io::Error::last_os_error()));
375    }
376    let rc = FlushInstructionCache(
377        GetCurrentProcess(),
378        dst as *const core::ffi::c_void,
379        code.len(),
380    );
381    if rc == 0 {
382        return Err(JitError::Protect(std::io::Error::last_os_error()));
383    }
384    Ok(())
385}
386
387#[cfg(test)]
388#[path = "../../logicaffeine_tests/unit/logicaffeine_forge/tests.rs"]
389mod tests;