Reverse Engineering for Beginners

(avery) #1

CHAPTER 19. MANIPULATING SPECIFIC BIT(S) CHAPTER 19. MANIPULATING SPECIFIC BIT(S)


or $at, $zero ; load delay slot, NOP
and $v0, $v1, $v0
; $v0 = a&(1<<i)
; is a&(1<<i) equals to zero? jump to loc_58 then:
beqz $v0, loc_58
or $at, $zero
; no jump occurred, that means a&(1<<i)!=0, so increment "rt" then:
lw $v0, 0x18+rt($fp)
or $at, $zero ; load delay slot, NOP
addiu $v0, 1
sw $v0, 0x18+rt($fp)


loc_58:
; increment i:
lw $v0, 0x18+i($fp)
or $at, $zero ; load delay slot, NOP
addiu $v0, 1
sw $v0, 0x18+i($fp)


loc_68:
; load i and compare it with 0x20 (32).
; jump to loc_20 if it is less then 0x20 (32):
lw $v0, 0x18+i($fp)
or $at, $zero ; load delay slot, NOP
slti $v0, 0x20 # ' '
bnez $v0, loc_20
or $at, $zero ; branch delay slot, NOP
; function epilogue. return rt:
lw $v0, 0x18+rt($fp)
move $sp, $fp ; load delay slot
lw $fp, 0x18+var_4($sp)
addiu $sp, 0x18 ; load delay slot
jr $ra
or $at, $zero ; branch delay slot, NOP


That is verbose: all local variables are located in the local stack and reloaded each time they’re needed. TheSLLVinstruction
is “Shift Word Left Logical Variable”, it differs fromSLLonly in that the shift amount is encoded in theSLLinstruction (and
is fixed, as a consequence), butSLLVtakes shift amount from a register.


Optimizing GCC


That is terser. There are two shift instructions instead of one. Why? It’s possible to replace the firstSLLVinstruction with
an unconditional branch instruction that jumps right to the secondSLLV. But this is another branching instruction in the
function, and it’s always favorable to get rid of them:33.1 on page 436.


Listing 19.37: Optimizing GCC 4.4.5 (IDA)

f:
; $a0=a
; rt variable will reside in $v0:
move $v0, $zero
; i variable will reside in $v1:
move $v1, $zero
li $t0, 1
li $a3, 32
sllv $a1, $t0, $v1
; $a1 = $t0<<$v1 = 1<<i


loc_14:
and $a1, $a0
; $a1 = a&(1<<i)
; increment i:
addiu $v1, 1
; jump to loc_28 if a&(1<<i)==0 and increment rt:
beqz $a1, loc_28
addiu $a2, $v0, 1
; if BEQZ was not triggered, save updated rt into $v0:
move $v0, $a2

Free download pdf