Panic
If something goes very wrong, a program will panic!.
esp-backtrace provides a panic! implementation through the panic-handler feature.
"Handling panic!" here means to print what was executed up to that point (the backtrace), and probably stops code execution as well.
We could use our own panic-handler instead, and no backtrace at all. For example, this one:
use core::panic::PanicInfo;
use core::sync::atomic::{self, Ordering};
#[inline(never)]
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {
atomic::compiler_fence(Ordering::SeqCst);
}
}
Warning
We need to
use esp-backtrace as _;so that this handler is included in the final binary.
In the exercise below, we configure a profile. Profiles are configurations cargo uses to control compilation. When unspecified, cargo sets sensible defaults for us.
Exercise 1
-
Access the project at
exercises/panic. -
Add all the boilerplate code described earlier.
-
Add a
panic!withinmain.- But remember, it's for irrecoverable errors!
-
Run the code with
cargo run; this uses the development profile.- It outputs debug information into the compiled binary.
-
Then run with release profile
cargo run --release.-
The default
--releasebehaviour excludes debug information and minimises the binary size; the backtrace shows the missing debug information with??.Hello world! ====================== PANIC ====================== panicked at examples/panic.rs:24:5: This is a panic Backtrace: 0x4200252a main at ??:??
-
examples/panic.rs contains a solution. It can be run with: cargo run --example panic --release.
Exercise 2
-
Edit the
.cargo/config.toml:+[profile.release] +debug = true- Now it will emit debug information in the ELF binary file; yet debug info isn't flashed into the target, it is just used to display the backtrace.
- Re-run the program with
--releaseand confirm??:??is now filled in.
-
Try another option:
+[profile.dev] +opt-level = "s"which turns size-optimisation on, and has debug info by default. Run it with
cargo run(no--releaseflag since we want to run the dev profile.)
Recap
- Using
esp-backtrace. - Using
panic!to exit the program on error. - Profiles:
- Tweak debug information on backtrace.
- Optimise binary size.