Files
WoW-Hybrid-gateway/ops/build_windows_codec.py
2026-11-23 03:28:32 +02:00

323 lines
23 KiB
Python

#!/usr/bin/env python3
"""Stage cached serializer sources, then compile a genuine native Windows codec.
No schema/source regeneration, installation, client launch or authentication.
"""
import argparse, concurrent.futures, hashlib, json, os, re, shlex, shutil, subprocess
from pathlib import Path
from windows_codec_writer_closure import selected_function
ROOT=Path(__file__).resolve().parents[1]
DEFAULT_CACHE=ROOT/'runtime/vm-build-share/runtime-codec-update-20261022'
def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def write(path,value): Path(path).write_text(json.dumps(value,indent=2)+'\n')
def profile_contract(proof,relative,hashes,unit_dependencies):
overrides={}
creation_profile=proof['staged_creation_profile']
if creation_profile is None:
canonical='gateway/include/gateway/turtle_login_profile.hpp'
if canonical not in hashes or canonical not in unit_dependencies.get('gateway/src/forever_create.cpp',[]):
raise ValueError('Canonical creation profile is not in the compiled source closure')
else:
creation=creation_profile['compiled_header']; creation_path=relative(creation['path'])
if creation_path is None or hashes.get(creation_path.as_posix())!=creation['sha256']:
raise ValueError('Compiled creation profile closure mismatch')
overrides['GW_TURTLE_LOGIN_PROFILE_HEADER']=creation_path.as_posix()
if 'staged_render_profile' not in proof:
raise ValueError('Render profile provenance missing')
render=proof['staged_render_profile']
if render is None:
canonical='gateway/include/gateway/item_render_profile.hpp'
if canonical not in hashes or canonical not in unit_dependencies.get('gateway/src/forever_create.cpp',[]):
raise ValueError('Canonical render profile is not in the compiled source closure')
render_profile={'mode':'canonical-header','path':canonical,'sha256':hashes[canonical]}
else:
h=render['compiled_header']; path=relative(h['path'])
if path is None or hashes.get(path.as_posix())!=h['sha256']:
raise ValueError('Compiled render profile closure mismatch')
overrides['GW_ITEM_RENDER_PROFILE_HEADER']=path.as_posix()
render_profile={'mode':'staged-override','path':path.as_posix(),'sha256':h['sha256']}
return overrides,render_profile
def prepare(cache,output):
cache=cache.resolve(strict=True); output=output.absolute()
if output.exists(): raise ValueError('Fresh closure directory required')
proof=json.loads((cache/'provenance.json').read_text())
forever=Path(proof['forever_source']); turtle=Path(proof['turtle_source'])
roots=[(cache,'generated'),(ROOT,'gateway'),(forever,'forever'),(turtle,'turtle')]
def relative(path):
path=Path(path).resolve(strict=True)
if path.parent==cache/'party-70291' and path.name in ('PartyPackets.cpp','PartyPackets.h'):
return Path('forever/src/server/game/Server/Packets')/path.name
for base,label in roots:
try:return Path(label)/path.relative_to(base.resolve(strict=True))
except ValueError:pass
return None
inputs=set()
for p in cache.glob('*.cache.json'):
if p.name=='forever_codec_cli.cache.json':continue
inputs.update(json.loads(p.read_text())['inputs'])
sources=sorted(x for x in inputs if x.endswith('.cpp'))
unit_dependencies={}
unit_force_includes={}
for p in cache.glob('*.cache.json'):
if p.name=='forever_codec_cli.cache.json':continue
values=json.loads(p.read_text())['inputs'];units=[n for n in values if n.endswith('.cpp')]
if len(units)!=1:raise ValueError('Ambiguous saved compilation unit')
unit=relative(units[0]).as_posix()
unit_dependencies[unit]=[relative(n).as_posix() for n in values if relative(n) is not None]
if Path(units[0]).name=='PartyPackets.cpp':
declaration=cache/'party-packet-forward-declarations.hpp'
if str(declaration) not in values or declaration.read_text()!='struct SkillLineEntry;\n':
raise ValueError('Original Party TU missing reviewed nominal forward declaration')
unit_force_includes[unit]=[relative(declaration).as_posix()]
if 'party_update_profile' in proof:
party_dir=cache/'party-70291'
party_hashes=proof['party_update_profile']['compiled_files']
if set(party_hashes)!={'PartyPackets.h','PartyPackets.cpp'}:
raise ValueError('Incomplete staged PartyUpdate writer profile')
for name,digest in party_hashes.items():
path=party_dir/name
if str(path) not in inputs or sha(path)!=digest:
raise ValueError('Changed stage input for PartyUpdate: '+name)
header=relative(party_dir/'PartyPackets.h').as_posix()
writer=relative(party_dir/'PartyPackets.cpp').as_posix()
for unit in (writer,'gateway/src/forever_create.cpp'):
if header not in unit_dependencies.get(unit,[]):
raise ValueError('Missing staged PartyUpdate header dependency: '+unit)
expected={'serializer.cpp','account_cache_init.cpp','auth_init.cpp','corpse_delay.cpp','guild_response.cpp',
'hotfix_init.cpp','merchant_response.cpp','packed_position.cpp','query_create.cpp','uf_create.cpp','forever_create.cpp',
'CollectionPackets.cpp','CombatLogPackets.cpp','CombatLogPacketsCommon.cpp','CombatPackets.cpp','ItemPacketsCommon.cpp',
'LootPackets.cpp','MovementPackets.cpp','MythicPlusPacketsCommon.cpp','NPCPackets.cpp','PerksProgramPacketsCommon.cpp',
'ReputationPackets.cpp','SpellPackets.cpp','SystemPackets.cpp'}
# Optional writer closures already qualified by the native Linux cache.
# Preserve older cache compatibility while accepting these exact units.
optional_units={'QuestPackets.cpp','SocialPackets.cpp','TradePackets.cpp','InstancePackets.cpp','contact_names_serializer.cpp',
'quest_log_serializer.cpp','quest_packets_serializer.cpp','social_packets_serializer.cpp'}
actual=[Path(name).name for name in sources]
expected.update(optional_units.intersection(actual))
if 'PartyPackets.cpp' in actual:expected.add('PartyPackets.cpp')
# Older dispatchers do not call these modes. A current dispatcher requires its complete pairs.
frozen_units=set(unit_dependencies)
dispatcher='\n'.join(Path(path).read_text() for path in sources if Path(path).name=='serializer.cpp')
for label,adapter,writer,entrypoints in (
('/who','who','who_response',('who',)),
('PvP statistics','pvp_statistics','pvp_statistics_response',('pvp_statistics',)),
('Auction','auction_browse','auction_browse_response',
('auction_buckets','auction_items','auction_personal','commodity_quote'))):
units={f'gateway/src/{adapter}_serializer.cpp', f'generated/{writer}.cpp'}
if units & frozen_units or any(f'gateway::serialize_{name}(' in dispatcher for name in entrypoints):
if not units <= frozen_units:
raise ValueError(f'Incomplete {label} serializer compilation units')
expected.update(Path(unit).name for unit in units)
if 'gateway::serialize_commodity_quote(' in dispatcher:
signature='WorldPacket const* AuctionGetCommodityQuoteResult::Write()'
upstream=forever/'src/server/game/Server/Packets/AuctionHousePackets.cpp'
cached=(cache/'auction_browse_response.cpp').read_text()
if selected_function(upstream.read_text(),signature) not in cached:
raise ValueError('Frozen auction source is missing the original commodity quote writer')
if len(actual)!=len(expected) or set(actual)!=expected:
raise ValueError('Unexpected serializer compilation-unit closure; expected reviewed writer units')
ninja=(forever/'build/build.ninja').read_text(); start=ninja.index('build src/server/game/CMakeFiles/game.dir/Entities/Object/Updates/UpdateFields.cpp.o:')
block=ninja[start:ninja.index('\n\nbuild ',start)]
include_args=shlex.split(re.search(r' INCLUDES = (.+)',block)[1])
includes=[Path('generated/compatibility-include')]
for flag in include_args:
if not flag.startswith('-I'): raise ValueError('Unexpected cached include flag')
target=relative(flag[2:])
if target is not None:includes.append(target)
includes += [Path('gateway/include'),Path('gateway/native'),Path('generated')]
output.mkdir(parents=True)
hashes={}; ignored=[]
for name in sorted(inputs):
target=relative(name)
if target is None:
if name.startswith('/usr/'):ignored.append(name);continue
raise ValueError('Unmapped cached dependency: '+name)
source=Path(name)
if not source.is_file():raise ValueError('Missing frozen dependency: '+name)
if target.as_posix() in hashes and hashes[target.as_posix()]!=sha(source):
raise ValueError('Conflicting frozen input at '+target.as_posix())
dest=output/target;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,dest)
hashes[target.as_posix()]=sha(dest)
for inc in includes:(output/inc).mkdir(parents=True,exist_ok=True)
overrides,render_profile=profile_contract(proof,relative,hashes,unit_dependencies)
definition='LIBRARY forever_codec\nEXPORTS\n gw_codec_abi\n gw_codec_serialize\n'
(output/'codec.def').write_text(definition);hashes['codec.def']=sha(output/'codec.def')
unit_flags={name:['-D_USE_MATH_DEFINES=1'] for name,deps in unit_dependencies.items() if any(Path(dep).name=='Position.h' for dep in deps)}
constexpr_budget=proof.get('per_tu_constexpr_budget')
metadata_compiler=proof.get('per_tu_compiler')
if constexpr_budget is None and metadata_compiler is not None:
metadata_unit=relative(metadata_compiler['source'])
if metadata_unit is not None and metadata_unit.as_posix()=='gateway/src/forever_create.cpp' and metadata_compiler['compiler']=='g++':
# Match build_forever_create.py's existing Clang alternative for
# the compact registry; Windows uses Clang even when that cache
# selected GCC for this one large metadata translation unit.
constexpr_budget={'source':metadata_compiler['source'],'steps':33554432,
'option':'-fconstexpr-steps=33554432',
'reason':'existing compact-registry Clang alternative to cached GCC unit'}
if constexpr_budget is not None:
unit=relative(constexpr_budget['source'])
steps=constexpr_budget['steps']
if unit is None or unit.as_posix()!='gateway/src/forever_create.cpp' or unit.as_posix() not in unit_dependencies or type(steps) is not int or not 0<steps<=2147483647 or constexpr_budget['option']!=f'-fconstexpr-steps={steps}':
raise ValueError('Unqualified per-unit constant initialization budget')
unit_flags.setdefault(unit.as_posix(),[]).append(constexpr_budget['option'])
manifest={'schema':1,'kind':'cached-source-native-Windows-codec','item_package_sha256':proof['item_package_sha256'],'upstream_provenance_sha256':sha(cache/'provenance.json'),'files':hashes,'sources':[relative(x).as_posix() for x in sources],'unit_dependencies':unit_dependencies,'unit_force_includes':unit_force_includes,'unit_flags':unit_flags,'per_tu_constexpr_budget':constexpr_budget,'includes':list(dict.fromkeys(x.as_posix() for x in includes)),'overrides':overrides,'render_profile':render_profile,'system_dependencies':'Use native UCRT64 Boost/OpenSSL/zlib headers and libraries; Linux system headers not copied.','ignored_system_dependency_count':len(ignored),'runtime_acceptance':False}
write(output/'windows-codec-closure.json',manifest)
return manifest
def native_archive(path):
data=Path(path).read_bytes()
if not data.startswith(b'!<arch>\n'):raise ValueError('Native Windows protocol archive required')
offset=8
while offset+60<=len(data):
header=data[offset:offset+60];name=header[:16].decode('ascii').strip();size=int(header[48:58]);body=data[offset+60:offset+60+size]
if header[58:60]!=b'`\n' or len(body)!=size:raise ValueError('Malformed protocol archive')
if name not in ('/','//','/SYM64/'):
if body[:2]!=b'\x64\x86':raise ValueError('Protocol archive must contain AMD64 COFF, not Linux ELF')
return
offset+=60+size+(size&1)
raise ValueError('Empty protocol archive')
METADATA_UNITS=frozenset(('gateway/src/forever_create.cpp','generated/windows_writer_helpers.cpp'))
def compiler_abi_flags(compiler):
name=compiler.name.lower()
if 'clang' in name:return ['--target=x86_64-w64-windows-gnu','-stdlib=libstdc++','--rtlib=libgcc']
# Native MSYS g++.exe needs the same large COFF sections as cross g++.
return ['-Wa,-mbig-obj'] if 'g++' in name else []
def rebase_unit_render_profile_flags(closure,manifest,unit,flags):
"""Bind a per-TU render include to its frozen local dependency.
Older closures recorded a foreign absolute include in unit_flags even
though their dependency/hash proof named a local generated header. Keep
legacy units without that define unchanged; never trust the foreign path.
"""
if not isinstance(flags,list) or len(flags)>256 or any(
not isinstance(flag,str) or len(flag)>8192 or '\0' in flag for flag in flags):
raise ValueError('Bounded per-unit compiler flags required')
macro='GW_ITEM_RENDER_PROFILE_HEADER';define='-D'+macro
matches=[];i=0
while i<len(flags):
flag=flags[i]
if flag==define or flag.startswith(define+'='):
if not flag.startswith(define+'='):raise ValueError('Render profile define lacks a value')
matches.append((i,i+1))
elif flag=='-D' and i+1<len(flags) and (flags[i+1]==macro or flags[i+1].startswith(macro+'=')):
if not flags[i+1].startswith(macro+'='):raise ValueError('Render profile define lacks a value')
matches.append((i,i+2));i+=1
i+=1
if not matches:return list(flags)
if len(matches)!=1:raise ValueError('Ambiguous per-unit render profile defines')
proof=manifest.get('render_profile')
if not isinstance(proof,dict):raise ValueError('Per-unit render profile proof missing')
relative=proof.get('path');digest=proof.get('sha256')
if (not isinstance(relative,str) or not 0<len(relative)<=4096 or
any(c in relative for c in ('\\','\0','\n','\r')) or
re.match(r'^[A-Za-z]:',relative) or Path(relative).is_absolute() or
'..' in Path(relative).parts or Path(relative).as_posix()!=relative or
not isinstance(digest,str) or not re.fullmatch('[0-9a-f]{64}',digest)):
raise ValueError('Local pinned render profile path/hash required')
files=manifest.get('files',{});dependency_map=manifest.get('unit_dependencies',{})
if not isinstance(dependency_map,dict):raise ValueError('Unit dependency closure missing')
dependencies=dependency_map.get(unit,[])
if not isinstance(files,dict) or files.get(relative)!=digest or not isinstance(dependencies,list) or relative not in dependencies:
raise ValueError('Render profile is not pinned in this unit dependency closure')
root=Path(closure).resolve();original=root/relative
try:
path=original.resolve(strict=True)
if (not path.is_relative_to(root) or original.is_symlink() or not path.is_file() or
not 0<path.stat().st_size<=16*1024*1024 or sha(path)!=digest):
raise ValueError('Frozen local render profile changed or escaped')
except OSError as error:
raise ValueError('Frozen local render profile is unavailable') from error
start,end=matches[0]
return flags[:start]+[define+'='+json.dumps(path.as_posix())]+flags[end:]
def verify_equipment_mappings(manifest, receipt):
"""Check the two equipment tables used by the player serializer against a reviewed catalogue."""
expected = json.loads(receipt.read_text()).get('headers', {})
unit = 'gateway/src/forever_create.cpp'
dependencies = manifest.get('unit_dependencies', {}).get(unit, [])
render_path = manifest.get('render_profile', {}).get('path')
peer_paths = [path for path in dependencies if Path(path).name == 'peer_item_appearances.hpp']
if len(peer_paths) != 1 or render_path not in dependencies:
raise ValueError('Player serializer must pin both equipment mapping headers')
compiled = {}
for name, path in [('item_render_profile.hpp', render_path), ('peer_item_appearances.hpp', peer_paths[0])]:
digest = manifest['files'].get(path)
if not isinstance(digest, str) or not re.fullmatch('[0-9a-f]{64}', digest) or expected.get(name) != digest:
raise ValueError(f'Equipment catalogue mismatch for {name}')
compiled[name] = digest
return compiled
def build(closure,output,compiler,library,jobs,linker="lld",metadata_compiler=None,equipment_receipt=None):
# GW_WINDOWS_CROSS=1: an x86_64-w64-mingw32 cross compiler produces the same PE/COFF output.
if os.name!='nt' and os.environ.get('GW_WINDOWS_CROSS')!='1':raise ValueError('Native Windows compilation must run on Windows')
closure=closure.resolve();output=output.resolve();library=library.resolve()
if output==closure or output.is_relative_to(closure):raise ValueError('Separate codec build directory required')
manifest=json.loads((closure/'windows-codec-closure.json').read_text())
if manifest.get('schema')!=1 or manifest.get('kind')!='cached-source-native-Windows-codec':raise ValueError('Unrecognized closure')
for name,digest in manifest['files'].items():
original=closure/name;path=original.resolve()
if not path.is_relative_to(closure) or original.is_symlink() or sha(path)!=digest:raise ValueError('Codec source closure changed')
mappings = verify_equipment_mappings(manifest, equipment_receipt) if equipment_receipt else None
native_archive(library)
output.mkdir(parents=True,exist_ok=True)
# The actual Windows mixed build qualifies GNU compilation only for these
# two metadata-header consumers. Keep the primary compiler for every other
# unit and for linking; this is not a whole-codec compiler switch.
selected=set()
if metadata_compiler is not None:
if 'clang' not in compiler.name.lower() or 'g++' not in metadata_compiler.name.lower():
raise ValueError('Metadata override requires Clang primary and GNU C++ alternate')
selected={name for name in manifest['sources'] if name in METADATA_UNITS and
any(Path(dep).name=='item_sparse_compat.hpp' for dep in manifest.get('unit_dependencies',{}).get(name,[]))}
if not selected:raise ValueError('No pinned metadata-header consumer in this closure')
abi_flags=compiler_abi_flags(compiler)
flags=['-std=c++20','-O1','-ffunction-sections','-fdata-sections','-DBOOST_BIND_NO_PLACEHOLDERS','-DBOOST_ASIO_NO_DEPRECATED','-DFMT_HEADER_ONLY','-DRAPIDJSON_HAS_STDSTRING','-DNOMINMAX','-D_WIN32_WINNT=0x0A00']
flags += ['-I'+str(closure/name) for name in manifest['includes']]
flags += ['-D'+macro+'='+json.dumps((closure/name).as_posix()) for macro,name in manifest['overrides'].items()]
compiler_id=subprocess.check_output([str(compiler),'--version'],text=True).splitlines()[0]
metadata_compiler_id=subprocess.check_output([str(metadata_compiler),'--version'],text=True).splitlines()[0] if selected else None
objects=[]
# A failed parallel unit must not force already successful frozen units to
# compile again on retry. Manifest dependencies come from the saved cache.
dependencies=manifest.get('unit_dependencies',{})
def compile_one(entry):
number,name=entry;obj=output/(str(number)+'-'+Path(name).stem+'.o')
stamp=obj.with_suffix('.cache.json')
unit_compiler=metadata_compiler if name in selected else compiler
unit_id=metadata_compiler_id if name in selected else compiler_id
local_flags=rebase_unit_render_profile_flags(closure,manifest,name,manifest.get('unit_flags',{}).get(name,[]))
unit_flags=compiler_abi_flags(unit_compiler)+flags+local_flags
if name in selected:
unit_flags=[flag.replace('-fconstexpr-steps=','-fconstexpr-ops-limit=') for flag in unit_flags]
for include in manifest.get('unit_force_includes',{}).get(name,[]):
if include not in dependencies.get(name,[]) or include not in manifest['files']:
raise ValueError('Unpinned per-unit forced include')
unit_flags+=['-include',str(closure/include)]
key={'compiler':unit_id,'flags':unit_flags,'source':name,'dependencies':{p:manifest['files'][p] for p in dependencies.get(name,manifest['files'])}}
if obj.exists() and stamp.exists() and json.loads(stamp.read_text())==key:return obj
subprocess.run([str(unit_compiler),*unit_flags,'-c',str(closure/name),'-o',str(obj)],check=True)
write(stamp,key)
return obj
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1,min(jobs,8))) as pool:
objects=list(pool.map(compile_one,enumerate(manifest['sources'])))
target=output/'forever_codec.dll';temporary=output/'forever_codec.new.dll'
subprocess.run([str(compiler),*abi_flags,'-fuse-ld='+linker,'-shared','-Wl,--gc-sections','-Wl,--exclude-all-symbols','-Wl,--no-undefined','-Wl,--out-implib,'+str(output/'libforever_codec.dll.a'),*map(str,objects),str(library),str(closure/'codec.def'),'-lcrypto','-lz','-lws2_32','-lcrypt32','-lbcrypt','-o',str(temporary)],check=True)
temporary.replace(target)
report={'status':'native-Windows-codec-linked','compiler':compiler_id,'linker':linker,'source_closure_sha256':sha(closure/'windows-codec-closure.json'),'protocol_library':str(library),'protocol_library_sha256':sha(library),'item_package_sha256':manifest['item_package_sha256'],'codec':str(target),'codec_sha256':sha(target),'compiled_units':len(objects),'runtime_acceptance':False}
if mappings:report['equipment_mapping_headers']=mappings
if selected:report.update(metadata_compiler=metadata_compiler_id,unit_compilers={name:metadata_compiler_id if name in selected else compiler_id for name in manifest['sources']})
write(output/'windows-codec-provenance.json',report);return report
def main():
p=argparse.ArgumentParser(description=__doc__);sub=p.add_subparsers(dest='command',required=True)
a=sub.add_parser('prepare');a.add_argument('--cache',type=Path,default=DEFAULT_CACHE);a.add_argument('--output',required=True,type=Path)
a=sub.add_parser('build');a.add_argument('--closure',required=True,type=Path);a.add_argument('--output',required=True,type=Path);a.add_argument('--compiler',required=True,type=Path);a.add_argument('--metadata-compiler',type=Path,help='GNU C++ alternate only for the two pinned item-metadata-header consumers; primary compiler still links');a.add_argument('--protocol-library',required=True,type=Path);a.add_argument('--jobs',type=int,default=4);a.add_argument('--linker',choices=['lld','bfd'],default='lld')
a.add_argument('--equipment-receipt',type=Path,help='Verify player render and peer lookup headers against a reviewed catalogue receipt before compiling')
a=p.parse_args()
if a.command=='prepare':r=prepare(a.cache,a.output);print('Prepared cached Windows codec closure:',len(r['sources']),'source units;',len(r['files']),'files.')
else:r=build(a.closure,a.output,a.compiler,a.protocol_library,a.jobs,a.linker,a.metadata_compiler,a.equipment_receipt);print('Native Windows codec linked; actual runtime acceptance pending.')
if __name__=='__main__':main()