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
use axerrno::LinuxError;
use core::ffi::{c_char, c_int};

/// The global errno variable.
#[cfg_attr(feature = "tls", thread_local)]
#[no_mangle]
#[allow(non_upper_case_globals)]
pub static mut errno: c_int = 0;

pub fn set_errno(code: i32) {
    unsafe {
        errno = code;
    }
}

/// Returns a pointer to the global errno variable.
#[no_mangle]
pub unsafe extern "C" fn __errno_location() -> *mut c_int {
    core::ptr::addr_of_mut!(errno)
}

/// Returns a pointer to the string representation of the given error code.
#[no_mangle]
pub unsafe extern "C" fn strerror(e: c_int) -> *mut c_char {
    #[allow(non_upper_case_globals)]
    static mut strerror_buf: [u8; 256] = [0; 256]; // TODO: thread safe

    let err_str = if e == 0 {
        "Success"
    } else {
        LinuxError::try_from(e)
            .map(|e| e.as_str())
            .unwrap_or("Unknown error")
    };
    unsafe {
        strerror_buf[..err_str.len()].copy_from_slice(err_str.as_bytes());
        strerror_buf.as_mut_ptr() as *mut c_char
    }
}