use core::{
panic::PanicInfo,
sync::atomic::{AtomicBool, Ordering},
};
use windows_sys::Wdk::System::SystemServices::{
DbgBreakPointWithStatus, KdRefreshDebuggerNotPresent, PsGetCurrentProcessId,
PsGetCurrentThreadId,
};
windows_link::link!("ntoskrnl.exe" "C" fn DbgPrintEx(componentid: u32, level: u32, format: *const u8, ...) -> u32);
windows_link::link!("ntoskrnl.exe" "system" fn KeBugCheckEx(bugcheckcode: u32, bugcheckparameter1: usize, bugcheckparameter2: usize, bugcheckparameter3: usize, bugcheckparameter4: usize) -> !);
#[cfg(target_arch = "x86_64")]
windows_link::link!("ntoskrnl.exe" "system" fn KeGetCurrentIrql() -> u8);
#[cfg(not(target_arch = "x86_64"))]
windows_link::link!("hal.dll" "system" fn KeGetCurrentIrql() -> u8);
const UNKNOWN_FILE: &str = "<unknown>";
const UNKNOWN_LINE: u32 = 0;
const UNKNOWN_COLUMN: u32 = 0;
const DEBUG_BREAK_STATUS: u32 = 0;
#[cfg(target_arch = "x86")]
const FIRST_IRQL_ABOVE_DIRQL: u8 = 27;
#[cfg(not(target_arch = "x86"))]
const FIRST_IRQL_ABOVE_DIRQL: u8 = 13;
static PANICKING: AtomicBool = AtomicBool::new(false);
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
let irql = unsafe { KeGetCurrentIrql() };
let (file, line, column) = info
.location()
.map_or((UNKNOWN_FILE, UNKNOWN_LINE, UNKNOWN_COLUMN), |location| {
(location.file(), location.line(), location.column())
});
if irql < FIRST_IRQL_ABOVE_DIRQL {
let component_id = crate::COMPONENT_ID.load(Ordering::Relaxed);
let level = crate::LEVEL.load(Ordering::Relaxed);
let path = crate::printed_path(file);
let (process_id, thread_id) = unsafe { (PsGetCurrentProcessId(), PsGetCurrentThreadId()) };
unsafe {
DbgPrintEx(
component_id,
level,
concat!(
"*************** RUST KERNEL PANIC at %.*s:%u ",
"(irql %u, pid %Iu, tid %Iu) ***************\n",
"\0"
)
.as_ptr(),
i32::try_from(path.len()).unwrap_or(i32::MAX),
path.as_ptr(),
line,
u32::from(irql),
process_id as usize,
thread_id as usize,
);
}
}
if !PANICKING.swap(true, Ordering::Relaxed) {
if let Some(callback) = crate::current_callback() {
callback(info, irql);
}
}
let debugger_not_present = unsafe { KdRefreshDebuggerNotPresent() };
if !debugger_not_present {
unsafe {
DbgBreakPointWithStatus(DEBUG_BREAK_STATUS);
}
}
unsafe {
KeBugCheckEx(
crate::BUG_CHECK_CODE.load(Ordering::Relaxed),
line as usize,
file.as_ptr() as usize,
file.len(),
column as usize,
)
}
}