在 C 中,确保多段代码的汇编指令数量是固定的
在我正在编写的虚拟机中,我希望能够以类似于以下伪代码的方式分派命令。
add: reg[memory[pc+1]] = reg[memory[pc+1]] + reg[memory[pc+2]]; pc += 2; goto done;
sub: reg[memory[pc+1]] = reg[memory[pc+1]] - reg[memory[pc+2]]; pc += 2; goto done;
cmp: /* Would take more space than simply x = x + y; */ goto done;
for(int pc = 0; memory[pc] != END; pc++) {
goto currentPositionInMemorySomehow + (memory[pc] * lengthOfInstruction);
done:
}
其中内存是包含字节码的数组,而 pc 是程序计数器。然而,要做到这一点,我们跳转到的每个位置在下一个块之前都具有完全相同数量的指令。转向汇编并不是一种选择,除非有一个出色的与平台无关的汇编代码,它允许人们采用相同的代码并编译到 Linux、Mac 和 Windows。无论每个处理器位于哪个处理器之上。任何和所有的帮助将不胜感激。
In a virtual machine I'm writing, I want to be able to dispatch commands in a manner similar to the following pseudo code.
add: reg[memory[pc+1]] = reg[memory[pc+1]] + reg[memory[pc+2]]; pc += 2; goto done;
sub: reg[memory[pc+1]] = reg[memory[pc+1]] - reg[memory[pc+2]]; pc += 2; goto done;
cmp: /* Would take more space than simply x = x + y; */ goto done;
for(int pc = 0; memory[pc] != END; pc++) {
goto currentPositionInMemorySomehow + (memory[pc] * lengthOfInstruction);
done:
}
Where memory is an array containing the bytecode, and pc a program counter. To do this however requires that each of these positions we jump to has the exact same number of instructions before the next block. Dropping down to assembly is not an option, unless there is a wonderful platform agnostic assembly code, which allows for one to take the same code and compile to Linux, Mac, and Windows. Regardless of the processor each is sitting on top of. Any and all help will be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然我不知道有什么方法可以准确实现您想要的目标(并且我知道唯一允许计算跳转的编译器是 gcc),但我建议您只需使用
switch
,它是最不错的优化编译器将转换为跳转表或计算跳转,以适合您平台的方式正确处理指令对齐。While I don't know of a way to achieve exactly what you want (and the only compiler I know that allows computed jumps is gcc), I suggest you simply use a
switch
, which most decent optimizing compilers will transform into either a jump table, or a computed jump, handling instruction alignment correctly in a way appropriate for your platform.您似乎想要编写一些 C 代码,这些代码将编译为大小独立于目标平台的可执行代码。这根本就是一个不切实际的目标。
You appear to want to write some C code that will compile to executable code of size that is independent of target platform. That is quite simply an unrealistic goal.