Re: [PATCH] panic: improve panic output from Rust panics

From: Miguel Ojeda
Date: Fri Jun 20 2025 - 05:37:03 EST


On Thu, Jun 19, 2025 at 6:10 PM Miguel Ojeda
<miguel.ojeda.sandonis@xxxxxxxxx> wrote:
>
> Yeah, I don't think we should do that.

By the way, if we are OK with just moving the line down, then we could
keep using `BUG()` taking advantage of `BUGFLAG_NO_CUT_HERE`.

Well, at least for x86 it seems straightforward -- see diff -- to get
output like e.g.:

[ 0.609779] ------------[ cut here ]------------
[ 0.609855] rust_kernel: panicked at samples/rust/rust_minimal.rs:29:9:
[ 0.609855] my Rust panic message
[ 0.610474] kernel BUG at rust/helpers/bug.c:7!
[ 0.610992] Oops: invalid opcode: 0000 [#1] SMP NOPTI

Cheers,
Miguel
From 25f303d4381d3b58c0e08f6cf524357509d936bd Mon Sep 17 00:00:00 2001
From: Miguel Ojeda <ojeda@xxxxxxxxxx>
Date: Thu, 19 Jun 2025 18:43:52 +0200
Subject: [PATCH] ...

---
arch/x86/include/asm/bug.h | 7 +++++--
rust/helpers/bug.c | 2 +-
rust/kernel/lib.rs | 3 +++
3 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/arch/x86/include/asm/bug.h b/arch/x86/include/asm/bug.h
index f0e9acf72547..1d862e16849b 100644
--- a/arch/x86/include/asm/bug.h
+++ b/arch/x86/include/asm/bug.h
@@ -79,12 +79,15 @@ do { \
#endif /* CONFIG_GENERIC_BUG */

#define HAVE_ARCH_BUG
-#define BUG() \
+#define BUG_FLAGS(flags) \
do { \
instrumentation_begin(); \
- _BUG_FLAGS(ASM_UD2, 0, ""); \
+ _BUG_FLAGS(ASM_UD2, flags, ""); \
__builtin_unreachable(); \
} while (0)
+#define BUG() BUG_FLAGS(0)
+#define BUG_RUST() BUG_FLAGS(BUGFLAG_NO_CUT_HERE)
+

/*
* This instrumentation_begin() is strictly speaking incorrect; but it
diff --git a/rust/helpers/bug.c b/rust/helpers/bug.c
index e2d13babc737..ef9be6a0c59b 100644
--- a/rust/helpers/bug.c
+++ b/rust/helpers/bug.c
@@ -4,5 +4,5 @@

__noreturn void rust_helper_BUG(void)
{
- BUG();
+ BUG_RUST();
}
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 6b4774b2b1c3..c5e2ab5da739 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -197,6 +197,9 @@ pub const fn as_ptr(&self) -> *mut bindings::module {
#[cfg(not(any(testlib, test)))]
#[panic_handler]
fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
+ unsafe {
+ bindings::_printk(str::CStr::from_bytes_with_nul_unchecked(bindings::CUT_HERE).as_ptr());
+ }
pr_emerg!("{}\n", info);
// SAFETY: FFI call.
unsafe { bindings::BUG() };

base-commit: e04c78d86a9699d136910cfc0bdcf01087e3267e
--
2.50.0