| 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 = "hurd" , 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 | unsafe fn get_errno() -> libc::c_int { *errno_location() } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | pub fn last_os_error() -> Error { |
| 56 | let errno = unsafe { get_errno() }; |
| 57 | if errno > 0 { |
| 58 | Error::from(NonZeroU32::new(errno as u32).unwrap()) |
| 59 | } else { |
| 60 | Error::ERRNO_NOT_POSITIVE |
| 61 | } |
| 62 | } |
| 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 | pub fn sys_fill_exact( |
| 68 | mut buf: &mut [MaybeUninit<u8>], |
| 69 | sys_fill: impl Fn(&mut [MaybeUninit<u8>]) -> libc::ssize_t, |
| 70 | ) -> Result<(), Error> { |
| 71 | while !buf.is_empty() { |
| 72 | let res = sys_fill(buf); |
| 73 | if res < 0 { |
| 74 | let err = last_os_error(); |
| 75 | // We should try again if the call was interrupted. |
| 76 | if err.raw_os_error() != Some(libc::EINTR) { |
| 77 | return Err(err); |
| 78 | } |
| 79 | } else { |
| 80 | // We don't check for EOF (ret = 0) as the data we are reading |
| 81 | // should be an infinite stream of random bytes. |
| 82 | let len = min(res as usize, buf.len()); |
| 83 | buf = &mut buf[len..]; |
| 84 | } |
| 85 | } |
| 86 | Ok(()) |
| 87 | } |
| 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 | pub const unsafe fn new(name: &'static str) -> Self { |
| 111 | Self { |
| 112 | name, |
| 113 | addr: AtomicPtr::new(Self::UNINIT), |
| 114 | } |
| 115 | } |
| 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 | pub fn ptr(&self) -> Option<NonNull<c_void>> { |
| 122 | // Despite having only a single atomic variable (self.addr), we still |
| 123 | // cannot always use Ordering::Relaxed, as we need to make sure a |
| 124 | // successful call to dlsym() is "ordered before" any data read through |
| 125 | // the returned pointer (which occurs when the function is called). |
| 126 | // Our implementation mirrors that of the one in libstd, meaning that |
| 127 | // the use of non-Relaxed operations is probably unnecessary. |
| 128 | match self.addr.load(Ordering::Relaxed) { |
| 129 | Self::UNINIT => { |
| 130 | let symbol = self.name.as_ptr() as *const _; |
| 131 | let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) }; |
| 132 | // Synchronizes with the Acquire fence below |
| 133 | self.addr.store(addr, Ordering::Release); |
| 134 | NonNull::new(addr) |
| 135 | } |
| 136 | addr => { |
| 137 | let func = NonNull::new(addr)?; |
| 138 | fence(Ordering::Acquire); |
| 139 | Some(func) |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // SAFETY: path must be null terminated, FD must be manually closed. |
| 146 | pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> { |
| 147 | debug_assert_eq!(path.as_bytes().last(), Some(&0)); |
| 148 | loop { |
| 149 | let fd = libc::open(path.as_ptr() as *const _, libc::O_RDONLY | libc::O_CLOEXEC); |
| 150 | if fd >= 0 { |
| 151 | return Ok(fd); |
| 152 | } |
| 153 | let err = last_os_error(); |
| 154 | // We should try again if open() was interrupted. |
| 155 | if err.raw_os_error() != Some(libc::EINTR) { |
| 156 | return Err(err); |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |