From b6f266d3b8ecb9c83ba744b14d0b520aa7cbdf03 Mon Sep 17 00:00:00 2001 From: Dean Li Date: Mon, 8 Nov 2021 16:29:55 +0000 Subject: [PATCH] os: implement getrandom --- vm/src/stdlib/posix.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index 3d841cba40..11205c4181 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -68,6 +68,10 @@ pub mod module { #[pyattr] use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW}; + #[cfg(target_os = "linux")] + #[pyattr] + use libc::{GRND_NONBLOCK, GRND_RANDOM}; + #[pyattr] const EX_OK: i8 = exitcode::OK as i8; #[pyattr] @@ -1975,4 +1979,23 @@ pub mod module { res.map_err(|err| err.into_pyexception(vm))?; Ok(vm.ctx.new_int(written as u64).into()) } + + #[cfg(target_os = "linux")] + #[pyfunction] + fn getrandom(size: isize, flags: OptionalArg, vm: &VirtualMachine) -> PyResult> { + let size = usize::try_from(size) + .map_err(|_| vm.new_os_error(format!("Invalid argument for size: {}", size)))?; + let mut buf = Vec::with_capacity(size); + unsafe { + let len = libc::getrandom( + buf.as_mut_ptr() as *mut libc::c_void, + size, + flags.unwrap_or(0), + ) + .try_into() + .map_err(|_| errno_err(vm))?; + buf.set_len(len); + } + Ok(buf) + } }