"""
02_stack_frames.py -- local variables in the stack frame (the slides' incr example)
====================================================================================

[Questions this demo answers]
  - When does a function need a STACK FRAME, and what goes in it?
  - call_incr passes &v1 to incr. Where does v1 live, and how does incr's
    change to *p become visible to call_incr?
  - What do the "set-up" and "finish" code of a frame look like (subq/addq,
    push/pop), and how does the frame stay 16-byte aligned?

[How to run]
  python3 02_stack_frames.py

[How to read the output]
  PART A runs the slides' gcc listing of call_incr/incr (as text) and prints
  the stack after each instruction -- the slides' "Before Calling incr" ...
  "Returning From call_incr" pictures. PART B does the same for clang's code
  from procs.c. PART C stops inside incr called from call_incr2 and draws
  both frames. PART D measures every function's frame size.

[Systems link / CS:APP 3.7.4-3.7.5]
  A frame is allocated by moving %rsp down on entry and released by moving it
  back before `ret`. Nothing else in the hardware knows about frames: they
  are a CONVENTION, which is why a bug that writes past a local array can
  overwrite the saved registers and the return address above it (Lecture 6).
"""

import os

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

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

# The slides' listing (gcc -Og on the shark machines), run as text.
GCC_INCR = """
call_incr:
  subq    $16, %rsp
  movq    $15213, 8(%rsp)
  movl    $3000, %esi
  leaq    8(%rsp), %rdi
  call    incr
  addq    8(%rsp), %rax
  addq    $16, %rsp
  ret
incr:
  movq    (%rdi), %rax
  addq    %rax, %rsi
  movq    %rsi, (%rdi)
  ret
"""


def slots(m, entry):
    """The stack between %rsp and the caller's slot, as 'value' strings, top first."""
    out = []
    a = entry
    while a >= m.regs["rsp"]:
        v = m.mem.peek(a, 8)
        out.append("RET" if v == x86sim.RETURN_SENTINEL else
                   ("ret->call_incr" if a < entry and v in frames.return_addresses(m.prog)
                    else frames.fmt_value(v)))
        a -= 8
    return " | ".join(out)


def step_through(prog, name, *args):
    """Run name(*args), printing each instruction and the stack after it."""
    m = x86sim.Machine(prog)
    m.start(name, *args)
    entry = m.regs["rsp"]
    print("  %-26s %-9s %-7s %-7s %s" % ("instruction", "%rsp", "%rdi", "%rax",
                                         "stack from the return address down to %rsp"))
    print("  %-26s ...%04x  %-7s %-7s %s" % ("(entry)", entry & 0xFFFF, "", "", slots(m, entry)))
    while not m.halted:
        ins = prog.instrs[prog.by_addr[m.rip]]
        depth = "  " if frames.current_function(m) != name else ""
        m.step()
        if m.halted:
            print("  %-26s (returned to the caller with %%rax = %d)" % (ins.text, m.regs["rax"]))
            break
        rdi = m.regs["rdi"]
        rdi_s = "...%04x" % (rdi & 0xFFFF) if rdi > 0xFFFF else str(rdi)
        print("  %-26s ...%04x  %-7s %-7s %s" % (depth + ins.text, m.regs["rsp"] & 0xFFFF, rdi_s,
                                                 frames.fmt_value(m.regs["rax"]), slots(m, entry)))
    return m.regs["rax"]


def part_a():
    print("PART A: the slides' gcc code for call_incr / incr")
    print("  long incr(long *p, long val) { long x = *p; long y = x + val; *p = y; return x; }")
    print("  long call_incr() { long v1 = 15213; long v2 = incr(&v1, 3000); return v1+v2; }\n")
    prog = x86sim.Program(GCC_INCR, "slides-gcc")
    r = step_through(prog, "call_incr")
    print("\n  Result %d = 18213 (the new v1) + 15213 (incr's return value, the old v1)." % r)
    print("  `subq $16` makes room for v1 at 8(%rsp); 0(%rsp) stays unused, because")
    print("  the frame must keep %rsp a multiple of 16 at the call. `leaq 8(%rsp),")
    print("  %rdi` computes &v1 -- lea used for what it was designed for: an address.\n")


def part_b():
    print("PART B: clang's code for the same functions (procs.c, -Og)")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("procs.c"))
    print(x86sim.listing(prog, "call_incr"))
    print(x86sim.listing(prog, "incr"))
    print()
    r = step_through(prog, "call_incr")
    print("\n  Same result, %d. clang allocates the 8 bytes with `pushq %%rax` (the" % r)
    print("  value pushed does not matter; it is overwritten at once) and frees them")
    print("  with `popq %rcx`. A push is a 1-byte instruction; `subq $8,%rsp` is 4.")
    print("  Either way: on entry %rsp % 16 == 8 (the call pushed 8 bytes), so")
    print("  exactly 8 more bytes make it a multiple of 16 again before the call.\n")
    return prog


def part_c(prog):
    print("PART C: call_incr2(100) -- a value that must survive the call")
    print("  long call_incr2(long x) { long v1 = 15213; long v2 = incr(&v1, 3000);")
    print("                            return x + v2; }")
    print(x86sim.listing(prog, "call_incr2"))
    m = x86sim.Machine(prog)
    m.regs["rbx"] = 0xCAFE                       # the caller's %rbx, to be preserved
    m.start("call_incr2", 100)
    entry = m.regs["rsp"]
    while frames.current_function(m) != "incr":  # run until incr's first instruction
        m.step()
    notes = {entry - 8: "saved %rbx (the caller's value 0xcafe = 51966)",
             entry - 16: "v1",
             entry - 24: "unused (alignment)"}
    print("\n  Stopped at incr's first instruction. %%rbx = %d (x, parked by call_incr2)."
          % m.regs["rbx"])
    print(frames.draw(m, notes=notes))
    print("  Above the dashed line: the outside caller's frame, ending (CS:APP's")
    print("  convention) with the return address it pushed. Below it: call_incr2's")
    print("  frame -- saved %rbx, the local v1, padding, and at the bottom the return")
    print("  address its own `call` pushed. incr, a LEAF, needs no frame at all.")
    while not m.halted:
        m.step()
    print("\n  call_incr2(100) = %d (= 100 + 15213); %%rbx after return = %s (restored).\n"
          % (m.regs["rax"], hex(m.regs["rbx"])))


def frame_sizes(prog, name, *args, setup=None):
    """
    [Idea] Run name(*args) and measure, for every function ACTIVATION, how far
      below its entry %rsp the stack pointer went while that activation was
      running (not counting its callees' frames). The entry %rsp points at the
      return address, so the result is the frame size WITHOUT the return
      address.
    [Returns] dict function name -> largest frame size seen (bytes).
    """
    m = x86sim.Machine(prog)
    if setup:
        setup(m)
    m.start(name, *args)
    acts = [[name, m.regs["rsp"], 0]]            # (function, entry rsp, max depth)
    sizes = {}
    while not m.halted:
        ins = prog.instrs[prog.by_addr[m.rip]] if m.rip in prog.by_addr else None
        m.step()
        if ins is None:                          # an external stub returned
            continue
        if ins.op == "call" and not m.halted:
            acts.append([frames.current_function(m), m.regs["rsp"], 0])
        elif ins.op == "ret":
            f, e, d = acts.pop()
            sizes[f] = max(sizes.get(f, 0), d)
        else:                                    # (a tail-call `jmp` keeps the frame)
            f, e, d = acts[-1]
            acts[-1][2] = max(d, e - m.regs["rsp"])
    return sizes


def part_d(prog):
    print("PART D: how big is each function's frame? (bytes below the return address)")
    heap = 0x10000

    def ptrs(m):
        for k in range(4):
            m.mem.write(heap + 8 * k, 8, 0)
    runs = [("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", (0b1011,)), ("rfact", (5,)),
            ("popcount_t", (0b1011, 0))]
    why = {"mult2": "leaf, registers only", "incr": "leaf, registers only",
           "proc": "leaf; reads its stack arguments from the CALLER's frame",
           "multstore": "saved %rbx", "call_incr": "v1 (these 8 bytes also restore 16-byte alignment)",
           "call_incr2": "saved %rbx, v1, 8 bytes padding",
           "call_proc": "locals x1..x4, padding, 16-byte argument build area",
           "pcount_r": "saved %r14, %rbx + 8 bytes padding (per recursive call!)",
           "rfact": "saved %rbx (per recursive call)",
           "popcount_t": "a tail call: `jmp`, not `call`, so no new frame"}
    seen = {}
    for name, args in runs:
        for f, size in frame_sizes(prog, name, *args, setup=ptrs).items():
            seen.setdefault(f, size)
    print("  %-12s %6s   %s" % ("function", "frame", "what is in it"))
    for name, _ in runs:
        print("  %-12s %6d   %s" % (name, seen.get(name, 0), why.get(name, "")))
    print("  Every non-leaf frame size + 8 (the return address) is a multiple of 16,")
    print("  so %rsp is 16-byte aligned at each call it makes.\n")


def main():
    print("=== Demo 02: stack frames -- locals, saved registers, alignment ===\n")
    part_a()
    prog = part_b()
    part_c(prog)
    part_d(prog)
    print("Observations:")
    print("  * A frame holds what does not fit in (or cannot live in) registers: locals")
    print("    whose address is taken, saved callee-saved registers, arguments 7+ for")
    print("    the next call, and padding for alignment. Leaf functions often need none.")
    print("  * Set-up = move %rsp down (subq, or pushes); finish = move it back (addq,")
    print("    or pops) right before `ret`, so that `ret` finds the return address.")
    print("  * gcc and clang lay the same frame out differently (v1 at 8(%rsp) vs")
    print("    0(%rsp); subq vs push) -- the convention fixes the INTERFACE, not the")
    print("    inside of a frame.")


if __name__ == "__main__":
    main()
