Reverse Engineering for Beginners

(avery) #1

CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI())


MOV r0,#0
B |L0.28|
|L0.12|
ADD r0,r0,r0,LSL #2
; R0=R0+R0<<2=rt5
ADD r0,r2,r0,LSL #1
; R0=input character + rt
5<<1 = input character + rt*10
; correct whole thing by subtracting '0' from rt:
SUB r0,r0,#0x30
; shift pointer to the next character:
ADD r1,r1,#1
|L0.28|
; load input character to R2
LDRB r2,[r1,#0]
; is it null byte? if no, jump to loop body.
CMP r2,#0
BNE |L0.12|
; exit if null byte.
; "rt" variable is still in R0 register, ready to be used in caller function
BX lr
ENDP


42.1.4 Optimizing Keil 6/2013 (Thumb mode).


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

my_atoi PROC
; R1 will be pointer to the input character
MOVS r1,r0
; R0 is allocated to "rt" variable
MOVS r0,#0
B |L0.16|
|L0.6|
MOVS r3,#0xa
; R3=10
MULS r0,r3,r0
; R0=R3R0=rt10
; shift pointer to the next character:
ADDS r1,r1,#1
; correct whole thing by subtracting 0' character from it':
SUBS r0,r0,#0x30
ADDS r0,r2,r0
; rt=R2+R0=input character + (rt*10 - '0')
|L0.16|
; load input character to R2
LDRB r2,[r1,#0]
; is it zero?
CMP r2,#0
; jump to loop body if it is not
BNE |L0.6|
; rt variable in R0 now, ready to be used in caller function
BX lr
ENDP


Interestingly, from school mathematics we may remember that the order of addition and subtraction operations doesn’t
matter. That’s our case: first, thert∗ 10 −′ 0 ′expression is computed, then the input character value is added to it. Indeed,
the result is the same, but the compiler did some regrouping.


42.1.5 Optimizing GCC 4.9.1 ARM64


The ARM64 compiler can use the pre-increment instruction suffix:


Listing 42.5: Optimizing GCC 4.9.1 ARM64

my_atoi:
; load input character into W1
ldrb w1, [x0]

Free download pdf