Skip to main content

fromsoftware_shared/
unknown_pointer.rs

1use std::{ffi::c_void, fmt};
2
3use crate::{Program, vftable_classname};
4
5/// A pointer whose target has not yet been reverse-engineered.
6///
7/// ## Safety
8///
9/// This may be null and has no particular alignment requirements, but it does
10/// require that if it's not nullit must point within the current process's
11/// memory space.
12#[repr(transparent)]
13#[derive(Clone, Copy)]
14pub struct UnknownPtr(*const c_void);
15
16impl UnknownPtr {
17    /// Interprets `value` as a pointer.
18    ///
19    /// ## Safety
20    ///
21    /// The caller must ensure that `value` is either 0 or a valid address in
22    /// the current address space.
23    pub unsafe fn from(value: usize) -> Self {
24        UnknownPtr(value as *const c_void)
25    }
26
27    /// Returns the class name for this pointer, if it's pointing to a vftable
28    /// whose name is in the RTTI.
29    pub fn rtti_classname(&self) -> Option<String> {
30        if self.0.is_null() {
31            return None;
32        }
33
34        let usize_ptr = self.cast::<usize>();
35        if !usize_ptr.is_aligned() {
36            return None;
37        }
38
39        // Even though we don't have any guarantees about what the pointer
40        // points to, we know it's aligned for `usize` and it's within the
41        // current address space so dereferencing it should be safe.
42        vftable_classname(&Program::current(), unsafe { *usize_ptr })
43    }
44
45    /// Returns `true` if this pointer is null.
46    pub fn is_null(&self) -> bool {
47        self.0.is_null()
48    }
49
50    /// Casts this to a pointer to `T`.
51    pub fn cast<T>(self) -> *const T {
52        self.0.cast::<T>()
53    }
54
55    /// Gets the "address" portion of the pointer.
56    pub fn addr(self) -> usize {
57        self.0.addr()
58    }
59}
60
61impl fmt::Debug for UnknownPtr {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
63        if let Some(name) = self.rtti_classname() {
64            write!(f, "{:?} [{name}*]", self.0)
65        } else {
66            fmt::Debug::fmt(&self.0, f)
67        }
68    }
69}
70
71impl fmt::Pointer for UnknownPtr {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
73        if let Some(name) = self.rtti_classname() {
74            write!(f, "{:p} [{name}*]", self.0)
75        } else {
76            fmt::Pointer::fmt(&self.0, f)
77        }
78    }
79}