Reverse Engineering for Beginners

(avery) #1

CHAPTER 14. LOOPS CHAPTER 14. LOOPS


Chapter 14


Loops


14.1 Simple example


14.1.1 x86


There is a specialLOOPinstruction in x86 instruction set for checking the value in registerECXand if it is not 0, todecrement
ECXand pass control flow to the label in theLOOPoperand. Probably this instruction is not very convenient, and there are
no any modern compilers which emit it automatically. So, if you see this instruction somewhere in code, it is most likely that
this is a manually written piece of assembly code.


In C/C++ loops are usually constructed usingfor(),while()ordo/while()statements.


Let’s start withfor().


This statement defines loop initialization (set loop counter to initial value), loop condition (is the counter bigger than a
limit?), what is done at each iteration (increment/decrement) and of course loop body.


for (initialization; condition; at each iteration)
{
loop_body;
}


The generated code is consisting of four parts as well.


Let’s start with a simple example:


#include <stdio.h>


void printing_function(int i)
{
printf ("f(%d)\n", i);
};


int main()
{
int i;


for (i=2; i<10; i++)
printing_function(i);

return 0;
};


Result (MSVC 2010):


Listing 14.1: MSVC 2010

_i$ = -4
_main PROC
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _i$[ebp], 2 ; loop initialization
jmp SHORT $LN3@main

Free download pdf