227 lines
13 KiB
Python
227 lines
13 KiB
Python
"""Keep the maintained Wire DEF bound to the matched native PE export ABI."""
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
|
|
import pefile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DEFINITION = ROOT / 'native/nohelper/wire_exports.def'
|
|
REFERENCE = json.loads((ROOT / 'tests/fixtures/native_wire_exports_70334.json').read_text())
|
|
# The fixture preserves the original 80-export binary. Subsequent versions
|
|
# append named functions so every earlier consumer keeps its existing ordinals.
|
|
EXPECTED_EXPORTS = REFERENCE['exports'] + [
|
|
dict(name=name, ordinal=ordinal, data=False) for ordinal, name in enumerate((
|
|
'gw_wire_account_ui_cancel_generation', 'gw_wire_priority_begin',
|
|
'gw_wire_priority_status', 'gw_wire_priority_use_public',
|
|
'gw_wire_account_ui_snapshot_scoped', 'gw_source_create_stage_challenges',
|
|
), 81)
|
|
]
|
|
|
|
|
|
|
|
def definition_rows():
|
|
rows = []
|
|
for line in DEFINITION.read_text().splitlines()[2:]:
|
|
match = re.fullmatch(r'\s+(\w+)\s+@(\d+)(\s+DATA)?', line)
|
|
if not match:
|
|
raise ValueError('Unexpected Wire export definition syntax')
|
|
rows.append(dict(name=match[1], ordinal=int(match[2]), data=bool(match[3])))
|
|
return rows
|
|
|
|
|
|
def pe_rows(path):
|
|
image = pefile.PE(str(path), fast_load=True)
|
|
image.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT']])
|
|
rows = []
|
|
for entry in image.DIRECTORY_ENTRY_EXPORT.symbols:
|
|
if not entry.name or entry.forwarder:
|
|
raise ValueError('Wire exports must have original names and direct definitions')
|
|
section = image.get_section_by_rva(entry.address)
|
|
rows.append(dict(name=entry.name.decode('ascii'), ordinal=entry.ordinal,
|
|
data=not bool(section.Characteristics & 0x20000000)))
|
|
image.close()
|
|
return sorted(rows, key=lambda row: row['ordinal'])
|
|
|
|
|
|
class NativeWireExportContract(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.work = ROOT / 'build/native-wire-export-contract-tests'
|
|
cls.work.mkdir(parents=True, exist_ok=True)
|
|
|
|
def test_definition_preserves_matched_native_name_ordinal_and_data_contract(self):
|
|
self.assertEqual(definition_rows(), EXPECTED_EXPORTS)
|
|
self.assertEqual([row['ordinal'] for row in EXPECTED_EXPORTS], list(range(1, 87)))
|
|
self.assertEqual(EXPECTED_EXPORTS[71],
|
|
dict(name='gw_wire_shutdown', ordinal=72, data=False))
|
|
self.assertEqual(EXPECTED_EXPORTS[79],
|
|
dict(name='gw_wire_profile5_admit_diag_data', ordinal=80, data=True))
|
|
|
|
def test_real_coff_link_preserves_exports_and_import_library_data_types(self):
|
|
compiler = shutil.which('clang')
|
|
linker = shutil.which('lld-link')
|
|
reader = shutil.which('llvm-readobj')
|
|
self.assertTrue(compiler and linker and reader, 'LLVM COFF tools are required')
|
|
with tempfile.TemporaryDirectory(prefix='wire-export-', dir=self.work) as directory:
|
|
folder = Path(directory)
|
|
source = folder / 'exports.c'
|
|
# No dllexport attributes: the actual maintained DEF must control
|
|
# this link, including DATA import records and explicit ordinals.
|
|
source.write_text('\n'.join(
|
|
('int {name} = {ordinal};' if row['data'] else
|
|
'int {name}(void) {{ return {ordinal}; }}').format(**row)
|
|
for row in EXPECTED_EXPORTS) + '\n')
|
|
obj = folder / 'exports.obj'
|
|
dll = folder / 'GWNativeWire.dll'
|
|
library = folder / 'GWNativeWire.lib'
|
|
subprocess.run([compiler, '--target=x86_64-pc-windows-msvc', '-ffreestanding',
|
|
'-c', str(source), '-o', str(obj)], check=True, capture_output=True)
|
|
subprocess.run([linker, '/dll', '/noentry', '/nodefaultlib', '/machine:x64',
|
|
'/def:' + str(DEFINITION), str(obj), '/out:' + str(dll),
|
|
'/implib:' + str(library)], check=True, capture_output=True)
|
|
self.assertEqual(pe_rows(dll), EXPECTED_EXPORTS)
|
|
headers = subprocess.check_output([reader, '--file-header', str(library)], text=True)
|
|
imports = {}
|
|
for block in headers.split('Format: COFF-import-file')[1:]:
|
|
type_match = re.search(r'^Type: (\w+)$', block, re.M)
|
|
symbols = re.findall(r'^Symbol: (\w+)$', block, re.M)
|
|
self.assertIsNotNone(type_match)
|
|
for symbol in symbols:
|
|
symbol = symbol.removeprefix('__imp_')
|
|
if symbol.startswith('gw_'):
|
|
imports[symbol] = type_match[1].lower() == 'data'
|
|
self.assertEqual(imports, {row['name']: row['data'] for row in EXPECTED_EXPORTS})
|
|
|
|
def test_actual_production_admission_unit_defines_diagnostic_for_both_profiles(self):
|
|
compiler = shutil.which('clang')
|
|
linker = shutil.which('lld-link')
|
|
reader = shutil.which('llvm-readobj')
|
|
self.assertTrue(compiler and linker and reader, 'LLVM COFF tools are required')
|
|
sdk = Path('/usr/include/wine')
|
|
runtime = Path('/usr/lib/wine/x86_64-windows/libmsvcrt.a')
|
|
self.assertTrue((sdk / 'windows/windows.h').is_file() and runtime.is_file(),
|
|
'The maintained Wine Windows SDK/import library is required')
|
|
with tempfile.TemporaryDirectory(prefix='wire-production-admit-', dir=self.work) as directory:
|
|
folder = Path(directory)
|
|
# Link the actual production TU alone, without a replacement for
|
|
# its exported variable or admission function. The other 79 exports
|
|
# are covered by the full contract link above, not stubbed here.
|
|
selected = next(line for line in DEFINITION.read_text().splitlines()
|
|
if re.match(r'\s+gw_wire_profile5_admit_diag_data\s', line))
|
|
definition = folder / 'diagnostic.def'
|
|
definition.write_text('LIBRARY GWNativeWire\nEXPORTS\n' + selected + '\n')
|
|
for profile in (2, 5):
|
|
with self.subTest(profile=profile):
|
|
obj = folder / ('admit-' + str(profile) + '.obj')
|
|
dll = folder / ('admit-' + str(profile) + '.dll')
|
|
library = dll.with_suffix('.lib')
|
|
command = [compiler, '--target=x86_64-pc-windows-msvc',
|
|
'-I' + str(sdk), '-I' + str(sdk / 'windows'),
|
|
'-I' + str(sdk / 'msvcrt'), '-I' + str(ROOT / 'native'),
|
|
'-I' + str(ROOT / 'native/nohelper'), '-O2', '-Wall',
|
|
'-Wextra', '-Werror', '-ffreestanding',
|
|
'-fno-stack-protector', '-funwind-tables',
|
|
'-DNOMINMAX', '-DWIN32_LEAN_AND_MEAN',
|
|
'-D_WIN32_WINNT=0x0A00', '-DGW_NATIVE_WINDOWS=1',
|
|
'-DGW_NATIVE_LINKED_BACKEND=1',
|
|
'-DGW_SOURCE_UI_CREATE_EXPERIMENT=1',
|
|
'-DGW_SOURCE_ONLY_PROFILE=' + str(profile)]
|
|
if profile == 5:
|
|
command.append('-DGW_SOURCE_LOCAL_AUTH_IPV4="192.168.122.1"')
|
|
dependency = obj.with_suffix('.d')
|
|
command.extend(['-MMD', '-MF', str(dependency), '-c',
|
|
str(ROOT / 'native/nohelper/wire_profile5_auto_realm.c'),
|
|
'-o', str(obj)])
|
|
subprocess.run(command, check=True, capture_output=True)
|
|
dependencies = dependency.read_text()
|
|
for header in ('native/nohelper/wire_profile5_auto_realm.private.h',
|
|
'native/wine_wire_host.h',
|
|
'native/wine_session_retirement.h',
|
|
'native/nohelper/wine_preopen_hook.private.h'):
|
|
self.assertIn(str(ROOT / header), dependencies)
|
|
directives = subprocess.check_output([reader, '--coff-directives', str(obj)], text=True)
|
|
self.assertIn('/EXPORT:gw_wire_profile5_admit_diag_data,DATA', directives)
|
|
# Keep the actual admission function in the link too; no
|
|
# dead-strip can hide an unresolved production dependency.
|
|
subprocess.run([linker, '/dll', '/noentry', '/nodefaultlib', '/machine:x64',
|
|
'/include:gw_wire_profile5_auto_realm_admit',
|
|
'/def:' + str(definition), str(obj), str(runtime),
|
|
'/out:' + str(dll), '/implib:' + str(library)],
|
|
check=True, capture_output=True)
|
|
self.assertEqual(pe_rows(dll), [row for row in EXPECTED_EXPORTS
|
|
if row['name'] == 'gw_wire_profile5_admit_diag_data'])
|
|
image = pefile.PE(str(dll), fast_load=True)
|
|
image.parse_data_directories(directories=[0])
|
|
entry = image.DIRECTORY_ENTRY_EXPORT.symbols[0]
|
|
self.assertEqual(image.get_data(entry.address, 48),
|
|
struct.pack('<II', 1, 48) + bytes(40))
|
|
image.close()
|
|
headers = subprocess.check_output([reader, '--file-header', str(library)], text=True)
|
|
self.assertRegex(headers, r'Type: data[\s\S]*Symbol: __imp_gw_wire_profile5_admit_diag_data')
|
|
|
|
def test_cmake_generated_wire_link_uses_definition_for_both_endpoint_profiles(self):
|
|
compiler = shutil.which('clang')
|
|
cmake = shutil.which('cmake')
|
|
ninja = shutil.which('ninja')
|
|
self.assertTrue(compiler and cmake and ninja, 'CMake, Ninja and Clang are required')
|
|
with tempfile.TemporaryDirectory(prefix='wire-cmake-', dir=self.work) as directory:
|
|
folder = Path(directory)
|
|
toolchain = folder / 'toolchain.cmake'
|
|
toolchain.write_text('\n'.join([
|
|
'set(CMAKE_SYSTEM_NAME Windows)',
|
|
f'set(CMAKE_C_COMPILER "{compiler}")',
|
|
'set(CMAKE_C_COMPILER_TARGET x86_64-w64-windows-gnu)',
|
|
f'set(CMAKE_ASM_COMPILER "{compiler}")',
|
|
'set(CMAKE_ASM_COMPILER_TARGET x86_64-w64-windows-gnu)',
|
|
'set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)',
|
|
]) + '\n')
|
|
dummy = folder / 'codec-import.a'
|
|
dummy.write_bytes(b'configuration-only import path; never linked')
|
|
(folder / 'CMakeLists.txt').write_text('\n'.join([
|
|
'cmake_minimum_required(VERSION 3.20)',
|
|
'project(wire_contract C)',
|
|
f'set(CMAKE_CURRENT_SOURCE_DIR "{ROOT.as_posix()}")',
|
|
'add_library(GWNativeBackend INTERFACE)',
|
|
'set(GW_WINDOWS_NOHELPER_PROFILE5 ON)',
|
|
f'set(GW_WINDOWS_CODEC_IMPORT_LIBRARY "{dummy.as_posix()}")',
|
|
f'include("{ROOT.as_posix()}/cmake/WindowsNohelperProfile5.cmake")',
|
|
'file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/wire-sources.txt"',
|
|
' CONTENT "$<JOIN:$<TARGET_PROPERTY:GWNativeWireProfile5,SOURCES>,\\n>")',
|
|
]) + '\n')
|
|
for endpoint in ('OCTO', 'LOCAL'):
|
|
with self.subTest(endpoint=endpoint):
|
|
build = folder / endpoint
|
|
command = [cmake, '-S', str(folder), '-B', str(build), '-G', 'Ninja',
|
|
'-DCMAKE_TOOLCHAIN_FILE=' + str(toolchain),
|
|
'-DGW_WINDOWS_SOURCE_ENDPOINT=' + endpoint]
|
|
if endpoint == 'LOCAL':
|
|
command.extend('-DGW_WINDOWS_PROFILE5_' + name + '=' + value
|
|
for name, value in [('AUTH_IPV4', '192.168.122.1'),
|
|
('AUTH_PORT', '3724'),
|
|
('REALM_IPV4', '192.168.122.1'),
|
|
('REALM_PORT', '8090')])
|
|
result = subprocess.run(command, capture_output=True, text=True)
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
definition = DEFINITION.as_posix()
|
|
self.assertIn(definition, (build / 'wire-sources.txt').read_text().splitlines())
|
|
graph = (build / 'build.ninja').read_text()
|
|
# The definition is both a dependency and an actual linker
|
|
# input, so changing it causes a relink with the pinned ABI.
|
|
wire_rule = next(line for line in graph.splitlines()
|
|
if line.startswith('build windows-profile5/GWNativeWire.dll'))
|
|
self.assertIn(definition, wire_rule)
|
|
start = graph.index(wire_rule)
|
|
block = graph[start:graph.find('\n\n', start)]
|
|
self.assertTrue(any(definition in line and ('LINK_FLAGS =' in line or 'LINK_LIBRARIES =' in line)
|
|
for line in block.splitlines()), block)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|