Expose a method to unmangle pointers in test builds
authorMatt Corallo <git@bluematt.me>
Mon, 29 Nov 2021 01:28:30 +0000 (01:28 +0000)
committerMatt Corallo <git@bluematt.me>
Tue, 30 Nov 2021 16:05:44 +0000 (16:05 +0000)
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.

lightning-c-bindings/cbindgen.toml
lightning-c-bindings/src/c_types/mod.rs

index ec6c74d97cb08ee5fadb86fc9f28150be38d11e3..f49d50e7d7c148a9de3c346a71cc9b2ff47479c2 100644 (file)
@@ -29,3 +29,6 @@ must_use = "MUST_USE_ENUM"
 
 [ptr]
 non_null_attribute = "NONNULL_PTR"
+
+[defines]
+"test_mod_pointers" = "LDK_DEBUG_BUILD"
index 3d6f08accc3926d3153ecd45aab38498ce0c5f0e..98e964ff6efb5b7d20ec7fe419103ee25f98c6f0 100644 (file)
@@ -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::<u8>().sub(4096).cast::<c_void>() }
+       }
+}
+
 pub(crate) struct SmartPtr<T> {
        ptr: *mut T,
 }