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
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,9 @@ jobs:

- uses: Swatinem/rust-cache@v2
with:
key: vtest-v1
# The vtest executor's build plan (profile, scope, features) lives in
# run-vtest.mjs; a change of it is a different cache.
key: vtest-${{ hashFiles('scripts/run-vtest.mjs') }}
save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}

- name: Initialize Rust test reports
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/rust-cache.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ jobs:
- uses: Swatinem/rust-cache@v2
id: cache
with:
key: vtest-v1
# The vtest executor's build plan (profile, scope, features) lives in
# run-vtest.mjs; a change of it is a different cache.
key: vtest-${{ hashFiles('scripts/run-vtest.mjs') }}
- name: Install cargo-nextest
if: steps.cache.outputs.cache-hit != 'true'
uses: taiki-e/install-action@v2
Expand Down
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
6 changes: 4 additions & 2 deletions crates/celox-sv-analyzer/src/ast/expression_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ mod strings;
pub(super) use calls::{statement as call_statement, statement_root as call_statement_root};
pub(super) use direct::{
arguments, bind_value, call_name as native_name, callable_name, cast_target_native,
format_arguments, member_context, real_value, remove_real_division_guards, ungroup,
format_arguments, member_context, real_value, remove_real_division_guards,
string_literal_bytes, ungroup,
};
pub(super) use lvalues::{net_lvalue, variable_lvalue};
pub(super) use objects::{
Expand All @@ -25,7 +26,8 @@ pub(super) use objects::{
receiver as object_receiver, static_property as object_static_property, this as object_this,
};
pub(super) use strings::{
call as string_call, method as string_method, native_string, to_string as string_operand,
call as string_call, method as string_method, native_string, string_value,
to_string as string_operand,
};
fn disagreement() -> AnalyzerError {
AnalyzerError::Parse("invalid native expression ownership".into())
Expand Down
19 changes: 13 additions & 6 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1879,6 +1879,18 @@ pub(in crate::ast) fn format_arguments(
/// String literals in integral contexts are unsigned packed arrays of bytes
/// (IEEE 1800-2023 5.9). Keep the semantic IR integral, including escapes.
fn packed_string_literal(text: &str) -> Option<String> {
let bytes = string_literal_bytes(text)?;
let width = (bytes.len() * 8).max(8);
Some(format!(
"{}'h{}",
width,
num_bigint::BigUint::from_bytes_be(&bytes).to_str_radix(16)
))
}

/// The bytes of string literal `text`, written with its quotes, after its
/// escapes (IEEE 1800-2023 5.9.1).
pub(in crate::ast) fn string_literal_bytes(text: &str) -> Option<Vec<u8>> {
let text = if let Some(text) = text.strip_prefix("\"\"\"") {
text.strip_suffix("\"\"\"")?
} else {
Expand Down Expand Up @@ -1939,12 +1951,7 @@ fn packed_string_literal(text: &str) -> Option<String> {
};
bytes.push(value);
}
let width = (bytes.len() * 8).max(8);
Some(format!(
"{}'h{}",
width,
num_bigint::BigUint::from_bytes_be(&bytes).to_str_radix(16)
))
Some(bytes)
}

pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> bool {
Expand Down
Loading
Loading