C 语言执行机器码指令
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
int main() {
typedef int (*func_t)();
unsigned char code[] = {
0xb8, 0x08, 0x00, 0x00, 0x00, // mov eax, 0x08
0xc3 // ret
};
// 申请一片可读可写可执行的匿名私有内存区域
unsigned char *pcode = (unsigned char *)mmap(
NULL, 4096, PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memcpy(pcode, code, sizeof(code));
func_t foo = pcode;
printf("%d\n", foo());
munmap(pcode, 4096);
return 0;
}