问题描述
我正在尝试编写一个程序来从内存中读取二进制文件并执行并退出,但操作系统似乎并未让我从内存中执行它,所以本练习的全部目的是在不加载内存的情况下加载一个二进制文件.标头插入内存.
I am trying to write a program to read a binary file from memory execute it and exit but the OS doesn't seem to let me execute it from memory, the entire point of this exercise is to load a binary file with no header into memory.
这是我的二进制文件代码:
This is my code for the binary file:
push eax
mov eax,3
mov edi,eax
sub eax,edi
pop eax
leave
ret
我的装载机如下:
int main(int argc, char **argv){
void (*ptr)(void);
FILE *fo = fopen(argv[1],"r");
int l = fseek(fo,0,SEEK_END);
fread((void*)ptr,l*sizeof(char),1,fo);
ptr();
return 0;
}
我知道我可能会以错误的方式进行操作.
I know I am probably going about this the wrong way.
推荐答案
虽然您显示的代码与位置无关,所以可以在任何地方执行,而不是为数据分配内存.操作系统的实际版本强制执行内存访问保护,明确拒绝对数据内存的执行.但是首先,您的程序中存在一个大错误,您尚未为要加载的代码定义任何内存:
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
从磁盘读取数据时,它将被写入内存中的某个位置,从而触发内存访问错误.要从OS获取可执行内存,您可以使用 VirtualAlloc ,然后使用其他功能作为 VirtualProtect .然后,您必须为函数指针分配可执行内存的地址,并且仅在那时才从磁盘读取代码.该过程通常用于恶意软件或代码注入,并且可以用于本地或远程过程,这就是为什么我不会给出更好的解释的原因.好奇心很好,但是...;-)
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... ;-)
这篇关于是否可以将二进制文件加载到内存中并在Windows中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!