Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
File diff suppressed because it is too large Load Diff
+81
View File
@@ -0,0 +1,81 @@
// Copyright 2015-2023 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::Modulus;
use crate::{
error,
limb::{self, Limb},
};
use alloc::{boxed::Box, vec};
use core::{
marker::PhantomData,
ops::{Deref, DerefMut},
};
/// All `BoxedLimbs<M>` are stored in the same number of limbs.
pub(super) struct BoxedLimbs<M> {
limbs: Box<[Limb]>,
/// The modulus *m* that determines the size of `limbx`.
m: PhantomData<M>,
}
impl<M> Deref for BoxedLimbs<M> {
type Target = [Limb];
#[inline]
fn deref(&self) -> &Self::Target {
&self.limbs
}
}
impl<M> DerefMut for BoxedLimbs<M> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.limbs
}
}
// TODO: `derive(Clone)` after https://github.com/rust-lang/rust/issues/26925
// is resolved or restrict `M: Clone`.
impl<M> Clone for BoxedLimbs<M> {
fn clone(&self) -> Self {
Self {
limbs: self.limbs.clone(),
m: self.m,
}
}
}
impl<M> BoxedLimbs<M> {
pub(super) fn from_be_bytes_padded_less_than(
input: untrusted::Input,
m: &Modulus<M>,
) -> Result<Self, error::Unspecified> {
let mut r = Self::zero(m.limbs().len());
limb::parse_big_endian_and_pad_consttime(input, &mut r)?;
limb::verify_limbs_less_than_limbs_leak_bit(&r, m.limbs())?;
Ok(r)
}
pub(super) fn zero(len: usize) -> Self {
Self {
limbs: vec![0; len].into_boxed_slice(),
m: PhantomData,
}
}
pub(super) fn into_limbs(self) -> Box<[Limb]> {
self.limbs
}
}
+202
View File
@@ -0,0 +1,202 @@
// Copyright 2015-2024 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::{
super::montgomery::Unencoded, unwrap_impossible_len_mismatch_error, BoxedLimbs, Elem,
OwnedModulusValue, PublicModulus, Storage, N0,
};
use crate::{
bits::BitLength,
cpu, error,
limb::{self, Limb, LIMB_BITS},
polyfill::LeadingZerosStripped,
};
use core::marker::PhantomData;
/// The modulus *m* for a ring ℤ/mℤ, along with the precomputed values needed
/// for efficient Montgomery multiplication modulo *m*. The value must be odd
/// and larger than 2. The larger-than-1 requirement is imposed, at least, by
/// the modular inversion code.
pub struct OwnedModulus<M> {
inner: OwnedModulusValue<M>,
// n0 * N == -1 (mod r).
//
// r == 2**(N0::LIMBS_USED * LIMB_BITS) and LG_LITTLE_R == lg(r). This
// ensures that we can do integer division by |r| by simply ignoring
// `N0::LIMBS_USED` limbs. Similarly, we can calculate values modulo `r` by
// just looking at the lowest `N0::LIMBS_USED` limbs. This is what makes
// Montgomery multiplication efficient.
//
// As shown in Algorithm 1 of "Fast Prime Field Elliptic Curve Cryptography
// with 256 Bit Primes" by Shay Gueron and Vlad Krasnov, in the loop of a
// multi-limb Montgomery multiplication of a * b (mod n), given the
// unreduced product t == a * b, we repeatedly calculate:
//
// t1 := t % r |t1| is |t|'s lowest limb (see previous paragraph).
// t2 := t1*n0*n
// t3 := t + t2
// t := t3 / r copy all limbs of |t3| except the lowest to |t|.
//
// In the last step, it would only make sense to ignore the lowest limb of
// |t3| if it were zero. The middle steps ensure that this is the case:
//
// t3 == 0 (mod r)
// t + t2 == 0 (mod r)
// t + t1*n0*n == 0 (mod r)
// t1*n0*n == -t (mod r)
// t*n0*n == -t (mod r)
// n0*n == -1 (mod r)
// n0 == -1/n (mod r)
//
// Thus, in each iteration of the loop, we multiply by the constant factor
// n0, the negative inverse of n (mod r).
//
// TODO(perf): Not all 32-bit platforms actually make use of n0[1]. For the
// ones that don't, we could use a shorter `R` value and use faster `Limb`
// calculations instead of double-precision `u64` calculations.
n0: N0,
}
impl<M: PublicModulus> Clone for OwnedModulus<M> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
n0: self.n0,
}
}
}
impl<M> OwnedModulus<M> {
pub(crate) fn from(n: OwnedModulusValue<M>) -> Self {
// n_mod_r = n % r. As explained in the documentation for `n0`, this is
// done by taking the lowest `N0::LIMBS_USED` limbs of `n`.
#[allow(clippy::useless_conversion)]
let n0 = {
prefixed_extern! {
fn bn_neg_inv_mod_r_u64(n: u64) -> u64;
}
// XXX: u64::from isn't guaranteed to be constant time.
let mut n_mod_r: u64 = u64::from(n.limbs()[0]);
if N0::LIMBS_USED == 2 {
// XXX: If we use `<< LIMB_BITS` here then 64-bit builds
// fail to compile because of `deny(exceeding_bitshifts)`.
debug_assert_eq!(LIMB_BITS, 32);
n_mod_r |= u64::from(n.limbs()[1]) << 32;
}
N0::precalculated(unsafe { bn_neg_inv_mod_r_u64(n_mod_r) })
};
Self { inner: n, n0 }
}
pub fn to_elem<L>(&self, l: &Modulus<L>) -> Result<Elem<L, Unencoded>, error::Unspecified> {
self.inner.verify_less_than(l)?;
let mut limbs = BoxedLimbs::zero(l.limbs().len());
limbs[..self.inner.limbs().len()].copy_from_slice(self.inner.limbs());
Ok(Elem {
limbs,
encoding: PhantomData,
})
}
pub(crate) fn modulus(&self, cpu_features: cpu::Features) -> Modulus<M> {
Modulus {
limbs: self.inner.limbs(),
n0: self.n0,
len_bits: self.len_bits(),
m: PhantomData,
cpu_features,
}
}
pub fn len_bits(&self) -> BitLength {
self.inner.len_bits()
}
}
impl<M: PublicModulus> OwnedModulus<M> {
pub fn be_bytes(&self) -> LeadingZerosStripped<impl ExactSizeIterator<Item = u8> + Clone + '_> {
LeadingZerosStripped::new(limb::unstripped_be_bytes(self.inner.limbs()))
}
}
pub struct Modulus<'a, M> {
limbs: &'a [Limb],
n0: N0,
len_bits: BitLength,
m: PhantomData<M>,
cpu_features: cpu::Features,
}
impl<M> Modulus<'_, M> {
pub(super) fn oneR(&self, out: &mut [Limb]) {
assert_eq!(self.limbs.len(), out.len());
let r = self.limbs.len() * LIMB_BITS;
// out = 2**r - m where m = self.
limb::limbs_negative_odd(out, self.limbs);
let lg_m = self.len_bits().as_bits();
let leading_zero_bits_in_m = r - lg_m;
// When m's length is a multiple of LIMB_BITS, which is the case we
// most want to optimize for, then we already have
// out == 2**r - m == 2**r (mod m).
if leading_zero_bits_in_m != 0 {
debug_assert!(leading_zero_bits_in_m < LIMB_BITS);
// Correct out to 2**(lg m) (mod m). `limbs_negative_odd` flipped
// all the leading zero bits to ones. Flip them back.
*out.last_mut().unwrap() &= (!0) >> leading_zero_bits_in_m;
// Now we have out == 2**(lg m) (mod m). Keep doubling until we get
// to 2**r (mod m).
for _ in 0..leading_zero_bits_in_m {
limb::limbs_double_mod(out, self.limbs)
.unwrap_or_else(unwrap_impossible_len_mismatch_error);
}
}
// Now out == 2**r (mod m) == 1*R.
}
// TODO: XXX Avoid duplication with `Modulus`.
pub fn alloc_zero(&self) -> Storage<M> {
Storage {
limbs: BoxedLimbs::zero(self.limbs.len()),
}
}
#[inline]
pub(super) fn limbs(&self) -> &[Limb] {
self.limbs
}
#[inline]
pub(super) fn n0(&self) -> &N0 {
&self.n0
}
pub fn len_bits(&self) -> BitLength {
self.len_bits
}
#[inline]
pub(crate) fn cpu_features(&self) -> cpu::Features {
self.cpu_features
}
}
+88
View File
@@ -0,0 +1,88 @@
// Copyright 2015-2024 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::{
super::{MAX_LIMBS, MIN_LIMBS},
BoxedLimbs, Modulus, PublicModulus,
};
use crate::{
bits::BitLength,
error,
limb::{self, Limb, LIMB_BYTES},
};
/// `OwnedModulus`, without the overhead of Montgomery multiplication support.
pub(crate) struct OwnedModulusValue<M> {
limbs: BoxedLimbs<M>, // Also `value >= 3`.
len_bits: BitLength,
}
impl<M: PublicModulus> Clone for OwnedModulusValue<M> {
fn clone(&self) -> Self {
Self {
limbs: self.limbs.clone(),
len_bits: self.len_bits,
}
}
}
impl<M> OwnedModulusValue<M> {
pub(crate) fn from_be_bytes(input: untrusted::Input) -> Result<Self, error::KeyRejected> {
let num_limbs = (input.len() + LIMB_BYTES - 1) / LIMB_BYTES;
const _MODULUS_MIN_LIMBS_AT_LEAST_2: () = assert!(MIN_LIMBS >= 2);
if num_limbs < MIN_LIMBS {
return Err(error::KeyRejected::unexpected_error());
}
if num_limbs > MAX_LIMBS {
return Err(error::KeyRejected::too_large());
}
// The above implies n >= 3, so we don't need to check that.
// Reject leading zeros. Also reject the value zero ([0]) because zero
// isn't positive.
if untrusted::Reader::new(input).peek(0) {
return Err(error::KeyRejected::invalid_encoding());
}
let mut limbs = BoxedLimbs::zero(num_limbs);
limb::parse_big_endian_and_pad_consttime(input, &mut limbs)
.map_err(|error::Unspecified| error::KeyRejected::unexpected_error())?;
limb::limbs_reject_even_leak_bit(&limbs)
.map_err(|_: error::Unspecified| error::KeyRejected::invalid_component())?;
let len_bits = limb::limbs_minimal_bits(&limbs);
Ok(Self { limbs, len_bits })
}
pub fn verify_less_than<L>(&self, l: &Modulus<L>) -> Result<(), error::Unspecified> {
if self.len_bits() > l.len_bits() {
return Err(error::Unspecified);
}
if self.limbs.len() == l.limbs().len() {
limb::verify_limbs_less_than_limbs_leak_bit(&self.limbs, l.limbs())?;
}
Ok(())
}
pub fn len_bits(&self) -> BitLength {
self.len_bits
}
#[inline]
pub(super) fn limbs(&self) -> &[Limb] {
&self.limbs
}
}
+77
View File
@@ -0,0 +1,77 @@
// Copyright 2015-2023 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::{limb, BoxedLimbs, Limb, Modulus};
use crate::error;
use alloc::boxed::Box;
pub struct PrivateExponent {
// Unlike most `[Limb]` we deal with, these are stored most significant
// word first.
limbs: Box<[Limb]>,
}
impl PrivateExponent {
// `p` is the modulus for which the exponent is in the interval [1, `p` - 1).
pub fn from_be_bytes_padded<M>(
input: untrusted::Input,
p: &Modulus<M>,
) -> Result<Self, error::Unspecified> {
let mut dP = BoxedLimbs::from_be_bytes_padded_less_than(input, p)?;
// Proof that `dP < p - 1`:
//
// If `dP < p` then either `dP == p - 1` or `dP < p - 1`. Since `p` is
// odd, `p - 1` is even. `d` is odd, and an odd number modulo an even
// number is odd. Therefore `dP` must be odd. But then it cannot be
// `p - 1` and so we know `dP < p - 1`.
//
// Further we know `dP != 0` because `dP` is not even.
limb::limbs_reject_even_leak_bit(&dP)?;
dP.reverse();
Ok(Self {
limbs: dP.into_limbs(),
})
}
// Create a `PrivateExponent` with a value that we do not support in
// production use, to allow testing with additional test vectors.
#[cfg(test)]
pub fn from_be_bytes_for_test_only<M>(
input: untrusted::Input,
p: &Modulus<M>,
) -> Result<Self, error::Unspecified> {
use crate::limb::LIMB_BYTES;
// Do exactly what `from_be_bytes_padded` does for any inputs it accepts.
if let r @ Ok(_) = Self::from_be_bytes_padded(input, p) {
return r;
}
let num_limbs = (input.len() + LIMB_BYTES - 1) / LIMB_BYTES;
let mut limbs = BoxedLimbs::<M>::zero(num_limbs);
limb::parse_big_endian_and_pad_consttime(input, &mut limbs)
.map_err(|error::Unspecified| error::KeyRejected::unexpected_error())?;
limbs.reverse();
Ok(Self {
limbs: limbs.into_limbs(),
})
}
#[inline]
pub(super) fn limbs(&self) -> &[Limb] {
&self.limbs
}
}
+27
View File
@@ -0,0 +1,27 @@
use crate::limb::LeakyLimb;
use core::mem::size_of;
const fn parse_digit(d: u8) -> u8 {
match d.to_ascii_lowercase() {
b'0'..=b'9' => d - b'0',
b'a'..=b'f' => d - b'a' + 10,
_ => panic!(),
}
}
// TODO: this would be nicer as a trait, but currently traits don't support const functions
pub const fn limbs_from_hex<const LIMBS: usize>(hex: &str) -> [LeakyLimb; LIMBS] {
let hex = hex.as_bytes();
let mut limbs = [0; LIMBS];
let limb_nibbles = size_of::<LeakyLimb>() * 2;
let mut i = 0;
while i < hex.len() {
let char = hex[hex.len() - 1 - i];
let val = parse_digit(char);
limbs[i / limb_nibbles] |= (val as LeakyLimb) << ((i % limb_nibbles) * 4);
i += 1;
}
limbs
}
+97
View File
@@ -0,0 +1,97 @@
// Copyright 2024-2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::{inout::AliasingSlices3, n0::N0, LimbSliceError, MAX_LIMBS, MIN_LIMBS};
use crate::{c, limb::Limb, polyfill::usize_from_u32};
use core::{mem::size_of, num::NonZeroUsize};
const _MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES: () = {
// BoringSSL's limit: 8 kiloBYTES.
const BN_MONTGOMERY_MAX_WORDS: usize = (8 * 1092) / size_of::<Limb>();
assert!(MAX_LIMBS <= BN_MONTGOMERY_MAX_WORDS);
// Some 64-bit assembly implementations were written to take `len` as a
// `c_int`, so they zero out the undefined top half of `len` to convert it
// to a `usize`. But, others don't.
assert!(MAX_LIMBS <= usize_from_u32(u32::MAX));
};
macro_rules! bn_mul_mont_ffi {
( $in_out:expr, $n:expr, $n0:expr, $cpu:expr,
unsafe { ($MIN_LEN:expr, $MOD_LEN:expr, $Cpu:ty) => $f:ident }) => {{
use crate::{c, limb::Limb};
prefixed_extern! {
// `r` and/or 'a' and/or 'b' may alias.
// XXX: BoringSSL declares these functions to return `int`.
fn $f(
r: *mut Limb,
a: *const Limb,
b: *const Limb,
n: *const Limb,
n0: &N0,
len: c::NonZero_size_t,
);
}
unsafe {
crate::arithmetic::ffi::bn_mul_mont_ffi::<$Cpu, { $MIN_LEN }, { $MOD_LEN }>(
$in_out, $n, $n0, $cpu, $f,
)
}
}};
}
#[inline]
pub(super) unsafe fn bn_mul_mont_ffi<Cpu, const LEN_MIN: usize, const LEN_MOD: usize>(
in_out: impl AliasingSlices3<Limb>,
n: &[Limb],
n0: &N0,
cpu: Cpu,
f: unsafe extern "C" fn(
r: *mut Limb,
a: *const Limb,
b: *const Limb,
n: *const Limb,
n0: &N0,
len: c::NonZero_size_t,
),
) -> Result<(), LimbSliceError> {
assert_eq!(n.len() % LEN_MOD, 0); // The caller should guard against this.
/// The x86 implementation of `bn_mul_mont`, at least, requires at least 4
/// limbs. For a long time we have required 4 limbs for all targets, though
/// this may be unnecessary.
const _MIN_LIMBS_AT_LEAST_4: () = assert!(MIN_LIMBS >= 4);
// We haven't tested shorter lengths.
assert!(LEN_MIN >= MIN_LIMBS);
if n.len() < LEN_MIN {
return Err(LimbSliceError::too_short(n.len()));
}
let len = NonZeroUsize::new(n.len()).unwrap_or_else(|| {
// Unreachable because we checked against `LEN_MIN`, and we checked
// `LEN_MIN` is nonzero.
unreachable!()
});
// Avoid stack overflow from the alloca inside.
if len.get() > MAX_LIMBS {
return Err(LimbSliceError::too_long(n.len()));
}
in_out
.with_non_dangling_non_null_pointers_rab(len, |r, a, b| {
let n = n.as_ptr();
let _: Cpu = cpu;
unsafe { f(r, a, b, n, n0, len) };
})
.map_err(LimbSliceError::len_mismatch)
}
+177
View File
@@ -0,0 +1,177 @@
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
pub(crate) use crate::error::LenMismatchError;
use core::num::NonZeroUsize;
pub(crate) trait AliasingSlices2<T> {
/// The pointers passed to `f` will be valid and non-null, and will not
/// be dangling, so they can be passed to C functions.
///
/// The first pointer, `r`, may be pointing to uninitialized memory for
/// `expected_len` elements of type `T`, properly aligned and writable.
/// `f` must not read from `r` before writing to it.
///
/// The second & third pointers, `a` and `b`, point to `expected_len`
/// values of type `T`, properly aligned.
///
/// `r`, `a`, and/or `b` may alias each other only in the following ways:
/// `ptr::eq(r, a)`, `ptr::eq(r, b)`, and/or `ptr::eq(a, b)`; i.e. they
/// will not be "overlapping."
///
/// Implementations of this trait shouldn't override this default
/// implementation.
#[inline(always)]
fn with_non_dangling_non_null_pointers_ra<R>(
self,
expected_len: NonZeroUsize,
f: impl FnOnce(*mut T, *const T) -> R,
) -> Result<R, LenMismatchError>
where
Self: Sized,
{
self.with_potentially_dangling_non_null_pointers_ra(expected_len.get(), f)
}
/// If `expected_len == 0` then the pointers passed to `f` may be
/// dangling pointers, which should not be passed to C functions. In all
/// other respects, this works like
/// `Self::with_non_dangling_non_null_pointers_rab`.
///
/// Implementations of this trait should implement this method and not
/// `with_non_dangling_non_null_pointers_rab`. Users of this trait should
/// use `with_non_dangling_non_null_pointers_rab` and not this.
fn with_potentially_dangling_non_null_pointers_ra<R>(
self,
expected_len: usize,
f: impl FnOnce(*mut T, *const T) -> R,
) -> Result<R, LenMismatchError>;
}
impl<T> AliasingSlices2<T> for &mut [T] {
fn with_potentially_dangling_non_null_pointers_ra<R>(
self,
expected_len: usize,
f: impl FnOnce(*mut T, *const T) -> R,
) -> Result<R, LenMismatchError> {
let r = self;
if r.len() != expected_len {
return Err(LenMismatchError::new(r.len()));
}
Ok(f(r.as_mut_ptr(), r.as_ptr()))
}
}
impl<T> AliasingSlices2<T> for (&mut [T], &[T]) {
fn with_potentially_dangling_non_null_pointers_ra<R>(
self,
expected_len: usize,
f: impl FnOnce(*mut T, *const T) -> R,
) -> Result<R, LenMismatchError> {
let (r, a) = self;
if r.len() != expected_len {
return Err(LenMismatchError::new(r.len()));
}
if a.len() != expected_len {
return Err(LenMismatchError::new(a.len()));
}
Ok(f(r.as_mut_ptr(), a.as_ptr()))
}
}
pub(crate) trait AliasingSlices3<T> {
/// The pointers passed to `f` will all be non-null and properly aligned,
/// and will not be dangling.
///
/// The first pointer, `r` points to potentially-uninitialized writable
/// space for `expected_len` elements of type `T`. Accordingly, `f` must
/// not read from `r` before writing to it.
///
/// The second & third pointers, `a` and `b`, point to `expected_len`
/// initialized values of type `T`.
///
/// `r`, `a`, and/or `b` may alias each other, but only in the following
/// ways: `ptr::eq(r, a)`, `ptr::eq(r, b)`, and/or `ptr::eq(a, b)`; they
/// will not be "overlapping."
///
/// Implementations of this trait shouldn't override this default
/// implementation.
#[inline(always)]
fn with_non_dangling_non_null_pointers_rab<R>(
self,
expected_len: NonZeroUsize,
f: impl FnOnce(*mut T, *const T, *const T) -> R,
) -> Result<R, LenMismatchError>
where
Self: Sized,
{
self.with_potentially_dangling_non_null_pointers_rab(expected_len.get(), f)
}
/// If `expected_len == 0` then the pointers passed to `f` may be
/// dangling pointers, which should not be passed to C functions. In all
/// other respects, this works like
/// `Self::with_non_dangling_non_null_pointers_rab`.
///
/// Implementations of this trait should implement this method and not
/// `with_non_dangling_non_null_pointers_rab`. Users of this trait should
/// use `with_non_dangling_non_null_pointers_rab` and not this.
fn with_potentially_dangling_non_null_pointers_rab<R>(
self,
expected_len: usize,
f: impl FnOnce(*mut T, *const T, *const T) -> R,
) -> Result<R, LenMismatchError>;
}
impl<T> AliasingSlices3<T> for &mut [T] {
fn with_potentially_dangling_non_null_pointers_rab<R>(
self,
expected_len: usize,
f: impl FnOnce(*mut T, *const T, *const T) -> R,
) -> Result<R, LenMismatchError> {
<Self as AliasingSlices2<T>>::with_potentially_dangling_non_null_pointers_ra(
self,
expected_len,
|r, a| f(r, r, a),
)
}
}
impl<T> AliasingSlices3<T> for (&mut [T], &[T], &[T]) {
fn with_potentially_dangling_non_null_pointers_rab<R>(
self,
expected_len: usize,
f: impl FnOnce(*mut T, *const T, *const T) -> R,
) -> Result<R, LenMismatchError> {
let (r, a, b) = self;
((r, a), b).with_potentially_dangling_non_null_pointers_rab(expected_len, f)
}
}
impl<RA, T> AliasingSlices3<T> for (RA, &[T])
where
RA: AliasingSlices2<T>,
{
fn with_potentially_dangling_non_null_pointers_rab<R>(
self,
expected_len: usize,
f: impl FnOnce(*mut T, *const T, *const T) -> R,
) -> Result<R, LenMismatchError> {
let (ra, b) = self;
if b.len() != expected_len {
return Err(LenMismatchError::new(b.len()));
}
ra.with_potentially_dangling_non_null_pointers_ra(expected_len, |r, a| f(r, a, b.as_ptr()))
}
}
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
pub(in super::super) mod mont;
+59
View File
@@ -0,0 +1,59 @@
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
use super::super::super::{inout::AliasingSlices3 as _, n0::N0, LimbSliceError, MAX_LIMBS};
use crate::{
c,
limb::Limb,
polyfill::slice::{AsChunks, AsChunksMut},
};
use core::num::NonZeroUsize;
#[inline]
pub(in super::super::super) fn sqr_mont5(
mut in_out: AsChunksMut<Limb, 8>,
n: AsChunks<Limb, 8>,
n0: &N0,
) -> Result<(), LimbSliceError> {
prefixed_extern! {
// `r` and/or 'a' may alias.
// XXX: BoringSSL (kinda, implicitly) declares this to return `int`.
// `num` must be a non-zero multiple of 8.
fn bn_sqr8x_mont(
rp: *mut Limb,
ap: *const Limb,
ap_again: *const Limb,
np: *const Limb,
n0: &N0,
num: c::NonZero_size_t);
}
let in_out = in_out.as_flattened_mut();
let n = n.as_flattened();
let num_limbs = NonZeroUsize::new(n.len()).ok_or_else(|| LimbSliceError::too_short(n.len()))?;
// Avoid stack overflow from the alloca inside.
if num_limbs.get() > MAX_LIMBS {
return Err(LimbSliceError::too_long(num_limbs.get()));
}
in_out
.with_non_dangling_non_null_pointers_rab(num_limbs, |r, a, a_again| {
let n = n.as_ptr(); // Non-dangling because num_limbs > 0.
unsafe { bn_sqr8x_mont(r, a, a_again, n, n0, num_limbs) };
})
.map_err(LimbSliceError::len_mismatch)
}
+16
View File
@@ -0,0 +1,16 @@
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
pub(super) mod aarch64;
pub(super) mod x86_64;
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#![cfg(target_arch = "x86_64")]
pub(in super::super::super) mod mont;
+312
View File
@@ -0,0 +1,312 @@
// Copyright 2015-2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#![cfg(target_arch = "x86_64")]
use super::super::super::{
inout::{AliasingSlices2, AliasingSlices3},
n0::N0,
LimbSliceError, MAX_LIMBS,
};
use crate::{
c,
cpu::intel::{Adx, Bmi1, Bmi2},
error::LenMismatchError,
limb::{LeakyWindow, Limb, Window},
polyfill::slice::{AsChunks, AsChunksMut},
};
use core::num::NonZeroUsize;
const _512_IS_LIMB_BITS_TIMES_8: () = assert!(8 * Limb::BITS == 512);
#[inline]
pub(in super::super::super) fn mul_mont5(
mut r: AsChunksMut<Limb, 8>,
a: AsChunks<Limb, 8>,
b: AsChunks<Limb, 8>,
m: AsChunks<Limb, 8>,
n0: &N0,
maybe_adx_bmi2: Option<(Adx, Bmi2)>,
) -> Result<(), LimbSliceError> {
mul_mont5_4x(
(r.as_flattened_mut(), a.as_flattened(), b.as_flattened()),
m.into(),
n0,
maybe_adx_bmi2,
)
}
pub const MIN_4X: usize = 8;
#[inline]
pub(in super::super::super) fn mul_mont5_4x(
in_out: impl AliasingSlices3<Limb>,
n: AsChunks<Limb, 4>,
n0: &N0,
maybe_adx_bmi2: Option<(Adx, Bmi2)>,
) -> Result<(), LimbSliceError> {
const MOD_4X: usize = 4;
let n = n.as_flattened();
if let Some(cpu) = maybe_adx_bmi2 {
bn_mul_mont_ffi!(in_out, n, n0, cpu, unsafe {
(MIN_4X, MOD_4X, (Adx, Bmi2)) => bn_mulx4x_mont
})
} else {
bn_mul_mont_ffi!(in_out, n, n0, (), unsafe {
(MIN_4X, MOD_4X, ()) => bn_mul4x_mont
})
}
}
#[inline]
pub(in super::super::super) fn sqr_mont5(
mut in_out: AsChunksMut<Limb, 8>,
n: AsChunks<Limb, 8>,
n0: &N0,
maybe_adx_bmi2: Option<(Adx, Bmi2)>,
) -> Result<(), LimbSliceError> {
prefixed_extern! {
// `r` and/or 'a' may alias.
// XXX: BoringSSL declares this to return `int`.
// `num` must be a non-zero multiple of 8.
fn bn_sqr8x_mont(
rp: *mut Limb,
ap: *const Limb,
mulx_adx_capable: Limb,
np: *const Limb,
n0: &N0,
num: c::NonZero_size_t);
}
let in_out = in_out.as_flattened_mut();
let n = n.as_flattened();
let num_limbs = NonZeroUsize::new(n.len()).ok_or_else(|| LimbSliceError::too_short(n.len()))?;
// Avoid stack overflow from the alloca inside.
if num_limbs.get() > MAX_LIMBS {
return Err(LimbSliceError::too_long(num_limbs.get()));
}
// `Limb::from(mulx_adx.is_some())`, but intentionally branchy.
let mulx_adx_capable = match maybe_adx_bmi2 {
Some(_) => Limb::from(true),
None => Limb::from(false),
};
in_out
.with_non_dangling_non_null_pointers_ra(num_limbs, |r, a| {
let n = n.as_ptr(); // Non-dangling because num_limbs > 0.
unsafe { bn_sqr8x_mont(r, a, mulx_adx_capable, n, n0, num_limbs) };
})
.map_err(LimbSliceError::len_mismatch)
}
#[inline(always)]
pub(in super::super::super) fn scatter5(
a: AsChunks<Limb, 8>,
mut table: AsChunksMut<Limb, 8>,
power: LeakyWindow,
) -> Result<(), LimbSliceError> {
prefixed_extern! {
// Upstream uses `num: c::size_t` too, and `power: c::size_t`; see
// `_MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES`.
fn bn_scatter5(
inp: *const Limb,
num: c::NonZero_size_t,
table: *mut Limb,
power: LeakyWindow,
);
}
let num_limbs = check_common(a, table.as_ref())?;
let a = a.as_flattened();
let table = table.as_flattened_mut();
assert!(power < 32);
unsafe { bn_scatter5(a.as_ptr(), num_limbs, table.as_mut_ptr(), power) };
Ok(())
}
// SAFETY: `power` must be less than 32.
#[inline(always)]
pub(in super::super::super) unsafe fn gather5(
mut r: AsChunksMut<Limb, 8>,
table: AsChunks<Limb, 8>,
power: Window,
) -> Result<(), LimbSliceError> {
prefixed_extern! {
// Upstream uses `num: c::size_t` too, and `power: c::size_t`; see
// `_MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES`.
fn bn_gather5(
out: *mut Limb,
num: c::NonZero_size_t,
table: *const Limb,
power: Window);
}
let num_limbs = check_common(r.as_ref(), table)?;
let r = r.as_flattened_mut();
let table = table.as_flattened();
// SAFETY: We cannot assert that `power` is in range because it is secret.
// TODO: Create a `Window5` type that is guaranteed to be in range.
unsafe { bn_gather5(r.as_mut_ptr(), num_limbs, table.as_ptr(), power) };
Ok(())
}
// SAFETY: `power` must be less than 32.
#[inline(always)]
pub(in super::super::super) unsafe fn mul_mont_gather5_amm(
mut r: AsChunksMut<Limb, 8>,
a: AsChunks<Limb, 8>,
table: AsChunks<Limb, 8>,
n: AsChunks<Limb, 8>,
n0: &N0,
power: Window,
maybe_adx_bmi1_bmi2: Option<(Adx, Bmi1, Bmi2)>,
) -> Result<(), LimbSliceError> {
prefixed_extern! {
// Upstream has `num: c_int` and `power: c_int`; see
// `_MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES`.
fn bn_mul4x_mont_gather5(
rp: *mut Limb,
ap: *const Limb,
table: *const Limb,
np: *const Limb,
n0: &N0,
num: c::NonZero_size_t,
power: Window,
);
// Upstream has `num: c_int` and `power: c_int`; see
// `_MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES`.
fn bn_mulx4x_mont_gather5(
rp: *mut Limb,
ap: *const Limb,
table: *const Limb,
np: *const Limb,
n0: &N0,
num: c::NonZero_size_t,
power: Window,
);
}
let num_limbs = check_common_with_n(r.as_ref(), table, n)?;
let a = a.as_flattened();
if a.len() != num_limbs.get() {
return Err(LimbSliceError::len_mismatch(LenMismatchError::new(a.len())));
}
let r = r.as_flattened_mut();
let r = r.as_mut_ptr();
let a = a.as_ptr();
let table = table.as_flattened();
let table = table.as_ptr();
let n = n.as_flattened();
let n = n.as_ptr();
// SAFETY: We cannot assert that `power` is in range because it is secret.
// TODO: Create a `Window5` type that is guaranteed to be in range.
if maybe_adx_bmi1_bmi2.is_some() {
unsafe { bn_mulx4x_mont_gather5(r, a, table, n, n0, num_limbs, power) }
} else {
unsafe { bn_mul4x_mont_gather5(r, a, table, n, n0, num_limbs, power) }
};
Ok(())
}
// SAFETY: `power` must be less than 32.
#[inline(always)]
pub(in super::super::super) unsafe fn power5_amm(
mut in_out: AsChunksMut<Limb, 8>,
table: AsChunks<Limb, 8>,
n: AsChunks<Limb, 8>,
n0: &N0,
power: Window,
maybe_adx_bmi1_bmi2: Option<(Adx, Bmi1, Bmi2)>,
) -> Result<(), LimbSliceError> {
prefixed_extern! {
// Upstream has `num: c_int` and `power: c_int`; see
// `_MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES`.
fn bn_power5_nohw(
rp: *mut Limb,
ap: *const Limb,
table: *const Limb,
np: *const Limb,
n0: &N0,
num: c::NonZero_size_t,
power: Window,
);
// Upstream has `num: c_int` and `power: c_int`; see
// `_MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES`.
fn bn_powerx5(
rp: *mut Limb,
ap: *const Limb,
table: *const Limb,
np: *const Limb,
n0: &N0,
num: c::NonZero_size_t,
power: Window,
);
}
let num_limbs = check_common_with_n(in_out.as_ref(), table, n)?;
let in_out = in_out.as_flattened_mut();
let r = in_out.as_mut_ptr();
let a = in_out.as_ptr();
let table = table.as_flattened();
let table = table.as_ptr();
let n = n.as_flattened();
let n = n.as_ptr();
// SAFETY: We cannot assert that `power` is in range because it is secret.
// TODO: Create a `Window5` type that is guaranteed to be in range.
if maybe_adx_bmi1_bmi2.is_some() {
unsafe { bn_powerx5(r, a, table, n, n0, num_limbs, power) }
} else {
unsafe { bn_power5_nohw(r, a, table, n, n0, num_limbs, power) }
};
Ok(())
}
// Helps the compiler will be able to hoist all of these checks out of the
// loops in the caller. Try to help the compiler by doing the checks
// consistently in each function and also by inlining this function and all the
// callers.
#[inline(always)]
fn check_common(
a: AsChunks<Limb, 8>,
table: AsChunks<Limb, 8>,
) -> Result<NonZeroUsize, LimbSliceError> {
assert_eq!((table.as_ptr() as usize) % 16, 0); // According to BoringSSL.
let a = a.as_flattened();
let table = table.as_flattened();
let num_limbs = NonZeroUsize::new(a.len()).ok_or_else(|| LimbSliceError::too_short(a.len()))?;
if num_limbs.get() > MAX_LIMBS {
return Err(LimbSliceError::too_long(a.len()));
}
if num_limbs.get() * 32 != table.len() {
return Err(LimbSliceError::len_mismatch(LenMismatchError::new(
table.len(),
)));
};
Ok(num_limbs)
}
#[inline(always)]
fn check_common_with_n(
a: AsChunks<Limb, 8>,
table: AsChunks<Limb, 8>,
n: AsChunks<Limb, 8>,
) -> Result<NonZeroUsize, LimbSliceError> {
// Choose `a` instead of `n` so that every function starts with
// `check_common` passing the exact same arguments, so that the compiler
// can easily de-dupe the checks.
let num_limbs = check_common(a, table)?;
let n = n.as_flattened();
if n.len() != num_limbs.get() {
return Err(LimbSliceError::len_mismatch(LenMismatchError::new(n.len())));
}
Ok(num_limbs)
}
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
mod storage;
pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
+60
View File
@@ -0,0 +1,60 @@
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::{
error::LenMismatchError,
limb::{Limb, LIMB_BITS},
polyfill::slice::{self, AsChunksMut},
};
use core::mem::{align_of, size_of};
// Some x86_64 assembly is written under the assumption that some of its
// input data and/or temporary storage is aligned to `MOD_EXP_CTIME_ALIGN`
// bytes, which was/is 64 in OpenSSL.
//
// We use this in the non-X86-64 implementation of exponentiation as well,
// with the hope of converging th two implementations into one.
#[repr(C, align(64))]
pub struct AlignedStorage<const N: usize>([Limb; N]);
const _LIMB_SIZE_DIVIDES_ALIGNMENT: () =
assert!(align_of::<AlignedStorage<1>>() % size_of::<Limb>() == 0);
pub const LIMBS_PER_CHUNK: usize = 512 / LIMB_BITS;
impl<const N: usize> AlignedStorage<N> {
pub fn zeroed() -> Self {
assert_eq!(N % LIMBS_PER_CHUNK, 0); // TODO: const.
Self([0; N])
}
// The result will have every chunk aligned on a 64 byte boundary.
pub fn aligned_chunks_mut(
&mut self,
num_entries: usize,
chunks_per_entry: usize,
) -> Result<AsChunksMut<Limb, LIMBS_PER_CHUNK>, LenMismatchError> {
let total_limbs = num_entries * chunks_per_entry * LIMBS_PER_CHUNK;
let len = self.0.len();
let flattened = self
.0
.get_mut(..total_limbs)
.ok_or_else(|| LenMismatchError::new(len))?;
match slice::as_chunks_mut(flattened) {
(chunks, []) => Ok(chunks),
(_, r) => Err(LenMismatchError::new(r.len())),
}
}
}
+384
View File
@@ -0,0 +1,384 @@
// Copyright 2017-2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
pub use super::n0::N0;
use super::{inout::AliasingSlices3, LimbSliceError, MIN_LIMBS};
use crate::cpu;
use cfg_if::cfg_if;
// Indicates that the element is not encoded; there is no *R* factor
// that needs to be canceled out.
#[derive(Copy, Clone)]
pub enum Unencoded {}
// Indicates that the element is encoded; the value has one *R*
// factor that needs to be canceled out.
#[derive(Copy, Clone)]
pub enum R {}
// Indicates the element is encoded three times; the value has three
// *R* factors that need to be canceled out.
#[allow(clippy::upper_case_acronyms)]
#[derive(Copy, Clone)]
pub enum RRR {}
// Indicates the element is encoded twice; the value has two *R*
// factors that need to be canceled out.
#[derive(Copy, Clone)]
pub enum RR {}
// Indicates the element is inversely encoded; the value has one
// 1/*R* factor that needs to be canceled out.
#[derive(Copy, Clone)]
pub enum RInverse {}
pub trait Encoding {}
impl Encoding for RRR {}
impl Encoding for RR {}
impl Encoding for R {}
impl Encoding for Unencoded {}
impl Encoding for RInverse {}
/// The encoding of the result of a reduction.
pub trait ReductionEncoding {
type Output: Encoding;
}
impl ReductionEncoding for RRR {
type Output = RR;
}
impl ReductionEncoding for RR {
type Output = R;
}
impl ReductionEncoding for R {
type Output = Unencoded;
}
impl ReductionEncoding for Unencoded {
type Output = RInverse;
}
/// The encoding of the result of a multiplication.
pub trait ProductEncoding {
type Output: Encoding;
}
impl<E: ReductionEncoding> ProductEncoding for (Unencoded, E) {
type Output = E::Output;
}
impl<E: Encoding> ProductEncoding for (R, E) {
type Output = E;
}
impl ProductEncoding for (RR, RR) {
type Output = RRR;
}
impl<E: ReductionEncoding> ProductEncoding for (RInverse, E)
where
E::Output: ReductionEncoding,
{
type Output = <<E as ReductionEncoding>::Output as ReductionEncoding>::Output;
}
// XXX: Rust doesn't allow overlapping impls,
// TODO (if/when Rust allows it):
// impl<E1, E2: ReductionEncoding> ProductEncoding for
// (E1, E2) {
// type Output = <(E2, E1) as ProductEncoding>::Output;
// }
impl ProductEncoding for (RR, Unencoded) {
type Output = <(Unencoded, RR) as ProductEncoding>::Output;
}
impl ProductEncoding for (RR, RInverse) {
type Output = <(RInverse, RR) as ProductEncoding>::Output;
}
impl ProductEncoding for (RRR, RInverse) {
type Output = <(RInverse, RRR) as ProductEncoding>::Output;
}
#[allow(unused_imports)]
use crate::{bssl, c, limb::Limb};
#[inline(always)]
pub(super) fn limbs_mul_mont(
in_out: impl AliasingSlices3<Limb>,
n: &[Limb],
n0: &N0,
cpu: cpu::Features,
) -> Result<(), LimbSliceError> {
const MOD_FALLBACK: usize = 1; // No restriction.
cfg_if! {
if #[cfg(all(target_arch = "aarch64", target_endian = "little"))] {
let _: cpu::Features = cpu;
const MIN_4X: usize = 4;
const MOD_4X: usize = 4;
if n.len() >= MIN_4X && n.len() % MOD_4X == 0 {
bn_mul_mont_ffi!(in_out, n, n0, (), unsafe {
(MIN_4X, MOD_4X, ()) => bn_mul4x_mont
})
} else {
bn_mul_mont_ffi!(in_out, n, n0, (), unsafe {
(MIN_LIMBS, MOD_FALLBACK, ()) => bn_mul_mont_nohw
})
}
} else if #[cfg(all(target_arch = "arm", target_endian = "little"))] {
const MIN_8X: usize = 8;
const MOD_8X: usize = 8;
if n.len() >= MIN_8X && n.len() % MOD_8X == 0 {
use crate::cpu::{GetFeature as _, arm::Neon};
if let Some(cpu) = cpu.get_feature() {
return bn_mul_mont_ffi!(in_out, n, n0, cpu, unsafe {
(MIN_8X, MOD_8X, Neon) => bn_mul8x_mont_neon
});
}
}
// The ARM version of `bn_mul_mont_nohw` has a minimum of 2.
const _MIN_LIMBS_AT_LEAST_2: () = assert!(MIN_LIMBS >= 2);
bn_mul_mont_ffi!(in_out, n, n0, (), unsafe {
(MIN_LIMBS, MOD_FALLBACK, ()) => bn_mul_mont_nohw
})
} else if #[cfg(target_arch = "x86")] {
use crate::{cpu::GetFeature as _, cpu::intel::Sse2};
// The X86 implementation of `bn_mul_mont` has a minimum of 4.
const _MIN_LIMBS_AT_LEAST_4: () = assert!(MIN_LIMBS >= 4);
if let Some(cpu) = cpu.get_feature() {
bn_mul_mont_ffi!(in_out, n, n0, cpu, unsafe {
(MIN_LIMBS, MOD_FALLBACK, Sse2) => bn_mul_mont
})
} else {
// This isn't really an FFI call; it's defined below.
unsafe {
super::ffi::bn_mul_mont_ffi::<(), {MIN_LIMBS}, 1>(in_out, n, n0, (),
bn_mul_mont_fallback)
}
}
} else if #[cfg(target_arch = "x86_64")] {
use crate::{cpu::GetFeature as _, polyfill::slice};
use super::limbs::x86_64;
if n.len() >= x86_64::mont::MIN_4X {
if let (n, []) = slice::as_chunks(n) {
return x86_64::mont::mul_mont5_4x(in_out, n, n0, cpu.get_feature());
}
}
bn_mul_mont_ffi!(in_out, n, n0, (), unsafe {
(MIN_LIMBS, MOD_FALLBACK, ()) => bn_mul_mont_nohw
})
} else {
// Use the fallback implementation implemented below through the
// FFI wrapper defined below, so that Rust and C code both go
// through `bn_mul_mont`.
bn_mul_mont_ffi!(in_out, n, n0, cpu, unsafe {
(MIN_LIMBS, MOD_FALLBACK, cpu::Features) => bn_mul_mont
})
}
}
}
cfg_if! {
if #[cfg(not(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86_64")))] {
// TODO: Stop calling this from C and un-export it.
#[cfg(not(target_arch = "x86"))]
prefixed_export! {
unsafe extern "C" fn bn_mul_mont(
r: *mut Limb,
a: *const Limb,
b: *const Limb,
n: *const Limb,
n0: &N0,
num_limbs: c::NonZero_size_t,
) {
unsafe { bn_mul_mont_fallback(r, a, b, n, n0, num_limbs) }
}
}
#[cfg_attr(target_arch = "x86", cold)]
#[cfg_attr(target_arch = "x86", inline(never))]
unsafe extern "C" fn bn_mul_mont_fallback(
r: *mut Limb,
a: *const Limb,
b: *const Limb,
n: *const Limb,
n0: &N0,
num_limbs: c::NonZero_size_t,
) {
use super::MAX_LIMBS;
let num_limbs = num_limbs.get();
// The mutable pointer `r` may alias `a` and/or `b`, so the lifetimes of
// any slices for `a` or `b` must not overlap with the lifetime of any
// mutable for `r`.
// Nothing aliases `n`
let n = unsafe { core::slice::from_raw_parts(n, num_limbs) };
let mut tmp = [0; 2 * MAX_LIMBS];
let tmp = &mut tmp[..(2 * num_limbs)];
{
let a: &[Limb] = unsafe { core::slice::from_raw_parts(a, num_limbs) };
let b: &[Limb] = unsafe { core::slice::from_raw_parts(b, num_limbs) };
limbs_mul(tmp, a, b);
}
let r: &mut [Limb] = unsafe { core::slice::from_raw_parts_mut(r, num_limbs) };
limbs_from_mont_in_place(r, tmp, n, n0);
}
}
}
// `bigint` needs then when the `alloc` feature is enabled. `bn_mul_mont` above needs this when
// we are using the platforms for which we don't have `bn_mul_mont` in assembly.
#[cfg(any(
feature = "alloc",
not(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86_64"
))
))]
pub(super) fn limbs_from_mont_in_place(r: &mut [Limb], tmp: &mut [Limb], m: &[Limb], n0: &N0) {
prefixed_extern! {
fn bn_from_montgomery_in_place(
r: *mut Limb,
num_r: c::size_t,
a: *mut Limb,
num_a: c::size_t,
n: *const Limb,
num_n: c::size_t,
n0: &N0,
) -> bssl::Result;
}
Result::from(unsafe {
bn_from_montgomery_in_place(
r.as_mut_ptr(),
r.len(),
tmp.as_mut_ptr(),
tmp.len(),
m.as_ptr(),
m.len(),
n0,
)
})
.unwrap()
}
#[cfg(not(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86_64"
)))]
fn limbs_mul(r: &mut [Limb], a: &[Limb], b: &[Limb]) {
debug_assert_eq!(r.len(), 2 * a.len());
debug_assert_eq!(a.len(), b.len());
let ab_len = a.len();
r[..ab_len].fill(0);
for (i, &b_limb) in b.iter().enumerate() {
r[ab_len + i] = unsafe {
limbs_mul_add_limb(r[i..][..ab_len].as_mut_ptr(), a.as_ptr(), b_limb, ab_len)
};
}
}
#[cfg(any(
test,
not(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86_64",
))
))]
prefixed_extern! {
// `r` must not alias `a`
#[must_use]
fn limbs_mul_add_limb(r: *mut Limb, a: *const Limb, b: Limb, num_limbs: c::size_t) -> Limb;
}
/// r = r**2
pub(super) fn limbs_square_mont(
r: &mut [Limb],
n: &[Limb],
n0: &N0,
cpu: cpu::Features,
) -> Result<(), LimbSliceError> {
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
{
use super::limbs::aarch64;
use crate::polyfill::slice;
if let ((r, []), (n, [])) = (slice::as_chunks_mut(r), slice::as_chunks(n)) {
return aarch64::mont::sqr_mont5(r, n, n0);
}
}
#[cfg(target_arch = "x86_64")]
{
use super::limbs::x86_64;
use crate::{cpu::GetFeature as _, polyfill::slice};
if let ((r, []), (n, [])) = (slice::as_chunks_mut(r), slice::as_chunks(n)) {
return x86_64::mont::sqr_mont5(r, n, n0, cpu.get_feature());
}
}
limbs_mul_mont(r, n, n0, cpu)
}
#[cfg(test)]
mod tests {
use super::super::MAX_LIMBS;
use super::*;
use crate::limb::Limb;
#[test]
// TODO: wasm
fn test_mul_add_words() {
const ZERO: Limb = 0;
const MAX: Limb = ZERO.wrapping_sub(1);
static TEST_CASES: &[(&[Limb], &[Limb], Limb, Limb, &[Limb])] = &[
(&[0], &[0], 0, 0, &[0]),
(&[MAX], &[0], MAX, 0, &[MAX]),
(&[0], &[MAX], MAX, MAX - 1, &[1]),
(&[MAX], &[MAX], MAX, MAX, &[0]),
(&[0, 0], &[MAX, MAX], MAX, MAX - 1, &[1, MAX]),
(&[1, 0], &[MAX, MAX], MAX, MAX - 1, &[2, MAX]),
(&[MAX, 0], &[MAX, MAX], MAX, MAX, &[0, 0]),
(&[0, 1], &[MAX, MAX], MAX, MAX, &[1, 0]),
(&[MAX, MAX], &[MAX, MAX], MAX, MAX, &[0, MAX]),
];
for (i, (r_input, a, w, expected_retval, expected_r)) in TEST_CASES.iter().enumerate() {
let mut r = [0; MAX_LIMBS];
let r = {
let r = &mut r[..r_input.len()];
r.copy_from_slice(r_input);
r
};
assert_eq!(r.len(), a.len()); // Sanity check
let actual_retval =
unsafe { limbs_mul_add_limb(r.as_mut_ptr(), a.as_ptr(), *w, a.len()) };
assert_eq!(&r, expected_r, "{}: {:x?} != {:x?}", i, r, expected_r);
assert_eq!(
actual_retval, *expected_retval,
"{}: {:x?} != {:x?}",
i, actual_retval, *expected_retval
);
}
}
}
+37
View File
@@ -0,0 +1,37 @@
// Copyright 2015-2022 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::limb::Limb;
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct N0([Limb; 2]);
impl N0 {
#[cfg(feature = "alloc")]
pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
#[inline]
pub const fn precalculated(n0: u64) -> Self {
#[cfg(target_pointer_width = "64")]
{
Self([n0, 0])
}
#[cfg(target_pointer_width = "32")]
{
Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
}
}
}