Here's a complete AT&T-style assembly implementation of a for loop, written for a 32-bit Linux environment using the int 0x80 system call interface. This example demonstrates a loop that runs from 0 to 9, and in the loop body, it adds the current loop index to a sum variable stored in memory.
✅ AT&T Assembly Code: For Loop Implementation
asm
.section .data
sum: .long 0 # Define a 32-bit variable to store the sum
.section .text
.global _start
_start:
# Initialize loop counter and sum
movl $0, %ecx # Counter (i = 0)
movl $0, %eax # Sum (sum = 0)
# Jump to loop condition check
jmp loop_start
loop_start:
# Compare counter with 10
cmpl $10, %ecx
jge loop_end # If i >= 10, exit loop
# Loop body: add current counter to sum
addl %ecx, sum # sum += i
# Increment counter
incl %ecx
# Jump back to the top of the loop
jmp loop_start
loop_end:
# Exit the program
movl $1, %eax # sys_exit
xorl %ebx, %ebx # exit code 0
int $0x80
📌 Explanation
Registers Used:
%ecx → Loop counter (i)
%eax → Accumulator (used to store the sum)
%ebx → Exit status (set to 0)
Loop Structure:
Initialization: movl $0, %ecx sets the loop counter to 0.
Condition Check: cmpl $10, %ecx compares the counter with 10. If it's greater than or equal to 10, the loop exits via jge loop_end.
Loop Body: addl %ecx, sum adds the current counter value to the sum variable.
Increment: incl %ecx increases the counter.
Jump Back: jmp loop_start returns to the top of the loop.
System Call:
movl $1, %eax sets the system call number for sys_exit.
xorl %ebx, %ebx sets the exit status to 0.
int $0x80 triggers the system call.
🧠 Notes
This code uses AT&T syntax, where the source operand comes after the destination (e.g., movl $0, %ecx).
The .data section contains the sum variable, which is a 32-bit integer.
The loop runs from i = 0 to i = 9, and the total sum is 0 + 1 + 2 + ... + 9 = 45.
🧪 Example Output
If you assemble and run this code, it will compute the sum of integers from 0 to 9 and exit cleanly with status 0. You can verify the result using a debugger or by inspecting the sum variable in memory.