Writing a VM - Learnings So Far

Filed under vms on December 29, 2022

I’ve been working on this VM on and off for a month or so now, and I’ve definitely had some ideas of what I could have done better. I’ve learned from this, and I’ll certainly be putting this into practice should I ever try to do something like this again.

Planning out my entire instruction set before coding

I’m in a bit of an awkward spot at the moment with my instruction set, and it’s likely to get a little messy as I go ahead. I’ve been adding instructions piecemeal as I’ve written each blog, and as a result I’m going to end up with bitwise actions and interrupt handling in strange spots in the table.

Were I do this again I’d most definitely plan out my entire instruction set before implementing anything

An accumulator register

What I have now works, but it can be a little verbose and awkward moving things around on registers between each operation. In any future VM I write, I’d like to have a dedicated accumulator register so I don’t clobber my input data.

Access modes and variable length instructions

One of the most awkward things in my VM design is that you can’t directly access memory from an instruction. If I want to use a number, I have to load it into the register before using it. In future, I’d like to be able to have up to two values in subsequent memory slots with flags in my instructions to suggest the mode

Figuring out interrupt handling before starting

Interrupts were another concept I thought I could defer for later as long as I had the basic idea in my head. I think in any future attempts it’ll be one of the first things I implement, since it affects the main execution loop and jumps the PC all over the memory.

Other miscellaneous learnings

I’ve cobbled together a basic assembler, it can’t do any linking yet and in the meantime I’m going to have to figure out how to do offsets and less clumsy address resolution in my second pass. Right now the offset is hardcoded to 0x100.

I should also have a better idea of my package structure, I initially crammed everything into the internal/ package, and have had to do some refactoring as I introduced more general concepts into my code.


I still have a bit to learn about this stuff, but working on this project and doing thorough write ups lets me keep track of my thought process pretty well and see where my thinking was flawed. I would like to eventually pick my NES emulator back up and actually finish it, maybe this project is a good stepping stone into understanding some of the ideas behind the NES hardware a little better.

Stephen Gream

Written by Stephen Gream who lives and works in Melbourne, Australia. You should follow him on Minds