【c-linux】linux系统,在c中写机器码,存到数组里,然后直接运行它

x86:

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

char code[] = {0x55,0x48,0x89,0xe5,0x89,0x7d,0xfc,0x48,
    0x89,0x75,0xf0,0xb8,0x2a,0x00,0x00,0x00,0xc9,0xc3,0x00};
/*
00000000004004b4 <main> 55                          push   %rbp
00000000004004b5 <main+0x1>  48 89 e5               mov    %rsp,%rbp
00000000004004b8 <main+0x4>  89 7d fc               mov    %edi,-0x4(%rbp)
00000000004004bb <main+0x7>  48 89 75 f0            mov    %rsi,-0x10(%rbp)
'return 42;'
00000000004004bf <main+0xb>  b8 2a 00 00 00         mov    $0x2a,%eax
'}'
00000000004004c4 <main+0x10> c9                     leaveq 
00000000004004c5 <main+0x11> c3                     retq 
*/

int main(int argc, char **argv) {
    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));

    int i = ((int (*) (void))buf)();
    printf("Done, return %d\n", i);

    return 0;
}

运行成功:

gcc example.c -o example
./example
Done, return 42

原帖:https://stackoverflow.com/questions/18476002/execute-binary-machine-code-from-c

难点在于栈中的数据,操作系统是拒绝执行的,如果强制转换成函数指针执行,会发生段错误,core dumped。
因此该博主用mmap把这一段机器码放到可以执行的区域。

另:
查看函数的机器码:

gcc -c target.c -o target.o
objdump -d -Mintel target.o
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值