-finstrument-function -O2 and printf() instrumentation

Martin Sebor msebor@gmail.com
Tue Aug 18 19:57:00 GMT 2015


On 08/17/2015 06:45 AM, Stefan Ruppert wrote:
> Hi all,
>
> I'm just playing arounnd with instrumenting source code using
> -finstrument-function compiler switch. I noticed the following behaviour
> within gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4:
>
> If I compile a simple C program using printf() calls without
> optimization the printf() calls are not instrumented. But if I compile
> the simple C program with -O2 the instrumentation functions are also
> called for any printf() call.
>
> However if I look into the object file using nm there is only an U
> reference to printf():
>
> nm ./ComplexChain-ComplexChain.o
>                   U __cyg_profile_func_enter
>                   U __cyg_profile_func_exit
> 0000000000000000 d _init.4299
> 0000000000000000 r .LC0
> 0000000000000000 T main
> 00000000000003a0 T Main
>                   U printf
>                   U __printf_chk
>                   U strtol
> 0000000000000110 T SubTran1
> 00000000000000c0 T SubTran2
>                   U time
>                   U usleep
>
> Any idea why func_enter and func_exit are called for printf() if
> compiled with -O2? Is the printf() call somehow inlined with -O2?

 From the nm output it looks like the program was compiled with
the _FORTIFY_SOURCE macro defined to a non-zero value (either
explicitly or otherwise(*)). With optimization (i.e., when the
__OPTIMIZE__ macro is also defined) printf is an inline function
defined in bits/stdio2.h that calls __printf_chk. It's this inline
function that's instrumented. When _FORTIFY_SOURCE is not defined
(or 0), or when not optimizing (_FORTIFY_SOURCE depends on
optimization), printf is a non-inline function defined in libc
and thus not subject to instrumentation.

Martin

[*] It's helpful to show the compiler options and the code when
posting these sorts of questions so that the results can be more
easily reproduced.



More information about the Gcc-help mailing list