TExcelTAD
Home › Reverse Engineering & Binary Analysis › A Tiny x86-64 Decoder in Python

A Tiny x86-64 Decoder in Python

Disassemblers feel like magic until you write one. x86-64 machine code is a variable-length encoding: an instruction is 1 to 15 bytes, made of optional prefixes, an opcode, an optional ModRM byte that names registers and memory operands, and optional displacement and immediate bytes. Decoding a few common instructions by hand teaches three things an analyst needs: why disassemblers can be confused by bytes that aren't code, how to read raw hex in a crash dump or a patch, and what a "byte pattern" in a YARA rule actually matches. This lesson builds a decoder for about twenty instructions and checks it against objdump on the same bytes.

The encoding, just enough of it

REX 0100WRXB opcode 1-3 B ModRM mod|reg|rm disp 0/1/4 B imm 0/1/4/8 B 48897d = 01 111 101f8 = -8none W=1: 64-bitmov r/m, rdisp8, reg=rdi, rm=rbp 48 89 7d f8 = mov QWORD PTR [rbp-0x8], rdi
  • REX prefix 0x40-0x4F: bit W (8) selects 64-bit operands; R (4), X (2) and B (1) add a fourth bit to the register numbers, reaching r8-r15.
  • Opcode: one byte for most common instructions (0x89 mov r/m←reg, 0x8B mov reg←r/m, 0x01 add, 0x29 sub, 0x31 xor, 0x39 cmp, 0x85 test), two bytes starting with 0x0F for others (0F 05 syscall). Some opcodes contain the register: 0x50+r push, 0x58+r pop, 0xB8+r mov reg, imm.
  • ModRM byte: mod (2 bits) says register (11) or memory with no, 8-bit or 32-bit displacement (00, 01, 10); reg (3 bits) is a register operand or, for "group" opcodes such as 0x83, an extension that picks the operation (/0 add, /5 sub, /7 cmp); rm (3 bits) is the other operand. Special cases: rm = 100 adds a SIB byte (scaled index), mod = 00 with rm = 101 means [rip+disp32].
  • Relative branches: 74/75 (je/jne) and EB (jmp) take an 8-bit signed displacement, E8 (call) and E9 (jmp) a 32-bit one, counted from the end of the instruction.

Register numbers 0 to 15 are rax rcx rdx rbx rsp rbp rsi rdi r8 ... r15; the order is historical, not alphabetical.

The reference: objdump on the same bytes

The session assembles a small function with NASM into raw bytes (no file format at all), prints them in hex, and disassembles them with objdump. The hex string is what the Python decoder below receives.

bash · try it yourself
cat > snip.asm <<'SRC'
bits 64
check:
    push rbp
    mov rbp, rsp
    sub rsp, 0x10
    mov [rbp-8], rdi
    xor eax, eax
    cmp rdi, 0x2a
    jne .no
    mov eax, 1
.no:
    add rax, rsi
    leave
    ret
SRC
nasm -f bin snip.asm -o snip.bin
xxd -p snip.bin
objdump -D -b binary -m i386:x86-64 -M intel snip.bin | grep -E '^\s+[0-9a-f]+:'
554889e54883ec1048897df831c04883ff2a7505b8010000004801f0c9c3
   0:	55                   	push   rbp
   1:	48 89 e5             	mov    rbp,rsp
   4:	48 83 ec 10          	sub    rsp,0x10
   8:	48 89 7d f8          	mov    QWORD PTR [rbp-0x8],rdi
   c:	31 c0                	xor    eax,eax
   e:	48 83 ff 2a          	cmp    rdi,0x2a
  12:	75 05                	jne    0x19
  14:	b8 01 00 00 00       	mov    eax,0x1
  19:	48 01 f0             	add    rax,rsi
  1c:	c9                   	leave
  1d:	c3                   	ret

The decoder

python · try it yourself
REG64 = ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
         "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"]
REG32 = ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
         "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"]
MODRM_OPS = {0x89: ("mov", "rm,reg"), 0x8B: ("mov", "reg,rm"), 0x01: ("add", "rm,reg"),
             0x29: ("sub", "rm,reg"), 0x31: ("xor", "rm,reg"), 0x39: ("cmp", "rm,reg"),
             0x85: ("test", "rm,reg")}
GROUP83 = {0: "add", 5: "sub", 7: "cmp"}
SIMPLE = {0xC3: "ret", 0xC9: "leave", 0x90: "nop", 0xCC: "int3"}

def s8(b):  return b - 256 if b > 127 else b
def s32(v): return v - (1 << 32) if v >= 1 << 31 else v
def hx(n):  return f"-0x{-n:x}" if n < 0 else f"0x{n:x}"

def modrm(code, i, rex, wide):
    """Decode a ModRM byte (no SIB support). Returns (reg_name, rm_text, new_i) or None."""
    m = code[i]; mod, reg, rm = m >> 6, (m >> 3) & 7, m & 7
    regs = REG64 if wide else REG32
    reg_name = regs[reg | (8 if rex & 4 else 0)]
    i += 1
    if mod == 3:
        return reg_name, regs[rm | (8 if rex & 1 else 0)], i
    if rm == 4:
        return None                      # SIB byte: not supported in this tiny decoder
    size = "QWORD PTR" if wide else "DWORD PTR"
    if mod == 0 and rm == 5:
        disp = s32(int.from_bytes(code[i:i + 4], "little")); i += 4
        return reg_name, f"{size} [rip{'+' if disp >= 0 else ''}{hx(disp)}]", i
    base = REG64[rm | (8 if rex & 1 else 0)]
    disp = 0
    if mod == 1: disp = s8(code[i]); i += 1
    if mod == 2: disp = s32(int.from_bytes(code[i:i + 4], "little")); i += 4
    tail = "" if disp == 0 else ("+" if disp > 0 else "") + hx(disp)
    return reg_name, f"{size} [{base}{tail}]", i

def decode_one(code, i):
    start, rex = i, 0
    if 0x40 <= code[i] <= 0x4F:
        rex = code[i]; i += 1
    wide = bool(rex & 8)
    op = code[i]; i += 1
    if op in SIMPLE:
        return SIMPLE[op], i
    if 0x50 <= op <= 0x57: return f"push {REG64[(op - 0x50) | (8 if rex & 1 else 0)]}", i
    if 0x58 <= op <= 0x5F: return f"pop {REG64[(op - 0x58) | (8 if rex & 1 else 0)]}", i
    if 0xB8 <= op <= 0xBF and not wide:
        imm = int.from_bytes(code[i:i + 4], "little")
        return f"mov {REG32[(op - 0xB8) | (8 if rex & 1 else 0)]},{hx(imm)}", i + 4
    if op in MODRM_OPS:
        name, form = MODRM_OPS[op]
        r = modrm(code, i, rex, wide)
        if r is None: return None, start + 1
        reg, rm, i = r
        return (f"{name} {rm},{reg}" if form == "rm,reg" else f"{name} {reg},{rm}"), i
    if op == 0x83:
        ext = (code[i] >> 3) & 7
        if ext in GROUP83:
            r = modrm(code, i, rex, wide)
            if r:
                _, rm, i = r
                return f"{GROUP83[ext]} {rm},{hx(s8(code[i]))}", i + 1
    if op in (0x74, 0x75, 0xEB):
        target = i + 1 + s8(code[i])
        return f"{ {0x74: 'je', 0x75: 'jne', 0xEB: 'jmp'}[op] } {hx(target)}", i + 1
    if op == 0xE8:
        target = i + 4 + s32(int.from_bytes(code[i:i + 4], "little"))
        return f"call {hx(target)}", i + 4
    if op == 0x0F and code[i] == 0x05:
        return "syscall", i + 1
    return None, start + 1                # unknown: skip one byte, like objdump's (bad)

def disassemble(hexstr):
    code = bytes.fromhex(hexstr)
    i = 0
    while i < len(code):
        text, nxt = decode_one(code, i)
        raw = " ".join(f"{b:02x}" for b in code[i:nxt])
        print(f"{i:4x}:  {raw:<16} {text if text else '(unknown)'}")
        i = nxt

disassemble("554889e54883ec1048897df831c04883ff2a7505b8010000004801f0c9c3")
print("--- a call, a syscall and bytes the decoder doesn't know")
disassemble("e8f6ffffff0f05" + "ff25" + "c3")
   0:  55               push rbp
   1:  48 89 e5         mov rbp,rsp
   4:  48 83 ec 10      sub rsp,0x10
   8:  48 89 7d f8      mov QWORD PTR [rbp-0x8],rdi
   c:  31 c0            xor eax,eax
   e:  48 83 ff 2a      cmp rdi,0x2a
  12:  75 05            jne 0x19
  14:  b8 01 00 00 00   mov eax,0x1
  19:  48 01 f0         add rax,rsi
  1c:  c9               leave
  1d:  c3               ret
--- a call, a syscall and bytes the decoder doesn't know
   0:  e8 f6 ff ff ff   call -0x5
   5:  0f 05            syscall
   7:  ff               (unknown)
   8:  25               (unknown)
   9:  c3               ret

The first listing matches objdump instruction for instruction; only the spacing differs. Look at how much of the work is the ModRM byte: 7d = 01 111 101 gives "memory, 8-bit displacement, register 7 (rdi), base 5 (rbp)". In the second listing, e8 f6 ff ff ff is a call with displacement -10 from the end of the instruction (offset 5), so the target is -5: before the start of the buffer, which a real disassembler would flag too. The decoder doesn't know ff 25 (the first two bytes of an indirect jmp through memory, used by PLT stubs), so it reports ff as unknown and resynchronises on the next byte: 25 is unknown on its own too, and then c3 decodes as ret. A real disassembler would read ff 25 as the start of a 6-byte instruction with a 4-byte displacement, swallow the c3 into it, and report the instruction as truncated: the opposite mistake, with the same root cause. That is exactly how a linear-sweep disassembler drifts out of step when it meets data or an opcode it gets wrong; the objdump lesson shows the same effect deliberately.

How this matters for detection

  • Byte signatures: YARA rules and AV signatures match instruction bytes, often with wildcards for the displacement and register bits that change between builds (48 8B 05 ?? ?? ?? ?? = mov rax, [rip+?]). Knowing the encoding lets you write signatures that survive recompilation.
  • Crash dumps and patches: a 5-byte E9 xx xx xx xx jump written over a function's first bytes is the classic inline hook; recognising it in a hex dump is the first step in detecting hooking (legitimate or not).
  • Anti-disassembly relies on decoders' assumptions; understanding them is how analysts spot it.

How mistakes are avoided

  • Test a decoder against a reference (objdump, Capstone, Zydis) on the same bytes, as above; production tools use those libraries rather than hand-written tables.
  • Use well-tested decoding libraries in your own tools (Capstone has Python bindings), and treat a hand-written decoder as a learning tool.

Pitfalls

  • Displacements are relative to the end of the instruction, not its start.
  • REX must come immediately before the opcode; other prefixes (66 operand size, F3 rep, 2E/3E segment and branch hints) come before it.
  • mov eax, imm32 vs mov rax, imm64: with REX.W, B8+r takes an 8-byte immediate; the tiny decoder refuses it rather than mis-decode it.
  • Same mnemonic, many encodings: mov rbp, rsp can be 48 89 e5 or 48 8b ec; assemblers choose, and the choice is a fingerprint of the tool.

Practice

1. Decode 48 89 c7 by hand.

REX.W, opcode 89 (mov r/m, reg), ModRM c7 = 11 000 111: register mode, reg 0 (rax), rm 7 (rdi): mov rdi, rax.

2. Add 0x48 0x8B with mod = 00, rm = 101 (rip-relative) to the test: what does 48 8b 05 10 00 00 00 decode to?

mov rax, QWORD PTR [rip+0x10]: load 8 bytes from 16 bytes after the end of this 7-byte instruction. Run disassemble("488b0510000000") to check.

3. A 75 fa sits at offset 0x20. Where does it jump?

0xfa = -6; the instruction ends at 0x22, so the target is 0x1c, a backward jump (a loop).

Test yourself

What does the W bit of a REX prefix select?

  1. A write to memory
  2. 64-bit operand size
  3. A wide string
  4. The rip-relative mode

In ModRM, what does mod = 11 mean?

  1. Memory with a 32-bit displacement
  2. Both operands are registers
  3. A SIB byte follows
  4. rip-relative addressing

75 05 at offset 0x12: where does jne go?

  1. 0x17
  2. 0x19
  3. 0x05
  4. 0x12

Why can one wrong or unknown byte make a linear disassembler produce garbage for the following bytes?

  1. Because x86 instructions have variable length, so a wrong boundary shifts every instruction after it
  2. Because of the REX prefix
  3. Because objdump is buggy
  4. It can't: x86 instructions are 4 bytes