feat: add memory reader

This commit is contained in:
2026-07-05 12:07:58 +02:00
parent 6dc1f4f703
commit 8c70c00ebd
2 changed files with 520 additions and 0 deletions
+1
View File
@@ -7,6 +7,7 @@ use tauri_plugin_fs::FsExt;
pub mod commands;
pub mod config;
pub mod memory_reader;
pub mod osudb;
pub mod presence;
pub mod state;
+519
View File
@@ -0,0 +1,519 @@
//! osu_memory_reader.rs
//!
//! External, read-only memory reader for the osu! stable client, structured
//! the same way community tools like tosu / gosumemory work:
//!
//! 1. Open the osu process with PROCESS_VM_READ.
//! 2. Enumerate its committed memory regions.
//! 3. Scan those regions for known byte-pattern "signatures".
//! 4. Walk a short pointer chain from each signature to the real struct.
//! 5. Parse out the fields you care about (username, mods, combo, etc).
//!
//! IMPORTANT: The actual signature bytes below are PLACEHOLDERS. osu!
//! updates its binary regularly, which shifts/breaks raw byte signatures.
//! Community tools maintain live, current signatures — pull up-to-date
//! ones from tosu's open-source repo (github.com/KotRikD/tosu, see its
//! `packages/tosu/src/memory/` signature definitions) and drop them into
//! the `SIGNATURES` table below. This file gives you the engine; you keep
//! the signature table current.
//!
//! This is entirely read-only (ReadProcessMemory only, never Write) and
//! only targets your own launched osu! process — no injection involved.
//!
//! ---------------------------------------------------------------------
//! Cargo.toml additions (on top of the ones from osu_scanner.rs):
//!
//! [dependencies]
//! windows = { version = "0.58", features = [
//! "Win32_System_Diagnostics_ToolHelp",
//! "Win32_System_Memory",
//! "Win32_System_Threading",
//! "Win32_System_Diagnostics_Debug",
//! "Win32_Foundation"
//! ] }
//! ---------------------------------------------------------------------
use serde::Serialize;
use std::collections::HashMap;
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows::Win32::System::Memory::{
MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQueryEx,
};
use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ};
// =========================================================================
// Signature table — REPLACE with current values, see module doc comment.
// =========================================================================
/// A byte pattern to search for in process memory. `None` = wildcard byte.
#[derive(Clone)]
pub struct Signature {
pub name: &'static str,
pub pattern: &'static [Option<u8>],
/// Byte offset from the START of the matched pattern to the address
/// (or start of a pointer chain) you actually want to read.
pub offset: isize,
}
/// Helper macro so signatures can be written like Cheat Engine AOB strings,
/// e.g. sig!("F8 01 74 04 ?? ?? ?? ??", offset = 5).
macro_rules! sig {
($bytes:expr) => {{ parse_aob($bytes) }};
}
fn parse_aob(s: &str) -> Vec<Option<u8>> {
s.split_whitespace()
.map(|tok| {
if tok == "??" || tok == "?" {
None
} else {
Some(u8::from_str_radix(tok, 16).expect("bad AOB byte"))
}
})
.collect()
}
/// NOTE: These are PLACEHOLDER patterns illustrating the *shape* tosu-style
/// signatures take (short, somewhat unique byte runs with wildcards around
/// the volatile parts). Do not expect these exact bytes to match a real
/// osu! binary — swap them for current ones before using this for real.
pub fn build_signature_table() -> HashMap<&'static str, Signature> {
let mut map = HashMap::new();
map.insert(
"username_ptr",
Signature {
name: "username_ptr",
pattern: Box::leak(sig!("75 04 33 C0 EB 0A A1 ?? ?? ?? ??").into_boxed_slice()),
offset: 7, // offset to the 4-byte address embedded in the instruction
},
);
map.insert(
"game_mode_ptr",
Signature {
name: "game_mode_ptr",
pattern: Box::leak(sig!("83 F8 08 7D 05 ?? ?? ?? ?? ??").into_boxed_slice()),
offset: 5,
},
);
map.insert(
"current_beatmap_ptr",
Signature {
name: "current_beatmap_ptr",
pattern: Box::leak(sig!("6A 01 6A 00 A1 ?? ?? ?? ?? 8B 00").into_boxed_slice()),
offset: 4,
},
);
map.insert(
"combo_ptr",
Signature {
name: "combo_ptr",
pattern: Box::leak(
sig!("83 3D ?? ?? ?? ?? 00 7E 34 A1 ?? ?? ?? ??").into_boxed_slice(),
),
offset: 9,
},
);
// userId typically lives on the same "player info" object as username,
// just at a different field offset — but tosu-style tools usually give
// it its own independent signature since it's read even when the
// username string hasn't been touched yet (e.g. right after login).
map.insert(
"user_id_ptr",
Signature {
name: "user_id_ptr",
pattern: Box::leak(sig!("A1 ?? ?? ?? ?? 89 45 ?? 8B 45 ?? 8B 0D").into_boxed_slice()),
offset: 1,
},
);
map
}
// =========================================================================
// Process handle + raw memory access
// =========================================================================
pub struct MemoryReader {
handle: HANDLE,
pid: u32,
/// Cached list of readable committed memory regions.
regions: Vec<(usize, usize)>, // (base_address, size)
}
impl MemoryReader {
/// Opens the given PID for reading. Returns None if the process can't
/// be opened (e.g. insufficient privileges, process exited).
pub fn open(pid: u32) -> Option<Self> {
let handle =
unsafe { OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pid).ok()? };
Some(Self {
handle,
pid,
regions: Vec::new(),
})
}
/// Re-enumerates committed, readable memory regions. Call once after
/// open() and periodically after (e.g. once per scan cycle), since the
/// process's memory layout can change.
pub fn refresh_regions(&mut self) {
self.regions.clear();
let mut address: usize = 0;
loop {
let mut mbi = MEMORY_BASIC_INFORMATION::default();
let result = unsafe {
VirtualQueryEx(
self.handle,
Some(address as *const _),
&mut mbi,
std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
)
};
if result == 0 {
break; // no more regions
}
let region_size = mbi.RegionSize;
let is_committed = mbi.State == MEM_COMMIT;
let is_guarded = (mbi.Protect & PAGE_GUARD).0 != 0;
let is_no_access = mbi.Protect == PAGE_NOACCESS;
if is_committed && !is_guarded && !is_no_access && region_size > 0 {
self.regions.push((mbi.BaseAddress as usize, region_size));
}
address = (mbi.BaseAddress as usize).saturating_add(region_size);
if address == 0 {
break;
}
}
}
/// Reads `size` bytes starting at `address`. Returns None on failure
/// (unmapped page, access denied, process exited mid-read, etc).
pub fn read_bytes(&self, address: usize, size: usize) -> Option<Vec<u8>> {
let mut buffer = vec![0u8; size];
let mut bytes_read = 0usize;
unsafe {
ReadProcessMemory(
self.handle,
address as *const _,
buffer.as_mut_ptr() as *mut _,
size,
Some(&mut bytes_read),
)
.ok()?;
}
buffer.truncate(bytes_read);
if buffer.is_empty() {
None
} else {
Some(buffer)
}
}
pub fn read_i32(&self, address: usize) -> Option<i32> {
let bytes = self.read_bytes(address, 4)?;
Some(i32::from_le_bytes(bytes.try_into().ok()?))
}
pub fn read_u32(&self, address: usize) -> Option<u32> {
let bytes = self.read_bytes(address, 4)?;
Some(u32::from_le_bytes(bytes.try_into().ok()?))
}
pub fn read_u16(&self, address: usize) -> Option<u16> {
let bytes = self.read_bytes(address, 2)?;
Some(u16::from_le_bytes(bytes.try_into().ok()?))
}
pub fn read_f64(&self, address: usize) -> Option<f64> {
let bytes = self.read_bytes(address, 8)?;
Some(f64::from_le_bytes(bytes.try_into().ok()?))
}
/// Reads a pointer-sized value (4 bytes for the 32-bit osu! stable
/// client). Change to 8 bytes if you ever target a 64-bit build.
pub fn read_ptr(&self, address: usize) -> Option<usize> {
self.read_u32(address).map(|v| v as usize)
}
/// Reads a .NET-style string: [object header][length: i32][utf16 chars].
/// `base` should point at the object header; the classic offset for
/// .NET string length is +0x4 and chars start at +0x8, but verify
/// against your target since layouts can differ.
pub fn read_dotnet_string(&self, base: usize, max_len: usize) -> Option<String> {
let len = self.read_i32(base + 0x4)? as usize;
let len = len.min(max_len);
if len == 0 {
return Some(String::new());
}
let bytes = self.read_bytes(base + 0x8, len * 2)?;
let utf16: Vec<u16> = bytes
.chunks_exact(2)
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.collect();
String::from_utf16(&utf16).ok()
}
/// Scans all cached regions for `signature.pattern`, returning the
/// absolute address where the pattern begins (before applying offset).
pub fn find_signature(&self, signature: &Signature) -> Option<usize> {
for &(base, size) in &self.regions {
// Read in chunks to avoid gigantic single allocations on huge
// regions; 1MB chunks with overlap so patterns aren't missed
// across a chunk boundary.
const CHUNK: usize = 1 << 20;
let overlap = signature.pattern.len().saturating_sub(1);
let mut offset = 0;
while offset < size {
let read_size = CHUNK.min(size - offset);
let Some(mem) = self.read_bytes(base + offset, read_size) else {
offset += CHUNK;
continue;
};
if let Some(pos) = find_pattern(&mem, signature.pattern) {
return Some(base + offset + pos);
}
offset += CHUNK.saturating_sub(overlap).max(1);
}
}
None
}
pub fn pid(&self) -> u32 {
self.pid
}
}
impl Drop for MemoryReader {
fn drop(&mut self) {
unsafe {
let _ = CloseHandle(self.handle);
}
}
}
/// Naive substring search over a byte pattern with wildcards. Fine for
/// per-scan-cycle use; swap for a Boyer-Moore-style skip table if you need
/// to scan very large regions many times per second.
fn find_pattern(haystack: &[u8], pattern: &[Option<u8>]) -> Option<usize> {
if pattern.is_empty() || haystack.len() < pattern.len() {
return None;
}
haystack.windows(pattern.len()).position(|window| {
window
.iter()
.zip(pattern.iter())
.all(|(b, p)| p.map_or(true, |expected| *b == expected))
})
}
// =========================================================================
// High-level "osu state" reader
// =========================================================================
#[derive(Serialize, Debug, Default, Clone)]
pub struct OsuState {
pub username: Option<String>,
pub user_id: Option<i32>,
pub game_mode: Option<i32>,
pub combo: Option<i32>,
pub beatmap_id: Option<i32>,
}
pub struct OsuMemoryClient {
reader: MemoryReader,
signatures: HashMap<&'static str, Signature>,
/// Cached resolved addresses so we don't re-scan the whole memory space
/// every single read — only re-resolve if a read at the cached address
/// stops making sense (e.g. after an osu update / restart).
resolved: HashMap<&'static str, usize>,
/// When true, prints signature resolution + read results to stderr.
/// Toggle via `new_with_debug`, or flip at runtime with `set_debug`.
debug: bool,
}
impl OsuMemoryClient {
pub fn new(pid: u32) -> Option<Self> {
Self::new_with_debug(pid, false)
}
/// Same as `new`, but with debug logging to stderr enabled/disabled
/// explicitly. Handy to wire up to a `--debug` CLI flag or a Tauri
/// dev-mode check (`cfg!(debug_assertions)`).
pub fn new_with_debug(pid: u32, debug: bool) -> Option<Self> {
let mut reader = MemoryReader::open(pid)?;
if debug {
eprintln!("[osu_memory] opening pid {pid} for reading");
}
reader.refresh_regions();
if debug {
eprintln!(
"[osu_memory] found {} readable regions",
reader.regions.len()
);
}
Some(Self {
reader,
signatures: build_signature_table(),
resolved: HashMap::new(),
debug,
})
}
pub fn set_debug(&mut self, debug: bool) {
self.debug = debug;
}
/// Call periodically (e.g. every few seconds, or whenever osu restarts)
/// to pick up new memory layout / re-find signatures.
pub fn refresh(&mut self) {
if self.debug {
eprintln!(
"[osu_memory] refreshing regions + clearing {} cached signature(s)",
self.resolved.len()
);
}
self.reader.refresh_regions();
self.resolved.clear();
if self.debug {
eprintln!(
"[osu_memory] {} readable regions after refresh",
self.reader.regions.len()
);
}
}
fn resolve(&mut self, key: &'static str) -> Option<usize> {
if let Some(addr) = self.resolved.get(key) {
if self.debug {
eprintln!("[osu_memory] {key} -> 0x{addr:X} (cached)");
}
return Some(*addr);
}
let sig = self.signatures.get(key)?.clone();
let Some(found) = self.reader.find_signature(&sig) else {
if self.debug {
eprintln!("[osu_memory] {key}: signature NOT FOUND in any scanned region");
}
return None;
};
let target = (found as isize + sig.offset) as usize;
if self.debug {
eprintln!(
"[osu_memory] {key}: signature matched at 0x{found:X}, target (offset {}) -> 0x{target:X}",
sig.offset
);
}
self.resolved.insert(key, target);
Some(target)
}
pub fn read_username(&mut self) -> Option<String> {
let addr = self.resolve("username_ptr")?;
let ptr = self.reader.read_ptr(addr)?;
let value = self.reader.read_dotnet_string(ptr, 64);
if self.debug {
eprintln!("[osu_memory] username -> {value:?}");
}
value
}
pub fn read_user_id(&mut self) -> Option<i32> {
let addr = self.resolve("user_id_ptr")?;
// Unlike username/combo/beatmap, this signature usually points
// straight at a static int slot rather than through an extra
// object pointer — verify against whatever real signature you use,
// some variants do need an extra self.reader.read_ptr() hop first.
let value = self.reader.read_i32(addr);
if self.debug {
eprintln!("[osu_memory] user_id -> {value:?}");
}
value
}
pub fn read_game_mode(&mut self) -> Option<i32> {
let addr = self.resolve("game_mode_ptr")?;
let ptr = self.reader.read_ptr(addr)?;
let value = self.reader.read_i32(ptr);
if self.debug {
eprintln!("[osu_memory] game_mode -> {value:?}");
}
value
}
pub fn read_combo(&mut self) -> Option<i32> {
let addr = self.resolve("combo_ptr")?;
let ptr = self.reader.read_ptr(addr)?;
let value = self.reader.read_i32(ptr);
if self.debug {
eprintln!("[osu_memory] combo -> {value:?}");
}
value
}
pub fn read_beatmap_id(&mut self) -> Option<i32> {
let addr = self.resolve("current_beatmap_ptr")?;
let ptr = self.reader.read_ptr(addr)?;
let value = self.reader.read_i32(ptr + 0xC); // example nested offset into the beatmap struct
if self.debug {
eprintln!("[osu_memory] beatmap_id -> {value:?}");
}
value
}
/// Convenience: read everything at once into a single struct, suitable
/// for bundling into your existing scan payload / emitting to the
/// frontend.
pub fn read_state(&mut self) -> OsuState {
if self.debug {
eprintln!(
"[osu_memory] --- reading full state (pid {}) ---",
self.reader.pid()
);
}
let state = OsuState {
username: self.read_username(),
user_id: self.read_user_id(),
game_mode: self.read_game_mode(),
combo: self.read_combo(),
beatmap_id: self.read_beatmap_id(),
};
if self.debug {
eprintln!("[osu_memory] state = {state:?}");
}
state
}
}
// =========================================================================
// Example wiring into your existing watcher loop
// =========================================================================
//
// let mut mem_client = OsuMemoryClient::new(osu_pid)?;
// loop {
// let state = mem_client.read_state();
// // attach `state` to your ScanPayload before POSTing to the server
// // if a read silently comes back all-None a few cycles in a row,
// // call mem_client.refresh() in case osu updated/restarted.
// }