Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getrandom impl using ctru_sys bindings #8

Merged
merged 3 commits into from
Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ license = "MIT/Apache 2.0"
edition = "2018"

[dependencies]
ctru-sys = { git = "https://github.com/Meziu/ctru-rs.git" }
libc = "0.2.116"
42 changes: 42 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,45 @@ unsafe extern "C" fn clock_gettime(

retval
}

#[no_mangle]
unsafe extern "C" fn getrandom(
buf: *mut libc::c_void,
mut buflen: libc::size_t,
flags: libc::c_uint,
) -> libc::ssize_t {
// Based on https://man7.org/linux/man-pages/man2/getrandom.2.html
// Technically we only have one source (no true /dev/random), but the
// behavior should be more expected this way.
let maxlen = if flags & libc::GRND_RANDOM != 0 {
512
} else {
0x1FFFFFF
};
buflen = buflen.min(maxlen);

let ret = ctru_sys::PS_GenerateRandomBytes(buf, buflen as libc::c_uint);

// avoid conflicting a real POSIX errno by using a value < 0
// should we define this in ctru-sys somewhere or something?
const ECTRU: libc::c_int = -1;

if ctru_sys::R_SUCCEEDED(ret) {
// safe because above ensures buflen < isize::MAX
buflen as libc::ssize_t
} else {
// best-effort attempt at translating return codes
*__errno() = match ctru_sys::R_SUMMARY(ret) as libc::c_uint {
ctru_sys::RS_WOULDBLOCK => libc::EAGAIN,
ctru_sys::RS_INVALIDARG | ctru_sys::RS_WRONGARG => {
match ctru_sys::R_DESCRIPTION(ret) as libc::c_uint {
// most likely user error, forgot to initialize PS module
ctru_sys::RD_INVALID_HANDLE => ECTRU,
_ => libc::EINVAL,
}
}
_ => ECTRU,
};
-1
}
}