Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions benchmarks/mixed-text-placement/relink.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
#!/usr/bin/env python3
"""Relink captured Mach-O objects, auditing isolated and whole-code movement."""
import argparse
from collections import Counter
import json
import pathlib
import re
import subprocess

AUDIT_DISPLACEMENT_LIMIT = 8
AUDIT_SAMPLE_LIMIT = 5


def symbols(binary):
"""Return {name: (address, kind)} from `nm -n` for the given Mach-O binary."""
Expand Down Expand Up @@ -45,14 +49,33 @@ def audit_step(mode, current, prior, selected, front_step):
"""Verify exact symbol displacement against the preceding placement."""
differences = {s: current[s][0] - prior[s][0] for s in current}
if mode == 'local':
unexpected = {s: d for s, d in differences.items() if d != (4 if s == selected else 0)}
audited = differences
unexpected = {s: d for s, d in audited.items() if d != (4 if s == selected else 0)}
else:
# Check the actual increment; reject linker alignment rounding.
unexpected = {s: d for s, d in differences.items()
if (current[s][1].lower() == 't' or prior[s][1].lower() == 't')
and s != '__mh_execute_header' and d != front_step}
if unexpected:
raise ValueError(f'{mode} placement audit failed: {unexpected}')
audited = {s: d for s, d in differences.items()
if (current[s][1].lower() == 't' or prior[s][1].lower() == 't')
and s != '__mh_execute_header'}
unexpected = {s: d for s, d in audited.items() if d != front_step}
if not unexpected:
return
if mode == 'local':
expectation = f'expected 4 bytes for {selected}, 0 otherwise'
ordered = sorted(unexpected, key=lambda s: (s != selected, current[s][0], s))
else:
expectation = f'expected {front_step} bytes'
ordered = sorted(unexpected, key=lambda s: (current[s][0], s))
counts = sorted(Counter(audited.values()).items(), key=lambda item: (-item[1], item[0]))
shown_counts = ', '.join(f'{shift}: {count}' for shift, count in counts[:AUDIT_DISPLACEMENT_LIMIT])
if len(counts) > AUDIT_DISPLACEMENT_LIMIT:
shown_counts += f' (+{len(counts) - AUDIT_DISPLACEMENT_LIMIT} more)'
shown_samples = ', '.join(f'{s} ({unexpected[s]})' for s in ordered[:AUDIT_SAMPLE_LIMIT])
if len(ordered) > AUDIT_SAMPLE_LIMIT:
shown_samples += f' (+{len(ordered) - AUDIT_SAMPLE_LIMIT} more)'
raise ValueError(
f'{mode} placement audit failed: {len(unexpected)}/{len(audited)} unexpected ({expectation}); '
f'observed displacements (bytes): {shown_counts}; sample: {shown_samples}'
)


def run(link, reference, output, count=32, front_step=16, front_only=False):
Expand Down
94 changes: 93 additions & 1 deletion benchmarks/mixed-text-placement/test_relink.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,90 @@ def changed_inventory(binary):
self.assertRaisesRegex(ValueError, 'expected at least one text symbol'):
relink.run(link, reference, root / 'empty-text', count=1, front_step=64, front_only=True)

def test_audit_summarizes_front_displacement_distribution_and_sample(self) -> None:
prior = {
'__mh_execute_header': (0x100000000, 'T'),
'_const_data': (0x100200000, 's'),
}
current = dict(prior)
for index in range(29):
addr = 0x100001000 + 16 * index
prior[f'_moved_{index:04}'] = (addr, 't')
current[f'_moved_{index:04}'] = (addr + 16, 't')
for index in range(5621):
addr = 0x100002000 + 16 * index
prior[f'_stuck_{index:04}'] = (addr, 'T')
current[f'_stuck_{index:04}'] = (addr, 'T')

with self.assertRaises(ValueError) as caught:
relink.audit_step('front', current, prior, None, 16)
message = str(caught.exception)
self.assertIn('front placement audit failed: 5621/5650 unexpected (expected 16 bytes)', message)
self.assertIn('observed displacements (bytes): 0: 5621, 16: 29', message)
self.assertIn(
'sample: _stuck_0000 (0), _stuck_0001 (0), _stuck_0002 (0), _stuck_0003 (0), _stuck_0004 (0) (+5616 more)',
message,
)
self.assertNotIn('_stuck_0005', message)
self.assertNotIn('_moved_0000', message)
self.assertNotIn('_const_data', message)
self.assertNotIn('__mh_execute_header', message)

def test_audit_summarizes_local_failures_and_caps_displacement_buckets(self) -> None:
selected = '__RNv_vibescript4json6writer10write_text'
prior = {
'__mh_execute_header': (0x100000000, 'T'),
selected: (0x100001000, 't'),
'_other': (0x100002000, 'T'),
}
with self.assertRaises(ValueError) as caught:
relink.audit_step('local', dict(prior), prior, selected, 16)
message = str(caught.exception)
self.assertEqual(
message,
f'local placement audit failed: 1/3 unexpected (expected 4 bytes for {selected}, 0 otherwise); '
f'observed displacements (bytes): 0: 3; sample: {selected} (0)',
)

prior_many = {selected: (0x100002000, 't'), '_still': (0x100003000, 'T')}
current_many = dict(prior_many)
for index in range(6):
addr = 0x100001000 + 16 * index
prior_many[f'_drifted_{index}'] = (addr, 'T')
current_many[f'_drifted_{index}'] = (addr + 16, 'T')
with self.assertRaises(ValueError) as caught:
relink.audit_step('local', current_many, prior_many, selected, 16)
message = str(caught.exception)
self.assertIn(
f'local placement audit failed: 7/8 unexpected (expected 4 bytes for {selected}, 0 otherwise)',
message,
)
self.assertIn('observed displacements (bytes): 16: 6, 0: 2', message)
self.assertIn(
f'sample: {selected} (0), _drifted_0 (16), _drifted_1 (16), _drifted_2 (16), _drifted_3 (16) (+2 more)',
message,
)
self.assertNotIn('_drifted_4', message)

prior_buckets = {}
current_buckets = {}
for index in range(10):
addr = 0x100001000 + 64 * index
prior_buckets[f'_sym_{index:02}'] = (addr, 't')
current_buckets[f'_sym_{index:02}'] = (addr + 4 * index, 't')
with self.assertRaises(ValueError) as caught:
relink.audit_step('front', current_buckets, prior_buckets, None, 16)
message = str(caught.exception)
self.assertIn('front placement audit failed: 9/10 unexpected (expected 16 bytes)', message)
self.assertIn(
'observed displacements (bytes): 0: 1, 4: 1, 8: 1, 12: 1, 16: 1, 20: 1, 24: 1, 28: 1 (+2 more)',
message,
)
self.assertIn(
'sample: _sym_00 (0), _sym_01 (4), _sym_02 (8), _sym_03 (12), _sym_05 (20) (+4 more)',
message,
)


@unittest.skipUnless(platform.system() == 'Darwin' and platform.machine() == 'arm64',
'Mach-O relink integration tests require Apple Silicon macOS')
Expand Down Expand Up @@ -211,8 +295,16 @@ def test_front_only_64_byte_stride_and_alignment_audit_on_real_binary(self) -> N
relink.run(link_json, binary, root / 'default-out', count=2, front_step=64)

# A 16-byte front stride is absorbed by work's 64-byte alignment and caught by audit.
with self.assertRaisesRegex(ValueError, 'front placement audit failed'):
with self.assertRaises(ValueError) as caught:
relink.run(link_json, binary, root / 'bad-16', count=3, front_step=16, front_only=True)
audit_error = str(caught.exception)
self.assertIn(
'front placement audit failed: 2/2 unexpected (expected 16 bytes); '
'observed displacements (bytes): 0: 2; sample: ',
audit_error,
)
self.assertIn('_work (0)', audit_error)
self.assertIn('_main (0)', audit_error)

# A 64-byte front-only sweep succeeds via CLI and produces runnable binaries.
out_64 = root / 'ok-64'
Expand Down
Loading