Merge pull request #2461 from jepler/urandom-hardfaults

Urandom hardfaults
This commit is contained in:
Scott Shawcroft 2020-01-10 11:37:59 -08:00 committed by GitHub
commit 8708d3dc45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 5 deletions

View File

@ -66,8 +66,24 @@ bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) {
uint8_t sd_en = 0; uint8_t sd_en = 0;
(void) sd_softdevice_is_enabled(&sd_en); (void) sd_softdevice_is_enabled(&sd_en);
if (sd_en) if (sd_en) {
return NRF_SUCCESS == sd_rand_application_vector_get(buffer, length); while (length != 0) {
uint8_t available = 0;
sd_rand_application_bytes_available_get(&available);
if (available) {
uint32_t request = MIN(length, available);
uint32_t result = sd_rand_application_vector_get(buffer, request);
if (result != NRF_SUCCESS) {
return false;
}
buffer += request;
length -= request;
} else {
RUN_BACKGROUND_TASKS;
}
}
return true;
}
#endif #endif
nrf_rng_event_clear(NRF_RNG, NRF_RNG_EVENT_VALRDY); nrf_rng_event_clear(NRF_RNG, NRF_RNG_EVENT_VALRDY);

View File

@ -50,6 +50,9 @@ void vstr_init(vstr_t *vstr, size_t alloc) {
// Init the vstr so it allocs exactly enough ram to hold a null-terminated // Init the vstr so it allocs exactly enough ram to hold a null-terminated
// string of the given length, and set the length. // string of the given length, and set the length.
void vstr_init_len(vstr_t *vstr, size_t len) { void vstr_init_len(vstr_t *vstr, size_t len) {
if(len == SIZE_MAX) {
m_malloc_fail(len);
}
vstr_init(vstr, len + 1); vstr_init(vstr, len + 1);
vstr->len = len; vstr->len = len;
} }

View File

@ -33,6 +33,7 @@
#include "lib/oofatfs/diskio.h" #include "lib/oofatfs/diskio.h"
#include "py/mpstate.h" #include "py/mpstate.h"
#include "py/obj.h" #include "py/obj.h"
#include "py/objstr.h"
#include "py/runtime.h" #include "py/runtime.h"
#include "shared-bindings/os/__init__.h" #include "shared-bindings/os/__init__.h"
@ -195,11 +196,11 @@ MP_DEFINE_CONST_FUN_OBJ_0(os_sync_obj, os_sync);
//| //|
STATIC mp_obj_t os_urandom(mp_obj_t size_in) { STATIC mp_obj_t os_urandom(mp_obj_t size_in) {
mp_int_t size = mp_obj_get_int(size_in); mp_int_t size = mp_obj_get_int(size_in);
uint8_t tmp[size]; mp_obj_str_t *result = MP_OBJ_TO_PTR(mp_obj_new_bytes_of_zeros(size));
if (!common_hal_os_urandom(tmp, size)) { if (!common_hal_os_urandom((uint8_t*) result->data, size)) {
mp_raise_NotImplementedError(translate("No hardware random available")); mp_raise_NotImplementedError(translate("No hardware random available"));
} }
return mp_obj_new_bytes(tmp, size); return result;
} }
MP_DEFINE_CONST_FUN_OBJ_1(os_urandom_obj, os_urandom); MP_DEFINE_CONST_FUN_OBJ_1(os_urandom_obj, os_urandom);