Trace Carl lifecycle and add read-only original state observer

This commit is contained in:
UnixNight committed 2026-11-06 10:27:10 -05:00
1 parent c642b69849
commit 4cd62d3627
28 files changed
+2387 -5

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Map verified original sections into a static Ghidra carrier at DEFAULT.
This is analysis input, not a runnable executable or a loaded-process image.
It preserves initialized section bytes and zero-fills virtual gaps/tails.
"""
import argparse
import hashlib
import json
from pathlib import Path
from checkpoint_script_state import EXE_SHA256, find_case
from pe_inspect import PE
START = 0x447CF0
def generate(original, output):
original, output = Path(original).resolve(), Path(output).resolve()
if output.is_relative_to(original) or original.is_relative_to(output):
raise ValueError('Output must be separate from originals')
pe = PE(find_case(original, 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unexpected original executable')
end = max(pe.base+s['rva']+max(s['virtual_size'], s['raw_size'])
for s in pe.sections)
if not START < end <= START+16*1024*1024:
raise ValueError('Unexpected source image extent')
carrier = bytearray(end-START)
ranges = []
for section in pe.sections:
a = max(START, pe.base+section['rva'])
b = min(end, pe.base+section['rva']+section['raw_size'])
if a >= b:
continue
offset = pe.offset(a-pe.base)
source = pe.data[offset:offset+b-a]
if len(source) != b-a:
raise ValueError('Truncated source section')
carrier[a-START:b-START] = source
ranges.append(dict(source_offset=offset, va=a, length=b-a,
carrier_offset=a-START))
result = dict(source_sha256=EXE_SHA256,
carrier_sha256=hashlib.sha256(carrier).hexdigest(),
start=hex(START), end=hex(end), ranges=ranges,
scope='Static raw analysis carrier with original byte mappings '
'and zero virtual tails, not an executable or runtime capture.')
output.mkdir(parents=True, exist_ok=True)
(output/'default.bin').write_bytes(carrier)
(output/'mapping.json').write_text(json.dumps(result, indent=2)+'\n')
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
parser.add_argument('--output', required=True, type=Path)
args = parser.parse_args()
print(json.dumps(generate(args.original, args.output), indent=2))
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Read-only original base/facing/animation return guards and probe generator."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import struct
import subprocess
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
REA_ID = 'ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904'
RANGES = ((0x40e050, 0x40e1c8), (0x462520, 0x462649),
(0x458930, 0x45893d), (0x473240, 0x473298),
(0x43a420, 0x43a5cd), (0x472480, 0x472570), (0x4732b0, 0x47331d),
(0x43a900, 0x43aa38), (0x424600, 0x424d10),
(0x43b28a, 0x43b2f4), (0x42afc0, 0x42aff0), (0x43a750, 0x43a786),
(0x43aff0, 0x43b5a2), (0x40dd90, 0x40df7c), (0x40da30, 0x40daad),
(0x462270, 0x462331), (0x429a00, 0x429a25))
SLOTS = ((0x4a3bdc, 0x104, 0x43a900), (0x4a3bdc, 0x100, 0x40df80),
(0x4a3bdc, 0xe0, 0x40dd90), (0x4a373c, 0x3d8, 0x43a420),
(0x4a373c, 0x3d4, 0x4732b0), (0x4a373c, 0x210, 0x4719f0),
(0x4a373c, 0x338, 0x472570), (0x4a373c, 0x410, 0x42afc0),
(0x4a3bdc, 0x150, 0x43aff0), (0x4a3bdc, 0xe4, 0x40da30),
(0x4a3bdc, 0xc8, 0x462270), (0x4a3bdc, 0x148, 0x429a00),
(0x4a373c, 0x110, 0x471240), (0x4a373c, 0x2e0, 0x4720c0),
(0x4a373c, 0x2e8, 0x472120))
def generate(original, output, rea):
original, output = Path(original).resolve(), Path(output).resolve()
if output.is_relative_to(original) or original.is_relative_to(output):
raise ValueError('Separate output required')
pe = PE(find_case(original, 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Original EXE identity')
evidence = next(r for r in json.loads(Path(rea).read_text())['records']
if r['evidence_id'] == REA_ID)
if evidence['subject']['digest']['sha256'] != EXE_SHA256:
raise ValueError('REA subject identity')
for table, slot, expected in SLOTS:
actual, = struct.unpack('<I', read_va(pe, table+slot, 4))
if actual != expected:
raise ValueError(f'Slot {table:#x}+{slot:#x}: {actual:#x}')
targets = set()
excerpts = {}
rows = []
for line in evidence['raw_result']['stdout'].splitlines():
match = re.match(r'\s*([0-9a-f]+):', line)
if match:
rows.append((int(match[1], 16), line))
for a, b in RANGES:
asm = subprocess.run(['objdump', '-d', '-Mintel', f'--start-address={a}',
f'--stop-address={b}', str(pe.path)],
capture_output=True, text=True, check=True).stdout
targets.update(int(v, 16) for v in re.findall(r'ds:0x([0-9a-f]+)', asm))
targets.update(int(v, 16) for v in re.findall(r'(?:push|mov\s+\w+,)\s*0x([0-9a-f]+)', asm)
if 0x48d000 <= int(v, 16) < 0x510000)
excerpts[hex(a)] = '\n'.join(line for va, line in rows if a <= va < b)+'\n'
if not excerpts[hex(a)].strip():
raise ValueError('Missing REA range')
output.mkdir(parents=True, exist_ok=True)
source = Path(__file__).with_name('jimmy_base_return_probe.c').read_text()
source = source.replace('/* RELOCATIONS */', ','.join(hex(x) for x in sorted(targets)))
(output/'jimmy_base_return_probe.c').write_text(source)
result = dict(source_sha256=EXE_SHA256, rea_evidence_id=REA_ID,
slots=[dict(table=hex(t), slot=hex(s), target=hex(v),
file_offset=hex(pe.offset(t+s-pe.base))) for t,s,v in SLOTS],
ranges=[dict(va=hex(a), file_offset=hex(pe.offset(a-pe.base)),
length=b-a, sha256=hashlib.sha256(read_va(pe,a,b-a)).hexdigest())
for a,b in RANGES], relocations=[hex(x) for x in sorted(targets)],
rea_extracts=excerpts,
scope='Static guards and synthetic-body actual base/animation component; no whole original Jimmy frame.')
(output/'source.json').write_text(json.dumps(result, indent=2)+'\n')
return result
def observations(output, capture):
output, capture = Path(output), Path(capture)
metadata = json.loads((capture/'capture.json').read_text())
if metadata['captures'][-1]['wineExit'] != 0:
raise ValueError('Probe exit was not zero')
log = (capture/'wine.log').read_text()
if 'JIMMY_BASE_RETURN_COMPLETE' not in log:
raise ValueError('Missing completion marker')
base, stop = [], []
for line in log.splitlines():
if not line.startswith(('CASE ', 'STOP_CASE ')):
continue
row = dict(item.split('=', 1) for item in line.split()[1:])
if int(row['mode']) != 1 or abs(float(row['turn'])-11.666668) > 1e-6:
raise ValueError('Retained state mismatch')
if line.startswith('CASE '):
ready, loop, last = (int(row[k]) for k in ('ready', 'loop', 'last'))
eligible = ready == 2 and not loop and last
special = row['action'] in ('FENCE', 'LADDER')
changed = special or row['action'] in ('HIT', 'SPLAT')
if int(row['ended']) != (180 if eligible else 0):
raise ValueError('End callback count')
if int(row['selected']) != int(eligible and changed):
raise ValueError('Selection count')
for field in ('stop', 'restore', 'enable'):
if int(row[field]) != int(eligible and special):
raise ValueError('Special cleanup count')
if row['current'] != '0,155,0' or row['target'] != '0,155,0':
raise ValueError('Euler publication')
base.append(row)
else:
if int(row['ticks']) != 180:
raise ValueError('Post-STOP base update count')
eligible = int(row['ready']) and (int(row['direct']) or row['prior'] in ('TALK', 'FALL'))
bound = int(bool(eligible) and bool(int(row['found'])))
if int(row['lookup']) != int(bool(eligible)) or int(row['shape']) != int(bool(eligible)):
raise ValueError('STOP acceptance path')
if any(int(row[k]) != bound for k in ('anim', 'frames', 'pauses')):
raise ValueError('STOP resource path')
if row['final'] != ('STOP' if eligible else row['prior']):
raise ValueError('STOP final action')
stop.append(row)
if len(base) != 84 or len(stop) != 56:
raise ValueError('Incomplete finite case matrix')
provenance = {}
for name, path in [('generated_source', output/'jimmy_base_return_probe.c'),
('executable', output/'probe.exe'),
('log', capture/'wine.log'), ('capture', capture/'capture.json'),
('source_contract', output/'source.json')]:
provenance[name] = dict(path=str(path), sha256=hashlib.sha256(path.read_bytes()).hexdigest())
result = dict(source_sha256=EXE_SHA256, rea_evidence_id=REA_ID,
base_cases=base, stop_cases=stop, provenance=provenance,
scope='140 bounded copied-original cases; synthetic body/resources, not full original gameplay.')
(output.parent/'native-observations.json').write_text(json.dumps(result, indent=2)+'\n')
return dict(base_cases=len(base), stop_cases=len(stop), wine_exit=0)
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
cli.add_argument('--output', type=Path, required=True)
cli.add_argument('--rea', type=Path, required=True)
cli.add_argument('--capture', type=Path)
args = cli.parse_args()
result = generate(args.original, args.output, args.rea)
if args.capture:
result['observations'] = observations(args.output, args.capture)
print(json.dumps({k: v for k, v in result.items() if k != 'rea_extracts'}, indent=2))
+133
View File
@@ -0,0 +1,133 @@
/* Actual animated base + common object + facing + animation-ended callback.
Synthetic body/resource records; no world, full Jimmy frame or renderer. */
#define main unused_scalar_main
#include "grappler_scalar_probe.c"
#undef main
typedef struct { float x,y,z,w; } Vec4;
static uintptr_t game[0x450/4], complete[0x220/4], morph[0x30/4];
static unsigned char record[0x50];
static unsigned char bounds_shape[0x60], definition[0x40];
static uintptr_t bounds_table[0x50/4];
static int found, lookups, bound_shapes, bound_anims, frame_sets, pauses;
static int frame_pos, ended, selected, stopped, restored, enabled;
#define OF(o) (*(float*)(object+(o)))
#define GF(o) OF(0xc0+(o))
#define MODE (*(short*)(object+0x7c4))
static void fix(uint32_t a,uint32_t b){
const uint32_t targets[]={/* RELOCATIONS */};
for(;a+4<=b;a++){
uint32_t v;memcpy(&v,AT(a),4);
for(unsigned i=0;i<sizeof(targets)/sizeof(targets[0]);i++)if(v==targets[i]){
v=(uintptr_t)AT(v);memcpy(AT(a),&v,4);a+=3;break;
}
}
}
static LONG CALLBACK exception(EXCEPTION_POINTERS*e){
fprintf(stderr,"PROBE_EXCEPTION pc=%lx source=%lx code=%lx fault=%lx\n",
e->ContextRecord->Eip,e->ContextRecord->Eip-(uintptr_t)mapped+0x400000,
e->ExceptionRecord->ExceptionCode,e->ExceptionRecord->ExceptionInformation[1]);
ExitProcess(2);return EXCEPTION_CONTINUE_SEARCH;
}
static int TC get_frame(void*self){require(self==object+0x90,"morph subobject");return frame_pos;}
static void TC anim_ended(void*self){require(self==object,"complete callback");ended++;((void(TC*)(void*))AT(0x43a900))(self);}
static void TC select_animation(void*self,const char*name,int force){
require(self==object,"select receiver");(void)force;selected++;
strncpy((char*)object+0x5e8,name,31);object[0x5e8+31]=0;
}
static void TC stop_motion(void*self){require(self==object+0xc0,"stop receiver");stopped++;}
static void TC restore_position(void*self,Vec4 v){require(self==object+0xc0,"position receiver");memcpy(object+0x2d4,&v,sizeof(v));restored++;}
static void TC enable_body(void*self,int value){require(self==object+0xc0&&value==1,"enable receiver");enabled++;}
static void*TC find_record(void*self,const char*name){require(self==object&&!strcmp(name,"HISTOP"),"record lookup");lookups++;return found?record:NULL;}
static void TC bind_shape(void*self,void*value){require(self==object&&value==bounds_shape,"shape binding");*(void**)(object+0x8c)=value;bound_shapes++;}
static void TC bind_anim(void*self,void*value){require(self==object&&value==definition,"animation binding");bound_anims++;}
static void TC set_frame(void*self,int frame,int loop){require(self==object+0x90&&frame==0&&loop==1,"frame selection");*(int*)(object+0xa0)=frame;frame_pos=frame;frame_sets++;}
static void TC set_pause(void*self,int value){require(self==object+0x90&&value==1,"animation pause");pauses++;}
static void TC shape_bounds(void*self,float*x1,float*y1,float*z1,float*x2,float*y2,float*z2){
require(self==bounds_shape,"shape bounds");*x1=-10;*y1=0;*z1=-20;*x2=10;*y2=70;*z2=20;
}
static void stop_suite(void){
complete[0xe0/4]=(uintptr_t)AT(0x40dd90);complete[0xe4/4]=(uintptr_t)AT(0x40da30);
complete[0xdc/4]=(uintptr_t)find_record;complete[0xc0/4]=(uintptr_t)bind_anim;
complete[0xc8/4]=(uintptr_t)AT(0x462270);complete[0x148/4]=(uintptr_t)AT(0x429a00);
complete[0x150/4]=(uintptr_t)AT(0x43aff0);
game[0x260/4]=(uintptr_t)AT(0x471b30);game[0x264/4]=(uintptr_t)AT(0x471b40);
game[0x278/4]=(uintptr_t)AT(0x471ba0);game[0x2c4/4]=(uintptr_t)AT(0x471f40);
game[0x110/4]=(uintptr_t)AT(0x471240);game[0x2e0/4]=(uintptr_t)AT(0x4720c0);game[0x2e8/4]=(uintptr_t)AT(0x472120);
morph[0x10/4]=(uintptr_t)set_frame;morph[0x24/4]=(uintptr_t)set_pause;
bounds_table[0x44/4]=(uintptr_t)shape_bounds;*(void**)bounds_shape=bounds_table;*(float*)(bounds_shape+0x4c)=80;
*(void**)AT(0x48d198)=bind_shape;
const char*actions[]={"STOP","TALK","FALL","HIT","SPLAT","FENCE","LADDER"};
for(unsigned a=0;a<sizeof(actions)/sizeof(actions[0]);a++)for(int r=0;r<2;r++)for(int f=0;f<2;f++)for(int direct=0;direct<2;direct++){
memset(object,0,sizeof(object));memset(record,0,sizeof(record));memset(definition,0,sizeof(definition));
*(void**)object=complete;*(void**)(object+0xc0)=game;*(void**)(object+0x90)=morph;
object[0x634]=object[0x635]=r;*(void**)(object+0x57c)=bounds_shape;
*(void**)(record+0x4c)=definition;*(int*)(record+0x44)=0;*(int*)(object+0xa44)=-1;
strncpy((char*)object+0x5e8,actions[a],31);MODE=1;OF(0x6d4)=11.666668f;OF(0x6c8)=33;
GF(0x608)=321;GF(0x1a4)=1;GF(0x1a8)=2;GF(0x1ac)=3;
GF(0x224)=13;GF(0x228)=155;GF(0x22c)=17;GF(0x274)=-40;GF(0x278)=154;GF(0x27c)=-12;
found=f;lookups=bound_shapes=bound_anims=frame_sets=pauses=0;
unsigned char euler[32];memcpy(euler,object+0x2e4,16);memcpy(euler+16,object+0x334,16);
if(direct)((void(TC*)(void*,const char*,int))AT(0x40dd90))(object,"STOP",1);
else ((void(TC*)(void*))AT(0x42afc0))(object+0xc0);
require(MODE==1&&OF(0x6d4)==11.666668f,"Stop retained mode/turn");
require(!memcmp(euler,object+0x2e4,16)&&!memcmp(euler+16,object+0x334,16),"Stop retained Euler vectors");
if(!direct)require(GF(0x608)==0&&GF(0x1a4)==0&&GF(0x1a8)==0&&GF(0x1ac)==0,"Stop speed/velocity");
/* Represent a separately flattened locked interval, then run the real base.
This seed is explicit; this suite does not execute CAM/MCA flatten itself. */
GF(0x224)=GF(0x274)=0;GF(0x228)=GF(0x278)=155;GF(0x22c)=GF(0x27c)=0;
object[0xc5]=1;object[0xc0+0x5f9]=1;*(int*)(object+0xc0+0x58c)=1;
*(int*)(object+0xc0+0x408)=*(int*)(object+0xc0+0x40c)=*(int*)(object+0xc0+0x410)=-1;
ended=0;
for(int tick=0;tick<180;tick++)((void(TC*)(void*,float))AT(0x40e050))(object+0xc0,1.f/60);
require(MODE==1&&OF(0x6d4)==11.666668f,"Post-Stop base retains mode/turn");
require(GF(0x224)==0&&GF(0x228)==155&&GF(0x22c)==0&&GF(0x274)==0&&GF(0x278)==155&&GF(0x27c)==0,"Post-Stop base retains upright vectors");
require(ended==0,"Real selected STOP loop prevents completion callbacks");
printf("STOP_CASE prior=%s ready=%d found=%d direct=%d lookup=%d shape=%d anim=%d frames=%d pauses=%d ticks=180 mode=%d turn=%.9g final=%s\n",actions[a],r,f,direct,lookups,bound_shapes,bound_anims,frame_sets,pauses,MODE,OF(0x6d4),object+0x5e8);
}
}
static void one(const char*action,int ready,int loop,int last){
memset(object,0,sizeof(object));memset(record,0,sizeof(record));
*(void**)object=complete;*(void**)(object+0xc0)=game;*(void**)(object+0x90)=morph;
object[0xc5]=1;object[0xc0+0x5f9]=1;*(int*)(object+0xc0+0x58c)=1;
object[0xc0+0x13e]=1; /* actual4719F0 true, actual472570 returns null body */
*(int*)(object+0xc0+0x408)=*(int*)(object+0xc0+0x40c)=*(int*)(object+0xc0+0x410)=-1;
object[0x634]=ready!=0;object[0x635]=ready==2;object[0xad]=loop;
*(void**)(object+0x62c)=record;*(int*)(record+0x48)=5;frame_pos=last?4:3;
strncpy((char*)object+0x5e8,action,31);
GF(0x224)=GF(0x274)=0;GF(0x228)=GF(0x278)=155;GF(0x22c)=GF(0x27c)=0;
MODE=1;OF(0x6d4)=11.666668f;OF(0x6c8)=33;object[0x6e4]=1;
OF(0x838)=10;OF(0x83c)=20;OF(0x840)=30;OF(0x844)=1;
ended=selected=stopped=restored=enabled=0;
unsigned char before[32];memcpy(before,object+0x2e4,16);memcpy(before+16,object+0x334,16);
for(int i=0;i<180;i++)((void(TC*)(void*,float))AT(0x40e050))(object+0xc0,1.f/60);
require(MODE==1&&OF(0x6d4)==11.666668f,"retained mode/turn");
require(!memcmp(before,object+0x2e4,16)&&!memcmp(before+16,object+0x334,16),"Euler vectors unchanged");
int should_end=ready==2&&!loop&&last;
int special=!strcmp(action,"FENCE")||!strcmp(action,"LADDER");
int hit=!strcmp(action,"HIT")||!strcmp(action,"SPLAT");
require(ended==(should_end?180:0),"completion eligibility/repetition");
require(selected==(should_end&&(special||hit)?1:0),"selected animation count");
require(stopped==(should_end&&special?1:0)&&restored==stopped&&enabled==stopped,"special cleanup callbacks");
printf("CASE action=%s ready=%d loop=%d last=%d ended=%d selected=%d stop=%d restore=%d enable=%d mode=%d turn=%.9g current=%.9g,%.9g,%.9g target=%.9g,%.9g,%.9g final=%s clock=%.9g\n",
action,ready,loop,last,ended,selected,stopped,restored,enabled,MODE,OF(0x6d4),
GF(0x224),GF(0x228),GF(0x22c),GF(0x274),GF(0x278),GF(0x27c),object+0x5e8,GF(0x4c4));
}
int main(void){
setbuf(stdout,NULL);map_source();AddVectoredExceptionHandler(1,exception);
const uint32_t ranges[][2]={{0x40e050,0x40e1c8},{0x462520,0x462649},{0x458930,0x45893d},{0x473240,0x473298},{0x4732b0,0x47331d},{0x43a420,0x43a5cd},{0x472480,0x472570},{0x43a900,0x43aa38},{0x42afc0,0x42aff0},{0x43a750,0x43a786},{0x43aff0,0x43b5a2},{0x40dd90,0x40df7c},{0x40da30,0x40daad},{0x462270,0x462331},{0x429a00,0x429a25}};
for(unsigned i=0;i<sizeof(ranges)/sizeof(ranges[0]);i++)fix(ranges[i][0],ranges[i][1]);
const unsigned char ready[]={0xb0,1,0xc3};memcpy(AT(0x475ca0),ready,3);
jump(AT(0x487c20),_stricmp);
game[0x210/4]=(uintptr_t)AT(0x4719f0);game[0x338/4]=(uintptr_t)AT(0x472570);
game[0x3d4/4]=(uintptr_t)AT(0x4732b0);game[0x3d8/4]=(uintptr_t)AT(0x43a420);
game[0x328/4]=(uintptr_t)AT(0x4723f0);game[0x334/4]=(uintptr_t)AT(0x458f90);
game[0x410/4]=(uintptr_t)stop_motion;game[0x314/4]=(uintptr_t)restore_position;game[0xa8/4]=(uintptr_t)enable_body;
complete[0x100/4]=(uintptr_t)AT(0x40df80);complete[0x104/4]=(uintptr_t)anim_ended;complete[0xe0/4]=(uintptr_t)select_animation;
morph[0x1c/4]=(uintptr_t)get_frame;
const char*actions[]={"STOP","TALK","FALL","HIT","SPLAT","FENCE","LADDER"};
for(unsigned a=0;a<sizeof(actions)/sizeof(actions[0]);a++)for(int r=0;r<3;r++)for(int l=0;l<2;l++)for(int f=0;f<2;f++)one(actions[a],r,l,f);
stop_suite();
puts("JIMMY_BASE_RETURN_COMPLETE");return 0;
}
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Guard original Carl talk admission and bootstrap boundaries, read-only."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import struct
import sys
from checkpoint_script_state import EXE_SHA256, find_case, read_va, rel_call_target
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels'))
import gam
REA_ID = 'ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904'
CALLS = (
('AI contact base', 0x40a3cd, 0x470a90),
('Jimmy contact base', 0x422d50, 0x470a90),
('friend update runs AI first', 0x41b95d, 0x408000),
('Carl progress base', 0x413e50, 0x41b810),
('bootstrap constructs app', 0x46a641, 0x46b160),
('bootstrap selects MAIN', 0x46a660, 0x46a310),
('bootstrap MAIN factory', 0x46a33d, 0x44d0e0),
('MAIN constructor', 0x44d122, 0x459110),
('MAIN base constructor', 0x459168, 0x44d2b0),
('Jimmy game generic base constructor', 0x44d306, 0x4745a0),
('MAIN initialize', 0x4591c3, 0x4749a0),
('menu New Game task route', 0x404b54, 0x460e70),
('script RESTARTGAME task route', 0x40d08e, 0x460e70),
('Jimmy sole direct constructor caller', 0x45b1e2, 0x422160),
)
SITES = (
('contact target pointer', 0x40a44c, '8b860006000085'),
('contact exact target identity', 0x40a45a, '3bf80f8531020000'),
('contact state6 admission', 0x40a676, '83be08060000067514'),
('contact state setter', 0x40a68d, 'ff9224010000'),
('AI state0 target invisible flag', 0x40847c, '8a889d04000084'),
('friend resulting AI state', 0x41b972, '8b860806000085'),
('friend state0 talk', 0x41b988, 'ff9240010000'),
('talk progress before trigger', 0x41b7cd, 'ff9280010000'),
('talk synchronous trigger', 0x41b7d8, 'ff505c'),
('AI state owner store', 0x4089fe, '8986c8060000'),
('lab contact game callback is no-op', 0x475d40, '83c8ffc20800'),
('pair permissions are unconditional', 0x472f80, 'b001c20400'),
('pair enabled reads own collision byte', 0x471a30, '8a8140010000c3'),
('pair geometry reads own collision kind', 0x471720, '8b8124010000c3'),
('MAIN enum', 0x46a65b, '684e49414d'),
('menu NewGame task string', 0x404b4f, '681cc74e00'),
('RESTARTGAME NewGame task string', 0x40d089, '681cc74e00'),
)
SLOTS = (
('Carl contact game+C0', 0x495364, 0x40, 0x40a3c0),
('Jimmy counterpart contact', 0x4a373c, 0x40, 0x422d30),
('Jimmy pair permission', 0x4a373c, 0x3a0, 0x472f80),
('Carl pair permission', 0x495364, 0x3a0, 0x472f80),
('Jimmy collision enabled', 0x4a373c, 0x220, 0x471a30),
('Carl collision enabled', 0x495364, 0x220, 0x471a30),
('Jimmy collision kind', 0x4a373c, 0x178, 0x471720),
('Carl collision kind', 0x495364, 0x178, 0x471720),
('Carl duplicate contact membership', 0x495364, 0x3c, 0x470a60),
('Carl update game+C0', 0x495364, 0x3c4, 0x41b950),
('Carl prepare is NPC velocity helper', 0x495364, 0x410, 0x40a6b0),
('Carl AI state complete', 0x495804, 0x124, 0x4089b0),
('Carl talk complete', 0x495804, 0x140, 0x41b7b0),
('Carl trigger resolver complete', 0x495804, 0x17c, 0x41bb20),
('Carl progress complete', 0x495804, 0x180, 0x413e50),
('Lab contact game callback complete', 0x4c3cd0, 0x144, 0x475d40),
('MAIN InitGame complete', 0x4d1070, 0xb4, 0x44d3d0),
('app bootstrap database', 0x4d5ea0, 0x118, 0x46f760),
('app bootstrap image', 0x4d5ea0, 0x12c, 0x46f830),
)
RANGES = (
('contact', 0x40a3c0, 0x40a69a), ('duplicate contact', 0x470a60, 0x470a88),
('contact base', 0x470a90, 0x470b19), ('AI state', 0x4089b0, 0x408bc0),
('physical pair notifications', 0x47a430, 0x47a5a4),
('Jimmy counterpart contact', 0x422d30, 0x423575),
('AI update', 0x408000, 0x408980), ('friend update', 0x41b950, 0x41bb20),
('talk', 0x41b7b0, 0x41b831), ('talk resolver', 0x41bb20, 0x41bc20),
('Carl progress', 0x413e50, 0x413ea6), ('NPC velocity', 0x40a6b0, 0x40a6ca),
('bootstrap MAIN route', 0x46a310, 0x46a355),
('bootstrap selection', 0x46a641, 0x46a6b0),
('MAIN factory', 0x44d0e0, 0x44d161), ('MAIN constructor', 0x459110, 0x4591f7),
('MAIN base constructor', 0x44d2b0, 0x44d353),
('MAIN InitGame', 0x44d3d0, 0x44d491),
('bootstrap database', 0x46f760, 0x46f830), ('bootstrap image', 0x46f830, 0x46fa84),
)
def collect(original, rea=None):
original = Path(original)
pe = PE(find_case(original, 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unexpected original executable')
calls=[]
for name, va, target in CALLS:
if rel_call_target(pe, va) != target: raise ValueError(name)
calls.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), target=hex(target)))
sites=[]
for name, va, expected in SITES:
if read_va(pe,va,len(bytes.fromhex(expected))).hex()!=expected: raise ValueError(name)
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=expected))
slots=[]
for name, table, slot, target in SLOTS:
if struct.unpack('<I',read_va(pe,table+slot,4))[0]!=target: raise ValueError(name)
slots.append(dict(name=name, table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base))))
level_path=find_case(original,'gam/level1b.gam'); level=gam.parse(level_path.read_bytes())
route=[]
for e in level.entities:
v=e.values()
if str(v.get('ObjectTag','')).casefold() in ('jim1','c3dcarl','neutron1a','carlwalk'):
route.append(dict(kind=e.kind,file_offset=hex(e.offset),fields=v))
result=dict(source_sha256=EXE_SHA256,rea_evidence_id=REA_ID,calls=calls,sites=sites,slots=slots,
ranges=[dict(name=n,va=hex(a),file_offset=hex(pe.offset(a-pe.base)),length=b-a,
sha256=hashlib.sha256(read_va(pe,a,b-a)).hexdigest()) for n,a,b in RANGES],
gam_sha256=hashlib.sha256(level_path.read_bytes()).hexdigest(),route=route,
scope='Static local contact/talk and bootstrap boundaries; not physical pair admission, whole talk chain or original full runtime.')
if rea:
record=next(r for r in json.loads(Path(rea).read_text())['records'] if r['evidence_id']==REA_ID)
if record['subject']['digest']['sha256']!=EXE_SHA256:raise ValueError('REA identity mismatch')
rows=[]
for line in record['raw_result']['stdout'].splitlines():
m=re.match(r'\s*([0-9a-f]+):',line)
if m:rows.append((int(m[1],16),line))
result['rea_extracts']={n:'\n'.join(l for va,l in rows if a<=va<b)+'\n' for n,a,b in RANGES}
if any(not x.strip() for x in result['rea_extracts'].values()):raise ValueError('Missing REA body')
return result
if __name__=='__main__':
cli=argparse.ArgumentParser(description=__doc__)
cli.add_argument('original',type=Path);cli.add_argument('--rea-disassembly',type=Path)
cli.add_argument('--generate-probe',type=Path);args=cli.parse_args()
result=collect(args.original,args.rea_disassembly)
if args.generate_probe:
out=args.generate_probe.resolve();original=args.original.resolve()
if out.is_relative_to(original) or original.is_relative_to(out):raise ValueError('Separate probe directory required')
out.mkdir(parents=True,exist_ok=True)
for name in ('jimmy_carl_entry_probe.c','grappler_scalar_probe.c'):
(out/name).write_text(Path(__file__).with_name(name).read_text())
(out/'source.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
+64
View File
@@ -0,0 +1,64 @@
/* Bounded original Carl contact dispatch, not physical pair admission or talk.
Synthetic actors; actual 40A3C0,470A90,470A60,4089B0,475D40 execute.
Native allocation and NPC animation/type callbacks are explicit adapters. */
#define main unused_grappler_main
#include "grappler_scalar_probe.c"
#undef main
static unsigned char jimmy[0x1f00], other[0x1f00], game[0x600];
static uintptr_t npc_complete[0x190/4], npc_game[0x440/4];
static uintptr_t jimmy_game[0x440/4], game_table[0x150/4];
static uintptr_t contacts[3];
static int support, support_calls, animation_calls, prepare_calls;
static int TC is_a(void *self, const char *type){(void)self;(void)type;return 0;}
static int TC supported(void *self){require(self==jimmy+0xc0,"support owner");support_calls++;return support;}
static void TC prepare(void *self){require(self==object,"NPC prepare owner");prepare_calls++;}
static void TC animate(void *self,const char *name,int repeat){
require(self==object&&name==(char*)object+0x898&&repeat==1,"NPC idle animation owner");animation_calls++;
}
static void *allocate(size_t size){require(size==12,"contact node allocation");return malloc(size);}
static void fix(uint32_t start,uint32_t end){
const uint32_t refs[]={0x509948,0x5099e4,0x408b94};
for(uint32_t a=start;a+4<=end;a++){
uint32_t value;memcpy(&value,AT(a),4);
for(unsigned i=0;i<sizeof(refs)/sizeof(refs[0]);i++)if(value==refs[i]){
value=(uintptr_t)AT(value);memcpy(AT(a),&value,4);a+=3;break;
}
}
}
int main(void){
setbuf(stdout,NULL);map_source();
fix(0x40a3c0,0x40a69a);fix(0x470a90,0x470b19);fix(0x4089b0,0x408b94);
for(unsigned i=0;i<11;i++){uint32_t *v=(void*)AT(0x408b94+4*i);*v=(uintptr_t)AT(*v);}
jump(AT(0x478990),allocate);
npc_complete[0x124/4]=(uintptr_t)AT(0x4089b0);
npc_complete[0x16c/4]=(uintptr_t)prepare;npc_complete[0xe0/4]=(uintptr_t)animate;
npc_game[0x3c/4]=(uintptr_t)AT(0x470a60);
jimmy_game[0x18/4]=(uintptr_t)is_a;jimmy_game[0x218/4]=(uintptr_t)supported;
game_table[0x144/4]=(uintptr_t)AT(0x475d40);*(void**)game=game_table;
*(void**)AT(0x509948)=game;
int cases=0;
for(int sup=0;sup<2;sup++)for(int mode=0;mode<2;mode++)for(int turn=-12;turn<=12;turn+=12)
for(int match=0;match<2;match++)for(int active=0;active<2;active++)for(int raw=0;raw<2;raw++){
memset(object,0,sizeof(object));memset(jimmy,0xa5,sizeof(jimmy));memset(other,0xa5,sizeof(other));
*(void**)object=npc_complete;*(void**)(object+0xc0)=npc_game;
*(void**)(jimmy+0xc0)=jimmy_game;*(void**)(other+0xc0)=jimmy_game;
*(short*)(jimmy+0xc0+0x704)=(short)mode;*(float*)(jimmy+0xc0+0x614)=(float)turn;
*(float*)(jimmy+0xc0+0x224)=15;*(float*)(jimmy+0xc0+0x22c)=28;
*(float*)(jimmy+0xc0+0x274)=7;*(float*)(jimmy+0xc0+0x27c)=-24;
contacts[0]=contacts[1]=(uintptr_t)contacts;contacts[2]=0;
*(void**)(object+0xc0+0x260)=contacts;*(int*)(object+0xc0+0x408)=-1;
*(void**)(object+0xc0+0x600)=jimmy+0xc0;*(int*)(object+0x6c8)=active?6:3;
*(void**)AT(0x5099e4)=(raw?jimmy:other)+0xc0;
unsigned char before[sizeof(jimmy)];memcpy(before,jimmy,sizeof(jimmy));
support=sup;support_calls=animation_calls=prepare_calls=0;
((void(TC*)(void*,void*))AT(0x40a3c0))(object+0xc0,(match?jimmy:other)+0xc0);
require(memcmp(before,jimmy,sizeof(jimmy))==0,"entire target Jimmy memory unchanged");
require(support_calls==0,"no support query");
require(*(int*)(object+0x6c8)==(match&&active?0:active?6:3),"NPC state admission");
require(animation_calls==(match&&active)&&prepare_calls==(match&&active),"NPC idle callback count");
require(*(int*)(object+0xc0+0x264)==1,"actual base contact appended node");
free((void*)contacts[0]);cases++;
}
printf("CARL_CONTACT {\"cases\":%d,\"jimmy_unchanged\":true,\"support_queries\":0}\n",cases);
puts("JIMMY_CARL_ENTRY_COMPLETE");return 0;
}
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
"""Guard and prepare a bounded original skip/input/player composition probe."""
import argparse,hashlib,json,re,struct,subprocess
from pathlib import Path
from checkpoint_script_state import EXE_SHA256,find_case,read_va
from pe_inspect import PE
REA_ID='ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904'
RANGES=((0x437940,0x437c3a),(0x438a60,0x438ba2),(0x439900,0x439e33),(0x43915d,0x4395cf),(0x43a420,0x43a5cd),(0x472480,0x472570),(0x475a40,0x475a4c),(0x431518,0x431590),(0x430f1d,0x430f5c),(0x429910,0x429963))
def generate(original,out,rea):
original=Path(original).resolve();out=Path(out).resolve()
if out.is_relative_to(original) or original.is_relative_to(out):raise ValueError('Separate output required')
p=PE(find_case(original,'Neutron.exe'))
if hashlib.sha256(p.data).hexdigest()!=EXE_SHA256:raise ValueError('Original EXE identity')
record=next(r for r in json.loads(Path(rea).read_text())['records'] if r['evidence_id']==REA_ID)
if record['subject']['digest']['sha256']!=EXE_SHA256:raise ValueError('REA subject identity')
targets={0x5099e4,0x4f83e4,0x4f8181,0x4f83e0,0x438ba4}
for a,b in RANGES:
asm=subprocess.run(['objdump','-d','-Mintel',f'--start-address={a}',f'--stop-address={b}',str(p.path)],capture_output=True,text=True,check=True).stdout
targets.update(int(v,16) for v in re.findall(r'ds:0x([0-9a-f]+)',asm))
out.mkdir(parents=True,exist_ok=True)
body=Path(__file__).with_name('jimmy_skip_composition_probe.c').read_text().replace('/* RELOCATIONS */',','.join(hex(x) for x in sorted(targets)))
(out/'jimmy_skip_composition_probe.c').write_text(body)
r=dict(source_sha256=EXE_SHA256,rea_evidence_id=REA_ID,ranges=[dict(va=hex(a),file_offset=hex(p.offset(a-p.base)),length=b-a,sha256=hashlib.sha256(read_va(p,a,b-a)).hexdigest()) for a,b in RANGES],relocations=[hex(x) for x in sorted(targets)],scope='Original bounded input/controller/facing and skip-prefix composition; synthetic support/resources, base-facing shim; not full skip or original gameplay.')
(out/'source.json').write_text(json.dumps(r,indent=2)+'\n');return r
if __name__=='__main__':
c=argparse.ArgumentParser();c.add_argument('original',type=Path);c.add_argument('--output',type=Path,required=True);c.add_argument('--rea',type=Path,required=True);a=c.parse_args();print(json.dumps(generate(a.original,a.output,a.rea),indent=2))
@@ -0,0 +1,80 @@
/* Composed copied original input/controller/facing/skip-prefix routines.
Synthetic supported Jimmy/menu/vtables, zero devices, no body/render/scheduler.
Base40E050 is replaced by actual facing43A420 only; motion/action methods are
recorded shims. This is not full original skip or gameplay execution. */
#define main unused_scalar_main
#include "grappler_scalar_probe.c"
#undef main
typedef struct {float x,y,z,w;} Vec;
static uintptr_t game[0x450/4],outer[0x190/4],menu[0x500/4];
static unsigned char menu_object[16];
static int actions,moves,stops;
static LONG CALLBACK exception(EXCEPTION_POINTERS*e){fprintf(stderr,"PROBE_EXCEPTION pc=%lx relative=%lx code=%lx\n",e->ContextRecord->Eip,e->ContextRecord->Eip-(uintptr_t)mapped+0x400000,e->ExceptionRecord->ExceptionCode);fprintf(stderr,"fault=%lx eax=%lx ecx=%lx edx=%lx esi=%lx esp=%lx\n",e->ExceptionRecord->ExceptionInformation[1],e->ContextRecord->Eax,e->ContextRecord->Ecx,e->ContextRecord->Edx,e->ContextRecord->Esi,e->ContextRecord->Esp);ExitProcess(2);return EXCEPTION_CONTINUE_SEARCH;}
#define OF(o) (*(float*)(object+(o)))
#define GF(o) OF(0xc0+(o))
#define MODE (*(short*)(object+0x7c4))
static void fix(uint32_t a,uint32_t b){
const uint32_t targets[]={/* RELOCATIONS */};
for(;a+4<=b;a++){uint32_t v;memcpy(&v,AT(a),4);for(unsigned i=0;i<sizeof(targets)/4;i++)if(v==targets[i]){v=(uintptr_t)AT(v);memcpy(AT(a),&v,4);a+=3;break;}}
}
static int TC yes(void*self){(void)self;return 1;}
static int TC no(void*self){(void)self;return 0;}
static void TC noop(void*self){(void)self;}
static const char*TC current_action(void*self){(void)self;return "STOP";}
static int compare_action(const char*a,const char*b){(void)a;(void)b;return 1;}
static void TC action(void*self,const char*name){(void)self;(void)name;actions++;}
static void TC motion(void*self,float dt){(void)self;(void)dt;moves++;}
static void TC base(void*self,float dt){((void(TC*)(void*,float))AT(0x43a420))(self,dt);}
static void mouse(short*x,short*y){*x=*y=0;}
static void*lookup(const char*tag){(void)tag;puts("CALL lookup");return object+0xc0;}
static void stop(int handle,int release){puts("CALL stop");(void)handle;(void)release;stops++;}
static void*entry(uint32_t start,uint32_t end,int ground){
unsigned char*c=VirtualAlloc(NULL,256,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE),*p=c;require(c!=NULL,"wrapper");
emit_byte(&p,0x53);emit_byte(&p,0x55);emit_byte(&p,0x56);emit_byte(&p,0x57);emit_byte(&p,0x81);emit_byte(&p,0xec);word(&p,0x90);
emit_byte(&p,0x31);emit_byte(&p,0xdb);emit_byte(&p,0xbe);word(&p,(uintptr_t)object);
if(ground){emit_byte(&p,0xbd);word(&p,(uintptr_t)object);emit_byte(&p,0x31);emit_byte(&p,0xff);emit_byte(&p,0xba);word(&p,1);emit_byte(&p,0x31);emit_byte(&p,0xf6);emit_byte(&p,0xbb);word(&p,(uintptr_t)(object+0x9bc));
const int slots[]={0x14,0x18,0x1c};for(int i=0;i<3;i++){emit_byte(&p,0xc7);emit_byte(&p,0x44);emit_byte(&p,0x24);emit_byte(&p,slots[i]);word(&p,0);}}
jump(p,AT(start));p+=5;unsigned char*exit=p;emit_byte(&p,0x81);emit_byte(&p,0xc4);word(&p,0x90);emit_byte(&p,0x5f);emit_byte(&p,0x5e);emit_byte(&p,0x5d);emit_byte(&p,0x5b);emit_byte(&p,0xc3);jump(AT(end),exit);return c;
}
static void(*ground_input)(void);
static void TC ground(void*self,float dt){(void)self;(void)dt;ground_input();}
static void snap(const char*phase){
printf("STATE %s mode=%d turn=%.9g current=%.9g,%.9g,%.9g target=%.9g,%.9g,%.9g dirty=%u latch=%u skip=%u actions=%d moves=%d stops=%d\n",phase,MODE,OF(0x6d4),GF(0x224),GF(0x228),GF(0x22c),GF(0x274),GF(0x278),GF(0x27c),object[0xca],object[0x1e00],*AT(0x4f83e4),actions,moves,stops);
}
static void one(int after,int skip,int sign,void(*skip_prefix)(void),void(*flatten)(void)){
memset(object,0,sizeof(object));*(void**)object=outer;*(void**)(object+0xc0)=game;
memset(AT(0x509830),0,0x1d0);*(short*)AT(0x4f0588)=-1;*AT(0x4f8181)=*AT(0x4f83e0)=*AT(0x4f83e4)=0;
*(void**)AT(0x5099e4)=object+0xc0;object[0xc5]=1;object[0xca]=1;
OF(0x6bc)=30;OF(0x6c0)=35;OF(0x6c4)=600;OF(0x6d4)=sign*11.666668f;object[0x6e6]=1;MODE=1;
GF(0x224)=343;GF(0x228)=155;GF(0x22c)=sign>0?357:3;GF(0x274)=-40;GF(0x278)=153;GF(0x27c)=-sign*11.666668f;
*(void**)(object+0xa18)=menu_object;*(int*)(object+0xa3c)=-1;
actions=moves=stops=0;
printf("CASE order=%s skip=%d sign=%d\n",after?"retained":"fresh",skip,sign);snap("before_entry");
flatten();snap("after_entry");
((void(TC*)(void*,void*))AT(0x475a40))(NULL,NULL);
for(int i=0;i<180;i++)((void(TC*)(void*,float))AT(0x437940))(object+0xc0,1.f/60);
snap("locked");
if(skip)skip_prefix();
snap("after_skip_prefix");
((void(TC*)(void*,void*))AT(0x475a40))(NULL,object+0xc0);*AT(0x4f83e4)=0;snap("control_granted");
if(after){((void(TC*)(void*,float))AT(0x437940))(object+0xc0,1.f/60);snap("first_player");((void(TC*)(void*,float))AT(0x438a60))(object+0xc0,1.f/60);snap("first_input");}
else {((void(TC*)(void*,float))AT(0x438a60))(object+0xc0,1.f/60);snap("first_input");((void(TC*)(void*,float))AT(0x437940))(object+0xc0,1.f/60);snap("first_player");}
for(int i=0;i<300;i++){
if(after)((void(TC*)(void*,float))AT(0x437940))(object+0xc0,1.f/60);
((void(TC*)(void*,float))AT(0x438a60))(object+0xc0,1.f/60);
if(!after)((void(TC*)(void*,float))AT(0x437940))(object+0xc0,1.f/60);
}snap("after_idle");
}
int main(void){
setbuf(stdout,NULL);map_source();AddVectoredExceptionHandler(1,exception);
const uint32_t ranges[][2]={{0x437940,0x437c3a},{0x438a60,0x438ba2},{0x439900,0x439e33},{0x43915d,0x4395cf},{0x43a420,0x43a5cd},{0x472480,0x472570},{0x475a40,0x475a4c},{0x431518,0x431590},{0x430f1d,0x430f5c},{0x429910,0x429963}};
for(unsigned i=0;i<sizeof(ranges)/sizeof(ranges[0]);i++)fix(ranges[i][0],ranges[i][1]);
for(unsigned i=0;i<4;i++){uint32_t*v=(void*)AT(0x438ba4+i*4);*v=(uintptr_t)AT(*v);}
const unsigned char ready[]={0xb0,1,0xc3};memcpy(AT(0x475ca0),ready,3);jump(AT(0x40e050),base);jump(AT(0x46a460),mouse);jump(AT(0x474070),lookup);jump(AT(0x47d7a0),stop);jump(AT(0x487c20),compare_action);
const unsigned char air_return[]={0x5f,0x5e,0x5d,0x5b,0x83,0xc4,0x7c,0xc2,4,0};memcpy(AT(0x439e33),air_return,sizeof(air_return));
game[0x218/4]=(uintptr_t)yes;game[0x328/4]=(uintptr_t)AT(0x4723f0);game[0x32c/4]=(uintptr_t)AT(0x472450);game[0x334/4]=(uintptr_t)AT(0x458f90);game[0x36c/4]=(uintptr_t)AT(0x472660);game[0x26c/4]=(uintptr_t)AT(0x471b60);
outer[0x100/4]=(uintptr_t)current_action;outer[0x124/4]=(uintptr_t)ground;outer[0x128/4]=(uintptr_t)AT(0x439900);outer[0x130/4]=(uintptr_t)motion;outer[0x134/4]=(uintptr_t)motion;outer[0x140/4]=(uintptr_t)AT(0x429910);outer[0x150/4]=(uintptr_t)action;outer[0x158/4]=(uintptr_t)no;outer[0x15c/4]=(uintptr_t)no;menu[0x488/4]=(uintptr_t)noop;*(void**)menu_object=menu;
ground_input=entry(0x43915d,0x4395cf,1);void(*skip_prefix)(void)=entry(0x430f1d,0x430f5c,0);void(*flatten)(void)=entry(0x431518,0x431590,0);
for(int after=0;after<2;after++)for(int skip=0;skip<2;skip++)for(int sign=-1;sign<=1;sign+=2)one(after,skip,sign,skip_prefix,flatten);
puts("JIMMY_SKIP_COMPOSITION_COMPLETE");return 0;
}
+245
View File
@@ -0,0 +1,245 @@
#!/usr/bin/env python3
"""Guard the original SCENE60 task broadcast and prepare a bounded probe.
The native probe executes assignment/dispatch and the objective leaf, with
explicit synthetic task/registry lists and callback adapters. It does not
execute every matching lab actor callback or the full skip/resume frame.
"""
import argparse
import hashlib
import json
from pathlib import Path
import re
import struct
import sys
from checkpoint_script_state import EXE_SHA256, find_case, read_va, rel_call_target
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels'))
import gam
REA_ID = 'ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904'
CALLS = (
('Carl progress queries SCENE', 0x413e5a, 0x45fea0),
('Carl progress SCENE50 to60', 0x413e9d, 0x45f990),
('task objective prephase', 0x45fb5b, 0x406f50),
('registry task-name comparison', 0x45fbc8, 0x487c20),
('Carl callback queries new SCENE', 0x413f3d, 0x45fea0),
('Carl callback generic activation', 0x413f4e, 0x40e340),
('generic callback task-state store', 0x40e349, 0x458880),
)
SITES = (
('SCENE name comparison operand', 0x45f9b5, '6820d24e00'),
('SCENE milestone switch', 0x45f9ec, '8a8848fc4500'),
('SCENE milestone jump table', 0x45f9f2, 'ff248df0fb4500'),
('SCENE60 objective arguments', 0x45fa0b, '6a016a03'),
('task record state mutation', 0x45fb7f, '895f64'),
('registry authored task name', 0x45fb9b, '8d8630040000'),
('skip nonmatching task callback', 0x45fbd0, '85c0750b'),
('matching task callback', 0x45fbd9, 'ff9024040000'),
('objective flags clear', 0x406f59, 'b92c00000033c0bf007d4f00f3ab'),
('objective selected id', 0x406f6b, '891594814f00'),
('objective timer clear', 0x406f76, 'c70588814f0000000000'),
('objective indexed enable', 0x406f80, '890495007d4f00'),
('plain task-state store', 0x458884, '898194040000c20400'),
('Carl lab branch', 0x414068, '85db0f8c9800000083fb3c'),
('Carl marker state', 0x4140aa, '6a06ff9024010000'),
('Carl marker root copy on own interface', 0x4140dc, '8b168bceff9214030000'),
('generic no-op callback', 0x472970, 'c3'),
)
SLOTS = (
('Jimmy post-task hook', 0x4a373c, 0x420, 0x472970),
('Jimmy task-state callback', 0x4a373c, 0x424, 0x40e340),
('Carl task-state callback', 0x495364, 0x424, 0x413f30),
('Carl post-task hook', 0x495364, 0x420, 0x413eb0),
('Carl own root setter', 0x495364, 0x314, 0x472360),
('Carl own AI-state setter', 0x495804, 0x124, 0x4089b0),
)
RANGES = (
('task assignment and dispatch', 0x45f990, 0x45fbef),
('objective leaf', 0x406f50, 0x406f89),
('plain task-state store', 0x458880, 0x45888d),
('task query', 0x45fea0, 0x45fedb),
('generic animated callback', 0x40e340, 0x40e3d3),
('Carl progress', 0x413e50, 0x413ea6),
('Carl task-state callback', 0x413f30, 0x414121),
('AIT task-state callback', 0x40ca80, 0x40caa0),
('pickup task-state callback', 0x45f2b0, 0x45f3a8),
('rocket task-state callback', 0x43ebb0, 0x43ec0a),
('animated activation', 0x40e3e0, 0x40e495),
('Carl animation preparation', 0x413d60, 0x413e4d),
('Carl AI state setter', 0x4089b0, 0x408b93),
('own root setter', 0x472360, 0x472384),
('own pickup-active setter', 0x471980, 0x47198d),
('own collision flag setter', 0x471a40, 0x471a4d),
('own animation-collision setter', 0x471a00, 0x471a0d),
('disable own collision', 0x473030, 0x47303b),
('enable own collision', 0x4730e0, 0x4730eb),
)
# JN-Engine class/constructor inventories supplied leads. Every table store,
# FourCC registration argument and virtual target below is checked against the
# authoritative original and retained REA instruction Evidence.
KINDS = (
# kind, game table, task callback, ctor table-immediate, FourCC push,
# complete table, complete activation hook (where applicable)
('3ROC', 0x4b25ac, 0x43ebb0, 0x43d8ba, 0x43d916, 0x4b2a4c, 0x472970),
('3CAR', 0x495364, 0x413f30, 0x413b6a, 0x413bb3, 0x495804, 0x413d60),
('3PIC', 0x4ae548, 0x45f2b0, 0x435928, 0x435971, None, None),
('3PAT', 0x4acee4, 0x458880, 0x434ba0, 0x434be7, None, None),
('3AIT', 0x48f8c0, 0x40ca80, 0x40bae0, 0x40bb27, None, None),
('LOAD', 0x4d025c, 0x458880, 0x457b80, 0x457bc7, None, None),
('STRT', 0x4b7654, 0x458880, 0x442351, 0x442398, None, None),
('3DUD', 0x4993ac, 0x40e340, 0x417572, 0x41764e, 0x49984c, 0x472970),
('3BUT', 0x493b60, 0x40e340, 0x41163a, 0x411748, 0x494000, 0x472970),
('3LIO', 0x4a686c, 0x458880, 0x42dc10, 0x42dc57, None, None),
('3TEL', 0x4ba49c, 0x40e340, 0x44567e, 0x445709, 0x4ba93c, 0x472970),
('3ANI', 0x4903f8, 0x45f2b0, 0x40e8f0, 0x40e937, None, None),
('3CAM', 0x497bfc, 0x458880, 0x415a7b, 0x415abd, None, None),
('3MCA', 0x4a8f64, 0x458880, 0x43094b, 0x43098d, None, None),
('3OMT', 0x4ac3b4, 0x40e340, 0x4345aa, 0x434646, 0x4ac854, 0x472970),
('3SOU', 0x4b59b0, 0x458880, 0x440e90, 0x440ed7, None, None),
('3NEU', 0x4aacdc, 0x458880, 0x432a10, 0x432a53, None, None),
)
def local_gate(fields, state, pickup):
"""Static authored level gate; it does not reconstruct runtime visibility."""
exact = fields.get('ExactLevel', -1)
required = fields.get('RequiredLevel', -1)
removed = fields.get('RemoveLevel', -1)
if exact != -1:
enabled = state == exact
elif required == -1:
return 'preserve existing state'
else:
enabled = state >= required and (pickup or removed == -1 or state < removed)
qualifier = 'if pickup state is uncollected' if pickup else 'own actor'
return ('enable' if enabled else 'disable')+' '+qualifier
def collect(original, rea):
original = Path(original)
pe = PE(find_case(original, 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unexpected original executable')
record = next(r for r in json.loads(Path(rea).read_text())['records']
if r['evidence_id'] == REA_ID)
if record['subject']['digest']['sha256'] != EXE_SHA256:
raise ValueError('Retained REA subject mismatch')
calls, sites, slots = [], [], []
for name, va, target in CALLS:
if rel_call_target(pe, va) != target:
raise ValueError(f'Changed direct call: {name}')
calls.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
target=hex(target)))
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
if actual != expected:
raise ValueError(f'Changed source site: {name}: {actual}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
bytes=actual))
for name, table, slot, target in SLOTS:
actual, = struct.unpack('<I', read_va(pe, table+slot, 4))
if actual != target:
raise ValueError(f'Changed virtual binding: {name}')
slots.append(dict(name=name, table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base))))
objective_index = read_va(pe, 0x45fc48+(60-35), 1)[0]
objective_target, = struct.unpack('<I', read_va(pe, 0x45fbf0+objective_index*4, 4))
if objective_index != 2 or objective_target != 0x45fa0b:
raise ValueError('Changed SCENE60 objective dispatch')
level_path = find_case(original, 'gam/level1b.gam')
level_bytes = level_path.read_bytes()
level = gam.parse(level_bytes)
kind_bindings = []
by_kind = {}
for kind, table, target, store, registration, complete, hook in KINDS:
actual, = struct.unpack('<I', read_va(pe, table+0x424, 4))
immediate, = struct.unpack('<I', read_va(pe, store, 4))
if actual != target or immediate != table:
raise ValueError(f'Changed {kind} constructor/task callback binding')
if read_va(pe, registration, 5) != b'\x68'+kind.encode('ascii')[::-1]:
raise ValueError(f'Changed {kind} registration argument')
if complete is not None:
if struct.unpack('<I', read_va(pe, complete+0x10c, 4))[0] != hook:
raise ValueError(f'Changed {kind} activation hook')
if struct.unpack('<I', read_va(pe, complete+0x110, 4))[0] != 0x40e3e0:
raise ValueError(f'Changed {kind} activation callback')
binding = dict(kind=kind, table=hex(table), slot='0x424', target=hex(target),
file_offset=hex(pe.offset(table+0x424-pe.base)),
constructor_table_immediate=hex(store),
constructor_table_file_offset=hex(pe.offset(store-pe.base)),
fourcc_registration_argument=hex(registration),
fourcc_registration_file_offset=hex(pe.offset(registration-pe.base)))
if complete is not None:
binding.update(complete_table=hex(complete), activation_hook=hex(hook))
kind_bindings.append(binding)
by_kind[kind] = binding
authored = []
matching = []
for index, entity in enumerate(level.entities):
fields = entity.values()
task = str(fields.get('TaskName', ''))
if task.casefold() == 'scene':
if entity.kind not in by_kind:
raise ValueError(f'Unmapped matching task actor kind: {entity.kind}')
gates = {k: fields[k] for k in ('RequiredLevel', 'ExactLevel', 'RemoveLevel',
'PickupIndex', 'InitallyActive', 'InitallyVisible', 'Activated') if k in fields}
target = by_kind[entity.kind]['target']
transition = 'store supplied TaskState only'
if target == '0x40ca80':
transition = 'store supplied TaskState, query own task; no activation/trigger dispatch'
elif target in ('0x40e340', '0x413f30', '0x43ebb0', '0x45f2b0'):
pickup = target == '0x45f2b0'
transition = dict(old50=local_gate(fields, 50, pickup),
new60=local_gate(fields, 60, pickup),
scope='Authored gates only; runtime pickup/display/collision state is not observed.')
matching.append(dict(index=index, kind=entity.kind,
file_offset=hex(entity.offset), tag=fields.get('ObjectTag'),
task_callback=target, authored_gates=gates,
transition=transition))
if str(fields.get('ObjectTag', '')).casefold() in ('jim1', 'c3dcarl'):
authored.append(dict(index=index, kind=entity.kind, file_offset=hex(entity.offset),
fields=fields))
if not any(str(e['fields'].get('ObjectTag', '')).casefold() == 'jim1'
and str(e['fields'].get('TaskName', '')).casefold() == 'none'
for e in authored):
raise ValueError('Actual lab Jimmy no longer has TaskName none')
rows = []
for line in record['raw_result']['stdout'].splitlines():
match = re.match(r'\s*([0-9a-f]+):', line)
if match:
rows.append((int(match[1], 16), line))
extracts = {name: '\n'.join(line for va, line in rows if a <= va < b)+'\n'
for name, a, b in RANGES}
if any(not value.strip() for value in extracts.values()):
raise ValueError('Retained REA lacks an inspected boundary')
return dict(source_sha256=EXE_SHA256, rea_evidence_id=REA_ID, calls=calls, sites=sites,
slots=slots, scene60_objective=dict(index=objective_index, target=hex(objective_target)),
ranges=[dict(name=name, va=hex(a), file_offset=hex(pe.offset(a-pe.base)),
length=b-a, sha256=hashlib.sha256(read_va(pe, a, b-a)).hexdigest())
for name, a, b in RANGES],
gam_sha256=hashlib.sha256(level_bytes).hexdigest(), authored_actors=authored,
matching_scene_records=matching, kind_bindings=kind_bindings,
rea_extracts=extracts,
scope='Static task/objective/callback ownership; native probe callbacks are explicit '
'adapters, not all authored matching actors or complete Carl skip/resume.')
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
cli.add_argument('--rea', required=True, type=Path)
cli.add_argument('--output', required=True, type=Path)
args = cli.parse_args()
result = collect(args.original, args.rea)
original, output = args.original.resolve(), args.output.resolve()
if output.is_relative_to(original) or original.is_relative_to(output):
raise ValueError('Output must be separate from originals')
output.mkdir(parents=True, exist_ok=True)
for name in ('jimmy_task_return_probe.c', 'grappler_scalar_probe.c'):
(output/name).write_text(Path(__file__).with_name(name).read_text())
(output/'source.json').write_text(json.dumps(result, indent=2)+'\n')
print(json.dumps({k: v for k, v in result.items() if k != 'rea_extracts'}, indent=2))
+60
View File
@@ -0,0 +1,60 @@
/* Original task assignment/dispatch + objective leaf. Synthetic registry/task
list; native case-insensitive comparison and callbacks are explicit adapters.
No game entrypoint, full Carl callback, skip, physics, input or renderer. */
#define main unused_grappler_main
#include "grappler_scalar_probe.c"
#undef main
static unsigned char jimmy[0x1f00],carl[0x1000],record[0x68];
static uintptr_t task_head[3],task_node[3],registry_head[3],registry_node[2][3];
static uintptr_t jimmy_table[0x428/4],carl_table[0x428/4];
static int jimmy_calls,carl_calls,expected_new;
static int compare(const char*a,const char*b){return _stricmp(a,b);}
static void TC callback(void*self,int value){
require(value==expected_new&&*(int*)(record+0x64)==expected_new,"callback sees assigned task state");
require(*(int*)AT(0x4f8194)==3&&*(int*)AT(0x4f7d00+3*4)==1,"objective prephase completed");
if(self==jimmy+0xc0)jimmy_calls++;else{require(self==carl+0xc0,"callback owner");carl_calls++;}
((void(TC*)(void*,int))AT(0x458880))(self,value);
}
static void fix(uint32_t start,uint32_t end){
const uint32_t refs[]={0x4ed220,0x45fc48,0x45fbf0,0x45fd98,0x45fd40,0x4fc5fc,0x50999c,
0x4f7d00,0x4f8194,0x4f8188};
for(uint32_t a=start;a+4<=end;a++){
uint32_t value;memcpy(&value,AT(a),4);
for(unsigned i=0;i<sizeof(refs)/sizeof(refs[0]);i++)if(value==refs[i]){
value=(uintptr_t)AT(value);memcpy(AT(a),&value,4);a+=3;break;
}
}
}
int main(void){
setbuf(stdout,NULL);map_source();fix(0x45f990,0x45fbef);fix(0x406f50,0x406f89);
for(unsigned i=0;i<22;i++){uint32_t*v=(void*)AT(0x45fbf0+4*i);*v=(uintptr_t)AT(*v);}
jump(AT(0x487c20),compare);
jimmy_table[0x424/4]=carl_table[0x424/4]=(uintptr_t)callback;
int cases=0;
for(int gate=0;gate<2;gate++)for(int task=0;task<2;task++)for(int old=50;old<=60;old+=10)
for(int mode=0;mode<2;mode++)for(int turn=-12;turn<=12;turn+=12){
memset(jimmy,0xa5,sizeof(jimmy));memset(carl,0,sizeof(carl));memset(record,0,sizeof(record));
*(void**)(jimmy+0xc0)=jimmy_table;*(void**)(carl+0xc0)=carl_table;
strcpy((char*)jimmy+0xc0+0x430,task?"SCENE":"none");strcpy((char*)carl+0xc0+0x430,"scene");
*(short*)(jimmy+0xc0+0x704)=(short)mode;*(float*)(jimmy+0xc0+0x614)=(float)turn;
strcpy((char*)record,"SCENE");*(int*)(record+0x64)=old;
task_head[0]=task_head[1]=(uintptr_t)task_node;task_node[0]=task_node[1]=(uintptr_t)task_head;
task_node[2]=(uintptr_t)record;*(void**)AT(0x4fc5fc)=task_head;
registry_head[0]=(uintptr_t)registry_node[0];registry_head[1]=(uintptr_t)registry_node[1];
registry_node[0][0]=(uintptr_t)registry_node[1];registry_node[0][1]=(uintptr_t)registry_head;registry_node[0][2]=(uintptr_t)jimmy+0xc0;
registry_node[1][0]=(uintptr_t)registry_head;registry_node[1][1]=(uintptr_t)registry_node[0];registry_node[1][2]=(uintptr_t)carl+0xc0;
*(void**)AT(0x50999c)=registry_head;
memset(AT(0x4f7d00),0xa5,0xb0);*(int*)AT(0x4f8194)=-1;F(0x4f8188)=123;
*AT(0x4f8198)=(unsigned char)gate;*AT(0x4f8430)=(unsigned char)gate;
unsigned char before[sizeof(jimmy)];memcpy(before,jimmy,sizeof(jimmy));
if(task)*(int*)(before+0xc0+0x494)=60;
expected_new=60;jimmy_calls=carl_calls=0;
((void(*)(const char*,int))AT(0x45f990))("sCeNe",60);
require(carl_calls==1&&jimmy_calls==task,"exact task-name callback admission");
require(memcmp(before,jimmy,sizeof(jimmy))==0,"exact Jimmy write set: only matching TaskState");
require(F(0x4f8188)==0&&*AT(0x4f8198)==gate&&*AT(0x4f8430)==gate,"objective timer reset without modal/input flag");
cases++;
}
printf("TASK_RETURN {\"cases\":%d,\"actual_none_task_skips_jimmy\":true,\"modal_unchanged\":true}\n",cases);
puts("JIMMY_TASK_RETURN_COMPLETE");return 0;
}
+43
View File
@@ -0,0 +1,43 @@
/* Wine-only integration driver, executed by reference_capture.py --asset-probe.
The wrapper supplies /work/game as a generated copy and hides Original.
Tests actual attach/read/leave-running behavior; no target memory writes.
Place the separately built observer at /work/observer-under-test.exe. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <string.h>
static BOOL CALLBACK close_owned(HWND window, LPARAM pid) {
DWORD owner = 0;
GetWindowThreadProcessId(window, &owner);
if (owner == (DWORD)pid && IsWindowVisible(window)) PostMessageA(window, WM_CLOSE, 0, 0);
return TRUE;
}
int main(void) {
STARTUPINFOA start = {0};
PROCESS_INFORMATION game = {0}, observer = {0};
char cwd[MAX_PATH], command[256];
DWORD code = 1, game_code = 0;
setbuf(stdout, NULL);
/* This driver deliberately works only at the generated Wine wrapper path. */
if (!GetCurrentDirectoryA(sizeof(cwd), cwd) || _stricmp(cwd, "Z:\\work\\game")) return 2;
start.cb = sizeof(start);
strcpy(command, "NeutronHDnoCD.exe");
if (!CreateProcessA(command, command, NULL, NULL, FALSE, 0, NULL, cwd, &start, &game)) return 3;
CloseHandle(game.hThread);
Sleep(1000);
snprintf(command, sizeof(command), "Z:\\work\\observer-under-test.exe --attach-copied-pid=%lu --seconds=10", game.dwProcessId);
if (!CreateProcessA("Z:\\work\\observer-under-test.exe", command, NULL, NULL, FALSE, 0, NULL, cwd, &start, &observer)) return 4;
CloseHandle(observer.hThread);
if (WaitForSingleObject(observer.hProcess, 20000) != WAIT_OBJECT_0) return 5;
GetExitCodeProcess(observer.hProcess, &code);
GetExitCodeProcess(game.hProcess, &game_code);
printf("OBSERVER_ATTACH_EXIT %lu ORIGINAL_STILL_RUNNING %d\n", code, game_code == STILL_ACTIVE);
/* Only the launcher-owned game receives an ordinary close, after the test. */
EnumWindows(close_owned, game.dwProcessId);
CloseHandle(observer.hProcess); CloseHandle(game.hProcess);
if (code || game_code != STILL_ACTIVE) return 6;
puts("ORIGINAL_OBSERVER_ATTACH_COMPLETE");
return 0;
}
+407
View File
@@ -0,0 +1,407 @@
/* Read-only, sampled original-state observer. It never patches target memory.
Launch only a generated game copy, with an explicitly attested path.
Build: i686-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror
tools/recon/original_state_observer.c -lbcrypt -o observer.exe
See docs/gameplay/original-state-observer.md for source identity and limits. */
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0601
#include <windows.h>
#include <bcrypt.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
#define MAX_NODES 1024
#define GAME_BYTES 0x1d44
#define CANONICAL_SHA "f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8"
#define HD_SHA "b6675b7e7f3fc37512185ddb4d6ce1fbe9a36c8b83f3b4b3ed6979a56db3d2d4"
#define HD_NOCD_SHA "8cd5d21997835a40978b8b83e344c97c92217bf6cd6858f7458b76935d64dedb"
typedef struct {
const char *name, *sha;
uint32_t owner, registry, dt, current, skip, input, modal, suppression;
} Profile;
static const Profile profiles[] = {
{"canonical",CANONICAL_SHA,0x5099e4,0x50999c,0x696030,0x509948,0x4f83e4,0x4f8430,0x4f8198,0x4f8182},
{"hd-resolution",HD_SHA,0x5099e4,0x50999c,0x696030,0x509948,0x4f83e4,0x4f8430,0x4f8198,0x4f8182},
{"hd-nocd",HD_NOCD_SHA,0x509a04,0x5099bc,0x696050,0x509968,0x4f8404,0x4f8450,0x4f81b8,0x4f81a2}
};
typedef struct { uint32_t payload, vtable; } Node;
typedef struct {
uint32_t sentinel, current, owner, jimmy, count;
int current_index, jimmy_index, registry_complete;
Node nodes[MAX_NODES];
} Registry;
static int read_memory(HANDLE process, uint32_t address, void *dest, SIZE_T length) {
SIZE_T got = 0;
return address >= 0x10000 &&
ReadProcessMemory(process, (const void *)(uintptr_t)address, dest, length, &got) &&
got == length;
}
static uint32_t u32(const unsigned char *p) {
return (uint32_t)p[0] | (uint32_t)p[1]<<8 | (uint32_t)p[2]<<16 | (uint32_t)p[3]<<24;
}
static float f32(const unsigned char *p) {
uint32_t bits = u32(p);
float value;
memcpy(&value, &bits, sizeof(value));
return value;
}
static void json_float(float value) {
if (isfinite(value)) printf("%.9g", (double)value);
else fputs("null", stdout);
}
static void json_string(const char *s) {
putchar('"');
for (; *s; ++s) {
unsigned char c = (unsigned char)*s;
if (c == '\\' || c == '"') printf("\\%c", c);
else if (c < 32 || c >= 127) printf("\\u%04x", (unsigned)c);
else putchar(c);
}
putchar('"');
}
static int original_component(const char *path) {
while (*path) {
const char *begin;
size_t length;
while (*path == '\\' || *path == '/') ++path;
begin = path;
while (*path && *path != '\\' && *path != '/') ++path;
length = (size_t)(path-begin);
if (length == 8 && !_strnicmp(begin, "Original", 8)) return 1;
}
return 0;
}
static int sha256(HANDLE file, char hex[65]) {
BCRYPT_ALG_HANDLE alg = NULL;
BCRYPT_HASH_HANDLE hash = NULL;
unsigned char buffer[16384], digest[32];
DWORD got;
LARGE_INTEGER zero;
int ok = 0;
zero.QuadPart = 0;
if (!SetFilePointerEx(file, zero, NULL, FILE_BEGIN) ||
BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, NULL, 0) < 0 ||
BCryptCreateHash(alg, &hash, NULL, 0, NULL, 0, 0) < 0) goto done;
for (;;) {
if (!ReadFile(file, buffer, sizeof(buffer), &got, NULL)) goto done;
if (!got) break;
if (BCryptHashData(hash, buffer, got, 0) < 0) goto done;
}
if (BCryptFinishHash(hash, digest, sizeof(digest), 0) < 0) goto done;
for (unsigned i = 0; i < sizeof(digest); ++i) sprintf(hex+2*i, "%02x", digest[i]);
hex[64] = 0;
ok = 1;
done:
if (hash) BCryptDestroyHash(hash);
if (alg) BCryptCloseAlgorithmProvider(alg, 0);
return ok;
}
/* The allow-listed hashes authenticate these anchors and all source offsets.
Retain an independent anchor check to detect an incorrectly mapped image. */
static int operand_guard(HANDLE process, uint32_t pc, const unsigned char *expected,
size_t length, unsigned operand, uint32_t address) {
unsigned char actual[16], guarded[16];
if (length > sizeof(actual) || operand+4 > length) return 0;
memcpy(guarded, expected, length);
for (unsigned i = 0; i < 4; ++i) guarded[operand+i] = (unsigned char)(address>>(8*i));
return read_memory(process, pc, actual, length) && !memcmp(actual, guarded, length);
}
static int runtime_identity(HANDLE process, const Profile *p) {
static const unsigned char setter[] = {0x8b,0x44,0x24,0x04,0xa3,0,0,0,0,0xc2,0x04,0x00};
static const unsigned char registry[] = {0xa1,0,0,0,0,0x56,0x8b,0x30};
static const unsigned char dt[] = {0x8b,0x15,0,0,0,0};
static const unsigned char current[] = {0xa3,0,0,0,0};
static const unsigned char skip[] = {0xc6,0x05,0,0,0,0,1};
static const unsigned char input[] = {0xa0,0,0,0,0};
static const unsigned char suppression[] = {0x38,0x1d,0,0,0,0};
return operand_guard(process,0x475a40,setter,sizeof(setter),5,p->owner) &&
operand_guard(process,0x473740,registry,sizeof(registry),1,p->registry) &&
operand_guard(process,0x47374f,dt,sizeof(dt),2,p->dt) &&
operand_guard(process,0x46e360,current,sizeof(current),1,p->current) &&
operand_guard(process,0x430f3e,skip,sizeof(skip),2,p->skip) &&
operand_guard(process,0x426062,input,sizeof(input),1,p->input) &&
operand_guard(process,0x407060,input,sizeof(input),1,p->modal) &&
operand_guard(process,0x430f11,suppression,sizeof(suppression),2,p->suppression);
}
static void registry_snapshot(HANDLE process, const Profile *profile, Registry *r) {
uint32_t next, node[3];
memset(r, 0, sizeof(*r));
r->current_index = r->jimmy_index = -1;
if (!read_memory(process, profile->current, &r->current, 4) ||
!read_memory(process, profile->owner, &r->owner, 4) ||
!read_memory(process, profile->registry, &r->sentinel, 4) ||
!read_memory(process, r->sentinel, &next, 4)) return;
while (next != r->sentinel && r->count < MAX_NODES) {
if (!read_memory(process, next, node, sizeof(node))) return;
for (uint32_t i = 0; i < r->count; ++i)
if (r->nodes[i].payload == node[2]) return; /* concurrent mutation/cycle */
r->nodes[r->count].payload = node[2];
if (!read_memory(process, node[2], &r->nodes[r->count].vtable, 4)) return;
if (node[2] == r->current+0x8c) r->current_index = (int)r->count;
if (r->nodes[r->count].vtable == 0x4a373c) {
r->jimmy = node[2];
r->jimmy_index = (int)r->count;
}
++r->count;
next = node[0];
}
r->registry_complete = next == r->sentinel;
}
static void print_registry(const Registry *r, ULONGLONG elapsed) {
printf("{\"kind\":\"registry\",\"elapsed_ms\":%llu,\"complete\":%s,\"sentinel\":%lu,"
"\"current_game\":%lu,\"raw_owner\":%lu,\"jimmy\":%lu,\"game_index\":%d,\"jimmy_index\":%d,\"nodes\":[",
(unsigned long long)elapsed, r->registry_complete ? "true" : "false",
(unsigned long)r->sentinel, (unsigned long)r->current, (unsigned long)r->owner,
(unsigned long)r->jimmy, r->current_index, r->jimmy_index);
for (uint32_t i = 0; i < r->count; ++i)
printf("%s[%lu,%lu]", i ? "," : "", (unsigned long)r->nodes[i].payload,
(unsigned long)r->nodes[i].vtable);
puts("]}");
}
static void vector(const unsigned char *p) {
putchar('[');
for (unsigned i = 0; i < 4; ++i) { if (i) putchar(','); json_float(f32(p+4*i)); }
putchar(']');
}
static void print_sample(HANDLE process, const Profile *profile, const Registry *r, ULONGLONG elapsed) {
unsigned char actor[GAME_BYTES], flags[4], dt[4];
const uint32_t addresses[] = {profile->skip,profile->input,profile->modal,profile->suppression};
unsigned valid = 0;
memset(actor, 0, sizeof(actor));
memset(flags, 0, sizeof(flags));
memset(dt, 0, sizeof(dt));
for (unsigned i = 0; i < 4; ++i)
if (read_memory(process, addresses[i], flags+i, 1)) valid |= 1u<<i;
if (read_memory(process, profile->dt, dt, 4)) valid |= 16;
if (r->jimmy && read_memory(process, r->jimmy, actor, sizeof(actor))) valid |= 32;
printf("{\"kind\":\"sample\",\"elapsed_ms\":%llu,\"valid_mask\":%u,\"raw_owner\":%lu,\"current_game\":%lu,\"jimmy\":%lu,\"dt\":",
(unsigned long long)elapsed, valid, (unsigned long)r->owner,
(unsigned long)r->current, (unsigned long)r->jimmy);
json_float(f32(dt));
printf(",\"shared_skip\":%u,\"input_block\":%u,\"modal_gate\":%u,\"skip_suppression\":%u",
flags[0],flags[1],flags[2],flags[3]);
if (valid & 32) {
printf(",\"mode\":%d,\"turn\":", (int)(int16_t)(actor[0x704] | actor[0x705]<<8));
json_float(f32(actor+0x614));
printf(",\"dirty\":%u,\"action_latch\":%u,\"cached_support\":%u,\"force_support\":%u,\"current_euler\":",
actor[0xa], actor[0x1d40], actor[0x13f], actor[0x4a0]);
vector(actor+0x224);
fputs(",\"destination_euler\":", stdout); vector(actor+0x274);
}
puts("}");
}
static BOOL CALLBACK owned_window(HWND window, LPARAM parameter) {
DWORD pid;
DWORD *search = (DWORD *)parameter;
GetWindowThreadProcessId(window, &pid);
if (pid == search[0] && IsWindowVisible(window) && !GetWindow(window, GW_OWNER)) {
search[1] = (DWORD)(uintptr_t)window;
return FALSE;
}
return TRUE;
}
static HWND find_window(DWORD pid) {
DWORD search[2] = {pid, 0};
EnumWindows(owned_window, (LPARAM)search);
return (HWND)(uintptr_t)search[1];
}
static void menu_key(DWORD pid, ULONGLONG elapsed, int release) {
HWND window = find_window(pid);
HWND foreground;
INPUT event;
char title[256];
DWORD thread = window ? GetWindowThreadProcessId(window,NULL) : 0;
unsigned sent = 0;
memset(&event, 0, sizeof(event));
memset(title,0,sizeof(title));
if (window) GetWindowTextA(window,title,sizeof(title));
if (window && !release) {
int attached = thread != GetCurrentThreadId() && AttachThreadInput(GetCurrentThreadId(),thread,TRUE);
BringWindowToTop(window); SetForegroundWindow(window); SetActiveWindow(window); SetFocus(window);
if (attached) AttachThreadInput(GetCurrentThreadId(),thread,FALSE);
}
foreground = GetForegroundWindow();
if (release || (window && foreground == window)) {
event.type = INPUT_KEYBOARD; event.ki.wVk = VK_RETURN;
event.ki.dwFlags = release ? KEYEVENTF_KEYUP : 0;
sent = SendInput(1, &event, sizeof(INPUT));
}
printf("{\"kind\":\"normal_input\",\"elapsed_ms\":%llu,\"key\":\"Return\",\"release\":%s,\"events_sent\":%u,\"window\":%lu,\"foreground\":%lu,\"title\":",
(unsigned long long)elapsed, release?"true":"false",sent,
(unsigned long)(uintptr_t)window,(unsigned long)(uintptr_t)foreground);
json_string(title); puts("}");
}
static void usage(FILE *stream) {
fputs("Usage: observer.exe --copied-game=<generated-copy.exe> [--seconds=1..120] [--menu-keys]\n"
" observer.exe --copied-game-menu=<generated-copy.exe> (single-argument menu-input opt-in)\n"
" observer.exe --attach-copied-pid=<PID> [--seconds=1..120] (read-only, no input/close)\n"
"Each copied option explicitly attests that the selected executable is a generated copy outside Original.\n",stream);
}
int main(int argc, char **argv) {
char path[32768], final[32768], directory[32768], hash[65], command[32772];
HANDLE file;
STARTUPINFOA start;
PROCESS_INFORMATION child;
Registry previous, current;
unsigned seconds = 15, key_index = 0, samples = 0;
int keys = 0, previous_valid = 0, identified = 0;
DWORD attach_pid = 0;
int key_down = 0;
ULONGLONG key_began = 0;
const Profile *profile = NULL;
ULONGLONG began, elapsed;
DWORD exit_code = STILL_ACTIVE;
const char *target = NULL;
memset(&child,0,sizeof(child));
if (argc == 2 && !strcmp(argv[1],"--help")) { usage(stdout); return 0; }
if (argc >= 2 && !strncmp(argv[1], "--copied-game=", 14)) target=argv[1]+14;
else if (argc >= 2 && !strncmp(argv[1], "--copied-game-menu=", 19)) { target=argv[1]+19; keys=1; }
else if (argc >= 2 && !strncmp(argv[1], "--attach-copied-pid=", 20)) {
char *end;
const char *number=argv[1]+20;
errno=0;
unsigned long pid=strtoul(number,&end,10);
if (!isdigit((unsigned char)*number) || *end || errno || !pid) return 2;
attach_pid=(DWORD)pid;
}
if ((!target || !*target) && !attach_pid) {
usage(stderr);
return 2;
}
for (int i = 2; i < argc; ++i) {
char *end;
if (!strncmp(argv[i], "--seconds=", 10)) {
unsigned long n = strtoul(argv[i]+10, &end, 10);
if (*end || n < 1 || n > 120) return 2;
seconds = (unsigned)n;
} else if (!strcmp(argv[i], "--menu-keys")) keys = 1;
else return 2;
}
if (attach_pid && keys) {
fputs("Attach mode never sends input; remove --menu-keys.\n",stderr);
return 2;
}
setbuf(stdout, NULL);
DWORD length;
if (attach_pid) {
child.hProcess=OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,attach_pid);
if (!child.hProcess) { fprintf(stderr,"OpenProcess failed: %lu\n",GetLastError()); return 2; }
child.dwProcessId=attach_pid;
length=sizeof(path);
if (!QueryFullProcessImageNameA(child.hProcess,0,path,&length) || !length || length>=sizeof(path)) {
fprintf(stderr,"QueryFullProcessImageName failed: %lu\n",GetLastError());
CloseHandle(child.hProcess); return 2;
}
} else length=GetFullPathNameA(target, sizeof(path), path, NULL);
if (!length || length >= sizeof(path) || original_component(path)) {
fputs("Rejected target path: use an explicitly attested generated copy outside Original.\n", stderr);
if (child.hProcess) CloseHandle(child.hProcess);
return 2;
}
file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE) {
fprintf(stderr,"Cannot open copied game: %lu\n",GetLastError());
if (child.hProcess) CloseHandle(child.hProcess);
return 2;
}
LARGE_INTEGER size;
if (!GetFileSizeEx(file,&size) || size.QuadPart != 1019904) {
fputs("Rejected target size.\n",stderr); CloseHandle(file);
if (child.hProcess) CloseHandle(child.hProcess);
return 2;
}
length = GetFinalPathNameByHandleA(file, final, sizeof(final), FILE_NAME_NORMALIZED);
if (sha256(file, hash))
for (unsigned i = 0; i < sizeof(profiles)/sizeof(profiles[0]); ++i)
if (!strcmp(hash,profiles[i].sha)) profile = profiles+i;
if (!length || length >= sizeof(final) || original_component(final) || !profile) {
fputs("Rejected target identity/path; only explicitly supported verified source profiles are accepted.\n", stderr);
CloseHandle(file);
if (child.hProcess) CloseHandle(child.hProcess);
return 2;
}
/* Keep the authenticated file handle open without FILE_SHARE_WRITE/DELETE
through process creation, preventing target-file replacement after hashing. */
if (!attach_pid) {
strcpy(directory, path);
char *slash = strrchr(directory, '\\');
if (!slash) { CloseHandle(file); return 2; }
*slash = 0;
snprintf(command, sizeof(command), "\"%s\"", path);
memset(&start, 0, sizeof(start)); start.cb = sizeof(start);
if (!CreateProcessA(path, command, NULL, NULL, FALSE, 0, NULL, directory, &start, &child)) {
fprintf(stderr,"CreateProcess failed: %lu\n",GetLastError()); CloseHandle(file); return 2;
}
CloseHandle(child.hThread);
}
CloseHandle(file);
fputs("{\"kind\":\"identity\",\"target\":", stdout); json_string(path);
printf(",\"sha256\":\"%s\",\"profile\":\"%s\",\"pid\":%lu,\"attached\":%s,\"interval_ms\":10,\"duration_ms\":%u,\"scope\":\"read-only sampled process state; no callback-order or whole-frame guarantee\"}\n",
hash, profile->name, child.dwProcessId, attach_pid?"true":"false",seconds*1000);
began = GetTickCount64();
do {
elapsed = GetTickCount64()-began;
if (WaitForSingleObject(child.hProcess, 0) == WAIT_OBJECT_0) break;
if (!identified) {
identified = runtime_identity(child.hProcess,profile);
if (!identified && elapsed > 5000) {
fputs("{\"kind\":\"error\",\"reason\":\"runtime source anchors unavailable after 5s; sampling refused\"}\n",stdout);
break;
}
}
if (identified) {
registry_snapshot(child.hProcess,profile,&current);
if (!previous_valid || memcmp(&current, &previous, sizeof(current))) {
print_registry(&current, elapsed); previous = current; previous_valid = 1;
}
print_sample(child.hProcess,profile,&current,elapsed); ++samples;
}
if (!attach_pid && key_down && elapsed-key_began >= 100) {
menu_key(child.dwProcessId,elapsed,1); key_down=0;
}
if (!attach_pid && keys && !key_down && key_index < 3 && elapsed >= (ULONGLONG)(key_index+1)*3000) {
menu_key(child.dwProcessId,elapsed,0); ++key_index; key_began=elapsed; key_down=1;
}
Sleep(10);
} while (elapsed < seconds*1000);
if (!attach_pid && key_down) menu_key(child.dwProcessId,GetTickCount64()-began,1);
GetExitCodeProcess(child.hProcess, &exit_code);
printf("{\"kind\":\"finish\",\"elapsed_ms\":%llu,\"samples\":%u,\"identified\":%s,\"game_exit\":%lu,\"left_running\":%s}\n",
(unsigned long long)(GetTickCount64()-began), samples, identified?"true":"false",
exit_code, exit_code == STILL_ACTIVE ? "true" : "false");
/* Request ordinary shutdown only for this launcher-owned process. Do not
terminate it or enumerate/kill unrelated game or Wine processes. */
if (!attach_pid && exit_code == STILL_ACTIVE) {
HWND window = find_window(child.dwProcessId);
if (window) PostMessageA(window, WM_CLOSE, 0, 0);
}
CloseHandle(child.hProcess);
if (!identified || !samples) return 3;
puts("{\"kind\":\"complete\",\"marker\":\"ORIGINAL_STATE_OBSERVER_COMPLETE\"}");
return 0;
}
+17 -3
View File
@@ -7,6 +7,7 @@ writable inside the namespace, and the original directory is not mounted.
"""
import argparse
import ctypes
import hashlib
import json
import os
from pathlib import Path
@@ -41,12 +42,14 @@ def inside(args):
if args.port_smoke: (work/'port-frame.ppm').unlink(missing_ok=True)
with (work/'xvfb.log').open('w') as xlog, (work/'wine.log').open('w') as wlog:
display = subprocess.Popen(['/native/usr/bin/Xvfb', ':89', '-screen', '0', '1024x768x24', '-nolisten', 'tcp'], stdout=xlog, stderr=xlog)
wine = None
wine = manager = None
try:
for _ in range(30):
if Path('/tmp/.X11-unix/X89').exists(): break
if display.poll() is not None: raise RuntimeError('Xvfb failed; see xvfb.log')
time.sleep(0.1)
if args.managed_desktop:
manager = subprocess.Popen(['dbus-run-session', '--', 'xfwm4', '--compositor=off'], stdout=xlog, stderr=xlog)
wine_env = dict(os.environ, LIBGL_DRIVERS_PATH='/native/usr/lib/i386-linux-gnu/dri')
application = ['/opt/wine-stable/bin/wine', args.game]
if args.port_smoke:
@@ -79,7 +82,7 @@ def inside(args):
'--assets', r'Z:\port\assets', '--cutscene-audio-smoke',
r'Z:\port\scenes\level1b\entities\entities.json']
if args.asset_probe:
application = ['/opt/wine-stable/bin/wine', r'Z:\probe.exe', args.probe_model]
application = ['/opt/wine-stable/bin/wine', r'Z:\probe.exe', args.probe_model, *args.probe_arg]
wine = subprocess.Popen(application, cwd='/work' if args.port_smoke else '/work/game', stdout=wlog, stderr=wlog, env=wine_env)
captures = []
for index in range(3):
@@ -102,6 +105,7 @@ def inside(args):
finally:
subprocess.run(['/opt/wine-stable/bin/wineserver', '-k'], timeout=10, check=False)
if wine and wine.poll() is None: wine.terminate()
if manager and manager.poll() is None: manager.terminate()
display.terminate()
display.wait(timeout=5)
@@ -113,6 +117,7 @@ def main():
p.add_argument('--seconds', type=int, default=24)
p.add_argument('--enter', action='store_true', help='Send Return after each screenshot')
p.add_argument('--debug', action='store_true', help='Record Wine process and exception diagnostics')
p.add_argument('--managed-desktop', action='store_true', help='Run an isolated xfwm4 desktop for original focus/fullscreen diagnostics')
p.add_argument('--wine-renderer', choices=['gl','vulkan'], default='gl')
p.add_argument('--port-smoke', action='store_true', help='Preliminary Windows port check under Wine64; not native Windows validation')
p.add_argument('--port-window', action='store_true', help='Windows port SDL window/input/resize/animation smoke under Wine64')
@@ -124,6 +129,7 @@ def main():
p.add_argument('--port-regression', choices=['objectives', 'carl'], help='Windows lab popup or conversation runtime regression under Wine64')
p.add_argument('--asset-probe', action='store_true', help='Run compiled read-only OMT shape probe inside isolated copy')
p.add_argument('--probe-model', default=r'ASE\jimstop.ase')
p.add_argument('--probe-arg', action='append', default=[], help='Additional explicit argument for the generated component probe (repeatable)')
p.add_argument('--probe-executable', type=Path, help='Local probe executable to mount read-only for --asset-probe')
p.add_argument('--probe-success', default='VERTICES ', help='Required output marker for an isolated component probe')
p.add_argument('--output', type=Path)
@@ -136,6 +142,7 @@ def main():
if args.port_cutscene_audio and (args.port_practice or args.port_story or args.port_walk or args.port_window or args.port_jetpack): p.error('Select audio lifecycle or rendering check')
if args.port_jetpack and (args.port_practice or args.port_story or args.port_walk or args.port_window): p.error('Select one jetpack or other port check')
if args.probe_executable and not args.asset_probe: p.error('--probe-executable requires --asset-probe')
if args.probe_arg and not args.asset_probe: p.error('--probe-arg requires --asset-probe')
if not 3 <= args.seconds <= 120: p.error('--seconds must be 3..120')
if args.inside: return inside(args)
project = Path(__file__).resolve().parents[2]
@@ -163,6 +170,9 @@ def main():
if args.asset_probe:
probe = (args.probe_executable or project/'artifacts/binary/omt_shape_probe.exe').resolve(strict=True)
if probe.is_relative_to(source.resolve()): p.error('Probe must be a generated executable outside originals')
probe_identity = {'path': str(probe), 'sha256': hashlib.sha256(probe.read_bytes()).hexdigest(),
'arguments': [args.probe_model, *args.probe_arg]}
(work/'probe-identity.json').write_text(json.dumps(probe_identity, indent=2)+'\n')
cmd += ['--ro-bind', str(probe), '/probe.exe']
for key,value in {'HOME':'/work/home', 'WINEPREFIX':'/work/prefix', 'WINEARCH':'win64' if args.port_smoke else 'win32',
'DISPLAY':':89', 'PATH':'/opt/wine-stable/bin:/usr/bin:/bin', 'LANG':'C.UTF-8',
@@ -180,6 +190,7 @@ def main():
cmd += ['--setenv', 'VK_DRIVER_FILES', '/native/usr/share/vulkan/icd.d/lvp_icd.json']
cmd += ['/usr/bin/python3', '/capture.py', '--inside', '--game', args.game, '--seconds', str(args.seconds)]
if args.enter: cmd += ['--enter']
if args.managed_desktop: cmd += ['--managed-desktop']
if args.port_smoke: cmd += ['--port-smoke']
if args.port_window: cmd += ['--port-window']
if args.port_walk: cmd += ['--port-walk']
@@ -188,7 +199,8 @@ def main():
if args.port_cutscene_audio: cmd += ['--port-cutscene-audio']
if args.port_jetpack: cmd += ['--port-jetpack']
if args.port_regression: cmd += ['--port-regression', args.port_regression]
if args.asset_probe: cmd += ['--asset-probe', '--probe-model', args.probe_model]
if args.asset_probe: cmd += ['--asset-probe', '--probe-model='+args.probe_model]
for argument in args.probe_arg: cmd += ['--probe-arg='+argument]
print('Running isolated Windows port' if args.port_smoke else 'Running copied original', 'with no network and no original-directory mount:', work, flush=True)
subprocess.run(cmd, check=True, timeout=args.seconds + 40)
print('Capture metadata:', work/'capture.json')
@@ -201,6 +213,8 @@ def main():
print('Windows port audio lifecycle passed under Wine; native Windows validation is still required' if args.port_cutscene_audio
else 'Windows port rendered under Wine; native Windows validation is still required')
if args.asset_probe:
if hashlib.sha256(probe.read_bytes()).hexdigest() != probe_identity['sha256']:
raise SystemExit('Probe executable changed during capture; observation identity is invalid')
result = json.loads((work/'capture.json').read_text())
if result['captures'][-1]['wineExit'] != 0 or args.probe_success not in (work/'wine.log').read_text():
raise SystemExit('Original component probe did not complete; inspect wine.log')