Skip to main content

procodile/scan/
pattern.rs

1//! Array-of-bytes (signature) scanning.
2
3use std::fmt;
4use std::ops::Range;
5use std::str::FromStr;
6
7use super::{Progress, chunks_where, par_map};
8use crate::{Address, Error, ProcessHandle, Result};
9
10/// A byte pattern with wildcards, written IDA-style: `48 8b ?? ?? 89 05`.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Pattern {
13    /// `None` matches any byte.
14    bytes: Vec<Option<u8>>,
15}
16
17impl Pattern {
18    pub fn exact(bytes: &[u8]) -> Self {
19        Self {
20            bytes: bytes.iter().copied().map(Some).collect(),
21        }
22    }
23
24    pub fn len(&self) -> usize {
25        self.bytes.len()
26    }
27
28    pub fn is_empty(&self) -> bool {
29        self.bytes.is_empty()
30    }
31
32    pub fn matches(&self, haystack: &[u8]) -> bool {
33        haystack.len() >= self.len()
34            && self
35                .bytes
36                .iter()
37                .zip(haystack)
38                .all(|(p, b)| p.is_none_or(|p| p == *b))
39    }
40
41    /// Offsets in `haystack` where the pattern starts, below `limit`.
42    fn find_in(&self, haystack: &[u8], limit: usize, out: &mut Vec<usize>) {
43        let Some(anchor) = self.bytes.iter().position(Option::is_some) else {
44            out.extend(0..limit.min((haystack.len() + 1).saturating_sub(self.len())));
45            return;
46        };
47        let anchor_byte = self.bytes[anchor].unwrap();
48        let mut start = 0;
49        while start < limit && start + self.len() <= haystack.len() {
50            let window = &haystack[start + anchor..=haystack.len() - self.len() + anchor];
51            let Some(hit) = window.iter().position(|&b| b == anchor_byte) else {
52                break;
53            };
54            let candidate = start + hit;
55            if candidate >= limit {
56                break;
57            }
58            if self.matches(&haystack[candidate..]) {
59                out.push(candidate);
60            }
61            start = candidate + 1;
62        }
63    }
64}
65
66impl FromStr for Pattern {
67    type Err = ParsePatternError;
68
69    /// Accepts space-separated hex bytes and `?`/`??` wildcards. Without spaces the input
70    /// is read two characters at a time (`488b??89`).
71    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
72        let err = || ParsePatternError(s.to_owned());
73        let tokens: Vec<&str> = if s.contains(char::is_whitespace) {
74            s.split_whitespace().collect()
75        } else {
76            if !s.len().is_multiple_of(2) || !s.is_ascii() {
77                return Err(err());
78            }
79            (0..s.len()).step_by(2).map(|i| &s[i..i + 2]).collect()
80        };
81        let bytes = tokens
82            .into_iter()
83            .map(|t| match t {
84                "?" | "??" => Ok(None),
85                _ if t.len() <= 2 => u8::from_str_radix(t, 16).map(Some).map_err(|_| err()),
86                _ => Err(err()),
87            })
88            .collect::<std::result::Result<Vec<_>, _>>()?;
89        if bytes.is_empty() {
90            return Err(err());
91        }
92        Ok(Self { bytes })
93    }
94}
95
96impl fmt::Display for Pattern {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        for (i, b) in self.bytes.iter().enumerate() {
99            if i > 0 {
100                f.write_str(" ")?;
101            }
102            match b {
103                Some(b) => write!(f, "{b:02x}")?,
104                None => f.write_str("??")?,
105            }
106        }
107        Ok(())
108    }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
112#[error("invalid byte pattern '{0}' (expected e.g. \"48 8b ?? 05\")")]
113pub struct ParsePatternError(pub String);
114
115#[derive(Debug, Clone, Default)]
116pub struct PatternOptions {
117    /// Restrict the search to this range, e.g. one module's span.
118    pub range: Option<Range<Address>>,
119    /// Only search executable memory, where code signatures live.
120    pub executable_only: bool,
121    /// Stop after this many matches; `0` means no limit.
122    pub limit: usize,
123}
124
125/// Finds every address where `pattern` occurs in readable memory, in address order.
126pub fn find_pattern(
127    handle: &ProcessHandle,
128    pattern: &Pattern,
129    options: &PatternOptions,
130    progress: Option<&Progress>,
131) -> Result<Vec<Address>> {
132    if pattern.is_empty() {
133        return Err(Error::InvalidScan("empty pattern".into()));
134    }
135    let chunks = chunks_where(handle, options.range.as_ref(), pattern.len(), |r| {
136        !options.executable_only || r.protection.executable()
137    })?;
138    let fallback = Progress::new();
139    let progress = progress.unwrap_or(&fallback);
140    progress.start(chunks.iter().map(|c| c.positions as u64).sum());
141
142    let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
143    let parts = par_map(&chunks, threads, |chunk| {
144        let mut offsets = Vec::new();
145        if !progress.is_cancelled() {
146            let mut bytes = vec![0; chunk.len];
147            let read = handle.read_bytes(chunk.base, &mut bytes).unwrap_or(0);
148            pattern.find_in(&bytes[..read], chunk.positions, &mut offsets);
149            progress.advance(chunk.positions);
150        }
151        offsets
152            .into_iter()
153            .map(|o| chunk.base + o)
154            .collect::<Vec<_>>()
155    });
156    if progress.is_cancelled() {
157        return Err(Error::Cancelled);
158    }
159
160    let mut found: Vec<Address> = parts.into_iter().flatten().collect();
161    if options.limit > 0 {
162        found.truncate(options.limit);
163    }
164    Ok(found)
165}
166
167#[cfg(test)]
168mod tests {
169    use std::hint::black_box;
170
171    use super::*;
172
173    #[test]
174    fn parse_patterns() {
175        let p: Pattern = "48 8B ?? ? 05".parse().unwrap();
176        assert_eq!(p.to_string(), "48 8b ?? ?? 05");
177        assert_eq!("488b??05".parse::<Pattern>().unwrap().len(), 4);
178        assert!("48 8g".parse::<Pattern>().is_err());
179        assert!("".parse::<Pattern>().is_err());
180    }
181
182    #[test]
183    fn find_in_buffer() {
184        let p: Pattern = "aa ?? cc".parse().unwrap();
185        let mut out = Vec::new();
186        p.find_in(&[0xaa, 0x00, 0xcc, 0xaa, 0xbb, 0xcc, 0xaa], 100, &mut out);
187        assert_eq!(out, [0, 3]);
188
189        out.clear();
190        p.find_in(&[0xaa, 0x00, 0xcc, 0xaa, 0xbb, 0xcc], 3, &mut out);
191        assert_eq!(out, [0]);
192    }
193
194    #[test]
195    fn finds_signature_in_heap() {
196        let handle = ProcessHandle::open_current().unwrap();
197        let mut buf = vec![0u8; 4096];
198        buf[1000..1008].copy_from_slice(&[0x13, 0x37, 0xde, 0xad, 0x99, 0xbe, 0xef, 0x42]);
199        let start = Address::new(buf.as_ptr() as usize);
200        let options = PatternOptions {
201            range: Some(start..start + buf.len()),
202            ..Default::default()
203        };
204        let pattern: Pattern = black_box("13 37 de ad ?? be ef 42").parse().unwrap();
205        let found = find_pattern(&handle, &pattern, &options, None).unwrap();
206        assert_eq!(found, [start + 1000]);
207    }
208}