Skip to content

Commit

Permalink
Populate all traps from 0x0000-0xFFFF with a NOP.
Browse files Browse the repository at this point in the history
This means the CPU doesn't need to report a warning/error.

Also updated the trap-signature such that each invoked handler
knows what number it was called by - which might be useful in
future.
  • Loading branch information
skx committed Jul 1, 2018
1 parent 9153ce2 commit 163fc32
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 9 deletions.
9 changes: 3 additions & 6 deletions cpu/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -720,14 +720,11 @@ func (c *CPU) Run() {
debugPrintf("TRAP\n")
c.ip += 1

addr := c.read2Val()
num := c.read2Val()

fn := TRAPS[addr]
fn := TRAPS[num]
if fn != nil {
fn(c)
} else {
fmt.Printf("Trap function not defined: 0x%04X\n", addr)

fn(c, num)
}
default:
fmt.Printf("Unrecognized/Unimplemented opcode %02X at IP %04X\n", instruction, c.ip)
Expand Down
20 changes: 17 additions & 3 deletions cpu/traps.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ package cpu

import (
"bufio"
"fmt"
"os"
)

//
// TrapFunction is the signature for a function that is available
// as a trap.
//
type TrapFunction func(c *CPU)
type TrapFunction func(c *CPU, num int)

//
// Create an array of trap-functions.
Expand All @@ -31,14 +32,18 @@ var reader *bufio.Reader
// Trap Functions now follow
//

func TrapNOP(c *CPU, num int) {
fmt.Printf("Trap function not defined: 0x%04X\n", num)
}

// StrLenTrap returns the length of a string.
//
// Input:
// The string to measure in register 0.
// Output:
// Sets register 0 with the length
//
func StrLenTrap(c *CPU) {
func StrLenTrap(c *CPU, num int) {
str := c.regs[0].GetString()
c.regs[0].SetInt(len(str))
}
Expand All @@ -50,7 +55,7 @@ func StrLenTrap(c *CPU) {
// Ouptut:
// Sets register 0 with the user-provided string
//
func ReadStringTrap(c *CPU) {
func ReadStringTrap(c *CPU, num int) {
text, _ := reader.ReadString('\n')
c.regs[0].SetString(text)
}
Expand All @@ -61,4 +66,13 @@ func init() {
reader = bufio.NewReader(os.Stdin)
TRAPS[0] = StrLenTrap
TRAPS[1] = ReadStringTrap

// Fill in the rest of the traps with
// a function that will just report that
// the given ID is not implemented
for i := 0; i < 0xFFFF; i++ {
if TRAPS[i] == nil {
TRAPS[i] = TrapNOP
}
}
}
18 changes: 18 additions & 0 deletions examples/trap.missing.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#
# About:
#
# This program demonstrates the invokation of a trap-function which isn't
# implemented.
#
# Usage:
#
# $ go.vm run ./trap.missing.in
#
# Or compile, then execute:
#
# $ go.vm compile ./trap.missing.in
# $ go.vm execute ./trap.missing.raw
#

# Call the trap
int 0xf00f

0 comments on commit 163fc32

Please sign in to comment.