use std::{
ffi::c_void,
panic::{AssertUnwindSafe, catch_unwind},
sync::Arc,
};
pub(crate) const RECORD_BOUNDS_VIOLATION_SYMBOL: &str = "__lehit_record_bounds_violation";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExecutionMode {
#[default]
Direct,
Checked,
}
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum ExecutionErrorCode {
#[default]
None = 0,
BoundsViolation = 1,
DivisionByZero = 2,
IntegerOverflow = 3,
InvalidShift = 4,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutionError {
BoundsViolation {
index: usize,
length: usize,
},
DivisionByZero,
IntegerOverflow,
InvalidShift {
amount: usize,
bit_width: usize,
},
}
impl std::fmt::Display for ExecutionError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BoundsViolation { index, length } => {
write!(
formatter,
"array index {index} is out of bounds for length {length}"
)
}
Self::DivisionByZero => formatter.write_str("integer division by zero"),
Self::IntegerOverflow => formatter.write_str("integer arithmetic overflow"),
Self::InvalidShift { amount, bit_width } => write!(
formatter,
"shift amount {amount} is invalid for a {bit_width}-bit integer"
),
}
}
}
impl std::error::Error for ExecutionError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuntimeErrorReport {
pub error: ExecutionError,
}
pub trait ErrorChannel: Send + Sync + 'static {
fn report(&self, report: &RuntimeErrorReport);
}
impl<F> ErrorChannel for F
where
F: Fn(&RuntimeErrorReport) + Send + Sync + 'static,
{
fn report(&self, report: &RuntimeErrorReport) {
self(report);
}
}
#[derive(Clone)]
pub(crate) struct RuntimeErrorSink {
state: Arc<RuntimeErrorSinkState>,
}
struct RuntimeErrorSinkState {
channel: Arc<dyn ErrorChannel>,
}
impl RuntimeErrorSink {
pub(crate) fn new(channel: Arc<dyn ErrorChannel>) -> Self {
Self {
state: Arc::new(RuntimeErrorSinkState { channel }),
}
}
pub(crate) fn context(&self) -> *const c_void {
Arc::as_ptr(&self.state).cast()
}
pub(crate) fn callback(&self) -> RuntimeErrorCallback {
report_runtime_error
}
}
pub(crate) type RuntimeErrorCallback =
unsafe extern "C" fn(context: *const c_void, code: u32, first: usize, second: usize);
unsafe extern "C" fn report_runtime_error(
context: *const c_void,
code: u32,
first: usize,
second: usize,
) {
let Some(state) = (unsafe { context.cast::<RuntimeErrorSinkState>().as_ref() }) else {
return;
};
let Some(error) = execution_error_from_raw(code, first, second) else {
return;
};
let report = RuntimeErrorReport { error };
let _ = catch_unwind(AssertUnwindSafe(|| state.channel.report(&report)));
}
pub(crate) fn execution_error_from_raw(
code: u32,
first: usize,
second: usize,
) -> Option<ExecutionError> {
match code {
value if value == ExecutionErrorCode::None as u32 => None,
value if value == ExecutionErrorCode::BoundsViolation as u32 => {
Some(ExecutionError::BoundsViolation {
index: first,
length: second,
})
}
value if value == ExecutionErrorCode::DivisionByZero as u32 => {
Some(ExecutionError::DivisionByZero)
}
value if value == ExecutionErrorCode::IntegerOverflow as u32 => {
Some(ExecutionError::IntegerOverflow)
}
value if value == ExecutionErrorCode::InvalidShift as u32 => {
Some(ExecutionError::InvalidShift {
amount: first,
bit_width: second,
})
}
_ => None,
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct ExecutionContext {
pub(crate) code: ExecutionErrorCode,
pub(crate) first: usize,
pub(crate) second: usize,
}
impl ExecutionContext {
#[cfg(test)]
pub(crate) fn new() -> Self {
Self::default()
}
#[cfg(test)]
pub(crate) fn clear(&mut self) {
*self = Self::default();
}
#[cfg(test)]
pub(crate) fn error(&self) -> Option<ExecutionError> {
match self.code {
ExecutionErrorCode::None => None,
ExecutionErrorCode::BoundsViolation => Some(ExecutionError::BoundsViolation {
index: self.first,
length: self.second,
}),
ExecutionErrorCode::DivisionByZero => Some(ExecutionError::DivisionByZero),
ExecutionErrorCode::IntegerOverflow => Some(ExecutionError::IntegerOverflow),
ExecutionErrorCode::InvalidShift => Some(ExecutionError::InvalidShift {
amount: self.first,
bit_width: self.second,
}),
}
}
pub(crate) fn record_bounds_violation(&mut self, index: usize, length: usize) {
if self.code == ExecutionErrorCode::None {
self.code = ExecutionErrorCode::BoundsViolation;
self.first = index;
self.second = length;
}
}
}
pub(crate) unsafe extern "C" fn record_bounds_violation(
context: *mut ExecutionContext,
index: usize,
length: usize,
) {
if let Some(context) = unsafe { context.as_mut() } {
context.record_bounds_violation(index, length);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_sink_reports_details_and_contains_channel_panics() {
let reports = Arc::new(std::sync::Mutex::new(Vec::new()));
let captured = Arc::clone(&reports);
let sink = RuntimeErrorSink::new(Arc::new(move |report: &RuntimeErrorReport| {
captured.lock().unwrap().push(*report);
}));
unsafe {
(sink.callback())(
sink.context(),
ExecutionErrorCode::BoundsViolation as u32,
7,
3,
);
}
assert_eq!(
reports.lock().unwrap().as_slice(),
&[RuntimeErrorReport {
error: ExecutionError::BoundsViolation {
index: 7,
length: 3,
},
}]
);
let panicking = RuntimeErrorSink::new(Arc::new(|_: &RuntimeErrorReport| panic!("channel")));
unsafe {
(panicking.callback())(
panicking.context(),
ExecutionErrorCode::DivisionByZero as u32,
0,
0,
);
}
}
#[test]
fn execution_context_records_the_first_structured_error() {
let mut context = ExecutionContext::new();
assert_eq!(context.error(), None);
context.record_bounds_violation(4, 2);
context.record_bounds_violation(8, 1);
assert_eq!(
context.error(),
Some(ExecutionError::BoundsViolation {
index: 4,
length: 2,
})
);
context.clear();
assert_eq!(context.error(), None);
}
#[test]
fn execution_context_has_a_c_abi_stable_field_order() {
assert_eq!(
std::mem::align_of::<ExecutionContext>(),
std::mem::align_of::<usize>()
);
assert!(std::mem::size_of::<ExecutionContext>() >= std::mem::size_of::<usize>() * 3);
}
}