Is it possible to load a binary file into memory and execute it in windows

空扰寡人 提交于 2019-12-04 18:47:00

While the code you showed is location independent, so can execute anywhere, it is not the case of memory allocated for data. Actual versions of OS's enforces the memory access protection explicitly denying execution on data memory. But first of all there is a big error in your program, you have not defined any memory for the code you want load:

void (*ptr)(void);  //This allocates only space for a function pointer, but no memory

When reading data from disk it will be write somewhere in memory triggering a memory access fault. To get executable memory from OS you can use functions as VirtualAlloc, and then make the allocated memory executable using other functions as VirtualProtect. Then you must assign to your function pointer the address of executable memory and only at that time read code from disk. This process is often used for malware or code injection, and can work for local or remote processes, that's why I'll not give better explanation. Curiosity is good, but... ;-)

Is it possible? Yes. But as people have commented, there's much more to it than what you're currently going on (even ignoring the pending seg fault in your code). Among other things you should realize that Visual Studio (at least) build programs that by default are explicitly prevented from executing 'data'. See documentation for the /NXCOMPAT flag and Data Execution Prevention

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!