c - Can function pointers be used to run "data"? -


Most people probably will not use it, but it just came to mind and wanted to make me angry.

Is it some machine code to say, in C-string, and then insert its function in the function pointer and then use it to run that machine code?

In principle, you can do it, per Karl Noor is called "self-modifying code".

In practice, which usually will prevent you from operating systems, most modern operating systems are designed to distinguish between "readable", "readable", and "executable" memory. When such an OS kernel loads a program, then it places the code in a special "executable" page which is marked only for reading so that a user application can not modify it; At the same time, GOTO is trying an address that is not in the "Executable" page, due to this there will also be a fault exception. This is for security purposes, because many types of malware and viruses and other hacks depend on the program to jump into modified memory. For example, a hacker can feed an app data, which causes some functions to write malicious code in the stack, and then run it.

But in the heart, what the operating system does to automatically load the program is what you describe - it loads the code in memory, flagens the memory as executable, and in it Jumps

In the embedded hardware world, you may not have an OS on your way, and so some platforms use this beautiful routine. I used to do it all the time at PlayStation 2- if there was a code that was specific to the level of the desert, and nowhere else, I do not keep it in memory all the time - instead I 'load it with the level of the desert, and Fix my work pointer's correct executable When the user left the level, I would dump that code out of memory, set all those function points to an exception handler, and load the next level code in one place.


Comments