栈式虚拟机比较好实现,同时指令也较为简单,类似risc
假设虚拟机指令
push i ;//立即数入栈
add //栈里面最近2元素相加,pop 2后,结果压栈
call //调用栈顶id指向的函数
//脚本
rotate(0,0,20+time()); //绕0,0旋转20+当前时间
编译为中间代码;//具体过程参考编译原理
push time
call
push 20
add
push 0
push 0
push rotate
call
现在的目的是把中间代码翻译为x86指令,然后就可以直接在cpu上面运行。
定义代码转换模板,右边是asm,程序里面使用机器码
push i push i
call pop eax
mov ebx,fun_table
call [eax+ebx]
push eax
add pop eax
pop ebx
add
push eax
通过这个模板,就可以把中间码转换为x86指令
上面的代码转换为
1
push time
2
pop eax
mov ebx,fun_table
call [eax+ebx]
push eax
3
push 20
4
pop eax
pop ebx
add
push eax
5
push 0
6
push 0
7
push rotete
8
pop eax
mov ebx,fun_table
call [eax+ebx]
push eax
最后,可以再稍做优化.
主要有2点优化
push xx
pop eax
优化为mov eax,xx
push eax
pop eax
直接去掉