feat(script): resolve default init writes
This commit is contained in:
@@ -143,6 +143,77 @@ pub struct Handler8StateChange {
|
||||
pub reset: Handler8Reset,
|
||||
}
|
||||
|
||||
/// One raw DWORD write made by the corpus-proven `Handler(19)` Init path.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Handler19DwordWrite {
|
||||
/// Compiled varset record index selected by the instruction reference.
|
||||
pub index: u32,
|
||||
/// Exact 32-bit payload passed to the original common varset setter.
|
||||
pub value: u32,
|
||||
}
|
||||
|
||||
/// Inputs already expressed at the original `Handler(19)` setter ABI boundary.
|
||||
///
|
||||
/// The first two words are results of original x87 `__ftol` calls. Keeping
|
||||
/// them as words prevents this package from silently substituting Rust's float
|
||||
/// conversion policy before captured x87 vectors are available.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Handler19InitInput {
|
||||
/// x87-converted value from VM field `+0x80`.
|
||||
pub first_x87_word: u32,
|
||||
/// x87-converted value from VM field `+0x84`.
|
||||
pub second_x87_word: u32,
|
||||
/// Raw word from VM field `+0x7c`.
|
||||
pub third_word: u32,
|
||||
}
|
||||
|
||||
/// Error resolving the three-target `Handler(19)` Init contract.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum Handler19ResolveError {
|
||||
/// One of the three required references was absent.
|
||||
MissingReference {
|
||||
/// Zero-based required target position.
|
||||
position: usize,
|
||||
},
|
||||
/// A compiled reference indexed outside the loaded varset.
|
||||
VarSetIndexOutOfBounds {
|
||||
/// Referenced compiled-varset index.
|
||||
index: u32,
|
||||
/// Available declaration count.
|
||||
declarations: usize,
|
||||
},
|
||||
/// The `AutoDemo` Init target was not a `DWORD` declaration.
|
||||
UnexpectedType {
|
||||
/// Zero-based target position.
|
||||
position: usize,
|
||||
/// Observed declaration type.
|
||||
found: VarSetType,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Handler19ResolveError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::MissingReference { position } => {
|
||||
write!(formatter, "Handler(19) is missing reference {position}")
|
||||
}
|
||||
Self::VarSetIndexOutOfBounds {
|
||||
index,
|
||||
declarations,
|
||||
} => write!(
|
||||
formatter,
|
||||
"Handler(19) reference {index} is outside {declarations} varset declarations"
|
||||
),
|
||||
Self::UnexpectedType { position, found } => write!(
|
||||
formatter,
|
||||
"Handler(19) reference {position} has {found:?}, expected Dword"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Handler19ResolveError {}
|
||||
|
||||
/// Error resolving the one-operand `Handler(8)` contract.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum Handler8ResolveError {
|
||||
@@ -391,6 +462,68 @@ impl VarSet {
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves the three DWORD targets written by GOG `Handler(19)`.
|
||||
///
|
||||
/// The caller supplies values at the original setter ABI boundary: the
|
||||
/// first two are already x87-converted `__ftol` results and the third is
|
||||
/// the raw VM word. This preserves the exact default-script Init path
|
||||
/// without claiming an unrecovered portable x87 policy.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns a typed failure for missing/out-of-range targets or a target
|
||||
/// type that differs from the observed `AutoDemo` `DWORD` contract.
|
||||
pub fn resolve_handler19(
|
||||
&self,
|
||||
instruction: &ScriptInstruction,
|
||||
input: Handler19InitInput,
|
||||
) -> Result<[Handler19DwordWrite; 3], Handler19ResolveError> {
|
||||
let targets = [
|
||||
self.resolve_handler19_target(instruction, 0)?,
|
||||
self.resolve_handler19_target(instruction, 1)?,
|
||||
self.resolve_handler19_target(instruction, 2)?,
|
||||
];
|
||||
Ok([
|
||||
Handler19DwordWrite {
|
||||
index: targets[0],
|
||||
value: input.first_x87_word,
|
||||
},
|
||||
Handler19DwordWrite {
|
||||
index: targets[1],
|
||||
value: input.second_x87_word,
|
||||
},
|
||||
Handler19DwordWrite {
|
||||
index: targets[2],
|
||||
value: input.third_word,
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
fn resolve_handler19_target(
|
||||
&self,
|
||||
instruction: &ScriptInstruction,
|
||||
position: usize,
|
||||
) -> Result<u32, Handler19ResolveError> {
|
||||
let index = *instruction
|
||||
.references
|
||||
.get(position)
|
||||
.ok_or(Handler19ResolveError::MissingReference { position })?;
|
||||
match self.declarations.get(index as usize) {
|
||||
Some(VarSetDeclaration {
|
||||
type_name: VarSetType::Dword,
|
||||
..
|
||||
}) => Ok(index),
|
||||
Some(declaration) => Err(Handler19ResolveError::UnexpectedType {
|
||||
position,
|
||||
found: declaration.type_name,
|
||||
}),
|
||||
None => Err(Handler19ResolveError::VarSetIndexOutOfBounds {
|
||||
index,
|
||||
declarations: self.declarations.len(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the fixed-width, corpus-proven operands of GOG `Handler(15)`.
|
||||
///
|
||||
/// Static analysis of `ai.dll` at `0x10008054` shows four DWORD slots,
|
||||
@@ -1033,9 +1166,10 @@ fn read_instruction(
|
||||
mod tests {
|
||||
use super::{
|
||||
decode, decode_with_limits, parse_varset, Handler15ResolveError, Handler15TargetPayload,
|
||||
Handler2RecordInput, Handler2RecordScheduler, Handler30ResolveError, Handler8Reset,
|
||||
Handler8ResolveError, ScriptDispatchSelector, ScriptInstruction, VarSetDefault,
|
||||
VarSetError, VarSetType, VmHostCallbackCommand, GOG_HANDLER_COUNT, INSTRUCTION_WORDS,
|
||||
Handler19DwordWrite, Handler19InitInput, Handler19ResolveError, Handler2RecordInput,
|
||||
Handler2RecordScheduler, Handler30ResolveError, Handler8Reset, Handler8ResolveError,
|
||||
ScriptDispatchSelector, ScriptInstruction, VarSetDefault, VarSetError, VarSetType,
|
||||
VmHostCallbackCommand, GOG_HANDLER_COUNT, INSTRUCTION_WORDS,
|
||||
};
|
||||
use fparkan_binary::{DecodeError, Limits};
|
||||
|
||||
@@ -1289,6 +1423,79 @@ STRING( 8, ignored, ignored, ignored)\r\n";
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_nineteen_writes_exact_default_init_dwords_without_float_coercion() {
|
||||
let varset = parse_varset(
|
||||
b"VAR( DWORD, ClanBaseX, 950)\nVAR( DWORD, ClanBaseY, 1000)\nVAR( DWORD, ClanID, 0)\n",
|
||||
)
|
||||
.expect("default Init targets");
|
||||
let writes = varset
|
||||
.resolve_handler19(
|
||||
&ScriptInstruction {
|
||||
header_words: [19, 0, 0, 0, 0, 3, 0],
|
||||
references: vec![0, 1, 2],
|
||||
},
|
||||
Handler19InitInput {
|
||||
first_x87_word: 500,
|
||||
second_x87_word: 752,
|
||||
third_word: 0,
|
||||
},
|
||||
)
|
||||
.expect("resolved Init writes");
|
||||
assert_eq!(
|
||||
writes,
|
||||
[
|
||||
Handler19DwordWrite {
|
||||
index: 0,
|
||||
value: 500
|
||||
},
|
||||
Handler19DwordWrite {
|
||||
index: 1,
|
||||
value: 752
|
||||
},
|
||||
Handler19DwordWrite { index: 2, value: 0 },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_nineteen_keeps_target_errors_explicit() {
|
||||
let float = parse_varset(b"VAR( float, f0, 1.0)\n").expect("float target");
|
||||
let instruction = ScriptInstruction {
|
||||
header_words: [19, 0, 0, 0, 0, 1, 0],
|
||||
references: vec![0],
|
||||
};
|
||||
assert_eq!(
|
||||
float.resolve_handler19(
|
||||
&instruction,
|
||||
Handler19InitInput {
|
||||
first_x87_word: 0,
|
||||
second_x87_word: 0,
|
||||
third_word: 0,
|
||||
},
|
||||
),
|
||||
Err(Handler19ResolveError::UnexpectedType {
|
||||
position: 0,
|
||||
found: VarSetType::Float,
|
||||
})
|
||||
);
|
||||
let empty = parse_varset(b"").expect("empty varset");
|
||||
assert_eq!(
|
||||
empty.resolve_handler19(
|
||||
&ScriptInstruction {
|
||||
header_words: [19, 0, 0, 0, 0, 0, 0],
|
||||
references: Vec::new(),
|
||||
},
|
||||
Handler19InitInput {
|
||||
first_x87_word: 0,
|
||||
second_x87_word: 0,
|
||||
third_word: 0,
|
||||
},
|
||||
),
|
||||
Err(Handler19ResolveError::MissingReference { position: 0 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_fifteen_resolves_exact_typed_target_by_place_operands() {
|
||||
let varset = parse_varset(
|
||||
|
||||
@@ -173,6 +173,38 @@ layout prerequisites/modifiers/unlocks. Formula evaluator требует strict
|
||||
grammar/version, typed operands, deterministic numeric policy, bounded stack и
|
||||
явных errors; x87-compatible rounding нужен там, где оно выбирает ветку.
|
||||
|
||||
### Handler(19): AutoDemo Init varset initialization
|
||||
|
||||
`Handler(19)` is the twentieth VM-table entry at GOG `ai.dll` VA `0x1000aa38`.
|
||||
It is the only instruction in the `Init` event of the two `default.scr` bundles
|
||||
referenced by `MISSIONS\\Autodemo.00\\data.tma`; together those bundles account for
|
||||
the observed 18 named script events. Each instruction references varset records
|
||||
`224`, `225`, and `226`: `ClanBaseX`, `ClanBaseY`, and `ClanID` respectively.
|
||||
|
||||
The original writes three raw DWORD values in order. It converts the VM fields
|
||||
at `+0x80` and `+0x84` through the x87 `__ftol` helper and stores the resulting
|
||||
words into references 0 and 1. It copies the raw word from `+0x7c` into reference
|
||||
2, then clears VM field `+0x50`. The default targets are `DWORD` records; the
|
||||
shared setter preserves the incoming word for that type. Therefore this is not
|
||||
a license to replace the first two conversions with Rust float casts: their
|
||||
rounding behavior remains an x87 compatibility boundary until it has captured
|
||||
test vectors.
|
||||
|
||||
`GetSuperAI` returns element `n` of the 64-pointer global table at preferred
|
||||
`ai.dll + 0x55398` for `n <= 63`. The read-only
|
||||
`tools/capture-ai-init.ps1` probe observed the running GOG AutoDemo values
|
||||
`(500, 752, 0)` for entry 0 and `(728, 449, 1)` for entry 1 at fields
|
||||
`(+0x80, +0x84, +0x7c)`. These values are integral samples, not a rounding
|
||||
profile.
|
||||
|
||||
The Rust reader exposes `VarSet::resolve_handler19`. It accepts the already
|
||||
converted first two words and the third raw word, produces three typed writes,
|
||||
and rejects missing, out-of-range, or non-`DWORD` targets. It deliberately does
|
||||
not guess how the mission creates the three source fields or execute a script
|
||||
event yet. The associated Ghidra scripts are
|
||||
`ExportAiVmHandler19.java`, `ExportAiVmHandler19Setter.java`,
|
||||
`ExportAiVmHandler19SetterCallee.java`, and `ExportAiGetSuperAi.java`.
|
||||
|
||||
### Handler(8): problem-record state write
|
||||
|
||||
`Handler(8)` is the ninth VM-table entry at GOG `ai.dll` VA `0x10009b0d`.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory = $true)][int]$ProcessId)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Read-only observer for ai.dll's `GetSuperAI` singleton array. It never sends
|
||||
# input, writes memory, suspends, injects, or calls into the original process.
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FparkanAiInitCapture {
|
||||
public const uint TH32CS_SNAPMODULE = 0x00000008;
|
||||
public const uint TH32CS_SNAPMODULE32 = 0x00000010;
|
||||
public const uint PROCESS_QUERY_INFORMATION = 0x00000400;
|
||||
public const uint PROCESS_VM_READ = 0x00000010;
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
public struct MODULEENTRY32 {
|
||||
public uint dwSize, th32ModuleID, th32ProcessID, GlblcntUsage, ProccntUsage;
|
||||
public IntPtr modBaseAddr;
|
||||
public uint modBaseSize;
|
||||
public IntPtr hModule;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string szModule;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExePath;
|
||||
}
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool Module32First(IntPtr snapshot, ref MODULEENTRY32 entry);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool Module32Next(IntPtr snapshot, ref MODULEENTRY32 entry);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern IntPtr OpenProcess(uint access, bool inheritHandle, uint processId);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern bool ReadProcessMemory(IntPtr process, IntPtr address,
|
||||
[Out] byte[] buffer, IntPtr size, out IntPtr bytesRead);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern bool CloseHandle(IntPtr handle);
|
||||
}
|
||||
'@
|
||||
|
||||
function Read-Bytes([IntPtr]$Process, [Int64]$Address, [int]$Length) {
|
||||
$bytes = [byte[]]::new($Length); $read = [IntPtr]::Zero
|
||||
if (-not [FparkanAiInitCapture]::ReadProcessMemory($Process, [IntPtr]$Address,
|
||||
$bytes, [IntPtr]$Length, [ref]$read) -or $read.ToInt64() -ne $Length) {
|
||||
throw "ReadProcessMemory failed at 0x$('{0:X8}' -f $Address)"
|
||||
}
|
||||
$bytes
|
||||
}
|
||||
|
||||
$snapshot = [FparkanAiInitCapture]::CreateToolhelp32Snapshot(
|
||||
[FparkanAiInitCapture]::TH32CS_SNAPMODULE -bor [FparkanAiInitCapture]::TH32CS_SNAPMODULE32,
|
||||
[uint32]$ProcessId)
|
||||
$aiBase = $null
|
||||
try {
|
||||
$entry = [FparkanAiInitCapture+MODULEENTRY32]::new()
|
||||
$entry.dwSize = [Runtime.InteropServices.Marshal]::SizeOf([type][FparkanAiInitCapture+MODULEENTRY32])
|
||||
if ([FparkanAiInitCapture]::Module32First($snapshot, [ref]$entry)) {
|
||||
do {
|
||||
if ($entry.szModule -ieq 'ai.dll') { $aiBase = $entry.modBaseAddr.ToInt64(); break }
|
||||
$entry = [FparkanAiInitCapture+MODULEENTRY32]::new()
|
||||
$entry.dwSize = [Runtime.InteropServices.Marshal]::SizeOf([type][FparkanAiInitCapture+MODULEENTRY32])
|
||||
} while ([FparkanAiInitCapture]::Module32Next($snapshot, [ref]$entry))
|
||||
}
|
||||
} finally { [void][FparkanAiInitCapture]::CloseHandle($snapshot) }
|
||||
if ($null -eq $aiBase) { throw "ai.dll is not loaded by process $ProcessId" }
|
||||
|
||||
$process = [FparkanAiInitCapture]::OpenProcess(
|
||||
[FparkanAiInitCapture]::PROCESS_QUERY_INFORMATION -bor [FparkanAiInitCapture]::PROCESS_VM_READ,
|
||||
$false, [uint32]$ProcessId)
|
||||
if ($process -eq [IntPtr]::Zero) { throw "OpenProcess read-only failed" }
|
||||
try {
|
||||
# GetSuperAI(i) returns (&DAT_10055398)[i], with ai.dll preferred base 0x10000000.
|
||||
$entries = Read-Bytes $process ($aiBase + 0x55398) (64 * 4)
|
||||
$samples = for ($index = 0; $index -lt 64; $index++) {
|
||||
$pointer = [BitConverter]::ToUInt32($entries, $index * 4)
|
||||
if ($pointer -le 0x10000) { continue }
|
||||
try {
|
||||
$fields = Read-Bytes $process ([int64]$pointer) 0x88
|
||||
[ordered]@{
|
||||
index = $index
|
||||
super_ai = ('0x{0:X8}' -f $pointer)
|
||||
word_7c = [BitConverter]::ToUInt32($fields, 0x7c)
|
||||
float_80 = [BitConverter]::ToSingle($fields, 0x80)
|
||||
float_84 = [BitConverter]::ToSingle($fields, 0x84)
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
[ordered]@{ schema = 'fparkan-ai-init-v1'; process_id = $ProcessId; ai_module_base = ('0x{0:X8}' -f $aiBase); entries = @($samples) } |
|
||||
ConvertTo-Json -Depth 4 -Compress
|
||||
} finally { [void][FparkanAiInitCapture]::CloseHandle($process) }
|
||||
@@ -0,0 +1,23 @@
|
||||
// Emits the GOG ai.dll GetSuperAI export to recover the live singleton
|
||||
// boundary for read-only handler-input capture.
|
||||
import ghidra.app.decompiler.DecompInterface;
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.Address;
|
||||
import ghidra.program.model.listing.Function;
|
||||
|
||||
public class ExportAiGetSuperAi extends GhidraScript {
|
||||
private static final long ADDRESS = 0x1000f780L;
|
||||
|
||||
@Override
|
||||
public void run() throws Exception {
|
||||
Address address = currentProgram.getAddressFactory().getDefaultAddressSpace()
|
||||
.getAddress(ADDRESS);
|
||||
Function function = currentProgram.getFunctionManager().getFunctionAt(address);
|
||||
println("===== AI GetSuperAI =====");
|
||||
if (function == null) { println("missing"); return; }
|
||||
DecompInterface decompiler = new DecompInterface();
|
||||
decompiler.openProgram(currentProgram);
|
||||
println(decompiler.decompileFunction(function, 60, monitor).getDecompiledFunction().getC());
|
||||
decompiler.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Emits Handler(19), the first instruction in both AutoDemo default-script
|
||||
// Init events. Run headless; the original PE remains read only.
|
||||
import ghidra.app.decompiler.DecompInterface;
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.Address;
|
||||
import ghidra.program.model.listing.Function;
|
||||
|
||||
public class ExportAiVmHandler19 extends GhidraScript {
|
||||
private static final long ADDRESS = 0x1000aa38L;
|
||||
|
||||
@Override
|
||||
public void run() throws Exception {
|
||||
Address address = currentProgram.getAddressFactory().getDefaultAddressSpace()
|
||||
.getAddress(ADDRESS);
|
||||
Function function = currentProgram.getFunctionManager().getFunctionAt(address);
|
||||
println("===== AI VM Handler(19) =====");
|
||||
if (function == null) { println("missing"); return; }
|
||||
DecompInterface decompiler = new DecompInterface();
|
||||
decompiler.openProgram(currentProgram);
|
||||
println(decompiler.decompileFunction(function, 60, monitor).getDecompiledFunction().getC());
|
||||
decompiler.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Emits Handler(19)'s common x87 varset setter. Run headless; the original PE
|
||||
// remains read only.
|
||||
import ghidra.app.decompiler.DecompInterface;
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.Address;
|
||||
import ghidra.program.model.listing.Function;
|
||||
|
||||
public class ExportAiVmHandler19Setter extends GhidraScript {
|
||||
private static final long ADDRESS = 0x10013770L;
|
||||
|
||||
@Override
|
||||
public void run() throws Exception {
|
||||
Address address = currentProgram.getAddressFactory().getDefaultAddressSpace()
|
||||
.getAddress(ADDRESS);
|
||||
Function function = currentProgram.getFunctionManager().getFunctionAt(address);
|
||||
println("===== AI VM Handler(19) setter =====");
|
||||
if (function == null) { println("missing"); return; }
|
||||
DecompInterface decompiler = new DecompInterface();
|
||||
decompiler.openProgram(currentProgram);
|
||||
println(decompiler.decompileFunction(function, 60, monitor).getDecompiledFunction().getC());
|
||||
decompiler.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Emits the common varset storage helper reached by Handler(19)'s setter.
|
||||
// Run headless; the original PE remains read only.
|
||||
import ghidra.app.decompiler.DecompInterface;
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.Address;
|
||||
import ghidra.program.model.listing.Function;
|
||||
|
||||
public class ExportAiVmHandler19SetterCallee extends GhidraScript {
|
||||
private static final long ADDRESS = 0x10012fe0L;
|
||||
|
||||
@Override
|
||||
public void run() throws Exception {
|
||||
Address address = currentProgram.getAddressFactory().getDefaultAddressSpace()
|
||||
.getAddress(ADDRESS);
|
||||
Function function = currentProgram.getFunctionManager().getFunctionAt(address);
|
||||
println("===== AI VM Handler(19) setter storage helper =====");
|
||||
if (function == null) { println("missing"); return; }
|
||||
DecompInterface decompiler = new DecompInterface();
|
||||
decompiler.openProgram(currentProgram);
|
||||
println(decompiler.decompileFunction(function, 60, monitor).getDecompiledFunction().getC());
|
||||
decompiler.dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user