rust-lang / rust-lang/rust

`#[derive(Debug)]` is introducing potentially panicking code

Open
#149,286 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-macros C-optimization T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

It looks like in some cases #[derive(Debug)] is implemented via debug_struct_fields_finish() which contains the following assertion:

https://github.com/rust-lang/rust/blob/42ec52babac2cbf2bb2b9d794f980cbcb3ebe413/library/core/src/fmt/mod.rs#L2565

This breaks an otherwise panic-free code.

Update with MCVE

Cargo.toml:

[package]
name = "debug_struct"
version = "0.1.0"
edition = "2024"

[dependencies]

[profile.release]
lto = "thin"
debug = true
opt-level="z"
panic="abort"

main.rs

#![no_std]
#![no_main]
use core::fmt::Write;

#[repr(C)]
#[derive(Debug)]
struct Test {
    a0: u32,
    a1: u32,
    a2: u32,
    a3: u32,
    a4: u32,
    a5: [u32; 33],
}

impl Default for Test {
    fn default() -> Self {
        Self {
            a5: [0; 33],
            .. Default::default()
        }
    }
}

struct FakeWriter;
impl core::fmt::Write for FakeWriter {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        for c in s.bytes() {
            unsafe {
                core::ptr::write_volatile(0x1000_0000 as *mut u8, c);
            }
        }
        Ok(())
    }
}
#[unsafe(no_mangle)]
extern "C" fn _start() {
    let test = Test::default();
    let _ = writeln!(FakeWriter, "{:#X?}", test);
}

#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    unsafe extern "C" {
        #[link_name = "\n\nError: panic is possible on some code path\n\n"]
        unsafe fn never_panic() -> !;
    }
    unsafe { never_panic() }
}

Build with command:

cargo build --release --target=riscv32imc-unknown-none-elf

Will fail with linking error due to the panic handler referencing undefined function (credits to the no-panics-whatsoever crate authors.

Observations:

  1. Will build with opt-level=3
  2. Will build with Test::a5 shorter than 33 elements (curiously the same threshold as for #[derive(Default)]
  3. Will build with number of fields 5 or less (likely because in that case debug_struct_fields_finish() is not being called, but debug_struct_fields_finishX is called instead

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the assertion in library/core/src/fmt/mod.rs around line 2565 and reproduce the MCVE using the provided Cargo project and riscv32imc-unknown-none-elf release build command. Compare the behavior across the reported field counts, array lengths, and optimization levels. Done means the reported panic path is addressed without breaking the affected Debug formatting behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.