11

编程小知识之 JIT执行

 3 years ago
source link: https://blog.csdn.net/tkokof1/article/details/103179521
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
编程小知识之 JIT执行_tkokof1的专栏-CSDN博客

本文简单介绍了 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 数据之后,再将该内存区域的写权限去除.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK