Z80 icon indicating copy to clipboard operation
Z80 copied to clipboard

Highly portable Zilog Z80 CPU emulator written in ANSI C


Zilog Z80 CPU Emulator

Discord

Introduction

The Z80 library implements a fast, small and accurate emulator of the Zilog Z80. It emulates all that is known to date about this CPU, including the undocumented behaviors, MEMPTR, Q and the special RESET. It also has the honor of having been the first open source project to provide full emulation of the interrupt mode 0.

The source code is written in ANSI C for maximum portability and is extensively commented. The aim has been to write a well-structured, easy to understand piece of software; something solid and elegant that can stand the test of time with no need for major changes.

Emulation accuracy

The Zilog Z80 emulator has a classic design with instruction-level granularity. This provides the best performance when speed is a critical factor, while still offering a reasonable flexibility to achieve precision down to the T-state level when accuracy is imperative.

Instruction-level granularity implies that, except in a few well-defined cases, the execution of a given instruction cannot stop until all its internal M-cycles are completed. This kind of emulation is also carried out in an efficient way: the pertinent registers are modified only once per instruction and the T-state counter is updated only after a whole instruction is executed.

That said, instructions, flags, memory accesses, interrupt and reset responses, clock cycles, etc. are accurately emulated as far as is known, according to the technical documentation available, the findings made after decades of research on the Z80 and electronic simulations. And, of course, the emulator passes the most exhaustive tests written to date:

Zilog Z80 CPU Test Suite, by Patrik Rak

This set of programs is intended to help the emulator authors to reach the desired level of the CPU emulation authenticity. Each of the included programs performs an exhaustive computation using each of the tested Z80 instructions, compares the results with values obtained from a real Sinclair ZX Spectrum 48K with Zilog Z80 CPU, and reports any deviations detected.

Results (v1.0)

z80full.tap

Tests all flags and registers.

z80doc.tap

Tests all registers, but only officially documented flags.

z80flags.tap

Tests all flags, ignores registers.

z80docflags.tap

Tests documented flags only, ignores registers.

z80ccf.tap

Tests all flags after executing ccf after each instruction tested.

z80memptr.tap

Tests all flags after executing bit n,(hl) after each instruction tested.
Results (v1.2)

z80full.tap

Tests all flags and registers.

z80doc.tap

Tests all registers, but only officially documented flags.

z80flags.tap

Tests all flags, ignores registers.

z80docflags.tap

Tests documented flags only, ignores registers.

z80ccf.tap

Tests all flags after executing ccf after each instruction tested.

z80memptr.tap

Tests all flags after executing bit n,(hl) after each instruction tested.

Z80 Test Suite, by Mark Woodmass

This suite performs a series of tests to verify the MEMPTR documents (English, Russian), which are spot on, as well as a brief run through several of the CBh/DDh/FDh opcode ranges. The test results in the program are compared against those from a NEC D780C-1 CPU, but Simon Conway kindly tested several other Z80 clones, confirming the same results.

Results

z80tests.tap

Z80 Instruction Set Exerciser, by Frank D. Cringle

Frank Cringle's Z80 Instruction Set Exerciser attempts to execute every Z80 opcode, putting them through a cycle of tests and comparing the results to actual results from running the code on a real Z80. The exerciser is supplied with Frank's YAZE (Yet Another Z80 Emulator). It is often difficult to track down, so Jonathan Graham Harston put it together here, as well as some conversions. The latest release of YAZE is available at Andreas Gerlich's website.

Results (Jonathan Graham Harston's version)

zexdoc.tap

Tests officially documented flag effects.

zexall.tap

Tests all flags changes.
Results (Jan Bobrowski's version)

zexfix.tap

Tests all flags changes.

zexbit.tap

Tests all flags changes of bit instructions.
Results (Patrik Rak's version)

zexall2.tap

Installation

Debian/Ubuntu

First add the ZXE repository:

apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv FE214A38D6A0C01D9AF514EE841EA3BD3A7E1487
add-apt-repository 'deb [arch=amd64] https://zxe.io/repos/apt stable main'

Next, install the Z80 library package:

apt install libz80

In case you need to build software that requires the Z80 library, install the development package too:

apt install libz80-dev

Gentoo Linux

First add the ZXE overlay:

eselect repository add zxe git https://github.com/redcode/zxe-gentoo-overlay.git
emaint sync --repo zxe

Next, install the Z80 library:

emerge z80

Installation from sources

You will need CMake v3.14 or later to build the package and, optionally, recent versions of Doxygen, Sphinx and Breathe to compile the documentation. Also make sure you have LaTeX with PDF support installed on your system if you want to generate the documentation in PDF format.

The emulator requires some types and macros included in Zeta, a dependency-free, header-only library used to retain compatibility with most C compilers. Install Zeta or extract its official source code package to the same directory of this README.md or its parent directory. Zeta is the sole dependency; the emulator is a freestanding implementation and as such does not depend on the C standard library.

Once all requirements are met, create a directory and run cmake from there to prepare the build system:

mkdir build
cd build
cmake <directory of this README.md> [options]

The resulting build files can be configured by passing options to cmake. To show a complete list of those available along with their current settings, type the following:

cmake -LAH

If in doubt, read the CMake documentation for more information on configuration options. The following are some of the most relevant standard options of CMake:

  • -DBUILD_SHARED_LIBS=(YES|NO)
    Build the project as a shared library rather than a static one.
    The default is NO.

  • -DCMAKE_BUILD_TYPE=(Debug|Release|RelWithDebInfo|MinSizeRel)
    Choose the type of build (configuration) to generate.
    The default is Release.

  • -DCMAKE_INSTALL_PREFIX="<path>"
    Specify the installation prefix on UNIX and UNIX-like operating systems.
    The default is "/usr/local".

Package-specific options are prefixed with Z80_ and can be divided into two groups. The first one controls aspects not related to the source code of the library:

  • -DZ80_DOWNLOAD_TEST_FILES=(YES|NO)
    Download the firmware and software used by the testing tool.
    The default is NO.

  • -DZ80_INSTALL_CMAKEDIR="<path>"
    Specify the directory in which to install the CMake config-file package.
    The default is "${CMAKE_INSTALL_LIBDIR}/cmake/Z80".

  • -DZ80_INSTALL_PKGCONFIGDIR="<path>"
    Specify the directory in which to install the pkg-config file.
    The default is "${CMAKE_INSTALL_LIBDIR}/pkgconfig".

  • -DZ80_NOSTDLIB_FLAGS=(Auto|[<flag>[;<flag>...]])
    Specify the linker flags used to avoid linking against system libraries.
    The default is Auto (autoconfigure flags). If you get linker errors, set this option to "".

  • -DZ80_SHARED_LIBS=(YES|NO)
    Build the project as a shared library rather than a static one.
    This option takes precedence over BUILD_SHARED_LIBS.
    Not defined by default.

  • -DZ80_SPHINX_HTML_THEME="[<name>]"
    Specify the Sphinx theme for the documentation in HTML format.
    The default is "" (use the default theme).

  • -DZ80_WITH_CMAKE_SUPPORT=(YES|NO)
    Generate and install the CMake config-file package.
    The default is NO.

  • -DZ80_WITH_HTML_DOCUMENTATION=(YES|NO)
    Build and install the documentation in HTML format.
    It requires Doxygen, Sphinx and Breathe.
    The default is NO.

  • -DZ80_WITH_PDF_DOCUMENTATION=(YES|NO)
    Build and install the documentation in PDF format.
    It requires Doxygen, Sphinx, Breathe and LaTeX with PDF support.
    The default is NO.

  • -DZ80_WITH_PKGCONFIG_SUPPORT=(YES|NO)
    Generate and install the pkg-config file.
    The default is NO.

  • -DZ80_WITH_STANDARD_DOCUMENTS=(YES|NO)
    Install the standard text documents distributed with the package: AUTHORS, COPYING, COPYING.LESSER, HISTORY, README and THANKS.
    The default is NO.

  • -DZ80_WITH_TESTS=(YES|NO)
    Build the testing tool.
    The default is NO.

The second group of package-specific options configures the source code of the library by predefining macros that enable optional implementations:

  • -DZ80_WITH_EXECUTE=(YES|NO)
    Build the implementation of the z80_execute function.
    The default is NO.

  • -DZ80_WITH_FULL_IM0=(YES|NO)
    Build the full implementation of the interrupt mode 0 rather than the reduced one.
    The default is NO.

  • -DZ80_WITH_Q=(YES|NO)
    Build the implementation of the Q "register".
    The default is NO.

  • -DZ80_WITH_SPECIAL_RESET=(YES|NO)
    Build the implementation of the special RESET.
    The default is NO.

  • -DZ80_WITH_UNOFFICIAL_RETI=(YES|NO)
    Configure the ED5Dh, ED6Dh and ED7Dh undocumented instructions as reti instead of retn.
    The default is NO.

  • -DZ80_WITH_ZILOG_NMOS_LD_A_IR_BUG=(YES|NO)
    Build the implementation of the bug affecting the Zilog Z80 NMOS, which causes the P/V flag to be reset when a maskable interrupt is accepted during the execution of the ld a,{i|r} instructions.
    The default is NO.

Package maintainers should use at least the following options for the shared library:

-DZ80_WITH_EXECUTE=YES
-DZ80_WITH_FULL_IM0=YES
-DZ80_WITH_Q=YES
-DZ80_WITH_ZILOG_NMOS_LD_A_IR_BUG=YES

Finally, once the build system is configured according to your needs, build and install the package:

make
make install/strip

Running the tests

The package includes a tool called test-Z80 capable of running all CP/M and ZX Spectrum versions of the major test suites. Configure the build system with -DZ80_WITH_TESTS=YES to enable its compilation and -DZ80_DOWNLOAD_TEST_FILES=YES to download the firmware and software required. Also note that the Z80 library must be built with -DZ80_WITH_Q=YES to be able to pass Patrik Rak's tests.

Once you have built the package, type the following to run all tests:

./test-Z80 -p downloads/firmware -p downloads/software/POSIX -p "downloads/software/ZX Spectrum" -a

The tool supports options and can run the tests individually. Type ./test-Z80 -h for help. If you prefer to run all tests through Make, just type make tests. For CTest, use ctest or ctest -V instead.

These are the complete logs generated by test-Z80 emulating the different CPU variants:

The CRC errors in the latter two are normal and match the values obtained on real hardware.

Integration

As an external dependency in CMake-based projects

The Z80 library includes a config-file package for integration into CMake-based projects, which should be installed for development. Use find_package to find the Z80 package. This creates the Z80 imported library target that carries the necessary transitive link dependencies. The linking method can optionally be selected by specifying the Shared or the Static component.

Example:

find_package(Z80 REQUIRED Shared)
target_link_libraries(your-target Z80)

When not specified as a component, the linking method is selected according to Z80_SHARED_LIBS. If this option is not defined, the config-file uses the type of library that is installed on the system and, if it finds both the shared and the static versions, BUILD_SHARED_LIBS determines which one to link against.

As a CMake subproject

To embed the Z80 library as a CMake subproject, place its entire source tree into a subdirectory of another project and use add_subdirectory in the parent project to add this subdirectory to the build process.

It is advisable to configure the library in the CMakeLists.txt of the parent project. This will prevent the user from having to specify configuration options for the Z80 subproject through the command line when building the main project.

Example:

set(Z80_SHARED_LIBS                 NO  CACHE BOOL "")
set(Z80_WITH_Q                      YES CACHE BOOL "")
set(Z80_WITH_ZILOG_NMOS_LD_A_IR_BUG YES CACHE BOOL "")

add_subdirectory(dependencies/Z80)
target_link_libraries(your-target Z80)

It is important to set the Z80_SHARED_LIBS option. Otherwise CMake will build the library type indicated by BUILD_SHARED_LIBS, which may not be the desired one.

Integrating the source code

There are several macros that can be used to configure the source code of the library. You can define those you need in your build system or at the beginning of the Z80.c file. The following ones allow you to configure the integration of Z80.h and Z80.c into the project:

  • #define Z80_DEPENDENCIES_HEADER "header name.h"
    Specifies the only external header to #include, replacing those of Zeta.
    If used, it must also be defined before including the Z80.h header.

  • #define Z80_STATIC
    Required to compile and/or use the emulator as a static library or as an internal part of another project.
    If used, it must also be defined before including the Z80.h header.

  • #define Z80_WITH_LOCAL_HEADER
    Tells Z80.c to #include "Z80.h" instead of <Z80.h>.

The second group of package-specific options, explained in the Installation from sources section of this document, activates various optional implementations in the source code by predefining the following macros:

  • #define Z80_WITH_EXECUTE
  • #define Z80_WITH_FULL_IM0
  • #define Z80_WITH_Q
  • #define Z80_WITH_SPECIAL_RESET
  • #define Z80_WITH_UNOFFICIAL_RETI
  • #define Z80_WITH_ZILOG_NMOS_LD_A_IR_BUG

Except for Z80_DEPENDENCIES_HEADER, the above macros do not need to be defined as any value; the source code only checks whether or not they are defined.

Please note that the activation of some of the optional implementations affects the speed of the emulator due to various factors (read the documentation for more details).

Showcase

This emulator has been used by the following projects (listed in alphabetical order):

Thanks

Many thanks to the following individuals (in alphabetical order):

  • Akimov, Vadim (lvd)
    • For testing the library on many different platforms and CPU architectures.
  • azesmbog
    1. For validating tests on real hardware. 1
    2. For his research on the unstable flag behavior of the ccf/scf instructions.
    3. For his invaluable help.
  • Banks, David (hoglet)
    1. For cracking the flag behavior of the block instructions. 2, 3
    2. For his research on the flag behavior of the ccf/scf instructions. 3
  • Beliansky, Anatoly (Tolik_Trek)
    • For validating tests on real hardware. 4
  • Bobrowski, Jan
    • For fixing the "Z80 Full Instruction Set Exerciser for Spectrum". 5
  • boo_boo
    • For cracking the behavior of the MEMPTR register. 6, 7, 8, 9
  • Brady, Stuart
    • For his research on the flag behavior of the ccf/scf instructions. 10
  • Brewer, Tony
    1. For his research on the special RESET. 11, 12
    2. For helping to crack the flag behavior of the block instructions. 2
    3. For conducting low-level tests on real hardware. 2
    4. For helping me to test different undocumented behaviors of the Zilog Z80.
  • Bystrov, Dmitry (Alone Coder)
    • For validating tests on real hardware. 4
  • Chunin, Roman (CHRV)
    • For testing the behavior of the MEMPTR register on real Z80 chips. 6, 7, 8, 9
  • Conway, Simon (BadBeard)
    • For validating the "Z80 Test Suite" on several Z80 clones. 13
  • Cooke, Simon
    • For finding out how the out (c),0 instruction behaves on the Zilog Z80 CMOS. 14
  • Cringle, Frank D.
    • For writing the "Z80 Instruction Set Exerciser". 15
  • Devic, Goran
    • For his research on undocumented behaviors of the Z80 CPU. 16
  • Flammenkamp, Achim
    • For his article on Z80 interrupts. 17
  • Gimeno Fortea, Pedro
    1. For his research work. 18
    2. For writing the first-ever ZX Spectrum emulator. 19, 20
  • goodboy
    • For testing the behavior of the MEMPTR register on real Z80 chips. 6, 7, 8, 9
  • Greenway, Ian
    • For testing the flag behavior of the ccf/scf instructions on real hardware. 10, 21
  • Harston, Jonathan Graham
    1. For his research work.
    2. For his technical documents about the Zilog Z80. 22, 23, 24
    3. For porting the "Z80 Instruction Set Exerciser" to the ZX Spectrum. 25
  • Helcmanovsky, Peter (Ped7g)
    1. For helping me to write the "IN-MEMPTR" test.
    2. For writing the "Z80 Block Flags Test". 26, 27
    3. For writing the "Z80 CCF SCF Outcome Stability" test. 27
    4. For writing the "Z80 INT Skip" test. 27
    5. For his research on the unstable flag behavior of the ccf/scf instructions.
    6. For his invaluable help.
  • icebear
    • For testing the behavior of the MEMPTR register on real Z80 chips. 6, 7, 8, 9
  • Kladov, Vladimir
    • For cracking the behavior of the MEMPTR register. 6, 7, 8, 9
  • Krook, Magnus
    • For validating tests on real hardware. 28
  • London, Matthew
    • For validating tests on real hardware.
  • Martínez Cantero, Ricardo (Kyp)
    • For validating tests on real hardware.
  • Molodtsov, Aleksandr
    • For testing the behavior of the MEMPTR register on real Z80 chips. 6, 7, 8, 9
  • Nair, Arjun
    • For validating tests on real hardware. 26
  • Nicolás-González, César
    • For helping me to research the unstable flag behavior of the ccf/scf instructions.
  • Ortega Sosa, Sofía
    • For her support.
  • Owen, Simon
    • For the idea of the hooking method used in this emulator.
  • Rak, Patrik
    1. For improving the "Z80 Instruction Set Exerciser for Spectrum". 29
    2. For cracking the flag behavior of the ccf/scf instructions. 13, 29
    3. For writing the "Zilog Z80 CPU Test Suite". 29, 30
    4. For his research on the unstable flag behavior of the ccf/scf instructions.
  • Rodríguez Jódar, Miguel Ángel (mcleod_ideafix)
    • For his reseach on the state of the registers after POWER/RESET. 31
  • Rodríguez Palomino, Mario (r-lyeh)
    • For teaching me how emulators work.
  • Sainz de Baranda y Romero, Manuel
    • For teaching me programming and giving me my first computer.
  • Sánchez Ordiñana, José Ismael (Vaporatorius)
    • For validating tests on real hardware. 32, 33
  • Stevenson, Dave
    1. For testing the special RESET on real hardware. 11
    2. For conducting low-level tests on real hardware. 34
  • Weissflog, Andre (Floh)
    1. For finding out that the reti/retn instructions defer the acceptance of the maskable interrupt. 35
    2. For writing the "Visual Z80 Remix" simulator. 36
  • Wilkinson, Oli (evolutional)
    • For validating tests on real hardware. 26
  • Wlodek
    • For testing the behavior of the MEMPTR register on real Z80 chips. 6, 7, 8, 9
  • Woodmass, Mark (Woody)
    1. For his invaluable contributions to the emuscene.
    2. For writing the "Z80 Test Suite". 13
    3. For his research on the flag behavior of the ccf/scf instructions. 37
    4. For writing the "HALT2INT" test.
    5. For writing the "EIHALT" test.
  • Young, Sean
    1. For his research work.
    2. For his technical documents about the Zilog Z80. 18, 38, 39
  • ZXGuesser
    • For validating tests on real hardware.

References

  1. https://spectrumcomputing.co.uk/forums/viewtopic.php?p=83384#p83384
  2. https://stardot.org.uk/forums/viewtopic.php?t=15464
    • https://stardot.org.uk/forums/viewtopic.php?p=211042#p211042
    • https://stardot.org.uk/forums/viewtopic.php?p=212021#p212021
  3. Banks, David (2018-08-21). "Undocumented Z80 Flags" revision 1.0.
    • https://github.com/hoglet67/Z80Decoder/wiki/Undocumented-Flags
    • https://stardot.org.uk/forums/download/file.php?id=39831
  4. https://spectrumcomputing.co.uk/forums/viewtopic.php?p=83041#p83041
  5. http://wizard.ae.krakow.pl/~jb/qaop/tests.html
  6. https://zxpress.ru/zxnet/zxnet.pc/5909
  7. https://zx-pk.ru/threads/2506-komanda-bit-n-(hl).html
  8. https://zx-pk.ru/threads/2586-prosba-realshchikam-ot-emulyatorshchikov.html
  9. boo_boo; Kladov, Vladimir (2006-03-29). "MEMPTR, Esoteric Register of the Zilog Z80 CPU".
    • http://zx.pk.ru/showpost.php?p=43688
    • http://zx.pk.ru/attachment.php?attachmentid=2984
    • http://zx.pk.ru/showpost.php?p=43800
    • http://zx.pk.ru/attachment.php?attachmentid=2989
  10. https://sourceforge.net/p/fuse-emulator/mailman/message/6929573
  11. Brewer, Tony (2014-12). "Z80 Special Reset".
    • http://primrosebank.net/computers/z80/z80_special_reset.htm
  12. https://stardot.org.uk/forums/viewtopic.php?p=357136#p357136
  13. https://worldofspectrum.org/forums/discussion/20345
  14. https://groups.google.com/g/comp.os.cpm/c/HfSTFpaIkuU/m/KotvMWu3bZoJ
  15. Cringle, Frank D. (1998-01-28). "Yaze - Yet Another Z80 Emulator" v1.10.
    • ftp://ftp.ping.de/pub/misc/emulators/yaze-1.10.tar.gz
  16. https://baltazarstudios.com/zilog-z80-undocumented-behavior
  17. Flammenkamp, Achim. "Interrupt Behaviour of the Z80 CPU".
    • http://z80.info/interrup.htm
  18. Young, Sean (1998-10). "Z80 Undocumented Features (in Software Behaviour)" v0.3.
    • http://www.msxnet.org/tech/Z80/z80undoc.txt
  19. https://elmundodelspectrum.com/desenterrando-el-primer-emulador-de-spectrum
  20. https://elmundodelspectrum.com/con-vosotros-el-emulador-de-pedro-gimeno-1989
  21. https://sourceforge.net/p/fuse-emulator/mailman/message/4502844
  22. Harston, Jonathan Graham (2008). "Full Z80 Opcode List Including Undocumented Opcodes" v0.11 (revised).
    • https://mdfs.net/Docs/Comp/Z80/OpList
  23. Harston, Jonathan Graham (2012). "Z80 Microprocessor Undocumented Instructions" v0.15.
    • https://mdfs.net/Docs/Comp/Z80/UnDocOps
  24. Harston, Jonathan Graham (2014). "Z80 Opcode Map" v0.10 (revised).
    • https://mdfs.net/Docs/Comp/Z80/OpCodeMap
  25. https://mdfs.net/Software/Z80/Exerciser/Spectrum
  26. https://spectrumcomputing.co.uk/forums/viewtopic.php?t=6102
  27. https://github.com/MrKWatkins/ZXSpectrumNextTests
  28. https://spectrumcomputing.co.uk/forums/viewtopic.php?p=83157#p83157
  29. https://worldofspectrum.org/forums/discussion/41704
    • http://zxds.raxoft.cz/taps/misc/zexall2.zip
  30. https://worldofspectrum.org/forums/discussion/41834
    • http://zxds.raxoft.cz/taps/misc/z80test-1.0.zip
    • https://github.com/raxoft/z80test
  31. https://worldofspectrum.org/forums/discussion/34574
  32. https://worldofspectrum.org/forums/discussion/comment/668760/#Comment_668760
  33. https://jisanchez.com/test-a-dos-placas-de-zx-spectrum
  34. https://stardot.org.uk/forums/viewtopic.php?p=212360#p212360
  35. https://floooh.github.io/2021/12/17/cycle-stepped-z80.html
  36. https://github.com/floooh/v6502r
  37. http://groups.google.co.uk/group/comp.sys.sinclair/msg/56dd1fd4ccb5fb3b
  38. Young, Sean (1997-09-21). "Zilog Z80 CPU Specifications".
    • http://www.msxnet.org/tech/Z80/z80.zip
  39. Young, Sean (2005-09-18). "Undocumented Z80 Documented, The" v0.91.
    • http://www.myquest.nl/z80undocumented
    • http://www.myquest.nl/z80undocumented/z80-documented-v0.91.pdf

License

Copyright © 1999-2022 Manuel Sainz de Baranda y Goñi.

This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library. If not, see https://www.gnu.org/licenses/.

Special licensing

Projects where the terms of the GNU Lesser General Public License prevent the use of this library, or require unwanted publication of the source code of commercial products, may apply for a special license.