Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 125 additions & 5 deletions crates/celox-backend-x86/src/backend/native/jit_mem.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! JIT memory: load emitted machine code into executable memory and call it.

use std::{io::Write, sync::Mutex};
use std::{
any::Any,
io::Write,
sync::{Arc, Mutex},
};

use memmap2::{Mmap, MmapMut};

Expand All @@ -24,7 +28,13 @@ pub struct JitSymbol {
/// Executable code region holding JIT-compiled machine code.
/// The code can be called as `fn(*mut u8) -> i64`.
pub struct JitCode {
_mmap: Mmap,
_mmap: Option<Mmap>,
_external_owner: Option<Arc<dyn Any + Send + Sync>>,
code_len: usize,
// Keep the retained allocation independent of the public, mutable entry.
// A function pointer preserves JitCode's Send/Sync traits without a raw
// pointer Send/Sync implementation.
image_base: JitFn,
pub fn_ptr: JitFn,
}

Expand Down Expand Up @@ -85,8 +95,43 @@ impl JitCode {
write_perf_map_entries(mmap.as_ptr() as usize, code.len().max(1), name, symbols)?;
}

let code_len = mmap.len();
Ok(Self {
_mmap: mmap,
_mmap: Some(mmap),
_external_owner: None,
code_len,
image_base: fn_ptr,
fn_ptr,
})
}

/// Retain an existing immutable executable region without copying it.
///
/// # Safety
/// `code` must point to `len` readable, executable bytes of valid target
/// code. The bytes must remain immutable and accessible while `owner` is
/// alive, and the entry must follow this backend's function ABI.
pub unsafe fn from_executable_owner(
owner: Arc<dyn Any + Send + Sync>,
code: *const u8,
len: usize,
name: &str,
symbols: &[JitSymbol],
perf_map: bool,
) -> Result<Self, std::io::Error> {
if code.is_null() || len == 0 || len > isize::MAX as usize {
return Err(std::io::Error::other("invalid executable code region"));
}
if perf_map {
write_perf_map_entries(code as usize, len, name, symbols)?;
}
// Safety: the caller supplies a live region with this entry ABI.
let fn_ptr: JitFn = unsafe { std::mem::transmute(code) };
Ok(Self {
_mmap: None,
_external_owner: Some(owner),
code_len: len,
image_base: fn_ptr,
fn_ptr,
})
}
Expand Down Expand Up @@ -124,14 +169,16 @@ impl JitCode {
/// trailing constant tables are copied together, so the runtime can retain
/// entry offsets and resolve them after placing the combined image.
pub fn entry_ptr(&self, offset: usize) -> Option<*const u8> {
(offset < self._mmap.len()).then(|| unsafe { self._mmap.as_ptr().add(offset) })
(offset < self.code_len).then(|| unsafe { (self.image_base as *const u8).add(offset) })
}

/// Bytes of the executable image, including alignment padding and constant
/// tables. This is the exact image that can later be copied into an AOT
/// container.
pub fn image(&self) -> &[u8] {
&self._mmap
// Safety: either owned mapping or external owner keeps this immutable
// executable region alive for the lifetime of this borrow.
unsafe { std::slice::from_raw_parts(self.image_base as *const u8, self.code_len) }
}
}

Expand Down Expand Up @@ -190,6 +237,79 @@ fn sanitize_perf_symbol(name: &str) -> String {
mod tests {
use super::*;

#[test]
fn external_executable_owner_survives_until_last_code_user() {
let bytes = [0xb8, 42, 0, 0, 0, 0xc3];
let owner = Arc::new(JitCode::new(&bytes).unwrap());
let weak = Arc::downgrade(&owner);
// Safety: the source is an immutable executable JitCode and the clone
// retained by this new region owns its complete backing allocation.
let borrowed = unsafe {
JitCode::from_executable_owner(
owner.clone(),
owner.image().as_ptr(),
owner.image().len(),
"owned_test_code",
&[],
false,
)
}
.unwrap();
drop(owner);
assert!(weak.upgrade().is_some());
assert_eq!(borrowed.image(), bytes);
assert!(borrowed.entry_ptr(bytes.len()).is_none());
assert_eq!(unsafe { borrowed.call(&mut []) }, 42);
drop(borrowed);
assert!(weak.upgrade().is_none());
}

fn assert_image_survives_entry_swap(mut code: JitCode, bytes: &[u8]) {
let base = code.image().as_ptr();
// Use an allocation of a different size, and release it after swapping
// the public entries. Neither image accessor may follow the new entry.
let mut other = JitCode::new(&[0xc3]).unwrap();
std::mem::swap(&mut code.fn_ptr, &mut other.fn_ptr);
assert_eq!(code.entry_ptr(0), Some(base));
drop(other);
assert_eq!(code.image(), bytes);
assert_eq!(
code.entry_ptr(bytes.len() - 1),
Some(unsafe { base.add(bytes.len() - 1) })
);
assert!(code.entry_ptr(bytes.len()).is_none());
// Execute through the retained image entry, not the swapped fn_ptr.
let entry: JitFn = unsafe { std::mem::transmute(code.entry_ptr(0).unwrap()) };
assert_eq!(unsafe { entry(std::ptr::null_mut()) }, 42);
}

#[test]
fn owned_image_is_independent_of_mutable_entry() {
let bytes = [0xb8, 42, 0, 0, 0, 0xc3];
assert_image_survives_entry_swap(JitCode::new(&bytes).unwrap(), &bytes);
}

#[test]
fn external_image_is_independent_of_mutable_entry() {
let bytes = [0xb8, 42, 0, 0, 0, 0xc3];
let owner = Arc::new(JitCode::new(&bytes).unwrap());
// Safety: owner retains the immutable executable allocation with the
// required entry ABI until the external JitCode is dropped.
let code = unsafe {
JitCode::from_executable_owner(
owner.clone(),
owner.image().as_ptr(),
owner.image().len(),
"entry_swap_test",
&[],
false,
)
}
.unwrap();
drop(owner);
assert_image_survives_entry_swap(code, &bytes);
}

#[test]
fn large_images_preserve_bytes_bounds_and_entry_points() {
for size in [4096, 2 * 1024 * 1024, 6 * 1024 * 1024 + 37] {
Expand Down
150 changes: 133 additions & 17 deletions crates/celox/src/backend/native/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use super::super::RuntimeEventBuffer;
use super::super::compile_cancel::{CompileCancel, cancelled, cancelled_error};
use super::super::traits::SimulatorErrorCode;
use super::super::{MemoryLayout, get_byte_size, memory_image::MemoryImage};
use super::code_bytes::NativeCodeBytes;
#[cfg(any(
feature = "x86_64-codegen",
all(target_arch = "x86_64", not(feature = "arm64-codegen"))
Expand Down Expand Up @@ -243,13 +244,57 @@ impl SharedNativeCode {
name: symbol.name.clone(),
})
.collect::<Vec<_>>();
let jit_image = jit_mem::JitCode::new_named_with_symbols_profiled(
program_image.code_image(),
"celox_native_image",
&symbols,
program_image.options.perf_map,
)
.map_err(|source| codegen_err(CodegenError::NativeMemory { source }))?;
#[cfg(all(
target_os = "linux",
target_arch = "x86_64",
not(feature = "arm64-codegen")
))]
let mapped = match &program_image.code {
NativeCodeBytes::Mapped { owner, range }
if program_image
.code_image()
.as_ptr()
.addr()
.is_multiple_of(64) =>
{
// Retain the previous executable allocation as a fallback if
// file execution is unavailable (for example a no-exec mount).
if owner.make_executable(range.clone()).is_ok() {
// Safety: image validation and the caller establish trusted
// target code; the Arc retains its immutable executable
// file mapping for every entry pointer's lifetime.
Some(unsafe {
jit_mem::JitCode::from_executable_owner(
owner.clone(),
program_image.code_image().as_ptr(),
program_image.code_image().len(),
"celox_native_image",
&symbols,
program_image.options.perf_map,
)
})
} else {
None
}
}
_ => None,
};
#[cfg(not(all(
target_os = "linux",
target_arch = "x86_64",
not(feature = "arm64-codegen")
)))]
let mapped: Option<Result<jit_mem::JitCode, std::io::Error>> = None;
let jit_image = mapped
.unwrap_or_else(|| {
jit_mem::JitCode::new_named_with_symbols_profiled(
program_image.code_image(),
"celox_native_image",
&symbols,
program_image.options.perf_map,
)
})
.map_err(|source| codegen_err(CodegenError::NativeMemory { source }))?;
let kernel_addresses = program_image
.runtime_schema
.native_kernel_offsets
Expand Down Expand Up @@ -460,7 +505,7 @@ pub(crate) struct NativeRuntimeSchema {
/// precompiled Celox runtime.
#[derive(Clone, Serialize, Deserialize)]
pub struct NativeProgramImage {
code: Vec<u8>,
code: NativeCodeBytes,
code_entries: Vec<NativeCodeEntry>,
symbols: Vec<NativeCodeSymbol>,
comb_offset: usize,
Expand All @@ -487,14 +532,14 @@ pub struct NativeProgramImage {

// Keep this private Postcard decoder in field order with NativeProgramImage.
// Postcard encodes both Vec<u8> and byte slices as a length followed by raw
// bytes. Borrowing that slice and copying once avoids per-byte sequence visits
// for large code images. The public Serde representation and container writer
// bytes. Borrowing that slice avoids per-byte sequence visits and allows file
// storage to back the code directly. The public Serde representation and payload
// remain unchanged, including for formats that distinguish arrays and bytes.
#[derive(Deserialize)]
#[serde(remote = "NativeProgramImage")]
struct PostcardNativeProgramImage {
#[serde(deserialize_with = "deserialize_postcard_code")]
code: Vec<u8>,
code: NativeCodeBytes,
code_entries: Vec<NativeCodeEntry>,
symbols: Vec<NativeCodeSymbol>,
comb_offset: usize,
Expand All @@ -519,16 +564,50 @@ struct PostcardNativeProgramImage {
lanes: Option<super::lanes::NativeLaneImage>,
}

fn deserialize_postcard_code<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
fn deserialize_postcard_code<'de, D>(deserializer: D) -> Result<NativeCodeBytes, D::Error>
where
D: serde::Deserializer<'de>,
{
<&[u8]>::deserialize(deserializer).map(<[u8]>::to_vec)
// The caller installs owned or mapped storage after decoding metadata.
<&[u8]>::deserialize(deserializer).map(|_| NativeCodeBytes::Owned(Vec::new()))
}

impl NativeProgramImage {
pub(super) fn from_postcard_bytes(bytes: &[u8]) -> Result<Self, postcard::Error> {
PostcardNativeProgramImage::deserialize(&mut postcard::Deserializer::from_bytes(bytes))
let (code, _) = postcard::take_from_bytes::<&[u8]>(bytes)?;
let mut image = PostcardNativeProgramImage::deserialize(
&mut postcard::Deserializer::from_bytes(bytes),
)?;
image.code = code.to_vec().into();
Ok(image)
}

#[cfg(target_os = "linux")]
pub(super) fn from_mapped_postcard_bytes(
bytes: &[u8],
owner: Arc<super::executable_mapping::ExecutableMapping>,
) -> Result<Self, postcard::Error> {
let (code, _) = postcard::take_from_bytes::<&[u8]>(bytes)?;
let mut image = PostcardNativeProgramImage::deserialize(
&mut postcard::Deserializer::from_bytes(bytes),
)?;
if !code.is_empty() {
// The container reader passes a payload slice from this same owner.
let start = code
.as_ptr()
.addr()
.checked_sub(owner.as_bytes().as_ptr().addr())
.ok_or(postcard::Error::DeserializeBadEncoding)?;
let end = start
.checked_add(code.len())
.filter(|&end| end <= owner.as_bytes().len())
.ok_or(postcard::Error::DeserializeBadEncoding)?;
image.code = NativeCodeBytes::Mapped {
owner,
range: start..end,
};
}
Ok(image)
}

/// Physical duration of one tick, retained in serialized native images.
Expand Down Expand Up @@ -3006,7 +3085,7 @@ fn compile_program_with_outlining_threshold(

Ok((
NativeProgramImage {
code: packed_image,
code: packed_image.into(),
code_entries,
symbols: image_symbols,
comb_offset,
Expand Down Expand Up @@ -4199,6 +4278,40 @@ mod tests {
BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue,
};

#[test]
fn replacing_images_does_not_accumulate_alignment_padding() {
let source =
"module Top(a: input bit<8>, b: input bit<8>, y: output bit<8>) { assign y = a + b; }";
let mut image = crate::Simulator::builder(source, "Top")
.compile_native()
.unwrap()
.into_program_image();
let original_code = image.code.to_vec();
assert!(original_code.len() < 16_383);
let directory = tempfile::tempdir().unwrap();
let runtime = directory.path().join("runtime");
std::fs::write(&runtime, b"precompiled runtime").unwrap();
let mut sizes = Vec::new();
// Crossing a Postcard length-prefix boundary changes the required
// padding. Trailing zeros test framing only and are never executed.
for length in [16_383, 16_384, 16_383, 16_384] {
let mut code = original_code.clone();
code.resize(length, 0);
image.code = code.into();
image.write_attached_runtime(&runtime, &runtime).unwrap();
let bytes = std::fs::read(&runtime).unwrap();
let found = NativeProgramImage::discover_appended(&bytes)
.unwrap()
.unwrap();
assert_eq!(found.image.code_image().len(), length);
assert!(bytes.starts_with(b"precompiled runtime"));
sizes.push(bytes.len());
}
assert_eq!(sizes[0], sizes[2]);
assert_eq!(sizes[1], sizes[3]);
assert_eq!(sizes[1], sizes[0] + 1);
}

#[test]
fn postcard_code_decoder_preserves_legacy_payloads() {
let source = "module Top(clk: input clock, d: input bit<8>, q: output bit<8>) { always_ff (clk) { q = d; } }";
Expand All @@ -4209,11 +4322,14 @@ mod tests {
// These byte patterns exercise the wire decoder only; no synthetic
// machine code is validated, mapped executable, or invoked.
for length in [0, 1, 127, 128, 255, 256, 1024] {
image.code = (0..length).map(|index| index as u8).collect();
image.code = (0..length)
.map(|index| index as u8)
.collect::<Vec<_>>()
.into();
let payload = postcard::to_allocvec(&image).unwrap();
let legacy: NativeProgramImage = postcard::from_bytes(&payload).unwrap();
let decoded = NativeProgramImage::from_postcard_bytes(&payload).unwrap();
assert_eq!(decoded.code, image.code);
assert_eq!(&*decoded.code, &*image.code);
assert_eq!(
postcard::to_allocvec(&decoded).unwrap(),
postcard::to_allocvec(&legacy).unwrap(),
Expand Down
Loading
Loading