Dereferencing function pointers in C to access CODE memory

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

提交回复
热议问题