"""
04_operands_and_sizes.py -- b, w, l, q: how many bytes does an instruction touch?
================================================================================

[Questions this demo answers]
  - movb, movw, movl, movq store 1, 2, 4, 8 bytes. Which bytes exactly?
  - %rax, %eax, %ax, %al are four names for parts of ONE register. When you
    write %eax, what happens to the upper half of %rax? (It becomes 0!)
    And when you write %ax or %al? (The rest is untouched.)
  - How do movz?? and movs?? widen a value (Lecture 2's zero/sign extension)?

[How to run]
  make            (builds build/oracle_x86 for PART B's hardware check)
  python3 04_operands_and_sizes.py

[How to read the output]
  PART A dumps 8 bytes of memory around each store. PART B compares the
  simulator with the REAL x86-64 processor (or Rosetta 2) for the same three
  instructions. PART C widens one byte four different ways.

[Systems link / CS:APP 3.3-3.4]
  The suffix (b=byte, w=word=2 bytes, l=long word=4 bytes, q=quad word=8
  bytes) follows the C type of the data (char, short, int, long/pointer).
  The "32-bit writes zero the upper half" rule was AMD's design choice for
  x86-64 in 2003: it avoids a dependency on the old upper bits, so the CPU
  never has to merge partial registers for the most common case.
"""

import os
import subprocess

import x86sim

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


def dump(m, addr, n=8):
    return " ".join("%02x" % m.mem.read(addr + i, 1) for i in range(n))


def part_a(prog):
    print("PART A: store_sizes(c, s, i, l) does *c=1; *s=2; *i=3; *l=4")
    print(x86sim.listing(prog, "store_sizes"))
    m = x86sim.Machine(prog)
    addrs = {"c": 0x200, "s": 0x210, "i": 0x220, "l": 0x230}
    for a in addrs.values():
        m.mem.write(a, 8, 0xAAAAAAAAAAAAAAAA)          # fill with a visible pattern
    print("  memory before (each pointer's 8 bytes, lowest address first):")
    for k, a in addrs.items():
        print("    %s -> 0x%x: %s" % (k, a, dump(m, a)))
    m.call("store_sizes", addrs["c"], addrs["s"], addrs["i"], addrs["l"])
    print("  memory after:")
    for k, a in addrs.items():
        print("    %s -> 0x%x: %s" % (k, a, dump(m, a)))
    print("  -> movb wrote 1 byte, movw 2, movl 4, movq 8; the rest kept 0xaa.")
    print("     The value 3 in 4 bytes is 03 00 00 00: little endian (Lecture 2).\n")


def part_b(prog):
    print("PART B: writing part of a register -- simulator vs real hardware")
    start = 0x0123456789ABCDEF
    print("  %%rax starts as 0x%016x, then one instruction writes a smaller name:" % start)
    real = {}
    exe = os.path.join("build", "oracle_x86")
    if os.path.exists(exe):
        lines = "".join("alias_%s 0x%x\n" % (k, start) for k in ("movl", "movw", "movb"))
        out = subprocess.run([exe], input=lines, capture_output=True, text=True).stdout.split()
        real = dict(zip(("movl", "movw", "movb"), out))
    m = x86sim.Machine(prog)
    rows = [("movl", "movl $0x11, %eax", "4 bytes, upper 4 bytes ZEROED"),
            ("movw", "movw $0x22, %ax ", "2 bytes, the other 6 kept"),
            ("movb", "movb $0x33, %al ", "1 byte, the other 7 kept")]
    for key, text, what in rows:
        sim = m.call("alias_" + key, start)
        hw = real.get(key)
        hw_text = ("0x%016x" % (int(hw) & x86sim.MASK[8])) if hw not in (None, "n/a") else "(not run)"
        agree = "agree" if hw_text == "0x%016x" % sim else "DIFFER"
        print("    %s -> sim 0x%016x, hardware %s  %s  (%s)" % (text, sim, hw_text, agree, what))
    print()


def part_c():
    print("PART C: widening the byte 0xf0 (= 240 unsigned, -16 signed) four ways")
    prog = x86sim.Program("""
    f:  movzbl %dil, %eax        # zero-extend byte -> 4 bytes (and upper 4 -> 0)
        movsbl %dil, %ecx        # sign-extend byte -> 4 bytes
        movzbq %dil, %rdx        # zero-extend byte -> 8 bytes
        movsbq %dil, %rsi        # sign-extend byte -> 8 bytes
        ret
    """)
    m = x86sim.Machine(prog)
    m.call("f", 0xF0)
    for reg, ins in (("rax", "movzbl %dil, %eax"), ("rcx", "movsbl %dil, %ecx"),
                     ("rdx", "movzbq %dil, %rdx"), ("rsi", "movsbq %dil, %rsi")):
        v = m.regs[reg]
        print("    %-18s -> %%%s = 0x%016x = %d" % (ins, reg, v, x86sim.to_signed(v, 8)))
    print("  -> 'z' copies 0s, 's' copies the sign bit (Lecture 2 section 6).")
    print("     movsbl leaves 0xfffffff0 in %ecx and ZEROES the upper half of %rcx,")
    print("     so as a 64-bit value it is 4294967280, not -16: the size matters.\n")

    prog2 = x86sim.Program.from_file(x86sim.compile_to_asm("funcs.c"))
    print("  load_disp(int *a, long i) returns a[i + 32] as a long:")
    print(x86sim.listing(prog2, "load_disp"))
    m2 = x86sim.Machine(prog2)
    base = 0x5000
    m2.mem.write(base + 4 * (3 + 32), 4, -7)            # a[35] = -7 (4-byte int)
    r = m2.call("load_disp", base, 3)
    print("    with a[35] = -7: result %d  (movslq sign-extended the 4-byte int)\n"
          % x86sim.to_signed(r, 8))


def part_d():
    print("PART D: the names of one register family, and the suffix rule")
    print("    size    suffix  C type            rax family   r8 family")
    for size, suffix, ctype in ((8, "q", "long, pointer"), (4, "l", "int"),
                                (2, "w", "short"), (1, "b", "char")):
        names = [n for n, (full, s, off) in x86sim.REGISTERS.items()
                 if full in ("rax", "r8") and s == size and off == 0]
        print("    %d bytes  %s       %-17s %-12s %s" % (size, suffix, ctype, names[0], names[1]))
    print("    (plus %ah = bits 8..15 of %rax, a leftover from the 16-bit 8086)\n")


def main():
    print("=== Demo 04: operand sizes and partial registers ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("funcs.c"))
    part_a(prog)
    part_b(prog)
    part_c()
    part_d()
    print("Observations:")
    print("  * The size suffix is the number of bytes touched: b=1, w=2, l=4, q=8.")
    print("  * Writing a 4-byte register (%eax) clears the upper 4 bytes of %rax;")
    print("    writing a 2- or 1-byte register (%ax, %al) leaves the rest alone.")
    print("    The real CPU agrees with the simulator on all three.")
    print("  * movz/movs implement zero/sign extension; the destination size decides")
    print("    what the upper bits are, which is why -16 can turn into 4294967280.")


if __name__ == "__main__":
    main()
