RS.DBZ.PANIC.UNCONDITIONAL

Unconditional division by zero

This checker identifies situations where the Rust compiler has inserted an unconditional call to its panic function for division by zero (core::panicking::panic_const::panic_const_div_by_zero), indicating that the divisor is statically known to be zero. An unconditional division by zero will always cause the Rust program to panic at runtime.

This differs from conditional panic checks, which only trigger when a divisor might be zero at runtime.

Vulnerability and risk

Division by zero is undefined behavior that causes program crashes. In Rust, the compiler automatically inserts runtime checks before division operations to verify that the divisor is not zero. When these checks determine that a division by zero will always occur (unconditional), it represents a critical bug that will cause the program to crash when the code path is executed.

Vulnerable code example

Copy
#[allow(unconditional_panic)]
fn calculate_ratio() -> i32 {
    let numerator = 100;
    let denominator = 0;  // Always zero
    numerator / denominator  // Unconditional panic
}

fn main() {
    let result = calculate_ratio();  // Will always panic here
    println!("Result: {}", result);
}

Fixed code example

Copy
fn calculate_ratio() -> Option<i32> {
    let numerator = 100;
    let denominator = 0;
    
    if denominator == 0 {
        return None;  // Handle the zero case
    }
    
    Some(numerator / denominator)
}

fn main() {
    match calculate_ratio() {
        Some(result) => println!("Result: {}", result),
        None => println!("Cannot divide by zero"),
    }
}