#!/usr/bin/env python3
"""Capture the first Tier 2 lookup region from a Graal workload on Linux x86-64."""

import argparse
from contextlib import ExitStack
import json
import os
from pathlib import Path
import re
import subprocess
from time import monotonic, sleep


ROOT = Path(__file__).resolve().parents[1]
INSTALL = re.compile(
    r"opt done.*\bsqlite3VdbeExecLookup\s+\|Tier 2\|.*?\|CodeSize\s+(\d+)\|Addr (0x[0-9a-f]+)"
)


def capture(child, trace, deadline):
    while monotonic() < deadline:
        line = trace.readline()
        if not line:
            if child.poll() is not None:
                break
            sleep(0.025)
            continue
        match = INSTALL.search(line)
        if match:
            size, address = int(match[1]), int(match[2], 16)
            # Open after the launcher has exec'd the AOT image.
            with open(f"/proc/{child.pid}/mem", "rb", buffering=0) as memory:
                code = os.pread(memory.fileno(), size, address)
            if len(code) != size:
                raise RuntimeError(f"read {len(code)} of {size} reported code bytes")
            return line, address, code
    raise RuntimeError("Graal did not install Tier 2 lookup code within the deadline")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("bitcode", type=Path, help="specialized lookup benchmark module")
    parser.add_argument("output", type=Path, help="new directory for capture and trace")
    parser.add_argument("--exe", type=Path, default=ROOT / "dist/sqlite-api-shell")
    parser.add_argument("--timeout", type=int, default=120)
    parser.add_argument("--runtime-arg", action="append", default=[], metavar="FLAG")
    parser.add_argument("--connection", choices=("serialized", "owned"),
                        help="explicitly select the lookup connection mode")
    args = parser.parse_args()
    output = args.output.resolve()
    output.mkdir(parents=True)
    command = [
        str(args.exe.resolve(strict=True)),
        "-Xmx896m", "-Dpolyglot.engine.BackgroundCompilation=false", *args.runtime_arg,
        "--run-module", "--trace-compilation", str(args.bitcode.resolve(strict=True)),
        "2048", "12000", "30000", "3",
    ]
    if args.connection:
        command.append(args.connection)
    (output / "command.json").write_text(json.dumps(command, indent=2) + "\n")
    with ExitStack() as stack:
        stdout = stack.enter_context((output / "graal.stdout").open("wb"))
        stderr = stack.enter_context((output / "graal.stderr").open("wb"))
        child = stack.enter_context(subprocess.Popen(command, stdout=stdout, stderr=stderr))
        trace = stack.enter_context((output / "graal.stderr").open())
        deadline = monotonic() + args.timeout
        try:
            event, address, code = capture(child, trace, deadline)
            status = child.wait(timeout=max(0, deadline - monotonic()))
            if status:
                raise subprocess.CalledProcessError(status, command)
        finally:
            if child.poll() is None:
                child.kill()
    binary = output / "graal-code.bin"
    binary.write_bytes(code)
    (output / "graal-code-event.txt").write_text(event)
    with (output / "graal-code.asm").open("w") as assembly:
        subprocess.run(
            ["objdump", "-D", "-b", "binary", "-m", "i386:x86-64",
             f"--adjust-vma={address:#x}", str(binary)],
            stdout=assembly, check=True,
        )
    print(event, end="")


if __name__ == "__main__":
    main()
