std/
rt.rs

1//! Runtime services
2//!
3//! The `rt` module provides a narrow set of runtime services,
4//! including the global heap (exported in `heap`) and unwinding and
5//! backtrace support. The APIs in this module are highly unstable,
6//! and should be considered as private implementation details for the
7//! time being.
8
9#![unstable(
10    feature = "rt",
11    reason = "this public module should not exist and is highly likely \
12              to disappear",
13    issue = "none"
14)]
15#![doc(hidden)]
16#![deny(unsafe_op_in_unsafe_fn)]
17#![allow(unused_macros)]
18
19#[rustfmt::skip]
20pub use crate::panicking::{begin_panic, panic_count};
21pub use core::panicking::{panic_display, panic_fmt};
22
23#[rustfmt::skip]
24use crate::any::Any;
25use crate::sync::Once;
26use crate::thread::{self, main_thread};
27use crate::{mem, panic, sys};
28
29// Prints to the "panic output", depending on the platform this may be:
30// - the standard error output
31// - some dedicated platform specific output
32// - nothing (so this macro is a no-op)
33macro_rules! rtprintpanic {
34    ($($t:tt)*) => {
35        #[cfg(not(feature = "panic_immediate_abort"))]
36        if let Some(mut out) = crate::sys::stdio::panic_output() {
37            let _ = crate::io::Write::write_fmt(&mut out, format_args!($($t)*));
38        }
39        #[cfg(feature = "panic_immediate_abort")]
40        {
41            let _ = format_args!($($t)*);
42        }
43    }
44}
45
46macro_rules! rtabort {
47    ($($t:tt)*) => {
48        {
49            rtprintpanic!("fatal runtime error: {}\n", format_args!($($t)*));
50            crate::sys::abort_internal();
51        }
52    }
53}
54
55macro_rules! rtassert {
56    ($e:expr) => {
57        if !$e {
58            rtabort!(concat!("assertion failed: ", stringify!($e)));
59        }
60    };
61}
62
63macro_rules! rtunwrap {
64    ($ok:ident, $e:expr) => {
65        match $e {
66            $ok(v) => v,
67            ref err => {
68                let err = err.as_ref().map(drop); // map Ok/Some which might not be Debug
69                rtabort!(concat!("unwrap failed: ", stringify!($e), " = {:?}"), err)
70            }
71        }
72    };
73}
74
75fn handle_rt_panic<T>(e: Box<dyn Any + Send>) -> T {
76    mem::forget(e);
77    rtabort!("initialization or cleanup bug");
78}
79
80// One-time runtime initialization.
81// Runs before `main`.
82// SAFETY: must be called only once during runtime initialization.
83// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
84//
85// # The `sigpipe` parameter
86//
87// Since 2014, the Rust runtime on Unix has set the `SIGPIPE` handler to
88// `SIG_IGN`. Applications have good reasons to want a different behavior
89// though, so there is a `-Zon-broken-pipe` compiler flag that
90// can be used to select how `SIGPIPE` shall be setup (if changed at all) before
91// `fn main()` is called. See <https://github.com/rust-lang/rust/issues/97889>
92// for more info.
93//
94// The `sigpipe` parameter to this function gets its value via the code that
95// rustc generates to invoke `fn lang_start()`. The reason we have `sigpipe` for
96// all platforms and not only Unix, is because std is not allowed to have `cfg`
97// directives as this high level. See the module docs in
98// `src/tools/tidy/src/pal.rs` for more info. On all other platforms, `sigpipe`
99// has a value, but its value is ignored.
100//
101// Even though it is an `u8`, it only ever has 4 values. These are documented in
102// `compiler/rustc_session/src/config/sigpipe.rs`.
103#[cfg_attr(test, allow(dead_code))]
104unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
105    #[cfg_attr(target_os = "teeos", allow(unused_unsafe))]
106    unsafe {
107        sys::init(argc, argv, sigpipe)
108    };
109
110    // Remember the main thread ID to give it the correct name.
111    // SAFETY: this is the only time and place where we call this function.
112    unsafe { main_thread::set(thread::current_id()) };
113}
114
115/// Clean up the thread-local runtime state. This *should* be run after all other
116/// code managed by the Rust runtime, but will not cause UB if that condition is
117/// not fulfilled. Also note that this function is not guaranteed to be run, but
118/// skipping it will cause leaks and therefore is to be avoided.
119pub(crate) fn thread_cleanup() {
120    // This function is run in situations where unwinding leads to an abort
121    // (think `extern "C"` functions). Abort here instead so that we can
122    // print a nice message.
123    panic::catch_unwind(|| {
124        crate::thread::drop_current();
125    })
126    .unwrap_or_else(handle_rt_panic);
127}
128
129// One-time runtime cleanup.
130// Runs after `main` or at program exit.
131// NOTE: this is not guaranteed to run, for example when the program aborts.
132pub(crate) fn cleanup() {
133    static CLEANUP: Once = Once::new();
134    CLEANUP.call_once(|| unsafe {
135        // Flush stdout and disable buffering.
136        crate::io::cleanup();
137        // SAFETY: Only called once during runtime cleanup.
138        sys::cleanup();
139    });
140}
141
142// To reduce the generated code of the new `lang_start`, this function is doing
143// the real work.
144#[cfg(not(test))]
145fn lang_start_internal(
146    main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindSafe),
147    argc: isize,
148    argv: *const *const u8,
149    sigpipe: u8,
150) -> isize {
151    // Guard against the code called by this function from unwinding outside of the Rust-controlled
152    // code, which is UB. This is a requirement imposed by a combination of how the
153    // `#[lang="start"]` attribute is implemented as well as by the implementation of the panicking
154    // mechanism itself.
155    //
156    // There are a couple of instances where unwinding can begin. First is inside of the
157    // `rt::init`, `rt::cleanup` and similar functions controlled by bstd. In those instances a
158    // panic is a std implementation bug. A quite likely one too, as there isn't any way to
159    // prevent std from accidentally introducing a panic to these functions. Another is from
160    // user code from `main` or, more nefariously, as described in e.g. issue #86030.
161    //
162    // We use `catch_unwind` with `handle_rt_panic` instead of `abort_unwind` to make the error in
163    // case of a panic a bit nicer.
164    panic::catch_unwind(move || {
165        // SAFETY: Only called once during runtime initialization.
166        unsafe { init(argc, argv, sigpipe) };
167
168        let ret_code = panic::catch_unwind(main).unwrap_or_else(move |payload| {
169            // Carefully dispose of the panic payload.
170            let payload = panic::AssertUnwindSafe(payload);
171            panic::catch_unwind(move || drop({ payload }.0)).unwrap_or_else(move |e| {
172                mem::forget(e); // do *not* drop the 2nd payload
173                rtabort!("drop of the panic payload panicked");
174            });
175            // Return error code for panicking programs.
176            101
177        });
178        let ret_code = ret_code as isize;
179
180        cleanup();
181        // Guard against multiple threads calling `libc::exit` concurrently.
182        // See the documentation for `unique_thread_exit` for more information.
183        crate::sys::exit_guard::unique_thread_exit();
184
185        ret_code
186    })
187    .unwrap_or_else(handle_rt_panic)
188}
189
190#[cfg(not(any(test, doctest)))]
191#[lang = "start"]
192fn lang_start<T: crate::process::Termination + 'static>(
193    main: fn() -> T,
194    argc: isize,
195    argv: *const *const u8,
196    sigpipe: u8,
197) -> isize {
198    lang_start_internal(
199        &move || crate::sys::backtrace::__rust_begin_short_backtrace(main).report().to_i32(),
200        argc,
201        argv,
202        sigpipe,
203    )
204}