mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 13:18:37 +00:00
Game actions: the title's script natives found by their handlers; god mode through them (god, native <hash>)
The natives were never found as a table (docs/mod-menu.md, "Looking for the script natives"): the title builds
its own at run time. Every handler has one shape, though: it checks its argument count first
(`cmp dword [rcx + 10h], 0`) and on a negative one jumps (`js`) to an error block that stores its native's own
64-bit hash where the result goes (`mov rax, [r]; mov r2, imm64; mov [rax], r2`).
- leonida_loader::natives: scan() reads that hash from every such handler in the code and keeps the start of the
function it lies in (from .pdata, at most 0x20 bytes before the check); a hash at two handlers names neither.
find() does it over the mapped image. In the 1.0.2.1 executable: more than 6,000 natives, PLAYER_PED_ID's and
SET_ENTITY_INVINCIBLE's hashes among them (the handler with the latter is the one El1xr's trainer calls for it).
- Game actions: call_native() passes a handler its call context (argument slots, the results' slots, the count;
16-byte aligned slots), on the title's thread that runs its cheats. New requests: God(on), SET_ENTITY_INVINCIBLE
on PLAYER_PED_ID's reference (`god <0|1>`), and Native { hash, args } (`native <0x hash> [slots]`, for tests).
The natives are scanned at install and counted in the console.
The shape and the call context are kylepelham/El1xr's findings (third_party/victory/.../modmenu/natives.rs,
GPL-3.0); the hashes are modpapi/scripthook-vi's native database's (CC BY 4.0). Written here anew.
Tests: natives::tests (a handler's hash names it, near and far jumps; a hash at two handlers, a handler outside the
unwind table, other registers or a load through rsp or a check too deep name nothing; the unwind table read
sorted; the retail executable's natives with LEONIDA_GAME_DIR), game_actions spawn_tests
a_native_call_hands_its_handler_the_slots_and_the_count, and the new commands in script_commands_read. All pass.
Not yet seen in the running title.
AI-assisted (Claude). Tested on an RTX 4060 Ti 16 GB, driver 616.64, Ryzen 5 7600X (unit tests and the
executable check only).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -12,7 +12,9 @@
|
||||
//! - `LEONIDA_GAME_ACTIONS_RUN="<s>:<command>;..."` asks for commands that many seconds after the start, for a
|
||||
//! test without the keyboard: `info`, `cheat <n>`, `wanted <n>`, `time <h> [m [s]]`, `hours <+-n>`,
|
||||
//! `pause <0|1>`, `weather <n|name|free>`, `nudge <dx> <dy> <dz> [frames]`, `spawn <model name|0x key>` (a
|
||||
//! vehicle of any model the title has, made by the spawn its vehicle cheats call).
|
||||
//! vehicle of any model the title has, made by the spawn its vehicle cheats call), `god <0|1>` (the player
|
||||
//! invincible, through the title's natives found by their handlers: `leonida_loader::natives`), and
|
||||
//! `native <0x hash> [slots]` (any native, its results into the log: the arguments are the asker's).
|
||||
//! - `LEONIDA_GAME_ACTIONS_WARP=1` lets a teleport write the ped's position on the title's thread: an
|
||||
//! experiment, the title's own function for moving a ped was not found.
|
||||
//!
|
||||
@ -26,6 +28,7 @@ use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use leonida_loader::game_actions::{self as places, Site, Sites};
|
||||
use leonida_loader::natives::{self, Natives};
|
||||
use leonida_menu::model::Value;
|
||||
|
||||
use crate::player::mem;
|
||||
@ -66,6 +69,11 @@ pub enum Request {
|
||||
/// A vehicle of this model key ([`model_key`]) made by the title's vehicle spawn, as its vehicle cheats make
|
||||
/// theirs (ahead of the player; the vehicle the spawn made before goes, as with the cheats).
|
||||
Spawn(u64),
|
||||
/// The player's ped invincible or not: SET_ENTITY_INVINCIBLE on PLAYER_PED_ID's reference ([`natives`]).
|
||||
God(bool),
|
||||
/// A native by its hash with these argument slots, its first four result slots into the log (for tests: the
|
||||
/// arguments are the caller's to get right).
|
||||
Native { hash: u64, args: Vec<u64> },
|
||||
/// What the runtime sees of the title, into the log.
|
||||
Info,
|
||||
}
|
||||
@ -77,6 +85,8 @@ struct Game {
|
||||
sites: Sites,
|
||||
cheats_update: unsafe extern "win64" fn(),
|
||||
defer: unsafe extern "win64" fn(u32, *const Closure),
|
||||
/// The title's natives by hash ([`natives::scan`]).
|
||||
natives: Natives,
|
||||
}
|
||||
|
||||
static GAME: OnceLock<Game> = OnceLock::new();
|
||||
@ -163,6 +173,49 @@ fn murmur3_x64_128_low(data: &[u8]) -> u64 {
|
||||
h1.wrapping_add(h2)
|
||||
}
|
||||
|
||||
/// Natives by their hash in modpapi/scripthook-vi's native database (CC BY 4.0, build 1.0.2.1). PLAYER_PED_ID takes
|
||||
/// nothing and gives the player's ped as a script reference of two slots; SET_ENTITY_INVINCIBLE takes an entity's
|
||||
/// reference (two slots) and on or off.
|
||||
const PLAYER_PED_ID: u64 = 0x6471_F11F_F69D_8A77;
|
||||
const SET_ENTITY_INVINCIBLE: u64 = 0x3BD9_0347_5A3C_78C9;
|
||||
|
||||
/// The most argument slots a native call passes.
|
||||
const NATIVE_SLOTS: usize = 32;
|
||||
|
||||
/// A native's call context as its handler reads it ([`natives`]): the argument slots, where the results go, and the
|
||||
/// argument count (a negative one sends the handler down its error block); room after it for fields some handlers
|
||||
/// may use. After kylepelham/El1xr's `modmenu/natives.rs` (GPL-3.0).
|
||||
#[repr(C)]
|
||||
struct CallContext {
|
||||
args: *mut u64,
|
||||
ret: *mut u64,
|
||||
count: i32,
|
||||
rest: [u32; 23],
|
||||
}
|
||||
|
||||
/// Argument or result slots, 16-byte aligned: a vector is four packed floats in two slots, which a handler may move
|
||||
/// with aligned loads and stores.
|
||||
#[repr(C, align(16))]
|
||||
struct Slots([u64; NATIVE_SLOTS]);
|
||||
|
||||
/// Calls the native handler at `entry` with `args` (at most [`NATIVE_SLOTS`]); its first four result slots.
|
||||
///
|
||||
/// # Safety
|
||||
/// `entry` is a native handler of the title ([`natives::scan`]), called on a title thread with the arguments that
|
||||
/// native takes.
|
||||
unsafe fn call_native(entry: usize, args: &[u64]) -> [u64; 4] {
|
||||
let mut slots = Slots([0; NATIVE_SLOTS]);
|
||||
let n = args.len().min(NATIVE_SLOTS);
|
||||
slots.0[..n].copy_from_slice(&args[..n]);
|
||||
let mut ret = Slots([0; NATIVE_SLOTS]);
|
||||
let mut context = CallContext { args: slots.0.as_mut_ptr(), ret: ret.0.as_mut_ptr(), count: n as i32, rest: [0; 23] };
|
||||
// SAFETY: the caller's contract: a handler, which takes one call context.
|
||||
let handler: unsafe extern "win64" fn(*mut CallContext) = unsafe { std::mem::transmute(entry) };
|
||||
// SAFETY: as above; the context and its slots live through the call.
|
||||
unsafe { handler(&mut context) };
|
||||
[ret.0[0], ret.0[1], ret.0[2], ret.0[3]]
|
||||
}
|
||||
|
||||
/// Where a vehicle cheat's handler at `at` calls, if it is one: `sub rsp, 28h; mov rcx, imm64` (the model's key),
|
||||
/// then `call rel32` (`code` from `at` on, 19 bytes or more).
|
||||
fn spawn_call_target(code: &[u8], at: usize) -> Option<usize> {
|
||||
@ -262,6 +315,25 @@ fn parse_command(text: &str) -> Result<Command, String> {
|
||||
None => model_key(word),
|
||||
})
|
||||
}
|
||||
"god" => Request::God(int(0)? != 0),
|
||||
"native" => {
|
||||
let slot = |word: &str| -> Result<u64, String> {
|
||||
match word.strip_prefix("0x") {
|
||||
Some(hex) => u64::from_str_radix(hex, 16).ok(),
|
||||
None => word.parse::<i64>().ok().map(|v| v as u64),
|
||||
}
|
||||
.ok_or_else(|| format!("native: {word} is not a number"))
|
||||
};
|
||||
let hash = rest.first().ok_or("native: a hash (0x...) and its arguments")?;
|
||||
if !hash.starts_with("0x") {
|
||||
return Err(format!("native: {hash} is not a 0x hash"));
|
||||
}
|
||||
let args = rest[1..].iter().map(|w| slot(w)).collect::<Result<Vec<u64>, String>>()?;
|
||||
if args.len() > NATIVE_SLOTS {
|
||||
return Err(format!("native: at most {NATIVE_SLOTS} arguments"));
|
||||
}
|
||||
Request::Native { hash: slot(hash)?, args }
|
||||
}
|
||||
_ => return Err(format!("{name}: not a command")),
|
||||
}))
|
||||
}
|
||||
@ -555,11 +627,39 @@ impl Game {
|
||||
unsafe { call(key) };
|
||||
Ok(format!("vehicle {key:#018x} asked of the title's spawn (+{:#x})", spawn - self.base))
|
||||
}
|
||||
Request::God(on) => {
|
||||
// SAFETY: forwarded from this function's contract; PLAYER_PED_ID takes no arguments.
|
||||
let me = unsafe { self.native(PLAYER_PED_ID, &[]) }?;
|
||||
if me[0] == 0 {
|
||||
return Err("no player reference".into());
|
||||
}
|
||||
// SAFETY: as above; SET_ENTITY_INVINCIBLE with the reference's two slots and on or off.
|
||||
unsafe { self.native(SET_ENTITY_INVINCIBLE, &[me[0], me[1], u64::from(on)]) }?;
|
||||
Ok(format!("god mode {} (the player's reference {:#x} {:#x})", if on { "on" } else { "off" }, me[0], me[1]))
|
||||
}
|
||||
Request::Native { hash, ref args } => {
|
||||
// SAFETY: forwarded from this function's contract; the arguments are the asker's.
|
||||
let out = unsafe { self.native(hash, args) }?;
|
||||
Ok(format!("native {hash:#018x} {args:x?}: {out:x?}"))
|
||||
}
|
||||
// SAFETY: forwarded from this function's contract.
|
||||
Request::Info => Ok(unsafe { self.info(frame) }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the native with `hash` ([`call_native`]); its first four result slots.
|
||||
///
|
||||
/// # Safety
|
||||
/// On the title's thread, from the deferred call, with the arguments that native takes.
|
||||
unsafe fn native(&self, hash: u64, args: &[u64]) -> Result<[u64; 4], String> {
|
||||
let rva = self.natives.find(hash).ok_or_else(|| format!("native {hash:#018x}: not found in this executable"))?;
|
||||
if args.len() > NATIVE_SLOTS {
|
||||
return Err(format!("native {hash:#018x}: at most {NATIVE_SLOTS} arguments"));
|
||||
}
|
||||
// SAFETY: a handler the scan found in the image; the rest is the caller's contract.
|
||||
Ok(unsafe { call_native(self.base + rva as usize, args) })
|
||||
}
|
||||
|
||||
/// The title's vehicle spawn: the function its vehicle cheats call with their model's key, read from their
|
||||
/// code through the cheat table ([`spawn_call_target`]). Every handler of that form must call the same function,
|
||||
/// inside the image, and there must be two or more of them, or the table is not what it was taken for.
|
||||
@ -967,7 +1067,15 @@ fn start(base: usize, info: &leonida_pe::ImageInfo, sites: Sites, hooked: Result
|
||||
std::mem::transmute::<usize, unsafe extern "win64" fn(u32, *const Closure)>(base + defer)
|
||||
},
|
||||
sites,
|
||||
// SAFETY: `install`'s contract (the only caller): the mapped image, none of its code running yet.
|
||||
natives: unsafe { natives::find(base, info) },
|
||||
};
|
||||
println!(
|
||||
"game actions natives: {} found by their handlers ({} hashes at two handlers, {} shapes outside a function)",
|
||||
game.natives.len(),
|
||||
game.natives.repeated,
|
||||
game.natives.unplaced
|
||||
);
|
||||
println!(
|
||||
"game actions on ({}=1): the title's cheat update is hooked; {} of {} things found; log in {}",
|
||||
places::ENV,
|
||||
@ -989,7 +1097,30 @@ fn start(base: usize, info: &leonida_pe::ImageInfo, sites: Sites, hooked: Result
|
||||
|
||||
#[cfg(test)]
|
||||
mod spawn_tests {
|
||||
use super::{model_key, murmur3_x64_128_low, spawn_call_target};
|
||||
use super::{CallContext, call_native, model_key, murmur3_x64_128_low, spawn_call_target};
|
||||
|
||||
/// Writes the sum of its arguments, their count and whether both slot arrays are 16-byte aligned (0) into
|
||||
/// its first three result slots, as a native handler writes its results.
|
||||
unsafe extern "win64" fn adder(context: *mut CallContext) {
|
||||
// SAFETY: `call_native`'s context and slots, alive through the call.
|
||||
unsafe {
|
||||
let c = &*context;
|
||||
let args = std::slice::from_raw_parts(c.args, c.count as usize);
|
||||
*c.ret = args.iter().sum();
|
||||
*c.ret.add(1) = c.count as u64;
|
||||
*c.ret.add(2) = (c.args as usize % 16 + c.ret as usize % 16) as u64;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_native_call_hands_its_handler_the_slots_and_the_count() {
|
||||
// SAFETY: a handler of this test's, which takes one call context.
|
||||
let out = unsafe { call_native(adder as unsafe extern "win64" fn(*mut CallContext) as usize, &[1, 2, 3]) };
|
||||
assert_eq!(out, [6, 3, 0, 0]);
|
||||
// SAFETY: as above.
|
||||
let none = unsafe { call_native(adder as unsafe extern "win64" fn(*mut CallContext) as usize, &[]) };
|
||||
assert_eq!(none, [0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_keys_are_murmur3_x64_128_of_the_lower_cased_name() {
|
||||
@ -1102,7 +1233,17 @@ mod tests {
|
||||
);
|
||||
assert_eq!(parse_command("spawn Sanchez"), d(Request::Spawn(model_key("sanchez"))));
|
||||
assert_eq!(parse_command("spawn 0x10d3"), d(Request::Spawn(0x10d3)));
|
||||
for wrong in ["", "fly", "cheat", "cheat x", "cheat -1", "wanted", "time", "weather", "nudge 1 2", "nudge 1 2 nan", "spawn", "spawn 0xzz"] {
|
||||
assert_eq!(parse_command("god 1"), d(Request::God(true)));
|
||||
assert_eq!(parse_command("god 0"), d(Request::God(false)));
|
||||
assert_eq!(parse_command("native 0x6471F11FF69D8A77"), d(Request::Native { hash: 0x6471_F11F_F69D_8A77, args: vec![] }));
|
||||
assert_eq!(
|
||||
parse_command("native 0x10 1 -1 0xff"),
|
||||
d(Request::Native { hash: 0x10, args: vec![1, u64::MAX, 0xff] })
|
||||
);
|
||||
for wrong in [
|
||||
"", "fly", "cheat", "cheat x", "cheat -1", "wanted", "time", "weather", "nudge 1 2", "nudge 1 2 nan", "spawn",
|
||||
"spawn 0xzz", "god", "native", "native 10", "native 0x10 x",
|
||||
] {
|
||||
assert!(parse_command(wrong).is_err(), "{wrong:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,6 +32,8 @@ mod vipatch;
|
||||
// Leonida: where the title's own cheat system is, and the once-a-frame hook the trainer menu's game actions
|
||||
// run through (`LEONIDA_GAME_ACTIONS=1`); docs/mod-menu.md.
|
||||
pub mod game_actions;
|
||||
// Leonida: the title's script natives by the shape of their handlers (the trainer's god mode and others).
|
||||
pub mod natives;
|
||||
pub mod prepare;
|
||||
pub(crate) mod publish;
|
||||
pub mod resolve;
|
||||
|
||||
270
d3d12/crates/leonida-loader/src/natives.rs
Normal file
270
d3d12/crates/leonida-loader/src/natives.rs
Normal file
@ -0,0 +1,270 @@
|
||||
//! The title's script natives, found by the shape of their handlers in its code (`docs/mod-menu.md`, "Game
|
||||
//! actions"): no addresses, and no table of the title's (it builds its own at run time, from nothing a scan of the
|
||||
//! file can follow).
|
||||
//!
|
||||
//! A native is a handler that takes one call context: its arguments as 8-byte slots, a pointer its results are
|
||||
//! written through, and the count of arguments. Every handler begins by checking that count
|
||||
//! (`cmp dword [rcx + 10h], 0`) and jumps on a negative one (`js`) to an error block that stores the native's own
|
||||
//! 64-bit hash where the result goes (`mov rax, [r]`; `mov r2, imm64`; `mov [rax], r2`). So the hash names the
|
||||
//! handler: [`scan`] reads it from each one and keeps the start of the function it lies in (from the image's
|
||||
//! unwind table, at most [`MOST_BEFORE`] bytes before the check). A hash found at two handlers names neither.
|
||||
//!
|
||||
//! The shape and the call context are kylepelham/El1xr's findings (`modmenu/natives.rs`, GPL-3.0); the hashes
|
||||
//! callers name are those of modpapi/scripthook-vi's native database (CC BY 4.0). Checked against the 1.0.2.1
|
||||
//! executable: the handler with SET_ENTITY_INVINCIBLE's hash is the one El1xr's trainer calls for it.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
/// `cmp dword [rcx + 10h], 0`: a handler's check of its argument count.
|
||||
const COUNT_CHECK: [u8; 4] = [0x83, 0x79, 0x10, 0x00];
|
||||
|
||||
/// How far into its function a handler's count check may lie.
|
||||
pub const MOST_BEFORE: u32 = 0x20;
|
||||
|
||||
/// The natives a scan found.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Natives {
|
||||
/// (hash, offset of the handler in the image), sorted by hash.
|
||||
list: Vec<(u64, u32)>,
|
||||
/// Hashes found at more than one handler (left out).
|
||||
pub repeated: usize,
|
||||
/// Handler shapes no function of the unwind table holds near enough (left out).
|
||||
pub unplaced: usize,
|
||||
}
|
||||
|
||||
impl Natives {
|
||||
/// The handler of the native with `hash`, as an offset in the image.
|
||||
pub fn find(&self, hash: u64) -> Option<u32> {
|
||||
self.list.binary_search_by_key(&hash, |e| e.0).ok().map(|i| self.list[i].1)
|
||||
}
|
||||
|
||||
/// How many natives were found.
|
||||
pub fn len(&self) -> usize {
|
||||
self.list.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.list.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The hash an error block at the start of `block` stores: `mov rax, [r]` (r not rsp or rbp, no displacement),
|
||||
/// `mov r2, imm64`, `mov [rax], r2`.
|
||||
fn error_hash(block: &[u8]) -> Option<u64> {
|
||||
let b = block.get(..16)?;
|
||||
let load = b[..2] == [0x48, 0x8B] && b[2] & 0xF8 == 0 && !matches!(b[2], 4 | 5);
|
||||
let movabs = b[3] == 0x48 && (0xB8..=0xBF).contains(&b[4]);
|
||||
let store = b[13..15] == [0x48, 0x89] && b[15] & 0xC7 == 0 && b[15] >> 3 == b[4] - 0xB8;
|
||||
(load && movabs && store).then(|| u64::from_le_bytes(b[5..13].try_into().unwrap()))
|
||||
}
|
||||
|
||||
/// Where the `js` in the ten bytes after a count check at `at` (an offset in `code`) jumps to, if one is there.
|
||||
fn error_target(code: &[u8], at: usize) -> Option<usize> {
|
||||
let tail = code.get(at + 4..at + 14)?;
|
||||
for k in 0..tail.len() {
|
||||
if tail[k] == 0x78 {
|
||||
let rel = *tail.get(k + 1)? as i8;
|
||||
return (at + 4 + k + 2).checked_add_signed(rel as isize);
|
||||
}
|
||||
if tail[k] == 0x0F && tail.get(k + 1) == Some(&0x88) {
|
||||
let rel = i32::from_le_bytes(tail.get(k + 2..k + 6)?.try_into().ok()?);
|
||||
return (at + 4 + k + 6).checked_add_signed(rel as isize);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The functions of an unwind table (`.pdata`: begin, end and unwind data, 12 bytes each) as (begin, end) RVAs,
|
||||
/// sorted by begin; entries that are not functions left out.
|
||||
pub fn functions_of(pdata: &[u8]) -> Vec<(u32, u32)> {
|
||||
let mut functions: Vec<(u32, u32)> = pdata
|
||||
.chunks_exact(12)
|
||||
.map(|e| (u32::from_le_bytes(e[..4].try_into().unwrap()), u32::from_le_bytes(e[4..8].try_into().unwrap())))
|
||||
.filter(|&(begin, end)| begin < end)
|
||||
.collect();
|
||||
functions.sort_unstable();
|
||||
functions
|
||||
}
|
||||
|
||||
/// The start of the function of `functions` that holds `rva`.
|
||||
fn function_start(functions: &[(u32, u32)], rva: u32) -> Option<u32> {
|
||||
let i = functions.partition_point(|f| f.0 <= rva).checked_sub(1)?;
|
||||
let (begin, end) = functions[i];
|
||||
(rva < end).then_some(begin)
|
||||
}
|
||||
|
||||
/// The natives of an image whose executable sections are `code` (offset in the image, bytes) and whose unwind
|
||||
/// table gives `functions` ([`functions_of`]).
|
||||
pub fn scan(code: &[(usize, &[u8])], functions: &[(u32, u32)]) -> Natives {
|
||||
let mut found: Vec<(u64, u32)> = Vec::new();
|
||||
let mut unplaced = 0;
|
||||
for &(start, bytes) in code {
|
||||
let mut from = 0;
|
||||
while let Some(k) = bytes.get(from..).and_then(|rest| rest.windows(4).position(|w| w == COUNT_CHECK)) {
|
||||
let at = from + k;
|
||||
from = at + 1;
|
||||
let Some(hash) = error_target(bytes, at).and_then(|t| bytes.get(t..)).and_then(error_hash) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(rva) = u32::try_from(start + at) else { continue };
|
||||
match function_start(functions, rva).filter(|&begin| rva - begin <= MOST_BEFORE) {
|
||||
Some(begin) => found.push((hash, begin)),
|
||||
None => unplaced += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
found.sort_unstable();
|
||||
found.dedup();
|
||||
let mut natives = Natives { unplaced, ..Natives::default() };
|
||||
for group in found.chunk_by(|a, b| a.0 == b.0) {
|
||||
match group {
|
||||
[one] => natives.list.push(*one),
|
||||
_ => natives.repeated += 1,
|
||||
}
|
||||
}
|
||||
natives
|
||||
}
|
||||
|
||||
/// The natives of the image mapped at `base`, from its code and its `.pdata` section. Reads the image and
|
||||
/// changes nothing.
|
||||
///
|
||||
/// # Safety
|
||||
/// `base` is the mapped image `info` describes, and nothing writes its code meanwhile.
|
||||
pub unsafe fn find(base: usize, info: &leonida_pe::ImageInfo) -> Natives {
|
||||
let fits = |s: &&leonida_pe::SectionInfo| u64::from(s.rva) + u64::from(s.virtual_size) <= u64::from(info.size_of_image);
|
||||
// SAFETY: sections of the mapped image, readable, which nothing writes now.
|
||||
let bytes = |s: &leonida_pe::SectionInfo| unsafe {
|
||||
std::slice::from_raw_parts((base + s.rva as usize) as *const u8, s.virtual_size as usize)
|
||||
};
|
||||
let code: Vec<(usize, &[u8])> = info
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|s| s.characteristics & crate::vipatch::SCN_MEM_EXECUTE != 0)
|
||||
.filter(fits)
|
||||
.map(|s| (s.rva as usize, bytes(s)))
|
||||
.collect();
|
||||
let functions = info.sections.iter().filter(fits).find(|s| s.name == ".pdata").map(|s| functions_of(bytes(s)));
|
||||
scan(&code, &functions.unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A handler as the title's are: a prologue, the count check, `mov rsi, rcx`, the `js` (near or far) to its
|
||||
/// error block right after a `ret`, which stores `hash`.
|
||||
fn handler(hash: u64, far: bool) -> Vec<u8> {
|
||||
let mut code = vec![0x56, 0x57, 0x48, 0x83, 0xEC, 0x28];
|
||||
code.extend(COUNT_CHECK);
|
||||
code.extend([0x48, 0x89, 0xCE]);
|
||||
// The error block lies after the jump and one `ret`.
|
||||
if far {
|
||||
code.extend([0x0F, 0x88]);
|
||||
code.extend(1i32.to_le_bytes());
|
||||
} else {
|
||||
code.extend([0x78, 0x01]);
|
||||
}
|
||||
code.push(0xC3);
|
||||
code.extend([0x48, 0x8B, 0x06, 0x48, 0xB9]);
|
||||
code.extend(hash.to_le_bytes());
|
||||
code.extend([0x48, 0x89, 0x08, 0xC3]);
|
||||
code
|
||||
}
|
||||
|
||||
/// `handlers` laid one after another at 64-byte steps from offset 0x1000, and the unwind table naming each.
|
||||
fn image(handlers: &[Vec<u8>]) -> (Vec<u8>, Vec<(u32, u32)>) {
|
||||
let mut code = Vec::new();
|
||||
let mut functions = Vec::new();
|
||||
for h in handlers {
|
||||
let begin = 0x1000 + code.len() as u32;
|
||||
functions.push((begin, begin + h.len() as u32));
|
||||
code.extend(h);
|
||||
code.resize(code.len().next_multiple_of(64), 0xCC);
|
||||
}
|
||||
(code, functions)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_native_is_named_by_the_hash_its_error_block_stores() {
|
||||
let (code, functions) = image(&[handler(0x1111, false), handler(0x2222, true), handler(0x3333, false)]);
|
||||
let natives = scan(&[(0x1000, &code)], &functions);
|
||||
assert_eq!(natives.len(), 3);
|
||||
assert_eq!(natives.find(0x1111), Some(0x1000));
|
||||
assert_eq!(natives.find(0x2222), Some(0x1040));
|
||||
assert_eq!(natives.find(0x3333), Some(0x1080));
|
||||
assert_eq!(natives.find(0x4444), None);
|
||||
assert_eq!((natives.repeated, natives.unplaced), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hash_at_two_handlers_and_a_handler_outside_the_unwind_table_name_nothing() {
|
||||
let (code, mut functions) = image(&[handler(0x1111, false), handler(0x1111, false), handler(0x3333, false)]);
|
||||
functions.pop();
|
||||
let natives = scan(&[(0x1000, &code)], &functions);
|
||||
assert!(natives.is_empty());
|
||||
assert_eq!((natives.repeated, natives.unplaced), (1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_error_block_s_own_shape_counts() {
|
||||
// The store from another register than the hash was put in; a load through rsp; the check too deep
|
||||
// into its function.
|
||||
let mut other = handler(0x1111, false);
|
||||
let at = other.len() - 4;
|
||||
other[at + 2] = 0x10;
|
||||
let mut rsp = handler(0x2222, false);
|
||||
let load = rsp.iter().rposition(|&b| b == 0x8B).unwrap();
|
||||
rsp[load + 1] = 0x04;
|
||||
let mut deep = vec![0x90; MOST_BEFORE as usize + 1];
|
||||
deep.extend(handler(0x3333, false));
|
||||
let (code, functions) = image(&[other, rsp, deep]);
|
||||
let natives = scan(&[(0x1000, &code)], &functions);
|
||||
assert!(natives.is_empty(), "{natives:?}");
|
||||
assert_eq!(natives.unplaced, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unwind_table_reads_as_sorted_functions() {
|
||||
let mut pdata = Vec::new();
|
||||
for (begin, end) in [(0x3000u32, 0x3010u32), (0x1000, 0x1040), (0x2000, 0x2000)] {
|
||||
pdata.extend(begin.to_le_bytes());
|
||||
pdata.extend(end.to_le_bytes());
|
||||
pdata.extend(0u32.to_le_bytes());
|
||||
}
|
||||
assert_eq!(functions_of(&pdata), [(0x1000, 0x1040), (0x3000, 0x3010)]);
|
||||
assert_eq!(function_start(&functions_of(&pdata), 0x103F), Some(0x1000));
|
||||
assert_eq!(function_start(&functions_of(&pdata), 0x1040), None);
|
||||
}
|
||||
|
||||
/// With `LEONIDA_GAME_DIR` set to the folder of the Xbox package: the natives of `game_scarlett_master.exe`,
|
||||
/// thousands, among them the two the trainer's god mode calls.
|
||||
#[test]
|
||||
fn the_retail_executable_s_natives_are_found() {
|
||||
let Some(dir) = std::env::var_os("LEONIDA_GAME_DIR") else {
|
||||
eprintln!("SKIP: LEONIDA_GAME_DIR is not set");
|
||||
return;
|
||||
};
|
||||
let path = std::path::Path::new(&dir).join("game_scarlett_master.exe");
|
||||
let Ok(data) = std::fs::read(&path) else {
|
||||
eprintln!("SKIP: {} is not there", path.display());
|
||||
return;
|
||||
};
|
||||
let info = leonida_pe::ImageInfo::parse(&data).expect("a PE image");
|
||||
let bytes = |s: &leonida_pe::SectionInfo| {
|
||||
let len = s.file_size.min(s.virtual_size) as usize;
|
||||
&data[s.file_offset as usize..s.file_offset as usize + len]
|
||||
};
|
||||
let code: Vec<(usize, &[u8])> = info
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|s| s.characteristics & crate::vipatch::SCN_MEM_EXECUTE != 0)
|
||||
.map(|s| (s.rva as usize, bytes(s)))
|
||||
.collect();
|
||||
let pdata = info.sections.iter().find(|s| s.name == ".pdata").map(bytes).expect("an unwind table");
|
||||
let natives = scan(&code, &functions_of(pdata));
|
||||
assert!(natives.len() > 6000, "{} natives", natives.len());
|
||||
// PLAYER_PED_ID and SET_ENTITY_INVINCIBLE (modpapi/scripthook-vi's native database).
|
||||
for hash in [0x6471_F11F_F69D_8A77, 0x3BD9_0347_5A3C_78C9] {
|
||||
assert!(natives.find(hash).is_some(), "{hash:#x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -216,16 +216,31 @@ the title's. A panic in our own work stops the work and not the title.
|
||||
(what the runtime sees: threads, whether the work ran at once or at the queue's point of rest, the ped, its
|
||||
position and forward vector, wanted level, clock, the weather types, the cheat table), `cheat <n>`, `wanted <n>`,
|
||||
`time <h> [m [s]]`, `hours <n>`, `pause <0|1>`, `weather <index|NAME|freeze|free>`, `nudge <dx> <dy> <dz>
|
||||
[frames]`. Everything asked and done is written to `%TEMP%\leonida-actions\log.txt` (addresses of the run: not
|
||||
for the repository).
|
||||
[frames]`, `spawn <model name|0x key>` (a vehicle of any model, by the spawn the vehicle cheats call), `god <0|1>`
|
||||
and `native <0x hash> [slots]` (below). Everything asked and done is written to `%TEMP%\leonida-actions\log.txt`
|
||||
(addresses of the run: not for the repository).
|
||||
|
||||
### Any vehicle, and the natives by their handlers (2026-11-30)
|
||||
|
||||
The nine vehicle cheats are each `mov rcx, <model key>` and a call of one function: `spawn` calls that function
|
||||
(taken from the cheats' own code through the table) with another model's key, the low 64 bits of
|
||||
MurmurHash3_x64_128 (seed 0) of the lower-cased model name (one cheat's key is that hash of its model's name).
|
||||
|
||||
The script natives turned out to be findable after all, by their handlers' shape rather than any table: each
|
||||
handler checks its argument count first and, on a negative one, stores its native's own 64-bit hash where the
|
||||
result goes. `leonida_loader::natives` reads that hash from every handler (6,000 and more in 1.0.2.1, the start of
|
||||
each from the unwind table), so a native is called by its hash: `god` is SET_ENTITY_INVINCIBLE on PLAYER_PED_ID's
|
||||
reference, both by the hashes of modpapi/scripthook-vi's native database (CC BY 4.0). The shape, the call context
|
||||
and the model key's form are kylepelham/El1xr's findings (GPL-3.0). Unit-tested and checked against the executable;
|
||||
not yet seen in the running title.
|
||||
|
||||
## What is not there yet, and why
|
||||
|
||||
God mode, stamina, fast run and swim, super jump, invisibility, ragdoll, the vehicle items other than the nine
|
||||
spawns, every weapon item, moon gravity, traffic, pedestrians, police, blackout, strong wind, moving the player
|
||||
(teleports), HUD and radio. These items go through `GameActions` (`actions.rs`); for them the backend answers
|
||||
with the reason, and the menu shows them dimmed with that reason in the help box. The title's functions for them
|
||||
were not looked for one by one: the cheat table has none of them, and the script commands (below) have no names.
|
||||
Stamina, fast run and swim, super jump, invisibility, ragdoll, every weapon item, moon gravity, traffic,
|
||||
pedestrians, police, blackout, strong wind, moving the player (teleports), HUD and radio, and the menu's own items
|
||||
for god mode and any vehicle (the run script has them). These items go through `GameActions` (`actions.rs`); for
|
||||
them the backend answers with the reason, and the menu shows them dimmed with that reason in the help box. Most of
|
||||
them are natives now within reach (above); each needs its hash and its arguments checked.
|
||||
|
||||
Moving the player: the ped and its position are known now (above), but the title's function that moves a ped was
|
||||
not found. Looked for among the script commands (below) by their arguments: 46 commands take a 16-byte handle,
|
||||
|
||||
Reference in New Issue
Block a user