c - 将文件中的 MachineCode 加载到内存中并在 C 中执行——mprotect 失败

标签 c memory machine-code mprotect

你好我正在尝试将原始机器代码加载到内存中并从 C 程序中运行它,现在当程序执行时它在尝试在内存上运行 mprotect 以使其可执行时中断。我也不完全确定如果内存确实设置正确,它就会执行。我目前在 Ubuntu Linux x86 上运行它(也许问题是 Ubuntu 的过度保护?)

我目前拥有的是:

#include <memory.h>
#include <sys/mman.h>
#include <stdio.h>

int main ( int argc, char **argv )
{
 FILE *fp;
 int sz = 0;
 char *membuf;
 int output = 0;

 fp = fopen(argv[1],"rb");

 if(fp == NULL)
 {
  printf("Failed to open file, aborting!\n");
  exit(1);
 }

 fseek(fp, 0L, SEEK_END);
 sz = ftell(fp);
 fseek(fp, 0L, SEEK_SET);


 membuf = (char *)malloc(sz*sizeof(char));
 if(membuf == NULL)
 {
  printf("Failed to allocate memory, aborting!\n");
  exit(1);
 }

  memset(membuf, 0x90, sz*sizeof(char));

 if( mprotect(membuf, sz*sizeof(char), PROT_EXEC | PROT_READ | PROT_WRITE) == -1)
 {
  perror("mprotect");
  printf("mprotect failed!!! aborting!\n");
  exit(1);
 }



 if(!(fread(membuf, sz*sizeof(char), 1, fp)))
 {
  perror("fread");
  printf("Read failed, aborting!\n");
  exit(1);
 }
 __asm__
 ( 
  "call %%eax;"
  : "=a" (output)
       : "a" (membuf)
 );
 printf("Output = %x\n", output);

 return 0;
}

我确实收到了编译器警告:

/tmp/ccVnhHak.s: Assembler messages:
/tmp/ccVnhHak.s:107: Warning: indirect call without `*'

我还没有得到运行这段代码的程序,所以我无法查看我的汇编代码是否在执行它应该执行的操作。

最佳答案

好的,根据我们在评论中的讨论,这是答案:)

内存区域应该与系统页面大小对齐。在这种情况下,posix_memalign() 调用是分配内存的正确方法:)

关于c - 将文件中的 MachineCode 加载到内存中并在 C 中执行——mprotect 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2437873/

相关文章:

interpreter - 机器代码如何与处理器通信?

c++ - "Objective C"与 "C++": difference in statement for method invocation

c - 指针&字符段错误

c - 从函数返回指针

c - 为什么头文件保证了C程序的模块化?

c++ - 如何从 STL 容器中获取只能 move 的类型?

c - 我的代码中是否有任何未初始化的值?

c++ - 大数据的内存组织

c - 强制程序使用输入字符串调用 C 函数

c - 使用 : as delimiter in shell 提取字符串