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
3 changes: 2 additions & 1 deletion benchmarks/downcase-placement/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ python3 "$TOOLS/relink.py" "$BUILD/link/link.json" "$BUILD/compare" "$BUILD/layo
```

Relinking needs `cc`, `as`, `nm`, `readelf` and `objcopy`; each link takes
about a second. Write the case's fixture from `scripts/fixtures.py`, then time
about a second. Each layout's `link.log` holds what its link printed, and a
link that fails stops the run with the end of that log. Write the case's fixture from `scripts/fixtures.py`, then time
and summarize:

```sh
Expand Down
21 changes: 19 additions & 2 deletions benchmarks/downcase-placement/relink.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

Each layout goes to OUTPUT/pad-NNNNN/compare or OUTPUT/seed-NNNNN/compare, with
debug sections stripped, and OUTPUT/manifest.json records where the code went.
Everything the linker printed for a layout, warnings included, is in link.log
beside it; a link that fails stops the run with the end of that log.
"""
import argparse
import hashlib
Expand All @@ -28,6 +30,8 @@
'ascii_run': re.compile(r'10vibescript4scan9ascii_run$'),
'copy': re.compile(r'10vibescript4text4case9transforms_0B7_$'),
}
# The lines of a failed link's output to show; its link.log keeps them all.
LOG_TAIL = 20


def text_range(binary):
Expand Down Expand Up @@ -68,13 +72,26 @@ def text_bytes(binary, scratch):


def link(captured, binary, extra):
"""Replays the captured link into `binary`, without debug sections, adding `extra` arguments."""
"""Replays the captured link into `binary`, without debug sections, adding `extra` arguments.

The linker's output goes to link.log beside `binary`, and a failed link
stops the run with the end of it.
"""
command = list(captured)
command[command.index('-o') + 1] = str(binary)
# Debug sections are never loaded; leaving them out keeps hundreds of
# layouts small without moving any code.
command.append('-Wl,--strip-debug')
subprocess.run(['cc', *command, *extra], check=True, capture_output=True, text=True)
log = binary.parent / 'link.log'
with log.open('wb') as output:
status = subprocess.run(['cc', *command, *extra], stdout=output, stderr=subprocess.STDOUT,
check=False).returncode
if status:
reason = f'was killed by signal {-status}' if status < 0 else f'exited with status {status}'
tail = log.read_text(encoding='utf-8', errors='replace').splitlines()[-LOG_TAIL:]
if not tail:
raise SystemExit(f'{binary.parent.name}: the link {reason}; {log} is empty')
raise SystemExit('\n'.join([f'{binary.parent.name}: the link {reason}; the end of {log}:', *tail]))


def front(captured, work, pad):
Expand Down
82 changes: 78 additions & 4 deletions benchmarks/downcase-placement/test_relink.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ def __init__(self, reference):
self.commands = []
# A test replaces this to change what a link produced, by layout.
self.after_link = lambda layout, binary: binary
# And this to change what the linker printed and its exit status. A
# link that fails leaves no binary.
self.linker = lambda layout: (b'', 0)

def check_output(self, command, text):
self.commands.append(command)
Expand All @@ -150,8 +153,16 @@ def check_output(self, command, text):
return binary.symbols()
raise AssertionError(f'unexpected command {command}')

def run(self, command, check, **_):
def run(self, command, check, stdout=None, stderr=None):
self.commands.append(command)
if command[0] == 'cc':
# The linker and the compiler driver print to stderr.
if stderr != subprocess.STDOUT:
raise AssertionError("the linker's messages must go to the link's log")
linked = subprocess.CompletedProcess(command, self.link(command[1:], stdout))
if check:
linked.check_returncode()
return linked
if not check:
raise AssertionError(f'{command[0]} must be checked')
if command[0] == 'as':
Expand All @@ -161,14 +172,17 @@ def run(self, command, check, **_):
pathlib.Path(output).write_bytes(b'')
elif command[0] == 'objcopy' and command[1:4] == ['-O', 'binary', '--only-section=.text']:
pathlib.Path(command[5]).write_bytes(self.binaries[command[4]].text)
elif command[0] == 'cc':
self.link(command[1:])
else:
raise AssertionError(f'unexpected command {command}')
return subprocess.CompletedProcess(command, 0, '', '')

def link(self, arguments):
def link(self, arguments, log):
"""Links as lld would, printing to the file `log` as a child process does, and returns the exit status."""
output = pathlib.Path(arguments[arguments.index('-o') + 1])
printed, status = self.linker(output.parent.name)
os.write(log.fileno(), printed)
if status:
return status
binary = REFERENCE
pads = [self.pads[argument] for argument in arguments if argument in self.pads]
orders = [argument.split('=', 1)[1] for argument in arguments
Expand All @@ -191,6 +205,7 @@ def link(self, arguments):
tuple((offset, kind, name) for offset, (_, kind, name) in zip(offsets, pieces)))
self.binaries[str(output)] = self.after_link(output.parent.name, binary)
output.write_bytes(b'')
return 0


class RelinkTestCase(unittest.TestCase):
Expand Down Expand Up @@ -355,6 +370,43 @@ def test_runs_add_to_one_manifest(self):
self.assertEqual(sorted(self.manifest()), ['pad-00000', 'pad-00016', 'seed-00005'])


class LinkLogTests(RelinkTestCase):
def test_each_layout_keeps_what_its_link_printed(self):
printed = {'pad-00016': b'ld.lld: warning: unknown -z value: pad-00016\n',
'seed-00003': b'ld.lld: warning: unknown -z value: seed-00003\n'}
self.tools.linker = lambda layout: (printed.get(layout, b''), 0)
self.relink('--front', 0, 16)
self.relink('--shuffle', 3)
for layout in ('pad-00000', 'pad-00016', 'seed-00003'):
self.assertEqual((self.output / layout / 'link.log').read_bytes(), printed.get(layout, b''))

def test_a_failed_link_stops_with_the_end_of_its_log(self):
printed = [line for symbol in range(10) for line in (f'ld.lld: error: undefined symbol: missing_{symbol}',
'>>> referenced by main.o:(main)')]
printed += ['ld.lld: error: too many errors emitted, stopping now (use --error-limit=0 to see all errors)',
'collect2: error: ld returned 1 exit status']
failure = ''.join(line + '\n' for line in printed).encode()
self.tools.linker = lambda layout: (failure, 1) if layout == 'pad-00032' else (b'', 0)
log = self.output / 'pad-00032' / 'link.log'
# The first error's two lines are only in the log.
self.assertEqual(self.rejection('--front', 0, 32, 64),
'\n'.join([f'pad-00032: the link exited with status 1; the end of {log}:', *printed[2:]]))
self.assertEqual(log.read_text().splitlines(), printed)
self.assertFalse((self.output / 'pad-00064').exists())

def test_a_log_that_is_not_utf8_still_shows(self):
self.tools.linker = lambda layout: (b'ld.lld: error: cannot open caf\xe9.o: No such file or directory\n', 1)
log = self.output / 'pad-00000' / 'link.log'
self.assertEqual(self.rejection('--front', 0),
f'pad-00000: the link exited with status 1; the end of {log}:\n'
'ld.lld: error: cannot open caf\ufffd.o: No such file or directory')

def test_a_link_killed_by_a_signal_says_so(self):
self.tools.linker = lambda layout: (b'', -9)
log = self.output / 'seed-00005' / 'link.log'
self.assertEqual(self.rejection('--shuffle', 5), f'seed-00005: the link was killed by signal 9; {log} is empty')


REAL_LINK_TOOLS = ('cc', 'as', 'ld.lld', 'nm', 'objcopy', 'readelf')
# Ubuntu's compilers mark objects as ready for IBT and shadow stacks by
# default, and a pad that dropped those properties moved .text; mark them
Expand Down Expand Up @@ -420,6 +472,28 @@ def test_pads_and_shuffles_move_code_and_keep_it_working(self):
listing = subprocess.check_output(['nm', '--defined-only', manifest['pad-00064']['path']], text=True)
self.assertEqual(len(re.findall(r' t helper$', listing, re.MULTILINE)), 2)

def with_captured(self, argument):
"""Adds `argument` to the captured link, as if the program had been linked with it."""
capture = self.root / 'capture' / 'link.json'
capture.write_text(json.dumps([*json.loads(capture.read_text()), argument]))

def test_each_layout_keeps_the_linkers_warnings(self):
self.with_captured('-Wl,-z,vibe234-unknown')
run = self.relink('--front', 0, 64)
self.assertEqual(run.returncode, 0, run.stderr)
for layout in ('pad-00000', 'pad-00064'):
self.assertEqual((self.root / 'layouts' / layout / 'link.log').read_text(),
'ld.lld: warning: unknown -z value: vibe234-unknown\n')

def test_a_link_the_linker_refuses_stops_with_its_error(self):
self.with_captured('-Wl,--vibe234-refused')
run = self.relink('--front', 0)
log = self.root / 'layouts' / 'pad-00000' / 'link.log'
printed = log.read_text()
self.assertIn("ld.lld: error: unknown argument '--vibe234-refused'\n", printed)
self.assertEqual(run.returncode, 1)
self.assertEqual(run.stderr, f'pad-00000: the link exited with status 1; the end of {log}:\n{printed}')

def test_a_pad_finer_than_a_functions_alignment_is_rejected(self):
run = self.relink('--front', 16)
self.assertEqual(run.returncode, 1)
Expand Down
6 changes: 2 additions & 4 deletions benchmarks/escape-layout/isolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / 'mixed-text-placement'))
from relink import symbols
from relink import run_link, symbols

SUFFIXES = {'string': 'json6writer12write_string',
'prefix': 'scan10run_prefix', 'run': '6Output7put_run'}
Expand Down Expand Up @@ -40,9 +40,7 @@ def run(link, reference, output, target):
command = args.copy()
command[command.index('-o') + 1] = str(binary)
command += [str(work / 'pad.o'), '-Wl,-order_file,' + str(work / 'order.txt')]
process = subprocess.run(['cc', *command], capture_output=True, text=True)
(work / 'link.log').write_text(process.stdout + process.stderr)
process.check_returncode()
run_link(command, work)
current = {s: v for s, v in symbols(binary).items() if not s.startswith('_vibe201_')}
if current.keys() != original.keys():
raise ValueError('relink changed symbol inventory')
Expand Down
2 changes: 2 additions & 0 deletions benchmarks/mixed-text-placement/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ python3 "$TOOLS/relink.py" "$BUILD/link/link.json" "$BUILD/compare" "$BUILD/plac
The linker wrapper copies all input object/archive files before Rust removes
its temporary files. The saved JSON argument vector is replayed directly,
without shell parsing. These tools require the macOS linker, `cc`, and `nm`.
Each placement's directory keeps everything its link printed in `link.log`,
and a link that fails stops the sweep with the end of that log.

Each variant gets **32 isolated placements**, in four-byte increments across
128 bytes, and **32 front-pad placements**, in sixteen-byte increments across
Expand Down
20 changes: 19 additions & 1 deletion benchmarks/mixed-text-placement/relink.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

AUDIT_DISPLACEMENT_LIMIT = 8
AUDIT_SAMPLE_LIMIT = 5
# The lines of a failed link's output to show; its link.log keeps them all.
LOG_TAIL = 20


def symbols(binary):
Expand Down Expand Up @@ -45,6 +47,22 @@ def write_padding(work, pads, order):
str(work / 'pad.s'), '-o', str(work / 'pad.o')], check=True)


def run_link(command, work):
"""Runs `cc` with the link `command`, keeping everything it prints in `work`/link.log.

A failed link raises RuntimeError with the end of that log.
"""
log = work / 'link.log'
with log.open('wb') as output:
status = subprocess.run(['cc', *command], stdout=output, stderr=subprocess.STDOUT, check=False).returncode
if status:
reason = f'was killed by signal {-status}' if status < 0 else f'exited with status {status}'
tail = log.read_text(encoding='utf-8', errors='replace').splitlines()[-LOG_TAIL:]
if not tail:
raise RuntimeError(f'the link {reason}; {log} is empty')
raise RuntimeError('\n'.join([f'the link {reason}; the end of {log}:', *tail]))


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}
Expand Down Expand Up @@ -114,7 +132,7 @@ def run(link, reference, output, count=32, front_step=16, front_only=False):
command = args.copy()
command[command.index('-o') + 1] = str(binary)
command += [str(work / 'pad.o'), '-Wl,-order_file,' + str(work / 'order.txt')]
subprocess.run(['cc', *command], capture_output=True, text=True, check=True)
run_link(command, work)
current = {s: v for s, v in symbols(binary).items() if not s.startswith('_vibe199_')}
if current.keys() != original.keys() or any(current[s][1] != original[s][1] for s in current):
raise ValueError('relink changed symbol inventory')
Expand Down
Loading
Loading