C dereference function pointers for accessing CODE memory

We are dealing with C here. I just had this idea, I wonder if it is possible to access the memory point where the function is stored, say foo and copy the contents of the function to another memory point. In particular, I am trying to get the following to work:

 #include <stdlib.h> #include <stdio.h> #include <string.h> void foo(){ printf("Hello World"); } int main(){ void (*bar)(void) = malloc(sizeof foo); memcpy(&bar, &foo, sizeof foo); bar(); return 0; } 

But at startup, it gives a bus error: Bus error: 10 . I am trying to copy the contents of the function foo to the memory space of bar , and then execute the newly created function bar .

This is not for any other reason than to see if it is possible to reveal the subtleties of the C language. I do not think about the practical application of this.

I am looking for guidance to make this work, or, otherwise, to be said, with a reason why this will not work

EDIT Looking at some answers and learning about reading, writing, and executable memory, it just became clear to me that it would be possible to create functions on the fly in C by writing to executable memory.

+7
c memory function-pointers memcpy
source share
2 answers

When using standard C, what you are trying to do is implementation-specific behavior and will not work portable. On this platform you can do this work.

The malloc memory gives you, as a rule, is not executable. Jumping there causes a bus error ( SIGBUS ). Assuming you are on a POSIX-like system, either allocate memory for the function using mmap , or flags that cause the memory area to be executed, or use mprotect to mark the region as executable.

You also need to be more careful with the amount of memory that you provide, you cannot just take the size of the function and expect that it is the length of the function, sizeof not designed to provide this kind of functionality, you need to find out the length of the function using a different approach.

+8
source share

On modern desktops, the virtual memory manager will bother you. Memory areas have three types of access: read, write, and execute. On systems where code segments have only permission to execute, memcpy will fail with a bus error. In the more typical case, when only code segments have permission to execute, you can copy this function, but not work, since the memory area containing bar will not have permission to execute.

Also, sizing a function is problematic. Consider the following program

 void foo( int *x ) { printf( "x:(%zu %zu) ", sizeof x, sizeof *x ); } int main( void ) { int x = 0; foo( &x ); printf( "foo:(%zu %zu)\n", sizeof foo, sizeof *foo ); } 

On my system, the output x:(8 4) foo:(1 1) indicates that using the sizeof function pointer or the function itself is not supported.

+6
source share

All Articles