Skip to content
systemcoding.dev
Assembly

The Complete Guide to x86-64 Assembly for Systems Programmers

A complete guide to x86-64 assembly on Linux: registers, flags, addressing, branches, the stack, calling C, atomics, encoding and a full worked program.

27 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the Intel, AMD and GNU logos.

You can be an effective systems programmer for years without writing a line of assembly, and you cannot be a complete one without being able to read it. The reason is always the same. Sooner or later a program does something its source does not explain: it crashes at an address with no source line, a loop is slower than the arithmetic says it should be, an optimizer deletes a check you wrote, or a binary arrives without its source. Every one of those is answered one level down, in the instructions the processor actually runs. This guide teaches that level for x86-64, the instruction set of nearly every PC, server and Intel-based Mac, with a bias toward what a systems programmer does with it: read compiler output, call between C and assembly, write small hot routines, and debug.

It is a complete route through the subject, built from first principles and ending in a worked program. Each section teaches one idea, shows it in code, and gives the output so you can check your reading. The code is written for NASM 2.16 in Intel syntax on x86-64 Linux, links with ld from binutils 2.43 or with GCC 14, and follows the System V AMD64 calling convention. Here is the claim the rest of the guide supports:

Almost everything in x86-64 assembly reduces to sixteen registers, one flags register, one address formula, and a stack. Learn those four things and the rest is a vocabulary of about forty instructions.

Who this is for, and who it is not for

This guide is for programmers who know C, or a language close to it, and want to understand what the machine does. You do not need prior assembly experience. You do need to be comfortable with pointers, with binary and hexadecimal numbers, and with a command line.

It does not fit three groups. If you want to optimize numerical kernels with SIMD, this guide stops before vector instructions, which have their own cluster of posts. If you target ARM, such as Apple Silicon or a phone, the registers and instructions differ entirely, and only the concepts transfer. If you need Windows specifics, the calling convention section marks the differences, but the examples assume Linux. And if your goal is to write most of a program in assembly, the honest advice is not to: write it in C, read the assembly it produces, and hand-write only the routines a compiler cannot express.

The map of this guide

The sections build on each other in this order:

  1. The tools, and how to see assembly for any C function.

  2. The machine model: registers, flags, memory.

  3. Your first complete program.

  4. Moving data and widening values.

  5. Arithmetic, division and the flags.

  6. Branches and loops.

  7. Addressing modes and lea.

  8. The stack, calls and stack frames.

  9. Calling conventions and mixing C with assembly.

  10. Strings, bits and shifts.

  11. Concurrency primitives and the memory model.

  12. Reading machine code and the instruction encoding.

  13. A complete worked program.

  14. A debugging workflow.

  15. Where the model ends.

Set up the tools and see your first assembly

You need four programs, all free and all in a standard Linux distribution:

ToolJob
nasmassembler: turns assembly text into an object file
ld or gcclinker: turns object files into an executable
objdumpdisassembler: turns machine code back into assembly
gdbdebugger: runs a program one instruction at a time

The fastest way to learn the instruction set is not to write assembly but to ask the compiler for it. Take this C function:

add3.cc
long add3(long a, long b, long c)
{
    return a + b + c;
}

and ask GCC 14 to stop after compiling and print assembly in Intel syntax:

Shell
gcc -O2 -S -masm=intel -o - add3.c

Without the directives, the function body is two instructions:

asm
add3:
        lea     rax, [rdi+rsi]
        add     rax, rdx
        ret

You can already read half of it. rdi, rsi and rdx are the first three arguments, rax is the return value, ret returns, and lea is arithmetic with an unusual name, covered below. For any C function you own, this one command is a free tutorial: write C, read the assembly, and ask why each line is there. To see the bytes alongside, assemble and dump:

Shell
gcc -O2 -c add3.c -o add3.o
objdump -d -M intel add3.o
Text
add3.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <add3>:
   0:	48 8d 04 37          	lea    rax,[rdi+rsi*1]
   4:	48 01 d0             	add    rax,rdx
   7:	c3                   	ret

The middle column is machine code, which a later section decodes by hand. Use -O1 or -O2 rather than -O0 while learning, because unoptimized output spends most of its instructions moving values to and from the stack, which hides the idea. Use -O0 when you want to see a one-to-one mapping from variables to memory.

The machine model

Four pieces of state make up everything a user-space program can see.

Sixteen registers

A register is a storage slot inside the processor. x86-64 has sixteen general-purpose registers, each 64 bits wide: rax, rbx, rcx, rdx, rsi, rdi, rbp, rsp, and r8 to r15. Each can be addressed at several widths. The 32-bit view of rax is eax, the 16-bit view is ax, and the 8-bit view is al. For r8 to r15 the suffixes are d, w and b: r8d, r8w, r8b.

One write rule explains most surprises: writing a 32-bit register clears bits 32 to 63 of the full register, while writing an 8-bit or 16-bit register leaves the other bits alone.

asm
        mov     rax, 0xFFFFFFFFFFFFFFFF
        mov     eax, 5              ; rax = 0x0000000000000005
        mov     rbx, 0xFFFFFFFFFFFFFFFF
        mov     bx, 5               ; rbx = 0xFFFFFFFFFFFF0005

That is why xor eax, eax zeroes all of rax and costs fewer bytes than the 64-bit form, and why a uint32_t converts to uint64_t for free. A few registers have fixed roles: rsp is the stack pointer, rcx is the shift and rep counter, and rax and rdx carry the results of multiply and divide. Everything else is convention, set by the calling convention covered later. The instruction pointer rip holds the address of the next instruction, and the flags register rflags holds the status bits discussed next.

The flags

Most arithmetic instructions leave flags behind, single bits in rflags that later instructions read. Four matter every day:

FlagNameSet when
ZFzerothe result was zero
SFsignthe top bit of the result is 1
CFcarryan unsigned operation carried out or borrowed
OFoverflowa signed result did not fit

The processor does not know whether your numbers are signed. It sets CF as though they were unsigned and OF as though they were signed on every operation, and your choice of conditional jump picks the interpretation. Take 8-bit values to see both at once:

asm
        mov     al, 0xFF
        add     al, 1               ; al = 0x00   CF=1 ZF=1 SF=0 OF=0
        mov     al, 0x7F
        add     al, 1               ; al = 0x80   CF=0 ZF=0 SF=1 OF=1

0xFF + 1 is a carry for an unsigned byte (255 plus 1 wraps) and not an overflow for a signed byte (-1 plus 1 is zero). 0x7F + 1 is the reverse: no unsigned carry, but a signed overflow (127 plus 1 is 128, which does not fit). Keep that table in your head, because every branch in the next sections is a decision about which flags to read.

Memory and the address formula

Memory is a flat array of bytes addressed by 64-bit numbers. An instruction names a memory location with one formula, written in square brackets:

Text
[ base + index * scale + displacement ]

The base and index are registers (the index cannot be rsp), the scale is 1, 2, 4 or 8, and the displacement is a signed constant. Every part is optional. The brackets mean "the memory at this address", so mov eax, [rdi] loads 4 bytes from the address in rdi, while mov eax, edi copies the register. The scale values match the sizes of char, short, int and long, so a[i] for an int array is one operand:

asm
        mov     eax, [rdi+rsi*4]    ; eax = a[i], with a in rdi and i in rsi

With rdi at 0x1000 and rsi equal to 3, the address is 0x1000 + 12 = 0x100c. A load or store has a width set by a register operand, or by a keyword (byte, word, dword, qword) when only a constant is involved: mov dword [rdi], 5 writes 4 bytes. There is also a rip-relative form, [rel label], that reaches globals without an absolute address and that position-independent code depends on. Only one operand of a normal instruction can be memory, so a copy from memory to memory goes through a register.

Why the modes and history matter a little

You will meet 16-bit and 32-bit code in boot sectors, old binaries and disassembly. x86 processors power on in 16-bit real mode, where addresses are a segment times 16 plus an offset, and an operating system moves them through 32-bit protected mode into 64-bit long mode, where this guide lives. The history is the reason the registers have the names they do: the e in eax stands for "extended" from the 32-bit generation, and the r was added for 64. It is also why a disassembler must be told which mode to decode. The same bytes read as dec eax in 32-bit mode and as a REX prefix in 64-bit mode.

Your first complete program

A Linux process needs no C library to run. This program prints a line and exits, using two system calls, which are requests to the kernel made with the syscall instruction:

hello.asmasm
global _start

section .rodata
msg:    db "Hello from x86-64", 10
len:    equ $ - msg                   ; assembler computes 18

section .text
_start:
        mov     eax, 1                ; syscall number 1 = write
        mov     edi, 1                ; fd 1 = standard output
        lea     rsi, [rel msg]        ; address of the bytes
        mov     edx, len              ; byte count
        syscall

        mov     eax, 60               ; syscall number 60 = exit
        xor     edi, edi              ; status 0
        syscall
Shell
nasm -f elf64 hello.asm -o hello.o
ld -o hello hello.o
./hello
echo $?
Text
Hello from x86-64
0

Read it as a contract with the kernel. On x86-64 Linux the system call number goes in rax, up to six arguments go in rdi, rsi, rdx, r10, r8 and r9, and the result comes back in rax. nasm -f elf64 produces an object file, and ld makes the executable with _start as the entry point. There is nothing before _start and nothing after the last syscall: forget the exit call and the processor runs off the end of the code and the program dies with Segmentation fault, because there is no caller to return to. strace ./hello shows exactly two system calls, which is the clearest picture of what a process is.

Moving data and widening values

mov dest, src copies and never changes flags. It cannot copy memory to memory. The width of the copy comes from the register or the size keyword, and it never widens: moving a byte does not touch the other bytes of a bigger register. To load a small value into a bigger register correctly, use one of the extending moves:

  • movzx fills the upper bits with zeros, for unsigned values.

  • movsx fills them with copies of the sign bit, for signed values (and movsxd for 32 to 64 bits).

asm
; with *rdi = 0xF6
        movzx   eax, byte [rdi]     ; rax = 0x00000000000000F6  (246)
        movsx   rax, byte [rdi]     ; rax = 0xFFFFFFFFFFFFFFF6  (-10)

The choice comes straight from the C type: unsigned char widens with movzx, signed char with movsx, and int to long with movsxd. A 32-bit unsigned to 64-bit conversion needs no instruction, since writing the 32-bit register already clears the upper half. Get this wrong and the bug is silent: a negative int used as an array index in a 64-bit register becomes a huge positive number if it was zero-extended instead of sign-extended.

Immediates have sizes too. Only mov reg, imm accepts a full 64-bit constant. Every other instruction takes a 32-bit immediate that the processor sign-extends, so mov qword [rdi], 0x100000000 is an error and the constant goes through a register first.

Arithmetic, division and the flags

add, sub, inc, dec and neg do what they say and set the flags, and the same instruction serves signed and unsigned values because two's complement arithmetic produces the same bits for both. imul multiplies; its two- and three-operand forms keep a result the same size as the operands:

asm
        imul    eax, ecx            ; eax = eax * ecx
        imul    eax, ecx, 10        ; eax = ecx * 10

One-operand mul and imul produce a double-width result in rdx:rax, and div and idiv divide the pair rdx:rax by their operand, returning the quotient in rax and the remainder in rdx. The upper half is the detail that bites. Before a signed division, sign-extend rax into rdx with cqo (or eax into edx with cdq), and before an unsigned division zero rdx:

asm
; int div_ok(int a, int b)       a in edi, b in esi
div_ok:
        mov     eax, edi
        cdq                         ; edx = sign extension of eax
        idiv    esi                 ; eax = quotient, edx = remainder
        ret
Text
div_ok(-7, 2)  -> -3          (truncation toward zero, remainder -1)

Replace cdq with xor edx, edx and div_ok(-7, 2) returns 2,147,483,644, because -7 was treated as the 64-bit value 0x00000000FFFFFFF9. A division by zero, or a quotient too large for its register (the case INT_MIN / -1), raises a hardware fault that Linux reports as Floating point exception (core dumped), so check the divisor first. Compilers avoid div for a constant divisor by multiplying by a fixed-point reciprocal: the constant 0xCCCCCCCD followed by a shift of 35 is unsigned division by 10, and recognizing it in a disassembly tells you the divisor.

Branches and loops

A conditional branch is two instructions: one sets flags, one reads them. cmp a, b computes a - b and keeps only the flags, and test a, b computes a AND b and keeps only the flags. Then a jcc instruction jumps if its condition holds. The conditions come in two families, and picking the wrong one is the commonest bug in hand-written assembly:

MeaningSignedUnsigned
lessjljb
less or equaljlejbe
greaterjgja
greater or equaljgejae
equal, not equalje, jneje, jne

Use the signed family for int and the unsigned family for pointers, sizes and anything from size_t. A C if compiles with the condition inverted, so the jump skips the body. Here is the maximum of two signed integers:

max.asmasm
; int max_i(int a, int b)   a in edi, b in esi
global max_i
max_i:
        mov     eax, edi            ; assume a is larger
        cmp     edi, esi
        jge     .done               ; a >= b: keep it
        mov     eax, esi            ; otherwise take b
.done:
        ret
Text
max_i(3, 9)    -> 9
max_i(-5, -2)  -> -2

test reg, reg is the idiom for "is it zero", one byte shorter than cmp reg, 0. setcc stores 0 or 1 from a condition, and cmovcc copies a value only when the condition holds, which gives a branch-free select. A cmov with a memory source always reads the memory, even when the move does not happen, so it cannot guard a null pointer dereference.

A loop is a label and a backward jump. The cheapest counts down with dec, which sets ZF itself:

sum_to.asmasm
; unsigned long sum_to(unsigned long n)   returns 1 + 2 + ... + n
global sum_to
sum_to:
        xor     eax, eax            ; total = 0
        test    rdi, rdi
        jz      .done               ; n == 0: nothing to add
.again:
        add     rax, rdi
        dec     rdi
        jnz     .again
.done:
        ret
Text
sum_to(0)    -> 0
sum_to(10)   -> 55
sum_to(100)  -> 5050

The guard at the top matters. A loop that tests at the bottom always runs once, so with rdi equal to zero the dec wraps to the largest unsigned value and the loop runs for an eternity. The loop instruction exists and no compiler emits it: dec plus jnz is as short in practice and executes faster on current processors.

Addressing modes and lea

lea, "load effective address", evaluates the address formula and stores the number, without reading memory and without changing flags. That makes it the Swiss Army knife of the instruction set:

asm
        lea     rax, [rdi+rsi]          ; rax = rdi + rsi  (a three-operand add)
        lea     rax, [rdi+rdi*2]        ; rax = rdi * 3
        lea     rax, [rdi+rdi*4+7]      ; rax = rdi * 5 + 7
        lea     rdi, [rel msg]          ; rdi = address of a global

A compiler multiplies by 3, 5 and 9 with lea and chains two for larger constants. When you read lea in disassembly and its result is never used as an address, it is arithmetic. The scale tops out at 8, so indexing an array of 12-byte structures needs lea rax, [rsi+rsi*2] followed by a scale-4 access. The rules that cause assembler errors are few: the index cannot be rsp, the scale must be 1, 2, 4 or 8, a memory operand with only a constant needs an explicit size, and all registers in one operand must have the same width.

The stack, calls and stack frames

The stack is ordinary memory that four instructions manage for you, and rsp always points at its top. It grows toward lower addresses. push src subtracts 8 from rsp and stores the value at the new top, and pop dst loads the value at the top and adds 8. call target pushes the address of the next instruction and jumps, and ret pops that address into rip:

callret.asmasm
global _start

section .text
square:                             ; long square(long x), x in rdi
        mov     rax, rdi
        imul    rax, rdi
        ret

_start:
        mov     rdi, 9
        call    square              ; pushes the return address, jumps
        mov     rdi, rax            ; back here after ret; rax = 81
        mov     eax, 60             ; exit(rdi)
        syscall

Run ./callret; echo $? and the shell prints 81, the low byte of the exit status. Trace rsp and you can predict everything: each push lowers it by eight, each pop raises it, and a function must leave it exactly where it found it. The rule that matters is balance. A function that pushes a register and forgets the matching pop makes ret take the saved register as its return address, and the processor jumps to an arbitrary number. The crash lands at an address that looks unrelated to your code, and that "unrelated address" is the signature of an unbalanced stack.

Frames

A function that needs local variables carves them out of the stack. Because rsp moves with every push, locals need a fixed reference point, and the conventional one is rbp. The standard prologue and epilogue are:

asm
        push    rbp                 ; save the caller's frame pointer
        mov     rbp, rsp            ; rbp = current stack top
        sub     rsp, 16             ; reserve 16 bytes for locals
        ; ... body: locals at [rbp-8], [rbp-16] ...
        leave                       ; mov rsp, rbp ; pop rbp
        ret

After the prologue the saved frame pointer is at [rbp], the return address is at [rbp+8], locals are at negative offsets, and arguments passed on the stack are at [rbp+16] and up. The saved rbp values form a linked list that debuggers follow to print a backtrace. Optimized builds drop the frame pointer (-fomit-frame-pointer, on by default at -O2) to free rbp as a general register, and rely on separate unwind tables instead. Profilers that sample call stacks often want -fno-omit-frame-pointer back.

A leaf function, one that calls nothing, may use the red zone: the 128 bytes below rsp, which the System V ABI guarantees no signal handler will touch, so it can store locals at [rsp-8] without a sub. The zone ends at the first call, because the call pushes its return address into it. Kernel code and Windows code must not use it, and the Linux kernel is built with -mno-red-zone.

Calling conventions and mixing C with assembly

A calling convention is the contract that lets separately compiled functions cooperate. On Linux, macOS and the BSDs it is the System V AMD64 ABI:

ItemRule
Integer and pointer argumentsrdi, rsi, rdx, rcx, r8, r9, then the stack
Floating-point argumentsxmm0 to xmm7
Return valuerax (and rdx:rax for 128 bits), xmm0 for floating point
Callee-saved registersrbx, rbp, r12 to r15
Everything elsecaller-saved: any call may overwrite it
Stack alignmentrsp is a multiple of 16 immediately before a call
Variadic callsal holds an upper bound on the vector registers used

A caller-saved register may be destroyed by any call, and a callee-saved register must come back unchanged, so a value that has to survive a call lives in rbx, rbp or r12 to r15:

sum_after.asmasm
extern foo

; long sum_after(long a)   returns a + foo()
global sum_after
sum_after:
        push    rbx                 ; save the caller's rbx, and align the stack
        mov     rbx, rdi            ; keep a across the call
        call    foo                 ; foo may overwrite rdi, never rbx
        add     rax, rbx
        pop     rbx
        ret

The push does two jobs. On entry rsp is 8 modulo 16 because the call pushed a return address, so one push makes it a multiple of 16, which is what the next call requires. Windows x64 uses a different convention: four argument registers rcx, rdx, r8 and r9, a mandatory 32-byte shadow space above the return address, and rdi and rsi callee-saved. The same C source compiles to different assembly on the two systems, and a function written for one cannot be called from the other without a thunk.

Calling C from assembly

To use the C library, write main instead of _start and let gcc link the runtime:

hello_c.asmasm
default rel
extern puts
extern printf
global main

section .rodata
msg:    db "Hello from assembly", 0
fmt:    db "%s has %d letters", 10, 0

section .text
main:
        sub     rsp, 8              ; align: entry rsp is 8 mod 16
        lea     rdi, [msg]
        call    puts wrt ..plt      ; puts(msg)
        lea     rdi, [fmt]
        lea     rsi, [msg]
        mov     edx, 19
        xor     eax, eax            ; variadic call: no vector registers
        call    printf wrt ..plt
        xor     eax, eax
        add     rsp, 8
        ret
Shell
nasm -f elf64 hello_c.asm -o hello_c.o
gcc -o hello_c hello_c.o
./hello_c
Text
Hello from assembly
Hello from assembly has 19 letters

wrt ..plt routes the call through the procedure linkage table, which position-independent executables require. The most common failure here is a segmentation fault inside printf with no obvious cause. It means rsp was not a multiple of 16 at the call, and the library executed an aligned movaps on a misaligned stack. Confirm it in GDB by printing $rsp at the call, which must end in 0, and fix it with a sub rsp, 8 or a push.

Calling assembly from C

The reverse direction is simpler and relies entirely on the prototype. The compiler turns a call into register assignments by reading the declaration, and it never checks the declaration against the assembly:

main.cc
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

uint64_t sum32(const uint32_t *p, size_t n);

int main(void)
{
    uint32_t data[] = {4000000000u, 4000000000u, 5u};
    printf("%" PRIu64 "\n", sum32(data, 3));
    return 0;
}

If the assembly routine returns a 64-bit sum in rax and the prototype says unsigned, the compiler reads only eax and the result is silently truncated. Declare the widest type the routine writes, export the symbol with global sum32:function, add a section .note.GNU-stack noalloc noexec nowrite progbits line to avoid an executable-stack warning, and preserve the callee-saved registers. GCC 14 turns an implicit declaration into a hard error, which is the protection you want.

Strings, bits and shifts

The string instructions movs, stos, lods, scas and cmps work through fixed registers: rsi as source, rdi as destination, rcx as a count and the accumulator as the value. A rep prefix repeats them rcx times. Two of them are a complete memcpy and memset:

asm
        mov     rcx, rdx            ; count
        rep movsb                   ; copy rcx bytes from [rsi] to [rdi]

        mov     rcx, rdx
        mov     al, 0               ; the fill byte
        rep stosb                   ; fill rcx bytes at [rdi]

The direction flag decides whether the pointers move up or down after each element. The ABI requires it clear on entry to and exit from every function, so a backward copy (std, for overlapping regions) must end with cld. On current Intel and AMD processors rep movsb is competitive with vector loops for medium and large sizes, and slower than plain mov pairs for a few bytes.

Shifts and rotates move bits: shl and shr shift with zero fill, sar shifts right copying the sign bit, and rol and ror rotate. The count is an immediate or cl, and it is masked to 5 bits (6 for 64-bit operands). The last bit shifted out lands in CF. Signed division by a power of two is the one place sar misleads, because it rounds toward negative infinity while C truncates toward zero, so the compiler adds a bias first:

asm
; int sdiv16(int x)
        mov     eax, edi
        sar     eax, 31             ; -1 if negative, else 0
        shr     eax, 28             ; 15 if negative, else 0
        add     eax, edi            ; add the bias to negative inputs
        sar     eax, 4              ; divide by 16, rounding toward zero
        ret
Text
sdiv16(-17) -> -1      sdiv16(40) -> 2

Counting bits has dedicated instructions: popcnt counts the set bits, lzcnt counts leading zeros and tzcnt counts trailing zeros, each defined for a zero input (the operand width for the last two). They sit behind CPUID feature bits, and lzcnt on a processor without the feature silently executes as bsr and returns a different number, so compile for a target that guarantees it, such as -march=x86-64-v3, or check the bit first.

Concurrency primitives and the memory model

A plain add [rdi], eax is a load, an add and a store, so two cores can lose an update. The lock prefix makes a read-modify-write atomic with respect to every other core:

asm
        lock inc    dword [rdi]         ; atomic counter increment
        lock xadd   [rdi], esi          ; atomic fetch-and-add: esi = old value
        mov         eax, 1
        xchg        [rdi], eax          ; atomic swap (always locked, with or without the prefix)

cmpxchg is the primitive for lock-free algorithms: it compares rax with the destination, stores the source if they match and sets ZF, and otherwise loads the current value into rax. A spinlock is an xchg that retries until it reads 0, a read-only wait loop between attempts, and a plain mov dword [rdi], 0 to release.

x86 has the strongest memory model among mainstream processors. Loads are not reordered with loads, stores are not reordered with stores, and stores are not reordered with earlier loads. One reordering is allowed: a later load may complete before an earlier store to a different address, because the store sits in a buffer. That is the only reason mfence exists in ordinary code, and it is needed for patterns like Dekker's algorithm and sequentially consistent stores, where a store must be visible before a later load runs. Message passing through a flag, a spinlock release and a single-producer queue need no fence at all on x86. The compiler is a separate matter: it may reorder what the hardware would not, so shared data uses C11 atomics or compiler barriers, never plain variables.

Reading machine code and the instruction encoding

An instruction is between one and fifteen bytes, built from optional prefixes, an optional REX byte, one to three opcode bytes, an optional ModRM byte, an optional SIB byte, a displacement and an immediate, in that order. REX has the form 0100WRXB: W selects 64-bit operands and the other three bits supply the fourth bit of a register number, which is how r8 to r15 are reached. ModRM is mod(2) reg(3) rm(3), and mod = 11 means a register operand while rm = 100 means a SIB byte follows.

Decode mov eax, [rdi+rsi*4+8], which is the four bytes 8b 44 b7 08:

Text
8b          opcode: MOV r32, r/m32
44          ModRM 01 000 100: mod=01 (8-bit displacement), reg=000 (eax), rm=100 (SIB follows)
b7          SIB   10 110 111: scale=4, index=110 (rsi), base=111 (rdi)
08          displacement 8

Now decode a whole function from its bytes, using the procedure in the previous section's style: take the bytes 55 48 89 e5 89 7d fc 83 7d fc 00 7e 05 8b 45 fc eb 05 b8 00 00 00 00 5d c3. 55 is push rbp, 48 89 e5 is mov rbp, rsp, 89 7d fc is mov [rbp-4], edi, 83 7d fc 00 is cmp DWORD PTR [rbp-4], 0, 7e 05 is jle five bytes forward, 8b 45 fc is mov eax, [rbp-4], eb 05 is jmp five bytes forward, b8 00 00 00 00 is mov eax, 0, 5d is pop rbp and c3 is ret. The function is return x > 0 ? x : 0; compiled without optimization. Jump displacements are measured from the end of the jump instruction, multi-byte fields are little-endian, and objdump -D -b binary -m i386:x86-64 -M intel file.bin checks the work.

AVX instructions use a different prefix. VEX (c5 or c4) and EVEX (62) fold the legacy prefixes and REX into a compact form with a third source register field vvvv stored inverted, a vector length bit, and for EVEX an opmask and 32 registers. c5 f4 58 c2 is vaddps ymm0, ymm1, ymm2.

A complete worked program

A guide should end by building something. This program computes a factorial with a loop and prints the result as a decimal number, using only system calls, so every instruction is ours. The conversion routine is the interesting part: a number becomes text by dividing by 10 repeatedly and collecting the remainders, which arrive in reverse order, so we fill a buffer from the end.

fact.asmasm
global _start

section .bss
buf:    resb 24                     ; room for 20 digits and a newline

section .text
; print_u64: write the unsigned decimal value in rdi, then a newline, to stdout
print_u64:
        lea     rsi, [rel buf+23]   ; rsi points at the last byte of the buffer
        mov     byte [rsi], 10      ; newline goes last
        mov     rax, rdi            ; the value to convert
        mov     ecx, 10             ; divisor
.digit:
        xor     edx, edx            ; upper half of the dividend = 0 (unsigned division)
        div     rcx                 ; rax = value / 10, rdx = value % 10
        add     dl, '0'             ; digit value to ASCII
        dec     rsi
        mov     [rsi], dl           ; store the digit before the ones already written
        test    rax, rax
        jnz     .digit              ; stop when the quotient is zero
        lea     rdx, [rel buf+24]   ; one past the end
        sub     rdx, rsi            ; length = end - start, newline included
        mov     edi, 1              ; fd 1
        mov     eax, 1              ; write
        syscall
        ret

_start:
        mov     eax, 1              ; result = 1
        mov     ecx, 10             ; n = 10
.fact:
        imul    rax, rcx            ; result *= n
        dec     ecx
        jnz     .fact               ; until n reaches 0
        mov     rdi, rax
        call    print_u64
        mov     eax, 60
        xor     edi, edi
        syscall
Shell
nasm -f elf64 fact.asm -o fact.o
ld -o fact fact.o
./fact
Text
3628800

Trace the loop to see why it works. rax starts at 1 and ecx at 10, and each pass multiplies and counts down:

Passecx beforerax after imul
11010
2990
38720
1013628800

The dec ecx after the tenth multiply sets ZF, the jnz falls through, and rax holds 10 factorial. Then print_u64 runs the digit loop: 3628800 divided by 10 leaves remainder 0, then 362880 leaves 0, and so on, so the first digit stored is the last one, and the string builds backward from the newline, finishing with 3. Change the starting ecx to 20 and the program prints 2432902008176640000, the largest factorial that fits in 64 bits. Change it to 21 and the product wraps and prints a wrong number with no error, because imul rax, rcx throws away the upper half. A checked version would use one-operand mul and test CF, which is set when the high half is nonzero.

Three things in the program are worth noticing. The xor edx, edx before div is not decoration: leave it out and a stale rdx becomes the top half of the dividend. The lea rsi, [rel buf+23] is position-independent addressing, the form that works in every kind of executable. And print_u64 never touches rbx, rbp or r12 to r15, so it obeys the callee-saved rule and could be called from C if its arguments and name were adjusted.

A debugging workflow

When a program misbehaves, the loop is always the same: stop at the start, step one instruction, look at the registers and the flags, and compare with your prediction. In GDB, assemble with debug information first, with nasm -f elf64 -g -F dwarf fact.asm, then:

Text
(gdb) break _start
(gdb) run
(gdb) stepi
(gdb) info registers rax rcx rip
rax            0x1                 1
rcx            0xa                 10
rip            0x401005            0x401005 <_start+5>
(gdb) x/4i $rip
=> 0x401005 <_start+5>:	imul   rax,rcx
   0x401009 <_start+9>:	dec    ecx
   0x40100b <_start+11>:	jne    0x401005 <_start+5>
   0x40100d <_start+13>:	mov    rdi,rax

The addresses depend on how the program was linked. The commands that do nearly all of the work are stepi (one instruction), nexti (one instruction, stepping over calls), info registers, x/Ni $rip (disassemble the next N instructions), x/4gx $rsp (dump four stack slots) and p/x $eflags, which prints the flags by name. When a crash gives you only an address, x/i $rip shows the faulting instruction, info registers shows the operands, and the earlier sections tell you what the instruction expects: a mov through a register holding 0 is a null dereference, a movaps on a stack address ending in 8 is a misaligned call, and an idiv is a division by zero or an overflowing quotient. For stack bugs, compare rsp at a function's first instruction and at its ret: they must differ by exactly 8.

A static view helps as well. objdump -d -M intel on a binary, and gcc -S -masm=intel on source, give you the whole function without running it. And never read a flag after an instruction that rewrote it: inc, dec and shifts update only some flags, and a mov between a cmp and its jcc is fine because mov leaves the flags alone, but an add in between destroys them.

Probing the processor

Two instructions ask the hardware about itself. cpuid takes a leaf number in eax and returns information in eax, ebx, ecx and edx: leaf 0 returns the vendor string in ebx, edx, ecx (in that order), and leaf 1 returns the family, model and feature bits. It overwrites rbx, which is callee-saved, so every wrapper must push rbx and pop rbx. Always test a feature bit before using an instruction it guards, never infer features from the model number, and cache the results, because cpuid is slow and traps in a virtual machine. rdtsc reads a 64-bit counter that ticks at a constant reference rate on current processors, not at the core clock, and because it does not wait for earlier instructions, a measurement fences the start with lfence and ends with rdtscp followed by lfence. For anything that must be portable, prefer clock_gettime.

Exercises that build the habit

Reading is a skill that needs repetition, and the cheapest practice is to compare your prediction with the compiler. Write four small C functions, predict their assembly line by line, then check with gcc -O1 -S -masm=intel.

  1. **int abs_i(int x)** returning x < 0 ? -x : x. Expect a neg and a cmov, or a sar and xor trick, and work out which flags each form reads.

  2. **unsigned long count_set(unsigned long x)** using a loop that clears the lowest set bit with x &= x - 1. Expect the loop to end on ZF from the and, with no separate compare, and expect popcnt instead if you add -mpopcnt.

  3. **size_t my_strlen(const char *s)** with a pointer loop. Expect a cmp BYTE PTR [rdi], 0 and a pointer subtraction at the end.

  4. **long sum_pairs(const struct pair *p, long n)** over an array of two-long structures. Expect the address formula with a scale of 8 and a displacement, or a lea multiplying by 2 first.

For each, find the callee-saved registers the compiler chose, if any, find the prologue, and decide whether the function is a leaf. Then change one thing, such as long to int or unsigned to signed, and find the instruction that changed. That single habit of changing one type and finding the one instruction that moved teaches the widening rules, the signed and unsigned jump families and the zero-extension behavior faster than any reference.

Where the model ends

Be clear about what this guide does not make you. It does not make you fast: modern cores reorder, fuse and predict, and two instruction sequences of equal length can differ widely in speed, so only a measurement on the target processor settles a performance question, and a hand-written routine rarely beats a compiler without one. It does not cover SIMD, where the real speedups live, nor floating point beyond a mention, nor the privileged instructions an operating system uses. It does not apply unchanged to another architecture: ARM and RISC-V have more registers, fixed-width instructions, and a link register for the return address in place of a stack push. It also assumes Linux, so the system call numbers, the red zone and the calling convention all change on Windows.

Three habits carry beyond the details. Read the compiler's output for code you own, because it is the best teacher available and it is correct. Treat every register and every flag as having a producer, and ask which instruction last wrote it. And when something is wrong, narrow it to one instruction with a debugger before theorizing. The instruction set is large, but the working vocabulary is small, and the sixteen registers, the flags, the address formula and the stack are enough to read almost any function you meet.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.