|
| 1 | +## #[panic_implementation] |
| 2 | + |
| 3 | +`#[panic_implementation]` is used to define the behavior of `panic!` in `#![no_std]` applications. |
| 4 | +The `#[panic_implementation]` 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]: https://doc.rust-lang.org/nightly/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_implementation]`. |
| 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 |
| 21 | +// crate: panic-semihosting -- log panic message to the host stderr using semihosting |
| 22 | + |
| 23 | +#![feature(core_intrinsics)] |
| 24 | +#![feature(panic_implementation)] |
| 25 | +#![no_std] |
| 26 | + |
| 27 | +#[panic_implementation] |
| 28 | +fn panic(info: &PanicInfo) -> ! { |
| 29 | + let host_stderr = /* .. */; |
| 30 | + |
| 31 | + writeln!(host_stderr, "{}", info).ok(); |
| 32 | + |
| 33 | + core::intrinsics::breakpoint(); |
| 34 | + |
| 35 | + loop {} |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +``` rust |
| 40 | +// crate: panic-abort -- abort on panic! |
| 41 | + |
| 42 | +#![feature(core_intrinsics)] |
| 43 | +#![feature(panic_implementation)] |
| 44 | +#![no_std] |
| 45 | + |
| 46 | +#[panic_implementation] |
| 47 | +fn panic(info: &PanicInfo) -> ! { |
| 48 | + unsafe { core::intrinsics::abort() } |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +``` rust |
| 53 | +// crate: app |
| 54 | + |
| 55 | +#![no_std] |
| 56 | + |
| 57 | +// dev profile |
| 58 | +#[cfg(debug_assertions)] |
| 59 | +extern crate panic_semihosting; |
| 60 | + |
| 61 | +// release profile |
| 62 | +#[cfg(not(debug_assertions))] |
| 63 | +extern crate panic_abort; |
| 64 | + |
| 65 | +// omitted: other `extern crate`s |
| 66 | + |
| 67 | +fn main() { |
| 68 | + // .. |
| 69 | +} |
| 70 | +``` |
0 commit comments