quack_rs/callback/payload.rs
1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Disposing of a caught panic payload without re-entering the unwinder.
7//!
8//! `catch_unwind` hands back the payload as a `Box<dyn Any + Send>`, and
9//! dropping that box runs the payload's `Drop` — which is arbitrary user code:
10//! `std::panic::panic_any(value)` makes *any* `Send + 'static` value the payload.
11//! If that `Drop` panics while the box is being dropped outside a guard, the new
12//! unwind reaches the `extern "C"` frame the payload was caught in and the
13//! process aborts (`panic_cannot_unwind`) — exactly what the first
14//! `catch_unwind` existed to prevent.
15//!
16//! Everything in this crate that catches a panic at an FFI boundary therefore
17//! gives the payload to [`take_panic_message`] or [`drop_panic_payload`] rather
18//! than letting it fall out of scope.
19
20use std::any::Any;
21use std::panic::{catch_unwind, AssertUnwindSafe};
22
23/// Drops a caught panic payload, containing any panic its `Drop` raises.
24///
25/// If dropping the payload panics, that second panic's payload is dropped the
26/// same way, and so on — a payload whose `Drop` panics usually panics with an
27/// ordinary message, whose own drop cannot panic, so the chain ends at once and
28/// nothing is leaked. Only after [`MAX_NESTED_PAYLOAD_DROPS`] consecutive
29/// panicking drops is the remaining payload leaked with [`std::mem::forget`]:
30/// the chain is user code with no inherent bound, and leaking one allocation is
31/// the price of never aborting.
32///
33/// # Example
34///
35/// ```rust
36/// struct Bomb;
37/// impl Drop for Bomb {
38/// fn drop(&mut self) {
39/// panic!("payload destructor exploded");
40/// }
41/// }
42///
43/// let payload = std::panic::catch_unwind(|| std::panic::panic_any(Bomb)).unwrap_err();
44/// // Dropping `payload` directly would unwind out of here.
45/// quack_rs::callback::drop_panic_payload(payload);
46/// ```
47pub fn drop_panic_payload(payload: Box<dyn Any + Send>) {
48 let mut payload = payload;
49 for _ in 0..MAX_NESTED_PAYLOAD_DROPS {
50 match catch_unwind(AssertUnwindSafe(move || drop(payload))) {
51 Ok(()) => return,
52 Err(next) => payload = next,
53 }
54 }
55 std::mem::forget(payload);
56}
57
58/// How many nested panicking payload drops [`drop_panic_payload`] unwinds
59/// through before it leaks what is left rather than keep going.
60pub const MAX_NESTED_PAYLOAD_DROPS: usize = 8;
61
62/// Extracts the panic message from a caught payload, then disposes of the
63/// payload with [`drop_panic_payload`].
64///
65/// The message is copied out first, so it survives even when the payload's
66/// `Drop` panics. Used by every callback macro in this crate; public because the
67/// macros expand in the extension crate and need to reach it.
68///
69/// # Example
70///
71/// ```rust
72/// let payload = std::panic::catch_unwind(|| panic!("boom")).unwrap_err();
73/// assert_eq!(quack_rs::callback::take_panic_message(payload), "boom");
74/// ```
75#[must_use]
76pub fn take_panic_message(payload: Box<dyn Any + Send>) -> String {
77 let message = super::panic_message(&payload);
78 drop_panic_payload(payload);
79 message
80}
81
82#[cfg(test)]
83mod tests {
84 use super::{drop_panic_payload, take_panic_message};
85 use crate::callback::catch_ffi_panic;
86 use std::cell::Cell;
87
88 thread_local! {
89 // Per thread, because the test harness runs these in parallel and the
90 // payload is always dropped on the thread that caught it.
91 static BOMB_DROPS: Cell<usize> = const { Cell::new(0) };
92 }
93
94 /// A panic payload whose destructor itself panics.
95 struct PayloadBomb;
96 impl Drop for PayloadBomb {
97 fn drop(&mut self) {
98 BOMB_DROPS.with(|n| n.set(n.get() + 1));
99 panic!("panic payload destructor deliberately exploded");
100 }
101 }
102
103 // Each of these would abort the whole test binary before the fix
104 // (`panic_cannot_unwind` / "panic in a function that cannot unwind"), so
105 // reaching the assertions is itself the regression check.
106
107 #[test]
108 fn a_payload_whose_drop_panics_is_contained() {
109 let payload = std::panic::catch_unwind(|| std::panic::panic_any(PayloadBomb))
110 .expect_err("panic_any must unwind");
111 let before = BOMB_DROPS.with(Cell::get);
112 drop_panic_payload(payload);
113 assert_eq!(BOMB_DROPS.with(Cell::get), before + 1);
114 }
115
116 #[test]
117 fn take_panic_message_survives_a_payload_whose_drop_panics() {
118 let payload = std::panic::catch_unwind(|| std::panic::panic_any(PayloadBomb))
119 .expect_err("panic_any must unwind");
120 assert_eq!(take_panic_message(payload), "<non-string panic payload>");
121 }
122
123 #[test]
124 fn catch_ffi_panic_contains_a_payload_whose_drop_panics() {
125 let outcome: Result<(), String> = catch_ffi_panic(|| std::panic::panic_any(PayloadBomb));
126 assert_eq!(outcome, Err("<non-string panic payload>".to_owned()));
127 }
128
129 // The generated destructor is the one macro with no DuckDB call in it, so it
130 // is the one that can be driven without a database.
131 crate::aggregate_destroy_callback!(bomb_destroy, |_states, _count| {
132 std::panic::panic_any(PayloadBomb);
133 });
134
135 #[test]
136 fn a_generated_destructor_contains_a_payload_whose_drop_panics() {
137 // SAFETY: the body ignores both arguments.
138 unsafe { bomb_destroy(std::ptr::null_mut(), 0) };
139 }
140
141 thread_local! {
142 static NESTED_DROPS: Cell<usize> = const { Cell::new(0) };
143 }
144
145 /// A payload whose `Drop` panics with another `NestedBomb` one level
146 /// shallower, until level 0, whose `Drop` returns normally.
147 struct NestedBomb(usize);
148 impl Drop for NestedBomb {
149 fn drop(&mut self) {
150 NESTED_DROPS.with(|n| n.set(n.get() + 1));
151 if self.0 > 0 {
152 std::panic::panic_any(Self(self.0 - 1));
153 }
154 }
155 }
156
157 /// Every payload in a chain shorter than the bound is dropped, not leaked:
158 /// before, the payload raised by the first panicking `Drop` was
159 /// `mem::forget`-ed unconditionally, which `LeakSanitizer` and Miri report.
160 #[test]
161 fn a_chain_of_panicking_payload_drops_is_freed_to_the_end() {
162 let depth = super::MAX_NESTED_PAYLOAD_DROPS - 2;
163 let payload = std::panic::catch_unwind(|| std::panic::panic_any(NestedBomb(depth)))
164 .expect_err("panic_any must unwind");
165 let before = NESTED_DROPS.with(Cell::get);
166 drop_panic_payload(payload);
167 // Levels `depth, depth - 1, …, 0` each dropped exactly once.
168 assert_eq!(NESTED_DROPS.with(Cell::get), before + depth + 1);
169 }
170
171 #[test]
172 fn a_string_payload_keeps_its_message() {
173 let payload =
174 std::panic::catch_unwind(|| panic!("boom {}", 7)).expect_err("panic must unwind");
175 assert_eq!(take_panic_message(payload), "boom 7");
176 }
177
178 /// The fourth audit's F16: a `Box<str>` payload (`panic_any` with a boxed
179 /// string) was reported as `<non-string panic payload>`.
180 #[test]
181 fn a_boxed_str_payload_keeps_its_message() {
182 let payload = std::panic::catch_unwind(|| {
183 std::panic::panic_any(Box::<str>::from("boxed boom"));
184 })
185 .expect_err("panic_any must unwind");
186 assert_eq!(take_panic_message(payload), "boxed boom");
187 }
188
189 /// The fourth audit's F12 / T3: every callback macro reports through
190 /// `panic_c_message`, which never hands `DuckDB` an empty message.
191 #[test]
192 fn panic_c_message_replaces_only_an_empty_message() {
193 use super::super::{panic_c_message, EMPTY_PANIC_PLACEHOLDER};
194 let empty = std::panic::catch_unwind(|| panic!("")).expect_err("panic must unwind");
195 assert_eq!(panic_c_message(empty).to_str(), Ok(EMPTY_PANIC_PLACEHOLDER));
196 let nul = std::panic::catch_unwind(|| panic!("a\0b")).expect_err("panic must unwind");
197 assert_eq!(panic_c_message(nul).to_str(), Ok("a?b"));
198 }
199}