1

I have a simple c file that prints a message in main and do nothing else Compiled it using gcc to generate .out file.Use the elf parser to get the entry_address of start function and using this addressas function pointer i am trying to execute the main function in c file but it is giving seg fault.

e.g

test.c
void main()
{
  print("something");
}

generated test.out elf file by gcc

and i get the following by doing nm test.out

0000000000601020 A _edata
0000000000601030 A _end
00000000004005e8 T _fini
00000000004003c8 T _init
0000000000400410 T _start
000000000040043c t call_gmon_start
0000000000601020 b completed.6531
0000000000601010 W data_start
0000000000601028 b dtor_idx.6533
00000000004004d0 t frame_dummy
00000000004004f4 T main

The start address is 0x0400410 T _start. Now i write another c code like below to execute the main function in test.c

execute.c
void main()
{

   typedef int func(void); 
   f = (func*)0x00400410;
   f();
 }

compiling excute.c by gcc execute.c -o execute.out is giving me segmentation fault on calling f().

The desired output is to print something.

Is it possible to execute elf file function from address,where i am getting wrong.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
user2251377
  • 31
  • 1
  • 4

1 Answers1

4

Your question demonstrates several fundamental mis-understandings. Let's take them one by one.

First, as hcs pointed out, test.out and execute.out have nothing to do with each other. When one is running, the other one is not loaded into your process space at all. Your expectation of being able to call a function in test.out from execute.out is not unlike counting money in my right front pant pocket (say you find a 25c coin there), then reaching into your own right front pant pocket and expecting to find that same 25c coin there.

Related to this, you are also expecting to even have the right pant pocket just because I have one (expecting to find _start at 0x00400410 in execute.out just because _start is at that address in test.out). You may in fact find _start at the same address, or you may not. Maybe you are wearing a kilt today, and it doesn't have a front right pant pocket at all.

Finally, think about the program execution. Who called your main routine? (That's right, _start did). Now you've arranged for your main to call _start again. What do you expect that do? It will call main again. And that will call _start again. This is called infinite recursion, and would cause your binary to crash with stack exaustion.

Note: the actual cause of the crash is different, and related to the fact that _start is not expecting to be called twice within the same process.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362