Reverse Engineering for Beginners

(avery) #1

CHAPTER 39. LOOPS: SEVERAL ITERATORS CHAPTER 39. LOOPS: SEVERAL ITERATORS


Chapter 39


Loops: several iterators


In most cases loops have only one iterator, but there could be several in the resulting code.


Here is a very simple example:


#include <stdio.h>


void f(int a1, int a2, size_t cnt)
{
size_t i;


// copy from one array to another in some weird scheme
for (i=0; i<cnt; i++)
a1[i3]=a2[i7];
};


There are two multiplications at each iteration and they are costly operations. Can we optimize it somehow? Yes, if we
notice that both array indices are jumping on values that we can easily calculate without multiplication.


39.1 Three iterators


Listing 39.1: Optimizing MSVC 2013 x64

f PROC
; RDX=a1
; RCX=a2
; R8=cnt
test r8, r8 ; cnt==0? exit then
je SHORT $LN1@f
npad 11
$LL3@f:
mov eax, DWORD PTR [rdx]
lea rcx, QWORD PTR [rcx+12]
lea rdx, QWORD PTR [rdx+28]
mov DWORD PTR [rcx-12], eax
dec r8
jne SHORT $LL3@f
$LN1@f:
ret 0
f ENDP


Now there are 3 iterators: thecntvariable and two indices, which are increased by 12 and 28 at each iteration. We can
rewrite this code in C/C++:


#include <stdio.h>


void f(int a1, int a2, size_t cnt)
{
size_t i;
size_t idx1=0; idx2=0;


// copy from one array to another in some weird scheme
Free download pdf