如何获得C code到执行十六进制字节code? [英] How to get c code to execute hex bytecode?

查看:142
本文介绍了如何获得C code到执行十六进制字节code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个简单的C方法,以便能够在Linux 64位计算机上运行的十六进制字节code。下面是我有C程序:

I want a simple C method to be able to run hex bytecode on a Linux 64 bit machine. Here's the C program that I have:

char code[] = "\x48\x31\xc0";
#include <stdio.h>
int main(int argc, char **argv)
{
        int (*func) ();
        func = (int (*)()) code;
        (int)(*func)();
        printf("%s\n","DONE");
}

这是我试图运行code(\\ X48 \\ X31 \\ XC0)我通过书面方式这个简单的汇编程序(它不应该获得真正做任何事情)

The code that I am trying to run ("\x48\x31\xc0") I obtained by writting this simple assembly program (it's not supposed to really do anything)

.text
.globl _start
_start:
        xorq %rax, %rax

然后编译和objdump的-ING它来获取字节code。

and then compiling and objdump-ing it to obtain the bytecode.

然而,当我运行我的C程序我得到一个分段错误。任何想法?

However, when I run my C program I get a segmentation fault. Any ideas?

推荐答案

下面是一个简单的例子。

Here is a simple example.

main.c中:

#include <sys/mman.h>
#include <string.h>

int main ()
{
  /*                                                              
        mov rax, 60          ; sys_exit
        mov rdi, 2
        syscall                                                   
  */
  char code[] = {
      0x48, 0xb8, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x48, 0xbf, 0x02, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x0f, 0x05
  };

  void *buf;

  /* copy code to executable buffer */    
  buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
              MAP_PRIVATE|MAP_ANON,-1,0);
  memcpy (buf, code, sizeof(code));

  /* run code */
  ((void (*) (void))buf)();

  return 0;
}

运行这个以

./main ;echo $?

我选择了做装配体中的_exit(2)可以很容易地检查code为正常运行。在实践中你会希望你的code的末尾添加一个RET返回控制。

I chose to do an _exit(2) in the assembly to make it easy to check that the code is run properly. In practice you'll want to add a ret at the end of your code to return control.

这篇关于如何获得C code到执行十六进制字节code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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