| 170 | } |
| 171 | |
| 172 | static void mi_random_init_ex(mi_random_ctx_t* ctx, bool use_weak) { |
| 173 | uint8_t key[32]; |
| 174 | if (use_weak || !_mi_prim_random_buf(key, sizeof(key))) { |
| 175 | // if we fail to get random data from the OS, we fall back to a |
| 176 | // weak random source based on the current time |
| 177 | #if !defined(__wasi__) |
| 178 | if (!use_weak) { _mi_warning_message("unable to use secure randomness\n"); } |
| 179 | #endif |
| 180 | uintptr_t x = _mi_os_random_weak(0); |
| 181 | for (size_t i = 0; i < 32; i+=4, x++) { |
| 182 | x = _mi_random_shuffle(x); |
| 183 | key[i] = (uint8_t)(x); |
| 184 | key[i+1] = (uint8_t)(x>>8); |
| 185 | key[i+2] = (uint8_t)(x>>16); |
| 186 | key[i+3] = (uint8_t)(x>>24); |
| 187 | } |
| 188 | ctx->weak = true; |
| 189 | } |
| 190 | else { |
| 191 | ctx->weak = false; |
| 192 | } |
| 193 | chacha_init(ctx, key, (uintptr_t)ctx /*nonce*/ ); |
| 194 | } |
| 195 | |
| 196 | void _mi_random_init(mi_random_ctx_t* ctx) { |
| 197 | mi_random_init_ex(ctx, false); |
no test coverage detected