Reputation: 89
int (*FuncPtr)(int,int) = NULL;
int add(int a, int b)
{
return a+b;
}
int temp;
int main (void)
{
add = 0x100;
FuncPtr = add;
temp = (*FuncPtr)(10,20);
}
I am trying to copy a function to a particular address can kindly help us.
Upvotes: 1
Views: 456
Reputation: 46
You can't copy a function to a particular address simply like this, but use gcc's attribute, you can do this in another way. first, the program should be like this:
#include <stdio.h>
int (*FuncPtr)(int, int) __attribute__((unused, section(".myown"))) = NULL;
int add(int a, int b)
{
return a + b;
}
int temp;
int main (void)
{
//add = 0x100;
FuncPtr = add;
temp = (*FuncPtr)(10,20);
}
then you must get the ld script, do this cmd in a shell:
ld --verbose > f.lds
the contents in the middle of "==================================================" is the script. add this just before the line "__bss_start = .;"
. = 0x90000000;
_myown_start = .;
.myown : { *(.myown) } = 0x90000000
_myown_end = .;
code_segment : { *(code_segment) }
the address 0x90000000 is where you want to put the function pointer in, you can try other addresses, but that might not work. finally, compile your program like this:
gcc f.c -Wl,-Tf.lds
you can use objdump to see the result:
080483c2 <main>:
80483c2: 55 push %ebp
80483c3: 89 e5 mov %esp,%ebp
80483c5: 83 e4 f0 and $0xfffffff0,%esp
80483c8: 83 ec 10 sub $0x10,%esp
80483cb: c7 05 00 00 00 90 b4 movl $0x80483b4,0x90000000
80483d2: 83 04 08
80483d5: a1 00 00 00 90 **mov 0x90000000,%eax**
80483da: c7 44 24 04 14 00 00 movl $0x14,0x4(%esp)
80483e1: 00
80483e2: c7 04 24 0a 00 00 00 movl $0xa,(%esp)
80483e9: ff d0 call *%eax
80483eb: a3 0c 00 00 90 mov %eax,0x9000000c
80483f0: c9 leave
80483f1: c3 ret
this is the example of putting a function pointer in a section, and you can use the attribute in the add function to put the whole function in the section like this:
int add(int a, int b) __attribute__((unused, section(".myown")));
int add(int a, int b)
{
return a + b;
}
hope to be able to help you.
Upvotes: 3
Reputation: 3340
FuncPtr is a type not a variable, so you should do like this:
FuncPtr myFunc = add;
temp = (*myFunc)(1,1); //actually this is the same as myFunc(1,1)
Upvotes: 0