Skip to content

Commit f355c2d

Browse files
committed
implemented strlen to deref the callback message
1 parent ea75907 commit f355c2d

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

src/ffi.rs

+35-5
Original file line numberDiff line numberDiff line change
@@ -268,9 +268,11 @@ extern "C" {
268268
///
269269
/// See also secp256k1_default_error_callback_fn.
270270
///
271-
pub extern "C" fn secp256k1_default_illegal_callback_fn(_message: *const c_char, _data: *mut c_void) {
272-
// Do we need to deref the message and print it? if so without std we'll need to use `strlen`
273-
panic!("[libsecp256k1] illegal argument.");
271+
pub unsafe extern "C" fn secp256k1_default_illegal_callback_fn(message: *const c_char, _data: *mut c_void) {
272+
use core::{str, slice};
273+
let msg_slice = slice::from_raw_parts(message as *const u8, strlen(message));
274+
let msg = str::from_utf8_unchecked(msg_slice);
275+
panic!("[libsecp256k1] illegal argument. {}", msg);
274276
}
275277

276278
#[no_mangle]
@@ -288,9 +290,22 @@ pub extern "C" fn secp256k1_default_illegal_callback_fn(_message: *const c_char,
288290
///
289291
/// See also secp256k1_default_illegal_callback_fn.
290292
///
291-
pub extern "C" fn secp256k1_default_error_callback_fn(_message: *const c_char, _data: *mut c_void) {
293+
pub unsafe extern "C" fn secp256k1_default_error_callback_fn(message: *const c_char, _data: *mut c_void) {
292294
// Do we need to deref the message and print it? if so without std we'll need to use `strlen`
293-
panic!("[libsecp256k1] internal consistency check failed.");
295+
use core::{str, slice};
296+
let msg_slice = slice::from_raw_parts(message as *const u8, strlen(message));
297+
let msg = str::from_utf8_unchecked(msg_slice);
298+
panic!("[libsecp256k1] internal consistency check failed {}", msg);
299+
}
300+
301+
302+
unsafe fn strlen(mut str_ptr: *const c_char) -> usize {
303+
let mut ctr = 0;
304+
while *str_ptr != '\0' as c_char {
305+
ctr += 1;
306+
str_ptr = str_ptr.offset(1);
307+
}
308+
ctr
294309
}
295310

296311

@@ -639,3 +654,18 @@ mod fuzz_dummy {
639654
}
640655
#[cfg(feature = "fuzztarget")]
641656
pub use self::fuzz_dummy::*;
657+
658+
659+
#[cfg(test)]
660+
mod tests {
661+
use std::ffi::CString;
662+
use super::strlen;
663+
664+
#[test]
665+
fn test_strlen() {
666+
let orig = "test strlen \t \n";
667+
let test = CString::new(orig).unwrap();
668+
669+
assert_eq!(orig.len(), unsafe {strlen(test.as_ptr())});
670+
}
671+
}

0 commit comments

Comments
 (0)