unityrs_texture/contain.rs
1//! Panic containment (`docs/plans/extract.md` E18): a decode that panics
2//! becomes [`DecodeError::Panicked`], which the engine records as the
3//! texture's `decoder_panic` skip (`docs/BATCH_SPEC.md` sections 7.3 and
4//! 9.3), and the batch goes on.
5//!
6//! The decoders do not panic on any input (indexing, `unwrap` and the rest
7//! are denied, arithmetic is checked or bounded, and the oracle and seeded
8//! tests feed them every size and every BC7 mode); this is the net under
9//! that rule, as E18 asks. [`crate::decode()`] runs only its pixel loop
10//! under it: the checks and the output's charge and allocation come before,
11//! outside it, so a panic there (a panicking `MemoryBudget`, say) unwinds
12//! out of `decode()` and is not taken for the decoder's. That is the rule
13//! for any closure [`contain()`] runs: it charges nothing, its checks and
14//! charges made before it, as `decode()` makes them. A closure that names a
15//! [`Meter`](unityrs_core::limits::Meter) is not [`UnwindSafe`] (its
16//! `dyn MemoryBudget` is not `RefUnwindSafe`), so it has to assert unwind
17//! safety ([`std::panic::AssertUnwindSafe`]); a budget that then panicked
18//! inside it would leave the meter charged with the bytes it was asking for
19//! (the core's `Meter::reserve` counts them before it asks the budget).
20//! Unwinding out of the loop drops the image being written, its buffer
21//! first and then its [`Charge`](unityrs_core::limits::Charge), so the
22//! meter is as it was before the call.
23//!
24//! The payload is kept as the unwinding carried it ([`Payload`]): the crate
25//! copies and allocates nothing on the panic path (the standard library
26//! allocates the payload and the unwinding's own state), whose payload may
27//! be as long as anything a decoder could format from its input, and which
28//! no meter has charged.
29//!
30//! Two things it cannot do: catch a panic in a build with
31//! `panic = "abort"` (the workspace sets no such profile), and stop the
32//! panic hook, which prints the panic to stderr before the unwinding begins;
33//! an engine that wants its stderr clean sets its own hook
34//! (`std::panic::set_hook`).
35
36use std::any::Any;
37use std::fmt;
38use std::panic::{UnwindSafe, catch_unwind};
39use std::sync::{Mutex, PoisonError};
40
41use crate::DecodeError;
42
43/// The text [`Payload::message`] gives when a panic's payload is neither a
44/// `&str` nor a `String` (`docs/BATCH_SPEC.md` section 7.3).
45pub const NON_STRING_PAYLOAD: &str = "non-string panic payload";
46
47/// The most bytes [`Payload::message`] gives: a `decoder_panic`'s detail is
48/// the payload cut to its first 1,024 bytes at a code point boundary
49/// (`docs/BATCH_SPEC.md` section 7.3).
50pub const MESSAGE_BYTES: usize = 1024;
51
52/// Runs `f`, a panic in it becoming [`DecodeError::Panicked`] with its
53/// payload. `f` charges nothing (module docs), and must be [`UnwindSafe`]:
54/// a caller whose closure writes into a buffer it then drops on the error
55/// asserts so itself ([`std::panic::AssertUnwindSafe`]), as
56/// [`crate::decode()`] does.
57pub fn contain<T, F>(f: F) -> Result<T, DecodeError>
58where
59 F: FnOnce() -> Result<T, DecodeError> + UnwindSafe,
60{
61 match catch_unwind(f) {
62 Ok(result) => result,
63 Err(payload) => Err(DecodeError::Panicked {
64 payload: Payload::new(payload),
65 }),
66 }
67}
68
69/// A panic's payload, kept whole, with no copy: the box the unwinding
70/// carried, downcast where it holds a `&str` or a `String` (what `panic!`
71/// and the standard library's panics carry), which moves nothing.
72pub struct Payload(Kept);
73
74// The payload's own boxes, downcast: unboxing them would free each box,
75// and `into_any` would then allocate a new one.
76#[allow(clippy::redundant_allocation, clippy::box_collection)]
77enum Kept {
78 Str(Box<&'static str>),
79 String(Box<String>),
80 /// Any other payload. The mutex only makes the error `Sync`, as the
81 /// payload need not be; it is never locked.
82 Other(Mutex<Box<dyn Any + Send>>),
83}
84
85const _: () = crate::send_sync::<Payload>();
86
87impl Payload {
88 fn new(payload: Box<dyn Any + Send>) -> Self {
89 let payload = match payload.downcast::<&'static str>() {
90 Ok(s) => return Self(Kept::Str(s)),
91 Err(other) => other,
92 };
93 match payload.downcast::<String>() {
94 Ok(s) => Self(Kept::String(s)),
95 Err(other) => Self(Kept::Other(Mutex::new(other))),
96 }
97 }
98
99 /// The whole text: the payload's, or [`NON_STRING_PAYLOAD`].
100 fn text(&self) -> &str {
101 match &self.0 {
102 Kept::Str(s) => s,
103 Kept::String(s) => s,
104 Kept::Other(_) => NON_STRING_PAYLOAD,
105 }
106 }
107
108 /// The payload's text, or [`NON_STRING_PAYLOAD`], cut to its first
109 /// [`MESSAGE_BYTES`] bytes at a code point boundary: a `decoder_panic`'s
110 /// detail.
111 #[must_use]
112 pub fn message(&self) -> &str {
113 let text = self.text();
114 text.get(..text.floor_char_boundary(MESSAGE_BYTES))
115 .unwrap_or(text)
116 }
117
118 /// Whether [`Self::message`] is cut: the manifest row's `cut`.
119 #[must_use]
120 pub fn is_cut(&self) -> bool {
121 self.text().len() > MESSAGE_BYTES
122 }
123
124 /// The payload as the unwinding carried it, for
125 /// [`std::panic::resume_unwind`].
126 #[must_use]
127 pub fn into_any(self) -> Box<dyn Any + Send> {
128 match self.0 {
129 Kept::Str(s) => s,
130 Kept::String(s) => s,
131 Kept::Other(m) => m.into_inner().unwrap_or_else(PoisonError::into_inner),
132 }
133 }
134}
135
136/// Two payloads are equal when their texts are.
137impl PartialEq for Payload {
138 fn eq(&self, other: &Self) -> bool {
139 self.text() == other.text()
140 }
141}
142
143impl Eq for Payload {}
144
145impl fmt::Debug for Payload {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.debug_tuple("Payload").field(&self.message()).finish()
148 }
149}
150
151/// [`Payload::message`].
152impl fmt::Display for Payload {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 f.write_str(self.message())
155 }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::{MESSAGE_BYTES, NON_STRING_PAYLOAD, Payload, contain};
161 use crate::DecodeError;
162
163 fn payload<T: std::fmt::Debug>(r: Result<T, DecodeError>) -> Payload {
164 match r {
165 Err(DecodeError::Panicked { payload }) => payload,
166 other => panic!("not a panic: {other:?}"),
167 }
168 }
169
170 #[test]
171 fn a_panic_is_an_error_with_its_payload() {
172 let p = payload(contain::<(), _>(|| panic!("boom {}", 7)));
173 assert_eq!((p.message(), p.is_cut()), ("boom 7", false));
174 let p = payload(contain::<(), _>(|| panic!("static")));
175 assert_eq!(p.message(), "static");
176 let p = payload(contain::<(), _>(|| std::panic::panic_any(42u8)));
177 assert_eq!(p.message(), NON_STRING_PAYLOAD);
178 assert_eq!(p.into_any().downcast_ref::<u8>(), Some(&42));
179 #[allow(clippy::indexing_slicing)]
180 let r: Result<u8, _> = contain(|| {
181 let v: Vec<u8> = Vec::new();
182 Ok(v[3])
183 });
184 assert!(matches!(r, Err(DecodeError::Panicked { .. })), "{r:?}");
185 }
186
187 /// The payload's own bytes, not a copy, cut at a code point boundary.
188 #[test]
189 fn the_payload_is_kept_and_its_message_cut() {
190 let text = format!("a{}", "é".repeat(MESSAGE_BYTES));
191 let at = text.as_ptr();
192 let p = payload(contain::<(), _>(move || std::panic::panic_any(text)));
193 assert_eq!(p.message().as_ptr(), at);
194 // "a", then two-byte code points: byte 1,024 is inside one.
195 assert_eq!(p.message().len(), MESSAGE_BYTES - 1);
196 assert!(p.is_cut());
197 assert_eq!(p.to_string(), p.message());
198 let whole = p.into_any().downcast::<String>().unwrap();
199 assert_eq!((whole.as_ptr(), whole.len()), (at, 1 + 2 * MESSAGE_BYTES));
200 let exact = "x".repeat(MESSAGE_BYTES);
201 let p = payload(contain::<(), _>(move || std::panic::panic_any(exact)));
202 assert_eq!((p.message().len(), p.is_cut()), (MESSAGE_BYTES, false));
203 }
204
205 #[test]
206 fn what_is_returned_or_raised_passes_through() {
207 assert_eq!(contain(|| Ok(5)), Ok(5));
208 assert_eq!(
209 contain::<(), _>(|| Err(DecodeError::NoImageData)),
210 Err(DecodeError::NoImageData)
211 );
212 }
213}