|
1 | 1 | # Beneath `std`
|
2 | 2 |
|
3 |
| -This section documents (or will document) features that are provided by the standard library and |
4 |
| -that `#![no_std]` developers have to deal with (i.e. provide) to build `#![no_std]` binary crates. A |
5 |
| -(likely incomplete) list of such features is shown below: |
6 |
| - |
7 |
| -- #[lang = "eh_personality"] |
8 |
| -- #[lang = "start"] |
9 |
| -- #[lang = "termination"] |
10 |
| -- #[panic_implementation] |
| 3 | +This section documents features that are provided by the standard library and that `#![no_std]` |
| 4 | +developers have to deal with (i.e. provide) to build `#![no_std]` binary crates. A list of such |
| 5 | +features is shown below: |
| 6 | + |
| 7 | +- `#[panic_implementation]` |
| 8 | + |
| 9 | +## `#[panic_implementation]` |
| 10 | + |
| 11 | +The `panic_implementation` attribute can only be applied to a function with signature |
| 12 | +`fn(&PanicInfo) -> !`. The function marked with this attribute defines the behavior of `panic!` in |
| 13 | +`#![no_std]` applications. The [`PanicInfo`] struct contains information about the location of the |
| 14 | +panic. There must be a single `panic_implementation` function in the dependency graph of a |
| 15 | +binary, dylib or cdylib crate. |
| 16 | + |
| 17 | +[`PanicInfo`]: https://doc.rust-lang.org/nightly/core/panic/struct.PanicInfo.html |
| 18 | + |
| 19 | +Below is shown a `panic_implementation` function that logs the panic message and then aborts the |
| 20 | +program. |
| 21 | + |
| 22 | +``` rust |
| 23 | +#![feature(core_intrinsics)] |
| 24 | +#![feature(panic_implementation)] |
| 25 | +#![no_std] |
| 26 | + |
| 27 | +use core::intrinsics; |
| 28 | +use core::panic::PanicInfo; |
| 29 | + |
| 30 | +#[panic_implementation] |
| 31 | +fn panic(info: &PanicInfo) -> ! { |
| 32 | + let mut sink = /* .. */; |
| 33 | + |
| 34 | + // logs "panicked at '$reason', src/main.rs:27:4" to some `sink` |
| 35 | + let _ = writeln!(sink, "{}", info); |
| 36 | + |
| 37 | + unsafe { intrinsics::abort() } |
| 38 | +} |
| 39 | +``` |
0 commit comments