Files

312 lines
19 KiB
Python

#!/usr/bin/env python3
"""Read-only Rocketship contracts and isolated input/vertical probe generators.
The input probe executes copied41A6C0 only through41AC0E, with synthetic
mouse/support/transform/audio dependencies. The vertical probe executes only
41A470..41A6A8 with synthetic body accessors. Neither runs the original game.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
from pathlib import Path
import re
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
BODIES = (
('ctor', 0x43d840, 0x43da40, '33d27053c2070f0c278bf3e14808d16c4479893d1ccb16c1ac8e199dfd9e53ba'),
('init', 0x43dd10, 0x43dd92, 'cd6e843749b7c87db7df223fd98f5f16c5b01b7097c0b0d4a661dd28eb1bd494'),
('flying_ctor', 0x419b70, 0x419db0, '85c0e74764282ed55e2c7268a0dec5944097b16f1a9df71054e5458b446ee2c0'),
('flight_apply', 0x41a140, 0x41a6b1, '20fc706986e58791dc19334a01a772dd517cbd260079382dac2f009fc8707bb7'),
('flight_input', 0x41a6c0, 0x41ade1, '4c68ae3cf48aecf266ef0a9e8ec81646bd4b774251aac4e38563765a51db2625'),
('rocket_input', 0x43e7e0, 0x43e854, 'db973aebd9dad23de493d79606b3016e3e04c7ba029452ee07a6fd6e9abfd5b9'),
('mount', 0x42944d, 0x429686, '2e8e15c52bf02a06afe2a56ccf8b31551368aefcde046c444ddb01a3ef978c70'),
('cleanup', 0x428512, 0x42871d, 'e35f82a6b4e791e77278cdf84bc3878237d57c54355254cfbeff3923d2c70ee6'),
('vr02_ctor', 0x456270, 0x456360, '058e77e27d8dbb2de5306c0582ccc1c7caf81cf29ae64caa43d3d1cd174b63c8'),
('fire_ctor', 0x4192e0, 0x41944c, 'e66ca12f68c3fc87bd855d0865871d387627684e31429460b84139f28e77afdb'),
)
VTABLES = ((0x4b25ac, 0x110, 0x471240), (0x4b25ac, 0x264, 0x471b40),
(0x4b25ac, 0x3c4, 0x43df70), (0x4b25ac, 0x3cc, 0x43e7e0),
(0x4b2a4c, 0x128, 0x43ea80), (0x4cdd30, 0x134, 0x475cd0))
CONSTANTS = ((0x49d5b0, -60.), (0x49d5b4, 60.), (0x49d5b8, 0.0181818176060915),
(0x49d5d4, 0.10000000149011612), (0x49d5dc, 0.9090909361839294),
(0x49d5e4, 160.), (0x49b1fc, 130.), (0x48e5bc, 500.))
PROBE_GLOBALS = (0x509a50, 0x50985d, 0x50985f, 0x509aa0, 0x509aa4,
0x48d914, 0x48d948, 0x48d94c, 0x49b1fc, 0x49d5e4,
0x509882, 0x509881, 0x509885, 0x509891, 0x509848,
0x50985e, 0x509834, 0x49d5e0, 0x49d5dc, 0x48e5bc,
0x509860, 0x50993a, 0x49d5d8, 0x49d5d4, 0x48e5ec,
0x495324, 0x49d5d0, 0x49d5cc, 0x49d5c8)
VERTICAL_GLOBALS = (0x48d96c, 0x48d914, 0x49d5b4, 0x49d5b0, 0x5cfc04)
def collect(original: Path | str):
pe = PE(find_case(Path(original), 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unexpected original EXE identity')
bodies = []
for name, start, end, expected in BODIES:
digest = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if digest != expected:
raise ValueError(f'Changed source span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=digest))
for table, slot, target in VTABLES:
if struct.unpack('<I', read_va(pe, table+slot, 4))[0] != target:
raise ValueError(f'Changed virtual {table:x}+{slot:x}')
for va, value in CONSTANTS:
if struct.unpack('<f', read_va(pe, va, 4))[0] != value:
raise ValueError(f'Changed constant {va:x}')
def operands(start, end, targets):
result = []
code = read_va(pe, start, end-start)
for target in targets:
encoded = struct.pack('<I', target)
for i in range(len(code)-3):
if code[i:i+4] == encoded:
result.append(dict(va=start+i, target=target))
return sorted(result, key=lambda r:r['va'])
return dict(sha256=EXE_SHA256, bodies=bodies,
probe_operands=operands(0x41a6c0, 0x41ac0e, PROBE_GLOBALS),
vertical_operands=operands(0x41a470, 0x41a6a8, VERTICAL_GLOBALS),
vtables=[dict(table=hex(t), slot=hex(s), target=hex(v)) for t,s,v in VTABLES],
constants=[dict(va=hex(a), value=v) for a,v in CONSTANTS],
item=1, raw_mode=1, owned_pointer='complete Jimmy+AB0',
rider_pointer='complete rocket+740 = game interface+680', radius=50.,
factor=0.6000000238418579, friction=0.800000011920929,
scope='Static recovery and isolated input/vertical probes; no live vehicle fidelity claim')
def probe_source(report, *, vertical=False):
operands = report['probe_operands'] + (report['vertical_operands'] if vertical else [])
relocations = ',\n'.join(f'{{0x{r["va"]:x},0x{r["target"]:x}}}' for r in operands)
return (VERTICAL_PROBE if vertical else PROBE).replace('/* RELOCATIONS */', relocations)
def probe_results(report, log: Path, executable: Path, *, vertical=False):
"""Pair observed copied-source outputs with the generator's literal cases."""
content = log.read_text()
marker = 'ROCKET_VERTICAL_COMPONENT_COMPLETE:' if vertical else 'ROCKET_INPUT_COMPONENT_COMPLETE:'
if marker not in content:
raise ValueError('Incomplete original input probe')
names = ('speed', 'height', 'velocity', 'command', 'up', 'down', 'gravity') if vertical else (
'speed', 'bank', 'keyboard', 'up', 'down', 'left', 'right', 'supported', 'dt')
literal = VERTICAL_PROBE if vertical else PROBE
cases = []
for name, values in re.findall(r'run(?:_vertical)?\("(\w+)",([^;]+)\);', literal):
def number(value):
value = value.strip()
parsed = 1/60 if value == '1.f/60' else float(value.removesuffix('f'))
return struct.unpack('<f', struct.pack('<f', parsed))[0]
inputs = dict(zip(names, map(number, values.split(',')), strict=True))
for key in ('keyboard', 'up', 'down', 'left', 'right', 'supported'):
if key in inputs:
inputs[key] = bool(inputs[key])
lines = re.findall(rf'^CASE {re.escape(name)} (.+)$', content, re.MULTILINE)
if len(lines) != 1:
raise ValueError(f'Missing or repeated original case {name}')
output = {}
for entry in lines[0].split():
key, value = entry.split('=', 1)
output[key] = [float(v) for v in value.split(',')] if ',' in value else float(value)
expected = {'height', 'velocity', 'command', 'bodyacceleration', 'vx', 'vz', 'ax', 'az'} if vertical else {
'speed', 'bank', 'keyboard', 'up', 'down', 'dest'}
if set(output) != expected:
raise ValueError(f'Unexpected original output fields {name}')
if not all(math.isfinite(v) for value in output.values()
for v in (value if isinstance(value, list) else [value])):
raise ValueError('Nonfinite original output')
for key in ('keyboard', 'up', 'down'):
if key in output:
output[key] = bool(output[key])
cases.append(dict(name=name, input=inputs, observed=output))
if len(cases) != 14 or len(re.findall(r'^CASE ', content, re.MULTILINE)) != len(cases):
raise ValueError('Unexpected original input case inventory')
return dict(scope=('Copied41A470..41A6A8 vertical publication, synthetic body getters/setters, no integration' if vertical else
'Copied41A6C0 input prefix, synthetic mouse/support/Euler/audio, camera tail skipped'),
source_sha256=report['sha256'], generator_sha256=hashlib.sha256(probe_source(report, vertical=vertical).encode()).hexdigest(),
executable_sha256=hashlib.sha256(executable.read_bytes()).hexdigest(),
log_sha256=hashlib.sha256(log.read_bytes()).hexdigest(),
source_input_body_sha256=next(b['sha256'] for b in report['bodies'] if b['name'] == ('flight_apply' if vertical else 'flight_input')),
tuning=dict(acceleration=400., deceleration=1., maximum_speed=1400.,
acceleration_lean=20., deceleration_lean=-20., maximum_height=3900.,
up_rate=650., down_rate=-650., maximum_vertical_speed=650.), cases=cases)
PROBE = r'''/* Generated isolated copied41A6C0 input prefix. No game entrypoint/import init.
* Mouse, support, Euler and audio are synthetic; camera tail is not executed. */
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TC __attribute__((thiscall))
static unsigned char *mapped,object[0x1000],camera[0x100];
static uintptr_t table[0x400/4],outer[0x200/4];
static int grounded;
static short mouse_x,mouse_y;
static float euler[4],destination[3];
#define AT(va) (mapped+(va)-0x400000)
#define F(g,off) (*(float*)((g)+(off)))
static void require(int condition,const char*message){if(!condition){fprintf(stderr,"FAIL %s\n",message);exit(2);}}
static void __cdecl mouse(short*x,short*y){*x=mouse_x;*y=mouse_y;}
static int TC supported(void*self){(void)self;return grounded;}
static float* TC rotation(void*self,float*out){(void)self;memcpy(out,euler,sizeof(euler));return out;}
static void TC desired(void*self,float x,float y,float z){(void)self;destination[0]=x;destination[1]=y;destination[2]=z;}
static void TC sound(void*self,int mode){(void)self;(void)mode;}
static void TC missing(void*self){(void)self;require(0,"unexpected virtual");}
static const struct{uint32_t va,target;} relocations[]={
/* RELOCATIONS */
};
static void map_copy(void){
mapped=VirtualAlloc(NULL,0x299000,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
require(mapped!=NULL,"map copied source");
FILE*f=fopen("Neutron.exe","rb");require(f!=NULL,"copied EXE");
fseek(f,0,SEEK_END);long size=ftell(f);rewind(f);require(size==1019904,"bounded EXE size");
unsigned char*data=malloc(size);require(data!=NULL,"file buffer");
require(fread(data,1,size,f)==(size_t)size,"read source");fclose(f);
require(*(uint16_t*)data==IMAGE_DOS_SIGNATURE,"DOS header");
uint32_t offset=*(uint32_t*)(data+0x3c);require(offset<(uint32_t)size-sizeof(IMAGE_NT_HEADERS32),"NT bounds");
IMAGE_NT_HEADERS32*nt=(void*)(data+offset);
require(nt->Signature==IMAGE_NT_SIGNATURE&&nt->FileHeader.Machine==IMAGE_FILE_MACHINE_I386&&nt->OptionalHeader.ImageBase==0x400000&&nt->OptionalHeader.SizeOfImage==0x299000,"PE identity");
IMAGE_SECTION_HEADER*sections=IMAGE_FIRST_SECTION(nt);
require((unsigned char*)(sections+nt->FileHeader.NumberOfSections)<=data+size,"section table");
for(unsigned i=0;i<nt->FileHeader.NumberOfSections;i++){
IMAGE_SECTION_HEADER*s=&sections[i];
require((uint64_t)s->PointerToRawData+s->SizeOfRawData<=(uint64_t)size&&(uint64_t)s->VirtualAddress+s->SizeOfRawData<=0x299000,"section bounds");
memcpy(mapped+s->VirtualAddress,data+s->PointerToRawData,s->SizeOfRawData);
}
free(data);
for(unsigned i=0;i<sizeof(relocations)/sizeof(relocations[0]);i++){
uint32_t*operand=(void*)AT(relocations[i].va);require(*operand==relocations[i].target,"relocation guard");
*operand=(uint32_t)AT(relocations[i].target);
}
/* Stub the mouse API dependency and replace ONLY the unobserved camera tail.
* Full original numeric input prefix and its support/transform calls remain. */
unsigned char*stub=AT(0x46a460);stub[0]=0xb8;*(uint32_t*)(stub+1)=(uint32_t)mouse;stub[5]=0xff;stub[6]=0xe0;
const unsigned char finish[]={0x5f,0x5e,0x5b,0x83,0xc4,0x68,0xc2,0x04,0x00};
memcpy(AT(0x41ac0e),finish,sizeof(finish));
*(void**)AT(0x509a50)=camera;
for(unsigned i=0;i<sizeof(table)/sizeof(table[0]);i++)table[i]=(uintptr_t)missing;
for(unsigned i=0;i<sizeof(outer)/sizeof(outer[0]);i++)outer[i]=(uintptr_t)missing;
table[0x218/4]=(uintptr_t)supported;table[0x328/4]=(uintptr_t)rotation;
table[0x36c/4]=(uintptr_t)desired;outer[0x128/4]=(uintptr_t)sound;
}
static void run(const char*name,float speed,float lean,int prior_keyboard,int up,int down,int left,int right,int support,float dt){
memset(object,0,sizeof(object));unsigned char*g=object+0xc0;*(uintptr_t**)object=outer;*(uintptr_t**)g=table;
memset(AT(0x509830),0,0x1d0);*(void**)AT(0x509a50)=camera;
*(unsigned char*)AT(0x50985e)=up;*(unsigned char*)AT(0x509860)=down;
*(unsigned char*)AT(0x50985d)=left;*(unsigned char*)AT(0x50985f)=right;grounded=support;
F(g,0x5fc)=400;F(g,0x600)=1;F(g,0x604)=1400;F(g,0x608)=speed;F(g,0x614)=lean;g[0x63a]=prior_keyboard;
F(g,0x660)=20;F(g,0x664)=-20;mouse_x=mouse_y=0;
((void(TC*)(void*,float))AT(0x41a6c0))(g,dt);
printf("CASE %s speed=%.9g bank=%.9g keyboard=%d up=%d down=%d dest=%.9g,%.9g,%.9g\n",name,F(g,0x608),F(g,0x614),g[0x63a],g[0x638],g[0x639],destination[0],destination[1],destination[2]);
}
int main(void){
setbuf(stdout,NULL);map_copy();
run("up_air",0,0,0,1,0,0,0,0,1.f/60);
run("up_air_dt",0,0,0,1,0,0,0,0,.1f);
run("up_supported",0,0,0,1,0,0,0,1,1.f/60);
run("up_down_air",0,0,0,1,1,0,0,0,1.f/60);
run("up_down_supported",0,0,0,1,1,0,0,1,1.f/60);
run("coast_high",1400,0,0,0,0,0,0,0,1.f/60);
run("coast_low",1200,0,0,0,0,0,0,0,1.f/60);
run("down_air",1000,0,0,0,1,0,0,0,1.f/60);
run("down_supported",1000,0,0,0,1,0,0,1,1.f/60);
run("left_precedence",0,0,0,0,0,1,1,0,.1f);
run("keyboard_recenter",0,10,1,0,0,0,0,0,.1f);
run("mouse_origin_hold",0,10,0,0,0,0,0,0,.1f);
run("bank_cap",0,44,1,0,0,1,0,0,.1f);
run("negative_down",-2,0,0,0,1,0,0,0,.1f);
puts("ROCKET_INPUT_COMPONENT_COMPLETE: copied41A6C0 prefix; synthetic dependencies, no camera/game runtime");return 0;
}
'''
VERTICAL_PROBE = PROBE[:PROBE.index('static void run(')] + r'''
/* Source entry41A470 expects the41A140 frame and saved callee registers.
* This thunk builds that frame and jumps into the unchanged vertical suffix;
* original epilogue restores it. Horizontal/animated prefixes do not execute. */
typedef struct{float x,y,z,w;} Vec;
static Vec root,velocity,acceleration;
static Vec* TC root_get(void*self,Vec*out){(void)self;*out=root;return out;}
static Vec* TC velocity_get(void*self,Vec*out){(void)self;*out=velocity;return out;}
static Vec* TC acceleration_get(void*self,Vec*out){(void)self;*out=acceleration;return out;}
static void TC root_xyz(void*self,float x,float y,float z){(void)self;root.x=x;root.y=y;root.z=z;}
static void TC velocity_xyz(void*self,float x,float y,float z){(void)self;velocity.x=x;velocity.y=y;velocity.z=z;}
static void TC acceleration_xyz(void*self,float x,float y,float z){(void)self;acceleration.x=x;acceleration.y=y;acceleration.z=z;}
static void TC velocity_set(void*self,Vec value){(void)self;velocity=value;}
static unsigned char*thunk;
static void setup_vertical(void){
table[0x310/4]=(uintptr_t)root_get;table[0x318/4]=(uintptr_t)root_xyz;
table[0x2bc/4]=(uintptr_t)velocity_get;table[0x2c0/4]=(uintptr_t)velocity_set;
table[0x2c4/4]=(uintptr_t)velocity_xyz;table[0x270/4]=(uintptr_t)acceleration_get;
table[0x278/4]=(uintptr_t)acceleration_xyz;
const unsigned char code[]={0x83,0xec,0x38,0x53,0x56,0x57,0x8b,0xf1,0x33,0xdb,0xe9,0,0,0,0};
thunk=VirtualAlloc(NULL,sizeof(code),MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
require(thunk!=NULL,"vertical thunk");memcpy(thunk,code,sizeof(code));
*(int32_t*)(thunk+11)=(int32_t)(AT(0x41a470)-(thunk+15));
}
static void run_vertical(const char*name,float speed,float height,float vy,float command,int up,int down,float gravity){
memset(object,0,sizeof(object));unsigned char*g=object+0xc0;*(uintptr_t**)g=table;
root=(Vec){1,height,2,1};velocity=(Vec){11,vy,22,0};acceleration=(Vec){33,55,44,0};
F(g,0x608)=speed;F(g,0x620)=3900;F(g,0x624)=650;F(g,0x628)=-650;F(g,0x62c)=650;
F(g,0x65c)=command;g[0x638]=up;g[0x639]=down;*(float*)AT(0x5cfc04)=gravity;
((void(TC*)(void*,float))thunk)(g,1.f/60);
printf("CASE %s height=%.9g velocity=%.9g command=%.9g bodyacceleration=%.9g vx=%.9g vz=%.9g ax=%.9g az=%.9g\n",name,root.y,velocity.y,F(g,0x65c),acceleration.y,velocity.x,velocity.z,acceleration.x,acceleration.z);
}
int main(void){
setbuf(stdout,NULL);map_copy();setup_vertical();
run_vertical("low_speed_retained",99,5000,900,123,0,0,-800);
run_vertical("up_below",100,100,0,0,1,0,-800);
run_vertical("down_below",100,100,0,0,0,1,-800);
run_vertical("neutral_positive",100,100,60,0,0,0,-800);
run_vertical("neutral_negative",100,100,-60,0,0,0,-800);
run_vertical("neutral_snap_positive",100,100,59.99f,0,0,0,-800);
run_vertical("neutral_snap_negative",100,100,-59.99f,0,0,0,-800);
run_vertical("neutral_zero",100,100,0,99,0,0,-800);
run_vertical("ceiling_up",100,5000,300,0,1,0,-800);
run_vertical("ceiling_down",100,5000,-900,0,0,1,-800);
run_vertical("velocity_cap_up",100,100,900,0,1,0,-800);
run_vertical("velocity_cap_down",100,100,-900,0,0,1,-800);
run_vertical("zero_gravity_up",100,100,0,0,1,0,0);
run_vertical("low_speed_gravity",0,100,-10,-33,1,0,-800);
puts("ROCKET_VERTICAL_COMPONENT_COMPLETE: copied41A470 suffix; synthetic body, no integration/game runtime");return 0;
}
'''
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
cli.add_argument('--probe-source', type=Path)
cli.add_argument('--probe-log', type=Path)
cli.add_argument('--probe-executable', type=Path)
cli.add_argument('--vertical-probe-source', type=Path)
cli.add_argument('--vertical-probe-log', type=Path)
cli.add_argument('--vertical-probe-executable', type=Path)
args = cli.parse_args()
report = collect(args.original)
if bool(args.probe_log) != bool(args.probe_executable):
cli.error('Use --probe-log and --probe-executable together')
if args.probe_source:
output = args.probe_source.resolve()
if output.is_relative_to(args.original.resolve()):
cli.error('Probe source must be generated outside originals')
output.write_text(probe_source(report))
if args.probe_log:
report['original_input_probe'] = probe_results(report, args.probe_log, args.probe_executable)
if args.vertical_probe_source:
output = args.vertical_probe_source.resolve()
if output.is_relative_to(args.original.resolve()):
cli.error('Probe source must be generated outside originals')
output.write_text(probe_source(report, vertical=True))
if bool(args.vertical_probe_log) != bool(args.vertical_probe_executable):
cli.error('Use --vertical-probe-log and --vertical-probe-executable together')
if args.vertical_probe_log:
report['original_vertical_probe'] = probe_results(report, args.vertical_probe_log,
args.vertical_probe_executable, vertical=True)
print(json.dumps(report, indent=2))