Page 1 of 1

elf64 calling loaded function

Posted: Sat Mar 05, 2022 1:58 am
by bradbobak
Hi. I'm currently working on my elf loader for .o files.

in testfile.c

Code: Select all

void entry_func()
{
  return;
}
objdump -d testfile.o

Code: Select all

testfile.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <entry_func>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	90                   	nop
   5:	5d                   	pop    %rbp
   6:	c3                   	retq   
Then, in my program, I load testfile.o.

Then, I find entry_func's address (lookup the symbol).

Code: Select all

  char *store = find_symbol("entry_func");

  for (int x = 0; x < 7; ++x) printf("%x ", store[x]);

  printf("\n");
then the output ->

Code: Select all

 55 48 89 e5 90 5d c3 
which matches the disassembly.

finally ->

Code: Select all

  void (*fp)();
  fp = store;
  printf("calling\n");
  fp();
  printf("called\n");
Then I get a segfault without 'called' being printed.

Should this not work? seems the .o file is parsed and loaded correctly as of the memory dump.
Do I need to do something prior to calling fp() (set up certain registers or somesuch)?

Re: elf64 calling loaded function

Posted: Sat Mar 05, 2022 3:36 am
by yasar11732
What does your GDT look like? Do you use paging?

It looks like your CPU thinks that memory location is not executable.

Re: elf64 calling loaded function

Posted: Sat Mar 05, 2022 4:00 am
by bradbobak
Yes. thats the reason. I was trying my elf loading stuff in linux userspace using malloc() which I've come to read that its memory cannot be executed. Guess thats what my problem was. I'll try it in uefi tomorrow or so. Guess this topic is closed.

Re: elf64 calling loaded function

Posted: Sat Mar 05, 2022 4:41 am
by yasar11732
You can allocate executable memory in linux userspace, load your program there and you can run it.

https://man7.org/linux/man-pages/man2/mmap.2.html

You should use it with NULL addr (so linux decide where will your memory be), PROT_EXEC and PROT_READ protection (so it can be executed), and MAP_ANONYMOUS flag (you don't need to back this memory to a file).

Edit: you should also set PROT_WRITE since you will need to load your program there.

Re: elf64 calling loaded function

Posted: Sat Mar 05, 2022 3:54 pm
by bradbobak
excellent. thank you.