"""
01_instruction_encoding.py -- how 'movq %rax, (%rbx)' becomes the bytes 48 89 03
================================================================================

[Questions this demo answers]
  - The slides split 48 89 03 into fields: REX = 0100 W R X B, opcode 89,
    ModRM = mod | reg | r/m. What does each field mean?
  - How are registers, memory operands D(Rb,Ri,S), and operand sizes encoded?
  - Is a 100-line decoder enough to read real programs? (We decode every
    register/memory mov in a real system binary and compare with objdump.)

[How to run]
  python3 01_instruction_encoding.py      (needs objdump)

[How to read the output]
  PART A dissects one instruction bit by bit. PART B decodes a few more
  shapes. PART C runs the decoder over every mov (opcodes 88/89/8a/8b) in
  an x86-64 program and counts agreements with objdump.

[Systems link / CS:APP 3.2.2, Intel SDM Vol. 2 chapter 2]
  An x86-64 instruction is: optional prefixes (0x66 = 16-bit operands,
  REX = 0x40..0x4f), an opcode, a ModRM byte naming the operands, an
  optional SIB byte (scale-index-base) and an optional displacement. The
  REX prefix was AMD's 2003 addition: W selects 64-bit operands, and R, X, B
  each supply a 4th register-number bit so that %r8..%r15 can be named.
"""

import os
import platform
import re
import subprocess

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

REG64 = ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
         "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"]     # hardware order!
REG32 = ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"] + ["r%dd" % i for i in range(8, 16)]
REG16 = ["ax", "cx", "dx", "bx", "sp", "bp", "si", "di"] + ["r%dw" % i for i in range(8, 16)]
REG8_REX = ["al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil"] + ["r%db" % i for i in range(8, 16)]
REG8_LEGACY = ["al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"]


def reg_name(num, size, rex_present):
    """Name of register number 0..15 for an operand of `size` bytes."""
    if size == 8:
        return REG64[num]
    if size == 4:
        return REG32[num]
    if size == 2:
        return REG16[num]
    return REG8_REX[num] if rex_present else REG8_LEGACY[num]


def decode_mov(code):
    """
    Decode one register/memory MOV (opcodes 88, 89, 8a, 8b).

    [Parameters] code -- list of byte values, starting at the instruction.
    [Returns] (text, length) such as ('movq %rax, (%rbx)', 3), or None if
      the bytes are not a MOV of this family.
    [Edge cases]
      * ModRM r/m = 100 means "an SIB byte follows" (needed for an index);
      * mod = 00 with r/m = 101 means RIP-relative disp32 (globals);
      * SIB index = 100 (without REX.X) means "no index";
      * SIB base = 101 with mod = 00 means "no base, disp32 follows".
    """
    i, opsize16, rex = 0, False, 0
    if code[i] == 0x66:                         # operand-size prefix: 16-bit
        opsize16, i = True, i + 1
    if 0x40 <= code[i] <= 0x4F:                 # REX = 0100 W R X B
        rex, i = code[i], i + 1
    op = code[i]
    if op not in (0x88, 0x89, 0x8A, 0x8B):
        return None
    i += 1
    W, R, X, B = (rex >> 3) & 1, (rex >> 2) & 1, (rex >> 1) & 1, rex & 1
    size = 1 if op in (0x88, 0x8A) else (8 if W else (2 if opsize16 else 4))
    suffix = {1: "b", 2: "w", 4: "l", 8: "q"}[size]

    modrm = code[i]
    i += 1
    mod, reg, rm = modrm >> 6, (modrm >> 3) & 7, modrm & 7
    reg_text = "%" + reg_name(reg | (R << 3), size, rex != 0)

    if mod == 3:                                # register-to-register
        rm_text = "%" + reg_name(rm | (B << 3), size, rex != 0)
    else:
        base = index = None
        scale, disp = 1, 0
        if rm == 4:                             # SIB byte follows
            sib = code[i]
            i += 1
            scale = 1 << (sib >> 6)
            idx = ((sib >> 3) & 7) | (X << 3)
            index = None if idx == 4 else REG64[idx]
            b = sib & 7
            if mod == 0 and b == 5:             # no base register, disp32
                base = "none"
            else:
                base = REG64[b | (B << 3)]
        elif mod == 0 and rm == 5:
            base = "rip"
        else:
            base = REG64[rm | (B << 3)]
        if mod == 1:
            disp = int.from_bytes(bytes(code[i:i + 1]), "little", signed=True)
            i += 1
        elif mod == 2 or base in ("rip", "none"):
            disp = int.from_bytes(bytes(code[i:i + 4]), "little", signed=True)
            i += 4
        inner = "" if base == "none" else "%" + base
        if index:
            inner += ",%" + index + ("," + str(scale) if scale != 1 else "")
        rm_text = ("%s(%s)" % (fmt_disp(disp) if disp or base == "none" else "", inner))
    if op in (0x88, 0x89):                      # reg -> r/m
        return "mov%s %s, %s" % (suffix, reg_text, rm_text), i
    return "mov%s %s, %s" % (suffix, rm_text, reg_text), i


def fmt_disp(d):
    return ("-0x%x" % -d) if d < 0 else "0x%x" % d


def normalize(text):
    """Make objdump's and our spellings comparable (sizes, spaces, number bases)."""
    text = text.split("#")[0].strip().lower()
    text = re.sub(r"^mov[bwlq]?\s+", "mov ", text)
    text = text.replace(" ", "").replace(",1)", ")")
    text = re.sub(r"-?0x[0-9a-f]+|-?\d+(?=\()",
                  lambda m: str(int(m.group(0), 16) if "x" in m.group(0) else int(m.group(0))),
                  text)
    return text


def parse_objdump(out):
    """Yield (address, [bytes], text) for each instruction line of objdump -d."""
    for line in out.splitlines():
        m = re.match(r"^\s*([0-9a-f]+):\s+((?:[0-9a-f]{2} )+)\s*(.*)$", line.replace("\t", " ") + "")
        if m:
            yield int(m.group(1), 16), [int(b, 16) for b in m.group(2).split()], m.group(3).strip()


def part_a():
    print("PART A: dissecting 48 89 03  (movq %rax, (%rbx), the slides' example)")
    code = [0x48, 0x89, 0x03]
    rex, op, modrm = code
    print("  48 = %s   REX prefix 0100|W R X B:  W=%d (64-bit operands)  R=%d X=%d B=%d"
          % (format(rex, "08b"), (rex >> 3) & 1, (rex >> 2) & 1, (rex >> 1) & 1, rex & 1))
    print("  89 = %s   opcode: MOV r/m <- reg  (8b would be reg <- r/m)" % format(op, "08b"))
    print("  03 = %s   ModRM: mod=%s  reg=%s  r/m=%s" % (format(modrm, "08b"),
          format(modrm >> 6, "02b"), format((modrm >> 3) & 7, "03b"), format(modrm & 7, "03b")))
    print("        mod=00 -> memory operand, no displacement")
    print("        reg=000 -> register 0 = %rax (the source)")
    print("        r/m=011 -> register 3 = %rbx, used as the ADDRESS: (%rbx)")
    print("  decoded:", decode_mov(code)[0])
    print("  (register numbers are 0 rax, 1 rcx, 2 rdx, 3 rbx, 4 rsp, 5 rbp, 6 rsi, 7 rdi;")
    print("   the REX bits R/X/B add 8 to reach %r8..%r15)\n")


def part_b():
    print("PART B: more shapes")
    samples = [
        ([0x48, 0x8B, 0x04, 0xF7], "array load a[i]: SIB byte, scale 8"),
        ([0x48, 0x63, 0x44, 0xB7, 0x80], "(movslq -- a different opcode, 63)"),
        ([0x4C, 0x89, 0xC0], "register to register, REX.R names %r8"),
        ([0x89, 0x54, 0xB7, 0x10], "no REX: 32-bit, disp8 = 0x10"),
        ([0x88, 0x14, 0x37], "byte store d[y] = a"),
        ([0x48, 0x8B, 0x05, 0x10, 0x00, 0x00, 0x00], "RIP-relative: a global variable"),
    ]
    for code, note in samples:
        r = decode_mov(code)
        text = r[0] if r else "(not a 88/89/8a/8b mov)"
        print("  %-24s -> %-34s %s" % (" ".join("%02x" % b for b in code), text, note))
    print()


def part_c():
    print("PART C: decode every 88/89/8a/8b mov in a real x86-64 program, compare with objdump")
    candidates = []
    if platform.system() == "Darwin":
        candidates.append((["objdump", "-d", "--arch=x86_64", "/bin/ls"], "/bin/ls (x86-64 slice)"))
    elif platform.machine().lower() in ("x86_64", "amd64"):
        candidates.append((["objdump", "-d", "/bin/ls"], "/bin/ls"))
    candidates.append((["objdump", "-d", "build/oracle_x86"], "build/oracle_x86"))
    for cmd, label in candidates:
        try:
            out = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout
        except (subprocess.CalledProcessError, FileNotFoundError):
            continue
        total = match = 0
        mismatches = []
        for addr, code, text in parse_objdump(out):
            r = decode_mov(code)
            if r is None or not text.startswith("mov"):
                continue
            total += 1
            ours, length = r
            if normalize(ours) == normalize(text) and length == len(code):
                match += 1
            elif len(mismatches) < 5:
                mismatches.append((addr, code, text, ours))
        print("  %s: %d mov instructions, decoder agrees with objdump on %d" % (label, total, match))
        for addr, code, text, ours in mismatches:
            print("    0x%x %s : objdump '%s' vs ours '%s'" % (addr, " ".join("%02x" % b for b in code),
                                                             text, ours))
        if total:
            return total, match
    print("  (no x86-64 binary found to test on)")
    return 0, 0


def main():
    print("=== Demo 01: x86-64 instruction encoding (the mov family) ===\n")
    part_a()
    part_b()
    total, match = part_c()
    print()
    print("Observations:")
    print("  * An instruction is prefix(es) + opcode + ModRM [+ SIB] [+ displacement].")
    print("    48 89 03: REX.W (64-bit), opcode 89 (store a register), ModRM 00 000 011")
    print("    = source %rax, destination memory at (%rbx).")
    print("  * The addressing mode D(Rb,Ri,S) is encoded directly: mod picks no/8-bit/")
    print("    32-bit displacement, the SIB byte holds scale, index and base.")
    print("  * Instructions vary in length (2-7 bytes in these samples, up to 15 on x86-64).")
    if total:
        print("  * A ~100-line decoder matched objdump on %d of %d real mov instructions."
              % (match, total))


if __name__ == "__main__":
    main()
