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
28 cfg_if! {
29 if #[cfg(target_os = "vxworks")] {
30 use libc::errnoGet as get_errno;
31 } else {
32 unsafe fn get_errno() -> libc::c_int { *errno_location() }
33 }
34 }
35
last_os_error() -> Error36 pub fn last_os_error() -> Error {
37 let errno = unsafe { get_errno() };
38 if errno > 0 {
39 Error::from(NonZeroU32::new(errno as u32).unwrap())
40 } else {
41 ERRNO_NOT_POSITIVE
42 }
43 }
44
45 // Fill a buffer by repeatedly invoking a system call. The `sys_fill` function:
46 // - should return -1 and set errno on failure
47 // - 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>48 pub fn sys_fill_exact(
49 mut buf: &mut [u8],
50 sys_fill: impl Fn(&mut [u8]) -> libc::ssize_t,
51 ) -> Result<(), Error> {
52 while !buf.is_empty() {
53 let res = sys_fill(buf);
54 if res < 0 {
55 let err = last_os_error();
56 // We should try again if the call was interrupted.
57 if err.raw_os_error() != Some(libc::EINTR) {
58 return Err(err);
59 }
60 } else {
61 // We don't check for EOF (ret = 0) as the data we are reading
62 // should be an infinite stream of random bytes.
63 buf = &mut buf[(res as usize)..];
64 }
65 }
66 Ok(())
67 }
68
69 // A "weak" binding to a C function that may or may not be present at runtime.
70 // Used for supporting newer OS features while still building on older systems.
71 // F must be a function pointer of type `unsafe extern "C" fn`. Based off of the
72 // weak! macro in libstd.
73 pub struct Weak {
74 name: &'static str,
75 addr: LazyUsize,
76 }
77
78 impl Weak {
79 // Construct a binding to a C function with a given name. This function is
80 // unsafe because `name` _must_ be null terminated.
new(name: &'static str) -> Self81 pub const unsafe fn new(name: &'static str) -> Self {
82 Self {
83 name,
84 addr: LazyUsize::new(),
85 }
86 }
87
88 // Return a function pointer if present at runtime. Otherwise, return null.
ptr(&self) -> Option<NonNull<libc::c_void>>89 pub fn ptr(&self) -> Option<NonNull<libc::c_void>> {
90 let addr = self.addr.unsync_init(|| unsafe {
91 libc::dlsym(libc::RTLD_DEFAULT, self.name.as_ptr() as *const _) as usize
92 });
93 NonNull::new(addr as *mut _)
94 }
95 }
96
97 cfg_if! {
98 if #[cfg(any(target_os = "linux", target_os = "emscripten"))] {
99 use libc::open64 as open;
100 } else {
101 use libc::open;
102 }
103 }
104
105 // SAFETY: path must be null terminated, FD must be manually closed.
open_readonly(path: &str) -> Result<libc::c_int, Error>106 pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> {
107 debug_assert!(path.as_bytes().last() == Some(&0));
108 let fd = open(path.as_ptr() as *const _, libc::O_RDONLY | libc::O_CLOEXEC);
109 if fd < 0 {
110 return Err(last_os_error());
111 }
112 // O_CLOEXEC works on all Unix targets except for older Linux kernels (pre
113 // 2.6.23), so we also use an ioctl to make sure FD_CLOEXEC is set.
114 #[cfg(target_os = "linux")]
115 libc::ioctl(fd, libc::FIOCLEX);
116 Ok(fd)
117 }
118