From ef86bbf531e6735156da7a7b0b88e3a1074e3cd3 Mon Sep 17 00:00:00 2001 From: Andrea Ciliberti Date: Wed, 15 Feb 2023 13:57:52 +0100 Subject: [PATCH] Add error handling --- src/lib.rs | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c74dbe3..bea1f81 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,30 +51,44 @@ pub unsafe extern "C" fn getrandom( }; buflen = buflen.min(maxlen); - let _ = ctru_sys::psInit(); - let ret = ctru_sys::PS_GenerateRandomBytes(buf, buflen); - - // avoid conflicting a real POSIX errno by using a value < 0 - // should we define this in ctru-sys somewhere or something? + // 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; + let ret = ctru_sys::psInit(); + + // Error handling code for psInit + if ctru_sys::R_FAILED(ret) { + // Best-effort attempt at translating return codes + *__errno() = match ctru_sys::R_SUMMARY(ret) as libc::c_uint { + // The service handle is full (would block to await availability) + ctru_sys::RS_WOULDBLOCK => libc::EAGAIN, + // The caller doesn't have the right to call the service + _ => ECTRU, + }; + return -1 + } + + let ret = ctru_sys::PS_GenerateRandomBytes(buf, buflen); + + // Error handling code for PS_GenerateRandomBytes if ctru_sys::R_SUCCEEDED(ret) { - // safe because above ensures buflen < isize::MAX + // Safe because above ensures buflen < isize::MAX buflen as libc::ssize_t } else { - // best-effort attempt at translating return codes + // 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 + // The handle is incorrect (even though we just made it) ctru_sys::RD_INVALID_HANDLE => ECTRU, _ => libc::EINVAL, } } _ => ECTRU, }; - -1 + return -1 } }