Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if C++ binary is optimized

Is there a flag or other reliable method to detect if a compiled C++ binary was compiled with optimizations?

I'm okay with compiler-specific solutions.


Edit: This is for a build deployment system, which could accidentally deploy binaries that were not built properly. A water-tight solution is unlikely, but it will save some pain (and money) if this can be detected some of the time.

The compiler will often be gcc, sometimes sun, and if there's a MSVC solution, I don't want to rule that out for the benefit of the community.

like image 525
Drew Dormann Avatar asked Jul 13 '09 17:07

Drew Dormann


2 Answers

Recent versions of GCC have a way to report which flags were used to compile a binary (third bullet point).

There is a related command line switch (--fverbose-asm) that "only records the information in the assembler output file as comments, so the information never reaches the object file." The --frecord-gcc-switches switch "causes the command line that was used to invoke the compiler to be recorded into the object file that is being created."

like image 179
Max Lybbert Avatar answered Sep 22 '22 06:09

Max Lybbert


Possible Heuristics Solution

If I would be given this task and it would prove it is a reasonable task (see below), I would perform "a frequency analysis" of the patterns seen in the executable disassembly. As a programmer I am able to distinguish between an optimized and an unoptimized (debug) code at a first glance. I would try to formalize the decision process, with Visual Studio and the x86 platform the typical features seen in an unoptimized exe would be:

  • functions with full prologue/epilogue (ebp based stack frames)
  • a lot of mov-s from/into memory (all variables placed in the memory)

This is definitely not 100 %, but with longer exe I would expect the results to be quite reliable.

I assume for other x86 platforms including GCC the rules will be similar, if not the same, and for other platforms similar rules can be found.

Other heuristics like detection of the runtime library may work as well, depending on compiler settings.

Task sounds silly

That said, I think such task "smells" and under most circumstances it would be sensible to avoid it completely. If you will provide the real reason behind such task, it is very likely some sensible solution will be found.

like image 25
Suma Avatar answered Sep 22 '22 06:09

Suma