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 use crate::error::ERRNO_NOT_POSITIVE;
9 use crate::util::LazyUsize;
10 use crate::Error;
11 use core::num::NonZeroU32;
12 use core::ptr::NonNull;
13 
14 cfg_if! {
15     if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] {
16         use libc::__errno as errno_location;
17     } else if #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "redox", target_os = "dragonfly"))] {
18         use libc::__errno_location as errno_location;
19     } else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
20         use libc::___errno as errno_location;
21     } else if #[cfg(any(target_os = "macos", target_os = "freebsd"))] {
22         use libc::__error as errno_location;
23     } else if #[cfg(target_os = "haiku")] {
24         use libc::_errnop as errno_location;
25     }
26 }
27 
last_os_error() -> Error28 pub fn last_os_error() -> Error {
29     let errno = unsafe { *errno_location() };
30     if errno > 0 {
31         Error::from(NonZeroU32::new(errno as u32).unwrap())
32     } else {
33         ERRNO_NOT_POSITIVE
34     }
35 }
36 
37 // Fill a buffer by repeatedly invoking a system call. The `sys_fill` function:
38 //   - should return -1 and set errno on failure
39 //   - should return the number of bytes written on success
sys_fill_exact( mut buf: &mut [u8], sys_fill: impl Fn(&mut [u8]) -> libc::ssize_t, ) -> Result<(), Error>40 pub fn sys_fill_exact(
41     mut buf: &mut [u8],
42     sys_fill: impl Fn(&mut [u8]) -> libc::ssize_t,
43 ) -> Result<(), Error> {
44     while !buf.is_empty() {
45         let res = sys_fill(buf);
46         if res < 0 {
47             let err = last_os_error();
48             // We should try again if the call was interrupted.
49             if err.raw_os_error() != Some(libc::EINTR) {
50                 return Err(err);
51             }
52         } else {
53             // We don't check for EOF (ret = 0) as the data we are reading
54             // should be an infinite stream of random bytes.
55             buf = &mut buf[(res as usize)..];
56         }
57     }
58     Ok(())
59 }
60 
61 // A "weak" binding to a C function that may or may not be present at runtime.
62 // Used for supporting newer OS features while still building on older systems.
63 // F must be a function pointer of type `unsafe extern "C" fn`. Based off of the
64 // weak! macro in libstd.
65 pub struct Weak {
66     name: &'static str,
67     addr: LazyUsize,
68 }
69 
70 impl Weak {
71     // Construct a binding to a C function with a given name. This function is
72     // unsafe because `name` _must_ be null terminated.
new(name: &'static str) -> Self73     pub const unsafe fn new(name: &'static str) -> Self {
74         Self {
75             name,
76             addr: LazyUsize::new(),
77         }
78     }
79 
80     // Return a function pointer if present at runtime. Otherwise, return null.
ptr(&self) -> Option<NonNull<libc::c_void>>81     pub fn ptr(&self) -> Option<NonNull<libc::c_void>> {
82         let addr = self.addr.unsync_init(|| unsafe {
83             libc::dlsym(libc::RTLD_DEFAULT, self.name.as_ptr() as *const _) as usize
84         });
85         NonNull::new(addr as *mut _)
86     }
87 }
88 
89 pub struct LazyFd(LazyUsize);
90 
91 impl LazyFd {
new() -> Self92     pub const fn new() -> Self {
93         Self(LazyUsize::new())
94     }
95 
96     // If init() returns Some(x), x should be nonnegative.
init(&self, init: impl FnOnce() -> Option<libc::c_int>) -> Option<libc::c_int>97     pub fn init(&self, init: impl FnOnce() -> Option<libc::c_int>) -> Option<libc::c_int> {
98         let fd = self.0.sync_init(
99             || match init() {
100                 // OK as val >= 0 and val <= c_int::MAX < usize::MAX
101                 Some(val) => val as usize,
102                 None => LazyUsize::UNINIT,
103             },
104             || unsafe {
105                 // We are usually waiting on an open(2) syscall to complete,
106                 // which typically takes < 10us if the file is a device.
107                 // However, we might end up waiting much longer if the entropy
108                 // pool isn't initialized, but even in that case, this loop will
109                 // consume a negligible amount of CPU on most platforms.
110                 libc::usleep(10);
111             },
112         );
113         match fd {
114             LazyUsize::UNINIT => None,
115             val => Some(val as libc::c_int),
116         }
117     }
118 }
119 
120 cfg_if! {
121     if #[cfg(any(target_os = "linux", target_os = "emscripten"))] {
122         use libc::open64 as open;
123     } else {
124         use libc::open;
125     }
126 }
127 
128 // SAFETY: path must be null terminated, FD must be manually closed.
open_readonly(path: &str) -> Option<libc::c_int>129 pub unsafe fn open_readonly(path: &str) -> Option<libc::c_int> {
130     debug_assert!(path.as_bytes().last() == Some(&0));
131     let fd = open(path.as_ptr() as *mut _, libc::O_RDONLY | libc::O_CLOEXEC);
132     if fd < 0 {
133         return None;
134     }
135     // O_CLOEXEC works on all Unix targets except for older Linux kernels (pre
136     // 2.6.23), so we also use an ioctl to make sure FD_CLOEXEC is set.
137     #[cfg(target_os = "linux")]
138     libc::ioctl(fd, libc::FIOCLEX);
139     Some(fd)
140 }
141