C ++, execute binary from a byte array

2

I am trying to use function pointers pointing to a binary stored in byte array, but it always results in segmentation fault.

unsigned char byteProg[] = {0x7F,0x45,0x4C,0x46,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x02,.......};

int main()

{

    int (*func_ptr)(void);

    func_ptr= (int (*)(void)) byteProg;

    (*func_ptr)();


    return 0;
}

i also tried with no luck:

typedef unsigned char uchar;

void func(void)
{

    printf("Hello\n");

}


void next_func_sector(void)

{


}


int main()

{
    uchar func_buff[0x1000];

    void (*prg)(void);


    memcpy(func_buff, (void *) func, ((uchar *) next_func_sector - (uchar *) func));


    prg= (void (*)(void)) func_buff;

    (*prg)();


    return 0;

}
    
asked by dante244 29.07.2017 в 20:34
source

1 answer

1

What you are trying to do is indefinite behavior.
The C ++ standard does not give any guarantee about what that program would do.

Which does not mean you can not do it. It may even be useful.
But what the program does depends on the compiler you use and the operating system in which the program is run. A program that does this may work when compiled with a compiler but may not work with another, it may not work with other versions of the same compiler.

Regarding the causes of segmentation fault, modern operating systems have protection mechanisms for the execution of memory areas. These systems prevent instructions from being executed in areas marked for data, which increases the security of the system. Surely your byteProg array is in that situation and that's why the program is interrupted when that security breach is detected.
There are ways to mark memory zones so they can be executed. But the way to do it depends on each operating system.

    
answered by 29.07.2017 в 23:47