feat: update memory reader

This commit is contained in:
2026-07-06 21:26:35 +02:00
parent 195eae4980
commit 804bad5d51
4 changed files with 403 additions and 189 deletions
+66 -36
View File
@@ -10,12 +10,23 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aead"
version = "0.6.1"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
dependencies = [
"crypto-common 0.2.2",
"inout",
"crypto-common 0.1.7",
"generic-array",
]
[[package]]
name = "aes"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher 0.4.4",
"cpufeatures 0.2.17",
]
[[package]]
@@ -24,20 +35,20 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66bd29a732b644c0431c6140f370d097879203d79b80c94a6747ba0872adaef8"
dependencies = [
"cipher",
"cipher 0.5.2",
"cpubits",
"cpufeatures 0.3.0",
]
[[package]]
name = "aes-gcm"
version = "0.11.0"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdf011db2e21ce0d575593d749db5554b47fed37aff429e4dc50bc91ac93a028"
checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
dependencies = [
"aead",
"aes",
"cipher",
"aes 0.8.4",
"cipher 0.4.4",
"ctr",
"ghash",
"subtle",
@@ -549,15 +560,24 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout 0.1.4",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer 0.12.0",
"crypto-common 0.2.2",
"inout",
"inout 0.2.2",
]
[[package]]
@@ -759,6 +779,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"rand_core 0.6.4",
"typenum",
]
@@ -768,9 +789,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"getrandom 0.4.2",
"hybrid-array",
"rand_core 0.10.1",
]
[[package]]
@@ -831,11 +850,11 @@ checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
[[package]]
name = "ctr"
version = "0.10.1"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
dependencies = [
"cipher",
"cipher 0.4.4",
]
[[package]]
@@ -1230,6 +1249,7 @@ dependencies = [
"hardware-id",
"hex",
"md5",
"memchr",
"once_cell",
"open",
"presenceforge",
@@ -1650,7 +1670,6 @@ dependencies = [
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
"wasip2",
"wasip3",
"wasm-bindgen",
@@ -1658,10 +1677,11 @@ dependencies = [
[[package]]
name = "ghash"
version = "0.6.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5"
checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
dependencies = [
"opaque-debug",
"polyval",
]
@@ -2237,6 +2257,15 @@ dependencies = [
"cfb",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "inout"
version = "0.2.2"
@@ -2592,9 +2621,9 @@ checksum = "ae960838283323069879657ca3de837e9f7bbb4c7bf6ea7f1b290d5e9476d2e0"
[[package]]
name = "memchr"
version = "2.7.6"
version = "2.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
[[package]]
name = "memoffset"
@@ -3011,6 +3040,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "opaque-debug"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "open"
version = "5.3.6"
@@ -3381,12 +3416,13 @@ dependencies = [
[[package]]
name = "polyval"
version = "0.7.1"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dfc63250416fea14f5749b90725916a6c903f599d51cb635aa7a52bfd03eede"
checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
dependencies = [
"cpubits",
"cpufeatures 0.3.0",
"cfg-if",
"cpufeatures 0.2.17",
"opaque-debug",
"universal-hash",
]
@@ -3716,12 +3752,6 @@ dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_hc"
version = "0.2.0"
@@ -5603,12 +5633,12 @@ checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "universal-hash"
version = "0.6.1"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
dependencies = [
"crypto-common 0.2.2",
"ctutils",
"crypto-common 0.1.7",
"subtle",
]
[[package]]
@@ -6870,7 +6900,7 @@ version = "8.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
dependencies = [
"aes",
"aes 0.9.0",
"bzip2",
"constant_time_eq",
"crc32fast",
+2 -1
View File
@@ -52,10 +52,11 @@ zip = "8.6.0"
sha1 = "0.11.0"
hex = "0.4.3"
rusqlite = { version = "0.40.1", features = ["bundled"] }
aes-gcm = "0.11.0"
aes-gcm = "0.10.3"
base64 = "0.22.1"
sha2 = "0.11.0"
thiserror = "2.0.18"
memchr = "2.8.2"
[target.'cfg(windows)'.dependencies]
winreg = "0.56.0"
+21
View File
@@ -1,4 +1,5 @@
use crate::config::ConfigError;
use crate::memory_reader::OsuMemoryClient;
use hardware_id::get_id;
use reqwest::Client;
use serde::{Deserialize, Serialize};
@@ -500,6 +501,26 @@ pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> {
}
}
let game_process_id = game_process.id().ok_or(-1);
if let Ok(pid) = game_process_id {
// OsuMemoryClient contains non-Send raw pointers; run its loop in a blocking task
let handle = tokio::task::spawn_blocking(move || {
let mut mem_client = OsuMemoryClient::new_with_debug(pid, true).unwrap();
loop {
if !mem_client.is_running() {
println!("Game process has exited or is not running.");
break;
}
let state = mem_client.read_state();
println!("Game state: {:?}", state);
// wait 5 seconds between iterations to avoid busy-looping
std::thread::sleep(std::time::Duration::from_secs(5));
}
});
handle.await.map_err(|e| e.to_string())?;
}
game_process.wait().await.map_err(|e| e.to_string())?;
Ok(())
}
+315 -153
View File
@@ -1,52 +1,16 @@
//! 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 memchr::memchr;
use serde::Serialize;
use std::collections::HashMap;
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::Foundation::{CloseHandle, HANDLE, STILL_ACTIVE};
use windows::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows::Win32::System::Memory::{
MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQueryEx,
MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE,
PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_NOACCESS, VirtualQueryEx,
};
use windows::Win32::System::Threading::{
GetExitCodeProcess, OpenProcess, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ,
};
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,
@@ -74,71 +38,59 @@ fn parse_aob(s: &str) -> Vec<Option<u8>> {
.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",
"user_profile_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",
name: "user_profile_ptr",
pattern: Box::leak(
sig!("83 3D ?? ?? ?? ?? 00 7E 34 A1 ?? ?? ?? ??").into_boxed_slice(),
sig!("FF 15 ?? ?? ?? ?? A1 ?? ?? ?? ?? 8B 48 54 33 D2").into_boxed_slice(),
),
offset: 9,
offset: 0x7,
},
);
// 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",
"base_addr",
Signature {
name: "user_id_ptr",
pattern: Box::leak(sig!("A1 ?? ?? ?? ?? 89 45 ?? 8B 45 ?? 8B 0D").into_boxed_slice()),
offset: 1,
name: "base_addr",
pattern: Box::leak(sig!("F8 01 74 04 83 65").into_boxed_slice()),
offset: 0,
},
);
map.insert(
"rulesets_addr",
Signature {
name: "rulesets_addr",
pattern: Box::leak(sig!("7D 15 A1 ?? ?? ?? ?? 85 C0").into_boxed_slice()),
offset: 0,
},
);
map.insert(
"status_ptr",
Signature {
name: "status_ptr",
pattern: Box::leak(sig!("48 83 F8 04 73 1E").into_boxed_slice()),
offset: -0x4,
},
);
map.insert(
"play_time_addr",
Signature {
name: "play_time_addr",
pattern: Box::leak(sig!("5E 5F 5D C3 A1 ?? ?? ?? ?? 89 ?? 04").into_boxed_slice()),
offset: 0,
},
);
map
}
// =========================================================================
// Process handle + raw memory access
// =========================================================================
pub struct MemoryReader {
handle: HANDLE,
pid: u32,
@@ -162,10 +114,27 @@ impl MemoryReader {
/// 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.
///
/// By default only keeps EXECUTABLE regions. This matters a lot for
/// speed: our signatures target JIT-compiled machine code, which only
/// ever lives in executable pages — the managed heap, GC data, and
/// other non-executable regions can be gigabytes in size and contain
/// nothing worth scanning. Skipping them is the single biggest speedup
/// available here. Pass `executable_only = false` only if you add a
/// signature that targets plain data instead of code.
pub fn refresh_regions(&mut self) {
self.refresh_regions_filtered(true);
}
pub fn refresh_regions_filtered(&mut self, executable_only: bool) {
self.regions.clear();
let mut address: usize = 0;
const EXECUTABLE_FLAGS: u32 = PAGE_EXECUTE.0
| PAGE_EXECUTE_READ.0
| PAGE_EXECUTE_READWRITE.0
| PAGE_EXECUTE_WRITECOPY.0;
loop {
let mut mbi = MEMORY_BASIC_INFORMATION::default();
let result = unsafe {
@@ -185,8 +154,15 @@ impl MemoryReader {
let is_committed = mbi.State == MEM_COMMIT;
let is_guarded = (mbi.Protect & PAGE_GUARD).0 != 0;
let is_no_access = mbi.Protect == PAGE_NOACCESS;
let is_executable = (mbi.Protect.0 & EXECUTABLE_FLAGS) != 0;
if is_committed && !is_guarded && !is_no_access && region_size > 0 {
let keep = is_committed
&& !is_guarded
&& !is_no_access
&& region_size > 0
&& (!executable_only || is_executable);
if keep {
self.regions.push((mbi.BaseAddress as usize, region_size));
}
@@ -222,6 +198,11 @@ impl MemoryReader {
}
}
pub fn read_u8(&self, address: usize) -> Option<u8> {
let bytes = self.read_bytes(address, 1)?;
Some(bytes[0])
}
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()?))
@@ -237,6 +218,16 @@ impl MemoryReader {
Some(u16::from_le_bytes(bytes.try_into().ok()?))
}
pub fn read_i64(&self, address: usize) -> Option<i64> {
let bytes = self.read_bytes(address, 8)?;
Some(i64::from_le_bytes(bytes.try_into().ok()?))
}
pub fn read_f32(&self, address: usize) -> Option<f32> {
let bytes = self.read_bytes(address, 4)?;
Some(f32::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()?))
@@ -299,6 +290,18 @@ impl MemoryReader {
pub fn pid(&self) -> u32 {
self.pid
}
/// Returns true if the target process is still running.
pub fn is_running(&self) -> bool {
let mut code: u32 = 0;
unsafe {
if GetExitCodeProcess(self.handle, &mut code).is_ok() {
// STILL_ACTIVE is an NTSTATUS; compare against its inner value as u32
return code == (STILL_ACTIVE.0 as u32);
}
}
false
}
}
impl Drop for MemoryReader {
@@ -309,33 +312,109 @@ impl Drop for MemoryReader {
}
}
/// 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.
/// Pattern search accelerated with `memchr`: instead of checking every
/// single byte offset, we jump straight to candidate positions for the
/// pattern's first non-wildcard byte, and only run the full (still naive,
/// but now rarely-invoked) comparison at those candidates. If the pattern
/// is all-wildcards up front (rare/pathological), falls back to a plain
/// per-offset scan.
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
let Some((anchor_idx, anchor_byte)) = pattern
.iter()
.enumerate()
.find_map(|(i, b)| b.map(|byte| (i, byte)))
else {
// Fully wildcarded pattern — nothing to anchor on, first position works.
return Some(0);
};
let max_start = haystack.len() - pattern.len();
// Absolute position in `haystack` from which we search for the anchor
// byte. Starts at anchor_idx since candidate_start can't go negative
// (candidate_start = anchor_pos - anchor_idx).
let mut anchor_pos = anchor_idx;
loop {
if anchor_pos >= haystack.len() {
return None;
}
let Some(rel) = memchr(anchor_byte, &haystack[anchor_pos..]) else {
return None; // anchor byte doesn't occur again — no match possible
};
let abs_anchor = anchor_pos + rel;
let candidate_start = abs_anchor - anchor_idx; // safe: abs_anchor >= anchor_pos >= anchor_idx
if candidate_start > max_start {
return None;
}
let window = &haystack[candidate_start..candidate_start + pattern.len()];
let matches = window
.iter()
.zip(pattern.iter())
.all(|(b, p)| p.map_or(true, |expected| *b == expected))
})
.all(|(b, p)| p.map_or(true, |expected| *b == expected));
if matches {
return Some(candidate_start);
}
anchor_pos = abs_anchor + 1;
}
}
// =========================================================================
// High-level "osu state" reader
// =========================================================================
#[derive(Serialize, Debug, Default, Clone)]
pub struct OsuProfile {
pub name: Option<String>,
pub id: Option<i32>,
pub accuracy: Option<f64>,
pub ranked_score: Option<i64>,
pub level: Option<f32>,
pub play_count: Option<i32>,
pub play_mode: Option<i32>,
pub rank: Option<i32>,
pub country_code: Option<i32>,
pub performance_points: Option<i32>,
/// ARGB packed color; convert with format!("{:08X}", background_colour)
pub background_colour: Option<u32>,
pub raw_bancho_status: Option<u8>,
}
#[derive(Serialize, Debug, Default, Clone)]
pub struct BeatmapInfo {
pub checksum: Option<String>,
pub filename: Option<String>,
pub artist: Option<String>,
pub artist_original: Option<String>,
pub title: Option<String>,
pub title_original: Option<String>,
pub creator: Option<String>,
pub difficulty_name: Option<String>,
pub folder: Option<String>,
pub audio_filename: Option<String>,
pub background_filename: Option<String>,
pub ar: Option<f32>,
pub cs: Option<f32>,
pub hp: Option<f32>,
pub od: Option<f32>,
pub map_id: Option<i32>,
pub set_id: Option<i32>,
pub ranked_status: Option<i32>,
pub object_count: Option<i32>,
}
#[derive(Serialize, Debug, Default, Clone)]
pub struct OsuState {
pub username: Option<String>,
pub user_id: Option<i32>,
pub profile: OsuProfile,
pub status: Option<i32>,
pub play_time: Option<i32>,
pub game_mode: Option<i32>,
pub combo: Option<i32>,
pub beatmap_id: Option<i32>,
pub beatmap: BeatmapInfo,
}
pub struct OsuMemoryClient {
@@ -345,6 +424,10 @@ pub struct OsuMemoryClient {
/// 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>,
/// Signatures that failed to resolve on the last attempt. Prevents
/// re-running a full (expensive) memory scan every single call when a
/// signature is missing/wrong — cleared only by `refresh()`.
failed: std::collections::HashSet<&'static str>,
/// When true, prints signature resolution + read results to stderr.
/// Toggle via `new_with_debug`, or flip at runtime with `set_debug`.
debug: bool,
@@ -374,6 +457,7 @@ impl OsuMemoryClient {
reader,
signatures: build_signature_table(),
resolved: HashMap::new(),
failed: std::collections::HashSet::new(),
debug,
})
}
@@ -393,6 +477,7 @@ impl OsuMemoryClient {
}
self.reader.refresh_regions();
self.resolved.clear();
self.failed.clear();
if self.debug {
eprintln!(
"[osu_memory] {} readable regions after refresh",
@@ -409,11 +494,21 @@ impl OsuMemoryClient {
return Some(*addr);
}
if self.failed.contains(key) {
if self.debug {
eprintln!(
"[osu_memory] {key}: skipping, previously failed this cycle (call refresh() to retry)"
);
}
return None;
}
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");
}
self.failed.insert(key);
return None;
};
let target = (found as isize + sig.offset) as usize;
@@ -429,62 +524,136 @@ impl OsuMemoryClient {
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);
/// Resolves the profile object pointer (one signature lookup + one
/// pointer dereference), shared by every field below so we don't
/// re-resolve the signature per-field.
fn resolve_profile_base(&mut self) -> Option<usize> {
let addr = self.resolve("user_profile_ptr")?;
let base = self.reader.read_ptr(addr)?;
if self.debug {
eprintln!("[osu_memory] username -> {value:?}");
eprintln!("[osu_memory] profileBase -> 0x{base:X}");
}
Some(base)
}
/// Reads the full player profile in one shot, mirroring tosu's `user()`
/// getter: one profileBase pointer, then every field at a fixed byte
/// offset from it.
pub fn read_profile(&mut self) -> OsuProfile {
let Some(base) = self.resolve_profile_base() else {
return OsuProfile::default();
};
let name_str_ptr = self.reader.read_i32(base + 0x30).map(|v| v as usize);
let name = name_str_ptr.and_then(|p| self.reader.read_dotnet_string(p, 64));
let profile = OsuProfile {
name,
id: self.reader.read_i32(base + 0x70),
accuracy: self.reader.read_f64(base + 0x4),
ranked_score: self.reader.read_i64(base + 0xc),
level: self.reader.read_f32(base + 0x74),
play_count: self.reader.read_i32(base + 0x7c),
play_mode: self.reader.read_i32(base + 0x80),
rank: self.reader.read_i32(base + 0x84),
country_code: self.reader.read_i32(base + 0x9c),
performance_points: self.reader.read_i32(base + 0x88),
background_colour: self.reader.read_u32(base + 0xac),
raw_bancho_status: self.reader.read_u8(base + 0x8c),
};
if self.debug {
eprintln!("[osu_memory] profile -> {profile:?}");
}
profile
}
pub fn read_status(&mut self) -> Option<i32> {
let addr = self.resolve("status_ptr")?;
let value = self.reader.read_i32(addr);
if self.debug {
eprintln!("[osu_memory] status -> {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);
pub fn read_play_time(&mut self) -> Option<i32> {
let addr = self.resolve("play_time_addr")?;
let ptr = self.reader.read_i32(addr + 0x5)? as usize;
let value = self.reader.read_i32(ptr);
if self.debug {
eprintln!("[osu_memory] user_id -> {value:?}");
eprintln!("[osu_memory] play_time -> {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);
let base = self.resolve("base_addr")?;
let value = self.reader.read_i32(base.wrapping_sub(0x33));
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);
#[allow(dead_code)]
fn resolve_ruleset_addr(&mut self) -> Option<usize> {
let sig_addr = self.resolve("rulesets_addr")?;
let step1 = self.reader.read_i32(sig_addr.wrapping_sub(0xb))? as usize;
let ruleset_addr = self.reader.read_i32(step1 + 0x4)? as usize;
if self.debug {
eprintln!("[osu_memory] combo -> {value:?}");
eprintln!("[osu_memory] ruleset_addr -> 0x{ruleset_addr:X}");
}
value
Some(ruleset_addr)
}
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
pub fn read_current_beatmap(&mut self) -> BeatmapInfo {
let Some(base) = self.resolve("base_addr") else {
return BeatmapInfo::default();
};
let Some(beatmap_addr) = self
.reader
.read_i32(base.wrapping_sub(0xc))
.map(|v| v as usize)
else {
return BeatmapInfo::default();
};
let read_str_field = |reader: &MemoryReader, off: usize| -> Option<String> {
let ptr = reader.read_i32(beatmap_addr + off)? as usize;
reader.read_dotnet_string(ptr, 512)
};
let info = BeatmapInfo {
checksum: read_str_field(&self.reader, 0x6c),
filename: read_str_field(&self.reader, 0x90),
artist: read_str_field(&self.reader, 0x18),
artist_original: read_str_field(&self.reader, 0x1c),
title: read_str_field(&self.reader, 0x24),
title_original: read_str_field(&self.reader, 0x28),
creator: read_str_field(&self.reader, 0x7c),
difficulty_name: read_str_field(&self.reader, 0xac),
folder: read_str_field(&self.reader, 0x78),
audio_filename: read_str_field(&self.reader, 0x64),
background_filename: read_str_field(&self.reader, 0x68),
ar: self.reader.read_f32(beatmap_addr + 0x2c),
cs: self.reader.read_f32(beatmap_addr + 0x30),
hp: self.reader.read_f32(beatmap_addr + 0x34),
od: self.reader.read_f32(beatmap_addr + 0x38),
map_id: self.reader.read_i32(beatmap_addr + 0xc8),
set_id: self.reader.read_i32(beatmap_addr + 0xcc),
ranked_status: self.reader.read_i32(beatmap_addr + 0x12c),
object_count: self.reader.read_i32(beatmap_addr + 0xf8),
};
if self.debug {
eprintln!("[osu_memory] beatmap_id -> {value:?}");
}
value
eprintln!("[osu_memory] beatmap -> {info:?}");
}
info
}
/// 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!(
@@ -493,27 +662,20 @@ impl OsuMemoryClient {
);
}
let state = OsuState {
username: self.read_username(),
user_id: self.read_user_id(),
profile: self.read_profile(),
status: self.read_status(),
play_time: self.read_play_time(),
game_mode: self.read_game_mode(),
combo: self.read_combo(),
beatmap_id: self.read_beatmap_id(),
beatmap: self.read_current_beatmap(),
};
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.
// }
/// Returns true if the target osu! process is still running.
pub fn is_running(&self) -> bool {
self.reader.is_running()
}
}