Crate z80emu

source ·
Expand description

§Z80 emu

z80emu crate provides building blocks for emulators based on Zilog’s Z80 CPU family.

To build the crate with no_std support make sure to set default-features to false and select the required features only.

  _______
=|       |=
=|       |=
=|       |= ---------------- =[   Clock   ]
=|       |=                         |
=|       |=                         |
=|       |=                         |
=|       |=                         |
=|       |=                         |
=|  Cpu  |=                    _____|_____
=|       |=                   |           |
=|  Z80  |= \                 |           |
=|       |= <--------------> =| Memory+Io |=:::::
=|       |= /                 |           |
=|       |=                   |___________|
=|       |=
=|       |=
=|       |=
=|       |=
=|       |=
=|_______|=

z80emu was developed as an attempt to create a minimalistic emulation library. It provides the necessary tools for the retro emulators to be built upon, avoiding any assumptions about side effects of those emulators.

The idea is to leverage the Rust’s trait based OO model for this purpose.

There are four important traits in this library - the essential components of an emulated computer:

  • Cpu - an interface to the finite state machine that can alter its state by executing the machine code instructions as one of the Z80 family processors.
  • Clock - an interface to the CPU cycle (T-state) counter, which can be used to synchronize the emulation with the emulator’s side effects.
  • Memory - an interface to the host’s memory that the Cpu is using to read from and write to it.
  • Io - an interface to the host’s I/O devices that the Cpu is using to access them.

z80emu crate provides the Cpu trait implementations and an example implementation for the Clock trait. The rest of the traits need to be implemented by the emulator’s developer. Please see the documentation of this module for more information on how to implement them.

The Z80 struct implements the Cpu trait with a selectable Flavour as its generic parameter.

Currently, there are 3 “flavour” implementations for which the following CPU types are available:

The difference between each of them is very subtle and only affects undocumented behavior. Alternatively, a Z80Any enum can be used if changing of the z80::Flavour in run time is required.

§Debugger

The Cpu interface provides ways to debug the executed Z80 machine code. Cpu::execute_next, Cpu::execute_instruction and Cpu::irq methods accept the optional callback argument: debug. The callback, if provided, is being fed with the extended information about the instruction being executed, and can be used to display a human-readable text of the disassembled instructions or gather statistics.

In z80emu the command execution code and the debugger are both implemented in a single unit. This way there is only a single machine code dispatcher. This minimizes the probability of a debugger suffering from “schizophrenic effects” showing results not compatible with the execution unit. The Rust and LLVM compilator can optimize out the debugger parts when they are not needed.

The debugger provides information in a form of a CpuDebug struct which implements Display, LowerHex, and UpperHex traits. The debug closure can just print the information out or provide a complete customized debugging solution.

§How To

Start by inspecting the tests directory and the shuffle example. All of the test cases run minimalistic Z80 virtual computers and can be useful in learning the essentials.

For a bigger picture see the crate’s repository example implementation of the imaginary Z80 based computer, to see how a system bus could be implemented with custom PIO and CTC peripheral chips.

For the most optimized emulator code execution, when the debugger is not needed, the emulators should use the Cpu::execute_with_limit method to execute code in time frames. The code is executed in a loop where mostly used Z80 registers can be kept in host CPU registers or its data cache. The optimizer removes all debugging related code for this method, even though it uses exactly the same instruction execution source underneath as Cpu::execute_next.

§Example

use z80emu::*;
use opconsts::HALT_OPCODE;
// Let's use the simple T-state counter.
type TsClock = host::TsCounter<i32>;

// Let's add some memory.
#[derive(Clone, Debug, Default)]
struct Bus {
    rom: [u8;11]
}

impl Io for Bus {
    type Timestamp = i32;
    type WrIoBreak = ();
    type RetiBreak = ();
}

impl Memory for Bus {
    type Timestamp = i32;
    fn read_debug(&self, addr: u16) -> u8 {
        self.rom[addr as usize]
    }
}

const FIB_N: u8 = 24; // 1..=24

let mut tsc = TsClock::default();
let mut fibbo = Bus { rom: [
    0x21, 0x00, 0x00, // 0x0000 LD   HL, 0x0000
    0x11, 0x01, 0x00, // 0x0003 LD   DE, 0x0001
    0xEB,             // 0x0006 EX   DE, HL
    0x19,             // 0x0007 ADD  HL, DE
    0x10, 0xFC,       // 0x0008 DJNZ 0x0006
    HALT_OPCODE       // 0x000A HALT
] };
let mut cpu = Z80NMOS::default();
cpu.reset(); // PC = 0
cpu.set_reg(Reg8::B, None, FIB_N); // Cpu register B = FIB_N
// Let's calculate a Fibbonacci number
loop {
    match cpu.execute_next(&mut fibbo, &mut tsc,
            Some(|deb| println!("{:#X}", deb) )) {
        Err(BreakCause::Halt) => { break }
        _ => {}
    }
}
// the content of the HL registers
let result = cpu.get_reg16(StkReg16::HL);
assert_eq!(result, 46368); // Fib(24)
// the number of T-states passed
assert_eq!(tsc.as_timestamp(), 10+10+(FIB_N as i32)*(4+11+13)-5+4);

Re-exports§

Modules§

  • Utilities for disassembling Z80 machine code.
  • This module contains traits that should be implemented by the builder of the host computer.
  • Helper macros when implementing Io, Memory and Clock for wrapper types.
  • Selected Z80 opcodes.
  • A home of the Cpu implementations.

Macros§

Structs§

  • This struct is being passed to the user debugger function when the command is being executed.
  • Z80 Cpu Flags.
  • A struct that represents a register pair, that can be treated as a single 16-bit register or a separate 8-bit (MSB/LSB) registers.

Enums§

Constants§

Traits§

  • The Cpu trait provides means to execute and debug machine code or change the state of self at User’s will.

Type Aliases§

  • The type that stores a copy of the instruction’s full byte code.
  • This type can be passed to Cpu methods that require a debug argument.