Skip to content

Commit

Permalink
use inline asm instead of read_volatile
Browse files Browse the repository at this point in the history
  • Loading branch information
newpavlov committed Aug 21, 2024
1 parent fb2f9a5 commit 4615b75
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions sha2/src/sha256/riscv_zknh.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::consts::K32;
use core::ptr::read_volatile;

#[cfg(target_arch = "riscv32")]
use core::arch::riscv32::*;
Expand All @@ -19,6 +18,24 @@ fn maj(x: u32, y: u32, z: u32) -> u32 {
(x & y) ^ (x & z) ^ (y & z)
}

/// Forcefully read the round constant to prevent its reconstruction on stack.
fn read_rk<const IDX: usize>() -> u32 {
assert!(IDX < K32.len());
let res;
unsafe {
core::arch::asm!(
"lw {dst}, 4*{IDX}({p})",
IDX = const IDX,
p = in(reg) &K32,
dst = out(reg) res,
// note: the `pure` option is intentionally not used to prevent
// caching of the round constant on stack
options(preserves_flags, nostack, readonly)
);
}
res
}

macro_rules! round {
(
$a: ident, $b: ident, $c: ident, $d: ident,
Expand All @@ -30,9 +47,7 @@ macro_rules! round {
$h = $h
.wrapping_add(unsafe { sha256sum1($e) })
.wrapping_add(ch($e, $f, $g))
// Volatile read is used to force reading from the static,
// otherwise compiler reconstructs round constants on stack.
.wrapping_add(unsafe { read_volatile(&K32[$k]) })
.wrapping_add(read_rk::<$k>())
.wrapping_add($w);
$d = $d.wrapping_add($h);
$h = $h
Expand Down

0 comments on commit 4615b75

Please sign in to comment.