|
| 1 | +## #[panic_handler] |
| 2 | + |
| 3 | +`#[panic_handler]` is used to define the behavior of `panic!` in `#![no_std]` applications. |
| 4 | +The `#[panic_handler]` attribute must be applied to a function with signature `fn(&PanicInfo) |
| 5 | +-> !` and such function must appear *once* in the dependency graph of a binary / dylib / cdylib |
| 6 | +crate. The API of `PanicInfo` can be found in the [API docs]. |
| 7 | + |
| 8 | +[API docs]: ../core/panic/struct.PanicInfo.html |
| 9 | + |
| 10 | +Given that `#![no_std]` applications have no *standard* output and that some `#![no_std]` |
| 11 | +applications, e.g. embedded applications, need different panicking behaviors for development and for |
| 12 | +release it can be helpful to have panic crates, crate that only contain a `#[panic_handler]`. |
| 13 | +This way applications can easily swap the panicking behavior by simply linking to a different panic |
| 14 | +crate. |
| 15 | + |
| 16 | +Below is shown an example where an application has a different panicking behavior depending on |
| 17 | +whether is compiled using the dev profile (`cargo build`) or using the release profile (`cargo build |
| 18 | +--release`). |
| 19 | + |
| 20 | +``` rust, ignore |
| 21 | +// crate: panic-semihosting -- log panic messages to the host stderr using semihosting |
| 22 | +
|
| 23 | +#![no_std] |
| 24 | +
|
| 25 | +use core::fmt::{Write, self}; |
| 26 | +use core::panic::PanicInfo; |
| 27 | +
|
| 28 | +struct HStderr { |
| 29 | + // .. |
| 30 | +# _0: (), |
| 31 | +} |
| 32 | +# |
| 33 | +# impl HStderr { |
| 34 | +# fn new() -> HStderr { HStderr { _0: () } } |
| 35 | +# } |
| 36 | +# |
| 37 | +# impl fmt::Write for HStderr { |
| 38 | +# fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) } |
| 39 | +# } |
| 40 | +
|
| 41 | +#[panic_handler] |
| 42 | +fn panic(info: &PanicInfo) -> ! { |
| 43 | + let mut host_stderr = HStderr::new(); |
| 44 | +
|
| 45 | + // logs "panicked at '$reason', src/main.rs:27:4" to the host stderr |
| 46 | + writeln!(host_stderr, "{}", info).ok(); |
| 47 | +
|
| 48 | + loop {} |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +``` rust, ignore |
| 53 | +// crate: panic-halt -- halt the thread on panic; messages are discarded |
| 54 | +
|
| 55 | +#![no_std] |
| 56 | +
|
| 57 | +use core::panic::PanicInfo; |
| 58 | +
|
| 59 | +#[panic_handler] |
| 60 | +fn panic(_info: &PanicInfo) -> ! { |
| 61 | + loop {} |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +``` rust, ignore |
| 66 | +// crate: app |
| 67 | +
|
| 68 | +#![no_std] |
| 69 | +
|
| 70 | +// dev profile |
| 71 | +#[cfg(debug_assertions)] |
| 72 | +extern crate panic_semihosting; |
| 73 | +
|
| 74 | +// release profile |
| 75 | +#[cfg(not(debug_assertions))] |
| 76 | +extern crate panic_halt; |
| 77 | +
|
| 78 | +// omitted: other `extern crate`s |
| 79 | +
|
| 80 | +fn main() { |
| 81 | + // .. |
| 82 | +} |
| 83 | +``` |
0 commit comments