├── .gitattributes ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── kernel.rs ├── lib.rs ├── memory_protection.rs ├── pid_util.rs ├── render.rs ├── slice_impl.rs └── tests.rs /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | 13 | #Added by cargo 14 | 15 | /target 16 | 17 | 18 | #Added by cargo 19 | # 20 | #already existing elements were commented out 21 | 22 | #/target 23 | #Cargo.lock 24 | 25 | .idea 26 | 27 | *.dmp.exe 28 | *.dmp 29 | 30 | imgui.ini 31 | 32 | # Added by cargo 33 | # 34 | # already existing elements were commented out 35 | 36 | #/target 37 | #Cargo.lock 38 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "memlib" 3 | version = "0.1.3" 4 | edition = "2021" 5 | authors = ["Ryan McCrystal"] 6 | readme = "README.md" 7 | repository = "https://github.com/rmccrystal/memlib-rs" 8 | license = "MIT" 9 | description = "An abstraction layer for interacting with memory" 10 | 11 | [features] 12 | kernel = [] 13 | render = [] 14 | test = ["env_logger", "log"] 15 | 16 | [dependencies] 17 | dataview = "1" 18 | auto_impl = "0.5.0" 19 | bitflags = "1.3.2" 20 | 21 | env_logger = { version = "0.9.0", optional = true } 22 | log = { version = "0.4.16", optional = true } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Ryan McCrystal 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # memlib 2 | 3 | Memlib is an abstraction layer for dealing with raw memory buffers, especially when dealing with process memory. 4 | It contains many traits that can be used across crates to have a common interface for dealing with memory. 5 | The core traits of this library are `MemoryRead` and `MemoryWrite` which contain extensive utility functions 6 | in the form of extension traits `MemoryReadExt` and `MemoryWriteExt`. This crate also contains other traits dealing 7 | with memory, including or `ModuleList`, `MemoryProtect`, `MemoryAllocate`. There are many more traits available 8 | for dealing with utility functions and overlay rendering. 9 | -------------------------------------------------------------------------------- /src/kernel.rs: -------------------------------------------------------------------------------- 1 | use crate::{MemoryRead, MemoryWrite}; 2 | 3 | /// Represents a type that can load and unload a kernel exploit 4 | pub trait LoadDriver { 5 | type DriverType: KernelMemoryRead + KernelMemoryWrite + MapPhysical + TranslatePhysical; 6 | 7 | fn load(&self) -> Option; 8 | fn unload(&self) -> Option<()>; 9 | } 10 | 11 | /// Implementing this trait marks that a MemoryRead implementation can read from kernel memory 12 | pub trait KernelMemoryRead: MemoryRead {} 13 | 14 | /// Implementing this trait marks that a MemoryWrite implementation can write to kernel memory 15 | pub trait KernelMemoryWrite: MemoryWrite {} 16 | 17 | /// A trait that represents a type that can read physical memory 18 | pub trait PhysicalMemoryRead { 19 | /// Reads bytes at a physical address into the buffer 20 | fn try_read_bytes_physical_into(&self, physical_address: u64, buffer: &mut [u8]) -> Option<()>; 21 | 22 | /// A utility type that transforms Self into a type that implements memlib::MemoryRead 23 | /// so memlib's utility functions can be used 24 | fn physical_reader(&self) -> PhysicalMemoryReader 25 | where Self: Sized { 26 | PhysicalMemoryReader::new(self) 27 | } 28 | 29 | /// Returns a type that uses the TranslatePhysical implementation to read virtual addresses using the physical memory reader 30 | fn virtual_reader(&self) -> VirtualMemoryReader 31 | where Self: Sized + TranslatePhysical { 32 | VirtualMemoryReader::new(self) 33 | } 34 | } 35 | 36 | pub struct VirtualMemoryReader<'a, T: PhysicalMemoryRead + TranslatePhysical>(&'a T); 37 | 38 | impl<'a, T: PhysicalMemoryRead + TranslatePhysical> VirtualMemoryReader<'a, T> { 39 | fn new(api: &'a T) -> Self { 40 | Self(api) 41 | } 42 | } 43 | 44 | impl<'a, T: PhysicalMemoryRead + TranslatePhysical> MemoryRead for VirtualMemoryReader<'a, T> { 45 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 46 | let physical_address = self.0.physical_address(address)?; 47 | self.0.try_read_bytes_physical_into(physical_address, buffer) 48 | } 49 | } 50 | 51 | impl<'a, T: PhysicalMemoryRead + TranslatePhysical> KernelMemoryRead for VirtualMemoryReader<'a, T> {} 52 | 53 | pub struct PhysicalMemoryReader<'a, T: PhysicalMemoryRead>(&'a T); 54 | 55 | impl<'a, T: PhysicalMemoryRead> PhysicalMemoryReader<'a, T> { 56 | pub fn new(api: &'a T) -> Self { 57 | Self(api) 58 | } 59 | } 60 | 61 | impl<'a, T: PhysicalMemoryRead> MemoryRead for PhysicalMemoryReader<'a, T> { 62 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 63 | self.0.try_read_bytes_physical_into(address, buffer) 64 | } 65 | } 66 | 67 | /// A trait that represents a type that can write physical memory 68 | pub trait PhysicalMemoryWrite { 69 | /// Writes bytes at a physical address from the buffer 70 | fn try_write_bytes_physical(&self, physical_address: u64, buffer: &[u8]) -> Option<()>; 71 | 72 | /// A utility type that transforms Self into a type that implements memlib::MemoryWrite 73 | /// so memlib's utility functions can be used 74 | fn physical_writer(&self) -> PhysicalMemoryWriter 75 | where Self: Sized { 76 | PhysicalMemoryWriter::new(self) 77 | } 78 | 79 | /// A utility type that transforms Self into a type that implements memlib::MemoryWrite + memlib::MemoryRead 80 | /// so memlib's utility functions can be used 81 | fn physical(&self) -> PhysicalMemory 82 | where Self: Sized + PhysicalMemoryRead { 83 | PhysicalMemory::new(self) 84 | } 85 | 86 | /// A utility type that transforms Self into a type that writes virtual memory using physical memory 87 | fn virtual_writer(&self) -> VirtualMemoryWriter 88 | where Self: Sized + TranslatePhysical { 89 | VirtualMemoryWriter::new(self) 90 | } 91 | 92 | /// A utility type that transforms Self into a type that reads and writes virtual memory using physical memory and TranslatePhysical 93 | fn virtual_memory(&self) -> VirtualMemory 94 | where Self: Sized + TranslatePhysical + PhysicalMemoryRead { 95 | VirtualMemory::new(self) 96 | } 97 | } 98 | 99 | pub struct VirtualMemory<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite + TranslatePhysical>(&'a T); 100 | 101 | impl<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite + TranslatePhysical> VirtualMemory<'a, T> { 102 | pub fn new(api: &'a T) -> Self { 103 | Self(api) 104 | } 105 | } 106 | 107 | impl<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite + TranslatePhysical> MemoryRead for VirtualMemory<'a, T> { 108 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 109 | let physical_address = self.0.physical_address(address)?; 110 | self.0.try_read_bytes_physical_into(physical_address, buffer) 111 | } 112 | } 113 | 114 | impl<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite + TranslatePhysical> MemoryWrite for VirtualMemory<'a, T> { 115 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()> { 116 | let physical_address = self.0.physical_address(address)?; 117 | self.0.try_write_bytes_physical(physical_address, buffer) 118 | } 119 | } 120 | 121 | pub struct VirtualMemoryWriter<'a, T: PhysicalMemoryWrite + TranslatePhysical>(&'a T); 122 | 123 | impl<'a, T: PhysicalMemoryWrite + TranslatePhysical> VirtualMemoryWriter<'a, T> { 124 | pub fn new(api: &'a T) -> Self { 125 | Self(api) 126 | } 127 | } 128 | 129 | impl<'a, T: PhysicalMemoryWrite + TranslatePhysical> MemoryWrite for VirtualMemoryWriter<'a, T> { 130 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()> { 131 | let physical_address = self.0.physical_address(address)?; 132 | self.0.try_write_bytes_physical(physical_address, buffer) 133 | } 134 | } 135 | 136 | impl<'a, T: PhysicalMemoryWrite + TranslatePhysical> KernelMemoryWrite for VirtualMemoryWriter<'a, T> {} 137 | 138 | pub struct PhysicalMemoryWriter<'a, T: PhysicalMemoryWrite>(&'a T); 139 | 140 | impl<'a, T: PhysicalMemoryWrite> PhysicalMemoryWriter<'a, T> { 141 | pub fn new(api: &'a T) -> Self { 142 | Self(api) 143 | } 144 | } 145 | 146 | impl<'a, T: PhysicalMemoryWrite> MemoryWrite for PhysicalMemoryWriter<'a, T> { 147 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()> { 148 | self.0.try_write_bytes_physical(address, buffer) 149 | } 150 | } 151 | 152 | pub struct PhysicalMemory<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite>(&'a T); 153 | 154 | impl<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite> PhysicalMemory<'a, T> { 155 | pub fn new(api: &'a T) -> Self { 156 | Self(api) 157 | } 158 | } 159 | 160 | impl<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite> MemoryRead for PhysicalMemory<'a, T> { 161 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 162 | self.0.try_read_bytes_physical_into(address, buffer) 163 | } 164 | } 165 | 166 | impl<'a, T: PhysicalMemoryRead + PhysicalMemoryWrite> MemoryWrite for PhysicalMemory<'a, T> { 167 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()> { 168 | self.0.try_write_bytes_physical(address, buffer) 169 | } 170 | } 171 | 172 | /// A trait for types that can call MmMapIoSpace, ZwMapViewOfSection, or any other way of mapping physical memory 173 | /// to a virtual buffer that can be used by KernelMemoryRead and KernelMemoryWrite. Note that the virtual memory 174 | /// created by this trait cannot be read directly 175 | pub trait MapPhysical { 176 | /// Maps a physical address into virtual memory with the specified size. 177 | /// Returns a usize pointing to the base of the mapped memory 178 | /// # Safety 179 | /// If this function is used incorrectly the computer may blue screen 180 | unsafe fn map_io_space(&self, physical_address: u64, size: usize) -> Option; 181 | 182 | /// Unmaps a physical address mapped with map_io_space 183 | /// # Safety 184 | /// This function may blue screen if invalid information is passed in the parameters 185 | unsafe fn unmap_io_space(&self, virtual_address: u64, size: usize) -> Option<()>; 186 | 187 | /// Nicer api for mapping physical memory. Maps a physical section according to the parameters 188 | /// and returns a MappedPhysicalMemory struct which implements MemoryRead and MemoryWrite, allowing 189 | /// reading and memory of the mapped buffer (note that the addresses start at zero when reading) 190 | /// This struct will automatically unmap its memory when it is dropped. 191 | fn map_physical(&self, physical_address: u64, size: usize) -> Option> 192 | where 193 | Self: Sized + KernelMemoryRead + KernelMemoryWrite, 194 | { 195 | unsafe { 196 | self.map_io_space(physical_address, size) 197 | .map(|base| MappedPhysicalMemory::new(self, base, size)) 198 | } 199 | } 200 | 201 | /// Converts the specified virtual address and then calls `map_physical`. 202 | fn map_virtual(&self, virtual_address: u64, size: usize) -> Option> 203 | where 204 | Self: Sized + KernelMemoryRead + KernelMemoryWrite + TranslatePhysical, 205 | { 206 | let phys = self.physical_address(virtual_address)?; 207 | self.map_physical(phys, size) 208 | } 209 | } 210 | 211 | impl PhysicalMemoryRead for T { 212 | fn try_read_bytes_physical_into(&self, physical_address: u64, buffer: &mut [u8]) -> Option<()> { 213 | unsafe { 214 | let map = self.map_io_space(physical_address, buffer.len())?; 215 | self.try_read_bytes_into(map, buffer)?; 216 | self.unmap_io_space(map, buffer.len())?; 217 | Some(()) 218 | } 219 | } 220 | } 221 | 222 | impl PhysicalMemoryWrite for T { 223 | fn try_write_bytes_physical(&self, physical_address: u64, buffer: &[u8]) -> Option<()> { 224 | unsafe { 225 | let map = self.map_io_space(physical_address, buffer.len())?; 226 | self.try_write_bytes(map, buffer)?; 227 | self.unmap_io_space(map, buffer.len())?; 228 | Some(()) 229 | } 230 | } 231 | } 232 | 233 | pub trait TranslatePhysical { 234 | fn physical_address(&self, virtual_address: u64) -> Option; 235 | } 236 | 237 | /// A struct describing a buffer of mapped physical memory generated by the MapPhysical trait 238 | pub struct MappedPhysicalMemory<'a, T: MapPhysical + KernelMemoryRead + KernelMemoryWrite> { 239 | api: &'a T, 240 | base: u64, 241 | size: usize, 242 | } 243 | 244 | impl<'a, T: MapPhysical + KernelMemoryRead + KernelMemoryWrite> MappedPhysicalMemory<'a, T> { 245 | pub(crate) unsafe fn new(api: &'a T, base: u64, size: usize) -> Self { 246 | Self { api, base, size } 247 | } 248 | } 249 | 250 | impl<'a, T: MapPhysical + KernelMemoryRead + KernelMemoryWrite> crate::MemoryRead 251 | for MappedPhysicalMemory<'a, T> 252 | { 253 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 254 | if address + buffer.len() as u64 > self.base + self.size as u64 { 255 | return None; 256 | } 257 | self.api 258 | .try_read_bytes_into(self.base as u64 + address, buffer) 259 | } 260 | } 261 | 262 | impl<'a, T: MapPhysical + KernelMemoryRead + KernelMemoryWrite> crate::MemoryWrite 263 | for MappedPhysicalMemory<'a, T> 264 | { 265 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()> { 266 | if address + buffer.len() as u64 > self.base + self.size as u64 { 267 | return None; 268 | } 269 | self.api.try_write_bytes(self.base as u64 + address, buffer) 270 | } 271 | } 272 | 273 | impl<'a, T: MapPhysical + KernelMemoryRead + KernelMemoryWrite> Drop 274 | for MappedPhysicalMemory<'a, T> 275 | { 276 | fn drop(&mut self) { 277 | unsafe { self.api.unmap_io_space(self.base, self.size).unwrap() } 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(decl_macro)] 2 | #![feature(associated_type_defaults)] 3 | #![feature(associated_type_bounds)] 4 | 5 | use alloc::string::{FromUtf16Error, FromUtf8Error}; 6 | use core::mem::MaybeUninit; 7 | use std::{mem, slice}; 8 | 9 | pub use dataview::Pod; 10 | use dataview::PodMethods; 11 | 12 | #[cfg(feature = "kernel")] 13 | pub mod kernel; 14 | 15 | #[cfg(feature = "kernel")] 16 | pub use kernel::*; 17 | 18 | #[cfg(feature = "render")] 19 | pub mod render; 20 | 21 | #[cfg(feature = "render")] 22 | pub use render::DrawExt; 23 | 24 | #[cfg(feature = "test")] 25 | #[macro_use] 26 | pub mod tests; 27 | 28 | mod memory_protection; 29 | mod pid_util; 30 | mod slice_impl; 31 | 32 | pub use pid_util::*; 33 | pub use slice_impl::*; 34 | 35 | pub use memory_protection::MemoryProtection; 36 | 37 | extern crate alloc; 38 | 39 | pub type MemoryRange = core::ops::Range; 40 | 41 | const MAX_STRING_SIZE: usize = 0x10000; 42 | 43 | /// Represents any type with a buffer that can be read from 44 | #[auto_impl::auto_impl(&, & mut, Box)] 45 | pub trait MemoryRead { 46 | /// Reads bytes from the process at the specified address into a buffer. 47 | /// Returns None if the address is not valid 48 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()>; 49 | 50 | /// Reads bytes from the process at the specified address and returns the bytes as a Vector. 51 | /// Returns none if the address is not valid 52 | fn try_read_bytes(&self, address: u64, len: usize) -> Option> { 53 | let mut buf = vec![0u8; len]; 54 | self.try_read_bytes_into(address, &mut buf).map(|_| buf) 55 | } 56 | 57 | /// Dumps a memory range into a Vector. If any part of the memory range is not 58 | /// valid, it will return None 59 | fn dump_memory(&self, range: MemoryRange) -> Option> { 60 | self.try_read_bytes(range.start, (range.end - range.start) as usize) 61 | } 62 | 63 | /// Returns true if the specified address is valid. By default reads one byte at that location 64 | /// and returns the success value 65 | fn valid_address(&self, address: u64) -> bool { 66 | self.try_read_bytes(address, 1).is_some() 67 | } 68 | 69 | /// Reads a string at the specified location with char length of 1. 70 | /// If the address is valid or there is no null terminator 71 | /// in MAX_STRING_SIZE characters, it will return None 72 | fn try_read_string(&self, address: u64) -> Option> { 73 | const CHUNK_SIZE: usize = 0x100; 74 | 75 | let mut bytes = Vec::new(); 76 | let mut buf: [u8; CHUNK_SIZE] = unsafe { core::mem::zeroed() }; 77 | for i in (0..MAX_STRING_SIZE).into_iter().step_by(CHUNK_SIZE) { 78 | self.try_read_bytes_into(address + i as u64, &mut buf)?; 79 | if let Some(n) = buf.iter().position(|n| *n == 0u8) { 80 | bytes.extend_from_slice(&buf[0..n]); 81 | break; 82 | } else { 83 | bytes.extend_from_slice(&buf); 84 | } 85 | } 86 | 87 | Some(String::from_utf8(bytes)) 88 | } 89 | 90 | /// Reads a wide string at the specified location with char length of 1. 91 | /// If the address is valid or there is no null terminator 92 | /// in MAX_STRING_SIZE characters, it will return None 93 | fn try_read_string_wide(&self, address: u64) -> Option> { 94 | const CHUNK_SIZE: usize = 0x100; 95 | 96 | let mut bytes = Vec::new(); 97 | for i in (0..MAX_STRING_SIZE).into_iter().step_by(CHUNK_SIZE * 2) { 98 | let buf = self.try_read::<[u16; CHUNK_SIZE]>(address + i as u64)?; 99 | if let Some(n) = buf.iter().position(|n| *n == 0) { 100 | bytes.extend_from_slice(&buf[0..n]); 101 | break; 102 | } else { 103 | bytes.extend_from_slice(&buf); 104 | } 105 | } 106 | 107 | Some(String::from_utf16(&bytes)) 108 | } 109 | } 110 | 111 | /// Extension trait for supplying generic util methods for MemoryRead 112 | pub trait MemoryReadExt: MemoryRead { 113 | /// Reads bytes from the process at the specified address into a value of type T. 114 | /// Returns None if the address is not valid 115 | fn try_read(&self, address: u64) -> Option { 116 | let mut buffer: MaybeUninit = mem::MaybeUninit::zeroed(); 117 | 118 | unsafe { 119 | self.try_read_bytes_into(address, buffer.assume_init_mut().as_bytes_mut())?; 120 | Some(buffer.assume_init()) 121 | } 122 | } 123 | 124 | /// Reads any type T from the process without the restriction of Pod 125 | #[allow(clippy::missing_safety_doc)] 126 | unsafe fn try_read_unchecked(&self, address: u64) -> Option { 127 | let mut buffer: MaybeUninit = mem::MaybeUninit::zeroed(); 128 | 129 | self.try_read_bytes_into( 130 | address, 131 | slice::from_raw_parts_mut(buffer.as_mut_ptr() as _, mem::size_of::()), 132 | )?; 133 | Some(buffer.assume_init()) 134 | } 135 | 136 | /// Reads bytes from the process at the specified address into a value of type T. 137 | /// Panics if the address is not valid 138 | fn read(&self, address: u64) -> T { 139 | self.try_read(address).unwrap() 140 | } 141 | 142 | /// Reads a const number of bytes from the process returning a stack allocated array. 143 | fn try_read_bytes_const(&self, address: u64) -> Option<[u8; LEN]> { 144 | let mut buffer: [u8; LEN] = [0u8; LEN]; 145 | self.try_read_bytes_into(address, &mut buffer)?; 146 | Some(buffer) 147 | } 148 | 149 | /// Reads bytes from the process in chunks with the specified size 150 | fn try_read_bytes_into_chunked(&self, address: u64, buf: &mut [u8]) -> Option<()> { 151 | let mut chunk = [0u8; CHUNK_SIZE]; 152 | for i in (0..buf.len()).into_iter().step_by(CHUNK_SIZE) { 153 | let read_len = if i + CHUNK_SIZE > buf.len() { 154 | buf.len() - i 155 | } else { 156 | CHUNK_SIZE 157 | }; 158 | self.try_read_bytes_into(address + i as u64, &mut chunk[0..read_len])?; 159 | buf[i..i + read_len].copy_from_slice(&chunk[0..read_len]); 160 | } 161 | 162 | Some(()) 163 | } 164 | 165 | /// Reads bytes from the process in chunks with the specified size. The function will return Some(n) 166 | /// with the number of bytes read unless every single chunk fails 167 | fn try_read_bytes_into_chunked_fallible(&self, address: u64, buf: &mut [u8]) -> Option { 168 | let mut chunk = [0u8; CHUNK_SIZE]; 169 | let mut success_count = 0; 170 | for i in (0..buf.len()).into_iter().step_by(CHUNK_SIZE) { 171 | let read_len = if i + CHUNK_SIZE > buf.len() { 172 | buf.len() - i 173 | } else { 174 | CHUNK_SIZE 175 | }; 176 | if self.try_read_bytes_into(address + i as u64, &mut chunk[0..read_len]).is_some() { 177 | success_count += read_len; 178 | buf[i..i + read_len].copy_from_slice(&chunk[0..read_len]); 179 | } 180 | } 181 | 182 | if success_count > 0 { 183 | Some(success_count) 184 | } else { 185 | None 186 | } 187 | } 188 | } 189 | 190 | impl MemoryReadExt for T {} 191 | 192 | impl MemoryReadExt for dyn MemoryRead {} 193 | 194 | /// Represents any type with a buffer that can be written to 195 | #[auto_impl::auto_impl(&, & mut, Box)] 196 | pub trait MemoryWrite { 197 | /// Writes bytes from the buffer into the process at the specified address. 198 | /// Returns None if the address is not valid 199 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()>; 200 | } 201 | 202 | /// Extension trait for supplying generic util methods for MemoryWrite 203 | pub trait MemoryWriteExt: MemoryWrite { 204 | /// Returns None if the address is not valid 205 | fn try_write(&self, address: u64, buffer: &T) -> Option<()> { 206 | self.try_write_bytes(address, buffer.as_bytes()) 207 | } 208 | 209 | /// Writes any type T to the process without the restriction of Pod 210 | #[allow(clippy::missing_safety_doc)] 211 | unsafe fn try_write_unchecked(&self, address: u64, buffer: &T) -> Option<()> { 212 | self.try_write_bytes( 213 | address, 214 | slice::from_raw_parts(buffer as *const T as _, mem::size_of::()), 215 | ) 216 | } 217 | 218 | /// Writes bytes to the process at the specified address with the value of type T. 219 | /// Panics if the address is not valid 220 | fn write(&self, address: u64, buffer: &T) { 221 | self.try_write(address, buffer).unwrap() 222 | } 223 | } 224 | 225 | impl MemoryWriteExt for T {} 226 | 227 | impl MemoryWriteExt for dyn MemoryWrite {} 228 | 229 | /// Represents a single process module with a name, base, and size 230 | #[derive(Debug, Clone)] 231 | #[repr(C)] 232 | pub struct Module { 233 | pub name: String, 234 | pub base: u64, 235 | pub size: u64, 236 | } 237 | 238 | impl Module { 239 | /// Returns the memory range of the entire module 240 | pub fn memory_range(&self) -> MemoryRange { 241 | self.base..(self.base + self.size) 242 | } 243 | } 244 | 245 | /// Represents a type that has access to a process's modules 246 | #[auto_impl::auto_impl(&, & mut, Box)] 247 | pub trait ModuleList { 248 | /// Returns a list of all modules. If the implementor can only 249 | /// provide a single module based on the name, this function should panic 250 | fn get_module_list(&self) -> Vec; 251 | 252 | /// Returns a single module by name. 253 | /// If the module name does not exist, returns None 254 | fn get_module(&self, name: &str) -> Option { 255 | self.get_module_list() 256 | .into_iter() 257 | .find(|m| m.name.to_lowercase() == name.to_lowercase()) 258 | } 259 | 260 | /// Gets the main module from the process. 261 | fn get_main_module(&self) -> Module; 262 | } 263 | 264 | #[non_exhaustive] 265 | #[derive(Debug)] 266 | pub enum MemoryProtectError { 267 | InvalidMemoryRange(MemoryRange), 268 | NtStatus(u32), 269 | Message(String), 270 | } 271 | 272 | pub trait MemoryProtect { 273 | /// Sets the protection of the memory range to the specified protection. 274 | /// Returns the old memory protection or an error 275 | fn set_protection(&self, range: MemoryRange, protection: MemoryProtection) -> Result; 276 | } 277 | 278 | #[non_exhaustive] 279 | #[derive(Debug)] 280 | pub enum MemoryAllocateError { 281 | NtStatus(u32), 282 | Message(String), 283 | } 284 | 285 | pub trait MemoryAllocate { 286 | /// Allocates size bytes of memory in the process with the specified protection. 287 | /// Returns the allocated memory or an error. 288 | fn allocate(&self, size: u64, protection: MemoryProtection) -> Result; 289 | 290 | /// Frees allocated memory at the specified address and size. 291 | fn free(&self, base: u64, size: u64) -> Result<(), MemoryAllocateError>; 292 | } 293 | 294 | /// Represents a type that can retrieve the corresponding process's name and peb base address 295 | #[auto_impl::auto_impl(&, & mut, Box)] 296 | pub trait ProcessInfo { 297 | fn process_name(&self) -> String; 298 | fn peb_base_address(&self) -> u64; 299 | fn pid(&self) -> u32; 300 | } 301 | 302 | /// Represents a type that allows for sending mouse inputs 303 | #[auto_impl::auto_impl(&, & mut, Box)] 304 | pub trait MouseMove { 305 | fn mouse_move(&self, dx: i32, dy: i32); 306 | } 307 | -------------------------------------------------------------------------------- /src/memory_protection.rs: -------------------------------------------------------------------------------- 1 | use bitflags::bitflags; 2 | 3 | bitflags! { 4 | pub struct MemoryProtection: u32 { 5 | const NONE = 0x0; 6 | /// Enables execute access to the committed region of pages.An attempt to write to the committed region results in an access violation. 7 | const EXECUTE = 0x10; 8 | /// Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. 9 | const EXECUTE_READ = 0x20; 10 | /// Enables read and execute access to the committed region of pages. An attempt to write to the committed region results in an access violation. 11 | const EXECUTE_READWRITE = 0x40; 12 | /// Enables read, write, and execute access to the committed region of pages. 13 | const EXECUTE_WRITECOPY = 0x80; 14 | /// Disables all access to the committed region of pages. An attempt to read from, write to, or execute the committed region results in an access violation. 15 | const NOACCESS = 0x01; 16 | /// Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. 17 | const READONLY = 0x02; 18 | /// Enables read and write access to the committed region of pages. 19 | const READWRITE = 0x04; 20 | /// Enables read-only or copy-on-write access to a mapped view of a file mapping object. An attempt to write to a committed copy-on-write page results in a private copy of the page being made for the process. 21 | const WRITECOPY = 0x08; 22 | /// Pages in the region become guard pages. Any attempt to access a guard page causes the system to raise a STATUS_GUARD_PAGE_VIOLATION exception and turn off the guard page status. Guard pages thus act as a one-time access alarm. 23 | const GUARD = 0x100; 24 | /// Sets all pages to be non-cachable. Applications should not use this attribute except when explicitly required for a device. 25 | const NOCACHE = 0x200; 26 | /// Sets all pages to be write-combined. 27 | const WRITECOMBINE = 0x400; 28 | } 29 | } -------------------------------------------------------------------------------- /src/pid_util.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | /// Represents a type that can attach to a process and return 4 | /// a struct that implements MemoryRead, MemoryWrite, and ModuleList 5 | pub trait ProcessAttach: Sized { 6 | /// The type of the resulting process after attaching 7 | type ProcessType<'a> where Self: 'a; 8 | 9 | /// Attaches to a process of name process_name. If no process is found None is returned. 10 | /// If there is an error internally, this function should panic 11 | fn attach(&self, process_name: &str) -> Option>; 12 | 13 | /// Attaches to a process by a pid. If the pid does not exist, this will return None 14 | fn attach_pid(&self, pid: u32) -> Option>; 15 | 16 | /// Attaches to the current process 17 | fn attach_current(&self) -> Self::ProcessType<'_>; 18 | } 19 | 20 | /// Represents a type that can attach to a process and return 21 | /// a struct that implements MemoryRead, MemoryWrite, and ModuleList while consuming Self 22 | pub trait ProcessAttachInto: Sized { 23 | /// The type of the resulting process after attaching 24 | type ProcessType; 25 | 26 | /// Attaches to a process of name process_name. If no process is found None is returned. 27 | /// If there is an error internally, this function should panic 28 | fn attach_into(self, process_name: &str) -> Option; 29 | 30 | /// Attaches to a process by a pid. If the pid does not exist, this will return None 31 | fn attach_into_pid(self, pid: u32) -> Option; 32 | 33 | /// Attaches to the current process, consuming Self 34 | fn attach_into_current(self) -> Self::ProcessType; 35 | } 36 | 37 | impl ProcessAttach for T 38 | where T: GetContext + 'static 39 | { 40 | type ProcessType<'a> = AttachedProcess<'a, Self> where Self: 'a; 41 | 42 | fn attach(&self, process_name: &str) -> Option> { 43 | self.get_context_from_name(process_name) 44 | .map(|ctx| AttachedProcess::new(self, ctx)) 45 | } 46 | 47 | fn attach_pid(&self, pid: u32) -> Option> { 48 | self.get_context_from_pid(pid) 49 | .map(|ctx| AttachedProcess::new(self, ctx)) 50 | } 51 | 52 | fn attach_current(&self) -> Self::ProcessType<'_> { 53 | let ctx = self.get_current_context(); 54 | AttachedProcess::new(self, ctx) 55 | } 56 | } 57 | 58 | impl ProcessAttachInto for T 59 | where 60 | T: GetContext + 'static, 61 | { 62 | type ProcessType = AttachedProcess<'static, Self>; 63 | 64 | fn attach_into(self, process_name: &str) -> Option { 65 | self.get_context_from_name(process_name) 66 | .map(|ctx| AttachedProcess::new_owned(self, ctx)) 67 | } 68 | 69 | fn attach_into_pid(self, pid: u32) -> Option { 70 | self.get_context_from_pid(pid) 71 | .map(|ctx| AttachedProcess::new_owned(self, ctx)) 72 | } 73 | 74 | fn attach_into_current(self) -> Self::ProcessType { 75 | let ctx = self.get_current_context(); 76 | AttachedProcess::new_owned(self, ctx) 77 | } 78 | } 79 | 80 | /// Gets the Pid type from a process name, a windows PID, or the current PID 81 | pub trait GetContext { 82 | type Context; 83 | 84 | fn get_context_from_name(&self, process_name: &str) -> Option; 85 | fn get_context_from_pid(&self, pid: u32) -> Option; 86 | fn get_current_context(&self) -> Self::Context; 87 | } 88 | 89 | #[derive(Clone)] 90 | pub enum MaybeOwned<'a, T> { 91 | Borrowed(&'a T), 92 | Owned(T), 93 | } 94 | 95 | impl<'a, T> From<&'a T> for MaybeOwned<'a, T> { 96 | fn from(n: &'a T) -> Self { 97 | Self::Borrowed(n) 98 | } 99 | } 100 | 101 | impl<'a, T> From for MaybeOwned<'a, T> { 102 | fn from(n: T) -> Self { 103 | Self::Owned(n) 104 | } 105 | } 106 | 107 | impl<'a, T> AsRef for MaybeOwned<'a, T> { 108 | fn as_ref(&self) -> &T { 109 | match self { 110 | Self::Borrowed(n) => n, 111 | Self::Owned(n) => n, 112 | } 113 | } 114 | } 115 | 116 | impl<'a, T> MaybeOwned<'a, T> { 117 | pub fn to_owned(self) -> T 118 | where T: Clone { 119 | match self { 120 | Self::Borrowed(n) => n.clone(), 121 | Self::Owned(n) => n 122 | } 123 | } 124 | } 125 | 126 | #[derive(Clone)] 127 | pub struct AttachedProcess<'a, T> 128 | where T: GetContext { 129 | pub api: MaybeOwned<'a, T>, 130 | pub context: T::Context, 131 | } 132 | 133 | impl<'a, T> AttachedProcess<'a, T> 134 | where T: GetContext { 135 | pub fn new_owned(api: T, context: T::Context) -> Self { 136 | Self { api: MaybeOwned::Owned(api), context } 137 | } 138 | 139 | pub fn new(api: &'a T, context: T::Context) -> Self { 140 | Self { api: MaybeOwned::Borrowed(api), context } 141 | } 142 | 143 | pub fn api(&self) -> &T { 144 | match &self.api { 145 | MaybeOwned::Borrowed(api) => api, 146 | MaybeOwned::Owned(api) => api 147 | } 148 | } 149 | 150 | pub fn context(&self) -> &T::Context { 151 | &self.context 152 | } 153 | } 154 | 155 | /// A trait that mirrors the MemoryRead trait but reads from a PID instead of directly from the implementor. 156 | /// Note that the Pid type is not necessarily a Windows process ID. One may implement this using another form of identifier such as a dirbase. 157 | pub trait MemoryReadPid: GetContext { 158 | /// Reads memory from the process with the given PID. 159 | fn try_read_bytes_into_pid(&self, ctx: &Self::Context, address: u64, buffer: &mut [u8]) -> Option<()>; 160 | } 161 | 162 | impl MemoryRead for AttachedProcess<'_, T> 163 | where 164 | T: MemoryReadPid 165 | { 166 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 167 | self.api().try_read_bytes_into_pid(self.context(), address, buffer) 168 | } 169 | } 170 | 171 | /// A trait that mirrors the MemoryWrite trait but writes to a PID instead of directly from the implementor. 172 | /// Note that the Pid type is not necessarily a Windows process ID. One may implement this using another form of identifier such as a dirbase. 173 | pub trait MemoryWritePid: GetContext { 174 | /// Writes memory to the process with the given PID. 175 | fn try_write_bytes_pid(&self, ctx: &Self::Context, address: u64, buffer: &[u8]) -> Option<()>; 176 | } 177 | 178 | impl MemoryWrite for AttachedProcess<'_, T> 179 | where 180 | T: MemoryWritePid, 181 | { 182 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()> { 183 | self.api().try_write_bytes_pid(self.context(), address, buffer) 184 | } 185 | } 186 | 187 | /// A trait that mirrors the ModuleList trait by gets information from a PID instead of directly from the implementor. 188 | /// Note that the Pid type is not necessarily a Windows process ID. One may implement this using another form of identifier such as a dirbase. 189 | pub trait ModuleListPid: GetContext { 190 | /// Returns a list of all modules from a Pid. If the implementor can only 191 | /// provide a single module based on the name, this function should panic 192 | fn get_module_list(&self, pid: &Self::Context) -> Vec; 193 | 194 | /// Returns a single module by name from the Pid. 195 | /// If the module name does not exist, returns None 196 | fn get_module(&self, pid: &Self::Context, name: &str) -> Option { 197 | self.get_module_list(pid) 198 | .into_iter() 199 | .find(|m| m.name.to_lowercase() == name.to_lowercase()) 200 | } 201 | 202 | /// Gets the main module from the Pid. 203 | fn get_main_module(&self, pid: &Self::Context) -> Module; 204 | } 205 | 206 | impl ModuleList for AttachedProcess<'_, T> 207 | where 208 | T: ModuleListPid, 209 | { 210 | fn get_module_list(&self) -> Vec { 211 | self.api().get_module_list(self.context()) 212 | } 213 | 214 | fn get_module(&self, name: &str) -> Option { 215 | self.api().get_module(self.context(), name) 216 | } 217 | 218 | fn get_main_module(&self) -> Module { 219 | self.api().get_main_module(self.context()) 220 | } 221 | } 222 | 223 | /// A trait that mirrors the ProcessInfo trait by gets information from a PID instead of directly from the implementor. 224 | /// Note that the Pid type is not necessarily a Windows process ID. One may implement this using another form of identifier such as a dirbase. 225 | pub trait ProcessInfoPid: GetContext { 226 | fn process_name(&self, pid: &Self::Context) -> String; 227 | fn peb_base_address(&self, pid: &Self::Context) -> u64; 228 | fn pid(&self, pid: &Self::Context) -> u32; 229 | } 230 | 231 | impl ProcessInfo for AttachedProcess<'_, T> 232 | where 233 | T: ProcessInfoPid, 234 | { 235 | fn process_name(&self) -> String { 236 | self.api().process_name(self.context()) 237 | } 238 | 239 | fn peb_base_address(&self) -> u64 { 240 | self.api().peb_base_address(self.context()) 241 | } 242 | 243 | fn pid(&self) -> u32 { 244 | self.api().pid(self.context()) 245 | } 246 | } 247 | 248 | pub trait MemoryAllocatePid: GetContext { 249 | /// Allocates size bytes of memory in the process with the specified protection. 250 | /// Returns the allocated memory or an error. 251 | fn allocate_pid(&self, pid: &Self::Context, size: u64, protection: MemoryProtection) -> Result; 252 | 253 | /// Frees allocated memory at the specified address and size. 254 | fn free_pid(&self, pid: &Self::Context, base: u64, size: u64) -> Result<(), MemoryAllocateError>; 255 | } 256 | 257 | impl MemoryAllocate for AttachedProcess<'_, T> 258 | where 259 | T: MemoryAllocatePid, 260 | { 261 | fn allocate(&self, size: u64, protection: MemoryProtection) -> Result { 262 | self.api().allocate_pid(self.context(), size, protection) 263 | } 264 | 265 | fn free(&self, base: u64, size: u64) -> Result<(), MemoryAllocateError> { 266 | self.api().free_pid(self.context(), base, size) 267 | } 268 | } 269 | 270 | pub trait MemoryProtectPid: GetContext { 271 | /// Sets the protection of the memory range to the specified protection. 272 | /// Returns the old memory protection or an error 273 | fn set_protection_pid(&self, pid: &Self::Context, range: MemoryRange, protection: MemoryProtection) -> Result; 274 | } 275 | 276 | impl MemoryProtect for AttachedProcess<'_, T> 277 | where 278 | T: MemoryProtectPid, 279 | { 280 | fn set_protection(&self, range: MemoryRange, protection: MemoryProtection) -> Result { 281 | self.api().set_protection_pid(self.context(), range, protection) 282 | } 283 | } 284 | 285 | /// A trait that mirrors the TranslatePhysical trait that translates a virtual 286 | /// address from a certain Context into a physical address 287 | #[cfg(feature = "kernel")] 288 | pub trait TranslatePhysicalPid: GetContext { 289 | fn physical_address_pid(&self, ctx: &Self::Context, virtual_address: u64) -> Option; 290 | } 291 | 292 | #[cfg(feature = "kernel")] 293 | impl TranslatePhysical for AttachedProcess<'_, T> 294 | where 295 | T: TranslatePhysicalPid 296 | { 297 | fn physical_address(&self, virtual_address: u64) -> Option { 298 | self.api().physical_address_pid(self.context(), virtual_address) 299 | } 300 | } -------------------------------------------------------------------------------- /src/render.rs: -------------------------------------------------------------------------------- 1 | #![allow(deprecated)] 2 | 3 | /// Represents a type that can create and render a type that implements Draw for drawing on an overlay 4 | pub trait Render { 5 | /// The frame type that the renderer generates 6 | type Frame: Draw; 7 | 8 | /// Adds a custom font by raw ttf data, the font size, and the id used to specify the 9 | /// font to use using Font::Custom. Panics if the font data cannot be parsed. 10 | fn add_custom_font(&mut self, font_data: Vec, font_size: f32, id: FontId) -> Option<()>; 11 | 12 | /// Gets the size of the frame 13 | fn frame_size(&self) -> (u32, u32); 14 | 15 | /// Creates a new instance of the Frame type 16 | fn frame(&mut self) -> &mut Self::Frame; 17 | 18 | /// Renders a modified frame crated by the frame function 19 | fn render(&mut self); 20 | } 21 | 22 | pub type Point = (f32, f32); 23 | /// [R, G, B, A] 24 | #[derive(Copy, Clone, Debug)] 25 | pub struct Color([u8; 4]); 26 | 27 | impl std::ops::Index for Color { 28 | type Output = u8; 29 | 30 | #[inline(always)] 31 | fn index(&self, index: usize) -> &u8 { 32 | &self.0[index] 33 | } 34 | } 35 | 36 | impl std::ops::IndexMut for Color { 37 | #[inline(always)] 38 | fn index_mut(&mut self, index: usize) -> &mut u8 { 39 | &mut self.0[index] 40 | } 41 | } 42 | 43 | impl Color { 44 | pub fn new(r: u8, g: u8, b: u8, a: u8) -> Color { 45 | Color([r, g, b, a]) 46 | } 47 | 48 | pub fn from_argb(argb: u32) -> Color { 49 | let b = argb as u8; 50 | let g = (argb >> 8) as u8; 51 | let r = (argb >> 16) as u8; 52 | let a = (argb >> 24) as u8; 53 | Color([r, g, b, a]) 54 | } 55 | } 56 | 57 | pub type FontId = String; 58 | 59 | #[derive(Hash, PartialEq, Eq, Clone)] 60 | pub enum Font { 61 | Default, 62 | Pixel, 63 | Custom(FontId), 64 | } 65 | 66 | pub struct TextOptions { 67 | pub font: Font, 68 | pub font_size: f32, 69 | } 70 | 71 | pub struct LineOptions { 72 | pub thickness: f32, 73 | } 74 | 75 | pub struct RectOptions { 76 | pub thickness: f32, 77 | pub rounding: f32, 78 | } 79 | 80 | pub struct CircleOptions { 81 | pub thickness: f32, 82 | } 83 | 84 | /// Represents a type that can be directly drew on 85 | pub trait Draw: Sized { 86 | #[deprecated(note = "Use the DrawExt trait instead of calling the Draw functions directly")] 87 | fn draw_text(&mut self, origin: Point, text: &str, color: Color, options: TextOptions); 88 | 89 | #[deprecated(note = "Use the DrawExt trait instead of calling the Draw functions directly")] 90 | fn draw_line(&mut self, p1: Point, p2: Point, color: Color, options: LineOptions); 91 | 92 | #[deprecated(note = "Use the DrawExt trait instead of calling the Draw functions directly")] 93 | fn draw_rect(&mut self, p1: Point, p2: Point, color: Color, options: RectOptions); 94 | 95 | #[deprecated(note = "Use the DrawExt trait instead of calling the Draw functions directly")] 96 | fn draw_rect_filled(&mut self, p1: Point, p2: Point, color: Color, options: RectOptions); 97 | 98 | #[deprecated(note = "Use the DrawExt trait instead of calling the Draw functions directly")] 99 | fn draw_circle(&mut self, origin: Point, radius: f32, color: Color, options: CircleOptions); 100 | 101 | #[deprecated(note = "Use the DrawExt trait instead of calling the Draw functions directly")] 102 | fn draw_circle_filled(&mut self, origin: Point, radius: f32, color: Color, options: CircleOptions); 103 | } 104 | 105 | 106 | /// Extension trait for Draw containing drawing builders for a cleaner drawing api. 107 | /// These functions should be used instead of the raw Draw functions 108 | pub trait DrawExt: Draw { 109 | fn text<'draw, 's>(&'draw mut self, origin: impl Into, text: &'s str, color: impl Into) -> Text<'draw, 's, Self> { 110 | Text { draw: self, origin: origin.into(), text, color: color.into(), font: Font::Default, font_size: 10., shadow_color: Color::from_argb(0xAA000000), style: TextStyle::Shadow } 111 | } 112 | 113 | fn line(&mut self, p1: impl Into, p2: impl Into, color: impl Into) -> Line { 114 | Line { draw: self, p1: p1.into(), p2: p2.into(), color: color.into(), thickness: 1. } 115 | } 116 | 117 | fn rect(&mut self, p1: impl Into, p2: impl Into, color: impl Into) -> Rect { 118 | Rect { draw: self, p1: p1.into(), p2: p2.into(), color: color.into(), thickness: 1., rounding: 1., filled: false } 119 | } 120 | 121 | fn circle(&mut self, origin: impl Into, radius: impl Into, color: impl Into) -> Circle { 122 | Circle { draw: self, origin: origin.into(), radius: radius.into(), color: color.into(), filled: false, thickness: 1. } 123 | } 124 | } 125 | 126 | impl DrawExt for T {} 127 | 128 | macro setter($member_name:ident, $setter_type:ty) { 129 | pub fn $member_name(mut self, $member_name: impl Into<$setter_type>) -> Self { 130 | self.$member_name = $member_name.into(); 131 | self 132 | } 133 | } 134 | 135 | pub enum TextStyle { 136 | None, 137 | Shadow, 138 | Outline, 139 | } 140 | 141 | #[must_use = "Should call .draw() to draw the object"] 142 | pub struct Text<'draw, 's, T: Draw> { 143 | draw: &'draw mut T, 144 | origin: Point, 145 | text: &'s str, 146 | color: Color, 147 | font: Font, 148 | font_size: f32, 149 | style: TextStyle, 150 | shadow_color: Color, 151 | } 152 | 153 | impl<'draw, 'b, T: Draw> Text<'draw, 'b, T> { 154 | setter! {font, Font} 155 | setter! {font_size, f32} 156 | setter! {style, TextStyle} 157 | setter! {shadow_color, Color} 158 | 159 | pub fn draw(self) { 160 | let mut draw = |color, offset: (f32, f32)| { 161 | self.draw.draw_text((self.origin.0 + offset.0, self.origin.1 + offset.1), self.text, color, TextOptions { font: self.font.clone(), font_size: self.font_size }); 162 | }; 163 | 164 | match self.style { 165 | TextStyle::Shadow => { 166 | draw(self.shadow_color, (1.0, 1.0)); 167 | } 168 | TextStyle::Outline => { 169 | draw(self.shadow_color, (1.0, 1.0)); 170 | draw(self.shadow_color, (1.0, -1.0)); 171 | draw(self.shadow_color, (-1.0, 1.0)); 172 | draw(self.shadow_color, (-1.0, -1.0)); 173 | draw(self.shadow_color, (0.0, 1.0)); 174 | draw(self.shadow_color, (0.0, -1.0)); 175 | draw(self.shadow_color, (1.0, 0.0)); 176 | draw(self.shadow_color, (-1.0, 0.0)); 177 | } 178 | TextStyle::None => {} 179 | } 180 | 181 | draw(self.color, (0., 0.)) 182 | } 183 | } 184 | 185 | #[must_use = "Should call .draw() to draw the object"] 186 | pub struct Line<'draw, T: Draw> { 187 | draw: &'draw mut T, 188 | p1: Point, 189 | p2: Point, 190 | color: Color, 191 | thickness: f32, 192 | } 193 | 194 | impl<'draw, T: Draw> Line<'draw, T> { 195 | setter! { thickness, f32 } 196 | 197 | pub fn draw(self) { 198 | self.draw.draw_line(self.p1, self.p2, self.color, LineOptions { thickness: self.thickness }) 199 | } 200 | } 201 | 202 | #[must_use = "Should call .draw() to draw the object"] 203 | pub struct Rect<'draw, T: Draw> { 204 | draw: &'draw mut T, 205 | p1: Point, 206 | p2: Point, 207 | color: Color, 208 | thickness: f32, 209 | rounding: f32, 210 | filled: bool, 211 | } 212 | 213 | impl<'draw, T: Draw> Rect<'draw, T> { 214 | setter! { thickness, f32 } 215 | setter! { filled, bool } 216 | 217 | pub fn draw(self) { 218 | match self.filled { 219 | false => self.draw.draw_rect(self.p1, self.p2, self.color, RectOptions { thickness: self.thickness, rounding: self.rounding }), 220 | true => self.draw.draw_rect_filled(self.p1, self.p2, self.color, RectOptions { thickness: self.thickness, rounding: self.rounding }), 221 | } 222 | } 223 | } 224 | 225 | #[must_use = "Should call .draw() to draw the object"] 226 | pub struct Circle<'draw, T: Draw> { 227 | draw: &'draw mut T, 228 | origin: Point, 229 | radius: f32, 230 | thickness: f32, 231 | color: Color, 232 | filled: bool, 233 | } 234 | 235 | impl<'draw, T: Draw> Circle<'draw, T> { 236 | setter! { filled, bool } 237 | setter! { thickness, f32 } 238 | 239 | pub fn draw(self) { 240 | match self.filled { 241 | false => self.draw.draw_circle(self.origin, self.radius, self.color, CircleOptions { thickness: self.thickness }), 242 | true => self.draw.draw_circle_filled(self.origin, self.radius, self.color, CircleOptions { thickness: self.thickness }), 243 | } 244 | } 245 | } 246 | 247 | pub struct NullFrame; 248 | 249 | #[allow(unused_variables)] 250 | impl Draw for NullFrame { 251 | fn draw_text(&mut self, origin: Point, text: &str, color: Color, options: TextOptions) {} 252 | 253 | fn draw_line(&mut self, p1: Point, p2: Point, color: Color, options: LineOptions) {} 254 | 255 | fn draw_rect(&mut self, p1: Point, p2: Point, color: Color, options: RectOptions) {} 256 | 257 | fn draw_rect_filled(&mut self, p1: Point, p2: Point, color: Color, options: RectOptions) {} 258 | 259 | fn draw_circle(&mut self, origin: Point, radius: f32, color: Color, options: CircleOptions) {} 260 | 261 | fn draw_circle_filled(&mut self, origin: Point, radius: f32, color: Color, options: CircleOptions) {} 262 | } 263 | 264 | pub struct NullOverlay(NullFrame); 265 | 266 | impl Default for NullOverlay { 267 | fn default() -> Self { 268 | Self(NullFrame {}) 269 | } 270 | } 271 | 272 | impl Render for NullOverlay { 273 | type Frame = NullFrame; 274 | 275 | fn add_custom_font(&mut self, _font_data: Vec, _font_size: f32, _id: FontId) -> Option<()> { 276 | Some(()) 277 | } 278 | 279 | fn frame_size(&self) -> (u32, u32) { 280 | (0, 0) 281 | } 282 | 283 | fn frame(&mut self) -> &mut Self::Frame { 284 | &mut self.0 285 | } 286 | 287 | fn render(&mut self) {} 288 | } -------------------------------------------------------------------------------- /src/slice_impl.rs: -------------------------------------------------------------------------------- 1 | use std::cell::{Cell}; 2 | use super::*; 3 | 4 | impl<'a> MemoryRead for &'a [u8] { 5 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 6 | if address as usize + buffer.len() > self.len() { 7 | return None; 8 | } 9 | 10 | buffer.copy_from_slice(&self[address as usize..address as usize + buffer.len()]); 11 | 12 | Some(()) 13 | } 14 | } 15 | 16 | impl> MemoryRead for Cell { 17 | fn try_read_bytes_into(&self, address: u64, buffer: &mut [u8]) -> Option<()> { 18 | let self_buf = unsafe { self.as_ptr().as_ref() }.unwrap(); 19 | if address as usize + buffer.len() > self_buf.as_ref().len() { 20 | return None; 21 | } 22 | 23 | buffer.copy_from_slice(&self_buf.as_ref()[address as usize..address as usize + buffer.len()]); 24 | 25 | Some(()) 26 | } 27 | } 28 | 29 | impl> MemoryWrite for Cell { 30 | fn try_write_bytes(&self, address: u64, buffer: &[u8]) -> Option<()> { 31 | let self_buf = unsafe { self.as_ptr().as_mut() }.unwrap(); 32 | if address as usize + buffer.len() > self_buf.as_mut().len() { 33 | return None; 34 | } 35 | 36 | self_buf.as_mut()[address as usize..address as usize + buffer.len()].copy_from_slice(buffer); 37 | 38 | Some(()) 39 | } 40 | } 41 | 42 | #[cfg(test)] 43 | mod tests { 44 | use super::*; 45 | use crate::*; 46 | 47 | fn use_read(read: impl MemoryRead) {} 48 | fn use_write(write: impl MemoryWrite) {} 49 | fn use_readwrite(readwrite: impl MemoryRead + MemoryWrite) {} 50 | 51 | #[test] 52 | fn test_slice_read() { 53 | let mut buffer = [0u8; 10]; 54 | let slice = &buffer[..]; 55 | use_read(slice); 56 | } 57 | 58 | #[test] 59 | fn test_cell_read() { 60 | let mut buffer = [0u8; 10]; 61 | let cell = Cell::new(buffer); 62 | use_read(cell); 63 | } 64 | 65 | #[test] 66 | fn test_cell_write() { 67 | let mut buffer = [0u8; 10]; 68 | let cell = Cell::new(buffer); 69 | use_write(cell); 70 | } 71 | 72 | #[test] 73 | fn test_cell_readwrite() { 74 | let mut buffer = [0u8; 10]; 75 | let cell = Cell::new(buffer); 76 | use_readwrite(cell); 77 | } 78 | 79 | static mut TEST_BUF: [u8; 10] = [0u8; 10]; 80 | fn get_test_buf() -> &'static mut [u8] { 81 | unsafe { 82 | &mut TEST_BUF 83 | } 84 | } 85 | 86 | #[test] 87 | fn test_static_cell_read() { 88 | let cell = Cell::new(get_test_buf()); 89 | use_read(cell); 90 | } 91 | 92 | #[test] 93 | fn test_static_cell_write() { 94 | let cell = Cell::new(get_test_buf()); 95 | use_write(cell); 96 | } 97 | 98 | #[test] 99 | fn test_static_cell_readwrite() { 100 | let cell = Cell::new(get_test_buf()); 101 | use_readwrite(cell); 102 | } 103 | } -------------------------------------------------------------------------------- /src/tests.rs: -------------------------------------------------------------------------------- 1 | pub macro generate_process_attach_tests($make_attach:expr) { 2 | use $crate::tests::process_attach_tests::ProcessAttachTests; 3 | 4 | fn get_tester() -> ProcessAttachTests + Clone> { 5 | let attach = $make_attach(); 6 | ProcessAttachTests::new(attach) 7 | } 8 | 9 | #[test] 10 | fn test_attach() { 11 | get_tester().test_attach(); 12 | } 13 | 14 | #[test] 15 | fn test_main_module() { 16 | get_tester().test_main_module(); 17 | } 18 | 19 | #[test] 20 | fn test_module_list() { 21 | get_tester().test_module_list(); 22 | } 23 | 24 | #[test] 25 | fn test_read() { 26 | get_tester().test_read(); 27 | } 28 | 29 | #[test] 30 | fn test_dump_module() { 31 | get_tester().test_dump_module(); 32 | } 33 | 34 | #[test] 35 | fn test_module_coverage() { 36 | get_tester().test_module_coverage(); 37 | } 38 | 39 | /* 40 | #[test] 41 | fn test_write() { 42 | get_tester().test_write(); 43 | } 44 | */ 45 | 46 | #[test] 47 | fn test_process_info() { 48 | get_tester().test_process_info(); 49 | } 50 | } 51 | 52 | pub mod process_attach_tests { 53 | use crate::{MemoryRead, MemoryWrite, ModuleList, ProcessAttachInto, ProcessInfo}; 54 | use log::LevelFilter; 55 | use std::process; 56 | 57 | struct TestProcess { 58 | proc: process::Child, 59 | } 60 | 61 | const TEST_PROCESS: &str = "winver.exe"; 62 | 63 | impl TestProcess { 64 | pub fn new() -> Self { 65 | Self { 66 | proc: process::Command::new(TEST_PROCESS).spawn().unwrap(), 67 | } 68 | } 69 | 70 | pub fn name(&self) -> String { 71 | TEST_PROCESS.to_string() 72 | } 73 | } 74 | 75 | impl Drop for TestProcess { 76 | fn drop(&mut self) { 77 | self.proc.kill().unwrap() 78 | } 79 | } 80 | 81 | fn init_tests() { 82 | let _ = env_logger::builder() 83 | .is_test(true) 84 | .filter_level(LevelFilter::Debug) 85 | .try_init(); 86 | } 87 | 88 | pub struct ProcessAttachTests + Clone> { 89 | api: T, 90 | proc: TestProcess, 91 | } 92 | 93 | impl + Clone> ProcessAttachTests { 94 | pub fn new(api: T) -> Self { 95 | init_tests(); 96 | Self { 97 | api, 98 | proc: TestProcess::new(), 99 | } 100 | } 101 | 102 | fn attach(&self) -> T::ProcessType { 103 | self.api.clone().attach_into_pid(self.proc.proc.id()).unwrap() 104 | } 105 | 106 | pub fn test_attach(&self) { 107 | let _ = self.attach(); 108 | } 109 | 110 | pub fn test_main_module(&self) { 111 | let handle = self.attach(); 112 | let main_module = handle.get_main_module(); 113 | dbg!(&main_module); 114 | assert_eq!(main_module.name, self.proc.name()); 115 | } 116 | 117 | pub fn test_module_list(&self) { 118 | let handle = self.attach(); 119 | let modules = handle.get_module_list(); 120 | dbg!(&modules); 121 | assert!(modules.len() > 5); 122 | assert!(modules.iter().any(|m| m.name.to_lowercase() == "ntdll.dll")); 123 | } 124 | 125 | pub fn test_read(&self) { 126 | let handle = self.attach(); 127 | let main_module = handle.get_main_module(); 128 | let header = handle 129 | .try_read_bytes(main_module.base, 2) 130 | .expect("Could not read bytes from the process"); 131 | assert_eq!(header[0], 0x4D); 132 | assert_eq!(header[1], 0x5A); 133 | } 134 | 135 | pub fn test_dump_module(&self) { 136 | let handle = self.attach(); 137 | let main_module = handle.get_main_module(); 138 | let range = main_module.memory_range(); 139 | let _ = handle 140 | .dump_memory(range) 141 | .expect("Could not dump memory range"); 142 | } 143 | 144 | pub fn test_module_coverage(&self) { 145 | let handle = self.attach(); 146 | let range = handle.get_main_module().memory_range(); 147 | 148 | const CHUNK_SIZE: usize = 0x8; 149 | 150 | let mut total = 0; 151 | let mut good = 0; 152 | for i in range.step_by(CHUNK_SIZE) { 153 | let valid = handle.try_read_bytes(i, CHUNK_SIZE).is_some(); 154 | total += 1; 155 | if valid { 156 | good += 1; 157 | } 158 | } 159 | 160 | eprintln!( 161 | "{}/{} ({:.1}%) chunks of {:#X} could be read", 162 | good, 163 | total, 164 | (good as f32 / total as f32) * 100.0, 165 | CHUNK_SIZE 166 | ); 167 | assert_eq!(good, total); 168 | } 169 | 170 | pub fn test_write(&self) { 171 | let handle = self.attach(); 172 | let main_module = handle.get_main_module(); 173 | let base = main_module.base; 174 | 175 | let test_data = [1u8, 2, 3, 4, 5, 6]; 176 | 177 | let orig_data = handle.try_read_bytes(base, test_data.len()).unwrap(); 178 | 179 | handle.try_write_bytes(base, &test_data).unwrap(); 180 | 181 | let actual_data = handle.try_read_bytes(base, test_data.len()).unwrap(); 182 | 183 | handle.try_write_bytes(base, &orig_data).unwrap(); 184 | 185 | assert_eq!(&test_data[..], &actual_data); 186 | } 187 | 188 | pub fn test_process_info(&self) { 189 | let handle = self.attach(); 190 | dbg!(handle.peb_base_address()); 191 | assert_ne!(handle.peb_base_address(), 0); 192 | assert_eq!(handle.pid(), self.proc.proc.id()); 193 | assert_eq!(handle.process_name(), self.proc.name()); 194 | } 195 | } 196 | } 197 | --------------------------------------------------------------------------------