Reverse Engineering for Beginners

(avery) #1

CHAPTER 12. CONDITIONAL JUMPS CHAPTER 12. CONDITIONAL JUMPS


12.2 Calculating absolute value.


A simple function:


int my_abs (int i)
{
if (i<0)
return -i;
else
return i;
};


12.2.1 Optimizing MSVC.


This is how the code is usually generated:


Listing 12.13: Optimizing MSVC 2012 x64

i$ = 8
my_abs PROC
; ECX = input
test ecx, ecx
; check for sign of input value
; skip NEG instruction if sign is positive
jns SHORT $LN2@my_abs
; negate value
neg ecx
$LN2@my_abs:
; prepare result in EAX:
mov eax, ecx
ret 0
my_abs ENDP


GCC 4.9 does mostly the same.


12.2.2 Optimizing Keil 6/2013: Thumb mode


Listing 12.14: Optimizing Keil 6/2013: Thumb mode

my_abs PROC
CMP r0,#0
; is input value equal to zero or greater than zero?
; skip RSBS instruction then
BGE |L0.6|
; subtract input value from 0:
RSBS r0,r0,#0
|L0.6|
BX lr
ENDP


ARM lacks a negate instruction, so the Keil compiler uses the “Reverse Subtract” instruction, which just subtracts with reversed
operands.


12.2.3 Optimizing Keil 6/2013: ARM mode.


It is possible to add condition codes to some instructions in ARM mode, so that is what the Keil compiler does:


Listing 12.15: Optimizing Keil 6/2013: ARM mode

my_abs PROC
CMP r0,#0
; execute "Reverse Subtract" instruction only if input value is less than 0:
RSBLT r0,r0,#0
BX lr
ENDP


Now there are no conditional jumps and this is good:33.1 on page 436.

Free download pdf