In Assembly there is a keyword command called “loops,” which iterates over a function/block, decrementing a counter each time and this repeats until the counter reaches 0.
It is important to remember that the counter is stored in ECX/RCX – this is where the loop command looks to find how many times it will iterate.
My Example Loop
I’ve added some code below to illustrate a loop in Assembly. In this case, the Assembly script will set the value 1 to RAX, then add 1 to that value 10 times:
; Author: Brian Warner ; Website: http://sdet.us ; global _start section .text _start: mov rax, 0x1 mov rcx, 10 Count: add rax, 0x1 loop Count mov rax, 60 mov rdi, 0 syscall
As you can see in the code above, the script itself is initializing rax and rcx. RAX is set to 1 and RCX is set to 10. We move into the Count: function which runs the command add on RAX with a value of 1 (so we’ll be adding 1 to whatever is in RAX.)
Next I invoke the loop keyword and declare it to run on the Count function.
If all goes well, we should see the rax register increment by 1 each time and the RCX value decrement by 1. When RCX reaches 0, we will break out of the loop and the run the last few lines of the script (which tells the application to invoke a syscall to exit the app.)
Running the Script into GDB
Once the script is started we see that rax is first set to 1:
Next RCX is set to 10:
Now we add 1 to RAX:
This will repeat until RCX reaches 0… when it reaches 0, we should see RAX update to a value of 60:
Similar to loops, there is a way to run a function until a condition is met. These are conditional jumps. A non-conditional jump is the basic JMP command in Assembly (which says “goto this location.”) A conditional jump can work the above script like so:
; Author: Brian Warner ; Website: http://sdet.us ; global _start section .text _start: mov rax, 0x9 ; set rax to the value 9. Count: dec rax ; decrement rax by 1. jnz Count ; jnz = jump while not zero. mov rax, 60 ; once rax is 0 we move to this line. mov rdi, 0 syscall
I’ve added some comments in the modified script. It clearly uses a conditional jump (jnz) to repeat the Count function as long as rax remains a non zero. Once it becomes 0, we exit the loop and RAX is set to 60 (the syscall to close the application, RDI is set to 0… which is our chosen exit code and we exit.)