Add getrandom and sys/random.h

This commit is contained in:
Jeremy Soller
2020-05-22 11:50:54 -06:00
parent 2cf3ccae72
commit a6fffd3fb5
7 changed files with 77 additions and 0 deletions
+4
View File
@@ -254,6 +254,10 @@ impl Pal for Sys {
e(unsafe { syscall!(GETPPID) }) as pid_t
}
fn getrandom(buf: &mut [u8], flags: c_uint) -> ssize_t {
e(unsafe { syscall!(GETRANDOM, buf.as_mut_ptr(), buf.len(), flags) }) as ssize_t
}
unsafe fn getrlimit(resource: c_int, rlim: *mut rlimit) -> c_int {
e(syscall!(GETRLIMIT, resource, rlim)) as c_int
}
+2
View File
@@ -91,6 +91,8 @@ pub trait Pal {
fn getppid() -> pid_t;
fn getrandom(buf: &mut [u8], flags: c_uint) -> ssize_t;
unsafe fn getrlimit(resource: c_int, rlim: *mut rlimit) -> c_int;
fn gettid() -> pid_t;
+28
View File
@@ -13,6 +13,7 @@ use crate::{
errno::{EINVAL, EIO, EPERM, ERANGE},
fcntl,
sys_mman::MAP_ANON,
sys_random,
sys_resource::{rlimit, RLIM_INFINITY},
sys_stat::stat,
sys_statvfs::statvfs,
@@ -555,6 +556,33 @@ impl Pal for Sys {
e(syscall::getppid()) as pid_t
}
fn getrandom(buf: &mut [u8], flags: c_uint) -> ssize_t {
//TODO: make this a system call?
let path = if flags & sys_random::GRND_RANDOM != 0 {
//TODO: /dev/random equivalent
"rand:"
} else {
"rand:"
};
let mut open_flags = syscall::O_RDONLY | syscall::O_CLOEXEC;
if flags & sys_random::GRND_NONBLOCK != 0 {
open_flags |= syscall::O_NONBLOCK;
}
let fd = e(syscall::open(path, open_flags));
if fd == !0 {
return -1;
}
let res = e(syscall::read(fd, buf)) as ssize_t;
let _ = syscall::close(fd);
res
}
unsafe fn getrlimit(resource: c_int, rlim: *mut rlimit) -> c_int {
//TODO
if !rlim.is_null() {
+19
View File
@@ -63,3 +63,22 @@ fn clock_gettime() {
assert_ne!(timespec.tv_nsec, -1);
}
}
//TDOO: everything else
#[test]
fn getrandom() {
use crate::header::sys_random;
use crate::platform::types::ssize_t;
let mut arrays = [[0; 32]; 32];
for i in 1..arrays.len() {
assert_eq!(Sys::getrandom(&mut arrays[i], 0), arrays[i].len() as ssize_t);
for j in 0..arrays.len() {
if i != j {
assert_ne!(&arrays[i], &arrays[j]);
}
}
}
}