/rust/registry/src/index.crates.io-1949cf8c6b5b557f/getrandom-0.2.7/src/linux_android.rs
Line | Count | Source |
1 | | // Copyright 2018 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 | | |
9 | | //! Implementation for Linux / Android |
10 | | use crate::{ |
11 | | util::LazyBool, |
12 | | util_libc::{last_os_error, sys_fill_exact}, |
13 | | {use_file, Error}, |
14 | | }; |
15 | | |
16 | 0 | pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { |
17 | | // getrandom(2) was introduced in Linux 3.17 |
18 | | static HAS_GETRANDOM: LazyBool = LazyBool::new(); |
19 | 0 | if HAS_GETRANDOM.unsync_init(is_getrandom_available) { |
20 | 0 | sys_fill_exact(dest, |buf| unsafe { |
21 | 0 | getrandom(buf.as_mut_ptr() as *mut libc::c_void, buf.len(), 0) |
22 | 0 | }) |
23 | | } else { |
24 | 0 | use_file::getrandom_inner(dest) |
25 | | } |
26 | 0 | } |
27 | | |
28 | 0 | fn is_getrandom_available() -> bool { |
29 | 0 | let res = unsafe { getrandom(core::ptr::null_mut(), 0, libc::GRND_NONBLOCK) }; |
30 | 0 | if res < 0 { |
31 | 0 | match last_os_error().raw_os_error() { |
32 | 0 | Some(libc::ENOSYS) => false, // No kernel support |
33 | 0 | Some(libc::EPERM) => false, // Blocked by seccomp |
34 | 0 | _ => true, |
35 | | } |
36 | | } else { |
37 | 0 | true |
38 | | } |
39 | 0 | } |
40 | | |
41 | 0 | unsafe fn getrandom( |
42 | 0 | buf: *mut libc::c_void, |
43 | 0 | buflen: libc::size_t, |
44 | 0 | flags: libc::c_uint, |
45 | 0 | ) -> libc::ssize_t { |
46 | 0 | libc::syscall(libc::SYS_getrandom, buf, buflen, flags) as libc::ssize_t |
47 | 0 | } |