Adding section to ELF file

19,914

Solution 1

There's a few (possibly) related answers in this question about ELF file headers. The accepted answer mentioned using objcopy to add sections to an ELF file, and the BSD bintools claims to have a BSD-licensed implementation of objcopy that might suit your needs.

Solution 2

I know this is an old question but i found a working example that helped me to apply it to my project. (In case anyone stumbles upon this question)

taken from Sourceware Mail Archiv

$ echo 'int main() { puts ("Hello world"); }' | gcc -x c - -c -o hello.o

$ echo "this is my special data" >mydata

$ objcopy --add-section .mydata=mydata \
          --set-section-flags .mydata=noload,readonly hello.o hello2.o

$ gcc hello2.o -o hello

$ ./hello
Hello world

$ objdump -sj .mydata hello

Solution 3

The following links could be useful:

Solution 4

have a look at ELFsh, which is now part of the ERESI project http://www.eresi-project.org/ They have a lot of documentation and cool uses of their tools.

Solution 5

Haven't tried it (yet) myself but you might look at the function elf_newscn in libelf

Share:
19,914
michaelwb11
Author by

michaelwb11

Updated on June 25, 2022

Comments

  • michaelwb11
    michaelwb11 almost 2 years

    I need to be able to add an arbitrary section to an ELF file. I cannot use GPL code in this program, so BFD is out of the question. I can use libelf/gelf to read sections, but the documentation is fairly sparse for these, and I cannot figure out how to add a section. Does anybody know how to do this? I would rather not write my own ELF code.

  • Zibri
    Zibri about 6 years
    and how do you access it from the program? by re-readin all the exe? naaaa there is a better way.
  • Ben
    Ben about 6 years
    thats a silly comment. The question was not how to access anything at runtime. The question is, how to add a section to ELF fil. Or i misunderstand the comment.
  • Zibri
    Zibri about 6 years
    your is a silly comment and a silly answer, if he needs to add a section I imagine he wants also to access it. It's just applied logic.
  • Zibri
    Zibri about 6 years
    Access it from the program, not with objdump! I did it in a program of mine... I asked that because if needed I can post the method.
  • Ben
    Ben about 6 years
    If you read the question, you have to acknowledge that it wasn’t even a question how to access it. “Adding section to ELF file” I don’t even know what we are arguing about.
  • Edd Barrett
    Edd Barrett over 4 years
    Well, he didn't ask how to read the section, but if you want you can either read the relevant section of the binary from disk, or remove the noload flag when making the section and use dl_iterate_phdr(3) to find it in memory.