执行dynamiclly malloc代码时出现“分段错误”

时间:2012-08-05 06:08:34

标签: c assembly posix x86-64

我在x86_64上编写了一个示例代码,尝试执行dynamiclly malloc代码。 有一个

  

编程接收信号SIGSEGV,分段故障。   0x0000000000601010在? ()

0x0000000000601010是 bin 的位置,有人可以说明原因吗?谢谢!

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/mman.h>
volatile int sum(int a,int b)
{
    return a+b;
}

int main(int argc, char **argv)
{
   char* bin = NULL;    
   unsigned int len = 0;
   int ret = 0;
   /*code_str is the compiled code for function sum.*/
   char code_str[] ={0x55,0x48,0x89,0xe5,0x89,0x7d,0xfc,0x89,
          0x75,0xf8,0x8b,0x45,0xf8,0x03,0x45,0xfc,0xc9,0xc3};
   len = sizeof(code_str)/sizeof(char);
   bin = (char*)malloc(len);
   memcpy(bin,code_str,len);
   mprotect(bin,len , PROT_EXEC | PROT_READ | PROT_WRITE);
   asm volatile ("mov $0x2,%%esi \n\t"
        "mov $0x8,%%edi \n\t"
        "mov %1,%%rbx \n\t"
        "call *%%rbx "
        :"=a"(ret)
        :"g"(bin)
        :"%rbx","%esi","%edi");

   printf("sum:%d\n",ret);
   return 0;
}

2 个答案:

答案 0 :(得分:2)

如果不检查系统功能的返回,切勿执行此类操作。我的mprotect手册页特别说:

   POSIX  says  that  the  behavior of mprotect() is unspecified if it
   is applied to a region of memory that was not obtained via mmap(2).

所以不要使用malloc ed缓冲区。

此外:

  • 缓冲区大小只是sizeof(code_str),没有理由除以sizeof(char)(保证为1,但这不会使其正确)。
  • 如果您将其更改为malloc,则无需强制转换mmap
  • code_str的正确类型为unsigned char,而非char

答案 1 :(得分:0)

问题是bin地址应该与多个PAGESIZE对齐,否则mprotect将返回-1,参数无效。

   bin = (char *)(((int) bin + PAGESIZE-1) & ~(PAGESIZE-1));//added....
   memcpy(bin,code_str,len);
   if(mprotect(bin, len , PROT_EXEC |PROT_READ | PROT_WRITE) == -1)
   {
     printf("mprotect error:%d\n",errno);
     return 0;
   }