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
use super::ModuleEntry;
use crate::{
    pattern::{Pattern, PatternSearcher},
    process::OwnedProcess,
};
use windows::Win32::System::Threading::PROCESS_VM_READ;

/// Iterator over module pattern occurences.
pub struct ModulePatIter {
    proc: OwnedProcess,
    pat: Pattern,
    from: usize,
    to: usize,
    buf: Box<[u8]>,
}

impl ModulePatIter {
    pub(crate) fn new(pid: u32, from: usize, to: usize, pat: Pattern) -> crate::Result<Self> {
        let proc = OwnedProcess::open_by_id(pid, false, PROCESS_VM_READ)?;

        Ok(Self {
            proc,
            from,
            to,
            buf: vec![0; pat.len()].into_boxed_slice(),
            pat,
        })
    }
}

impl Iterator for ModulePatIter {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if self.from > self.to - self.pat.len() {
            None
        } else {
            loop {
                if let Err(_) = self.proc.read_buf(self.from, &mut self.buf[..]) {
                    return None;
                }

                if self.pat.matches(&self.buf) {
                    break Some(self.from);
                }
                self.from += 1;
            }
        }
    }
}

impl PatternSearcher for ModuleEntry {
    type Output = usize;
    type Iter = ModulePatIter;

    fn find_all(&self, pat: Pattern) -> crate::Result<Self::Iter> {
        Self::Iter::new(
            self.process_id,
            self.base_address,
            self.base_address + self.size,
            pat,
        )
    }
}