Lesson 3 of 8

Control flow in assembly

Goal

Compare and jump instead of if and loops

01

Explanation

Assembly has no if statement and no while loop, only a comparison followed by a jump. The cmp a, b instruction compares the two and stores the result in flags inside the CPU, and the conditional jump after it reads those flags: either it jumps to a label, or execution continues to the next line.

  • jg jumps if the first is greater, and jle if it's less than or equal.
  • je jumps if the two are equal, and jne if they differ.
  • jmp always jumps, with no condition.

These jumps treat the numbers as signed, meaning they take into account that a number may be negative, and they have unsigned counterparts such as ja and jb. When you look at assembly, the first question to ask is when it jumps, because compilers usually emit a jump that skips over the body of an if when its condition is false, so the jump carries the opposite condition:

h:
  cmp  edi, 10
  jle  .small
  mov  eax, 1
  ret
.small:
  mov  eax, 0
  ret

So jle .small means: if x is less than or equal to ten, go to .small and return 0; otherwise continue to the next line and return 1.

A loop is a jump backward. In this function, eax holds the sum and ecx holds the counter. The instruction xor eax, eax is the shorthand compilers use to zero a register, and inc adds one. The jg .done jump takes you out of the loop once the counter exceeds n, and jmp .top takes you back to its start:

loop_sum:
  xor  eax, eax   ; eax = 0
  mov  ecx, 1     ; ecx = 1
.top:
  cmp  ecx, edi
  jg   .done      ; ecx > n
  add  eax, ecx   ; eax += ecx
  inc  ecx        ; ecx += 1
  jmp  .top
.done:
  ret

Before you write anything, think about what the loop does when n is zero or negative. The assembly is what counts, not the function's name or what you expect it to do.

02

Your task

Write the function h(x) that returns 1 if x is greater than ten and 0 otherwise, and the function loop_sum(n) that matches the loop above in every case, including zero and negative numbers.

Checks

6 checks
  1. h returns 1 for values above ten
  2. h returns 0 for ten itself
  3. h matches the assembly on many numbers
  4. loop_sum adds up 1 through n
  5. loop_sum works on other values
  6. loop_sum returns 0 for a negative number, as the loop does
03

Hints

0/3
Track lessons0 of 8 done

Read assembly, calling conventions and control flow, then build a disassembler and an emulator for a tiny machine, patch its bytes and check their integrity.

Intermediate level, 8 lessons, 2 hours in total.

main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Read assembly, calling conventions and control flow, then build a disassembler and an emulator for a tiny machine, patch its bytes and check their integrity.

Intermediate level, 8 lessons, 2 hours in total.