"""
01_c_to_machine_code.py -- one C function, followed all the way down
=====================================================================

[Questions this demo answers]
  - What does the compiler turn sumstore() into? (assembly, AT&T syntax)
  - What do those instructions look like as BYTES? (machine code)
  - Why does the call instruction in the .o file end in 00 00 00 00, and who
    fills it in? (the linker -- Lecture 7)
  - Same bytes, two spellings: AT&T vs Intel syntax.
  - Same C, a different ISA: the arm64 version for comparison.

[How to run]
  python3 01_c_to_machine_code.py        (needs a C compiler and objdump)

[How to read the output]
  Each STEP prints the artifact of one stage of the toolchain
  (C -> .s -> .o -> executable), cut down to the sumstore function.

[Systems link / CS:APP 3.2]
  gcc -Og -S produces assembly; gcc -c (the assembler) encodes it into
  machine code in an object file; the linker joins object files and fixes up
  the addresses that were unknown before. objdump -d (a disassembler) turns
  bytes back into assembly -- on ANY bytes, which is how bomblab works.
"""

import os
import platform
import subprocess
import sys

import x86sim

HERE = os.path.dirname(os.path.abspath(__file__))
os.chdir(HERE)                   # so relative paths like build/ work anywhere


def run(cmd):
    """Run a command; return its stdout as text (raise if it fails)."""
    return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout


def objdump_function(path, name, intel=False):
    """
    Disassemble `path` and keep only the block of function `name`.
    [Idea] objdump prints '<name>:' (Linux) or '<_name>:' (macOS) followed by
      one line per instruction and then a blank line.
    [Edge cases] LLVM's objdump wants --x86-asm-syntax=intel, GNU's wants
      -M intel; we try LLVM's spelling first.
    """
    cmds = [["objdump", "-d", path]]
    if intel:
        cmds = [["objdump", "-d", "--x86-asm-syntax=intel", path],
                ["objdump", "-d", "-M", "intel", path]]
    for cmd in cmds:
        try:
            out = run(cmd)
            break
        except subprocess.CalledProcessError:
            continue
    else:
        return "(objdump failed)"
    lines, keep = [], False
    for line in out.splitlines():
        if line.rstrip().endswith(("<%s>:" % name, "<_%s>:" % name)):
            keep = True
        elif keep and not line.strip():
            break
        if keep and "nop" not in line:          # drop alignment padding
            lines.append(line.replace("\t", "  "))
    return "\n".join(lines)


def parse_listing(block):
    """
    Split objdump lines like '100000b74: e8 e7 ff ff ff   callq ...' into
    (address, [byte values], text).
    [Idea] after the 'address:' come two-hex-digit byte tokens, then the
      instruction text. We take tokens while they look like bytes.
    """
    result = []
    for line in block.splitlines():
        if ":" not in line or line.rstrip().endswith(">:"):
            continue
        addr_text, rest = line.split(":", 1)
        try:
            addr = int(addr_text.strip(), 16)
        except ValueError:
            continue
        tokens = rest.split()
        code = []
        while tokens and len(tokens[0]) == 2 and all(c in "0123456789abcdef" for c in tokens[0]):
            code.append(int(tokens.pop(0), 16))
        result.append((addr, code, " ".join(tokens)))
    return result


def main():
    print("=== Demo 01: from C to machine code (function sumstore) ===\n")

    print("STEP 1. The C source (funcs.c):")
    print("    long plus(long x, long y);")
    print("    void sumstore(long x, long y, long *dest) {")
    print("        long t = plus(x, y);")
    print("        *dest = t;")
    print("    }\n")

    asm = x86sim.compile_to_asm("funcs.c")
    prog = x86sim.Program.from_file(asm)
    print("STEP 2. Assembly from the compiler (x86-64, AT&T syntax, -Og), %s:" % asm)
    print(x86sim.listing(prog, "sumstore"))
    print("  (left column: the simulator's made-up addresses, 4 apart)\n")

    print("STEP 3. Assembled into an object file (.o) -- addresses start at the")
    print("        file's own offset and the call target is still unknown:")
    obj = os.path.join("build", "funcs.x86_64.o")
    flags = ["-std=c11"] + x86sim.ASM_FLAGS
    run(x86sim.x86_64_compiler() + ["-c", "-o", obj] + flags + ["funcs.c"])
    print(objdump_function(obj, "sumstore"))
    print()

    exe = os.path.join("build", "oracle_x86")
    if not os.path.exists(exe):
        run(["make", "-s", "build/oracle_x86"])
    print("STEP 4. Linked into an executable -- now the call has a real target:")
    linked = objdump_function(exe, "sumstore")
    print(linked)
    insns = parse_listing(linked)
    print("  -> sumstore is %d bytes of machine code in %d instructions" %
          (sum(len(b) for _, b, _ in insns), len(insns)))
    for addr, code, text in insns:
        if code and code[0] == 0xE8:                 # call rel32
            disp = int.from_bytes(bytes(code[1:5]), "little", signed=True)
            nxt = addr + len(code)
            print("  -> decoding the call: e8 = 'call rel32'; displacement bytes %s"
                  % " ".join("%02x" % b for b in code[1:5]))
            print("     read little endian = %d; target = next instruction 0x%x %+d = 0x%x"
                  % (disp, nxt, disp, nxt + disp))
    print()

    print("STEP 5. The same bytes in Intel syntax (destination first, no %, no size suffix):")
    print(objdump_function(exe, "sumstore", intel=True))
    print()

    if platform.machine().lower() not in ("x86_64", "amd64"):
        print("STEP 6. The same C compiled for THIS machine (%s):" % platform.machine())
        native = os.path.join("build", "funcs.native.s")
        run(["cc", "-std=c11", "-Og", "-fno-asynchronous-unwind-tables", "-S",
             "-o", native, "funcs.c"])
        nprog_lines, keep = [], False
        for line in open(native):
            s = line.strip()
            if s.startswith("_sumstore:") or s.startswith("sumstore:"):
                keep = True
                continue
            if keep:
                if s.startswith(";") or s.startswith("//") or s.startswith(".") or not s:
                    continue
                nprog_lines.append("    " + s.split(";")[0].rstrip().replace("\t", " "))
                if s.startswith("ret"):
                    break
        print("\n".join(nprog_lines))
        print("  (arm64: fixed 4-byte instructions, 31 registers x0..x30, the return")
        print("   address lives in register x30 -- different ISA, same C semantics)\n")

    print("Observations:")
    print("  * The compiler turns 2 lines of C into 6 instructions: save %rbx, keep")
    print("    dest in %rbx across the call, call plus, store %rax through dest.")
    print("  * Machine code is just bytes: 'movq %rax,(%rbx)' is 48 89 03, 'ret' is c3.")
    print("    x86-64 instructions have different lengths (1, 3 or 5 bytes here).")
    print("  * In the .o file the call's 4-byte displacement is 00 00 00 00; the")
    print("    linker fills it in (Lecture 7). Displacements are little endian.")
    print("  * AT&T (source, destination) and Intel (destination, source) are two")
    print("    spellings of the same machine code; 15-213 uses AT&T.")


if __name__ == "__main__":
    try:
        main()
    except (subprocess.CalledProcessError, FileNotFoundError, x86sim.SimError) as e:
        print("could not run the toolchain:", e)
        sys.exit(1)
