From: Matt Corallo Date: Mon, 29 Nov 2021 01:28:30 +0000 (+0000) Subject: Expose a method to unmangle pointers in test builds X-Git-Tag: v0.0.103.1^2~3 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=ce0ec2494f33662d8cfb14efc00cb49d22190e2c;p=ldk-c-bindings Expose a method to unmangle pointers in test builds This is used by Java bindings to compare all pointers against those returned by its malloc wrap, possibly catching some simple use-after-free or invalid pointer deref bugs. It is exposed only when built as debug and defined in C headers with `LDK_DEBUG_BUILD` defined. --- diff --git a/lightning-c-bindings/cbindgen.toml b/lightning-c-bindings/cbindgen.toml index ec6c74d..f49d50e 100644 --- a/lightning-c-bindings/cbindgen.toml +++ b/lightning-c-bindings/cbindgen.toml @@ -29,3 +29,6 @@ must_use = "MUST_USE_ENUM" [ptr] non_null_attribute = "NONNULL_PTR" + +[defines] +"test_mod_pointers" = "LDK_DEBUG_BUILD" diff --git a/lightning-c-bindings/src/c_types/mod.rs b/lightning-c-bindings/src/c_types/mod.rs index 3d6f08a..98e964f 100644 --- a/lightning-c-bindings/src/c_types/mod.rs +++ b/lightning-c-bindings/src/c_types/mod.rs @@ -14,7 +14,7 @@ use bitcoin::secp256k1::recovery::RecoverableSignature as SecpRecoverableSignatu use bitcoin::bech32; use std::convert::TryInto; // Bindings need at least rustc 1.34 - +use core::ffi::c_void; use std::io::{Cursor, Read}; // TODO: We should use core2 here when we support no_std #[repr(C)] @@ -618,6 +618,18 @@ pub(crate) mod ObjOps { } } +#[cfg(test_mod_pointers)] +#[no_mangle] +/// This function exists for memory safety testing purposes. It should never be used in production +/// code +pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void { + if ptr as usize == 1 { + core::ptr::null() + } else { + unsafe { ptr.cast::().sub(4096).cast::() } + } +} + pub(crate) struct SmartPtr { ptr: *mut T, }