Skip to main content

tor_error/
internal.rs

1//! The InternalError type, macro for generating it, etc.
2
3use std::convert::Infallible;
4use std::fmt::{self, Debug, Display};
5use std::panic;
6use std::sync::Arc;
7use void::Void;
8
9use super::*;
10
11#[cfg(all(feature = "backtrace", not(miri)))]
12/// Backtrace implementation for when the feature is enabled
13mod ie_backtrace {
14    use super::*;
15    use std::backtrace::Backtrace;
16
17    #[derive(Debug, Clone)]
18    /// Captured backtrace, if turned on
19    pub(crate) struct Captured(Arc<Backtrace>);
20
21    /// Capture a backtrace, if turned on
22    pub(crate) fn capture() -> Captured {
23        Captured(Arc::new(Backtrace::force_capture()))
24    }
25
26    impl Display for Captured {
27        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
28            Display::fmt(&self.0, f)
29        }
30    }
31}
32
33#[cfg(any(not(feature = "backtrace"), miri))]
34/// Backtrace implementation for when the feature is disabled
35mod ie_backtrace {
36    use super::*;
37
38    #[derive(Debug, Clone)]
39    /// "Captured backtrace", but actually nothing
40    pub(crate) struct Captured;
41
42    /// "Capture a backtrace", but actually return nothing
43    pub(crate) fn capture() -> Captured {
44        Captured
45    }
46
47    impl Display for Captured {
48        fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
49            Ok(())
50        }
51    }
52}
53
54#[derive(Debug, Clone)]
55/// Programming error (a bug)
56//
57// Boxed because it is fairly large (>=12 words), and will be in a variant in many other errors.
58//
59// This is a single Bug type containing a kind in BugRepr, rather than separate InternalError and
60// BadApiUsage types, primarily because that means that one Bug(#[from] tor_error::Bug) suffices in
61// every crate's particular error type.
62pub struct Bug(Box<BugRepr>);
63
64/// The source of a Bug
65type SourceError = Arc<dyn std::error::Error + Send + Sync + 'static>;
66
67#[derive(Debug, Clone)]
68/// Internal error (a bug)
69struct BugRepr {
70    /// Message, usually from internal!() like format!
71    message: String,
72
73    /// File and line number
74    location: &'static panic::Location<'static>,
75
76    /// Backtrace, perhaps
77    backtrace: ie_backtrace::Captured,
78
79    /// Source, perhaps
80    source: Option<SourceError>,
81
82    /// Kind
83    ///
84    /// `Internal` or `BadApiUsage`
85    kind: ErrorKind,
86}
87
88impl Bug {
89    /// Create a bug error report capturing this call site and backtrace
90    ///
91    /// Prefer to use [`internal!`],
92    /// as that makes it easy to add additional information
93    /// via format parameters.
94    #[track_caller]
95    pub fn new<S: Into<String>>(kind: ErrorKind, message: S) -> Self {
96        Bug::new_inner(kind, message.into(), None)
97    }
98
99    /// Create an internal error
100    #[track_caller]
101    fn new_inner(kind: ErrorKind, message: String, source: Option<SourceError>) -> Self {
102        Bug(BugRepr {
103            kind,
104            message,
105            source,
106            location: panic::Location::caller(),
107            backtrace: ie_backtrace::capture(),
108        }
109        .into())
110    }
111
112    /// Create a bug error report from another error, capturing this call site and backtrace
113    ///
114    /// In `map_err`, and perhaps elsewhere, prefer to use [`into_internal!`],
115    /// as that makes it easy to add additional information
116    /// via format parameters.
117    #[track_caller]
118    pub fn from_error<E, S>(kind: ErrorKind, source: E, message: S) -> Self
119    where
120        S: Into<String>,
121        E: std::error::Error + Send + Sync + 'static,
122    {
123        Bug::new_inner(kind, message.into(), Some(Arc::new(source)))
124    }
125
126    /// Adds context to an internal error or bug
127    ///
128    /// Prepends `prepend + ": "` to the message.
129    //
130    // The name is by analogy with `anyhow`, and matches the `BugContext` trait
131    // (But distinguished to avoid mental and trait method clashes with `anyhow`
132    // and make things clear at the call site.)
133    pub fn bug_context(mut self, prepend: impl Display) -> Self {
134        self.0.message = format!("{prepend}: {}", self.0.message);
135        self
136    }
137}
138
139impl std::error::Error for Bug {
140    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
141        self.0
142            .source
143            .as_deref()
144            .map(|traitobj| traitobj as _ /* cast away Send and Sync */)
145    }
146}
147
148impl Display for Bug {
149    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150        writeln!(
151            f,
152            "{} at {}: {}",
153            self.0.kind, self.0.location, self.0.message
154        )?;
155        Display::fmt(&self.0.backtrace, f)?;
156        Ok(())
157    }
158}
159
160/// Extension trait for `.bug_context()` on `Result`
161pub trait BugContext: Sealed {
162    /// Adds context to an internal error or bug
163    ///
164    /// Prepends `prepend + ": "` to the error message, if it's an error (`[Bug]`).
165    fn bug_context<D: Display>(self, prefix: D) -> Self;
166}
167impl<T> BugContext for Result<T, Bug> {
168    fn bug_context<D: Display>(self, prefix: D) -> Self {
169        self.map_err(move |e| e.bug_context(prefix))
170    }
171}
172impl<T> Sealed for Result<T, Bug> {}
173/// Sealed (for `BugContext`)
174// Separate from crate::sealed::Sealed because that has wide blanket impls which we don't want
175mod sealed {
176    /// Sealed
177    pub trait Sealed {}
178}
179use sealed::Sealed;
180
181/// Create an internal error, including a message like `format!`, and capturing this call site
182///
183/// The calling stack backtrace is also captured,
184/// when the `backtrace` cargo feature this is enabled.
185///
186/// # Examples
187///
188/// ```
189/// use tor_error::internal;
190///
191/// # fn main() -> Result<(), tor_error::Bug> {
192/// # let mut cells = [()].iter();
193/// let need_cell = cells.next().ok_or_else(|| internal!("no cells"))?;
194/// # Ok(())
195/// # }
196/// ```
197//
198// In principle this macro could perhaps support internal!(from=source, "format", ...)
199// but there are alternative ways of writing that:
200//    Bug::new_from(source, format!(...)) or
201//    into_internal!("format", ...)(source)
202// Those are not so bad for what we think will be the rare cases not
203// covered by internal!(...) or map_err(into_internal!(...))
204#[macro_export]
205macro_rules! internal {
206    { $( $arg:tt )* } => {
207        $crate::Bug::new($crate::ErrorKind::Internal, format!($($arg)*))
208    }
209}
210
211/// Create a bad API usage error, including a message like `format!`, and capturing this call site
212///
213/// The calling stack backtrace is also captured,
214/// when the `backtrace` cargo feature this is enabled.
215///
216/// # Examples
217///
218/// ```
219/// use tor_error::bad_api_usage;
220///
221/// # fn main() -> Result<(), tor_error::Bug> {
222/// # let mut targets = [()].iter();
223/// let need_target = targets.next().ok_or_else(|| bad_api_usage!("no targets"))?;
224/// # Ok(())
225/// # }
226#[macro_export]
227macro_rules! bad_api_usage {
228    { $( $arg:tt )* } => {
229        $crate::Bug::new($crate::ErrorKind::BadApiUsage, format!($($arg)*))
230    }
231}
232
233/// Helper for converting an error into an internal error
234///
235/// Returns a closure implementing `FnOnce(E) -> Bug`.
236/// The source error `E` must be `std::error::Error + Send + Sync + 'static`.
237///
238/// # Examples
239/// ```
240/// use tor_error::into_internal;
241///
242/// # fn main() -> Result<(), tor_error::Bug> {
243/// # let s = b"";
244/// let s = std::str::from_utf8(s).map_err(into_internal!("bad bytes: {:?}", s))?;
245/// # Ok(())
246/// # }
247/// ```
248#[macro_export]
249macro_rules! into_internal {
250    { $( $arg:tt )* } => {
251      std::convert::identity( // Hides the IEFI from clippy::redundant_closure_call
252        |source| $crate::Bug::from_error($crate::ErrorKind::Internal, source, format!($($arg)*))
253      )
254    }
255}
256
257/// Helper for converting an error into an bad API usage error
258///
259/// Returns a closure implementing `FnOnce(E) -> InternalError`.
260/// The source error `E` must be `std::error::Error + Send + Sync + 'static`.
261///
262/// # Examples
263/// ```
264/// use tor_error::into_bad_api_usage;
265///
266/// # fn main() -> Result<(), tor_error::Bug> {
267/// # let host = b"";
268/// let host = std::str::from_utf8(host).map_err(into_bad_api_usage!("hostname is bad UTF-8: {:?}", host))?;
269/// # Ok(())
270/// # }
271/// ```
272#[macro_export]
273macro_rules! into_bad_api_usage {
274    { $( $arg:tt )* } => {
275      std::convert::identity( // Hides the IEFI from clippy::redundant_closure_call
276        |source| $crate::Bug::from_error($crate::ErrorKind::BadApiUsage, source, format!($($arg)*))
277      )
278    }
279}
280
281impl HasKind for Bug {
282    fn kind(&self) -> ErrorKind {
283        self.0.kind
284    }
285}
286
287impl From<Infallible> for Bug {
288    fn from(i: Infallible) -> Self {
289        match i {}
290    }
291}
292
293impl From<Void> for Bug {
294    fn from(v: Void) -> Self {
295        match v {}
296    }
297}
298
299#[cfg(test)]
300mod test {
301    // @@ begin test lint list maintained by maint/add_warning @@
302    #![allow(clippy::bool_assert_comparison)]
303    #![allow(clippy::clone_on_copy)]
304    #![allow(clippy::dbg_macro)]
305    #![allow(clippy::mixed_attributes_style)]
306    #![allow(clippy::print_stderr)]
307    #![allow(clippy::print_stdout)]
308    #![allow(clippy::single_char_pattern)]
309    #![allow(clippy::unwrap_used)]
310    #![allow(clippy::unchecked_time_subtraction)]
311    #![allow(clippy::useless_vec)]
312    #![allow(clippy::needless_pass_by_value)]
313    #![allow(clippy::string_slice)] // See arti#2571
314    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
315    use super::*;
316
317    // We test this on "important" and "reliable" platforms only.
318    //
319    // This test case mainly is to ensure that we are using the backtrace module correctly, etc.,
320    // which can be checked by doing it on one platform.
321    //
322    // Doing the test on *all* platforms would simply expose us to the vagaries of platform
323    // backtrace support.  Arti ought not to fail its tests just because someone is using a
324    // platform with poor backtrace support.
325    //
326    // On the other hand, we *do* want to know that things are correct on platforms where we think
327    // Rust backtraces work properly.
328    //
329    // So this list is a compromise.  See
330    //   https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/509#note_2803085
331    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
332    #[test]
333    #[inline(never)]
334    fn internal_macro_test() {
335        let start_of_func = line!();
336
337        let e = internal!("Couldn't {} the {}.", "wobble", "wobbling device");
338        assert_eq!(e.0.message, "Couldn't wobble the wobbling device.");
339        assert!(e.0.location.file().ends_with("internal.rs"));
340        assert!(e.0.location.line() > start_of_func);
341        assert!(e.0.source.is_none());
342
343        let s = e.to_string();
344        dbg!(&s);
345
346        assert!(s.starts_with("internal error (bug) at "));
347        assert!(s.contains("Couldn't wobble the wobbling device."));
348        #[cfg(feature = "backtrace")]
349        assert!(s.contains("internal_macro_test"));
350
351        #[derive(thiserror::Error, Debug)]
352        enum Wrap {
353            #[error("Internal error")]
354            Internal(#[from] Bug),
355        }
356
357        let w: Wrap = e.into();
358        let s = format!("Got: {}", w.report());
359        dbg!(&s);
360        assert!(s.contains("Couldn't wobble the wobbling device."));
361    }
362
363    #[test]
364    fn source() {
365        use std::error::Error;
366        use std::str::FromStr;
367
368        let start_of_func = line!();
369        let s = "penguin";
370        let inner = u32::from_str(s).unwrap_err();
371        let outer = u32::from_str(s)
372            .map_err(into_internal!("{} is not a number", s))
373            .unwrap_err();
374
375        let afterwards = line!();
376
377        assert_eq!(outer.source().unwrap().to_string(), inner.to_string());
378        assert!(outer.0.location.line() > start_of_func);
379        assert!(outer.0.location.line() < afterwards);
380    }
381}