Example Virtual Machine
A Local Inukshuk
This is a small virtual machine that runs the Sieve of Eratosthenes and explores managing the instruction opcode set.
Sieve of Eratosthenes in 'C'This is the original sieve.c program I downloaded from the Web. This is what I hand assembled into the VM language.
Some Opcode ManagementThese are the 3 files involved:
HALT is instruction 0. It is a reserved opcode. It helps to make the VM stop when it runs out of bounds.
Key the opcodes into defines.v.
Then compile and run mkdefine.c which generates define.h.
Why This is Good
MakingThis is the Windows / Watcom batch file:
This is the Unix / gcc script:
vmsieve.cThis is the toplevel 'C' program.
It combines the subfiles into a complete program.
prog.sThis is the instruction word.
main.cThis is the main program. Scroll to the bottom to see the main loop.
The virtual machine has 256 registers and a 10000 integer word memory.
The first part of the program is 2 hand assembled, hard coded programs in the virtual machine language.
The comments are from the original sieve.c.
I used a couple of hacks to make hand assembly easier.
There are 256 registers so the use of character 'A' translates to register 65 and register 'Z' is register 90. It makes the code a little more readable.
The goto labels are arbitrary numbers, not absolute jumps. The Linker turns the label numbers into absolute addresses. Hand assembly and absolute addresses are just too painful.
The p variable points to the program to be run.
Why the Disassembler?Think of the disassembler as your own personal coding Yoda.
Having to implement each instruction twice makes you think.
A disassembler is a good tool to have when developing.
One function builds an instruction and another function executes it.
Being able to dump the instruction as it sits in memory allows you to see if the instruction was properly compiled.
Build all the Tools TogetherA complete set of tools consists of a
Start with just the HALT and NOP instructions.
IF OPCODE[IP] == 0 THEN HALTI borrowed the concept that opcode 0 should halt the machine from a CPU designer somewhere on the web. I would like to extend my thanks to this gentleman.
His theory was
"If the CPU hits a instruction with an opcode zero, it stops."Because
"It is easy and fast to initialize a huge block of memory to all zeros. Setting unused or unknown values to zero is a common practice."So that
"If something goes FUBAR, the preferred failure mode is to HALT."
Other than HALT == 0, there are no other opcode string to opcode number mappings with a special meaning.
Copyright © 2008, 2010, 2011, 2012