I have the following simple hello-world program compiled with gcc in a standard elf binary:
#include <stdio.h>
void hello() {
printf("Preinit hello!\n");
}
int main() {
printf("Hello World\n");
return 0;
}
How can I create a new elf file using libelf (or any other suggested C library for such operations) in order to add a .preinit_array section that calls hello()?
My end goal is to "simulate" what a compiler would do with the following:
__attribute__((section(".preinit_array"))) typeof(hello) *hello_p = hello;
I read libelf by example but I found it completely cryptic and outdated with 32-bit examples only.
I also found this related SO question. objcopy is doing pretty much what I would like to do but obviously I don't want to call objcopy from my C program. Additionally, I tried to copy objcopy's source code from here with little success as the code is quite complicated and interconnected.