New books from Apress

Peter Corlett abuse at
Sun May 21 10:58:21 BST 2006

Andy Armstrong <andy at> wrote:
> I wonder how fast you could get a Perl 6502 emulator going... I'm almost
> tempted.

That's a very interesting question now you come to mention it. Let's look at
the standard naive C approach:

* Variables for the registers;
* A 256-element switch() for the instruction decode; and
* A 64kB char array for the memory.

A simple bit of code, right?

Well.. the 6502's memory isn't a flat 64kB area of RAM: it's RAM, ROM, MMIO
and bank-switched. There's lots of inefficient frobbing of status registers.
Some instructions change how they work based on the status registers, in
particular BCD mode. Suddenly the code explodes with special cases and it's
not fun to hack on any more.

We use Perl to avoid code that's not fun to hack on. So let's see what Perl
gives us:

We don't have a switch() statement which initially looks like a deficiency,
but forces us to step back and look for a different approach. An array of
coderefs looks good. It gets better when you realise that to support BCD
mode, you can have a parallel array with the appropriate instructions
replaced. Switch between them as appropriate.

Memory would obviously be a 65,536-element array. Some other approaches
might suggest themselves, until you realise that MMIO is suddenly easy once
you have tied scalars on the job. Bank-switching? That's what splice() is

But we're still emulating a dumb apprach in a clever way.

Keep the 65,536-element memory array. Have a parallel array of coderefs.
When you come to execute code, check the coderef and if it doesn't exist,
start scanning forwards in memory and create a suitable coderef. Tie the
memory scalars to notify you on writes to catch self-modifying code and thus
invalidate the coderefs. Hey presto, a crude JIT. There's plenty of gotchas
(this is a *hard* problem with lots of edge cases), but it'd be educational
and potentially less horrible to debug than a C implementation.

>> If I embark upon this vital project, I'll probably do it in C++ for that
>> extra "eww" feeling.
> Eww.


PGP key ID E85DC776 - finger abuse at for full key

More information about the mailing list