Copy a function in memory and execute it

Posted by Elinghton on Stack Overflow See other posts from Stack Overflow or by Elinghton
Published on 2010-12-28T12:35:23Z Indexed on 2010/12/28 12:53 UTC
Read the original article Hit count: 234

Filed under:
|
|
|
|

Hi everybody,

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

I'm trying to do something like this:

typedef void(*FUN)(int *);
char * myNewFunc;

char *allocExecutablePages (int pages)
{
    template = (char *) valloc (getpagesize () * pages);
    if (mprotect (template, getpagesize (), 
          PROT_READ|PROT_EXEC|PROT_WRITE) == -1) {
        perror ("mprotect");
    } 
}

void f1 (int *v) {
    *v = 10;
}

// allocate enough spcae but how much ??
myNewFunc = allocExecutablePages(...)

/* Copy f1 somewere else
 * (how? assume that i know the size of f1 having done a (nm -S foo.o))
 */

((FUN)template)(&val);
printf("%i",val);

Thanks for your answers

© Stack Overflow or respective owner

Related posts about c

    Related posts about memory