Assembly Language for Beginners

(nextflipdebug2) #1

3.11 Inline functions


Try to explain, what happened and why.


3.11 Inline functions


Inlined code is when the compiler, instead of placing a call instruction to a small or tiny function, just
places its body right in-place.


Listing 3.29: A simple example

#include <stdio.h>


int celsius_to_fahrenheit (int celsius)
{
return celsius * 9 / 5 + 32;
};


int main(int argc, char *argv[])
{
int celsius=atol(argv[1]);
printf ("%d\n", celsius_to_fahrenheit (celsius));
};


...is compiled in very predictable way, however, if we turn on GCC optimizations (-O3), we’ll see:


Listing 3.30: Optimizing GCC 4.8.1

_main:
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
call ___main
mov eax, DWORD PTR [ebp+12]
mov eax, DWORD PTR [eax+4]
mov DWORD PTR [esp], eax
call _atol
mov edx, 1717986919
mov DWORD PTR [esp], OFFSET FLAT:LC2 ; "%d\12\0"
lea ecx, [eax+eax*8]
mov eax, ecx
imul edx
sar ecx, 31
sar edx
sub edx, ecx
add edx, 32
mov DWORD PTR [esp+4], edx
call _printf
leave
ret


(Here the division is performed by multiplication(3.9 on page 497).)


Yes, our small functioncelsius_to_fahrenheit()has just been placed before theprintf()call.


Why? It can be faster than executing this function’s code plus the overhead of calling/returning.


Modern optimizing compilers are choosing small functions for inlining automatically. But it’s possible to
force compiler additionally to inline some function, if to mark it with the “inline” keyword in its declaration.


3.11.1 Strings and memory functions


Another very common automatic optimization tactic is the inlining of string functions like strcpy(),str-
cmp(),strlen(),memset(),memcmp(),memcpy(), etc..


Sometimes it’s faster than to call a separate function.


These are very frequent patterns and it is highly advisable for reverse engineers to learn to detect auto-
matically.

Free download pdf