Reverse Engineering for Beginners

(avery) #1

CHAPTER 18. ARRAYS CHAPTER 18. ARRAYS


};


char get_by_coordinates2 (char array, int a, int b)
{
// treat input array as one-dimensional
// 4 is array width here
return array[a
4+b];
};


char get_by_coordinates3 (char array, int a, int b)
{
// treat input array as pointer,
// calculate address, get value at it
// 4 is array width here
return
(array+a*4+b);
};


int main()
{
a[2][3]=123;
printf ("%d\n", get_by_coordinates1(a, 2, 3));
printf ("%d\n", get_by_coordinates2(a, 2, 3));
printf ("%d\n", get_by_coordinates3(a, 2, 3));
};


Compile and run it: it shows correct values.


What MSVC 2013 did is fascinating, all three routines are just the same!


Listing 18.22: Optimizing MSVC 2013 x64

array$ = 8
a$ = 16
b$ = 24
get_by_coordinates3 PROC
; RCX=address of array
; RDX=a
; R8=b
movsxd rax, r8d
; EAX=b
movsxd r9, edx
; R9=a
add rax, rcx
; RAX=b+address of array
movzx eax, BYTE PTR [rax+r94]
; AL=load byte at address RAX+R9
4=b+address of array+a4=address of array+a4+b
ret 0
get_by_coordinates3 ENDP


array$ = 8
a$ = 16
b$ = 24
get_by_coordinates2 PROC
movsxd rax, r8d
movsxd r9, edx
add rax, rcx
movzx eax, BYTE PTR [rax+r9*4]
ret 0
get_by_coordinates2 ENDP


array$ = 8
a$ = 16
b$ = 24
get_by_coordinates1 PROC
movsxd rax, r8d
movsxd r9, edx
add rax, rcx
movzx eax, BYTE PTR [rax+r9*4]
ret 0
get_by_coordinates1 ENDP

Free download pdf