开发者

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

开发者 https://www.devze.com 2023-03-13 18:18 出处:网络
i have the following code: void print(const char* str){ system_call(4,1,str,strlen(str)); } void foo2(void){ print(\"goo \\n\");}

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 her开发者_Python百科e? which line is the problematic one?

thank you for your help


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.


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."


First and foremost, C function pointers mechanism is for equal-signature function calling abstraction. This is powerful and error-prone enough without these stunts.

I can't see an advantage/sense in trying to copying code from one place to another. As some have commented, it's not easy to tell the amount of relativeness/rellocatable code within a C function.

You tried copying the code of a function onto a data memory region. Some microcontrollers would just told you "Buzz off!". On machine architectures that have data/program separated memories, given a very understanding compiler (or one that recognizes data/code modifiers/attributes), it would compile to the specific Code-Data Move instructions. It seams it would work... However, even in data/code separated memory archs, data-memory instruction execution is not possible.

On the other hand, in "normal" data/code shared memory PCs, likely it would also not work because data/code segments are declared (by the loader) on the MMU of the processor. Depending on the processor and OS, attempts to run code on data segments, is a segmentation fault.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号