Tell me, is it possible to somehow transfer the control of a program in C / C ++ to an arbitrary available memory?

Made a test example (mingw, Windows), but does not work, the program crashes when pw3 (5) is called.

#include <iostream> using namespace std; void work1(int value){ cout << "work1 " <<value <<endl; } void work2(int value){ cout << "work2 " <<value <<endl; } void (*pw1)(int) = work1; void (*pw2)(int) = work2; unsigned char data[100]={}; unsigned char *funcData = (unsigned char *)pw1; int main() { cout << "start test programm" << endl; work1(1); work2(2); pw1(3); pw2(4); cout <<(void*)pw1 << endl; cout <<(void*)pw2 << endl; void (*pw3)(int) = (void (*)(int))data; for(int i=0;i<100;i++){ data[i] = funcData[i]; } pw3(5); cout <<"end work"<< endl; return 0; } 

1 answer 1

You can or cannot do this depends not only on the "correctness" of pointer conversion, but also on the properties of the underlying platform. No modern [interactive] OS will allow you to simply transfer control to the data area. This is one of the pillars of system security. Protection of this kind (Data Execution Prevention) is implemented both at the OS level and at the processor level.

Your OS may provide the means to disable this protection. Without disabling this protection, you need to mark your data with OS-dependent means as executable code, and only after that transfer control to it. But to access the appropriate API, your program must have the necessary (very high) privileges.

We should also note that no one promised you that the function code is located in memory in some compact continuous manner. Those. Your belief that your for loop copies the function code to the funcData array is groundless.

There is also no guarantee that the function code is position-independent. If you have not specifically provided for the generation of position-independent code, it may turn out that even if you successfully copy the function code into the funcData array, this code in the new place will not behave as you expect.

  • changed the experimental code, overwritten the data functions work2, still the program crashes when you try to call - Alex
  • @Alex: What did you want? You are doing a complex low-level crap, and expect that you can get rid of a simple copy of the memory? Track the execution of the code before and after copying, find the difference in the values ​​of the registers. There is nothing difficult in this, just boring and painstaking work. - VladD
  • 2
    @Alex, AnT (in my opinion is somewhat veiled), I wrote to you that the code that is copied to data[] cannot be executed, since this memory is not available for execution . You can ask Google about keywords виртуальная память права доступа защита памяти - avp