diff --git a/src/context.rs b/src/context.rs index 5dec6245e..230cfaa73 100644 --- a/src/context.rs +++ b/src/context.rs @@ -7,6 +7,21 @@ use Secp256k1; #[cfg(feature = "std")] pub use self::std_only::*; + + +/// A type that represents the type with the biggest alignment we can get in rust. +/// Trying to match what `malloc` does in C, this should be aligned enough to contain pointers too. +/// This type can have different size/alignment depending on the architecture. +#[cfg(any(target_pointer_width = "32", target_pointer_width = "16", target_pointer_wid = "8"))] +pub type AlignType = u64; + +/// A type that represents the type with the biggest alignment we can get in rust. +/// Trying to match what `malloc` does in C, this should be aligned enough to contain pointers too. +/// This type can have different size/alignment depending on the architecture. +#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "16", target_pointer_wid = "8")))] +pub type AlignType = usize; + + /// A trait for all kinds of Context's that Lets you define the exact flags and a function to deallocate memory. /// * DO NOT * implement it for your own types. pub unsafe trait Context { @@ -15,7 +30,7 @@ pub unsafe trait Context { /// A constant description of the context. const DESCRIPTION: &'static str; /// A function to deallocate the memory when the context is dropped. - fn deallocate(ptr: *mut [u8]); + fn deallocate(ptr: *mut [AlignType]); } /// Marker trait for indicating that an instance of `Secp256k1` can be used for signing. @@ -62,7 +77,7 @@ mod std_only { const FLAGS: c_uint = ffi::SECP256K1_START_SIGN; const DESCRIPTION: &'static str = "signing only"; - fn deallocate(ptr: *mut [u8]) { + fn deallocate(ptr: *mut [AlignType]) { let _ = unsafe { Box::from_raw(ptr) }; } } @@ -71,7 +86,7 @@ mod std_only { const FLAGS: c_uint = ffi::SECP256K1_START_VERIFY; const DESCRIPTION: &'static str = "verification only"; - fn deallocate(ptr: *mut [u8]) { + fn deallocate(ptr: *mut [AlignType]) { let _ = unsafe { Box::from_raw(ptr) }; } } @@ -80,7 +95,7 @@ mod std_only { const FLAGS: c_uint = VerifyOnly::FLAGS | SignOnly::FLAGS; const DESCRIPTION: &'static str = "all capabilities"; - fn deallocate(ptr: *mut [u8]) { + fn deallocate(ptr: *mut [AlignType]) { let _ = unsafe { Box::from_raw(ptr) }; } } @@ -88,7 +103,7 @@ mod std_only { impl Secp256k1 { /// Lets you create a context in a generic manner(sign/verify/all) pub fn gen_new() -> Secp256k1 { - let buf = vec![0u8; Self::preallocate_size_gen()].into_boxed_slice(); + let buf = vec![0 as AlignType; Self::preallocate_size_gen()].into_boxed_slice(); let ptr = Box::into_raw(buf); Secp256k1 { ctx: unsafe { ffi::secp256k1_context_preallocated_create(ptr as *mut c_void, C::FLAGS) }, @@ -128,7 +143,7 @@ mod std_only { impl Clone for Secp256k1 { fn clone(&self) -> Secp256k1 { let clone_size = unsafe {ffi::secp256k1_context_preallocated_clone_size(self.ctx)}; - let ptr_buf = Box::into_raw(vec![0u8; clone_size].into_boxed_slice()); + let ptr_buf = Box::into_raw(vec![0 as AlignType; clone_size].into_boxed_slice()); Secp256k1 { ctx: unsafe { ffi::secp256k1_context_preallocated_clone(self.ctx, ptr_buf as *mut c_void) }, phantom: PhantomData, @@ -149,7 +164,7 @@ unsafe impl<'buf> Context for SignOnlyPreallocated<'buf> { const FLAGS: c_uint = ffi::SECP256K1_START_SIGN; const DESCRIPTION: &'static str = "signing only"; - fn deallocate(_ptr: *mut [u8]) { + fn deallocate(_ptr: *mut [AlignType]) { // Allocated by the user } } @@ -158,7 +173,7 @@ unsafe impl<'buf> Context for VerifyOnlyPreallocated<'buf> { const FLAGS: c_uint = ffi::SECP256K1_START_VERIFY; const DESCRIPTION: &'static str = "verification only"; - fn deallocate(_ptr: *mut [u8]) { + fn deallocate(_ptr: *mut [AlignType]) { // Allocated by the user } } @@ -167,14 +182,14 @@ unsafe impl<'buf> Context for AllPreallocated<'buf> { const FLAGS: c_uint = SignOnlyPreallocated::FLAGS | VerifyOnlyPreallocated::FLAGS; const DESCRIPTION: &'static str = "all capabilities"; - fn deallocate(_ptr: *mut [u8]) { + fn deallocate(_ptr: *mut [AlignType]) { // Allocated by the user } } impl<'buf, C: Context + 'buf> Secp256k1 { /// Lets you create a context with preallocated buffer in a generic manner(sign/verify/all) - pub fn preallocated_gen_new(buf: &'buf mut [u8]) -> Result, Error> { + pub fn preallocated_gen_new(buf: &'buf mut [AlignType]) -> Result, Error> { if buf.len() < Self::preallocate_size_gen() { return Err(Error::NotEnoughMemory); } @@ -185,17 +200,28 @@ impl<'buf, C: Context + 'buf> Secp256k1 { C::FLAGS) }, phantom: PhantomData, - buf: buf as *mut [u8], + buf: buf as *mut [AlignType], }) } } impl<'buf> Secp256k1> { /// Creates a new Secp256k1 context with all capabilities - pub fn preallocated_new(buf: &'buf mut [u8]) -> Result>, Error> { + pub fn preallocated_new(buf: &'buf mut [AlignType]) -> Result>, Error> { Secp256k1::preallocated_gen_new(buf) } - /// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for a context + /// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all) + /// + /// Notice that the memory returned is in [AlignedType](type.AlignType.html) + /// + /// ## Examples + /// ```rust + /// # use secp256k1::*; + /// let buf_size = Secp256k1::preallocate_size(); + /// let mut buf = vec![0; buf_size]; + /// let secp = Secp256k1::preallocated_new(&mut buf).unwrap(); + /// + /// ``` pub fn preallocate_size() -> usize { Self::preallocate_size_gen() } @@ -203,11 +229,22 @@ impl<'buf> Secp256k1> { impl<'buf> Secp256k1> { /// Creates a new Secp256k1 context that can only be used for signing - pub fn preallocated_signing_only(buf: &'buf mut [u8]) -> Result>, Error> { + pub fn preallocated_signing_only(buf: &'buf mut [AlignType]) -> Result>, Error> { Secp256k1::preallocated_gen_new(buf) } - /// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for the context + /// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all) + /// + /// Notice that the memory returned is in [AlignedType](type.AlignType.html) + /// + /// ## Examples + /// ```rust + /// # use secp256k1::*; + /// let buf_size = Secp256k1::preallocate_signing_size(); + /// let mut buf = vec![0; buf_size]; + /// let secp = Secp256k1::preallocated_signing_only(&mut buf).unwrap(); + /// + /// ``` #[inline] pub fn preallocate_signing_size() -> usize { Self::preallocate_size_gen() @@ -216,11 +253,22 @@ impl<'buf> Secp256k1> { impl<'buf> Secp256k1> { /// Creates a new Secp256k1 context that can only be used for verification - pub fn preallocated_verification_only(buf: &'buf mut [u8]) -> Result>, Error> { + pub fn preallocated_verification_only(buf: &'buf mut [AlignType]) -> Result>, Error> { Secp256k1::preallocated_gen_new(buf) } - /// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for the context + /// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all) + /// + /// Notice that the memory returned is in [AlignedType](type.AlignType.html) + /// + /// ## Examples + /// ```rust + /// # use secp256k1::*; + /// let buf_size = Secp256k1::preallocate_verification_size(); + /// let mut buf = vec![0; buf_size]; + /// let secp = Secp256k1::preallocated_verification_only(&mut buf).unwrap(); + /// + /// ``` #[inline] pub fn preallocate_verification_size() -> usize { Self::preallocate_size_gen() diff --git a/src/ffi.rs b/src/ffi.rs index f5a4a98fa..1817ddf7c 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -18,6 +18,7 @@ //! not be needed for most users. use core::{mem, hash, slice}; use types::*; +use context::AlignType; /// Flag for context to enable no precomputation pub const SECP256K1_START_NONE: c_uint = 1; @@ -271,16 +272,18 @@ extern "C" { // Returns: a newly created context object. // In: flags: which parts of the context to initialize. pub unsafe extern "C" fn secp256k1_context_create(flags: c_uint) -> *mut Context { - assert!(mem::align_of::() >= mem::align_of::()); - assert_eq!(mem::size_of::(), mem::size_of::<&usize>()); + assert!(mem::align_of::() >= mem::align_of::()); + assert!(mem::align_of::() >= mem::align_of::()); + assert!(mem::size_of::() >= mem::size_of::()); + assert!(mem::align_of::() >= mem::align_of::<&AlignType>()); - let word_size = mem::size_of::(); + let word_size = mem::size_of::(); let n_words = (secp256k1_context_preallocated_size(flags) + word_size - 1) / word_size; - let buf = vec![0usize; n_words + 1].into_boxed_slice(); - let ptr = Box::into_raw(buf) as *mut usize; - ::core::ptr::write(ptr, n_words); - let ptr: *mut usize = ptr.offset(1); + let buf = vec![0 as AlignType; n_words + 1].into_boxed_slice(); + let ptr = Box::into_raw(buf) as *mut AlignType; + ::core::ptr::write(ptr, n_words as AlignType); + let ptr: *mut AlignType = ptr.offset(1); secp256k1_context_preallocated_create(ptr as *mut c_void, flags) } @@ -295,12 +298,12 @@ pub unsafe extern "C" fn secp256k1_context_create(flags: c_uint) -> *mut Context /// pub unsafe extern "C" fn secp256k1_context_destroy(ctx: *mut Context) { secp256k1_context_preallocated_destroy(ctx); - let ctx: *mut usize = ctx as *mut usize; + let ctx: *mut AlignType = ctx as *mut AlignType; - let n_words_ptr: *mut usize = ctx.offset(-1); - let n_words: usize = ::core::ptr::read(n_words_ptr); - let slice: &mut [usize] = slice::from_raw_parts_mut(n_words_ptr , n_words+1); - let _ = Box::from_raw(slice as *mut [usize]); + let n_words_ptr: *mut AlignType = ctx.offset(-1); + let n_words: AlignType = ::core::ptr::read(n_words_ptr); + let slice: &mut [AlignType] = slice::from_raw_parts_mut(n_words_ptr , (n_words+1) as usize); + let _ = Box::from_raw(slice as *mut [AlignType]); } diff --git a/src/lib.rs b/src/lib.rs index a05dd2c4e..615efb7f7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -143,7 +143,9 @@ #[cfg(any(test, feature = "rand"))] use rand::Rng; #[cfg(any(test, feature = "std"))] extern crate core; -use core::{fmt, ptr, str}; +use core::{fmt, mem, ptr, str}; + +pub use context::AlignType; #[macro_use] mod macros; @@ -502,7 +504,7 @@ impl std::error::Error for Error { pub struct Secp256k1 { ctx: *mut ffi::Context, phantom: PhantomData, - buf: *mut [u8], + buf: *mut [AlignType], } // The underlying secp context does not contain any references to memory it does not own @@ -571,8 +573,19 @@ impl Secp256k1 { } /// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all) + /// + /// Notice that the memory returned is in [AlignedType](type.AlignType.html) + /// pub fn preallocate_size_gen() -> usize { - unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) } + assert!(mem::align_of::() >= mem::align_of::()); + assert!(mem::align_of::() >= mem::align_of::()); + assert!(mem::size_of::() >= mem::size_of::()); + assert!(mem::align_of::() >= mem::align_of::<&AlignType>()); + + let bytes_size = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) }; + let word_size = mem::size_of::(); + let n_words = (bytes_size + word_size - 1) / word_size; + n_words } /// (Re)randomizes the Secp256k1 context for cheap sidechannel resistance; @@ -706,7 +719,7 @@ mod tests { let ctx_sign = unsafe { ffi::secp256k1_context_create(SignOnlyPreallocated::FLAGS) }; let ctx_vrfy = unsafe { ffi::secp256k1_context_create(VerifyOnlyPreallocated::FLAGS) }; - let buf: *mut [u8] = &mut [0u8;0] as _; + let buf: *mut [AlignType] = &mut [0 as AlignType;0] as _; let full: Secp256k1 = Secp256k1{ctx: ctx_full, phantom: PhantomData, buf}; let sign: Secp256k1 = Secp256k1{ctx: ctx_sign, phantom: PhantomData, buf}; let vrfy: Secp256k1 = Secp256k1{ctx: ctx_vrfy, phantom: PhantomData, buf}; @@ -730,10 +743,10 @@ mod tests { #[test] fn test_preallocation() { - let mut buf_ful = vec![0u8; Secp256k1::preallocate_size()]; - let mut buf_sign = vec![0u8; Secp256k1::preallocate_signing_size()]; - let mut buf_vfy = vec![0u8; Secp256k1::preallocate_verification_size()]; -// + let mut buf_ful = vec![0; Secp256k1::preallocate_size()]; + let mut buf_sign = vec![0; Secp256k1::preallocate_signing_size()]; + let mut buf_vfy = vec![0; Secp256k1::preallocate_verification_size()]; + let full = Secp256k1::preallocated_new(&mut buf_ful).unwrap(); let sign = Secp256k1::preallocated_signing_only(&mut buf_sign).unwrap(); let vrfy = Secp256k1::preallocated_verification_only(&mut buf_vfy).unwrap();