"""
06_stack_call_ret.py -- the stack, push/pop, and how call and ret find their way
================================================================================

[Questions this demo answers]
  - The x86-64 stack grows toward LOWER addresses and %rsp points at its top
    element. What exactly do push and pop do to %rsp and to memory?
  - How does `call` know where to come back to? (It pushes the address of the
    next instruction -- the return address -- and `ret` pops it into %rip.)
  - Why does multstore save %rbx before calling mult2?

[How to run]
  python3 06_stack_call_ret.py

[How to read the output]
  PART A runs four hand-written push/pop instructions and prints %rsp and the
  top of the stack after each. PART B traces multstore -> mult2 -> back,
  printing %rip (the simulator's made-up instruction addresses), %rsp and the
  stack: the slides' "Control Flow Example #1-#4".

[Systems link / CS:APP 3.7.1-3.7.2]
  The stack is ordinary memory used with a discipline: last in, first out.
  Each call needs somewhere to remember its return point, and calls nest
  (and recurse), so the most recent return point is always the next one
  needed -- exactly what a stack gives you. Lecture 5 builds the rest of the
  calling convention (arguments, locals, saved registers) on this.
"""

import os

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

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


def stack_view(m, words=4):
    """The top `words` 8-byte stack slots, from %rsp upward."""
    rsp = m.regs["rsp"]
    cells = []
    for k in range(words):
        a = rsp + 8 * k
        if a >= x86sim.STACK_TOP:
            break
        v = m.mem.read(a, 8)
        cells.append("[0x%x]=%s" % (a & 0xFFFF, "RET-TO-CALLER" if v == x86sim.RETURN_SENTINEL
                                     else hex(v)))
    return " ".join(cells) if cells else "(empty)"


def part_a():
    print("PART A: push and pop")
    prog = x86sim.Program("""
    f:  pushq  $0x11
        pushq  $0x22
        popq   %rax
        popq   %rbx
        ret
    """)
    m = x86sim.Machine(prog)
    m.regs["rsp"] = x86sim.STACK_TOP
    m.push(x86sim.RETURN_SENTINEL)
    m.rip, m.halted = prog.address_of("f"), False
    print("  (stack addresses shown as their low 16 bits; %%rsp starts at ...%04x)"
          % (m.regs["rsp"] & 0xFFFF))
    while not m.halted:
        ins = prog.instrs[prog.by_addr[m.rip]]
        m.step()
        if ins.op == "ret":
            break
        extra = ""
        if ins.op == "pop":
            reg = ins.operands[0].reg
            extra = "  %%%s=%s" % (reg, hex(m.regs[reg]))
        print("    %-16s %%rsp=...%04x  stack: %s%s" % (ins.text, m.regs["rsp"] & 0xFFFF,
                                                       stack_view(m), extra))
    print("  push: %rsp -= 8, then store.  pop: load, then %rsp += 8.")
    print("  After a pop the value is still in memory (just below %rsp) -- it is")
    print("  simply no longer part of the stack.\n")


def part_b(prog):
    print("PART B: multstore(x, y, dest) calls mult2(x, y)")
    print(x86sim.listing(prog, "multstore"))
    print(x86sim.listing(prog, "mult2"))
    m = x86sim.Machine(prog)
    m.regs["rbx"] = 0xBBBB                              # pretend the caller uses %rbx
    m.push(x86sim.RETURN_SENTINEL)
    m.regs["rdi"], m.regs["rsi"], m.regs["rdx"] = 6, 7, 0x8000
    m.rip, m.halted = prog.address_of("multstore"), False
    print("\n  %-24s %-10s %-8s %-8s %s" % ("instruction", "%rip after", "%rsp", "%rbx", "stack (top first)"))
    print("  %-24s 0x%-8x ...%04x  %-8s %s" % ("(entry)", m.rip, m.regs["rsp"] & 0xFFFF,
                                              hex(m.regs["rbx"]), stack_view(m)))
    while not m.halted:
        ins = prog.instrs[prog.by_addr[m.rip]]
        m.step()
        note = ""
        if ins.op == "call":
            note = "   <- pushed the return address 0x%x" % prog.next_addr[ins.addr]
        if ins.op == "ret" and not m.halted:
            note = "   <- popped it into %rip"
        rip = "(done)" if m.halted else "0x%x" % m.rip
        print("  %-24s %-10s ...%04x  %-8s %s%s" % (ins.text, rip, m.regs["rsp"] & 0xFFFF,
                                                   hex(m.regs["rbx"]), stack_view(m, 3), note))
    print("\n  *dest = %d (= 6 * 7); %%rbx is back to %s, as the caller expects."
          % (m.mem.read(0x8000, 8), hex(m.regs["rbx"])))
    print("  Why save %rbx? dest arrives in %rdx, but mult2 is allowed to overwrite")
    print("  %rdx. %rbx is 'callee-saved': mult2 must preserve it, so multstore parks")
    print("  dest there -- and, being a callee itself, must restore the caller's %rbx.\n")


def main():
    print("=== Demo 06: the stack, call and ret ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("control.c"))
    part_a()
    part_b(prog)
    print("Observations:")
    print("  * The stack grows DOWN: push subtracts 8 from %rsp, pop adds 8.")
    print("  * call = push the address of the next instruction + jump; ret = pop that")
    print("    address into %rip. Nothing else connects a function to its caller.")
    print("  * Registers are shared by all functions, so a convention decides who")
    print("    saves what (caller-saved vs callee-saved) -- Lecture 5 continues here.")


if __name__ == "__main__":
    main()
