/rust/registry/src/index.crates.io-1949cf8c6b5b557f/getrandom-0.2.7/src/util_libc.rs
Line | Count | Source |
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 | 0 | unsafe fn get_errno() -> libc::c_int { *errno_location() } |
46 | | } |
47 | | } |
48 | | |
49 | 0 | pub fn last_os_error() -> Error { |
50 | 0 | let errno = unsafe { get_errno() }; |
51 | 0 | if errno > 0 { |
52 | 0 | Error::from(NonZeroU32::new(errno as u32).unwrap()) |
53 | | } else { |
54 | 0 | Error::ERRNO_NOT_POSITIVE |
55 | | } |
56 | 0 | } |
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 |
61 | 0 | pub fn sys_fill_exact( |
62 | 0 | mut buf: &mut [u8], |
63 | 0 | sys_fill: impl Fn(&mut [u8]) -> libc::ssize_t, |
64 | 0 | ) -> Result<(), Error> { |
65 | 0 | while !buf.is_empty() { |
66 | 0 | let res = sys_fill(buf); |
67 | 0 | if res < 0 { |
68 | 0 | let err = last_os_error(); |
69 | | // We should try again if the call was interrupted. |
70 | 0 | if err.raw_os_error() != Some(libc::EINTR) { |
71 | 0 | return Err(err); |
72 | 0 | } |
73 | 0 | } else { |
74 | 0 | // We don't check for EOF (ret = 0) as the data we are reading |
75 | 0 | // should be an infinite stream of random bytes. |
76 | 0 | buf = &mut buf[(res as usize)..]; |
77 | 0 | } |
78 | | } |
79 | 0 | Ok(()) |
80 | 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}> |
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. |
103 | 0 | pub const unsafe fn new(name: &'static str) -> Self { |
104 | 0 | Self { |
105 | 0 | name, |
106 | 0 | addr: AtomicPtr::new(Self::UNINIT), |
107 | 0 | } |
108 | 0 | } |
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. |
114 | 0 | 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 | 0 | match self.addr.load(Ordering::Relaxed) { |
122 | 0 | Self::UNINIT => { |
123 | 0 | let symbol = self.name.as_ptr() as *const _; |
124 | 0 | let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) }; |
125 | | // Synchronizes with the Acquire fence below |
126 | 0 | self.addr.store(addr, Ordering::Release); |
127 | 0 | NonNull::new(addr) |
128 | | } |
129 | 0 | addr => { |
130 | 0 | let func = NonNull::new(addr)?; |
131 | 0 | fence(Ordering::Acquire); |
132 | 0 | Some(func) |
133 | | } |
134 | | } |
135 | 0 | } |
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. |
147 | 0 | pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> { |
148 | 0 | debug_assert_eq!(path.as_bytes().last(), Some(&0)); |
149 | | loop { |
150 | 0 | let fd = open(path.as_ptr() as *const _, libc::O_RDONLY | libc::O_CLOEXEC); |
151 | 0 | if fd >= 0 { |
152 | 0 | return Ok(fd); |
153 | 0 | } |
154 | 0 | let err = last_os_error(); |
155 | | // We should try again if open() was interrupted. |
156 | 0 | if err.raw_os_error() != Some(libc::EINTR) { |
157 | 0 | return Err(err); |
158 | 0 | } |
159 | | } |
160 | 0 | } |