装载机code从文件到内存中,并用C执行 - 则mprotect失败 [英] Loading MachineCode From File Into Memory and Executing in C -- mprotect Failing

查看:464
本文介绍了装载机code从文件到内存中,并用C执行 - 则mprotect失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我想,当程序运行试图在运行内存则mprotect使其可执行文件时,它打破原始机器code加载到内存中,并从一个C程序中运行它,现在。我也不能完全肯定,如果内存没有得到正确设置它会执行。我目前在Ubuntu Linux x86上运行这个(也许问题是Ubuntu的过度保护?)

Hi I'm trying to load raw machine code into memory and run it from within a C program, right now when the program executes it breaks when trying to run mprotect on the memory to make it executable. I'm also not entirely sure that if the memory does get set right it will execute. I am currently running this on Ubuntu Linux x86 (Maybe the problem is Ubuntu's over-protection?)

我现在有如下:

#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;
}

我得到的编译器警告:

I do get the compiler warning:

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

我没有得到的程序来达到这个code尚未所以我无法看到,如果我的汇编code是做什么它应该。

I've not gotten the program to reach this code yet so I am unable to see if my assembler code is doing what it should.

推荐答案

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

Ok, here's the answer, according to our discussion in the comments :)

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

The memory region should be aligned to the system page size. posix_memalign() call is a right way to allocate memory in such case :)

这篇关于装载机code从文件到内存中,并用C执行 - 则mprotect失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆