Files
WoW-Hybrid-gateway/ops/dx12_native_bootstrap.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

308 lines
15 KiB
Python

"""Build the pinned DX12 gateway carrier without changing an installed Wine prefix.
The retained VKD3D D3D12CreateDevice body stays at RVA 0x11d80. Its export
entry forwards to GWNativeBridge.gw_startup_D3D12CreateDevice, whose wrapper
calls that retained body directly after the native gateway has started.
"""
import argparse
import hashlib
import json
import os
import shutil
import struct
from pathlib import Path
import pefile
if __package__:
from .native_pe_bridge import add_imports, checksum
else:
from native_pe_bridge import add_imports, checksum
SOURCE_SHA256 = '21d1cb64f521d55bb417d17824a796994569c2af3d891cfc16ae2e3bcf156c13'
SOURCE_BYTES = 126976
SOURCE_SECTIONS = 10
ORIGINAL_CREATE_RVA = 0x11d80
FORWARDER = b'GWNativeBridge.gw_startup_D3D12CreateDevice'
DEPENDENCIES = (('GWNativeBridge.dll', 'gw_bridge_abi'),
('GWNativeWire.dll', 'gw_wire_abi'))
ORIGINAL_IMPORTS = (b'KERNEL32.dll', b'msvcrt.dll',
b'api-ms-win-core-path-l1-1-0.dll', b'VERSION.dll')
ORIGINAL_EXPORTS = {
b'D3D12CreateRootSignatureDeserializer': (95, 0x11df0),
b'D3D12CreateVersionedRootSignatureDeserializer': (96, 0x11e60),
b'D3D12EnableExperimentalFeatures': (97, 0x11ed0),
b'D3D12GetInterface': (98, 0x11fe0),
b'D3D12SerializeRootSignature': (99, 0x120f0),
b'D3D12SerializeVersionedRootSignature': (100, 0x12160),
b'D3D12CreateDevice': (101, ORIGINAL_CREATE_RVA),
b'D3D12GetDebugInterface': (102, 0x11f70),
}
def sha(data):
return hashlib.sha256(data).hexdigest()
def align(value, unit):
return (value + unit - 1) // unit * unit
def imports(pe):
return [(row.dll, tuple((item.name, item.ordinal) for item in row.imports))
for row in pe.DIRECTORY_ENTRY_IMPORT]
def exports(pe):
return {row.name: (row.ordinal, row.address, row.forwarder)
for row in pe.DIRECTORY_ENTRY_EXPORT.symbols if row.name}
def verify_original(data):
if len(data) != SOURCE_BYTES or sha(data) != SOURCE_SHA256:
raise ValueError('Pinned original VKD3D d3d12.dll identity differs')
pe = pefile.PE(data=data)
if (pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20b
or pe.FILE_HEADER.NumberOfSections != SOURCE_SECTIONS):
raise ValueError('Pinned AMD64 PE32+ section contract differs')
if tuple(row.dll for row in pe.DIRECTORY_ENTRY_IMPORT) != ORIGINAL_IMPORTS:
raise ValueError('Pinned original VKD3D imports differ')
found = exports(pe)
if (len(found) != len(ORIGINAL_EXPORTS)
or {name: (ordinal, address) for name, (ordinal, address, forward) in found.items()}
!= ORIGINAL_EXPORTS or any(forward for _, _, forward in found.values())):
raise ValueError('Pinned original VKD3D export contract differs')
return pe
def add_creation_forwarder(data):
"""Clone the export directory, changing only D3D12CreateDevice's EAT RVA."""
source = pefile.PE(data=data)
old = source.DIRECTORY_ENTRY_EXPORT.struct
symbols = list(source.DIRECTORY_ENTRY_EXPORT.symbols)
target = next((row for row in symbols if row.name == b'D3D12CreateDevice'), None)
if (target is None or target.ordinal != 101 or target.address != ORIGINAL_CREATE_RVA
or target.forwarder):
raise ValueError('Original D3D12CreateDevice export body differs')
section_rva = align(max(section.VirtualAddress +
max(section.Misc_VirtualSize, section.SizeOfRawData)
for section in source.sections),
source.OPTIONAL_HEADER.SectionAlignment)
raw = align(len(data), source.OPTIONAL_HEADER.FileAlignment)
header_offset = source.sections[-1].get_file_offset() + 40
if (header_offset + 40 > min(section.PointerToRawData for section in source.sections
if section.PointerToRawData)
or any(data[header_offset:header_offset + 40])):
raise ValueError('No empty second section header for export metadata')
names = sorted((row for row in symbols if row.name), key=lambda row: row.name)
func_offset = 40
name_offset = func_offset + 4 * old.NumberOfFunctions
ordinal_offset = name_offset + 4 * len(names)
blob = bytearray(ordinal_offset + 2 * len(names))
def string(value):
address = section_rva + len(blob)
blob.extend(value + b'\0')
return address
module_name = string(source.get_string_at_rva(old.Name))
old_export_dir = source.OPTIONAL_HEADER.DATA_DIRECTORY[0]
for index in range(old.NumberOfFunctions):
address = source.get_dword_at_rva(old.AddressOfFunctions + 4 * index)
if old_export_dir.VirtualAddress <= address < old_export_dir.VirtualAddress + old_export_dir.Size:
address = string(source.get_string_at_rva(address))
struct.pack_into('<I', blob, func_offset + 4 * index, address)
for index, row in enumerate(names):
struct.pack_into('<I', blob, name_offset + 4 * index, string(row.name))
struct.pack_into('<H', blob, ordinal_offset + 2 * index, row.ordinal - old.Base)
forwarder_rva = string(FORWARDER)
struct.pack_into('<I', blob, func_offset + 4 * (target.ordinal - old.Base),
forwarder_rva)
struct.pack_into('<IIHHIIIIIII', blob, 0, old.Characteristics, old.TimeDateStamp,
old.MajorVersion, old.MinorVersion, module_name, old.Base,
old.NumberOfFunctions, len(names), section_rva + func_offset,
section_rva + name_offset, section_rva + ordinal_offset)
raw_size = align(len(blob), source.OPTIONAL_HEADER.FileAlignment)
output = bytearray(data)
output[header_offset:header_offset + 40] = struct.pack(
'<8sIIIIIIHHI', b'.gwexp\0\0', len(blob), section_rva, raw_size, raw,
0, 0, 0, 0, 0x40000040)
struct.pack_into('<H', output,
source.FILE_HEADER.get_field_absolute_offset('NumberOfSections'),
source.FILE_HEADER.NumberOfSections + 1)
struct.pack_into('<I', output,
source.OPTIONAL_HEADER.get_field_absolute_offset('SizeOfImage'),
align(section_rva + len(blob), source.OPTIONAL_HEADER.SectionAlignment))
struct.pack_into('<II', output, old_export_dir.get_file_offset(),
section_rva, len(blob))
output.extend(bytes(raw - len(output)))
output.extend(blob)
output.extend(bytes(raw_size - len(blob)))
parsed = pefile.PE(data=bytes(output))
checksum_offset = parsed.OPTIONAL_HEADER.get_field_absolute_offset('CheckSum')
struct.pack_into('<I', output, checksum_offset, checksum(output, checksum_offset))
return bytes(output)
def verify_candidate(original, candidate):
before = verify_original(original)
after = pefile.PE(data=candidate)
if after.FILE_HEADER.NumberOfSections != SOURCE_SECTIONS + 2:
raise ValueError('DX12 candidate section count differs')
if [section.Name.rstrip(b'\0') for section in after.sections[-2:]] != [b'.gwimp', b'.gwexp']:
raise ValueError('DX12 candidate sections differ')
before_imports = imports(before)
after_imports = imports(after)
if (after_imports[:len(before_imports)] != before_imports
or [name for name, _ in after_imports[len(before_imports):]]
!= [b'GWNativeBridge.dll', b'GWNativeWire.dll']
or [symbols for _, symbols in after_imports[len(before_imports):]]
!= [((b'gw_bridge_abi', None),), ((b'gw_wire_abi', None),)]):
raise ValueError('Original imports or gateway dependency imports differ')
before_exports = exports(before)
after_exports = exports(after)
if before_exports.keys() != after_exports.keys():
raise ValueError('Export names changed')
for name, old in before_exports.items():
new = after_exports[name]
if name == b'D3D12CreateDevice':
if new[0] != old[0] or new[2] != FORWARDER:
raise ValueError('D3D12CreateDevice forwarder differs')
elif new != old:
raise ValueError('Other VKD3D export changed: ' + name.decode())
for old, new in zip(before.sections, after.sections):
if (old.__pack__() != new.__pack__()
or original[old.PointerToRawData:old.PointerToRawData + old.SizeOfRawData]
!= candidate[new.PointerToRawData:new.PointerToRawData + new.SizeOfRawData]):
raise ValueError('Original VKD3D section bytes or header changed')
for index, (old, new) in enumerate(zip(before.OPTIONAL_HEADER.DATA_DIRECTORY,
after.OPTIONAL_HEADER.DATA_DIRECTORY)):
if index not in (0, 1) and old.__pack__() != new.__pack__():
raise ValueError(f'Non-import/export PE data directory {index} changed')
checksum_offset = after.OPTIONAL_HEADER.get_field_absolute_offset('CheckSum')
if after.OPTIONAL_HEADER.CheckSum != checksum(candidate, checksum_offset):
raise ValueError('DX12 candidate PE checksum differs')
# The original file is untouched except for six documented PE header fields
# and two previously empty section-header slots. All original code is exact.
permitted = set()
for offset, length in (
(before.FILE_HEADER.get_field_absolute_offset('NumberOfSections'), 2),
(before.OPTIONAL_HEADER.get_field_absolute_offset('SizeOfImage'), 4),
(before.OPTIONAL_HEADER.get_field_absolute_offset('CheckSum'), 4),
(before.OPTIONAL_HEADER.DATA_DIRECTORY[0].get_file_offset(), 8),
(before.OPTIONAL_HEADER.DATA_DIRECTORY[1].get_file_offset(), 8),
(before.sections[-1].get_file_offset() + 40, 80),
):
permitted.update(range(offset, offset + length))
changed = [index for index, (old, new) in enumerate(zip(original, candidate))
if old != new]
if any(index not in permitted for index in changed):
raise ValueError('DX12 candidate changed an unexpected original byte')
return {
'source_sha256': SOURCE_SHA256, 'candidate_sha256': sha(candidate),
'source_bytes': len(original), 'candidate_bytes': len(candidate),
'original_create_rva': hex(ORIGINAL_CREATE_RVA),
'create_forwarder': FORWARDER.decode(),
'original_exports_preserved': len(before_exports) - 1,
'original_import_descriptors_preserved': len(before_imports),
'original_sections_preserved': len(before.sections),
'changed_original_header_bytes': len(changed),
'runtime_acceptance': 'pending',
}
def verify_pair(candidate_dir, bridge_path, wire_path):
"""Check the exact PE dependency pair before any owned trial installation."""
candidate_dir = Path(candidate_dir)
bridge_path = Path(bridge_path)
wire_path = Path(wire_path)
if any(path.is_symlink() or not path.is_file() for path in
(candidate_dir / 'd3d12.dll', candidate_dir / 'preimages/d3d12.dll',
bridge_path, wire_path)):
raise ValueError('DX12 pair requires regular pinned PE files')
original = (candidate_dir / 'preimages/d3d12.dll').read_bytes()
candidate = (candidate_dir / 'd3d12.dll').read_bytes()
audit = verify_candidate(original, candidate)
metadata = json.loads((candidate_dir / 'candidate.json').read_text())
if (metadata.get('source_sha256') != audit['source_sha256']
or metadata.get('candidate_sha256') != audit['candidate_sha256']
or metadata.get('create_forwarder') != FORWARDER.decode()):
raise ValueError('DX12 candidate receipt differs from bytes')
bridge = pefile.PE(str(bridge_path))
wire = pefile.PE(str(wire_path))
bridge_exports = exports(bridge)
wire_exports = exports(wire)
if bridge_exports.get(b'gw_startup_D3D12CreateDevice', (None,))[0] != 27:
raise ValueError('Paired Bridge lacks DX12 startup export ordinal 27')
if b'gw_bridge_abi' not in bridge_exports or b'gw_wire_abi' not in wire_exports:
raise ValueError('Paired Bridge/Wire ABI import symbols absent')
if bridge.OPTIONAL_HEADER.AddressOfEntryPoint:
raise ValueError('Paired Bridge must keep no-entry loader contract')
return {
'candidate_sha256': audit['candidate_sha256'],
'bridge_sha256': sha(bridge_path.read_bytes()),
'wire_sha256': sha(wire_path.read_bytes()),
'required_export': FORWARDER.decode(),
'bridge_export_ordinal': 27,
'bridge_no_entry': True,
'pe_pair_verified': True,
'installed': False,
'launched': False,
}
def build(source_path, output_dir):
source_path = Path(source_path)
output_dir = Path(output_dir)
if source_path.is_symlink() or not source_path.is_file():
raise ValueError('Pinned original VKD3D source must be a regular file')
if output_dir.exists():
raise ValueError('Candidate output directory already exists; preserve earlier build')
original = source_path.read_bytes()
verify_original(original)
imported = add_imports(original, DEPENDENCIES)
candidate = add_creation_forwarder(imported)
receipt = verify_candidate(original, candidate)
partial = output_dir.with_name(output_dir.name + '.partial')
if partial.exists():
raise ValueError('Candidate partial directory already exists')
partial.mkdir(parents=True, mode=0o700)
try:
preimages = partial / 'preimages'
preimages.mkdir(mode=0o700)
shutil.copy2(source_path, preimages / 'd3d12.dll')
if sha((preimages / 'd3d12.dll').read_bytes()) != SOURCE_SHA256:
raise ValueError('Offline VKD3D preimage copy differs')
(preimages / 'd3d12.dll').chmod(0o400)
target = partial / 'd3d12.dll'
with target.open('xb') as stream:
stream.write(candidate)
stream.flush()
os.fsync(stream.fileno())
target.chmod(0o600)
receipt.update(kind='dx12-gateway-import-and-create-forwarder-v1',
original_path=str(source_path),
candidate_path=str(output_dir / 'd3d12.dll'),
preimage_path=str(output_dir / 'preimages/d3d12.dll'),
deployment_target='selected-owned-Wine-prefix/drive_c/windows/system32/d3d12.dll',
bridge_required_export='gw_startup_D3D12CreateDevice',
bridge_pair_required=True, profile='independent of profile2/profile5',
installed=False, launched=False)
(partial / 'candidate.json').write_text(json.dumps(receipt, indent=2) + '\n')
partial.rename(output_dir)
except BaseException:
# Preserve evidence on a failure instead of modifying the source or
# silently replacing an earlier candidate.
raise
return receipt
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--source', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
print(json.dumps(build(args.source, args.output), indent=2))