Reverse Engineering for Beginners

(avery) #1

CHAPTER 12. CONDITIONAL JUMPS CHAPTER 12. CONDITIONAL JUMPS


There is one unneededJMPinstruction in each function, which MSVC probably left by mistake.


Branchless


ARM for Thumb mode reminds us of x86 code:


Listing 12.27: Optimizing Keil 6/2013 (Thumb mode)

my_max PROC
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; branch if A is greater then B:
BGT |L0.6|
; otherwise (A<=B) return R1 (B):
MOVS r0,r1
|L0.6|
; return
BX lr
ENDP


my_min PROC
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; branch if A is less then B:
BLT |L0.14|
; otherwise (A>=B) return R1 (B):
MOVS r0,r1
|L0.14|
; return
BX lr
ENDP


The functions differ in the branching instruction: BGT and BLT.


It’s possible to use conditional suffixes in ARM mode, so the code is shorter. MOVcc is to be executed only if the condition
is met:


Listing 12.28: Optimizing Keil 6/2013 (ARM mode)

my_max PROC
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; return B instead of A by placing B in R0
; this instruction will trigger only if A<=B (hence, LE - Less or Equal)
; if instruction is not triggered (in case of A>B), A is still in R0 register
MOVLE r0,r1
BX lr
ENDP


my_min PROC
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; return B instead of A by placing B in R0
; this instruction will trigger only if A>=B (hence, GE - Greater or Equal)
; if instruction is not triggered (in case of A<B), A value is still in R0 register
MOVGE r0,r1
BX lr
ENDP


Optimizing GCC 4.8.1 and optimizing MSVC 2013 can use CMOVcc instruction, which is analogous to MOVcc in ARM:


Listing 12.29: Optimizing MSVC 2013
Free download pdf