Blog Archives

Make your programs lose weight: stripping binaries

`objcopy‘  is one of the utilities included in the GNU Binutils package. This tool allows copying binary files while transforming them in the process.

One of the typical purposes of modifying binary files after they have been compiled is to separate the debugging symbols and sections and the real executable. If you compiled you binary with debugging information (option ‘-g’ in gcc), the size of the binary will grow a lot due to the extra symbols, sections and human-readable stuff stored within the binary. That information is really useful when you are debugging your app, anyway, so you don’t really want to completely get rid of it.

So, we can use objcopy to move all the debugging information from the binary to another file, so that:

  • Binary is smaller
  • Binary does not include any ‘human-readable’ information of the program
  • Debugging information can be kept by the developers, so that if any ‘core’ file is received for that specific binary, debugging with GDB is possible.

[Step 1] Copy the binary to another file, keeping only the debugging information. This will create the symbol file for the binary, and will be kept by the developers of the program for debugging purposes:

objcopy --only-keep-debug $BINARY_PATH $DEBUG_INFO_FILE

[Step 2] Once you have created the symbol file, you can now remove all the debugging information from the binary itself:

objcopy --strip-debug $BINARY_PATH

[Step 3] After you have created both files, an extra optional option is to add a debug-link to the binary, to specify which is the exact file containing the debug information for that binary:

objcopy --add-gnu-debuglink=$DEBUG_INFO_FILE $BINARY_PATH

Please note that this third step is optional, as we can use specific GDB commands when debugging a core file to specify in which file the debug information is located.