"""Generate a single-step test corpus from MAME 0.285's MC6800/MC6803 core. No 6800-family test corpus exists anywhere (docs/validation.md), so this makes one the way neetandev/m6809 made its 6809 corpus: by running MAME's own CPU code standalone over random machine states. The code is taken verbatim, at build time, from the hash-pinned MAME 0.285 sources that scripts/fetch_mame_source.py puts in reference/mame0285 -- the macros, flag tables and opcode/cycle tables of m6800.cpp and m6801.cpp, and every handler in 6800ops.hxx -- and compiled against a small shim class standing in for MAME's device framework. Nothing from MAME is committed; the generated C++, the binary and the corpus live in gitignored directories. python scripts/mame_corpus.py build # -> mame-work/corpus/gen python scripts/mame_corpus.py generate [--cases 1000] [--seed 6800] # -> tests/vectors/{m6800,m6803}/XX.jsonl **Tier: emulator-derived.** The corpus records what MAME does; it is a detector, never a judge (docs/validation.md). What the shim changes, and why: * **No interrupt lines.** ``check_irq_lines()`` does nothing: a single-step case has no IRQ or NMI. * **One instruction per case.** MAME's ``CLI`` and ``TAP`` handlers call ``execute_one()`` to run the *next* instruction inline (their IRQ-delay mechanism). The shim suppresses that nested call and records ``"inline_next": true`` instead, so each case is exactly one opcode. * **WAI does not eat the timeslice.** ``eat_cycles()`` does nothing; the case records ``"wai": true`` and the table cycle count. Each case is one JSON line:: {"name": "8B 0007", "initial": {"pc", "s", "x", "a", "b", "cc", "ram": [[addr, value], ...]}, "final": {... same ...}, "cycles": n, "bus": [["r"|"w", addr, value], ...], "wai": bool, "inline_next": bool} Memory is sparse: every address the instruction reads that was not written first gets a random byte, recorded in the initial ``ram``; ``final.ram`` has every address touched. The opcode itself is at ``pc``. """ from __future__ import annotations import argparse import hashlib import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = ROOT / "reference" / "mame0285" WORK = ROOT / "mame-work" / "corpus" VECTORS = ROOT / "tests" / "vectors" # The six MAME 0.285 files, as pinned in docs/validation.md; only four are used. PINNED = { "m6800.cpp": "974d0c205992d81bfa5c60bb4e2bccf03b7102c047b272c60285bf30180e4485", "m6801.cpp": "f744e99e7deb17c1d4c47747611c58f5ad13a47531a55c163067e18c42b75e95", "6800ops.hxx": "f4c692a1c51435a9c0b76a36c66dc8060fc6e6963da7cba84d75ac65fcc5dec1", "m6800.h": "42cf7ecb77327d9d660519d666c2b06918898360c2a40d97f53573ba2a05c7c4", } SHIM = r""" // Generated by scripts/mame_corpus.py from MAME 0.285 sources; do not commit. #include #include #include #include #include #include #include #include #include typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; union PAIR { struct { u8 l, h, h2, h3; } b; struct { u16 l, h; } w; u32 d; }; #define logerror(...) do {} while (0) #define LOGMASKED(...) do {} while (0) #define ATTR_COLD enum { CLEAR_LINE = 0 }; struct Access { char kind; u16 addr; u8 value; }; struct Memory { std::unordered_map ram; // current contents of touched addresses std::unordered_map initial; // first-read values (and the opcode) std::vector log; std::mt19937 *rng = nullptr; u8 read_byte(u32 address) { u16 a = address & 0xffff; auto it = ram.find(a); u8 v; if (it == ram.end()) { v = (*rng)() & 0xff; ram[a] = v; initial[a] = v; } else { v = it->second; } log.push_back({'r', a, v}); return v; } void write_byte(u32 address, u8 value) { u16 a = address & 0xffff; if (ram.find(a) == ram.end()) initial[a] = (*rng)() & 0xff; // a byte was there ram[a] = value; log.push_back({'w', a, value}); } }; enum { M6800_WAI = 8, M6800_SLP = 0x10 }; enum { M6800_IRQ_LINE = 0 }; class m6800_cpu_device { public: typedef void (m6800_cpu_device::*op_func)(); PAIR m_ppc, m_pc, m_s, m_x, m_d, m_ea; u8 m_cc = 0, m_wai_state = 0, m_nmi_state = 0, m_nmi_pending = 0; u8 m_irq_state[5] = {0, 0, 0, 0, 0}; const op_func *m_insn = nullptr; const u8 *m_cycles = nullptr; int m_icount = 0; int depth = 0; bool inline_next = false; Memory m_program; Memory &m_cprogram = m_program; Memory &m_copcodes = m_program; static const u8 flags8i[256]; static const u8 flags8d[256]; static const u8 cycles_6800[256]; static const op_func m6800_insn[256]; u32 RM16(u32 Addr); void WM16(u32 Addr, PAIR *p); void increment_counter(int amount) { m_icount -= amount; } void eat_cycles() {} // WAI/SLP: recorded, not eaten void check_irq_lines() {} // single-step cases have no interrupt lines void check_irq2() {} void take_trap() {} void standard_irq_callback(int, u16) {} void debugger_instruction_hook(u32) {} void enter_interrupt(const char *, u16) {} bool check_irq1_enabled() { return false; } void execute_one(); HANDLER_DECLARATIONS }; class m6801_cpu_device : public m6800_cpu_device { public: static const u8 cycles_6803[256]; static const m6800_cpu_device::op_func m6803_insn[0x100]; }; """ MAIN = r""" void m6800_cpu_device::execute_one() { if (depth > 0) { inline_next = true; return; } // CLI/TAP's inline next opcode depth++; pPPC = pPC; u8 ireg = M_RDOP(PCD); PC++; (this->*m_insn[ireg])(); increment_counter(m_cycles[ireg]); depth--; } static void dump_state(FILE *f, m6800_cpu_device &c, const std::unordered_map &ram) { std::vector> cells(ram.begin(), ram.end()); std::sort(cells.begin(), cells.end()); fprintf(f, "{\"pc\":%u,\"s\":%u,\"x\":%u,\"a\":%u,\"b\":%u,\"cc\":%u,\"ram\":[", c.m_pc.w.l, c.m_s.w.l, c.m_x.w.l, c.m_d.b.h, c.m_d.b.l, c.m_cc); for (size_t i = 0; i < cells.size(); i++) fprintf(f, "%s[%u,%u]", i ? "," : "", cells[i].first, cells[i].second); fprintf(f, "]}"); } int main(int argc, char **argv) { if (argc != 5) { fprintf(stderr, "usage: gen 6800|6803 SEED CASES OUTDIR\n"); return 2; } bool is6803 = std::strcmp(argv[1], "6803") == 0; unsigned seed = std::strtoul(argv[2], nullptr, 10); int cases = std::atoi(argv[3]); std::string outdir = argv[4]; for (int opcode = 0; opcode < 256; opcode++) { char path[4096]; snprintf(path, sizeof path, "%s/%02X.jsonl", outdir.c_str(), opcode); FILE *f = fopen(path, "w"); if (!f) { perror(path); return 1; } std::mt19937 rng(seed * 1000003u + opcode * 7919u + (is6803 ? 1 : 0)); for (int n = 0; n < cases; n++) { m6800_cpu_device c; c.m_program.rng = &rng; c.m_insn = is6803 ? m6801_cpu_device::m6803_insn : m6800_cpu_device::m6800_insn; c.m_cycles = is6803 ? m6801_cpu_device::cycles_6803 : m6800_cpu_device::cycles_6800; c.m_pc.d = rng() & 0xffff; c.m_s.d = rng() & 0xffff; c.m_x.d = rng() & 0xffff; c.m_d.d = rng() & 0xffff; c.m_cc = 0xc0 | (rng() & 0x3f); c.m_ea.d = 0; c.m_ppc.d = 0; c.m_program.ram[c.m_pc.w.l] = opcode; c.m_program.initial[c.m_pc.w.l] = opcode; m6800_cpu_device start = c; // registers before c.m_icount = 1000; c.execute_one(); int cycles = 1000 - c.m_icount; // Every address touched ends up in both images. std::unordered_map initial = c.m_program.initial; fprintf(f, "{\"name\":\"%02X %04d\",\"initial\":", opcode, n); dump_state(f, start, initial); fprintf(f, ",\"final\":"); dump_state(f, c, c.m_program.ram); fprintf(f, ",\"cycles\":%d,\"bus\":[", cycles); for (size_t i = 0; i < c.m_program.log.size(); i++) { const Access &a = c.m_program.log[i]; fprintf(f, "%s[\"%c\",%u,%u]", i ? "," : "", a.kind, a.addr, a.value); } fprintf(f, "],\"wai\":%s,\"inline_next\":%s}\n", (c.m_wai_state & M6800_WAI) ? "true" : "false", c.inline_next ? "true" : "false"); } fclose(f); } return 0; } """ def verify_sources() -> None: for name, digest in PINNED.items(): path = MAME / name if not path.exists(): sys.exit(f"{path} missing: run scripts/fetch_mame_source.py first") actual = hashlib.sha256(path.read_bytes()).hexdigest() if actual != digest: sys.exit(f"{path}: SHA-256 {actual} is not the pinned MAME 0.285 file") def between(text: str, start: str, end: str) -> str: a = text.index(start) return text[a : text.index(end, a)] def table(text: str, declaration: str) -> str: """The C definition that starts with ``declaration``, through its closing '};'.""" a = text.index(declaration) return text[a : text.index("\n};", a) + 3] def generate_source() -> str: m6800 = (MAME / "m6800.cpp").read_text() m6801 = (MAME / "m6801.cpp").read_text() ops = (MAME / "6800ops.hxx").read_text() handlers = sorted(set(re.findall(r"OP_HANDLER\(\s*(\w+)\s*\)", ops))) declarations = "\n ".join(f"void {name}();" for name in handlers) macros = between(m6800, "#define pPPC", "/* include the opcode functions */") # RM/WM/M_RDOP read through the shim's Memory; the macro text is MAME's. parts = [ SHIM.replace("HANDLER_DECLARATIONS", declarations), macros, ops, "#define XX 4 // illegal opcode unknown cycle count (MAME 0.285)", table(m6800, "const u8 m6800_cpu_device::cycles_6800[256]"), table(m6800, "const m6800_cpu_device::op_func m6800_cpu_device::m6800_insn[0x100]"), table(m6801, "const u8 m6801_cpu_device::cycles_6803[256]"), table(m6801, "const m6800_cpu_device::op_func m6801_cpu_device::m6803_insn[0x100]"), # RM16/WM16 are MAME's (m6800.cpp), repeated here because they sit in # the device-constructor section this script does not extract. "u32 m6800_cpu_device::RM16(u32 Addr)\n{\n\tu32 result = RM(Addr) << 8;\n" "\treturn result | RM((Addr+1) & 0xffff);\n}\n", "void m6800_cpu_device::WM16(u32 Addr, PAIR *p)\n{\n\tWM(Addr, p->b.h);\n" "\tWM((Addr+1) & 0xffff, p->b.l);\n}\n", MAIN, ] return "\n".join(parts) def build() -> Path: verify_sources() WORK.mkdir(parents=True, exist_ok=True) source = WORK / "gen.cpp" source.write_text(generate_source()) binary = WORK / "gen" subprocess.run(["g++", "-O2", "-std=c++17", "-w", "-o", str(binary), str(source)], check=True) return binary def main() -> None: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("command", choices=["build", "generate"]) parser.add_argument("--cases", type=int, default=1000) parser.add_argument("--seed", type=int, default=6800) args = parser.parse_args() binary = build() if args.command == "build": print(binary) return for part in ("6800", "6803"): outdir = VECTORS / f"m{part}" outdir.mkdir(parents=True, exist_ok=True) subprocess.run( [str(binary), part, str(args.seed), str(args.cases), str(outdir)], check=True ) print(f"{outdir}: 256 files x {args.cases} cases") if __name__ == "__main__": main()