ELF Files? Loading/Running :)

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
User avatar
deleted
Member
Member
Posts: 82
Joined: Mon Jul 21, 2014 7:23 pm

ELF Files? Loading/Running :)

Post by deleted »

Hello all,

I am attempting to add a module to my OS to load and execute a simple ELF file. Just a:

Code: Select all

int main(){
    return 0;
}
Kindof thing. Just for a little background, I am trying to read it from an INITRD. I can read the file in as needed.

1. How do I load them (in memory?)
2. What do I do? (Use my program as a parser to execute the code?)
3. What is the right way to do this?

Please point me in the right direction, tutorials, specs, old dust books, etc.

Thanks!
User avatar
max
Member
Member
Posts: 616
Joined: Mon Mar 05, 2012 11:23 am
Libera.chat IRC: maxdev
Location: Germany
Contact:

Re: ELF Files? Loading/Running :)

Post by max »

Heyho :)

I'll assume that you have your virtual memory management & multitasking set up.
If you don't have virtual memory management, you should implement it before doing this.

What you do is:
  • Read the specification, especially part 2
  • Read the ELF header of the file & validate it. This header contains all the information you need for loading
  • Set up an empty process/task
  • Copy all "load segments" into memory: each of these segments has a virtual address (vaddr) where it should to be copied to, the amount of bytes that have to be copied (filesz) and the amount of memory that has to be zero'd (memsz), both based on the vaddr (read specification for more details)
  • Set the instruction pointer of the task to start at the entry point specified in the program header (e_entry)
  • Add the task to your scheduler
This should be appropriate for the start. In essence you load all "load" segments into memory and kick off the executable at it's entry point.

Greets,
Max
User avatar
sortie
Member
Member
Posts: 931
Joined: Wed Mar 21, 2012 3:01 pm
Libera.chat IRC: sortie

Re: ELF Files? Loading/Running :)

Post by sortie »

You want the System V ABI as the true standard of ELF. The trick is to parse the header and recognize it is an ELF. You then parse the program headers (not section headers!) and load each entry by allocating memory at the desired address and copying data from the file there, and zeroing the rest. Pretty simple. You locate the program entry point in the ELF header, and transfer execution there after setting up a stack.
Post Reply