diff --git a/benchmarks/downcase-placement/README.md b/benchmarks/downcase-placement/README.md index 253a92afd..c2eaef275 100644 --- a/benchmarks/downcase-placement/README.md +++ b/benchmarks/downcase-placement/README.md @@ -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 diff --git a/benchmarks/downcase-placement/relink.py b/benchmarks/downcase-placement/relink.py index 5b6bc9e4d..04af5509e 100644 --- a/benchmarks/downcase-placement/relink.py +++ b/benchmarks/downcase-placement/relink.py @@ -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 @@ -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): @@ -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): diff --git a/benchmarks/downcase-placement/test_relink.py b/benchmarks/downcase-placement/test_relink.py index 69a31bb63..d3a8f35aa 100644 --- a/benchmarks/downcase-placement/test_relink.py +++ b/benchmarks/downcase-placement/test_relink.py @@ -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) @@ -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': @@ -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 @@ -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): @@ -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 @@ -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) diff --git a/benchmarks/escape-layout/isolate.py b/benchmarks/escape-layout/isolate.py index d590e0f59..9baebf3b3 100644 --- a/benchmarks/escape-layout/isolate.py +++ b/benchmarks/escape-layout/isolate.py @@ -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'} @@ -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') diff --git a/benchmarks/mixed-text-placement/README.md b/benchmarks/mixed-text-placement/README.md index 09b9af36c..cad34e5fb 100644 --- a/benchmarks/mixed-text-placement/README.md +++ b/benchmarks/mixed-text-placement/README.md @@ -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 diff --git a/benchmarks/mixed-text-placement/relink.py b/benchmarks/mixed-text-placement/relink.py index 7ccdfa8bc..b74e50faf 100644 --- a/benchmarks/mixed-text-placement/relink.py +++ b/benchmarks/mixed-text-placement/relink.py @@ -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): @@ -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} @@ -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') diff --git a/benchmarks/mixed-text-placement/test_relink.py b/benchmarks/mixed-text-placement/test_relink.py index 752fc23e9..4c8492084 100644 --- a/benchmarks/mixed-text-placement/test_relink.py +++ b/benchmarks/mixed-text-placement/test_relink.py @@ -13,6 +13,8 @@ CAPTURE_LINK = pathlib.Path(__file__).resolve().with_name('capture_link.py') RELINK_SCRIPT = pathlib.Path(__file__).resolve().with_name('relink.py') +# What a patched subprocess.run returns: every command, links included, succeeds. +SUCCEEDED = subprocess.CompletedProcess([], 0) def fake_link_inputs(directory: pathlib.Path) -> tuple[pathlib.Path, pathlib.Path]: @@ -24,6 +26,36 @@ def fake_link_inputs(directory: pathlib.Path) -> tuple[pathlib.Path, pathlib.Pat return link, reference +def front_only_symbols(root, step): + """nm's symbols for the reference in `root` and for each front-only placement, `step` bytes apart.""" + def symbols(binary): + parent = pathlib.Path(binary).parent + if parent == root: + return {'__mh_execute_header': (0x100000000, 'T'), '_main': (0x1000008c0, 'T')} + shift = step * int(parent.name.split('-')[1]) + return {'__mh_execute_header': (0x100000000, 'T'), '_vibe199_pad_a': (0x1000008c0, 'T'), + '_main': (0x1000008c0 + shift, 'T')} + return symbols + + +def fake_cc(outcome): + """Stands in for subprocess.run. Assembling a pad succeeds, and each link + prints and exits as `outcome(placement)` says, writing to its stderr as + cc and ld do.""" + def run(command, check, stdout=None, stderr=None): + status = 0 + if '-c' not in command: + if stderr != subprocess.STDOUT: + raise AssertionError("the linker's messages must go to the link's log") + printed, status = outcome(pathlib.Path(command[command.index('-o') + 1]).parent.name) + os.write(stdout.fileno(), printed) + done = subprocess.CompletedProcess(command, status) + if check: + done.check_returncode() + return done + return run + + class RelinkUnitTests(unittest.TestCase): """Exercise front-only strides, defaults, validation, and symbol audits.""" @@ -54,7 +86,7 @@ def fake_symbols(binary): } with patch.object(relink, 'symbols', side_effect=fake_symbols), \ - patch.object(relink.subprocess, 'run') as mock_run, \ + patch.object(relink.subprocess, 'run', return_value=SUCCEEDED) as mock_run, \ patch('builtins.print'): relink.run(link, reference, output, count=3, front_step=64, front_only=True) @@ -103,7 +135,7 @@ def fake_symbols(binary): } with patch.object(relink, 'symbols', side_effect=fake_symbols), \ - patch.object(relink.subprocess, 'run'), \ + patch.object(relink.subprocess, 'run', return_value=SUCCEEDED), \ patch('builtins.print'): # Match phase200.py's 5-argument positional call. relink.run(link, reference, output, 2, 4) @@ -159,7 +191,7 @@ def rounded_symbols(binary): return {'__mh_execute_header': (0x100000000, 'T'), '_main': (addr, 'T')} with patch.object(relink, 'symbols', side_effect=rounded_symbols), \ - patch.object(relink.subprocess, 'run'), \ + patch.object(relink.subprocess, 'run', return_value=SUCCEEDED), \ self.assertRaisesRegex(ValueError, 'front placement audit failed'): relink.run(link, reference, root / 'rounded', count=2, front_step=16, front_only=True) @@ -170,12 +202,12 @@ def changed_inventory(binary): return {'_main': (0x1000008d0, 'T'), '_extra': (0x100000900, 't')} with patch.object(relink, 'symbols', side_effect=changed_inventory), \ - patch.object(relink.subprocess, 'run'), \ + patch.object(relink.subprocess, 'run', return_value=SUCCEEDED), \ self.assertRaisesRegex(ValueError, 'relink changed symbol inventory'): relink.run(link, reference, root / 'inventory', count=2, front_step=16, front_only=True) with patch.object(relink, 'symbols', return_value={'__mh_execute_header': (0x100000000, 'T')}), \ - patch.object(relink.subprocess, 'run'), \ + patch.object(relink.subprocess, 'run', return_value=SUCCEEDED), \ self.assertRaisesRegex(ValueError, 'expected at least one text symbol'): relink.run(link, reference, root / 'empty-text', count=1, front_step=64, front_only=True) @@ -264,6 +296,60 @@ def test_audit_summarizes_local_failures_and_caps_displacement_buckets(self) -> ) +class LinkLogTests(unittest.TestCase): + """Each placement keeps its link's output in link.log, and a failed link shows the end of it.""" + + def setUp(self) -> None: + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = pathlib.Path(directory.name) + self.link, self.reference = fake_link_inputs(self.root) + self.output = self.root / 'placements' + + def relink(self, outcome) -> None: + with patch.object(relink, 'symbols', side_effect=front_only_symbols(self.root, 64)), \ + patch.object(relink.subprocess, 'run', side_effect=fake_cc(outcome)), \ + patch('builtins.print'): + relink.run(self.link, self.reference, self.output, count=3, front_step=64, front_only=True) + + def failure(self, outcome) -> str: + """The message relink.run fails with.""" + with self.assertRaises(RuntimeError) as failed: + self.relink(outcome) + return str(failed.exception) + + def test_each_placement_keeps_what_its_link_printed(self) -> None: + printed = {'front-02': b"ld: warning: ignoring duplicate libraries: '-lc'\n"} + self.relink(lambda placement: (printed.get(placement, b''), 0)) + for placement in ('front-01', 'front-02', 'front-03'): + self.assertEqual((self.output / placement / 'link.log').read_bytes(), printed.get(placement, b'')) + + def test_a_failed_link_raises_the_end_of_its_log(self) -> None: + printed = ['Undefined symbols for architecture arm64:'] + printed += [line for symbol in range(10) for line in (f' "_missing_{symbol}", referenced from:', + ' _main in input.o')] + printed += ['ld: symbol(s) not found for architecture arm64', + 'clang: error: linker command failed with exit code 1 (use -v to see invocation)'] + failure = ''.join(line + '\n' for line in printed).encode() + log = self.output / 'front-02' / 'link.log' + # The first three lines are only in the log. + self.assertEqual(self.failure(lambda placement: (failure, 1) if placement == 'front-02' else (b'', 0)), + '\n'.join([f'the link exited with status 1; the end of {log}:', *printed[3:]])) + self.assertEqual(log.read_text().splitlines(), printed) + self.assertFalse((self.output / 'front-03').exists()) + + def test_a_log_that_is_not_utf8_still_shows(self) -> None: + printed = b"ld: file cannot be open()ed, errno=2 path=caf\xe9.o in 'caf\xe9.o'\n" + log = self.output / 'front-01' / 'link.log' + self.assertEqual(self.failure(lambda placement: (printed, 1)), + f'the link exited with status 1; the end of {log}:\n' + "ld: file cannot be open()ed, errno=2 path=caf\ufffd.o in 'caf\ufffd.o'") + + def test_a_link_killed_by_a_signal_says_so(self) -> None: + log = self.output / 'front-01' / 'link.log' + self.assertEqual(self.failure(lambda placement: (b'', -9)), f'the link was killed by signal 9; {log} is empty') + + @unittest.skipUnless(platform.system() == 'Darwin' and platform.machine() == 'arm64', 'Mach-O relink integration tests require Apple Silicon macOS') class RelinkMachOIntegrationTests(unittest.TestCase):