rust_native_obf/
pointer.rs

1use core::hint::black_box;
2
3const fn ptr_mangle<const SEED: u64>(offset: u32) -> usize {
4    let mut val = offset as u64;
5    val ^= SEED;
6    val = val.wrapping_mul(0x517cc1b727220a95);
7    val ^= val >> 27;
8    val = val.wrapping_mul(0x94d049bb133111eb);
9    (val & 0xffff) as usize
10}
11
12#[inline(never)]
13fn restore_ptr<const SEED: u64>(base: *const u8, offset: u32) -> *const u8 {
14    base.wrapping_add(ptr_mangle::<SEED>(offset))
15}
16
17pub fn obf_ref<T: ?Sized, const OFF: u32, const SEED: u64>(r: &'static T) -> &'static T {
18    unsafe {
19        let mut ptr: *const T = r;
20        let base_ptr = (ptr as *const u8).wrapping_sub(ptr_mangle::<SEED>(OFF));
21        let restored = restore_ptr::<SEED>(black_box(base_ptr), black_box(OFF));
22        *(&mut ptr as *mut *const T as *mut *const u8) = restored;
23        &*ptr
24    }
25}
26
27pub fn obf_ref_mut<T: ?Sized, const OFF: u32, const SEED: u64>(r: &'static mut T) -> &'static mut T {
28    unsafe {
29        let mut ptr: *mut T = r;
30        let base_ptr = (ptr as *mut u8).wrapping_sub(ptr_mangle::<SEED>(OFF));
31        let restored = restore_ptr::<SEED>(black_box(base_ptr as *const u8), black_box(OFF)) as *mut u8;
32        *(&mut ptr as *mut *mut T as *mut *mut u8) = restored;
33        &mut *ptr
34    }
35}
36
37#[macro_export]
38macro_rules! obf_static_ref {
39    ($e:expr) => {
40        $crate::pointer::obf_ref::<_,
41            { $crate::ct_rand!(u32, stringify!($e)) },
42            { $crate::ct_rand!(u64, stringify!($e), "ptr") }>($e)
43    };
44}
45
46#[macro_export]
47macro_rules! obf_static_mut {
48    ($e:expr) => {
49        $crate::pointer::obf_ref_mut::<_,
50            { $crate::ct_rand!(u32, stringify!($e)) },
51            { $crate::ct_rand!(u64, stringify!($e), "ptr") }>($e)
52    };
53}
54