Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - calling a function via func_ptr, why doesnt it work?

i have the following code:

void print(const char* str){
      system_call(4,1,str,strlen(str)); }

void foo2(void){ print("goo \n");}


void buz(void){ ...}

int main(){
char buf[256];
    void (*func_ptr)(void)=(void(*)(void))buf;
    memcpy(buf,foo2, ((void*)buz)-((void*)foo2));
    func_ptr();
    return 0;
}

the question is, why will this code fall?

the answer was, something about calling a function not via pointer is to a relative address, but i havent been able to figure out whats wrong here? which line is the problematic one?

thank you for your help

like image 404
Raz Avatar asked Jun 18 '11 21:06

Raz


People also ask

Can a pointer call a function?

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.

Can we pass function as a parameter in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.

How can a function pointer be declared?

You can use a trailing return type in the declaration or definition of a pointer to a function. For example: auto(*fp)()->int; In this example, fp is a pointer to a function that returns int .


2 Answers

Well to begin with, there is nothing which says that foo2() and buz() must be next to each other in memory. And for another, as you guess, the code must be relative for stunts like that to work. But most of all, it is not allowed by the standard.

As Chris Luts referred to, stack (auto) variables are not executable on many operating systems, to protect from attacks.

like image 186
Prof. Falken Avatar answered Sep 30 '22 01:09

Prof. Falken


The first two lines in your main() function are problematic.

Line 1. (void(*)(void))buf converting buf to a function pointer is undefined

Line 2. ((void*)buz)-((void*)foo2) subtraction of pointers is undefined unless the pointers point within the same array.

Also, Section 5.8 Functions of H&S says "Although a pointer to a function is often assumed to be the address of the function's code in memory, on some computers a function pointer actually points to a block of information needed to invoke the function."

like image 20
sigjuice Avatar answered Sep 29 '22 23:09

sigjuice