isr_macros/
symbols.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use crate::Error;

/// A symbol descriptor.
#[derive(Debug, Clone)]
pub struct SymbolDescriptor {
    /// The virtual address offset of the symbol.
    pub offset: u64,
}

impl TryFrom<SymbolDescriptor> for u64 {
    type Error = Error;

    fn try_from(value: SymbolDescriptor) -> Result<Self, Self::Error> {
        Ok(value.offset)
    }
}

//
//
//

pub trait IntoSymbol<T> {
    type Error;

    fn into_symbol(self) -> Result<T, Error>;
}

impl IntoSymbol<u64> for Result<SymbolDescriptor, Error> {
    type Error = Error;

    fn into_symbol(self) -> Result<u64, Error> {
        self?.try_into()
    }
}

impl IntoSymbol<Option<u64>> for Result<SymbolDescriptor, Error> {
    type Error = Error;

    fn into_symbol(self) -> Result<Option<u64>, Error> {
        match self {
            Ok(symbol) => Ok(Some(symbol.try_into()?)),
            Err(_) => Ok(None),
        }
    }
}

/// Defines a set of symbols.
///
/// This macro simplifies the process of defining symbols for later use with the `isr` crate,
/// enabling type-safe access to symbol addresses and offsets. It generates a struct
/// with fields corresponding to the defined symbols.
///
/// # Usage
///
/// ```rust
/// # use isr::{
/// #     cache::{Codec as _, JsonCodec},
/// #     macros::symbols,
/// # };
/// #
/// symbols! {
///     #[derive(Debug)]
///     pub struct Symbols {
///         PsActiveProcessHead: u64,
///
///         // Optional symbols might be missing from profile.
///         PsInitialSystemProcess: Option<u64>,
///         NonExistentSymbol: Option<u64>,
///
///         // Provide aliases when symbols might have different names across builds.
///         #[isr(alias = "KiSystemCall64Shadow")]
///         KiSystemCall64: u64,
///
///         // Multiple aliases for a symbol.
///         #[isr(alias = ["_NtOpenFile@24", "NtOpenFile"])]
///         NtOpenFile: u64, // Address of the NtOpenFile function
///     }
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Use the profile of a Windows 10.0.18362.356 kernel.
/// # let profile = JsonCodec::decode(include_bytes!("../../../tests/assets/cache/windows/ntkrnlmp.pdb/ce7ffb00c20b87500211456b3e905c471/profile.json"))?;
/// let symbols = Symbols::new(&profile)?;
/// assert_eq!(symbols.PsActiveProcessHead, 0x437BC0);
/// assert_eq!(symbols.PsInitialSystemProcess, Some(0x5733A0));
/// assert_eq!(symbols.NonExistentSymbol, None);
/// # Ok(())
/// # }
/// ```
///
/// # Attributes
///
/// - `#[isr(alias = "alternative_name")]`: Specifies an alternative name for the
///   symbol. This is useful when the symbol has different names across different
///   OS builds or versions.
///
/// - `#[isr(alias = ["name1", "name2", ...])]`: Specifies multiple alternative
///   names for the symbol.
///
/// The generated struct provides a `new` method that takes a reference to an
/// [`Profile`] and returns a `Result` containing the populated struct or an
/// error if any symbols are not found.
///
/// [`Profile`]: isr_core::Profile
#[macro_export]
macro_rules! symbols {
    (
        $(#[$symbols_attrs:meta])*
        $vis:vis struct $name:ident {
            $(
                $(#[isr($($isr_attr:tt)*)])?
                $fname:ident: $ftype:ty
            ),+ $(,)?
        }
    ) => {
        $(#[$symbols_attrs])*
        #[allow(non_camel_case_types, non_snake_case, missing_docs)]
        $vis struct $name {
            $($vis $fname: $ftype),+
        }

        impl $name {
            /// Creates a new symbol instance.
            $vis fn new(profile: &$crate::__private::Profile) -> Result<Self, $crate::Error> {
                use $crate::__private::IntoSymbol as _;

                Ok(Self {
                    $(
                        $fname: $crate::symbols!(@assign
                            profile,
                            $fname,
                            [$($($isr_attr)*)?]
                        ).into_symbol()?,
                    )*
                })
            }
        }
    };

    (@assign
        $profile:ident,
        $fname:ident,
        []
    ) => {{
        use $crate::__private::ProfileExt as _;

        $profile
            .find_symbol_descriptor(stringify!($fname))
    }};

    (@assign
        $profile:ident,
        $fname:ident,
        [alias = $alias:literal]
    ) => {{
        use $crate::__private::ProfileExt as _;

        $profile
            .find_symbol_descriptor(stringify!($fname))
            .or_else(|_| $profile
                .find_symbol_descriptor($alias)
            )
    }};

    (@assign
        $profile:ident,
        $fname:ident,
        [alias = [$($alias:literal),+ $(,)?]]
    ) => {{
        use $crate::__private::ProfileExt as _;

        $profile
            .find_symbol_descriptor(stringify!($fname))
            $(
                .or_else(|_| $profile
                    .find_symbol_descriptor($alias)
                )
            )+
    }};
}