summary refs log tree commit diff
path: root/src/libstd/sys/sgx/abi/panic.rs
blob: de86394b4b88cdfd8013b57b089988f60567df04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use super::usercalls::{alloc::UserRef, self};
use crate::cmp;
use crate::io::{self, Write};
use crate::mem;

extern "C" {
    fn take_debug_panic_buf_ptr() -> *mut u8;
    static DEBUG: u8;
}

pub(crate) struct SgxPanicOutput(Option<&'static mut UserRef<[u8]>>);

fn empty_user_slice() -> &'static mut UserRef<[u8]> {
    unsafe { UserRef::from_raw_parts_mut(1 as *mut u8, 0) }
}

impl SgxPanicOutput {
    pub(crate) fn new() -> Option<Self> {
        if unsafe { DEBUG == 0 } {
            None
        } else {
            Some(SgxPanicOutput(None))
        }
    }

    fn init(&mut self) -> &mut &'static mut UserRef<[u8]> {
        self.0.get_or_insert_with(|| unsafe {
            let ptr = take_debug_panic_buf_ptr();
            if ptr.is_null() {
                empty_user_slice()
            } else {
                UserRef::from_raw_parts_mut(ptr, 1024)
            }
        })
    }
}

impl Write for SgxPanicOutput {
    fn write(&mut self, src: &[u8]) -> io::Result<usize> {
        let dst = mem::replace(self.init(), empty_user_slice());
        let written = cmp::min(src.len(), dst.len());
        dst[..written].copy_from_enclave(&src[..written]);
        self.0 = Some(&mut dst[written..]);
        Ok(written)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn panic_msg(msg: &str) -> ! {
    let _ = SgxPanicOutput::new().map(|mut out| out.write(msg.as_bytes()));
    usercalls::exit(true)
}