ntpanic 0.1.0

Panic handler for Windows kernel-mode Rust drivers: reports the panic, then bug-checks the system.
Documentation
//! Panic handling for Windows kernel-mode Rust drivers.
//!
//! This module defines the crate's global `#[panic_handler]`, described at [`panic()`].
//! The panic path is intentionally fatal. Continuing execution after a panic in
//! kernel mode is unsafe and unsupported by this crate.

use core::{
    panic::PanicInfo,
    sync::atomic::{AtomicBool, Ordering},
};
use windows_sys::Wdk::System::SystemServices::{
    DbgBreakPointWithStatus, KdRefreshDebuggerNotPresent, PsGetCurrentProcessId,
    PsGetCurrentThreadId,
};

// windows-sys imports DbgPrintEx from ntdll.dll, which a driver cannot load.
windows_link::link!("ntoskrnl.exe" "C" fn DbgPrintEx(componentid: u32, level: u32, format: *const u8, ...) -> u32);
// Declared here for `-> !`: the WDK marks it DECLSPEC_NORETURN, windows-sys does not.
windows_link::link!("ntoskrnl.exe" "system" fn KeBugCheckEx(bugcheckcode: u32, bugcheckparameter1: usize, bugcheckparameter2: usize, bugcheckparameter3: usize, bugcheckparameter4: usize) -> !);
// wdm.h exports KeGetCurrentIrql from ntoskrnl.exe on x64 and from hal.dll on every
// other architecture; windows-sys names ntoskrnl.exe for all of them.
#[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);

// Reported when the panic carries no location.
const UNKNOWN_FILE: &str = "<unknown>";
const UNKNOWN_LINE: u32 = 0;
const UNKNOWN_COLUMN: u32 = 0;

// Status sent to the debugger with the break-in.
const DEBUG_BREAK_STATUS: u32 = 0;

// DbgPrintEx is documented for IRQL <= DIRQL and can deadlock above it. This is the
// first IRQL above every device IRQL in wdm.h: PROFILE_LEVEL on x86, CLOCK_LEVEL on
// every other architecture.
#[cfg(target_arch = "x86")]
const FIRST_IRQL_ABOVE_DIRQL: u8 = 27;
#[cfg(not(target_arch = "x86"))]
const FIRST_IRQL_ABOVE_DIRQL: u8 = 13;

// Set by the first panic, so that no later one calls the callback: not one inside it, on
// another processor, or after the callback was set again. Only the swap's atomicity
// matters, so Relaxed ordering is enough.
static PANICKING: AtomicBool = AtomicBool::new(false);

/// Global panic handler for Windows kernel-mode drivers.
///
/// This function is the crate's global `#[panic_handler]`. When a panic occurs,
/// it attempts to report the panic location through `DbgPrintEx`, calls the
/// optional callback, optionally breaks into the kernel debugger if one is
/// attached, and then terminates the system with `KeBugCheckEx`.
///
/// # Behavior
///
/// On panic, the handler:
///
/// 1. extracts the source file path, line and column from [`PanicInfo`], when available;
/// 2. prints a diagnostic message with `DbgPrintEx` that gives the location (only the
///    end of a very long path), the IRQL and the process and thread IDs, unless the
///    IRQL is above DIRQL, where `DbgPrintEx` can deadlock;
/// 3. calls the function set with [`set_callback`](crate::set_callback), if any, for the
///    first panic only;
/// 4. checks whether a kernel debugger is present via `KdRefreshDebuggerNotPresent`;
/// 5. calls `DbgBreakPointWithStatus(0)` if a debugger is attached;
/// 6. invokes `KeBugCheckEx` with the code set with
///    [`set_bug_check_code`](crate::set_bug_check_code), "RUST" by default, and the
///    parameters described there.
///
/// # Panics
///
/// This function never returns.
///
/// # Notes
///
/// This handler is intended for `#![no_std]` Rust drivers running in
/// Windows kernel mode. Panic recovery is not attempted, since continuing
/// execution after a panic in kernel space is considered unsafe.
#[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,
        )
    }
}