sail-riscv
sail-riscv copied to clipboard
rv_16_random_bits is not deterministic and uses /dev/urandom
This function is used to provide random data to the seed CSR:
// Provides entropy for the scalar cryptography extension.
uint64_t rv_16_random_bits(void)
{
// This function can be changed to support deterministic sequences of
// pseudo-random bytes. This is useful for testing.
const char *name = "/dev/urandom";
FILE *f = fopen(name, "rb");
uint16_t val;
if (fread(&val, 2, 1, f) != 1) {
fprintf(stderr, "Unable to read 2 bytes from %s\n", name);
}
fclose(f);
return (uint64_t)val;
}
It seems like the author was aware that just using /dev/urandom was a bad idea. Since we are using C++ now a better implementation is trivial:
// Provides entropy for the scalar cryptography extension.
uint64_t rv_16_random_bits()
{
static std::mt19937_64 rng(0);
return static_cast<uint16_t>(rng());
}
This is deterministic and should give identical results across different compilers/C++ libraries (weirdly only some C++ PRNGs are guarnateed to do that). The global static is unfortunate but we can solve that later.