Reverse Engineering for Beginners

(avery) #1

CHAPTER 12. CONDITIONAL JUMPS CHAPTER 12. CONDITIONAL JUMPS


ldr x19, [sp,16]
ldp x29, x30, [sp], 48
ret
.L27:
ldr x19, [sp,16]
adrp x0, .LC11 ; "a<b"
ldp x29, x30, [sp], 48
add x0, x0, :lo12:.LC11
b puts
.L25:
adrp x0, .LC9 ; "a>b"
str x1, [x29,40]
add x0, x0, :lo12:.LC9
bl puts
ldr x1, [x29,40]
cmp w19, w1
bne .L23 ; Branch if Not Equal
.L26:
ldr x19, [sp,16]
adrp x0, .LC10 ; "a==b"
ldp x29, x30, [sp], 48
add x0, x0, :lo12:.LC10
b puts


The comments were added by the author of this book. What is striking is that the compiler is not aware that some conditions
are not possible at all, so there is dead code at some places, which can never be executed.


Exercise


Try to optimize these functions manually for size, removing redundant instructions, without adding new ones.


12.1.3 MIPS.


One distinctive MIPS feature is the absence of flags. Apparently, it was done to simplify the analysis of data dependencies.


There are instructions similar to SETcc in x86: SLT (“Set on Less Than”: signed version) and SLTU (unsigned version). These
instructions sets destination register value to 1 if the condition is true or to 0 if otherwise.


The destination register is then checked using BEQ (“Branch on Equal”) or BNE (“Branch on Not Equal”) and a jump may occur.


So, this instruction pair has to be used in MIPS for comparison and branch.


Let’s first start with the signed version of our function:


Listing 12.11: Non-optimizing GCC 4.4.5 (IDA)

.text:00000000 f_signed: # CODE XREF: main+18
.text:00000000
.text:00000000 var_10 = -0x10
.text:00000000 var_8 = -8
.text:00000000 var_4 = -4
.text:00000000 arg_0 = 0
.text:00000000 arg_4 = 4
.text:00000000
.text:00000000 addiu $sp, -0x20
.text:00000004 sw $ra, 0x20+var_4($sp)
.text:00000008 sw $fp, 0x20+var_8($sp)
.text:0000000C move $fp, $sp
.text:00000010 la $gp, __gnu_local_gp
.text:00000018 sw $gp, 0x20+var_10($sp)
; store input values into local stack:
.text:0000001C sw $a0, 0x20+arg_0($fp)
.text:00000020 sw $a1, 0x20+arg_4($fp)
; reload them.
.text:00000024 lw $v1, 0x20+arg_0($fp)
.text:00000028 lw $v0, 0x20+arg_4($fp)
; $v0=b
; $v1=a
.text:0000002C or $at, $zero ; NOP

Free download pdf