Loops
In Assembly, a loop decrements ECX register. When ECX==0, loop will end.
We can make a loop using either control instructions like jmp, jnz etc (like in last page) or we can also use the loop instruction as well!
Make sure we preserve ecx throughout the program. Use stack to do this.
Question: Write a loop to display "hello world" 10 times using a loop.
As we can see here, I am using the rax technique as in last article to loop. Let us use the instruction "loop" to re-write this:
Using loop instruction, we are utilizing rcx, avoiding the risk of spoiling rax. We are also reducing the hassle of decrementing rax on loops. Finally, we are simplifying some logic too.
Please note, if we don't preserve rcx here, after the write syscall, rcx will become all f's. This would become an infinite loop. So we have to preserve this value manually using a stack.
There are some variations of loop as well: LOOPE, LOOPNE, LOOPNZ, LOOPZ Ref Page 652 of the intel manual (https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-vol-3c-part-3-manual.pdf)
Rep can also be used to loop through. Majorly used in string operations
Last updated