10

Here I have an executable without knowing its build environment, with the assumption of gcc/g++ being used. Is there a way to find out the optimization flag used during compilation (like O0, O2, ...)?

All means are welcomed, no matter it's by analyzing the binary or some debug test via gdb (if we assume that -g flag is available during compilation).

John
  • 101
  • 1
  • 3
  • This question might help: http://stackoverflow.com/questions/189350/detect-gcc-compile-time-flags-of-a-binary – Nick Feb 16 '12 at 08:51
  • 4
    I'd be very interested in the reason for such a request. Notably, you should know that optimizations can be turned on and off on an individual basis, and the `O` levels are just groups for convenience. – Matthieu M. Feb 16 '12 at 08:59
  • 1
    In particular see [this informative answer](http://stackoverflow.com/a/340828/15416) to that question. That's conclusive proof that you can't do it reliably. – MSalters Feb 16 '12 at 09:00
  • 1
    Plus, thanks to function attributes, gcc lets you turn optimizations on and off on a per-function level (or on a coarser scope, using #pragma). – Damon Feb 16 '12 at 13:05

2 Answers2

4

If you are lucky, the command-line is present in the executable file itself, depending on the operating system and file format used. If it is an Elf-file, try to dump the content using the objdump from GNU binutils

Lindydancer
  • 25,428
  • 4
  • 49
  • 68
3

I really don't know if this can help, but checking O0 is quite easy in the disassembly (objdump -d), since the generated code has no optimization at all and adds some few instructions to simplify debugging.

Typically on an x86, the prologue of a function includes saving the stack pointer (for the backtrace, I presume). So if you locate, for example, the main function, you should see something like:

... main: ... push %rbp ... mov %rsp,%rbp

And you should see this "pattern" at almost every beginning of the functions. For other targets (I dunno what your target platform is), you should see more or less similar assembly sequences in the prologues or before the function calls.

For other optimization levels, things are way way trickier.

Sorry for remaining vague and not answering the entire question... Just hoping it will help.

user5922822
  • 209
  • 2
  • 5