This simple function calculates the sum of the squares of the first N natural numbers. While the function logic is obvious by just looking at the decompiler output, the assembly listing has too much noise and requires studying it. The decompiler saves your time and allows you to concentrate on more exciting aspects of reverse engineering.
f:
.set back_chain, -0x20
.set var_4, -4
stw r31, var_4(r1)
stwu r1, back_chain(r1)
mr r31, r1
stw r3, 0x14(r31)
mr r4, r3
cmpwi r3, 0
stw r4, 8(r31)
bgt loc_30
b loc_24
loc_24:
li r3, 0
stw r3, 0x18(r31)
b loc_88
loc_30:
li r3, 0
stw r3, 0x10(r31)
stw r3, 0xC(r31)
b loc_40
loc_40:
lwz r3, 0x14(r31)
lwz r4, 0xC(r31)
cmpw r4, r3
bge loc_7C
b loc_54
loc_54:
lwz r3, 0xC(r31)
mullw r3, r3, r3
lwz r4, 0x10(r31)
add r3, r4, r3
stw r3, 0x10(r31)
b loc_6C
loc_6C:
lwz r3, 0xC(r31)
addi r3, r3, 1
stw r3, 0xC(r31)
b loc_40
loc_7C:
lwz r3, 0x10(r31)
stw r3, 0x18(r31)
b loc_88
loc_88:
lwz r3, 0x18(r31)
addi r1, r1, 0x20
lwz r31, var_4(r1)
blr
# End of function f
int __fastcall f(int a1)
{
int i; // [sp+Ch] [-14h]@3
int v3; // [sp+10h] [-10h]@3
if ( a1 )
return 0;
v3 = 0;
for ( i = 0; i < a1; ++i )
v3 += i * i;
return v3;
}
Linear execution
The PowerPC processor has a number of instructions which can be used to avoid branches (for example cntlzw). The decompiler restores the conditional logic and makes code easier to understand.
The PowerPC processor contains a number of complex floating point instructions which perform several operations at once. It is not easy to recover an expression from the assembler code but not for the decompiler.
Compilers can decompose a multiplication/division instruction into a sequence of cheaper instructions (additions, shifts, etc). This example demonstrates how the decompiler recognizes them and coagulates back to the original operation.
The pseudocode is not something static because the decompiler is interactive the same way as IDA. You can change variable types and names, change function prototypes, add comments and more. The example above presents the result after these modifications.
Surely the result is not ideal, and there is a lot of room for improvement, but we hope that you got the idea.