如何获取c代码来执行十六进制机器码? [英] How to get c code to execute hex machine code?
问题描述
我想要一个简单的 C 方法,能够在 Linux 64 位机器上运行十六进制字节码.这是我拥有的 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[] = "x48x31xc0";
#include <stdio.h>
int main(int argc, char **argv)
{
int (*func) ();
func = (int (*)()) code;
(int)(*func)();
printf("%s
","DONE");
}
我试图运行的代码 ("x48x31xc0"
) 我是通过编写这个简单的汇编程序获得的(它不应该真的做任何事情)
The code that I am trying to run ("x48x31xc0"
) 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得到字节码.
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?
推荐答案
机器代码必须位于可执行页面中.您的 char code[]
位于 read+write data 部分,没有 exec 权限,因此无法从那里执行代码.
Machine code has to be in an executable page. Your char code[]
is in the read+write data section, without exec permission, so the code cannot be executed from there.
这是一个使用 mmap
分配可执行页面的简单示例:
Here is a simple example of allocating an executable page with mmap
:
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
int main ()
{
char code[] = {
0x8D, 0x04, 0x37, // lea eax,[rdi+rsi]
0xC3 // ret
};
int (*sum) (int, int) = NULL;
// allocate executable buffer
sum = mmap (0, sizeof(code), PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
// copy code to buffer
memcpy (sum, code, sizeof(code));
// doesn't actually flush cache on x86, but ensure memcpy isn't
// optimized away as a dead store.
__builtin___clear_cache (sum, sum + sizeof(sum)); // GNU C
// run code
int a = 2;
int b = 3;
int c = sum (a, b);
printf ("%d + %d = %d
", a, b, c);
}
参见关于这个问题的另一个答案 有关 __builtin___clear_cache
的详细信息.
See another answer on this question for details about __builtin___clear_cache
.
这篇关于如何获取c代码来执行十六进制机器码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!