Monday, 6 October 2008

Remember Me

The thing about emulating a CPU is, it needs something to work with - after all, what is a CPU but a fast little box for reading data and then spitting it out somewhere having changed it in some way? Every byte of data passing through a CPU is either a nugget of raw data, coming in, an instruction to do something to it, or a nugget of processed data on its way out. Disregarding those instructions that merely change the state of the CPU in some way, of course - though even they still have to come from somewhere.

So to get the emulation to do anything, we have to connect it to a structure of some sort, containing some instructions and some data to work with. That means, in the case of a 6502, a memory object to represent the 64K that it can talk to - the simplest approach (in a high level language like C#) being a 65536-element byte array, although I also want some extra functionality that will let me provide a small amount of memory protection, and also make it easier to see what memory is allocated. To do this, I decided to make each element in the array a structure that combines both the memory 'cell' itself, plus a couple of metadata items that tell me something about what that cell is doing - so, for example, if the CPU attempts to execute an STA to a memory cell that's marked as ROM, we can just ignore it. 65000-odd of those strung together, and there's our memory space - though I've since switched from Byte storage units to Integers.

With a fairly simple array of my MemoryCell structure, plus a few routines to manage the initialisation of bits of it as either RAM or ROM (where either of these can be loaded from binary files) or as Undefined - essentially areas of 'dead' or unmapped memory, plus a special definition of Mapped I/O (of which more later), we have a mechanism to emulate any configuration of a 64K memory space. Initially we'll be setting it all up to look like an unexpanded (5K) VIC-20, but there's nothing at all to stop us changing that to reflect the map of any other 6502-based machine, anywhere, ever. Want to embed our CPU emulation in a C64? Or an Atari VCS? Apple II? BBC Micro? Atari 800? KIM-1? PET? You get the idea. Obviously the specific hardware needs emulating in each case as well, but the memory model will fit them all.

Note though, that this rather neat flexibility can also be a right pain if you make even the tiniest mistake when configuring it. I'll recount that little distraction next time...

1 comments:

Loada (from YY) said...

Sounds good so far!