From e45cb217be58beabdf460bc43329a0c94a99b7c0 Mon Sep 17 00:00:00 2001 From: David Nadlinger Date: Thu, 3 Feb 2022 23:57:17 +0000 Subject: [PATCH] firmware: Explicitly use wrapping integer math in PRNGs Patch by Hannah McLaughlin; apparently, the overflow actually doesn't get checked/reported without `opt-level = 2` and `lto = "thin"`. --- artiq/firmware/bootloader/main.rs | 4 ++-- artiq/firmware/libboard_misoc/sdram.rs | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/artiq/firmware/bootloader/main.rs b/artiq/firmware/bootloader/main.rs index 9a41bdb4b..8c428bedb 100644 --- a/artiq/firmware/bootloader/main.rs +++ b/artiq/firmware/bootloader/main.rs @@ -65,8 +65,8 @@ fn memory_test(total: &mut usize, wrong: &mut usize) -> bool { }) } - fn prng32(seed: &mut u32) -> u32 { *seed = 1664525 * *seed + 1013904223; *seed } - fn prng16(seed: &mut u16) -> u16 { *seed = 25173 * *seed + 13849; *seed } + fn prng32(seed: &mut u32) -> u32 { *seed = u32::wrapping_add(u32::wrapping_mul(1664525, *seed), 1013904223); *seed } + fn prng16(seed: &mut u16) -> u16 { *seed = u16::wrapping_add(u16::wrapping_mul(25173, *seed), 13849); *seed } for _ in 0..4 { // Test data bus diff --git a/artiq/firmware/libboard_misoc/sdram.rs b/artiq/firmware/libboard_misoc/sdram.rs index b3e112eb0..1227b411d 100644 --- a/artiq/firmware/libboard_misoc/sdram.rs +++ b/artiq/firmware/libboard_misoc/sdram.rs @@ -211,9 +211,10 @@ mod ddr { // Generate pseudo-random sequence let mut prs = [0; DFII_NPHASES * DFII_PIX_DATA_SIZE]; - let mut prv = 42; + let mut prv: u32 = 42; for b in prs.iter_mut() { - prv = 1664525 * prv + 1013904223; + + prv = u32::wrapping_add(u32::wrapping_mul(1664525, prv), 1013904223); *b = prv as u8; } @@ -296,7 +297,7 @@ mod ddr { let mut prs = [0; DFII_NPHASES * DFII_PIX_DATA_SIZE]; let mut prv = 42; for b in prs.iter_mut() { - prv = 1664525 * prv + 1013904223; + prv = u32::wrapping_add(u32::wrapping_mul(1664525, prv), 1013904223); *b = prv as u8; }