Page 1 of 1

How to do a elf linker in a C kernel ?

Posted: Fri Nov 06, 2009 11:54 am
by SamyPesse
Hello everybody, for my os, i want to do a elf linker to load dynamic library, i have already a elf loader but i don't how the dynamic elf works,
This is my elf loader code to load static elf :
sorry for my english, i'm french

Code: Select all

u32 load_elf(char *file, struct process *proc)
{
	char *p;
	u32 v_begin, v_end;
	Elf32_Ehdr *hdr;
	Elf32_Phdr *p_entry;
	int i, pe;

	hdr = (Elf32_Ehdr *) file;
	p_entry = (Elf32_Phdr *) (file + hdr->e_phoff);	/* Program header table offset */

	if (!is_elf(file)) {
		printk("INFO: load_elf(): file not in ELF format !\n");
		return 0;
	}

	for (pe = 0; pe < hdr->e_phnum; pe++, p_entry++) {	/* Read each entry */

		if (p_entry->p_type == PT_LOAD) {
			v_begin = p_entry->p_vaddr;
			v_end = p_entry->p_vaddr + p_entry->p_memsz;

			if (v_begin < USER_OFFSET) {
				printk ("INFO: load_elf(): can't load executable below %p\n", USER_OFFSET);
				return 0;
			}

			if (v_end > USER_STACK) {
				printk ("INFO: load_elf(): can't load executable above %p\n", USER_STACK);
				return 0;
			}


			/* Description de la zone exec + rodata */
			if (p_entry->p_flags == PF_X + PF_R) {	
				proc->b_exec = (char*) v_begin;
				proc->e_exec = (char*) v_end;
			}

			/* Description de la zone bss */
			if (p_entry->p_flags == PF_W + PF_R) {	
				proc->b_bss = (char*) v_begin;
				proc->e_bss = (char*) v_end;
			}

			memcpy((char *) v_begin, (char *) (file + p_entry->p_offset), p_entry->p_filesz);

			if (p_entry->p_memsz > p_entry->p_filesz)
				for (i = p_entry->p_filesz, p = (char *) p_entry->p_vaddr; i < (int)(p_entry->p_memsz); i++)
					p[i] = 0;
		}
	}

	/* Return program entry point */
	return hdr->e_entry;
}

Re: How to do a elf linker in a C kernel ?

Posted: Fri Nov 06, 2009 2:00 pm
by DeleteMe
you shuodt implemtent reclocations. as i can see you have'nt impemented it yet. then you can load object files, with undfinned symbols. =D>

sorry aboute my bad englisk, im from danmark

Re: How to do a elf linker in a C kernel ?

Posted: Sat Nov 07, 2009 9:53 am
by thepowersgang
I suggest reading the ELF specs.
You would want to implement the sections on the "Program Header", "Program Loading" and "Dynamic Linking" (in my copy they are in section 2)
It is actually quite simple to do, once you understand the specifcation.