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