How a Computer Runs Code

Foundations · Assembly 1

Why Assembly

Every language you have used is translated, in the end, into machine code: numbers the processor executes directly. Assembly is a human-readable spelling of those numbers, one line per instruction. You learn it not to write big programs but to understand what the machine actually does: why a loop is slow, what a pointer is, how a function call works, and what a compiler did with your code.

What this sheet covers
What you need
  • x86-64, the 64-bit architecture in nearly every laptop, desktop and server (Intel and AMD).
  • Linux and the NASM assembler with Intel syntax: mov rax, 5 means “put 5 in rax”, destination first.
  • The System V calling convention, which is how C and assembly talk to each other on Linux and macOS.
  • A tab at the end on AT&T syntax, which is what gcc -S and most textbooks print, so you can read both.
  • A Linux machine, a virtual machine, WSL on Windows, or an online assembler sandbox.
  • nasm (the assembler), ld or gcc (the linker) and gdb (the debugger): sudo apt install nasm gcc gdb.
  • Any text editor. Save files as .asm.

The Pieces of the Machine

PartWhat it isIn assembly
CPU (processor)Executes one instruction after another, billions per secondYour code is the list it executes
RegistersA handful of tiny, extremely fast storage slots inside the CPU, 64 bits eachrax, rbx, rcx, … the names you use most
Memory (RAM)Billions of numbered bytes; slow compared with registers[address]: square brackets mean “the contents at”
Instruction pointerThe register rip: the address of the next instructionJumps and calls change it; you never write to it directly
FlagsA register of yes/no bits set by the last arithmetic: was it zero, negative, did it overflowWhat conditional jumps look at
StackA region of memory that grows and shrinks at one end, tracked by rsppush, pop, call, ret
The fetch-decode-execute cycle
From source to running program
  • Fetch — read the instruction bytes at rip
  • Decode — work out which operation and which operands
  • Execute — do it: move data, add, compare, jump
  • Advance — rip moves to the next instruction, unless this one was a jump
  • hello.asm — what you write
  • nasm -f elf64 hello.asm — the assembler turns it into an object file hello.o of machine code with unresolved addresses
  • ld hello.o -o hello — the linker fixes the addresses and produces the executable
  • ./hello — the operating system loads it into memory and sets rip to _start

What an Instruction Looks Like

Anatomy of a line

; label:   mnemonic  destination, source      ; comment
loop_top: add       rax, rbx                  ; rax = rax + rbx
          mov       rcx, [rdi + 8]            ; rcx = the 8 bytes in memory at address rdi + 8
          cmp       rax, 100                  ; set the flags from rax - 100
          jl        loop_top                  ; jump back if rax < 100 (signed)
  • Mnemonic: the operation, such as mov, add, cmp, jmp. About thirty cover a first course.
  • Operands: at most two for most instructions, destination first in Intel syntax. At most one may be a memory operand.
  • Label: a name for an address, ending in a colon. Jumps and calls use labels; the assembler turns them into numbers.
  • Comment: from ; to the end of the line. Assembly needs more comments than any other language: say what the register means, not what the instruction does.
  • One instruction does one small thing. x = a + b is two or three instructions; a for loop is five or six.

Assembly has no types and no safety net. A register is just 64 bits; whether they are a number, an address or four characters is up to you. Nothing stops you adding an address to a letter or jumping into data. The assembler checks spelling, not meaning.

Number Systems: Binary, Hex and Two’s Complement

Foundations · Assembly 1

Binary and Hexadecimal

The machine stores everything as bits. Writing 64 bits in binary is unreadable, so assembly programmers use hexadecimal: one hex digit per four bits, two per byte. Learn to convert between the three without thinking.

DecimalBinaryHexDecimalBinaryHex
000000810008
100011910019
200102101010A
300113111011B
401004121100C
501015131101D
601106141110E
701117151111F

Converting

  • Binary → hex: group into fours from the right, convert each group. 1011 0110 → B6.
  • Hex → decimal: each digit is a power of 16. 0x1F = 1×16 + 15 = 31.
  • Decimal → binary: divide by 2 repeatedly, read the remainders bottom up. 13 → 1101.
  • Powers of two to know by heart: 28 = 256, 210 = 1024, 216 = 65,536, 232 ≈ 4.29 billion.

How NASM writes them

mov rax, 255          ; decimal
mov rax, 0xFF         ; hex, C style
mov rax, 0FFh         ; hex, old style (must start with a digit)
mov rax, 0b1111_1111  ; binary (underscores allowed)
mov rax, 'A'          ; a character: its code, 65
mov rax, -1           ; all 64 bits set: 0xFFFFFFFFFFFFFFFF

Sizes and Two’s Complement

SizeBitsUnsigned rangeSigned rangeNASM name
byte80 to 255-128 to 127byte / db
word160 to 65,535-32,768 to 32,767word / dw
double word320 to about 4.29 billion± about 2.15 billiondword / dd
quad word640 to about 1.8 × 1019± about 9.2 × 1018qword / dq

Negative numbers use two’s complement: to negate, flip every bit and add 1. The top bit is the sign bit. The same bits mean different numbers depending on whether you read them as signed or unsigned; the hardware does not know which you meant, so it keeps flags for both.

Negating by hand (8 bits)

  5      = 0000 0101
flip     = 1111 1010
add 1    = 1111 1011   = -5   (= 251 if read as unsigned)

-1       = 1111 1111   (all ones, in every size)
-128     = 1000 0000   (the most negative value has no positive partner)

Why it works

  • Addition is the same circuit for signed and unsigned: 5 + (-5) = 0000 0101 + 1111 1011 = 1 0000 0000, and the carry out is dropped, leaving 0.
  • Subtraction is adding the negation. The CPU has one adder.
  • Sign extension: to widen -5 from 8 to 16 bits, copy the sign bit: 1111 1111 1111 1011. movsx does this; movzx fills with zeros instead.
  • Overflow: 127 + 1 in 8 bits is 1000 0000 = -128. The hardware sets the overflow flag (signed) or carry flag (unsigned) and carries on.

Bits, Bytes and Addresses

  • Memory is addressed by byte. A qword at address 1000 occupies bytes 1000 through 1007; the next qword starts at 1008.
  • x86 is little-endian: the least significant byte comes first in memory. The qword 0x0000000000000102 at address 1000 is stored as bytes 02 01 00 00 00 00 00 00. Reading the first byte alone gives 2.
  • An address is itself a 64-bit number and fits in a register. “Pointer” is just a name for a register or variable that holds an address.
  • Characters are bytes: 'A' is 65, 'a' is 97, '0' is 48, newline is 10. 'a' - 'A' is 32, so clearing bit 5 uppercases a letter.

Signed or unsigned is your decision, instruction by instruction. cmp rax, rbx sets flags for both interpretations; jl (jump if less) reads the signed ones and jb (jump if below) the unsigned ones. Choosing the wrong one is the classic assembly bug, and it only shows up for values with the top bit set.

Registers, Memory and Addressing

Foundations · Assembly 1

The General-Purpose Registers

x86-64 has sixteen 64-bit general-purpose registers. Each can be used as a whole or in parts: the low 32, 16 or 8 bits have their own names, and writing the 32-bit part zeroes the upper 32 bits (writing the 16- or 8-bit part does not).

64-bit32-bit16-bit8-bitConventional use
raxeaxaxalAccumulator; return value; syscall number
rbxebxbxblCallee-saved scratch
rcxecxcxclCounter; 4th argument; shift count
rdxedxdxdl3rd argument; high half of multiply/divide
rsiesisisil2nd argument; source index
rdiedididil1st argument; destination index
rbpebpbpbplFrame pointer (base of the current stack frame)
rspespspsplStack pointer: always the top of the stack
r8 to r15r8d …r8w …r8b …r8, r9 are the 5th and 6th arguments; the rest are scratch

Parts of a register

mov rax, 0x1122334455667788
; rax = 1122334455667788
; eax =         55667788   (low 32 bits)
;  ax =             7788   (low 16)
;  al =               88   (low 8)
;  ah =             77     (bits 8-15; only a, b, c, d have an h part)

mov eax, 1          ; rax is now 0000000000000001: the upper half is CLEARED
mov ax, 1           ; only the low 16 bits change; the rest keep their value

Special registers

RegisterHolds
ripAddress of the next instruction
rflagsThe flags: ZF (zero), SF (sign), CF (carry), OF (overflow), and others
xmm0 to xmm15Floating-point and vector values; xmm0 returns a double
Segment registersLegacy; you will not touch them in a first course

Memory Operands

Square brackets mean “the contents of memory at this address”. The address inside can combine a base register, an index register scaled by 1, 2, 4 or 8, and a constant. This one shape handles variables, arrays, structures and stack slots.

; general form:  [base + index*scale + displacement]
mov rax, [rbx]               ; the qword at the address in rbx
mov rax, [rbx + 8]           ; 8 bytes further on: the next qword
mov rax, [rbx + rcx*8]       ; element rcx of an array of qwords starting at rbx
mov eax, [rbx + rcx*4 + 16]  ; element rcx of a dword array that starts 16 bytes into a structure
mov rax, [counter]           ; a variable, by name (its address is a constant)
mov rax, [rel counter]       ; the same, position-independent (needed when linking with gcc)

Size matters

mov rax, [rbx]            ; 8 bytes: the size comes from rax
mov al, [rbx]             ; 1 byte: from al
mov [rbx], rax            ; store 8 bytes
mov qword [rbx], 0        ; storing a constant: NASM must be TOLD the size
mov byte [rbx], 'A'
mov dword [rbx + 4], 7
movzx eax, byte [rbx]     ; load a byte and zero-extend into eax
movsx rax, dword [rbx]    ; load a dword and sign-extend into rax

Rules

  • At most one operand may be in memory. mov [a], [b] does not exist; go through a register.
  • When neither operand is a register the size is ambiguous and NASM demands byte, word, dword or qword: mov [rbx], 0 stops with error: operation size not specified. With a register operand the size is never ambiguous, and writing a size that disagrees with the register (mov qword [rbx], eax) is error: invalid combination of opcode and operands.
  • lea (load effective address) computes the address without reading memory: lea rax, [rbx + rcx*8] puts the address in rax. It is also a free three-operand add.
  • Reading memory is tens to hundreds of times slower than a register. Keep hot values in registers inside loops.

Where Things Live

SectionDirectiveContentsExample
.datasection .dataInitialized variables and constantsmsg db "Hello", 10, count dq 0
.bsssection .bssUninitialized space, zero at start, costs nothing in the filebuffer resb 64, total resq 1
.textsection .textThe instructionsglobal _start and your code
Stacknone; managed by rspReturn addresses, saved registers, local variablespush rbx, sub rsp, 32
RegistersnoneThe values you are working on right now

A variable name in NASM is an address. mov rax, count loads the address of count; mov rax, [count] loads its value. Forgetting the brackets is the second classic assembly bug.

Your First Program

Writing Programs · Assembly 1

Hello, World with System Calls

With no libraries at all, a program asks the operating system to do things through system calls: put a number in rax saying which service, the arguments in rdi, rsi, rdx, and execute syscall. Writing to the screen is call 1; exiting is call 60.

hello.asm

; hello.asm - prints a line and exits (Linux x86-64, NASM)
section .data
    msg     db  "Hello, World!", 10      ; the text, then a newline (10)
    msg_len equ $ - msg                  ; length = current address - start of msg

section .text
    global _start                        ; the linker needs to see the entry point

_start:
    mov rax, 1          ; syscall number 1 = write
    mov rdi, 1          ; file descriptor 1 = standard output
    mov rsi, msg        ; address of the text
    mov rdx, msg_len    ; how many bytes
    syscall

    mov rax, 60         ; syscall number 60 = exit
    xor edi, edi        ; exit code 0 (xor a register with itself is the idiom for zero)
    syscall

Assemble, link, run

nasm -f elf64 hello.asm -o hello.o
ld hello.o -o hello
./hello
echo $?            # the exit code: 0
Hello, World!
0

Read it

  • section .data holds the bytes of the message; db means “define bytes”.
  • equ defines a constant at assembly time. $ is “the address here”, so $ - msg is the length.
  • global _start exports the label; ld starts the program there.
  • Each syscall is a request to the kernel. Nothing prints until the kernel does it.
  • Without the exit call the CPU would run off the end of your code into garbage and crash.

What the first mistakes look like

  • Leave out the exit syscall: the text prints, then Segmentation fault and echo $? shows 139 (128 + signal 11). The CPU kept executing past your last instruction.
  • Write mov rsi, [msg] instead of mov rsi, msg: the program prints nothing and exits normally. You passed the first eight letters of the message as an address; the kernel refused it and returned an error code in rax, which nothing checked.
  • Forget global _start: ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000. It usually still works because your code happens to start there, but it is luck; export the label.
  • Forget the , 10 after the message: it prints, but the shell prompt appears on the same line.
Linux syscallraxrdirsirdxReturns in rax
read0fd (0 = keyboard)buffer addressmax bytesbytes read, 0 at end of input
write1fd (1 = screen, 2 = errors)text addressbyte countbytes written
exit60exit codenever returns

Hello, World with the C Library

Most courses link with gcc instead, so you can call printf, scanf and friends. Then your entry point is main, and the C library handles starting up and exiting.

hello2.asm

; hello2.asm - the same program, calling printf
default rel                      ; use rip-relative addresses (required for modern gcc)
extern printf                    ; defined in the C library

section .data
    fmt db "Hello, %s! You are %d.", 10, 0    ; printf wants a 0-terminated string
    who db "World", 0

section .text
    global main

main:
    push rbp                     ; keep the stack 16-byte aligned for the call
    mov rbp, rsp

    lea rdi, [fmt]               ; 1st argument: the format string
    lea rsi, [who]               ; 2nd argument: the %s
    mov edx, 42                  ; 3rd argument: the %d
    xor eax, eax                 ; number of vector registers used = 0 (printf is variadic)
    call printf

    xor eax, eax                 ; return 0 from main
    pop rbp
    ret
nasm -f elf64 hello2.asm -o hello2.o
gcc -no-pie hello2.o -o hello2
./hello2
Hello, World! You are 42.
  • C strings end with a 0 byte; the syscall version needed a length instead. Mixing the two conventions is a common bug.
  • lea rdi, [fmt] with default rel loads the address relative to rip, which is what position-independent executables need. mov rdi, fmt works only with -no-pie.
  • Before any call, rsp must be a multiple of 16. On entry to main it is 8 off (the return address was pushed); one push rbp fixes it.
  • xor eax, eax before a variadic function such as printf tells it how many floating-point arguments are in xmm registers. Forgetting it can crash.

The Shape of Every Source File

Template

default rel
extern printf, scanf, puts          ; C functions you call
global main                         ; or _start if you link with ld

section .data                       ; initialized data
    ; name  size  value
    fmt     db   "%d", 10, 0
    total   dq   0

section .bss                        ; zeroed space
    buffer  resb 256

section .text                       ; code
main:
    push rbp
    mov rbp, rsp
    ; ... your program ...
    xor eax, eax
    pop rbp
    ret

Habits that save hours

  • Comment the meaning of every register at the top of each routine: ; rdi = array, rsi = length, rax = running sum.
  • Assemble often. NASM’s messages name the line.
  • Run under gdb from the first day: gdb ./hello, then break main, run, stepi, info registers, x/8xb &buffer. Watching registers change teaches more than any explanation.
  • A crash with Segmentation fault means a bad address: unbalanced push/pop, a missing ret, brackets where you meant none, or a call with a misaligned stack.

Reading the assembler’s and linker’s messages

MessageCauseFix
error: symbol `done' not definedA label is misspelled, or a .done local label is used from a different routineMatch the spelling; local labels belong to the nearest non-dot label above them
error: parser: instruction expectedA typo in a mnemonic (mvo), or a label without its colon followed by an operandFix the spelling; every label ends in :
error: invalid combination of opcode and operandsOperand sizes differ (add rax, ecx), two memory operands, a constant as destination (mov 5, rax), or idiv 10 with an immediateWiden first, go through a register, swap the operands, put the divisor in a register
error: operation size not specifiedmov [rbx], 0: neither operand says how many bytesmov qword [rbx], 0
warning: byte data exceeds boundsx db 300: 300 does not fit in a byte; 44 (300 − 256) is storedUse dw or larger
ld: warning: cannot find entry symbol _startYou wrote main but linked with ld, or forgot global _startld needs _start; gcc needs main
multiple definition of `_start'You wrote _start and linked with gcc, which brings its ownRename the entry point to main and return with ret
undefined reference to `printf'Called a C function but linked with ldLink with gcc -no-pie file.o

NASM reports the file and line before every message (hello.asm:12: error: ...) and keeps going, so fix the first error and re-assemble; later ones are often consequences of it.

The three ways a first program dies: the stack is misaligned at a call (printf crashes), a string is missing its terminating 0 (printf prints garbage), or you wrote mov rsi, [msg] and passed the first eight letters as the address.

Data Movement and Arithmetic

Writing Programs · Assembly 1

Moving Data

InstructionDoesNotes
mov dst, srcCopies src to dstRegister, memory or immediate; not memory to memory; sizes must match
movzx dst, srcCopies a smaller value and fills the top with zerosUnsigned widening: movzx eax, byte [rsi]
movsx dst, srcCopies a smaller value and fills the top with the sign bitSigned widening; movsxd rax, ecx for 32 to 64
lea dst, [expr]Puts the address expr in dstNo memory access; also a fast dst = base + index*scale + k
xchg a, bSwaps two operandsRarely needed; use three movs
push src / pop dstCopies to / from the top of the stack and moves rsp by 8See The Stack
mov rax, 10            ; rax = 10
mov rbx, rax           ; rbx = 10
mov [total], rax       ; store to memory
mov rcx, [total]       ; load from memory
mov eax, [total]       ; load only the low 4 bytes (and clear the top of rax)
lea rax, [rbx + rbx*2] ; rax = 3 * rbx, in one instruction, flags untouched
xor eax, eax           ; rax = 0: shorter than mov rax, 0 and the idiom everyone uses

Add, Subtract and Friends

InstructionDoesFlags
add dst, srcdst = dst + srcZF, SF, CF, OF set from the result
sub dst, srcdst = dst - srcSame; cmp is a sub that throws the result away
inc dst / dec dstdst ± 1Does not touch CF
neg dstdst = -dst (two’s complement)
adc / sbbAdd / subtract with the carryFor numbers wider than 64 bits

C to assembly

; int x = a + b - 7;    (a in rdi, b in rsi)
mov rax, rdi
add rax, rsi
sub rax, 7

; x += 5;     count--;     y = -y;
add qword [x], 5
dec qword [count]
neg rcx

Common mistakes

  • The sizes of the two operands must agree: add rax, ecx is rejected with error: invalid combination of opcode and operands; widen first with movsxd rcx, ecx.
  • An immediate (constant) is at most 32 bits for most instructions, sign-extended. Only mov reg, imm64 takes a full 64-bit constant; add rax, 0x100000000 assembles with warning: signed dword value exceeds bounds and adds the wrong number. Load the constant into a register with mov first.
  • add and sub change the destination and the flags; cmp changes only the flags. Reading add rax, rbx as “rax += rbx” keeps the operand order straight: the destination is on the left in every two-operand instruction.
  • Every arithmetic instruction overwrites the flags. Do the cmp right before the jump that needs it.

Multiply and Divide

Multiplication is friendly; division is the awkward one. Signed division works on the 128-bit pair rdx:rax, so you must sign-extend rax into rdx first with cqo, or zero rdx for unsigned division. Forgetting this is the number one cause of wrong answers and “floating point exception” crashes.

Multiply

imul rax, rbx           ; rax = rax * rbx (signed, low 64 bits)
imul rax, rbx, 10       ; rax = rbx * 10 (three operands)
imul rax, [count]       ; rax = rax * memory
; unsigned full-width: mul rbx   -> rdx:rax = rax * rbx

; multiply by constants without imul:
shl rax, 3              ; rax * 8
lea rax, [rax + rax*4]  ; rax * 5

Divide

; signed:  quotient = rax / divisor, remainder in rdx
mov rax, [dividend]
cqo                     ; sign-extend rax into rdx (rdx:rax)
idiv rbx                ; rax = quotient, rdx = remainder
; idiv by a constant is not allowed: put it in a register first
mov rcx, 10
idiv rcx

; unsigned: zero rdx instead
mov rax, [dividend]
xor edx, edx
div rbx
InstructionBeforeAfterUse for
cqoraxrdx:rax sign-extended64-bit signed division
cdqeaxedx:eax sign-extended32-bit signed division (idiv ecx)
cdqeeaxrax sign-extendedWidening a 32-bit int to 64

Dividing by zero, or a quotient that does not fit, raises an exception and kills the program. Check the divisor first. And remember idiv uses all of rdx:rax: a leftover value in rdx silently gives a huge wrong quotient or a crash.

The crash looks like this in the shell: Floating point exception (core dumped), and echo $? shows 136 (128 + signal 8, SIGFPE), even though no floating point was involved: the CPU raises the same “divide error” for integer division by zero and for a quotient too big for 64 bits. idiv 10 is a different failure, at assembly time: error: invalid combination of opcode and operands, because idiv takes no immediate operand.

A Worked Example: Average of Three

; average = (a + b + c) / 3        a, b, c are qwords in memory; result in rax, remainder in rdx
    mov  rax, [a]
    add  rax, [b]
    add  rax, [c]
    cqo
    mov  rcx, 3
    idiv rcx            ; rax = average (truncated), rdx = remainder
    mov  [avg], rax
; the same routine traced with a = 10, b = 20, c = 35
    mov  rax, [a]       ; rax = 10
    add  rax, [b]       ; rax = 30
    add  rax, [c]       ; rax = 65
    cqo                 ; rdx = 0: rax is positive, so the sign-extension is all zeros
    mov  rcx, 3         ; rcx = 3 (idiv needs the divisor in a register or memory)
    idiv rcx            ; rdx:rax = 65 divided by 3 -> rax = 21, rdx = 2
    mov  [avg], rax     ; avg = 21

; with a = -101 instead: rax = -46, cqo makes rdx all ones (-1),
; idiv gives rax = -15, rdx = -1: the quotient truncates toward zero and
; the remainder takes the sign of the dividend, exactly like C

Two things to notice. add rax, [b] reads memory as the source; the size (8 bytes) comes from rax. And cqo must come after the sum is complete and before idiv: putting mov rcx, 3 between them is harmless, but any instruction that writes rdx there would corrupt the dividend.

Read a routine like this by annotating the register contents after every line in the margin. That habit is the whole skill of reading assembly.

Comparisons and Jumps

Writing Programs · Assembly 1

How Decisions Work

There is no if. A decision is two instructions: a compare that sets the flags, then a conditional jump that changes rip if the flags say so, and otherwise falls through to the next line. Everything higher-level is built from this.

cmp rax, rbx        ; computes rax - rbx, keeps only the flags
je  equal           ; jump if the result was zero (rax == rbx)
; ... code for rax != rbx ...
jmp done            ; unconditional: skip the other branch
equal:
; ... code for rax == rbx ...
done:
After cmp a, bSigned jumpUnsigned jumpReads flags
a == bje (jz)jeZF = 1
a != bjne (jnz)jneZF = 0
a < bjljbSF ≠ OF / CF = 1
a ≤ bjlejbe
a > bjgja
a ≥ bjgejaeSF = OF / CF = 0

Mnemonic: less and greater are signed; below and above are unsigned. Addresses, sizes and counts are unsigned; most arithmetic values are signed.

test, and Jumps Without a cmp

test for bits and zero

test rax, rax       ; AND with itself: sets ZF if rax == 0, SF if negative
jz   is_zero        ; shorter and faster than cmp rax, 0
js   is_negative

test al, 1          ; is the low bit set?
jnz  is_odd

test rdi, rdi       ; the idiom for "is this pointer null?"
je   null_pointer

Flags set by arithmetic

sub rcx, 1          ; the flags already describe rcx
jnz  loop_top       ; so no cmp is needed

dec rcx
jnz  loop_top       ; dec sets ZF too (but not CF)

add rax, rbx
jo   overflow       ; signed overflow happened
jc   carried        ; unsigned carry out
Other conditional jumpsJump when
js / jnsthe result was negative / not negative (SF)
jo / jnosigned overflow / no overflow (OF)
jc / jnccarry / no carry (CF); same as jb / jae
jmpalways; also jmp rax or jmp [table + rcx*8] to a computed address

Translating if, else and &&

if / else if / else

; if (x < 0)       y = -1;
; else if (x == 0) y = 0;
; else             y = 1;          x in rdi, y in rax
    cmp rdi, 0
    jge not_negative
    mov rax, -1
    jmp done
not_negative:
    jne positive
    xor eax, eax
    jmp done
positive:
    mov rax, 1
done:

Compound conditions: jump past the body

; if (x > 0 && x < 10) { body }      x in rdi
    cmp rdi, 0
    jle skip            ; first test false: skip
    cmp rdi, 10
    jge skip            ; second test false: skip
    ; ... body ...
skip:

; if (x < 0 || x > 9) { body }
    cmp rdi, 0
    jl  body            ; first test true: go
    cmp rdi, 9
    jle skip            ; both false: skip
body:
    ; ...
skip:

Conditional moves: no branch at all

; max = (a > b) ? a : b        a in rdi, b in rsi
    mov  rax, rsi
    cmp  rdi, rsi
    cmovg rax, rdi      ; move only if rdi > rsi (signed)

; setcc: a 0/1 result from the flags
    cmp  rdi, rsi
    setl al             ; al = 1 if rdi < rsi, else 0
    movzx eax, al       ; clear the rest of rax

Rules of thumb

  • Write the condition, then jump when it is false to skip the body. That mirrors the C and keeps the code in order.
  • The jump instruction must be the next flag-reading instruction after the cmp or test; anything arithmetic in between clobbers the flags. mov and lea are safe.
  • Every path needs a way out: an if without else falls through, an if/else needs the jmp done or the first branch runs into the second.
  • Label names are free: .loop, .done with a leading dot are local to the nearest non-dot label, so you can reuse them in every routine.

Loops

Writing Programs · Assembly 1

A Loop Is a Backward Jump

A loop is a label, a body, and a conditional jump back to the label. The test can be at the top (a while) or at the bottom (a do-while). Compilers prefer the test at the bottom, with one jump per iteration instead of two.

Instruction in the loops belowDoesFlags
xor eax, eaxrax = 0 (writing eax clears the top half); the idiom for i = 0, sum = 0ZF = 1, CF = OF = 0
cmp rcx, rsiComputes rcx − rsi and throws the result away; neither operand changesSets all of them, for the next jump
jl, jge, jle, jgJump on a signed compare: less, greater-or-equal, … (jb, jae for unsigned counts and addresses)Reads SF, OF, ZF
inc rcx / dec rcxrcx ± 1ZF, SF, OF, but not CF
test rcx, rcxAND of rcx with itself, result discarded: the shortest way to ask “is it zero?”ZF = 1 if rcx == 0, SF = its sign bit
jz / jnzJump if the last result was zero / not zero (same instructions as je / jne)Reads ZF
jmp .topAlways jumpNone
add rax, [rdi + rcx*8]rax += element rcx of a qword array at rdi; the source may be memory, the size comes from raxAll
call printfPush the return address and jump; on return rax, rcx, rdx, rsi, rdi, r8 to r11 may hold anythingAnything

while, test at the top

; while (i < n) { sum += a[i]; i++; }      rdi = a, rsi = n, rcx = i, rax = sum
    xor eax, eax
    xor ecx, ecx
.top:
    cmp rcx, rsi
    jge .done                   ; exit when the condition fails
    add rax, [rdi + rcx*8]
    inc rcx
    jmp .top
.done:

The same loop, test at the bottom

    xor eax, eax
    xor ecx, ecx
    cmp rcx, rsi
    jge .done                   ; guard: skip entirely if n <= 0
.top:
    add rax, [rdi + rcx*8]
    inc rcx
    cmp rcx, rsi
    jl  .top                    ; one jump per iteration
.done:

Counting down to zero

; for (i = n; i > 0; i--) body        rcx = i
    mov rcx, rsi
    test rcx, rcx
    jz  .done
.top:
    ; ... body (must preserve rcx) ...
    dec rcx
    jnz .top                    ; dec sets ZF: no cmp needed
.done:

do-while

; do { x = read(); } while (x != 0);
.again:
    call read_number            ; result in rax
    test rax, rax
    jnz .again

Setting up a loop, step by step

  • 1. Write the C version as a comment above the code: ; while (i < n) { sum += a[i]; i++; }. You will check every instruction against it.
  • 2. Assign a register to every variable and write the map down: ; rdi = a, rsi = n, rcx = i, rax = sum. If the body contains a call, put the counter and the running total in rbx, r12 to r15 instead, because the callee may destroy the others.
  • 3. Initialize before the label: xor eax, eax for the sum, xor ecx, ecx for the counter. Nothing inside the loop may reset them.
  • 4. Guard the zero case if the body must not run when n is 0: cmp rcx, rsi / jge .done (or test rsi, rsi / jz .done) before the label.
  • 5. Label, body, step: .top:, the work, then inc rcx (or add rsi, 8 if you walk a pointer).
  • 6. Compare and jump back with the condition for continuing: cmp rcx, rsi / jl .top means “go again while i < n”. Nothing that changes flags may sit between the cmp and the jump.
  • 7. Trace n = 0, 1 and 2 on paper, writing the registers after every line. This catches the off-by-one (jl versus jle) and a counter that is never stepped before you run anything.

Classic Loop Algorithms

Sum and maximum of an array

; rdi = address of qword array, rsi = count; returns max in rax
array_max:
    mov  rax, [rdi]             ; start with the first element
    mov  rcx, 1
.top:
    cmp  rcx, rsi
    jge  .done
    mov  rdx, [rdi + rcx*8]
    cmp  rdx, rax
    jle  .next                  ; not bigger: skip
    mov  rax, rdx
.next:
    inc  rcx
    jmp  .top
.done:
    ret

Length of a C string

; rdi = address of a 0-terminated string; returns length in rax
strlen:
    xor eax, eax
.top:
    cmp byte [rdi + rax], 0     ; the byte at position rax
    je  .done
    inc rax
    jmp .top
.done:
    ret

Linear search

; rdi = array, rsi = count, rdx = target; returns index in rax or -1
find:
    xor ecx, ecx
.top:
    cmp rcx, rsi
    jge .missing
    cmp [rdi + rcx*8], rdx
    je  .found
    inc rcx
    jmp .top
.found:
    mov rax, rcx
    ret
.missing:
    mov rax, -1
    ret

Nested loops: a multiplication table

; for (r = 1; r <= 3; r++) for (c = 1; c <= 4; c++) print(r*c)
    mov r12, 1                  ; r (callee-saved, survives the call)
.rows:
    mov r13, 1                  ; c
.cols:
    mov rax, r12
    imul rax, r13
    mov rsi, rax
    lea rdi, [fmt]              ; "%4d"
    xor eax, eax
    call printf
    inc r13
    cmp r13, 4
    jle .cols
    ; print newline, then
    inc r12
    cmp r12, 3
    jle .rows

Traps

  • The body clobbers the counter. A call inside the loop may destroy rcx, rdx, rsi, rdi and every other caller-saved register. Keep the counter in rbx, r12 to r15, or on the stack.
  • Off by one. jle versus jl is the difference between <= and <. Trace n = 0 and n = 1 by hand.
  • Wrong signedness. A count compared with jl works until it exceeds 263; an index compared with jb treats -1 as enormous. Pick deliberately.
  • Scale. [rdi + rcx*8] for qwords, *4 for dwords, *1 for bytes. Using the wrong scale reads between elements.
  • The flags are stale. An inc or add between the cmp and the jump changes what the jump sees. Put the compare last.

The loop instruction (decrement rcx, jump if not zero) exists, but it is slow on modern CPUs and compilers never emit it. Use dec rcx / jnz.

Memory, Arrays and Strings

Data and Procedures · Assembly 1

Defining Data

DirectiveReservesExampleMeaning
db1 byte eachmsg db "Hi", 10, 0The bytes 72, 105, 10, 0
dw2 bytes eachports dw 80, 443Two 16-bit values
dd4 bytes eachnums dd 1, 2, 3Three 32-bit ints (a C int array)
dq8 bytes eachbig dq 1 << 40, pi dq 3.1415964-bit ints or doubles
times nrepeatszeros times 10 dq 0Ten qwords of 0
resb / resw / resd / resquninitialized, in .bssbuf resb 256256 bytes, zero at start
equnothing: a constantN equ 100Replaced at assembly time
section .data
    scores  dq  88, 92, 79, 95          ; an array of four qwords
    count   equ ($ - scores) / 8        ; 4, computed by the assembler
    name    db  "Max", 0                ; a C string
    grid    times 3*4 dd 0              ; a 3 by 4 table of dwords

section .bss
    input   resb 128
    total   resq 1
  • scores is 32 bytes long; count equ ($ - scores) / 8 divides that by the element size, so adding a fifth score changes count automatically. $ is the address at the point where it is written.
  • grid times 3*4 dd 0 is 12 dwords; the assembler evaluates 3*4 for you. There is no two-dimensional directive: the row and column arithmetic is yours (see Indexing Arrays).
  • A value that does not fit is a warning, not an error: x db 300 assembles with warning: byte data exceeds bounds and stores 44, which is 300 − 256. Treat that warning as an error.
  • pi dq 3.14159 stores the 8 bytes of a double. Integer instructions such as add will happily operate on them and produce nonsense; floating point needs movsd xmm0, [pi] and the SSE instructions, which are beyond this sheet.
  • Nothing in .bss may have a value; total resq 1 reserves 8 zero bytes and total dq 0 in .data does the same but takes 8 bytes in the executable file.

Indexing Arrays

The address of element i of an array is base + i × element size. The addressing mode does that multiplication for sizes 1, 2, 4 and 8, so an array access is one instruction. For other sizes (a structure of 24 bytes, say) multiply first with imul or lea.

By index

mov rax, [scores + rcx*8]       ; scores[rcx]   (qwords)
mov eax, [grid + rcx*4]         ; grid[rcx]     (dwords, flat)
movzx eax, byte [name + rcx]    ; name[rcx]     (bytes)
mov [scores + rcx*8], rax       ; scores[rcx] = rax

; two-dimensional, row-major: grid[r][c] = base + (r*COLS + c)*4
mov rax, r8                     ; r
imul rax, 4                     ; COLS = 4
add rax, r9                     ; r*COLS + c
mov eax, [grid + rax*4]

By pointer

; walk an array with a moving address
lea rsi, [scores]               ; rsi = &scores[0]
lea rdx, [scores + count*8]     ; one past the end
xor eax, eax
.top:
    cmp rsi, rdx
    jae .done                   ; unsigned: addresses
    add rax, [rsi]
    add rsi, 8                  ; next element
    jmp .top
.done:

Both styles are common. Index form keeps i around for other uses; pointer form saves an instruction per iteration. Compilers emit both.

Strings and Bytes

Upper-case a C string in place

; rdi = string
to_upper:
.top:
    mov al, [rdi]
    test al, al
    jz  .done                   ; the 0 terminator
    cmp al, 'a'
    jb  .next
    cmp al, 'z'
    ja  .next
    and al, 0xDF                ; clear bit 5: 'a' (0x61) -> 'A' (0x41)
    mov [rdi], al
.next:
    inc rdi
    jmp .top
.done:
    ret

Digits to a number (atoi)

; rdi = string of digits; returns value in rax
atoi:
    xor eax, eax
.top:
    movzx ecx, byte [rdi]
    sub   ecx, '0'              ; '0'..'9' -> 0..9
    cmp   ecx, 9
    ja    .done                 ; unsigned: anything not a digit, including the 0 terminator (which went negative = huge)
    imul  rax, 10
    add   rax, rcx
    inc   rdi
    jmp   .top
.done:
    ret

Copy a block of memory

; rdi = destination, rsi = source, rcx = byte count
    rep movsb                   ; the one-instruction memcpy: see the note below

; the long way
.top:
    test rcx, rcx
    jz  .done
    mov al, [rsi]
    mov [rdi], al
    inc rsi
    inc rdi
    dec rcx
    jmp .top
.done:

Little-endian in practice

section .data
    v dq 0x0102030405060708

    mov al,  [v]        ; 0x08: the LOWEST byte is stored first
    mov ax,  [v]        ; 0x0708
    mov eax, [v]        ; 0x05060708
    mov rax, [v]        ; 0x0102030405060708
; gdb: x/8xb &v  prints  08 07 06 05 04 03 02 01

rep movsb is two things: movsb copies the byte at [rsi] to [rdi] and adds 1 to both registers; the rep prefix repeats it rcx times, decrementing rcx to 0. The registers are fixed, which is why the long version above uses the same three. movsq copies 8 bytes at a time (and steps by 8); rep stosb fills rcx bytes at [rdi] with al, the one-instruction memset. The System V convention guarantees the direction flag is clear on entry to every function, so the pointers count upward.

No bounds, no terminator, no mercy. Writing past the end of buf overwrites whatever is next in memory, often the return address on the stack. A string without its 0 byte makes printf and your own loops run into the next variable. These two bugs are the origin of most security holes ever found.

The Stack and Procedures

Data and Procedures · Assembly 1

How the Stack Works

The stack is a region of memory that grows downward: push subtracts 8 from rsp and stores the value there; pop loads from [rsp] and adds 8. rsp always points at the most recently pushed item. It holds return addresses, saved registers and local variables, and it is why recursion works at all.

push rax            ; rsp -= 8 ; [rsp] = rax
push rbx            ; rsp -= 8 ; [rsp] = rbx          (rax is now at [rsp + 8])
mov  rcx, [rsp]     ; peek at the top without popping
pop  rbx            ; rbx = [rsp] ; rsp += 8
pop  rax            ; rax = [rsp] ; rsp += 8           pops come out in REVERSE order

sub rsp, 32         ; reserve 32 bytes of local space (four qwords) in one go
mov [rsp], rax      ; local 0
mov [rsp + 8], rbx  ; local 1
add rsp, 32         ; give it back

call and ret

call square         ; push the address of the NEXT instruction, then jump to square
; ... execution resumes here after ret ...

square:             ; rdi = x ; returns x*x in rax
    mov rax, rdi
    imul rax, rdi
    ret             ; pop the return address into rip

The two rules

  • Every push has a pop, and every sub rsp has an add rsp, before the ret. Otherwise ret pops the wrong thing into rip and the program jumps into garbage.
  • Never write below rsp (at addresses less than rsp). That memory is not yours: a signal or a call may overwrite it at any moment. Reserve space first with sub rsp.

The Stack Frame

A stack frame is the part of the stack belonging to one call: the return address, the caller’s saved rbp, saved registers, and locals. Using rbp as a fixed frame pointer makes locals easy to address while rsp moves around; compilers often skip it, but it is the right way to learn.

The standard prologue and epilogue

my_function:
    ; prologue
    push rbp                ; save the caller's frame pointer
    mov  rbp, rsp           ; this frame starts here
    sub  rsp, 16            ; two qword locals: [rbp - 8] and [rbp - 16]
    push rbx                ; save a callee-saved register we intend to use

    ; body: the locals and arguments by fixed offsets from rbp
    mov  [rbp - 8], rdi     ; local a = first argument
    mov  rbx, [rbp - 8]
    ; [rbp + 8]  is the return address
    ; [rbp + 16] is the first stack-passed argument (the 7th argument, if any)

    ; epilogue: undo everything in reverse
    pop  rbx
    mov  rsp, rbp           ; discard the locals, however many
    pop  rbp
    ret
AddressHoldsWho put it there
[rbp + 16], [rbp + 24] …Arguments 7, 8, … (only if there are more than six)The caller, by pushing before call
[rbp + 8]The return addresscall
[rbp]The caller’s saved rbppush rbp
[rbp - 8], [rbp - 16] …Local variablessub rsp, N
below the locals, down to rspSaved callee-saved registers, temporary pushespush

leave is a one-instruction mov rsp, rbp / pop rbp. enter exists too but is slow; write the prologue out.

Recursion on the Stack

Factorial

; rdi = n ; returns n! in rax
factorial:
    cmp  rdi, 1
    jg   .recurse
    mov  rax, 1                 ; base case
    ret
.recurse:
    push rdi                    ; save n: the recursive call will change rdi
    dec  rdi
    call factorial              ; rax = (n-1)!
    pop  rdi                    ; n is back
    imul rax, rdi               ; n * (n-1)!
    ret

What the stack looks like during factorial(3)

higher addresses
   ...
   return address into main
   3            <- pushed by factorial(3)
   return address into factorial
   2            <- pushed by factorial(2)
   return address into factorial     <- rsp, inside factorial(1)
lower addresses

Each level keeps its own n safe on the stack while the deeper call runs.
Ten thousand levels deep, the stack (usually 8 MB) runs out: a segfault.
  • Anything you need after a call must be in a callee-saved register (rbx, rbp, r12 to r15) or on the stack. Everything else may come back changed.
  • If you use a callee-saved register, you must push it at the start and pop it at the end of your routine, so your caller finds it intact.
  • Match the pushes and pops in the same order reversed. Drawing the stack on paper for each routine is not cheating; it is the method.

Symptoms of a broken stack: ret jumps somewhere random (segfault at a weird address), a variable changes “by itself” after a call, or a recursive routine returns the wrong answer only for n > 1. Check that pushes and pops balance on every path, including early returns.

Calling Conventions: Talking to C

Data and Procedures · Assembly 1

The System V AMD64 Convention

A calling convention is the agreement about where arguments go, where the result comes back, who saves which registers and how the stack is aligned. On Linux and macOS it is System V AMD64. Follow it and your assembly can call any C function, and C can call your assembly.

WhatWhereNotes
Integer / pointer arguments 1 to 6rdi, rsi, rdx, rcx, r8, r9In that order. “Diane’s silk dress costs $89”
Arguments 7 and upPushed on the stack, right to leftAt [rbp + 16], [rbp + 24], … inside the callee
Floating-point argumentsxmm0 to xmm7al = how many, for variadic functions such as printf
Return valuerax (and rdx for 128 bits); xmm0 for doubles
Caller-saved (scratch)rax, rcx, rdx, rsi, rdi, r8 to r11A called function may destroy them; save what you need before the call
Callee-saved (preserved)rbx, rbp, r12 to r15A function that uses them must restore them before ret
Stack alignmentrsp is a multiple of 16 at the moment of every callSo inside a function, right after entry, rsp is 8 mod 16
Red zone128 bytes below rspLeaf functions (that call nothing) may use it without sub rsp

Windows uses a different convention (arguments in rcx, rdx, r8, r9, plus 32 bytes of “shadow space”). If your course uses Visual Studio and MASM, the register names change but the ideas do not.

Calling C from Assembly

add_two.asm: nasm -f elf64 add_two.asm && gcc -no-pie add_two.o -o add_two

default rel
extern printf, scanf
global main

section .data
    prompt  db "Enter two numbers: ", 0
    in_fmt  db "%ld %ld", 0
    out_fmt db "%ld + %ld = %ld", 10, 0

section .bss
    a resq 1
    b resq 1

section .text
main:
    push rbp
    mov  rbp, rsp                 ; rsp is now 16-byte aligned

    lea  rdi, [prompt]
    xor  eax, eax
    call printf

    lea  rdi, [in_fmt]            ; scanf("%ld %ld", &a, &b)
    lea  rsi, [a]                 ; ADDRESSES, because scanf writes into them
    lea  rdx, [b]
    xor  eax, eax
    call scanf

    mov  rsi, [a]                 ; printf("%ld + %ld = %ld\n", a, b, a + b)
    mov  rdx, [b]
    mov  rcx, rsi
    add  rcx, rdx
    lea  rdi, [out_fmt]
    xor  eax, eax
    call printf

    xor  eax, eax                 ; return 0
    pop  rbp
    ret
  • scanf and anything that fills in a result takes addresses (lea); printf takes values (mov from memory).
  • Use %ld for 64-bit values; %d reads or prints only 32 bits.
  • After the call, assume rax, rcx, rdx, rsi, rdi, r8 to r11 are garbage. Here [a] and [b] live in memory, so nothing is lost.
  • Alignment: main starts 8 mod 16; push rbp makes it 0 mod 16; every call above happens with no further pushes, so all are aligned. Push one more register and you must sub rsp, 8 to compensate.

Calling a C function, step by step

  • 1. Declare it at the top of the file: extern printf, and default rel so that lea rdi, [fmt] works in a position-independent executable.
  • 2. Save what you still need. Anything live in rax, rcx, rdx, rsi, rdi, r8 to r11 must be moved to a callee-saved register (rbx, r12 to r15, pushed in your prologue) or to memory, because the callee may overwrite them.
  • 3. Load the arguments, in order: 1st rdi, 2nd rsi, 3rd rdx, 4th rcx, 5th r8, 6th r9. mov for values, lea for addresses (format strings, buffers, anything scanf fills in). A 7th and later are pushed right to left.
  • 4. Set al for a variadic function (printf, scanf): the number of xmm registers holding arguments, so xor eax, eax when there are no doubles. Non-variadic functions ignore it.
  • 5. Check the alignment. rsp must be a multiple of 16 at the call. You enter main 8 off; each push moves 8. An odd number of pushes (counting push rbp) makes it right; otherwise add sub rsp, 8 and undo it afterwards.
  • 6. call the function.
  • 7. Collect the result from rax (xmm0 for a double) before anything else clobbers it, pop any stack arguments with add rsp, 8*k, and remember that the registers from step 2 are now garbage.

Applied to printf("%ld + %ld = %ld\n", a, b, a + b) above: rdi = format, rsi = a, rdx = b, rcx = a + b, al = 0, one push rbp since entry, call printf. The return value (the number of characters printed) is in rax and ignored.

Writing a Function C Can Call

Assembly

; long sum_array(const long *a, long n);
global sum_array
section .text
sum_array:                  ; rdi = a, rsi = n
    xor  eax, eax           ; sum = 0
    test rsi, rsi
    jle  .done
    xor  ecx, ecx           ; i = 0
.top:
    add  rax, [rdi + rcx*8]
    inc  rcx
    cmp  rcx, rsi
    jl   .top
.done:
    ret                     ; result already in rax; nothing to restore

C

#include <stdio.h>

long sum_array(const long *a, long n);   /* defined in sum.asm */

int main(void)
{
    long data[] = { 3, 1, 4, 1, 5, 9 };
    printf("%ld\n", sum_array(data, 6));   /* 23 */
    return 0;
}

/* nasm -f elf64 sum.asm && gcc main.c sum.o -o prog */

A function that needs more registers

; long dot(const long *a, const long *b, long n);
global dot
dot:
    push rbx                ; we will use rbx: callee-saved, so save it
    xor  eax, eax
    xor  ecx, ecx
.top:
    cmp  rcx, rdx
    jge  .done
    mov  rbx, [rdi + rcx*8]
    imul rbx, [rsi + rcx*8]
    add  rax, rbx
    inc  rcx
    jmp  .top
.done:
    pop  rbx                ; restore before returning
    ret

Checklist for a callable routine

  • Arguments arrive in rdi, rsi, rdx, rcx, r8, r9; the result leaves in rax.
  • Push any of rbx, rbp, r12 to r15 you use; pop them in reverse before ret.
  • If you call anything, align the stack (an odd number of pushes, or sub rsp, 8) and keep your own live values in callee-saved registers.
  • Declare the label global, and write the C prototype so the types match the registers you read.

Bit Manipulation and Shifts

Going Deeper · Assembly 1

The Logical Instructions

InstructionEach bit of the result isUse for
and dst, src1 only if both bits are 1Clearing bits, keeping a field (masking), testing
or dst, src1 if either bit is 1Setting bits
xor dst, src1 if the bits differToggling bits; zeroing a register (xor eax, eax); swapping without a temporary
not dstflippedInverting a mask
test a, ban and that only sets flagsIs a bit set? Is the value zero?

Set, clear, toggle, test bit k

or   rax, 1 << 3        ; set bit 3
and  rax, ~(1 << 3)     ; clear bit 3    (~ is NASM's bitwise not, computed at assembly time)
xor  rax, 1 << 3        ; toggle bit 3
test rax, 1 << 3        ; is bit 3 set?  ZF = 0 if so
jnz  .bit_is_set

bt   rax, 3             ; "bit test": copies bit 3 into CF
jc   .bit_is_set
bts  rax, 3             ; test and set ; btr: test and reset ; btc: test and complement

Masks

and  eax, 0xFF          ; keep the low byte (eax = eax mod 256)
and  eax, 0xFFFFFFF0    ; round down to a multiple of 16
and  rsp, -16           ; align the stack pointer down to 16 (-16 = ...FFF0)
mov  edx, eax
shr  edx, 8
and  edx, 0xFF          ; extract the SECOND byte
or   eax, 0x80000000    ; set the sign bit of a 32-bit value

Shifts

InstructionDoesFills withArithmetic meaning
shl dst, k (= sal)Shift left k bitsZeros on the rightMultiply by 2k
shr dst, kShift right k bits, logicalZeros on the leftUnsigned divide by 2k
sar dst, kShift right k bits, arithmeticCopies of the sign bitSigned divide by 2k, rounding toward minus infinity
rol / ror dst, kRotate: bits that fall off come back on the other sideHashing, cryptography
shl dst, clShift by a variable countThe count must be in cl

Powers of two

shl rax, 1              ; rax * 2
shl rax, 4              ; rax * 16
shr rax, 3              ; rax / 8   (unsigned)
sar rax, 3              ; rax / 8   (signed; -9 >> 3 = -2, not -1)

; the compiler's signed division by 8 that rounds toward zero like C:
mov rdx, rax
sar rdx, 63             ; rdx = all ones if negative, else zero
and rdx, 7              ; bias = 7 for negative numbers, 0 otherwise
add rax, rdx
sar rax, 3

Why shifts and masks

  • A shift is one cycle; imul is three or four and idiv twenty to ninety. Compilers turn every multiply or divide by a power of two into shifts.
  • Flags are stored one bit each: a byte holds eight yes/no values, and a mask picks one out.
  • Hardware registers, file permissions (rwxr-xr-x = 0755), network headers and pixel colors (0xRRGGBB) are all bit fields you read with shifts and masks.
  • The last bit shifted out lands in CF, so shr rax, 1 / jc odd tests the low bit.

Worked Examples

Count the 1 bits (population count)

; rdi = value ; returns count in rax
popcount:
    xor eax, eax
.top:
    test rdi, rdi
    jz   .done
    mov  rcx, rdi
    and  rcx, 1             ; the low bit
    add  rax, rcx
    shr  rdi, 1             ; next bit
    jmp  .top
.done:
    ret
; one instruction on modern CPUs: popcnt rax, rdi

Is it a power of two?

; a power of two has exactly one 1 bit, so n & (n - 1) clears it to zero
; rdi = n ; returns 1 in rax if a power of two, else 0
is_pow2:
    xor  eax, eax
    test rdi, rdi
    jz   .done              ; 0 is not a power of two
    lea  rcx, [rdi - 1]
    test rdi, rcx
    setz al                 ; al = 1 if (n & (n-1)) == 0
.done:
    ret

Pack and unpack a color

; rgb = (r << 16) | (g << 8) | b          r, g, b in edi, esi, edx (0..255)
    mov  eax, edi
    shl  eax, 16
    shl  esi, 8
    or   eax, esi
    or   eax, edx           ; eax = 0x00RRGGBB

; green = (rgb >> 8) & 0xFF
    mov  ecx, eax
    shr  ecx, 8
    and  ecx, 0xFF

Swap two registers with xor

xor rax, rbx
xor rbx, rax
xor rax, rbx            ; rax and rbx have traded values, no temporary needed
; (a classic trick; on real CPUs three movs or xchg are just as fast)

shr on a signed number is wrong. -8 shr 1 is a huge positive number, not -4. Use sar for signed values, shr for unsigned, and remember that C’s / rounds toward zero while sar rounds down, which is why compilers add the bias shown above.

Reading Compiler Output and AT&T Syntax

Going Deeper · Assembly 1

Seeing What the Compiler Did

The payoff of the course: take C you understand, ask the compiler for the assembly, and recognize every construct from the earlier tabs. gcc -S produces AT&T syntax by default; -masm=intel gives the syntax used on this sheet.

Commands

gcc -O1 -S -masm=intel -fno-asynchronous-unwind-tables sum.c      # writes sum.s, readable
gcc -O0 -S sum.c                       # unoptimized: every variable lives on the stack, easiest to map to the C
gcc -O2 -S sum.c                       # optimized: what ships; loops rewritten, variables in registers
objdump -d -M intel prog | less        # disassemble a finished executable
gdb ./prog  ->  disassemble main       # or inside the debugger

C

long sum(const long *a, long n)
{
    long total = 0;
    for (long i = 0; i < n; i++)
        total += a[i];
    return total;
}

gcc -O1 -masm=intel (lightly cleaned)

sum:
    test rsi, rsi            ; if (n <= 0) goto zero
    jle  .L4
    mov  eax, 0              ; total = 0
    mov  edx, 0              ; i = 0
.L3:
    add  rax, [rdi + rdx*8]  ; total += a[i]
    add  rdx, 1              ; i++
    cmp  rsi, rdx
    jne  .L3                 ; loop while i != n  (the compiler knows i never passes n)
    ret
.L4:
    mov  eax, 0
    ret

Notice: the test moved to the bottom, i < n became i != n, mov eax, 0 is used because writing eax clears rax in fewer bytes, and nothing touched the stack because the function is a leaf with everything in registers.

Recognizing Constructs

In the CIn the assemblyTell-tale signs
if / elsecmp or test + a conditional jump that skips a block; jmp over the elseTwo labels close together
? : or a small if assigning one valuecmovcc or setccNo jump at all
while / forA label, a body, a cmp and a jump backward; often a guard jump before the labelA jump to a lower address
switch with dense casesA bounds check, then jmp [table + rax*8]: a jump table.rodata holds a list of label addresses
Function callArguments into rdi, rsi, …; call; result read from raxPushes of callee-saved registers at the start of the callee
Local variables at -O0[rbp - 8], [rbp - 12], …Loads before every use, stores after
Array indexing[base + index*8] or a pointer that advances by 8lea computing addresses
x * 10, x / 8, x % 16lea + shl; sar with a bias; and with 15No imul or idiv for constants
struct field accessA fixed displacement: [rdi + 16]Offsets are multiples of the field sizes
Returning a valueLast write to rax (or eax) before ret

A switch becomes a jump table

; switch (x) { case 0: ... case 1: ... case 2: ... default: ... }
    cmp  rdi, 2
    ja   .default           ; unsigned compare handles negatives too
    jmp  [.table + rdi*8]
.table: dq .case0, .case1, .case2
.case0: ...

A struct and a pointer

; struct point { long x; long y; };  long sum(struct point *p) { return p->x + p->y; }
sum:
    mov rax, [rdi]          ; p->x  (offset 0)
    add rax, [rdi + 8]      ; p->y  (offset 8)
    ret

AT&T Syntax: The Other Spelling

gcc, objdump and gdb default to AT&T syntax, used by the GNU assembler. Same instructions, different spelling. Four rules convert one to the other.

RuleIntel (NASM, this sheet)AT&T (gas, gcc -S)
Operand order is reversed: source first, destination lastmov rax, rbxmovq %rbx, %rax
Registers get %, immediates get $mov rax, 5movq $5, %rax
The size is a suffix on the mnemonic: b, w, l, qmov dword [rbx], 1movl $1, (%rbx)
Memory is disp(base, index, scale)mov rax, [rdi + rcx*8 + 16]movq 16(%rdi, %rcx, 8), %rax
Variables by namemov rax, [count] / lea rax, [rel count]movq count(%rip), %rax / leaq count(%rip), %rax
Comments; text# text
Jumps and callsthe samethe same; indirect ones get a *: jmp *%rax

Intel (NASM): the same square() function

; Intel (NASM)
    push rbp
    mov  rbp, rsp
    mov  dword [rbp - 4], edi
    mov  eax, [rbp - 4]
    imul eax, eax
    pop  rbp
    ret

AT&T (gas)

# AT&T (gas)
    pushq %rbp
    movq  %rsp, %rbp
    movl  %edi, -4(%rbp)
    movl  -4(%rbp), %eax
    imull %eax, %eax
    popq  %rbp
    ret
  • Read AT&T left to right as “move this into that”; read Intel as “set that to this”.
  • When a listing has % signs, it is AT&T. Flip the operands in your head before anything else.
  • gdb: set disassembly-flavor intel switches it permanently (put it in ~/.gdbinit).
  • Textbooks: Computer Systems: A Programmer’s Perspective uses AT&T; most NASM tutorials and Intel’s manuals use Intel. You will meet both, and after a week you stop noticing.

The single most common reading error is applying one syntax’s operand order to the other. mov rax, rbx and movq %rax, %rbx look alike and do opposite things.