ring/arithmetic/ffi.rs
1// Copyright 2024-2025 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15use super::{inout::AliasingSlices3, n0::N0, LimbSliceError, MAX_LIMBS, MIN_LIMBS};
16use crate::{c, limb::Limb, polyfill::usize_from_u32};
17use core::{mem::size_of, num::NonZeroUsize};
18
19const _MAX_LIMBS_ADDRESSES_MEMORY_SAFETY_ISSUES: () = {
20 // BoringSSL's limit: 8 kiloBYTES.
21 const BN_MONTGOMERY_MAX_WORDS: usize = (8 * 1092) / size_of::<Limb>();
22 assert!(MAX_LIMBS <= BN_MONTGOMERY_MAX_WORDS);
23
24 // Some 64-bit assembly implementations were written to take `len` as a
25 // `c_int`, so they zero out the undefined top half of `len` to convert it
26 // to a `usize`. But, others don't.
27 assert!(MAX_LIMBS <= usize_from_u32(u32::MAX));
28};
29
30macro_rules! bn_mul_mont_ffi {
31 ( $in_out:expr, $n:expr, $n0:expr, $cpu:expr,
32 unsafe { ($MIN_LEN:expr, $MOD_LEN:expr, $Cpu:ty) => $f:ident }) => {{
33 use crate::{c, limb::Limb};
34 prefixed_extern! {
35 // `r` and/or 'a' and/or 'b' may alias.
36 // XXX: BoringSSL declares these functions to return `int`.
37 fn $f(
38 r: *mut Limb,
39 a: *const Limb,
40 b: *const Limb,
41 n: *const Limb,
42 n0: &N0,
43 len: c::NonZero_size_t,
44 );
45 }
46 unsafe {
47 crate::arithmetic::ffi::bn_mul_mont_ffi::<$Cpu, { $MIN_LEN }, { $MOD_LEN }>(
48 $in_out, $n, $n0, $cpu, $f,
49 )
50 }
51 }};
52}
53
54#[inline]
55pub(super) unsafe fn bn_mul_mont_ffi<Cpu, const LEN_MIN: usize, const LEN_MOD: usize>(
56 in_out: impl AliasingSlices3<Limb>,
57 n: &[Limb],
58 n0: &N0,
59 cpu: Cpu,
60 f: unsafe extern "C" fn(
61 r: *mut Limb,
62 a: *const Limb,
63 b: *const Limb,
64 n: *const Limb,
65 n0: &N0,
66 len: c::NonZero_size_t,
67 ),
68) -> Result<(), LimbSliceError> {
69 assert_eq!(n.len() % LEN_MOD, 0); // The caller should guard against this.
70
71 /// The x86 implementation of `bn_mul_mont`, at least, requires at least 4
72 /// limbs. For a long time we have required 4 limbs for all targets, though
73 /// this may be unnecessary.
74 const _MIN_LIMBS_AT_LEAST_4: () = assert!(MIN_LIMBS >= 4);
75 // We haven't tested shorter lengths.
76 assert!(LEN_MIN >= MIN_LIMBS);
77 if n.len() < LEN_MIN {
78 return Err(LimbSliceError::too_short(n.len()));
79 }
80 let len = NonZeroUsize::new(n.len()).unwrap_or_else(|| {
81 // Unreachable because we checked against `LEN_MIN`, and we checked
82 // `LEN_MIN` is nonzero.
83 unreachable!()
84 });
85
86 // Avoid stack overflow from the alloca inside.
87 if len.get() > MAX_LIMBS {
88 return Err(LimbSliceError::too_long(n.len()));
89 }
90 in_out
91 .with_non_dangling_non_null_pointers_rab(len, |r, a, b| {
92 let n = n.as_ptr();
93 let _: Cpu = cpu;
94 unsafe { f(r, a, b, n, n0, len) };
95 })
96 .map_err(LimbSliceError::len_mismatch)
97}