Reverse Engineering for Beginners

(avery) #1

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


As was noted before (41.2.1 on page 470), there are no separate shifting instructions in ARM mode. However, there are
modifiers LSL (Logical Shift Left), LSR (Logical Shift Right), ASR (Arithmetic Shift Right), ROR (Rotate Right) and RRX (Rotate Right
with Extend) , which may be added to such instructions asMOV,TST,CMP,ADD,SUB,RSB^11.


These modificators define how to shift the second operand and by how many bits.


Thus the“TST R1, R2,LSL R3”instruction works here asR 1 ∧(R 2 ≪R3).


19.5.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode)


Almost the same, but here are twoLSL.W/TSTinstructions are used instead of a singleTST, because in Thumb mode it is
not possible to defineLSLmodifier directly inTST.


MOV R1, R0
MOVS R0, #0
MOV.W R9, #1
MOVS R3, #0
loc_2F7A
LSL.W R2, R9, R3
TST R2, R1
ADD.W R3, R3, #1
IT NE
ADDNE R0, #1
CMP R3, #32
BNE loc_2F7A
BX LR


19.5.5 ARM64 + Optimizing GCC 4.9


Let’s take the 64-bit example which has been already used:19.5.2 on page 314.


Listing 19.34: Optimizing GCC (Linaro) 4.8

f:
mov w2, 0 ; rt=0
mov x5, 1
mov w1, w2
.L2:
lsl x4, x5, x1 ; w4 = w5<<w1 = 1<<i
add w3, w2, 1 ; new_rt=rt+1
tst x4, x0 ; (1<<i) & a
add w1, w1, 1 ; i++
; result of TST was non-zero?
; then w2=w3 or rt=new_rt.
; otherwise: w2=w2 or rt=rt (idle operation)
csel w2, w3, w2, ne
cmp w1, 64 ; i<64?
bne .L2 ; yes
mov w0, w2 ; return rt
ret


The result is very similar to what GCC generates for x64:19.30 on page 315.


TheCSELinstruction is “Conditional SELect”. It just chooses one variable of two depending on the flags set byTSTand
copies the value intoW2, which holds the “rt” variable.


19.5.6 ARM64 + Non-optimizing GCC 4.9


And again, we’ll work on the 64-bit example which was already used:19.5.2 on page 314.


The code is more verbose, as usual.


Listing 19.35: Non-optimizing GCC (Linaro) 4.8

f:
sub sp, sp, #32


(^11) These instructions are also called “data processing instructions”

Free download pdf