Many different types of math operations can be performed in C programming, and we’ll present the disassembly of those operations in this section.
Example 6-6 shows the C code for two variables
and a variety of arithmetic operations. Two of these are the --
and ++
operations, which are used to decrement by 1 and increment
by 1, respectively. The %
operation performs the
modulo between the two variables, which is the remainder after performing a
division operation.
Example 6-6. C code with two variables and a variety of arithmetic
int a = 0; int b = 1; a = a + 11; a = a - b; a--; b++; b = a % 3;
Example 6-7 shows the assembly for the C code shown in Example 6-6, which can be broken down to translate back to C.
Example 6-7. Assembly code for the arithmetic example in Example 6-6
00401006 mov [ebp+var_4], 0 0040100D mov [ebp+var_8], 1 00401014 mov eax, [ebp+var_4] ❶ 00401017 add eax, 0Bh 0040101A mov [ebp+var_4], eax 0040101D mov ecx, [ebp+var_4] 00401020 sub ecx, [ebp+var_8] ❷ 00401023 mov [ebp+var_4], ecx 00401026 mov edx, [ebp+var_4] 00401029 sub edx, 1 ❸ 0040102C mov [ebp+var_4], edx 0040102F mov eax, [ebp+var_8] 00401032 add eax, 1 ❹ 00401035 mov [ebp+var_8], eax 00401038 mov eax, [ebp+var_4] 0040103B cdq 0040103C mov ecx, 3 00401041 idiv ecx 00401043 mov [ebp+var_8], edx ❺
In this example, a
and b
are local variables because they are referenced by the stack. IDA Pro has labeled
a
as var_4
and b
as var_8
. First, var_4
and var_8
are initialized to 0
and 1, respectively. a
is moved into eax
❶, and then 0x0b is added to eax
, thereby incrementing a
by 11. b
is then subtracted from a
❷. (The compiler decided to use the sub
and add
instructions ❸ and ❹, instead of
the inc
and dec
functions.)
The final five assembly instructions implement the modulo. When performing the div
or idiv
instruction ❺, you are dividing edx:eax
by
the operand and storing the result in eax
and the remainder in
edx
. That is why edx
is moved
into var_8
❺.