Control Flow Challenge
Time to wire it all together. In this lesson you'll write a full program that sorts integers into buckets using comparisons, loops, and conditionals. No new instructions — your first synthesis exercise, built entirely from pieces you already know.
The Challenge: Number Classifier
Write a program that walks an array of integers and bins each one into three categories:
- Negative - the value is less than zero
- Zero - the value is exactly zero
- Positive - the value is greater than zero
Tally up how many values land in each bucket, then print the totals.
Step 1: Define the Data
Set up the data section with test values and the labels we'll print alongside them:
SYS_WRITE equ 1SYS_EXIT equ 60STDOUT equ 1
section .data ; Test data: a mix of negative, zero, and positive values values dq -5, 3, 0, -1, 7, 0, -3, 12, 0, 4 num_values equ 10
; Output messages msg_neg db "Negative count: " msg_neg_len equ $ - msg_neg msg_zero db "Zero count: " msg_zero_len equ $ - msg_zero msg_pos db "Positive count: " msg_pos_len equ $ - msg_pos newline db 10
section .bss ; Buffer for converting numbers to ASCII numbuf resb 4Step 2: The Classification Loop
The core loop steps through the array and branches three ways on each value:
section .text global _start
_start: ; Initialize counters xor r12, r12 ; r12 = negative count xor r13, r13 ; r13 = zero count xor r14, r14 ; r14 = positive count xor rcx, rcx ; rcx = loop index lea rsi, [rel values] ; rsi = pointer to array
.classify_loop: cmp rcx, num_values jge .print_results ; done classifying
mov rax, [rsi + rcx*8] ; load values[rcx] ; Three-way branch: negative, zero, or positive test rax, rax js .is_negative ; sign flag set = negative jz .is_zero ; zero flag set = zero ; Falls through to positive inc r14 ; positive_count++ jmp .next
.is_negative: inc r12 ; negative_count++ jmp .next
.is_zero: inc r13 ; zero_count++
.next: inc rcx jmp .classify_loopNotice TEST rax, rax rather than CMP rax, 0. Both work; TEST is the idiomatic way to probe a register for zero or negativity. SF flags negativity, ZF flags zero. Neither set? The value is positive.
Step 3: Integer-to-ASCII Conversion
To print the counts you need to turn integers into ASCII digit characters — one of the bread-and-butter routines in assembly:
; Convert a single digit (0-9) to ASCII and write it; Input: rdi = value (0-9); Clobbers: rax, rdx, rsiprint_digit: add rdi, '0' ; convert to ASCII ('0' = 0x30) mov [rel numbuf], dil ; store the ASCII digit mov rax, SYS_WRITE mov rdi, STDOUT lea rsi, [rel numbuf] mov rdx, 1 syscall retOur test data only produces single-digit counts (0-9), so this minimal conversion works. Real code would loop, dividing by 10 each iteration to peel off digits.
Step 4: Print the Results
.print_results: ; Print "Negative count: N\n" mov rax, SYS_WRITE mov rdi, STDOUT lea rsi, [rel msg_neg] mov rdx, msg_neg_len syscall mov rdi, r12 ; negative count call print_digit mov rax, SYS_WRITE mov rdi, STDOUT lea rsi, [rel newline] mov rdx, 1 syscall
; Print "Zero count: N\n" mov rax, SYS_WRITE mov rdi, STDOUT lea rsi, [rel msg_zero] mov rdx, msg_zero_len syscall mov rdi, r13 ; zero count call print_digit mov rax, SYS_WRITE mov rdi, STDOUT lea rsi, [rel newline] mov rdx, 1 syscall
; Print "Positive count: N\n" mov rax, SYS_WRITE mov rdi, STDOUT lea rsi, [rel msg_pos] mov rdx, msg_pos_len syscall mov rdi, r14 ; positive count call print_digit mov rax, SYS_WRITE mov rdi, STDOUT lea rsi, [rel newline] mov rdx, 1 syscall
; Exit mov rax, SYS_EXIT xor rdi, rdi syscallExpected Output
With the test data {-5, 3, 0, -1, 7, 0, -3, 12, 0, 4}:
Negative count: 3Zero count: 3Positive count: 4Extension Challenge: Branchless Classification
Can you redo the classification with SETcc (or CMOVcc) and zero conditional jumps? Sketch:
; Branchless classification of value in rax; Uses SETcc to determine category without branching
; Prepare potential increments xor r8, r8 ; will be 1 if negative, else 0 xor r9, r9 ; will be 1 if zero, else 0 xor r10, r10 ; will be 1 if positive, else 0
test rax, rax sets r8b ; r8b = 1 if negative (SF set) setz r9b ; r9b = 1 if zero (ZF set) setg r10b ; r10b = 1 if positive (not negative, not zero) ; Note: setg checks "greater than 0" which means SF=OF and ZF=0
add r12, r8 ; negative_count += (is_negative ? 1 : 0) add r13, r9 ; zero_count += (is_zero ? 1 : 0) add r14, r10 ; positive_count += (is_positive ? 1 : 0)Every input runs the same instructions inside the loop body. No branches on the value, so no mispredictions that depend on it.
For this exercise, timing doesn't matter at all: the test values sit in the binary and nobody's trying to hide them. Branch-free code only buys you security when the data being branched on is a secret the attacker wants and they can time your code while it runs on that secret. Key bytes, password comparisons and secret-dependent table lookups are the classic cases. Note also that the loop around the sketch still branches on the index, which is fine because the index isn't secret. It's the same principle that keeps cryptographic code safe from timing side-channels, applied to a toy.
Debugging Tips
When the program misbehaves:
-
Check your flags logic. Signed (JG/JL) or unsigned (JA/JB)? Signed integers need the signed flavour.
-
Watch for clobbered registers.
syscalltrashesrcxandr11. Ifrcxis your loop counter, stash it before the syscall and restore it after. -
Reach for strace.
strace ./classifierprints every syscall with arguments and return value — the fastest way to spot a bad pointer or wrong size. -
Drop into GDB.
break _start, thenstepiyour way through.info registersshows you the current CPU state at any point.
# Build and runnasm -f elf64 classifier.asm -o classifier.old classifier.o -o classifier./classifier
# Debug with GDBgdb ./classifier(gdb) break _start(gdb) run(gdb) stepi(gdb) info registersTry It Yourself
Pop open the sandbox and build the classifier. Twiddle the test data, add categories like even/odd, or take a swing at the branchless version.
Practise on your own machine
You need Linux on x86-64: a virtual machine, WSL 2 on Windows, or a container. Then install the tools with sudo apt install nasm gcc gdb binutils.
What is Next
You've now got the foundations of x86-64 under your belt: registers, data movement, arithmetic, control flow. The next module digs into the stack and calling conventions — the machinery that makes functions, recursion, and C interop work at all. The stack is also exploit ground zero, so for security work you'll want to know it cold.
Challenges
Write a program that computes the sum of integers from 1 to 10 using a loop, then prints the result (55) followed by a newline.