Skip to content

Commit 96ddf07

Browse files
committed
Don't panic across FFI
Panicking across FFI was UB in older Rust versions and thus because of MSRV it's safer to avoid it. This replaces the panic with print+abort on `std` and double panic on no-std. Closes rust-bitcoin#354
1 parent 6911734 commit 96ddf07

File tree

3 files changed

+109
-6
lines changed

3 files changed

+109
-6
lines changed

contrib/test.sh

+3-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,9 @@ if [ "$DO_ASAN" = true ]; then
8080
fi
8181

8282
# Test if panic in C code aborts the process (either with a real panic or with SIGILL)
83-
cargo test -- --ignored --exact 'tests::test_panic_raw_ctx_should_terminate_abnormally' 2>&1 | tee /dev/stderr | grep "SIGILL\\|panicked at '\[libsecp256k1\]"
83+
cargo test -- --ignored --exact 'tests::test_panic_raw_ctx_should_terminate_abnormally' 2>&1 | tee /dev/stderr | grep "SIGABRT\\|SIGILL\\|panicked at '\[libsecp256k1\]"
84+
# Test custom handler
85+
cargo test -- --ignored --nocapture --exact 'tests::test_custom_abort_handler' 2>&1 | tee /dev/stderr | grep '^this is a custom abort handler:'
8486

8587
# Bench
8688
if [ "$DO_BENCH" = true ]; then

secp256k1-sys/src/lib.rs

+81-3
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ pub mod types;
4040
pub mod recovery;
4141

4242
use core::{slice, ptr};
43+
use core::sync::atomic::AtomicPtr;
4344
use types::*;
4445

4546
/// Flag for context to enable no precomputation
@@ -576,6 +577,83 @@ pub unsafe fn secp256k1_context_destroy(ctx: *mut Context) {
576577
rustsecp256k1_v0_4_1_context_destroy(ctx)
577578
}
578579

580+
static ABORT_HANDLER: AtomicPtr<fn(&dyn core::fmt::Display) -> !> = AtomicPtr::new(core::ptr::null_mut());
581+
582+
/// Registers custom abort handler globally.
583+
///
584+
/// libsecp256k1 may want to abort in case of invalid inputs. These are definitely bugs.
585+
/// The default handler aborts with `std` and **loops forever without `std`**.
586+
/// You can provide your own handler if you wish to override this behavior.
587+
///
588+
/// This function is `unsafe` because the supplied handler MUST NOT unwind
589+
/// since unwinding would cross FFI boundary.
590+
/// Double panic is *also* wrong!
591+
///
592+
/// Supplying panicking function may be safe if your program is compiled with `panic = "abort"`.
593+
/// It's **not** recommended to call this function from library crates - only binaries, somewhere
594+
/// near the beginning of `main()`.
595+
///
596+
/// The parameter passed to the handler is an error message that can be displayed (logged).
597+
///
598+
/// Note that the handler is a reference to function pointer rather than a function pointer itself
599+
/// because of [a missing Rust feature](https://github.com/rust-lang/rfcs/issues/2481).
600+
/// It's a bit tricky to use it, so here's an example:
601+
///
602+
/// ```
603+
/// fn custom_abort(message: &dyn std::fmt::Display) -> ! {
604+
/// eprintln!("this is a custom abort handler: {}", message);
605+
/// std::process::abort()
606+
/// }
607+
/// // We need to put the function pointer into a static variable because we need a 'static
608+
/// // reference to variable holding function pointer.
609+
/// static CUSTOM_ABORT: fn (&dyn std::fmt::Display) -> ! = custom_abort;
610+
///
611+
/// unsafe {
612+
/// secp256k1_sys::set_abort_handler(&CUSTOM_ABORT);
613+
/// }
614+
/// ```
615+
///
616+
/// The function does not guarantee any memory ordering so you MUST NOT abuse it for synchronization!
617+
/// Use some other synchronization primitive if you need to synchronize.
618+
pub unsafe fn set_abort_handler(handler: &'static fn(&dyn core::fmt::Display) -> !) {
619+
ABORT_HANDLER.store(handler as *const _ as *mut _, core::sync::atomic::Ordering::Relaxed);
620+
}
621+
622+
/// FFI-safe replacement for panic
623+
///
624+
/// Prints to stderr and aborts with `std`, double panics without `std`.
625+
#[cfg_attr(not(feature = "std"), allow(unused))]
626+
fn abort_fallback(message: impl core::fmt::Display) -> ! {
627+
#[cfg(feature = "std")]
628+
{
629+
eprintln!("[libsecp256k1] {}", message);
630+
std::process::abort()
631+
}
632+
#[cfg(not(feature = "std"))]
633+
{
634+
// no better way to "abort" without std :(
635+
loop {}
636+
}
637+
}
638+
639+
/// Ensures that types both sides of cast stay in sync and only the constness changes.
640+
///
641+
/// This elliminates the risk that if we change the type signature of abort handler the cast
642+
/// silently converts the types and causes UB.
643+
fn ptr_mut_to_const_cast<T>(ptr: *const T) -> *mut T {
644+
ptr as _
645+
}
646+
647+
fn abort_with_message(message: impl core::fmt::Display) -> ! {
648+
unsafe {
649+
let handler = ptr_mut_to_const_cast(ABORT_HANDLER.load(core::sync::atomic::Ordering::Relaxed));
650+
if !handler.is_null() {
651+
(*handler)(&message)
652+
} else {
653+
abort_fallback(message)
654+
}
655+
}
656+
}
579657

580658
/// **This function is an override for the C function, this is the an edited version of the original description:**
581659
///
@@ -601,7 +679,7 @@ pub unsafe extern "C" fn rustsecp256k1_v0_4_1_default_illegal_callback_fn(messag
601679
use core::str;
602680
let msg_slice = slice::from_raw_parts(message as *const u8, strlen(message));
603681
let msg = str::from_utf8_unchecked(msg_slice);
604-
panic!("[libsecp256k1] illegal argument. {}", msg);
682+
abort_with_message(format_args!("illegal argument. {}", msg));
605683
}
606684

607685
/// **This function is an override for the C function, this is the an edited version of the original description:**
@@ -624,7 +702,7 @@ pub unsafe extern "C" fn rustsecp256k1_v0_4_1_default_error_callback_fn(message:
624702
use core::str;
625703
let msg_slice = slice::from_raw_parts(message as *const u8, strlen(message));
626704
let msg = str::from_utf8_unchecked(msg_slice);
627-
panic!("[libsecp256k1] internal consistency check failed {}", msg);
705+
abort_with_message(format_args!("internal consistency check failed {}", msg));
628706
}
629707

630708
#[cfg(not(rust_secp_no_symbol_renaming))]
@@ -833,7 +911,7 @@ mod fuzz_dummy {
833911
*output = 4;
834912
ptr::copy((*pk).0.as_ptr(), output.offset(1), 64);
835913
} else {
836-
panic!("Bad flags");
914+
abort_with_message(format_args!("Bad flags"));
837915
}
838916
1
839917
}

src/lib.rs

+25-2
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,9 @@
112112
//!
113113
//! ## Crate features/optional dependencies
114114
//!
115+
//! This crate supports `no_std` however **you should check the documentation of
116+
//! [`ffi::set_abort_handler`] if you intend to use it without `std`!**
117+
//!
115118
//! This crate provides the following opt-in Cargo features:
116119
//!
117120
//! * `std` - use standard Rust library, enabled by default.
@@ -578,16 +581,36 @@ mod tests {
578581
drop(ctx_vrfy);
579582
}
580583

581-
#[cfg(not(target_arch = "wasm32"))]
584+
#[cfg(all(not(target_arch = "wasm32"), feature = "std"))]
582585
#[test]
583-
#[ignore] // Panicking from C may trap (SIGILL) intentionally, so we test this manually.
586+
#[ignore] // Aborting intentionally, so we test this manually.
584587
fn test_panic_raw_ctx_should_terminate_abnormally() {
585588
let ctx_vrfy = Secp256k1::verification_only();
586589
let raw_ctx_verify_as_full = unsafe {Secp256k1::from_raw_all(ctx_vrfy.ctx)};
587590
// Generating a key pair in verify context will panic (ARG_CHECK).
588591
raw_ctx_verify_as_full.generate_keypair(&mut thread_rng());
589592
}
590593

594+
#[cfg(all(not(target_arch = "wasm32"), feature = "std"))]
595+
#[test]
596+
#[ignore] // Aborting intentionally, so we test this manually.
597+
fn test_custom_abort_handler() {
598+
fn custom_abort(message: &dyn std::fmt::Display) -> ! {
599+
eprintln!("this is a custom abort handler: {}", message);
600+
std::process::abort()
601+
}
602+
static CUSTOM_ABORT: fn (&dyn std::fmt::Display) -> ! = custom_abort;
603+
604+
unsafe {
605+
ffi::set_abort_handler(&CUSTOM_ABORT);
606+
}
607+
608+
let ctx_vrfy = Secp256k1::verification_only();
609+
let raw_ctx_verify_as_full = unsafe {Secp256k1::from_raw_all(ctx_vrfy.ctx)};
610+
// Generating a key pair in verify context will panic (ARG_CHECK).
611+
raw_ctx_verify_as_full.generate_keypair(&mut thread_rng());
612+
}
613+
591614
#[test]
592615
fn test_preallocation() {
593616
let mut buf_ful = vec![AlignedType::zeroed(); Secp256k1::preallocate_size()];

0 commit comments

Comments
 (0)