Reverse Engineering for Beginners

(avery) #1

CHAPTER 43. INLINE FUNCTIONS CHAPTER 43. INLINE FUNCTIONS


Chapter 43


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 43.1: 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 43.2: 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 done by multiplication(41 on page 468).)


Yes, our small functioncelsius_to_fahrenheit()was just 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.

Free download pdf