5. Disassembly: Reading Machine Code Like an Analyst
From raw bytes to readable functions: how disassemblers decode x86-64, the instructions and calling conventions you need to follow Windows and Linux code, and a workflow for finding what matters in a sample
Imagine a telegram that arrives with every space and every punctuation mark stripped out:
THEREDONATEDALLHISMONEY
Start reading at the first letter and you get "there donated all his money". Start one letter late and you get "here donated all his money". Start three letters in and you get "red on a ted all his money": nonsense, but nonsense made entirely of real words. Worse, every one of those readings falls back into step with the real one, so a reader who started in the wrong place gets a few garbled words and then a perfectly sensible ending, with nothing to tell them that the beginning was wrong.
That is exactly the problem a disassembler faces. An x86-64 program is a stream of bytes with no spaces: instructions are anywhere from 1 to 15 bytes long, nothing marks where one ends and the next begins, and the same stream can hold data as well as code. Start decoding at the right byte and you read the program as the CPU will run it. Start at the wrong byte, or wander into a table of data, and you read a plausible-looking program that the CPU will never run.
In the PE and ELF articles we learned to read a program's headers: where the code is, what it imports, what runs first. This article reads the code itself. We'll see how disassemblers turn bytes into instructions and why they sometimes get it wrong, learn just enough x86-64 to follow a real function, hand-decode a few instructions, compare the Windows and Linux calling conventions so you can see which arguments go into each API call, and finish with the workflow analysts actually use to find the ten functions that matter among thousands.
Everything here is synthetic
Every byte of machine code on this page was written for this article: a 58-byte buffer
holding a toy "configuration decoder" that XORs eleven bytes with a key, a few small
functions compiled from C, and individual instructions assembled with GNU
as. None of it is real malware, and none of it does anything harmful. The
"configuration" it decodes is a reserved example domain, shown defanged as
cdn[.]example. The interactive tools decode bytes in your browser and never
execute anything. As always in this series, real samples belong only inside your
lab.
What a Disassembler Does
A CPU doesn't run assembly language. It runs machine code: bytes that encode operations
in a format designed for hardware to decode quickly, not for people to read. An
assembler turns human-written instructions such as mov eax, 60 into bytes (B8 3C 00 00 00). A disassembler goes the other way: it takes bytes and prints the instructions
they encode.
Turning one instruction's bytes back into text is mechanical. The x86 instruction set is documented in exhaustive detail in Intel's and AMD's manuals, and every byte pattern either decodes to exactly one instruction or is invalid. The hard part is the question the telegram raised: where does each instruction start? On x86-64:
- Instructions vary in length, from one byte (
C3,ret) to fifteen. You only learn an instruction's length by decoding it. - Nothing in the file says which bytes are code. The PE and ELF headers mark a section or segment as executable, but an executable region can also hold jump tables, string constants, padding and alignment bytes, or deliberately planted junk.
- Almost every byte value starts some valid instruction. Data decoded as code rarely looks obviously broken. It looks like slightly odd code.
A disassembler therefore has to decide which bytes are instructions, and different tools decide in different ways. The two classic strategies are worth understanding properly, because they explain most of the confusing things you'll see in a disassembler's output. First, though, we need enough of the language to read that output at all.
Just Enough x86-64
x86-64 (also called AMD64 or x64) is the 64-bit extension of Intel's 1978 8086 architecture, designed by AMD and shipped in 2003. It carries nearly fifty years of history, and the full instruction set fills thousands of pages of manuals. You don't need most of it. A couple of dozen instructions cover the large majority of compiler-generated code, and that is what this section teaches.
Registers
A register is a small storage slot inside the CPU. x86-64 has sixteen general-purpose 64-bit registers, plus the instruction pointer and a flags register:
| 64-bit | 32 / 8-bit | Usual job |
|---|---|---|
rax |
eax / al |
Return value; scratch |
rbx |
ebx / bl |
Preserved across calls |
rcx |
ecx / cl |
Argument 1 (Win), 4 (Linux) |
rdx |
edx / dl |
Argument 2 (Win), 3 (Linux) |
rsi |
esi / sil |
Argument 2 (Linux) |
rdi |
edi / dil |
Argument 1 (Linux) |
rbp |
ebp / bpl |
Frame pointer, or preserved |
rsp |
esp / spl |
Stack pointer |
r8–r15 |
r8d / r8b … |
r8, r9: arguments |
rip |
Instruction pointer | |
rflags |
Condition flags |
The narrower names are views of the same register: eax is the low 32 bits of rax, and al
its lowest byte. There are 16-bit names too (ax, cx, and so on, up to r15w), but you'll
rarely meet them in 64-bit code. rip always holds the address of the next instruction, and
rflags the condition flags set by arithmetic and comparisons. One rule
trips everyone up at first: writing a 32-bit register clears the top 32 bits of the
64-bit register, but writing a 16-bit or 8-bit one leaves the rest alone. That's why
compilers write xor eax, eax (2 bytes) to set all of rax to zero, and why you'll see the
odd-looking mov edi, edi, which does nothing to the low half but zeroes the high half.
The flags you'll care about are the zero flag (ZF, the result was zero), the sign flag (SF, the result was negative), the carry flag (CF, an unsigned overflow or borrow) and the overflow flag (OF, a signed overflow). You almost never read them directly; conditional jumps read them for you.
Syntax: Intel and AT&T
There are two ways of writing the same instructions, and you'll meet both. Intel syntax,
used by Intel's manuals, IDA, Ghidra, Binary Ninja and x64dbg, puts the destination first.
AT&T syntax, the default for GNU tools such as objdump and gdb, puts it last, prefixes
registers with % and constants with $, and writes memory operands differently:
Intel syntax (objdump -M intel)
push rbp
mov rbp,rsp
xor eax,eax
jmp 33
xor BYTE PTR [rdi+rax*1],dl
inc rax
cmp rax,rsi
jb 2d
AT&T syntax (objdump default)
push %rbp
mov %rsp,%rbp
xor %eax,%eax
jmp 33
xor %dl,(%rdi,%rax,1)
inc %rax
cmp %rsi,%rax
jb 2d
This article uses Intel syntax throughout. If a tool shows you AT&T, either switch it
(objdump -M intel, set disassembly-flavor intel in gdb) or remember to read operands
right to left.
Memory operands
Square brackets mean "the memory at this address". Inside them, x86-64 can combine up to four parts:
[ base + index * scale + displacement ]
[rbp-0x8] a local variable: base rbp, displacement -8
[rdi+rax*1] buf[i] for a byte array: base rdi, index rax, scale 1
[rdx+rax*4] table[i] for 4-byte entries
[rip+0x12] RIP-relative: 0x12 bytes past the next instruction
The scale can be 1, 2, 4 or 8, which is exactly the set of sizes of C's basic types: that's
how array indexing is so cheap. When the size of the memory being touched isn't clear from a
register, the disassembler adds it: BYTE PTR (1), WORD PTR (2), DWORD PTR (4),
QWORD PTR (8).
The last form, RIP-relative addressing, is new in 64-bit mode and is everywhere. Instead
of hard-coding the absolute address of a global variable or a string, the instruction stores
its distance from the next instruction. The code then works wherever the program is loaded,
which is what position-independent executables and ASLR need. Disassemblers do the
arithmetic for you and print the target in a comment, as in lea rdi,[rip+0x12] # 0x19.
The instructions you'll actually see
| Instruction | What it does | How an analyst reads it |
|---|---|---|
mov dst, src |
Copy | Assignment, e.g. reading a local |
movzx / movsx / movsxd |
Copy and widen, with zeros or with the sign | A char, short or int being widened |
lea dst, [addr] |
Compute the address, don't read memory | Taking an address (&buf), or quick arithmetic such as x * 3 (see below) |
add, sub, inc, dec, imul |
Arithmetic | Counters, sizes, pointer steps |
and, or, xor, not, shl, shr, sar, rol, ror |
Bitwise | Flags and masks; xor with anything but itself in a loop is a cipher hint |
cmp a, b |
Compute a - b, set flags, discard the result |
The if before a conditional jump |
test a, b |
Compute a & b, set flags, discard the result |
test eax, eax: "is it zero?" |
jmp target |
Go to target | goto, the end of an if branch, a loop |
jcc target |
Go to target if a condition holds | if, while, for |
call target |
Push the return address, go to target | A function call |
ret |
Pop an address and go there | Function return |
push / pop |
Store to / load from the top of the stack | Saving registers in prologues and epilogues |
nop |
Nothing | Padding between functions |
syscall |
Enter the kernel | A Linux system call (and Windows' own ntdll stubs) |
int3 |
Breakpoint trap | Padding on Windows (CC CC CC), or a debugger's breakpoint |
Conditions: cmp, test and the conditional jumps
A comparison and the jump after it always travel together. cmp rax, rsi sets the flags as
if it had computed rax - rsi; the next instruction picks a condition. The same comparison
can mean different things depending on whether the values are signed or unsigned,
and the jump tells you which the programmer used:
| Jump | Opcode (short) | Jumps if | After cmp a, b means |
|---|---|---|---|
je / jz |
74 |
ZF = 1 | a == b |
jne / jnz |
75 |
ZF = 0 | a != b |
jb / jc |
72 |
CF = 1 | a < b, unsigned |
jae / jnc |
73 |
CF = 0 | a >= b, unsigned |
jbe |
76 |
CF = 1 or ZF = 1 | a <= b, unsigned |
ja |
77 |
CF = 0 and ZF = 0 | a > b, unsigned |
jl |
7C |
SF ≠ OF | a < b, signed |
jge |
7D |
SF = OF | a >= b, signed |
jle |
7E |
ZF = 1 or SF ≠ OF | a <= b, signed |
jg |
7F |
ZF = 0 and SF = OF | a > b, signed |
js / jns |
78 / 79 |
SF = 1 / 0 | Result negative / not negative |
"Below" and "above" are the unsigned words; "less" and "greater" the signed ones. That small
detail recovers type information the compiler threw away: a loop that ends with jb is
counting with an unsigned type such as size_t.
Instruction Encoding: Taking Bytes Apart
You will rarely decode instructions by hand. But doing it a few times explains why
disassemblers desynchronise, why one wrong byte changes everything after it, and what those
48 and 41 bytes are that start so many instructions. Every x86-64 instruction follows the
same template:
- Legacy prefixes modify the instruction:
66switches to 16-bit operands,F2/F3are repeat prefixes for string instructions (and select some SSE instructions),F0islock,64/65select thefs/gssegments. Most instructions have none. - REX (
40to4F) is the 64-bit mode prefix. Its bits are0100WRXB:Wselects 64-bit operands, andR,XandBeach supply a fourth bit to a register number, which is howr8tor15are reached. That's why so many instructions start with48(Wset) or4C,41,44,49. - The opcode says which operation, and implies which of the remaining fields follow.
One-byte opcodes are the common case;
0Fstarts two-byte opcodes such as0F 05(syscall) and the long conditional jumps0F 80to0F 8F. - ModRM names the operands:
modsays register or memory (and how big the displacement is),regis a register (or, for some opcodes, an extension of the opcode itself, written/0to/7in Intel's tables),rmis the other register or the base of a memory address. - SIB (scale-index-base) follows whenever ModRM describes memory (
modis not11) andrmis100. That covers addresses with an index, and also addresses based onrsporr12with no index at all, which is why[rsp+0x20]always carries an SIB byte. - Displacement and immediate carry the constant offset and the constant value, in little-endian order.
Worked example 1: mov rax, [rbp-0x8]
Decoding 48 8B 45 F8
48is in40to4F, so it's a REX prefix:0100 1000.W = 1(64-bit operands);R,X,Bare 0.8Bis the opcodeMOV r, r/m: copy from the ModRM'srmoperand into itsregoperand. It takes a ModRM byte.45is the ModRM byte:01 000 101.mod = 01: memory, with a 1-byte displacement.reg = 000(plusR = 0): register 0, which at 64 bits israx.rm = 101(plusB = 0): register 5,rbp.F8is the 1-byte displacement, signed:0xF8is −8.- Result:
mov rax, QWORD PTR [rbp-0x8], four bytes. In a function with a frame pointer, that's "load the 8-byte local variable atrbp-8".
Worked example 2: xor [rcx+rax*1], r8b
Decoding 44 30 04 01
44: REX0100 0100.W = 0,R = 1: add 8 to the ModRMregnumber.30:XOR r/m8, r8, a byte-sized XOR into thermoperand.04: ModRM00 000 100.mod = 00: memory, no displacement.reg = 000plusRgives 8:r8, and at byte sizer8b.rm = 100: an SIB byte follows.01: SIB00 000 001.scale = 00: ×1.index = 000:rax.base = 001:rcx.- Result:
xor BYTE PTR [rcx+rax*1], r8b. Without the44, the same three bytes30 04 01would meanxor [rcx+rax*1], al: one prefix bit changes which register is used.
Worked example 3: RIP-relative, and how jumps find their targets
Decoding 48 8D 3D 12 00 00 00 at address 0x00
48: REX.W.8D:LEA r, m.3D: ModRM00 111 101.reg = 111:rdi.mod = 00withrm = 101is the special case that means RIP-relative in 64-bit mode: a 4-byte displacement follows, measured from the end of this instruction.12 00 00 00: displacement0x12. The instruction is 7 bytes long and starts at0x00, so the next instruction is at0x07, and the target is0x07 + 0x12 = 0x19.- Result:
lea rdi, [rip+0x12], which loads the address0x19intordi.
Relative calls and jumps work the same way. E8 (call) and E9 (jmp) take a 4-byte
signed displacement; EB (short jmp) and 70 to 7F (short conditional jumps) take a
1-byte one.
For an instruction at address that is bytes long, with signed displacement :
So E8 0F 00 00 00 at 0x11 calls 0x11 + 5 + 0x0F = 0x25, and 72 F5 at 0x36 jumps to
0x36 + 2 − 11 = 0x2D, backwards, because F5 is −11. A backwards jump is your first clue
that you're looking at a loop.
The decoder below handles a well-defined subset of x86-64, the instructions in this article, and shows every field of every instruction. Paste bytes from any listing on this page, or try the presets.
x86-64 Instruction Decoder
Type or paste machine code as hex (spaces, commas, 0x and \x
prefixes are all fine), set the address of the first byte, and decode. Each instruction is
shown in Intel syntax with its bytes coloured by field: prefixes, REX (with its W, R, X and
B bits), opcode, ModRM (mod, reg, rm), SIB (scale, index, base), displacement and
immediate. Jump, call and RIP-relative targets are computed for you. The decoder knows a
deliberately small subset of x86-64: anything outside it is flagged, never guessed at.
The output text matches objdump -M intel for everything it accepts. Nothing
you enter is executed.
Hex, for example 48 8B 45 F8, 0x48,0x8b or \x48\x8b. Ctrl+Enter decodes.
Or start from a preset:
| Address | Bytes | Instruction | Target / note |
|---|
Click a row, or focus it and press Enter, to show or hide its field breakdown.
Two Ways to Find the Instructions
Back to the telegram. Given a region of bytes, how does a disassembler decide where the instructions start? There are two classic answers, analysed side by side by Benjamin Schwarz, Saumya Debray and Gregory Andrews in their 2002 paper Disassembly of Executable Code Revisited.
Linear sweep
Linear sweep starts at the beginning of the code section and decodes one instruction after another, each starting where the previous one ended, until it reaches the end:
linear_sweep(bytes, start, end):
addr = start
while addr < end:
insn = decode(bytes, addr)
if insn is invalid:
print "(bad)" for one byte
addr = addr + 1
else:
print insn
addr = addr + insn.length
It's simple, fast, and covers every byte. GNU objdump -d works this way, which is why its
output is so predictable. The weakness is that it assumes every byte in the region is an
instruction. When it meets data, it decodes the data as instructions, and when the data ends
it is very likely to be out of step: the last "instruction" it decoded from data runs on
into the real code, and it starts reading the real code from the middle of an instruction.
Like the telegram, x86 tends to fall back into step after a few instructions, which makes
the error easy to miss.
Recursive descent
Recursive descent (also called recursive traversal) follows the program's control flow instead of its byte order. It starts from known entry points and decodes along the paths execution can take:
recursive_descent(bytes, entry_points):
worklist = entry_points
seen = {}
while worklist is not empty:
addr = worklist.pop()
while addr is in the code and addr not in seen:
insn = decode(bytes, addr)
seen[addr] = insn
for each address insn can transfer control to: # jump and call targets
worklist.push(that address)
if insn is ret, jmp or an indirect jump:
break # no fall-through
addr = addr + insn.length
Entry points come from the headers: the PE AddressOfEntryPoint or ELF e_entry, exports,
symbols, TLS callbacks and ELF constructors (the code-before-the-entry-point we met in both
format articles). On 64-bit Windows there's a bonus: the exception directory (.pdata)
lists the start and end of nearly every function that isn't a simple leaf, for stack unwinding, and
disassemblers use it as a ready-made list of function starts. On Linux, .eh_frame plays a
similar role.
Recursive descent never decodes bytes that nothing jumps to, so it steps around data in the
middle of code. Its weakness is the opposite one: it only finds code it can prove is
reachable, and it can't see where an indirect jump (jmp rax) or an indirect call
(call [rbx+0x10]) goes without extra analysis. Real tools (IDA, Ghidra, Binary Ninja,
radare2's analysis) are recursive descent plus a large set of heuristics: recognising jump
tables, scanning the gaps for things that look like function prologues, matching known
library code.
Watching linear sweep fall out of step
Here is the synthetic 58-byte buffer this article is built around. It holds a tiny main
that calls decode_config, with twelve bytes of data in between: an encoded configuration
string and a zero byte of padding.
00000000 48 8D 3D 12 00 00 00 BE 0B 00 00 00 BA 5A 00 00 H.=..........Z..
00000010 00 E8 0F 00 00 00 31 C0 C3 39 3E 34 74 3F 22 3B ......1..9>4t?";
00000020 37 2A 36 3F 00 55 48 89 E5 31 C0 EB 06 30 14 07 7*6?.UH..1...0..
00000030 48 FF C0 48 39 F0 72 F5 5D C3 H..H9.r.].
Strip away the symbols and give the raw bytes to objdump, which can only sweep:
$ objdump -D -b binary -m i386:x86-64 -M intel sample.bin
0: 48 8d 3d 12 00 00 00 lea rdi,[rip+0x12] # 0x19
7: be 0b 00 00 00 mov esi,0xb
c: ba 5a 00 00 00 mov edx,0x5a
11: e8 0f 00 00 00 call 0x25
16: 31 c0 xor eax,eax
18: c3 ret
19: 39 3e cmp DWORD PTR [rsi],edi
1b: 34 74 xor al,0x74
1d: 3f (bad)
1e: 22 3b and bh,BYTE PTR [rbx]
20: 37 (bad)
21: 2a 36 sub dh,BYTE PTR [rsi]
23: 3f (bad)
24: 00 55 48 add BYTE PTR [rbp+0x48],dl
27: 89 e5 mov ebp,esp
29: 31 c0 xor eax,eax
2b: eb 06 jmp 0x33
2d: 30 14 07 xor BYTE PTR [rdi+rax*1],dl
30: 48 ff c0 inc rax
33: 48 39 f0 cmp rax,rsi
36: 72 f5 jb 0x2d
38: 5d pop rbp
39: c3 ret
Everything from 0x19 to 0x28 is wrong. The data decodes as a comparison, an XOR, some
logic, and three (bad) bytes (3F and 37 were one-byte BCD instructions in 32-bit x86
and are invalid in 64-bit mode). Then the zero byte at 0x24 does real damage: 00 is
add r/m8, r8, which needs a ModRM byte, so the decoder takes the next byte, 55, as ModRM
(01 010 101: memory at rbp plus a 1-byte displacement), and the byte after that, 48,
as the displacement. In three bytes it has swallowed decode_config's first instruction
(push rbp) and the REX prefix of its second, which turns mov rbp, rsp into
mov ebp, esp. From 0x29 it's back in step, and the rest of the function is correct.
Recursive descent, given only the entry point 0x00, never has this problem. It decodes
main, sees call 0x25 and queues 0x25, stops at ret, then decodes decode_config from
its true start. Nothing ever transfers control to 0x19, so it is never decoded as code; and
since the lea at 0x00 computes its address, a good tool labels it as data that the code
refers to.
Why real samples make this worse
Compilers mix data into code more often than you might expect: MSVC keeps switch jump
tables in .text, alongside the code, by default on x64 (Microsoft added the /jumptablerdata
option in Visual Studio 2022 17.7 to move them to .rdata), hand-written assembly embeds
constants, and alignment padding sits between functions. Malware authors who want to slow
analysts down go further, with anti-disassembly tricks aimed at each strategy:
- Junk bytes after an unconditional jump.
EB 01jumps over one byte. If that byte isE8, the opcode ofcall rel32, linear sweep decodes acallthat swallows the next four bytes of real code. Recursive descent follows the jump and is unaffected. - Opaque predicates. A conditional jump whose condition is always true (say,
xor eax, eaxfollowed byjz) looks to a disassembler like it has two possible successors, so recursive descent dutifully decodes the never-taken one too, which leads into junk. - Overlapping instructions. A jump into the middle of an instruction, so that the same bytes are executed as two different instruction sequences. Both strategies can show only one reading of those bytes at a time.
- Computed jumps.
jmp raxwithraxcalculated at run time hides the target from recursive descent entirely, and the code behind it looks unreachable.
You don't need to master these now (the obfuscation article later in the series does), but
you should recognise the symptoms: (bad) bytes, calls to absurd addresses, instructions
that touch registers in ways no compiler would, or a function that "starts" in the middle of
another one. When you see them, assume the disassembler has lost its place before assuming
the code is bizarre. Every good tool lets you tell it "this is code" or "this is data" at a
given address and re-analyse.
The visualizer below runs both strategies side by side, one step at a time, over this
article's 58-byte buffer and two more synthetic samples: a switch with its jump table in the
middle of the code, and a junk byte after a jump.
Disassembly Sweep Visualizer
Choose a sample, then step both disassemblers forward together, one instruction each per step. The byte strip is shared: the top band of each byte shows what linear sweep made of it and the bottom band what recursive descent made of it (code, data, or not yet reached), and the two listings show the instructions found so far. Bytes where the two disagree are tinted red, and the point where linear sweep falls back into step is marked. For the jump-table sample, turn jump-table recognition off to see what plain recursive descent misses. Both strategies use the same decoder as the tool above. All three samples are small synthetic buffers written for this article; nothing is executed.
The Stack and the Function Frame
Before we can read function calls, we need the stack: a region of memory that every
thread uses for return addresses, saved registers, local variables and, sometimes,
arguments. On x86 it grows downwards. rsp points at the most recently pushed value:
push rbxsubtracts 8 fromrspand storesrbxat[rsp].pop rbxloads[rsp]intorbxand adds 8.call targetpushes the address of the next instruction (the return address) and jumps totarget.retpops the return address and jumps to it.
A function usually begins with a prologue that sets up its frame (its slice of the
stack) and ends with an epilogue that tears it down. The classic shape, with rbp as a
frame pointer:
push rbp ; save the caller's rbp
mov rbp, rsp ; rbp = this frame's base
sub rsp, 0x20 ; reserve 32 bytes for locals
... ; locals are at [rbp-0x8], [rbp-0x10], ...
leave ; = mov rsp, rbp; pop rbp
ret
With a frame pointer, locals sit at fixed negative offsets from rbp for the whole function,
which makes them easy to name: rename [rbp-0x8] to count once and the disassembler
renames it everywhere. Optimised code often omits the frame pointer: GCC and Clang do so
by default when optimising on x86-64, so locals are addressed from rsp instead ([rsp+0x28]),
and the offsets shift whenever rsp moves. (Some Linux distributions, Fedora and Ubuntu
among them, have recently started building their own packages with frame pointers to help
profilers, so you will see both.) MSVC on x64 rarely uses a frame pointer at all; a typical prologue there is
just sub rsp, 0x28 and a few mov [rsp+...], reg to save registers. Disassemblers track
rsp through the function and name stack slots either way, which is why IDA shows var_8
and Ghidra local_10 rather than raw offsets.
The prologue also tells you how many registers the function needs to preserve and roughly
how big its locals are. A sub rsp, 0x1010 in a small function suggests a 4 KB buffer on the
stack: a path, a received packet, or a decoded blob.
Calling Conventions: Windows and Linux Side by Side
When one function calls another, both must agree where the arguments go, where the result comes back, and which registers the callee is allowed to destroy. That agreement is the calling convention, part of the platform's ABI. x86-64 has two in common use, and they differ in ways that matter every time you read a call:
- Microsoft x64, used by every 64-bit Windows program and DLL.
- System V AMD64, from the same System V ABI family as ELF, used by Linux, the BSDs and macOS.
| Microsoft x64 (Windows) | System V AMD64 (Linux) | |
|---|---|---|
| Integer and pointer arguments | rcx, rdx, r8, r9 |
rdi, rsi, rdx, rcx, r8, r9 |
| Floating-point arguments | xmm0 to xmm3, sharing the four positions with the integers |
xmm0 to xmm7, counted separately |
| Further arguments | On the stack, from [rsp+0x20] at the call |
On the stack, from [rsp] at the call |
| Return value | rax (or xmm0) |
rax (or xmm0; rdx:rax for 128-bit values) |
| Caller always reserves | 32 bytes of shadow space above the return address | Nothing |
Below rsp |
Off limits | 128-byte red zone a function may use freely |
| Callee must preserve | rbx, rbp, rdi, rsi, rsp, r12 to r15, xmm6 to xmm15 |
rbx, rbp, rsp, r12 to r15 |
| Callee may destroy | rax, rcx, rdx, r8 to r11, xmm0 to xmm5 |
rax, rcx, rdx, rsi, rdi, r8 to r11, all xmm |
| Stack alignment | 16 bytes at each call |
16 bytes at each call |
The shadow space (Microsoft also calls it the home space) is 32 bytes that the caller
reserves on the stack, even when the callee takes fewer than four arguments, so the callee can
spill rcx, rdx, r8 and r9 into it if it wants. That's why Windows functions that call
anything start with sub rsp, 0x28 or larger: 32 bytes of shadow space plus 8 to restore 16-byte
alignment after the return address. The red zone is Linux's opposite convenience: a
function that calls nothing can keep up to 128 bytes of locals below rsp without
adjusting rsp at all, because the ABI promises nothing asynchronous will overwrite them.
Note also which registers differ in their job. rsi and rdi carry arguments on Linux but
must be preserved on Windows; rcx is the first argument on Windows and the fourth on Linux.
If you misidentify the convention, a decompiler will happily show you the wrong arguments, so
check it whenever you look at code from a binary you haven't identified with certainty.
Reading arguments at a call site
The payoff: at any call, the arguments are just the registers (and stack slots) set up in
the instructions before it. Compilers interleave them with other work and don't load them in
order, so read backwards from the call and look for the last write to each argument
register.
Here's a Windows function that writes a message to a file handle, assembled for this article
at PE-style addresses with a real call through an IAT slot (FF 15 is call QWORD PTR [rip+disp32]):
140001000: 48 83 ec 38 sub rsp,0x38
140001004: 4c 8d 4c 24 30 lea r9,[rsp+0x30]
140001009: 48 c7 44 24 20 00 00 00 mov QWORD PTR [rsp+0x20],0x0
00
140001012: 41 b8 0b 00 00 00 mov r8d,0xb
140001018: 48 8d 15 e1 0f 00 00 lea rdx,[rip+0xfe1] # 0x140002000
14000101f: ff 15 5b 10 00 00 call QWORD PTR [rip+0x105b] # 0x140002080
140001025: 48 83 c4 38 add rsp,0x38
140001029: c3 ret
If 0x140002080 is the IAT slot for KERNEL32!WriteFile (as the PE article
showed, a disassembler reads the import table and names every slot), the call reads like a
sentence. WriteFile takes five arguments:
-
hFile in rcx
Nothing here writes
rcx. So the handle is whatever arrived inrcx: this function's own first argument, passed straight through. Rename the function's parameter tohFile. -
lpBuffer in rdx
lea rdx, [rip+0xfe1]: the address0x140002000, in the data. Jump there and you'll find the bytes being written. -
nNumberOfBytesToWrite in r8
mov r8d, 0xb: 11 bytes. (Writingr8dclears the top ofr8, as always.) -
lpNumberOfBytesWritten in r9
lea r9, [rsp+0x30]: the address of a local variable, whichWriteFilewill fill in. -
lpOverlapped on the stack
The fifth argument goes just above the shadow space:
[rsp+0x20], set to 0 (NULL). Thesub rsp, 0x38reserved 32 bytes of shadow space, 8 for this argument, 8 for the local, and 8 to keeprsp16-byte aligned.
The same job on Linux, from a small C program compiled with GCC and linked as a normal dynamic executable:
0000000000001139 <main>:
1139: 55 push rbp
113a: 48 89 e5 mov rbp,rsp
113d: ba 0b 00 00 00 mov edx,0xb
1142: 48 8d 35 bf 0e 00 00 lea rsi,[rip+0xebf] # 2008 <msg>
1149: bf 01 00 00 00 mov edi,0x1
114e: e8 dd fe ff ff call 1030 <write@plt>
1153: b8 00 00 00 00 mov eax,0x0
1158: 5d pop rbp
1159: c3 ret
write(fd, buf, count): rdi = 1 (standard output), rsi = the message at 0x2008,
rdx = 11. The call goes to write@plt, the trampoline we dissected in the
ELF article. Follow it and you find a single
jmp QWORD PTR [rip+0x2fca] through the GOT slot for write; objdump names the stub from
the .rela.plt relocations, which is exactly why @plt names survive stripping.
System calls
Linux programs can skip the C library and ask the kernel directly with the syscall
instruction. The convention is close to System V's, with one swap: the number goes in rax,
arguments in rdi, rsi, rdx, r10 (not rcx, because syscall itself overwrites
rcx and r11), r8 and r9, and the result comes back in rax. The numbers are fixed per
architecture; a few you'll meet on x86-64:
rax |
Call |
|---|---|
| 0 | read |
| 1 | write |
| 2 | open |
| 3 | close |
| 9 | mmap |
| 10 | mprotect |
| 41 | socket |
| 42 | connect |
| 59 | execve |
| 60 | exit |
| 62 | kill |
| 101 | ptrace |
| 231 | exit_group |
| 257 | openat |
The ELF article's synthetic program ended with mov eax, 60; syscall: exit. Statically linked and hand-written Linux malware often makes system calls
directly, and in a stripped static binary the syscall sites and their rax values may be
the most reliable labels you have. A raw mmap or mprotect asking for memory that is
writable and executable, followed shortly by a jump into it, is the shape of an unpacker.
Windows works differently. Its system call numbers change between Windows builds, so programs
never use them directly: they call documented APIs in DLLs such as kernel32.dll, which call
ntdll.dll, whose tiny stubs (in essence mov r10, rcx; mov eax, <number>; syscall) are, along with
win32u.dll's equivalent stubs for graphics and windowing calls, the normal place a syscall
instruction appears in user mode. A Windows sample that contains its
own syscall instructions is going around ntdll, usually to avoid the hooks security
products place there, and that alone is worth a line in your notes.
Control Flow: Blocks, Graphs and Idioms
Reading a function line by line works for ten instructions. For a hundred, you need its
shape. Disassemblers split every function into basic blocks: runs of instructions with
one way in (the first instruction) and one way out (the last). A block ends at any jump,
ret or conditional branch, and a new block starts at any instruction something jumps to.
Connect the blocks with their possible transfers and you have a control-flow graph (CFG),
the view IDA, Ghidra, Binary Ninja and Cutter show when you press space or open the graph
window.
Here's decode_config, this article's toy decoder, as four blocks:
Most of what a compiler emits is built from three or four shapes, and once you can spot them in the graph you can read a function's logic before reading its instructions.
if and if/else
A cmp or test, then a conditional jump around the code that should only run in one
case. Compilers usually invert the condition, which takes a moment to get used to: if (n == 0) { A } B becomes "test n; jump to B if not zero; A; B". In the graph it's a diamond, or a
triangle when there's no else.
test eax,eax
jne skip ; if (eax == 0) {
... ; the "then" block
skip: ; }
Loops
A loop is a back edge: a jump to a lower address that leads back to code already seen.
decode_config has the shape GCC emits for loops at -O0: jump forward to the
condition first, put the body above it, and loop back while the condition holds. Other
compilers test at the top and jump back from the bottom; either way, find the back edge, the
condition that leaves the loop, and the register that changes on every trip round (here
rax, incremented by inc rax). In decode_config that's enough to write it in C: for each
i from 0 while i < len (unsigned, from jb), XOR byte buf[i] with the low byte of the
third argument.
switch and jump tables
A switch with many dense cases compiles into a jump table: an array of targets indexed
by the case value. Here's one from GCC, compiled for this article (five cases, 0 to 4, and
a default):
0000000000001140 <handle>:
1140: 83 ff 04 cmp edi,0x4
1143: 77 4f ja 1194 ; default if cmd > 4 (unsigned)
1145: 48 8d 05 b8 0e 00 00 lea rax,[rip+0xeb8] ; table at 0x2004 in .rodata
114c: 89 ff mov edi,edi ; zero-extend the index
114e: 48 63 14 b8 movsxd rdx,DWORD PTR [rax+rdi*4]
1152: 48 01 c2 add rdx,rax ; target = table + entry
1155: ff e2 jmp rdx
$ objdump -s -j .rodata handle-demo
2000 01000200 7cf1ffff 84f1ffff 8cf1ffff ....|...........
2010 5cf1ffff 6cf1ffff \...l...
Every part of the idiom is there: a bounds check (cmp and an unsigned ja to the
default, which also catches negative numbers, since they look huge when treated as unsigned),
the table's address, an indexed load, and an indirect jump. The entries are 4-byte
signed offsets from the table itself: 0xFFFFF17C is −0xE84, and 0x2004 − 0xE84 = 0x1180,
case 0. Working out all five gives 0x1180, 0x1188, 0x1190, 0x1160 and 0x1170. This
is the pattern disassemblers recognise to resolve jmp rdx; when they fail (an unusual
compiler, an obfuscator, a table in an odd place), the cases look like unreachable code
until you resolve the table by hand and tell the tool. MSVC's version on Windows looks
slightly different: its table entries are typically 32-bit offsets from the image base (RVAs)
rather than from the table.
A large switch on a value received from the network or read from a file is one of the most
important shapes in malware: it's often the command dispatcher of a backdoor, with one case
per command the operator can send. Each case's code tells you one capability.
Other idioms worth knowing
- Tail calls. A function that ends with
jmp other_functioninstead ofcallandretis handing over its frame: the callee returns straight to the original caller. - Strength reduction. Compilers replace slow operations with fast ones:
lea eax, [rsi+rsi*2]forx * 3, shifts for powers of two, and multiplication by a large "magic" constant followed by a shift for division by a constant. If you seeimulormulby something like0xCCCCCCCD, it's almost always a division (that one is by 10, or by 5, depending on the shift). - Inlined library functions.
rep movsbandrep stosbarememcpyandmemset; a short loop comparing bytes until one is zero isstrlenorstrcmp. - Stack strings. A run of
mov BYTE PTR [rsp+...], imm8ormov DWORD PTR [rsp+...], imm32building text one piece at a time is a string kept out of thestringsoutput on purpose. Decode the immediates in order and you have it.
Cross-References, Imports and Strings
The most useful feature of any disassembler isn't the listing. It's the cross-reference (xref): for any address, the list of every instruction that refers to it. For a function, xrefs are its callers. For a string, they're the code that uses it. For an import, they're every place the program calls that API. Cross-references turn a flat listing into a web you can walk in both directions, and they're how analysts find their way around without reading everything.
Imports name the calls
On Windows, every call to an imported function goes through the program's import address
table (call QWORD PTR [rip+...], or a jmp thunk to the same thing), and disassemblers name
each IAT slot from the import directory, so you see call cs:WriteFile (IDA) or
CALL qword ptr [->KERNEL32.DLL::WriteFile] (Ghidra) rather than an address. On Linux,
calls go through the PLT and get @plt names from the relocations. Either way, imports
are the landmarks: the one kind of name a stripped, unpacked program can't easily hide.
That's also why triage and the PE
article spent so long on the import table. Each capability family in the PE article's table
becomes a question you can answer in the disassembler: where is connect called, and with
what address? Which function calls RegSetValueExW, and what is the value's name?
Strings name the purpose
A string such as a registry path, a URL path, a user agent, a file name or an error message
says what nearby code is for. Most disassemblers have a strings window (IDA: Shift+F12;
Ghidra: Search → For Strings, or the Defined Strings window; radare2: iz), and every
string's xrefs lead to the code that uses it. Strings that have no references are
interesting too: they may be decoded or found at run time, or be leftovers.
Renaming is the analysis
Disassemblers name everything they don't know generically: sub_140001000 or FUN_00101139
for functions, var_8 or local_10 for locals, dword_140003010 or DAT_00104010 for
globals. As you understand a piece of code, rename it: decode_config, key, c2_port.
Add a comment. Fix a type (tell the tool a parameter is a char * or a structure you've
defined). Every name you choose immediately appears at every reference, so understanding
compounds: the next function you open, which calls decode_config on something and then
connects to the result, mostly reads itself. A well-annotated database is the real product
of static analysis; the report is written from it.
Decompilers, and Where They Go Wrong
A decompiler goes one step further than a disassembler: it turns the instructions into
C-like pseudocode. Ghidra, IDA (with the Hex-Rays decompiler), Binary Ninja, and radare2 and
Rizin through plugins that embed Ghidra's decompiler, all have one. Internally they lift
instructions into an intermediate language, track how values flow between registers and
memory, recover variables and types, apply the calling convention to find arguments, and
rebuild if, while and switch from the CFG. For our toy, the result typically looks like
this (Ghidra-style output; exact names and types vary between tools and versions):
As the decompiler first shows it
void FUN_00000025(long param_1,
ulong param_2,
byte param_3)
{
ulong uVar1;
for (uVar1 = 0; uVar1 < param_2;
uVar1 = uVar1 + 1) {
*(byte *)(param_1 + uVar1) =
*(byte *)(param_1 + uVar1)
^ param_3;
}
return;
}
After the analyst renames and retypes
void decode_config(uint8_t *buf,
size_t len,
uint8_t key)
{
size_t i;
for (i = 0; i < len; i = i + 1) {
buf[i] = buf[i] ^ key;
}
return;
}
That is a huge time-saver, and for clean compiled code it's usually right. But a decompiler's output is a hypothesis, built on every assumption below it, and it can be wrong in ways that look completely convincing:
- Wrong disassembly in, wrong pseudocode out. If the disassembler lost its place, the decompiler faithfully decompiles the junk.
- Wrong calling convention, wrong arguments. Hand-written code, obfuscated code, and functions the tool assigned the wrong convention to come out with missing, extra or shuffled parameters.
- Types are guesses. Structures appear as raw offsets (
*(int *)(param_1 + 0x18)) until you define them. Achartreated as signed or unsigned changes comparisons. - Indirect calls are opaque.
(*(code *)puVar3)(...), a call through a pointer computed at run time, is where API hashing and dynamically resolved imports hide. - Obfuscation is aimed at decompilers. Control-flow flattening turns a function into one
giant
switchin a loop; opaque predicates add branches that never run; junk arithmetic bloats every expression. - Optimisation reshapes code. Inlined functions, merged branches, reused registers and stack slots make one source variable look like several, or several like one.
The habit to build: read the pseudocode to get the gist, and drop into the disassembly whenever something matters, such as a constant you'll put in a detection rule, a decryption loop, a comparison that gates behaviour, or anything that looks slightly off.
The Tools
All of these do the same core job; they differ in price, licence, platform, scripting and how much they'll do automatically. Use whichever your lab has, and learn one well.
- Ghidra. The NSA's reverse-engineering suite, released as open source (Apache 2.0) in 2019. Disassembler, decompiler, CFG view, scripting in Java and Python, many architectures, and project sharing for teams. Runs entirely locally, which makes it a natural fit for an isolated lab. Included in FLARE-VM and REMnux.
- IDA Free. The free, non-commercial edition of Hex-Rays' IDA, the long-time industry standard. Current versions include x86 and x64 analysis, a local debugger, and a cloud-based x86/x64 decompiler; scripting and many processors are reserved for paid editions. Included in FLARE-VM.
- Binary Ninja. A commercial tool from Vector 35 with a strong intermediate-language design and API. Its Free edition (non-commercial) runs locally with a decompiler for x86, x86-64 and ARM, but without the plugin API; Binary Ninja Cloud runs in the browser and requires uploading the file.
- radare2 and Rizin. Open-source, command-line-first frameworks for disassembly, analysis, debugging and patching. Rizin is a 2020 fork of radare2; Cutter is a graphical front end built on Rizin, and iaito one for radare2. Both have a plugin that embeds Ghidra's decompiler. radare2 and Cutter are on REMnux.
- objdump. Part of GNU binutils, on every Linux machine with a compiler. Linear sweep
only, no cross-references or naming beyond symbols and
@plt, and it needs section headers (as the ELF article showed, it prints nothing for a file without them unless you treat it as raw bytes). Ideal for a quick look at a known function, and for scripting.
Lab note: cloud features and isolated VMs
Your analysis VMs have no route to the internet (that was the point of the lab), so cloud features simply won't work there. More importantly, a cloud decompiler or a browser-based disassembler works by sending the sample's code to someone else's server. For a sample from a real incident, that can break your organisation's handling rules or tip off an attacker who watches for their file appearing in public services. Prefer tools that run locally (Ghidra, radare2 or Rizin, objdump, or a locally installed commercial licence), and treat any upload as a deliberate decision, never a default.
objdump and radare2 in practice
Both work in a terminal on REMnux with no network. A few commands go a long way:
$ objdump -d -M intel sample.elf | less # all code sections, Intel syntax
$ objdump -d -M intel --no-show-raw-insn sample.elf # mnemonics only, easier to read
$ objdump -d -M intel --start-address=0x1139 --stop-address=0x115a sample.elf
$ objdump -D -b binary -m i386:x86-64 -M intel blob.bin # raw bytes, no headers needed
$ objdump -s -j .rodata sample.elf # hex dump of one section
$ r2 -A sample.elf # open and run full analysis (same as "aaa" after opening)
[0x00001050]> afl # list the functions found
[0x00001050]> ii # imports
[0x00001050]> iz # strings in the data sections
[0x00001050]> s main # seek to main
[0x00001139]> pdf # print the current function's disassembly
[0x00001139]> axt @ sym.imp.write # cross-references to the write import
[0x00001139]> afn print_banner # rename the current function
[0x00001139]> CC writes the banner # add a comment here
[0x00001139]> VV # visual graph mode (q to leave)
Rizin uses the same commands (start it with rizin -A), and Cutter puts the same analysis
behind windows and menus.
An Analyst's Workflow
A real sample might contain five thousand functions, most of them C runtime, compiler helpers and statically linked libraries. Nobody reads them all. Static code analysis is a search for the few functions that carry the sample's behaviour, guided by everything triage and the headers already told you.
-
Start from your triage notes
Type, architecture, compiler, packed or not, interesting strings, imports, entry point, constructors and TLS callbacks. If the sample is packed, the code you can see is mostly the unpacking stub: unpack it first (a later article) or read just enough of the stub to learn where it puts the real program.
-
Let the tool do its first pass, then check it
Run auto-analysis. Apply library signatures (IDA's FLIRT, Ghidra's Function ID, or a Go/Rust symbol recovery tool) so the runtime gets named and fades into the background. Check that
main(orWinMain, orDllMain) was found, and look for(bad)-style signs that analysis lost its place. -
Pick a thread: an import or a string
Choose something that matters to your questions. "Who is it talking to?" starts at
connect,InternetOpenW,WinHttpSendRequestor a URL-like string. "How does it persist?" starts atRegSetValueExWor aRunkey string. Open its cross-references. -
Read the call site, then work outwards
At each call, recover the arguments from the registers as we did above. Where did the host name come from? Follow that value backwards to the function that produced it, and that function's callers, until you reach something you understand. Go up and down the call tree, not straight through the listing.
-
Rename, retype, comment, as you go
The moment you understand something, write it into the database. Prefer names that say what the code does (
decode_config,send_beacon) and mark guesses as guesses (maybe_parse_cmd). -
Time-box, and skip what doesn't matter
If a function is clearly library code, a memory allocator or a string routine, name it and move on. If one is taking an hour, note what you know and come back later; the debugger (next article) often answers in a minute what static analysis takes an hour to prove.
-
Write down what you'd hand to a defender
Addresses of key functions, decoded strings and configuration, constants and byte patterns unique to this sample (future YARA material), and behaviours to confirm when you run it. Each claim should point to the code that supports it.
Worked example: decoding the configuration without running anything
Let's put it together on this article's buffer, pretending we found decode_config by
following a cross-reference from a networking call that used its output.
From call site to plaintext
- The call site (
0x00to0x11):lea rdi, [rip+0x12]puts the address0x19in the first argument,mov esi, 0xbmakes the second 11,mov edx, 0x5amakes the third0x5A. System V convention, so the call isdecode_config(&data_19, 11, 0x5A). - The function, from its CFG: for each
ibelowlen,buf[i] ^= key. A single-byte XOR, decoding in place. - The data at
0x19, 11 bytes:39 3E 34 74 3F 22 3B 37 2A 36 3F. (The 12th byte,00, is the padding that tripped up linear sweep; the length argument tells us it isn't part of the data.) - Decode it yourself, outside the sample: XOR each byte with
0x5A.0x39 ^ 0x5A = 0x63,c;0x3E ^ 0x5A = 0x64,d; and so on. - Record it: the decoded configuration is the host
cdn[.]example, XOR key0x5A, stored at offset0x19. The encoded bytes and the decoding loop are both candidates for a detection rule.
You can reproduce step 4 with one line of Node (or a CyberChef "XOR" recipe), without ever running the sample:
$ node -e 'const b = [0x39,0x3e,0x34,0x74,0x3f,0x22,0x3b,0x37,0x2a,0x36,0x3f];
console.log(String.fromCharCode(...b.map(x => x ^ 0x5a)))'
cdn[.]example (defanged here; the actual output has a plain dot)
This is static analysis at its best: we never ran a single instruction, and we have the sample's configuration, the algorithm that hides it, the key, and the exact bytes that make it recognisable. Real samples use longer keys, multi-byte or rolling XOR, RC4 or AES, and compressed or structured configs, but the method is the same: find the decoder from its caller, read the algorithm, find the key and the data, and reimplement the algorithm outside the sample.
What's Next
You can now read x86-64 the way analysts do: tell a disassembler's guess from the truth, decode an instruction from its prefix, REX, opcode, ModRM and SIB bytes, recover a call's arguments under either calling convention, recognise loops, conditions and jump tables in a control-flow graph, and navigate a program through its imports, strings and cross-references, renaming as you go. You also know where the tools' assumptions break: data in code, junk bytes, indirect jumps, and decompiler output that reads like source code but is only a hypothesis.
Static analysis has a limit, though. Some values only exist at run time: a key derived from the machine, a configuration fetched from a server, a payload that unpacks itself into memory. The next tool in the series watches the code as it runs: the debugger, used safely inside the lab, to confirm what you've read here and fill in what you couldn't.