potential fix for sporadic assertion failure on random returning 0 (issue #1039)

This commit is contained in:
Daan 2025-03-19 19:06:21 -07:00
parent 26fa8be427
commit 47bf3a5b1b

View file

@ -143,13 +143,17 @@ void _mi_random_split(mi_random_ctx_t* ctx, mi_random_ctx_t* ctx_new) {
uintptr_t _mi_random_next(mi_random_ctx_t* ctx) { uintptr_t _mi_random_next(mi_random_ctx_t* ctx) {
mi_assert_internal(mi_random_is_initialized(ctx)); mi_assert_internal(mi_random_is_initialized(ctx));
#if MI_INTPTR_SIZE <= 4 uintptr_t r;
return chacha_next32(ctx); do {
#elif MI_INTPTR_SIZE == 8 #if MI_INTPTR_SIZE <= 4
return (((uintptr_t)chacha_next32(ctx) << 32) | chacha_next32(ctx)); r = chacha_next32(ctx);
#else #elif MI_INTPTR_SIZE == 8
# error "define mi_random_next for this platform" r = (((uintptr_t)chacha_next32(ctx) << 32) | chacha_next32(ctx));
#endif #else
# error "define mi_random_next for this platform"
#endif
} while (r==0);
return r;
} }
@ -163,7 +167,7 @@ uintptr_t _mi_os_random_weak(uintptr_t extra_seed) {
x ^= _mi_prim_clock_now(); x ^= _mi_prim_clock_now();
// and do a few randomization steps // and do a few randomization steps
uintptr_t max = ((x ^ (x >> 17)) & 0x0F) + 1; uintptr_t max = ((x ^ (x >> 17)) & 0x0F) + 1;
for (uintptr_t i = 0; i < max; i++) { for (uintptr_t i = 0; i < max || x==0; i++, x++) {
x = _mi_random_shuffle(x); x = _mi_random_shuffle(x);
} }
mi_assert_internal(x != 0); mi_assert_internal(x != 0);
@ -179,7 +183,7 @@ static void mi_random_init_ex(mi_random_ctx_t* ctx, bool use_weak) {
if (!use_weak) { _mi_warning_message("unable to use secure randomness\n"); } if (!use_weak) { _mi_warning_message("unable to use secure randomness\n"); }
#endif #endif
uintptr_t x = _mi_os_random_weak(0); uintptr_t x = _mi_os_random_weak(0);
for (size_t i = 0; i < 8; i++) { // key is eight 32-bit words. for (size_t i = 0; i < 8; i++, x++) { // key is eight 32-bit words.
x = _mi_random_shuffle(x); x = _mi_random_shuffle(x);
((uint32_t*)key)[i] = (uint32_t)x; ((uint32_t*)key)[i] = (uint32_t)x;
} }