"""
03_register_conventions.py -- caller-saved vs callee-saved, and a checker
==========================================================================

[Questions this demo answers]
  - All functions share ONE set of registers. What goes wrong if a caller
    keeps a value in a register and the callee overwrites it?
  - What do the two fixes -- "caller saves" and "callee saves" -- look like?
  - Does the compiler's code really obey the x86-64 convention? Can a tool
    check that automatically?

[How to run]
  python3 03_register_conventions.py

[How to read the output]
  PART A runs the slides' yoo/who example (hand-written assembly) three ways:
  broken, fixed by the caller, fixed by the callee. PART B runs every
  function of procs.c (clang -Og and -O1) with random garbage in all 16
  registers and checks the rules: callee-saved registers and %rsp come back
  unchanged, and %rsp is a multiple of 16 at every call. PART C feeds the
  checker a deliberately broken function and shows what that bug does to a
  caller.

[Systems link / CS:APP 3.7.5]
  The convention is a CONTRACT between separately compiled functions. The
  compiler of `who` never sees `yoo`; only the contract lets them cooperate.
  Hand-written assembly (and buggy compilers) can break the contract, and the
  symptom then shows up far away, in the caller -- a classic "action at a
  distance" bug.
"""

import os
import random

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

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

CALLEE_SAVED = ["rbx", "rbp", "r12", "r13", "r14", "r15"]
CALLER_SAVED = ["rax", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11"]

# The slides' example: yoo keeps 15213 in %rdx across a call to who, and who
# uses %rdx as a scratch register. (who returns 0 so the right answer is easy.)
YOO_BROKEN = """
yoo:
    movq  $15213, %rdx      # a temporary yoo wants to keep
    call  who
    addq  %rdx, %rax        # expects %rdx == 15213 here
    ret
who:
    movq  $0, %rax
    subq  $18213, %rdx      # who uses %rdx as scratch
    ret
"""

YOO_CALLER_SAVES = """
yoo:
    movq  $15213, %rdx
    pushq %rdx              # CALLER saves %rdx in its frame before the call
    call  who
    popq  %rdx              # ... and restores it afterwards
    addq  %rdx, %rax
    ret
who:
    movq  $0, %rax
    subq  $18213, %rdx
    ret
"""

YOO_CALLEE_SAVES = """
yoo:
    pushq %rbx              # yoo is a callee too: save ITS caller's %rbx
    movq  $15213, %rbx      # keep the value in a callee-saved register
    call  who
    addq  %rbx, %rax
    popq  %rbx
    ret
who:
    pushq %rbx              # CALLEE saves %rbx before using it ...
    movq  $0, %rax
    movq  $-18213, %rbx
    popq  %rbx              # ... and restores it before returning
    ret
"""


def part_a():
    print("PART A: the slides' yoo/who example -- registers are shared")
    for title, text in [("broken: who clobbers %rdx", YOO_BROKEN),
                        ("fix 1: CALLER saves %rdx around the call", YOO_CALLER_SAVES),
                        ("fix 2: keep it in %rbx; every CALLEE saves %rbx", YOO_CALLEE_SAVES)]:
        prog = x86sim.Program(text, title)
        m = x86sim.Machine(prog)
        r = x86sim.to_signed(m.call("yoo"), 8)
        print("  %-48s yoo() = %6d  %s" % (title, r, "(correct: 0 + 15213)" if r == 15213 else "WRONG"))
    print("  Both fixes work; the convention decides WHICH one each register uses,")
    print("  so that two functions compiled separately agree on who saves what.\n")


def random_regs(rng):
    return {r: rng.getrandbits(64) for r in x86sim.REG64 if r != "rsp"}


def check(prog, name, args, setup=None, seed=213):
    """
    [Idea] Run name(*args) with every register filled with random garbage and
      check the calling convention from the OUTSIDE, like a test harness:
        1. every callee-saved register has its old value at the end,
        2. %rsp is back where it was (the caller's stack is intact),
        3. at every `call` it makes, %rsp is a multiple of 16.
      Also report which caller-saved registers it changed (allowed).
    [Returns] dict with the findings.
    """
    rng = random.Random(seed)
    m = x86sim.Machine(prog)
    if setup:
        setup(m)
    for r, v in random_regs(rng).items():
        m.regs[r] = v
    before = dict(m.regs)
    m.start(name, *args)
    after_setup = dict(m.regs)                   # argument registers now set
    misaligned = 0
    calls = 0
    used_callee = set()
    while not m.halted:
        ins = prog.instrs[prog.by_addr[m.rip]] if m.rip in prog.by_addr else None
        if ins is not None and ins.op == "call":
            calls += 1
            misaligned += (m.regs["rsp"] % 16 != 0)
        m.step()
        for r in CALLEE_SAVED:
            if m.regs[r] != before[r]:
                used_callee.add(r)
    m.regs["rsp"] += m.arg_bytes
    return {"broken": [r for r in CALLEE_SAVED if m.regs[r] != before[r]],
            "rsp_ok": m.regs["rsp"] == before["rsp"],
            "calls": calls, "misaligned": misaligned,
            "used_callee": sorted(used_callee, key=CALLEE_SAVED.index),
            "clobbered": [r for r in CALLER_SAVED if r != "rax" and m.regs[r] != after_setup[r]]}


def test_runs(prog):
    """Every function of procs.c with sensible arguments (pointers into sim memory)."""
    heap = 0x10000
    mat = 0x20000

    def setup(m):
        for k in range(4):
            m.mem.write(heap + 8 * k, 8, 1000 * (k + 1))
        for r in range(16):
            for c in range(16):
                m.mem.write(mat + 4 * (16 * r + c), 4, (7 * r + 3 * c) % 11 - 5)
    cmu = prog.address_of("cmu")
    return setup, [
        ("mult2", (6, 7)), ("multstore", (6, 7, heap)), ("incr", (heap, 5)),
        ("call_incr", ()), ("call_incr2", (100,)),
        ("proc", (1, heap, 2, heap + 8, 3, heap + 16, 4, heap + 24)), ("call_proc", ()),
        ("pcount_r", (0xF0F0,)), ("popcount_t", (0xF0F0, 0)), ("rfact", (10,)),
        ("get_digit", (cmu, 2)), ("zincr", (heap,)), ("get_pgh_zip", (2,)),
        ("get_pgh_digit", (2, 3)), ("get_univ_digit", (1, 2)), ("fix_ele", (mat, 3, 4)),
        ("var_ele", (5, mat, 2, 3)), ("fix_prod_ele", (mat, mat, 1, 2))]


def part_b():
    print("PART B: checking every compiled function against the convention")
    print("  (all 16 registers start as random garbage; arguments as in C)\n")
    total = bad = 0
    for opt in ("-Og", "-O1"):
        prog = x86sim.Program.from_file(x86sim.compile_to_asm("procs.c", opt=opt))
        setup, runs = test_runs(prog)
        print("  clang %s" % opt)
        print("    %-14s %-5s %-9s %-24s %s" % ("function", "calls", "aligned?", "callee-saved it used",
                                                 "caller-saved it changed (allowed)"))
        for name, args in runs:
            res = check(prog, name, args, setup)
            total += 1
            ok = not res["broken"] and res["rsp_ok"] and res["misaligned"] == 0
            bad += not ok
            aligned = "-" if res["calls"] == 0 else ("yes" if res["misaligned"] == 0 else "NO")
            print("    %-14s %-5d %-9s %-24s %s%s" % (
                name, res["calls"], aligned,
                " ".join("%" + r for r in res["used_callee"]) or "-",
                " ".join("%" + r for r in res["clobbered"]) or "-",
                "" if ok else "   <-- VIOLATION %s" % res["broken"]))
        print()
    print("  %d function runs checked, %d violations. 'Used' callee-saved registers" % (total, bad))
    print("  changed DURING the call but were restored before `ret`.\n")


BAD_SUM3 = """
bad_sum3:                   # long bad_sum3(long a, long b, long c) { return a+b+c; }
    movq  %rdi, %rbx        # BUG: uses callee-saved %rbx without saving it
    addq  %rsi, %rbx
    addq  %rdx, %rbx
    movq  %rbx, %rax
    ret
caller:                     # long caller() { long k = 100; return bad_sum3(1,2,3) + k; }
    pushq %rbx
    movq  $100, %rbx        # k lives in callee-saved %rbx: safe across calls...
    movl  $1, %edi
    movl  $2, %esi
    movl  $3, %edx
    call  bad_sum3
    addq  %rbx, %rax        # ... unless the callee breaks the contract
    popq  %rbx
    ret
"""


def part_c():
    print("PART C: a function that breaks the contract")
    prog = x86sim.Program(BAD_SUM3, "bad")
    res = check(prog, "bad_sum3", (1, 2, 3))
    print("  checker on bad_sum3(1, 2, 3): callee-saved registers not restored: %s"
          % (" ".join("%" + r for r in res["broken"]) or "none"))
    m = x86sim.Machine(prog)
    r = m.call("caller")
    print("  caller() = %d, but C says bad_sum3(1,2,3) + 100 = 106." % r)
    print("  The bug is in bad_sum3, the wrong answer appears in caller: bad_sum3")
    print("  itself returns the right sum (6), so testing it alone finds nothing.\n")


def main():
    print("=== Demo 03: register saving conventions ===\n")
    part_a()
    part_b()
    part_c()
    print("Observations:")
    print("  * Caller-saved (%rax %rcx %rdx %rsi %rdi %r8-%r11): a callee may change them")
    print("    freely, so a caller that needs one after a call must save it itself.")
    print("  * Callee-saved (%rbx %rbp %r12-%r15): a callee that uses one must save the")
    print("    old value and restore it -- the push/pop pairs at the start and end of")
    print("    multstore, call_incr2, pcount_r and rfact.")
    print("  * %rsp is special: every function returns it exactly as it found it, and")
    print("    keeps it 16-byte aligned at each call.")
    print("  * Compilers obey the contract (0 violations above); hand-written assembly")
    print("    can break it, and the damage shows up in the CALLER.")


if __name__ == "__main__":
    main()
