]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/rt.rs
Move most init to `sys::init`
[rust.git] / library / std / src / sys_common / rt.rs
1 use crate::sync::Once;
2 use crate::sys;
3 use crate::sys_common::thread_info;
4 use crate::thread::Thread;
5
6 // One-time runtime initialization.
7 // Runs before `main`.
8 #[cfg_attr(test, allow(dead_code))]
9 pub fn init(argc: isize, argv: *const *const u8) {
10     static INIT: Once = Once::new();
11     INIT.call_once(|| unsafe {
12         // SAFETY: Only called once during runtime initialization.
13         sys::init(argc, argv);
14
15         let main_guard = sys::thread::guard::init();
16         // Next, set up the current Thread with the guard information we just
17         // created. Note that this isn't necessary in general for new threads,
18         // but we just do this to name the main thread and to give it correct
19         // info about the stack bounds.
20         let thread = Thread::new(Some("main".to_owned()));
21         thread_info::set(main_guard, thread);
22     });
23 }
24
25 // One-time runtime cleanup.
26 // Runs after `main` or at program exit. Note however that this is not guaranteed to run,
27 // for example when the program aborts.
28 #[cfg_attr(test, allow(dead_code))]
29 pub fn cleanup() {
30     static CLEANUP: Once = Once::new();
31     CLEANUP.call_once(|| unsafe {
32         // SAFETY: Only called once during runtime cleanup.
33         sys::cleanup();
34         // Flush stdout and disable buffering.
35         crate::io::cleanup();
36     });
37 }
38
39 macro_rules! rtabort {
40     ($($t:tt)*) => (crate::sys_common::util::abort(format_args!($($t)*)))
41 }
42
43 macro_rules! rtassert {
44     ($e:expr) => {
45         if !$e {
46             rtabort!(concat!("assertion failed: ", stringify!($e)));
47         }
48     };
49 }
50
51 #[allow(unused_macros)] // not used on all platforms
52 macro_rules! rtunwrap {
53     ($ok:ident, $e:expr) => {
54         match $e {
55             $ok(v) => v,
56             ref err => {
57                 let err = err.as_ref().map(drop); // map Ok/Some which might not be Debug
58                 rtabort!(concat!("unwrap failed: ", stringify!($e), " = {:?}"), err)
59             }
60         }
61     };
62 }