]> git.proxmox.com Git - rustc.git/blame - src/doc/reference/src/runtime.md
New upstream version 1.41.1+dfsg1
[rustc.git] / src / doc / reference / src / runtime.md
CommitLineData
532ac7d7
XL
1# The Rust runtime
2
3This section documents features that define some aspects of the Rust runtime.
4
5## The `panic_handler` attribute
6
7The *`panic_handler` attribute* can only be applied to a function with signature
8`fn(&PanicInfo) -> !`. The function marked with this [attribute] defines the behavior of panics. The
9[`PanicInfo`] struct contains information about the location of the panic. There must be a single
10`panic_handler` function in the dependency graph of a binary, dylib or cdylib crate.
11
12Below is shown a `panic_handler` function that logs the panic message and then halts the
13thread.
14
60c5eb7d
XL
15<!-- ignore: test infrastructure can't handle no_std -->
16```rust,ignore
532ac7d7
XL
17#![no_std]
18
19use core::fmt::{self, Write};
20use core::panic::PanicInfo;
21
22struct Sink {
23 // ..
24# _0: (),
25}
26#
27# impl Sink {
28# fn new() -> Sink { Sink { _0: () }}
29# }
30#
31# impl fmt::Write for Sink {
32# fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) }
33# }
34
35#[panic_handler]
36fn panic(info: &PanicInfo) -> ! {
37 let mut sink = Sink::new();
38
39 // logs "panicked at '$reason', src/main.rs:27:4" to some `sink`
40 let _ = writeln!(sink, "{}", info);
41
42 loop {}
43}
44```
45
46### Standard behavior
47
48The standard library provides an implementation of `panic_handler` that
49defaults to unwinding the stack but that can be [changed to abort the
50process][abort]. The standard library's panic behavior can be modified at
51runtime with the [set_hook] function.
52
53## The `global_allocator` attribute
54
55The *`global_allocator` attribute* is used on a [static item] implementing the
56[`GlobalAlloc`] trait to set the global allocator.
57
58## The `windows_subsystem` attribute
59
60The *`windows_subsystem` attribute* may be applied at the crate level to set
61the [subsystem] when linking on a Windows target. It uses the
62[_MetaNameValueStr_] syntax to specify the subsystem with a value of either
63`console` or `windows`. This attribute is ignored on non-Windows targets, and
64for non-`bin` [crate types].
65
60c5eb7d 66```rust
532ac7d7
XL
67#![windows_subsystem = "windows"]
68```
69
416331ca 70[_MetaNameValueStr_]: attributes.md#meta-item-attribute-syntax
532ac7d7
XL
71[`GlobalAlloc`]: ../alloc/alloc/trait.GlobalAlloc.html
72[`PanicInfo`]: ../core/panic/struct.PanicInfo.html
73[abort]: ../book/ch09-01-unrecoverable-errors-with-panic.html
416331ca
XL
74[attribute]: attributes.md
75[crate types]: linkage.md
532ac7d7 76[set_hook]: ../std/panic/fn.set_hook.html
416331ca 77[static item]: items/static-items.md
532ac7d7 78[subsystem]: https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx