"""Observe nested consteval returns on stock x86-64 Linux GCC 16.2 using GDB.""" import argparse import json from pathlib import Path import subprocess import sys import tempfile def observe(gdb): # The type object is loaded only in GDB. The installed cc1plus runs the # original source with its ordinary flags and receives no plugin. tree = gdb.lookup_type("tree_node").pointer() codes = {name: int(gdb.parse_and_eval(name)) for name in ("CALL_EXPR", "ADDR_EXPR", "FUNCTION_DECL", "IDENTIFIER_NODE", "INTEGER_CST")} def code(node): return int(node["base"]["code"]) def operand(node, index): return (node["exp"]["operands"][0].address + index).dereference() def callee(call): if code(call) != codes["CALL_EXPR"]: return None function = operand(call, 1) if function and code(function) == codes["ADDR_EXPR"]: function = operand(function, 0) if not function or code(function) != codes["FUNCTION_DECL"]: return None identifier = function["decl_minimal"]["name"] if not identifier or code(identifier) != codes["IDENTIFIER_NODE"]: return None entry = identifier["identifier"]["id"] length = int(entry["len"]) if 0 < length <= 64: return entry["str"].string(length=length) return None hits = [] active = [] observations = [] class Entry(gdb.Breakpoint): def stop(self): hits.append((None, None)) return True class Return(gdb.FinishBreakpoint): def __init__(self, name): super().__init__(gdb.newest_frame(), internal=True) self.function_name = name def stop(self): result = gdb.newest_frame().read_register("rax").cast(tree) value = int(result["int_cst"]["val"][0]) if result and code(result) == codes["INTEGER_CST"] else None hits.append((self.function_name, value)) return True # The unmodified package retains this out-of-line function symbol. # rsi and rax are the second argument and return registers of this ABI. signature = "cxx_eval_call_expression(constexpr_ctx const*, tree_node*, value_cat, bool*, bool*, tree_node**)" Entry(f"*'{signature}'", internal=True) command = "run" for _ in range(1024): hits.clear() stopped = gdb.execute(command, to_string=True) if not gdb.selected_inferior().pid: break if len(hits) != 1: raise RuntimeError(f"Unexpected stop {hits}: {stopped}") frame = gdb.newest_frame() name, value = hits[0] if name is None: name = callee(frame.read_register("rsi").cast(tree)) if name in ("twice", "reflected_value"): active.append(name) Return(name) else: if not active or active.pop() != name: raise RuntimeError("Unexpected evaluator return order") observations.append([name, active.copy(), value, gdb.selected_inferior().pid]) command = "continue" else: raise RuntimeError("Exceeded the fixture stop limit") if active or int(gdb.parse_and_eval("$_exitcode")) != 0: raise RuntimeError("Incomplete stock compiler run") print("VLS_STOCK_RETURNS " + json.dumps(observations)) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--cxx", default="g++") parser.add_argument("--gdb", default="gdb") parser.add_argument("--include-dir", action="append", default=[], type=Path, help="additional header directory for building the GDB type object") args = parser.parse_args() def compiler_value(option): return subprocess.check_output([args.cxx, option], text=True, timeout=10).strip() target = compiler_value("-dumpmachine") if compiler_value("-dumpfullversion") != "16.2.0" or not target.startswith("x86_64-") or "linux" not in target: parser.error("this fixture adapter covers x86-64 Linux GCC 16.2.0") frontend = compiler_value("-print-prog-name=cc1plus") headers = Path(compiler_value("-print-file-name=plugin")) / "include" script = Path(__file__).resolve() fixture = script.with_name("gcc-live.cpp").read_text() if fixture.count("Ready = 17") != 1: raise RuntimeError("Missing the unique fixture edit") with tempfile.TemporaryDirectory(prefix="vls-stock-gcc-") as temporary: directory = Path(temporary) (directory / "types.cc").write_text( '#include "gcc-plugin.h"\n#include "tree.h"\n' 'tree_node *vls_debug_tree;\ntree_code vls_debug_code;\n') includes = [f"-I{path.resolve()}" for path in [headers, *args.include_dir]] subprocess.run([args.cxx, "-g", "-O0", "-c", *includes, "types.cc", "-o", "types.o"], cwd=directory, check=True, timeout=30) for value in (17, 41): (directory / "fixture.cpp").write_text(fixture.replace("Ready = 17", f"Ready = {value}")) command = [args.gdb, "-nx", "-nh", "-q", "-batch", "-iex", "set auto-load off", "-iex", "set debuginfod enabled off", "-ex", "add-symbol-file types.o 0", "-x", str(script), "--args", frontend, "-quiet", "-std=c++26", "-freflection", "-fsyntax-only", "-nostdinc", "fixture.cpp", "-o", "/dev/null"] output = subprocess.check_output(command, cwd=directory, text=True, timeout=20) prefix = "VLS_STOCK_RETURNS " rows, = (json.loads(line[len(prefix):]) for line in output.splitlines() if line.startswith(prefix)) pairs = [(inner[2], outer[2]) for inner, outer in zip(rows, rows[1:]) if inner[:2] == ["reflected_value", ["twice"]] and outer[:2] == ["twice", []]] if pairs != [(value, 2 * value), (value + 5, 2 * (value + 5))] or len({row[3] for row in rows}) != 1: raise RuntimeError(f"Unexpected stock compiler observations {rows}") print(f"Stock GCC 16.2 returned {pairs} live in PID {rows[0][3]}.") if "gdb" in sys.modules: observe(sys.modules["gdb"]) elif __name__ == "__main__": main()