"""
08_crosscheck.py -- is the simulator right about procedures and arrays?
=======================================================================

[Questions this demo answers]
  - Do x86sim's results for every function in procs.c match the REAL x86-64
    machine code (and the native build), on many inputs, at -Og and -O1?
  - Would this check notice if the simulator handled stack arguments wrongly?

[How to run]
  python3 08_crosscheck.py       (about 10 seconds)

[How to read the output]
  One line per function: number of test inputs and disagreements between
  simulator / real x86-64 / native build. Then a "planted bug" run: the
  simulator is temporarily changed to push stack arguments in the wrong
  order, and the same check runs again.

[Systems link]
  Lecture 4's version of this check found two real simulator bugs. Testing a
  model against the real system is how every simulator (and every emulator,
  such as Rosetta 2 itself) earns trust.
"""

import os
import random
import subprocess

import course_path
course_path.use("lecture03")
import x86sim                                         # noqa: E402

os.chdir(os.path.dirname(os.path.abspath(__file__)))

HEAP = 0x10000
P_BASE, Q_BASE, F_BASE = 0x20000, 0x21000, 0x22000


def gen(rng):
    """[Returns] a list of test lines in oracle.c's input format."""
    big = [0, 1, -1, 2**31 - 1, -2**31, 2**63 - 1, -2**63, 15213, -15213]

    def num():
        return rng.choice(big) if rng.random() < 0.3 else rng.randrange(-2**40, 2**40)
    lines = []
    for _ in range(40):
        lines.append("mult2 %d %d" % (num(), num()))
        lines.append("multstore %d %d" % (num(), num()))
        lines.append("incr %d %d" % (num(), num()))
        lines.append("call_incr2 %d" % num())
        lines.append("proc %d %d %d %d" % (num(), num(), num(), num()))
        x = rng.getrandbits(rng.choice([1, 8, 20, 64]))
        lines.append("pcount_r %d" % x)
        lines.append("popcount_t %d %d" % (x, rng.randrange(-100, 100)))
        lines.append("rfact %d" % rng.randrange(-3, 26))
    lines.append("call_incr")
    lines.append("call_proc")
    lines.append("zincr")
    for d in range(5):
        lines.append("get_digit %d" % d)
    for i in range(4):
        lines.append("get_pgh_zip %d" % i)
        for d in range(5):
            lines.append("get_pgh_digit %d %d" % (i, d))
    for i in range(3):
        for d in range(5):
            lines.append("get_univ_digit %d %d" % (i, d))
    for _ in range(60):
        lines.append("fix_ele %d %d" % (rng.randrange(16), rng.randrange(16)))
        n = rng.randrange(1, 9)
        lines.append("var_ele %d %d %d" % (n, rng.randrange(n), rng.randrange(n)))
        lines.append("fix_prod_ele %d %d" % (rng.randrange(16), rng.randrange(16)))
    return lines


def fill(m, base, n, f):
    for r in range(n):
        for c in range(n):
            m.mem.write(base + 4 * (n * r + c), 4, f(r, c) & 0xFFFFFFFF)


def sim_result(prog, line):
    """Run one oracle-format test line in the simulator; return the same text."""
    parts = line.split()
    name, a = parts[0], [int(x) for x in parts[1:]]
    m = x86sim.Machine(prog)
    s8 = lambda v: x86sim.to_signed(v, 8)                     # noqa: E731
    s4 = lambda v: x86sim.to_signed(v, 4)                     # noqa: E731
    if name == "multstore":
        m.call(name, a[0], a[1], HEAP)
        return str(s8(m.mem.peek(HEAP, 8)))
    if name == "incr":
        m.mem.write(HEAP, 8, a[0])
        old = m.call(name, HEAP, a[1])
        return "%d %d" % (s8(old), s8(m.mem.peek(HEAP, 8)))
    if name == "proc":
        m.mem.write(HEAP, 8, 1000)
        m.mem.write(HEAP + 8, 4, 2000)
        m.mem.write(HEAP + 16, 2, 3000)
        m.mem.write(HEAP + 24, 1, 40)
        m.call(name, a[0], HEAP, a[1], HEAP + 8, a[2], HEAP + 16, a[3], HEAP + 24)
        return "%d %d %d %d" % (s8(m.mem.peek(HEAP, 8)), s4(m.mem.peek(HEAP + 8, 4)),
                                x86sim.to_signed(m.mem.peek(HEAP + 16, 2), 2),
                                x86sim.to_signed(m.mem.peek(HEAP + 24, 1), 1))
    if name == "zincr":
        for k, v in enumerate([1, 5, 2, 1, 3]):
            m.mem.write(HEAP + 4 * k, 4, v)
        m.call(name, HEAP)
        return " ".join(str(s4(m.mem.peek(HEAP + 4 * k, 4))) for k in range(5))
    if name == "get_digit":
        return str(s4(m.call(name, prog.address_of("cmu"), a[0])))
    if name == "get_pgh_zip":
        return str(s8(m.call(name, a[0])) - prog.address_of("pgh"))
    if name in ("get_pgh_digit", "get_univ_digit"):
        return str(s4(m.call(name, *a)))
    if name == "fix_ele":
        fill(m, F_BASE, 16, lambda r, c: 100 * r + c)
        return str(s4(m.call(name, F_BASE, a[0], a[1])))
    if name == "var_ele":
        fill(m, HEAP, a[0], lambda r, c: 1000 * r + c)
        return str(s4(m.call(name, a[0], HEAP, a[1], a[2])))
    if name == "fix_prod_ele":
        fill(m, P_BASE, 16, lambda r, c: (7 * r + 3 * c) % 11 - 5)
        fill(m, Q_BASE, 16, lambda r, c: (5 * r + 2 * c) % 13 - 6)
        return str(s4(m.call(name, P_BASE, Q_BASE, a[0], a[1])))
    return str(s8(m.call(name, *a)))


def run_oracle(binary, lines):
    if not os.path.exists(binary):
        return None
    out = subprocess.run([binary], input="\n".join(lines) + "\n", capture_output=True,
                         text=True, check=True).stdout
    return out.split("\n")[:len(lines)]


def check(lines, real, native, label, verbose=True):
    progs = {opt: x86sim.Program.from_file(x86sim.compile_to_asm("procs.c", opt=opt))
             for opt in ("-Og", "-O1")}
    stats = {}
    first_bad = None
    for k, line in enumerate(lines):
        name = line.split()[0]
        st = stats.setdefault(name, [0, 0, 0, 0])
        st[0] += 1
        for col, opt in ((1, "-Og"), (2, "-O1")):
            try:
                s = sim_result(progs[opt], line)
            except (x86sim.SimError, x86sim.SimFault) as e:
                s = "error: %s" % e
            if s != real[k]:
                st[col] += 1
                first_bad = first_bad or (line, opt, s, real[k])
        if native is not None and native[k] != real[k]:
            st[3] += 1
    total = sum(v[0] for v in stats.values())
    bad = sum(v[1] + v[2] for v in stats.values())
    if verbose:
        print("  %-16s %-6s %-14s %-14s %s" % ("function", "tests", "sim -Og diffs", "sim -O1 diffs",
                                               "native diffs"))
        for name, (n, d1, d2, d3) in stats.items():
            print("  %-16s %-6d %-14d %-14d %d" % (name, n, d1, d2, d3))
    print("  %s: %d tests x 2 optimization levels, %d disagreements with real x86-64"
          % (label, total, bad))
    if first_bad:
        print("    first one: %r at %s -> simulator %r, hardware %r" % first_bad)
    return bad


def planted_bug():
    """[Idea] A Machine.start that pushes stack arguments in the WRONG order."""
    original = x86sim.Machine.start

    def wrong_start(self, name, *args):
        if len(args) > 6:
            args = args[:6] + tuple(reversed(args[6:]))
        return original(self, name, *args)
    return original, wrong_start


def main():
    print("=== Demo 08: simulator vs real x86-64 (procedures and arrays) ===\n")
    if not os.path.exists("build/oracle_x86"):
        subprocess.run(["make", "-s", "build/oracle", "build/oracle_x86"], check=False)
    lines = gen(random.Random(15213))
    real = run_oracle("build/oracle_x86", lines)
    native = run_oracle("build/oracle", lines)
    if real is None:
        print("  build/oracle_x86 is missing (no x86-64 compiler?); comparing with native")
        real, native = native, None
    check(lines, real, native, "correct simulator")
    print("\nPlanted bug: arguments 7 and 8 pushed in the wrong order")
    original, wrong = planted_bug()
    x86sim.Machine.start = wrong
    try:
        check(lines, real, native, "buggy simulator", verbose=False)
    finally:
        x86sim.Machine.start = original
    print("\nObservations:")
    print("  * 0 disagreements: the simulator agrees with the hardware on every")
    print("    function, input and optimization level (and so does the arm64 build).")
    print("  * The planted bug is caught, by exactly the function with 8 arguments")
    print("    (proc): a check is only as good as the cases it exercises.")


if __name__ == "__main__":
    main()
