Dereferencing function pointers in C to access CODE memory

后端 未结 2 1106
孤城傲影
孤城傲影 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.

    0 讨论(0)
  • 2021-01-05 07:44

    With standard C, what you try to do is implementation defined behaviour and won't work portably. On a given platform, you might be able to make this work.

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

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

    0 讨论(0)
提交回复
热议问题