summaryrefslogtreecommitdiff
path: root/crates/windows-kernel-rs/src/memory.rs
blob: d2ad77b971b609eb3d225461bbac270d3b2935a3 (plain) (blame)
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
use windows_kernel_sys::base::{
  MM_COPY_ADDRESS,
  MM_COPY_MEMORY_PHYSICAL,
  MM_COPY_MEMORY_VIRTUAL,
  PHYSICAL_ADDRESS,
  _MEMORY_CACHING_TYPE as MEMORY_CACHING_TYPE,
};

use crate::error::{Error, IntoResult};

#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MemoryCaching {
  NonCached          = MEMORY_CACHING_TYPE::MmNonCached,
  Cached             = MEMORY_CACHING_TYPE::MmCached,
  WriteCombined      = MEMORY_CACHING_TYPE::MmWriteCombined,
  #[cfg(feature = "system")]
  HardwareCoherentCached = MEMORY_CACHING_TYPE::MmHardwareCoherentCached,
  #[cfg(feature = "system")]
  NonCachedUnordered = MEMORY_CACHING_TYPE::MmNonCachedUnordered,
  #[cfg(feature = "system")]
  USWCCached         = MEMORY_CACHING_TYPE::MmUSWCCached,
  NotMapped          = MEMORY_CACHING_TYPE::MmNotMapped,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct PhysicalAddress(u64);

impl From<u64> for PhysicalAddress {
  fn from(value: u64) -> Self { Self(value) }
}

// impl Into<u64> for PhysicalAddress {
//   fn into(self) -> u64 { self.0 }
// }
impl From<PhysicalAddress> for u64 {
  fn from(p: PhysicalAddress) -> Self {
    p.0
  }
}

impl From<PHYSICAL_ADDRESS> for PhysicalAddress {
  fn from(value: PHYSICAL_ADDRESS) -> Self { Self(unsafe { value.QuadPart } as _) }
}

// impl Into<PHYSICAL_ADDRESS> for PhysicalAddress {
//   fn into(self) -> PHYSICAL_ADDRESS {
//     let mut addr: PHYSICAL_ADDRESS = unsafe { core::mem::zeroed() };
//
//     addr.QuadPart = self.0 as _;
//
//     addr
//   }
// }
impl From<PhysicalAddress> for PHYSICAL_ADDRESS {
  fn from(p: PhysicalAddress) -> Self {
    let mut addr: PHYSICAL_ADDRESS = unsafe { core::mem::zeroed() };

    addr.QuadPart = p.0 as _;

    addr
  }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CopyAddress {
  Virtual(*mut core::ffi::c_void),
  Physical(PhysicalAddress),
}

unsafe impl Send for CopyAddress {}
unsafe impl Sync for CopyAddress {}

// impl Into<(u32, MM_COPY_ADDRESS)> for CopyAddress {
//   fn into(self) -> (u32, MM_COPY_ADDRESS) {
//     let mut copy_addr: MM_COPY_ADDRESS = unsafe { core::mem::zeroed() };
//
//     let flags = match self {
//       CopyAddress::Virtual(addr) => {
//         copy_addr.__bindgen_anon_1.VirtualAddress = addr as _;
//         MM_COPY_MEMORY_VIRTUAL
//       }
//       CopyAddress::Physical(addr) => {
//         copy_addr.__bindgen_anon_1.PhysicalAddress = addr.into();
//         MM_COPY_MEMORY_PHYSICAL
//       }
//     };
//
//     (flags, copy_addr)
//   }
// }
impl From<CopyAddress> for (u32, MM_COPY_ADDRESS) {
  fn from(c: CopyAddress) -> Self {
    let mut copy_addr: MM_COPY_ADDRESS = unsafe { core::mem::zeroed() };

    let flags = match c {
      CopyAddress::Virtual(addr) => {
        copy_addr.__bindgen_anon_1.VirtualAddress = addr as _;
        MM_COPY_MEMORY_VIRTUAL
      }
      CopyAddress::Physical(addr) => {
        copy_addr.__bindgen_anon_1.PhysicalAddress = addr.into();
        MM_COPY_MEMORY_PHYSICAL
      }
    };

    (flags, copy_addr)
  }
}

pub struct IoMapping {
  ptr:  *mut core::ffi::c_void,
  size: usize,
}

unsafe impl Send for IoMapping {}
unsafe impl Sync for IoMapping {}

impl IoMapping {
  pub fn new(addr: PhysicalAddress, size: usize, caching: MemoryCaching) -> Result<Self, Error> {
    use windows_kernel_sys::ntoskrnl::MmMapIoSpace;

    let ptr = unsafe { MmMapIoSpace(addr.into(), size as _, caching as _) };

    if ptr.is_null() {
      return Err(Error::INVALID_PARAMETER);
    }

    Ok(Self {
      ptr,
      size,
    })
  }

  pub fn ptr(&self) -> *mut core::ffi::c_void { self.ptr }

  pub fn size(&self) -> usize { self.size }
}

impl Drop for IoMapping {
  fn drop(&mut self) {
    use windows_kernel_sys::ntoskrnl::MmUnmapIoSpace;

    unsafe {
      MmUnmapIoSpace(self.ptr, self.size as _);
    }
  }
}

#[cfg(feature = "system")]
pub fn get_virtual_for_physical(addr: PhysicalAddress) -> *mut core::ffi::c_void {
  use windows_kernel_sys::ntoskrnl::MmGetVirtualForPhysical;

  let virt_addr = unsafe { MmGetVirtualForPhysical(addr.into()) };

  virt_addr as _
}

pub fn read_memory(buffer: &mut [u8], source: CopyAddress) -> Result<usize, Error> {
  use windows_kernel_sys::ntoskrnl::MmCopyMemory;

  let (flags, copy_addr) = source.into();
  let mut bytes = 0;

  unsafe {
    MmCopyMemory(
      buffer.as_mut_ptr() as _,
      copy_addr,
      buffer.len() as _,
      flags,
      &mut bytes,
    )
  }
  .into_result()?;

  Ok(bytes as _)
}

#[cfg(feature = "system")]
pub fn write_memory(target: CopyAddress, buffer: &[u8]) -> Result<usize, Error> {
  use windows_kernel_sys::ntoskrnl::MmCopyMemory;

  let mut copy_addr: MM_COPY_ADDRESS = unsafe { core::mem::zeroed() };
  let mut bytes = 0;

  let target = match target {
    CopyAddress::Virtual(addr) => addr,
    CopyAddress::Physical(addr) => get_virtual_for_physical(addr),
  };

  copy_addr.__bindgen_anon_1.VirtualAddress = buffer.as_ptr() as _;

  unsafe {
    MmCopyMemory(
      target as _,
      copy_addr,
      buffer.len() as _,
      MM_COPY_MEMORY_VIRTUAL,
      &mut bytes,
    )
  }
  .into_result()?;

  Ok(bytes as _)
}