]> git.proxmox.com Git - rustc.git/blob - library/std/src/rt.rs
Merge tag 'debian/1.65.0+dfsg1-1_exp3' into debian/sid
[rustc.git] / library / std / src / 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 use crate::ffi::CString;
20
21 // Re-export some of our utilities which are expected by other crates.
22 pub use crate::panicking::{begin_panic, panic_count};
23 pub use core::panicking::{panic_display, panic_fmt};
24
25 use crate::sync::Once;
26 use crate::sys;
27 use crate::sys_common::thread_info;
28 use crate::thread::Thread;
29
30 // Prints to the "panic output", depending on the platform this may be:
31 // - the standard error output
32 // - some dedicated platform specific output
33 // - nothing (so this macro is a no-op)
34 macro_rules! rtprintpanic {
35 ($($t:tt)*) => {
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 }
40 }
41
42 macro_rules! rtabort {
43 ($($t:tt)*) => {
44 {
45 rtprintpanic!("fatal runtime error: {}\n", format_args!($($t)*));
46 crate::sys::abort_internal();
47 }
48 }
49 }
50
51 macro_rules! rtassert {
52 ($e:expr) => {
53 if !$e {
54 rtabort!(concat!("assertion failed: ", stringify!($e)));
55 }
56 };
57 }
58
59 macro_rules! rtunwrap {
60 ($ok:ident, $e:expr) => {
61 match $e {
62 $ok(v) => v,
63 ref err => {
64 let err = err.as_ref().map(drop); // map Ok/Some which might not be Debug
65 rtabort!(concat!("unwrap failed: ", stringify!($e), " = {:?}"), err)
66 }
67 }
68 };
69 }
70
71 // One-time runtime initialization.
72 // Runs before `main`.
73 // SAFETY: must be called only once during runtime initialization.
74 // NOTE: this is not guaranteed to run, for example when Rust code is called externally.
75 //
76 // # The `sigpipe` parameter
77 //
78 // Since 2014, the Rust runtime on Unix has set the `SIGPIPE` handler to
79 // `SIG_IGN`. Applications have good reasons to want a different behavior
80 // though, so there is a `#[unix_sigpipe = "..."]` attribute on `fn main()` that
81 // can be used to select how `SIGPIPE` shall be setup (if changed at all) before
82 // `fn main()` is called. See <https://github.com/rust-lang/rust/issues/97889>
83 // for more info.
84 //
85 // The `sigpipe` parameter to this function gets its value via the code that
86 // rustc generates to invoke `fn lang_start()`. The reason we have `sigpipe` for
87 // all platforms and not only Unix, is because std is not allowed to have `cfg`
88 // directives as this high level. See the module docs in
89 // `src/tools/tidy/src/pal.rs` for more info. On all other platforms, `sigpipe`
90 // has a value, but its value is ignored.
91 //
92 // Even though it is an `u8`, it only ever has 3 values. These are documented in
93 // `compiler/rustc_session/src/config/sigpipe.rs`.
94 #[cfg_attr(test, allow(dead_code))]
95 unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
96 unsafe {
97 sys::init(argc, argv, sigpipe);
98
99 let main_guard = sys::thread::guard::init();
100 // Next, set up the current Thread with the guard information we just
101 // created. Note that this isn't necessary in general for new threads,
102 // but we just do this to name the main thread and to give it correct
103 // info about the stack bounds.
104 let thread = Thread::new(Some(rtunwrap!(Ok, CString::new("main"))));
105 thread_info::set(main_guard, thread);
106 }
107 }
108
109 // One-time runtime cleanup.
110 // Runs after `main` or at program exit.
111 // NOTE: this is not guaranteed to run, for example when the program aborts.
112 pub(crate) fn cleanup() {
113 static CLEANUP: Once = Once::new();
114 CLEANUP.call_once(|| unsafe {
115 // Flush stdout and disable buffering.
116 crate::io::cleanup();
117 // SAFETY: Only called once during runtime cleanup.
118 sys::cleanup();
119 });
120 }
121
122 // To reduce the generated code of the new `lang_start`, this function is doing
123 // the real work.
124 #[cfg(not(test))]
125 fn lang_start_internal(
126 main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindSafe),
127 argc: isize,
128 argv: *const *const u8,
129 sigpipe: u8,
130 ) -> Result<isize, !> {
131 use crate::{mem, panic};
132 let rt_abort = move |e| {
133 mem::forget(e);
134 rtabort!("initialization or cleanup bug");
135 };
136 // Guard against the code called by this function from unwinding outside of the Rust-controlled
137 // code, which is UB. This is a requirement imposed by a combination of how the
138 // `#[lang="start"]` attribute is implemented as well as by the implementation of the panicking
139 // mechanism itself.
140 //
141 // There are a couple of instances where unwinding can begin. First is inside of the
142 // `rt::init`, `rt::cleanup` and similar functions controlled by libstd. In those instances a
143 // panic is a libstd implementation bug. A quite likely one too, as there isn't any way to
144 // prevent libstd from accidentally introducing a panic to these functions. Another is from
145 // user code from `main` or, more nefariously, as described in e.g. issue #86030.
146 // SAFETY: Only called once during runtime initialization.
147 panic::catch_unwind(move || unsafe { init(argc, argv, sigpipe) }).map_err(rt_abort)?;
148 let ret_code = panic::catch_unwind(move || panic::catch_unwind(main).unwrap_or(101) as isize)
149 .map_err(move |e| {
150 mem::forget(e);
151 rtabort!("drop of the panic payload panicked");
152 });
153 panic::catch_unwind(cleanup).map_err(rt_abort)?;
154 ret_code
155 }
156
157 #[cfg(not(test))]
158 #[lang = "start"]
159 fn lang_start<T: crate::process::Termination + 'static>(
160 main: fn() -> T,
161 argc: isize,
162 argv: *const *const u8,
163 #[cfg(not(bootstrap))] sigpipe: u8,
164 ) -> isize {
165 let Ok(v) = lang_start_internal(
166 &move || crate::sys_common::backtrace::__rust_begin_short_backtrace(main).report().to_i32(),
167 argc,
168 argv,
169 #[cfg(bootstrap)]
170 2, // Temporary inlining of sigpipe::DEFAULT until bootstrap stops being special
171 #[cfg(not(bootstrap))]
172 sigpipe,
173 );
174 v
175 }