Skip to main content

Trapping Execution

Source

Adapted from Trapping execution.

The Spectranet CPLD has fixed traps for reset, NMI handling, BASIC extension handling, and ROM paging. It also has one programmable execution trap that can be set to an arbitrary Z80 address, including an address in RAM.

How the programmable trap works

Fixed traps page Spectranet ROM directly when the CPU fetches an instruction at a selected address. The programmable trap instead raises an NMI. After the trapped instruction completes, the CPU enters the NMI handler, which pages in Spectranet ROM and decides whether the event was the programmable trap or a normal NMI button event.

The ROM provides three routines:

  • settrap: sets the trap address, handler, and paging information, then enables the trap
  • disabletrap: disables the trap without changing its address
  • enabletrap: enables an already configured trap

Trap descriptor

settrap takes HL pointing to a descriptor:

  • byte 0: page to map into paging area B, 0 for no paging, or 0xFF for the current area B page
  • bytes 1-2: handler address
  • bytes 3-4: address expected on the stack when the NMI runs
  • bytes 5-6: address to trap

Multi-byte values are little-endian.

The "come from" address is usually one to four bytes after the trapped address because the Z80 completes the current instruction before servicing the NMI.

Handler entry and return

When the handler is called, Spectranet memory is paged in and the main registers have already been pushed. The original page state and the stacked registers must be handled correctly before returning.

For simple cases, the ROM routine TRAPRETURN restores the stack and unpages Spectranet:

EXECTRAP
; handler code
jp TRAPRETURN

More advanced handlers can inspect or alter the stacked registers, change the return address, or leave through custom code, but they must still restore a coherent CPU and memory state.

Limitations

The programmable trap observes instruction fetches. It fires after the trapped instruction has completed, so handlers must account for the instruction length. It is useful for tape traps, debugging hooks, and other controlled interception points, but it is not a general-purpose breakpoint system unless the handler carefully manages side effects and return state.