如何制作可以运行x86十六进制代码的C程序 [英] How to make a C program that can run x86 hex codes
问题描述
我有一系列可转换为汇编指令的十六进制代码,我想用C创建可以执行这些指令的程序.
I have an array of hex codes that translate into assembly instructions and I want to create program in C that can execute these.
unsigned char rawData[5356] = {
0x4C, 0x01, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x0C, 0x00, 0x00,
0x3D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x2E, 0x74, 0x65, 0x78,
0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xB4, 0x05, 0x00, 0x00, 0xA4, 0x01, 0x00, 0x00, 0x68, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x20, 0x00, 0x30, 0x60,
0x2E, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x30, 0xC0, 0x2E, 0x62, 0x73, 0x73, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x30, 0xC0, 0x2F, 0x34, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x58, 0x07, 0x00, 0x00, 0x32, 0x0C, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x10, 0x30, 0x60,
0x2F, 0x33, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x6C, 0x07, 0x00, 0x00,...and so on
推荐答案
使用x86可以实现.
这是一个小样本.分配具有写/执行权限的页面,并在其中复制您的操作码.
Here's a small sample. Allocate the page with write/exec privileges and copy your opcodes there.
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#endif
int main(){
char opcodes[] = { ..... };
#ifdef _WIN32
HANDLE mem_handle = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, length, NULL);
void* mem_map = MapViewOfFile( mem_handle, FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE, 0x0, 0x0, length);
#else // posix
void* mem_map = mmap(NULL, sizeof(opcodes), PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
#endif
memcpy(mem_map, opcodes, sizeof(opcodes));
(( void(*)() )mem_map)();
return 0;
}
对于POSIX系统,请使用mmap()调用.
For POSIX systems use the mmap() call.
还阅读有关蹦床的信息.请参阅链接: http://pages.cs.wisc.edu/~weinrich /papers/method_dispatch.pdf
Also read about trampolines. See the link: http://pages.cs.wisc.edu/~weinrich/papers/method_dispatch.pdf
您没有告诉您这是一个完整的程序还是单个功能.相对/绝对地址可能存在问题.
You didn't tell if this is a complete program or a single function. There might be problems with relative/absolute adressing.
小注释:此代码也适用于PowerPC和启用了MMU的ARM.
Small remark: this code works also with PowerPC and ARMs with MMU enabled.
这篇关于如何制作可以运行x86十六进制代码的C程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!