编程小知识之 JIT执行

49 篇文章 1 订阅

本文简单介绍了 JIT 如何动态执行 native code 的知识

自己之前对 DEP(数据执行保护) 有些依稀印象,简单认为在一般情况下,程序是不能动态执行 native code 的,后来突然想到 JIT(简单理解就是一种动态生成并执行 native code 的技术),虽然 JIT 的关注点大多都在如何生成 native code 上,但是自己却对 JIT 如何动态执行 native code 更有兴趣,因为这与我之前对 DEP 的认知相悖.

实际上, DEP 并不是完全禁止 native code 的动态执行,而是禁止"没有执行权限"的 native code 的动态执行,而所谓"没有执行权限"的 native code,就是指那些存储于没有执行权限的内存区域的 native code,对于一般程序而言,其相关的堆栈(可操作内存区域)都仅有读写权限,而没有执行权限,所以一般程序是不能动态执行 native code 的.

但是操作系统基本都提供了申请拥有可执行权限的内存区域的方法,基于此,我们便可以动态执行 native code 了:(代码基本来自这里,有一些改动)

// x86 Windows

#include <stdio.h>
#include <assert.h>
#include <windows.h>

typedef unsigned char byte;

typedef void (*pfunc)(void);

union funcptr {
	pfunc x;
	byte* y;
};

int dynamic_multiply(int arg1, int arg2)
{
	// alloc executable memory
	HANDLE process = GetCurrentProcess();
	byte* buf = (byte*)VirtualAllocEx(process, 0, 1 << 16, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
	assert(buf != 0);

	byte* p = buf;

	*p++ = 0x50; // push eax
	*p++ = 0x52; // push edx

	// mov eax, [arg2]
	*p++ = 0xA1;
	(int*&)p[0] = &arg2; 
	p += sizeof(int*);

	*p++ = 0x92; // xchg edx,eax

	// mov eax, [arg1]
	*p++ = 0xA1;
	(int*&)p[0] = &arg1; 
	p += sizeof(int*);

	// imul edx
	*p++ = 0xF7; 
	*p++ = 0xEA;

	// mov [ret],eax
	int ret = 0;
	*p++ = 0xA3;
	(int*&)p[0] = &ret;
	p += sizeof(int*);

	*p++ = 0x5A; // pop edx
	*p++ = 0x58; // pop eax
	*p++ = 0xC3; // ret

	// call generated code (using union)
	funcptr func;
	func.y = buf;
	func.x();

	// release executable memory
	VirtualFreeEx(process, buf, 0, MEM_RELEASE);
    
	return ret;
}

由于 native code 的关系,上述代码是与架构和平台相关的(x86 Windows),在代码中,我们直接申请了拥有可执行权限(并带有读写权限)的内存区域,一种更安全的做法是,首先申请拥有可执行权限(并带有读写权限)的内存区域,生成完 native code 数据之后,再将该内存区域的写权限去除.

参考资料
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值