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
use super::OwnedProcess;
use windows::Win32::System::Memory::{
    PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_NOACCESS,
    PAGE_PROTECTION_FLAGS, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY,
};

/// Allows to easily query process memory.
pub struct Query<'a>(pub(crate) &'a OwnedProcess);
impl<'a> Query<'a> {
    /// Checks if it's possible to read memory at the address.
    #[inline]
    pub fn read_at(&self, addr: usize) -> bool {
        if let Ok(mem) = self.0.query_memory(addr) {
            return (mem.protection.0 & PAGE_READONLY.0 != 0)
                || (mem.protection.0 & PAGE_READWRITE.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_READ.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_READWRITE.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_WRITECOPY.0 != 0);
        }
        false
    }

    /// Checks if it's possible to write memory to the address.
    #[inline]
    pub fn write_at(&self, addr: usize) -> bool {
        if let Ok(mem) = self.0.query_memory(addr) {
            return (mem.protection.0 & PAGE_WRITECOPY.0 != 0)
                || (mem.protection.0 & PAGE_READWRITE.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_READWRITE.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_WRITECOPY.0 != 0);
        }
        false
    }

    /// Checks if it's possible to execute memory at the address.
    #[inline]
    pub fn execute_at(&self, addr: usize) -> bool {
        if let Ok(mem) = self.0.query_memory(addr) {
            return (mem.protection.0 & PAGE_EXECUTE.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_READ.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_READWRITE.0 != 0)
                || (mem.protection.0 & PAGE_EXECUTE_WRITECOPY.0 != 0);
        }
        false
    }

    /// Returns the start of the next allocated chunk
    #[inline]
    pub fn boundary(&self, addr: usize) -> Option<usize> {
        self.0
            .query_memory(addr)
            .ok()
            .map(|m| m.alloc_base + m.region_size)
    }

    /// Returns the base address of this allocated chunk.
    #[inline]
    pub fn base(&self, addr: usize) -> Option<usize> {
        self.0.query_memory(addr).ok().map(|m| m.alloc_base)
    }

    /// Returns the protection of the memory
    #[inline]
    pub fn access(&self, addr: usize) -> PAGE_PROTECTION_FLAGS {
        self.0
            .query_memory(addr)
            .map(|m| m.protection)
            .unwrap_or(PAGE_NOACCESS)
    }
}