I’m writing a small tool for experimenting with ELF-64 object code which is intended to parse and load ELF-64 object code for execution in the parent process. I believe I’m on the right track for now, but I need some pointers for the last steps.
Step 1: I parse the object file and extract all necessary information. I’ve verified this to be correct using the readelf tool.
Step 2: I loop through all section headers with the SHF_ALLOC-bit set and mmap memory.
Step 3: This seemingly simple and useless object consisting of only a main-routine and a return statement, requires no symbol relocating as far as I know (I’ve double-checked with readelf). I’ve compiled with TinyCC to avoid .eh_frame and its relocation entries from being emitted.
But at this point I need to load the sections with SHF_ALLOC-bit set into memory, and this is where I suspect I’m doing wrong.
offset = 0
foreach section in sections
if section.flags & SHF_ALLOC
memcpy(memory_address + offset, object_code + section.offset, section.size)
offset += section_size
Step 4: The last step which I’m unsure of also. I need to call into the allocated memory which I’ve marked as executable.
typedef int (main_t)(int argc, char* argv[]);
((main_t)object->address)(0, NULL);
I’d very much appreciate some input on this. I believe it boils down to lack of understanding what exactly .text-segment contains and how they are intended to be stored in memory.
Some thoughts:
- is
mainlocated at offset0x0in the.text-segment? - are allocated segments intended to be stored sequentially with the right alignments?
Anything to point me in the right direction will help immensely! Thanks!
PS. I intend to learn about relocating symbols shortly. One step at a time. 🙂
I managed to pull this off after a good night’s sleep.
I first disassembled the object file using
objdumpwhich produced:This output ensured me the location of
mainto be at0x0, meaning if I copy the.text-segment correctly into memory at the address returned bymmap, I should be able to call it with the snippet found in the question (which I was unsure about). It’ll use the stack of the calling thread.I then found a small error when copying the sections to memory where
section.offsetwas the offset from the beginning of the file, which I mistakenly assumed was the offset from the beginning of the section header entry.It’ll be much simpler to experiment when I know the basics work. 🙂