elf64 calling loaded function

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
bradbobak
Member
Member
Posts: 26
Joined: Fri Apr 14, 2006 11:00 pm

elf64 calling loaded function

Post 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)?
yasar11732
Member
Member
Posts: 28
Joined: Thu Sep 27, 2018 5:10 pm
Libera.chat IRC: yasar
Location: Turkey
Contact:

Re: elf64 calling loaded function

Post by yasar11732 »

What does your GDT look like? Do you use paging?

It looks like your CPU thinks that memory location is not executable.
bradbobak
Member
Member
Posts: 26
Joined: Fri Apr 14, 2006 11:00 pm

Re: elf64 calling loaded function

Post 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.
yasar11732
Member
Member
Posts: 28
Joined: Thu Sep 27, 2018 5:10 pm
Libera.chat IRC: yasar
Location: Turkey
Contact:

Re: elf64 calling loaded function

Post 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.
bradbobak
Member
Member
Posts: 26
Joined: Fri Apr 14, 2006 11:00 pm

Re: elf64 calling loaded function

Post by bradbobak »

excellent. thank you.
Post Reply