"""
03_struct_code.py -- machine code for structures: offsets, lists, arrays of structs
====================================================================================

[Questions this demo answers]
  - In assembly the field NAMES are gone. How does r->next become 24(%rdi),
    and r->i become 16(%rdi)?
  - What does following a linked list look like, instruction by instruction?
  - How does the compiler index an ARRAY of structs (struct S3 a[10]), whose
    elements are 12 bytes including padding?
  - Does the simulator agree with the real x86-64 machine code?

[How to run]
  python3 03_struct_code.py

[How to read the output]
  Each part prints clang's -Og listing, then a trace or a table. The
  addresses of the simulated list nodes are made up (0x10000, 0x10200, ...);
  the FIELD OFFSETS are the point. The last part checks the simulator against
  the real x86-64 build (and the native build).

[Systems link / CS:APP 3.9.1-3.9.2]
  A struct is a block of memory; a field is a fixed OFFSET into it, computed
  by the compiler from the declaration. That is why a binary file format or a
  network packet layout is really just a struct, and why two programs that
  disagree about a struct's declaration cannot share its data.
"""

import os
import subprocess

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

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

NODES = [0x10000, 0x10200, 0x10100, 0x10300]          # a few, deliberately not in address order


def node_addr(k):
    """Address of node k: the first four from NODES, the rest spaced out."""
    return NODES[k] if k < len(NODES) else 0x20000 + 0x100 * k


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


def build_list(m, index_fields):
    """Write a linked list of struct rec into simulator memory; return its head."""
    n = len(index_fields)
    for k in range(n):
        base = node_addr(k)
        for j in range(4):
            m.mem.write(base + 4 * j, 4, 0)                        # a[0..3] = 0
        m.mem.write(base + 16, 8, index_fields[k])                # r->i
        m.mem.write(base + 24, 8, node_addr(k + 1) if k + 1 < n else 0)   # r->next
    return node_addr(0) if n else 0


def part_a(prog):
    print("PART A: struct rec { int a[4]; size_t i; struct rec *next; }  -- 32 bytes")
    print("  field offsets: a at 0 (16 bytes), i at 16, next at 24")
    print("  int *get_ap(struct rec *r, size_t idx) { return &r->a[idx]; }")
    print(x86sim.listing(prog, "get_ap"))
    m = x86sim.Machine(prog)
    outs = ["get_ap(r, %d) = r + %d" % (k, m.call("get_ap", 0x10000, k) - 0x10000) for k in range(4)]
    print("  " + "; ".join(outs))
    print("  &r->a[idx] = r + 0 + 4*idx: one lea, no memory access (a is at offset 0).\n")


def part_b(prog):
    print("PART B: length(r) -- following r->next (offset 24) until NULL")
    print(x86sim.listing(prog, "length"))
    m = x86sim.Machine(prog)
    head = build_list(m, [0, 0, 0, 0])
    r = m.call("length", head, trace=True)
    print("  a list of 4 nodes at %s:" % " -> ".join(hex(node_addr(k)) for k in range(4)))
    for st in m.trace:
        if "24(%rdi)" in st.text:
            change = next(((o, n) for reg, o, n in st.reg_changes if reg == "rdi"), None)
            if change:
                print("    movq 24(%%rdi), %%rdi : r = M[0x%x + 24] = %s" % (change[0], hex(change[1])))
    print("  length = %d. Each step reads the pointer field at offset 24; the loop" % r)
    print("  stops when it reads 0 (the last node's next). Exactly the slides' code.\n")


def part_c(prog):
    print("PART C: get_j(idx) -- an ARRAY of structs, struct S3 { short i; float v; short j; }")
    print("  struct S3 is 12 bytes (2 + 2 pad + 4 + 2 + 2 pad); a[idx].j is at a + 12*idx + 8")
    print(x86sim.listing(prog, "get_j"))
    m = x86sim.Machine(prog)
    base = prog.address_of("s3_array")
    for idx in range(10):                                  # fill j fields from the data section
        pass
    print("  s3_array lives at 0x%x; the .j fields initialized in structs.c are 100..109" % base)
    outs = [str(x86sim.to_signed(m.call("get_j", idx), 2)) for idx in range(10)]
    print("  get_j(0..9) = %s" % ", ".join(outs))
    print("  The index is scaled by 12 (leaq (%rcx,%rcx,2) = 3*idx, then *4), and 8 is")
    print("  added for field j: the struct's size, PADDING INCLUDED, is the stride.\n")


def gen(rng):
    lines = []
    for idx in range(6):
        lines.append("get_ap %d" % idx)
    for n in range(0, 9):
        lines.append("length %d" % n)
    for idx in range(10):
        lines.append("get_j %d" % idx)
    for _ in range(40):                                    # set_val with VALID indices (0..3)
        count = rng.randint(1, 6)
        idxs = [rng.randint(0, 3) for _ in range(count)]
        lines.append("set_val %d %s" % (rng.randint(-5, 5), " ".join(map(str, idxs))))
    return lines


def sim_line(prog, line):
    parts = line.split()
    name, a = parts[0], [int(x) for x in parts[1:]]
    m = x86sim.Machine(prog)
    if name == "get_ap":
        return str(m.call("get_ap", 0x10000, a[0]) - 0x10000)
    if name == "length":
        head = build_list(m, [0] * a[0]) if a[0] else 0
        return str(m.call("length", head))
    if name == "get_j":
        return str(x86sim.to_signed(m.call("get_j", a[0]), 2))
    if name == "set_val":
        val, idxs = a[0], a[1:]
        head = build_list(m, idxs)
        m.call("set_val", head, val)
        rows = []
        for k in range(len(idxs)):
            rows.append(" ".join(str(x86sim.to_signed(m.mem.peek(node_addr(k) + 4 * j, 4), 4))
                                 for j in range(4)))
        return " | ".join(rows)
    return "?"


def part_d():
    print("PART D: simulator vs real x86-64 (and native arm64)")
    if not os.path.exists("build/oracle_x86"):
        subprocess.run(["make", "-s", "build/oracle", "build/oracle_x86"], check=False)
    import random
    lines = gen(random.Random(213))
    real = oracle("build/oracle_x86", lines)
    native = oracle("build/oracle", lines)
    if real is None:
        real, native = native, None
    bad = 0
    first = None
    for opt in ("-Og", "-O1"):
        prog = x86sim.Program.from_file(x86sim.compile_to_asm("structs.c", opt=opt))
        for k, line in enumerate(lines):
            s = sim_line(prog, line)
            if s != real[k]:
                bad += 1
                first = first or (opt, line, s, real[k])
    nbad = sum(native[k] != real[k] for k in range(len(lines))) if native else 0
    print("  %d tests x 2 optimization levels: %d disagreements with real x86-64" % (len(lines), bad))
    print("  native arm64 vs real x86-64: %d disagreements" % nbad)
    if first:
        print("    first: %r at %s -> sim %r, hw %r" % (first[1], first[0], first[2], first[3]))
    print()


def main():
    print("=== Demo 02: structure machine code ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("structs.c"))
    part_a(prog)
    part_b(prog)
    part_c(prog)
    part_d()
    print("Observations:")
    print("  * A field access is a fixed offset: r->i is 16(%rdi), r->next is 24(%rdi).")
    print("    The compiler computed those offsets from the declaration; the assembly")
    print("    has no field names.")
    print("  * Following a linked list is one pointer load per node, from offset 24.")
    print("  * Indexing an array of structs multiplies by the struct's full size,")
    print("    padding included (12 for struct S3), then adds the field offset.")
    print("  * 0 disagreements with the hardware, at both optimization levels.")


if __name__ == "__main__":
    main()
