Files
WoW-Hybrid-gateway/ops/forever_opcode_profile.py

106 lines
9.1 KiB
Python

#!/usr/bin/env python3
"""Reuse pinned original ClassicOpcodes normalization without a game server.
Compile an isolated read-only source oracle, not a gateway/client/session tool.
Only environment selection is frozen to the70334 development profile: extra
server group shift 1, the reviewed server insertion and the original client insertion. Mapping functions,
explicit tables, blocked opcodes and stubs remain verbatim original source.
"""
import argparse,hashlib,json,re,subprocess
from pathlib import Path
from codec_build_cache import Cache,write_changed
ROOT=Path(__file__).resolve().parents[1]
SOURCE=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever'
DEFAULT_NAMES=('SMSG_GUILD_BANK_QUERY_RESULTS','SMSG_GUILD_BANK_LOG_QUERY_RESULTS','SMSG_GUILD_BANK_REMAINING_WITHDRAW_MONEY','SMSG_GUILD_PERMISSIONS_QUERY_RESULTS','SMSG_GUILD_INVITE','SMSG_GUILD_COMMAND_RESULT','SMSG_AURA_UPDATE','SMSG_QUERY_GUILD_INFO_RESPONSE','SMSG_SELL_RESPONSE','SMSG_BUY_SUCCEEDED','SMSG_BUY_FAILED','SMSG_TRAINER_LIST','SMSG_TRAINER_BUY_FAILED','SMSG_POWER_UPDATE','SMSG_ITEM_ENCHANT_TIME_UPDATE','SMSG_CHAT','SMSG_GUILD_ROSTER','SMSG_LEARNED_SPELLS','SMSG_UNLEARNED_SPELLS','SMSG_SUPERCEDED_SPELLS','SMSG_SPELL_PERIODIC_AURA_LOG','SMSG_INITIALIZE_FACTIONS','SMSG_SET_FACTION_STANDING','SMSG_SET_FACTION_VISIBLE','SMSG_SPELL_NON_MELEE_DAMAGE_LOG','SMSG_PVP_CREDIT','SMSG_DISPLAY_GAME_ERROR','SMSG_AUCTION_COMMAND_RESULT','SMSG_AUCTION_WON_NOTIFICATION','SMSG_AUCTION_CLOSED_NOTIFICATION','SMSG_AUCTION_OWNER_BID_NOTIFICATION','SMSG_AUCTION_LIST_OWNED_ITEMS_RESULT','SMSG_AUCTION_LIST_BIDDED_ITEMS_RESULT','SMSG_BATTLEFIELD_LIST','SMSG_BATTLEGROUND_PLAYER_JOINED','SMSG_BATTLEGROUND_PLAYER_LEFT','SMSG_BATTLEFIELD_STATUS_QUEUED','SMSG_BATTLEFIELD_STATUS_NEED_CONFIRMATION','SMSG_BATTLEFIELD_STATUS_NONE')
def method_span(text,signature):
start=text.index(signature);brace=text.index('{',start);end=brace+1;depth=1
while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1
return start,end
def build(source=SOURCE):
prefix='src/server/game/Server/Protocol/';profile=json.loads((ROOT/'docs/FOREVER_SCHEMA_PROFILE.json').read_text());files={}
for name in ('ClassicOpcodes.cpp','ClassicClientOpcodes.inc'):
data=(source/prefix/name).read_bytes();sha=hashlib.sha256(data).hexdigest()
if sha!=profile['forever_sha256'][prefix+name]:raise ValueError('Pinned opcode source changed; review before generation')
files[name]=(data.decode(),sha)
enum_data=(source/prefix/'Opcodes.h').read_bytes();names={name:int(value,16) for name,value in re.findall(r'\b([CS]MSG_\w+)\s*=\s*(0x[0-9A-Fa-f]+)',enum_data.decode())}
if len(names)<2000:raise ValueError('Original opcode enum parse incomplete')
output=ROOT/'build/opcode-profile';output.mkdir(exist_ok=True,parents=True)
write_changed(output/'Opcodes.h','#pragma once\n#include <cstdint>\nusing uint32=uint32_t;\nenum :uint32 {\n'+''.join(f'{n}=0x{v:x},\n' for n,v in names.items())+'};\n')
write_changed(output/'ClassicClientOpcodes.inc',files['ClassicClientOpcodes.inc'][0])
write_changed(output/'ClassicOpcodes.h','''#pragma once
#include <cstdint>
#include <vector>
using uint32=uint32_t;using int32=int32_t;using uint8=uint8_t;
namespace ClassicOpcodes {
bool IsBuild70291OrLater();uint32 TranslateClientOpcode(uint32);uint32 TranslateServerOpcode(uint32);
uint32 TranslateClientOpcode70245(uint32);uint32 TranslateServerOpcode70245(uint32);
bool IsServerOpcodeBlocked(uint32);std::vector<uint8> const* GetServerStubPayload(uint32);
}
''')
text=files['ClassicOpcodes.cpp'][0]
for name in ('Config.h','Realm.h','RealmList.h'):text=text.replace('#include "'+name+'"','')
start,end=method_span(text,'static uint32 ExtraGroupShift()')
text=text[:start]+'static uint32 ExtraGroupShift() { return 1; } // Explicit70334 profile, no realm/config service.\n'+text[end:]
config='''#include <stdexcept>
#include <string_view>
#include <cstdint>
struct ProfileConfig { int32_t GetIntDefault(const char* key,int32_t fallback)const {
// The pinned source predates the 0x98 insertion boundary in upstream 5a125dfe.
if (std::string_view(key)=="Classic.MainGroupInsertIndex" && fallback==0x93) return 0x98;
if (std::string_view(key)=="Classic.ClientMainGroupInsertIndex" && fallback==0x13B) return fallback;
throw std::runtime_error("Unreviewed opcode profile configuration");
}};
static ProfileConfig profileConfig;static ProfileConfig const* sConfigMgr=&profileConfig;
'''
write_changed(output/'mapping.cpp',config+text)
write_changed(output/'main.cpp','''#include "ClassicOpcodes.h"
#include <iostream>
int main(){try{char direction;uint32 opcode;while(std::cin>>direction>>std::hex>>opcode){
if(direction=='S'){auto stub=ClassicOpcodes::GetServerStubPayload(opcode);std::cout<<std::hex<<ClassicOpcodes::TranslateServerOpcode(opcode)<<std::dec<<" "<<ClassicOpcodes::IsServerOpcodeBlocked(opcode)<<" "<<(stub?int(stub->size()):-1)<<"\\n";}
else if(direction=='C')std::cout<<std::hex<<ClassicOpcodes::TranslateClientOpcode(opcode)<<" 0 -1\\n";else return 1;
}return 0;}catch(const std::exception&){return 2;}}
''')
cache=Cache('clang++');flags=['clang++','-std=c++20','-O2','-I'+str(output)]
objects=[cache.compile(flags,output/name,output/(Path(name).stem+'.o')) for name in ('mapping.cpp','main.cpp')]
executable=output/'opcode-map';cache.link(['clang++',*map(str,objects),'-o',str(executable.with_suffix('.new'))],objects,executable)
provenance={n:sha for n,(text,sha) in files.items()};provenance['Opcodes.h']=hashlib.sha256(enum_data).hexdigest()
return executable,names,provenance
def normalize(server_names=DEFAULT_NAMES,client_opcodes=()):
executable,names,inputs=build();requests=[]
for name in server_names:
if name not in names or not name.startswith('SMSG_'):raise ValueError('Unknown original server opcode name')
requests.append(('S',names[name],name))
for opcode in client_opcodes:
if not 0<=opcode<=0xffffff:raise ValueError('Client opcode bound')
requests.append(('C',opcode,None))
result=subprocess.run([str(executable)],input=''.join(f'{d} {v:x}\n' for d,v,n in requests),capture_output=True,text=True,check=True)
lines=result.stdout.splitlines()
if len(lines)!=len(requests):raise ValueError('Opcode oracle output count differs')
rows=[]
for (direction,value,name),line in zip(requests,lines):
parts=line.split();translated=int(parts[0],16);blocked=int(parts[1]);stub=int(parts[2])
rows.append(dict(direction='server' if direction=='S' else 'client',name=name,source_opcode=hex(value),translated_opcode=hex(translated),blocked=bool(blocked),stub_bytes=None if stub<0 else stub))
native=json.loads((ROOT/'docs/evidence/protocol/merchant-opcodes-70334.json').read_text())
actual={int(r['source_opcode'],16):int.from_bytes(bytes.fromhex(r['getter_code'])[2:6],'little') for r in native['routes']}
for row in rows:
if row['direction']=='server' and int(row['source_opcode'],16) in actual and int(row['translated_opcode'],16)!=actual[int(row['source_opcode'],16)]:raise ValueError('Source mapping differs from actual70334 getter evidence')
return dict(build='1.60.1.70334',kind='source-transport-normalization-oracle',source_inputs_sha256=inputs,environment=dict(extra_group_shift=1,main_insert_index='0x98',client_main_insert_index='0x13b'),rows=rows,limits=['Pure offline source normalization, not packet-body or actual-gameplay verification.','Source comments identify some insertion boundaries as hypotheses; actual merchant getters independently agree.','Blocked/stub messages require explicit treatment, never fabricated gameplay results.'])
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--server-name',action='append');p.add_argument('--client-opcode',type=lambda v:int(v,0),action='append',default=[]);p.add_argument('--output',type=Path,default=ROOT/'runtime/source-opcode-profile.json');p.add_argument('--header',type=Path);p.add_argument('--check-header',action='store_true');a=p.parse_args()
if not a.output.resolve().is_relative_to(ROOT):p.error('Keep generated reports in gateway workspace')
report=normalize(a.server_name or DEFAULT_NAMES,a.client_opcode);a.output.write_text(json.dumps(report,indent=2)+'\n')
if a.header:
if not a.header.resolve().is_relative_to(ROOT):p.error('Keep generated header in gateway workspace')
if a.server_name:raise ValueError('Header uses only the reviewed default server set')
rows=[row for row in report['rows'] if row['direction']=='server']
if any(row['blocked'] or row['stub_bytes'] is not None for row in rows):raise ValueError('Do not emit blocked/stub native routes')
header='// Generated from pinned original ClassicOpcodes normalization for70334.\n#pragma once\nnamespace gateway::forever_opcodes {\n'+''.join(f"inline constexpr unsigned {row['name']}={row['translated_opcode']};\n" for row in rows)+'}\n'
if a.check_header:
if a.header.read_text()!=header:raise ValueError('Source-derived native opcode header drift')
else:write_changed(a.header,header)
print(json.dumps(report['rows'],indent=2));print('Reused original source normalization; no services, sockets, client calls or reference edits.')