Reversing : The Hacker's Guide to Reverse Engineering

(ff) #1
Here is the same code with a slight modification:

mov eax, DWORD PTR [c]
mov ecx, DWORD PTR [array]
LoopStart:
cmp DWORD PTR [ecx+eax*4], 0
jne NextCycle
mov DWORD PTR [ecx+eax*4], eax
NextCycle:
add eax, 1
cmp eax, 1000
jl SHORT LoopStart

The only difference here is that NextCycleis now placed earlier, before the
counter-incrementing code. This means that unlike before, the continue
statement will increment the counter andrun the loop’s logic. This indicates
that the loop was probably implemented using the forkeyword. Another
way of implementing this type of sequence without using a forloop is by
using a whileor do...whileloop and incrementing the counter insidethe
conditional statement, using the ++operator. In this case, the logical statement
would look like this:

do { ... } while (++c < 1000);

Loop Unrolling

Loop unrolling is a code-shaping level optimization that is not CPU- or
instruction-set-specific, which means that it is essentially a restructuring of the
high-level code aimed at producing more efficient machine code. The follow-
ing is an assembly language example of a partially unrolled loop:

xor ecx,ecx
pop ebx
lea ecx,[ecx]
LoopStart:
mov edx,dword ptr [esp+ecx*4+8]
add edx,dword ptr [esp+ecx*4+4]
add ecx,3
add edx,dword ptr [esp+ecx*4-0Ch]
add eax,edx
cmp ecx,3E7h
jl LoopStart

This loop is clearly a partially unrolled loop, and the best indicator that this
is the case is the fact that the counter is incremented by three in each iteration.
Essentially what the compiler has done is it duplicated the loop’s body three

508 Appendix A

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

Free download pdf