diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-13 09:28:38 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-13 09:28:38 -0300 |
| commit | 5c0230ea5a77f85de77ad4354788cd6c27aa1ef6 (patch) | |
| tree | e01a903bdee092965b86e118dfaab85c3bd60004 /gui/bench/control.py | |
| parent | 5a40dca5adb6e9e650f55f3ec6f254a13bf50493 (diff) | |
| download | computeranim-5c0230ea5a77f85de77ad4354788cd6c27aa1ef6.tar.gz computeranim-5c0230ea5a77f85de77ad4354788cd6c27aa1ef6.zip | |
debugger: follow natural V8 deoptimization with adaptive live views
Diffstat (limited to 'gui/bench/control.py')
| -rw-r--r-- | gui/bench/control.py | 180 |
1 files changed, 180 insertions, 0 deletions
diff --git a/gui/bench/control.py b/gui/bench/control.py new file mode 100644 index 0000000..eb3ff92 --- /dev/null +++ b/gui/bench/control.py @@ -0,0 +1,180 @@ +"""Small driver for the live controller; no tracing between requested stops.""" +import json +import os +from pathlib import Path +import re +import select +import struct +import subprocess +import time + +ROOT = Path(__file__).resolve().parents[2] + + +class Controller: + def __init__(self, ztrace, out, name, argv): + self.ztrace = Path(ztrace).resolve() + self.recording = out / (name + '.ztrace') + self.log = (out / (name + '.log')).open('w+') + self.process = subprocess.Popen([str(self.ztrace), 'serve', str(self.recording), '--', *argv], + cwd=out, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, bufsize=0) + self.pending = b'' + + def read(self): + deadline = time.monotonic() + 60 + while b'\n' not in self.pending: + if not select.select([self.process.stdout], [], [], max(0, deadline - time.monotonic()))[0]: + raise TimeoutError('controller timeout: ' + self.log.name) + data = os.read(self.process.stdout.fileno(), 4096) + if not data: + raise RuntimeError('controller exited: ' + self.log.name) + self.pending += data + line, self.pending = self.pending.split(b'\n', 1) + return json.loads(line) + + def command(self, command, status='stopped'): + self.process.stdin.write((command + '\n').encode()) + while True: + reply = self.read() + if reply['status'] != 'running': + assert reply['status'] == status, (command, reply) + return reply + + def output(self): + self.log.seek(0) + return self.log.read() + + def show(self): + return subprocess.check_output([str(self.ztrace), 'show', str(self.recording), '-1'], text=True) + + def regs(self): + return {name: int(value, 16) for name, value in re.findall(r'^ (\w+)\s+([0-9a-f]+)', self.show(), re.M)} + + def close(self): + try: + if self.process.poll() is None: + self.process.stdin.write(b'quit\n') + self.process.wait(timeout=30) + finally: + if self.process.poll() is None: + self.process.kill() + self.process.wait() + self.process.stdin.close() + self.process.stdout.close() + self.log.close() + + +def natural(ztrace, d8, out, source): + js = out / f'natural-{os.getpid()}.js' + js.write_bytes((ROOT / 'gui/targets/jit.js').read_bytes()) + c = Controller(ztrace, out, 'v8', [str(Path(d8).resolve()), '--trace-opt', '--trace-deopt', + '--trace-deopt-verbose', '--print-opt-code', '--print-opt-code-filter=jitWork', + '--gdbjit', '--gdbjit-dump', '--gdbjit-dump-filter=jitWork', js.name]) + try: + assert c.read()['status'] == 'stopped' + c.command('break main') + c.command('continue') + c.command('clear 1') + c.command('source-map ../../src ' + str(source / 'src')) + c.command('break v8::internal::Deoptimizer::New') + c.command('break v8::internal::Runtime_NotifyDeoptimized') + # Stop on an unrelated outer-loop bailout after natural compilation. + for _ in range(30): + stop = c.command('continue') + code = c.output() + if 'kind = TURBOFAN_JS' in code and "deopt reason 'wrong map'" in code: + break + else: + raise AssertionError('jitWork did not naturally reach TurboFan') + assert 'target MAGLEV' in code and 'target TURBOFAN_JS' in code + # The optimized-code block belongs to jitWork, selected by V8's own filter. + block = next(b.split('--- End code ---')[0] for b in reversed(code.split('--- Optimized code ---')) if 'kind = TURBOFAN_JS' in b and "deopt reason 'wrong map'" in b) + instructions = re.findall(r'^(0x[0-9a-f]+)\s+[0-9a-f]+\s+[0-9a-f]+\s+(.+)$', block, re.M) + assert instructions + start = int(instructions[0][0], 16) + end = int(instructions[-1][0], 16) + 16 + c.command('break *' + hex(start)) + for _ in range(30): + stop = c.command('continue') + if stop['pc'] == start: + break + else: + raise AssertionError('optimized warm call was not reached') + c.command('clear 4') + candidates = list(Path('/tmp').glob('elfdumpjitWork ' + js.name + ':*.o')) + def owns_start(path): + data = path.read_bytes() + shoff = struct.unpack_from('<Q', data, 40)[0] + size, count = struct.unpack_from('<HH', data, 58) + return any((lambda sh: sh[2] & 4 and sh[3] <= start < sh[3] + sh[5])( + struct.unpack_from('<IIQQQQIIQQ', data, shoff + i * size)) for i in range(count)) + elf, = [path for path in candidates if owns_start(path)] + c.command('symbols ' + str(elf)) + c.command(f'inspect code {start} 128') + return c, js, elf, (start, end), instructions, stop + except BaseException: + c.close() + raise + + +def deoptimization(c, bounds, instructions, source): + transition = [] + wrong_return = int(re.search(r'^(0x[0-9a-f]+)\s+deopt reason\s+\(wrong map\)', c.output(), re.M)[1], 16) + exit_call = max(int(a, 16) for a, _ in instructions if int(a, 16) < wrong_return) + guard = next(int(a, 16) for a, text in instructions if re.match(r'j\w+ ' + hex(exit_call) + r'\b', text)) + c.command('break *' + hex(exit_call)) + for _ in range(30): + generated = c.command('continue') + if generated['pc'] == exit_call: + break + else: + raise AssertionError('wrong-map generated exit not reached') + transition.append(dict(stage='generated wrong-map exit', guard_pc=guard, **generated)) + c.command('clear 5') + # Deoptimizer::New receives the originating generated return PC in rdx. + for _ in range(30): + stop = c.command('continue') + if stop['reason'] == 'breakpoint 2': + regs = c.regs() + if bounds[0] <= regs['rdx'] < bounds[1]: + entry = stop + origin = regs['rdx'] + break + else: + raise AssertionError('no deoptimization originating in jitWork') + shown = c.show() + assert str(source / 'src/deoptimizer/deoptimizer.cc') in shown, shown[:1000] + assert (source / 'src/deoptimizer/deoptimizer.cc').exists() + transition.append(dict(stage='Deoptimizer::New', **entry)) + origin_instruction = guard + c.command(f'inspect code {origin_instruction} 16') + notify = c.command('continue') + assert notify['reason'] == 'breakpoint 3', notify + log = c.output() + wrong_maps = [int(pc, 16) for pc in re.findall(r'^(0x[0-9a-f]+)\s+deopt reason\s+\(wrong map\)', log, re.M)] + assert origin in wrong_maps, (hex(origin), [hex(pc) for pc in wrong_maps]) + assert str(source / 'src/runtime/runtime-compiler.cc') in c.show() + transition.append(dict(stage='Runtime_NotifyDeoptimized', **notify)) + c.command('break Builtins_InterpreterEnterAtBytecode') + fallback = c.command('continue') + assert fallback['reason'] == 'breakpoint 6', fallback + transition.append(dict(stage='InterpreterEnterAtBytecode', **fallback)) + # Prove dispatch into the bytecode handler, not just the frame-reconstruction log. + dispatch = None + for _ in range(300): + step = c.command('stepi') + shown = c.show() + rip = next(line for line in shown.splitlines() if line.startswith(' rip ')) + if 'Builtins_InterpreterEntryTrampoline' not in rip and 'Builtins_InterpreterEnterAtBytecode' not in rip and re.search(r'Builtins_(GetNamedProperty|LdaNamedProperty|GetNamedPropertyFromSuper)', rip): + dispatch = dict(stage='Ignition property bytecode handler', symbol=rip.strip(), **step) + break + assert dispatch, c.show()[:1600] + transition.append(dispatch) + for bp in (2, 3, 6): + c.command(f'clear {bp}') + c.command('continue', status='exited') + log = c.output() + assert re.search(r'reason: wrong map.*<JSFunction jitWork', log), log[-6000:] + assert 'mismatch 499509' in log and 'fallback 499507' in log + return dict(reason='wrong map', function='jitWork', optimized_tier='TurboFan', fallback_tier='Ignition', + origin_return_pc=origin, origin_instruction=origin_instruction, deopt_call=exit_call, stops=transition) |
