Dereferencing function pointers in C to access CODE memory

后端 未结 2 1109
孤城傲影
孤城傲影 2021-01-05 07:15

We are dealing with C here. I\'m just had this idea, wondering if it is possible to access the point in memory where a function is stored, say foo and copying t

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-05 07:29

    On modern desktops, the virtual memory manager is going to get in your way. Memory regions have three types of access: read, write, and execute. On systems where code segments have only execute permission, the memcpy will fail with a bus error. In the more typical case, where only code segments have the execute permission, you can copy the function, but not run, because the memory region that contains bar will not have execute permission.

    Also, determining the size of the 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 is x:(8 4) foo:(1 1) indicating that taking the sizeof a function pointer, or the function itself, is not a supported operation.

提交回复
热议问题