"""
01_passing_data.py -- where arguments travel: six registers, then the stack
============================================================================

[Questions this demo answers]
  - The first six integer/pointer arguments go in %rdi, %rsi, %rdx, %rcx, %r8,
    %r9. Where do arguments 7 and 8 go, and where does the callee find them?
  - An argument of type char or short still occupies a whole register or a
    whole 8-byte stack slot. Which part of it does the callee actually read?
  - What does the caller's "argument build area" look like at the moment of
    the call?

[How to run]
  python3 01_passing_data.py          (or `make run` for every demo)

[How to read the output]
  PART A lists proc() (CS:APP Figure 3.29), which takes 8 arguments of four
  sizes, and says where each argument lives. PART B runs call_proc() (Figure
  3.32) in the simulator and STOPS at its `call _proc` instruction to print
  the argument registers and the stack. PART C calls proc() directly with
  values that do not fit their C types and compares with the real machine.

[Systems link / CS:APP 3.7.3]
  The register list is part of the System V AMD64 ABI, the agreement that
  lets code from different compilers and libraries call each other. Six
  registers cover almost every real call, so most arguments never touch
  memory -- that is why x86-64 code is faster than old 32-bit x86 code, which
  passed EVERY argument on the stack.
"""

import os
import subprocess

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

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

ARGS = [("a1", "long", 8), ("a1p", "long *", 8), ("a2", "int", 4), ("a2p", "int *", 8),
        ("a3", "short", 2), ("a3p", "short *", 8), ("a4", "char", 1), ("a4p", "char *", 8)]
REG_BY_SIZE = {"rdi": {8: "%rdi", 4: "%edi", 2: "%di", 1: "%dil"},
               "rsi": {8: "%rsi", 4: "%esi", 2: "%si", 1: "%sil"},
               "rdx": {8: "%rdx", 4: "%edx", 2: "%dx", 1: "%dl"},
               "rcx": {8: "%rcx", 4: "%ecx", 2: "%cx", 1: "%cl"},
               "r8": {8: "%r8", 4: "%r8d", 2: "%r8w", 1: "%r8b"},
               "r9": {8: "%r9", 4: "%r9d", 2: "%r9w", 1: "%r9b"}}


def part_a(prog):
    print("PART A: proc(a1, a1p, a2, a2p, a3, a3p, a4, a4p) -- 8 arguments, 4 sizes")
    print("  void proc(long a1, long *a1p, int a2, int *a2p,")
    print("            short a3, short *a3p, char a4, char *a4p)")
    print("  { *a1p += a1;  *a2p += a2;  *a3p += a3;  *a4p += a4; }\n")
    print(x86sim.listing(prog, "proc"))
    print("\n  arg  name  C type    size  where it is on entry to proc")
    for k, (name, ctype, size) in enumerate(ARGS, 1):
        if k <= 6:
            reg = x86sim.ARG_REGS[k - 1]
            where = "register %s (the %d-byte part of %%%s)" % (REG_BY_SIZE[reg][size], size, reg)
        else:
            where = "stack, %d(%%rsp): its own 8-byte slot" % (8 * (k - 6))
        print("  %-4d %-5s %-9s %-5d %s" % (k, name, ctype, size, where))
    print("  (on entry, 0(%rsp) holds the return address, so argument 7 is at 8(%rsp))\n")


def part_b(prog):
    print("PART B: call_proc() builds the arguments, stopped at `call _proc`")
    print("  long call_proc() { long x1 = 1; int x2 = 2; short x3 = 3; char x4 = 4;")
    print("                     proc(x1, &x1, x2, &x2, x3, &x3, x4, &x4);")
    print("                     return (x1+x2)*(x3-x4); }\n")
    print(x86sim.listing(prog, "call_proc"))
    m = x86sim.Machine(prog)
    m.start("call_proc")
    entry_rsp = m.regs["rsp"]
    proc_addr = prog.address_of("proc")
    while True:                                   # run up to (not including) the call
        ins = prog.instrs[prog.by_addr[m.rip]]
        if ins.op == "call" and ins.operands[0].value == proc_addr:
            break
        m.step()
    rsp = m.regs["rsp"]
    off = entry_rsp - rsp                          # bytes below the entry %rsp
    print("\n  At the call: %%rsp = entry %%rsp - %d; %%rsp %% 16 = %d (the ABI wants 0)"
          % (off, rsp % 16))
    print("  Argument registers (each shown at the argument's size):")
    for k, (name, ctype, size) in enumerate(ARGS[:6], 1):
        reg = x86sim.ARG_REGS[k - 1]
        v = m.regs[reg] & x86sim.MASK[size]
        what = v
        if ctype.endswith("*"):
            what = "0x%x = &x%d  (entry %%rsp - %d)" % (v, (k + 1) // 2, entry_rsp - v)
        print("    %-6s %-5s = %s" % (REG_BY_SIZE[reg][size], name, what))
    notes = {}
    for a in range(rsp, entry_rsp, 8):
        notes[a] = ""
    notes[rsp] = "argument 7: a4 = 4 (a char, in a full 8-byte slot)"
    notes[rsp + 8] = "argument 8: a4p = &x4"
    x_addr = {m.regs["rsi"]: "x1 (long, 8 bytes)", m.regs["rcx"]: "x2 (int, 4 bytes)",
              m.regs["r9"]: "x3 (short, 2 bytes)", m.mem.peek(rsp + 8, 8): "x4 (char, 1 byte)"}
    for a in sorted(x_addr):
        slot = a & ~7
        notes[slot] = (notes.get(slot, "") + "; " if notes.get(slot) else "") + \
            "%s at byte %d" % (x_addr[a], a - slot)
    for a in notes:
        if not notes[a]:
            notes[a] = "unused: padding so that %rsp is a multiple of 16 at the call"
    print("\n  The stack, highest address first (one 8-byte slot per line):")
    print(frames.draw(m, notes=notes))
    print("\n  Read it bottom-up: the two pushes at the bottom are the ARGUMENT BUILD")
    print("  AREA (argument 7 on top, i.e. at the lowest address); above them, one")
    print("  slot of padding; then the four local variables, packed by size into two")
    print("  slots (byte 0 of the x4/x3/x2 slot is unused); then the return address")
    print("  into whoever called call_proc. The frame is 24 bytes (subq $24) + 16")
    print("  bytes of pushed arguments.")
    while not m.halted:
        m.step()
    print("\n  call_proc() returned %d = (2+4)*(6-8), as C says.\n"
          % x86sim.to_signed(m.regs["rax"], 8))


def oracle(binary, lines):
    out = subprocess.run([binary], input="\n".join(lines) + "\n", capture_output=True,
                         text=True, check=True).stdout
    return out.split("\n")[:len(lines)]


def sim_proc(prog, a1, a2, a3, a4):
    """Call proc in the simulator with pointers to 1000, 2000, 3000, 40."""
    m = x86sim.Machine(prog)
    base = 0x10000
    m.mem.write(base, 8, 1000)
    m.mem.write(base + 8, 4, 2000)
    m.mem.write(base + 16, 2, 3000)
    m.mem.write(base + 24, 1, 40)
    m.call("proc", a1, base, a2, base + 8, a3, base + 16, a4, base + 24)
    vals = [x86sim.to_signed(m.mem.peek(base, 8), 8), x86sim.to_signed(m.mem.peek(base + 8, 4), 4),
            x86sim.to_signed(m.mem.peek(base + 16, 2), 2), x86sim.to_signed(m.mem.peek(base + 24, 1), 1)]
    return " ".join(str(v) for v in vals)


def part_c(prog):
    print("PART C: values that do not fit their C type")
    print("  A C caller converts each argument to the parameter's type first; on")
    print("  x86-64 the upper bytes of the register or stack slot are then left")
    print("  unspecified, and the callee reads only the bytes it needs. Here the")
    print("  simulator passes the FULL 64-bit value (upper bytes = 'garbage'); the")
    print("  real program passes it through C's conversion. Pointed-to values start")
    print("  as 1000, 2000, 3000, 40.\n")
    cases = [(1, 2, 3, 4), (5, 70000, 70000, 300), (-1, -1, -1, -1), (7, 2**31, 2**15, 128)]
    lines = ["proc %d %d %d %d" % c for c in cases]
    have_x86 = os.path.exists("build/oracle_x86")
    real = oracle("build/oracle_x86", lines) if have_x86 else ["(not built)"] * len(cases)
    print("  %-28s %-28s %-28s" % ("a1, a2, a3, a4 passed", "simulator", "real x86-64"))
    agree = 0
    for c, r in zip(cases, real):
        s = sim_proc(prog, *c)
        agree += (s == r)
        print("  %-28s %-28s %-28s %s" % (", ".join(map(str, c)), s, r, "same" if s == r else "DIFFERENT"))
    print("\n  %d of %d agree. E.g. a4 = 300 adds only its low byte 300 %% 256 = 44: 40+44 = 84;"
          % (agree, len(cases)))
    print("  a2 = 70000 does fit an int (2000+70000 = 72000), a3 = 70000 does not fit a")
    print("  short: 70000 - 65536 = 4464, so 3000+4464 = 7464. The `addw %r8w` and")
    print("  `addb %al` instructions only look at the low 2 and 1 bytes.\n")


def main():
    print("=== Demo 01: passing data -- registers and the stack ===\n")
    if not os.path.exists("build/oracle_x86"):
        subprocess.run(["make", "-s", "build/oracle_x86"], check=False)
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("procs.c"))
    part_a(prog)
    part_b(prog)
    part_c(prog)
    print("Observations:")
    print("  * Arguments 1-6 travel in registers (%rdi %rsi %rdx %rcx %r8 %r9); the")
    print("    callee uses each at the argument's size (%edx for an int, %r8w for a")
    print("    short). Arguments 7 and up travel on the stack, 8 bytes each.")
    print("  * The CALLER puts arguments 7+ at the very top of its frame (the argument")
    print("    build area); after `call` pushes the return address, the callee finds")
    print("    them at 8(%rsp), 16(%rsp), ...")
    print("  * Local variables whose address is taken (&x1 ... &x4) must live in")
    print("    memory, in the caller's frame; registers have no addresses.")
    print("  * %rsp is a multiple of 16 at every call: an ABI rule that lets callees")
    print("    use 16-byte aligned vector instructions on their stack data.")


if __name__ == "__main__":
    main()
