Linux – Effectively adds new sections to the ELF file

Effectively adds new sections to the ELF file… here is a solution to the problem.

Effectively adds new sections to the ELF file

I want to add a new section to an ELF file (e.g. E) that stores the integrity hash of the .text section. Suppose I chunk the .text part into T1,T2:. Tn and get hashed H1,H2:. Hn and add all hashes to E in the new .my_hash section.

An easy way to do this is

  • Scan file E and calculate the hash value/store it in a separate binary B
  • Convert B to a B.o file
  • objcopy –rename_section rename the .data section to the .my_hash section
  • Finally merge E.o

  • (assuming I also had E before generating E) and B.o

Is there a better way?

Solution

Use objcopy --add-section. You may also need —set-section-flags.

Related Problems and Solutions