Reputation: 1430
I want to add a 4KB space to the bss section of an executable elf file. How can this be done?
If not bss section, can I increase the size of the data section or define a new data section and initialize the region ?
If possible, can this be done with binary file formats other than elf ?
PS: I need this to add some extra instructions for instrumentation and saving the data in dedicated locations which have to be printed later.
Upvotes: 1
Views: 1101
Reputation: 213646
I want to add a 4KB space to the bss section of an executable elf file. How can this be done?
Assuming you want to do that to an already linked ELF
executable, note that sections are not used at all by anything (other than perhaps debugging tools) after the link is done; you want to modify the corresponding segment.
What you are asking for is impossible in general, but might be possible for your particular executable. In particular, it should be possible if the LOAD
segment "covering" the .bss
section is the last one, or if there is an in-memory gap between that segment and the next LOAD
segment.
If there is space (in memory) to extend the LOAD
segment in question, then all you have to do is patch its program header's .p_memsz
and increment it by 4096.
You would need to understand the output from readelf -Wl a.out
in detail.
Update:
assuming that bss occurs last, is there a tool to change .p_memsz of the last segment in a line or two ?
I don't know of any tool to do this, but it's pretty trivial: program headers are fixed sized table starting at file offset ehdr->e_phoff
. The table contains ehdr->e_phnum
records. You read each record until you find the last PT_LOAD
segment, update the .p_memsz
member, seek back and write the updated record on top of what was there.
The libelf
or elfio
libraries may (or may not) make writing this tool easier.
I guess to make the elf conformant, we also need to change the section size of bss accordingly ?
No, you don't:
.bss
and the load segment matchUpvotes: 3