From f3dfe1d49ecbcbadc256bea8ba452e1c3b05053a Mon Sep 17 00:00:00 2001 From: Damian Gryski Date: Wed, 18 Sep 2024 12:28:55 -0700 Subject: [PATCH] runtime: seed fastrand() with hardware randomness --- builder/sizes_test.go | 4 ++-- src/runtime/algorithm.go | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/builder/sizes_test.go b/builder/sizes_test.go index 9755abe819..64cd4e77bf 100644 --- a/builder/sizes_test.go +++ b/builder/sizes_test.go @@ -42,8 +42,8 @@ func TestBinarySize(t *testing.T) { tests := []sizeTest{ // microcontrollers {"hifive1b", "examples/echo", 4484, 280, 0, 2252}, - {"microbit", "examples/serial", 2732, 388, 8, 2256}, - {"wioterminal", "examples/pininterrupt", 6016, 1484, 116, 6816}, + {"microbit", "examples/serial", 2808, 388, 8, 2256}, + {"wioterminal", "examples/pininterrupt", 6064, 1484, 116, 6816}, // TODO: also check wasm. Right now this is difficult, because // wasm binaries are run through wasm-opt and therefore the diff --git a/src/runtime/algorithm.go b/src/runtime/algorithm.go index 15ca2b7f5d..24571498b2 100644 --- a/src/runtime/algorithm.go +++ b/src/runtime/algorithm.go @@ -23,7 +23,13 @@ func fastrand() uint32 { return xorshift32State } -var xorshift32State uint32 = 1 +func init() { + r, _ := hardwareRand() + xorshift64State = uint64(r | 1) // protect against 0 + xorshift32State = uint32(xorshift64State) +} + +var xorshift32State uint32 func xorshift32(x uint32) uint32 { // Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs". @@ -43,7 +49,7 @@ func fastrand64() uint64 { return xorshift64State } -var xorshift64State uint64 = 1 +var xorshift64State uint64 // 64-bit xorshift multiply rng from http://vigna.di.unimi.it/ftp/papers/xorshift.pdf func xorshiftMult64(x uint64) uint64 {