w1coding.comAll tutorials

Assembly Execution

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

Conditional Execution

Conditional execution in assembly is achieved using conditional jump instructions. These instructions allow branching based on the results of comparisons or arithmetic operations.

Common Conditional Jump Instructions

  • je: Jump if equal (zero flag is set).
  • jne: Jump if not equal (zero flag is not set).
  • jg: Jump if greater (signed).
  • jl: Jump if less (signed).
  • jge: Jump if greater or equal (signed).
  • jle: Jump if less or equal (signed).
  • ja: Jump if above (unsigned).
  • jb: Jump if below (unsigned).

Example: Comparing Two Numbers

This example demonstrates comparing two numbers and branching based on the result.

section .text
    global _start

_start:
    mov rax, 10       ; Load the first number into rax
    mov rbx, 20       ; Load the second number into rbx

    cmp rax, rbx      ; Compare rax and rbx
    jl less           ; Jump to 'less' if rax < rbx
    jg greater        ; Jump to 'greater' if rax > rbx
    je equal          ; Jump to 'equal' if rax == rbx

less:
    ; Code for less condition
    mov rax, 1        ; System call: exit
    xor rdi, rdi
    syscall

greater:
    ; Code for greater condition
    mov rax, 60       ; System call: exit
    xor rdi, rdi
    syscall

equal:
    ; Code for equal condition
    mov rax, 60       ; System call: exit
    xor rdi, rdi
    syscall
    

Example: Looping with Conditional Execution

Conditional jumps are commonly used to implement loops.

section .data
    counter db 5        ; Initialize counter with 5

section .text
    global _start

_start:
    mov rbx, 0          ; Initialize sum to 0
    mov rsi, counter    ; Load counter address

loop_start:
    cmp byte [rsi], 0   ; Check if counter is 0
    je loop_end         ; Exit loop if counter == 0

    add rbx, [rsi]      ; Add counter value to sum
    dec byte [rsi]      ; Decrement counter
    jmp loop_start      ; Repeat loop

loop_end:
    mov rax, 60         ; System call: exit
    xor rdi, rdi        ; Exit code: 0
    syscall
    

Key Notes

  • Use cmp to compare two values before conditional jumps.
  • Make sure to handle all possible conditions to avoid unexpected behavior.
  • Keep your code readable by properly labeling your jump targets.