2

Creating Your Own Abstract Processor is a quick paper on what I am trying to do.

http://malcon.org/ctm.rar is the exact specifications on what the emulator should be.

I am writing a sort of an emulator in Perl. This program will read in a binary file and process the hex of the binary into actions, how a processor works, but software based with different opcodes. Just a challenge thing.

Anyhow, I am not entirely sure how to read the binary file into an array and then assign the hex from the array to the opcodes. This is part of my code:

my $opcode='';
my $file= "path/to/file";
my $IP=0;
my $SP=0;
my $FLAG=0;
my $A=0;
my $B=0;
my $X=0;
my @STACK=(0);

open(F, "<".$file) || die("Could not open file");
binmode(F);
my @ROM = <F>;
close(F);

while($IP >= 0)
{
    $opcode="$ROM[$IP]";
    if ($opcode eq 11) {
        $A = $STACK[$SP];
        $IP++;
    }
    if ($opcode eq 12) {
        $B = $STACK[$SP];
        $IP++;
    }
    if ($opcode eq 13) {
        $A = $B;
        $IP++;
    }
    if ($opcode eq 14) {
        $B = $A;
        $IP++;
    }

This is just the part of the code I need help with. If you need to see more of it for some reason, just let me know.

So I changed my code to reflect an answer above, my code now looks like this:

my $opcode='';
my $file= "CTM-bootrom";
my $IP=0;
my $SP=0;
my $FLAG=0;
my $A=0;
my $B=0;
my $X=0;
my @STACK=(0);

open my $ROM, '<:raw', $file or die "Cannot open '$file': $!";

{
    local $/ = \1; # Read one byte at a time
    while (my $byte = <$ROM>){
        while($IP >= 0)
        {
            $opcode=$ROM[$IP];
            if ($opcode eq 11) {
                $A = $STACK[$SP];
                $IP++;
            }
            if ($opcode eq 12) {
                $B = $STACK[$SP];
                $IP++;
            }
            if ($opcode eq 13) {
                $A = $B;
                $IP++;
            }

But now I get an error:

Use of uninitialized value $opcode in string eq at Aod8.pl line 73,

<$ROM> to me it looks like opcode is initialized... How can I fix this problem?

1

4 Answers 4

2

I don't necessarily think it is a good idea to read the binary one character at a time (although, for small enough files, you'll be fetching from a buffer most of the time). Conceptually, reading the file into a flat array is better. You can get that by using

my @ROM = do {
    local $/ = \1;
    map ord, <$fh>;
};

I think that answers the gist of your question.

Now, as for the idea of not reading the entire file into an array, but using the file itself as the executable image, here is a little script I wrote based on earlier versions of this post and feedback.

Please note that the whole scalar filehandle thing is there to provide scaffolding for running ROMs included in the article you linked by copying and pasting instead of having to create binary files.

#!/usr/bin/env perl

use strict;
use warnings;

use Fcntl ':seek';
use Try::Tiny;

my %ROMS = (

    rom1 => [0x04, 0x41, 0x09, 0x02, 0x0a],

    rom2 => [
        0x04, 0x41, 0x09, 0x02,
        0x07, 0x09, 0x02, 0x07,
        0x09, 0x02, 0x07, 0x09,
        0x02, 0x07, 0x09, 0x02,
        0x0A,
    ],

    rom3 => [
        0x04,   69, 0x09, 0x02, 0x04,  110, 0x09, 0x02,
        0x04,  116, 0x09, 0x02, 0x04,  101, 0x09, 0x02,
        0x04,  114, 0x09, 0x02, 0x04,   32, 0x09, 0x02,
        0x04,   97, 0x09, 0x02, 0x04,   32, 0x09, 0x02,
        0x04,   67, 0x09, 0x02, 0x04,  104, 0x09, 0x02,
        0x04,   97, 0x09, 0x02, 0x04,  114, 0x09, 0x02,
        0x04,   32, 0x09, 0x02, 0x04,   58, 0x09, 0x02,
        0x04,   32, 0x09, 0x02, 0x04,   50, 0x03, 0x01,
        0x04,    2, 0x03, 0x04,   89, 0x09, 0x02, 0x04,
         111, 0x09, 0x02, 0x04,  117, 0x09, 0x02, 0x04,
         32,  0x09, 0x02, 0x04,   84, 0x09, 0x02, 0x04,
         121, 0x09, 0x02, 0x04,  112, 0x09, 0x02, 0x04,
         101, 0x09, 0x02, 0x04,  100, 0x09, 0x02, 0x04,
          32, 0x09, 0x02, 0x04,   58, 0x09, 0x02, 0x04,
          32, 0x09, 0x02, 0x04,   50, 0x03, 0x02, 0x0A,
    ]

);

for my $rom (sort keys %ROMS) {
    my $rom_s = join '', map chr, @{ $ROMS{ $rom } };

    open my $rom_h, '<:raw', \$rom_s
        or die "Cannot open handle to ROM string: $!\n";

    print "Executing $rom\n";

    try {
        execute($rom_h);
    }
    catch {
        print "\n$rom: $_\n";
    };

    close $rom_h
        or die "Cannot close handle to ROM string: $!\n";
}

sub get_next_byte {
    my ($fh) = @_;
    my $byte = do {
        local $/ = \1;
        scalar <$fh>;
    };

    return unless defined $byte;

    $byte = ord $byte;

    return $byte;
}

sub execute {
    my ($ROM) = @_;

    my $FLAG = 0;
    my $SP = 0;
    my $X = 0;
    my @STACK;

    my @machine = (

        # NOP
        sub {},

        # INPUT
        sub { $STACK[$SP] = ord(getc STDIN) },

        # OUTPUT
        sub { printf STDOUT '%c', $STACK[$SP] },

        # MOV SP, X
        sub { $SP = $X },

        # MOV X, DATA
        sub {
            $X = get_next_byte($ROM);
        },

        # CMP X, DATA
        sub {
            $FLAG = $X - get_next_byte($ROM);
        },

        # JE
        sub {
            my $offset = get_next_byte($ROM);

            if ($FLAG == 0) {
                seek $ROM, $offset, SEEK_CUR
            }
        },

        # INC X
        sub { $X += 1 },

        # INC SP
        sub { $SP += 1 },

        # MOV [SP], X
        sub { $STACK[$SP] = $X },

        # HALT
        sub {
            die "HALT\n";
        },
    );

    while (1) {
        my $opcode = get_next_byte($ROM);

        last unless defined $opcode;

        if (($opcode >= 0) and ($opcode < @machine)) {
            $machine[ $opcode ]->();
        }
        else {
            die sprintf(
                "Invalid opcode '%02x' at offset '%x'\n",
                $opcode, $.,
            );
        }
    }
}

Output:

Executing rom1
A
rom1: HALT

Executing rom2
ABCDE
rom2: HALT

Executing rom3
Enter a Char : d
You Typed : d
rom3: HALT
9
  • Quite the opposite, he does need the whole file to be loaded; he's just loading it wrong.
    – ikegami
    Nov 21, 2011 at 21:06
  • Why can't the ROM be on disk? Nov 21, 2011 at 23:20
  • Memery accessed linearly. If you want to do a seek before each read, go ahead, but it's definitely a waste. And then there's the case that the ROM wouldn't be very read-only if you didn't make a copy of it into RAM. Did you forget about store operations?
    – ikegami
    Nov 22, 2011 at 2:52
  • I see you added a dispatch table. I'm not sure that's the best approach. If any thought went into his virtual machine, the opcode isn't indicated by the whole byte. Most of the bits of the byte are actually the operands (i.e. data). There are really only 12 opcodes or so.
    – ikegami
    Nov 22, 2011 at 3:02
  • s/Memery accessed linearly./Memory isn't accessed linearly./
    – ikegami
    Nov 22, 2011 at 3:25
1

If $opcode is undef, then $ROM[$IP] is undef.

In the second version of the code, you didn't show @ROM being populated, so that's not surprising that $ROM[$IP] is undef then.

The first version of the code is closer to what you want. However, @ROM is incorrectly initialised. Each line of the file (which isn't even made of lines) is assigned to an element of @ROM, but you want each byte of the file to be assigned to an element of @ROM. This is done as follows:

my @ROM = do {
   open(my $fh, '<', $file)
      or die("Can't open ROM file \"$file\": $!\n");
   binmode($fh);
   local $/;  # Read entire file at once.
   map ord, split //, <$fh>
};

After fixing up the rest of the code, it looks like the following:

my @STACK;
my $A  = 0;
my $B  = 0;
my $SP = 0;
my $IP = 0;
for (;;) {
   die(sprintf("Bad address 0x%04X\n", $IP)) if $IP >= @ROM;
   my $instruction = $ROM[$IP++];

   if    ($opcode == 0x11) { $A = $STACK[$SP]; }
   elsif ($opcode == 0x12) { $B = $STACK[$SP]; }
   elsif ($opcode == 0x13) { $A = $B; }
   ...
   else { die(sprintf("Bad opcode 0x%02X\n", $opcode)); }
}

Note that :raw is not quite equivalent to binmode despite documentation to that effect.

Note the use or ord to convert the chars into their numerical value, and the use of numerical comparison operators (==) to compare those numbers.

Note that I used hexadecimal numbers. Hex (or maybe octal depending on the machine being emulated) will be clearer than using decimal since similar opcodes tend to vary in bits, not digits. Furthermore, the numbers you were provider are already in hex, so opcode 11 is actually seventeen.

$char_from_file eq 11          # XXX What you had.
$char_from_file eq chr(0x11)   # Ok, but a bit suboptimal.
ord($char_from_file) == 0x11   # Ok. What I have.
18
  • packetstormsecurity.org/files/105938/Abstract-Processor.pdf This is a quick paper on what I am trying to do. malcon.org/ctm.rar This is the exact specifications on what the emulator should be. Nov 22, 2011 at 2:37
  • It does seem to have a separate stack. That's very unrealistic, but so be it. I've removed my comments regarding the stack.
    – ikegami
    Nov 22, 2011 at 3:37
  • @quantumdisaster, The opcode numbers are in hex in the PDF. so when you were comparing to eleven, you should have been comparing to seventeen (0x11). Adjusted my post.
    – ikegami
    Nov 22, 2011 at 3:46
  • 1
    @quantumdisaster, Whoever designed that machine doesn't know much about machine design. This would be very inefficient to implement in hardware.
    – ikegami
    Nov 22, 2011 at 3:58
  • the line map ord, split puts the data in my array as decimal numbers, i need them there as hex values Nov 22, 2011 at 17:23
0

If you just want split the file byte by byte to @ROM, try

local $/; # get the whole file once, see perldoc perlvar for details
my @ROM = split //, <F>;
0

I got it now...everything is now working like needed:

my $IP=0;
my $FLAG=0;
my $SP=0;
my $A=0;
my $B=0;
my @STACK=(0);
my $byte=0;
$| = 1;

open(BOOTROM, "<bootrom.txt");
binmode(BOOTROM);

my (@ROM, $instruction);
while ((read BOOTROM, $instruction, 1) != 0) {
    @ROM[$IP] = $instruction;
    $IP++;
}
close(BOOTROM);

$IP = 0;
while ($IP >= 0 && $byte != 0x3C) {
    $byte = ord(@ROM[$IP]);

    if ($byte == 0x11) {
        $A = (@STACK[$SP]);
        $IP++;
    }
    elsif ($byte == 0x12) {
        $B = (@STACK[$SP]);
        $IP++;
    }
    elsif ($byte == 0x13) {
        $A = $B;
        $IP++;
    }
    elsif ($byte == 0x14) {
        $B = $A;
        $IP++;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.