Skip to main content

ax_libc/
errno.rs

1use core::ffi::{c_char, c_int};
2
3use syscalls::Errno;
4
5/// The global errno variable.
6#[cfg_attr(feature = "tls", thread_local)]
7#[unsafe(no_mangle)]
8#[allow(non_upper_case_globals)]
9pub static mut errno: c_int = 0;
10
11pub fn set_errno(code: i32) {
12    unsafe {
13        errno = code;
14    }
15}
16
17/// Returns a pointer to the global errno variable.
18#[unsafe(no_mangle)]
19pub unsafe extern "C" fn __errno_location() -> *mut c_int {
20    core::ptr::addr_of_mut!(errno)
21}
22
23/// Returns a pointer to the string representation of the given error code.
24#[unsafe(no_mangle)]
25pub unsafe extern "C" fn strerror(e: c_int) -> *mut c_char {
26    #[allow(non_upper_case_globals)]
27    static mut strerror_buf: [u8; 256] = [0; 256]; // TODO: thread safe
28
29    let err_str = if e == 0 {
30        "Success"
31    } else {
32        Errno::new(e).description().unwrap_or("Unknown error")
33    };
34    unsafe {
35        strerror_buf[..err_str.len()].copy_from_slice(err_str.as_bytes());
36        &raw mut strerror_buf as *mut c_char
37    }
38}