panic_no_std/
lib.rs

1#![deny(warnings)]
2
3#![no_std]
4
5use core::fmt::{self};
6use core::fmt::Write as fmt_Write;
7use core::panic::PanicInfo;
8use exit_no_std::exit;
9
10#[cfg(all(not(target_os="dos"), windows))]
11fn write_ascii_char(c: u8) {
12    use core::ptr::null_mut;
13    use winapi::shared::minwindef::DWORD;
14    use winapi::um::fileapi::WriteFile;
15    use winapi::um::handleapi::INVALID_HANDLE_VALUE;
16    use winapi::um::processenv::GetStdHandle;
17    use winapi::um::winbase::STD_ERROR_HANDLE;
18
19    let stderr = unsafe { GetStdHandle(STD_ERROR_HANDLE) };
20    if !stderr.is_null() && stderr != INVALID_HANDLE_VALUE {
21        let mut written: DWORD = 0;
22        unsafe { WriteFile(stderr, &c as *const _ as _, 1, &mut written as *mut _, null_mut()); }
23    }
24}
25
26#[cfg(all(not(target_os="dos"), not(windows)))]
27fn write_ascii_char(c: u8) {
28    unsafe { libc::write(2, &c as *const _ as _, 1); }
29}
30
31#[cfg(target_os="dos")]
32fn write_ascii_char(c: u8) {
33    use pc_ints::int_21h_ah_02h_out_ch;
34
35    if c == b'\n' {
36        int_21h_ah_02h_out_ch(b'\r');
37    }
38    int_21h_ah_02h_out_ch(c);
39}
40
41struct LastChanceWriter;
42
43impl fmt::Write for LastChanceWriter {
44    fn write_char(&mut self, c: char) -> fmt::Result {
45        let c = c as u32;
46        let c = if c > 0x7F || c == '\r' as u32 {
47            b'?'
48        } else {
49            c as u8
50        };
51        write_ascii_char(c);
52        Ok(())
53    }
54
55    fn write_str(&mut self, s: &str) -> fmt::Result {
56        for c in s.chars() {
57            self.write_char(c)?;
58        }
59        Ok(())
60    }
61}
62
63/// Prints panic message and terminates the current process with the specified exit code.
64pub fn panic(info: &PanicInfo, exit_code: u8) -> ! {
65    let _ = write!(LastChanceWriter, "Panic: {}", info.message());
66    if let Some(location) = info.location() {
67        let _ = write!(LastChanceWriter, " ({location})");
68    }
69    let _ = writeln!(LastChanceWriter, ".");
70    exit(exit_code)
71}