Reversing : The Hacker's Guide to Reverse Engineering

(ff) #1
mov ecx, DWORD PTR [array]
xor eax, eax
LoopStart:
mov DWORD PTR [ecx+eax*4], eax
add eax, 1
cmp eax, 1000
jl LoopStart

It appears that even though the condition in the source code was located
beforethe loop, the compiler saw fit to relocate it. The reason that this happens
is that testing the counter after the loop provides a (relatively minor) perfor-
mance improvement. As I’ve explained, converting this loop to a posttested
one means that the compiler can eliminate the unconditional JMPinstruction
at the end of the loop.
There is one potential risk with this implementation. What happens if the
counter starts out at an out-of-bounds value? That could cause problems
because the loop body uses the loop counter for accessing an array. The pro-
grammer was expecting that the counter be tested before running the loop
body, not after! The reason that this is not a problem in this particular case is
that the counter is explicitly initialized to zero before the loop starts, so the
compiler knows that it is zero and that there’s nothing to check. If the counter
were to come from an unknown source (as a parameter passed from some
other, unknown function for instance), the compiler would probably place the
logic where it belongs: in the beginning of the sequence.
Let’s try this out by changing the above C loop to take the value of counter
cfrom an external source, and recompile this sequence. The following is the
output from the Microsoft compiler in this case:

mov eax, DWORD PTR [c]
mov ecx, DWORD PTR [array]
cmp eax, 1000
jge EndOfLoop
LoopStart:
mov DWORD PTR [ecx+eax*4], eax
add eax, 1
cmp eax, 1000
jl LoopStart
EndOfLoop:

It seems that even in this case the compiler is intent on avoiding the two
jumps. Instead of moving the comparison to the beginning of the loop and
adding an unconditional jump at the end, the compiler leaves everything as it
is and simply adds another condition at the beginning of the loop. This initial
check (which only gets executed once) will make sure that the loop is not
entered if the counter has an illegal value. The rest of the loop remains the same.

Deciphering Code Structures 505

21_574817 appa.qxd 3/16/05 8:54 PM Page 505

Free download pdf