Reverse Engineering for Beginners

(avery) #1

CHAPTER 15. SIMPLE C-STRINGS PROCESSING CHAPTER 15. SIMPLE C-STRINGS PROCESSING


See also: “Signed number representations” (30 on page 431).


In other words, at the end of the function just after loop body, these operations are executed:


ecx=str;
eax=eos;
ecx=(-ecx)-1;
eax=eax+ecx
return eax


... and this is effectively equivalent to:


ecx=str;
eax=eos;
eax=eax-ecx;
eax=eax-1;
return eax


Why did GCC decide it would be better? Hard to guess. But perhaps the both variants are equivalent in efficiency.


15.1.2 ARM.


32-bit ARM


Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode)


Listing 15.2: Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode)

_strlen


eos = -8
str = -4


SUB SP, SP, #8 ; allocate 8 bytes for local variables
STR R0, [SP,#8+str]
LDR R0, [SP,#8+str]
STR R0, [SP,#8+eos]

loc_2CB8 ; CODE XREF: _strlen+28
LDR R0, [SP,#8+eos]
ADD R1, R0, #1
STR R1, [SP,#8+eos]
LDRSB R0, [R0]
CMP R0, #0
BEQ loc_2CD4
B loc_2CB8
loc_2CD4 ; CODE XREF: _strlen+24
LDR R0, [SP,#8+eos]
LDR R1, [SP,#8+str]
SUB R0, R0, R1 ; R0=eos-str
SUB R0, R0, #1 ; R0=R0-1
ADD SP, SP, #8 ; free allocated 8 bytes
BX LR


Non-optimizing LLVM generates too much code, however, here we can see how the function works with local variables in
the stack. There are only two local variables in our function:eosandstr. In this listing, generated byIDA, we have manually
renamedvar_8andvar_4toeosandstr.


The first instructions just saves the input values into bothstrandeos.


The body of the loop starts at labelloc_2CB8.


The first three instruction in the loop body (LDR,ADD,STR) load the value ofeosintoR0. Then the value isincremented
and saved back intoeos, which is located in the stack.


The next instruction,LDRSB R0, [R0](“Load Register Signed Byte”) , loads a byte from memory at the address stored in
R0and sign-extends it to 32-bit^2. This is similar to theMOVSXinstruction in x86. The compiler treats this byte as signed


(^2) The Keil compiler treats thechartype as signed, just like MSVC and GCC.

Free download pdf