Coverage Report

Created: 2024-04-26 06:25

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