`#[derive(Debug)]` is introducing potentially panicking code
Nobody has claimed this yet.
- 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:
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:
- Will build with
opt-level=3 - Will build with
Test::a5shorter than 33 elements (curiously the same threshold as for#[derive(Default)] - Will build with number of fields 5 or less (likely because in that case
debug_struct_fields_finish()is not being called, butdebug_struct_fields_finishXis called instead
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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