From 943ba42ba1e6f1d0a73c7ea793bcb196ea52c58a Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 03:56:58 +0900 Subject: [PATCH] perf(native): keep attached machine code in file mappings Loading an attached image allocated an owned copy of its machine code before copying it again into executable memory. Retain immutable mapped code with Arc ownership and use aligned file pages directly on Linux x86-64. Unsupported or unaligned mappings retain the anonymous executable allocation path. Align newly attached code to 4 KiB, or 2 MiB for large images. A checksummed optional prefix descriptor records the original runtime length so replacement across Postcard length boundaries cannot accumulate padding. The Postcard payload, generic Serde representation and container version remain compatible. Keep image bytes and offset resolution tied to a private immutable base, even when callers replace the public entry pointer. Cover both owned and external backing lifetimes with entry-swap and owner-drop regressions. Validation: 20 native units, 627 x86 backend units, 36 native image/cache consumer tests, 68 VPI unit/API tests, 10 cocotb integrations, 330 native common cases (including wide, four-state and parallel execution), affected-target clippy with warnings denied, and formatting. Regressions cover retained owner lifetimes, legacy payload encoding, bounded replacement and corrupt padding. Change-Id: Idc33e7f4db1b90e2cf48d03f0fd39049aebda302 --- .../src/backend/native/jit_mem.rs | 130 ++++++++++- crates/celox/src/backend/native/backend.rs | 150 +++++++++++-- crates/celox/src/backend/native/code_bytes.rs | 47 ++++ .../src/backend/native/executable_mapping.rs | 34 +++ crates/celox/src/backend/native/image_file.rs | 207 +++++++++++++++--- crates/celox/src/backend/native/mod.rs | 1 + crates/celox/tests/shared_jit_cache.rs | 15 +- 7 files changed, 532 insertions(+), 52 deletions(-) create mode 100644 crates/celox/src/backend/native/code_bytes.rs diff --git a/crates/celox-backend-x86/src/backend/native/jit_mem.rs b/crates/celox-backend-x86/src/backend/native/jit_mem.rs index 52b03e3bb19..420f4853903 100644 --- a/crates/celox-backend-x86/src/backend/native/jit_mem.rs +++ b/crates/celox-backend-x86/src/backend/native/jit_mem.rs @@ -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}; @@ -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, + _external_owner: Option>, + 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, } @@ -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, + code: *const u8, + len: usize, + name: &str, + symbols: &[JitSymbol], + perf_map: bool, + ) -> Result { + 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, }) } @@ -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) } } } @@ -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] { diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 7b8be141152..dda7a05dfeb 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -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")) @@ -243,13 +244,57 @@ impl SharedNativeCode { name: symbol.name.clone(), }) .collect::>(); - 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> = 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 @@ -460,7 +505,7 @@ pub(crate) struct NativeRuntimeSchema { /// precompiled Celox runtime. #[derive(Clone, Serialize, Deserialize)] pub struct NativeProgramImage { - code: Vec, + code: NativeCodeBytes, code_entries: Vec, symbols: Vec, comb_offset: usize, @@ -487,14 +532,14 @@ pub struct NativeProgramImage { // Keep this private Postcard decoder in field order with NativeProgramImage. // Postcard encodes both Vec 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, + code: NativeCodeBytes, code_entries: Vec, symbols: Vec, comb_offset: usize, @@ -519,16 +564,50 @@ struct PostcardNativeProgramImage { lanes: Option, } -fn deserialize_postcard_code<'de, D>(deserializer: D) -> Result, D::Error> +fn deserialize_postcard_code<'de, D>(deserializer: D) -> Result 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 { - 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, + ) -> Result { + 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. @@ -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, @@ -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; } }"; @@ -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::>() + .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(), diff --git a/crates/celox/src/backend/native/code_bytes.rs b/crates/celox/src/backend/native/code_bytes.rs new file mode 100644 index 00000000000..93f83cdb7b8 --- /dev/null +++ b/crates/celox/src/backend/native/code_bytes.rs @@ -0,0 +1,47 @@ +use std::ops::Deref; +#[cfg(target_os = "linux")] +use std::{ops::Range, sync::Arc}; + +#[cfg(target_os = "linux")] +use super::executable_mapping::ExecutableMapping; +use serde::{Deserialize, Serialize}; + +#[derive(Clone)] +pub(super) enum NativeCodeBytes { + Owned(Vec), + #[cfg(target_os = "linux")] + Mapped { + owner: Arc, + range: Range, + }, +} + +impl From> for NativeCodeBytes { + fn from(bytes: Vec) -> Self { + Self::Owned(bytes) + } +} + +impl Deref for NativeCodeBytes { + type Target = [u8]; + fn deref(&self) -> &[u8] { + match self { + Self::Owned(bytes) => bytes, + #[cfg(target_os = "linux")] + Self::Mapped { owner, range } => &owner.as_bytes()[range.clone()], + } + } +} + +// Preserve the generic Vec Serde representation, including array-based +// formats. Only the private container decoder borrows Postcard byte spans. +impl Serialize for NativeCodeBytes { + fn serialize(&self, serializer: S) -> Result { + self.deref().serialize(serializer) + } +} +impl<'de> Deserialize<'de> for NativeCodeBytes { + fn deserialize>(deserializer: D) -> Result { + Vec::::deserialize(deserializer).map(Self::Owned) + } +} diff --git a/crates/celox/src/backend/native/executable_mapping.rs b/crates/celox/src/backend/native/executable_mapping.rs index dda28f1961f..251dafb9b14 100644 --- a/crates/celox/src/backend/native/executable_mapping.rs +++ b/crates/celox/src/backend/native/executable_mapping.rs @@ -6,6 +6,12 @@ pub(super) struct ExecutableMapping { len: usize, } +// Safety: the executing inode cannot be written while it is running. This +// owner only changes page permissions from read-only to read/execute, never +// makes bytes mutable, and unmaps only after the last Arc owner/borrow ends. +unsafe impl Send for ExecutableMapping {} +unsafe impl Sync for ExecutableMapping {} + impl ExecutableMapping { pub(super) fn current() -> io::Result { // Open the executing inode, even after its pathname has been replaced. @@ -42,6 +48,34 @@ impl ExecutableMapping { Ok(Self { address, len }) } + #[cfg(all(target_arch = "x86_64", not(feature = "arm64-codegen")))] + pub(super) fn make_executable(&self, range: std::ops::Range) -> io::Result<()> { + if range.is_empty() || range.end > self.len { + return Err(io::Error::other("invalid executable code range")); + } + // Safety: sysconf has no pointer arguments and does not mutate memory. + let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + let page = usize::try_from(page) + .ok() + .filter(|&page| page != 0) + .ok_or_else(|| io::Error::other("cannot determine page size"))?; + let start = range.start / page * page; + // mprotect rounds the end up to the final mapped page itself. + // Safety: the checked subrange belongs to this live mapping. Read + // permission is retained; no writable alias is introduced. + let result = unsafe { + libc::mprotect( + self.address.as_ptr().add(start).cast(), + range.end - start, + libc::PROT_READ | libc::PROT_EXEC, + ) + }; + if result != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + pub(super) fn as_bytes(&self) -> &[u8] { // Safety: this owner retains an immutable mapping of the checked size; // the returned slice cannot outlive it. diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 1140e4ac56d..d3e948fe8a4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -13,6 +13,14 @@ const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; // Concurrent assertion kernels suspend into Observed and Reactive regions. const CONTAINER_VERSION: u16 = 52; const TRAILER_SIZE: usize = 32; +// This optional prefix descriptor does not change the Postcard payload. Older +// readers ignore framing flags and continue to locate the payload at EOF. +const RUNTIME_PADDING_FLAG: u8 = 1; +const RUNTIME_PADDING_MAGIC: &[u8; 8] = b"CELOXPAD"; +const RUNTIME_PADDING_SIZE: usize = 32; +const SMALL_CODE_ALIGNMENT: usize = 4096; +const HUGE_CODE_ALIGNMENT: usize = 2 * 1024 * 1024; + const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; @@ -62,7 +70,7 @@ impl fmt::Display for NativeImageArchitecture { /// Result of finding and decoding an image appended to another byte sequence. pub struct AppendedNativeImage { - /// Length of the original runtime prefix before the serialized image. + /// Length of the runtime prefix, including alignment padding, before the serialized image. pub runtime_len: usize, /// Decoded pointer-free program image. pub image: NativeProgramImage, @@ -72,6 +80,7 @@ struct AppendedNativePayload<'a> { runtime_len: usize, version: u16, architecture: u8, + flags: u8, payload: &'a [u8], } @@ -128,11 +137,37 @@ impl NativeProgramImage { /// the runtime discover the payload without parsing its own executable /// format. pub fn append_to_runtime(&self, runtime: &[u8]) -> Result, NativeImageContainerError> { + self.append_to_runtime_aligned(runtime, 1) + } + + fn append_to_runtime_aligned( + &self, + runtime: &[u8], + alignment: usize, + ) -> Result, NativeImageContainerError> { + debug_assert!(alignment.is_power_of_two()); self.validate() .map_err(NativeImageContainerError::InvalidImage)?; let payload = postcard::to_allocvec(self)?; - let total_len = runtime + let (code, remaining) = postcard::take_from_bytes::<&[u8]>(&payload)?; + let code_prefix = payload.len() - remaining.len() - code.len(); + let descriptor_size = if alignment > 1 { + RUNTIME_PADDING_SIZE + } else { + 0 + }; + let code_start = runtime .len() + .checked_add(descriptor_size) + .and_then(|size| size.checked_add(code_prefix)) + .ok_or(NativeImageContainerError::SizeOverflow)?; + let padding = (alignment - code_start % alignment) % alignment; + let runtime_len = runtime + .len() + .checked_add(padding) + .and_then(|size| size.checked_add(descriptor_size)) + .ok_or(NativeImageContainerError::SizeOverflow)?; + let total_len = runtime_len .checked_add(payload.len()) .and_then(|size| size.checked_add(TRAILER_SIZE)) .ok_or(NativeImageContainerError::SizeOverflow)?; @@ -141,11 +176,25 @@ impl NativeProgramImage { let mut output = Vec::with_capacity(total_len); output.extend_from_slice(runtime); + output.resize(runtime_len - descriptor_size, 0); + if descriptor_size != 0 { + let mut descriptor = [0u8; RUNTIME_PADDING_SIZE]; + descriptor[..8].copy_from_slice(RUNTIME_PADDING_MAGIC); + descriptor[8..16].copy_from_slice(&(runtime.len() as u64).to_le_bytes()); + descriptor[16..24].copy_from_slice(&(padding as u64).to_le_bytes()); + let hash = checksum(&descriptor[..24]); + descriptor[24..32].copy_from_slice(&hash.to_le_bytes()); + output.extend_from_slice(&descriptor); + } output.extend_from_slice(&payload); output.extend_from_slice(TRAILER_MAGIC); output.extend_from_slice(&CONTAINER_VERSION.to_le_bytes()); output.push(NativeImageArchitecture::current() as u8); - output.push(0); // flags, reserved for future container revisions + output.push(if descriptor_size != 0 { + RUNTIME_PADDING_FLAG + } else { + 0 + }); output.extend_from_slice(&(TRAILER_SIZE as u32).to_le_bytes()); output.extend_from_slice(&payload_len.to_le_bytes()); output.extend_from_slice(&checksum(&payload).to_le_bytes()); @@ -167,10 +216,18 @@ impl NativeProgramImage { let output_path = output_path.as_ref(); let metadata = std::fs::metadata(runtime_path)?; let runtime = std::fs::read(runtime_path)?; - let runtime_len = discover_appended_payload(&runtime)? - .map(|appended| appended.runtime_len) - .unwrap_or(runtime.len()); - let output = self.append_to_runtime(&runtime[..runtime_len])?; + let runtime_len = match discover_appended_payload(&runtime)? { + Some(appended) => unpadded_runtime_len(&runtime, &appended)?, + None => runtime.len(), + }; + // The Postcard payload stays unchanged; padding belongs to the runtime + // prefix so older format-compatible readers can still load the image. + let alignment = if self.code_image().len() >= HUGE_CODE_ALIGNMENT { + HUGE_CODE_ALIGNMENT + } else { + SMALL_CODE_ALIGNMENT + }; + let output = self.append_to_runtime_aligned(&runtime[..runtime_len], alignment)?; std::fs::write(output_path, output)?; std::fs::set_permissions(output_path, metadata.permissions())?; Ok(()) @@ -195,24 +252,10 @@ impl NativeProgramImage { let Some(appended) = discover_appended_payload(bytes)? else { return Ok(None); }; - if appended.version != CONTAINER_VERSION { - return Err(NativeImageContainerError::UnsupportedVersion( - appended.version, - )); - } - let found = NativeImageArchitecture::decode(appended.architecture)?; - let expected = NativeImageArchitecture::current(); - if found != expected { - return Err(NativeImageContainerError::ArchitectureMismatch { expected, found }); - } - let image = NativeProgramImage::from_postcard_bytes(appended.payload)?; - image - .validate() - .map_err(NativeImageContainerError::InvalidImage)?; - Ok(Some(AppendedNativeImage { - runtime_len: appended.runtime_len, - image, - })) + Ok(Some(decode_appended_image( + appended, + Self::from_postcard_bytes, + )?)) } /// Read the running executable and discover an image attached at EOF. @@ -220,9 +263,13 @@ impl NativeProgramImage { -> Result, NativeImageContainerError> { #[cfg(target_os = "linux")] if let Ok(mapping) = super::executable_mapping::ExecutableMapping::current() { - // The decoder returns owned metadata/code, so the temporary input - // mapping can be released immediately after decoding. - return Self::discover_appended(mapping.as_bytes()); + let owner = std::sync::Arc::new(mapping); + let Some(appended) = discover_appended_payload(owner.as_bytes())? else { + return Ok(None); + }; + return Ok(Some(decode_appended_image(appended, |payload| { + Self::from_mapped_postcard_bytes(payload, owner.clone()) + })?)); } let executable = std::env::current_exe()?; let mut file = std::fs::File::open(executable)?; @@ -230,6 +277,30 @@ impl NativeProgramImage { } } +fn decode_appended_image( + appended: AppendedNativePayload<'_>, + decode: impl FnOnce(&[u8]) -> Result, +) -> Result { + if appended.version != CONTAINER_VERSION { + return Err(NativeImageContainerError::UnsupportedVersion( + appended.version, + )); + } + let found = NativeImageArchitecture::decode(appended.architecture)?; + let expected = NativeImageArchitecture::current(); + if found != expected { + return Err(NativeImageContainerError::ArchitectureMismatch { expected, found }); + } + let image = decode(appended.payload)?; + image + .validate() + .map_err(NativeImageContainerError::InvalidImage)?; + Ok(AppendedNativeImage { + runtime_len: appended.runtime_len, + image, + }) +} + // Read the trailer first so ordinary CLI commands do not copy the runtime // executable and attached runs allocate only their serialized image. fn discover_reader( @@ -312,10 +383,50 @@ fn discover_appended_payload( runtime_len, version: u16::from_le_bytes(trailer[8..10].try_into().unwrap()), architecture: trailer[10], + flags: trailer[11], payload, })) } +fn unpadded_runtime_len( + bytes: &[u8], + appended: &AppendedNativePayload<'_>, +) -> Result { + if appended.flags & RUNTIME_PADDING_FLAG == 0 { + return Ok(appended.runtime_len); + } + let invalid = || { + NativeImageContainerError::Io(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "invalid attached-runtime padding descriptor", + )) + }; + let start = appended + .runtime_len + .checked_sub(RUNTIME_PADDING_SIZE) + .ok_or_else(invalid)?; + let descriptor = bytes.get(start..appended.runtime_len).ok_or_else(invalid)?; + if &descriptor[..8] != RUNTIME_PADDING_MAGIC { + return Err(invalid()); + } + let expected = u64::from_le_bytes(descriptor[24..32].try_into().unwrap()); + if checksum(&descriptor[..24]) != expected { + return Err(NativeImageContainerError::ChecksumMismatch); + } + let raw_len = usize::try_from(u64::from_le_bytes(descriptor[8..16].try_into().unwrap())) + .map_err(|_| NativeImageContainerError::SizeOverflow)?; + let padding = usize::try_from(u64::from_le_bytes(descriptor[16..24].try_into().unwrap())) + .map_err(|_| NativeImageContainerError::SizeOverflow)?; + if raw_len.checked_add(padding) != Some(start) + || bytes + .get(raw_len..start) + .is_none_or(|padding| padding.iter().any(|&byte| byte != 0)) + { + return Err(invalid()); + } + Ok(raw_len) +} + fn checksum(bytes: &[u8]) -> u64 { bytes.iter().fold(FNV_OFFSET_BASIS, |hash, byte| { (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME) @@ -410,6 +521,46 @@ mod tests { } } + #[test] + fn aligned_prefix_preserves_the_legacy_payload_and_original_runtime() { + let image = image(); + let runtime = b"precompiled runtime"; + let legacy = image.append_to_runtime(runtime).unwrap(); + let aligned = image + .append_to_runtime_aligned(runtime, HUGE_CODE_ALIGNMENT) + .unwrap(); + let old = discover_appended_payload(&legacy).unwrap().unwrap(); + let new = discover_appended_payload(&aligned).unwrap().unwrap(); + assert_eq!(old.flags, 0); + assert_eq!(new.flags, RUNTIME_PADDING_FLAG); + assert_eq!(new.payload, old.payload); + assert_eq!(unpadded_runtime_len(&aligned, &new).unwrap(), runtime.len()); + let (code, remaining) = postcard::take_from_bytes::<&[u8]>(new.payload).unwrap(); + let offset = aligned.len() - TRAILER_SIZE - remaining.len() - code.len(); + assert!(offset.is_multiple_of(HUGE_CODE_ALIGNMENT)); + let decoded: NativeProgramImage = postcard::from_bytes(new.payload).unwrap(); + assert_eq!(decoded.code_image(), image.code_image()); + } + + #[test] + fn corrupt_padding_descriptor_does_not_overwrite_the_runtime() { + let image = image(); + let mut bytes = image + .append_to_runtime_aligned(b"runtime", HUGE_CODE_ALIGNMENT) + .unwrap(); + let frame = discover_appended_payload(&bytes).unwrap().unwrap(); + let descriptor = frame.runtime_len - RUNTIME_PADDING_SIZE; + bytes[descriptor + 8] ^= 1; + let directory = tempfile::tempdir().unwrap(); + let runtime = directory.path().join("runtime"); + std::fs::write(&runtime, &bytes).unwrap(); + assert!(matches!( + image.write_attached_runtime(&runtime, &runtime), + Err(NativeImageContainerError::ChecksumMismatch) + )); + assert_eq!(std::fs::read(runtime).unwrap(), bytes); + } + #[test] fn reader_ignores_runtime_prefix_and_preserves_image_and_offset() { let image = image(); diff --git a/crates/celox/src/backend/native/mod.rs b/crates/celox/src/backend/native/mod.rs index 49bc3968db2..f8ba60caa24 100644 --- a/crates/celox/src/backend/native/mod.rs +++ b/crates/celox/src/backend/native/mod.rs @@ -1,5 +1,6 @@ pub mod backend; mod clock_aliases; +mod code_bytes; mod compile_resources; #[cfg(target_os = "linux")] mod executable_mapping; diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 1bf274b058a..7f7cf95f8f6 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -861,8 +861,19 @@ fn native_program_image_writes_an_executable_runtime_file() { let appended = celox::NativeProgramImage::discover_appended(&output) .unwrap() .unwrap(); - assert_eq!(appended.runtime_len, b"precompiled runtime".len()); - assert_eq!(&output[..appended.runtime_len], b"precompiled runtime"); + let prefix = b"precompiled runtime"; + assert_eq!(&output[..prefix.len()], prefix); + assert!(appended.runtime_len >= prefix.len()); + let payload = &output[appended.runtime_len..output.len() - NATIVE_IMAGE_TRAILER_SIZE]; + let (code, remaining) = postcard::take_from_bytes::<&[u8]>(payload).unwrap(); + let code_start = output.len() - NATIVE_IMAGE_TRAILER_SIZE - remaining.len() - code.len(); + let alignment = if code.len() >= 2 * 1024 * 1024 { + 2 * 1024 * 1024 + } else { + 4096 + }; + assert!(code_start.is_multiple_of(alignment)); + assert_eq!(code, image.code_image()); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt;