twz_rt/
preinit.rs

1//! Utilities that enable formatted printing for early runtime init.
2
3use std::fmt;
4
5use twizzler_abi::syscall::{
6    sys_kernel_console_write, KernelConsoleSource, KernelConsoleWriteFlags,
7};
8
9#[repr(C)]
10struct PreinitLogger;
11
12impl fmt::Write for PreinitLogger {
13    fn write_str(&mut self, s: &str) -> fmt::Result {
14        sys_kernel_console_write(
15            KernelConsoleSource::Console,
16            s.as_bytes(),
17            KernelConsoleWriteFlags::empty(),
18        );
19        Ok(())
20    }
21}
22
23#[doc(hidden)]
24pub fn _print_normal(args: core::fmt::Arguments) {
25    use fmt::Write;
26    let _ = PreinitLogger.write_fmt(args);
27}
28
29#[macro_export]
30macro_rules! preinit_print {
31    ($($arg:tt)*) => {
32        $crate::preinit::_print_normal(format_args!($($arg)*))
33    };
34}
35
36#[macro_export]
37macro_rules! preinit_println {
38    () => {
39        $crate::preinit_print!("\n")
40    };
41    ($fmt:expr) => {
42        $crate::preinit_print!(concat!($fmt, "\n"))
43    };
44    ($fmt:expr, $($arg:tt)*) => {
45        $crate::preinit_print!(concat!($fmt, "\n"), $($arg)*)
46    };
47}
48
49#[track_caller]
50pub fn preinit_abort() -> ! {
51    #[allow(unused_unsafe)]
52    unsafe {
53        core::intrinsics::abort()
54    }
55}
56
57#[track_caller]
58pub fn preinit_unwrap<T>(op: Option<T>) -> T {
59    match op {
60        Some(item) => item,
61        None => {
62            preinit_println!(
63                "failed to unwrap option: {}",
64                core::panic::Location::caller()
65            );
66            preinit_abort();
67        }
68    }
69}
70
71#[track_caller]
72#[allow(dead_code)]
73pub fn preinit_unwrap_result<T, E: core::fmt::Display>(op: Result<T, E>) -> T {
74    match op {
75        Ok(item) => item,
76        Err(e) => {
77            preinit_println!(
78                "failed to unwrap result: {} at {}",
79                e,
80                core::panic::Location::caller()
81            );
82            preinit_abort();
83        }
84    }
85}