axlibc/
errno.rs

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