Debian Codegraph @

debian/rust-vendor/getrandom/src/backends/vxworks.rs

raw
1 //! Implementation for VxWorks
2 use crate::Error;
3 use core::{
4 cmp::Ordering::{Equal, Greater, Less},
5 mem::MaybeUninit,
6 sync::atomic::{AtomicBool, Ordering::Relaxed},
7 };
8
9 pub use crate::util::{inner_u32, inner_u64};
10
11 static RNG_INIT: AtomicBool = AtomicBool::new(false);
12
13 #[cold]
14 fn init() -> Result<(), Error> {
15 let ret = unsafe { libc::randSecure() };
16 match ret.cmp(&0) {
17 Greater => RNG_INIT.store(true, Relaxed),
18 Equal => unsafe {
19 libc::usleep(10);
20 },
21 Less => return Err(Error::VXWORKS_RAND_SECURE),
22 }
23 Ok(())
24 }
25
26 #[inline]
27 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
28 while !RNG_INIT.load(Relaxed) {
29 init()?;
30 }
31
32 // Prevent overflow of i32
33 let chunk_size = usize::try_from(i32::MAX).expect("VxWorks does not support 16-bit targets");
34 for chunk in dest.chunks_mut(chunk_size) {
35 let chunk_len: libc::c_int = chunk
36 .len()
37 .try_into()
38 .expect("chunk size is bounded by i32::MAX");
39 let p: *mut libc::c_uchar = chunk.as_mut_ptr().cast();
40 let ret = unsafe { libc::randABytes(p, chunk_len) };
41 match ret {
42 0 => continue,
43 -1 => {
44 let errno = unsafe { libc::errnoGet() };
45 return Err(Error::from_errno(errno));
46 }
47 _ => return Err(Error::UNEXPECTED),
48 }
49 }
50 Ok(())
51 }
52
53 impl Error {
54 /// On VxWorks, call to `randSecure` failed (random number generator is not yet initialized).
55 pub(crate) const VXWORKS_RAND_SECURE: Error = Self::new_internal(10);
56 }