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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
extern crate alloc;
use alloc::vec::Vec;

mod searcher;
pub use searcher::*;

use crate::FaitheError;

#[derive(Debug, Clone, Copy)]
pub(crate) enum ByteMatch {
    Exact(u8),
    Any,
}

impl ByteMatch {
    #[inline]
    pub fn matches(&self, b: u8) -> bool {
        match self {
            ByteMatch::Exact(e) => *e == b,
            ByteMatch::Any => true,
        }
    }
}

/// Memory pattern
#[derive(Debug, Clone)]
pub struct Pattern(pub(crate) Vec<ByteMatch>);

impl Pattern {
    pub(crate) fn len(&self) -> usize {
        self.0.len()
    }

    pub(crate) fn matches(&self, data: &[u8]) -> bool {
        data.iter().zip(self.0.iter()).all(|(b, m)| m.matches(*b))
    }
}

impl Pattern {
    /// Parses ida style pattern.
    /// # Panics
    /// Panics if pattern of invalid style was supplied or failed to parse a byte.
    /// ```
    /// # use faithe::pattern::Pattern;
    /// let ida_pat = Pattern::from_ida_style("48 89 85 F0 00 00 00 4C 8B ? ? ? ? ? 48 8D");
    /// ```
    pub fn from_ida_style(pat: impl AsRef<str>) -> Self {
        assert!(pat.as_ref().is_ascii());

        Self(
            pat.as_ref()
                .split_ascii_whitespace()
                .map(|s| {
                    if s == "?" {
                        ByteMatch::Any
                    } else {
                        ByteMatch::Exact(
                            u8::from_str_radix(s, 16).expect("Failed to parse the pattern."),
                        )
                    }
                })
                .collect::<Vec<ByteMatch>>(),
        )
    }

    /// Parses ida style pattern. Same as [`Self::from_ida_style`] but no panics.
    /// # Panics
    /// Panics if pattern of invalid style was supplied or failed to parse a byte.
    /// ```
    /// # use faithe::pattern::Pattern;
    /// let ida_pat = Pattern::from_ida_style("48 89 85 F0 00 00 00 4C 8B ? ? ? ? ? 48 8D");
    /// ```
    pub fn try_from_ida_style(pat: impl AsRef<str>) -> crate::Result<Self> {
        if pat.as_ref().is_ascii() {
            Err(FaitheError::NonAsciiPattern)
        } else {
            Ok(Self(
                pat.as_ref()
                    .split_ascii_whitespace()
                    .map(|s| {
                        if s == "?" {
                            Ok(ByteMatch::Any)
                        } else {
                            if let Ok(b) = u8::from_str_radix(s, 16) {
                                Ok(ByteMatch::Exact(b))
                            } else {
                                Err(FaitheError::InvalidPattern)
                            }
                        }
                    })
                    .collect::<crate::Result<Vec<ByteMatch>>>()?,
            ))
        }
    }

    /// Parses PEiD style pattern.
    /// # Panics
    /// Panics if pattern of invalid style was supplied or failed to parse a byte.
    /// ```
    /// # use faithe::pattern::Pattern;
    /// let peid_pat = Pattern::from_peid_style("48 89 85 F0 00 00 00 4C 8B ?? ?? ?? ?? ?? 48 8D");
    /// ```
    pub fn from_peid_style(pat: impl AsRef<str>) -> Self {
        Self(
            pat.as_ref()
                .split_ascii_whitespace()
                .map(|s| {
                    assert_eq!(s.len(), 2);
                    if s == "??" {
                        ByteMatch::Any
                    } else {
                        ByteMatch::Exact(
                            u8::from_str_radix(s, 16).expect("Failed to parse the pattern."),
                        )
                    }
                })
                .collect::<Vec<ByteMatch>>(),
        )
    }

    /// Parses PEiD style pattern.
    /// # Panics
    /// Panics if pattern of invalid style was supplied or failed to parse a byte.
    /// ```
    /// # use faithe::pattern::Pattern;
    /// let peid_pat = Pattern::from_peid_style("48 89 85 F0 00 00 00 4C 8B ?? ?? ?? ?? ?? 48 8D");
    /// ```
    pub fn try_from_peid_style(pat: impl AsRef<str>) -> crate::Result<Self> {
        if pat.as_ref().is_ascii() {
            Err(FaitheError::NonAsciiPattern)
        } else {
            Ok(Self(
                pat.as_ref()
                    .split_ascii_whitespace()
                    .map(|s| {
                        if s == "??" {
                            Ok(ByteMatch::Any)
                        } else {
                            if let Ok(b) = u8::from_str_radix(s, 16) {
                                Ok(ByteMatch::Exact(b))
                            } else {
                                Err(FaitheError::InvalidPattern)
                            }
                        }
                    })
                    .collect::<crate::Result<Vec<ByteMatch>>>()?,
            ))
        }
    }

    /// Parses code style pattern.
    /// # Panics
    /// Panics if length os mask is not equal to the length of the pattern.
    /// ```
    /// # use faithe::pattern::Pattern;
    /// let code_pat = Pattern::from_code_style(
    ///     b"\x48\x89\x85\xF0\x00\x00\x00\x4C\x8B\x00\x00\x00\x00\x00\x48\x8D",
    ///     b"xxxxxxxxx?????xx"
    /// );
    /// ```
    pub fn from_code_style(pat: &[u8], mask: &[u8]) -> Self {
        assert_eq!(pat.len(), mask.len());

        Self(
            pat.iter()
                .zip(mask.iter())
                .map(|(p, m)| {
                    if *m == b'?' {
                        ByteMatch::Any
                    } else {
                        ByteMatch::Exact(*p)
                    }
                })
                .collect(),
        )
    }

    /// Parses code style pattern.
    /// # Panics
    /// Panics if length os mask is not equal to the length of the pattern.
    /// ```
    /// # use faithe::pattern::Pattern;
    /// let code_pat = Pattern::from_code_style(
    ///     b"\x48\x89\x85\xF0\x00\x00\x00\x4C\x8B\x00\x00\x00\x00\x00\x48\x8D",
    ///     b"xxxxxxxxx?????xx"
    /// );
    /// ```
    pub fn try_from_code_style(pat: &[u8], mask: &[u8]) -> crate::Result<Self> {
        if pat.len() != mask.len() {
            Err(FaitheError::PatternMaskMismatch)
        } else {
            Ok(Self(
                pat.iter()
                    .zip(mask.iter())
                    .map(|(p, m)| {
                        if *m == b'?' {
                            ByteMatch::Any
                        } else {
                            ByteMatch::Exact(*p)
                        }
                    })
                    .collect(),
            ))
        }
    }
}

impl Pattern {
    /// Finds all pattern occurences in memory range
    /// Panics
    /// if `from` > `to`
    pub unsafe fn find_all(
        &self,
        from: *const u8,
        to: *const u8,
    ) -> impl Iterator<Item = *const u8> + '_ {
        assert!(to as usize >= from as usize);

        core::slice::from_raw_parts(from, to.offset_from(from) as usize)
            .windows(self.len())
            .enumerate()
            .filter(|(_, w)| self.matches(*w))
            .map(move |(i, _)| from.add(i))
    }
}