diff --git a/BUILDING.md b/BUILDING.md index 38c06ce27a..daeeaccb2e 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -67,13 +67,6 @@ e.g. export `CFLAGS=-D__ANDROID_API__=21`. Additional Features that are Useful for Development --------------------------------------------------- - -The `use_heap` feature enables functionality that uses the heap. This is on by -default. Disabling it is useful for code running in kernel space and some -embedded applications. For now some RSA, ECDH, and ECDSA signing functionality -still uses the heap. This feature will go away once RSA signing is the only -feature that uses the heap. - The `internal_benches` feature enable benchmarks of internal functions. These benchmarks are only useful for people hacking on the implementation of *ring*. (The benchmarks for the *ring* API are in the diff --git a/Cargo.toml b/Cargo.toml index 98cd19d0cd..62c90b88e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -325,12 +325,13 @@ cc = { version = "1.0.37", default-features = false } [features] # These features are documented in the top-level module's documentation. -default = ["use_heap", "dev_urandom_fallback"] -dev_urandom_fallback = ["use_heap", "lazy_static"] +default = ["alloc", "dev_urandom_fallback", "std"] +alloc = [] +dev_urandom_fallback = ["std", "lazy_static"] internal_benches = [] slow_tests = [] -test_logging = [] -use_heap = [] +std = ["alloc"] +test_logging = ["std"] # XXX: debug = false because of https://github.com/rust-lang/rust/issues/34122 diff --git a/STYLE.md b/STYLE.md index 601e8e9088..882b7f5d8b 100644 --- a/STYLE.md +++ b/STYLE.md @@ -88,7 +88,7 @@ The C code generally uses the C `int` type as a return value, where 1 indicates success and 0 indicates failure. The module [ring::bssl](src/bssl.rs) contains a [transparent] `Result` type which should be used as the return type when declaring foreign functions which follow this convention. A -`ring::bssl::Result` should be converted to a `std::result::Result` using the +`ring::bssl::Result` should be converted to a `core::result::Result` using the pattern in the following example (note the placement of `unsafe`): [transparent]: https://doc.rust-lang.org/nightly/reference/type-layout.html#the-transparent-representation diff --git a/src/aead/chacha.rs b/src/aead/chacha.rs index 56db5d4f25..23dc81bc30 100644 --- a/src/aead/chacha.rs +++ b/src/aead/chacha.rs @@ -142,8 +142,8 @@ pub const KEY_LEN: usize = KEY_BLOCKS * BLOCK_LEN; mod tests { use super::*; use crate::test; + use alloc::vec; use core::convert::TryInto; - use std::vec; // This verifies the encryption functionality provided by ChaCha20_ctr32 // is successful when either computed on disjoint input/output buffers, diff --git a/src/arithmetic.rs b/src/arithmetic.rs index 0bf0edbdbd..b8074f4f46 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -14,5 +14,8 @@ #[macro_use] pub mod constant; + +#[cfg(feature = "alloc")] pub mod bigint; + pub mod montgomery; diff --git a/src/arithmetic/bigint.rs b/src/arithmetic/bigint.rs index 1ab5ab46a1..5070bd3776 100644 --- a/src/arithmetic/bigint.rs +++ b/src/arithmetic/bigint.rs @@ -36,18 +36,16 @@ //! [Static checking of units in Servo]: //! https://blog.mozilla.org/research/2014/06/23/static-checking-of-units-in-servo/ -#![allow(box_pointers)] - use crate::{ arithmetic::montgomery::*, bits, bssl, c, error, limb::{self, Limb, LimbMask, LIMB_BITS, LIMB_BYTES}, }; +use alloc::{borrow::ToOwned as _, boxed::Box, vec, vec::Vec}; use core::{ marker::PhantomData, ops::{Deref, DerefMut}, }; -use std::{borrow::ToOwned as _, boxed::Box, vec, vec::Vec}; use untrusted; pub unsafe trait Prime {} @@ -1292,7 +1290,7 @@ extern "C" { mod tests { use super::*; use crate::test; - use std::format; + use alloc::format; use untrusted; // Type-level representation of an arbitrary modulus. diff --git a/src/bits.rs b/src/bits.rs index b2d4ca5774..b228466c6d 100644 --- a/src/bits.rs +++ b/src/bits.rs @@ -31,7 +31,7 @@ impl BitLength { Ok(Self::from_usize_bits(bits)) } - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] #[inline] pub fn half_rounded_up(&self) -> Self { let round_up = self.0 & 1; @@ -43,7 +43,7 @@ impl BitLength { self.0 } - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] #[inline] pub fn as_usize_bytes_rounded_up(&self) -> usize { // Equivalent to (self.0 + 7) / 8, except with no potential for @@ -55,7 +55,7 @@ impl BitLength { (self.0 / 8) + round_up } - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] #[inline] pub fn try_sub_1(self) -> Result { let sum = self.0.checked_sub(1).ok_or(error::Unspecified)?; diff --git a/src/digest.rs b/src/digest.rs index 2e6f209030..be3268178f 100644 --- a/src/digest.rs +++ b/src/digest.rs @@ -182,7 +182,7 @@ impl Context { /// # Examples: /// /// ``` -/// # #[cfg(feature = "use_heap")] +/// # #[cfg(feature = "alloc")] /// # { /// use ring::{digest, test}; /// let expected_hex = "09ca7e4eaa6e8ae9c7d261167129184883644d07dfba7cbfbc4c8a2e08360d5b"; @@ -489,7 +489,7 @@ mod tests { mod max_input { use super::super::super::digest; use crate::polyfill; - use std::vec; + use alloc::vec; macro_rules! max_input_tests { ( $algorithm_name:ident ) => { diff --git a/src/ec/suite_b/ecdsa/verification.rs b/src/ec/suite_b/ecdsa/verification.rs index 654a90f1ae..2b4ccbed69 100644 --- a/src/ec/suite_b/ecdsa/verification.rs +++ b/src/ec/suite_b/ecdsa/verification.rs @@ -289,7 +289,7 @@ pub static ECDSA_P384_SHA384_ASN1: EcdsaVerificationAlgorithm = EcdsaVerificatio mod tests { use super::*; use crate::test; - use std::vec::Vec; + use alloc::vec::Vec; #[test] fn test_digest_based_test_vectors() { diff --git a/src/ec/suite_b/ops.rs b/src/ec/suite_b/ops.rs index a9ac8c5921..d6cc43175d 100644 --- a/src/ec/suite_b/ops.rs +++ b/src/ec/suite_b/ops.rs @@ -440,7 +440,7 @@ extern "C" { mod tests { use super::*; use crate::test; - use std::{format, print, vec, vec::Vec}; + use alloc::{format, vec, vec::Vec}; use untrusted; const ZERO_SCALAR: Scalar = Scalar { @@ -1115,12 +1115,11 @@ mod tests { ) { for i in 0..ops.num_limbs { if actual[i] != expected[i] { - let mut s = std::string::String::new(); + let mut s = alloc::string::String::new(); for j in 0..ops.num_limbs { let formatted = format!("{:016x}", actual[ops.num_limbs - j - 1]); s.push_str(&formatted); } - print!("\n"); panic!("Actual != Expected,\nActual = {}", s); } } diff --git a/src/error.rs b/src/error.rs index e6416cf855..e186f00060 100644 --- a/src/error.rs +++ b/src/error.rs @@ -36,7 +36,7 @@ use untrusted; /// enum Error { /// CryptoError, /// -/// # #[cfg(feature = "use_heap")] +/// # #[cfg(feature = "alloc")] /// IOError(std::io::Error), /// // [...] /// } @@ -88,7 +88,7 @@ impl core::fmt::Display for Unspecified { } } -#[cfg(feature = "use_heap")] +#[cfg(feature = "std")] impl std::error::Error for Unspecified { #[inline] fn cause(&self) -> Option<&dyn std::error::Error> { @@ -168,12 +168,12 @@ impl KeyRejected { KeyRejected("PublicKeyIsMissing") } - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] pub(crate) fn too_small() -> Self { KeyRejected("TooSmall") } - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] pub(crate) fn too_large() -> Self { KeyRejected("TooLarge") } @@ -186,7 +186,7 @@ impl KeyRejected { KeyRejected("WrongAlgorithm") } - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] pub(crate) fn private_modulus_len_not_multiple_of_512_bits() -> Self { KeyRejected("PrivateModulusLenNotMultipleOf512Bits") } @@ -196,7 +196,7 @@ impl KeyRejected { } } -#[cfg(feature = "use_heap")] +#[cfg(feature = "std")] impl std::error::Error for KeyRejected { fn cause(&self) -> Option<&dyn std::error::Error> { None diff --git a/src/io.rs b/src/io.rs index e28fb66f6f..e7f7cc36f5 100644 --- a/src/io.rs +++ b/src/io.rs @@ -17,10 +17,10 @@ #[doc(hidden)] pub mod der; -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] mod writer; -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] pub(crate) mod der_writer; pub(crate) mod positive; diff --git a/src/io/der_writer.rs b/src/io/der_writer.rs index 4de247f389..4c166eb9eb 100644 --- a/src/io/der_writer.rs +++ b/src/io/der_writer.rs @@ -13,7 +13,7 @@ // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. use super::{der::*, writer::*, *}; -use std::boxed::Box; +use alloc::boxed::Box; pub(crate) fn write_positive_integer(output: &mut dyn Accumulator, value: &Positive) { let first_byte = value.first_byte(); diff --git a/src/io/writer.rs b/src/io/writer.rs index ff4bbb1461..24436bd53d 100644 --- a/src/io/writer.rs +++ b/src/io/writer.rs @@ -12,7 +12,7 @@ // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -use std::{boxed::Box, vec::Vec}; +use alloc::{boxed::Box, vec::Vec}; pub trait Accumulator { fn write_byte(&mut self, value: u8); diff --git a/src/lib.rs b/src/lib.rs index 6565bcf1fd..d7abd241d5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,6 +22,8 @@ //! //!
Feature //! Description +//!
alloc (default) +//! Enable features that require use of the heap, RSA in particular. //!
dev_urandom_fallback (default) //! This is only applicable to Linux. On Linux, by default, //! ring::rand::SystemRandom will fall back to reading @@ -30,8 +32,9 @@ //! dev_urandom_fallback feature is disabled, such //! fallbacks will not occur. See the documentation for //! rand::SystemRandom for more details. -//!
use_heap (default) -//! Enable features that require use of the heap, RSA in particular. +//!
std (default) +//! Enable features that use libstd, in particular `std::error::Error` +//! integration. //!
#![doc(html_root_url = "https://briansmith.org/rustdoc/")] @@ -62,13 +65,15 @@ #![no_std] #![cfg_attr(feature = "internal_benches", allow(unstable_features), feature(test))] -#[cfg(any(test, feature = "use_heap"))] +#[cfg(feature = "alloc")] +extern crate alloc; + +#[cfg(feature = "std")] extern crate std; #[macro_use] mod debug; -#[cfg(any(test, feature = "use_heap"))] #[macro_use] pub mod test; @@ -103,7 +108,7 @@ pub mod pbkdf2; pub mod pkcs8; pub mod rand; -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] mod rsa; pub mod signature; diff --git a/src/limb.rs b/src/limb.rs index 79b25da94e..65fdae5ca7 100644 --- a/src/limb.rs +++ b/src/limb.rs @@ -21,10 +21,10 @@ use crate::{c, error}; use untrusted; -#[cfg(any(test, feature = "use_heap"))] +#[cfg(feature = "alloc")] use crate::bits; -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] use core::num::Wrapping; // XXX: Not correct for x32 ABIs. @@ -77,7 +77,7 @@ pub fn limbs_less_than_limbs_vartime(a: &[Limb], b: &[Limb]) -> bool { } #[inline] -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] pub fn limbs_less_than_limb_constant_time(a: &[Limb], b: Limb) -> LimbMask { unsafe { LIMBS_less_than_limb(a.as_ptr(), b, a.len()) } } @@ -87,13 +87,13 @@ pub fn limbs_are_zero_constant_time(limbs: &[Limb]) -> LimbMask { unsafe { LIMBS_are_zero(limbs.as_ptr(), limbs.len()) } } -#[cfg(any(test, feature = "use_heap"))] +#[cfg(feature = "alloc")] #[inline] pub fn limbs_are_even_constant_time(limbs: &[Limb]) -> LimbMask { unsafe { LIMBS_are_even(limbs.as_ptr(), limbs.len()) } } -#[cfg(any(test, feature = "use_heap"))] +#[cfg(feature = "alloc")] #[inline] pub fn limbs_equal_limb_constant_time(a: &[Limb], b: Limb) -> LimbMask { unsafe { LIMBS_equal_limb(a.as_ptr(), b, a.len()) } @@ -106,7 +106,7 @@ pub fn limbs_equal_limb_constant_time(a: &[Limb], b: Limb) -> LimbMask { // with respect to `a.len()` or the value of the result or the value of the // most significant bit (It's 1, unless the input is zero, in which case it's // zero.) -#[cfg(any(test, feature = "use_heap"))] +#[cfg(feature = "alloc")] pub fn limbs_minimal_bits(a: &[Limb]) -> bits::BitLength { for num_limbs in (1..=a.len()).rev() { let high_limb = a[num_limbs - 1]; @@ -252,7 +252,7 @@ pub fn big_endian_from_limbs(limbs: &[Limb], out: &mut [u8]) { } } -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] pub type Window = Limb; /// Processes `limbs` as a sequence of 5-bit windows, folding the windows from @@ -267,7 +267,7 @@ pub type Window = Limb; /// channels as long as `init` and `fold` are side-channel free. /// /// Panics if `limbs` is empty. -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] pub fn fold_5_bit_windows R, F: Fn(R, Window) -> R>( limbs: &[Limb], init: I, @@ -333,16 +333,16 @@ pub fn fold_5_bit_windows R, F: Fn(R, Window) -> R>( } extern "C" { - #[cfg(any(test, feature = "use_heap"))] + #[cfg(feature = "alloc")] fn LIMB_shr(a: Limb, shift: c::size_t) -> Limb; - #[cfg(any(test, feature = "use_heap"))] + #[cfg(feature = "alloc")] fn LIMBS_are_even(a: *const Limb, num_limbs: c::size_t) -> LimbMask; fn LIMBS_are_zero(a: *const Limb, num_limbs: c::size_t) -> LimbMask; - #[cfg(any(test, feature = "use_heap"))] + #[cfg(feature = "alloc")] fn LIMBS_equal_limb(a: *const Limb, b: Limb, num_limbs: c::size_t) -> LimbMask; fn LIMBS_less_than(a: *const Limb, b: *const Limb, num_limbs: c::size_t) -> LimbMask; - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] fn LIMBS_less_than_limb(a: *const Limb, b: Limb, num_limbs: c::size_t) -> LimbMask; fn LIMBS_reduce_once(r: *mut Limb, m: *const Limb, num_limbs: c::size_t); } @@ -453,7 +453,7 @@ mod tests { } #[test] - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] fn test_limbs_less_than_limb_constant_time() { static LESSER: &[(&[Limb], Limb)] = &[ (&[0], 1), diff --git a/src/rsa/padding.rs b/src/rsa/padding.rs index bc84db017b..bf06abbd0b 100644 --- a/src/rsa/padding.rs +++ b/src/rsa/padding.rs @@ -16,7 +16,7 @@ use super::PUBLIC_KEY_PUBLIC_MODULUS_MAX_LEN; use crate::{bits, digest, error, io::der}; use untrusted; -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] use crate::rand; /// Common features of both RSA padding encoding and RSA padding verification. @@ -29,7 +29,7 @@ pub trait Padding: 'static + Sync + crate::sealed::Sealed + core::fmt::Debug { /// An RSA signature encoding as described in [RFC 3447 Section 8]. /// /// [RFC 3447 Section 8]: https://tools.ietf.org/html/rfc3447#section-8 -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] pub trait RsaEncoding: Padding { #[doc(hidden)] fn encode( @@ -74,7 +74,7 @@ impl Padding for PKCS1 { } } -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] impl RsaEncoding for PKCS1 { fn encode( &self, @@ -398,7 +398,7 @@ impl Verification for PSS { } struct PSSMetrics { - #[cfg_attr(not(feature = "use_heap"), allow(dead_code))] + #[cfg_attr(not(feature = "alloc"), allow(dead_code))] em_len: usize, db_len: usize, ps_len: usize, @@ -521,7 +521,7 @@ rsa_pss_padding!( mod test { use super::*; use crate::{digest, error, test}; - use std::vec; + use alloc::vec; use untrusted; #[test] @@ -562,7 +562,7 @@ mod test { } // Tests PSS encoding for various public modulus lengths. - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] #[test] fn test_pss_padding_encode() { test::run( diff --git a/src/rsa/signing.rs b/src/rsa/signing.rs index 3b8ec31f70..fa8ec5b005 100644 --- a/src/rsa/signing.rs +++ b/src/rsa/signing.rs @@ -24,7 +24,7 @@ use crate::{ io::{self, der, der_writer}, pkcs8, rand, signature, }; -use std::boxed::Box; +use alloc::boxed::Box; use untrusted; /// An RSA key pair, used for signing. @@ -610,7 +610,7 @@ mod tests { // We intentionally avoid `use super::*` so that we are sure to use only // the public API; this ensures that enough of the API is public. use crate::{rand, signature}; - use std::vec; + use alloc::vec; // `KeyPair::sign` requires that the output buffer is the same length as // the public key modulus. Test what happens when it isn't the same length. diff --git a/src/rsa/verification.rs b/src/rsa/verification.rs index ae02201f89..4b81c2d118 100644 --- a/src/rsa/verification.rs +++ b/src/rsa/verification.rs @@ -107,7 +107,7 @@ macro_rules! rsa_params { $doc_str:expr ) => { #[doc=$doc_str] /// - /// Only available in `use_heap` mode. + /// Only available in `alloc` mode. pub static $VERIFY_ALGORITHM: RsaParameters = RsaParameters { padding_alg: $PADDING_ALGORITHM, min_bits: bits::BitLength::from_usize_bits($min_bits), diff --git a/src/signature.rs b/src/signature.rs index d309ba8fef..40d395ea22 100644 --- a/src/signature.rs +++ b/src/signature.rs @@ -195,7 +195,7 @@ //! ``` //! use ring::{rand, signature}; //! -//! # #[cfg(feature = "use_heap")] +//! # #[cfg(feature = "std")] //! fn sign_and_verify_rsa(private_key_path: &std::path::Path, //! public_key_path: &std::path::Path) //! -> Result<(), MyError> { @@ -223,14 +223,14 @@ //! //! #[derive(Debug)] //! enum MyError { -//! # #[cfg(feature = "use_heap")] +//! # #[cfg(feature = "std")] //! IO(std::io::Error), //! BadPrivateKey, //! OOM, //! BadSignature, //! } //! -//! # #[cfg(feature = "use_heap")] +//! # #[cfg(feature = "std")] //! fn read_file(path: &std::path::Path) -> Result, MyError> { //! use std::io::Read; //! @@ -240,7 +240,7 @@ //! Ok(contents) //! } //! # -//! # #[cfg(not(feature = "use_heap"))] +//! # #[cfg(not(feature = "std"))] //! # fn sign_and_verify_rsa(_private_key_path: &std::path::Path, //! # _public_key_path: &std::path::Path) //! # -> Result<(), ()> { @@ -279,7 +279,7 @@ pub use crate::ec::{ }, }; -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] pub use crate::rsa::{ signing::RsaKeyPair, signing::RsaSubjectPublicKey, diff --git a/src/test.rs b/src/test.rs index 75fe703d70..330b698ef7 100644 --- a/src/test.rs +++ b/src/test.rs @@ -117,13 +117,14 @@ //! stack trace to the line in the test code that panicked: entry 9 in the //! stack trace pointing to line 652 of the file `example.rs`. -#[cfg(feature = "use_heap")] -use crate::bits; +#[cfg(feature = "alloc")] +use alloc::{format, string::String, vec::Vec}; -use crate::{digest, error}; +#[cfg(feature = "alloc")] +use crate::{bits, digest, error}; -use std::{format, string::String, vec::Vec}; -use std::{panic, println}; +#[cfg(feature = "std")] +use std::println; /// `compile_time_assert_clone::();` fails to compile if `T` doesn't /// implement `Clone`. @@ -145,14 +146,23 @@ pub fn compile_time_assert_sync() {} /// implement `Debug`. pub fn compile_time_assert_debug() {} +/// `compile_time_assert_debug::();` fails to compile if `T` doesn't +/// implement `std::error::Error`. +#[cfg(feature = "std")] +pub fn compile_time_assert_std_error_error() {} + /// A test case. A test case consists of a set of named attributes. Every /// attribute in the test case must be consumed exactly once; this helps catch /// typos and omissions. +/// +/// Requires the `std` default feature to be enabled. +#[cfg(feature = "alloc")] #[derive(Debug)] pub struct TestCase { attributes: Vec<(String, String, bool)>, } +#[cfg(feature = "alloc")] impl TestCase { /// Maps the string "true" to true and the string "false" to false. pub fn consume_bool(&mut self, key: &str) -> bool { @@ -247,7 +257,7 @@ impl TestCase { /// Returns the value of an attribute that is an integer, in decimal /// notation, as a bit length. - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] pub fn consume_usize_bits(&mut self, key: &str) -> bits::BitLength { let s = self.consume_string(key); let bits = s.parse::().unwrap(); @@ -278,6 +288,7 @@ impl TestCase { } /// References a test input file. +#[cfg(feature = "alloc")] #[macro_export] macro_rules! test_file { ($file_name:expr) => { @@ -289,6 +300,7 @@ macro_rules! test_file { } /// A test input file. +#[cfg(feature = "alloc")] pub struct File<'a> { /// The name (path) of the file. pub file_name: &'a str, @@ -300,6 +312,9 @@ pub struct File<'a> { /// Parses test cases out of the given file, calling `f` on each vector until /// `f` fails or until all the test vectors have been read. `f` can indicate /// failure either by returning `Err()` or by panicking. +/// +/// Requires the `std` default feature to be enabled +#[cfg(feature = "alloc")] pub fn run(test_file: File, mut f: F) where F: FnMut(&str, &mut TestCase) -> Result<(), error::Unspecified>, @@ -309,11 +324,15 @@ where let mut current_section = String::from(""); let mut failed = false; - #[allow(box_pointers)] while let Some(mut test_case) = parse_test_case(&mut current_section, lines) { - let result = panic::catch_unwind(panic::AssertUnwindSafe(|| { + #[cfg(feature = "std")] + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { f(¤t_section, &mut test_case) })); + + #[cfg(not(feature = "std"))] + let result: Result<_, error::Unspecified> = Ok(f(¤t_section, &mut test_case)); + let result = match result { Ok(Ok(())) => { if !test_case @@ -331,15 +350,21 @@ where Err(_) => Err("Test panicked."), }; - if let Err(msg) = result { + if result.is_err() { failed = true; + } - println!("{}: {}", test_file.file_name, msg); - for (name, value, consumed) in test_case.attributes { - let consumed_str = if consumed { "" } else { " (unconsumed)" }; - println!("{}{} = {}", name, consumed_str, value); - } - }; + #[cfg(feature = "std")] + { + if let Err(msg) = result { + println!("{}: {}", test_file.file_name, msg); + + for (name, value, consumed) in test_case.attributes { + let consumed_str = if consumed { "" } else { " (unconsumed)" }; + println!("{}{} = {}", name, consumed_str, value); + } + }; + } } if failed { @@ -349,6 +374,7 @@ where /// Decode an string of hex digits into a sequence of bytes. The input must /// have an even number of digits. +#[cfg(feature = "alloc")] pub fn from_hex(hex_str: &str) -> Result, String> { if hex_str.len() % 2 != 0 { return Err(String::from( @@ -365,6 +391,7 @@ pub fn from_hex(hex_str: &str) -> Result, String> { Ok(result) } +#[cfg(feature = "alloc")] fn from_hex_digit(d: u8) -> Result { if d >= b'0' && d <= b'9' { Ok(d - b'0') @@ -377,6 +404,7 @@ fn from_hex_digit(d: u8) -> Result { } } +#[cfg(feature = "alloc")] fn parse_test_case( current_section: &mut String, lines: &mut dyn Iterator, @@ -387,7 +415,8 @@ fn parse_test_case( loop { let line = lines.next(); - if cfg!(feature = "test_logging") { + #[cfg(feature = "test_logging")] + { if let Some(text) = &line { println!("Line: {}", text); } @@ -453,7 +482,7 @@ fn parse_test_case( /// of randomized algorithms & protocols using known-answer-tests where the /// test vectors contain the random seed to use. They are also especially /// useful for some types of fuzzing. -#[allow(missing_docs)] +#[doc(hidden)] pub mod rand { use crate::{error, polyfill, rand}; @@ -545,7 +574,8 @@ mod tests { } #[test] - #[should_panic(expected = "Test failed.")] + #[cfg_attr(feature = "std", should_panic(expected = "Test failed."))] + #[cfg_attr(not(feature = "std"), should_panic)] fn one_panics() { test::run(test_file!("test_1_tests.txt"), |_, test_case| { let _ = test_case.consume_string("Key"); @@ -586,19 +616,22 @@ mod tests { } #[test] - #[should_panic(expected = "Test failed.")] + #[cfg_attr(feature = "std", should_panic(expected = "Test failed."))] + #[cfg_attr(not(feature = "std"), should_panic)] fn first_panic() { panic_one(0) } #[test] - #[should_panic(expected = "Test failed.")] + #[cfg_attr(feature = "std", should_panic(expected = "Test failed."))] + #[cfg_attr(not(feature = "std"), should_panic)] fn middle_panic() { panic_one(1) } #[test] - #[should_panic(expected = "Test failed.")] + #[cfg_attr(feature = "std", should_panic(expected = "Test failed."))] + #[cfg_attr(not(feature = "std"), should_panic)] fn last_panic() { panic_one(2) } diff --git a/tests/agreement_tests.rs b/tests/agreement_tests.rs index 1d22b9fd42..e3eb48e551 100644 --- a/tests/agreement_tests.rs +++ b/tests/agreement_tests.rs @@ -97,7 +97,7 @@ fn test_agreement_ecdh_x25519_rfc_iterated() { fn expect_iterated_x25519( expected_result: &str, - range: std::ops::Range, + range: core::ops::Range, k: &mut Vec, u: &mut Vec, ) { diff --git a/tests/ecdsa_tests.rs b/tests/ecdsa_tests.rs index b6a1ea864b..a4148a4528 100644 --- a/tests/ecdsa_tests.rs +++ b/tests/ecdsa_tests.rs @@ -39,14 +39,12 @@ use ring::{ // ECDSA *signing* tests are in src/ec/ecdsa/signing.rs. -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn ecdsa_from_pkcs8_test() { test::run( test_file!("ecdsa_from_pkcs8_tests.txt"), |section, test_case| { - use std::error::Error; - assert_eq!(section, ""); let curve_name = test_case.consume_string("Curve"); @@ -85,7 +83,7 @@ fn ecdsa_from_pkcs8_test() { (Ok(_), None) => (), (Err(e), None) => panic!("Failed with error \"{}\", but expected to succeed", e), (Ok(_), Some(e)) => panic!("Succeeded, but expected error \"{}\"", e), - (Err(actual), Some(expected)) => assert_eq!(actual.description(), expected), + (Err(actual), Some(expected)) => assert_eq!(format!("{}", actual), expected), }; match ( @@ -95,7 +93,7 @@ fn ecdsa_from_pkcs8_test() { (Ok(_), None) => (), (Err(e), None) => panic!("Failed with error \"{}\", but expected to succeed", e), (Ok(_), Some(e)) => panic!("Succeeded, but expected error \"{}\"", e), - (Err(actual), Some(expected)) => assert_eq!(actual.description(), expected), + (Err(actual), Some(expected)) => assert_eq!(format!("{}", actual), expected), }; assert!(signature::EcdsaKeyPair::from_pkcs8(other_fixed, &input).is_err()); @@ -125,7 +123,7 @@ fn ecdsa_generate_pkcs8_test() { println!(); println!(); - #[cfg(feature = "use_heap")] + #[cfg(feature = "alloc")] let _ = signature::EcdsaKeyPair::from_pkcs8(*alg, pkcs8.as_ref()).unwrap(); } } diff --git a/tests/error_tests.rs b/tests/error_tests.rs new file mode 100644 index 0000000000..8e78c7023f --- /dev/null +++ b/tests/error_tests.rs @@ -0,0 +1,7 @@ +#[cfg(feature = "std")] +#[test] +fn error_impl_std_error_error_test() { + use ring::{error, test}; + test::compile_time_assert_std_error_error::(); + test::compile_time_assert_std_error_error::(); +} diff --git a/tests/pbkdf2_tests.rs b/tests/pbkdf2_tests.rs index 17c3ad0fa2..07c77263d8 100644 --- a/tests/pbkdf2_tests.rs +++ b/tests/pbkdf2_tests.rs @@ -32,7 +32,7 @@ )] use ring::{digest, error, pbkdf2, test, test_file}; -use std::num::NonZeroU32; +use core::num::NonZeroU32; #[test] pub fn pbkdf2_tests() { diff --git a/tests/rsa_tests.rs b/tests/rsa_tests.rs index 3c4f58ffc3..c140e8fbcc 100644 --- a/tests/rsa_tests.rs +++ b/tests/rsa_tests.rs @@ -31,7 +31,7 @@ warnings )] -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] use ring::{ error, io::der, @@ -40,14 +40,12 @@ use ring::{ test, test_file, }; -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn rsa_from_pkcs8_test() { test::run( test_file!("rsa_from_pkcs8_tests.txt"), |section, test_case| { - use std::error::Error; - assert_eq!(section, ""); let input = test_case.consume_bytes("Input"); @@ -57,7 +55,7 @@ fn rsa_from_pkcs8_test() { (Ok(_), None) => (), (Err(e), None) => panic!("Failed with error \"{}\", but expected to succeed", e), (Ok(_), Some(e)) => panic!("Succeeded, but expected error \"{}\"", e), - (Err(actual), Some(expected)) => assert_eq!(actual.description(), expected), + (Err(actual), Some(expected)) => assert_eq!(format!("{}", actual), expected), }; Ok(()) @@ -65,7 +63,7 @@ fn rsa_from_pkcs8_test() { ); } -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn test_signature_rsa_pkcs1_sign() { let rng = rand::SystemRandom::new(); @@ -93,7 +91,6 @@ fn test_signature_rsa_pkcs1_sign() { return Ok(()); } let key_pair = key_pair.unwrap(); - let key_pair = std::sync::Arc::new(key_pair); // XXX: This test is too slow on Android ARM Travis CI builds. // TODO: re-enable these tests on Android ARM. @@ -107,7 +104,7 @@ fn test_signature_rsa_pkcs1_sign() { ); } -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn test_signature_rsa_pss_sign() { test::run( @@ -144,7 +141,7 @@ fn test_signature_rsa_pss_sign() { ); } -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn test_signature_rsa_pkcs1_verify() { test::run( @@ -202,7 +199,7 @@ fn test_signature_rsa_pkcs1_verify() { ); } -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn test_signature_rsa_pss_verify() { test::run( @@ -260,7 +257,7 @@ fn test_signature_rsa_pss_verify() { // Test for `primitive::verify()`. Read public key parts from a file // and use them to verify a signature. -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn test_signature_rsa_primitive_verification() { test::run( @@ -280,7 +277,7 @@ fn test_signature_rsa_primitive_verification() { ) } -#[cfg(feature = "use_heap")] +#[cfg(feature = "alloc")] #[test] fn rsa_test_public_key_coverage() { const PRIVATE_KEY: &[u8] = include_bytes!("rsa_test_private_key_2048.p8");