Skip to content

Commit

Permalink
Merge #535: call the alloc error handle if we get NULL from the alloc…
Browse files Browse the repository at this point in the history
…ator

8b17fc0 call the alloc error handle if we get NULL from the allocator (Elichai Turkel)

Pull request description:

  Found that this was missing in this discussion: #529 (comment)

  It is documented here that it returns a NULL on memory exhaustion: https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html#tymethod.alloc
  And you can see that this is called in this example: https://doc.rust-lang.org/alloc/alloc/fn.alloc.html
  Docs for the handle itself: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html

ACKs for top commit:
  apoelstra:
    ACK 8b17fc0
  Kixunil:
    Good argument, ACK 8b17fc0

Tree-SHA512: 4b8f79ab5f691cb92621a314ceb8556c26fa7e159de359697b766043a0269e1ecf9746e6d4bfd5b45f18bccaff435c1fff491168b8bb77459ae849c38664d563
  • Loading branch information
apoelstra committed Nov 24, 2022
2 parents e4baf79 + 8b17fc0 commit 8ab0bbc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
3 changes: 3 additions & 0 deletions secp256k1-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,9 @@ pub unsafe extern "C" fn rustsecp256k1_v0_6_1_context_create(flags: c_uint) -> *
let bytes = secp256k1_context_preallocated_size(flags) + ALIGN_TO;
let layout = alloc::Layout::from_size_align(bytes, ALIGN_TO).unwrap();
let ptr = alloc::alloc(layout);
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}
(ptr as *mut usize).write(bytes);
// We must offset a whole ALIGN_TO in order to preserve the same alignment
// this means we "lose" ALIGN_TO-size_of(usize) for padding.
Expand Down
6 changes: 6 additions & 0 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ mod alloc_only {
let size = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) };
let layout = alloc::Layout::from_size_align(size, ALIGN_TO).unwrap();
let ptr = unsafe { alloc::alloc(layout) };
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}

#[allow(unused_mut)] // ctx is not mutated under some feature combinations.
let mut ctx = Secp256k1 {
Expand Down Expand Up @@ -262,6 +265,9 @@ mod alloc_only {
let size = unsafe { ffi::secp256k1_context_preallocated_clone_size(self.ctx as _) };
let layout = alloc::Layout::from_size_align(size, ALIGN_TO).unwrap();
let ptr = unsafe { alloc::alloc(layout) };
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}
Secp256k1 {
ctx: unsafe {
ffi::secp256k1_context_preallocated_clone(self.ctx, ptr as *mut c_void)
Expand Down

0 comments on commit 8ab0bbc

Please sign in to comment.