Coverage Report

Created: 2025-02-22 06:51

/rust/registry/src/index.crates.io-6f17d22bba15001f/getrandom-0.2.15/src/util_libc.rs
Line
Count
Source (jump to first uncovered line)
1
#![allow(dead_code)]
2
use crate::Error;
3
use core::{
4
    mem::MaybeUninit,
5
    num::NonZeroU32,
6
    ptr::NonNull,
7
    sync::atomic::{fence, AtomicPtr, Ordering},
8
};
9
use libc::c_void;
10
11
cfg_if! {
12
    if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] {
13
        use libc::__errno as errno_location;
14
    } else if #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "hurd", target_os = "redox", target_os = "dragonfly"))] {
15
        use libc::__errno_location as errno_location;
16
    } else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
17
        use libc::___errno as errno_location;
18
    } else if #[cfg(any(target_os = "macos", target_os = "freebsd"))] {
19
        use libc::__error as errno_location;
20
    } else if #[cfg(target_os = "haiku")] {
21
        use libc::_errnop as errno_location;
22
    } else if #[cfg(target_os = "nto")] {
23
        use libc::__get_errno_ptr as errno_location;
24
    } else if #[cfg(any(all(target_os = "horizon", target_arch = "arm"), target_os = "vita"))] {
25
        extern "C" {
26
            // Not provided by libc: https://github.com/rust-lang/libc/issues/1995
27
            fn __errno() -> *mut libc::c_int;
28
        }
29
        use __errno as errno_location;
30
    } else if #[cfg(target_os = "aix")] {
31
        use libc::_Errno as errno_location;
32
    }
33
}
34
35
cfg_if! {
36
    if #[cfg(target_os = "vxworks")] {
37
        use libc::errnoGet as get_errno;
38
    } else {
39
0
        unsafe fn get_errno() -> libc::c_int { *errno_location() }
40
    }
41
}
42
43
0
pub fn last_os_error() -> Error {
44
0
    let errno = unsafe { get_errno() };
45
0
    if errno > 0 {
46
0
        Error::from(NonZeroU32::new(errno as u32).unwrap())
47
    } else {
48
0
        Error::ERRNO_NOT_POSITIVE
49
    }
50
0
}
51
52
// Fill a buffer by repeatedly invoking a system call. The `sys_fill` function:
53
//   - should return -1 and set errno on failure
54
//   - should return the number of bytes written on success
55
0
pub fn sys_fill_exact(
56
0
    mut buf: &mut [MaybeUninit<u8>],
57
0
    sys_fill: impl Fn(&mut [MaybeUninit<u8>]) -> libc::ssize_t,
58
0
) -> Result<(), Error> {
59
0
    while !buf.is_empty() {
60
0
        let res = sys_fill(buf);
61
0
        match res {
62
0
            res if res > 0 => buf = buf.get_mut(res as usize..).ok_or(Error::UNEXPECTED)?,
63
            -1 => {
64
0
                let err = last_os_error();
65
0
                // We should try again if the call was interrupted.
66
0
                if err.raw_os_error() != Some(libc::EINTR) {
67
0
                    return Err(err);
68
0
                }
69
            }
70
            // Negative return codes not equal to -1 should be impossible.
71
            // EOF (ret = 0) should be impossible, as the data we are reading
72
            // should be an infinite stream of random bytes.
73
0
            _ => return Err(Error::UNEXPECTED),
74
        }
75
    }
76
0
    Ok(())
77
0
}
Unexecuted instantiation: getrandom::util_libc::sys_fill_exact::<getrandom::use_file::getrandom_inner::{closure#0}>
Unexecuted instantiation: getrandom::util_libc::sys_fill_exact::<getrandom::util_libc::getrandom_syscall>
78
79
// A "weak" binding to a C function that may or may not be present at runtime.
80
// Used for supporting newer OS features while still building on older systems.
81
// Based off of the DlsymWeak struct in libstd:
82
// https://github.com/rust-lang/rust/blob/1.61.0/library/std/src/sys/unix/weak.rs#L84
83
// except that the caller must manually cast self.ptr() to a function pointer.
84
pub struct Weak {
85
    name: &'static str,
86
    addr: AtomicPtr<c_void>,
87
}
88
89
impl Weak {
90
    // A non-null pointer value which indicates we are uninitialized. This
91
    // constant should ideally not be a valid address of a function pointer.
92
    // However, if by chance libc::dlsym does return UNINIT, there will not
93
    // be undefined behavior. libc::dlsym will just be called each time ptr()
94
    // is called. This would be inefficient, but correct.
95
    // TODO: Replace with core::ptr::invalid_mut(1) when that is stable.
96
    const UNINIT: *mut c_void = 1 as *mut c_void;
97
98
    // Construct a binding to a C function with a given name. This function is
99
    // unsafe because `name` _must_ be null terminated.
100
0
    pub const unsafe fn new(name: &'static str) -> Self {
101
0
        Self {
102
0
            name,
103
0
            addr: AtomicPtr::new(Self::UNINIT),
104
0
        }
105
0
    }
106
107
    // Return the address of a function if present at runtime. Otherwise,
108
    // return None. Multiple callers can call ptr() concurrently. It will
109
    // always return _some_ value returned by libc::dlsym. However, the
110
    // dlsym function may be called multiple times.
111
0
    pub fn ptr(&self) -> Option<NonNull<c_void>> {
112
0
        // Despite having only a single atomic variable (self.addr), we still
113
0
        // cannot always use Ordering::Relaxed, as we need to make sure a
114
0
        // successful call to dlsym() is "ordered before" any data read through
115
0
        // the returned pointer (which occurs when the function is called).
116
0
        // Our implementation mirrors that of the one in libstd, meaning that
117
0
        // the use of non-Relaxed operations is probably unnecessary.
118
0
        match self.addr.load(Ordering::Relaxed) {
119
0
            Self::UNINIT => {
120
0
                let symbol = self.name.as_ptr() as *const _;
121
0
                let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) };
122
0
                // Synchronizes with the Acquire fence below
123
0
                self.addr.store(addr, Ordering::Release);
124
0
                NonNull::new(addr)
125
            }
126
0
            addr => {
127
0
                let func = NonNull::new(addr)?;
128
0
                fence(Ordering::Acquire);
129
0
                Some(func)
130
            }
131
        }
132
0
    }
133
}
134
135
// SAFETY: path must be null terminated, FD must be manually closed.
136
0
pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> {
137
0
    debug_assert_eq!(path.as_bytes().last(), Some(&0));
138
    loop {
139
0
        let fd = libc::open(path.as_ptr() as *const _, libc::O_RDONLY | libc::O_CLOEXEC);
140
0
        if fd >= 0 {
141
0
            return Ok(fd);
142
0
        }
143
0
        let err = last_os_error();
144
0
        // We should try again if open() was interrupted.
145
0
        if err.raw_os_error() != Some(libc::EINTR) {
146
0
            return Err(err);
147
0
        }
148
    }
149
0
}
150
151
/// Thin wrapper around the `getrandom()` Linux system call
152
#[cfg(any(target_os = "android", target_os = "linux"))]
153
0
pub fn getrandom_syscall(buf: &mut [MaybeUninit<u8>]) -> libc::ssize_t {
154
0
    unsafe {
155
0
        libc::syscall(
156
0
            libc::SYS_getrandom,
157
0
            buf.as_mut_ptr() as *mut libc::c_void,
158
0
            buf.len(),
159
0
            0,
160
0
        ) as libc::ssize_t
161
0
    }
162
0
}