Crate unwind_context

Source
Expand description

The unwind-context crate makes debugging panics easier by adding a colored panic context with a simple macro.

$ cargo -q run --example demo --features="detect-color-support"
thread 'main' panicked at examples/demo.rs:36:12:
byte index 1 is not a char boundary; it is inside 'á' (bytes 0..2) of `áöù`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fn split(value: "áöù", at: 1)
    at examples/demo.rs:35:16
fn rotate_left(value: "áöù", mid: 1)
    at examples/demo.rs:29:16
fn collect_rotations(value: "áöù")
    at examples/demo.rs:22:16
fn app_logic(value.clone(): Wrapper("abc\nbcd"), arr: [1, 2], ..., flag: false)
    at examples/demo.rs:14:16

§Introduction

In Rust, panics are typically used when an unrecoverable error occurs or when writing examples, prototype code, or tests.

However, it can be difficult to pinpoint the exact cause of a panic, especially if it happens deep in the code or within a loop. While adding logs can help, this may lead to a large number of log entries, making it challenging to identify which ones are related to the panic.

§About

The goal of this crate is to make the panic context addition simple, and the context itself detailed enough, and easy to read. Accordingly, it also makes it easier to add context to assertions in your tests. This crate provides unwind_context and debug_unwind_context macros and some other auxiliary types, traits, functions, and macros that help you define function or scope context and write it to std::io::stderr or another writeable target if panic occurs. If panic occurs, the context will be written in “reverse” chronological order during the unwinding process.

This library adds very little overhead to compiled functions unless they are panicked:

  • First, it constructs a structure containing the context data, code location, writer, and color scheme on the stack. It also stores a reference to the custom panic detector, if specified.
  • And when this “context scope guard” structure is dropped, its destructor checks for std::thread::panicking and calls the cold print function if panic has been detected.

This crate is intended for diagnostic use. The exact contents and format of the messages printed on panic are not specified, other than being a clear and compact description.

Note that the context will only be printed if the panic setting is set to unwind, which is the default for both dev and release profiles.

§Usage

First, add the following to your Cargo.toml:

[dependencies]
unwind-context = "0.2.2"

Then, add the macro call with the given function arguments or scope arguments to the beginning of the functions to be tracked and bind the result to some scope variable (otherwise the unwind context scope guard will be immediately dropped):

use unwind_context::unwind_context;

fn func1(a: u32, b: &str, c: bool) {
    let _ctx = unwind_context!(fn(a, b, c));
    // ...
    for i in 0..10 {
        let _ctx = unwind_context!(i);
        // ...
    }
    // ...
}

With unwind_context!(a, b, c) syntax, it will print code location, given argument names (stringified expressions), and values on unwind, whereas with unwind_context!(fn(a, b, c)) it will also print function names as well. Note that it uses the core::fmt::Debug representation. If you want to use the core::fmt::Display representation, you can use the WithDisplay wrapper.

You can use the set_colors_enabled function to unconditionally enable the 16-ANSI-color colorization. If you want to enable colorization only if supported by the terminal, you can use the enable_colors_if_supported function, which will require enabling the detect-color-support feature flag:

[dependencies.unwind-context]
version = "0.2.2"
features = [ "detect-color-support" ]
fn main() {
    unwind_context::enable_colors_if_supported();
    // ...
}

#[test]
fn test() {
    unwind_context::enable_colors_if_supported()
    // ...
}

If you want to specify a custom color scheme, you can use the set_default_color_scheme function. Also, colorization can be customized separately for each context scope guard with the unwind_context_with_io and unwind_context_with_fmt macros.

This crate depends on the standard library by default that is needed to write to std::io::stderr and to detect panicking using std::thread::panicking. To use this crate in a #![no_std] context with your custom core::fmt::Write writer and custom PanicDetector, use default-features = false in your Cargo.toml as shown below:

[dependencies.unwind-context]
version = "0.2.2"
default-features = false

§Examples

The following crate example:

#![allow(missing_docs, unused_crate_dependencies)]

use unwind_context::unwind_context;

#[derive(Clone, Debug)]
struct Wrapper<T>(T);

fn main() {
    unwind_context::enable_colors_if_supported();
    app_logic(Wrapper("abc\nbcd".to_owned()), &[1, 2], "secret", false);
}

fn app_logic(value: Wrapper<String>, arr: &[u8], secret: &str, flag: bool) {
    let _ctx = unwind_context!(fn(value.clone(), arr, ..., flag));
    // ...
    let _ = collect_rotations("áöù");
    // ...
    let _ = (value, arr, secret, flag);
}

fn collect_rotations(value: &str) -> Vec<String> {
    let _ctx = unwind_context!(fn(value));
    (0..value.len())
        .map(|mid| rotate_left(value, mid))
        .collect()
}

fn rotate_left(value: &str, mid: usize) -> String {
    let _ctx = unwind_context!(fn(value, mid));
    let (left, right) = split(value, mid);
    format!("{right}{left}")
}

fn split(value: &str, at: usize) -> (&str, &str) {
    let _ctx = unwind_context!(fn(value, at));
    (&value[0..at], &value[at..])
}

will output:

$ cargo -q run --example demo --features="detect-color-support"
thread 'main' panicked at examples/demo.rs:36:12:
byte index 1 is not a char boundary; it is inside 'á' (bytes 0..2) of `áöù`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fn split(value: "áöù", at: 1)
    at examples/demo.rs:35:16
fn rotate_left(value: "áöù", mid: 1)
    at examples/demo.rs:29:16
fn collect_rotations(value: "áöù")
    at examples/demo.rs:22:16
fn app_logic(value.clone(): Wrapper("abc\nbcd"), arr: [1, 2], ..., flag: false)
    at examples/demo.rs:14:16

§Macro expansion

The following function:

use unwind_context::unwind_context;

fn foo(a: &str, b: Vec<u8>, c: bool, d: String) {
    let _ctx = unwind_context!(fn(a, &b, ..., d.clone()));
    // ...
    for i in 0..10 {
        let _ctx = unwind_context!(i);
        // ...
    }
}

will partially expand into:

fn foo(a: u32, b: Vec<u8>, c: bool, d: String) {
    let _ctx = unwind_context::UnwindContextWithIo::new(
        unwind_context::UnwindContextFunc::new(
            {
                struct Item;
                let module_path = ::core::module_path!();
                let item_type_name = ::core::any::type_name::<Item>();
                unwind_context::func_name_from_item_type_name(
                    module_path, item_type_name
                )
            },
            (
                unwind_context::UnwindContextArg::new(Some("a"), a),
                (
                    unwind_context::UnwindContextArg::new(Some("&b"), &b),
                    (
                        unwind_context::UnwindContextArg::new(
                            None,
                            unwind_context::NonExhaustiveMarker,
                        ),
                        (
                            unwind_context::UnwindContextArg::new(
                                Some("d.clone()"), d.clone()
                               ),
                            (),
                        ),
                    ),
                ),
            ),
        ),
        ::std::io::stderr(),
        unwind_context::StdPanicDetector,
        unwind_context::get_default_color_scheme_if_enabled(),
    );
    // ...
    for i in 0..10 {
        let _ctx = unwind_context::UnwindContextWithIo::new(
            unwind_context::UnwindContextArgs::new((
                unwind_context::UnwindContextArg::new(Some("i"), i),
                (),
            )),
            ::std::io::stderr(),
            unwind_context::StdPanicDetector,
            unwind_context::get_default_color_scheme_if_enabled(),
        );
        // ...
    }
}

§Feature Flags

§Similar crates

  • scopeguard allows you to run any code at the end of a scope. It has both success and unwind guard variants, and it doesn’t require panic hook modification.
  • panic-context allows you to specify and modify panic context using a custom panic hook. It provides more fine-grained control over the output. However, it implicitly modifies the panic hook using a mutex for a one-time thread local initialization and doesn’t add any automatic context or colorization.
  • econtext allows you to specify panic context and automatically adds some context including function name and location. However, it requires panic hook modification via the init function and uses dynamic dispatch and some unsafe code.

§License

Licensed under either of

at your option.

§Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Macros§

build_unwind_context_data
Creates either UnwindContextFunc or UnwindContextArgs wrapper with the given function arguments or scope variables.
debug_unwind_contextstd
Creates UnwindContextWithIo with a default writer, panic detector, color scheme , and given function or scope context in debug builds only.
debug_unwind_context_with_fmt
Creates UnwindContextWithFmt with a given core::fmt::Write writer, panic detector, color scheme, and a given function or scope context in debug builds only.
debug_unwind_context_with_iostd
Creates UnwindContextWithIo with a given std::io::Write writer, panic detector, color scheme, and a given function or scope context in debug builds only.
func_name
Returns the name of the function where the macro is invoked. Returns a &'static str.
unwind_contextstd
Creates UnwindContextWithIo with a default writer, panic detector, color scheme , and given function or scope context.
unwind_context_with_fmt
Creates UnwindContextWithFmt with a given core::fmt::Write writer, panic detector, color scheme, and a given function or scope context.
unwind_context_with_iostd
Creates UnwindContextWithIo with a given std::io::Write writer, panic detector, color scheme, and a given function or scope context.

Structs§

AnsiColorScheme
A structure representing an ANSI color scheme used by DebugAnsiColored formatter.
AnsiColored
An utility wrapper type is used to forward value core::fmt::Debug implementation to DebugAnsiColored implementation with a given AnsiColorScheme.
NonExhaustiveMarker
A marker type which is used in arguments list to indicate that there are some other arguments that are omitted.
StdPanicDetectorstd
A default PanicDetector for a crates compiled with the Rust standard library.
UnwindContextArg
A structure representing an argument name and its value.
UnwindContextArgs
A structure representing function argument names and their values.
UnwindContextFunc
A structure representing function name and its argument names and values.
UnwindContextWithFmt
A structure representing a scoped guard with unwind context with std::io::Write writer.
UnwindContextWithIostd
A structure representing a scoped guard with unwind context with core::fmt::Write writer.
WithDisplay
An utility wrapper type which is used to forward both core::fmt::Debug and core::fmt::Display value implementations to its core::fmt::Display implementation.
WithPrettyDebug
An utility wrapper type which is used to forward both core::fmt::Debug and core::fmt::Display value implementations to its core::fmt::Debug implementation with pretty flag.

Statics§

DEFAULT_DEFAULT_COLOR_SCHEME
The default ANSI color scheme, which is used if colorization is enabled but no custom color scheme is set.

Traits§

DebugAnsiColored
An utility alternative core::fmt::Debug trait which can used for colored context formatting.
PanicDetector
An utility trait which is used to detect panic.

Functions§

are_colors_enabled
Returns true if ANSI colors were enabled before.
enable_colors_if_supporteddetect-color-support
Enables ANSI colors if supported by the terminal for stderr stream for all threads.
get_default_color_scheme
Returns the currently set default ANSI color scheme.
get_default_color_scheme_if_enabled
Returns current ANSI color scheme if ANSI colors were enabled, None otherwise.
set_colors_enabled
Enables or disables ANSI colorization.
set_default_color_schemecustom-default-colors
Sets default ANSI color scheme for all threads.