Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Cold-boot the Book 6 Atlas backup after an interruption between renames."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="save the actual recovery screen as a PNG")
args = parser.parse_args()
runtime, core, roms = [p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
blank = root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK"
bin_dir = runtime / "bin"
tool = bin_dir / "writecocofile"
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(bin_dir) + os.pathsep + os.environ["PATH"])
# Existing visits to Earth and Mars must survive both the save and recovery.
names = [b"MERCURY: CRATERS", b"VENUS: CLOUDS", b"EARTH: BLUE SEA", b"MARS: RED RIDGE"]
original = b"".join(name.ljust(23, b"\0") + flag for name, flag in zip(names, (b"\0", b"\0", b"V", b"V")))
updated = original[:72] + b"MARS: DUST STORM".ljust(23, b"\0") + original[-1:]
note = b"ANOTHER CREW'S FILE\r"
with tempfile.TemporaryDirectory(prefix="vcc-atlas-backup-") as tmp:
work = Path(tmp)
card = work / "card"
card.mkdir()
disk = card / "VOL.DSK"
(card / "startup.cfg").write_text("0=VOL.DSK\n")
result = work / "result.dsk"
def run(*command, **kwargs):
return subprocess.run(command, cwd=work, env=env, check=True, **kwargs)
def add(dsk, filename, contents):
(work / filename).write_bytes(contents)
run(tool, "--binary", dsk, filename)
def check_files(expected):
for filename in ("ATLAS.DAT", "ATLAS.BAK", "ATLAS.NEW", "CREW.TXT"):
extraction = subprocess.run([tool, "--stdout", result, filename], cwd=work, capture_output=True)
if filename in expected:
if extraction.returncode or extraction.stdout != expected[filename]:
raise AssertionError(f"Wrong contents for {filename}: {extraction.stderr!r} {extraction.stdout!r}")
elif not extraction.returncode or b"not found on disk image" not in extraction.stdout + extraction.stderr:
raise AssertionError(f"Expected absent {filename}: {extraction.stdout!r} {extraction.stderr!r}")
def boot(cpu, profile, phase, image):
shutil.copyfile(image, disk)
result.unlink(missing_ok=True)
run("./run", roms, "BACKUP.BIN", cpu, profile, phase)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
for opt in ("-O0", "-O2"):
run(bin_dir / "cmoc", "--coco", opt, "-Werror", "--org=2800", "-o", "BACKUP.BIN",
root / "examples/cmoc/manual/atlasbackup.c", "-lvcccompat", "-ldecbfile")
seed = work / "seed.dsk"
shutil.copyfile(blank, seed)
run(tool, seed, "BACKUP.BIN")
add(seed, "CREW.TXT", note)
fresh = work / "fresh.dsk"
shutil.copyfile(seed, fresh)
other_draft = work / "other-draft.dsk"
shutil.copyfile(seed, other_draft)
add(other_draft, "ATLAS.BAK", original)
# Looks like the correct edition, but the Mars visit flag differs.
unrelated = updated[:-1] + b"\0"
add(other_draft, "ATLAS.NEW", unrelated)
malformed = work / "malformed.dsk"
shutil.copyfile(seed, malformed)
add(malformed, "ATLAS.BAK", original[:-1])
add(malformed, "ATLAS.NEW", updated)
add(seed, "ATLAS.DAT", original)
for cpu in ("6809", "6309"):
for profile in ("disk", "rgb-hd", "sdc"):
boot(cpu, profile, "interrupt", seed)
check_files({"ATLAS.BAK": original, "ATLAS.NEW": updated, "CREW.TXT": note})
capture = args.capture and (opt, cpu, profile) == ("-O2", "6809", "disk")
boot(cpu, profile, "capture" if capture else "recover", result)
check_files({"ATLAS.DAT": original, "CREW.TXT": note})
if capture:
run("sips", "-s", "format", "png", "recovered.ppm", "--out", args.capture.resolve())
boot(cpu, profile, "save", result)
check_files({"ATLAS.DAT": updated, "ATLAS.BAK": original, "CREW.TXT": note})
saved = result.read_bytes()
boot(cpu, profile, "repeat", result)
if result.read_bytes() != saved:
raise AssertionError("Reopening a completed save changed the disk")
boot(cpu, profile, "refuse", malformed)
if result.read_bytes() != malformed.read_bytes():
raise AssertionError("An invalid backup caused disk changes")
boot(cpu, profile, "keep-draft", other_draft)
check_files({"ATLAS.DAT": original, "ATLAS.NEW": unrelated, "CREW.TXT": note})
if profile == "disk":
boot(cpu, profile, "save", fresh)
unvisited = b"".join(name.ljust(24, b"\0") for name in names)
check_files({"ATLAS.DAT": unvisited[:72] + b"MARS: DUST STORM".ljust(24, b"\0"),
"ATLAS.BAK": unvisited, "CREW.TXT": note})
print(f"PASS {cpu} {opt} {profile}: interrupted, recovered, saved, reopened; "
"whole atlas, visit flags and unrelated file preserved", flush=True)
if __name__ == "__main__":
main()
+56
View File
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
int main(int argc, char** argv)
{
try {
require(argc == 6, "Usage: run ROMDIR BIN CPU PROFILE PHASE");
const auto cpu = std::string(argv[3]) == "6809" ? Processor::MC6809 : Processor::HD6309;
const std::string mode = argv[4], phase = argv[5];
const auto profile = mode == "disk" ? Profile::fd : mode == "rgb-hd" ? Profile::rgbHD : Profile::sdc;
Session guest(argv[1], "card/VOL.DSK", cpu, profile);
if (phase == "recover" || phase == "capture")
guest.type("LOADM\"BACKUP\":EXEC\r");
else
guest.launch(argv[2]);
if (phase == "interrupt" || phase == "save") {
guest.until("BACKUP IN PLACE");
guest.until("PRESS A KEY TO INSTALL");
if (phase == "interrupt") {
// Terminate the whole guest process here. Only its disk goes
// to the next invocation, which starts from the boot ROM.
saveVolume(guest, "result.dsk");
return 0;
}
guest.type("Y");
guest.until("UPDATED ATLAS SAVED");
} else if (phase == "recover" || phase == "capture") {
guest.until("ORIGINAL ATLAS RESTORED");
guest.until("MARS: RED RIDGE");
} else if (phase == "keep-draft") {
guest.until("ORIGINAL ATLAS RESTORED");
guest.until("KEPT UNEXPECTED ATLAS.NEW");
} else if (phase == "repeat") {
guest.until("ATLAS ALREADY UPDATED");
} else if (phase == "refuse") {
guest.until("SAVE STOPPED - CHECK DISK");
} else {
throw std::logic_error("Unknown test phase " + phase);
}
guest.until("OK");
if (phase == "capture") {
guest.frames(3);
saveActiveFrame(*guest.machine.snapshot().frame, "recovered.ppm");
}
guest.verifyReturn();
saveVolume(guest, "result.dsk");
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 1;
}
}
+72
View File
@@ -0,0 +1,72 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Qualify the editable Planet Atlas on three Disk BASIC storage setups."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="save the Mars trip as a PNG and the input example alongside it with an -input suffix")
args = parser.parse_args()
runtime, core, roms = [p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
blank = root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK"
source = root / "examples/cmoc/manual/atlas.c"
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
cards = [b"MERCURY: CRATERS", b"VENUS: CLOUDS", b"EARTH: BLUE SEA", b"MARS: RED RIDGE"]
original = b"".join(card.ljust(24, b"\x00") for card in cards)
with tempfile.TemporaryDirectory(prefix="vcc-planet-atlas-") as tmp:
work = Path(tmp)
def run(*cmd, **kwargs):
return subprocess.run(cmd, cwd=work, env=env, check=True, **kwargs)
# Earth and an extra Jupiter card surround the edited Mars record.
edited = original[:72] + b"MARS: DUST STORM".ljust(24, b"\x00") + b"JUPITER: STORM".ljust(24, b"\x00")
full = original[:72] + b"X" * 24
for disk, atlas in (("seed.dsk", edited), ("short.dsk", original[:80]), ("full.dsk", full)):
shutil.copyfile(blank, work / disk)
(work / "ATLAS.DAT").write_bytes(atlas)
run(runtime / "bin/writecocofile", "--binary", disk, "ATLAS.DAT")
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
for opt in ("-O0", "-O2"):
run(runtime / "bin/cmoc", "--coco", opt, "-Werror", "--org=2800",
"-o", "ATLAS.BIN", source, "-lvcccompat", "-ldecbfile")
shutil.copyfile(work / "seed.dsk", work / "launch.dsk")
run(runtime / "bin/writecocofile", "launch.dsk", "ATLAS.BIN")
for cpu in ("6809", "6309"):
for profile in ("disk", "rgb-hd", "sdc"):
for folder, disk in (("blank", blank), ("edited", work / "launch.dsk"),
("short", work / "short.dsk"), ("full", work / "full.dsk")):
(work / folder).mkdir(exist_ok=True)
shutil.copyfile(disk, work / folder / "VOL.DSK")
(work / folder / "startup.cfg").write_text("0=VOL.DSK\n")
capture = args.capture and (cpu, opt, profile) == ("6809", "-O2", "disk")
run("./run", roms, "ATLAS.BIN", cpu, profile, "capture" if capture else "check")
for name, before in (("saved", original), ("edited", edited)):
actual = run(runtime / "bin/writecocofile", "--stdout", name + "-atlas.dsk", "ATLAS.DAT",
stdout=subprocess.PIPE).stdout
expected = bytearray(before)
expected[95] = ord("V")
if actual != expected:
raise AssertionError(f"{cpu} {opt} {profile}: unexpected {name} atlas contents")
if capture:
destination = args.capture.resolve()
for suffix in ("", "-input"):
run("sips", "-s", "format", "png", f"atlas{suffix}.ppm", "--out",
destination.with_stem(destination.stem + suffix))
print(f"PASS {cpu} {opt} {profile}: persisted visit, protected refusal, preserved records, "
"numeric choices, disk launch and BASIC return", flush=True)
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
static void openAtlas(Session& guest, const fs::path& binary)
{
guest.launch(binary);
guest.until("PICK A PLANET (1-4), THEN ENTER");
}
static void expectTrip(Session& guest, int position, const std::string& chosen, const std::string& visit)
{
guest.until("YOUR PICK AT BYTE " + std::to_string(position) + "\n" + chosen +
"\nHOME BASE\nEARTH: BLUE SEA\nBACK TO YOUR BOOKMARK\n" + chosen +
"\nFIRST CARD\nMERCURY: CRATERS\n" + visit);
guest.until("OK");
}
static void visitPracticeDisk(const fs::path& roms, const fs::path& binary, Processor cpu, Profile profile, bool capture)
{
Session guest(roms, "blank/VOL.DSK", cpu, profile);
openAtlas(guest, binary);
guest.type("4\r");
expectTrip(guest, 72, "MARS: RED RIDGE", "VISIT SAVED\nATLAS CLOSED");
if (capture) {
guest.frames(3);
saveActiveFrame(*guest.machine.snapshot().frame, "atlas.ppm");
}
guest.verifyReturn();
saveVolume(guest, "saved-atlas.dsk");
// A second launch reads the disk flag, without needing to write it again.
setVolumeProtected(guest, true);
const auto original = volume(guest);
openAtlas(guest, binary);
guest.type("4\r");
expectTrip(guest, 72, "MARS: RED RIDGE", "ALREADY VISITED\nATLAS CLOSED");
guest.verifyReturn();
// Venus is still unvisited. A protected write must fail without damage.
openAtlas(guest, binary);
guest.type("2X\r");
guest.until("EXTRA CHARACTER: X\nPICK A PLANET (1-4), THEN ENTER");
if (capture) {
guest.frames(3);
saveActiveFrame(*guest.machine.snapshot().frame, "atlas-input.ppm");
}
guest.type("MARS\r");
guest.until("START WITH A DIGIT");
guest.type("4294967298\r");
guest.until("CHOOSE A NUMBER FROM 1 TO 4");
guest.type("0X2\r");
expectTrip(guest, 24, "VENUS: CLOUDS", "CANNOT SAVE VISIT");
guest.verifyReturn();
openAtlas(guest, binary);
guest.type("2\r");
expectTrip(guest, 24, "VENUS: CLOUDS", "CANNOT SAVE VISIT");
guest.verifyReturn();
require(volume(guest) == original, "Protected atlas changed");
}
static void visitEditedDisk(const fs::path& roms, Processor cpu, Profile profile)
{
Session guest(roms, "edited/VOL.DSK", cpu, profile);
guest.type("LOADM\"ATLAS\":EXEC\r");
guest.until("PICK A PLANET (1-4), THEN ENTER");
guest.type("4\r");
expectTrip(guest, 72, "MARS: DUST STORM", "VISIT SAVED\nATLAS CLOSED");
guest.verifyReturn();
saveVolume(guest, "edited-atlas.dsk");
}
static void visitUnchangedDisk(const fs::path& roms, const fs::path& binary, Processor cpu,
Profile profile, const fs::path& disk, const std::string& expected)
{
Session guest(roms, disk, cpu, profile);
openAtlas(guest, binary);
guest.type("4\r");
guest.until(expected);
guest.verifyReturn();
guest.verifyMedia();
}
int main(int argc, char** argv)
{
try {
require(argc == 6, "Usage: run ROMDIR BIN CPU PROFILE CAPTURE");
const auto cpu = std::string(argv[3]) == "6809" ? Processor::MC6809 : Processor::HD6309;
const std::string mode = argv[4];
const auto profile = mode == "disk" ? Profile::fd : mode == "rgb-hd" ? Profile::rgbHD : Profile::sdc;
visitPracticeDisk(argv[1], argv[2], cpu, profile, std::string(argv[5]) == "capture");
visitEditedDisk(argv[1], cpu, profile);
visitUnchangedDisk(argv[1], argv[2], cpu, profile, "short/VOL.DSK", "CANNOT READ ATLAS CARD");
visitUnchangedDisk(argv[1], argv[2], cpu, profile, "full/VOL.DSK", "NO ROOM FOR VISIT MARK\nATLAS CLOSED");
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 1;
}
}
+43
View File
@@ -0,0 +1,43 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run the banked landscape lesson on both CoCo CPUs and capture the guest display."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged ToolchainBundle")
parser.add_argument("core", type=Path, help="libVCCCore.a")
parser.add_argument("roms", type=Path, help="CoCo 3 and Disk BASIC ROM directory")
parser.add_argument("--captures", type=Path, help="write ridge-earth.png and ridge-mars.png here")
args = parser.parse_args()
runtime, core, roms = [p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="0", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-ridge-") as folder:
def run(*command):
subprocess.run(command, cwd=folder, env=env, check=True)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
for opt in ("-O0", "-O2"):
print("Checking", opt, flush=True)
run(runtime / "bin/cmoc", "--coco", "--org=2800", opt, "-Werror", "-o", "RIDGE.BIN",
root / "examples/cmoc/manual/ridge.c", "-lbank", "-lgime", "-lhirestxt")
(Path(folder) / "RIDGE.DSK").write_bytes(b"\xff" * (35 * 18 * 256))
run(runtime / "bin/writecocofile", "RIDGE.DSK", "RIDGE.BIN")
capture = args.captures and opt == "-O2"
run("./run", roms, "RIDGE.DSK", "RIDGE.BIN", *(["capture"] if capture else []))
if capture:
args.captures.mkdir(parents=True, exist_ok=True)
for planet in ("earth", "mars"):
png = args.captures.resolve() / f"ridge-{planet}.png"
run("sips", "-s", "format", "png", f"{planet}.ppm", "--out", png)
if __name__ == "__main__":
main()
+102
View File
@@ -0,0 +1,102 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../basic-disk-session.h"
using namespace BasicDiskTests;
static std::uint32_t pixel(const Frame& frame, unsigned x, unsigned y)
{
const auto area = frame.activeArea;
return frame.pixels[(area.y + y * area.height / 192) * Frame::width + area.x + x * area.width / 320];
}
// The highlighted ridge top and the ship's lower edge both use the header color.
static void expectScene(Session& session, unsigned y, unsigned column,
std::uint32_t accent, bool initial = false)
{
for (unsigned n = 0; n < 900; ++n) {
session.frames(1);
const auto frame = session.machine.snapshot().frame;
if (!frame) continue;
const auto edge = pixel(*frame, 12, 19);
if ((initial || edge == accent) && edge != pixel(*frame, 12, 22) &&
pixel(*frame, column * 16 + 2, 59) == edge &&
pixel(*frame, column * 16 + 2, y) == edge &&
pixel(*frame, column * 16 + 2, y + 3) != edge) {
session.frames(3); // Finish the first scan after the vertical-blank flip.
return;
}
}
throw std::runtime_error("Expected ridge at y=" + std::to_string(y) +
" under probe column " + std::to_string(column) +
"\n" + session.machine.copyScreenText());
}
static void savePicture(const Frame& frame, const fs::path& file)
{
if (file.empty()) return;
const auto area = frame.activeArea;
std::ofstream out(file, std::ios::binary);
out << "P6\n" << area.width << " " << area.height << "\n255\n";
for (int y = 0; y < area.height; ++y)
for (int x = 0; x < area.width; ++x) {
const auto rgb = frame.pixels[(area.y + y) * Frame::width + area.x + x];
out.put(char(rgb >> 16)); out.put(char(rgb >> 8)); out.put(char(rgb));
}
require(out.good(), "Could not save the guest display");
}
static void verify(const fs::path& roms, const fs::path& disk, const fs::path& bin,
Processor cpu, bool fromDisk, bool capture)
{
Session session(roms, disk, cpu, Profile::fd);
if (fromDisk) session.type("LOADM\"RIDGE\":EXEC\r");
else session.launch(bin);
expectScene(session, 132, 10, 0, true);
auto frame = session.machine.snapshot().frame;
const auto earthEdge = pixel(*frame, 12, 19);
if (capture) savePicture(*frame, "earth.ppm");
session.type("D");
expectScene(session, 140, 11, earthEdge);
session.type("A");
expectScene(session, 132, 10, earthEdge);
session.type(" ");
expectScene(session, 152, 10, 0, true);
const auto marsEdge = pixel(*session.machine.snapshot().frame, 12, 19);
require(marsEdge != earthEdge, "The two planets have the same terrain color");
session.type("R");
expectScene(session, 136, 10, marsEdge);
auto byteAt = [&](unsigned address) {
return session.machine.debuggerMemoryRange(address, 1, true).bytes.at(0);
};
require(byteAt(0x5000A) == 132 && byteAt(0x5200A) == 136,
"The screen changed without writing the two documented physical bytes");
session.type(" ");
expectScene(session, 132, 10, earthEdge);
session.type(" ");
expectScene(session, 136, 10, marsEdge);
if (capture) savePicture(*session.machine.snapshot().frame, "mars.ppm");
session.type("Q");
session.until("SURVEY COMPLETE");
session.verifyReturn();
session.verifyMedia();
}
int main(int argc, char** argv)
{
try {
require(argc == 4 || argc == 5, "Usage: run ROMS DISK BIN [capture]");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
verify(argv[1], argv[2], argv[3], cpu, false, argc == 5 && cpu == Processor::MC6809);
verify(argv[1], argv[2], argv[3], cpu, true, false);
}
std::cout << "PASS MC6809/HD6309 direct Run and disk EXEC: flight, planet switch, "
"physical ridge edit, return visit and BASIC return\n";
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+41
View File
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run banked-memory transfers in the emulator on both CPUs at every RAM setting."""
import argparse
import os
import re
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged guest toolchain containing libbank.a")
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("rom", type=Path, help="local CoCo 3 ROM")
args = parser.parse_args()
runtime = args.runtime.resolve(strict=True)
fixture = Path(__file__).resolve().parent
env = dict(os.environ, PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-banked-memory-") as work:
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", fixture.parents[2] / "src", fixture / "run.cpp",
args.core.resolve(strict=True), "-o", "check"], cwd=work, check=True)
for optimization in ("-O0", "-O2"):
print("Checking", optimization, flush=True)
layouts = (("QUAL.BIN", ("--org=2800",)),
("SPLIT.BIN", ("--org=3800", "--data=2800")))
for binary, flags in layouts:
subprocess.run([runtime / "bin/cmoc", "--coco", optimization, "--intermediate", "-Werror",
*flags, "-o", binary, fixture / "qualification.c", "-lbank"],
cwd=work, env=env, check=True)
listing = (Path(work) / "QUAL.map").read_text()
symbol = re.search(r"^Symbol: _bank_open \(.+?\) = ([0-9A-F]+)$", listing, re.MULTILINE)
if not symbol:
raise RuntimeError("Missing bank_open in the linker map")
subprocess.run(["./check", args.rom.resolve(strict=True), "QUAL.BIN", symbol[1], "SPLIT.BIN"],
cwd=work, check=True)
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <cmoc.h>
#include <vcc/bank.h>
#define CHECK(test) do { if (!(test)) return __LINE__; } while (0)
#define REG(address) (*(unsigned char *)(address))
static unsigned char buffer[515];
static asm unsigned char interruptMasks(void)
{
asm {
tfr cc,b
andb #$50
}
}
static int exercise(void)
{
unsigned i, boundary;
unsigned char saved, opened, actual;
CHECK(!bank_read(0, buffer, 1) && !bank_write(0, buffer, 1));
if (!bank_open()) {
printf("BANK UNAVAILABLE\n");
return 0;
}
bank_close();
// An inactive task has as much right to an explicit reservation as the active one.
saved = REG(0xffa8);
REG(0xffa8) = BANK_FIRST_PAGE;
opened = bank_open();
actual = REG(0xffa8);
if (opened) bank_close();
REG(0xffa8) = saved;
CHECK(!opened && (actual & 63) == BANK_FIRST_PAGE);
CHECK(bank_open());
CHECK(!bank_open());
// A caller can mask both IRQ and FIRQ for a transfer. Restore the masks
// even if the test fails, before printf or BASIC attempts to use IRQs.
saved = interruptMasks();
asm("orcc", "#$50");
opened = bank_read(0, buffer, 1);
actual = interruptMasks();
asm {
tfr cc,b
andb #$af
orb :saved
tfr b,cc
}
CHECK(opened && actual == 0x50);
CHECK(bank_read(BANK_CAPACITY, NULL, 0) && bank_write(0, NULL, 0));
CHECK(!bank_read(BANK_CAPACITY + 1, NULL, 0));
CHECK(!bank_write(BANK_CAPACITY, buffer, 1));
CHECK(!bank_write(0xffffu, buffer, 2));
CHECK(!bank_write(1, buffer, 0xffffu));
CHECK(!bank_write(17, NULL, 1) && !bank_read(17, NULL, 1));
CHECK(!bank_read(17, (void *)0x21, 1)); // BASIC's stack top
CHECK(!bank_write(17, (void *)0x21, 1));
CHECK(!bank_read(17, (void *)0x2800, 1)); // this binary's entry page
CHECK(!bank_write(17, (const void *)0x7fff, 2));
CHECK(!bank_read(17, (void *)0x8000, 1));
CHECK(!bank_write(17, (const void *)0xfffe, 3));
for (boundary = BANK_PAGE_SIZE; boundary < BANK_CAPACITY; boundary += BANK_PAGE_SIZE) {
// Straddle each boundary with an odd count and protect the two buffer ends.
for (i = 1; i <= 513; ++i)
buffer[i] = (unsigned char)(boundary / BANK_PAGE_SIZE + i);
CHECK(bank_write(boundary - 3, buffer + 1, 513));
memset(buffer, 0xd7, sizeof(buffer));
CHECK(bank_read(boundary - 3, buffer + 1, 513));
CHECK(buffer[0] == 0xd7 && buffer[514] == 0xd7);
for (i = 1; i <= 513; ++i)
CHECK(buffer[i] == (unsigned char)(boundary / BANK_PAGE_SIZE + i));
}
buffer[0] = 0xbd;
CHECK(bank_write(BANK_CAPACITY - 1, buffer, 1));
buffer[0] = 0x44;
CHECK(!bank_write(BANK_CAPACITY - 1, buffer, 2));
memset(buffer, 0xbb, sizeof(buffer));
CHECK(!bank_read(BANK_CAPACITY - 1, buffer, 2));
CHECK(buffer[0] == 0xbb && buffer[1] == 0xbb);
bank_close();
bank_close();
CHECK(!bank_write(0, buffer, 1) && !bank_read(0, buffer, 1));
CHECK(bank_open());
CHECK(bank_read(BANK_CAPACITY - 1, buffer, 1) && buffer[0] == 0xbd);
bank_close();
printf("BANK PASSED\n");
return 0;
}
int main(void)
{
int line = exercise();
if (line) printf("FAIL LINE %d\n", line);
return 0;
}
+158
View File
@@ -0,0 +1,158 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../basic-disk-session.h"
using namespace BasicDiskTests;
namespace {
constexpr unsigned bankBase = 0x50000;
constexpr unsigned bankSize = 8192;
constexpr unsigned capacity = 4 * bankSize;
bool sameMapping(const VCC::MMUState& before, const VCC::MMUState& after) {
return before.Enabled == after.Enabled && before.ActiveTask == after.ActiveTask &&
before.RamVectors == after.RamVectors && before.RomMap == after.RomMap &&
before.AllRAM == after.AllRAM && before.Prefix == after.Prefix &&
before.Task0 == after.Task0 && before.Task1 == after.Task1;
}
void until(MachineSession& machine, const std::string& message) {
for (unsigned n = 0; n < 1000; ++n) {
const auto screen = machine.copyScreenText();
if (screen.find(message) != screen.npos) return;
if (screen.find("FAIL LINE") != screen.npos) {
for (unsigned i = 0; i < 6; ++i) machine.advance();
throw std::runtime_error(machine.copyScreenText());
}
machine.advance();
machine.takeAudio();
}
throw std::runtime_error("Expected " + message + " on screen: " + machine.copyScreenText());
}
enum class Mapping { basic, taskOne, disabled, splitLayout };
void stopAt(MachineSession& machine, std::uint16_t address) {
machine.debuggerSetBreakpoints({address});
machine.resume();
for (unsigned i = 0; i < 300 && machine.snapshot().state == RunState::Running; ++i)
machine.advance();
require(machine.debuggerSnapshot().cpu.PC == address, "Did not reach bank API breakpoint");
machine.debuggerSetBreakpoints({});
}
// Inject unusual mappings only around bank_open(). BASIC's own screen/IRQ
// handling can program the GIME again after it regains control.
void checkRejectedMapping(MachineSession& machine, Mapping mapping, std::uint16_t open) {
stopAt(machine, open);
const auto before = machine.debuggerSnapshot();
const auto stack = machine.debuggerMemoryRange(before.cpu.S, 2, false).bytes;
const auto caller = std::uint16_t(stack[0] << 8 | stack[1]);
const auto init0 = SafeMemRead8(0xff90);
const auto init1 = SafeMemRead8(0xff91);
if (mapping == Mapping::taskOne) {
// Mirror task 0 to keep the running instructions and stack in place.
for (unsigned i = 0; i < 8; ++i)
MmuWrite8(std::uint8_t(before.mmu.Task0[i]), std::uint16_t(0xffa8 + i));
MmuWrite8(init1 | 1, 0xff91);
} else {
MmuWrite8(init0 & ~0x40, 0xff90);
}
const auto challenged = machine.debuggerSnapshot().mmu;
require(challenged.ActiveTask == (mapping == Mapping::taskOne) &&
challenged.Enabled == (mapping != Mapping::disabled), "Failed to establish test mapping");
stopAt(machine, caller);
const auto after = machine.debuggerSnapshot();
require(sameMapping(challenged, after.mmu), "Rejected open changed custom mapping");
require(after.cpu.B == 0, "Unexpected open with custom mapping");
MmuWrite8(init0, 0xff90);
MmuWrite8(init1, 0xff91);
if (mapping == Mapping::taskOne)
for (unsigned i = 0; i < 8; ++i)
MmuWrite8(std::uint8_t(before.mmu.Task1[i]), std::uint16_t(0xffa8 + i));
}
void qualify(const Bytes& rom, const Bytes& program, Processor cpu, unsigned ram, Mapping mapping, std::uint16_t open) {
MachineConfiguration configuration;
configuration.processor = cpu;
configuration.ram = ram;
MachineSession machine;
machine.configure(configuration);
machine.load(rom, cpu);
machine.resume();
until(machine, "OK");
auto physical = [&](unsigned address, unsigned length) {
return machine.debuggerMemoryRange(address, length, true).bytes;
};
const auto size = program.size();
require(size >= 5 && program[size - 5] == 0xff, "Invalid DECB fixture");
machine.debuggerLoadBinary(program, std::uint16_t(program[size - 2] << 8 | program.back()));
machine.debuggerClearDevelopmentBreakpoints();
const auto initial = machine.debuggerSnapshot().mmu;
const bool supported = ram != 0 && mapping == Mapping::basic;
Bytes expected;
Bytes freeRam, belowProgram;
if (ram != 0) {
// One real physical byte on either side catches off-by-one accesses.
expected = physical(bankBase - 1, capacity + 2);
} else {
// On 128 KiB the asset banks mirror BASIC's physical banks $08..$0B.
// Exclude live BASIC state and the loaded program, starting at $2800.
freeRam = physical(0, 65536);
belowProgram = physical(0x11000, 0x1800);
}
if (supported) {
for (unsigned boundary = bankSize; boundary < capacity; boundary += bankSize) {
for (unsigned i = 1; i <= 513; ++i)
expected[boundary - 3 + i] = std::uint8_t(boundary / bankSize + i);
}
expected[capacity] = 0xbd; // index zero is the lower guard byte
}
if (mapping == Mapping::taskOne || mapping == Mapping::disabled)
checkRejectedMapping(machine, mapping, open);
machine.resume();
until(machine, supported ? "BANK PASSED\nOK" : "BANK UNAVAILABLE\nOK");
require(sameMapping(initial, machine.debuggerSnapshot().mmu), "Guest changed the BASIC MMU map");
if (ram != 0) {
require(physical(bankBase - 1, capacity + 2) == expected,
"A reserved byte or a neighboring physical byte differs from the expected image");
} else {
require(physical(0, 65536) == freeRam && physical(0x11000, 0x1800) == belowProgram,
"RAM changed during a rejected 128 KiB reservation");
}
// Enter PRINT 7*9 through the keyboard matrix after returning from main.
constexpr auto key = [](unsigned bit) { return std::uint64_t(1) << bit; };
machine.paste({key(16), key(18), key(9), key(14), key(20), key(31),
key(39), key(55) | key(42), key(41), key(48)});
until(machine, " 63");
std::cout << "PASS " << (cpu == Processor::MC6809 ? "6809" : "6309") << ", "
<< initial.RAMBytes / 1024 << " KiB: ";
if (mapping == Mapping::taskOne) std::cout << "task 1, ";
if (mapping == Mapping::disabled) std::cout << "MMU disabled, ";
if (mapping == Mapping::splitLayout) std::cout << "writable data below code, ";
std::cout << (supported ? "physical bank contents" : "safe refusal")
<< ", restored MMU and BASIC input\n";
}
} // namespace
int main(int argc, char** argv) {
try {
require(argc == 5, "Usage: bank-check COCO3_ROM QUAL.BIN BANK_OPEN SPLIT.BIN");
const auto rom = readFile(argv[1]);
const auto program = readFile(argv[2]);
const auto split = readFile(argv[4]);
const auto open = std::uint16_t(std::stoul(argv[3], nullptr, 16));
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
for (unsigned ram = 0; ram < 4; ++ram)
qualify(rom, program, cpu, ram, Mapping::basic, open);
qualify(rom, program, cpu, 1, Mapping::taskOne, open);
qualify(rom, program, cpu, 1, Mapping::disabled, open);
qualify(rom, split, cpu, 1, Mapping::splitLayout, 0);
}
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+159
View File
@@ -0,0 +1,159 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "core/MachineSession.h"
#include "devices/FD502/Fd502Device.h"
#include "devices/HardDisk/HardDiskDevice.h"
#include "devices/SDCDevice.h"
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace BasicDiskTests {
using namespace VCC::Mac;
using namespace VCC::Devices;
namespace fs = std::filesystem;
using Bytes = std::vector<std::uint8_t>;
static Bytes readFile(const fs::path& path) {
std::ifstream f(path, std::ios::binary);
if (!f) throw std::runtime_error("Cannot open " + path.string());
return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
}
static void require(bool ok, const std::string& reason) {
if (!ok) throw std::runtime_error(reason);
}
enum class Profile { fd, rgbHD, rgbFD, sdc };
constexpr std::size_t rgbStart = 0x5a000u * 256;
struct Session {
MachineSession machine;
std::shared_ptr<Fd502Device> floppy;
std::shared_ptr<HardDiskDevice> hard;
std::shared_ptr<SDCDevice> sdc;
fs::path diskPath;
Bytes original;
Bytes second;
Profile profile;
Session(const fs::path& roms, const fs::path& disk, Processor cpu, Profile mode, bool expectSDCStartupMount = true)
: diskPath(disk), original(readFile(disk)), profile(mode) {
require(original.size() == 35 * 18 * 256, "Expected a 35-track test disk");
const auto secondPath = disk.parent_path() / "SECOND.DSK";
if (fs::exists(secondPath)) second = readFile(secondPath);
if (mode == Profile::sdc) {
// startup.cfg lives next to the disposable disk and selects SDC drive 0.
sdc = std::make_shared<SDCDevice>(readFile(roms / "sdcdos.rom"), disk.parent_path().string(), false);
machine.cartridges().configure({nullptr, nullptr, nullptr, nullptr, sdc}, true, 4);
} else {
floppy = std::make_shared<Fd502Device>(readFile(roms / (mode == Profile::fd ? "disk11.rom" : "rgbdos.rom")));
floppy->mount(0, DiskImage::load(original));
if (!second.empty()) floppy->mount(1, DiskImage::load(second, true));
if (mode != Profile::fd) {
hard = std::make_shared<HardDiskDevice>();
Bytes vhd(rgbStart + original.size() + second.size(), 0);
std::copy(original.begin(), original.end(), vhd.begin() + rgbStart);
std::copy(second.begin(), second.end(), vhd.begin() + rgbStart + original.size());
hard->mount(0, HardDiskImage(std::move(vhd)));
}
machine.cartridges().configure({nullptr, hard, nullptr, nullptr, floppy}, true, 4);
}
machine.load(readFile(roms / "coco3.rom"), cpu);
if (sdc) {
auto config = machine.snapshot().configuration;
config.ram = 2; // 2 MiB, as in the built-in CoCo SDC profile
machine.configure(config);
}
machine.resume();
frames(300);
until(hard ? "HARD DISK BASIC" : "OK");
if (sdc) require(sdc->snapshot().drives[0].mounted == expectSDCStartupMount, "Unexpected SDC drive 0 at startup");
if (mode == Profile::rgbFD) type("DRIVE OFF\r");
type("CLS\r");
}
void frames(unsigned count) {
while (count--) machine.advance();
machine.takeAudio();
}
void until(const std::string& marker, unsigned limit = 9000) {
for (unsigned i = 0; i < limit; ++i) {
auto text = machine.copyScreenText();
if (text.find("FAIL LINE") != text.npos) {
frames(10);
throw std::runtime_error(machine.copyScreenText());
}
if (text.find(marker) != text.npos) return;
frames(1);
}
throw std::runtime_error("Timed out waiting for " + marker + "\n" + machine.copyScreenText());
}
void type(const std::string& keys) {
for (char c : keys) {
unsigned bit;
bool shift = false;
if (c >= 'A' && c <= 'Z') bit = c - '@';
else if (c >= '0' && c <= '9') bit = 32 + c - '0';
else if (c == ' ') bit = 31;
else if (c == '\r') bit = 48;
else if (c == ':') bit = 42;
else if (c == '"') { bit = 34; shift = true; }
else if (c == '*') { bit = 42; shift = true; }
else throw std::logic_error("Unknown fixture key");
machine.setKeyboard((std::uint64_t(1) << bit) | (std::uint64_t(shift) << 55));
frames(5);
machine.setKeyboard(0);
frames(5);
}
}
void launch(const fs::path& binary) {
const auto program = readFile(binary);
const auto n = program.size();
require(n >= 5 && program[n - 5] == 0xff, "Incomplete DECB binary");
machine.debuggerLoadBinary(program, std::uint16_t(program[n - 2] << 8 | program[n - 1]));
machine.debuggerClearDevelopmentBreakpoints();
machine.resume();
}
std::uint64_t reads() const {
if (sdc) return sdc->snapshot().drives[0].reads;
if (profile == Profile::rgbHD) return hard->readEvents(0);
return floppy->readEvents(0);
}
std::uint64_t otherReads() const {
if (!hard) return 0;
return profile == Profile::rgbHD ? floppy->readEvents(0) : hard->readEvents(0);
}
void verifyMedia() const {
if (floppy) require(floppy->writeEvents(0) == 0 && floppy->image(0)->bytes() == original, "Floppy changed");
if (floppy && !second.empty())
require(floppy->writeEvents(1) == 0 && floppy->image(1)->bytes() == second, "Second floppy changed");
if (hard) {
const auto& bytes = hard->image(0)->bytes();
require(hard->writeEvents(0) == 0 && !hard->image(0)->dirty() &&
bytes.size() == rgbStart + original.size() + second.size() &&
std::equal(second.begin(), second.end(), bytes.begin() + rgbStart + original.size()) &&
std::equal(original.begin(), original.end(), bytes.begin() + rgbStart), "VHD changed");
}
if (sdc && !second.empty())
require(sdc->snapshot().drives[1].writes == 0 && readFile(diskPath.parent_path() / "SECOND.DSK") == second,
"Second SDC image changed");
if (sdc) require(sdc->snapshot().drives[0].writes == 0 && readFile(diskPath) == original, "SDC image changed");
}
void eject() {
if (sdc) sdc->eject(0);
else if (profile == Profile::rgbHD) hard->eject(0);
else floppy->eject(0);
}
void verifyReturn() {
until("OK");
// OK is drawn before the ROM finishes returning to its line editor.
frames(12);
type("PRINT 7*9\r");
until(" 63");
}
};
} // namespace BasicDiskTests
+54
View File
@@ -0,0 +1,54 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Cross-read tapes recorded by the real BASIC ROM and by the packaged CMOC SDK."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="save the guest's flight replay screen")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
lessons = root / "examples/cmoc/manual"
disk = root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK"
env = dict(os.environ, PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"], VCC_CMOC_COMPAT="1")
with tempfile.TemporaryDirectory(prefix="vcc-cassette-demo-") as tmp:
def run(*command):
subprocess.run(command, cwd=tmp, env=env, check=True)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
card = Path(tmp) / "card"
card.mkdir()
practice = card / "VOL.DSK"
shutil.copyfile(disk, practice)
(card / "startup.cfg").write_text("0=VOL.DSK\n")
for opt in ("-O0", "-O2"):
for source, binary in ((lessons / "flightrecorder.c", "FLIGHT.BIN"),
(fixture / "qualification.c", "QUAL.BIN")):
run(runtime / "bin/cmoc", "--coco", opt, "-Werror", "--org=2800",
"-o", binary, source, "-lvcccompat")
for cpu in ("6809", "6309"):
starter = root / "platforms/macos/Resources/StarterMedia/Hello World.cas"
run("./run", roms, practice, cpu, lessons, starter, "disk")
if opt == "-O2":
for setup in ("wav", "rgb-hd", "sdc"):
run("./run", roms, practice, cpu, lessons, starter, setup)
print(f"PASS {cpu} {opt} {setup}: recorded in C and read in BASIC, and vice versa", flush=True)
if args.capture and (cpu, opt) == ("6809", "-O2"):
run("sips", "-s", "format", "png", "flight.ppm", "--out", args.capture.resolve())
print(f"PASS {cpu} {opt}: BASIC/C cassette exchange, empty files, cross-block records and damaged tapes",
flush=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,68 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <coco.h>
#include <vcc/cassette.h>
#define CHECK(expr) do { if (!(expr)) { printf("FAIL LINE %u\n", (unsigned)__LINE__); return 1; } } while (0)
int main(void)
{
char line[251];
unsigned i;
cls(1);
printf("EMPTY OR BLOCK CHECK\n");
char choice = waitkey(0);
if (choice == 'W' || choice == 'P') {
CHECK(vcc_tape_open_write(choice == 'W' ? "Flight" : "FLIGHT") == VCC_TAPE_OK);
if (choice == 'P') {
for (i = 0; i < 2; ++i) {
memset(line, i ? 'B' : 'A', 180);
line[180] = 0;
CHECK(vcc_tape_write_line(line) == VCC_TAPE_OK);
}
CHECK(vcc_tape_write_line("") == VCC_TAPE_OK);
}
} else {
CHECK(vcc_tape_open_read(choice == 'E' ? "Flight" : "FLIGHT") == VCC_TAPE_OK);
CHECK(vcc_tape_open_write("OTHER") == VCC_TAPE_BUSY);
if (choice == 'T') {
int status;
do {
status = vcc_tape_read_line(line, sizeof line);
} while (status == VCC_TAPE_OK);
CHECK(status < 0);
vcc_tape_close();
printf("MOUNT GOOD TAPE AND PRESS R\n");
CHECK(waitkey(0) == 'R');
CHECK(vcc_tape_open_read("FLIGHT") == VCC_TAPE_OK);
CHECK(vcc_tape_read_line(line, sizeof line) == VCC_TAPE_OK);
CHECK(strcmp(line, "EARTH TIDE POOL") == 0);
CHECK(vcc_tape_read_line(line, sizeof line) == VCC_TAPE_OK);
CHECK(strcmp(line, "MARS DUST DEVIL") == 0);
} else if (choice == 'L') {
char small[6] = "KEEP";
small[5] = 'X';
CHECK(vcc_tape_read_line(small, 5) == VCC_TAPE_LONG);
CHECK(small[0] == 0 && small[5] == 'X');
CHECK(vcc_tape_read_line(line, sizeof line) == VCC_TAPE_OK);
CHECK(strcmp(line, "MARS DUST DEVIL") == 0);
} else if (choice == 'B') {
/* Two long records make the second span a 255-byte ROM data block. */
for (i = 0; i < 2; ++i) {
CHECK(vcc_tape_read_line(line, sizeof line) == VCC_TAPE_OK);
CHECK(strlen(line) == 180);
for (unsigned j = 0; j < 180; ++j)
CHECK(line[j] == (i ? 'B' : 'A'));
}
CHECK(vcc_tape_read_line(line, sizeof line) == VCC_TAPE_OK);
CHECK(line[0] == 0); /* A blank line is a record; an empty file has none. */
CHECK(vcc_tape_read_line(line, sizeof line) == VCC_TAPE_OK);
CHECK(strcmp(line, "TAIL") == 0); /* Final BASIC PRINT used a semicolon. */
} else {
CHECK(choice == 'E');
}
CHECK(vcc_tape_read_line(line, sizeof line) == VCC_TAPE_EOF);
}
CHECK(vcc_tape_close() == VCC_TAPE_OK);
printf("CASSETTE CHECK PASSED\n");
return 0;
}
+209
View File
@@ -0,0 +1,209 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
static void atPrompt(Session& g)
{
g.verifyReturn();
g.type("CLS\r");
g.frames(15);
}
static std::string basicSource(const fs::path& path)
{
auto bytes = readFile(path);
return {bytes.begin(), bytes.end()};
}
static void basic(Session& g, const std::string& source)
{
g.machine.basicLoadSource(source, true);
}
static void selectC(Session& g, const char* binary, const char* prompt, const char* choice)
{
g.launch(binary);
g.until(prompt);
g.type(choice);
}
static void play(Session& g, const Bytes& image, TapeFormat format = TapeFormat::CAS)
{
auto& tape = g.machine.cassette();
tape.mount(image, format);
tape.play();
}
static Bytes finishRecording(Session& g, const char* marker)
{
g.until(marker);
g.until("OK");
auto& tape = g.machine.cassette();
require(tape.snapshot().writeEvents && !tape.snapshot().motor, "Recording should finish with the motor off");
auto image = tape.exportImage();
require(!image.empty(), "Recorder did not produce an image");
atPrompt(g);
return image;
}
static void checkScreen(Session& g, const std::string& expected)
{
auto screen = g.machine.copyScreenText();
require(screen.find(expected) != std::string::npos, "Unexpected flight records:\n" + screen);
}
static std::size_t blockSync(const Bytes& tape, unsigned type)
{
const Bytes pattern = {0x55, 0x3c, static_cast<std::uint8_t>(type)};
auto p = std::search(tape.begin(), tape.end(), pattern.begin(), pattern.end());
require(p != tape.end(), "Expected filename/data/EOF block in the real recording");
return static_cast<std::size_t>(p - tape.begin()) + 1;
}
int main(int argc, char** argv)
{
try {
require(argc == 7, "Usage: run ROM-DIRECTORY DISK CPU LESSONS STARTER-CAS SETUP");
const fs::path lessons = argv[4];
const auto reader = basicSource(lessons / "flightread.bas");
const auto writer = basicSource(lessons / "flightwrite.bas");
const auto cpu = std::string(argv[3]) == "6809" ? Processor::MC6809 : Processor::HD6309;
const std::string setup = argv[6];
const auto profile = setup == "sdc" ? Profile::sdc : setup == "rgb-hd" ? Profile::rgbHD : Profile::fd;
const auto format = setup == "wav" ? TapeFormat::WAV : TapeFormat::CAS;
Session g(argv[1], argv[2], cpu, profile);
auto& tape = g.machine.cassette();
tape.record(format);
selectC(g, "FLIGHT.BIN", "W WRITE R READ", "W");
const auto fromC = finishRecording(g, "FLIGHT SAVED");
play(g, fromC, format);
basic(g, reader);
g.until("END OF FLIGHT");
checkScreen(g, "EARTH BLUE SEA\nMARS RED RIDGE\nEND OF FLIGHT");
atPrompt(g);
tape.record(format);
basic(g, writer);
const auto fromBASIC = finishRecording(g, "FLIGHT SAVED");
play(g, fromBASIC, format);
selectC(g, "FLIGHT.BIN", "W WRITE R READ", "R");
g.until("END OF FLIGHT");
checkScreen(g, "EARTH TIDE POOL\nMARS DUST DEVIL\nEND OF FLIGHT");
g.until("OK");
g.frames(3);
if (setup != "disk") {
atPrompt(g);
g.verifyMedia();
return 0;
}
saveActiveFrame(*g.machine.snapshot().frame, "flight.ppm");
atPrompt(g);
tape.record(TapeFormat::CAS);
selectC(g, "QUAL.BIN", "EMPTY OR BLOCK CHECK", "W");
play(g, finishRecording(g, "CASSETTE CHECK PASSED"));
basic(g, "10 OPEN \"I\",#-1,\"Flight\"\n20 IF NOT EOF(-1) THEN PRINT \"FAIL LINE 20\":END\n"
"30 CLOSE #-1:PRINT \"EMPTY IN BASIC\"\n");
g.until("EMPTY IN BASIC");
atPrompt(g);
tape.record(TapeFormat::CAS);
basic(g, "10 OPEN \"O\",#-1,\"Flight\"\n20 CLOSE #-1:PRINT \"BASIC EMPTY SAVED\"\n");
play(g, finishRecording(g, "BASIC EMPTY SAVED"));
selectC(g, "QUAL.BIN", "EMPTY OR BLOCK CHECK", "E");
g.until("CASSETTE CHECK PASSED");
atPrompt(g);
tape.record(TapeFormat::CAS);
basic(g, "10 OPEN \"O\",#-1,\"FLIGHT\"\n20 PRINT #-1,STRING$(180,65)\n"
"30 PRINT #-1,STRING$(180,66)\n40 PRINT #-1,\"\"\n45 PRINT #-1,\"TAIL\";\n50 CLOSE #-1:PRINT \"BLOCKS SAVED\"\n");
play(g, finishRecording(g, "BLOCKS SAVED"));
selectC(g, "QUAL.BIN", "EMPTY OR BLOCK CHECK", "B");
g.until("CASSETTE CHECK PASSED");
atPrompt(g);
tape.record(TapeFormat::CAS);
selectC(g, "QUAL.BIN", "EMPTY OR BLOCK CHECK", "P");
play(g, finishRecording(g, "CASSETTE CHECK PASSED"));
basic(g, "10 CLEAR 1024:OPEN \"I\",#-1,\"FLIGHT\"\n"
"20 FOR I=65 TO 66:LINE INPUT #-1,A$\n"
"30 IF A$<>STRING$(180,I) THEN PRINT \"FAIL LINE 30\":END\n40 NEXT I\n"
"50 LINE INPUT #-1,A$:IF LEN(A$)<>0 THEN PRINT \"FAIL LINE 50\":END\n"
"60 IF NOT EOF(-1) THEN PRINT \"FAIL LINE 60\":END\n70 CLOSE #-1:PRINT \"C BLOCKS VERIFIED\"\n");
g.until("C BLOCKS VERIFIED");
atPrompt(g);
// The reader must pass an unrelated named file, consume a too-long line, then read the next.
tape.record(TapeFormat::CAS);
basic(g, "5 OPEN \"O\",#-1,\"OTHER\":PRINT #-1,\"IGNORE ME\":CLOSE #-1\n" + writer);
play(g, finishRecording(g, "FLIGHT SAVED"));
selectC(g, "QUAL.BIN", "EMPTY OR BLOCK CHECK", "L");
g.until("CASSETTE CHECK PASSED");
atPrompt(g);
// Program files can have consecutive blocks with short leaders. Search past the
// bundled tokenized BASIC program to reach a BASIC-written sequential data file.
auto mixed = readFile(argv[5]);
mixed.insert(mixed.end(), fromBASIC.begin(), fromBASIC.end());
for (bool fast : {false, true}) {
tape.setFast(fast);
play(g, mixed);
selectC(g, "FLIGHT.BIN", "W WRITE R READ", "R");
g.until("END OF FLIGHT");
checkScreen(g, "EARTH TIDE POOL\nMARS DUST DEVIL\nEND OF FLIGHT");
atPrompt(g);
}
tape.setFast(false);
// Cut the real BASIC recording within a data block, at the end marker, and before its checksum.
const auto data = blockSync(fromBASIC, 1);
const auto end = blockSync(fromBASIC, 255);
for (auto length : {data + 6, end, end + 3}) {
play(g, Bytes(fromBASIC.begin(), fromBASIC.begin() + length));
selectC(g, "FLIGHT.BIN", "W WRITE R READ", "R");
g.until("TAPE ERROR");
const auto screen = g.machine.copyScreenText();
require(screen.find("END OF FLIGHT") == screen.npos, "A short tape was accepted as EOF");
require(!tape.snapshot().motor, "C left the motor running after a read error");
atPrompt(g);
}
play(g, Bytes(fromBASIC.begin(), fromBASIC.begin() + end));
selectC(g, "QUAL.BIN", "EMPTY OR BLOCK CHECK", "T");
g.until("MOUNT GOOD TAPE AND PRESS R");
require(!tape.snapshot().motor, "Close after read error left motor on");
play(g, fromBASIC);
g.type("R");
g.until("CASSETTE CHECK PASSED");
atPrompt(g);
auto damaged = fromC;
const auto dataSync = blockSync(damaged, 1);
damaged[dataSync + 3 + damaged.at(dataSync + 2)] ^= 1; // corrupt only the checksum
play(g, damaged);
basic(g, reader);
g.until("?IO ERROR");
// Reset the ROM after its error before starting the separate physical-end test.
g.machine.softReset();
g.machine.resume();
g.frames(300);
g.type("CLS\r");
g.frames(15);
// The unmodified BASIC ROM has no missing-carrier timeout. Check the guest at physical end,
// then observe another five guest seconds; a truncated C tape must never yield the EOF marker.
play(g, Bytes(fromC.begin(), fromC.begin() + blockSync(fromC, 255)));
basic(g, reader);
for (unsigned i = 0; i < 1500 && tape.snapshot().position < tape.snapshot().length; ++i) g.frames(1);
require(tape.snapshot().position == tape.snapshot().length, "BASIC did not reach the cut");
g.frames(300);
const auto screen = g.machine.copyScreenText();
require(screen.find("END OF FLIGHT") == screen.npos && tape.snapshot().motor &&
tape.snapshot().mode == TapeMode::Stopped, "BASIC reported a completed file on a truncated tape:\n" + screen);
g.verifyMedia();
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+57
View File
@@ -0,0 +1,57 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build Planet Expedition from source and fly its real disks under SDC-DOS."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="save the guest's Mars landing as a PNG")
args = parser.parse_args()
runtime, core, roms = [p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-planet-expedition-") as tmp:
work = Path(tmp)
run = work / "run"
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", run], check=True)
for config in ("Debug", "Release"):
project = work / config
shutil.copytree(root / "examples/cmoc/PlanetExpedition", project)
subprocess.run([runtime / "bin/make", "-j3", "VCC_CONFIGURATION=" + config],
cwd=project, env=env, check=True)
card = project / "EXPED"
if {p.name for p in card.iterdir()} != {"EXPLORE.DSK", "EARTH.DSK", "MARS.DSK"}:
raise AssertionError("Expected the three practice images in EXPED")
originals = {p.name: p.read_bytes() for p in card.iterdir()}
capture = bool(args.capture) and config == "Release"
subprocess.run([run, roms, card, project / "EXPLORE.BIN", "capture" if capture else "check"],
cwd=work, check=True)
if {p.name: p.read_bytes() for p in card.iterdir()} != originals:
raise AssertionError("The guest changed the practice card or the starter disk")
if capture:
subprocess.run(["sips", "-s", "format", "png", work / "expedition.ppm",
"--out", args.capture.resolve()], check=True)
if config == "Release":
(project / "assets/mars.txt").write_text("MARS: ICE CAP\nLAND NEAR THE POLE.\n")
subprocess.run([runtime / "bin/make", "VCC_CONFIGURATION=Release"], cwd=project, env=env, check=True)
if (card / "MARS.DSK").read_bytes() == originals["MARS.DSK"]:
raise AssertionError("Editing the Mars landing instructions did not rebuild the data disk")
for name in ("EARTH.DSK", "EXPLORE.DSK"):
if (card / name).read_bytes() != originals[name]:
raise AssertionError(f"Unrelated image {name} changed")
subprocess.run([run, roms, card, project / "EXPLORE.BIN", "edited"], cwd=work, check=True)
print(f"PASS {config}: directory, disk load, two destinations, missing disk, direct Run and read-only media")
if __name__ == "__main__":
main()
+113
View File
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
// The SDC-DOS mount command also needs three punctuation keys.
static void enter(Session& guest, const std::string& command)
{
for (char c : command) {
if (c == ',' || c == '.' || c == '/') {
guest.machine.setKeyboard(std::uint64_t(1) << (c == ',' ? 44 : c == '.' ? 46 : 47));
guest.frames(5);
guest.machine.setKeyboard(0);
guest.frames(5);
} else {
guest.type(std::string(1, c));
}
}
}
static void checkChart(Session& guest)
{
guest.until("Q QUIT");
guest.frames(8);
const auto text = guest.machine.copyScreenText();
for (auto name : {" EARTH.DSK", " MARS.DSK", " EXPLORE.DSK", "SDC0: EXPLORE.DSK", "SDC1: EMPTY"})
require(text.find(name) != text.npos, "Chart is missing " + std::string(name) + "\n" + text);
}
static void checkMounts(Session& guest, const std::string& planet)
{
const auto disks = guest.sdc->snapshot().drives;
require(disks[0].mounted && fs::path(disks[0].name).filename() == "EXPLORE.DSK", "Program disk changed");
require(disks[1].mounted && fs::path(disks[1].name).filename() == planet, "Unexpected planet disk");
require(disks[1].reads > 0 && !disks[1].writes && !disks[0].writes, "Expected read-only planet visit");
}
static void fly(const fs::path& roms, const fs::path& card, const fs::path& binary, Processor cpu, const std::string& mode)
{
const std::string mars = mode == "edited" ? "MARS: ICE CAP\nLAND NEAR THE POLE." : "MARS: RED RIDGE\nLAND BEYOND THE DUST FIELD.";
Session guest(roms, card / "EXPLORE.DSK", cpu, Profile::sdc, false);
guest.sdc->setWriteProtected(true);
enter(guest, "DRIVE 0,\"/EXPLORE.DSK\"\r");
guest.until("OK");
require(fs::path(guest.sdc->snapshot().drives[0].name).filename() == "EXPLORE.DSK", "BASIC did not mount program disk");
enter(guest, "LOADM\"EXPLORE:0\":EXEC\r");
checkChart(guest);
guest.type("1");
guest.until("SDC1: EARTH.DSK");
guest.until("EARTH: BLUE OCEAN\nSPLASH DOWN BESIDE THE BUOY.");
checkMounts(guest, "EARTH.DSK");
guest.until("Q QUIT");
guest.frames(8);
guest.type("2");
guest.until("SDC1: MARS.DSK");
guest.until(mars);
guest.until("Q QUIT");
checkMounts(guest, "MARS.DSK");
if (mode == "capture" && cpu == Processor::MC6809) {
guest.frames(3);
saveActiveFrame(*guest.machine.snapshot().frame, "expedition.ppm");
}
guest.type("3");
guest.until("COULD NOT MOUNT /MISSING.DSK");
guest.until(mars);
guest.until("SDC1: MARS.DSK");
checkMounts(guest, "MARS.DSK");
guest.until("Q QUIT");
guest.frames(8);
guest.type("Q");
guest.until("EXPEDITION COMPLETE");
guest.verifyReturn();
guest.verifyMedia();
guest.type("CLS\rDIR 0\r");
guest.until("EXPLORE");
guest.until("BIN");
guest.until("OK");
guest.frames(12);
guest.type("CLS\rDIR 1\r");
guest.until("LANDING");
guest.until("TXT");
guest.until("OK");
guest.frames(12);
// Running the same binary directly uses the card that is still mounted.
guest.launch(binary);
guest.until("DISKS ON THE PRACTICE CARD");
guest.until("Q QUIT");
guest.frames(8);
guest.until("SDC1: MARS.DSK");
guest.type("1");
guest.until("SPLASH DOWN BESIDE THE BUOY.");
checkMounts(guest, "EARTH.DSK");
guest.until("Q QUIT");
guest.frames(8);
guest.type("Q");
guest.until("EXPEDITION COMPLETE");
guest.verifyReturn();
}
int main(int argc, char** argv)
{
try {
require(argc == 5, "Usage: run ROMDIR CARD BIN CAPTURE");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
fly(argv[1], argv[2], argv[3], cpu, argv[4]);
std::cout << "PASS " << (cpu == Processor::MC6809 ? "6809" : "6309") << " expedition under SDC-DOS\n";
}
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 1;
}
}
+115
View File
@@ -0,0 +1,115 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Qualify bounded fixed-decimal output using exact BASIC-float test vectors."""
import argparse
from fractions import Fraction
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def floor_code(value):
"""Positive BASIC encoding at or immediately below a positive rational."""
exponent = value.numerator.bit_length() - value.denominator.bit_length()
if Fraction(2) ** exponent > value:
exponent -= 1
significand = int(value * Fraction(2) ** (31 - exponent))
return ((exponent + 129) << 31) + significand - (1 << 31)
def write_vectors(path):
# Changing this positive encoding by one steps one representable value,
# including across a power of two. Exercise both signs of each input.
cases = set()
for places in range(4):
scale = 10 ** places
centers = [Fraction(n, 2 * scale) for n in (1, 3, 19, 20 * scale - 1, 131072 * scale - 1)]
centers.extend([Fraction(1, 2 ** (places + 1)), Fraction(65536)])
codes = {0, 1 << 31, (256 << 31) - 1}
for center in centers:
code = floor_code(center)
codes.update((code - 1, code, code + 1))
for code in codes:
for negative in (False, True):
cases.add((code, negative, places))
cases.update([(floor_code(Fraction(1)), False, 4), (0, False, 255)])
rows = []
for code, negative, places in sorted(cases):
exp, fraction = divmod(code, 1 << 31)
magnitude = Fraction((1 << 31) + fraction) * Fraction(2) ** (exp - 160) if exp else Fraction(0)
packed = bytes([exp]) + (fraction | (int(negative) << 31)).to_bytes(4, 'big')
expected = 'NULL'
if magnitude < 65536 and places <= 3:
scale = 10 ** places
rounded = int(magnitude * scale + Fraction(1, 2))
whole, tail = divmod(rounded, scale)
sign = '-' if rounded and negative else ''
decimal = f'.{tail:0{places}d}' if places else ''
expected = f'"{sign}{whole}{decimal}"'
octets = ', '.join(f'0x{b:02x}' for b in packed)
rows.append(f' {{ {{ {octets} }}, {places}, {expected} }},')
path.write_text('\n'.join(rows) + '\n')
return len(rows)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('runtime', type=Path)
parser.add_argument('core', type=Path)
parser.add_argument('roms', type=Path)
parser.add_argument('--capture', type=Path, help="save the optimized 6809 guest display as a PNG")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-descent-") as temp:
work = Path(temp)
def run(*cmd):
subprocess.run(cmd, cwd=work, env=env, check=True)
print(f'{write_vectors(work / "vectors.inc")} exact rational vectors', flush=True)
shutil.copyfile(fixture / 'qualification.c', work / 'qualification.c')
run('xcrun', 'clang++', '-std=c++17', '-O2', '-mmacosx-version-min=14.0', '-I', root / 'src',
fixture / 'run.cpp', core, '-o', 'run')
cmoc = runtime / 'bin/cmoc'
descent = root / 'examples/cmoc/manual/descent.c'
# These are the two edits readers can try in the chapter.
source = descent.read_text()
(work / 'level.c').write_text(source.replace('report(105.50f,', 'report(101.75f,'))
(work / 'short.c').write_text(source.replace('char field[12]', 'char field[5]'))
for opt in ('-O0', '-O2'):
build = [cmoc, '--coco', '--org=2800', '-Werror', opt]
run(*build, '-o', 'QUAL.BIN', 'qualification.c', '-lvcccompat')
if opt == '-O0':
# Production archive objects always use -O2. Also build the
# formatter itself without optimization to catch compiler issues.
run(*build, '-c', '-o', 'fixed-plain.o', root / 'sdk/cmoc/compat/fixed.c')
run(*build, '-o', 'PLAIN.BIN', 'qualification.c', 'fixed-plain.o')
run(*build, '--intermediate', '-o', 'DESCENT.BIN', descent, '-lvcccompat')
for name in ('level', 'short'):
run(*build, '-o', name.upper() + '.BIN', name + '.c', '-lvcccompat')
shutil.copyfile(root / 'docs/manuals/software-storage-and-peripherals/media/BLANK.DSK', work / 'VOL.DSK')
run(runtime / 'bin/writecocofile', 'VOL.DSK', 'DESCENT.BIN')
print(f'{opt}: DESCENT.BIN {(work / "DESCENT.BIN").stat().st_size} bytes', flush=True)
for line in (work / 'DESCENT.map').read_text().splitlines():
if line.startswith('Section: ') and '(fixed.o)' in line:
print(line, flush=True)
capture = args.capture and opt == '-O2'
run('./run', roms, opt, *(['capture'] if capture else []))
if capture:
run('sips', '-s', 'format', 'png', 'descent.ppm', '--out', args.capture.resolve())
# Linking vcccompat for an integer-only report must not charge this object.
(work / 'integer.c').write_text('#include <stdio.h>\nint main(void) {\n'
' char out[4]; return snprintf(out, sizeof(out), "%d", 12);\n}\n')
run(cmoc, '--coco', '-O2', '--intermediate', '-Werror', '-o', 'INTEGER.BIN', 'integer.c', '-lvcccompat')
if '(fixed.o)' in (work / 'INTEGER.map').read_text():
raise AssertionError('Integer-only report linked the floating-point formatter')
if __name__ == '__main__':
main()
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <cmoc.h>
#include <vcc/decimal.h>
struct Vector {
unsigned char packed[5];
unsigned char places;
const char *expected; // NULL marks an out-of-range value.
};
static const struct Vector vectors[] = {
#include "vectors.inc"
};
static unsigned index;
static int check(void)
{
char storage[16];
char *out = storage + 1;
float value;
if (sizeof(value) != 5)
return __LINE__;
for (index = 0; index < sizeof(vectors) / sizeof(vectors[0]); ++index) {
const struct Vector *test = vectors + index;
const char *expected = test->expected;
int wanted = expected ? (int) strlen(expected) : -1;
memcpy(&value, test->packed, sizeof(value));
if (vcc_fixed(NULL, 0, value, test->places) != wanted)
return __LINE__;
// Each short capacity, exact fit and spare capacity. Compare both
// sentinels and all bytes beyond the output (also when capacity is 0).
unsigned capacity;
for (capacity = 0; capacity <= (unsigned)(wanted < 0 ? 3 : wanted + 2); ++capacity) {
memset(storage, '@', sizeof(storage));
if (vcc_fixed(out, capacity, value, test->places) != wanted)
return __LINE__;
unsigned used = 0;
if (capacity) {
unsigned prefix = expected ? (unsigned) wanted : 0u;
if (prefix >= capacity)
prefix = capacity - 1;
if ((prefix && memcmp(out, expected, prefix)) || out[prefix])
return __LINE__;
used = prefix + 1;
}
if (storage[0] != '@')
return __LINE__;
while (used < sizeof(storage) - 1)
if (out[used++] != '@')
return __LINE__;
}
}
if (vcc_fixed(NULL, 1, 1.0f, 3) != -1)
return __LINE__;
return 0;
}
int main(void)
{
int failure = check();
if (failure)
printf("FAIL LINE %d CASE %u\n", failure, index);
else
printf("DECIMAL CHECKS PASSED\n");
return failure != 0;
}
+69
View File
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
static void exercise(const fs::path& roms, Processor cpu, bool disk, bool capture)
{
Session guest(roms, "VOL.DSK", cpu, Profile::fd);
setVolumeProtected(guest, true);
if (disk)
guest.type("LOADM\"DESCENT\":EXEC\r");
else
guest.launch("DESCENT.BIN");
guest.until("RADAR PASS COMPLETE");
const auto screen = guest.machine.copyScreenText();
for (const char *line : {"DESCENT COMPUTER", "HEIGHT 101.75 M", "SPEED -1.88 M/S", "ETA 54.3 S"})
require(screen.find(line) != std::string::npos, "Missing telemetry line in\n" + screen);
if (capture) {
guest.frames(12);
saveActiveFrame(*guest.machine.snapshot().frame, "descent.ppm");
}
guest.verifyReturn();
guest.verifyMedia();
if (disk)
require(guest.reads() > 0, "Expected to load Descent Computer from FD0");
}
int main(int argc, char **argv)
{
try {
require(argc == 3 || argc == 4, "Expected ROM directory, optimization level and optional capture flag");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
{
Session guest(argv[1], "VOL.DSK", cpu, Profile::fd);
guest.launch("QUAL.BIN");
guest.until("DECIMAL CHECKS PASSED");
guest.verifyReturn();
guest.verifyMedia();
if (std::string(argv[2]) == "-O0") {
guest.type("CLS\r");
guest.launch("PLAIN.BIN");
guest.until("DECIMAL CHECKS PASSED");
guest.verifyReturn();
}
guest.type("CLS\r");
guest.launch("SHORT.BIN");
guest.until("RADAR PASS COMPLETE");
guest.until("HEIGHT --- M");
guest.until("SPEED --- M/S");
guest.until("ETA 54.3 S");
guest.verifyReturn();
guest.type("CLS\r");
guest.launch("LEVEL.BIN");
guest.until("RADAR PASS COMPLETE");
guest.until("SPEED 0.00 M/S");
guest.until("ETA NO DESCENT");
guest.verifyReturn();
guest.verifyMedia();
}
exercise(argv[1], cpu, false, argc == 4 && cpu == Processor::MC6809);
exercise(argv[1], cpu, true, false);
std::cout << (cpu == Processor::MC6809 ? "6809" : "6309")
<< ": exact decimal conversions, direct and disk telemetry, BASIC return and unchanged disk\n";
}
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+10
View File
@@ -0,0 +1,10 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include <cmoc.h>
int main(void)
{
volatile float a = 3.5f;
volatile float b = 2.0f;
float result = (a * b) / b + 0.5f;
printf(result == 4.0f ? "MC6839 MATH OK\n" : "MC6839 MATH FAILED\n");
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Compile and run the GIME qualification and joystick exercise against a real CoCo 3 ROM."""
import argparse
import os
from pathlib import Path
import re
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("rom", type=Path, help="privately supplied CoCo 3 BASIC ROM")
parser.add_argument("--capture", type=Path, help="save the lander display to this PNG")
parser.add_argument("--disk-roms", type=Path, help="also test disk EXEC with the local profile ROMs")
args = parser.parse_args()
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
runtime = args.runtime.resolve(strict=True)
env = dict(os.environ, VCC_CMOC_COMPAT="0", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-gime-") as tmp:
work = Path(tmp)
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", args.core.resolve(strict=True), "-o", "run"],
cwd=work, check=True)
for optimization in ("-O0", "-O2"):
for source, output in ((fixture / "qualification.c", "QUAL"),
(root / "examples/cmoc/manual/lander.c", "LANDER")):
subprocess.run([runtime / "bin/cmoc", "--coco", "--intermediate", optimization, "-Werror",
"--org=2800", "-o", output + ".bin", source, "-lgime", "-lbgraph", "-lbcontrol"],
cwd=work, env=env, check=True)
symbols = dict(re.findall(r"^Symbol: _(\w+) \(.+?\) = ([0-9A-F]+)$",
(work / "QUAL.map").read_text(), re.MULTILINE))
print("Checking", optimization, flush=True)
subprocess.run(["./run", args.rom.resolve(strict=True), "QUAL.bin", "LANDER.bin",
*(symbols[name] for name in ("stage", "advanceStage", "finishedFlips"))],
cwd=work, check=True)
if args.disk_roms:
from disk import check_disk_launch
check_disk_launch(runtime, args.core.resolve(strict=True), args.disk_roms.resolve(strict=True),
work, work / "LANDER.bin")
if args.capture:
args.capture.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(["sips", "-s", "format", "png", work / "lander.bmp", "--out", args.capture],
check=True, stdout=subprocess.DEVNULL)
if __name__ == "__main__":
main()
+33
View File
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../basic-disk-session.h"
using namespace BasicDiskTests;
int main(int argc, char** argv) {
try {
if (argc != 3) throw std::runtime_error("Usage: disk ROM_DIRECTORY LANDER.DSK");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
for (auto profile : {Profile::fd, Profile::rgbHD, Profile::sdc}) {
Session session(argv[1], argv[2], cpu, profile);
const auto reads = session.reads(), otherReads = session.otherReads();
session.type("LOADM\"LANDER\":EXEC\r");
session.frames(1000); // Allow disk spin-up, loading and both landscape draws.
const auto preview = session.machine.debuggerGraphicsPreview(true, true, 0, DebugGraphicsMode::HSCREEN2);
require(!preview.text && preview.width == 320 && preview.height == 192 && preview.pixelsPerByte == 2,
"Disk launch did not enter 320 x 192 x 16: " + preview.modeName);
session.type("Q");
session.until("FLIGHT ENDED");
session.verifyReturn();
require(session.reads() > reads && session.otherReads() == otherReads,
"Unexpected route for LOADM");
session.verifyMedia();
const char* device = profile == Profile::fd ? "FD-502" : profile == Profile::sdc ? "SDC" : "RGB-DOS HD";
std::cout << "PASS " << (cpu == Processor::MC6809 ? "MC6809 " : "HD6309 ") << device
<< ": disk EXEC, graphics, Q, return to BASIC and intact media\n";
}
}
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+21
View File
@@ -0,0 +1,21 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build the guest disk and exercise LOADM/EXEC on the three BASIC storage profiles."""
from pathlib import Path
import shutil
import subprocess
def check_disk_launch(runtime, core, roms, work, lander):
fixture = Path(__file__).resolve().parent
destination = Path(work) / "disk-launch"
destination.mkdir()
shutil.copyfile(lander, destination / "LANDER.BIN")
disk = destination / "LANDER.DSK"
disk.write_bytes(b"\xff" * (35 * 18 * 256))
subprocess.run([runtime / "bin/writecocofile", "--binary", disk, "LANDER.BIN"],
cwd=destination, check=True)
(destination / "startup.cfg").write_text("0=LANDER.DSK\n")
runner = destination / "disk"
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", fixture.parents[2] / "src", fixture / "disk.cpp", core, "-o", runner], check=True)
subprocess.run([runner, roms, disk], check=True)
+86
View File
@@ -0,0 +1,86 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Mailbox lets the host inspect the real guest's RAM/scanout at stable points.
#include <cmoc.h>
#include <vcc/gime.h>
unsigned char stage, advanceStage;
static void checkpoint(unsigned char n)
{
stage = n;
asm {
lda :n
@wait cmpa :advanceStage
bne @wait
}
}
// Keep this marker visible in the linker map for the instruction/VSYNC trace.
void finishedFlips(void)
{
checkpoint(4);
}
int main(void)
{
unsigned char i, unexpected, savedBank;
unsigned char *inactiveBank = (unsigned char *)0xffa8;
if (gime_present()) { printf("FAIL IDLE PRESENT\n"); return 1; }
gime_close();
gime_set_palette(1, 5);
gime_clear(7);
// Refuse a screen bank owned by the inactive task, preserving its mapping.
savedBank = *inactiveBank;
*inactiveBank = 0x24;
unexpected = gime_open();
if (unexpected) gime_close();
if ((*inactiveBank & 0x3f) != 0x24) unexpected = 1;
*inactiveBank = savedBank;
if (unexpected) { printf("FAIL RESERVED BANK\n"); return 1; }
asm("orcc", "#$10");
unexpected = gime_open();
asm("andcc", "#$ef");
if (unexpected) { gime_close(); printf("FAIL IRQ OPEN\n"); return 1; }
if (!gime_open()) { printf("GRAPHICS UNAVAILABLE\n"); return 0; }
if (gime_open()) { gime_close(); printf("FAIL SECOND OPEN\n"); return 1; }
gime_set_palette(0, 0);
gime_set_palette(1, 9); // blue
gime_set_palette(2, 36); // red
gime_set_palette(3, 63); // white
gime_clear(1);
// Byte 8191 at (62,51) is adjacent to an 8 KiB bank boundary.
gime_fill_rect(63, 51, 4, 2, 2);
gime_fill_rect(318, 191, 14, 4, 2);
gime_plot(319, 191, 3);
gime_plot(320, 191, 2);
gime_plot(319, 192, 2);
gime_fill_rect(42, 18, 0, 9, 2);
gime_plot(19, 30, 16);
checkpoint(1); // first page remains visible
if (!gime_present()) return 2;
gime_clear(2); // immediately reuse the old front page
checkpoint(2);
if (!gime_present()) return 3;
checkpoint(3);
// Consecutive swaps without drawing must still be frame-paced.
for (i = 0; i < 4; ++i)
if (!gime_present()) return 4;
finishedFlips();
// A missing interrupt must time out and leave both page identities intact.
asm("orcc", "#$10");
unexpected = gime_present();
gime_plot(319, 191, 1);
checkpoint(6);
gime_close(); // Even a stopped timer must allow cleanup.
asm("andcc", "#$ef");
if (unexpected) { printf("FAIL IRQ TIMEOUT\n"); return 1; }
gime_close();
if (gime_present()) { printf("FAIL CLOSED PRESENT\n"); return 1; }
if (!gime_open()) { printf("FAIL REOPEN\n"); return 1; }
gime_close();
checkpoint(5);
printf("GRAPHICS PASSED\n");
return 0;
}
+323
View File
@@ -0,0 +1,323 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/MachineSession.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
using namespace VCC::Mac;
using Bytes = std::vector<std::uint8_t>;
constexpr unsigned pageA = 0x40000, pageB = 0x48000, pageBytes = 160 * 192;
static void require(bool ok, const std::string& message) {
if (!ok) throw std::runtime_error(message);
}
static Bytes fileBytes(const char* path) {
std::ifstream file(path, std::ios::binary);
require(file.good(), std::string("Cannot read ") + path);
return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
}
static void tick(MachineSession& machine, unsigned frames = 1) {
for (unsigned i = 0; i < frames; ++i) {
machine.advance();
machine.takeAudio();
}
}
static std::string screen(MachineSession& machine) {
try { return machine.copyScreenText(); }
catch (const std::exception&) { return {}; } // Bitmap mode has no hardware text.
}
static void waitText(MachineSession& machine, const std::string& expected) {
for (unsigned n = 0; n < 600; ++n) {
if (screen(machine).find(expected) != std::string::npos) return;
tick(machine);
}
throw std::runtime_error("Expected " + expected + " on screen: " + screen(machine));
}
static void type(MachineSession& machine, const std::string& text) {
std::vector<std::uint64_t> keys;
auto key = [](int bit) { return std::uint64_t{1} << bit; };
for (char c : text) {
if (c >= 'A' && c <= 'Z') keys.push_back(key(c - '@'));
else if (c >= '0' && c <= '9') keys.push_back(key(c - '0' + 32));
else if (c == ' ') keys.push_back(key(31));
else if (c == '\r') keys.push_back(key(48));
else if (c == ',') keys.push_back(key(44));
else if (c == '*') keys.push_back(key(55) | key(42));
else throw std::logic_error("Unhandled keyboard character");
}
machine.paste(keys);
while (machine.pasteRemaining()) tick(machine);
tick(machine, 6);
}
static void boot(MachineSession& machine, const Bytes& rom, Processor cpu, unsigned ram) {
MachineConfiguration config;
config.ram = ram;
config.processor = cpu;
machine.configure(config);
machine.load(rom, cpu);
machine.resume();
tick(machine, 180);
waitText(machine, "OK");
}
static void launch(MachineSession& machine, const Bytes& binary) {
require(binary.size() >= 5 && binary[binary.size() - 5] == 0xff, "Missing DECB entry point");
machine.debuggerLoadBinary(binary, (binary[binary.size() - 2] << 8) | binary.back());
machine.debuggerClearDevelopmentBreakpoints();
machine.resume();
}
static void checkBasic(MachineSession& machine) {
type(machine, "PRINT 7*9\r");
waitText(machine, " 63");
}
static Bytes memory(MachineSession& machine, unsigned address, unsigned length, bool physical = false) {
return machine.debuggerMemoryRange(address, length, physical).bytes;
}
static DebugGraphicsPreview video(MachineSession& machine) {
return machine.debuggerGraphicsPreview(true, true, 0, DebugGraphicsMode::HSCREEN1);
}
static void waitStage(MachineSession& machine, unsigned mailbox, unsigned stage) {
for (unsigned n = 0; n < 600; ++n) {
if (memory(machine, mailbox, 1).front() == stage) {
tick(machine, 2); // Observe two completed rasters at the stable checkpoint.
return;
}
tick(machine);
}
throw std::runtime_error("Guest did not reach stage " + std::to_string(stage) + ": " + screen(machine));
}
static void releaseStage(MachineSession& machine, unsigned mailbox, unsigned stage) {
machine.pause();
machine.debuggerWriteMemory(mailbox, {static_cast<std::uint8_t>(stage)});
machine.resume();
}
static void checkMmu(const VCC::MMUState& initial, const VCC::MMUState& current, const char* when) {
for (unsigned i = 0; i < 8; ++i)
if (initial.Task0[i] != current.Task0[i] || initial.Task1[i] != current.Task1[i])
std::cerr << when << " MMU bank " << i << " tasks " << initial.Task0[i] << "/" << initial.Task1[i]
<< " -> " << current.Task0[i] << "/" << current.Task1[i] << '\n';
require(initial.Enabled == current.Enabled && initial.ActiveTask == current.ActiveTask &&
initial.AllRAM == current.AllRAM && initial.Prefix == current.Prefix &&
initial.RamVectors == current.RamVectors && initial.RomMap == current.RomMap &&
initial.Task0 == current.Task0 && initial.Task1 == current.Task1, "MMU mapping changed: tasks " + std::to_string(initial.ActiveTask) + "/" + std::to_string(current.ActiveTask)
+ ", control " + std::to_string(initial.RomMap) + "/" + std::to_string(current.RomMap));
}
// Check actual RGB pixels presented for a complete frame, including untouched neighbors.
static void checkRaster(MachineSession& machine, unsigned address, const Bytes& expected) {
const auto image = video(machine);
require(image.width == 320 && image.height == 192 && image.bytesPerRow == 160 &&
image.address == address && !image.text, "Unexpected active graphics page or format");
require(image.bytes == expected, "Wrong displayed page contents");
const auto frame = machine.snapshot().frame;
const auto area = frame->activeArea;
require(area.width == 640 && area.height == 384, "Wrong active scanout dimensions");
const std::uint32_t colors[] = {0x000000, 0x0000ff, 0xff0000, 0xffffff};
for (unsigned y = 0; y < image.height; ++y) {
for (unsigned x = 0; x < image.width; ++x) {
const auto byte = expected[y * 160 + x / 2];
const auto index = x % 2 ? byte & 0xf : byte >> 4;
const auto offset = (area.y + 2 * y) * Frame::width + area.x + 2 * x;
require(index < 4 && frame->pixels[offset] == colors[index], "Mixed or miscolored active raster at "
+ std::to_string(x) + "," + std::to_string(y) + " actual " + std::to_string(frame->pixels[offset]));
}
}
}
// Four consecutive calls must write alternating page origins outside active scanout,
// each separated by an actual active field. The trace timestamps are guest video events.
static void checkTrace(MachineSession& machine) {
const auto summary = machine.debuggerTrace();
require(summary.status.find("Stop address") != std::string::npos, "Missing swap trace end");
unsigned line = 0, field = 0, lastField = 0, count = 0, address = pageA;
for (const auto& event : machine.debuggerTraceForExport(0, summary.total).records) {
if (event.event == VCC::TraceEvent::ScreenHSYNCLow) {
line = event.line;
if (line == 128) ++field;
} else if (event.event == VCC::TraceEvent::ScreenReg && event.detail.rfind("VOFF: ", 0) == 0) {
const unsigned next = std::stoul(event.detail.substr(6), nullptr, 16);
require(line < 43 || line >= 235, "Video origin changed during active scanout");
if (next != address) {
require(next == (address == pageA ? pageB : pageA), "Unexpected video origin");
require(!count || field > lastField, "Two swaps in a single blanking interval");
address = next;
lastField = field;
++count;
}
}
}
require(count == 4, "Expected four independently synchronized flips, saw " + std::to_string(count));
}
static void qualify(const Bytes& rom, const Bytes& binary, Processor cpu, unsigned ram, unsigned stage,
unsigned ack, unsigned finished) {
MachineSession machine;
boot(machine, rom, cpu, ram);
const unsigned width = ram == 2 ? 40 : ram == 3 ? 80 : 32;
if (width != 32) type(machine, "WIDTH " + std::to_string(width) + "\r");
type(machine, "PALETTE 1,38\r");
const auto text = video(machine);
const auto mmu = machine.debuggerSnapshot().mmu;
const auto palette = memory(machine, 0xffb0, 16);
const auto display = memory(machine, 0xff98, 8);
require(palette[1] == 38, "Could not install BASIC's custom palette");
require(text.text && text.bytesPerRow / text.bytesPerCell == width, "Unexpected BASIC width before Run");
const Bytes mirrored = ram == 0 ? memory(machine, 0, 65536, true) : Bytes{};
launch(machine, binary);
if (ram == 0) {
waitText(machine, "GRAPHICS UNAVAILABLE\nOK");
require(memory(machine, 0, 65536, true) == mirrored, "Graphics probe corrupted mirrored RAM");
} else {
waitStage(machine, stage, 1);
checkMmu(mmu, machine.debuggerSnapshot().mmu, "open");
Bytes drawn(pageBytes, 0x11);
for (unsigned y : {51, 52}) {
drawn[y * 160 + 31] = 0x12;
drawn[y * 160 + 32] = 0x22;
drawn[y * 160 + 33] = 0x21;
}
drawn.back() = 0x23;
require(memory(machine, pageB, pageBytes, true) == drawn, "Incorrect hidden page after drawing");
checkRaster(machine, pageA, Bytes(pageBytes, 0));
releaseStage(machine, ack, 1);
waitStage(machine, stage, 2);
checkRaster(machine, pageB, drawn);
require(memory(machine, pageA, pageBytes, true) == Bytes(pageBytes, 0x22), "Old front could not be reused");
releaseStage(machine, ack, 2);
waitStage(machine, stage, 3);
checkRaster(machine, pageA, Bytes(pageBytes, 0x22));
releaseStage(machine, ack, 3);
machine.debuggerStartTrace(100000, {}, {static_cast<std::uint16_t>(finished)}, true, false);
waitStage(machine, stage, 4);
checkTrace(machine);
checkRaster(machine, pageA, Bytes(pageBytes, 0x22));
releaseStage(machine, ack, 4);
waitStage(machine, stage, 6);
checkRaster(machine, pageA, Bytes(pageBytes, 0x22));
drawn.back() = 0x21; // Still wrote to the hidden page after a failed present.
require(memory(machine, pageB, pageBytes, true) == drawn, "Failed swap changed the draw destination");
releaseStage(machine, ack, 6);
waitStage(machine, stage, 5);
checkMmu(mmu, machine.debuggerSnapshot().mmu, "closed");
releaseStage(machine, ack, 5);
waitText(machine, "GRAPHICS PASSED\nOK");
}
require(memory(machine, 0xffb0, 16) == palette, "Custom BASIC palette was not restored");
require(memory(machine, 0xff98, 8) == display, "BASIC video registers were not restored");
const auto restored = video(machine);
require(restored.text && restored.address == text.address &&
restored.bytesPerRow == text.bytesPerRow && restored.width == text.width, "BASIC text layout changed");
checkBasic(machine);
std::cout << " " << mmu.RAMBytes / 1024 << " KiB, WIDTH " << width << ": "
<< (ram == 0 ? "safe refusal" : "page contents, raster, timing")
<< ", restored BASIC keyboard, palette and mapping\n";
}
// OS/2 24-bit BMP of the emulator's published active area, for the optional manual capture.
static void saveFrame(const Frame& frame) {
const auto area = frame.activeArea;
const unsigned stride = (3 * area.width + 3u) & ~3u;
std::ofstream out("lander.bmp", std::ios::binary);
auto le = [&](unsigned value, unsigned bytes) {
for (unsigned n = 0; n < bytes; ++n) out.put(static_cast<char>(value >> (8 * n)));
};
out.write("BM", 2);
le(26 + stride * area.height, 4); le(0, 4); le(26, 4); le(12, 4);
le(area.width, 2); le(area.height, 2); le(1, 2); le(24, 2);
for (int y = area.height - 1; y >= 0; --y) {
for (int x = 0; x < area.width; ++x)
le(frame.pixels[(area.y + y) * Frame::width + area.x + x], 3);
for (unsigned n = 3 * area.width; n < stride; ++n) out.put(0);
}
require(out.good(), "Unable to capture guest frame");
}
static int craftLeft(MachineSession& machine) {
if (!(memory(machine, 0xff98, 1)[0] & 0x80)) return -1;
const auto image = video(machine);
if (image.width != 320 || image.height != 192) return -1;
const auto start = image.pixels.begin() + 89 * image.width;
const auto x = std::find(start, start + image.width, 0xffffff);
return x == start + image.width ? -1 : int(x - start) - 2;
}
static void fly(const Bytes& rom, const Bytes& binary, Processor cpu) {
MachineSession machine;
boot(machine, rom, cpu, 1);
machine.setJoystick(0, 8191, 8191, 0, 0);
launch(machine, binary);
for (unsigned n = 0; n < 600 && craftLeft(machine) != 144; ++n) tick(machine);
require(craftLeft(machine) == 144, "Lander did not appear at its documented position");
machine.setJoystick(0, 16383, 8191, 0, 0);
int x = 144;
unsigned firstMeasuredField = 0, measuredSteps = 0, elapsedFields = 0;
for (unsigned n = 0; n < 360 && x < 226; ++n) {
tick(machine);
const int next = craftLeft(machine);
// Skip the two one-time landscape draws when measuring steady flight.
if (next > x && x >= 152) {
if (firstMeasuredField) {
++measuredSteps;
elapsedFields = n - firstMeasuredField;
} else {
firstMeasuredField = n;
}
}
x = next;
}
require(x >= 226 && x <= 246, "Right joystick did not steer across the display");
machine.setJoystick(0, 8191, 8191, 0, 0);
tick(machine, 12);
const auto frame = machine.snapshot().frame;
const auto area = frame->activeArea;
const auto row = frame->pixels.begin() + (area.y + 2 * 89) * Frame::width + area.x;
require(row[2 * (144 + 8)] == 0 && row[2 * (craftLeft(machine) + 8)] == 0xffffff,
"Craft was absent or left a trail on the visible raster");
const auto landscape = video(machine);
require((landscape.bytes[168 * 160 + 315 / 2] & 0xf) == 6, "Right edge of the ridge is missing");
if (cpu == Processor::MC6809) {
saveFrame(*frame);
machine.setJoystick(0, 8191, 16383, 0, 0);
waitText(machine, "ON THE PAD!\nOK");
} else {
machine.setKeyboard(std::uint64_t{1} << 17); // Q on the real CoCo keyboard matrix
tick(machine, 3);
machine.setKeyboard(0);
waitText(machine, "FLIGHT ENDED\nOK");
}
checkBasic(machine);
std::cout << " Lander: " << measuredSteps << " moves in " << elapsedFields
<< " steady-flight fields; old location erased; returned to BASIC\n";
}
int main(int argc, char** argv) {
try {
require(argc == 7, "Usage: run ROM QUAL.BIN LANDER.BIN STAGE ACK TRACE_STOP");
const auto rom = fileBytes(argv[1]), probe = fileBytes(argv[2]), lander = fileBytes(argv[3]);
const auto stage = std::stoul(argv[4], nullptr, 16), ack = std::stoul(argv[5], nullptr, 16);
const auto end = std::stoul(argv[6], nullptr, 16);
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
std::cout << (cpu == Processor::MC6809 ? "6809" : "6309") << std::endl;
for (unsigned ram = 0; ram < 4; ++ram) qualify(rom, probe, cpu, ram, stage, ack, end);
fly(rom, lander, cpu);
}
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+55
View File
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "basic-disk-session.h"
namespace BasicDiskTests {
inline Bytes volume(const Session& guest)
{
if (guest.sdc) return readFile(guest.diskPath);
if (guest.profile == Profile::rgbHD) {
require(guest.floppy->image(0)->bytes() == guest.original, "HD operation changed FD0");
const auto& bytes = guest.hard->image(0)->bytes();
return {bytes.begin() + rgbStart, bytes.begin() + rgbStart + guest.original.size()};
}
return guest.floppy->image(0)->bytes();
}
inline void saveVolume(const Session& guest, const fs::path& path)
{
const auto bytes = volume(guest);
std::ofstream out(path, std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
require(out.good(), "Could not save " + path.string());
}
inline void setVolumeProtected(Session& guest, bool protect)
{
if (guest.sdc) guest.sdc->setWriteProtected(protect);
else if (guest.profile == Profile::rgbHD) guest.hard->image(0)->protect(protect);
else guest.floppy->setWriteProtected(0, protect);
}
inline void saveDisk(const DiskImage& disk, const fs::path& path)
{
const auto& bytes = disk.bytes();
std::ofstream out(path, std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
require(out.good(), "Could not save guest disk");
}
inline void saveActiveFrame(const Frame& frame, const fs::path& path)
{
const auto area = frame.activeArea;
std::ofstream out(path, std::ios::binary);
out << "P6\n" << area.width << ' ' << area.height << "\n255\n";
for (int y = 0; y < area.height; ++y)
for (int x = 0; x < area.width; ++x) {
auto rgb = frame.pixels[(area.y + y) * Frame::width + area.x + x];
out.put(char(rgb >> 16)); out.put(char(rgb >> 8)); out.put(char(rgb));
}
require(out.good(), "Could not save guest display");
}
} // namespace BasicDiskTests
+34
View File
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run bounded-allocation checks and the manual's crew example on both guest CPUs."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged toolchain with vcccompat and wydealloc")
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("rom", type=Path, help="privately supplied CoCo 3 ROM")
args = parser.parse_args()
runtime = args.runtime.resolve(strict=True)
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-heap-") as work:
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", args.core.resolve(strict=True), "-o", "run"],
cwd=work, check=True)
for optimization in ("-O0", "-O2"):
for source, name in ((fixture / "qualification.c", "QUAL.BIN"),
(root / "examples/cmoc/manual/crew.c", "CREW.BIN")):
subprocess.run([runtime / "bin/cmoc", "--coco", optimization, "-Werror", "--org=2800",
"-o", name, source, "-lvcccompat", "-lwydealloc"], env=env, cwd=work, check=True)
print("Checking", optimization, flush=True)
subprocess.run(["./run", args.rom.resolve(strict=True), "QUAL.BIN", "CREW.BIN"], cwd=work, check=True)
if __name__ == "__main__":
main()
+123
View File
@@ -0,0 +1,123 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <stdlib.h>
#include <coco.h>
#define CHECK(test) do { if (!(test)) return __LINE__; } while (0)
#define BUDGET 240
// Keep guard bytes immediately before and after the exact array given to the heap.
static byte guarded[BUDGET + 2];
static byte alternate[48];
// Materialize logical negation as an int result. This also checks the
// optimized CMOC call sequence, which differs from a branch on success.
static int initializationFailed(byte *storage, unsigned capacity)
{
return !vcc_heap_init(storage, capacity);
}
static int qualifies(void)
{
byte stackGuard[15];
byte *pool = guarded + 1, *p, *q, *other, *left, *middle, *right, *end;
unsigned i;
memset(guarded, 0xB9, sizeof(guarded));
memset(alternate, 0xCD, sizeof(alternate));
for (i = 0; i < sizeof(stackGuard); ++i)
stackGuard[i] = (byte)(i + 97);
// No hidden default heap, and a range wrapping through zero is not usable.
free(NULL);
CHECK(!malloc(1) && !calloc(1, 2) && !realloc(NULL, 3));
CHECK(!vcc_heap_init(NULL, BUDGET) && !vcc_heap_init(pool, 15));
CHECK(!vcc_heap_init((void *)0xFFF0, 32));
CHECK(initializationFailed(alternate, 15) == 1);
CHECK(initializationFailed(alternate, 16) == 0);
p = (byte *)malloc(1);
CHECK(p && p >= alternate && p < alternate + 16);
free(p);
CHECK(vcc_heap_init(pool, BUDGET));
CHECK(!malloc(0) && !calloc(0, 3) && !calloc(3, 0));
CHECK(!calloc(256, 256) && !calloc(32769U, 2) && !malloc(65535U));
p = (byte *)calloc(4, 9);
CHECK(p && p >= pool && p + 36 <= pool + BUDGET);
for (i = 0; i < 36; ++i) {
CHECK(p[i] == 0);
p[i] = (byte)(33 + i);
}
// A rejected reinitialization leaves both the old block and new region alone.
memset(alternate, 0xCD, sizeof(alternate));
CHECK(!vcc_heap_init(alternate, sizeof(alternate)));
CHECK(!vcc_heap_init(pool, BUDGET));
for (i = 0; i < sizeof(alternate); ++i) CHECK(alternate[i] == 0xCD);
other = (byte *)realloc(NULL, 24);
CHECK(other);
memset(other, 0x3A, 24);
CHECK(!realloc(p, 65535U));
q = (byte *)realloc(p, 68);
CHECK(q);
for (i = 0; i < 36; ++i) CHECK(q[i] == (byte)(33 + i));
for (i = 0; i < 24; ++i) CHECK(other[i] == 0x3A);
CHECK(!realloc(q, BUDGET)); // Exhaustion even though the integer size fits.
for (i = 0; i < 36; ++i) CHECK(q[i] == (byte)(33 + i));
p = (byte *)realloc(q, 11);
CHECK(p);
for (i = 0; i < 11; ++i) CHECK(p[i] == (byte)(33 + i));
CHECK(realloc(other, 0) == NULL);
free(p);
// Four live objects divide the pool. The two separate holes cannot hold
// 64 bytes until the middle object is freed and the three holes coalesce.
left = (byte *)malloc(40);
middle = (byte *)malloc(40);
right = (byte *)malloc(40);
end = (byte *)malloc(40);
CHECK(left && middle && right && end);
memset(end, 0x37, 40);
free(left);
free(right);
CHECK(!malloc(64));
free(middle);
p = (byte *)malloc(90);
CHECK(p);
memset(p, 0xAA, 90);
for (i = 0; i < 40; ++i) CHECK(end[i] == 0x37);
free(end);
free(p);
// After several fill/release cycles the pool must regain its original room.
for (i = 0; i < 50; ++i) {
p = (byte *)malloc(200);
CHECK(p && p >= pool && p + 200 <= pool + BUDGET);
memset(p, 0x35, 200);
free(p);
}
p = (byte *)calloc(100, 2);
CHECK(p);
for (i = 0; i < 200; ++i) CHECK(!p[i]);
free(p);
CHECK(!vcc_heap_init(NULL, BUDGET));
p = (byte *)malloc(200);
CHECK(p && p >= pool && p + 200 <= pool + BUDGET);
free(p);
CHECK(vcc_heap_init(alternate, sizeof(alternate)));
p = (byte *)malloc(16);
CHECK(p && p >= alternate && p + 16 <= alternate + sizeof(alternate));
free(p);
CHECK(guarded[0] == 0xB9 && guarded[BUDGET + 1] == 0xB9);
for (i = 0; i < sizeof(stackGuard); ++i) CHECK(stackGuard[i] == (byte)(i + 97));
return 0;
}
int main(void)
{
int line;
cls(1);
line = qualifies();
if (line) printf("FAIL LINE %d\n", line);
else printf("BOUNDED HEAP PASSED\n");
return line != 0;
}
+63
View File
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Exercise the same Direct Run entry point used by the C development workspace.
#include "core/MachineSession.h"
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
using namespace VCC::Mac;
using Bytes = std::vector<std::uint8_t>;
static Bytes readFile(const char* path) {
std::ifstream input(path, std::ios::binary);
if (!input) throw std::runtime_error(std::string("Cannot open ") + path);
return {std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
}
static void waitFor(MachineSession& machine, const std::string& expected) {
for (unsigned frame = 0; frame < 900; ++frame) {
const auto text = machine.copyScreenText();
if (text.find("FAIL LINE") != std::string::npos) break;
if (text.find(expected) != std::string::npos) return;
machine.advance();
}
throw std::runtime_error("Expected " + expected + " on screen:\n" + machine.copyScreenText());
}
static void run(const Bytes& rom, const Bytes& binary, Processor cpu, const std::string& expected) {
MachineSession machine;
machine.load(rom, cpu);
machine.resume();
for (unsigned frame = 0; frame < 180; ++frame) machine.advance();
waitFor(machine, "OK");
if (binary.size() < 5 || binary[binary.size() - 5] != 0xFF)
throw std::runtime_error("Expected a DECB executable with an entry point");
const auto n = binary.size();
machine.debuggerLoadBinary(binary, std::uint16_t((binary[n - 2] << 8) | binary[n - 1]));
machine.debuggerClearDevelopmentBreakpoints();
machine.resume();
waitFor(machine, expected);
// PRINT 7*9, followed by Enter, through the guest keyboard matrix. The
// calculation confirms the interpreter accepted input after main returned.
auto key = [](int bit) { return std::uint64_t(1) << bit; };
machine.paste({key(16), key(18), key(9), key(14), key(20), key(31),
key(39), key(55) | key(42), key(41), key(48)});
waitFor(machine, " 63");
}
int main(int argc, char** argv) {
try {
if (argc != 4) throw std::runtime_error("Usage: run COCO3_ROM QUAL_BIN CREW_BIN");
const auto rom = readFile(argv[1]), qual = readFile(argv[2]), crew = readFile(argv[3]);
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
run(rom, qual, cpu, "BOUNDED HEAP PASSED\nOK");
run(rom, crew, cpu, "CREW AT LAUNCH: 0\nCREW AFTER GROWTH: 3\nNO ROOM FOR 200\nCREW STILL ABOARD: 3\nCREW LOG CLOSED\nOK");
std::cout << "PASS " << (cpu == Processor::MC6809 ? "MC6809" : "HD6309")
<< ": heap boundaries, manual exercise and BASIC return\n";
}
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+7
View File
@@ -0,0 +1,7 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include <cmoc.h>
int main(void)
{
printf("HELLO FROM CMOC\n");
return 0;
}
@@ -0,0 +1,31 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Check the actual CMOC indexed-load peephole rule in a source build."""
import argparse
import subprocess
import tempfile
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source_build", type=Path, help="build.py output's work/cmoc directory")
args = parser.parse_args()
src = args.source_build.resolve(strict=True) / "src"
objects = sorted(path for path in src.glob("cmoc-*.o") if path.name != "cmoc-main.o")
if not objects:
parser.error("Build CMOC first; compiler objects are required")
fixture = Path(__file__).resolve().parent / "optimizer-rule.cpp"
with tempfile.TemporaryDirectory(prefix="vcc-cmoc-rule-") as work:
out = Path(work)
# Retain all normal compiler definitions and rename only its CLI entry
# in this extra object. The rule itself comes from unchanged build objects.
subprocess.run(["xcrun", "clang++", "-std=c++11", "-Dmain=vccCompilerDriverMain",
'-DPACKAGE="cmoc"', '-DVERSION="0.1.100"', '-DPKGDATADIR="."',
"-D__unix", "-I", src, "-c", src / "main.cpp", "-o", out / "driver.o"], check=True)
subprocess.run(["xcrun", "clang++", "-std=c++11", "-I", src, fixture,
out / "driver.o", *objects, "-o", out / "rule-check"], check=True)
subprocess.run([out / "rule-check"], check=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,42 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Execute indexed-argument-load regressions on both emulated guest CPUs."""
import argparse
import os
import subprocess
import tempfile
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged CMOC toolchain")
parser.add_argument("core", type=Path, help="libVCCCore.a")
parser.add_argument("rom", type=Path, help="locally supplied CoCo 3 ROM")
parser.add_argument("--host-arch", choices=("arm64", "x86_64"),
help="select a macOS compiler slice (x86_64 uses Rosetta on Apple Silicon)")
args = parser.parse_args()
fixture = Path(__file__).resolve().parent
runtime = args.runtime.resolve(strict=True)
compiler = runtime / "bin/cmoc"
command = (["/usr/bin/arch", "-" + args.host_arch] if args.host_arch else []) + [compiler]
env = dict(os.environ, PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
# Same adjacent-element call at runtime indices 0 and 2, using a byte
# parameter, word parameter and pointer bases. Expectations are host-owned.
pair = (4, 12, 8, 16, 20, 28, 24, 32)
expected = "ARGS " + "".join(f"{value:02X}" for value in pair * 3) + " END"
with tempfile.TemporaryDirectory(prefix="vcc-indexed-arguments-") as work:
runner = Path(work) / "run-compiled"
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
fixture.parent / "run-compiled.cpp", args.core.resolve(strict=True), "-o", runner],
check=True)
for optimization in ("-O0", "-O2"):
print("Checking indexed arguments", optimization, flush=True)
subprocess.run(command + ["--coco", optimization, "--no-relocate", "--switch=jump", "--org=2800",
"--intermediate", "-Werror", "-o", "TEST.BIN", fixture / "qualification.c"],
cwd=work, env=env, check=True)
subprocess.run([runner, args.rom.resolve(strict=True), "TEST.BIN", expected],
cwd=work, check=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Exercise the actual built compiler rule; expose its private entry only in
// this test translation unit. Vendor sources and normal objects stay unchanged.
#include "util.h"
#include <utility>
#include <functional>
#define private public
#include "ASMText.h"
#undef private
#include <iostream>
#include <stdexcept>
void check(const char* first, const char* middleOp, const char* middle, const char* last, bool expectRemoval) {
ASMText text(true);
text.ins("LDB", first); text.ins(middleOp, middle); text.ins("LDB", last);
const bool removed = text.removeUselessLdaOrLdb(0);
if (removed != expectRemoval) throw std::runtime_error(std::string(first) + "; " + middleOp + " " + middle + "; LDB " + last);
}
int main() {
try {
check("5,U", "LDX", "#array", "D,X", false);
check("5,U", "LDX", "#array", "B,X", false);
check("5,U", "LDX", "#array", "[D,X]", false);
check("5,U", "LDX", "#array", "[B,X]", false);
check("5,U", "LDX", "D,Y", ",X", false);
check("5,U", "LDX", "B,Y", ",X", false);
check("5,U", "LDX", "[D,Y]", ",X", false);
check("5,U", "LEAX", "D,Y", ",X", false);
check("5,U", "LEAX", "B,Y", ",X", false);
check(",S+", "LDX", "#array", ",X", false);
check(",--X", "LDX", "#array", ",X", false);
check("[,Y++]", "LDX", "#array", ",X", false);
check("[,--U]", "LDX", "#array", ",X", false);
check("5,U", "LDX", "#array", ",X", true);
check("5,U", "LEAX", "4,Y", "4,X", true);
std::cout << "PASS indexed-load rule: 13 dependency/side-effect guards, 2 safe removals\n";
return 0;
} catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; }
}
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <cmoc.h>
// Distinct in-range sentinels make a stale loaded value used as a second
// subscript visibly wrong, without depending on neighboring globals' layout.
static unsigned char joystick_axes[64];
static struct { unsigned char centers[64]; } preferences;
static unsigned char chosen;
static void capture(unsigned char x, unsigned char y, unsigned char cx, unsigned char cy)
{
// Print actual bytes; the host owns all comparisons and expected results.
printf("%02x%02x%02x%02x", (unsigned)x, (unsigned)y, (unsigned)cx, (unsigned)cy);
}
static void sampleByte(unsigned char index)
{
capture(joystick_axes[index], joystick_axes[index + 1],
preferences.centers[index], preferences.centers[index + 1]);
}
static void sampleWord(unsigned index)
{
capture(joystick_axes[index], joystick_axes[index + 1],
preferences.centers[index], preferences.centers[index + 1]);
}
static void samplePointer(unsigned char index, const unsigned char *axes, const unsigned char *centers)
{
capture(axes[index], axes[index + 1], centers[index], centers[index + 1]);
}
int main(void)
{
unsigned i;
for (i = 0; i < sizeof(joystick_axes); ++i)
{
joystick_axes[i] = 0x35;
preferences.centers[i] = 0x3a;
}
joystick_axes[0] = 4; joystick_axes[1] = 12;
joystick_axes[2] = 20; joystick_axes[3] = 28;
preferences.centers[0] = 8; preferences.centers[1] = 16;
preferences.centers[2] = 24; preferences.centers[3] = 32;
printf("ARGS ");
// Runtime parameters preserve the original indexed argument expressions.
chosen = 0; sampleByte(chosen);
chosen = 2; sampleByte(chosen);
chosen = 0; sampleWord(chosen);
chosen = 2; sampleWord(chosen);
chosen = 0; samplePointer(chosen, joystick_axes, preferences.centers);
chosen = 2; samplePointer(chosen, joystick_axes, preferences.centers);
printf(" END\n");
return 0;
}
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Execute CMOC byte-subtraction regression cases on both emulated CPUs."""
import argparse
import subprocess
import tempfile
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged CMOC toolchain")
parser.add_argument("core", type=Path, help="libVCCCore.a")
parser.add_argument("rom", type=Path, help="locally supplied CoCo 3 ROM")
args = parser.parse_args()
fixture = Path(__file__).resolve().parent
compiler = args.runtime.resolve(strict=True) / "bin/cmoc"
with tempfile.TemporaryDirectory(prefix="vcc-indexed-subtraction-") as work:
runner = Path(work) / "run-compiled"
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
fixture.parent / "run-compiled.cpp", args.core.resolve(strict=True), "-o", runner],
check=True)
for optimization in ("-O0", "-O2"):
print("Checking indexed subtraction", optimization, flush=True)
subprocess.run([compiler, "--coco", "--org=2800", optimization, "-Werror", "-o", "TEST.BIN",
fixture / "qualification.c"], cwd=work, check=True)
# Terrain, equal/unequal pairs, pointer indexing, byte index, reversed subtraction and two reads.
expected = [172, 150, 128, 106, 0, 1, 169, 240, 0, 128, 0, 234, 66, 190]
marker = "HX " + "".join(f"{value:02X}" for value in expected)
subprocess.run([runner, args.rom.resolve(strict=True), "TEST.BIN", marker],
cwd=work, check=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <cmoc.h>
static const unsigned char heights[] = { 12, 34, 56, 78 };
static unsigned char samples[258];
static unsigned char terrain(unsigned i)
{
return 184 - heights[i];
}
static unsigned char fromPointer(const unsigned char *array, unsigned i, unsigned char base)
{
return base - array[i];
}
static unsigned char differs(unsigned char actual, unsigned i)
{
return actual != heights[i];
}
static unsigned char byteIndex(unsigned char i)
{
return 184 - heights[i];
}
static unsigned char reversed(unsigned i)
{
return heights[i] - 34;
}
static unsigned char twoReads(unsigned left, unsigned right)
{
return heights[left] - heights[right];
}
// Print result bytes so that the host can check them independently of any
// equality or subtraction code emitted by the compiler under test.
static void emit(unsigned char value)
{
printf("%02x", (unsigned)value);
}
int main(void)
{
unsigned i;
printf("HX ");
for (i = 0; i < sizeof(heights); ++i)
emit(terrain(i));
// The comparison must see the same index regardless of the other operand.
emit(differs(34, 1));
emit(differs(12, 1));
// These indices have equal low bytes. Subtracting 200 from 184 must
// wrap to 240 when the result is converted to unsigned char.
samples[1] = 15;
samples[257] = 200;
emit(fromPointer(samples, 1, 184));
emit(fromPointer(samples, 257, 184));
emit(fromPointer(samples, 257, 200));
emit(byteIndex(2));
emit(reversed(1));
emit(reversed(0));
emit(twoReads(3, 0));
emit(twoReads(0, 3));
printf("\n");
return 0;
}
+42
View File
@@ -0,0 +1,42 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Fly the published joystick exercise on both CPUs using the actual guest screen."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged ToolchainBundle")
parser.add_argument("core", type=Path, help="libVCCCore.a")
parser.add_argument("roms", type=Path, help="folder with CoCo 3 and Disk BASIC ROMs")
parser.add_argument("--capture", type=Path, help="optional PNG of the charged probe in flight")
args = parser.parse_args()
runtime, core, roms = [x.resolve(strict=True) for x in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="0", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-survey-probe-") as folder:
work = Path(folder)
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run"], cwd=work, check=True)
for optimization in ("-O0", "-O2"):
subprocess.run([runtime / "bin/cmoc", "--coco", "--org=2800", optimization, "-Werror",
"-o", "PROBE.BIN", root / "examples/cmoc/manual/probe.c",
"-lgime", "-linput", "-lbcontrol"], cwd=work, env=env, check=True)
(work / "PROBE.DSK").write_bytes(b"\xff" * (35 * 18 * 256))
subprocess.run([runtime / "bin/writecocofile", "PROBE.DSK", "PROBE.BIN"], cwd=work, check=True)
argv = ["./run", roms, "PROBE.DSK", "PROBE.BIN"]
if args.capture and optimization == "-O2":
argv.append("survey.ppm")
print("Checking", optimization, flush=True)
subprocess.run(argv, cwd=work, check=True)
if args.capture:
subprocess.run(["sips", "-s", "format", "png", "survey.ppm", "--out", args.capture.resolve()],
cwd=work, check=True, stdout=subprocess.DEVNULL)
if __name__ == "__main__":
main()
+111
View File
@@ -0,0 +1,111 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../basic-disk-session.h"
using namespace BasicDiskTests;
// Read the completed scanout, including the GIME palette and active-image placement.
static std::uint32_t pixel(const Frame& frame, unsigned x, unsigned y)
{
const auto area = frame.activeArea;
return frame.pixels[(area.y + y * area.height / 192) * Frame::width + area.x + x * area.width / 320];
}
template<class Predicate>
static void waitFor(Session& session, Predicate ready, const char* failure)
{
for (unsigned n = 0; n < 900; ++n) {
session.frames(1);
const auto frame = session.machine.snapshot().frame;
if (frame && ready(*frame)) return;
}
throw std::runtime_error(failure);
}
static void capture(const Frame& frame, const fs::path& filename)
{
const auto area = frame.activeArea;
std::ofstream out(filename, std::ios::binary);
out << "P6\n" << area.width << " " << area.height << "\n255\n";
for (int y = 0; y < area.height; ++y)
for (int x = 0; x < area.width; ++x) {
auto rgb = frame.pixels[(area.y + y) * Frame::width + area.x + x];
out.put(char(rgb >> 16)); out.put(char(rgb >> 8)); out.put(char(rgb));
}
require(out.good(), "Failed to write scanout");
}
static void fly(const fs::path& roms, const fs::path& disk, const fs::path& binary,
Processor cpu, bool fromDisk, const fs::path& screenshot)
{
Session session(roms, disk, cpu, Profile::fd);
constexpr auto center = 8191;
auto joystick = [&](unsigned x, unsigned button) {
session.machine.setJoystick(0, x, center, button, 0);
};
if (!fromDisk) {
session.launch(binary); // The workspace's ordinary development Run.
} else {
session.type("LOADM\"PROBE\":EXEC\r");
}
joystick(center, 0);
auto shipAt = [](const Frame& f, unsigned x) {
return pixel(f, x, 57) == 0xffffff && pixel(f, x + 19, 57) == 0xffffff;
};
waitFor(session, [&](const Frame& f) { return shipAt(f, 144); }, "Lander never appeared");
joystick(16383, 0);
waitFor(session, [&](const Frame& f) { return shipAt(f, 214); }, "Steering did not approach the deposit");
joystick(center, 0);
session.frames(16);
const auto initial = session.machine.snapshot().frame;
const auto gold = pixel(*initial, 218, 152);
const auto cyan = pixel(*initial, 219, 158); // Support beneath the deposit.
const auto sky = pixel(*initial, 212, 130);
require(pixel(*initial, 2, 172) != sky && pixel(*initial, 192, 162) == pixel(*initial, 2, 172) &&
pixel(*initial, 2, 162) == sky, "Terrain profile lost its changing heights");
require(gold != cyan && cyan != sky && gold != sky, "Invalid survey palette or missing deposit");
unsigned launchX = 0;
for (unsigned x = 200; x < 240; ++x) {
if (pixel(*initial, x, 57) == 0xffffff) { launchX = x + 9; break; }
}
require(launchX >= 216 && launchX < 242, "Lander did not stop above the deposit");
joystick(center, 1);
waitFor(session, [&](const Frame& f) { return pixel(f, launchX, 67) == cyan; },
"A press did not launch the short probe");
waitFor(session, [&](const Frame& f) { return pixel(f, 56, 10) == gold; }, "Holding did not fill the gauge");
// Give the first probe enough time to disappear; a repeating press would
// leave a probe in the sky, hit the deposit, or increase the final count.
session.frames(60);
const auto charged = session.machine.snapshot().frame;
require(pixel(*charged, 218, 152) == gold, "First probe reached the distant deposit");
for (unsigned y = 66; y < 150; ++y)
require(pixel(*charged, launchX, y) == sky, "Holding the button relaunched a probe");
joystick(center, 0);
waitFor(session, [&](const Frame& f) { return pixel(f, 56, 10) == cyan; }, "Release did not lock the charge");
joystick(center, 1);
waitFor(session, [&](const Frame& f) { return pixel(f, launchX, 104) == cyan; },
"Second launch did not travel beyond the first probe's range");
if (!screenshot.empty()) capture(*session.machine.snapshot().frame, screenshot);
waitFor(session, [&](const Frame& f) { return pixel(f, 218, 152) == cyan; }, "Charged probe missed the deposit");
joystick(center, 0);
session.frames(12);
session.type("Q");
session.until("PROBES LAUNCHED: 2\nDEPOSIT SURVEYED");
session.verifyReturn();
session.verifyMedia();
}
int main(int argc, char** argv)
{
try {
require(argc == 4 || argc == 5, "Usage: run ROM_DIR DISK BIN [CAPTURE.ppm]");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
const bool captureDirectRun = argc == 5 && cpu == Processor::MC6809;
fly(argv[1], argv[2], argv[3], cpu, false, captureDirectRun ? argv[4] : "");
fly(argv[1], argv[2], argv[3], cpu, true, "");
}
std::cout << "PASS MC6809 and HD6309 direct Run and disk EXEC: steering, two presses, charge, release, deposit and BASIC return\n";
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+37
View File
@@ -0,0 +1,37 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run the guest input and audio qualification on both CoCo 3 processors."""
import argparse
import os
from pathlib import Path
import re
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged CMOC toolchain")
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("roms", type=Path, help="local CoCo 3 and Speech/Sound ROM directory")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
env = dict(os.environ, PATH=str(runtime / "bin") + ":/usr/bin:/bin", VCC_CMOC_COMPAT="0")
with tempfile.TemporaryDirectory(prefix="vcc-input-") as folder:
work = Path(folder)
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", fixture.parents[2] / "src", fixture / "run.cpp", core, "-o", work / "run"],
check=True)
for optimization in ("-O0", "-O2"):
subprocess.run([runtime / "bin/cmoc", "--coco", "--intermediate", "--org=2800", optimization,
"-Werror", "-o", "QUAL.bin", fixture / "qualification.c", "-linput", "-lbcontrol",
"-lssc", "-lorch90"], env=env, cwd=work, check=True)
symbols = dict(re.findall(r"^Symbol: _(\w+) \(.+?\) = ([0-9A-F]+)$",
(work / "QUAL.map").read_text(), re.MULTILINE))
print("Checking compiled input caller", optimization, flush=True)
subprocess.run([work / "run", roms, work / "QUAL.bin", *(symbols[n] for n in ("stage", "ack", "report"))],
check=True)
if __name__ == "__main__":
main()
+144
View File
@@ -0,0 +1,144 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <coco.h>
#include <vcc/input.h>
#include <vcc/ssc.h>
#include <vcc/orch90.h>
unsigned char stage, ack, report[14];
static VccInput right, left;
#define REG(a) (*(unsigned char *)(a))
static void waitForHost(unsigned char n)
{
stage = n;
asm {
lda :n
@wait cmpa :ack
bne @wait
}
}
/* Marshal the public fields explicitly so the host test is independent of
their layout, padding and signedness in a host C++ compiler. */
static void reportPort(unsigned char *p, const VccInput *s)
{
p[0] = s->x;
p[1] = s->y;
p[2] = s->dx;
p[3] = s->dy;
p[4] = s->held;
p[5] = s->pressed;
p[6] = s->released;
}
static unsigned char readBoth(unsigned char n)
{
unsigned char columns = REG(0xff02), dac = REG(0xff20);
unsigned char muxLow = REG(0xff01) & 63, muxHigh = REG(0xff03) & 63;
unsigned char speaker = REG(0xff23) & 63;
if (n == 1 || n == 7) {
input_init(&right, INPUT_RIGHT);
input_init(&left, INPUT_LEFT);
} else {
input_sample(&right);
input_sample(&left);
}
reportPort(report, &right);
reportPort(report + 7, &left);
return columns == REG(0xff02) && dac == REG(0xff20) &&
muxLow == (REG(0xff01) & 63) && muxHigh == (REG(0xff03) & 63) &&
speaker == (REG(0xff23) & 63);
}
#define COUNT 256
static struct orch90_frame leftSound[COUNT], rightSound[COUNT];
static unsigned char stereo(unsigned char clock)
{
unsigned char capturedPress;
setHighSpeed(clock);
asm {
sync
sync
}
input_init(&right, INPUT_RIGHT);
orch90_write(32, 80);
if (!orch90_play(leftSound, COUNT, clock)) return 0;
input_sample(&right); /* The host pressed fire during the left block. */
capturedPress = right.pressed;
if (!orch90_play(rightSound, COUNT, clock)) return 0;
input_sample(&right); /* The host released it during the right block. */
orch90_write(0, 0);
return capturedPress == INPUT_PRIMARY && right.released == INPUT_PRIMARY;
}
int main(void)
{
unsigned char n;
unsigned int i, start, route = ssc_route_audio();
VccInput inactive;
unsigned char oldFlags, restoredMask, preserved;
input_init(0, INPUT_RIGHT);
input_sample(0);
input_init(&inactive, 7);
input_sample(&inactive);
if (inactive.x != 31 || inactive.y != 31 || inactive.dx || inactive.dy ||
inactive.held || inactive.pressed || inactive.released) {
printf("FAIL INVALID PORT\n"); return 1;
}
for (n = 1; n <= 8; ++n) {
waitForHost(n);
/* Non-default keyboard columns and DAC baseline reveal side effects.
Preserve a consistent test setup across the two guest samples. */
asm {
tfr cc,a
sta :oldFlags
orcc #$50
}
REG(0xff02) = 0xfd;
REG(0xff20) = 0x56;
preserved = readBoth(n);
asm {
tfr cc,a
anda #$50
sta :restoredMask
lda :oldFlags
tfr a,cc
}
if (!preserved || restoredMask != 0x50) {
printf("FAIL PIA\n"); return 1;
}
}
waitForHost(9);
for (i = 0; i < COUNT; ++i) {
leftSound[i].left = (i & 8) ? 64 : 128;
rightSound[i].right = leftSound[i].left;
}
for (n = 0; n < 2; ++n) {
waitForHost(10 + n);
if (!stereo(n)) { printf("FAIL STEREO INPUT\n"); return 1; }
}
setHighSpeed(0);
input_init(&right, INPUT_RIGHT);
if (ssc_say("SURVEY PROBE READY", 16384) != SSC_OK) { printf("FAIL SPEECH\n"); return 1; }
start = getTimer();
while (ssc_status() & SSC_SPEECH_IDLE)
if ((unsigned)(getTimer() - start) > 120) return 1;
waitForHost(12);
input_sample(&right);
if (right.pressed != INPUT_PRIMARY || (ssc_status() & SSC_SPEECH_IDLE)) {
printf("FAIL SPEECH INPUT\n"); return 1;
}
start = getTimer();
while ((unsigned)(getTimer() - start) < 120) {
asm("sync"); /* Sample once per refresh while firmware speaks. */
input_sample(&right);
if (right.held != INPUT_PRIMARY || right.pressed || right.released) {
printf("FAIL SPEECH HOLD\n"); return 1;
}
}
ssc_restore_audio(route);
printf("INPUT PASSED\n");
return 0;
}
+196
View File
@@ -0,0 +1,196 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/MachineSession.h"
#include "devices/Orchestra90Device.h"
#include "devices/SpeechSoundDevice.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace VCC::Mac;
using namespace VCC::Devices;
namespace fs = std::filesystem;
using Bytes = std::vector<std::uint8_t>;
static void require(bool ok, const std::string& reason) {
if (!ok) throw std::runtime_error(reason);
}
static Bytes read(const fs::path& path) {
std::ifstream file(path, std::ios::binary);
require(file.good(), "Cannot open " + path.string());
return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
}
struct Session {
MachineSession machine;
std::shared_ptr<SpeechSoundDevice> speech;
std::shared_ptr<Orchestra90Device> stereo = std::make_shared<Orchestra90Device>();
unsigned stage, ack, report;
std::vector<StereoSample> pcm;
Session(const fs::path& roms, const Bytes& guest, Processor cpu, unsigned s, unsigned a, unsigned r)
: stage(s), ack(a), report(r) {
auto chips = read(roms / "pic-7040-510.bin");
auto phonemes = read(roms / "sp0256-al2.bin");
chips.insert(chips.end(), phonemes.begin(), phonemes.end());
speech = std::make_shared<SpeechSoundDevice>(chips);
machine.cartridges().configure({nullptr, speech, stereo, nullptr, nullptr}, true, 4);
machine.load(read(roms / "coco3.rom"), cpu);
machine.resume();
for (unsigned i = 0; i < 180; ++i) machine.advance();
require(machine.copyScreenText().find("OK") != std::string::npos, "BASIC did not boot");
require(guest.size() >= 5 && guest[guest.size()-5] == 0xff, "Missing guest entry point");
auto entry = std::uint16_t((guest[guest.size()-2] << 8) | guest.back());
machine.debuggerLoadBinary(guest, entry);
machine.debuggerClearDevelopmentBreakpoints();
machine.resume();
machine.takeAudio();
}
void tick() {
machine.advance();
auto block = machine.takeAudio();
pcm.insert(pcm.end(), block.begin(), block.end());
}
void wait(unsigned target) {
for (unsigned i = 0; i < 400; ++i) {
if (machine.debuggerMemoryRange(stage, 1, false).bytes[0] == target) return;
tick();
}
throw std::runtime_error("Guest missed checkpoint " + std::to_string(target) + ": " + machine.copyScreenText());
}
void release(unsigned target) {
machine.pause();
machine.debuggerWriteMemory(ack, {static_cast<std::uint8_t>(target)});
machine.resume();
}
};
// Each guest row is x, y, dx, dy, held, pressed, released. Opposite ports
// deliberately have different axes/buttons to detect accidental shared state.
using Row = std::array<int, 7>;
using Pair = std::array<Row, 2>;
static const Pair steps[] = {
{{{31,32,0,0,1,0,0}, {63,0,1,-1,2,0,0}}}, // Baseline with held buttons.
{{{26,37,0,0,1,0,0}, {37,26,0,0,2,0,0}}}, // Inclusive dead zone limits.
{{{25,38,-1,1,3,2,0}, {38,25,1,-1,1,1,2}}},
{{{0,63,-1,1,2,0,1}, {63,0,1,-1,0,0,1}}},
{{{32,31,0,0,0,0,2}, {31,32,0,0,2,2,0}}},
{{{32,31,0,0,1,1,0}, {31,32,0,0,2,0,0}}},
{{{32,31,0,0,3,0,0}, {31,32,0,0,3,0,0}}}, // Explicit re-baseline.
{{{32,31,0,0,0,0,3}, {31,32,0,0,0,0,3}}}
};
static void checkInputs(Session& run) {
run.wait(1);
for (unsigned i = 0; i < std::size(steps); ++i) {
run.release(i + 1); // Pausing releases the host controls, so apply them after resuming.
for (unsigned port = 0; port < 2; ++port) {
const auto& row = steps[i][port];
// Sample exactly at a six-bit DAC threshold with the serial pin set.
run.machine.setJoystick(port, 256 * row[0], 256 * row[1], row[4], 0);
}
run.machine.setKeyboard(std::uint64_t(1) << 1); // A held during sampling must not become fire.
run.wait(i + 2);
auto bytes = run.machine.debuggerMemoryRange(run.report, 14, false).bytes;
for (unsigned port = 0; port < 2; ++port) {
for (unsigned j = 0; j < steps[i][port].size(); ++j) {
auto expected = static_cast<std::uint8_t>(steps[i][port][j]);
require(bytes[7 * port + j] == expected, "Input mismatch at update " + std::to_string(i+1) +
", port " + std::to_string(port) + ", field " + std::to_string(j) +
": expected " + std::to_string(expected) + ", got " + std::to_string(bytes[7 * port + j]));
}
}
}
run.release(9);
}
// Measure from the first through the last plateau onset *within* each block.
// The last sample stays latched while the CoCo polls input between blocks.
static void analyzeBlock(const std::vector<StereoSample>& pcm, bool right) {
unsigned plateaus = 0, first = 0, last = 0;
float previous = 0;
for (unsigned i = 0; i < pcm.size(); ++i) {
const float delta = right ? pcm[i].right - pcm[i].left : pcm[i].left - pcm[i].right;
if (delta != 0.25f && delta != 0.50f) continue;
if (delta != previous) {
require(delta == (plateaus % 2 ? 0.25f : 0.50f), "Wrong stereo level or channel order");
if (!plateaus) first = i;
last = i;
previous = delta;
++plateaus;
}
}
require(plateaus == 32, "Expected 32 alternating stereo plateaus, found " + std::to_string(plateaus));
const double rate = 44100.0 * (31 * 8) / (last - first);
require(std::fabs(rate - 4000.0) < 200, "Stereo playback rate drifted: " + std::to_string(rate));
std::cout << (right ? "right " : "left ") << int(rate) << " Hz ";
}
static void checkStereo(Session& run, unsigned clock) {
unsigned stage = 10 + clock;
run.wait(stage);
run.pcm.clear();
run.release(stage);
// Change the physical button mid-block. Guest software first sees the
// change when orch90_play returns and input_sample reads the port.
for (bool right : {false, true}) {
unsigned n = 0;
while (n++ < 90) {
run.tick();
auto latch = run.stereo->audio();
if (right ? (latch == 64 || latch == 128) : (latch == 16384 || latch == 32768)) break;
}
require(n <= 90, "Missing stereo block: " + run.machine.copyScreenText());
run.machine.setJoystick(0,8191,8191,right ? 0 : 1,0);
}
run.wait(stage + 1);
analyzeBlock(run.pcm, false);
analyzeBlock(run.pcm, true);
std::cout << (clock ? "(fast)\n" : "(normal)\n");
}
static void checkSpeech(Session& run) {
run.wait(12);
run.release(12);
run.machine.setJoystick(0,8191,8191,1,0);
run.pcm.clear();
for (unsigned i = 0; i < 240; ++i) {
run.tick();
if (run.machine.copyScreenText().find("INPUT PASSED\nOK") != std::string::npos) break;
}
require(run.machine.copyScreenText().find("INPUT PASSED\nOK") != std::string::npos,
"Guest did not return to BASIC: " + run.machine.copyScreenText());
auto& diagnostics = run.speech->diagnostics();
require(diagnostics.AldSpeechCount() > 4 && diagnostics.CpuIllegalCount() == 0 &&
diagnostics.CommandCount() == std::string("SURVEY PROBE READY").size()+2, "Incomplete spoken phrase");
require(!run.pcm.empty(), "No speech samples captured");
auto range = std::minmax_element(run.pcm.begin(), run.pcm.end(),
[](auto a, auto b){ return a.left < b.left; });
require(range.second->left - range.first->left > 0.02f, "Speech PCM stayed silent");
std::cout << diagnostics.AldSpeechCount() << " speech phonemes while polling, input and return passed\n";
}
int main(int argc, char** argv) {
try {
require(argc == 6, "Usage: run ROM_DIR QUAL.BIN STAGE ACK REPORT");
const auto guest = read(argv[2]);
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
Session run(argv[1], guest, cpu, std::stoul(argv[3],nullptr,16),
std::stoul(argv[4],nullptr,16), std::stoul(argv[5],nullptr,16));
std::cout << (cpu == Processor::MC6809 ? "6809\n" : "6309\n");
checkInputs(run);
for (unsigned clock = 0; clock <= 1; ++clock) checkStereo(run, clock);
checkSpeech(run);
}
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Print actual int results so the host can check them independently of CMOC.
#include <cmoc.h>
static unsigned char ready = 1;
static unsigned word;
static int getReady(void)
{
return ready;
}
static int failure(void)
{
return !getReady();
}
static unsigned getWord(void)
{
return word;
}
static int wordIsZero(void)
{
return !getWord();
}
int main(void)
{
printf("NOT %d", failure());
ready = 0;
printf("%d", failure());
ready = 255;
printf("%d ", failure());
// Exercise zero, only B set, only A set, and both halves set.
word = 0;
printf("%d", wordIsZero());
word = 0x0080;
printf("%d", wordIsZero());
word = 0x8000;
printf("%d", wordIsZero());
word = 0xFFFF;
printf("%d END\n", wordIsZero());
return 0;
}
+94
View File
@@ -0,0 +1,94 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build the complete Mission Recorder project and fly it using real guest ROMs."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged ToolchainBundle")
parser.add_argument("core", type=Path, help="libVCCCore.a for the host architecture")
parser.add_argument("roms", type=Path, help="CoCo 3, Disk BASIC and both Speech/Sound ROMs")
parser.add_argument("--capture", type=Path, help="save the optimized 6809's live flight as a PNG")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-mission-recorder-") as folder:
work = Path(folder)
runner = work / "run"
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", runner], check=True)
tool = runtime / "bin/writecocofile"
note = b"EARLIER CREW\rDO NOT OVERWRITE\r"
blank = root / "platforms/macos/Resources/StarterMedia/Blank Disk.dsk"
draft = b"PART OF A PREVIOUS FLIGHT\r"
for config in ("Debug", "Release"):
project = work / config
shutil.copytree(root / "examples/cmoc/MissionRecorder", project)
subprocess.run([runtime / "bin/make", "-j3", "disk", "VCC_CONFIGURATION=" + config],
cwd=project, env=env, check=True)
binary, disk = project / "RECORDER.bin", project / "RECORDER.dsk"
occupied = project / "occupied.dsk"
shutil.copyfile(disk, occupied)
(project / "LOG01.TXT").write_bytes(note)
subprocess.run([tool, "--binary", occupied, "LOG01.TXT"], cwd=project, check=True)
(project / "LOG02.TMP").write_bytes(draft)
subprocess.run([tool, "--binary", occupied, "LOG02.TMP"], cwd=project, check=True)
for cpu in ("6809", "6309"):
for path in ("direct", "disk", "quiet", "speech", "stereo", "missing", "discard"):
media = occupied if path == "disk" else blank
original = media.read_bytes()
capture = args.capture and (cpu, config, path) == ("6809", "Release", "direct")
subprocess.run([runner, roms, cpu, path, binary, media, *(["capture"] if capture else [])],
cwd=project, check=True)
result = project / "returned.dsk"
if path == "discard":
if result.read_bytes() != original:
raise AssertionError("Discarding a flight changed its disk")
else:
log = "LOG03.TXT" if path == "disk" else "LOG01.TXT"
def extract(name):
return subprocess.check_output([tool, "--stdout", result, name], cwd=project)
if extract(log) != (project / "printed.bin").read_bytes():
raise AssertionError("The saved and printed reports differ")
if path == "disk" and extract("LOG01.TXT") != note:
raise AssertionError("The earlier report changed")
if path == "disk" and extract("LOG02.TMP") != draft:
raise AssertionError("An earlier unfinished flight was overwritten")
if path == "disk" and extract("RECORDER.BIN") != binary.read_bytes():
raise AssertionError("The guest damaged its program disk")
if media.read_bytes() != original:
raise AssertionError("The test modified its input image")
if capture:
subprocess.run(["sips", "-s", "format", "png", project / "flight.ppm",
"--out", args.capture.resolve()], check=True)
print(f"PASS {config}, {binary.stat().st_size} program bytes, {disk.stat().st_size} disk bytes",
flush=True)
# Boot the optimized project disk on the two other BASIC storage profiles.
# Read the result from the backing volume used by the guest.
profile_runner = work / "profiles"
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "profiles.cpp", core, "-o", profile_runner], check=True)
card = work / "practice card"
card.mkdir()
(card / "startup.cfg").write_text("0=VOL.DSK\n", encoding="ascii")
for cpu in ("6809", "6309"):
for profile in ("rgb-hd", "sdc"):
volume = card / "VOL.DSK"
shutil.copyfile(work / "Release/RECORDER.dsk", volume)
subprocess.run([profile_runner, roms, cpu, profile, volume], cwd=work, check=True)
report = subprocess.check_output([tool, "--stdout", work / "returned.dsk", "LOG01.TXT"])
if report != b"MISSION RECORDER\rSECTOR 07\r":
raise AssertionError(f"{cpu} {profile}: unexpected report {report!r}")
print(f"PASS {cpu} {profile}: saved starting sector and returned to BASIC", flush=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
int main(int argc, char** argv)
{
try {
require(argc == 5, "Usage: profiles ROMs CPU rgb-hd|sdc disk");
const auto profile = std::string(argv[3]) == "sdc" ? Profile::sdc : Profile::rgbHD;
const auto cpu = std::string(argv[2]) == "6809" ? Processor::MC6809 : Processor::HD6309;
Session guest(argv[1], argv[4], cpu, profile);
guest.type("LOADM\"RECORDER\":EXEC\r");
guest.until("SELECT AUDIO");
guest.frames(15);
guest.type("1");
guest.frames(500); // Finish painting both GIME pages before pressing Space.
guest.type(" ");
guest.frames(120);
require(guest.machine.debuggerMemoryRange(0x50000, 1, true).bytes[0] == 7,
"Keyboard pilot did not record the starting sector in bank $28");
guest.type("S");
guest.frames(120); // Return to hardware text before querying the guest screen.
guest.until("SAVED LOG01.TXT");
guest.verifyReturn();
saveVolume(guest, "returned.dsk");
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+211
View File
@@ -0,0 +1,211 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../ssc/session.h"
#include "../guest-captures.h"
// An electrically silent observer in the spare Multi-Pak slot counts writes.
// Sound comes exclusively from the real emulated cartridges in slots 1 and 2.
struct DacObserver final : CartridgeDevice {
std::uint64_t changes = 0;
std::uint8_t left = 128, right = 128;
void reset() override { changes = 0; left = right = 128; }
void horizontalSync(DeviceHost&) override {}
std::uint8_t readMemory(std::uint16_t) const override { return 0xff; }
std::uint8_t readPort(std::uint8_t, DeviceHost&) override { return 0; }
void writePort(std::uint8_t port, std::uint8_t value, DeviceHost&) override {
if (port == 0x7a) { left = value; ++changes; }
if (port == 0x7b) { right = value; ++changes; }
}
};
template<class Condition>
static void waitFor(Session& guest, Condition success, const std::string& message, unsigned limit = 900) {
for (unsigned n = 0; n < limit; ++n) {
guest.tick();
if (success()) return;
}
throw std::runtime_error(message);
}
static void frames(Session& guest, unsigned count) {
while (count--) guest.tick();
}
static std::uint32_t pixel(const Frame& frame, unsigned x, unsigned y) {
const auto a = frame.activeArea;
return frame.pixels.at((a.y + y * a.height / 192) * Frame::width + a.x + x * a.width / 320);
}
static void expectShip(Session& guest, unsigned sector) {
waitFor(guest, [&] {
auto frame = guest.machine.snapshot().frame;
if (!frame) return false;
return pixel(*frame, 10 + 20 * sector, 54) != pixel(*frame, 2 + 20 * sector, 54);
}, "Ship did not appear in sector " + std::to_string(sector));
}
// gime_close() restores the text mode on a frame boundary. Text scanout
// is unavailable for the remaining graphics frames after the save/quit key.
static void untilText(Session& guest, const std::string& text, unsigned limit = 1200) {
waitFor(guest, [&] {
try {
return guest.contains(text);
} catch (const std::logic_error&) {
return false;
}
}, "Did not see " + text, limit);
}
static void verifyBasic(Session& guest) {
untilText(guest, "OK");
frames(guest, 12);
guest.press(47, true); guest.press(39); guest.press(43, true);
guest.press(35); guest.press(48); // ?7+3
guest.until(" 10");
}
static void fly(const fs::path& roms, Processor cpu, const std::string& mode,
const fs::path& binary, const fs::path& image, bool capture) {
const bool quiet = mode == "quiet", discard = mode == "discard", fromDisk = mode == "disk";
auto chips = readFile(roms / "pic-7040-510.bin");
auto voice = readFile(roms / "sp0256-al2.bin");
require(chips.size() == 4096 && voice.size() == 2048, "Incorrect Speech/Sound ROM sizes");
chips.insert(chips.end(), voice.begin(), voice.end());
const bool missing = mode == "missing";
const bool speech = !quiet && mode != "stereo";
const bool stereo = !quiet && mode != "speech";
auto ssc = speech && !missing ? std::make_shared<SpeechSoundDevice>(chips) : nullptr;
auto dac = std::make_shared<DacObserver>();
Session guest(cpu, readFile(roms / "coco3.rom"), readFile(roms / "disk11.rom"), ssc, stereo && !missing, dac);
auto& machine = guest.machine;
auto& printer = machine.printer();
printer.setEnabled(true);
auto ram = [&](unsigned address, unsigned count, bool physical = false) {
return machine.debuggerMemoryRange(address, count, physical).bytes;
};
const auto irq = ram(0xfef7, 3), palette = ram(0xffb0, 16);
const auto before = machine.debuggerSnapshot().mmu;
const auto disk = readFile(image);
if (fromDisk) guest.diskExec(disk, "RECORDER");
else {
guest.floppy->mount(0, DiskImage::load(disk, false));
guest.launch(readFile(binary));
}
guest.until("SELECT AUDIO", 1200);
frames(guest, 12);
guest.audio.clear();
const auto beforeSpeech = ssc ? ssc->diagnostics().AldSpeechCount() : 0;
// The first screen can appear while the guest is still painting the second
// landscape. Both GIME presentations must have completed before sending D.
guest.press(33 + unsigned(speech) + 2 * unsigned(stereo));
waitFor(guest, [&] { return ram(0xff9d, 1)[0] == 0x90; }, "First GIME page was never displayed");
waitFor(guest, [&] { return ram(0xff9d, 1)[0] == 0x80; }, "Second GIME page was never displayed");
expectShip(guest, 7);
if (stereo) waitFor(guest, [&] { return dac->changes > 100; }, "Stereo player did not start");
// The keyboard nudges the craft, then the physical right-stick reaches the edge.
guest.press(4);
expectShip(guest, 8);
machine.setJoystick(0, 16383, 8191, 0, 0);
expectShip(guest, 15);
machine.setJoystick(0, 8191, 8191, 0, 0);
if (stereo) {
require(ram(0xfef7, 3) != irq, "Stereo never installed its interrupt handler");
unsigned left = 0, right = 0;
for (auto sample : guest.audio) {
left += sample.left > sample.right + 0.02f;
right += sample.right > sample.left + 0.02f;
}
if (missing) require(!left && !right, "Stereo without an installed cartridge");
else require(left > 50 && right > 50, "No distinct left and right PCM during steering");
}
// Press and release the first right joystick button; no test writes guest RAM.
machine.setJoystick(0, 8191, 8191, 1, 0);
waitFor(guest, [&] { return ram(0x50000, 1, true)[0] == 15; }, "Flight mark missing in physical bank $28");
machine.setJoystick(0, 8191, 8191, 0, 0);
if (ssc) {
waitFor(guest, [&] { return ssc->diagnostics().AldSpeechCount() > beforeSpeech; },
"Speech chip did not start the mark announcement");
}
// With no Orchestra cartridge contributing audio, the voiced phrase should
// be audible on both channels, with no channel divergence.
if (speech && !stereo) {
guest.audio.clear();
frames(guest, 90);
guest.checkSignal(0);
require(std::all_of(guest.audio.begin(), guest.audio.end(),
[](auto sample) { return sample.left == sample.right; }), "Speech was not centered");
}
const auto spokenAtDeparture = ssc ? ssc->diagnostics().AldSpeechCount() : 0;
const auto writesAtDeparture = dac->changes;
// Leave the marked sector. The flight report must use the saved mark.
machine.setJoystick(0, 0, 8191, 0, 0);
expectShip(guest, 7);
if (ssc && stereo) {
require(ssc->diagnostics().AldSpeechCount() > spokenAtDeparture && dac->changes > writesAtDeparture,
"Speech or stereo stalled while steering away from the mark");
}
machine.setJoystick(0, 8191, 8191, 0, 0);
frames(guest, 30);
const auto frame = machine.snapshot().frame;
require(pixel(*frame, 310, 69) != pixel(*frame, 302, 69), "Saved mark disappeared after steering away");
if (capture) BasicDiskTests::saveActiveFrame(*machine.snapshot().frame, "flight.ppm");
if (discard) {
machine.setKeyboard(std::uint64_t{1} << 17); // Q
untilText(guest, "FLIGHT DISCARDED");
machine.setKeyboard(0);
require(printer.bytes().empty(), "Discard printed a report");
} else {
machine.setKeyboard(std::uint64_t{1} << 19); // S, through the current draw
if (fromDisk) {
untilText(guest, "SAVE FAILED", 1600);
require(guest.floppy->image(0)->bytes() == disk && printer.bytes().empty(),
"The failed save touched the disk or printer");
machine.setKeyboard(0);
guest.floppy->setWriteProtected(0, false);
frames(guest, 12);
guest.press(18); // R
}
untilText(guest, fromDisk ? "SAVED LOG03.TXT" : "SAVED LOG01.TXT", 1800);
machine.setKeyboard(0);
}
verifyBasic(guest);
const auto after = machine.debuggerSnapshot().mmu;
require(after.Task0 == before.Task0 && after.Task1 == before.Task1 &&
after.ActiveTask == before.ActiveTask, "Effective MMU banks were not restored");
require(ram(0xfef7, 3) == irq, "BASIC interrupt vector was not restored");
require(ram(0xffb0, 16) == palette, "BASIC palette was not restored");
const auto stopped = dac->changes;
frames(guest, 15);
require(dac->changes == stopped && dac->left == 128 && dac->right == 128,
"Background DAC writes continued after exit or a channel was left on");
if (!stereo) require(!dac->changes, "Software wrote to an unselected Orchestra DAC");
if (discard) {
require(guest.floppy->writeEvents(0) == 0 && printer.bytes().empty(), "Discard produced output");
} else {
require(guest.floppy->writeEvents(0) > 0, "No guest FD-502 writes");
const auto& bytes = printer.bytes();
require(std::string(bytes.begin(), bytes.end()) == "MISSION RECORDER\rSECTOR 15\r" &&
printer.droppedBytes() == 0, "Unexpected TP-10 report");
std::ofstream out("printed.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
require(out.good(), "Could not save printer output for comparison");
}
if (ssc) require(ssc->diagnostics().CpuIllegalCount() == 0, "Speech cartridge executed an illegal instruction");
BasicDiskTests::saveDisk(*guest.floppy->image(0), "returned.dsk");
std::cout << "PASS " << (cpu == Processor::MC6809 ? "6809" : "6309") << " " << mode
<< ", " << dac->changes << " DAC writes, "
<< (ssc ? ssc->diagnostics().AldSpeechCount() - beforeSpeech : 0) << " phonemes, "
<< guest.floppy->readEvents(0) << " reads, " << guest.floppy->writeEvents(0) << " writes\n";
}
int main(int argc, char** argv) {
try {
require(argc == 6 || argc == 7, "Usage: run ROMS CPU direct|disk|quiet|speech|stereo|missing|discard BIN DSK [capture]");
fly(argv[1], std::string(argv[2]) == "6809" ? Processor::MC6809 : Processor::HD6309,
argv[3], argv[4], argv[5], argc == 7);
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Check signed and unsigned base conversion under both guest CPUs and CMOC optimizations."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged toolchain with base-aware vcccompat")
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("rom", type=Path, help="private CoCo 3 ROM")
args = parser.parse_args()
runtime, core, rom = [p.resolve(strict=True) for p in (args.runtime, args.core, args.rom)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="1")
with tempfile.TemporaryDirectory(prefix="vcc-number-conversion-") as work:
runner = Path(work) / "run-compiled"
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
fixture.parent / "run-compiled.cpp", core, "-o", runner], cwd=work, check=True)
compiler = [runtime / "bin/cmoc", "--coco", "-Werror"]
for opt in ("-O0", "-O2"):
caller = [*compiler, opt, "--org=2800", "-o", "TEST.BIN"]
if opt == "-O2":
caller.append("-DCMOC_HEADER_FIRST")
caller.append(fixture / "qualification.c")
# The installed library is optimized. Check it with both app
# settings, then exercise the conversion code itself unoptimized.
subprocess.run([*caller, "-lvcccompat"], cwd=work, env=env, check=True)
print(f"{opt} caller, staged archive", flush=True)
subprocess.run([runner, rom, "TEST.BIN", "NUMBER CONVERSIONS PASSED", "450"], cwd=work, check=True)
if opt == "-O0":
subprocess.run([*compiler, opt, "-c", "-o", "strto.o", root / "sdk/cmoc/compat/strto.c"],
cwd=work, env=env, check=True)
subprocess.run([*caller, "strto.o"], cwd=work, env=env, check=True)
print("-O0 caller and conversion implementation", flush=True)
subprocess.run([runner, rom, "TEST.BIN", "NUMBER CONVERSIONS PASSED", "450"], cwd=work, check=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#ifdef CMOC_HEADER_FIRST
#include <cmoc.h>
#include <stdlib.h>
#else
#include <stdlib.h>
#include <cmoc.h>
#endif
#include <errno.h>
#include <limits.h>
// The upstream cmoc.h has decimal-only macros. Both include orders must
// expose the base-aware calls and their addresses when compatibility is on.
static long (*signedParser)(const char *, char **, int) = strtol;
static unsigned long (*unsignedParser)(const char *, char **, int) = strtoul;
#define UNCHANGED 73
struct Conversion {
const char *text;
int base;
unsigned consumed;
long signedValue;
unsigned long unsignedValue;
int signedError;
int unsignedError;
};
static const struct Conversion cases[] = {
{ "", 10, 0, 0, 0, UNCHANGED, UNCHANGED },
{ " ", 0, 0, 0, 0, UNCHANGED, UNCHANGED },
{ " +!", 10, 0, 0, 0, UNCHANGED, UNCHANGED },
{ "-", 10, 0, 0, 0, UNCHANGED, UNCHANGED },
{ "MARS", 10, 0, 0, 0, UNCHANGED, UNCHANGED },
{ "0", 0, 1, 0, 0, UNCHANGED, UNCHANGED },
{ " -0", 0, 4, 0, 0, UNCHANGED, UNCHANGED },
{ "+0779", 0, 4, 63, 63, UNCHANGED, UNCHANGED },
{ "09", 10, 2, 9, 9, UNCHANGED, UNCHANGED },
{ "0x", 0, 1, 0, 0, UNCHANGED, UNCHANGED },
{ "0XG", 16, 1, 0, 0, UNCHANGED, UNCHANGED },
{ "0x12", 10, 1, 0, 0, UNCHANGED, UNCHANGED },
{ "0b11", 0, 1, 0, 0, UNCHANGED, UNCHANGED },
{ "0X010f!", 0, 6, 271, 271, UNCHANGED, UNCHANGED },
{ "2X", 0, 1, 2, 2, UNCHANGED, UNCHANGED },
{ "\t\n\v\f\r +1012", 2, 10, 5, 5, UNCHANGED, UNCHANGED },
{ " -aB", 16, 4, -171, 4294967125UL, UNCHANGED, UNCHANGED },
{ "zZ.", 36, 2, 1295, 1295, UNCHANGED, UNCHANGED },
{ "2147483647", 10, 10, LONG_MAX, 2147483647UL, UNCHANGED, UNCHANGED },
{ "2147483648", 10, 10, LONG_MAX, 2147483648UL, ERANGE, UNCHANGED },
{ "-2147483648", 10, 11, -2147483648L, 2147483648UL, UNCHANGED, UNCHANGED },
{ "-2147483649", 10, 11, -2147483648L, 2147483647UL, ERANGE, UNCHANGED },
{ "4294967295!", 10, 10, LONG_MAX, ULONG_MAX, ERANGE, UNCHANGED },
{ "4294967296", 10, 10, LONG_MAX, ULONG_MAX, ERANGE, ERANGE },
{ "-4294967295", 10, 11, -2147483648L, 1, ERANGE, UNCHANGED },
{ "-4294967296", 10, 11, -2147483648L, ULONG_MAX, ERANGE, ERANGE },
{ "0xffffffff!", 0, 10, LONG_MAX, ULONG_MAX, ERANGE, UNCHANGED },
{ "-0x80000000", 0, 11, -2147483648L, 2147483648UL, UNCHANGED, UNCHANGED },
{ "100000000000000000000000000000!", 16, 30, LONG_MAX, ULONG_MAX, ERANGE, ERANGE },
{ "37777777777!", 8, 11, LONG_MAX, ULONG_MAX, ERANGE, UNCHANGED },
{ "40000000000!", 8, 11, LONG_MAX, ULONG_MAX, ERANGE, ERANGE },
{ " +42", -2, 0, 0, 0, EINVAL, EINVAL },
{ " +42", 1, 0, 0, 0, EINVAL, EINVAL },
{ " +42", 37, 0, 0, 0, EINVAL, EINVAL }
};
static int check(void)
{
unsigned i;
for (i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) {
const struct Conversion *c = &cases[i];
char *end = NULL;
errno = UNCHANGED;
long s = signedParser(c->text, &end, c->base);
if (s != c->signedValue || errno != c->signedError || end != c->text + c->consumed) {
printf("SIGNED CASE %u\n", i);
return __LINE__;
}
end = NULL;
errno = UNCHANGED;
unsigned long u = unsignedParser(c->text, &end, c->base);
if (u != c->unsignedValue || errno != c->unsignedError || end != c->text + c->consumed) {
printf("UNSIGNED CASE %u\n", i);
return __LINE__;
}
}
// One more than the highest digit is a terminator in each radix.
const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz!";
for (i = 2; i <= 36; ++i) {
char text[4], *end;
text[0] = '1';
text[1] = digits[i - 1];
text[2] = digits[i];
text[3] = 0;
if (strtol(text, &end, i) != (long)(2 * i - 1) || end != text + 2)
return __LINE__;
if (strtoul(text, &end, i) != (unsigned long)(2 * i - 1) || end != text + 2)
return __LINE__;
}
if (strtoul("ff", NULL, 16) != 255 || strtol("-10", NULL, 2) != -2)
return __LINE__;
char highByte[] = { (char) 0xff, '3', 0 };
char *end;
if (strtol(highByte, &end, 10) != 0 || end != highByte)
return __LINE__;
return 0;
}
int main(void)
{
int line = check();
if (line) printf("FAIL LINE %d\n", line);
else printf("NUMBER CONVERSIONS PASSED\n");
return line != 0;
}
@@ -0,0 +1,48 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run the Orchestra-90 background player and Stereo Flyby on the emulated CoCo."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="write the optimized 6809 live display to a PNG")
parser.add_argument("--audio", type=Path, help="write the corresponding 44.1 kHz stereo recording")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
repo = fixture.parents[2]
env = dict(os.environ, PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"], VCC_CMOC_COMPAT="0")
with tempfile.TemporaryDirectory(prefix="vcc-stereo-flyby-") as temp:
work = Path(temp)
def run(*cmd):
subprocess.run(cmd, cwd=work, env=env, check=True)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", repo / "src", fixture / "run.cpp", core, "-o", "run")
for opt in ("-O0", "-O2"):
run(runtime / "bin/cmoc", "--coco", "--org=2800", opt, "-Werror", "-o", "QUAL.BIN",
fixture / "qualification.c", "-lorch90")
run(runtime / "bin/cmoc", "--coco", "--org=2800", opt, "-Werror", "-o", "FLYBY.BIN",
repo / "examples/cmoc/manual/flyby.c", "-lorch90", "-linput", "-lbcontrol")
shutil.copyfile(repo / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK", work / "VOL.DSK")
run(runtime / "bin/writecocofile", "VOL.DSK", "FLYBY.BIN")
capture = opt == "-O2" and (args.capture or args.audio)
print(f"Checking {opt}", flush=True)
run("./run", roms, *(["capture"] if capture else []))
if capture and args.capture:
run("sips", "-s", "format", "png", "flyby.ppm", "--out", args.capture.resolve())
if capture and args.audio:
shutil.copyfile(work / "flyby.wav", args.audio.resolve())
if __name__ == "__main__":
main()
@@ -0,0 +1,183 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <cmoc.h>
#include <coco.h>
#include <vcc/orch90.h>
#define COUNT 512
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u\n", (unsigned)__LINE__); return 1; } } while (0)
static struct orch90_frame source[COUNT];
static byte savedVector[3];
asm byte interruptMasks(void)
{
asm {
tfr cc,b
andb #$50
}
}
// Same timed instruction loop before and after playback, starting at a
// vertical sync. This detects returning to BASIC at twice/half its old speed.
asm unsigned int speedProbe(void)
{
asm {
sync
ldd >$0112
addd #3
ldx #0
@count leax 1,x
cmpd >$0112
bne @count
tfr x,d
}
}
static byte refusedForeignVector(byte clock)
{
// JMP $010C reaches the same handler as BASIC's stock LBRA $010C.
// It is safe to execute yet a visibly different owner's vector.
byte result;
asm("orcc", "#$10");
*(byte *)0xfef7 = 0x7e;
*(unsigned *)0xfef8 = 0x010c;
asm("andcc", "#$ef");
result = !orch90_start(source, COUNT, 0, clock);
asm("orcc", "#$10");
memcpy((void *)0xfef7, savedVector, sizeof(savedVector));
asm("andcc", "#$ef");
return result;
}
asm byte control(void)
{
asm {
ldb >$ff01
andb #$3f
}
}
// Keep the stock IRQ entry, but give the already enabled HSYNC source a
// temporary consumer. A refused start must leave this user's PIA bit alone.
static asm __norts__ void occupiedHS(void)
{
asm {
tst >$ff00
tst >$ff02
rti
}
}
static byte refusedBusyHS(byte clock)
{
byte normalControl = control(), jump[3], result;
setHighSpeed(TRUE);
asm { sync }
asm { sync }
asm("orcc", "#$10");
memcpy(jump, (const void *)0x010c, 3);
*(byte *)0x010c = 0x7e;
*(unsigned *)0x010d = (unsigned)occupiedHS;
*(byte *)0xff01 = normalControl | 1;
asm("andcc", "#$ef");
result = !orch90_start(source, COUNT, 0, ORCH90_CLOCK_FAST);
asm("orcc", "#$10");
if (!(control() & 1)) result = 0;
*(byte *)0xff01 = normalControl;
memcpy((void *)0x010c, jump, 3);
asm("andcc", "#$ef");
setHighSpeed(clock == ORCH90_CLOCK_FAST);
return result;
}
int main(void)
{
byte clock, masks, initial, vertical, changed, status;
unsigned i, before, after, ticks, work = 0;
printf("SELECT CLOCK\n");
clock = waitkey(FALSE) == '2' ? ORCH90_CLOCK_FAST : ORCH90_CLOCK_NORMAL;
setHighSpeed(clock == ORCH90_CLOCK_FAST);
before = speedProbe();
initial = control();
masks = interruptMasks();
memcpy(savedVector, (const void *)0xfef7, sizeof(savedVector));
for (i = 0; i < COUNT; ++i) {
byte level = (i & 8) ? 64 : 192;
source[i].left = i < COUNT / 2 ? level : 128;
source[i].right = i >= COUNT / 2 ? level : 128;
}
orch90_write(19, 235);
CHECK(!orch90_active());
orch90_stop(); // Idle stop must leave another producer's DACs alone.
CHECK(!orch90_start(0, 1, 0, clock));
CHECK(!orch90_start(source, 0, 0, clock));
CHECK(!orch90_start((const struct orch90_frame *)0xffff, 1, 0, clock));
CHECK(!orch90_start(source, 1, 2, clock));
CHECK(!orch90_start(source, 1, 0, 2));
asm("orcc", "#$10");
status = orch90_start(source, COUNT, 0, clock);
asm("andcc", "#$ef");
CHECK(!status);
CHECK(refusedForeignVector(clock));
CHECK(refusedBusyHS(clock));
*(byte *)0xff01 = initial & 0x3b; // The data address now selects a DDR.
status = orch90_start(source, COUNT, 0, clock);
*(byte *)0xff01 = initial;
CHECK(!status);
vertical = *(byte *)0xff03 & 63;
*(byte *)0xff03 = vertical & 0x3e; // VSYNC disabled: arming would hang.
status = orch90_start(source, COUNT, 0, clock);
*(byte *)0xff03 = vertical;
CHECK(!status);
CHECK(!orch90_active());
CHECK(control() == initial && interruptMasks() == masks);
CHECK(!memcmp(savedVector, (const void *)0xfef7, sizeof(savedVector)));
// Before the second VSYNC arms HSYNC, cancellation releases the vector
// without reading any sample or leaving the clock at the borrowed speed.
CHECK(orch90_start(source, COUNT, 1, clock));
CHECK(orch90_active());
orch90_stop();
CHECK(!orch90_active() && control() == initial);
CHECK(!memcmp(savedVector, (const void *)0xfef7, sizeof(savedVector)));
after = speedProbe();
CHECK(after > before - before / 8 && after < before + before / 8);
ticks = getTimer();
CHECK(orch90_start(source, COUNT, 0, clock));
CHECK(!orch90_start(source, 1, 1, clock));
while (orch90_active()) ++work;
CHECK(work > 16 && (unsigned)(getTimer() - ticks) >= 4);
CHECK(!memcmp(savedVector, (const void *)0xfef7, sizeof(savedVector)));
CHECK(control() == initial && interruptMasks() == masks);
after = speedProbe();
CHECK(after > before - before / 8 && after < before + before / 8);
// A one-frame clip completes and a subsequent loop can be stopped at will.
CHECK(orch90_start(source, 1, 0, clock));
while (orch90_active()) {}
CHECK(orch90_start(source, 16, 1, clock));
ticks = getTimer();
while ((unsigned)(getTimer() - ticks) < 6) ++work;
CHECK(orch90_active());
asm("orcc", "#$50");
changed = initial ^ 8;
*(byte *)0xff01 = changed | 1; // Foreground changed a PIA field it still owns.
orch90_stop();
CHECK(interruptMasks() == 0x50 && control() == changed);
*(byte *)0xff01 = initial;
asm {
lda :masks
tfr a,cc
}
orch90_stop();
CHECK(!orch90_active());
CHECK(!memcmp(savedVector, (const void *)0xfef7, sizeof(savedVector)));
CHECK(control() == initial && interruptMasks() == masks);
after = speedProbe();
CHECK(after > before - before / 8 && after < before + before / 8);
orch90_write(21, 233);
setHighSpeed(FALSE);
printf("RESTORED\n");
return 0;
}
+196
View File
@@ -0,0 +1,196 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../ssc/session.h"
#include "../guest-captures.h"
// Observe the actual guest writes in a spare MPI slot. The Orchestra-90 in a
// different slot supplies every host audio sample independently of this probe.
struct DacLog final : CartridgeDevice {
struct Write { unsigned audioTick; unsigned char port, value; };
std::vector<Write> writes;
unsigned audioTick = 0;
void reset() override { writes.clear(); audioTick = 0; }
void horizontalSync(DeviceHost&) override {}
void advanceAudio() override { ++audioTick; }
std::uint8_t readMemory(std::uint16_t) const override { return 0xff; }
std::uint8_t readPort(std::uint8_t, DeviceHost&) override { return 0; }
void writePort(std::uint8_t port, std::uint8_t value, DeviceHost&) override {
if (port == 0x7a || port == 0x7b) writes.push_back({audioTick, port, value});
}
};
static void frames(Session& session, unsigned count) {
for (unsigned i = 0; i < count; ++i) session.tick();
}
static void verifyBasic(Session& session) {
session.until("OK", 180);
frames(session, 12);
session.press(47, true); session.press(39); session.press(43, true);
session.press(35); session.press(48); // ?7+3
session.until(" 10");
}
struct Pair { unsigned tick; unsigned char left, right; };
static std::vector<Pair> pairs(const DacLog& log) {
std::vector<Pair> result;
require(log.writes.size() % 2 == 0, "An incomplete stereo DAC pair");
for (std::size_t i = 0; i < log.writes.size(); i += 2) {
const auto& l = log.writes[i];
const auto& r = log.writes[i + 1];
require(l.port == 0x7a && r.port == 0x7b, "DAC writes out of stereo order");
result.push_back({l.audioTick, l.value, r.value});
}
return result;
}
static double measuredRate(std::size_t intervals, unsigned audioTicks) {
require(audioTicks != 0, "Elapsed audio ticks must be positive");
return 44100.0 * intervals / audioTicks;
}
static void qualify(Session& run, DacLog& log, bool fast) {
run.launch(readFile("QUAL.BIN"));
run.until("SELECT CLOCK");
log.writes.clear();
run.press(fast ? 34 : 33);
run.until("RESTORED", 240);
const auto writes = pairs(log);
require(writes.size() > 518, "One-shot or loop failed to write frames");
require(writes[0].left == 19 && writes[0].right == 235, "Missing fixture DAC marker");
require(writes[1].left == 128 && writes[1].right == 128, "Cancelled startup emitted a sample");
for (unsigned i = 0; i < 512; ++i) {
auto level = (i & 8) ? 64 : 192;
require(writes[i + 2].left == (i < 256 ? level : 128) &&
writes[i + 2].right == (i < 256 ? 128 : level), "One-shot frames dropped, reordered or distorted");
}
require(writes[514].left == 128 && writes[514].right == 128, "Natural end left a DAC on");
require(writes[515].left == 192 && writes[515].right == 128 &&
writes[516].left == 128 && writes[516].right == 128, "Single-frame replay failed");
const auto count = writes.size();
require(writes[count - 1].left == 21 && writes[count - 1].right == 233, "Missing final DAC marker");
require(writes[count - 2].left == 128 && writes[count - 2].right == 128, "Manual stop left a DAC on");
for (unsigned i = 517; i + 2 < count; ++i) {
auto level = ((i - 517) & 8) ? 64 : 192;
require(writes[i].left == level && writes[i].right == 128, "Loop boundary or frame mismatch");
}
const auto rate = measuredRate(511, writes[513].tick - writes[2].tick);
require(rate > 3600 && rate < 4050, "Quiet foreground sample rate: " + std::to_string(rate));
std::cout << " " << (fast ? "fast" : "normal") << " entry, " << rate
<< " frames/s, CPU speed and interrupts restored\n";
verifyBasic(run);
}
// Look at the real text scanout so a frozen picture can't pass as animation.
static int marker(Session& run, unsigned row, char symbol) {
const auto screen = run.machine.copyScreenText();
std::size_t start = 0;
for (unsigned i = 0; i < row; ++i) {
auto next = screen.find('\n', start);
if (next == std::string::npos) return -1;
start = next + 1;
}
const auto end = screen.find('\n', start);
auto column = screen.substr(start, end - start).find(symbol);
return column == std::string::npos ? -1 : int(column);
}
static void bookExercise(Session& run, DacLog& log, bool disk, bool capture, bool installed = true) {
if (disk) run.diskExec(readFile("VOL.DSK"), "FLYBY");
else run.launch(readFile("FLYBY.BIN"));
run.until("STEREO FLYBY", 1200);
for (unsigned i = 0; i < 180 && marker(run, 10, '^') != 15; ++i) run.tick();
require(marker(run, 10, '^') == 15, "Ship did not appear at its starting position");
run.press(33);
run.until("BEACON ON AIR", 240);
run.machine.setJoystick(0, 16383, 8191, 0, 0);
const auto logsBefore = log.writes.size();
const auto originalTick = log.audioTick;
run.audio.clear();
int firstStar = marker(run, 8, '*');
bool moved = false;
for (unsigned f = 0; f < 120; ++f) {
run.tick();
int star = marker(run, 8, '*');
if (star >= 2 && firstStar >= 2 && star != firstStar) moved = true;
}
require(moved && marker(run, 10, '^') >= 28, "Star or joystick-controlled ship stalled during sound");
run.machine.setJoystick(0, 8191, 8191, 0, 0);
const double rate = measuredRate((log.writes.size() - logsBefore) / 2, log.audioTick - originalTick);
require(rate > 3450 && rate < 4050, "Active foreground sample rate: " + std::to_string(rate));
std::size_t channelFrames[2] = {}, periods[2] = {}, elapsed[2] = {}, last[2] = {};
bool high[2] = {};
for (std::size_t i = 0; i < run.audio.size(); ++i) {
const auto sample = run.audio[i];
if (!installed) {
require(sample.left == sample.right, "Unexpected stereo with cartridge absent");
continue;
}
const float levels[] = {sample.left, sample.right};
require(sample.left == 0.5f || sample.right == 0.5f, "A stereo note crossed or dropped out");
for (unsigned side = 0; side < 2; ++side) {
channelFrames[side] += std::abs(levels[side] - 0.5f) > 0.04f;
bool nowHigh = levels[side] > 0.55f;
if (nowHigh && !high[side]) {
auto distance = i - last[side];
// The loop has silent gaps between its two notes. Count only
// adjacent waveform periods inside one note, ignoring gaps.
if (last[side] && distance < 300) {
++periods[side];
elapsed[side] += distance;
}
last[side] = i;
}
high[side] = nowHigh;
}
}
if (installed) {
for (unsigned side = 0; side < 2; ++side) {
require(channelFrames[side] > 2000 && periods[side] > 30, "Missing stereo cycles");
const double frequency = 44100.0 * periods[side] / elapsed[side];
const double expected = rate / (side ? 8 : 16);
require(std::abs(frequency - expected) < expected * 0.05, "Incorrect stereo note pitch");
std::cout << (side ? "right " : " left ") << frequency << " Hz ";
}
std::cout << '\n';
}
if (capture) {
BasicDiskTests::saveActiveFrame(*run.machine.snapshot().frame, "flyby.ppm");
saveWav("flyby.wav", run.audio);
}
run.press(17);
run.until("FLYBY COMPLETE");
const auto stopped = log.writes.size();
verifyBasic(run);
require(log.writes.size() == stopped, "Background writes continued after BASIC regained control");
if (disk) require(run.floppy->readEvents(0) > 0 && run.floppy->writeEvents(0) == 0, "Unexpected demo disk I/O");
std::cout << " " << (installed ? "stereo" : "absent") << " " << (disk ? "disk" : "direct")
<< ", steering/animation: " << rate << " frames/s\n";
}
int main(int argc, char** argv) {
try {
require(argc == 2 || argc == 3, "Usage: run ROM_DIRECTORY [capture]");
const fs::path rom(argv[1]);
const auto system = readFile(rom / "coco3.rom"), disk = readFile(rom / "disk11.rom");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
std::cout << (cpu == Processor::MC6809 ? "6809" : "6309") << std::endl;
for (bool fast : {false, true}) {
auto log = std::make_shared<DacLog>();
Session guest(cpu, system, disk, nullptr, true, log);
qualify(guest, *log, fast);
}
for (bool fromDisk : {false, true}) {
auto log = std::make_shared<DacLog>();
Session guest(cpu, system, disk, nullptr, true, log);
bookExercise(guest, *log, fromDisk, argc == 3 && cpu == Processor::MC6809 && !fromDisk);
}
auto log = std::make_shared<DacLog>();
Session absent(cpu, system, disk, nullptr, false, log);
bookExercise(absent, *log, false, false, false);
}
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
return 1;
}
}
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Measure compiled Orchestra-90 stereo through VCC Plus at both CoCo clock speeds."""
import argparse
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged Toolchain directory with liborch90.a")
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("rom", type=Path, help="local 32 KiB CoCo 3 system ROM")
args = parser.parse_args()
fixture = Path(__file__).resolve().parent
with tempfile.TemporaryDirectory(prefix="vcc-orch90-") as work:
subprocess.run([args.runtime.resolve() / "bin/cmoc", "--coco", "-o", "PLAY.BIN",
fixture / "playback.c", "-lorch90"], cwd=work, check=True)
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
fixture / "measure.cpp", args.core.resolve(), "-o", "measure"], cwd=work, check=True)
subprocess.run(["./measure", args.rom.resolve(), "PLAY.BIN"], cwd=work, check=True)
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../../../src/core/MachineSession.h"
#include "../../../src/devices/Orchestra90Device.h"
#include <cmath>
#include <cstdio>
#include <fstream>
#include <iterator>
#include <stdexcept>
using namespace VCC::Mac;
static std::vector<std::uint8_t> readFile(const char* path) {
std::ifstream input(path, std::ios::binary);
if (!input) throw std::runtime_error("Cannot open a test input");
return {std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
}
static void measure(Processor processor, const std::vector<std::uint8_t>& system,
const std::vector<std::uint8_t>& binary) {
MachineSession machine;
auto orchestra = std::make_shared<VCC::Devices::Orchestra90Device>();
machine.cartridges().configure({nullptr, orchestra, nullptr, nullptr, nullptr}, true, 4);
machine.load(system, processor);
machine.resume();
for (unsigned i = 0; i < 150; ++i) machine.advance();
machine.takeAudio();
machine.quickLoad(binary);
std::vector<StereoSample> pcm;
for (unsigned i = 0; i < 120; ++i) {
machine.advance();
auto chunk = machine.takeAudio();
pcm.insert(pcm.end(), chunk.begin(), chunk.end());
}
// Marker 32/96 establishes channel order; each following block must contain
// 32 alternating plateaus on one side, with the other side fully silent.
std::size_t cursor = 0;
for (auto clock : {"normal", "fast"}) {
auto isMarker = [](StereoSample p) { return p.left == 0.125f && p.right == 0.375f; };
while (cursor < pcm.size() && !isMarker(pcm[cursor])) ++cursor;
if (cursor == pcm.size()) throw std::runtime_error("Raw stereo marker missing");
while (cursor < pcm.size() && isMarker(pcm[cursor])) ++cursor;
for (unsigned side = 0; side < 2; ++side) {
const auto start = cursor;
unsigned plateaus = 0;
float previous = -1;
while (cursor < pcm.size()) {
const auto sample = pcm[cursor];
float active = side ? sample.right : sample.left;
float other = side ? sample.left : sample.right;
if (other != 0 || (active != 0.25f && active != 0.5f)) break;
if (active != previous) {
if (active != (plateaus % 2 ? 0.25f : 0.5f))
throw std::runtime_error("Wrong alternating sample amplitude");
++plateaus;
previous = active;
}
++cursor;
}
if (plateaus != 32) throw std::runtime_error("Missing sample transitions or channel bleed");
const double rate = 44100.0 * 256 / (cursor - start);
std::printf("%s %-6s %s: %.1f frames/s\n", processor == Processor::MC6809 ? "6809" : "6309",
clock, side ? "right" : "left", rate);
if (std::abs(rate - 4000.0) > 200.0) throw std::runtime_error("Playback rate outside 5% tolerance");
}
}
if (cursor == pcm.size() || pcm.back().left != 16 / 256.0f || pcm.back().right != 80 / 256.0f)
throw std::runtime_error("Guest fixture did not reach the final stereo marker");
}
int main(int argc, char** argv) {
try {
if (argc != 3) throw std::runtime_error("Usage: measure COCO3_ROM PLAYBACK_BIN");
const auto system = readFile(argv[1]), binary = readFile(argv[2]);
for (auto cpu : {Processor::MC6809, Processor::HD6309}) measure(cpu, system, binary);
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Compiled by CMOC and executed inside each guest processor by measure.cpp.
#include <coco.h>
#include <vcc/orch90.h>
#define FRAMES 256
static struct orch90_frame leftBlock[FRAMES];
static struct orch90_frame rightBlock[FRAMES];
static void fail(void)
{
orch90_write(9, 17);
for (;;) {}
}
static void playBothSides(unsigned char clock)
{
setHighSpeed(clock == ORCH90_CLOCK_FAST);
// VCC applies a requested clock change at the next video frame boundary.
// The BASIC startup enabled vertical IRQs; wait for two before measuring.
asm {
sync
sync
}
// Non-playing calls must leave the marker on the two DACs.
orch90_write(32, 96);
if (!orch90_play(0, 0, clock) || orch90_play(0, 1, clock) ||
orch90_play(leftBlock, FRAMES, 9) ||
orch90_play((const struct orch90_frame *)0xffff, 1, clock))
fail();
if (!orch90_play(leftBlock, FRAMES, clock) ||
!orch90_play(rightBlock, FRAMES, clock))
fail();
orch90_write(0, 0);
}
int main(void)
{
unsigned i;
for (i = 0; i < FRAMES; ++i) {
unsigned char level = (i & 8) ? 64 : 128;
leftBlock[i].left = level;
rightBlock[i].right = level;
}
playBothSides(ORCH90_CLOCK_NORMAL);
playBothSides(ORCH90_CLOCK_FAST);
orch90_write(16, 80);
for (;;) {} // Leave a stable, distinguishable success marker for the test.
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Exercise guest C printer output and compare the emulator's raw captured bytes."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="save a real guest screen as a PNG")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-printer-") as tmp:
work = Path(tmp)
def run(*cmd):
subprocess.run(cmd, cwd=work, env=env, check=True)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
card = work / "card"
card.mkdir()
(card / "startup.cfg").write_text("0=VOL.DSK\n")
for opt in ("-O0", "-O2"):
for source, binary in ((root / "examples/cmoc/manual/flightreport.c", "FLIGHT.BIN"),
(fixture / "qualification.c", "QUAL.BIN")):
run(runtime / "bin/cmoc", "--coco", opt, "-Werror", "--org=2800",
"-o", binary, source, "-lvcccompat")
shutil.copyfile(root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK", card / "VOL.DSK")
run(runtime / "bin/writecocofile", card / "VOL.DSK", "FLIGHT.BIN")
for cpu in ("6809", "6309"):
for profile in ("disk", "rgb-hd", "sdc"):
capture = args.capture and (cpu, opt, profile) == ("6809", "-O2", "disk")
run("./run", roms, cpu, profile, "capture" if capture else "check")
if capture:
run("sips", "-s", "format", "png", "flight.ppm", "--out", args.capture.resolve())
print(f"PASS {cpu} {opt} {profile}: direct and disk launch, capture off/on, raw flight report, "
"variadic formatting, device and console hook restoration, BASIC return", flush=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <coco.h>
#include <stdarg.h>
#include <vcc/printer.h>
static int sendArgs(const char *format, ...)
{
va_list args;
va_start(args, format);
int count = vcc_printer_vprintf(format, args);
va_end(args);
return count;
}
/* A custom console hook receives A and must preserve B, X, Y and U. */
static asm void ignoreConsoleCharacter(void)
{
asm { rts }
}
int main(void)
{
const byte *device = (const byte *)0x006F; /* BASIC DEVNUM */
ConsoleOutHook savedHook;
int count, invalid, nullFormat, empty, previousDevicePreserved;
cls(1);
setOutputDevice(DEV_CASSETTE);
savedHook = setConsoleOutHook(ignoreConsoleCharacter);
count = sendArgs("%04u %-4s %c %%\n", 9U, "IO", 'X');
invalid = vcc_printer_printf("PREFIX%f");
nullFormat = vcc_printer_printf(NULL);
empty = vcc_printer_printf("");
previousDevicePreserved = *device == (byte)DEV_CASSETTE;
ConsoleOutHook active = setConsoleOutHook(savedHook);
setOutputDevice(DEV_SCREEN);
if (count != 14 || invalid >= 0 || nullFormat >= 0 || empty != 0 || !previousDevicePreserved ||
active != ignoreConsoleCharacter)
{
printf("FAIL LINE %u COUNT %d\n", (unsigned)__LINE__, count);
return 1;
}
printf("PRINTER CHECKS PASSED\n");
return 0;
}
+67
View File
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
static void sendReport(Session& guest)
{
guest.until("PRESS SPACE TO SEND REPORT");
guest.type(" ");
guest.until("REPORT SENT TO PRINTER PORT");
const auto screen = guest.machine.copyScreenText();
require(screen.find("BLUE SEA") == std::string::npos && screen.find("RED RIDGE") == std::string::npos,
"Printer lines leaked onto the CoCo display");
guest.until("OK");
}
static void checkBytes(const PrinterCapture& printer, const std::string& expected)
{
const auto& actual = printer.bytes();
require(std::string(actual.begin(), actual.end()) == expected && printer.droppedBytes() == 0,
"Unexpected raw printer data (" + std::to_string(actual.size()) + " bytes): " +
std::string(actual.begin(), actual.end()));
}
int main(int argc, char** argv)
{
try {
require(argc == 5, "Usage: run ROMDIR CPU PROFILE CAPTURE");
const auto cpu = std::string(argv[2]) == "6809" ? Processor::MC6809 : Processor::HD6309;
const std::string mode = argv[3];
const auto profile = mode == "disk" ? Profile::fd : mode == "rgb-hd" ? Profile::rgbHD : Profile::sdc;
Session guest(argv[1], "card/VOL.DSK", cpu, profile);
auto& printer = guest.machine.printer();
require(!printer.enabled(), "Capture should start off");
guest.launch("FLIGHT.BIN");
sendReport(guest);
checkBytes(printer, "");
guest.verifyReturn();
guest.type("CLS\r");
printer.setEnabled(true);
guest.launch("FLIGHT.BIN");
sendReport(guest);
const std::string report = "TP-10 FLIGHT REPORT\r01 EARTH BLUE SEA\r02 MARS RED RIDGE\rEND OF REPORT\r";
checkBytes(printer, report);
guest.verifyReturn();
guest.type("CLS\r");
guest.type("LOADM\"FLIGHT\":EXEC\r");
sendReport(guest);
checkBytes(printer, report + report);
if (std::string(argv[4]) == "capture") {
guest.frames(3);
saveActiveFrame(*guest.machine.snapshot().frame, "flight.ppm");
}
guest.verifyReturn();
guest.launch("QUAL.BIN");
guest.until("PRINTER CHECKS PASSED");
guest.verifyReturn();
checkBytes(printer, report + report + "0009 IO X %\rPREFIX");
guest.verifyMedia();
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+77
View File
@@ -0,0 +1,77 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Optional integration check; all ROMs and generated media stay outside Git.
#include "../../src/core/MachineSession.h"
#include "../../src/devices/FD502/Fd502Device.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace VCC::Mac;
using namespace VCC::Devices;
namespace fs = std::filesystem;
static std::vector<std::uint8_t> read(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("Cannot read " + path.string());
return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
}
static void picture(const MachineSession& machine, const fs::path& path) {
const auto frame = machine.snapshot().frame;
if (!frame) throw std::runtime_error("Missing frame");
std::ofstream out(path, std::ios::binary);
out << "P6\n" << Frame::width << ' ' << Frame::height << "\n255\n";
for (auto pixel : frame->pixels) {
out.put(char(pixel >> 16)); out.put(char(pixel >> 8)); out.put(char(pixel));
}
if (!out) throw std::runtime_error("Cannot save capture");
}
int main(int argc, char** argv) {
try {
if (argc != 5) throw std::runtime_error("Usage: run-coco-letters COCO3_ROM DISK_ROM GAME_DSK OUTPUT_DIR");
const auto system = read(argv[1]), diskROM = read(argv[2]), disk = read(argv[3]);
fs::create_directories(argv[4]);
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
const std::string name = cpu == Processor::MC6809 ? "6809" : "6309";
MachineSession machine;
auto floppy = std::make_shared<Fd502Device>(diskROM);
floppy->mount(0, DiskImage::load(disk, true));
machine.cartridges().configure({nullptr, nullptr, nullptr, nullptr, floppy}, true, 4);
MachineConfiguration config; config.processor = cpu; config.ram = 0;
machine.configure(config); machine.setVideoOutput(VideoOutput::RGB);
machine.load(system, cpu); machine.resume();
std::uint64_t audio = 0;
auto advance = [&](unsigned count) {
while (count--) {
machine.advance();
for (const auto sample : machine.takeAudio())
if (sample.left || sample.right) ++audio;
}
};
auto press = [&](unsigned bit) {
machine.setKeyboard(std::uint64_t{1} << bit); advance(8);
machine.setKeyboard(0); advance(8);
};
advance(240);
for (auto bit : {4u, 15u, 19u, 48u}) press(bit); // DOS + Return
advance(1200);
auto text = machine.copyScreenText();
std::cout << name << " title:\n" << text << std::endl;
if (text.find("CoCo Letters") == std::string::npos)
throw std::runtime_error("DOS did not reach the game title");
picture(machine, fs::path(argv[4]) / (name + "-title.ppm"));
press(18); advance(120); // RGB
press(5); advance(120); // Easy
press(21); advance(600); // User plays first
picture(machine, fs::path(argv[4]) / (name + "-board.ppm"));
const auto before = machine.snapshot().frame->pixels;
press(30); advance(60); // Right arrow moves the board cursor.
picture(machine, fs::path(argv[4]) / (name + "-input.ppm"));
if (before == machine.snapshot().frame->pixels)
throw std::runtime_error("Game did not respond to cursor input");
if (!floppy->readEvents(0) || floppy->writeEvents(0) || floppy->image(0)->bytes() != disk)
throw std::runtime_error("Unexpected disk activity or modification");
if (!audio) throw std::runtime_error("No game audio");
std::cout << "PASS " << name << ": 128 KB, DOS title, RGB/Easy/User selection, cursor response; "
<< floppy->readEvents(0) << " reads, no writes, " << audio << " audible samples.\n";
}
} catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; }
}
+44
View File
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Read-only optional ROM check: quickload newly compiled code on both guest CPUs.
#include "../../src/core/MachineSession.h"
#include "../../src/core/tcc1014mmu.h"
#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace VCC::Mac;
static std::vector<std::uint8_t> read(const char* path) {
std::ifstream input(path, std::ios::binary);
if (!input) throw std::runtime_error("Cannot open input");
return {std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
}
int main(int argc, char** argv) {
try {
if (argc < 3 || argc > 5) throw std::runtime_error("Usage: run-compiled COCO3_ROM PROGRAM_BIN [EXPECTED [FRAMES]]");
const int runFrames = argc == 5 ? std::stoi(argv[4]) : 120;
if (runFrames < 1) throw std::runtime_error("Frame count must be positive");
const auto rom=read(argv[1]), binary=read(argv[2]);
bool passed = true;
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
MachineSession machine;
machine.load(rom,cpu);machine.resume();
for(unsigned n=0;n<180;++n)machine.advance();
machine.quickLoad(binary);
for (int n = 0; n < runFrames; ++n) machine.advance();
std::string screen;
for(unsigned n=0;n<512;++n) {
unsigned c=SafeMemRead8(0x400+n)&63;
screen+=char(c<32?c+64:c);
}
const char* name = cpu == Processor::MC6809 ? "6809" : "6309";
const char* expected = argc >= 4 ? argv[3] : "HELLO FROM CMOC";
if (screen.find(expected) == std::string::npos) {
std::cerr << name << " expected " << expected << ", guest screen:\n"
<< machine.copyScreenText() << '\n';
passed = false;
} else {
std::cout << "PASS compiled CMOC program: " << name << '\n';
}
}
return passed ? 0 : 1;
} catch(const std::exception& error) { std::cerr<<error.what()<<'\n'; return 1; }
}
+70
View File
@@ -0,0 +1,70 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build and run the C SDC interface against disposable cards on both guest CPUs."""
import argparse
import hashlib
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def contents(card):
return {p.relative_to(card): hashlib.sha256(p.read_bytes()).digest()
for p in card.rglob("*") if p.is_file()}
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ("runtime", "core", "roms"):
parser.add_argument(name, type=Path)
args = parser.parse_args()
runtime, core, roms = [p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-sdc-sdk-") as temp:
work = Path(temp)
def run(*cmd):
subprocess.run(cmd, cwd=work, env=env, check=True)
card = work / "card"
survey = card / "SURVEY"
survey.mkdir(parents=True)
# More than one hardware directory page. An additional pattern matches
# exactly 16 entries, requiring an empty final block to detect the end.
group = card / "GROUP"
group.mkdir()
(group / "CHILD").mkdir()
for i in range(17):
extension = "TXT" if i < 16 else "BIN"
(group / f"A{i:02}.{extension}").write_bytes(bytes(i + 1))
(group / "A00.TXT").chmod(0o444)
(card / "BAD.DSK").write_bytes(b"bad geometry")
(card / "startup.cfg").write_text("0=BOOT.DSK\n", encoding="ascii")
blank = root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK"
for image, name, data in ((card / "BOOT.DSK", "BOOTMAP.DAT", b"B"),
(survey / "EARTH.DSK", "ROVER.DAT", b"E"),
(survey / "MARS.DSK", "ROVER.DAT", b"M")):
shutil.copyfile(blank, image)
(work / name).write_bytes(data)
run(runtime / "bin/writecocofile", "--binary", image, name)
# The M: firmware command also mounts disk sets when given a directory.
# The C API promises a named image even if a directory has a .DSK suffix.
(card / "BUNDLE.DSK").mkdir()
shutil.copyfile(blank, card / "BUNDLE.DSK/DISK1.DSK")
initial = contents(card)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
for opt in ("-O0", "-O2"):
run(runtime / "bin/cmoc", "--coco", opt, "-Werror", "--org=2800", "-o", "SDCTEST.BIN",
fixture / "qualification.c", "-lsdc", "-lvcccompat", "-ldecbfile")
run("./run", roms, card / "BOOT.DSK", "SDCTEST.BIN")
if contents(card) != initial:
raise AssertionError(f"{opt}: card content changed")
print(f"PASS {opt}: both guest CPUs, original card and floppy bytes verified", flush=True)
if __name__ == "__main__":
main()
+167
View File
@@ -0,0 +1,167 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// A real guest client. The host constructs the card and checks it again afterwards.
#include <cmoc.h>
#include <coco.h>
#include <stdio.h>
#include <vcc/sdc.h>
#define CHECK(x) do { if (!(x)) { printf("FAIL LINE %u\n", (unsigned)__LINE__); return 1; } } while (0)
static SdcEntry entry;
static char overlong[256];
static asm byte irqMask(void)
{
asm {
tfr cc,b
andb #$50
}
}
// Called only between guest operations; preserve every CC bit except IRQ/FIRQ.
static asm void setIrqMask(byte mask)
{
asm {
tfr cc,b
andb #$af
orb 3,s
tfr b,cc
}
}
static int checkMasks(void)
{
static const byte masks[] = { 0, 0x10, 0x40, 0x50 };
byte original = irqMask();
byte i, entered, returned, status;
for (i = 0; i < sizeof(masks); ++i) {
setIrqMask(masks[i]);
entered = irqMask();
status = sdc_probe();
returned = irqMask();
setIrqMask(original);
CHECK(entered == masks[i] && returned == entered && status == SDC_OK);
}
return 0;
}
static int listing(void)
{
unsigned char i, result, index, seen[17], parent = 0, child = 0;
memset(seen, 0, sizeof(seen));
CHECK(sdc_list_begin("/GROUP/*") == SDC_OK);
while ((result = sdc_list_next(&entry)) == SDC_OK) {
if (!strcmp(entry.name, "..")) {
CHECK(entry.attributes & SDC_DIRECTORY);
++parent;
} else if (!strcmp(entry.name, "CHILD")) {
CHECK(entry.attributes & SDC_DIRECTORY);
++child;
} else {
CHECK(strlen(entry.name) == 7 && entry.name[0] == 'A');
index = (entry.name[1] - '0') * 10 + entry.name[2] - '0';
CHECK(index < 17 && !seen[index] && !(entry.attributes & SDC_DIRECTORY));
seen[index] = 1;
CHECK(entry.size == (unsigned long)(index + 1));
CHECK(!!(entry.attributes & SDC_READ_ONLY) == (index == 0));
}
}
CHECK(result == SDC_END && parent == 1 && child == 1);
for (i = 0; i < 17; ++i) CHECK(seen[i]);
CHECK(sdc_list_next(&entry) == SDC_END);
CHECK(sdc_list_begin("/group/*.txt") == SDC_OK);
for (i = 0; i < 16; ++i) CHECK(sdc_list_next(&entry) == SDC_OK);
CHECK(sdc_list_next(&entry) == SDC_END);
CHECK(sdc_list_begin("/GROUP/*.XYZ") == SDC_OK);
CHECK(sdc_list_next(&entry) == SDC_END);
CHECK(sdc_list_begin(NULL) == SDC_OK);
CHECK(sdc_list_next(&entry) == SDC_OK);
// Starting a second enumeration replaces the first.
CHECK(sdc_list_begin("/SURVEY/MARS.DSK") == SDC_OK);
CHECK(sdc_list_next(&entry) == SDC_OK && !strcmp(entry.name, "MARS.DSK"));
CHECK(entry.size == 161280UL && sdc_list_next(&entry) == SDC_END);
return 0;
}
static int readByte(const char *path, int expected)
{
FILE *f = fopen(path, "rb");
CHECK(f && fgetc(f) == expected && fgetc(f) == EOF && feof(f));
CHECK(fclose(f) == 0);
return 0;
}
static int mounts(byte protectedCard)
{
byte *driveOneFAT = (byte *)(0x0800 + 74);
CHECK(sdc_mounted(0, &entry) == SDC_OK && !strcmp(entry.name, "BOOT.DSK"));
CHECK(entry.size == 161280UL && !!(entry.attributes & SDC_READ_ONLY) == protectedCard);
CHECK(sdc_mounted(1, &entry) == SDC_NOT_FOUND);
CHECK(sdc_mount(1, "/survey/earth.dsk") == SDC_OK);
CHECK(sdc_mounted(1, &entry) == SDC_OK && !strcmp(entry.name, "EARTH.DSK"));
CHECK(!readByte("ROVER.DAT:1", 'E'));
CHECK(sdc_mount(1, "/SURVEY/UNKNOWN.DSK") == SDC_NOT_FOUND);
CHECK(sdc_mount(1, "/BAD.DSK") == SDC_INVALID);
CHECK(sdc_mount(1, "/BUNDLE.DSK") == SDC_INVALID);
CHECK(sdc_mount(1, "/SURVEY/MAR*.DSK") == SDC_INVALID);
CHECK(sdc_mount(1, "/SURVEY/MAR") == SDC_INVALID);
CHECK(sdc_mount(1, "/BOOT.DSK") == SDC_IN_USE);
CHECK(sdc_mount(1, "") == SDC_INVALID);
CHECK(sdc_mount(1, NULL) == SDC_INVALID);
CHECK(sdc_mount(2, "/SURVEY/MARS.DSK") == SDC_INVALID);
CHECK(sdc_mounted(2, &entry) == SDC_INVALID);
memset(overlong, 'A', sizeof(overlong) - 1);
CHECK(sdc_mount(1, overlong) == SDC_INVALID);
CHECK(sdc_mounted(1, &entry) == SDC_OK && !strcmp(entry.name, "EARTH.DSK"));
CHECK(!readByte("ROVER.DAT:1", 'E'));
// Independently exercise both DOS cache guards in guest memory.
CHECK(!driveOneFAT[0] && !driveOneFAT[1]);
driveOneFAT[0] = 1;
CHECK(sdc_mount(1, "/SURVEY/MARS.DSK") == SDC_IN_USE);
driveOneFAT[0] = 0;
driveOneFAT[1] = 1;
CHECK(sdc_mount(1, "/SURVEY/MARS.DSK") == SDC_IN_USE);
driveOneFAT[1] = 0;
CHECK(!readByte("ROVER.DAT:1", 'E'));
CHECK(sdc_mount(1, "/SURVEY/MARS.DSK") == SDC_OK);
CHECK(sdc_mounted(1, &entry) == SDC_OK && !strcmp(entry.name, "MARS.DSK"));
CHECK(!readByte("ROVER.DAT:1", 'M') && !readByte("BOOTMAP.DAT:0", 'B'));
return 0;
}
static int unavailable(void)
{
CHECK(sdc_probe() == SDC_UNAVAILABLE);
CHECK(sdc_list_begin("*") == SDC_UNAVAILABLE);
CHECK(sdc_mounted(0, &entry) == SDC_UNAVAILABLE);
CHECK(sdc_mount(0, "/SURVEY/MARS.DSK") == SDC_UNAVAILABLE);
return 0;
}
int main(void)
{
unsigned char choice;
cls(1);
printf("SELECT SDC TEST\n");
choice = waitkey(0);
if (choice == 'T') {
CHECK(sdc_probe() == SDC_TIMEOUT); // Waiting for idle.
CHECK(sdc_mounted(0, &entry) == SDC_TIMEOUT); // Waiting for data.
CHECK(sdc_probe() == SDC_OK);
CHECK(!readByte("BOOTMAP.DAT:0", 'B'));
} else if (choice == 'S' || choice == 'W') {
CHECK(sdc_probe() == SDC_OK);
CHECK(!readByte("BOOTMAP.DAT:0", 'B')); // DOS uses the next sector exactly as requested.
if (checkMasks() || listing() || mounts(choice == 'S')) return 1;
} else {
CHECK(choice == 'F');
if (unavailable()) return 1;
}
printf("SDC CHECKS PASSED\n");
return 0;
}
+108
View File
@@ -0,0 +1,108 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../basic-disk-session.h"
using namespace BasicDiskTests;
static void start(Session& guest, const fs::path& binary, char selection)
{
guest.launch(binary);
guest.until("SELECT SDC TEST");
guest.type(std::string(1, selection));
guest.until("SDC CHECKS PASSED");
}
static void available(const fs::path& roms, const fs::path& disk, Processor cpu,
const fs::path& binary, bool protect)
{
Session guest(roms, disk, cpu, Profile::sdc);
guest.sdc->setWriteProtected(protect);
start(guest, binary, protect ? 'S' : 'W');
const auto state = guest.sdc->snapshot();
require(state.currentDirectory == "/" && state.drives[0].name == "/BOOT.DSK" &&
state.drives[1].name == "/SURVEY/MARS.DSK", "Wrong final SDC mount or current directory");
require(state.drives[1].reads > 0 && !state.drives[1].writes, "Unexpected SDC activity");
guest.verifyReturn();
// SDC-DOS must still be able to take over the controller from the SDK.
guest.type("DIR 1\r");
guest.until("ROVER");
guest.type("DIR 0\r");
guest.until("BOOTMAP");
guest.verifyMedia();
}
static void unavailable(const fs::path& roms, const fs::path& disk, Processor cpu,
const fs::path& binary, bool split)
{
Session guest(roms, disk, cpu, split ? Profile::sdc : Profile::fd);
if (split) {
// The ROM still identifies as SDC while all controller I/O goes to a real FD-502.
guest.floppy = std::make_shared<Fd502Device>(readFile(roms / "disk11.rom"));
guest.floppy->mount(0, DiskImage::load(guest.original));
guest.machine.cartridges().configure({nullptr, nullptr, nullptr, guest.floppy, guest.sdc}, true, 4);
guest.machine.cartridges().writePort(0x7f, 0x32);
}
const auto before = guest.floppy->snapshot();
const auto reads = guest.floppy->readEvents(0);
start(guest, binary, 'F');
const auto after = guest.floppy->snapshot();
require(after.drive == before.drive && after.track == before.track && after.sector == before.sector &&
after.motor == before.motor && before.head == after.head && guest.floppy->readEvents(0) == reads,
"SDC probing touched the FD-502");
const auto& bus = guest.machine.cartridges();
require(bus.romSlot() == 4 && bus.ioSlot() == (split ? 3 : 4), "Guest changed MPI routing");
if (split) guest.machine.cartridges().writePort(0x7f, 0x33);
guest.verifyReturn();
guest.verifyMedia();
}
// Inject a stuck BUSY bit into two otherwise genuine SDC-DOS transactions.
// Leaving command mode permits the next transaction to proceed normally.
class BusyController final : public CartridgeDevice {
public:
explicit BusyController(SDCDevice& device) : sdc(device) {}
unsigned remaining = 2;
void reset() override { sdc.reset(); }
void horizontalSync(DeviceHost& host) override { sdc.horizontalSync(host); }
std::uint8_t readMemory(std::uint16_t address) const override { return sdc.readMemory(address); }
std::uint8_t readPort(std::uint8_t port, DeviceHost& host) override {
return stall && port == 0x48 ? 1 : sdc.readPort(port, host);
}
void writePort(std::uint8_t port, std::uint8_t value, DeviceHost& host) override {
if (port == 0x48 && remaining) stall = true;
if (port == 0x40 && value == 0 && stall) { stall = false; --remaining; }
sdc.writePort(port, value, host);
}
private:
SDCDevice& sdc;
bool stall = false;
};
static void timeout(const fs::path& roms, const fs::path& disk, Processor cpu, const fs::path& binary)
{
Session guest(roms, disk, cpu, Profile::sdc);
auto fault = std::make_shared<BusyController>(*guest.sdc);
guest.machine.cartridges().configure({nullptr, nullptr, nullptr, nullptr, fault}, true, 4);
start(guest, binary, 'T');
require(fault->remaining == 0, "Both timed-out commands must release the controller");
guest.verifyReturn();
guest.verifyMedia();
}
int main(int argc, char** argv)
{
try {
require(argc == 4, "Usage: run ROMS DISK BIN");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
available(argv[1], argv[2], cpu, argv[3], true);
available(argv[1], argv[2], cpu, argv[3], false);
unavailable(argv[1], argv[2], cpu, argv[3], false);
unavailable(argv[1], argv[2], cpu, argv[3], true);
timeout(argv[1], argv[2], cpu, argv[3]);
std::cout << "PASS " << (cpu == Processor::MC6809 ? "6809" : "6309")
<< " SDC-DOS, FD-502, split MPI, stuck BUSY recovery and Disk BASIC reads\n";
}
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 1;
}
}
+48
View File
@@ -0,0 +1,48 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run the stored Speech/Sound API and Book 6 Mission Announcer on the emulator."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="write the actual guest display as a PNG")
parser.add_argument("--audio", type=Path, help="save the emulator's Mission Announcer stereo PCM as a WAV")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
env = dict(os.environ, VCC_CMOC_COMPAT="0", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-announcer-") as temp:
work = Path(temp)
def run(*cmd):
subprocess.run(cmd, cwd=work, env=env, check=True)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
for opt in ("-O0", "-O2"):
run(runtime / "bin/cmoc", "--coco", "--org=2800", opt, "-Werror", "-o", "QUAL.BIN",
fixture / "qualification.c", "-lssc")
run(runtime / "bin/cmoc", "--coco", "--org=2800", opt, "-Werror", "-o", "ANNOUNCE.BIN",
root / "examples/cmoc/manual/announcer.c", "-lssc", "-linput", "-lbcontrol")
shutil.copyfile(root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK", work / "VOL.DSK")
run(runtime / "bin/writecocofile", "VOL.DSK", "ANNOUNCE.BIN")
print(f"Checking {opt}", flush=True)
capture = (args.capture or args.audio) and opt == "-O2"
run("./run", roms, *(["capture"] if capture else []))
if args.audio and opt == "-O2":
shutil.copyfile(work / "announcer.wav", args.audio.resolve())
if args.capture and opt == "-O2":
run("sips", "-s", "format", "png", "announcer.ppm", "--out", args.capture.resolve())
if __name__ == "__main__":
main()
+84
View File
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <coco.h>
#include <cmoc.h>
#include <vcc/ssc.h>
#define POLLS 8192
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u\n", (unsigned)__LINE__); return 1; } } while (0)
static unsigned char codes[62];
static const unsigned char name[] = { SSC_AL_ZZ, SSC_AL_OR, SSC_AL_AX };
static void wait_for_fire_during(unsigned char idle)
{
unsigned int start = getTimer();
while ((unsigned int)(getTimer() - start) < 180) {
if (!(ssc_status() & idle) && !(readJoystickButtons() & JOYSTK_BUTTON_1_RIGHT)) {
printf("FIRE DURING %s\n", idle == SSC_EFFECT_IDLE ? "ALERT" : "NAME");
return;
}
}
}
int main(void)
{
unsigned char i;
unsigned int saved;
for (i = 0; i < sizeof(codes); ++i)
codes[i] = i + 2; // Include 63 at the last usable position.
CHECK(ssc_store_allophones(8, name, 3, POLLS) == SSC_INVALID);
CHECK(ssc_store_allophones(0, 0, 3, POLLS) == SSC_INVALID);
CHECK(ssc_store_allophones(0, name, 0, POLLS) == SSC_INVALID);
CHECK(ssc_store_allophones(0, name, 63, POLLS) == SSC_INVALID);
CHECK(ssc_store_allophones(0, name, 256, POLLS) == SSC_INVALID);
codes[61] = 64;
CHECK(ssc_store_allophones(0, codes, 62, POLLS) == SSC_INVALID);
codes[61] = 63;
CHECK(ssc_play_allophones(8, POLLS) == SSC_INVALID);
CHECK(ssc_store_phrase(8, "OK", POLLS) == SSC_INVALID);
CHECK(ssc_store_phrase(1, 0, POLLS) == SSC_INVALID);
CHECK(ssc_store_phrase(1, "", POLLS) == SSC_INVALID);
CHECK(ssc_store_phrase(1, "A\rB", POLLS) == SSC_INVALID);
CHECK(ssc_play_phrase(8, POLLS) == SSC_INVALID);
CHECK(ssc_store_phrase(1, "OK", 0) == SSC_TIMEOUT);
CHECK(ssc_play_phrase(1, 0) == SSC_TIMEOUT);
CHECK(ssc_store_enveloped_tone(8, 0, 1, 0, 1, 1, POLLS) == SSC_INVALID);
CHECK(ssc_store_enveloped_tone(0, 3, 1, 0, 1, 1, POLLS) == SSC_INVALID);
CHECK(ssc_store_enveloped_tone(0, 0, 0, 0, 1, 1, POLLS) == SSC_INVALID);
CHECK(ssc_store_enveloped_tone(0, 0, 4096, 0, 1, 1, POLLS) == SSC_INVALID);
CHECK(ssc_store_enveloped_tone(0, 0, 1, 16, 1, 1, POLLS) == SSC_INVALID);
CHECK(ssc_store_enveloped_tone(0, 0, 1, 0, 0, 1, POLLS) == SSC_INVALID);
CHECK(ssc_play_stored_effect(8, POLLS) == SSC_INVALID);
CHECK(ssc_store_allophones(0, name, 1, 0) == SSC_TIMEOUT);
CHECK(ssc_play_allophones(0, 0) == SSC_TIMEOUT);
CHECK(ssc_store_enveloped_tone(0, 0, 1, 0, 1, 0, 0) == SSC_TIMEOUT);
CHECK(ssc_play_stored_effect(0, 0) == SSC_TIMEOUT);
saved = ssc_route_audio();
if (ssc_store_allophones(7, codes, sizeof(codes), POLLS) == SSC_TIMEOUT) {
ssc_restore_audio(saved);
printf("NO SPEECH CART\n");
return 0;
}
CHECK(ssc_store_allophones(0, name, sizeof(name), POLLS) == SSC_OK);
CHECK(ssc_store_phrase(7, "mars", POLLS) == SSC_OK); // Replaces the long allophone buffer.
CHECK(ssc_store_enveloped_tone(7, 2, 4095, 15, 65535, 255, POLLS) == SSC_OK);
CHECK(ssc_store_enveloped_tone(0, 0, 250, SSC_ENV_DECAY, 4096, 60, POLLS) == SSC_OK);
printf("BANKS LOADED\n");
waitkey(FALSE);
CHECK(ssc_play_allophones(0, POLLS) == SSC_OK);
wait_for_fire_during(SSC_SPEECH_IDLE);
printf("ALERT READY\n");
waitkey(FALSE);
CHECK(ssc_play_stored_effect(0, POLLS) == SSC_OK);
wait_for_fire_during(SSC_EFFECT_IDLE);
printf("REPLAY READY\n");
waitkey(FALSE);
CHECK(ssc_play_allophones(0, POLLS) == SSC_OK);
printf("TEXT READY\n");
waitkey(FALSE);
CHECK(ssc_play_phrase(7, POLLS) == SSC_OK);
ssc_restore_audio(saved);
printf("BANKS PASSED\n");
return 0;
}
+191
View File
@@ -0,0 +1,191 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../ssc/session.h"
#include "../guest-captures.h"
// A passive second MPI slot records commands in bus order. The real SSC
// supplies every status read, runs both ROMs and produces the captured audio.
struct CommandLog final : CartridgeDevice {
Bytes bytes;
void reset() override { bytes.clear(); }
void horizontalSync(DeviceHost&) override {}
std::uint8_t readMemory(std::uint16_t) const override { return 0xff; }
std::uint8_t readPort(std::uint8_t, DeviceHost&) override { return 0; }
void writePort(std::uint8_t port, std::uint8_t value, DeviceHost&) override {
if (port == 0x7e) bytes.push_back(value);
}
};
template<class Predicate>
static void waitUntil(Session& run, Predicate done, const char* failure) {
for (unsigned i = 0; i < 360; ++i) {
if (done()) return;
run.tick();
}
throw std::runtime_error(std::string(failure) + "\n" + run.machine.copyScreenText());
}
static void frames(Session& run, unsigned count) {
while (count--) run.tick();
}
static void fire(Session& run, bool pressed) {
run.machine.setJoystick(0, 8191, 8191, pressed ? 1 : 0, 0);
}
static void awaitSpeech(Session& run, unsigned baseline) {
waitUntil(run, [&] {
return run.ssc->diagnostics().AldSpeechCount() > baseline &&
!(run.machine.cartridges().readPort(0x7e) & 0x40);
}, "The speech chip never began a new phoneme");
}
static float amplitude(const std::vector<StereoSample>& pcm, std::size_t first, std::size_t last) {
require(first < last && last <= pcm.size(), "Empty PCM measurement");
auto range = std::minmax_element(pcm.begin() + first, pcm.begin() + last,
[](const auto& a, const auto& b) { return a.left < b.left; });
return range.second->left - range.first->left;
}
static Bytes expectedBanks() {
Bytes writes{0xb7};
for (unsigned i = 2; i <= 63; ++i) writes.push_back(i);
writes.insert(writes.end(), {
0, 0xff,
0xb0, 43, 58, 15, 0, 0xff, // SP0256 ZZ, OR, AX, PA1
0x97, 'M', 'A', 'R', 'S', ' ', 13,
0x9f, 0x6f, 255, 255, 0, 0x50, 15, 255, 255, 0x6f, 255, 255, 0, 0x40, 15, 255, 0, 255,
0x98, 0x60, 16, 0, 0, 0x10, 0, 250, 60, 0x60, 16, 0, 0, 0, 0, 250, 0, 255
});
return writes;
}
static void qualify(Session& run, const Bytes& guest, CommandLog& log) {
log.bytes.clear();
run.launch(guest);
run.until("BANKS LOADED");
frames(run, 20);
auto expected = expectedBanks();
require(log.bytes == expected, "Invalid input wrote a byte or a stored packet was malformed");
const auto& chip = run.ssc->diagnostics();
require(chip.AldSpeechCount() == 0, "Loading a slot played it");
run.press(1);
awaitSpeech(run, 0);
fire(run, true);
run.until("FIRE DURING NAME");
run.until("ALERT READY");
fire(run, false);
frames(run, 120); // isolate the tone from the earlier phrase
require(chip.AldSpeechCount() == 3, "Unexpected stored pronunciation length");
run.machine.setKeyboard(std::uint64_t{1} << 2);
waitUntil(run, [&] { return !(run.machine.cartridges().readPort(0x7e) & 0x20); },
"Stored envelope never raised the sound activity signal");
run.machine.setKeyboard(0);
const auto start = run.audio.size();
fire(run, true);
run.until("FIRE DURING ALERT", 30);
fire(run, false);
run.until("REPLAY READY");
frames(run, 7);
const auto middle = run.audio.size();
frames(run, 14);
const auto late = run.audio.size();
frames(run, 40);
const auto tail = run.audio.size();
frames(run, 10);
const auto earlyAmplitude = amplitude(run.audio, start, middle);
const auto laterAmplitude = amplitude(run.audio, late, tail);
const auto tailAmplitude = amplitude(run.audio, tail, run.audio.size());
require(earlyAmplitude > 0.02f && laterAmplitude < earlyAmplitude * 0.7f && tailAmplitude < 0.01f,
"Expected a loud attack, a softer envelope and silence: " + std::to_string(earlyAmplitude) +
", " + std::to_string(laterAmplitude) + ", " + std::to_string(tailAmplitude));
require((run.machine.cartridges().readPort(0x7e) & 0x20) != 0, "SAC stayed active after the effect");
run.press(3);
run.until("TEXT READY");
frames(run, 150);
require(chip.AldSpeechCount() == 6, "One-byte replay did not reproduce the first pronunciation");
run.press(4);
run.until("BANKS PASSED");
frames(run, 150);
require(chip.AldSpeechCount() > 6 && chip.CpuIllegalCount() == 0, "English phrase failed");
expected.insert(expected.end(), {0xf0, 0xd8, 0xf0, 0xd7});
require(log.bytes == expected, "Replay rewrote a stored buffer");
std::cout << " " << log.bytes.size() << " commands, " << chip.AldSpeechCount()
<< " phonemes, envelope peak-to-peak " << earlyAmplitude << " -> "
<< laterAmplitude << " -> " << tailAmplitude << '\n';
}
static void bookExercise(Session& run, bool fromDisk, bool capture) {
if (fromDisk)
run.diskExec(readFile("VOL.DSK"), "ANNOUNCE");
else
run.launch(readFile("ANNOUNCE.BIN"));
run.until("Q RETURN TO BASIC", 1200);
run.audio.clear();
const auto& chip = run.ssc->diagnostics();
run.press(34); // 2: English text in its own slot
awaitSpeech(run, 0);
frames(run, 180);
auto baseline = chip.AldSpeechCount();
require(baseline > 3, "WELCOME ABOARD never spoke");
run.press(33); // 1: invented planet name
run.until("APPROACHING ZORA");
awaitSpeech(run, baseline);
fire(run, true);
run.until("LANDING ALERT 1", 30);
frames(run, 50);
require(!run.contains("LANDING ALERT 2"), "Holding fire repeated the alert");
fire(run, false);
frames(run, 5);
fire(run, true);
run.until("LANDING ALERT 2", 30);
fire(run, false);
frames(run, 70);
require(chip.AldSpeechCount() == baseline + 3, "Joystick input interrupted the announcement");
run.checkSignal(0);
if (capture) {
BasicDiskTests::saveActiveFrame(*run.machine.snapshot().frame, "announcer.ppm");
saveWav("announcer.wav", run.audio);
}
run.press(17); // Q
run.until("OK");
frames(run, 12);
run.press(47, true); run.press(39); run.press(43, true); run.press(35); run.press(48); // ?7+3
run.until(" 10");
if (fromDisk)
require(run.floppy->readEvents(0) > 0 && run.floppy->writeEvents(0) == 0, "Unexpected demo disk I/O");
}
int main(int argc, char** argv) {
try {
require(argc == 2 || argc == 3, "Usage: run ROM_DIRECTORY [capture]");
const fs::path rom(argv[1]);
const auto system = readFile(rom / "coco3.rom"), disk = readFile(rom / "disk11.rom");
auto chips = readFile(rom / "pic-7040-510.bin");
auto speech = readFile(rom / "sp0256-al2.bin");
require(chips.size() == 4096 && speech.size() == 2048, "Missing Speech/Sound firmware");
chips.insert(chips.end(), speech.begin(), speech.end());
const auto guest = readFile("QUAL.BIN");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
std::cout << (cpu == Processor::MC6809 ? "6809" : "6309") << std::endl;
{
auto log = std::make_shared<CommandLog>();
Session fixture(cpu, system, disk, std::make_shared<SpeechSoundDevice>(chips), false, log);
qualify(fixture, guest, *log);
}
{
Session absent(cpu, system, disk, nullptr);
absent.launch(guest);
absent.until("NO SPEECH CART");
}
for (bool fromDisk : {false, true}) {
Session demo(cpu, system, disk, std::make_shared<SpeechSoundDevice>(chips));
bookExercise(demo, fromDisk, argc == 3 && !fromDisk && cpu == Processor::MC6809);
}
std::cout << " PASS stored banks, joystick during speech and alert, direct and disk launch, BASIC return\n";
}
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
return 1;
}
}
+35
View File
@@ -0,0 +1,35 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run the Speech/Sound C API fixture on both guest CPUs with private local ROMs."""
import argparse
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged Toolchain directory containing libssc.a")
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("roms", type=Path, help="directory with CoCo 3, Disk BASIC, PIC and speech ROMs")
parser.add_argument("--lander", type=Path, help="also run LANDER.bin and LANDER.dsk from this directory")
parser.add_argument("--captures", type=Path, help="directory for the Lander stereo WAVs (requires --lander)")
args = parser.parse_args()
if bool(args.lander) != bool(args.captures):
parser.error("--lander and --captures must be supplied together")
fixture = Path(__file__).resolve().parent
roms = args.roms.resolve()
with tempfile.TemporaryDirectory(prefix="vcc-ssc-") as work:
subprocess.run([args.runtime.resolve() / "bin/cmoc", "--coco", "-O2", "-Werror", "-o", "QUAL.BIN",
fixture / "qualification.c", "-lssc"], cwd=work, check=True)
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
fixture / "run.cpp", args.core.resolve(), "-o", "run-ssc"], cwd=work, check=True)
command = ["./run-ssc", roms / "coco3.rom", roms / "disk11.rom", roms / "pic-7040-510.bin",
roms / "sp0256-al2.bin", "QUAL.BIN"]
if args.lander:
project = args.lander.resolve()
command.extend([project / "LANDER.bin", project / "LANDER.dsk", args.captures.resolve()])
subprocess.run(command, cwd=work, check=True)
if __name__ == "__main__":
main()
+86
View File
@@ -0,0 +1,86 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Run with the accompanying host fixture, once with and once without firmware.
#include <coco.h>
#include <cmoc.h>
#include <vcc/ssc.h>
static void wait_ticks(unsigned int count)
{
unsigned int start = getTimer();
while ((unsigned int)(getTimer() - start) < count) {
asm { nop }
}
}
int main(void)
{
ssc_phrase phrase;
unsigned int start, saved;
unsigned char result, saw_input = 0;
unsigned char low = *(unsigned char *)0xFF01 & 63;
unsigned char high = *(unsigned char *)0xFF03 & 63;
unsigned char sound = *(unsigned char *)0xFF23 & 63;
if (ssc_begin_phrase(&phrase, "") != SSC_INVALID ||
ssc_begin_phrase(&phrase, "123456789012345678901234567890123456789012345678901234567890123") != SSC_INVALID ||
ssc_begin_phrase(&phrase, "BAD\rDATA") != SSC_INVALID ||
ssc_say("TEST", 0) != SSC_TIMEOUT ||
ssc_play_effect(3, 1, 15, 2, 100) != SSC_INVALID ||
ssc_play_noise(0, 32, 15, 2, 100) != SSC_INVALID)
return 1;
saved = ssc_route_audio();
if ((*(unsigned char *)0xFF01 & 63) != ((low & 7) | 0x30) ||
(*(unsigned char *)0xFF03 & 63) != ((high & 7) | 0x38) ||
(*(unsigned char *)0xFF23 & 63) != ((sound & 7) | 0x38))
return 2;
ssc_restore_audio(saved);
if ((*(unsigned char *)0xFF01 & 63) != low || (*(unsigned char *)0xFF03 & 63) != high ||
(*(unsigned char *)0xFF23 & 63) != sound)
return 3;
saved = ssc_route_audio();
result = ssc_say("blue planet earth", 8192);
if (result == SSC_TIMEOUT) {
printf("SSC UNAVAILABLE\n");
ssc_restore_audio(saved);
return 0;
}
if (result != SSC_OK)
return 4;
printf("FIRST SUBMITTED\n");
start = getTimer();
while ((unsigned int)(getTimer() - start) < 180) {
if (!(ssc_status() & SSC_SPEECH_IDLE) && !(readJoystickButtons() & JOYSTK_BUTTON_1_RIGHT)) {
if (readJoystickPositions()[JOYSTK_RIGHT_HORIZ] > 50)
saw_input = 1;
ssc_route_audio();
}
}
if (!saw_input)
return 5;
printf("INPUT DURING SPEECH\n");
if (ssc_begin_phrase(&phrase, "cold red mars") != SSC_OK)
return 6;
start = getTimer();
while ((result = ssc_service(&phrase)) == SSC_PENDING) {
if ((unsigned int)(getTimer() - start) >= 120)
return 7;
}
if (result != SSC_OK || ssc_service(&phrase) != SSC_OK)
return 8;
printf("SECOND SUBMITTED\n");
wait_ticks(180);
printf("TONE TEST\n");
if (ssc_play_effect(0, 250, 12, 8, 8192) != SSC_OK)
return 9;
wait_ticks(60);
printf("NOISE TEST\n");
if (ssc_play_noise(2, 16, 12, 8, 8192) != SSC_OK)
return 10;
wait_ticks(60);
ssc_restore_audio(saved);
printf("SSC API PASSED\n");
return 0;
}
+128
View File
@@ -0,0 +1,128 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "session.h"
static void checkGuest(Session& run, const Bytes& guest, bool present) {
run.launch(guest);
if (!present) {
run.until("SSC UNAVAILABLE");
return;
}
run.until("FIRST SUBMITTED");
run.machine.setJoystick(0, 16383, 8191, 1, 0); // move right and press fire during speech
run.until("INPUT DURING SPEECH");
run.machine.setJoystick(0, 8191, 8191, 0, 0);
auto& diagnostics = run.ssc->diagnostics();
auto first = diagnostics.AldSpeechCount();
require(first >= 4, "First phrase did not produce phonemes");
run.until("SECOND SUBMITTED");
run.until("TONE TEST");
require(diagnostics.AldSpeechCount() >= first + 4, "Second phrase did not produce phonemes");
const auto toneStart = run.audio.size();
run.until("NOISE TEST");
run.checkSignal(toneStart);
const auto noiseStart = run.audio.size();
run.until("SSC API PASSED");
run.checkSignal(noiseStart);
require(diagnostics.CpuIllegalCount() == 0, "Illegal speech firmware instruction");
// Each phrase includes a trailing space and CR, followed by the complete
// 11-byte tone / 9-byte noise packets. Invalid calls must do no writes.
const unsigned expected = 17 + 2 + 13 + 2 + 11 + 9;
require(diagnostics.CommandCount() == expected,
"Unexpected number of guest writes: " + std::to_string(diagnostics.CommandCount()));
}
static void checkLander(Session& run, const Bytes& bin, const Bytes& disk, bool bootDisk, const fs::path& wav) {
if (bootDisk)
run.diskExec(disk, "LANDER");
else
run.launch(bin);
run.until("2 MARS", 1200);
run.audio.clear(); // Start the listening capture at the planet choice, after Disk BASIC setup.
run.press(bootDisk ? 34 : 33); // Mars on disk, Earth on direct Run
run.until(bootDisk ? "DESTINATION MARS" : "DESTINATION EARTH");
for (unsigned f = 0; f < 300 && run.ssc->diagnostics().AldSpeechCount() < 2; ++f) run.tick();
require(run.ssc->diagnostics().AldSpeechCount() >= 2, "First Lander phrase did not begin");
run.machine.setJoystick(0, 8191, 8191, 1, 0);
run.until("THRUST", 60);
run.machine.setJoystick(0, 8191, 8191, 0, 0);
run.until("TOUCHDOWN", 1200);
run.until("OK", 120); // Normal Direct Run and EXEC must both return to BASIC.
for (unsigned i = 0; i < 90; ++i) run.tick();
run.checkSignal(0);
require(std::count_if(run.audio.begin(), run.audio.end(), [](auto sample) {
return std::fabs(sample.left - sample.right) > 0.01f;
}) > 100, "No stereo beacon from Orchestra-90");
const auto& chip = run.ssc->diagnostics();
// Each string is followed by one space and one carriage return.
const unsigned expected = std::string(bootDisk ? "DESTINATION MARS" : "DESTINATION EARTH").size()
+ std::string("LANDING COMPLETE").size() + 4;
require(chip.CommandCount() == expected && chip.AldSpeechCount() >= 12 &&
chip.CpuIllegalCount() == 0, "Incomplete Lander speech");
if (bootDisk)
require(run.floppy->readEvents(0) > 0 && run.floppy->writeEvents(0) == 0, "Unexpected disk I/O");
saveWav(wav, run.audio);
std::cout << wav.filename() << ": " << chip.AldSpeechCount() << " phonemes, "
<< chip.CommandCount() << " submitted bytes, " << run.audio.size() << " frames\n";
}
// A single sound cartridge or a disk-only machine still completes the mission.
// Ask BASIC to compute a new result after the guest returns.
static void checkOptionalCartridges(Session& run, const Bytes& binary, bool hasStereo) {
run.launch(binary);
run.until("2 MARS");
run.audio.clear();
run.press(33);
run.until("DESTINATION EARTH");
run.until("TOUCHDOWN", 1200);
run.until("OK");
run.press(47, true); // ? (PRINT)
run.press(39); // 7
run.press(43, true); // +
run.press(35); // 3
run.press(48);
run.until("10");
const bool stereo = std::any_of(run.audio.begin(), run.audio.end(), [](auto frame) {
return std::fabs(frame.left - frame.right) > 0.01f;
});
require(stereo == hasStereo, "Unexpected channel activity with optional cartridges");
if (run.ssc) require(run.ssc->diagnostics().CommandCount() == 37, "Speech-only landing missed a phrase");
}
int main(int argc, char** argv) {
try {
if (argc != 6 && argc != 9)
throw std::runtime_error("Usage: run-ssc SYSTEM_ROM DISK_ROM PIC_ROM SPEECH_ROM QUAL.BIN [LANDER.BIN LANDER.DSK WAV_DIRECTORY]");
const auto system = readFile(argv[1]), diskRom = readFile(argv[2]), speech = readFile(argv[4]);
auto chips = readFile(argv[3]);
require(chips.size() == 4096 && speech.size() == 2048, "SSC needs both exact size chip images");
chips.insert(chips.end(), speech.begin(), speech.end());
const auto guest = readFile(argv[5]);
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
const std::string label = cpu == Processor::MC6809 ? "6809" : "6309";
for (auto device : {std::shared_ptr<SpeechSoundDevice>{}, std::make_shared<SpeechSoundDevice>(),
std::make_shared<SpeechSoundDevice>(chips)}) {
Session run(cpu, system, diskRom, device);
checkGuest(run, guest, device && device->ready());
}
std::cout << "PASS " << label << " absence, missing firmware, two phrases, joystick, tones and noise\n";
if (argc == 9) {
const auto binary = readFile(argv[6]);
for (int setup = 0; setup < 3; ++setup) {
auto speechOnly = setup == 1 ? std::make_shared<SpeechSoundDevice>(chips) : nullptr;
Session optional(cpu, system, diskRom, speechOnly, setup == 2);
checkOptionalCartridges(optional, binary, setup == 2);
}
std::cout << "PASS " << label << " disk-only, speech-only and stereo-only landings and BASIC return\n";
fs::create_directories(argv[8]);
for (bool bootDisk : {false, true}) {
Session run(cpu, system, diskRom, std::make_shared<SpeechSoundDevice>(chips), true);
const auto file = "talking-lander-" + label + (bootDisk ? "-disk.wav" : "-direct.wav");
checkLander(run, readFile(argv[6]), readFile(argv[7]), bootDisk, fs::path(argv[8]) / file);
}
}
}
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+111
View File
@@ -0,0 +1,111 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Real ROM boot, CMOC development launch, PIA input and guest audio.
#include "../../../src/core/MachineSession.h"
#include "../../../src/devices/FD502/Fd502Device.h"
#include "../../../src/devices/SpeechSoundDevice.h"
#include "../../../src/devices/Orchestra90Device.h"
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace VCC::Mac;
using namespace VCC::Devices;
namespace fs = std::filesystem;
using Bytes = std::vector<std::uint8_t>;
static Bytes readFile(const fs::path& path) {
std::ifstream file(path, std::ios::binary);
if (!file) throw std::runtime_error("Cannot open " + path.string());
return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
}
static void require(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
struct Session {
MachineSession machine;
std::shared_ptr<Fd502Device> floppy;
std::shared_ptr<SpeechSoundDevice> ssc;
std::vector<StereoSample> audio;
Session(Processor cpu, const Bytes& system, const Bytes& diskRom,
std::shared_ptr<SpeechSoundDevice> cartridge, bool useOrchestra = false,
std::shared_ptr<CartridgeDevice> observer = nullptr)
: floppy(std::make_shared<Fd502Device>(diskRom)), ssc(std::move(cartridge)) {
auto orchestra = useOrchestra ? std::make_shared<Orchestra90Device>() : nullptr;
machine.cartridges().configure({nullptr, ssc, orchestra, observer, floppy}, true, 4);
machine.load(system, cpu);
machine.resume();
for (unsigned n = 0; n < 180; ++n) machine.advance();
machine.takeAudio();
require(contains("DISK EXTENDED"), "FD-502 in startup slot 4 did not boot Disk BASIC");
}
bool contains(const std::string& text) { return machine.copyScreenText().find(text) != std::string::npos; }
void tick() {
machine.advance();
auto samples = machine.takeAudio();
audio.insert(audio.end(), samples.begin(), samples.end());
}
void until(const std::string& text, unsigned maxFrames = 360) {
for (unsigned i = 0; i < maxFrames; ++i) {
if (contains(text)) return;
tick();
}
throw std::runtime_error("Timed out waiting for " + text + "\n" + machine.copyScreenText());
}
void launch(const Bytes& binary) {
require(binary.size() >= 5, "Incomplete binary");
auto entry = std::uint16_t(binary[binary.size() - 2] << 8 | binary.back());
machine.debuggerLoadBinary(binary, entry);
machine.debuggerClearDevelopmentBreakpoints();
machine.resume();
}
void press(unsigned bit, bool shift = false) {
machine.setKeyboard((std::uint64_t{1} << bit) | (std::uint64_t(shift) << 55));
for (int i = 0; i < 6; ++i) tick();
machine.setKeyboard(0);
for (int i = 0; i < 6; ++i) tick();
}
void diskExec(const Bytes& disk, const std::string& basename) {
floppy->mount(0, DiskImage::load(disk, true));
for (char c : "LOADM\"" + basename + "\":EXEC\r") {
if (c == '"') press(34, true);
else if (c == ':') press(42);
else if (c == '\r') press(48);
else if (c >= 'A' && c <= 'Z') press(c - '@');
else throw std::logic_error("Unsupported fixture key");
}
}
void checkSignal(std::size_t from) const {
require(from < audio.size(), "Missing PCM samples");
auto range = std::minmax_element(audio.begin() + from, audio.end(),
[](auto a, auto b) { return a.left < b.left; });
require(range.second->left - range.first->left > 0.02f, "Expected audible output");
}
};
static void saveWav(const fs::path& path, const std::vector<StereoSample>& pcm) {
std::ofstream file(path, std::ios::binary);
auto little = [&](unsigned value, unsigned bytes) {
while (bytes--) { file.put(char(value)); value >>= 8; }
};
const unsigned size = unsigned(pcm.size()) * 4;
file.write("RIFF", 4); little(36 + size, 4); file.write("WAVEfmt ", 8);
little(16, 4); little(1, 2); little(2, 2); little(44100, 4); little(176400, 4);
little(4, 2); little(16, 2); file.write("data", 4); little(size, 4);
for (auto sample : pcm) {
for (float value : {sample.left, sample.right}) {
const auto converted = std::lround(value * 32767.0f);
little(static_cast<std::uint16_t>(std::clamp(converted, -32768l, 32767l)), 2);
}
}
if (!file) throw std::runtime_error("Cannot save " + path.string());
}
@@ -0,0 +1,65 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Test the recoverable save in Book 6's return-trip lesson on each Disk BASIC storage setup."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="save the completed Mars flight and a companion -retry PNG")
args = parser.parse_args()
runtime, core, roms = [p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
blank = root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK"
source = root / "examples/cmoc/manual/returntrip.c"
tool = runtime / "bin/writecocofile"
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
earth = b"VISIT 1: EARTH\r"
mars = earth + b"VISIT 2: MARS\r"
with tempfile.TemporaryDirectory(prefix="vcc-return-trip-") as tmp:
work = Path(tmp)
def run(*command, **kwargs):
return subprocess.run(command, cwd=work, env=env, check=True, **kwargs)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "returntrip.cpp", core, "-o", "run")
(work / "TRIP.LOG").write_bytes(b"ANOTHER CREW'S FLIGHT PLAN\r")
shutil.copyfile(blank, work / "other.dsk")
run(tool, "--binary", "other.dsk", "TRIP.LOG")
for folder in ("card", "other"):
(work / folder).mkdir()
(work / folder / "startup.cfg").write_text("0=VOL.DSK\n")
for opt in ("-O0", "-O2"):
run(runtime / "bin/cmoc", "--coco", opt, "-Werror", "--org=2800", "-o", "TRIP.BIN",
source, "-lvcccompat", "-ldecbfile")
shutil.copyfile(blank, work / "launch.dsk")
run(tool, "launch.dsk", "TRIP.BIN")
for cpu in ("6809", "6309"):
for profile in ("disk", "rgb-hd", "sdc"):
shutil.copyfile(work / "launch.dsk", work / "card/VOL.DSK")
shutil.copyfile(work / "other.dsk", work / "other/VOL.DSK")
capture = args.capture and (cpu, opt, profile) == ("6809", "-O2", "disk")
run("./run", roms, "TRIP.BIN", cpu, profile, "capture" if capture else "check")
for disk, expected in (("earth.dsk", earth), ("mars.dsk", mars)):
actual = run(tool, "--stdout", disk, "TRIP.LOG", stdout=subprocess.PIPE).stdout
if actual != expected:
raise AssertionError(f"{cpu} {opt} {profile} {disk}: {actual!r}")
if capture:
for suffix in ("", "-retry"):
target = args.capture.with_stem(args.capture.stem + suffix)
run("sips", "-s", "format", "png", f"trip{suffix}.ppm", "--out", target.resolve())
print(f"PASS {cpu} {opt} {profile}: Earth, protected quit and refusal, successful flush retry, "
"exact Earth and Mars bytes, completed trip, unrelated file, BASIC return", flush=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,56 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run the C book's field log exercise, inspect its flushed disk and try its append edit."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--capture", type=Path, help="write a PNG of the completed first survey")
args = parser.parse_args()
runtime, core, roms = [p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)]
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
example = root / "examples/cmoc/manual/fieldlog.c"
blank = root / "docs/manuals/software-storage-and-peripherals/media/BLANK.DSK"
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-field-log-") as tmp:
work = Path(tmp)
def run(*command, **kwargs):
return subprocess.run(command, cwd=work, env=env, check=True, **kwargs)
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", "run")
original = example.read_text()
edit = 'fopen(LOG_NAME, "w")'
assert original.count(edit) == 1, "The lesson's append edit no longer matches the source"
(work / "append.c").write_text(original.replace(edit, 'fopen(LOG_NAME, "a")'))
for opt in ("-O0", "-O2"):
for src, binary in ((example, "LOG.BIN"), ("append.c", "APPEND.BIN")):
run(runtime / "bin/cmoc", "--coco", opt, "-Werror", "--org=2800",
"-o", binary, src, "-lvcccompat", "-ldecbfile")
capture = args.capture and opt == "-O2"
run("./run", roms, blank, "LOG.BIN", "APPEND.BIN", "capture" if capture else "check")
for cpu in ("6809", "6309"):
first, second = b"EARTH: BLUE SEA\r", b"MARS: RED RIDGE\r"
for mode, prior in (("fresh", b""), ("append", first + second)):
for stage, expected in (("checkpoint", prior + first), ("closed", prior + first + second)):
disk = f"{cpu}-{mode}-{stage}.dsk"
actual = run(runtime / "bin/writecocofile", "--stdout", disk, "FIELD.LOG",
stdout=subprocess.PIPE).stdout
if actual != expected:
raise RuntimeError(f"{disk}: expected {expected!r}, got {actual!r}")
print(f"PASS {opt}: fresh/append, independent disk read before/after close, protection, BASIC return", flush=True)
if capture:
run("sips", "-s", "format", "png", "log.ppm", "--out", args.capture.resolve())
if __name__ == "__main__":
main()
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
static void visit(const fs::path& roms, const fs::path& binary, Processor cpu, Profile profile, bool capture)
{
Session guest(roms, "card/VOL.DSK", cpu, profile);
guest.launch(binary);
guest.until("AT BYTE ZERO\nFILING EARTH\nREOPENED TRIP.LOG\nVISIT 1: EARTH");
guest.verifyReturn();
saveVolume(guest, "earth.dsk");
setVolumeProtected(guest, true);
const auto earth = volume(guest);
const std::string prompt = "R: RETRY Q: QUIT";
guest.launch(binary);
guest.until(prompt);
guest.type("Q");
guest.until("CHECK DISK AND LOG");
guest.verifyReturn();
require(volume(guest) == earth, "Protected trip changed the disk");
// Run the disk copy and leave this Mars flight waiting in the guest.
guest.type("CLS\r");
require(guest.machine.copyScreenText().find(prompt) == std::string::npos, "Old retry prompt is still visible");
guest.type("LOADM\"TRIP\":EXEC\r");
guest.until(prompt);
if (capture) {
guest.frames(3);
saveActiveFrame(*guest.machine.snapshot().frame, "trip-retry.ppm");
}
guest.type("R");
guest.until("RETRYING SAVE\nSAVE FAILED\nKEEP THE SAME DISK IN DRIVE 0\nIF PROTECTED, TURN PROTECT OFF\n" + prompt);
require(volume(guest) == earth, "Retry while protected changed the disk");
setVolumeProtected(guest, false);
// The learner returns from changing protection in the host. Let the
// ROM observe the released key before the learner presses R again.
guest.frames(30);
guest.type("R");
guest.until("REOPENED TRIP.LOG\nVISIT 1: EARTH\nVISIT 2: MARS");
guest.until("OK");
if (capture) {
guest.frames(3);
saveActiveFrame(*guest.machine.snapshot().frame, "trip.ppm");
}
guest.verifyReturn();
saveVolume(guest, "mars.dsk");
const auto mars = volume(guest);
guest.launch(binary);
guest.until("BOTH VISITS ALREADY FILED\nREOPENED TRIP.LOG\nVISIT 1: EARTH\nVISIT 2: MARS");
guest.verifyReturn();
require(volume(guest) == mars, "Third trip changed a completed log");
}
int main(int argc, char** argv)
{
try {
require(argc == 6, "Usage: returntrip ROMDIR BIN CPU PROFILE CAPTURE");
const auto cpu = std::string(argv[3]) == "6809" ? Processor::MC6809 : Processor::HD6309;
const std::string mode = argv[4];
const auto profile = mode == "disk" ? Profile::fd : mode == "rgb-hd" ? Profile::rgbHD : Profile::sdc;
visit(argv[1], argv[2], cpu, profile, std::string(argv[5]) == "capture");
Session other(argv[1], "other/VOL.DSK", cpu, profile);
other.launch(argv[2]);
other.until("UNRECOGNIZED TRIP.LOG\nCHECK DISK AND LOG");
other.verifyReturn();
require(volume(other) == other.original, "Trip changed an unrelated file");
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 1;
}
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
int main(int argc, char** argv)
{
try {
require(argc == 6, "Usage: run ROMDIR DISK BIN APPEND_BIN CAPTURE");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
Session session(argv[1], argv[2], cpu, Profile::fd);
std::string prefix = cpu == Processor::MC6809 ? "6809-" : "6309-";
// First run starts a fresh log. The lesson's one-character edit appends on the second.
for (const auto& mode : {"fresh", "append"}) {
const bool append = std::string(mode) == "append";
session.type("CLS\r");
session.launch(argv[append ? 4 : 3]);
session.until("SPACE TO LAND ON MARS");
session.until("CHECKPOINT READER SEES:\nEARTH: BLUE SEA");
saveDisk(*session.floppy->image(0), prefix + mode + "-checkpoint.dsk");
session.frames(12);
session.type(" ");
session.until("SURVEY FILED");
session.until("FINAL READER SEES:\nEARTH: BLUE SEA\nMARS: RED RIDGE");
saveDisk(*session.floppy->image(0), prefix + mode + "-closed.dsk");
if (!append && cpu == Processor::MC6809 && std::string(argv[5]) == "capture") {
session.until("OK");
session.frames(4);
saveActiveFrame(*session.machine.snapshot().frame, "log.ppm");
}
session.verifyReturn();
}
session.floppy->setWriteProtected(0, true);
const auto previous = session.floppy->image(0)->bytes();
for (const auto binary : {argv[3], argv[4]}) {
session.type("CLS\r");
session.launch(binary);
// A DOS may detect protection at open or at the first flush.
for (unsigned n = 0; n < 2000; ++n) {
session.frames(1);
const auto text = session.machine.copyScreenText();
if (text.find("CANNOT START FIELD.LOG") != text.npos ||
text.find("CHECK DISK AND LOG") != text.npos) break;
require(n + 1 < 2000, "Expected a protected disk error: " + text);
}
require(previous == session.floppy->image(0)->bytes(), "Protected disk was changed");
session.verifyReturn();
}
// Read the first two records with the resident Disk BASIC ROM.
session.frames(12);
session.machine.basicLoadSource("10 CLS:OPEN \"I\",#1,\"FIELD.LOG\"\n"
"20 LINE INPUT #1,A$:PRINT A$\n"
"30 LINE INPUT #1,A$:PRINT A$\n"
"40 CLOSE #1\n", true);
session.until("EARTH: BLUE SEA\nMARS: RED RIDGE");
session.verifyReturn();
}
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 1;
}
}
+278
View File
@@ -0,0 +1,278 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Qualify Disk BASIC stream writes and positioning against independently decoded volumes."""
import argparse
import os
import shutil
from pathlib import Path
import subprocess
import tempfile
SECTOR = 256
GRANULE = 9 * SECTOR
FAT = (17 * 18 + 1) * SECTOR
TEXT_RECORDS = b"X" * 255 + b"\r\nMARS\rEUROPA\nTITAN\r\n"
SENTINEL = b"previously saved data\x00\r\xff" * 57
FILL = bytes((i * 3 + 11) & 255 for i in range(66 * GRANULE))
DISTANT = bytes((i * 7 + i // SECTOR) & 255 for i in range(65537))
def contents(raw):
"""Decode directory and FAT independently, rejecting leaks, cross-links and cycles."""
files = {}
owners = set()
for row in range(FAT + SECTOR, (17 + 1) * 18 * SECTOR, 32):
entry = raw[row:row + 32]
if entry[0] == 0xff:
break
if entry[0] == 0:
continue
name = entry[:8].decode().rstrip() + "." + entry[8:11].decode().rstrip()
granule = entry[13]
data = bytearray()
while True:
if granule >= 68 or granule in owners:
raise AssertionError(f"{name} references missing or shared granule {granule}")
owners.add(granule)
addr = (granule + (2 if granule >= 34 else 0)) * GRANULE
link = raw[FAT + granule]
if link < 68:
data.extend(raw[addr:addr + GRANULE])
granule = link
continue
count, last = link - 0xc0, int.from_bytes(entry[14:16], "big")
if count not in range(10) or last > SECTOR or (not count and last):
raise AssertionError(f"Invalid final size in {name}: FAT {link} / directory {last}")
length = (count - 1) * SECTOR + last if count else 0
data.extend(raw[addr:addr + length])
break
if name in files:
raise AssertionError(f"Duplicate directory entry {name}")
files[name] = bytes(data)
occupied = {i for i in range(68) if raw[FAT + i] != 255}
if owners != occupied:
raise AssertionError(f"Leaked/missing granules {sorted(owners ^ occupied)}")
return files
def check_files(folder, stage, expected):
actual = contents((folder / (stage + ".dsk")).read_bytes())
if actual != expected:
names = {name for name in actual.keys() | expected.keys() if actual.get(name) != expected.get(name)}
raise AssertionError(f"{stage}: mismatched {[(n, len(actual.get(n,b'')), len(expected.get(n,b''))) for n in names]}")
def fragment_second_granule(raw, filename):
"""Relocate the second granule to the end of the disk without changing the file."""
directory = range(FAT + SECTOR, (17 + 1) * 18 * SECTOR, 32)
entry = next(row for row in directory if raw[row:row + 11] == filename)
head = raw[entry + 13]
second = raw[FAT + head]
unused = 67
assert head < 34 and second < 34 and raw[FAT + unused] == 255
old = second * GRANULE
new = (unused + 2) * GRANULE # Skip track 17 on the way to the final track.
raw[new:new + GRANULE] = raw[old:old + GRANULE]
raw[old:old + GRANULE] = bytes(GRANULE)
raw[FAT + unused] = raw[FAT + second]
raw[FAT + head] = unused
raw[FAT + second] = 255
def write_fixture(folder, tool, scenario):
volume = folder / "VOL.DSK"
volume.write_bytes(b"\xff" * (35 * 18 * SECTOR))
files = {"SAFE.DAT": SENTINEL}
if scenario == "F":
files["FILL.DAT"] = FILL
elif scenario == "W":
files["LOG.BIN"] = b"replace this old chain" * 150
files["DISTANT.DAT"] = DISTANT
if scenario in ("S", "U"):
files.update({"DISTANT.DAT": DISTANT, "RECORDS.TXT": TEXT_RECORDS})
if scenario == "U":
files["RESET.DAT"] = b"old log" * 800
if scenario == "N":
files.update({f"PAD{i}.DAT": bytes([i]) for i in range(7)})
files["DELETE.DAT"] = b"multi-granule" * 400
if scenario == "C":
files["CROSS.DAT"] = b"aliased by fixture"
for name, data in files.items():
(folder / name).write_bytes(data)
subprocess.run([tool, "--binary", volume, name], cwd=folder, check=True)
assert contents(volume.read_bytes()) == files
if scenario in ("S", "U"):
raw = bytearray(volume.read_bytes())
fragment_second_granule(raw, b"DISTANT DAT")
assert contents(raw) == files
volume.write_bytes(raw)
if scenario == "C":
raw = bytearray(volume.read_bytes())
directory = FAT + SECTOR
assert raw[directory:directory + 4] == b"SAFE" and raw[directory + 32:directory + 37] == b"CROSS"
raw[directory + 32 + 13] = raw[directory + 13]
volume.write_bytes(raw)
if scenario == "N":
(folder / "SECOND.DSK").write_bytes(volume.read_bytes())
(folder / "initial.dsk").write_bytes(volume.read_bytes())
(folder / "startup.cfg").write_text("0=VOL.DSK\n")
return volume
def inspect(folder, scenario):
base = {"SAFE.DAT": SENTINEL}
if scenario == "N":
expected = {f"PAD{i}.DAT": bytes([i]) for i in range(7)}
expected.update({"OVERLAND.BAK": SENTINEL, "HOLD.TXT": b"still open"})
check_files(folder, "closed", expected)
restored = {"SAFE.DAT": SENTINEL, "DELETE.DAT": b"multi-granule" * 400, "HOLD.TXT": b""}
restored.update({f"PAD{i}.DAT": bytes([i]) for i in range(7)})
check_files(folder, "rollback", restored)
if (folder / "drive1.dsk").exists():
second = contents((folder / "SECOND.DSK").read_bytes())
second["DRIVEONE.DAT"] = second.pop("SAFE.DAT")
del second["DELETE.DAT"]
check_files(folder, "drive1", second)
elif scenario == "U":
patched = bytearray(DISTANT)
patched[255:259] = b"SECT"
patched[2302:2306] = b"GRAN"
expected = {**base, "DISTANT.DAT": patched + b"END!", "RECORDS.TXT": TEXT_RECORDS.replace(b"EUROPA", b"PHOBOS"),
"TRIPS.DAT": b"\0\xffABC", "RESET.DAT": b"NOW", "EMPTY.TXT": b"", "CREATED.TXT": b"LOG\r",
"FORMAT.TXT": b"HELLO 00042\r"}
check_files(folder, "closed", expected)
assert (folder / "protected.dsk").read_bytes() == (folder / "closed.dsk").read_bytes()
elif scenario == "S":
patched = bytearray((i + sector) & 255 for sector in range(10) for i in range(256))
patched.extend(b"\xa5" * 19)
patched[255:259] = b"SECT"
patched[2302:2306] = b"GRAN"
patched[-3:] = b"TAIL++"
patched[0] = ord("H")
patched.extend(b"END!")
check_files(folder, "closed", {**base, "DISTANT.DAT": DISTANT + b"!", "RECORDS.TXT": TEXT_RECORDS,
"PATCH.BIN": patched})
elif scenario == "T":
check_files(folder, "protected", {**base, "REPORT.BIN": b"ORBIT"})
assert (folder / "protected.dsk").read_bytes() == (folder / "refused.dsk").read_bytes()
check_files(folder, "closed", {**base, "REPORT.BIN": b"OXBIT"})
elif scenario in ("C", "B", "M"):
assert (folder / "closed.dsk").read_bytes() == (folder / "initial.dsk").read_bytes()
elif scenario == "P":
expected = dict(base, **{"REPORT.TXT": b"MARS RIDGE\r"})
check_files(folder, "protected", expected)
assert (folder / "protected.dsk").read_bytes() == (folder / "closed.dsk").read_bytes()
elif scenario == "F":
expected = dict(base, **{"FILL.DAT": FILL, "LAST.DAT": b"abcdefghij" * 230})
check_files(folder, "full", expected)
# The four remaining bytes physically fit; the buffered next sector does not.
# Existing committed bytes and all unrelated data must survive.
actual = contents((folder / "closed.dsk").read_bytes())
last = actual.pop("LAST.DAT")
committed = expected.pop("LAST.DAT")
assert actual == expected and last.startswith(committed)
tail = last[len(committed):]
assert tail == b"\xf3" * 4
else:
binary = b"".join(bytes((i + sec) & 255 for i in range(256)) for sec in range(9))
first = {**base, "REPORT.TXT": b"MARS RIDGE\r", "LOG.BIN": binary[:256], "DISTANT.DAT": DISTANT}
check_files(folder, "sector", first)
first["LOG.BIN"] = binary
check_files(folder, "granule", first)
first["LOG.BIN"] += b"\xff\x00"
first["DISTANT.DAT"] += b"\xfe"
first["REPORT.TXT"] += b"SECOND\r"
check_files(folder, "append", first)
first.update({"LOG.BIN": b"", "ABSENT.TXT": b"A\r"})
check_files(folder, "closed", first)
first["BASIC.TXT"] = b"FROM BASIC\r"
check_files(folder, "basic", first)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path)
parser.add_argument("core", type=Path)
parser.add_argument("roms", type=Path)
parser.add_argument("--profile", action="append", choices=("disk", "rgb-hd", "rgb-fd", "sdc"))
parser.add_argument("--suite", choices=("all", "writes", "position", "update", "directory"), default="all")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
with tempfile.TemporaryDirectory(prefix="vcc-stream-writes-") as tmp:
work = Path(tmp)
compiler = [runtime / "bin/cmoc", "--coco", "-Werror"]
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", fixture.parents[2] / "src", fixture / "run.cpp", core, "-o", "run"], cwd=work, check=True)
# The installed archive uses -O2. Exercise both caller settings against
# that archive and separately compile the stream implementation at -O0.
builds = (("writes", "qualification", "-O2", False), ("position", "position", "-O2", False),
("update", "update", "-O0", False), ("update", "update", "-O2", False),
("update", "update", "-O0", True), ("directory", "directory", "-O0", False),
("directory", "directory", "-O2", False))
for suite, source, level, compile_streams in builds:
if args.suite not in ("all", suite):
continue
implementation = "source" if compile_streams else "staged"
objects = []
if suite == "position":
for obj, defines in (("legacy-first.o", ["-DLEGACY_FIRST"]), ("stdio-first.o", [])):
subprocess.run([*compiler, level, *defines, "-c", "-o", obj, fixture / "mixed-rewind.c"],
cwd=work, env=env, check=True)
objects.append(obj)
if compile_streams:
for unit in ("streams", "format", "fileformat"):
source_path = fixture.parents[2] / "sdk/cmoc/compat" / (unit + ".c")
subprocess.run([*compiler, level, "-c", "-o", unit + ".o", source_path],
cwd=work, env=env, check=True)
objects.append(unit + ".o")
disk_library = "-ldecbfile"
if suite == "directory":
# Swap only the ROM I/O object in a disposable copy so a guest
# can exercise one transient write failure without a production hook.
shutil.copyfile(runtime / "share/cmoc/lib/libdecbfile.a", work / "libdiskfault.a")
subprocess.run([*compiler, level, "-c", "-o", "dskcon.o", fixture / "refuse-fat.c"],
cwd=work, env=env, check=True)
subprocess.run([runtime / "bin/lwar", "--replace", "libdiskfault.a", "dskcon.o"],
cwd=work, env=env, check=True)
objects.append("-L.")
disk_library = "-ldiskfault"
if suite == "update":
objects.append(fixture / "formatted.c")
if not compile_streams:
objects.append("-lvcccompat")
binary = work / (source + ".bin")
# The all-source -O0 qualification program needs another 2 KiB
# below the guest stack and the ROM mapped at $8000.
origin = "--org=2000" if compile_streams else "--org=2800"
subprocess.run([*compiler, level, origin, "-o", binary, fixture / (source + ".c"),
*objects, disk_library], cwd=work, env=env, check=True)
for profile in args.profile or ("disk", "rgb-fd", "rgb-hd", "sdc"):
if suite == "writes":
cases = [("W", "streams and BASIC exchange"), ("F", "disk-full partial write"),
("P", "protected flush")]
if profile == "disk":
cases += [("C", "cross-linked FAT refusal"), ("B", "active Disk BASIC file refusal")]
elif suite == "directory":
cases = [("N", "rename without replacement and reclaim removed files")]
elif suite == "position":
cases = [("S", "seek, tell, rewind and in-place overwrite"),
("T", "protected seek and rewind recovery")]
if profile == "disk":
cases.append(("M", "stdio and legacy rewind in both header orders"))
else:
cases = [("U", "update directions, protected writes, unchanged neighbors and EOF growth")]
for cpu in ("6809", "6309"):
for scenario, description in cases:
with tempfile.TemporaryDirectory(dir=work) as test:
folder = Path(test)
volume = write_fixture(folder, runtime / "bin/writecocofile", scenario)
subprocess.run([work / "run", roms, volume, binary, profile, cpu, scenario],
cwd=folder, check=True)
inspect(folder, scenario)
print(f"PASS {profile} {cpu} {level} {implementation}: {description}", flush=True)
if __name__ == "__main__":
main()
+67
View File
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <stdio.h>
#include <cmoc.h>
#include <coco.h>
#include <decbfile.h>
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u ERR %u\n", (unsigned)__LINE__, (unsigned)vcc_file_error()); return 1; } } while (0)
#define REFUSED(call, error) ((call) == EOF && vcc_file_error() == (error))
extern byte refuseNextFATWrite;
int main(void)
{
DECBDrive registry;
byte before, after, unused;
cls(1);
printf("SELECT CHECK\n");
byte testSecondDrive = waitkey(0) == 'D';
if (testSecondDrive)
{
CHECK(rename("SAFE.DAT:1", "DRIVEONE.DAT:1") == 0);
CHECK(remove("DELETE.DAT:1") == 0);
}
CHECK(decb_init(&registry, 1) == DECB_OK && decb_registerDrive(0) == DECB_OK);
CHECK(decb_getNumFreeGranules(0, &before) == DECB_OK);
unused = decb_findFreeGranule(0);
CHECK(unused < 68 && decb_setFATEntry(0, unused, 0xc1) == DECB_OK);
CHECK(REFUSED(remove("SAFE.DAT"), DECB_ERR_ALREADY_EXISTS));
CHECK(REFUSED(rename("SAFE.DAT", "SAVED.DAT"), DECB_ERR_ALREADY_EXISTS));
CHECK(decb_setFATEntry(0, unused, 0xff) == DECB_OK && decb_writeFAT(0) == DECB_OK);
CHECK(REFUSED(rename("SAFE.DAT", "MOVED.DAT:1"), DECB_ERR_INVALID_ARGUMENT));
CHECK(REFUSED(rename("SAFE.DAT", NULL), DECB_ERR_INVALID_ARGUMENT));
CHECK(REFUSED(rename(NULL, "NEW.DAT"), DECB_ERR_INVALID_ARGUMENT));
CHECK(REFUSED(remove("BAD.*"), DECB_ERR_INVALID_ARGUMENT));
CHECK(REFUSED(remove(NULL), DECB_ERR_INVALID_ARGUMENT));
CHECK(REFUSED(remove("ABSENT.DAT"), DECB_ERR_NOT_FOUND));
CHECK(REFUSED(rename("ABSENT.DAT", "NEW.DAT"), DECB_ERR_NOT_FOUND));
CHECK(REFUSED(rename("Safe.Dat", "Safe.dat:0"), DECB_ERR_ALREADY_EXISTS));
// The existing destination is past a full directory sector.
CHECK(REFUSED(rename("SAFE.DAT", "DELETE.DAT"), DECB_ERR_ALREADY_EXISTS));
FILE *reader = fopen("Safe.Dat", "r");
FILE *writer = fopen("Hold.Txt:0", "w");
CHECK(reader && writer && fputs("still open", writer) == 0);
CHECK(REFUSED(remove("SAFE.DAT:0"), DECB_ERR_ALREADY_EXISTS));
CHECK(REFUSED(rename("safe.dat", "SAVED.DAT"), DECB_ERR_ALREADY_EXISTS));
CHECK(REFUSED(rename("DELETE.DAT", "hold.txt"), DECB_ERR_ALREADY_EXISTS));
CHECK(REFUSED(remove("HOLD.TXT"), DECB_ERR_ALREADY_EXISTS));
// The directory write succeeds, then the FAT refuses a single write.
// Report failure and recover the pre-delete directory when it is safe.
refuseNextFATWrite = 1;
CHECK(REFUSED(remove("DELETE.DAT"), DECB_ERR_IO) && !refuseNextFATWrite);
printf("RECLAIM REFUSED\n");
while (waitkey(0) != 'X') {}
CHECK(rename("DELETE.DAT", "Doomed.Dat:0") == 0);
CHECK(remove("doomed.dat") == 0 && REFUSED(remove("DOOMED.DAT"), DECB_ERR_NOT_FOUND));
CHECK(fgetc(reader) == 'p' && fclose(reader) == 0 && fclose(writer) == 0);
CHECK(rename("SAFE.DAT", "OverLand.Bak") == 0);
FILE *empty = fopen("EMPTY.BIN", "wb");
CHECK(empty && fclose(empty) == 0 && remove("empty.bin") == 0);
// DELETE.DAT used three granules; HOLD.TXT now uses one of the free granules.
CHECK(decb_getNumFreeGranules(0, &after) == DECB_OK && after == before + 2);
decb_shutdown();
printf("DIRECTORY PASSED\n");
return 0;
}
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <stdio.h>
#include <cmoc.h>
#include <decbfile.h>
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u ERR %u\n", (unsigned)__LINE__, (unsigned)vcc_file_error()); return 1; } } while (0)
static int writeArgs(FILE *stream, const char *format, ...)
{
va_list args;
va_start(args, format);
int result = vfprintf(stream, format, args);
va_end(args);
return result;
}
int formattedChecks(void)
{
FILE *stream = fopen("FORMAT.TXT", "w+b");
char expected[64], actual[64];
const char *format = "%%|%-6.3s|%04d|%.0u|%lo|%lX|%c|%lx";
int length = snprintf(expected, sizeof(expected), format, "MARS", -7, 0U,
0xFFFFFFFFUL, 0xDEADBEEFUL, 0, 0xABCUL);
CHECK(stream && fprintf(stream, NULL) < 0 && ftell(stream) == 0L);
CHECK(length > 0 && (unsigned) length < sizeof(expected));
CHECK(writeArgs(stream, format, "MARS", -7, 0U, 0xFFFFFFFFUL, 0xDEADBEEFUL, 0, 0xABCUL) == length);
CHECK(fseek(stream, 0L, SEEK_SET) == 0 && fread(actual, 1, length, stream) == (unsigned) length);
CHECK(!memcmp(expected, actual, length));
// A read with no EOF requires positioning, including for formatted writes.
CHECK(fprintf(stream, "%s", "X") < 0 && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
CHECK(fseek(stream, 0L, SEEK_SET) == 0 && fprintf(stream, "%530s", "X") == 530);
CHECK(fprintf(stream, "ABC%f") < 0);
CHECK(fprintf(stream, "%32768d", 0) < 0 && ftell(stream) == 533L);
CHECK(fseek(stream, 0L, SEEK_SET) == 0);
for (unsigned i = 0; i < 529; ++i) CHECK(fgetc(stream) == ' ');
CHECK(fgetc(stream) == 'X' && fgetc(stream) == 'A' && fgetc(stream) == 'B' && fgetc(stream) == 'C');
// A valid format can emit more bytes than a 16-bit int can report.
CHECK(fseek(stream, 0L, SEEK_SET) == 0 && fprintf(stream, "%32767sX", "") < 0);
CHECK(ftell(stream) == 32768L && fclose(stream) == 0);
stream = fopen("FORMAT.TXT", "w");
CHECK(stream && fprintf(stream, "") == 0);
CHECK(fprintf(stream, "%s %05u\n", "HELLO", 42U) == 12 && fclose(stream) == 0);
stream = fopen("FORMAT.TXT", "r");
CHECK(stream && fprintf(stream, "") < 0 && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
CHECK(fclose(stream) == 0);
return 0;
}
int formattedProtectedChecks(void)
{
// A short write can succeed in memory. A longer one reaches the
// protected disk while formatting and reports the failure immediately.
FILE *stream = fopen("SAFE.DAT", "r+b");
CHECK(stream && fprintf(stream, "%s", "X") == 1);
CHECK(fprintf(stream, "%300s", "Y") < 0 && ferror(stream) == DECB_ERR_IO);
CHECK(fprintf(stream, "") < 0 && fclose(stream) == EOF);
return 0;
}
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Compile both ways and link with a third source that uses stdio rewind alone.
#ifdef LEGACY_FIRST
#include <disk.h>
#include <stdio.h>
#define CHECK_ORDER checkLegacyFirst
#else
#include <stdio.h>
#include <disk.h>
#define CHECK_ORDER checkStdioFirst
#endif
int CHECK_ORDER(void)
{
static byte fat[MAX_NUM_GRANULES];
static struct FileDesc descriptor;
void (*resetDescriptor)(struct FileDesc *) = rewind;
void (*resetStream)(FILE *) = vcc_rewind;
char bytes[3];
FILE *stream;
int ok;
// initdisk installs this source file’s FAT buffer without clearing the cache flag.
fatUpToDate = FALSE;
if (!initdisk(fat) || !openfile(&descriptor, "SAFE.DAT"))
return 1;
ok = read(&descriptor, bytes, 3) == 3 && memcmp(bytes, "pre", 3) == 0;
resetDescriptor(&descriptor);
ok = ok && read(&descriptor, bytes, 3) == 3 && memcmp(bytes, "pre", 3) == 0;
if (close(&descriptor) || !ok)
return 1;
stream = fopen("SAFE.DAT", "rb");
if (!stream)
return 1;
ok = fgetc(stream) == 'p' && fgetc(stream) == 'r';
resetStream(stream);
ok = ok && ftell(stream) == 0L && fgetc(stream) == 'p';
return fclose(stream) || !ok;
}
+160
View File
@@ -0,0 +1,160 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Host-created data and the final raw disk are checked independently of this API.
#include <stdio.h>
#include <limits.h>
#include <cmoc.h>
#include <coco.h>
#include <decbfile.h>
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u ERR %u\n", (unsigned)__LINE__, (unsigned)vcc_file_error()); return 1; } } while (0)
int checkLegacyFirst(void);
int checkStdioFirst(void);
static byte block[256];
static int binaryInput(void)
{
FILE *f = fopen("DISTANT.DAT", "rb");
CHECK(f && ftell(f) == 0L);
CHECK(fseek(f, 255L, SEEK_SET) == 0);
CHECK(fread(block, 1, 2, f) == 2 && block[0] == 249 && block[1] == 1);
// This pair of bytes crosses a deliberately noncontiguous granule.
CHECK(fseek(f, 2303L, SEEK_SET) == 0 && ftell(f) == 2303L);
CHECK(fgetc(f) == 1 && fgetc(f) == 9);
CHECK(fseek(f, -2L, SEEK_CUR) == 0 && fgetc(f) == 1);
CHECK(fseek(f, -2L, SEEK_END) == 0 && ftell(f) == 65535L);
CHECK(fgetc(f) == 248 && ftell(f) == 65536L);
CHECK(fgetc(f) == 0 && ftell(f) == 65537L);
CHECK(fgetc(f) == EOF && feof(f));
CHECK(fseek(f, LONG_MAX, SEEK_CUR) != 0 && feof(f) && ftell(f) == 65537L);
CHECK(fseek(f, LONG_MIN, SEEK_END) != 0 && feof(f) && ftell(f) == 65537L);
CHECK(fseek(f, 0L, 17) != 0 && feof(f));
CHECK(fseek(f, -65537L, SEEK_CUR) == 0 && !feof(f) && ftell(f) == 0L);
CHECK(fseek(f, -1L, SEEK_SET) != 0 && ftell(f) == 0L);
CHECK(fseek(f, 65538L, SEEK_SET) != 0 && ftell(f) == 0L && fgetc(f) == 0);
CHECK(fseek(f, 65536L, SEEK_SET) == 0 && ftell(f) == 65536L && fgetc(f) == 0);
CHECK(fgetc(f) == EOF && feof(f));
rewind(f);
CHECK(ftell(f) == 0L);
CHECK(!feof(f));
CHECK(!ferror(f));
CHECK(fgetc(f) == 0);
CHECK(fclose(f) == 0);
f = fopen("DISTANT.DAT", "ab");
CHECK(f && ftell(f) == 65537L && fseek(f, 0L, SEEK_SET) == 0);
CHECK(ftell(f) == 0L && fputc('!', f) == '!' && ftell(f) == 65538L && fclose(f) == 0);
CHECK(ftell(NULL) == -1L && fseek(NULL, 0L, SEEK_SET) != 0);
return 0;
}
static int textBookmarks(void)
{
FILE *f = fopen("RECORDS.TXT", "r");
long before, after;
char line[16];
CHECK(f && fread(block, 1, 255, f) == 255);
before = ftell(f); // The CR is the final byte of sector 0.
CHECK(before >= 0 && fgetc(f) == '\n');
after = ftell(f); // The paired LF starts sector 1.
clearerr(f); // Preserve the pending CRLF translation.
CHECK(after >= 0 && after != before && fgetc(f) == 'M');
CHECK(fseek(f, before, SEEK_SET) == 0 && fgetc(f) == '\n' && fgetc(f) == 'M');
CHECK(fseek(f, after, SEEK_SET) == 0);
CHECK(fgets(line, sizeof(line), f) && !strcmp(line, "MARS\n"));
CHECK(fseek(f, after, SEEK_SET) == 0);
CHECK(fseek(f, 1L, SEEK_CUR) != 0 && fseek(f, -1L, SEEK_END) != 0);
CHECK(ftell(f) == after && fgetc(f) == 'M');
CHECK(fseek(f, 0L, SEEK_END) == 0 && fgetc(f) == EOF && feof(f));
rewind(f);
CHECK(!feof(f) && ftell(f) == 0L && fgetc(f) == 'X');
CHECK(fclose(f) == 0);
return 0;
}
static int editBinary(void)
{
unsigned sector, i;
const long originalSize = 2579L;
FILE *f = fopen("PATCH.BIN", "wb");
FILE *reader;
CHECK(f && ftell(f) == 0L && fseek(f, 0L, SEEK_END) == 0);
for (sector = 0; sector < 10; ++sector) {
for (i = 0; i < sizeof(block); ++i) block[i] = (byte)(sector + i);
CHECK(fwrite(block, 1, sizeof(block), f) == sizeof(block));
}
memset(block, 0xa5, 19);
CHECK(fwrite(block, 1, 19, f) == 19 && ftell(f) == originalSize);
// The last 19 bytes are still pending when the invalid seek is refused.
CHECK(fseek(f, 1L, SEEK_END) != 0 && ftell(f) == originalSize);
CHECK(fseek(f, -19L, SEEK_END) == 0 && ftell(f) == 2560L);
reader = fopen("PATCH.BIN", "rb");
CHECK(reader && fseek(reader, -1L, SEEK_END) == 0 && fgetc(reader) == 0xa5);
CHECK(fseek(f, 255L, SEEK_SET) == 0 && fputs("SECT", f) >= 0 && ftell(f) == 259L);
CHECK(fflush(f) == 0);
CHECK(fseek(f, 2302L, SEEK_SET) == 0 && fputs("GRAN", f) >= 0);
CHECK(fseek(f, -3L, SEEK_END) == 0 && fputs("TAIL++", f) >= 0);
CHECK(ftell(f) == originalSize + 3L && fflush(f) == 0);
CHECK(fseek(reader, 0L, SEEK_END) == 0 && ftell(reader) == originalSize);
CHECK(fgetc(reader) == EOF && feof(reader));
CHECK(fclose(reader) == 0);
rewind(f);
CHECK(ftell(f) == 0L && fputc('H', f) == 'H' && fclose(f) == 0);
f = fopen("PATCH.BIN", "ab");
CHECK(f && ftell(f) == originalSize + 3L && fseek(f, 3L, SEEK_SET) == 0);
CHECK(ftell(f) == 3L && fputs("END", f) >= 0 && ftell(f) == originalSize + 6L);
rewind(f);
CHECK(ftell(f) == 0L && fputc('!', f) == '!' && ftell(f) == originalSize + 7L);
CHECK(fclose(f) == 0);
return 0;
}
static int protectedSeek(void)
{
FILE *f = fopen("REPORT.BIN", "wb");
CHECK(f && fputs("ORBIT", f) >= 0 && fseek(f, 1L, SEEK_SET) == 0);
CHECK(fputc('X', f) == 'X' && ftell(f) == 2L);
printf("PROTECT NOW\n");
while (waitkey(0) != 'X') {}
CHECK(fseek(f, 4L, SEEK_SET) != 0 && ferror(f) == DECB_ERR_IO);
CHECK(ftell(f) == 2L);
// Only this writer is cleared. The second stream has its own EOF.
FILE *reader = fopen("REPORT.BIN", "rb");
CHECK(reader && fseek(reader, 0L, SEEK_END) == 0 && fgetc(reader) == EOF && feof(reader));
clearerr(f);
CHECK(ferror(f) == 0 && ftell(f) == 2L && feof(reader));
CHECK(fflush(f) == EOF && ferror(f) == DECB_ERR_IO);
clearerr(reader);
CHECK(!feof(reader) && !ferror(reader) && ferror(f) == DECB_ERR_IO);
CHECK(ftell(reader) == 5L && fgetc(reader) == EOF && feof(reader));
CHECK(fclose(reader) == 0);
clearerr(reader);
CHECK(vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
rewind(f); // Still protected: position and error survive.
CHECK(ftell(f) == 2L && ferror(f) == DECB_ERR_IO);
printf("ALLOW RETRY\n");
while (waitkey(0) != 'Y') {}
rewind(f); // The buffered overwrite can now be delivered.
CHECK(ftell(f) == 0L && !ferror(f) && fclose(f) == 0);
return 0;
}
int main(void)
{
int result = 1;
cls(1);
printf("SELECT CHECK\n");
switch (waitkey(0)) {
case 'M':
result = checkLegacyFirst() || checkStdioFirst();
break;
case 'S':
result = binaryInput() || textBookmarks() || editBinary();
break;
case 'T':
result = protectedSeek();
break;
}
if (!result) printf("POSITIONS PASSED\n");
return result;
}
@@ -0,0 +1,145 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// The host examines actual directory, FAT and sectors at each pause.
#include <stdio.h>
#include <cmoc.h>
#include <coco.h>
#include <decbfile.h>
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u ERR %u\n", (unsigned)__LINE__, (unsigned)vcc_file_error()); return 1; } } while (0)
static byte block[256];
static byte ten[10];
static DECBDrive registry;
static void checkpoint(const char *name, char key)
{
printf("%s\n", name);
while (waitkey(0) != key) {}
}
static int writeFiles(void)
{
unsigned i, sector;
FILE *text, *binary, *snapshot;
char line[20];
byte before, after, unused;
// A caller with an unpublished low-level FAT owns it until it is saved.
CHECK(decb_init(&registry, 1) == DECB_OK && decb_registerDrive(0) == DECB_OK);
CHECK(decb_getNumFreeGranules(0, &before) == DECB_OK);
unused = decb_findFreeGranule(0);
CHECK(unused < 68 && decb_setFATEntry(0, unused, 0xc1) == DECB_OK);
CHECK(!fopen("BUSY.TXT", "w") && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
CHECK(decb_setFATEntry(0, unused, 0xff) == DECB_OK && decb_writeFAT(0) == DECB_OK);
// Interleave two writers so a stale cached directory or FAT loses a file.
text = fopen("REPORT.TXT", "w");
binary = fopen("LOG.BIN:0", "wb");
CHECK(text && binary);
CHECK(fputs("MARS RIDGE\n", text) >= 0);
CHECK(fwrite(NULL, 0, 70, binary) == 0 && fwrite(NULL, 70, 0, binary) == 0);
for (i = 0; i < 256; ++i) block[i] = (byte)i;
CHECK(fwrite(block, 16, 16, binary) == 16);
CHECK(fflush(NULL) == 0 && fflush(text) == 0);
checkpoint("FIRST FLUSH", 'X');
CHECK(fclose(text) == 0);
CHECK(fopen("log.bin", "ab") == NULL); // another writer owns the same file
snapshot = fopen("log.bin", "rb");
CHECK(snapshot && fread(block, 1, 256, snapshot) == 256);
for (i = 0; i < 256; ++i) CHECK(block[i] == (byte)i);
for (sector = 1; sector < 9; ++sector) {
for (i = 0; i < 256; ++i) block[i] = (byte)(i + sector);
CHECK(fwrite(block, 16, 16, binary) == 16);
}
CHECK(fflush(binary) == 0);
CHECK(fgetc(snapshot) == EOF && feof(snapshot) && !ferror(snapshot));
CHECK(fclose(snapshot) == 0 && fclose(binary) == 0);
checkpoint("FULL GRANULE", 'Y');
text = fopen("REPORT.TXT", "a");
binary = fopen("LOG.BIN", "ab");
CHECK(text && binary);
CHECK(fputc(0x1ff, binary) == 255 && fputc(0, binary) == 0);
CHECK(fputs("SECOND\n", text) >= 0);
CHECK(fclose(text) == 0 && fclose(binary) == 0);
text = fopen("REPORT.TXT", "r");
CHECK(text && fgets(line, sizeof(line), text) && strcmp(line, "MARS RIDGE\n") == 0);
CHECK(fgets(line, sizeof(line), text) && strcmp(line, "SECOND\n") == 0);
CHECK(fclose(text) == 0);
// This file already spans 65,537 bytes; the append position must not wrap.
binary = fopen("DISTANT.DAT", "ab");
CHECK(binary && fputc(0xfe, binary) == 254 && fclose(binary) == 0);
checkpoint("APPENDED", 'Z');
binary = fopen("LOG.BIN", "wb"); // truncation gives back an occupied granule
CHECK(binary && fflush(binary) == 0 && fclose(binary) == 0);
text = fopen("ABSENT.TXT", "a"); // append creates a missing file
CHECK(text && fputs("A\n", text) >= 0 && fclose(text) == 0);
// The library created two files and shrank the original two-granule log.
CHECK(decb_getNumFreeGranules(0, &after) == DECB_OK && after + 1 == before);
decb_shutdown();
return 0;
}
static int fillDisk(void)
{
FILE *out = fopen("LAST.DAT", "wb");
unsigned i;
CHECK(out);
for (i = 0; i < 10; ++i) ten[i] = (byte)('a' + i);
// One free granule before open. Check that fwrite counts complete items
// and exposes the full-volume error whether a sector was buffered or not.
for (i = 0; i < 230; ++i) CHECK(fwrite(ten, 10, 1, out) == 1);
CHECK(fflush(out) == 0);
checkpoint("LAST FOUR BYTES", 'X');
// Four bytes fit on disk and one 256-byte sector fits in the buffer.
// 260 bytes accepted means 86 complete three-byte objects.
byte tail[270];
memset(tail, 0xf3, sizeof(tail));
CHECK(fwrite(tail, 3, 90, out) == 86);
CHECK(ferror(out) == DECB_ERR_OUT_OF_SPACE);
CHECK(fclose(out) == EOF);
CHECK(fopen("NOSPACE.DAT", "wb") == NULL && vcc_file_error() == DECB_ERR_OUT_OF_SPACE);
return 0;
}
static int protectDuringFlush(void)
{
FILE *out = fopen("REPORT.TXT", "w");
CHECK(out && fputs("MARS RIDGE\n", out) >= 0 && fflush(out) == 0);
CHECK(fputs("UNSAVED\n", out) >= 0);
checkpoint("PROTECT NOW", 'X');
CHECK(fflush(out) == EOF && ferror(out) == DECB_ERR_IO);
CHECK(fclose(out) == EOF && vcc_file_error() == DECB_ERR_IO);
CHECK(!fopen("REPORT.TXT", "w") && vcc_file_error() == DECB_ERR_IO);
CHECK(!fopen("ABSENT.TXT", "w") && vcc_file_error() == DECB_ERR_IO);
CHECK(rename("SAFE.DAT", "SAVED.DAT") == EOF && vcc_file_error() == DECB_ERR_IO);
CHECK(remove("SAFE.DAT") == EOF && vcc_file_error() == DECB_ERR_IO);
return 0;
}
int main(void)
{
int result;
cls(1);
printf("SELECT CHECK\n");
switch(waitkey(0)) {
case 'B': // Disk BASIC has left an input file open on this drive.
CHECK(!fopen("SAFE.DAT", "w") && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
CHECK(rename("SAFE.DAT", "SAVED.DAT") == EOF && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
CHECK(remove("SAFE.DAT") == EOF && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
result = 0;
break;
case 'C': // Two directory entries name the same physical chain.
CHECK(!fopen("SAFE.DAT", "w") && vcc_file_error() == DECB_ERR_CORRUPT_FAT);
CHECK(!fopen("NEW.DAT", "a") && vcc_file_error() == DECB_ERR_CORRUPT_FAT);
CHECK(rename("SAFE.DAT", "SAVED.DAT") == EOF && vcc_file_error() == DECB_ERR_CORRUPT_FAT);
CHECK(remove("SAFE.DAT") == EOF && vcc_file_error() == DECB_ERR_CORRUPT_FAT);
result = 0;
break;
case 'W': result = writeFiles(); break;
case 'F': result = fillDisk(); break;
case 'P': result = protectDuringFlush(); break;
default: return 1;
}
if (!result) printf("WRITES PASSED\n");
return result;
}
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Route every operation through the same ROM routine as decbfile, except for
// one explicitly armed FAT write. This exercises a partial remove on a real
// guest volume without changing either the library or the machine controller.
#define decb_dskcon testROMDiskIO
#include "../../../third_party/cmoc-libraries/decbfile/dskcon.c"
#undef decb_dskcon
byte refuseNextFATWrite;
byte decb_dskcon(byte operation, void *buffer, byte drive, byte track, byte sector)
{
if (refuseNextFATWrite && operation == DECB_DSKCON_WRITE && track == 17 && sector == 2)
{
refuseNextFATWrite = 0;
return FALSE;
}
return testROMDiskIO(operation, buffer, drive, track, sector);
}
+143
View File
@@ -0,0 +1,143 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../basic-disk-session.h"
using namespace BasicDiskTests;
static void snapshot(Session& session, const char *name) {
const auto& original = session.original;
Bytes volume;
if (session.profile == Profile::rgbHD) {
const auto& vhd = session.hard->image(0)->bytes();
volume.assign(vhd.begin() + rgbStart, vhd.begin() + rgbStart + original.size());
require(session.floppy->image(0)->bytes() == original, "Hard-disk run changed FD0");
} else if (session.sdc) {
volume = readFile(session.diskPath);
} else {
volume = session.floppy->image(0)->bytes();
if (session.hard) require(!session.hard->image(0)->dirty(), "DRIVE OFF wrote to the VHD");
}
std::ofstream out(name, std::ios::binary);
out.write(reinterpret_cast<const char*>(volume.data()), volume.size());
require(bool(out), "Could not save volume at a checkpoint");
}
static void protect(Session& session, bool enabled) {
if (session.sdc) session.sdc->setWriteProtected(enabled);
else if (session.profile == Profile::rgbHD) session.hard->image(0)->protect(enabled);
else session.floppy->setWriteProtected(0, enabled);
}
// Additional matrix chords for ordinary Disk BASIC file commands.
static void basic(Session& session, const std::string& command) {
std::vector<std::uint64_t> chords;
for (const auto c : command) {
unsigned bit;
bool shift = false;
if (c >= 'A' && c <= 'Z') bit = c - '@';
else if (c >= '0' && c <= '9') bit = c - '0' + 32;
else if (c == ' ') bit = 31;
else if (c == ':') bit = 42;
else if (c == ',') bit = 44;
else if (c == '.') bit = 46;
else if (c == '\r') bit = 48;
else {
shift = true;
const std::string shifted = "!\"#$%&'()";
const auto n = shifted.find(c);
require(n != std::string::npos, "Unhandled guest key");
bit = 33 + n;
}
chords.push_back((std::uint64_t(1) << bit) | (std::uint64_t(shift) << 55));
}
session.machine.paste(chords);
for (unsigned n = 0; session.machine.pasteRemaining() && n < 9000; ++n) session.frames(1);
require(!session.machine.pasteRemaining(), "Guest paste did not complete");
if (!command.empty() && command.front() >= '0' && command.front() <= '9') { session.frames(10); return; }
for (unsigned n = 0; n < 1200; ++n) {
session.frames(1);
const auto screen = session.machine.copyScreenText();
require(screen.find("ERROR") == std::string::npos, "Disk BASIC command failed: " + screen);
const auto end = screen.find_last_not_of(" \r\n");
if (end != std::string::npos && end > 0 && screen.compare(end - 1, 2, "OK") == 0) return;
}
throw std::runtime_error("Disk BASIC did not return: " + session.machine.copyScreenText());
}
static void run(const fs::path& roms, const fs::path& disk, const fs::path& binary,
Processor cpu, Profile profile, const std::string& scenario) {
Session session(roms, disk, cpu, profile);
// Prime Disk BASIC's own DOS allocation table before the C program writes.
basic(session, "PRINT FREE(0)\r");
if (scenario == "B") basic(session, "OPEN\"I\",#1,\"SAFE.DAT\"\r");
session.launch(binary);
session.until("SELECT CHECK");
if (scenario == "N" && profile == Profile::fd) {
session.floppy->setWriteProtected(1, false);
session.type("D");
} else session.type(scenario);
if (scenario == "W") {
char key = 'X'; // Distinct keys at adjacent prompts avoid ROM keyboard repeat debounce.
for (const auto& stage : {std::pair{"FIRST FLUSH", "sector.dsk"},
{"FULL GRANULE", "granule.dsk"}, {"APPENDED", "append.dsk"}}) {
session.until(stage.first);
snapshot(session, stage.second);
session.frames(10);
session.type(std::string(1, key++));
}
} else if (scenario == "N") {
session.until("RECLAIM REFUSED");
snapshot(session, "rollback.dsk");
session.type("X");
} else if (scenario == "F") {
session.until("LAST FOUR BYTES");
snapshot(session, "full.dsk");
session.type("X");
} else if (scenario == "P" || scenario == "T" || scenario == "U") {
session.until("PROTECT NOW");
snapshot(session, "protected.dsk");
protect(session, true);
session.type("X");
if (scenario == "T") {
session.until("ALLOW RETRY");
snapshot(session, "refused.dsk");
protect(session, false);
session.type("Y");
}
}
if (scenario == "N") session.until("DIRECTORY PASSED");
else if (scenario == "U") session.until("UPDATES PASSED");
else if (scenario == "S" || scenario == "T" || scenario == "M") session.until("POSITIONS PASSED");
else session.until("WRITES PASSED");
session.verifyReturn();
snapshot(session, "closed.dsk");
if (scenario == "N" && profile == Profile::fd) {
const auto& drive1 = session.floppy->image(1)->bytes();
std::ofstream out("drive1.dsk", std::ios::binary);
out.write(reinterpret_cast<const char*>(drive1.data()), drive1.size());
require(bool(out), "Could not capture FD1");
}
if (scenario == "W") {
basic(session, "10 OPEN\"I\",#1,\"REPORT.TXT\"\r");
basic(session, "20 LINE INPUT #1,A$\r");
basic(session, "30 CLOSE#1:PRINT A$\r");
basic(session, "40 OPEN\"O\",#1,\"BASIC.TXT\"\r");
basic(session, "50 PRINT#1,\"FROM BASIC\":CLOSE#1\r");
basic(session, "RUN\r");
session.until("MARS RIDGE");
snapshot(session, "basic.dsk");
}
}
int main(int argc, char** argv) {
try {
require(argc == 7, "Usage: run ROMS DSK BIN PROFILE CPU TEST");
const std::string profile = argv[4];
const auto mode = profile == "disk" ? Profile::fd : profile == "rgb-fd" ? Profile::rgbFD :
profile == "rgb-hd" ? Profile::rgbHD : Profile::sdc;
const auto cpu = std::string(argv[5]) == "6809" ? Processor::MC6809 : Processor::HD6309;
run(argv[1], argv[2], argv[3], cpu, mode, argv[6]);
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+141
View File
@@ -0,0 +1,141 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// The host checks every final file byte against its own fixtures and compares
// the raw volume before and after a guest flush on write-protected media.
#include <stdio.h>
#include <cmoc.h>
#include <coco.h>
#include <decbfile.h>
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u ERR %u\n", (unsigned)__LINE__, (unsigned)vcc_file_error()); return 1; } } while (0)
int formattedChecks(void);
int formattedProtectedChecks(void);
static int binaryUpdate(void)
{
FILE *f, *reader;
byte pair[2];
CHECK(!fopen("MISSING.DAT", "r+b") && vcc_file_error() == DECB_ERR_NOT_FOUND);
CHECK(!fopen("SAFE.DAT", "r++") && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
CHECK(!fopen("SAFE.DAT", "rb+b") && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
reader = fopen("distant.dat", "rb");
CHECK(reader && !fopen("DISTANT.DAT:0", "rb+") && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
CHECK(fclose(reader) == 0);
f = fopen("DISTANT.DAT", "rb+");
CHECK(f && ftell(f) == 0L && fgetc(f) == 0);
CHECK(!fopen("distant.dat:0", "r+b") && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
CHECK(!fopen("distant.dat:0", "w") && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
// An all-stream flush cannot authorize a write after reading.
CHECK(fflush(f) == EOF && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
CHECK(fflush(NULL) == 0);
clearerr(f); // Clearing flags is not a direction change.
CHECK(fputc('!', f) == EOF && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT && ftell(f) == 1L);
CHECK(fseek(f, 255L, SEEK_SET) == 0);
CHECK(fwrite("SECT", 2, 2, f) == 2);
// A rejected seek cannot authorize reading after writing.
clearerr(f);
CHECK(fseek(f, -1L, SEEK_SET) == EOF);
CHECK(fread(pair, 1, 2, f) == 0 && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT && ftell(f) == 259L);
CHECK(fflush(NULL) == 0);
CHECK(fgetc(f) == 22 && ftell(f) == 260L);
reader = fopen("DISTANT.DAT", "rb");
CHECK(reader && fseek(reader, 255L, SEEK_SET) == 0);
CHECK(fgetc(reader) == 'S' && fgetc(reader) == 'E' && fclose(reader) == 0);
// Logical byte 2304 is in the deliberately relocated second granule.
CHECK(fseek(f, 2302L, SEEK_SET) == 0 && fputs("GRAN", f) >= 0);
CHECK(fflush(f) == 0 && fgetc(f) == 23);
CHECK(fseek(f, -1L, SEEK_END) == 0 && ftell(f) == 65536L);
CHECK(fread(pair, 1, 2, f) == 1 && pair[0] == 0 && feof(f));
clearerr(f);
CHECK(!feof(f) && !ferror(f) && ftell(f) == 65537L);
// Clearing the indicator does not undo the read that encountered EOF.
CHECK(fwrite("END", 1, 3, f) == 3 && !feof(f));
CHECK(fseek(f, -3L, SEEK_END) == 0 && fgetc(f) == 'E' && ftell(f) == 65538L);
CHECK(fclose(f) == 0);
return 0;
}
static int textUpdate(void)
{
FILE *f = fopen("RECORDS.TXT", "r+");
long bookmark;
char line[16];
unsigned i;
CHECK(f);
for (i = 0; i < 255; ++i) CHECK(fgetc(f) == 'X');
bookmark = ftell(f);
CHECK(fgetc(f) == '\n');
CHECK(fseek(f, bookmark, SEEK_SET) == 0);
// Replace a CR at the end of one sector; its paired LF begins the next.
CHECK(fputc('\n', f) == '\n' && fflush(f) == 0);
CHECK(fgets(line, sizeof(line), f) && !strcmp(line, "MARS\n"));
// Overwrite the next planet's name after positioning at the same cursor.
CHECK(fseek(f, 0L, SEEK_CUR) == 0 && fputs("PHOBOS", f) >= 0);
CHECK(fflush(f) == 0 && fgetc(f) == '\n');
rewind(f);
CHECK(ftell(f) == 0L && fgetc(f) == 'X' && fclose(f) == 0);
return 0;
}
static int createAppendUpdate(void)
{
FILE *f;
CHECK(!fopen("SAFE.DAT", "wb+b") && !fopen("SAFE.DAT", "a++"));
f = fopen("TRIPS.DAT", "w+b");
CHECK(f && fputc(0, f) == 0 && fputc(255, f) == 255);
rewind(f);
CHECK(fgetc(f) == 0 && fgetc(f) == 255 && fclose(f) == 0);
// Replace an existing multi-granule file and release its old chain.
f = fopen("RESET.DAT", "wb+");
CHECK(f && fgetc(f) == EOF && feof(f));
CHECK(fputs("NEW", f) >= 0 && fseek(f, 1L, SEEK_SET) == 0);
CHECK(fputc('O', f) == 'O' && fclose(f) == 0);
f = fopen("EMPTY.TXT", "w+");
CHECK(f && fgetc(f) == EOF && feof(f) && fclose(f) == 0);
f = fopen("TRIPS.DAT", "a+b");
CHECK(f && ftell(f) == 0L && fputc('A', f) == 'A' && ftell(f) == 3L);
rewind(f);
CHECK(fgetc(f) == 0 && fputc('X', f) == EOF && ftell(f) == 1L);
CHECK(fseek(f, 0L, SEEK_CUR) == 0 && fwrite("BC", 1, 2, f) == 2);
CHECK(fclose(f) == 0);
f = fopen("DISTANT.DAT", "ab+");
CHECK(f && fgetc(f) == 0 && fseek(f, 256L, SEEK_SET) == 0);
CHECK(fputc('!', f) == '!' && ftell(f) == 65541L && fclose(f) == 0);
f = fopen("CREATED.TXT", "a+");
CHECK(f && fgetc(f) == EOF && fputs("LOG\n", f) >= 0);
rewind(f);
CHECK(fgetc(f) == 'L' && fclose(f) == 0);
return 0;
}
static int protectedUpdate(void)
{
printf("PROTECT NOW\n");
while (waitkey(0) != 'X') {}
// The Disk BASIC ROM reports write protection at the actual sector write.
FILE *f = fopen("SAFE.DAT", "r+b");
CHECK(f && fgetc(f) == 'p' && fseek(f, 0L, SEEK_SET) == 0);
CHECK(fputc('!', f) == '!' && fflush(f) == EOF && ferror(f) == DECB_ERR_IO);
CHECK(fclose(f) == EOF && vcc_file_error() == DECB_ERR_IO);
f = fopen("SAFE.DAT", "r+b");
CHECK(f && fgetc(f) == 'p' && fclose(f) == 0);
CHECK(!fopen("SAFE.DAT", "w+") && !fopen("MISSING.DAT", "a+"));
f = fopen("SAFE.DAT", "a+");
CHECK(f && fgetc(f) == 'p' && fseek(f, 0L, SEEK_SET) == 0);
CHECK(fputc('!', f) == '!' && fflush(f) == EOF && fclose(f) == EOF);
return formattedProtectedChecks();
}
int main(void)
{
cls(1);
printf("SELECT CHECK\n");
if (waitkey(0) != 'U' || binaryUpdate() || textUpdate()
|| createAppendUpdate() || formattedChecks() || protectedUpdate()) return 1;
printf("UPDATES PASSED\n");
return 0;
}
+102
View File
@@ -0,0 +1,102 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Exercise read-only guest streams through three real DOS ROMs on both CPUs."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
def qualification_disk(folder, disk_tool):
folder.mkdir()
disk = folder / "QUAL.DSK"
disk.write_bytes(bytes([255]) * (35 * 18 * 256))
files = {
"LARGE.DAT": b"".join(bytes((i + j) & 255 for j in range(256)) for i in range(257)),
"MIXED.TXT": b"A" * 255 + b"\r\nBETA\rRED\nLAST",
"SHORT.DAT": bytes([0, 255, 1, 2, 3, 4, 5, 6, 7]),
# Allocate distinct real directory entries before preparing boundary cases.
"EMPTY0.DAT": b".", "EMPTY1.DAT": b".", "CYCLE.DAT": b".", "INVALID.DAT": b".",
}
for name, data in files.items():
(folder / name).write_bytes(data)
subprocess.run([disk_tool, "--binary", disk, name], cwd=folder, check=True)
raw = bytearray(disk.read_bytes())
fat = (17 * 18 + 1) * 256
directory = fat + 256
for row in range(directory, directory + 256, 32):
name = raw[row:row + 8].rstrip()
granule = raw[row + 13]
if name in (b"EMPTY0", b"EMPTY1"):
raw[fat + granule] = 0xc0 if name == b"EMPTY0" else 0xc1
raw[row + 14:row + 16] = bytes(2)
elif name == b"INVALID":
raw[row + 14:row + 16] = (257).to_bytes(2, "big")
elif name == b"CYCLE":
raw[fat + granule] = granule
disk.write_bytes(raw)
second = folder / "SECOND.DSK"
second.write_bytes(bytes([255]) * (35 * 18 * 256))
(folder / "SIDE.TXT").write_bytes(b"1")
subprocess.run([disk_tool, second, "SIDE.TXT"], cwd=folder, check=True)
(folder / "startup.cfg").write_text("0=QUAL.DSK\n1=SECOND.DSK\n")
return disk
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="staged Toolchain directory")
parser.add_argument("core", type=Path, help="current libVCCCore.a")
parser.add_argument("roms", type=Path, help="directory containing the privately supplied ROMs")
parser.add_argument("--profile", action="append", choices=("disk", "rgb-hd", "rgb-fd", "sdc"),
help="limit a diagnostic run to this route (repeatable)")
parser.add_argument("--capture", type=Path, help="save the Disk BASIC Mars report as a PNG")
args = parser.parse_args()
runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms))
fixture = Path(__file__).resolve().parent
root = fixture.parents[2]
with tempfile.TemporaryDirectory(prefix="vcc-streams-") as tmp:
work = Path(tmp)
env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"])
subprocess.run([runtime / "bin/cmoc", "--coco", "-O2", "-Werror", "--org=2800",
"-o", "QUAL.BIN", fixture / "qualification.c", "-lvcccompat", "-ldecbfile"],
env=env, cwd=work, check=True)
disk = qualification_disk(work / "qualification", runtime / "bin/writecocofile")
subprocess.run(["xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
"-I", root / "src", fixture / "run.cpp", core, "-o", work / "run"],
cwd=work, check=True)
for config in ("Debug", "Release"):
example = work / config
shutil.copytree(root / "examples/cmoc/PlanetSurvey", example)
make = [runtime / "bin/make", "disk", "VCC_CONFIGURATION=" + config]
subprocess.run(make, cwd=example, env=env, check=True)
data = (example / "generated/PLANETS.TXT").read_bytes()
if data[254:258] != b"MARS":
raise AssertionError("The published Mars record must straddle the sector boundary")
(example / "startup.cfg").write_text("0=SURVEY.dsk\n")
# Rebuild after editing just the data, as a reader would.
edited = work / (config + "-edited")
shutil.copytree(example, edited)
source = edited / "assets/planets.txt"
lines = source.read_text().splitlines()
lines[lines.index("MARS|RED,COLD|4")] = "MARS ORBIT|DUSTY,COLD|4"
source.write_text("\n".join(lines) + "\n")
subprocess.run(make, cwd=edited, env=env, check=True)
bad = example / "malformed"
bad.mkdir()
(bad / "BAD.DSK").write_bytes(bytes([255]) * (35 * 18 * 256))
(bad / "PLANETS.TXT").write_bytes(b"EARTH|BLUE|3\rMARS|RED,COLD|4X\r")
subprocess.run([runtime / "bin/writecocofile", "BAD.DSK", "PLANETS.TXT"], cwd=bad, check=True)
for mode in args.profile or ("disk", "rgb-hd", "rgb-fd", "sdc"):
capture = args.capture and mode == "disk" and config == "Debug"
subprocess.run([work / "run", roms, disk, work / "QUAL.BIN", mode, example, edited, config,
"capture" if capture else "check"],
cwd=work, check=True)
if capture:
subprocess.run(["sips", "-s", "format", "png", "survey.ppm", "--out", args.capture.resolve()],
cwd=work, check=True)
if __name__ == "__main__":
main()
+105
View File
@@ -0,0 +1,105 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// This executable runs under a real disk ROM. The host supplies two malformed
// directory entries, then ejects the disk only after the program asks for it.
#include <stdio.h>
#include <cmoc.h>
#include <coco.h>
#include <decbfile.h>
#define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u ERR %u\n", (unsigned)__LINE__, (unsigned)vcc_file_error()); return 1; } } while (0)
static unsigned char sector[256];
static DECBDrive callerDrive;
int main(void)
{
FILE *a, *b;
unsigned i;
char text[12];
byte freeBefore, freeAfter;
cls(1);
CHECK(!fopen("ABSENT.TXT", "r") && vcc_file_error() == DECB_ERR_NOT_FOUND);
CHECK(!fopen("SHORT.DAT", "w++") && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
CHECK(!fopen("SHORT.DAT:4", "rb") && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
CHECK(!fopen("sub/SHORT.DAT", "r") && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT);
CHECK(!fopen("CYCLE.DAT", "r") && vcc_file_error() == DECB_ERR_CORRUPT_FAT);
// Even an unrelated truncate must leave a volume with a cyclic FAT alone.
CHECK(!fopen("SHORT.DAT", "r+b") && vcc_file_error() == DECB_ERR_CORRUPT_FAT);
CHECK(!fopen("SHORT.DAT", "wb") && vcc_file_error() == DECB_ERR_CORRUPT_FAT);
CHECK(!fopen("INVALID.DAT", "r") && vcc_file_error() == DECB_ERR_CORRUPT_DIR);
CHECK(!fopen("SIDE.TXT", "r") && vcc_file_error() == DECB_ERR_NOT_FOUND);
a = fopen("SIDE.TXT:1", "r");
CHECK(a && fgetc(a) == '1' && fclose(a) == 0);
// An application may already be using the sector API on this drive.
CHECK(decb_init(&callerDrive, 1) == DECB_OK);
CHECK(decb_registerDrive(0) == DECB_OK);
CHECK(decb_getNumFreeGranules(0, &freeBefore) == DECB_OK);
// Mark the caller's cached FAT dirty without changing the byte itself.
// A stream must neither overwrite nor discard the caller's pending FAT.
CHECK(decb_setFATEntry(0, 0, callerDrive.fatBuffer[0]) == DECB_OK);
CHECK(!fopen("FENCE.DAT", "w") && vcc_file_error() == DECB_ERR_ALREADY_EXISTS);
CHECK(callerDrive.fatNeedsSave);
callerDrive.fatNeedsSave = FALSE; // fixture wrote the identical value above
a = fopen("mixed.txt:0", "r");
b = fopen("SHORT.DAT", "rb");
CHECK(a && b);
CHECK(!fopen("SHORT.DAT", "rb") && vcc_file_error() == DECB_ERR_OUT_OF_SPACE);
CHECK(fgets(text, 1, a) == text && !text[0]);
for (i = 0; i < 255; ++i) CHECK(fgetc(a) == 'A');
// The CR and LF forming this one line ending came from different sectors.
CHECK(fgetc(a) == '\n');
CHECK(fgets(text, 3, a) == text && strcmp(text, "BE") == 0);
CHECK(fgets(text, sizeof(text), a) == text && strcmp(text, "TA\n") == 0);
CHECK(fgets(text, sizeof(text), a) == text && strcmp(text, "RED\n") == 0);
CHECK(fgets(text, sizeof(text), a) == text && strcmp(text, "LAST") == 0);
CHECK(!fgets(text, sizeof(text), a) && feof(a) && !ferror(a));
CHECK(fclose(a) == 0);
// Zero count and zero size must leave both the file position and flags alone.
CHECK(!fread(sector, 3, 0, b) && !fread(sector, 0, 3, b) && !feof(b));
CHECK(fgetc(b) == 0);
CHECK(fgetc(b) == 255);
// A 16-bit size*count would wrap to zero. Only seven input bytes remain.
memset(sector, 0xee, 8);
CHECK(fread(sector, 2, 32768U, b) == 3);
for (i = 0; i < 7; ++i) CHECK(sector[i] == i + 1);
CHECK(sector[7] == 0xee && feof(b) && !ferror(b));
CHECK(fclose(b) == 0);
// Both empty-file encodings occur on DECB disks.
for (i = 0; i < 2; ++i) {
a = fopen(i ? "EMPTY1.DAT" : "EMPTY0.DAT", "rb");
CHECK(a && !feof(a));
CHECK(fgetc(a) == EOF && feof(a) && !ferror(a));
CHECK(fclose(a) == 0);
}
a = fopen("LARGE.DAT:0", "rb");
CHECK(a);
// 65,792 bytes cross both a granule boundary and the guest's 16-bit limit.
for (i = 0; i < 257; ++i) {
CHECK(fread(sector, 16, 16, a) == 16);
CHECK(sector[0] == (byte)i && sector[255] == (byte)(i + 255));
}
CHECK(!feof(a) && !ferror(a));
CHECK(fgetc(a) == EOF && feof(a) && !ferror(a));
CHECK(fclose(a) == 0);
CHECK(decb_getNumFreeGranules(0, &freeAfter) == DECB_OK && freeBefore == freeAfter);
decb_shutdown();
a = fopen("LARGE.DAT", "rb");
CHECK(a && fread(sector, 1, 256, a) == 256);
printf("EJECT DISK\n");
while (waitkey(0) != 'X') {}
CHECK(fgetc(a) == EOF && ferror(a) == DECB_ERR_IO && !feof(a));
CHECK(fgetc(a) == EOF && ferror(a) == DECB_ERR_IO && !feof(a));
CHECK(fclose(a) == 0);
printf("STREAMS PASSED\n");
return 0;
}
+89
View File
@@ -0,0 +1,89 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../guest-captures.h"
using namespace BasicDiskTests;
enum class Scenario { qualification, direct, disk, edited };
static void run(const fs::path& roms, const fs::path& disk, const fs::path& binary,
Processor cpu, Profile profile, Scenario scenario, bool capture = false) {
const bool survey = scenario != Scenario::qualification;
const bool diskLaunch = scenario == Scenario::disk || scenario == Scenario::edited;
Session session(roms, disk, cpu, profile);
const auto reads = session.reads(), otherReads = session.otherReads();
if (diskLaunch) session.type("LOADM\"SURVEY\":EXEC\r");
else session.launch(binary);
if (survey) {
session.until("2 MARS");
session.type(diskLaunch ? "2" : "1");
const char *report = "SURVEY: EARTH\nTRAITS: BLUE AND WET\nORBIT FROM SUN: 3";
if (scenario == Scenario::disk)
report = "SURVEY: MARS\nTRAITS: RED AND COLD\nORBIT FROM SUN: 4";
if (scenario == Scenario::edited)
report = "SURVEY: MARS ORBIT\nTRAITS: DUSTY AND COLD\nORBIT FROM SUN: 4";
session.until(std::string(report) + "\nSURVEY COMPLETE");
if (capture) {
session.until("OK");
session.frames(3);
saveActiveFrame(*session.machine.snapshot().frame, "survey.ppm");
}
} else {
session.until("EJECT DISK");
}
require(session.reads() > reads && session.otherReads() == otherReads, "Wrong guest device serviced reads");
session.verifyMedia();
if (!survey) {
session.eject();
session.type("X");
session.until("STREAMS PASSED");
}
session.verifyReturn();
}
static void checkMalformedRecords(const fs::path& roms, const fs::path& example, Processor cpu) {
Session session(roms, example / "malformed/BAD.DSK", cpu, Profile::fd);
for (const char* choice : {"1", "2"}) {
session.launch(example / "SURVEY.bin");
session.until("2 MARS");
session.type(choice);
session.until("INVALID SURVEY RECORD");
require(session.machine.copyScreenText().find("SURVEY COMPLETE") == std::string::npos,
"A malformed record was reported as complete");
session.verifyReturn();
}
session.verifyMedia();
}
int main(int argc, char** argv) {
try {
require(argc == 9, "Usage: run ROMDIR QUAL_DISK QUAL_BIN PROFILE SURVEY_PROJECT EDITED_PROJECT CONFIG CAPTURE");
const fs::path example = argv[5], edited = argv[6];
const std::string name = argv[4];
Profile profile;
if (name == "disk") profile = Profile::fd;
else if (name == "rgb-hd") profile = Profile::rgbHD;
else if (name == "rgb-fd") profile = Profile::rgbFD;
else if (name == "sdc") profile = Profile::sdc;
else throw std::invalid_argument("Unknown profile");
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
auto label = name + (cpu == Processor::MC6809 ? " 6809" : " 6309");
if (std::string(argv[7]) == "Debug") {
run(argv[1], argv[2], argv[3], cpu, profile, Scenario::qualification);
std::cout << "PASS " << label << " stream qualification, unchanged medium, I/O error and BASIC return" << std::endl;
}
const auto binary = example / "SURVEY.bin";
run(argv[1], example / "SURVEY.dsk", binary, cpu, profile, Scenario::direct);
run(argv[1], example / "SURVEY.dsk", binary, cpu, profile, Scenario::disk,
cpu == Processor::MC6809 && std::string(argv[8]) == "capture");
run(argv[1], edited / "SURVEY.dsk", binary, cpu, profile, Scenario::edited);
std::cout << "PASS " << label << " " << argv[7] << " Planet Survey direct Earth, disk Mars and edited Mars Orbit, traits and orbit" << std::endl;
if (profile == Profile::fd) {
checkMalformedRecords(argv[1], example, cpu);
std::cout << "PASS " << label << " " << argv[7] << " missing trait and invalid orbit" << std::endl;
}
}
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 1;
}
}
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Standalone CMOC preprocessing regression checks (set VCC_TOOLCHAIN to test another runtime)."""
import os
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
RUNTIME = Path(os.environ.get('VCC_TOOLCHAIN', ROOT / 'platforms/macos/LocalResources/ToolchainBundle'))
@unittest.skipUnless((RUNTIME / 'bin/cpp').is_file(), 'Locally staged compiler runtime unavailable')
class InlineAssemblyCompatibility(unittest.TestCase):
def preprocess(self, source, **files):
with tempfile.TemporaryDirectory(prefix='vcc-cpp-regression-') as folder:
work = Path(folder)
(work / 'main.c').write_text(source)
for name, content in files.items(): (work / name).write_text(content)
return subprocess.run([str(RUNTIME / 'bin/cpp'), '-xc++', '-undef', '-nostdinc', 'main.c'],
cwd=work, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def test_assembly_macro_operands_preserve_c_token_boundaries(self):
result = self.preprocess('''#define COUNT 32
#define MINUS -
#define TEXT(x) #x
const char *literal = "asm { ldb #COUNT }";
const char *words = TEXT(hello world);
int expression(int a, int b) { return a-MINUS b; }
void f(void) {
asm {
ldb #COUNT
leax -COUNT,x
fcc "hello world"
}
}
''')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertRegex(result.stdout, r'ldb #32\b')
self.assertRegex(result.stdout, r'leax -32,x\b')
self.assertRegex(result.stdout, r'a-\s+-\s+b')
self.assertIn('"asm { ldb #COUNT }"', result.stdout)
self.assertIn('"hello world"', result.stdout)
def test_multiple_blocks_headers_and_source_markers(self):
result = self.preprocess('''#include "values.h"
#line 91 "game/main.c"
void a(void) { asm {
ldb #VALUE
} }
void b(void) { asm {
leax -VALUE,x
} }
''', **{'values.h': '#define VALUE 17\n'})
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('# 91 "game/main.c"', result.stdout)
self.assertIn('ldb #17', result.stdout)
self.assertIn('leax -17,x', result.stdout)
def test_c_invalid_token_paste_still_fails(self):
result = self.preprocess('''#define BAD(a,b) a##b
int value = BAD(+,*);
void f(void) { asm { rts } }
''')
self.assertNotEqual(result.returncode, 0)
self.assertIn('error', result.stderr)
def test_preprocessor_failure_preserves_source_line(self):
result = self.preprocess('#line 72 "broken.c"\n#error EXPECTED_FAILURE\n')
self.assertNotEqual(result.returncode, 0)
self.assertIn(':72: error', result.stderr)
self.assertIn('EXPECTED_FAILURE', result.stderr)
def test_real_machine_code_matches_macro_immediate(self):
with tempfile.TemporaryDirectory(prefix='vcc-cpp-code-') as folder:
work = Path(folder)
(work / 'main.c').write_text('''#include <cmoc.h>
#define VALUE 42
asm unsigned char number(void) {
asm {
ldb #VALUE
rts
}
}
int main(void) { return number() != 42; }
''')
env = dict(os.environ, PATH=str(RUNTIME / 'bin') + ':/usr/bin:/bin',
DEVELOPER_DIR='/VCC-no-developer-tools', SDKROOT='/VCC-no-sdk')
result = subprocess.run([str(RUNTIME / 'bin/cmoc'), '--coco', '--intermediate', '-O0',
'-o', 'main.bin', 'main.c'], cwd=work, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
self.assertEqual(result.returncode, 0, result.stdout)
listing = (work / 'main.lst').read_text()
self.assertRegex(listing, r'C62A\s+.*ldb\s+#42')
self.assertIn(bytes.fromhex('c62a39'), (work / 'main.bin').read_bytes())
if __name__ == '__main__': unittest.main()
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Ensure distributed project templates contain authored sources, not local builds."""
import importlib.util
from pathlib import Path
import shutil
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SPEC = importlib.util.spec_from_file_location('development_templates', ROOT / 'platforms/macos/Tools/prepare-development-templates.py')
TEMPLATES = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(TEMPLATES)
class DevelopmentTemplateTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='vcc-template-')
self.root = Path(self.temp.name).resolve()
self.source = self.root / 'source'
shutil.copytree(ROOT / 'examples/cmoc/HelloDisk', self.source)
self.destination = self.root / 'VCC Plus.app/Contents/Resources/DevelopmentTemplates'
def tearDown(self):
self.temp.cleanup()
def test_source_only_copy_removes_stale_payload_and_ignores_local_products(self):
(self.source / 'HELLO.bin').write_bytes(b'private local program')
(self.source / 'HELLO.dsk').write_bytes(b'private local disk')
self.destination.mkdir(parents=True)
(self.destination / 'stale.bin').write_bytes(b'old')
TEMPLATES.stage(self.source, self.destination)
actual = {p.relative_to(self.destination / 'HelloDisk').as_posix()
for p in (self.destination / 'HelloDisk').rglob('*') if p.is_file()}
self.assertEqual(actual, set(TEMPLATES.HELLO_DISK_FILES))
self.assertFalse((self.destination / 'stale.bin').exists())
for relative in actual:
self.assertEqual((self.source / relative).read_bytes(), (self.destination / 'HelloDisk' / relative).read_bytes())
def test_linked_or_missing_source_fails_before_replacing_existing_template(self):
self.destination.mkdir(parents=True)
marker = self.destination / 'unchanged'
marker.write_text('preserve')
(self.source / 'main.c').unlink()
(self.source / 'main.c').symlink_to(ROOT / 'examples/cmoc/HelloDisk/main.c')
with self.assertRaises(ValueError):
TEMPLATES.stage(self.source, self.destination)
self.assertEqual(marker.read_text(), 'preserve')
def test_cleanup_is_restricted_to_app_template_directory(self):
with self.assertRaises(ValueError):
TEMPLATES.stage(self.source, self.source)
self.assertTrue((self.source / 'main.c').is_file())
if __name__ == '__main__':
unittest.main()
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
import hashlib
from pathlib import Path
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'tools/toolchain'))
from runtime_inputs import STANDALONE_FILES, validate_private_inputs
class RuntimeInputsTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
hashes = {}
for name in STANDALONE_FILES:
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(name.encode())
hashes[name] = hashlib.sha256(path.read_bytes()).hexdigest()
self.record = {'privateRuntimeInputs': True, 'standaloneDisk': {
'profile': 'decb-derived-standalone', 'license': 'public-domain-except-DECB-derived-portions',
'sourceSHA256': 'a' * 64, 'filesSHA256': hashes}}
def testExplicitExtensionAndSourceOnlyRuntime(self):
validate_private_inputs(self.root, self.record)
for name in STANDALONE_FILES:
if not name.endswith('.h'): (self.root / name).unlink()
validate_private_inputs(self.root, {'privateRuntimeInputs': False})
def testUndeclaredPrivatePayloadRejected(self):
with self.assertRaises(ValueError): validate_private_inputs(self.root, {'privateRuntimeInputs': False})
with self.assertRaises(ValueError): validate_private_inputs(self.root, {'privateRuntimeInputs': True})
def testMissingOrModifiedNoticeRejected(self):
notice = self.root / 'LICENSES/DSKCON-STANDALONE-NOTICE.txt'
notice.write_text('incorrect GPL-only notice')
with self.assertRaises(ValueError): validate_private_inputs(self.root, self.record)
notice.unlink()
with self.assertRaises(ValueError): validate_private_inputs(self.root, self.record)
def testManifestCannotDeclareArbitraryPrivatePaths(self):
self.record['standaloneDisk']['filesSHA256']['../outside'] = 'a' * 64
with self.assertRaises(ValueError): validate_private_inputs(self.root, self.record)
if __name__ == '__main__': unittest.main()