diff --git a/ports/nrf/common-hal/os/__init__.c b/ports/nrf/common-hal/os/__init__.c index e38226f94e..b2ad00a5ca 100644 --- a/ports/nrf/common-hal/os/__init__.c +++ b/ports/nrf/common-hal/os/__init__.c @@ -66,8 +66,24 @@ bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { uint8_t sd_en = 0; (void) sd_softdevice_is_enabled(&sd_en); - if (sd_en) - return NRF_SUCCESS == sd_rand_application_vector_get(buffer, length); + if (sd_en) { + 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 nrf_rng_event_clear(NRF_RNG, NRF_RNG_EVENT_VALRDY); diff --git a/py/vstr.c b/py/vstr.c index 869b278057..91cd7f584f 100644 --- a/py/vstr.c +++ b/py/vstr.c @@ -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 // string of the given length, and set the length. void vstr_init_len(vstr_t *vstr, size_t len) { + if(len == SIZE_MAX) { + m_malloc_fail(len); + } vstr_init(vstr, len + 1); vstr->len = len; } diff --git a/shared-bindings/os/__init__.c b/shared-bindings/os/__init__.c index 55ebd6f59f..c2b63bbcee 100644 --- a/shared-bindings/os/__init__.c +++ b/shared-bindings/os/__init__.c @@ -33,6 +33,7 @@ #include "lib/oofatfs/diskio.h" #include "py/mpstate.h" #include "py/obj.h" +#include "py/objstr.h" #include "py/runtime.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) { mp_int_t size = mp_obj_get_int(size_in); - uint8_t tmp[size]; - if (!common_hal_os_urandom(tmp, size)) { + mp_obj_str_t *result = MP_OBJ_TO_PTR(mp_obj_new_bytes_of_zeros(size)); + if (!common_hal_os_urandom((uint8_t*) result->data, size)) { 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);