Files

482 lines
33 KiB
Python

#!/usr/bin/env python3
"""Build private PE components and a guarded no-helper loader candidate.
The legacy prepare/restore actions patch only a private DXVK dependency.
The separate build-loader-package action derives a signed-loader copy from
the pinned original and the REA contract; it never installs that copy.
"""
import hashlib,json,os,struct,subprocess,sys
from pathlib import Path
import pefile
ROOT=Path(__file__).resolve().parents[1]
ORIGINAL='c49ce22c3e0aaeb7a7007a5c5cb792e4c3e6cdecc55a1145a5933fc113e3e57f'
V44_LOADER='061822ced913c69c4927b6ab7c329f2da4449be0add490dfa43cbf771ae26faf'
GAME=ROOT/'runtime/native-client/_classic_beta_'
PRISTINE=ROOT/'runtime/pristine-forever/World of Warcraft/_classic_beta_/WowB.exe'
MANIFEST=ROOT/'runtime/native-engine-pe.json'
LOADER_SOURCE_SHA='ce09256540963a1920fe375af5b6fb37817f65ba0756b7c859c23288990f98dd'
LOADER_CANDIDATE_SHA='061822ced913c69c4927b6ab7c329f2da4449be0add490dfa43cbf771ae26faf'
LOADER_STORE_RVA=0xA283C6
LOADER_STORE_OFFSET=0xA187C6
LOADER_STORE_BEFORE=bytes.fromhex('897038')
LOADER_STORE_AFTER=bytes.fromhex('909090')
LOADER_PACKAGE_KIND='nohelper-candidate-install-manifest-v44-loader-store-suppression'
def sha(data):return hashlib.sha256(data).hexdigest()
def align(value,boundary):return (value+boundary-1)//boundary*boundary
def fast_pe(data):
pe=pefile.PE(data=data,fast_load=True)
pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']])
return pe
def build_loader_package(*,source,rea_receipt,package_template,output_directory):
"""Derive the accepted V44 loader and rebase the existing eight-file journal manifest.
This creates a fresh package only. The current trial installer owns any later
client write and its exact eight-file rollback.
"""
source=Path(source);rea_receipt=Path(rea_receipt);package_template=Path(package_template)
for path in (source,rea_receipt,package_template):
if path.is_symlink() or not path.is_file():raise ValueError('Regular pinned loader package input required')
out=Path(output_directory).absolute()
if (out.exists() or out.is_symlink() or not out.parent.is_dir()
or out.parent.is_symlink() or not out.parent.resolve().is_relative_to(ROOT.resolve())
or not any(out.parent.resolve().is_relative_to((ROOT/folder).resolve()) for folder in ('build','runtime'))):
raise ValueError('Fresh owned build/runtime output directory required')
partial=out.with_name(out.name+'.partial')
if partial.exists() or partial.is_symlink():raise ValueError('Existing loader package partial preserved')
evidence=json.loads(rea_receipt.read_text())
if (evidence.get('input_sha256')!=LOADER_SOURCE_SHA
or evidence.get('candidate_sha256')!=LOADER_CANDIDATE_SHA
or int(evidence.get('file_offset',-1),0)!=LOADER_STORE_OFFSET
or int(evidence.get('rva',-1),0)!=LOADER_STORE_RVA
or evidence.get('original_bytes')!=LOADER_STORE_BEFORE.hex()
or evidence.get('candidate_bytes')!=LOADER_STORE_AFTER.hex()):
raise ValueError('Pinned loader REA patch contract differs')
original=source.read_bytes()
if len(original)!=42637008 or sha(original)!=LOADER_SOURCE_SHA:
raise ValueError('Original loader identity differs')
pe=pefile.PE(data=original,fast_load=True)
if (pe.FILE_HEADER.Machine!=0x8664 or pe.OPTIONAL_HEADER.Magic!=0x20b
or pe.get_offset_from_rva(LOADER_STORE_RVA)!=LOADER_STORE_OFFSET
or not any(section.Name.rstrip(b'\0')==b'.text' and
section.VirtualAddress<=LOADER_STORE_RVA<
section.VirtualAddress+section.Misc_VirtualSize for section in pe.sections)
or not pe.OPTIONAL_HEADER.DATA_DIRECTORY[4].Size):
raise ValueError('Original signed loader PE location differs')
if original[LOADER_STORE_OFFSET:LOADER_STORE_OFFSET+3]!=LOADER_STORE_BEFORE:
raise ValueError('Original loader writer preimage differs')
candidate=bytearray(original)
candidate[LOADER_STORE_OFFSET:LOADER_STORE_OFFSET+3]=LOADER_STORE_AFTER
if sha(candidate)!=LOADER_CANDIDATE_SHA:raise ValueError('Loader candidate identity differs')
template=json.loads(package_template.read_text())
rows=template.get('files')
names={'GWNativeBridge.dll','GWNativeWire.dll','version-hash.bin','addon-tail.bin',
'libgateway_wine_wire.so','libgateway_native.so','libforever_codec.so','WowB_loader.dll'}
if (template.get('kind')!=LOADER_PACKAGE_KIND or not isinstance(rows,list) or len(rows)!=8
or {row.get('target_name') for row in rows}!=names):
raise ValueError('Existing eight-file no-helper manifest differs')
patch=template.get('loader_store_patch') or {}
if (patch.get('file_offset')!=LOADER_STORE_OFFSET
or patch.get('original_bytes')!=LOADER_STORE_BEFORE.hex()
or patch.get('candidate_bytes')!=LOADER_STORE_AFTER.hex()
or patch.get('runtime_acceptance')!='pending'):
raise ValueError('Existing package patch admission differs')
loader=next(row for row in rows if row['target_name']=='WowB_loader.dll')
if (loader.get('candidate_sha256')!=LOADER_CANDIDATE_SHA
or loader.get('preimage_sha256')!=LOADER_SOURCE_SHA
or loader.get('target_relative')!='runtime/native-client/_classic_beta_/WowB_loader.dll'):
raise ValueError('Existing loader package row differs')
for row in rows:
if row is loader:continue
path=Path(row.get('candidate_path',''))
if path.is_symlink() or not path.is_file() or sha(path.read_bytes())!=row.get('candidate_sha256'):
raise ValueError('Maintained package dependency differs: '+str(row.get('target_name')))
loader['candidate_path']=str(out/'WowB_loader.dll')
patch['rea_receipt']=str(rea_receipt.resolve())
partial.mkdir(mode=0o700)
with (partial/'WowB_loader.dll').open('xb') as stream:
stream.write(candidate);stream.flush();os.fsync(stream.fileno())
manifest=partial/'nohelper-v44-eight-file-package.private.json'
with manifest.open('x') as stream:
json.dump(template,stream,indent=2);stream.write('\n');stream.flush();os.fsync(stream.fileno())
receipt={'kind':'maintained-nohelper-v44-loader-package','original_sha256':LOADER_SOURCE_SHA,
'candidate_sha256':LOADER_CANDIDATE_SHA,'rea_receipt':str(rea_receipt.resolve()),
'source':str(source.resolve()),'manifest':str(out/manifest.name),
'manifest_sha256':sha(manifest.read_bytes()),'files':len(rows),
'native_acceptance':'Exact E9+V44 Linux/Wine tuple reached rendered World in isolated R12 and fresh DXVK package runs; long-run/reconnect and Windows pending',
'rollback':'Existing eight-file trial journal restores the full original loader preimage after exact owner exit and prefix idle.'}
with (partial/'build-receipt.private.json').open('x') as stream:
json.dump(receipt,stream,indent=2);stream.write('\n');stream.flush();os.fsync(stream.fileno())
if sha((partial/'WowB_loader.dll').read_bytes())!=LOADER_CANDIDATE_SHA:
raise ValueError('Written loader candidate differs')
partial.rename(out)
return receipt
def checksum(data,offset):
copy=bytearray(data);struct.pack_into('<I',copy,offset,0)
copy.extend(bytes((-len(copy))%4))
if sys.byteorder!='little':raise RuntimeError('Require little-endian patch host')
total=sum(memoryview(copy).cast('I'))
while total>>32:total=(total&0xffffffff)+(total>>32)
total=(total&0xffff)+(total>>16);total=(total&0xffff)+(total>>16)
return (total&0xffff)+len(data)
def add_import(data):
return add_imports(data,(("GWNativeBridge.dll","gw_bridge_abi"),))
def add_imports(data,dependencies,*,prepend=False):
"""Preserve original imports and add only declared development dependencies."""
dependencies=tuple(dependencies)
allowed={("GWNativeBridge.dll","gw_bridge_abi"),("GWNativeWire.dll","gw_wire_abi")}
native_d3d=("d3d11.dll","D3D11CreateDevice")
native_d3d_append=(not prepend and dependencies==(native_d3d,) and sha(data)==ORIGINAL)
if prepend:
if dependencies!=(native_d3d,) or sha(data)!=ORIGINAL:
raise ValueError('Preload requires exact original WowB and native D3D11 creation import')
elif not native_d3d_append and (not dependencies or len(dependencies)>2 or len(set(dependencies))!=len(dependencies) or any(row not in allowed for row in dependencies)):
raise ValueError('Unsupported owned dependency list')
pe=fast_pe(data)
if pe.FILE_HEADER.Machine!=0x8664 or pe.OPTIONAL_HEADER.Magic!=0x20b:raise ValueError('Require AMD64 PE32+')
count=pe.FILE_HEADER.NumberOfSections
section_header=pe.sections[-1].get_file_offset()+40
if section_header+40>min(pe.OPTIONAL_HEADER.SizeOfHeaders,pe.sections[0].PointerToRawData):raise ValueError('No spare section header; original preserved')
if any(data[section_header:section_header+40]):raise ValueError('Spare header is not empty')
if any(s.Name.rstrip(b'\0')==b'.gwimp' for s in pe.sections):raise ValueError('Already patched')
directory=pe.OPTIONAL_HEADER.DATA_DIRECTORY[1]
original=[];pos=pe.get_offset_from_rva(directory.VirtualAddress)
for i in range(64):
row=data[pos+i*20:pos+(i+1)*20]
if len(row)!=20:raise ValueError('Truncated imports')
if row==bytes(20):break
original.append(row)
else:raise ValueError('Unbounded imports')
if not original:raise ValueError('Missing original imports')
rva=align(max(s.VirtualAddress+max(s.Misc_VirtualSize,s.SizeOfRawData) for s in pe.sections),pe.OPTIONAL_HEADER.SectionAlignment)
payload=bytearray((bytes(len(dependencies)*20)+b''.join(original)+bytes(20)) if prepend
else (b''.join(original)+bytes((len(dependencies)+1)*20)))
def append(blob,boundary=1):
while len(payload)%boundary:payload.append(0)
address=rva+len(payload);payload.extend(blob);return address
for index,(library,symbol) in enumerate(dependencies):
name=append(library.encode('ascii')+b'\0')
hint=append(b'\0\0'+symbol.encode('ascii')+b'\0',2)
ilt=append(struct.pack('<QQ',hint,0),8)
iat=append(struct.pack('<QQ',hint,0),8)
struct.pack_into('<IIIII',payload,(index if prepend else len(original)+index)*20,ilt,0,0,name,iat)
raw=align(len(data),pe.OPTIONAL_HEADER.FileAlignment)
raw_size=align(len(payload),pe.OPTIONAL_HEADER.FileAlignment)
patched=bytearray(data);patched.extend(bytes(raw-len(patched)));patched.extend(payload);patched.extend(bytes(raw_size-len(payload)))
struct.pack_into('<8sIIIIIIHHI',patched,section_header,b'.gwimp\0\0',len(payload),rva,raw_size,raw,0,0,0,0,0xc0000040)
struct.pack_into('<H',patched,pe.FILE_HEADER.get_field_absolute_offset('NumberOfSections'),count+1)
struct.pack_into('<I',patched,pe.OPTIONAL_HEADER.get_field_absolute_offset('SizeOfImage'),align(rva+len(payload),pe.OPTIONAL_HEADER.SectionAlignment))
struct.pack_into('<II',patched,directory.get_file_offset(),rva,(len(original)+len(dependencies)+1)*20)
# The certificate bytes/directory remain; the signature is explicitly invalid
# for this experimental derivative. Never disable or forge its validation.
check=fast_pe(patched)
struct.pack_into('<I',patched,check.OPTIONAL_HEADER.get_field_absolute_offset('CheckSum'),checksum(patched,check.OPTIONAL_HEADER.get_field_absolute_offset('CheckSum')))
verify=fast_pe(patched)
expected=[name.encode('ascii') for name,_ in dependencies]
expected=expected+[x.dll for x in pe.DIRECTORY_ENTRY_IMPORT] if prepend else [x.dll for x in pe.DIRECTORY_ENTRY_IMPORT]+expected
if [x.dll for x in verify.DIRECTORY_ENTRY_IMPORT]!=expected:raise ValueError('Import preservation failed')
return bytes(patched)
def add_native_windows_entry_slot_observer(data, payload, symbol_offsets):
"""Append the bounded original-entry observation carrier without new imports.
This is a private REA diagnostic, not a bootstrap or authentication bypass.
The payload queries page protection before reading the one pinned runtime
import slot and tail-jumps the exact original entrypoint. Code is RX and
its observation record is a separate RW section.
"""
if sha(data) != ORIGINAL:
raise ValueError("entry observer requires the pinned original c49 executable")
pe = fast_pe(data)
if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20b:
raise ValueError("entry observer requires PE32+ AMD64")
if pe.OPTIONAL_HEADER.AddressOfEntryPoint != 0x1d91d0:
raise ValueError("original entry contract differs")
count = pe.FILE_HEADER.NumberOfSections
section_header = pe.sections[-1].get_file_offset() + 40
if section_header + 80 > min(pe.OPTIONAL_HEADER.SizeOfHeaders,
pe.sections[0].PointerToRawData):
raise ValueError("entry observer needs two spare section headers")
if any(data[section_header:section_header + 80]):
raise ValueError("entry observer section header preimage is occupied")
required = ("gw_aep_observer_entry", "gw_aep_record_rva",
"gw_aep_slot_rva", "gw_aep_tail_displacement")
if any(k not in symbol_offsets for k in required):
raise ValueError("entry observer payload symbols are incomplete")
if not payload or len(payload) > 4096:
raise ValueError("entry observer payload exceeds the bounded code page")
code_rva = align(max(s.VirtualAddress + max(s.Misc_VirtualSize, s.SizeOfRawData)
for s in pe.sections), pe.OPTIONAL_HEADER.SectionAlignment)
record_rva = align(code_rva + len(payload), pe.OPTIONAL_HEADER.SectionAlignment)
code = bytearray(payload)
for name in required:
if not 0 <= symbol_offsets[name] < len(code):
raise ValueError("entry observer payload symbol is outside the code")
for name in required[1:]:
if symbol_offsets[name] + 4 > len(code):
raise ValueError("entry observer payload field is truncated")
struct.pack_into("<I", code, symbol_offsets["gw_aep_record_rva"], record_rva)
struct.pack_into("<I", code, symbol_offsets["gw_aep_slot_rva"], 0x47c2cb8)
tail = symbol_offsets["gw_aep_tail_displacement"]
if code[tail - 1] != 0xe9:
raise ValueError("entry observer tail is not a relative jump")
struct.pack_into("<i", code, tail, 0x1d91d0 - (code_rva + tail + 4))
raw = align(len(data), pe.OPTIONAL_HEADER.FileAlignment)
code_raw = align(len(code), pe.OPTIONAL_HEADER.FileAlignment)
record_raw = align(64, pe.OPTIONAL_HEADER.FileAlignment)
patched = bytearray(data)
patched.extend(bytes(raw - len(patched)))
patched.extend(code)
patched.extend(bytes(code_raw - len(code) + record_raw))
struct.pack_into("<8sIIIIIIHHI", patched, section_header,
b".gwaep\0\0", len(code), code_rva, code_raw, raw,
0, 0, 0, 0, 0x60000020)
struct.pack_into("<8sIIIIIIHHI", patched, section_header + 40,
b".gwobs\0\0", 64, record_rva, record_raw, raw + code_raw,
0, 0, 0, 0, 0xc0000040)
for field, value in (("AddressOfEntryPoint", code_rva + symbol_offsets[required[0]]),
("SizeOfImage", align(record_rva + 64, pe.OPTIONAL_HEADER.SectionAlignment)),
("SizeOfCode", pe.OPTIONAL_HEADER.SizeOfCode + code_raw),
("SizeOfInitializedData", pe.OPTIONAL_HEADER.SizeOfInitializedData + record_raw)):
struct.pack_into("<I", patched, pe.OPTIONAL_HEADER.get_field_absolute_offset(field), value)
struct.pack_into("<H", patched, pe.FILE_HEADER.get_field_absolute_offset("NumberOfSections"), count + 2)
check_offset = pe.OPTIONAL_HEADER.get_field_absolute_offset("CheckSum")
struct.pack_into("<I", patched, check_offset, checksum(patched, check_offset))
return bytes(patched), {"entry_rva": code_rva + symbol_offsets[required[0]],
"code_rva": code_rva, "record_rva": record_rva,
"record_size": 64, "observed_slot_rva": 0x47c2cb8,
"original_entry_rva": 0x1d91d0}
def add_native_windows_d3d_preload(data):
"""Force the native app-local carrier to load before WowB_loader in a private EXE copy."""
return add_imports(data,(("d3d11.dll","D3D11CreateDevice"),),prepend=True)
def add_native_windows_d3d_append(data):
"""Test native carrier import after the original loader in an exact-c49 private EXE copy."""
if sha(data)!=ORIGINAL:
raise ValueError('Append diagnostic requires exact original WowB')
return add_imports(data,(("d3d11.dll","D3D11CreateDevice"),))
def add_native_windows_loader_bridge_import(data):
"""Test Bridge loading from the exact V44 loader without changing the EXE."""
if sha(data)!=V44_LOADER:
raise ValueError('Loader Bridge diagnostic requires exact V44 loader')
return add_imports(data,(("GWNativeBridge.dll","gw_bridge_abi"),))
def _build_nohelper_profile5(out, *, login_dr0_candidate=False,
login_dr0_diagnostic=False, public_profile=0,
profile5_auth_host='127.0.0.1',owned_signin_only=False):
"""Build the maintained direct-seam client component in an isolated directory.
owned_signin_only builds with -DGW_OWNED_SIGNIN_ONLY=1: the stock Login site is
never patched or re-armed and its capture thunk is not linked; only the owned
Account page row C_Login.SignInTurtleAccount publishes the sign-in mailbox.
profile5_auth_host is the local realmd IPv4 the Bridge pins and compares with
the Wire's auth endpoint (direct_profile5_prepare); it must equal the Wire's
--source-local-auth-host (127.0.0.1 on the Wine host, 192.168.122.1 from the VM)."""
source_dir=ROOT/'native/nohelper'
octets=str(profile5_auth_host).split('.')
if len(octets)!=4 or not all(o.isdigit() and 0<=int(o)<=255 and o==str(int(o)) for o in octets):
raise ValueError('profile5 auth host must be a dotted IPv4 literal')
names=('bridge_coordinator.c','owner_poll_self.c','poll_coordinator.c',
'startup_nohelper.c','startup_windows_transaction.c',
'startup_graphics_dispatch.S','blizzard_egress.c',
'direct_login_patch_plan.c','direct_near_relays.c',
'direct_login_thunk.S','direct_two_site_transaction.c',
'direct_two_site_install.c','direct_profile5_prepare.c',
'direct_login_capture.c','direct_login_dr0_observer.c',
'original_c49_capture.c',
'original_connect_export_hook.c',
'original_connect_export_thunk.S',
'pipe_admission_snapshot.c',
'pipe_return_callback.c','pipe_return_thunk.S',
'openrealm_return_plan.c','pipe_atomic.c','pipe_live_input.c',
'constructor_seam_plan.c','realm_seam_page.c','login_site_pages.c','bridge_marker.c',
'clogin_realm_rows.c','clogin_register_thunk.S')
canonical=('engine_pe_bridge.c','engine_registration.c','engine_poll_host.c',
'engine_packet_host.c','source_login_registration.c')
flags=['--target=x86_64-pc-windows-msvc','-O2','-Wall','-Wextra','-Werror',
'-Wno-missing-field-initializers','-fno-stack-protector',
'-ffreestanding','-fno-builtin','-funwind-tables','-D_ACRTIMP=',
'-DGW_SOURCE_ONLY_PROFILE=3',
*(['-DGW_DIRECT_PUBLIC_PROFILE=%d'%public_profile] if public_profile else
['-DGW_DIRECT_PROFILE5_AUTH_IPV4="%s"'%profile5_auth_host,
'-DGW_DIRECT_PROFILE5_AUTH_PORT=3724']),
*(['-DGW_OWNED_SIGNIN_ONLY=1'] if owned_signin_only else []),'-I/usr/include/wine',
'-I/usr/include/wine/windows','-I/usr/include/wine/msvcrt',
'-I'+str(source_dir),'-I'+str(ROOT/'native')]
if login_dr0_candidate or login_dr0_diagnostic:
raise ValueError('The DR0 Login experiment is archived; maintained profile5 uses the accepted first-login E9/C49 route')
objects=[]
for index,path in enumerate([*(ROOT/'native'/n for n in canonical),
*(source_dir/n for n in names)]):
obj=out/('profile5-%02d.obj'%index)
source_flags=flags
if path.name=='startup_nohelper.c':
source_flags=[flag for flag in flags if not flag.startswith('-DGW_SOURCE_ONLY_PROFILE=')]
source_flags.append('-DGW_SOURCE_ONLY_PROFILE=2')
result=subprocess.run(['clang',*source_flags,'-c',str(path),'-o',str(obj)],
capture_output=True,text=True)
(out/('profile5-%02d.compile.private.log'%index)).write_text(
result.stdout+result.stderr)
if result.returncode:raise RuntimeError('Profile5 compile failed: '+path.name)
objects.append(str(obj))
dll=out/'GWNativeBridge.dll'
command=['lld-link','/dll','/noentry','/nodefaultlib','/timestamp:0',
'/def:'+str(source_dir/'exports.def'),'/out:'+str(dll),
'/implib:'+str(out/'GWNativeBridge.lib'),*objects,
'/usr/lib/wine/x86_64-windows/libmsvcrt.a',
'/usr/lib/wine/x86_64-windows/libkernel32.a',
'/usr/lib/wine/x86_64-windows/libuser32.a']
result=subprocess.run(command,capture_output=True,text=True)
(out/'profile5-link.private.log').write_text(result.stdout+result.stderr)
if result.returncode:raise RuntimeError('Profile5 Bridge link failed')
binary=dll.read_bytes();pe=pefile.PE(data=binary)
if not getattr(pe,'DIRECTORY_ENTRY_EXCEPTION',None) or pe.OPTIONAL_HEADER.AddressOfEntryPoint:
raise RuntimeError('Profile5 Bridge unwind or no-entry contract failed')
imports={row.dll.lower() for row in pe.DIRECTORY_ENTRY_IMPORT}
if not imports <= {b'kernel32.dll',b'user32.dll',b'msvcrt.dll'}:
raise RuntimeError('Profile5 Bridge imports changed')
exports={row.name.decode():row.address for row in pe.DIRECTORY_ENTRY_EXPORT.symbols if row.name}
required={'gw_bridge_abi','gw_bridge_nohelper_status','gw_poll_collection_pages_v33'}
if not required <= exports.keys():
raise RuntimeError('Profile5 Bridge exports missing')
if owned_signin_only and (0x14242e19e).to_bytes(8,'little') in binary:
raise RuntimeError('Owned-sign-in-only Bridge still carries the stock Login resume')
return binary,exports
def build(*,source_only_profile=0,output_directory=None,
login_dr0_candidate=False,login_dr0_diagnostic=False,nohelper_public=False,
profile5_auth_host='127.0.0.1',owned_signin_only=False):
if type(source_only_profile) is not int or source_only_profile not in (0,2,3,4,5):
raise ValueError('Unsupported Source-only profile')
default_out=ROOT/'build/native-pe'
out=Path(output_directory).resolve() if output_directory is not None else default_out
if source_only_profile and out==default_out.resolve():
raise ValueError('Source-only candidates require a separate output directory')
if login_dr0_candidate or login_dr0_diagnostic:
raise ValueError('The DR0 Login experiment is archived; maintained profile5 uses the accepted first-login E9/C49 route')
if owned_signin_only and (source_only_profile!=5 or nohelper_public):
raise ValueError('--owned-signin-only applies to the profile-5 Bridge only')
out.mkdir(parents=True,exist_ok=True)
if nohelper_public:
# Helper-free direct Bridge bound to the public profile-2 Source.
if source_only_profile!=2:raise ValueError('Helper-free public Bridge is profile 2 only')
return _build_nohelper_profile5(out,public_profile=2)
if source_only_profile==5:
return _build_nohelper_profile5(out,
login_dr0_candidate=login_dr0_candidate,
login_dr0_diagnostic=login_dr0_diagnostic,
profile5_auth_host=profile5_auth_host,
owned_signin_only=owned_signin_only)
if profile5_auth_host!='127.0.0.1':
raise ValueError('--profile5-auth-host applies to the profile-5 Bridge only')
objects=[]
sources=('engine_pe_bridge','engine_registration','engine_poll_host','engine_packet_host')
if source_only_profile:sources+=('source_login_registration',)
for source in sources:
obj=out/(source+'.obj');objects.append(str(obj))
flags=['clang','--target=x86_64-pc-windows-msvc','-O2','-Wall','-Wextra','-Werror','-Wno-missing-field-initializers','-fno-stack-protector','-ffreestanding','-funwind-tables']
if source_only_profile:flags.append('-DGW_SOURCE_ONLY_PROFILE='+str(source_only_profile))
subprocess.run([*flags,'-c',str(ROOT/'native'/(source+'.c')),'-o',str(obj)],check=True)
subprocess.run(['lld-link','/dll','/noentry','/nodefaultlib','/timestamp:0','/out:'+str(out/'GWNativeBridge.dll'),*objects],check=True)
binary=(out/'GWNativeBridge.dll').read_bytes();pe=pefile.PE(data=binary)
if not getattr(pe,'DIRECTORY_ENTRY_EXCEPTION',None):raise RuntimeError('Missing Windows unwind metadata')
validate_bridge_imports(pe)
return binary,{x.name.decode():x.address for x in pe.DIRECTORY_ENTRY_EXPORT.symbols if x.name}
def validate_bridge_imports(pe):
imports=getattr(pe,'DIRECTORY_ENTRY_IMPORT',[])
if imports or pe.OPTIONAL_HEADER.AddressOfEntryPoint:
raise RuntimeError('Registration provider must have no imports or DLL initialization entrypoint')
def validate_adapter_locations(data):
# Padding was observed as INT3 in executable70334 captures. The protected
# on-disk bytes are encrypted, so live bytes must ALSO match before patch.
pe=fast_pe(data);directory=pe.OPTIONAL_HEADER.DATA_DIRECTORY[3]
offset=pe.get_offset_from_rva(directory.VirtualAddress)
functions=list(struct.iter_unpack('<III',data[offset:offset+directory.Size]))
for address in (0x144597493,0x1445979a4):
rva=address-0x140000000
if any(begin<rva+12 and rva<end for begin,end,_ in functions):raise RuntimeError('Adapter overlaps a real function/unwind range')
if not any(s.VirtualAddress<=rva and rva+12<=s.VirtualAddress+s.Misc_VirtualSize and s.Characteristics&0x20000000 for s in pe.sections):raise RuntimeError('Adapter outside client executable section')
def prepare():
from client_installation import running_clients
if running_clients():raise RuntimeError('Close development WowB before preparing its private prefix')
client=(GAME/'WowB.exe').read_bytes()
if sha(client)!=ORIGINAL:raise RuntimeError('Require unchanged experimental WowB; preserve unrelated modifications')
validate_adapter_locations(client)
source=Path.home()/'Projects/WoW-Hybrid/wine-forever'
prefix=ROOT/'runtime/native-wine-prefix';marker=prefix/'gateway-private-prefix.json'
if not prefix.exists():
temporary=ROOT/'runtime/native-wine-prefix.new'
if temporary.exists():raise RuntimeError('Existing staged prefix preserved')
subprocess.run(['cp','--archive','--reflink=always',str(source),str(temporary)],check=True)
(temporary/'gateway-private-prefix.json').write_text(json.dumps({'source':str(source),'kind':'complete private CoW copy','original_modified':False})+'\n')
temporary.rename(prefix)
if not marker.exists() or json.loads(marker.read_text()).get('source')!=str(source):raise RuntimeError('Unrecognized private prefix preserved')
system=prefix/'drive_c/windows/system32';target=system/'d3d11.dll'
if target.is_symlink():raise RuntimeError('Never overwrite a linked system dependency')
previous=json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {}
baseline=(source/'drive_c/windows/system32/d3d11.dll').read_bytes()
if sha(target.read_bytes()) not in (sha(baseline),previous.get('dependency_patched_sha256')):raise RuntimeError('Unrelated private dependency changes preserved')
recovery=ROOT/'recovery/native-pe-graphics';recovery.mkdir(exist_ok=True,mode=0o700)
backup=recovery/'d3d11.dll'
if not backup.exists():backup.write_bytes(baseline)
if sha(backup.read_bytes())!=sha(baseline):raise RuntimeError('Original dependency changed since backup; preserve both versions')
binary,exports=build();patched=add_import(baseline)
dll=system/'GWNativeBridge.dll'
if dll.exists() and sha(dll.read_bytes()) not in (sha(binary),previous.get('dll_sha256')):raise RuntimeError('Unrelated bridge DLL preserved')
for path,data in ((dll,binary),(target,patched)):
temporary=path.with_name(path.name+'.native-new');temporary.write_bytes(data);temporary.replace(path)
manifest={'host':'private_prefix_d3d11','wine_prefix':str(prefix),'original_sha256':ORIGINAL,'patched_sha256':ORIGINAL,
'dll_sha256':sha(binary),'exports':exports,'dependency_baseline_sha256':sha(baseline),'dependency_patched_sha256':sha(patched),
'original_loader_modified':False,'original_wine_prefix_modified':False,'client_authenticode_signature_changed':False,
'schema_validation_modified':False,'restored':False,'namespace_registered':False,
'purpose':'Windows-unwind-aware observer and registration provider; opt-in debugger extends genuine namespace arguments once; no engine authentication',
'rollback':'Close experimental WowB, then python3 ops/native_pe_bridge.py restore. Original client/prefix unchanged.'}
MANIFEST.write_text(json.dumps(manifest,indent=2)+'\n')
print('Prepared Windows-unwind-aware observer in complete private CoW prefix. Original WowB, loader and Wine prefix unchanged.')
def restore():
from client_installation import running_clients
if running_clients():raise RuntimeError('Close development WowB before rollback')
m=json.loads(MANIFEST.read_text());prefix=Path(m['wine_prefix'])
if prefix!=ROOT/'runtime/native-wine-prefix':raise RuntimeError('Unexpected prefix; preserved')
if sha((GAME/'WowB.exe').read_bytes())!=ORIGINAL:raise RuntimeError('Unrelated PE changes preserved')
target=prefix/'drive_c/windows/system32/d3d11.dll'
baseline=(ROOT/'recovery/native-pe-graphics/d3d11.dll').read_bytes()
if sha(baseline)!=m['dependency_baseline_sha256']:raise RuntimeError('Recovery identity mismatch')
if target.is_symlink() or sha(target.read_bytes()) not in (m['dependency_baseline_sha256'],m['dependency_patched_sha256'],m.get('dependency_previous_patched_sha256')):raise RuntimeError('Unrelated dependency changes preserved')
temporary=target.with_name('d3d11.dll.native-restore');temporary.write_bytes(baseline);temporary.replace(target)
m['restored']=True;MANIFEST.write_text(json.dumps(m,indent=2)+'\n')
print('Restored byte-identical DXVK in private prefix. Original installation/prefix never changed; unused observer DLL retained.')
if __name__=='__main__':
import argparse,os
os.umask(0o077)
p=argparse.ArgumentParser();p.add_argument('action',choices=('build','prepare','restore','build-loader-package'))
p.add_argument('--source-only-profile',type=int,choices=(0,2,3,4,5),default=0)
p.add_argument('--output-directory',type=Path)
p.add_argument('--login-dr0-candidate',action='store_true')
p.add_argument('--login-dr0-diagnostic',action='store_true')
p.add_argument('--nohelper-public',action='store_true')
p.add_argument('--loader-source',type=Path)
p.add_argument('--loader-rea-receipt',type=Path)
p.add_argument('--package-template',type=Path)
p.add_argument('--profile5-auth-host',default='127.0.0.1',
help='local realmd IPv4 the profile-5 Bridge pins; must equal the Wire --source-local-auth-host (VM: 192.168.122.1)')
p.add_argument('--owned-signin-only',action='store_true',
help='profile-5 Bridge without the stock Login-site hook; sign-in only from the owned Account page row')
a=p.parse_args()
if a.action=='build':build(source_only_profile=a.source_only_profile,
output_directory=a.output_directory,
login_dr0_candidate=a.login_dr0_candidate,
login_dr0_diagnostic=a.login_dr0_diagnostic,
nohelper_public=a.nohelper_public,
profile5_auth_host=a.profile5_auth_host,
owned_signin_only=a.owned_signin_only)
elif a.action=='build-loader-package':
if a.source_only_profile or not all((a.output_directory,a.loader_source,a.loader_rea_receipt,a.package_template)):
p.error('Fresh output, loader source, REA receipt and existing package template required')
result=build_loader_package(source=a.loader_source,rea_receipt=a.loader_rea_receipt,
package_template=a.package_template,output_directory=a.output_directory)
print('Guarded V44 loader package staged:',result['manifest'])
else:
if a.source_only_profile or a.output_directory or any((a.loader_source,a.loader_rea_receipt,a.package_template)):
p.error('Build arguments do not apply to prepare/restore')
globals()[a.action]()