33

I was working on Ubuntu 17.10 with GPROF for some testing with C files, and when I execute with gprof the file generated (gmon.out), compiling and linking with -pg option, I got an empty flat and call graph.

However, I found that this is a GCC bug, and I would have to compile and link the file with -no-pie option.

  • Compile:

    gcc -c main.c file-1.c file-2.c -pg [-no-pie]
    
  • Link:

    gcc -o test main.o file-1.o file-2.o -pg [-no-pie]
    

I have the GCC 7.2 version.

How does this option work and why the graphs are empty if I don't use that option?

MarianD
  • 13,096
  • 12
  • 42
  • 54
SGodoy
  • 703
  • 1
  • 5
  • 13

1 Answers1

42

That flag is telling gcc not to make a position independent executable (PIE). PIE is a precondition to enable address space layout randomization (ASLR). ASLR is a security feature where the kernel loads the binary and dependencies into a random location of virtual memory each time it's run.

colm.anseo
  • 19,337
  • 4
  • 43
  • 52
Paul
  • 663
  • 7
  • 11
  • 1
    And why PIE or non-PIE mode affects binutils's gprof, `-pg` of compiler, and some library (glibc or gcc internal?) implementing counting? https://sourceware.org/binutils/docs/gprof/Implementation.html#Implementation says "The mcount routine, included in the profiling library" but don't name the profiling library used. Can the issue be connected with profiling library or gprof don't supporting randomized address? – osgx May 31 '18 at 04:36
  • 1
    The issue is that every time the executable is loaded it gets a new random address, which gprof doesn't know. – rsaxvc Feb 12 '19 at 16:01
  • 22
    PIE is not a security feature. It just means that the code is position independent. A result of PIE is that Address Space Layout Randomization (ASLR) can be enabled (these days the default for security reasons, which is why also PIE is the default these days). Down voted because you can compile an executable as PIE but turn off ASLR just fine. – Carlo Wood Jul 29 '19 at 22:38
  • 2
    Yeah I should have said position indepandant code is largely for building shared libraries where the runtime location of the shared library depends on outside factors. – Paul May 19 '20 at 14:46
  • @Paul This was a **BRILLIANT** answer. – William Martens Jul 16 '22 at 12:29
  • 3
    @Paul - but what is the benefit of NOT generating a PIE -- why would someone want to use `-no_pie` in the first place? – Iron Savior Nov 29 '22 at 17:36
  • @IronSavior PIE code can require additional instructions to implement, giving a (generally mild to nonexistent) performance cost. – geometrian Feb 12 '23 at 19:29