From 897f2bc5fd030daa0c73dc5a530a0537ae5460f2 Mon Sep 17 00:00:00 2001 From: "MakKi (makki_d)" Date: Thu, 18 Dec 2025 04:05:43 +0900 Subject: [PATCH] runtime: avoid fixed math/rand sequence on RP2040/RP2350 (#5124) * runtime: avoid fixed math/rand sequence on RP2040/RP2350 * fix typo --- src/runtime/rand_norng.go | 2 +- src/runtime/rand_rp2.go | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 src/runtime/rand_rp2.go diff --git a/src/runtime/rand_norng.go b/src/runtime/rand_norng.go index aa79c500d..ebeba91cb 100644 --- a/src/runtime/rand_norng.go +++ b/src/runtime/rand_norng.go @@ -1,4 +1,4 @@ -//go:build baremetal && !(nrf || (stm32 && !(stm32f103 || stm32l0x1)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || tkey || (tinygo.riscv32 && virt)) +//go:build baremetal && !(nrf || (stm32 && !(stm32f103 || stm32l0x1)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || tkey || (tinygo.riscv32 && virt) || rp2040 || rp2350) package runtime diff --git a/src/runtime/rand_rp2.go b/src/runtime/rand_rp2.go new file mode 100644 index 000000000..89af3f98f --- /dev/null +++ b/src/runtime/rand_rp2.go @@ -0,0 +1,20 @@ +//go:build rp2040 || rp2350 + +package runtime + +import "machine" + +var hardwareRandValue uint64 + +func hardwareRand() (n uint64, ok bool) { + if hardwareRandValue == 0 { + n1, _ := machine.GetRNG() + n2, _ := machine.GetRNG() + hardwareRandValue = uint64(n1)<<32 | uint64(n2) + } + + // Return ok=false to keep using fastrand64(), + // with hardwareRandVal used only as its initial random state. + + return hardwareRandValue, false +}