Skip to content
Merged
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
97 changes: 95 additions & 2 deletions crates/celox-backend-x86/src/backend/native/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,32 @@ pub fn emit(
)
}

/// Emit a caller with disjoint storage above every generated callee's arena.
/// Pass `required_state_size` from each reachable callee's `EmitResult`;
/// each callee must itself have been emitted with its own callees' extents.
/// `state_size` describes the common semantic state, not an arena reservation.
pub fn emit_with_callees(
func: &MFunction,
assignment: &AssignmentMap,
spill_frame_size: u32,
state_size: usize,
callee_ends: &[usize],
) -> Result<EmitResult, EmitError> {
verify_emission_inputs(func, assignment, spill_frame_size, false)?;
let plan = SsaDestructionPlan::build(func, assignment)?;
plan.verify(func, assignment, spill_frame_size)?;
emit_planned_with_callees(
func,
assignment,
spill_frame_size,
state_size,
&plan,
false,
false,
callee_ends,
)
}

/// Direct emitter tests do not carry a complete `MemoryLayout`. Place their
/// native arena beyond every statically named SimState byte plus a guard so
/// test-owned sentinel bytes cannot alias prologue/scratch storage.
Expand Down Expand Up @@ -845,18 +871,20 @@ pub(crate) fn emit_with_plan(
assignment: &AssignmentMap,
spill_frame_size: u32,
state_size: usize,
callee_ends: &[usize],
plan: &SsaDestructionPlan,
) -> Result<EmitResult, EmitError> {
verify_emission_inputs(func, assignment, spill_frame_size, false)?;
plan.verify(func, assignment, spill_frame_size)?;
emit_planned(
emit_planned_with_callees(
func,
assignment,
spill_frame_size,
state_size,
plan,
false,
false,
callee_ends,
)
}

Expand All @@ -865,19 +893,21 @@ fn emit_with_plan_tick_loop(
assignment: &AssignmentMap,
spill_frame_size: u32,
state_size: usize,
callee_ends: &[usize],
plan: &SsaDestructionPlan,
check_runtime_events: bool,
) -> Result<EmitResult, EmitError> {
verify_emission_inputs(func, assignment, spill_frame_size, true)?;
plan.verify(func, assignment, spill_frame_size)?;
emit_planned(
emit_planned_with_callees(
func,
assignment,
spill_frame_size,
state_size,
plan,
true,
check_runtime_events,
callee_ends,
)
}

Expand Down Expand Up @@ -1043,6 +1073,45 @@ fn emit_planned(
tick_loop: bool,
check_runtime_events: bool,
) -> Result<EmitResult, EmitError> {
emit_planned_with_callees(
func,
assignment,
spill_frame_size,
state_size,
plan,
tick_loop,
check_runtime_events,
&[],
)
}

/// Callee extents include their own recursively reserved callees. The state
/// pointer stays unchanged; only the caller's private arena is placed above
/// those complete extents. Merely using the same semantic state size for both
/// functions is not sufficient to isolate live spills and pinned saves.
fn emit_planned_with_callees(
func: &MFunction,
assignment: &AssignmentMap,
spill_frame_size: u32,
state_size: usize,
plan: &SsaDestructionPlan,
tick_loop: bool,
check_runtime_events: bool,
callee_ends: &[usize],
) -> Result<EmitResult, EmitError> {
let has_kernels = func.blocks.iter().flat_map(|b| &b.insts).any(|inst|
matches!(inst, MInst::CallExtern { func, .. } if celox_sir::extern_abi::native_kernel_index(*func).is_some()));
if has_kernels && (callee_ends.is_empty() || callee_ends.contains(&0)) {
return Err(EmitInputError::new(
"EMIT.NATIVE_CALLEE_ARENA",
None,
None,
None,
"generated kernel calls require the callees' complete required_state_size extents",
)
.into());
}
let state_size = callee_ends.iter().copied().fold(state_size, usize::max);
let mut uses_bmi2 = false;
let mut uses_avx = false;
let mut uses_popcnt = false;
Expand Down Expand Up @@ -1297,6 +1366,30 @@ fn emit_planned(
asm.jmp(epilogue_label)?;
}
}
MInst::CallExtern { func, arg_count }
if celox_sir::extern_abi::native_kernel_index(*func).is_some() =>
{
extern_call::emit_call_extern(&mut asm, *func, *arg_count)?;
// The call restored our state base and pinned registers.
// RAX still holds the complete signed callee status.
asm.test(rax, rax)?;
if tick_loop {
let mut success = asm.create_label();
asm.jz(success)?;
// Match ReturnError's completed-tick accounting while
// retaining RAX for the common epilogue.
asm.movq(r10, xmm15)?;
asm.dec(r10)?;
asm.movq(xmm15, r10)?;
asm.jmp(epilogue_label)?;
asm.set_label(&mut success)?;
// A following MIR block may start here; code_asm
// cannot bind two labels to the same instruction.
asm.nop()?;
} else {
asm.jnz(epilogue_label)?;
}
}
MInst::ReturnError { code } => {
if tick_loop {
asm.movq(rax, xmm15)?;
Expand Down
26 changes: 15 additions & 11 deletions crates/celox-backend-x86/src/backend/native/emit/extern_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@ pub(super) fn set_call_area(
}

/// The XMM registers a call must save: pinned ones the callee may change.
fn saved_xmms(context: &EmissionContext) -> impl Iterator<Item = usize> {
let saved = context.pinned_xmms & !C_PRESERVED_XMMS;
fn saved_xmms(context: &EmissionContext, native_kernel: bool) -> impl Iterator<Item = usize> {
// Generated x86 functions use SysV on every host, including Windows.
let preserved = if native_kernel { 0 } else { C_PRESERVED_XMMS };
let saved = context.pinned_xmms & !preserved;
(0..16).filter(move |index| saved & (1 << index) != 0)
}

Expand Down Expand Up @@ -98,11 +100,12 @@ pub(super) fn emit_call_extern(
let context = asm.context;
let area = call_area(&context);
let strategy = state_base_strategy(&context);
let kernel = celox_sir::extern_abi::native_kernel_index(func);

// RBX is callee-saved in every C ABI and free here: it holds the state
// pointer while the segment base belongs to C code.
emit_state_base(asm, rbx)?;
for index in saved_xmms(&context) {
for index in saved_xmms(&context, kernel.is_some()) {
asm.movq(
qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)),
xmm_register(index),
Expand All @@ -119,14 +122,15 @@ pub(super) fn emit_call_extern(
StateBaseStrategy::R15 => {}
}

let (registers, shadow): (&[AsmRegister64], i32) = if cfg!(target_os = "windows") {
(&[rcx, rdx, r8, r9], 32)
} else {
(&[rdi, rsi, rdx, rcx, r8, r9], 0)
};
let (registers, shadow): (&[AsmRegister64], i32) =
if cfg!(target_os = "windows") && kernel.is_none() {
(&[rcx, rdx, r8, r9], 32)
} else {
(&[rdi, rsi, rdx, rcx, r8, r9], 0)
};
// The heap helper takes the state pointer before the staged arguments.
let heap = func == celox_sir::extern_abi::HEAP_HELPER_ID;
let leading = usize::from(heap);
let leading = usize::from(heap || kernel.is_some());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Isolate native callees from the caller's live arena

When the target is another generated function emitted with the same simulation-state size, passing the unchanged state pointer also shares the caller's spill and scratch storage: NativeArenaLayout::build sets each function's spill_base to align16(state_size). A callee that spills therefore overwrites caller values spilled across this call, and nested calls can also overwrite saved pinned registers when their call areas overlap. The added regression uses a Rust callee, which never accesses this arena and consequently cannot expose the corruption. Allocate disjoint per-function/per-call arena storage, or preserve the caller's live arena around generated-kernel calls.

Useful? React with 👍 / 👎.

let arg_count = usize::from(arg_count) + leading;
let stack_args = arg_count.saturating_sub(registers.len()) as i32;
// Generated code is entered with RSP = 8 (mod 16) and never moves it.
Expand Down Expand Up @@ -158,7 +162,7 @@ pub(super) fn emit_call_extern(
} else if heap {
-16
} else {
i32::try_from(u64::from(func) * 8).expect("extern function index")
i32::try_from(u64::from(kernel.unwrap_or(func)) * 8).expect("extern function index")
};
asm.mov(rax, qword_ptr(rax + offset))?;
asm.call(rax)?;
Expand All @@ -170,7 +174,7 @@ pub(super) fn emit_call_extern(
StateBaseStrategy::Gs => asm.wrgsbase(rbx)?,
StateBaseStrategy::R15 => {}
}
for index in saved_xmms(&context) {
for index in saved_xmms(&context, kernel.is_some()) {
asm.movq(
xmm_register(index),
qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)),
Expand Down
8 changes: 8 additions & 0 deletions crates/celox-backend-x86/src/backend/native/emit/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,12 +336,19 @@ fn emit_prepared_eu_inner(
let state_size = options
.arena_base
.map_or(semantic_size, |base| base.max(semantic_size));
let native_callee_end = [options.arena_base.unwrap_or(0)];
let callee_ends = if options.arena_base.is_some() {
&native_callee_end[..]
} else {
&[]
};
let result = if label == "eval_comb_apply_ff" && options.native_tick_loop {
emit_with_plan_tick_loop(
&mfunc,
&ra.assignment,
ra.spill_frame_size,
state_size,
callee_ends,
&ssa_destruction,
check_runtime_events,
)?
Expand All @@ -351,6 +358,7 @@ fn emit_prepared_eu_inner(
&ra.assignment,
ra.spill_frame_size,
state_size,
callee_ends,
&ssa_destruction,
)?
};
Expand Down
Loading
Loading