Copy a function in memory and execute it

后端 未结 5 873
走了就别回头了
走了就别回头了 2020-12-10 07:41

I would like to know how in C in can copy the content of a function into memory and the execute it?

I\'m trying to do something like this:

typedef vo         


        
5条回答
  •  庸人自扰
    2020-12-10 08:10

    Hacky solution and simple proof of concept that works for me (and compiles without warning on Mac OS X/GCC 4.2.1):

    #include "stdio.h"
    #include "stdlib.h"
    #include "string.h"
    #include 
    
    int function1(int x){
       return x-5;
    }
    
    int function2(int x){
      return x+5;
    }
    
    
    int main(){
      int diff = (&function2 - &function1);
      printf("pagesize: %d, diff: %d\n",getpagesize(),diff);
    
      int (*fptr)(int);
    
      void *memfun = malloc(4096);
    
      if (mprotect(memfun, 4096, PROT_READ|PROT_EXEC|PROT_WRITE) == -1) {
          perror ("mprotect");
      }
    
      memcpy(memfun, (const void*)&function2, diff);
    
      fptr = &function1;
      printf("native: %d\n",(*fptr)(6));
      fptr = memfun;
      printf("memory: %d\n",(*fptr)(6) );
      fptr = &function1;
      printf("native: %d\n",(*fptr)(6));
    
      free(memfun);
      return 0;
    }
    

提交回复
热议问题