Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -0,0 +1,209 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/core/AudioBuffer.h"
|
||||
#include "../../src/devices/Orchestra90Device.h"
|
||||
#include "../../src/core/FramePacing.h"
|
||||
#include "../../src/core/mc6821.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include <stdexcept>
|
||||
#include <cmath>
|
||||
#include <thread>
|
||||
#include <algorithm>
|
||||
using namespace VCC::Mac;
|
||||
namespace {
|
||||
void require(bool v,const char* text) { if(!v) throw std::runtime_error(text); }
|
||||
template<class F> void rejects(F f) { bool rejected=false; try { f(); } catch(const std::exception&) { rejected=true; } require(rejected,"Malformed cassette must be rejected"); }
|
||||
}
|
||||
void CheckAudioBuffer() {
|
||||
auto s=ConvertDAC(0x4000c000); require(s.left==0.5f && s.right==-0.5f,"Explicit signed PCM and stereo order");
|
||||
AudioBuffer ring; ring.gain=1;
|
||||
StereoSample input[2]={{.25f,-.5f},{.5f,-.25f}};
|
||||
float left[4],right[4]; ring.write(input,2); ring.read(left,right,4);
|
||||
require(left[0]==.25f && right[1]==-.25f && left[3]==0 && ring.underruns==2,"Bounded render fills underruns with silence");
|
||||
std::vector<StereoSample> full(9000,{1,-1}); ring.write(full.data(),full.size());
|
||||
require(ring.size()==8192 && ring.overruns==808,"Audio overflow bounded and counted");
|
||||
require(ring.submitted==9002 && ring.signalSamples==8194,"Diagnostics count submitted and accepted nonzero samples independently of gain");
|
||||
ring.clear(); ring.gain=0; ring.write(input,2); ring.read(left,right,2);
|
||||
require(left[0]==0 && right[1]==0 && ring.size()==0,"Mute still consumes audio clock");
|
||||
ring.gain=1;
|
||||
std::thread producer([&] { for(unsigned i=0;i<100000;++i) { while(ring.size()>=4000) std::this_thread::yield(); StereoSample value{float(i),-float(i)}; ring.write(&value,1); } });
|
||||
bool ordered=true;
|
||||
for(unsigned i=0;i<100000;++i) { while(!ring.size()) std::this_thread::yield(); ring.read(left,right,1); ordered &= left[0]==float(i) && right[0]==-float(i); }
|
||||
producer.join(); require(ordered,"Concurrent audio preserves order across wraparound");
|
||||
// Model an 80 ms producer stall while the device continues reading every 10 ms.
|
||||
// The previous 50 ms target would underrun during this interval.
|
||||
AudioBuffer reserve; reserve.gain = 1;
|
||||
std::vector<StereoSample> frame(739, {.25f, -.25f});
|
||||
while (reserve.size() < audioTargetSamples) reserve.write(frame.data(), frame.size());
|
||||
float blockLeft[441], blockRight[441];
|
||||
for (unsigned block = 0; block < 8; ++block) {
|
||||
reserve.read(blockLeft, blockRight, 441);
|
||||
require(blockLeft[440] == .25f && blockRight[440] == -.25f, "Audio reserve survives an 80 ms producer stall");
|
||||
}
|
||||
require(reserve.underruns == 0 && reserve.maximumRequest == 441, "Stall recovery preserves samples and records callback demand");
|
||||
while (reserve.size() < audioTargetSamples) reserve.write(frame.data(), frame.size());
|
||||
require(reserve.overruns == 0 && reserve.size() < audioTargetSamples + frame.size(), "Refill stays bounded to the target plus one guest frame");
|
||||
}
|
||||
void CheckAudioScheduling() {
|
||||
for(auto cpu:{Processor::MC6809,Processor::HD6309}) {
|
||||
MachineSession machine; machine.loadDiagnostic(cpu); machine.resume();
|
||||
pia1_write(4,0x21); pia1_write(12,0x23); pia1_write(128,0x20);
|
||||
unsigned samples=0;
|
||||
for(unsigned i=0;i<60;++i) { machine.advance(); auto a=machine.takeAudio(); samples+=a.size(); require(!a.empty() && a[0].left==.25f,"Real PIA DAC reaches audio frames"); }
|
||||
require(samples>44300 && samples<44400,"44.1 kHz audio follows nominal emulated NTSC time");
|
||||
machine.pause(); machine.advance(); require(machine.takeAudio().empty(),"Pause generates no samples");
|
||||
machine.softReset(); require(GetDACSample()==0 && GetCasSample()==0,"Reset clears PIA sound latches");
|
||||
machine.resume(); machine.advance(); require(machine.takeAudio().size()<800,"Reset schedules one sampler, not duplicate callbacks");
|
||||
}
|
||||
}
|
||||
void CheckAudioRouting() {
|
||||
struct SpeakerSource final : VCC::Devices::CartridgeDevice {
|
||||
std::uint16_t value = 0x8080;
|
||||
void reset() override { }
|
||||
void horizontalSync(VCC::Devices::DeviceHost&) override { }
|
||||
std::uint8_t readMemory(std::uint16_t) const override { return 0xff; }
|
||||
std::uint8_t readPort(std::uint8_t, VCC::Devices::DeviceHost&) override { return 0; }
|
||||
void writePort(std::uint8_t, std::uint8_t, VCC::Devices::DeviceHost&) override { }
|
||||
bool hasCartridgeAudioOutput() const override { return true; }
|
||||
std::uint16_t audio() const override { return value; }
|
||||
};
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
auto speaker = std::make_shared<SpeakerSource>();
|
||||
auto orchestra = std::make_shared<VCC::Devices::Orchestra90Device>();
|
||||
machine.cartridges().configure({nullptr, speaker, orchestra, nullptr, nullptr}, true, 4);
|
||||
machine.loadDiagnostic(cpu); machine.resume();
|
||||
auto mux = [&](unsigned selection) {
|
||||
pia0_write(0x34 | ((selection & 1) << 3), 0x01);
|
||||
pia0_write(0x34 | ((selection & 2) << 2), 0x03);
|
||||
};
|
||||
auto sample = [&](float left, float right, const char* reason) {
|
||||
machine.takeAudio(); machine.advance(); const auto pcm = machine.takeAudio();
|
||||
require(!pcm.empty() && std::all_of(pcm.begin(), pcm.end(), [&](auto value) {
|
||||
return value.left == left && value.right == right;
|
||||
}), reason);
|
||||
};
|
||||
pia1_write(0x34, 0x21); pia1_write(0x34, 0x23);
|
||||
// Joystick conversion writes the DAC while the sound gate is closed.
|
||||
pia1_write(252, 0x20);
|
||||
for (unsigned repeat = 0; repeat < 3; ++repeat) for (unsigned selection = 0; selection < 4; ++selection) {
|
||||
mux(selection); speaker->value = repeat == 0 ? 0x8080 : 0x10f0;
|
||||
sample(0, 0, "Disabled analog sound must remain silent through joystick-style mux changes");
|
||||
}
|
||||
pia1_write(0x3c, 0x23); mux(0);
|
||||
sample(126/256.0f, 126/256.0f, "Re-enabling sound reads the current DAC latch");
|
||||
speaker->value = 0x4080; mux(2);
|
||||
sample(-.25f, 0, "Cartridge SND is centered and selected only on its analog input");
|
||||
speaker->value = 0;
|
||||
sample(-.5f, -.5f, "A cartridge zero sample is a valid negative peak, not absence");
|
||||
speaker->value = 0x8080;
|
||||
sample(0, 0, "An idle cartridge midpoint is silence");
|
||||
mux(3); sample(0, 0, "Unused analog mux input is grounded");
|
||||
// The stopped cassette has midpoint128, even with a cartridge installed.
|
||||
mux(1); sample(0, 0, "Stopped tape does not leak cartridge sound");
|
||||
machine.cartridges().writePort(0x7a, 64); machine.cartridges().writePort(0x7b, 192);
|
||||
pia1_write(0x34, 0x23);
|
||||
for (unsigned selection = 0; selection < 4; ++selection) {
|
||||
mux(selection); sample(.25f, .75f, "External Orchestra-90 stereo bypasses the speaker gate and mux");
|
||||
}
|
||||
machine.cartridges().writePort(0x7a, 0); machine.cartridges().writePort(0x7b, 0);
|
||||
// Configure the one-bit output and check that it is independent too.
|
||||
pia1_write(0x30, 0x23); pia1_write(2, 0x22); pia1_write(0x34, 0x23); pia1_write(2, 0x22);
|
||||
sample(.5f, .5f, "Single-bit sound remains audible with the analog gate closed");
|
||||
machine.cartridges().writePort(0x7a, 255); machine.cartridges().writePort(0x7b, 0);
|
||||
mux(0); pia1_write(0x3c, 0x23);
|
||||
sample(1.0f, 254/256.0f, "Combined sources saturate instead of wrapping signed PCM");
|
||||
}
|
||||
}
|
||||
void CheckCassetteImages() {
|
||||
CassetteDeck deck; deck.mount({0x55,0x3c,0xa5},TapeFormat::CAS); deck.play();
|
||||
for(unsigned i=0;i<1000;++i) require(deck.tick(0)==128,"Motor gates tape movement");
|
||||
require(deck.snapshot().position==0,"Motor-off playback preserves position"); deck.motor(true);
|
||||
for(unsigned i=0;i<32000;++i) deck.tick(0);
|
||||
require(deck.snapshot().mode==TapeMode::Stopped && deck.snapshot().position==3,"CAS playback ends without wrapping");
|
||||
deck.seek(1000); require(deck.snapshot().position==3,"Seeking clamps to end of tape");
|
||||
deck.seek(1); require(deck.snapshot().position==1 && deck.snapshot().mode==TapeMode::Stopped,"Seeking stops at selected byte");
|
||||
deck.rewind(); require(deck.exportImage()==std::vector<std::uint8_t>({0x55,0x3c,0xa5}),"CAS export retains original bytes");
|
||||
rejects([&]{deck.mount({1,2,3},TapeFormat::WAV);});
|
||||
require(deck.exportImage().size()==3,"Failed mount leaves old tape intact");
|
||||
deck.record(TapeFormat::WAV); deck.motor(true);
|
||||
for(unsigned i=0;i<101;++i) deck.tick(i*2);
|
||||
auto wav=deck.exportImage(); require(deck.snapshot().dirty,"Export does not mark an unsaved recording as saved");
|
||||
deck.markSaved(); require(!deck.snapshot().dirty,"Successful save clears dirty state");
|
||||
require(wav.size()==146 && wav[40]==101,"WAV header sizes include odd-byte padding correctly");
|
||||
deck.mount(wav,TapeFormat::WAV); deck.play();
|
||||
for(unsigned i=0;i<101;++i) require(deck.tick(0)==i*2,"WAV recording reloads sample-exactly");
|
||||
auto truncated=wav; truncated.resize(30); rejects([&]{deck.mount(truncated,TapeFormat::WAV);});
|
||||
auto bad=wav; bad[22]=3; rejects([&]{deck.mount(bad,TapeFormat::WAV);});
|
||||
auto chunked=wav; chunked.insert(chunked.begin()+12,{'J','U','N','K',2,0,0,0,0,0}); chunked[4]+=10;
|
||||
deck.mount(chunked,TapeFormat::WAV); require(deck.snapshot().length==101,"WAV parser walks unknown chunks");
|
||||
// Independent PCM fixtures: stereo extrema at 22.05 kHz, each repeated twice
|
||||
// by the 44.1 kHz tape input. Exercise sign extension and float conversion.
|
||||
for(unsigned bits:{8,16,24,32}) for(unsigned encoding:{1,3}) {
|
||||
if(encoding==3 && bits!=32) continue;
|
||||
std::vector<std::uint8_t> fixture(44,0);
|
||||
auto put=[&](unsigned offset,std::uint32_t value,unsigned width) {
|
||||
for(unsigned j=0;j<width;++j) fixture[offset+j]=(value>>(8*j))&255;
|
||||
};
|
||||
const char* riff="RIFF"; const char* wave="WAVEfmt "; const char* data="data";
|
||||
std::copy_n(riff,4,fixture.begin()); std::copy_n(wave,8,fixture.begin()+8); std::copy_n(data,4,fixture.begin()+36);
|
||||
unsigned align=bits/8*2;
|
||||
put(16,16,4); put(20,encoding,2); put(22,2,2); put(24,22050,4);
|
||||
put(28,22050*align,4); put(32,align,2); put(34,bits,2); put(40,align*3,4); put(4,36+align*3,4);
|
||||
for(unsigned level=0;level<3;++level) for(unsigned channel=0;channel<2;++channel) {
|
||||
std::uint32_t sample=encoding==3 ? (level==0 ? 0xbf800000u : level==1 ? 0 : 0x3f800000u) :
|
||||
bits==8 ? (level==0 ? 0 : level==1 ? 128 : 255) :
|
||||
level==0 ? (std::uint32_t(1)<<(bits-1)) : level==1 ? 0 : (std::uint32_t(1)<<(bits-1))-1;
|
||||
for(unsigned j=0;j<bits/8;++j) fixture.push_back((sample>>(8*j))&255);
|
||||
}
|
||||
deck.mount(fixture,TapeFormat::WAV); deck.play();
|
||||
for(unsigned expected:{0,0,128,128,255,255}) require(deck.tick(0)==expected,"PCM/float stereo conversion and sample-rate normalization");
|
||||
if(encoding==3) { fixture[46]=0xc0; fixture[47]=0x7f; rejects([&]{deck.mount(fixture,TapeFormat::WAV);}); }
|
||||
}
|
||||
for(std::size_t n=0;n<wav.size();++n) {
|
||||
auto prefix=std::vector<std::uint8_t>(wav.begin(),wav.begin()+n);
|
||||
rejects([&]{deck.mount(prefix,TapeFormat::WAV);});
|
||||
}
|
||||
deck.eject(); rejects([&]{deck.play();});
|
||||
}
|
||||
void CheckCassetteMachine() {
|
||||
MachineSession machine; machine.loadDiagnostic();
|
||||
auto& deck=machine.cassette(); deck.mount({0x55,0xaa},TapeFormat::CAS); deck.setFast(true); deck.play();
|
||||
pia1_write(12,0x21); // actual PIA motor and data-register selection
|
||||
require(deck.snapshot().motor && deck.fastLoading(),"PIA motor connects to CAS transport");
|
||||
for(unsigned i=0;i<30000;++i) deck.tick(0);
|
||||
for(unsigned bit=0;bit<8;++bit) {
|
||||
require((pia1_read(0x20)&1)==1 && SafeMemRead8(0x83)==((0x55>>bit)&1?10:20),"Fast load supplies ROM pulse width");
|
||||
require((pia1_read(0x20)&1)==0,"Fast load alternates half bits");
|
||||
}
|
||||
require(deck.snapshot().position==1,"Fast load advances exactly one byte");
|
||||
machine.softReset(); require(!deck.snapshot().motor && deck.snapshot().position==1,"Soft reset stops motor and retains media position");
|
||||
machine.reset(); require(machine.cassette().snapshot().length==2,"Cold reset retains mounted tape");
|
||||
|
||||
// Tape is a mono speaker source. The two Orchestra-90 jacks are external.
|
||||
deck.record(TapeFormat::WAV);
|
||||
deck.motor(true);
|
||||
for (unsigned i = 0; i < 4096; ++i) deck.tick(160);
|
||||
deck.mount(deck.exportImage(), TapeFormat::WAV);
|
||||
deck.play();
|
||||
deck.motor(true);
|
||||
pia0_write(12, 0x01);
|
||||
pia0_write(4, 0x03);
|
||||
pia1_write(0x3c, 0x23); // explicitly enable the selected analog source
|
||||
require(GetMuxState() == PIA_MUX_CASSETTE, "Tape input selected");
|
||||
machine.resume();
|
||||
machine.advance();
|
||||
auto tapeOnly = machine.takeAudio();
|
||||
require(!tapeOnly.empty() && std::all_of(tapeOnly.begin(), tapeOnly.end(), [](auto sample) {
|
||||
return sample.left == .125f && sample.right == .125f;
|
||||
}), "Tape monitor plays its mono input on both channels");
|
||||
machine.cartridges().install(std::make_unique<VCC::Devices::Orchestra90Device>());
|
||||
machine.cartridges().writePort(0x7a, 32);
|
||||
machine.cartridges().writePort(0x7b, 160);
|
||||
machine.advance();
|
||||
auto mixed = machine.takeAudio();
|
||||
require(!mixed.empty() && std::all_of(mixed.begin(), mixed.end(), [](auto sample) {
|
||||
return sample.left == .25f && sample.right == .75f;
|
||||
}), "External left and right DACs remain audible alongside a playing tape");
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/BasicProgram.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include <stdexcept>
|
||||
#include <functional>
|
||||
#include <algorithm>
|
||||
using namespace VCC::Mac;
|
||||
namespace {
|
||||
void require(bool yes, const char* why) { if (!yes) throw std::runtime_error(why); }
|
||||
void rejects(const std::function<void()>& call) {
|
||||
try { call(); } catch (const std::exception&) { return; }
|
||||
throw std::runtime_error("Malformed BASIC input was accepted");
|
||||
}
|
||||
std::vector<BasicToken> dictionary() {
|
||||
return {{"GO",0x81},{"REM",0x82},{"'",0x83},{"ELSE",0x84},{"IF",0x85},{"DATA",0x86},{"PRINT",0x87},
|
||||
{"END",0x8a},{"TO",0xa5},{"THEN",0xa7},{"+",0xab},{"*",0xad},{"=",0xb3},
|
||||
{"HSCREEN",0xe4},{"LEFT$",0x9c,true}};
|
||||
}
|
||||
}
|
||||
void CheckBasicProgramTokens() {
|
||||
const auto dict = dictionary();
|
||||
const std::string source = "50 HSCREEN 0\n30 ? LEFT$(\"PRINT:REM\",2)\n10 REM PRINT remains text\n20 DATA PRINT,\"X:Y\":PRINT6*7\n40 IF A=1 THEN ?1 ELSE ?2 'PRINT\n60 XPRINT=1\n";
|
||||
const auto encoded = BasicProgram::encode(source, 0x2601, 0x7000, dict);
|
||||
const auto decoded = BasicProgram::decode(encoded, 0x2601, dict);
|
||||
require(decoded.find("10 REM PRINT remains text\n20 DATA PRINT,\"X:Y\":PRINT6*7") == 0, "BASIC sorting, REM or DATA changed");
|
||||
require(decoded.find("30 PRINT LEFT$(\"PRINT:REM\",2)") != std::string::npos, "Function/PRINT shortcut changed");
|
||||
require(decoded.find("40 IF A=1 THEN PRINT1 ELSE PRINT2 'PRINT") != std::string::npos, "ELSE/apostrophe did not roundtrip");
|
||||
require(decoded.find("60 XPRINT=1") != std::string::npos, "Embedded keyword in identifier changed");
|
||||
require(BasicProgram::encode(decoded,0x2601,0x7000,dict) == encoded, "BASIC decode/encode is not byte stable");
|
||||
std::vector<BasicSourceLocation> locations;
|
||||
require(BasicProgram::encode(source,0x2601,0x7000,dict,&locations) == encoded, "Debug mapping changed program bytes");
|
||||
require(!locations.empty(), "Missing BASIC source map");
|
||||
for (const auto& location : locations) {
|
||||
require(location.address >= 0x2605 && location.address < 0x2601 + encoded.size(), "Source map address outside program");
|
||||
require(location.length > 0 && location.offset + location.length <= source.size(), "Source map span outside editor");
|
||||
const auto token = encoded[location.address - 0x2601];
|
||||
if (token == 0x87) require(source.substr(location.offset, location.length) == "PRINT" || source.substr(location.offset, location.length) == "?", "PRINT map misses original spelling");
|
||||
}
|
||||
require(BasicProgram::decode(BasicProgram::encode("\n\r\n",0x2601,0x7000,dict),0x2601,dict).empty(), "Empty BASIC program failed");
|
||||
require(BasicProgram::decode(BasicProgram::encode("10 print \"Mixed Case\"\r\n",0x2601,0x7000,dict),0x2601,dict) == "10 PRINT \"Mixed Case\"\n", "Case normalization changed a string");
|
||||
}
|
||||
void CheckBasicProgramValidation() {
|
||||
const auto dict = dictionary();
|
||||
for (const auto& bad : {"PRINT 1", "64000 PRINT1", "10 PRINT1\n10 PRINT2", "10 PRINT\x01", "10 PRINT \xc3\xa9"})
|
||||
rejects([&] { BasicProgram::encode(bad,0x2601,0x7000,dict); });
|
||||
rejects([&] { BasicProgram::encode("10 REM " + std::string(250,'X'),0x2601,0x7000,dict); });
|
||||
rejects([&] { BasicProgram::encode("10 PRINT1",0x2601,0x2608,dict); });
|
||||
auto encoded = BasicProgram::encode("10 PRINT1\n20 END",0x2601,0x7000,dict);
|
||||
auto bad = encoded; bad[0]=0;bad[1]=1;
|
||||
rejects([&] { BasicProgram::decode(bad,0x2601,dict); });
|
||||
bad=encoded;bad.back()=1;
|
||||
rejects([&] { BasicProgram::decode(bad,0x2601,dict); });
|
||||
bad=encoded;bad[4]=0xfe;
|
||||
rejects([&] { BasicProgram::decode(bad,0x2601,dict); });
|
||||
const auto disk = BasicProgram::exportImage(encoded,"hello",BasicExportFormat::Disk);
|
||||
require(disk.size()==161280, "BASIC export disk geometry differs");
|
||||
constexpr unsigned fat=(17*18+1)*256, entry=(17*18+2)*256;
|
||||
require(std::string(disk.begin()+entry,disk.begin()+entry+11)=="HELLO BAS" && disk[entry+11]==0 && disk[entry+12]==0,
|
||||
"BASIC export directory metadata differs");
|
||||
require(disk[0]==0xff && ((unsigned(disk[1])<<8)|disk[2])==encoded.size() &&
|
||||
std::equal(encoded.begin(),encoded.end(),disk.begin()+3), "BASIC disk file differs from SAVE binary layout");
|
||||
require(disk[fat]==0xc1 && disk[fat+1]==0xff && disk[entry+15]==encoded.size()+3, "BASIC disk allocation differs");
|
||||
// Exercise exact-sector size and a file spanning multiple granules.
|
||||
for (std::size_t size : {std::size_t(253),std::size_t(4608)}) {
|
||||
std::vector<std::uint8_t> payload(size,0); auto image=BasicProgram::exportImage(payload,"BOUNDARY",BasicExportFormat::Disk);
|
||||
const auto length=size+3, count=(length+2303)/2304;
|
||||
require(image[entry+14]*256+image[entry+15]==(length-1)%256+1, "Last-sector length is wrong");
|
||||
for(std::size_t g=0;g<count;++g) require(image[fat+g]==(g+1<count?g+1:0xc0+((length-g*2304)+255)/256), "Granule chain is wrong");
|
||||
}
|
||||
const auto tape=BasicProgram::exportImage(encoded,"hello",BasicExportFormat::Cassette);
|
||||
std::vector<std::uint8_t> recovered; std::size_t at=0; unsigned blocks=0; bool eof=false;
|
||||
while(at<tape.size()) {
|
||||
while(at<tape.size() && tape[at]==0x55) ++at;
|
||||
require(at+4<=tape.size() && tape[at++]==0x3c, "Cassette block marker missing");
|
||||
const auto type=tape[at++], length=tape[at++]; unsigned sum=type+length;
|
||||
require(at+length+2<=tape.size(), "Cassette block truncated");
|
||||
if(type==0) require(length==15 && std::string(tape.begin()+at,tape.begin()+at+8)=="HELLO " && tape[at+8]==0 && tape[at+9]==0 && tape[at+10]==0,"Cassette BASIC name metadata differs");
|
||||
else if(type==1) recovered.insert(recovered.end(),tape.begin()+at,tape.begin()+at+length);
|
||||
else { require(type==0xff && length==0, "Cassette EOF differs"); eof=true; }
|
||||
for(unsigned i=0;i<length;++i)sum+=tape[at++];
|
||||
require(tape[at++]==(sum&255) && tape[at++]==0x55,"Cassette checksum/trailer differs"); ++blocks;
|
||||
if(eof)break;
|
||||
}
|
||||
require(eof && at==tape.size() && blocks==3 && recovered==encoded,"Cassette payload did not roundtrip");
|
||||
for(const auto& name:{"","LONGERTHAN8","A.BAS","HI THERE","../A","CAFÉ"}) rejects([&]{BasicProgram::exportImage(encoded,name,BasicExportFormat::Disk);});
|
||||
rejects([&]{BasicProgram::exportImage({},"HELLO",BasicExportFormat::Cassette);});
|
||||
rejects([&]{BasicProgram::exportImage(std::vector<std::uint8_t>(0x5900,0),"HELLO",BasicExportFormat::Disk);});
|
||||
rejects([&]{BasicProgram::exportImage({0,1},"HELLO",BasicExportFormat::Cassette);});
|
||||
rejects([&]{BasicProgram::exportImage(encoded,"HELLO",static_cast<BasicExportFormat>(99));});
|
||||
// Decoder guardrails use synthetic RAM, independent of proprietary ROMs.
|
||||
std::vector<std::uint8_t> memory(0x8000,0);
|
||||
auto word = [&](unsigned at, unsigned v) { memory[at] = v >> 8; memory[at+1] = v & 255; };
|
||||
word(0x19,0x2601); word(0x1b,0x2610); word(0x1d,0x2617); word(0x1f,0x2617); word(0x21,0x7000);
|
||||
memory[0x2610]='A'; memory[0x2612]=0x81; memory[0x2613]=0xc0; // -1.5
|
||||
require(BasicProgram::inspect(memory).at(0).value=="-1.5", "BASIC numeric format differs");
|
||||
memory[0x2611]=0x80; memory[0x2612]=3; word(0x2614,0x4000);
|
||||
memory[0x4000]='a'; memory[0x4001]=0; memory[0x4002]=255;
|
||||
require(BasicProgram::inspect(memory).at(0).value=="\"a\\x00\\xFF\"", "String escaping or flag differs");
|
||||
word(0x2614,0xff00);
|
||||
require(BasicProgram::inspect(memory).at(0).value.find("Unavailable") == 0,"String device address accepted");
|
||||
memory[0x2612]=0;
|
||||
require(BasicProgram::inspect(memory).at(0).value=="\"\"", "Empty string dereferenced an unused pointer");
|
||||
auto saved=memory;
|
||||
for (unsigned ptr : {0x1bu,0x1du,0x1fu,0x21u}) { word(ptr,0xffff); rejects([&]{ BasicProgram::inspect(memory); }); memory=saved; }
|
||||
word(0x1d,0x2618); rejects([&]{ BasicProgram::inspect(memory); }); memory=saved;
|
||||
// Array descriptor: two dimensions (source order 2,3), six elements.
|
||||
word(0x1f,0x2617+39); memory[0x2617]='M'; word(0x2619,39); memory[0x261b]=2;
|
||||
word(0x261c,3); word(0x261e,2);
|
||||
auto array=BasicProgram::inspect(memory).at(1);
|
||||
require(array.dimensions==std::vector<unsigned>({2,3}) && array.elements.size()==6,"Array dimensions are not in source order");
|
||||
saved=memory;
|
||||
for(unsigned badsize : {0u,8u,38u,40u,65535u}) { word(0x2619,badsize); rejects([&]{ BasicProgram::inspect(memory); }); memory=saved; }
|
||||
for(unsigned rank : {0u,3u,255u}) { memory[0x261b]=rank; rejects([&]{ BasicProgram::inspect(memory); }); memory=saved; }
|
||||
for(unsigned length : {0u,65535u}) { word(0x261c,length); rejects([&]{ BasicProgram::inspect(memory); }); memory=saved; }
|
||||
rejects([&]{ BasicProgram::inspect(std::vector<std::uint8_t>(2)); });
|
||||
MachineSession machine;
|
||||
rejects([&] { machine.basicReadSource(); }); rejects([&] { machine.basicLoadSource("10 PRINT1",true); });
|
||||
machine.loadDiagnostic();
|
||||
const auto before=machine.snapshot();
|
||||
rejects([&] { machine.basicLoadSource("10 PRINT1",true); });
|
||||
require(machine.snapshot().cpu.PC == before.cpu.PC && machine.snapshot().cycles == before.cycles, "Rejected BASIC load changed diagnostic execution");
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/BinaryImage.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/core/MachineHost.h"
|
||||
#include "../../src/devices/FD502/Fd502Device.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include "../../src/core/Event.h"
|
||||
#include <algorithm>
|
||||
using namespace VCC::Mac;
|
||||
namespace {
|
||||
void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); }
|
||||
template<class F> void rejects(F operation) {
|
||||
bool rejected = false;
|
||||
try { operation(); } catch (const std::exception&) { rejected = true; }
|
||||
require(rejected, "Invalid binary must be rejected");
|
||||
}
|
||||
using Bytes = std::vector<std::uint8_t>;
|
||||
void block(Bytes& file, std::uint16_t address, const Bytes& bytes) {
|
||||
file.insert(file.end(), {0, std::uint8_t(bytes.size() >> 8), std::uint8_t(bytes.size()),
|
||||
std::uint8_t(address >> 8), std::uint8_t(address)});
|
||||
file.insert(file.end(), bytes.begin(), bytes.end());
|
||||
}
|
||||
void finish(Bytes& file, std::uint16_t entry = 0x3000) {
|
||||
file.insert(file.end(), {255,0,0,std::uint8_t(entry >> 8),std::uint8_t(entry)});
|
||||
}
|
||||
Bytes program() {
|
||||
Bytes file; block(file, 0x3000, {0x86,0x6b,0xb7,0x50,0,0x20,0xfe}); // LDA #$6B; STA $5000; BRA *
|
||||
finish(file); return file;
|
||||
}
|
||||
void checkPausedGraphicsBuffers(Processor processor) {
|
||||
MachineSession machine; machine.loadDiagnostic(processor); machine.pause();
|
||||
machine.setVideoOutput(VideoOutput::RGB);
|
||||
auto* ram = Get_mem_pointer();
|
||||
constexpr unsigned address = 0x10000, length = 160 * 192;
|
||||
std::fill_n(ram + address, length, 0x22);
|
||||
const auto before = machine.snapshot();
|
||||
const Bytes original(ram, ram + GetMMUState().RAMBytes);
|
||||
const DebugGraphicsBuffer back{"back", address, DebugGraphicsMode::HSCREEN2};
|
||||
const auto capture = machine.debuggerGraphicsCapture(back);
|
||||
const auto after = machine.snapshot();
|
||||
require(capture.declared && capture.declaredIdentifier == "back" && capture.displayed.address == 0 &&
|
||||
capture.declared->address == address && capture.displayed.width == 320 && capture.displayed.height == 192 &&
|
||||
capture.displayed.bytesPerRow == 160 && capture.declared->bytes == Bytes(length, 0x22),
|
||||
"Paused graphics capture identifies the actual display and explicitly declared physical buffer on both CPUs");
|
||||
require(capture.displayed.palette == capture.declared->palette && capture.displayed.pixels.front() != capture.declared->pixels.front() &&
|
||||
capture.declared->pixels.front() == 0x00ff00,
|
||||
"Declared preview renders its actual bytes using the same captured palette rather than duplicating the display image");
|
||||
require(capture.displayed.generation == capture.declared->generation && capture.displayed.cycles == capture.declared->cycles &&
|
||||
before.generation == after.generation && before.cycles == after.cycles && before.frames == after.frames &&
|
||||
before.cpu.PC == after.cpu.PC && before.frame == after.frame &&
|
||||
std::equal(original.begin(), original.end(), ram),
|
||||
"Paired captures do not execute the guest, publish a new raster frame or change RAM");
|
||||
const auto withoutBack = machine.debuggerGraphicsCapture();
|
||||
require(!withoutBack.declared && withoutBack.displayed.pixels == capture.displayed.pixels,
|
||||
"A displayed-only stopped preview needs no inferred back buffer");
|
||||
std::fill_n(ram + address, length, 0x33);
|
||||
const auto changed = machine.debuggerGraphicsCapture(back);
|
||||
require(capture.declared->bytes.front() == 0x22 && changed.declared->bytes.front() == 0x33 &&
|
||||
capture.declared->pixels.front() != changed.declared->pixels.front(),
|
||||
"Graphics snapshots own immutable bytes and reflect later authored buffer updates only in a new snapshot");
|
||||
// Guest video writes can select another page before a raster is published.
|
||||
// The fresh preview identifies this register selection, never a guessed
|
||||
// provenance for the previous published Frame.
|
||||
VCC::Machine().VideoWrite(VCC::VideoRegister::Offset, address / 8);
|
||||
const auto selected = machine.debuggerGraphicsCapture();
|
||||
require(selected.displayed.address == address && selected.displayed.bytes.front() == 0x33 &&
|
||||
machine.snapshot().frame == before.frame && machine.snapshot().cycles == before.cycles,
|
||||
"Current video-register selection is distinct from published-frame history without advancing the guest");
|
||||
rejects([&] { machine.debuggerGraphicsCapture(DebugGraphicsBuffer{"outside", GetMMUState().RAMBytes - 1, DebugGraphicsMode::HSCREEN2}); });
|
||||
rejects([&] { machine.debuggerGraphicsCapture(DebugGraphicsBuffer{"invalid", 0, static_cast<DebugGraphicsMode>(255)}); });
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cycles == before.cycles,
|
||||
"Rejected buffer ranges and formats preserve paused execution state");
|
||||
machine.resume();
|
||||
rejects([&] { machine.debuggerGraphicsCapture(back); });
|
||||
require(machine.snapshot().state == RunState::Running && machine.snapshot().cycles == before.cycles,
|
||||
"A paired capture requires an explicit pause and cannot pause or advance a running machine");
|
||||
}
|
||||
void checkCurrentGimeCanvases(Processor processor) {
|
||||
MachineSession machine; machine.loadDiagnostic(processor); machine.pause();
|
||||
machine.setVideoOutput(VideoOutput::RGB);
|
||||
auto* ram = Get_mem_pointer();
|
||||
const auto ramSize = GetMMUState().RAMBytes;
|
||||
const auto writeVideo = [](VCC::VideoRegister reg, unsigned value) { VCC::Machine().VideoWrite(reg, value); };
|
||||
writeVideo(VCC::VideoRegister::Compatibility, 0);
|
||||
writeVideo(VCC::VideoRegister::Mode, 0x80);
|
||||
writeVideo(VCC::VideoRegister::HorizontalOffset, 0xfe); // 256-byte pitch, pan 252, horizontal row wrap.
|
||||
for (const auto height : {225u, 192u}) {
|
||||
const unsigned front = height == 225 ? 0 : 0x40000, back = height == 225 ? 0x20000 : 0x50000;
|
||||
std::fill_n(ram + front, 65536, 0x11); std::fill_n(ram + back, 65536, 0x22);
|
||||
// Distinguish the last four bytes of a row from its wrapped beginning.
|
||||
ram[front + 4096 + 252] = 0x33; ram[front + 4096] = 0x44;
|
||||
ram[back + 4096 + 252] = 0x22; ram[back + 4096] = 0x11;
|
||||
writeVideo(VCC::VideoRegister::Resolution, height == 225 ? 0x7e : 0x1e);
|
||||
writeVideo(VCC::VideoRegister::Offset, (front + 4096) / 8);
|
||||
const std::vector<DebugGraphicsBuffer> canvases{
|
||||
{"front", front, DebugGraphicsMode::CurrentGime, false, 65536},
|
||||
{"back", back, DebugGraphicsMode::CurrentGime, false, 65536}};
|
||||
const auto before = machine.snapshot();
|
||||
const Bytes memory(ram, ram + ramSize);
|
||||
const auto capture = machine.debuggerGraphicsCapture(canvases[1], canvases);
|
||||
const auto& a = capture.displayed; const auto& b = *capture.declared;
|
||||
require(a.width == 320 && a.height == height && b.width == 320 && b.height == height &&
|
||||
a.bytesPerRow == 160 && a.rowStrideBytes == 256 && b.rowStrideBytes == 256 &&
|
||||
a.horizontalOffsetBytes == 252 && b.horizontalOffsetBytes == 252 &&
|
||||
a.canvasIdentifier == "front" && b.canvasIdentifier == "back" &&
|
||||
a.canvasAddress == front && b.canvasAddress == back && a.canvasBytes == 65536 && b.canvasBytes == 65536 &&
|
||||
a.viewportOffset == 4096 && b.viewportOffset == 4096 &&
|
||||
a.videoOrigin == front + 4096 && b.videoOrigin == back + 4096,
|
||||
"Custom GIME previews preserve actual 225/192-row geometry, pitch, pan and viewport offset on both CPUs");
|
||||
require(a.address == front + 4096 + 252 && b.address == back + 4096 + 252 &&
|
||||
a.byteAddresses[3] == front + 4096 + 255 && a.byteAddresses[4] == front + 4096 &&
|
||||
b.byteAddresses[4] == back + 4096 && a.byteAddresses[160] == front + 4096 + 256 + 252 &&
|
||||
a.bytes.front() == 0x33 && a.bytes[4] == 0x44 && b.bytes.front() == 0x22 && b.bytes[4] == 0x11 &&
|
||||
a.pixels.front() == 0x0000ff && b.pixels.front() == 0x00ff00 &&
|
||||
a.pixels[8] != a.pixels.front() && a.palette == b.palette,
|
||||
"Custom GIME previews render live physical samples with real 256-byte horizontal wrap and palette");
|
||||
const auto after = machine.snapshot();
|
||||
require(a.generation == b.generation && a.cycles == b.cycles && before.generation == after.generation &&
|
||||
before.cycles == after.cycles && before.frames == after.frames && before.cpu.PC == after.cpu.PC &&
|
||||
before.debuggerMappingFingerprint == after.debuggerMappingFingerprint && before.frame == after.frame &&
|
||||
std::equal(memory.begin(), memory.end(), ram),
|
||||
"Custom paired previews do not advance either guest CPU, change RAM/MMU or publish a frame");
|
||||
writeVideo(VCC::VideoRegister::Offset, (back + 4096) / 8);
|
||||
const auto flipped = machine.debuggerGraphicsCapture(canvases[0], canvases);
|
||||
require(flipped.displayed.canvasIdentifier == "back" && flipped.displayed.pixels == b.pixels &&
|
||||
flipped.declared->canvasIdentifier == "front" && flipped.declared->pixels == a.pixels &&
|
||||
capture.displayed.bytes.front() == 0x33,
|
||||
"A live canvas flip selects its real declared identity and rebases the other immutable viewport");
|
||||
rejects([&] { machine.debuggerGraphicsCapture(canvases[0]); });
|
||||
auto invalid = canvases; invalid[0].canvasBytes = 61440;
|
||||
rejects([&] { machine.debuggerGraphicsCapture(invalid[0], invalid); });
|
||||
invalid = canvases; invalid[0].physicalAddress += 4096;
|
||||
rejects([&] { machine.debuggerGraphicsCapture(invalid[0], invalid); });
|
||||
invalid = canvases; invalid[0].physicalAddress = ramSize;
|
||||
rejects([&] { machine.debuggerGraphicsCapture(invalid[0], invalid); });
|
||||
invalid = canvases; invalid[0].canvasBytes = 0;
|
||||
rejects([&] { machine.debuggerGraphicsCapture(invalid[0], invalid); });
|
||||
invalid = canvases; invalid[1].physicalAddress = front;
|
||||
rejects([&] { machine.debuggerGraphicsCapture(invalid[0], invalid); });
|
||||
invalid = canvases; invalid[1].canvasBytes = 8192;
|
||||
rejects([&] { machine.debuggerGraphicsCapture(invalid[1], invalid); });
|
||||
writeVideo(VCC::VideoRegister::Offset, (front + 0xf000) / 8);
|
||||
rejects([&] { machine.debuggerGraphicsCapture(canvases[1], canvases); });
|
||||
const std::vector<DebugGraphicsBuffer> allRam{{"whole", 0, DebugGraphicsMode::CurrentGime, false, ramSize}};
|
||||
writeVideo(VCC::VideoRegister::Offset, (ramSize - 4096) / 8);
|
||||
rejects([&] { machine.debuggerGraphicsCapture(allRam[0], allRam); });
|
||||
require(machine.snapshot().cycles == before.cycles && std::equal(memory.begin(), memory.end(), ram),
|
||||
"Out-of-canvas raster addresses are refused without inventing vertical wrapping or mutating the guest");
|
||||
writeVideo(VCC::VideoRegister::Offset, front / 8);
|
||||
writeVideo(VCC::VideoRegister::Mode, 0); // A future graphics canvas can currently contain BASIC text.
|
||||
const auto text = machine.debuggerGraphicsCapture(std::nullopt, canvases);
|
||||
require(text.displayed.text && text.displayed.canvasIdentifier.empty(),
|
||||
"Text registers inside a declared canvas are not falsely identified as a live graphics canvas");
|
||||
rejects([&] { machine.debuggerGraphicsCapture(canvases[1], canvases); });
|
||||
writeVideo(VCC::VideoRegister::Mode, 0x80);
|
||||
}
|
||||
}
|
||||
void checkBankedDevelopment(Processor processor) {
|
||||
MachineSession machine; machine.loadDiagnostic(processor);
|
||||
MmuSetMapType(1); Set_MmuEnabled(1); SetMmuRegister(0, 0); SetMmuRegister(2, 2);
|
||||
auto* ram = Get_mem_pointer();
|
||||
const Bytes a{0x12,0x20,0xfe}, b{0x12,0x12,0x20,0xfe};
|
||||
std::copy(a.begin(), a.end(), ram + 2 * 8192);
|
||||
std::copy(b.begin(), b.end(), ram + 3 * 8192);
|
||||
std::copy(a.begin(), a.end(), ram + 4 * 8192); // Identical code in an unqualified bank.
|
||||
const std::vector<DebugBankedModule> modules{
|
||||
{"a", {{2,2}}, {{0x4000,a}}},
|
||||
{"b", {{2,3}}, {{0x4000,b}}}
|
||||
};
|
||||
machine.debuggerSetPC(0x4000);
|
||||
machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, modules);
|
||||
const auto armed = machine.snapshot();
|
||||
require(armed.debuggerBankedDevelopment && armed.debuggerDevelopmentAttached,
|
||||
"Banked attachment verifies the current module without requiring overlapping overlays simultaneously");
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x4000,
|
||||
"Bank-qualified source stop fires before the mapped instruction on both CPUs");
|
||||
SetMmuRegister(2, 3);
|
||||
require(machine.snapshot().debuggerDevelopmentAttached && machine.snapshot().debuggerBankedDevelopment &&
|
||||
machine.snapshot().debuggerMappingFingerprint != armed.debuggerMappingFingerprint,
|
||||
"Expected overlay switch preserves banked attachment despite a changed flat fingerprint");
|
||||
ram[3 * 8192 + 1] = 0x39;
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached,
|
||||
"Banked source identity checks complete module code beyond a coincidentally matching current opcode");
|
||||
ram[3 * 8192 + 1] = 0x12;
|
||||
SetMmuRegister(2, 4);
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached && machine.snapshot().debuggerBankedDevelopment,
|
||||
"Identical bytes in a different physical RAM page cannot claim source identity");
|
||||
machine.debuggerSetPC(0x4000); machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Running,
|
||||
"Conditional source point ignores a matching opcode in the wrong physical bank");
|
||||
machine.pause(); machine.debuggerClearDevelopmentBreakpoints();
|
||||
auto qualified = modules;
|
||||
qualified[0].breakpointAddresses = std::vector<std::uint16_t>{0x4000};
|
||||
qualified[1].breakpointAddresses = std::vector<std::uint16_t>{};
|
||||
SetMmuRegister(2, 3); machine.debuggerSetPC(0x4000);
|
||||
machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, qualified);
|
||||
require(machine.snapshot().debuggerDevelopmentAttached,
|
||||
"A module without selected source stops remains available for source inspection and stepping");
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Running,
|
||||
"A source breakpoint in overlay a does not stop overlay b at the same logical address and opcode");
|
||||
machine.pause(); SetMmuRegister(2, 2); machine.debuggerSetPC(0x4000);
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x4000,
|
||||
"The selected module's source point still stops in its physical bank");
|
||||
machine.debuggerSetBreakpoints({0x4567});
|
||||
machine.debuggerArmBankedDevelopmentBreakpoints({}, modules);
|
||||
require(machine.snapshot().debuggerBankedDevelopment && machine.snapshot().debuggerDevelopmentAttached &&
|
||||
machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>{0x4567},
|
||||
"Inspect-only bank attachment preserves module evidence and independent manual breakpoints");
|
||||
machine.resume(); machine.advance(); machine.pause();
|
||||
require(machine.snapshot().debuggerDevelopmentAttached,
|
||||
"Pause after continuing without source stops can still inspect verified banked code");
|
||||
machine.debuggerClearDevelopmentBreakpoints(); machine.debuggerSetBreakpoints({});
|
||||
qualified[0].breakpointAddresses = std::vector<std::uint16_t>{0x4001};
|
||||
rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, qualified); });
|
||||
qualified[0].breakpointAddresses = std::vector<std::uint16_t>{};
|
||||
rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, qualified); });
|
||||
require(!machine.snapshot().debuggerBankedDevelopment,
|
||||
"Unqualified points cannot replace a valid source-breakpoint configuration");
|
||||
SetMmuRegister(2, 4);
|
||||
machine.debuggerSetBreakpoints({0x4000});
|
||||
machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, modules);
|
||||
machine.debuggerSetPC(0x4000); machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && !machine.snapshot().debuggerDevelopmentAttached,
|
||||
"An independently owned manual point still stops in an unqualified bank");
|
||||
machine.debuggerClearDevelopmentBreakpoints();
|
||||
require(machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>{0x4000},
|
||||
"Clearing banked source stops preserves independently owned manual points");
|
||||
machine.debuggerSetBreakpoints({});
|
||||
rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, {{"bad",{{1,2}},modules[0].guards}}); });
|
||||
rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, {{"bad",{{2,64}},modules[0].guards}}); });
|
||||
rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, {modules[0],modules[0]}); });
|
||||
auto ambiguous = modules[0]; ambiguous.identifier = "ambiguous";
|
||||
rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000}, {modules[0],ambiguous}); });
|
||||
require(!machine.snapshot().debuggerBankedDevelopment && machine.debuggerSnapshot().breakpoints.empty(),
|
||||
"Invalid banked configurations leave breakpoint ownership unchanged");
|
||||
|
||||
// A resident thunk selects overlay b while stepping. Logical instruction
|
||||
// addresses overlap with overlay a, including their first identical opcode.
|
||||
const Bytes thunk{0x86,0x03,0xb7,0xff,0xa2,0x7e,0x40,0x00};
|
||||
std::copy(thunk.begin(), thunk.end(), ram + 0x1000);
|
||||
auto steppingModules = modules;
|
||||
steppingModules.push_back({"resident",{{0,0}},{{0x1000,thunk}}});
|
||||
SetMmuRegister(2, 2); machine.debuggerSetPC(0x1000);
|
||||
machine.debuggerArmBankedDevelopmentBreakpoints({0x1000}, steppingModules);
|
||||
const std::vector<DebugSourceInstruction> instructions{
|
||||
{0x1000,1,{0x86,0x03},"resident"},{0x1002,1,{0xb7,0xff,0xa2},"resident"},{0x1005,1,{0x7e,0x40,0x00},"resident"},
|
||||
{0x4000,10,{0x12},"a"},{0x4001,11,{0x20,0xfe},"a"},
|
||||
{0x4000,20,{0x12},"b"},{0x4001,21,{0x12},"b"},{0x4002,22,{0x20,0xfe},"b"}
|
||||
};
|
||||
const auto start = machine.snapshot();
|
||||
rejects([&] { machine.debuggerStepSource(SourceStepMode::Into, instructions, start.generation,
|
||||
start.debuggerProgramRevision, start.debuggerMappingFingerprint + 1, start.cpu.PC); });
|
||||
machine.debuggerStepSource(SourceStepMode::Into, instructions, start.generation,
|
||||
start.debuggerProgramRevision, start.debuggerMappingFingerprint, start.cpu.PC);
|
||||
machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x4000 &&
|
||||
GetMMUState().Effective[2].SourceStart == 3 * 8192 && machine.snapshot().debuggerDevelopmentAttached &&
|
||||
machine.debuggerSnapshot().stopReason == "C source location reached",
|
||||
"Banked C step follows a verified resident bank switch and selects the matching overlay source");
|
||||
machine.debuggerClearDevelopmentBreakpoints();
|
||||
require(!machine.snapshot().debuggerBankedDevelopment, "Explicit detach clears bank-qualified mode");
|
||||
}
|
||||
void checkAssemblyInstructionBoundary(Processor processor) {
|
||||
MachineSession machine;
|
||||
machine.loadDiagnostic(processor);
|
||||
machine.debuggerConfigureBreakpoints({0x4567}, {0x3f02});
|
||||
Bytes binary;
|
||||
block(binary, 0x3f00, {0x86,0x8f,0xb7,0x04,0x00,0x20,0xfe});
|
||||
finish(binary, 0x3f00);
|
||||
const std::vector<DebugCodeGuard> guards{
|
||||
{0x3f00,{0x86,0x8f}}, {0x3f02,{0xb7,0x04,0x00}}, {0x3f05,{0x20,0xfe}}
|
||||
};
|
||||
const auto before = machine.snapshot();
|
||||
auto launch = [&](const std::vector<std::uint16_t>& points, const std::vector<DebugCodeGuard>& code,
|
||||
bool pause, bool hitachi, const Snapshot& expected) {
|
||||
machine.launchAssembly(binary, points, code, pause, hitachi, expected.generation, expected.debuggerProgramRevision, expected.debuggerMappingFingerprint);
|
||||
};
|
||||
MemWrite8(0x41, 0x0400);
|
||||
if (processor == Processor::MC6809) rejects([&] { launch({}, guards, true, true, before); });
|
||||
rejects([&] { launch({0x3f01}, guards, true, false, before); });
|
||||
rejects([&] { launch({}, {{0x3f02,{0xb7,0x04,0x01}}}, true, false, before); });
|
||||
require(machine.snapshot().cpu.PC == before.cpu.PC && machine.snapshot().debuggerProgramRevision == before.debuggerProgramRevision,
|
||||
"A rejected assembly launch preserves execution and ownership");
|
||||
launch({0x3f02}, guards, true, false, before);
|
||||
auto entry = machine.snapshot();
|
||||
require(entry.state == RunState::Paused && entry.cpu.PC == 0x3f00 && entry.cycles == before.cycles,
|
||||
"Debug from Entry stops before running any instruction");
|
||||
machine.controlAssembly(false, entry);
|
||||
machine.advance();
|
||||
auto store = machine.snapshot();
|
||||
require(store.state == RunState::Paused && store.cpu.PC == 0x3f02 && MemRead8(0x0400) == 0x41,
|
||||
"Assembly source breakpoint stops before the screen store");
|
||||
machine.controlAssembly(true, store);
|
||||
require(machine.snapshot().cpu.PC == 0x3f05 && MemRead8(0x0400) == 0x8f,
|
||||
"Step executes the store once");
|
||||
rejects([&] { machine.controlAssembly(true, store); });
|
||||
machine.updateAssembly({}, machine.snapshot());
|
||||
require(machine.debuggerSnapshot().disabledBreakpoints == std::vector<std::uint16_t>{0x3f02},
|
||||
"Removing an assembly point restores a disabled manual point");
|
||||
launch({}, guards, false, false, machine.snapshot());
|
||||
const auto repeated = machine.snapshot();
|
||||
machine.clearAssembly(entry);
|
||||
machine.advance();
|
||||
require(machine.snapshot().state == RunState::Running && machine.snapshot().debuggerDevelopmentAttached &&
|
||||
machine.snapshot().cpu.PC == 0x3f05, "Repeat run has no implicit breakpoint or stale ownership");
|
||||
const auto live = machine.snapshot();
|
||||
rejects([&] { machine.pauseAssembly(entry); });
|
||||
auto after = machine.snapshot();
|
||||
require(after.state == RunState::Running && after.cpu.PC == live.cpu.PC && after.cycles == live.cycles &&
|
||||
after.debuggerAssemblyAttached, "A queued Pause from the previous program leaves the new owner running");
|
||||
machine.pauseAssembly(repeated);
|
||||
after = machine.snapshot();
|
||||
require(after.state == RunState::Paused && after.cpu.PC == live.cpu.PC && after.cycles == live.cycles,
|
||||
"Pause honors the current owner after its guest has advanced");
|
||||
MemWrite8(0x12, 0x3f00);
|
||||
rejects([&] { machine.controlAssembly(true, machine.snapshot()); });
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached, "Changed instruction bytes invalidate source stepping");
|
||||
machine.clearAssembly(machine.snapshot());
|
||||
require(machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>{0x4567}, "Manual breakpoint survives source detach");
|
||||
}
|
||||
|
||||
}
|
||||
void CheckBinaryParsing() {
|
||||
Bytes file; block(file,0x1234,{1,2,3}); block(file,0xabcd,{}); block(file,0x1235,{4,5}); finish(file,0x7fff);
|
||||
const auto image = BinaryImage::parse(file);
|
||||
require(image.entry==0x7fff && image.blocks.size()==3, "Multi-record parser preserves entry and record order");
|
||||
require(image.blocks[0].address==0x1234 && image.blocks[0].bytes==Bytes({1,2,3}) &&
|
||||
image.blocks[1].address==0xabcd && image.blocks[1].bytes.empty() && image.blocks[2].bytes==Bytes({4,5}),
|
||||
"Headers are big-endian and zero-length/overlapping records are retained");
|
||||
Bytes jump; finish(jump,1); require(BinaryImage::parse(jump).blocks.empty(), "A transfer-only file retains the Windows jump behavior");
|
||||
Bytes large; block(large,0,Bytes(65535,0x5a)); finish(large);
|
||||
require(BinaryImage::parse(large).blocks[0].bytes.size()==65535, "Maximum 16-bit block length is accepted");
|
||||
}
|
||||
void CheckBinaryValidation() {
|
||||
const auto good = program();
|
||||
for (std::size_t size=0; size<good.size(); ++size)
|
||||
rejects([&] { BinaryImage::parse({good.begin(),good.begin()+size}); });
|
||||
for (unsigned type : {1u,2u,254u}) {
|
||||
auto bad=good; bad[0]=type; rejects([&] { BinaryImage::parse(bad); });
|
||||
}
|
||||
for (unsigned address : {0u,0x8000u,0xffffu}) {
|
||||
Bytes bad; finish(bad,address); rejects([&] { BinaryImage::parse(bad); });
|
||||
}
|
||||
auto bad=good; bad[bad.size()-3]=1; rejects([&] { BinaryImage::parse(bad); });
|
||||
bad=good; bad.push_back(0); rejects([&] { BinaryImage::parse(bad); });
|
||||
rejects([&] { BinaryImage::parse(Bytes(BinaryImage::maxBytes+1)); });
|
||||
// A valid first block followed by bad input must not reach memory or I/O.
|
||||
for (auto cpu : {Processor::MC6809,Processor::HD6309}) {
|
||||
MachineSession machine; machine.loadDiagnostic(cpu); machine.resume(); machine.advance();
|
||||
Bytes bytes; block(bytes,0x5000,{0x77}); block(bytes,0xffdf,{0}); bytes.push_back(9);
|
||||
const auto before=machine.snapshot(); const auto memory=Get_mem_pointer();
|
||||
const Bytes saved(memory,memory+0x80000); const auto events=VCC::gEvents.GetSize();
|
||||
rejects([&] { machine.quickLoad(bytes); });
|
||||
require(std::equal(saved.begin(),saved.end(),memory) && !MemCheckWrite(0x8000), "Late invalid header preserves all RAM and mapped I/O state");
|
||||
const auto after=machine.snapshot();
|
||||
require(after.state==before.state && after.cpu.PC==before.cpu.PC && after.cycles==before.cycles &&
|
||||
after.frame==before.frame && events==VCC::gEvents.GetSize(), "Rejected binary preserves execution and scheduled events");
|
||||
}
|
||||
}
|
||||
void CheckBinarySession() {
|
||||
MachineSession empty; rejects([&] { empty.quickLoad(program()); });
|
||||
for (auto cpu : {Processor::MC6809,Processor::HD6309}) {
|
||||
for (bool running : {false,true}) {
|
||||
MachineSession machine; machine.loadDiagnostic(cpu); machine.resume(); machine.advance();
|
||||
auto disk=std::make_shared<VCC::Devices::Fd502Device>(Bytes(8192));
|
||||
disk->mount(0,VCC::Devices::DiskImage::blank());
|
||||
machine.cartridges().configure({nullptr,nullptr,nullptr,nullptr,disk},true,4);
|
||||
machine.cassette().mount({0x55,0x3c},TapeFormat::CAS);
|
||||
MemWrite8(0xa5,0x6000); if (!running) machine.pause();
|
||||
MemWrite8(0xff,0xff02); MemWrite8(4,0xff03); MemWrite8(4,0xff01); MemWrite8(0xfd,0xff02);
|
||||
machine.setKeyboard(std::uint64_t{1}<<1);
|
||||
const auto before=machine.snapshot(); const auto events=VCC::gEvents.GetSize();
|
||||
machine.quickLoad(program()); const auto loaded=machine.snapshot();
|
||||
require(loaded.cpu.PC==0x3000 && loaded.state==RunState::Running, "Quick-load starts selected CPU at the execution record");
|
||||
require(MemRead8(0x6000)==0xa5 && loaded.frames==before.frames && loaded.cycles==before.cycles &&
|
||||
loaded.generation==before.generation && events==VCC::gEvents.GetSize(), "Quick-load retains unrelated memory, timing and machine identity");
|
||||
require(disk->image(0) && disk->image(0)->dirty() && machine.cassette().snapshot().mounted &&
|
||||
machine.cartridges().physicalSlot()==4, "Quick-load retains dirty floppy, cassette and cartridge assignments");
|
||||
require((MemRead8(0xff00)&0x7f)==0x7f, "Quick-load releases held keys");
|
||||
machine.advance(); require(MemRead8(0x5000)==0x6b && machine.snapshot().cpu.PC==0x3005, "Loaded program executes on both CPU engines");
|
||||
}
|
||||
}
|
||||
}
|
||||
void CheckBinaryMappedWrites() {
|
||||
checkPausedGraphicsBuffers(Processor::MC6809);
|
||||
checkPausedGraphicsBuffers(Processor::HD6309);
|
||||
checkCurrentGimeCanvases(Processor::MC6809);
|
||||
checkCurrentGimeCanvases(Processor::HD6309);
|
||||
checkBankedDevelopment(Processor::MC6809);
|
||||
checkBankedDevelopment(Processor::HD6309);
|
||||
checkAssemblyInstructionBoundary(Processor::MC6809);
|
||||
checkAssemblyInstructionBoundary(Processor::HD6309);
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine; machine.loadDiagnostic(cpu);
|
||||
machine.debuggerConfigureBreakpoints({0x4500}, {0x3005});
|
||||
machine.debuggerLoadBinary(program(), 0x3005);
|
||||
machine.advance();
|
||||
rejects([&] { machine.debuggerContinueFromEntry(0x3000); });
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x3005,
|
||||
"Continuing a different source stop preserves the actual stop");
|
||||
machine.debuggerContinueFromEntry(0x3005);
|
||||
machine.advance();
|
||||
require(machine.snapshot().state == RunState::Running && machine.snapshot().debuggerDevelopmentAttached &&
|
||||
machine.snapshot().cpu.PC == 0x3005, "Play continues through its one-time entry and retains the C program identity");
|
||||
require(machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>{0x4500} &&
|
||||
machine.debuggerSnapshot().disabledBreakpoints == std::vector<std::uint16_t>{0x3005},
|
||||
"The one-time C entry preserves independently configured manual breakpoints");
|
||||
machine.debuggerConfigureBreakpoints({0x4500}, {0x3005});
|
||||
machine.debuggerLoadBinary(program(), std::vector<std::uint16_t>{0x3000,0x3005});
|
||||
machine.advance(); require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x3000,
|
||||
"Multiple development points stop before the first instruction on both CPUs");
|
||||
require(machine.snapshot().debuggerDevelopmentAttached, "Atomic quickload attaches its verified source epoch");
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x3005,
|
||||
"Continuing passes only the current point and can stop in another source file");
|
||||
machine.debuggerClearDevelopmentBreakpoints();
|
||||
auto state = machine.debuggerSnapshot();
|
||||
require(state.breakpoints == std::vector<std::uint16_t>{0x4500} && state.disabledBreakpoints == std::vector<std::uint16_t>{0x3005},
|
||||
"Clearing development points preserves manual points and restores temporarily enabled ones");
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached, "Explicit detach clears source attachment");
|
||||
|
||||
// Guards cover code beyond the selected instruction, so a coincidentally
|
||||
// matching opcode in an earlier loader cannot be mistaken for the program.
|
||||
const std::vector<DebugCodeGuard> guards{{0x3000,{0x86,0x6b}}, {0x3002,{0xb7,0x50,0}}, {0x3005,{0x20,0xfe}}, {0x6000,{0x39}}};
|
||||
machine.debuggerSetPC(0x3000);
|
||||
machine.debuggerArmDevelopmentBreakpoints({}, guards);
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached,
|
||||
"Empty flat inspection guards do not invent an attachment before a verified stop");
|
||||
machine.debuggerArmDevelopmentBreakpoints({0x3000}, guards);
|
||||
const auto before = machine.snapshot(); machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Running && !machine.snapshot().debuggerDevelopmentAttached,
|
||||
"Disk-source points ignore boot code until every expected code range is loaded");
|
||||
machine.pause(); MemWrite8(0x39,0x6000); machine.debuggerSetPC(0x3000);
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x3000 &&
|
||||
machine.snapshot().debuggerDevelopmentAttached && machine.snapshot().generation == before.generation &&
|
||||
machine.snapshot().debuggerProgramRevision == before.debuggerProgramRevision,
|
||||
"Disk-loaded exact code attaches and stops without quickload or resetting the machine");
|
||||
const std::vector<DebugCodeGuard> mergedGuards{{0x3000,{0x86,0x6b,0xb7,0x50,0,0x20,0xfe}}, {0x6000,{0x39}}};
|
||||
machine.debuggerArmDevelopmentBreakpoints({}, mergedGuards);
|
||||
require(machine.snapshot().debuggerDevelopmentAttached,
|
||||
"Empty inspection preserves verified mapping when only guard segmentation changes");
|
||||
machine.resume(); machine.advance(); machine.pause();
|
||||
require(machine.snapshot().debuggerDevelopmentAttached && machine.snapshot().cpu.PC == 0x3005,
|
||||
"Flat continue removes selected stops while retaining verified code identity");
|
||||
MemWrite8(0x12,0x6000);
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached,
|
||||
"Paused capture rejects guest-modified executable bytes without debugger writes");
|
||||
MemWrite8(0x39,0x6000); machine.debuggerSetPC(0x3000);
|
||||
machine.debuggerArmDevelopmentBreakpoints({0x3000}, guards); machine.resume(); machine.advance();
|
||||
require(machine.snapshot().debuggerDevelopmentAttached,
|
||||
"A new verified stop can re-establish exact flat code and runtime mapping");
|
||||
machine.debuggerWriteMemory(0x6000,{0x12});
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached && machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>{0x4500},
|
||||
"Debugger writes cancel conditional source points and preserve manual points");
|
||||
machine.debuggerConfigureBreakpoints({0x3000,0x4500}, {0x3005});
|
||||
machine.debuggerSetPC(0x3000); machine.debuggerArmDevelopmentBreakpoints({0x3000}, guards);
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && !machine.snapshot().debuggerDevelopmentAttached,
|
||||
"An independently enabled manual breakpoint still stops before disk code is loaded");
|
||||
machine.debuggerClearDevelopmentBreakpoints();
|
||||
require(machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>({0x3000,0x4500}),
|
||||
"A shared manual breakpoint is never claimed by the development feature");
|
||||
rejects([&] { machine.debuggerArmDevelopmentBreakpoints({0x3001}, guards); });
|
||||
rejects([&] { machine.debuggerArmDevelopmentBreakpoints({0x3000}, {{0x3000,{0x12}}, {0x3000,{0x12}}}); });
|
||||
rejects([&] { machine.debuggerArmDevelopmentBreakpoints({0xff00}, {{0xff00,{0x12}}}); });
|
||||
machine.debuggerArmDevelopmentBreakpoints({0x3002}, guards); machine.softReset();
|
||||
require(!machine.snapshot().debuggerDevelopmentAttached &&
|
||||
machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>({0x3000,0x4500}),
|
||||
"Reset drops pending development points without erasing user breakpoints");
|
||||
}
|
||||
// The development loader is stricter than legacy quickload: two logical
|
||||
// spans must not overwrite the same physical RAM through MMU aliases.
|
||||
for (auto cpu : {Processor::MC6809,Processor::HD6309}) {
|
||||
MachineSession machine; machine.loadDiagnostic(cpu);
|
||||
const auto original = machine.snapshot();
|
||||
Set_MmuEnabled(1); SetMmuRegister(0,3); SetMmuRegister(1,3);
|
||||
const auto remapped = machine.snapshot();
|
||||
require(original.debuggerMappingFingerprint != remapped.debuggerMappingFingerprint,
|
||||
"Source provenance detects active MMU remapping without a reset");
|
||||
SetMmuRegister(9,12); // Task 1 is inactive.
|
||||
require(machine.snapshot().debuggerMappingFingerprint == remapped.debuggerMappingFingerprint,
|
||||
"Inactive-task register edits do not change effective source mapping");
|
||||
machine.debuggerSetBreakpoints({0x4500});
|
||||
Bytes image; block(image,0x0100,{0x12}); block(image,0x2100,{0x39}); finish(image,0x0100);
|
||||
auto* ram = Get_mem_pointer(); const auto previousByte = ram[3*8192+0x100];
|
||||
rejects([&] { machine.debuggerLoadBinary(image,0x0100); });
|
||||
require(ram[3*8192+0x100] == previousByte && machine.snapshot().debuggerProgramRevision == remapped.debuggerProgramRevision &&
|
||||
machine.debuggerSnapshot().breakpoints == std::vector<std::uint16_t>{0x4500},
|
||||
"Rejected aliased development image preserves RAM, breakpoints and provenance epoch");
|
||||
SetMmuRegister(1,4);
|
||||
machine.debuggerLoadBinary(image,0x0100);
|
||||
const auto loaded = machine.snapshot();
|
||||
require(loaded.debuggerProgramRevision > remapped.debuggerProgramRevision && loaded.generation == remapped.generation,
|
||||
"Successful development load changes program provenance without restarting machine");
|
||||
machine.pause(); machine.debuggerStep();
|
||||
require(machine.snapshot().debuggerProgramRevision == loaded.debuggerProgramRevision,
|
||||
"Pause and instruction stepping preserve program provenance");
|
||||
machine.debuggerWriteMemory(0x2100,{0x12});
|
||||
require(machine.snapshot().debuggerProgramRevision > loaded.debuggerProgramRevision,
|
||||
"Explicit debugger memory edits invalidate a loaded C source map");
|
||||
}
|
||||
for (auto cpu : {Processor::MC6809,Processor::HD6309}) {
|
||||
MachineSession machine; machine.loadDiagnostic(cpu);
|
||||
Set_MmuEnabled(1); SetMmuRegister(0,3); SetMmuRegister(1,9);
|
||||
Bytes file; block(file,0x1ffe,{1,2,3,4}); block(file,0x1fff,{9}); finish(file);
|
||||
machine.quickLoad(file);
|
||||
auto* ram=Get_mem_pointer();
|
||||
require(ram[3*8192+8190]==1 && ram[3*8192+8191]==9 && ram[9*8192]==3 && ram[9*8192+1]==4,
|
||||
"Ordered overlapping loads follow MMU mapping across a bank boundary");
|
||||
// Ordered I/O writes can change the mapping before a later data record.
|
||||
file.clear(); block(file,0xffa0,{5}); block(file,0x123,{0x7a}); block(file,0xffdf,{0});
|
||||
block(file,0x8000,{0x66}); block(file,0xfffe,{0x11,0x22,0x33,0x44}); finish(file);
|
||||
machine.quickLoad(file);
|
||||
require(GetMMUState().Task0[0]==5 && ram[5*8192+0x123]==0x7a && MemRead8(0x8000)==0x66,
|
||||
"Quick-load preserves live I/O writes and RAM under a disabled ROM overlay");
|
||||
require(MemRead8(0)==0x33 && MemRead8(1)==0x44, "Records wrap at the 16-bit address boundary");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "../../src/devices/DriveWireDevice.h"
|
||||
#include <algorithm>
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/devices/Ramdisk/memboard.h"
|
||||
#include "../../src/devices/ssc/tms7000.h"
|
||||
#include "../../src/devices/ssc/ssc_core.h"
|
||||
#include <array>
|
||||
#include <stdexcept>
|
||||
|
||||
static void require(bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
void CheckRamDisk() {
|
||||
require(!InitMemBoard(), "RAM disk allocation failed");
|
||||
// Same offset and bank values as the Windows guest probe.
|
||||
WritePort(0x40, 0x34); WritePort(0x41, 0x12);
|
||||
for (unsigned char bank = 0; bank < 8; ++bank) {
|
||||
WritePort(0x42, bank); WriteArray(17 + bank);
|
||||
}
|
||||
for (unsigned char bank = 0; bank < 8; ++bank) {
|
||||
WritePort(0x42, bank);
|
||||
require(ReadArray() == 17 + bank, "RAM disk bank data aliases another bank");
|
||||
require(ReadArray() == 17 + bank, "RAM disk read unexpectedly advances address");
|
||||
}
|
||||
// High address bits are masked to three bits by the hardware contract.
|
||||
WritePort(0x42, 0xff);
|
||||
require(ReadArray() == 24, "RAM disk bank mask differs");
|
||||
WritePort(0x40, 0xff); WritePort(0x41, 0xff);
|
||||
WriteArray(0xa5);
|
||||
require(ReadArray() == 0xa5, "Last RAM disk byte is inaccessible");
|
||||
require(!InitMemBoard(), "RAM disk reinitialization failed");
|
||||
require(ReadArray() == 0, "RAM disk address zero did not reset");
|
||||
WritePort(0x40, 0xff); WritePort(0x41, 0xff); WritePort(0x42, 7);
|
||||
require(ReadArray() == 0, "RAM disk reinitialization did not clear last byte");
|
||||
}
|
||||
|
||||
void CheckMicrocontroller() {
|
||||
std::array<uint8_t, 4096> rom{};
|
||||
rom.fill(0xff);
|
||||
rom[0] = 0xb3; // INC A
|
||||
rom[1] = 0xe0; rom[2] = 0xfd; // JMP back
|
||||
rom[4094] = 0xf0; rom[4095] = 0;
|
||||
ssc::Tms7000 cpu;
|
||||
cpu.LoadRom(rom.data(), rom.size()); cpu.Reset();
|
||||
require(cpu.PC() == 0xf000, "TMS7000 big-endian reset vector failed");
|
||||
const auto initial = cpu.PeekReg(0);
|
||||
int cycles = 0;
|
||||
for (int i = 0; i < 50; ++i) cycles += cpu.Execute(360);
|
||||
require(cycles == 18000, "TMS7000 cycle accounting differs");
|
||||
require(cpu.PC() == 0xf000, "TMS7000 branch target differs");
|
||||
require(cpu.PeekReg(0) == uint8_t(initial + 1500), "TMS7000 increment/wrap failed");
|
||||
}
|
||||
|
||||
void CheckCartridgeBus() {
|
||||
ssc::SscCore core;
|
||||
core.Reset();
|
||||
// An unaddressed cartridge must stay silent for MPI disk reads.
|
||||
for (int port = 0; port < 256; ++port)
|
||||
if (port != 0x7d && port != 0x7e)
|
||||
require(core.ReadPort(uint8_t(port)) == 0, "SSC intercepts another device's port");
|
||||
require(core.ReadPort(0x7d) == 0xff, "SSC control-port read differs");
|
||||
require((core.ReadPort(0x7e) & 0x80) != 0, "SSC initially busy");
|
||||
core.WritePort(0x7e, 0x55);
|
||||
require((core.ReadPort(0x7e) & 0x80) == 0, "SSC command did not assert busy");
|
||||
core.WritePort(0x7d, 0);
|
||||
require((core.ReadPort(0x7e) & 0x80) != 0, "SSC reset edge did not clear busy");
|
||||
}
|
||||
|
||||
namespace {
|
||||
using VCC::Devices::DriveWireDevice;
|
||||
using VCC::Devices::DriveWireTransport;
|
||||
|
||||
struct EchoWire final : DriveWireTransport {
|
||||
State status = State::connecting;
|
||||
std::deque<std::uint8_t> echo;
|
||||
State state() override { return status; }
|
||||
std::size_t read(std::uint8_t* bytes, std::size_t limit) override {
|
||||
std::size_t count = std::min(limit, echo.size());
|
||||
for (std::size_t i = 0; i < count; ++i) { bytes[i] = echo.front(); echo.pop_front(); }
|
||||
return count;
|
||||
}
|
||||
bool write(const std::uint8_t* bytes, std::size_t size) override {
|
||||
echo.insert(echo.end(), bytes, bytes + size);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
void CheckDriveWireProtocol() {
|
||||
DriveWireDevice dw;
|
||||
std::vector<EchoWire*> sockets;
|
||||
dw.setFactory([&](const std::string& host, std::uint16_t port) {
|
||||
require(host == "localhost" && port == 2323, "Wrong DriveWire TCP destination");
|
||||
auto socket = std::make_unique<EchoWire>();
|
||||
sockets.push_back(socket.get());
|
||||
return socket;
|
||||
});
|
||||
auto send = [&](std::initializer_list<std::uint8_t> bytes) {
|
||||
for (auto byte : bytes) dw.writePort(0x42, byte);
|
||||
};
|
||||
auto receive = [&](const std::vector<std::uint8_t>& expected) {
|
||||
for (auto byte : expected) {
|
||||
require(dw.readPort(0x41) == 2 && dw.readPort(0x41) == 2, "Becker polling consumed a byte");
|
||||
require(dw.readPort(0x42) == byte, "DriveWire response mismatch");
|
||||
}
|
||||
require(dw.readPort(0x41) == 0 && dw.readPort(0x42) == 0, "Unexpected trailing DriveWire response");
|
||||
};
|
||||
auto fast = [&](std::uint8_t channel, const std::string& data) {
|
||||
for (auto c : data) send({std::uint8_t(0x80 + channel), std::uint8_t(c)});
|
||||
};
|
||||
auto response = [&](std::uint8_t channel, const std::string& text) {
|
||||
send({0x43}); receive({std::uint8_t(17 + channel), std::uint8_t(text.size())});
|
||||
send({0x63, channel, std::uint8_t(text.size())}); receive({text.begin(), text.end()});
|
||||
};
|
||||
|
||||
// Only data-register writes feed packets. DWINIT responds after both bytes.
|
||||
dw.writePort(0x41, 0x43); send({0x5a}); receive({}); send({1}); receive({4});
|
||||
fast(0, "tcp connect localhost 2323\r");
|
||||
require(sockets.empty(), "Unopened DriveWire channel connected");
|
||||
|
||||
send({0x45, 0, 0xc4, 0, 0x29}); // driver Init and per-path SS.Open
|
||||
send({0xc4, 0, 0x28});
|
||||
for (unsigned i = 0; i < 26; ++i) send({0xff}); // opaque SS.ComSt descriptor
|
||||
fast(0, "TCP CONNECT localhost 2323\r");
|
||||
require(sockets.size() == 1, "Expected exactly one outbound connection");
|
||||
send({0x43}); receive({0, 0}); // socket handshaking
|
||||
sockets[0]->status = DriveWireTransport::State::connected;
|
||||
response(0, "SUCCESS\n\r");
|
||||
send({0xc4, 0, 0x29}); // duplicate open must preserve an active stream
|
||||
send({0x64, 0, 3, 0, 0xff, 0x43}); // preserve arbitrary bytes, including opcodes
|
||||
send({0x43}); receive({17, 3}); send({0x63, 0, 2}); receive({0, 0xff});
|
||||
send({0x43}); receive({1, 0x43});
|
||||
send({0xc3, 0, 0x7f}); sockets[0]->status = DriveWireTransport::State::closed;
|
||||
send({0x43}); receive({1, 0x7f}); // preserve bytes received just before EOF
|
||||
send({0x43}); receive({16, 0}); send({0x43}); receive({0, 0});
|
||||
|
||||
send({0x45, 2}); fast(2, "tcp listen 8080\r");
|
||||
response(2, "FAIL 203\n\r");
|
||||
send({0x43}); receive({16, 2});
|
||||
send({0x45, 2}); fast(2, "tcp connect localhost 99999\r");
|
||||
response(2, "FAIL 203\n\r");
|
||||
send({0x43}); receive({16, 2});
|
||||
require(sockets.size() == 1, "Invalid or inbound command created a socket");
|
||||
|
||||
send({0x45, 2}); fast(2, "tcp connect localhost 2323\r");
|
||||
sockets.back()->status = DriveWireTransport::State::failed;
|
||||
response(2, "FAIL 246\n\r");
|
||||
send({0x43}); receive({16, 2});
|
||||
|
||||
// Reset cancels an in-flight connection and restores byte framing.
|
||||
send({0x45, 2}); fast(2, "tcp connect localhost 2323\r");
|
||||
send({0xff, 0x43}); receive({0, 0});
|
||||
send({0x45, 2}); fast(2, "tcp connect localhost 2323\r");
|
||||
require(sockets.size() == 4, "Connection did not reopen after reset");
|
||||
sockets.back()->status = DriveWireTransport::State::connected;
|
||||
response(2, "SUCCESS\n\r");
|
||||
send({0xc5, 2, 0x43}); receive({0, 0});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
void CheckDriveWireProtocol();
|
||||
void CheckRamDisk();
|
||||
void CheckMicrocontroller();
|
||||
void CheckCartridgeBus();
|
||||
int smoke_cpu();
|
||||
int smoke_sp0256();
|
||||
int smoke_ay8913();
|
||||
int smoke_ssc_core();
|
||||
void Check6809Execution();
|
||||
void Check6309Execution();
|
||||
void Check6809Interrupts();
|
||||
void Check6309Interrupts();
|
||||
void Check6309Native();
|
||||
void CheckCpuDebugHooks();
|
||||
void CheckEventScheduler();
|
||||
void CheckMmuMapping();
|
||||
void CheckMmuRomAndVectors();
|
||||
void CheckMmuLifecycle();
|
||||
void CheckGimeRegisters();
|
||||
void CheckPiaRegisters();
|
||||
void CheckPiaInterrupts();
|
||||
void CheckMappedCpuExecution();
|
||||
void CheckVideoPixels();
|
||||
void CheckVideoModes();
|
||||
void CheckRasterTiming();
|
||||
void CheckGimeTimers();
|
||||
void CheckVideoLifecycle();
|
||||
void CheckFrameStops();
|
||||
void CheckRasterPixels();
|
||||
|
||||
void CheckSessionLifecycle();
|
||||
void CheckSessionReset();
|
||||
void CheckSessionFrameOwnership();
|
||||
void CheckSessionExclusion();
|
||||
void CheckSessionRomValidation();
|
||||
void CheckSessionKeyboard();
|
||||
void CheckSessionAutomaticBoot();
|
||||
void CheckRomBoot(const char* path); // optional user-ROM integration check
|
||||
void CheckSessionSoftReset();
|
||||
|
||||
void CheckAudioBuffer();
|
||||
void CheckAudioScheduling();
|
||||
void CheckAudioRouting();
|
||||
void CheckCassetteImages();
|
||||
void CheckCassetteMachine();
|
||||
void CheckDiskImages();
|
||||
void CheckFloppyCommands();
|
||||
void CheckFloppyTransfers();
|
||||
void CheckFloppyProtection();
|
||||
void CheckBuiltinDeviceBus();
|
||||
void CheckFloppySession();
|
||||
void CheckDiskRom(const char* systemPath, const char* diskPath); // optional supplied-ROM integration
|
||||
|
||||
void CheckHardDiskRom(const char* systemPath, const char* rgbPath, const char* imagePath, const char* dataPath = nullptr); // optional supplied-image integration
|
||||
|
||||
void CheckBinaryParsing();
|
||||
void CheckBinaryValidation();
|
||||
void CheckBinarySession();
|
||||
void CheckBinaryMappedWrites();
|
||||
|
||||
void CheckJoystickComparator();
|
||||
void CheckJoystickRamps();
|
||||
void CheckJoystickSession();
|
||||
|
||||
void CheckFramePacing();
|
||||
void CheckAudioProgress();
|
||||
void CheckAcceleratedTiming();
|
||||
|
||||
void CheckSessionVideoOutput();
|
||||
void CheckGraphicsPreviewModes();
|
||||
void CheckGraphicsPreviewColorSets();
|
||||
void CheckGraphicsPreviewRom(const char* systemPath, const char* diskPath, const char* programPath);
|
||||
|
||||
void CheckMachineMemorySettings();
|
||||
void CheckMachinePresentationSettings();
|
||||
void CheckConfiguredOverclock();
|
||||
|
||||
void CreateStarterMedia(const char* systemPath, const char* diskPath, const char* output);
|
||||
|
||||
void CreateHardBasicMedia(const char*, const char*, const char*, const char*);
|
||||
|
||||
void CheckSessionClipboard();
|
||||
void CheckClipboardRom(const char* path);
|
||||
|
||||
void CheckOrchestraRom(const char* systemPath, const char* orchestraPath, const char* outputPrefix);
|
||||
|
||||
void CheckSpeechSoundRom(const char* systemPath, const char* picPath, const char* speechPath, const char* outputPrefix);
|
||||
|
||||
void CheckBasicProgramTokens();
|
||||
void CheckBasicProgramValidation();
|
||||
void CheckBasicProgramRom(const char* systemPath, const char* diskPath);
|
||||
@@ -0,0 +1,311 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/CpuHost.h"
|
||||
#include "../../src/core/CpuMemory.h"
|
||||
#include "../../src/core/Event.h"
|
||||
#include "../../src/core/mc6809.h"
|
||||
#include "../../src/core/hd6309.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <initializer_list>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
// Test-only bus and joystick clock. These must never be linked into the app:
|
||||
// there is no ROM protection, MMU, GIME, I/O decoding, or peripheral emulation.
|
||||
namespace {
|
||||
std::array<unsigned char, 65536> memory;
|
||||
unsigned char mapType;
|
||||
struct FlatBus final : VCC::CpuMemoryBus {
|
||||
std::function<void(unsigned short)> beforeRead;
|
||||
unsigned char Read(unsigned short address) override {
|
||||
if (beforeRead) beforeRead(address);
|
||||
return memory[address];
|
||||
}
|
||||
void Write(unsigned char value, unsigned short address) override { memory[address] = value; }
|
||||
void SelectMap(unsigned char type) override { mapType = type; }
|
||||
};
|
||||
void require(bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
struct Hooks final : VCC::CpuDebugHooks {
|
||||
bool halted = false, stepping = false, enabled = false, tracing = false;
|
||||
std::vector<VCC::CPUState> before, after;
|
||||
std::vector<unsigned char> requested, serviced, executing;
|
||||
bool IsHalted() const override { return halted; }
|
||||
bool IsStepping() const override { return stepping; }
|
||||
void Halt() override { halted = true; stepping = false; }
|
||||
bool IsTracingEnabled() const override { return enabled; }
|
||||
bool IsTracing() const override { return tracing; }
|
||||
void TraceStart() override { tracing = true; }
|
||||
void TraceCaptureBefore(long, const VCC::CPUState& s) override { before.push_back(s); }
|
||||
void TraceCaptureAfter(long, const VCC::CPUState& s) override { after.push_back(s); }
|
||||
void TraceCaptureInterruptRequest(unsigned char irq, long, const VCC::CPUState&) override { requested.push_back(irq); }
|
||||
void TraceCaptureInterruptServicing(unsigned char irq, long, const VCC::CPUState&) override { serviced.push_back(irq); }
|
||||
void TraceCaptureInterruptExecuting(unsigned char irq, long, const VCC::CPUState&) override { executing.push_back(irq); }
|
||||
};
|
||||
struct Cpu {
|
||||
void (*init)();
|
||||
void (*reset)();
|
||||
int (*exec)(int);
|
||||
VCC::CPUState (*state)();
|
||||
void (*assertIRQ)(InterruptSource, Interrupt);
|
||||
void (*clearIRQ)(InterruptSource, Interrupt);
|
||||
void (*breakpoints)(const std::vector<unsigned short>&);
|
||||
void (*triggers)(const std::vector<unsigned short>&);
|
||||
};
|
||||
const Cpu m6809 {MC6809Init, MC6809Reset, MC6809Exec, MC6809GetState,
|
||||
MC6809AssertInterupt, MC6809DeAssertInterupt, MC6809SetBreakpoints, MC6809SetTraceTriggers};
|
||||
const Cpu h6309 {HD6309Init, HD6309Reset, HD6309Exec, HD6309GetState,
|
||||
HD6309AssertInterupt, HD6309DeAssertInterupt, HD6309SetBreakpoints, HD6309SetTraceTriggers};
|
||||
|
||||
struct Fixture {
|
||||
const Cpu& cpu;
|
||||
Hooks hooks;
|
||||
FlatBus bus;
|
||||
explicit Fixture(const Cpu& c) : cpu(c) {
|
||||
VCC::SetCpuMemoryBus(&bus);
|
||||
memory.fill(0);
|
||||
mapType = 255;
|
||||
VCC::gEvents.Reset();
|
||||
VCC::SetCpuDebugHooks(&hooks);
|
||||
cpu.init();
|
||||
cpu.breakpoints({}); cpu.triggers({});
|
||||
MemWrite16(0x4000, 0xfffe);
|
||||
cpu.reset();
|
||||
}
|
||||
~Fixture() {
|
||||
cpu.breakpoints({}); cpu.triggers({});
|
||||
VCC::SetCpuDebugHooks(nullptr);
|
||||
VCC::SetCpuMemoryBus(nullptr);
|
||||
VCC::gEvents.Reset();
|
||||
}
|
||||
void load(std::initializer_list<unsigned char> bytes, unsigned short address = 0x4000) {
|
||||
std::copy(bytes.begin(), bytes.end(), memory.begin() + address);
|
||||
}
|
||||
int instruction() { return 1 - cpu.exec(1); }
|
||||
};
|
||||
|
||||
void execution(const Cpu& cpu) {
|
||||
Fixture f(cpu);
|
||||
auto s = cpu.state();
|
||||
require(s.PC == 0x4000 && s.CC == 0x50 && s.A == 0 && s.B == 0 &&
|
||||
s.X == 0 && s.Y == 0 && s.U == 0 && s.S == 0 && s.DP == 0 && !s.IsNative6309,
|
||||
"CPU reset registers/vector/masks");
|
||||
require(mapType == 0, "CPU reset selects map zero");
|
||||
// Authored guest fixture: docs/macos/reference/cpu6809.asm, no ROM needed.
|
||||
f.load({0x1a,0x50,0x10,0xce,0x70,0x00,0x8e,0x41,0x00,0x4f,
|
||||
0xc6,0x10,0x4c,0xa7,0x80,0x5a,0x26,0xfa,0x20,0xfe});
|
||||
cpu.breakpoints({0x4012});
|
||||
f.hooks.enabled = true;
|
||||
const int cycles = 1000 - cpu.exec(1000);
|
||||
s = cpu.state();
|
||||
require(f.hooks.halted && s.PC == 0x4012 && s.A == 16 && s.B == 0 &&
|
||||
s.X == 0x4110 && s.S == 0x7000, "CPU guest loop final registers/breakpoint");
|
||||
for (unsigned i = 0; i < 16; ++i)
|
||||
require(memory[0x4100+i] == i+1, "CPU guest loop indexed stores");
|
||||
require(f.hooks.before.size() == 69 && f.hooks.after.size() == 69,
|
||||
"CPU guest loop executes 69 instructions");
|
||||
require(cycles == 222 && VCC::gEvents.GetClocks() == 222*16,
|
||||
"CPU guest loop cycle budget and scheduler clocks");
|
||||
|
||||
f.hooks.halted = false; cpu.breakpoints({}); cpu.reset();
|
||||
f.load({0x86,0x7f,0x8b,0x01,0x8b,0x80,0x80,0x01});
|
||||
require(f.instruction() == 2, "LDA immediate cycles");
|
||||
f.instruction(); s = cpu.state();
|
||||
require(s.A == 0x80 && (s.CC & 0x2f) == 0x2a, "ADDA signed overflow/half-carry flags");
|
||||
f.instruction(); s = cpu.state();
|
||||
require(s.A == 0 && (s.CC & 0x2f) == 0x07, "ADDA unsigned carry/zero/overflow flags");
|
||||
f.instruction(); s = cpu.state();
|
||||
require(s.A == 0xff && (s.CC & 0x0f) == 0x09, "SUBA borrow/negative flags");
|
||||
|
||||
cpu.reset();
|
||||
f.load({0xcc,0x12,0x34,0xfd,0xff,0xff}); // LDD #$1234; STD $FFFF
|
||||
f.instruction(); f.instruction();
|
||||
require(memory[0xffff] == 0x12 && memory[0] == 0x34, "CPU big-endian word store wraps bus address");
|
||||
}
|
||||
|
||||
// A changing peripheral flag must be sampled during TST, before instruction
|
||||
// completion/IRQ entry. An all-at-the-end tick starves polling loops whenever
|
||||
// the IRQ handler acknowledges the same flag. No proprietary guest code needed.
|
||||
void testOperandTiming(const Cpu& cpu) {
|
||||
for (unsigned mode = 0; mode < 4; ++mode) {
|
||||
// Direct, ,X, extended, and 8-bit indexed offset (extra EA cycle).
|
||||
const unsigned cycles = mode == 2 || mode == 3 ? 7 : 6;
|
||||
const unsigned readCycle = cycles - 2;
|
||||
for (unsigned edge = 1; edge <= cycles; ++edge) {
|
||||
Fixture f(cpu);
|
||||
f.load({0x86,0x42,0x1f,0x8b,0x8e,0x42,0x00,0x1a,0x03}); // DP=$42, X=$4200; set V/C
|
||||
for (unsigned n = 0; n < 4; ++n) f.instruction();
|
||||
if (mode == 0) f.load({0x0d,0x00}, 0x4009);
|
||||
if (mode == 1) f.load({0x6d,0x84}, 0x4009);
|
||||
if (mode == 2) f.load({0x7d,0x42,0x00}, 0x4009);
|
||||
if (mode == 3) f.load({0x6d,0x88,0x01}, 0x4009);
|
||||
const unsigned address = mode == 3 ? 0x4201 : 0x4200;
|
||||
const auto start = VCC::gEvents.GetClocks();
|
||||
unsigned reads = 0;
|
||||
f.bus.beforeRead = [&](unsigned short a) {
|
||||
if (a == address) {
|
||||
++reads;
|
||||
require(VCC::gEvents.GetClocks() - start == readCycle * 16,
|
||||
"TST samples operand after addressing/data cycles, before trailing cycles");
|
||||
}
|
||||
};
|
||||
// Place the edge just before the cycle boundary (scheduler intervals are half-open).
|
||||
VCC::gEvents.Queue(edge * 16 - 1, [&] { memory[address] = 0x80; }, 1);
|
||||
require(f.instruction() == cycles, "TST retains total instruction timing");
|
||||
require(reads == 1 && memory[address] == 0x80, "TST reads exactly once and advances pending events");
|
||||
require((cpu.state().CC & 0x0f) == (edge <= readCycle ? 0x09 : 0x05),
|
||||
"TST sees only edges before operand sampling, clears V and preserves C");
|
||||
}
|
||||
Fixture f(cpu);
|
||||
f.load({0x10,0xce,0x70,0x00,0x86,0x42,0x1f,0x8b,0x8e,0x42,0x00,0x1c,0xaf});
|
||||
for (unsigned n = 0; n < 5; ++n) f.instruction(); // LDS, LDA, TFR, LDX, ANDCC
|
||||
unsigned short passed = 0;
|
||||
if (mode == 0) { f.load({0x0d,0x00,0x2a,0xfc,0x12}, 0x400d); passed = 0x4011; }
|
||||
if (mode == 1) { f.load({0x6d,0x84,0x2a,0xfc,0x12}, 0x400d); passed = 0x4011; }
|
||||
if (mode == 2) { f.load({0x7d,0x42,0x00,0x2a,0xfb,0x12}, 0x400d); passed = 0x4012; }
|
||||
if (mode == 3) { f.load({0x6d,0x88,0x01,0x2a,0xfb,0x12}, 0x400d); passed = 0x4012; }
|
||||
const unsigned address = mode == 3 ? 0x4201 : 0x4200;
|
||||
f.load({0xb6,0x43,0x00,0x3b}, 0x5000); // IRQ: read peripheral acknowledge; RTI
|
||||
MemWrite16(0x5000, 0xfff8);
|
||||
unsigned acknowledgements = 0;
|
||||
f.bus.beforeRead = [&](unsigned short a) {
|
||||
if (a == 0x4300) {
|
||||
++acknowledgements;
|
||||
memory[address] = 0;
|
||||
cpu.clearIRQ(IS_PIA0_VSYNC, INT_IRQ);
|
||||
}
|
||||
};
|
||||
VCC::gEvents.Queue(2 * 16, [&] {
|
||||
memory[address] = 0x80;
|
||||
cpu.assertIRQ(IS_PIA0_VSYNC, INT_IRQ);
|
||||
}, 1);
|
||||
cpu.breakpoints({passed});
|
||||
cpu.exec(200);
|
||||
require(f.hooks.halted && cpu.state().PC == passed && acknowledgements == 1 &&
|
||||
memory[address] == 0 && cpu.state().S == 0x7000,
|
||||
"TST polling exits after IRQ acknowledges flag and RTI restores sampled condition codes");
|
||||
}
|
||||
}
|
||||
|
||||
void interrupts(const Cpu& cpu) {
|
||||
for (auto irq : {INT_IRQ, INT_FIRQ, INT_NMI}) {
|
||||
Fixture f(cpu);
|
||||
f.load({0x10,0xce,0x70,0x00,0x1c,0xaf,0x12}); // LDS; ANDCC clears I/F; NOP
|
||||
f.load({0x3b}, 0x5000); // RTI
|
||||
const unsigned short vector = irq == INT_IRQ ? 0xfff8 : irq == INT_FIRQ ? 0xfff6 : 0xfffc;
|
||||
MemWrite16(0x5000, vector);
|
||||
f.instruction(); f.instruction();
|
||||
const auto before = cpu.state();
|
||||
f.hooks.tracing = true;
|
||||
cpu.breakpoints({0x5000});
|
||||
const auto source = irq == INT_NMI ? IS_NMI : IS_GIME;
|
||||
cpu.assertIRQ(source, irq);
|
||||
if (irq != INT_NMI) {
|
||||
// Independent sources share a line; clearing one must not clear the other.
|
||||
cpu.assertIRQ(IS_PIA0_HSYNC, irq);
|
||||
cpu.clearIRQ(source, irq);
|
||||
}
|
||||
cpu.exec(100);
|
||||
const auto handler = cpu.state();
|
||||
const unsigned frameBytes = irq == INT_FIRQ ? 3 : 12;
|
||||
require(f.hooks.halted && handler.PC == 0x5000 && handler.S == 0x7000-frameBytes,
|
||||
"CPU interrupt vector and stack frame");
|
||||
require(MemRead16(0x6ffe) == before.PC, "CPU interrupt stacked return address");
|
||||
require((memory[handler.S] & 0x80) == (irq == INT_FIRQ ? 0 : 0x80),
|
||||
"CPU interrupt entire-state flag");
|
||||
require(f.hooks.serviced == std::vector<unsigned char>{static_cast<unsigned char>(irq)} &&
|
||||
f.hooks.executing == f.hooks.serviced && !f.hooks.requested.empty(),
|
||||
"CPU interrupt debug callbacks");
|
||||
cpu.clearIRQ(source, irq);
|
||||
if (irq != INT_NMI) cpu.clearIRQ(IS_PIA0_HSYNC, irq);
|
||||
cpu.breakpoints({}); f.hooks.halted = false;
|
||||
f.instruction();
|
||||
const auto restored = cpu.state();
|
||||
require(restored.PC == before.PC && restored.S == before.S &&
|
||||
restored.A == before.A && restored.B == before.B &&
|
||||
(restored.CC & 0x7f) == (before.CC & 0x7f), "CPU RTI restores interrupted state");
|
||||
}
|
||||
// Reset masks IRQ/FIRQ; reset also clears previously asserted sources.
|
||||
for (auto irq : {INT_IRQ, INT_FIRQ}) {
|
||||
Fixture f(cpu);
|
||||
f.load({0x12,0x12});
|
||||
cpu.assertIRQ(IS_GIME, irq);
|
||||
f.instruction();
|
||||
require(cpu.state().PC == 0x4001, "CPU masks IRQ/FIRQ after reset");
|
||||
cpu.reset();
|
||||
f.load({0x1c,0xaf,0x12});
|
||||
f.instruction(); f.instruction();
|
||||
require(cpu.state().PC == 0x4003, "CPU reset clears interrupt sources");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Check6809Execution() { execution(m6809); }
|
||||
void Check6309Execution() { execution(h6309); }
|
||||
void Check6809Interrupts() { interrupts(m6809); testOperandTiming(m6809); }
|
||||
void Check6309Interrupts() { interrupts(h6309); testOperandTiming(h6309); }
|
||||
|
||||
void Check6309Native() {
|
||||
Fixture f(h6309);
|
||||
// LDMD #1; LDQ #$12345678; STQ $4200; NOP.
|
||||
f.load({0x11,0x3d,0x01,0xcd,0x12,0x34,0x56,0x78,0x10,0xfd,0x42,0x00,0x12});
|
||||
f.instruction();
|
||||
require(h6309.state().IsNative6309, "6309 enters native mode");
|
||||
f.instruction();
|
||||
auto s = h6309.state();
|
||||
require(s.A == 0x12 && s.B == 0x34 && s.E == 0x56 && s.F == 0x78,
|
||||
"6309 LDQ register byte order");
|
||||
f.instruction();
|
||||
require(MemRead16(0x4200) == 0x1234 && MemRead16(0x4202) == 0x5678,
|
||||
"6309 STQ memory byte order");
|
||||
require(f.instruction() == 1, "6309 native NOP timing");
|
||||
h6309.reset(); f.load({0x12});
|
||||
require(!h6309.state().IsNative6309 && f.instruction() == 2,
|
||||
"6309 reset restores emulation mode timing");
|
||||
}
|
||||
|
||||
void CheckCpuDebugHooks() {
|
||||
for (const auto& cpu : {m6809, h6309}) {
|
||||
Fixture f(cpu);
|
||||
f.load({0x12,0x12,0x12,0x12});
|
||||
cpu.triggers({0x4001}); cpu.breakpoints({0x4003});
|
||||
f.hooks.enabled = true;
|
||||
cpu.exec(100);
|
||||
require(f.hooks.halted && f.hooks.before.size() == 2 && f.hooks.after.size() == 2 &&
|
||||
f.hooks.before.front().PC == 0x4001 && f.hooks.after.back().PC == 0x4003,
|
||||
"CPU trace trigger starts at requested instruction and stops before breakpoint");
|
||||
require(cpu.exec(10) == 10 && cpu.state().PC == 0x4003,
|
||||
"CPU halt consumes no cycles/instructions");
|
||||
f.hooks.halted = false; f.hooks.stepping = true;
|
||||
require(f.instruction() == 2 && cpu.state().PC == 0x4004 && f.hooks.halted,
|
||||
"CPU debugger single-step advances exactly one instruction");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckEventScheduler() {
|
||||
VCC::Event event;
|
||||
event.Tick(1);
|
||||
require(event.GetClocks() == 16, "Event constructor initializes default clock rate");
|
||||
event.Reset();
|
||||
std::vector<int> order;
|
||||
event.Queue(32, [&] { order.push_back(2); event.Queue(1, [&] { order.push_back(3); }); });
|
||||
event.Queue(16, [&] { order.push_back(1); });
|
||||
event.Tick(1);
|
||||
require(order.empty(), "Events at exact tick boundary remain queued");
|
||||
event.Tick(2);
|
||||
require(order == std::vector<int>({1,2,3}) && event.GetClocks() == 48,
|
||||
"Events run in clock order including reentrant queue");
|
||||
event.Queue(32, [&] { order.push_back(4); }, 1);
|
||||
event.ReQueue(16, [&] { order.push_back(5); }, 1);
|
||||
event.Queue(16, [&] { order.push_back(6); }, 2);
|
||||
event.Erase(2); event.Rebase(); event.Tick(2);
|
||||
require(order.back() == 5 && order.size() == 4 && event.GetSize() == 0,
|
||||
"Event reschedule/erase/rebase preserves remaining delays");
|
||||
event.SetClocksPerCycle(8); event.SetOverclock(2); event.Rebase(); event.Tick(2);
|
||||
require(event.GetClocks() == 8, "Event overclock and cycle rate apply at rebase");
|
||||
event.Reset(); event.Rebase(); event.Tick(1);
|
||||
require(event.GetClocks() == 16, "Event reset clears requested rate/overclock");
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Authored fixtures only; no ROM or disk content from external releases.
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/devices/FD502/Fd502Device.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
using namespace VCC::Devices;
|
||||
namespace {
|
||||
void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); }
|
||||
template<class F> void rejects(F f, const char* message) {
|
||||
bool rejected = false; try { f(); } catch (const std::exception&) { rejected = true; }
|
||||
require(rejected, message);
|
||||
}
|
||||
struct Host final : DeviceHost { unsigned nmis = 0; void cartridgeNmi() override { ++nmis; } };
|
||||
struct Rig {
|
||||
Host host;
|
||||
Fd502Device fdc{std::vector<std::uint8_t>(8192, 0x42)};
|
||||
void w(unsigned p, unsigned v) { fdc.writePort(p, v, host); }
|
||||
std::uint8_t r(unsigned p) { return fdc.readPort(p, host); }
|
||||
void tick(unsigned count = 1) { while (count--) fdc.horizontalSync(host); }
|
||||
void finish() {
|
||||
for (unsigned n = 0; n < 200000 && fdc.snapshot().busy; ++n) tick();
|
||||
require(!fdc.snapshot().busy, "Controller operation must finish within bounded scanlines");
|
||||
}
|
||||
};
|
||||
DiskImage fixture(DiskGeometry g = {}) {
|
||||
auto disk = DiskImage::blank(g);
|
||||
for (unsigned t = 0; t < g.tracks; ++t)
|
||||
for (unsigned side = 0; side < g.sides; ++side)
|
||||
for (unsigned s = g.firstSector; s < g.firstSector + g.sectors; ++s) {
|
||||
std::vector<std::uint8_t> bytes(g.sectorBytes());
|
||||
for (unsigned i = 0; i < bytes.size(); ++i) bytes[i] = t * 7 + side * 31 + s + i;
|
||||
require(disk.writeSector(t, side, s, bytes), "Author test sector");
|
||||
}
|
||||
disk.markSaved(); return disk;
|
||||
}
|
||||
std::vector<std::uint8_t> trackStream(unsigned track, unsigned side) {
|
||||
std::vector<std::uint8_t> bytes;
|
||||
for (unsigned s = 1; s <= 18; ++s) {
|
||||
bytes.insert(bytes.end(), 12, 0x4e);
|
||||
bytes.insert(bytes.end(), {0xfe, std::uint8_t(track), std::uint8_t(side), std::uint8_t(s), 1, 0xf7});
|
||||
bytes.insert(bytes.end(), 12, 0x4e); bytes.push_back(0xfb);
|
||||
bytes.insert(bytes.end(), 256, std::uint8_t(s)); bytes.push_back(0xf7);
|
||||
}
|
||||
bytes.resize(6272, 0x4e); return bytes;
|
||||
}
|
||||
using Bytes = std::vector<std::uint8_t>;
|
||||
|
||||
// 0xcdb4 is the CCITT seed after three MFM A1 sync bytes; FM starts at 0xffff.
|
||||
std::uint16_t testCRC(const Bytes& bytes, std::size_t offset, std::size_t count, std::uint16_t crc = 0xcdb4) {
|
||||
for (std::size_t i = offset; i < offset + count; ++i) {
|
||||
crc ^= static_cast<std::uint16_t>(bytes[i]) << 8;
|
||||
for (unsigned bit = 0; bit < 8; ++bit)
|
||||
crc = (crc & 0x8000) ? (crc << 1) ^ 0x1021 : crc << 1;
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
// A 128-byte deleted sector followed by a 256-byte sector, both claiming
|
||||
// cylinder 7 on physical head position 0.
|
||||
Bytes dmkFixture() {
|
||||
constexpr unsigned trackBytes = 6400;
|
||||
Bytes bytes(16 + trackBytes, 0x4e);
|
||||
std::fill_n(bytes.begin(), 16 + 128, 0);
|
||||
bytes[1] = 1; bytes[2] = trackBytes & 255; bytes[3] = trackBytes >> 8; bytes[4] = 0x10;
|
||||
auto record = [&](unsigned id, unsigned slot, unsigned sectorID, unsigned lengthCode, std::uint8_t mark) {
|
||||
bytes[16 + slot*2] = id & 255;
|
||||
bytes[17 + slot*2] = 0x80 | (id >> 8);
|
||||
const unsigned address = 16 + id;
|
||||
auto putCRC = [&](unsigned at, unsigned size) {
|
||||
const auto crc = testCRC(bytes, at, size);
|
||||
bytes[at+size] = crc >> 8;
|
||||
bytes[at+size+1] = crc & 255;
|
||||
};
|
||||
std::fill_n(bytes.begin()+address-3, 3, 0xa1);
|
||||
bytes[address] = 0xfe;
|
||||
bytes[address+1] = 7; bytes[address+2] = 0;
|
||||
bytes[address+3] = sectorID; bytes[address+4] = lengthCode;
|
||||
putCRC(address, 5);
|
||||
const unsigned dam = address + 32;
|
||||
std::fill_n(bytes.begin()+dam-3, 3, 0xa1);
|
||||
bytes[dam] = mark;
|
||||
const unsigned size = 128u << lengthCode;
|
||||
std::fill_n(bytes.begin()+dam+1, size, sectorID);
|
||||
putCRC(dam, size+1);
|
||||
};
|
||||
record(160, 0, 6, 0, 0xf8);
|
||||
record(480, 1, 2, 1, 0xfb);
|
||||
return bytes;
|
||||
}
|
||||
Bytes readCommand(Rig& r, unsigned cmd, unsigned count) {
|
||||
r.w(0x48, cmd);
|
||||
Bytes result;
|
||||
for (unsigned i = 0; i < count; ++i) result.push_back(r.r(0x4b));
|
||||
r.tick(10); // completion after the final data byte
|
||||
return result;
|
||||
}
|
||||
void checkDmkTransfers() {
|
||||
Rig r;
|
||||
auto original = dmkFixture();
|
||||
r.fdc.mount(0, DiskImage::load(original));
|
||||
r.w(0x40, 0x29);
|
||||
auto first = readCommand(r, 0xc0, 6);
|
||||
auto second = readCommand(r, 0xc0, 6);
|
||||
require(first == Bytes(original.begin()+177, original.begin()+183) &&
|
||||
second == Bytes(original.begin()+497, original.begin()+503),
|
||||
"DMK READ ADDRESS reports both real ID records, lengths, CRCs and on-disk ordering");
|
||||
require(readCommand(r, 0xe0, 6272) == Bytes(original.begin()+144, original.end()),
|
||||
"DMK READ TRACK returns the raw revolution without the container pointer table");
|
||||
|
||||
r.w(0x4a, 6);
|
||||
r.w(0x48, 0x80); r.r(0x4b);
|
||||
require(r.r(0x48) == 0x10, "Wrong logical cylinder cannot match a DMK sector");
|
||||
r.w(0x49, 7);
|
||||
require(readCommand(r, 0x80, 128) == Bytes(128, 6) && r.r(0x48) == 0x20,
|
||||
"DMK returns stored length and deleted-data mark after a complete read");
|
||||
|
||||
r.w(0x4a, 2);
|
||||
r.w(0x48, 0xa1); // write deleted data mark
|
||||
for (unsigned i = 0; i < 256; ++i) r.w(0x4b, 0xa5);
|
||||
r.tick(10);
|
||||
require(r.r(0x48) == 0 && r.fdc.image(0)->dirty(), "DMK write completed");
|
||||
auto expected = original;
|
||||
constexpr unsigned dam = 16 + 480 + 32;
|
||||
expected[dam] = 0xf8;
|
||||
std::fill_n(expected.begin()+dam+1, 256, 0xa5);
|
||||
const auto crc = testCRC(expected, dam, 257);
|
||||
expected[dam+257] = crc >> 8; expected[dam+258] = crc & 255;
|
||||
require(expected == r.fdc.image(0)->bytes(), "DMK write updates only the mark, data and CRC");
|
||||
expected[dam+258] ^= 1;
|
||||
r.fdc.mount(0, DiskImage::load(expected), true);
|
||||
r.w(0x4a, 2);
|
||||
require(readCommand(r, 0x80, 256) == Bytes(256, 0xa5) && r.r(0x48) == 0x28,
|
||||
"A deleted DMK sector with a bad data CRC returns the bytes and WD status");
|
||||
|
||||
// Formatting synthesizes fresh ID pointers inside this track only.
|
||||
r.w(0x49, 0);
|
||||
r.w(0x48, 0xf0);
|
||||
for (auto b : trackStream(0, 0)) r.w(0x4b, b);
|
||||
r.tick(10);
|
||||
require(r.r(0x48) == 0 && DiskImage::load(r.fdc.image(0)->bytes()).readSector(0, 0, 18) == Bytes(256, 18),
|
||||
"DMK formatted via WRITE TRACK reopens with its new sectors");
|
||||
|
||||
original[0] = 0xff;
|
||||
r.fdc.mount(0, DiskImage::load(original), true);
|
||||
r.fdc.setWriteProtected(0, false); // software override cannot clear the format protection
|
||||
r.w(0x48, 0xf0);
|
||||
require(r.r(0x48) == 0x50 && !r.fdc.image(0)->dirty(), "DMK header protects format commands");
|
||||
}
|
||||
|
||||
void checkFmAndDamagedRecords() {
|
||||
auto bytes = dmkFixture();
|
||||
std::fill(bytes.begin()+16, bytes.end(), 0);
|
||||
bytes[16] = 160; // pointer with bit 15 clear: a single-density record in double-rate storage
|
||||
auto storeDoubled = [&](unsigned offset, Bytes field) {
|
||||
const auto crc = testCRC(field, 0, field.size(), 0xffff);
|
||||
field.push_back(crc >> 8); field.push_back(crc & 255);
|
||||
for (auto value : field) {
|
||||
bytes[16 + offset++] = value;
|
||||
bytes[16 + offset++] = value;
|
||||
}
|
||||
};
|
||||
storeDoubled(160, {0xfe, 0, 0, 1, 1});
|
||||
// A copy-protected track (as in Shamus) can put an extra table pointer
|
||||
// between a real ID and its data. Its malformed ID must not hide that data.
|
||||
bytes[18] = 178;
|
||||
storeDoubled(178, {0xfe, 9, 8, 7, 3});
|
||||
bytes[16 + 178 + 10] ^= 1; bytes[16 + 178 + 11] ^= 1;
|
||||
Bytes data(257, 0xe5); data.front() = 0xfb;
|
||||
storeDoubled(200, data);
|
||||
Rig r;
|
||||
r.fdc.mount(0, DiskImage::load(bytes));
|
||||
r.w(0x40, 0x29); r.w(0x4a, 1);
|
||||
readCommand(r, 0xc0, 6); // first, valid FM address
|
||||
const auto badAddress = readCommand(r, 0xc0, 6);
|
||||
require(badAddress[0] == 9 && badAddress[2] == 7 && r.r(0x48) == 8,
|
||||
"DMK READ ADDRESS delivers the original bytes and signals a bad address CRC");
|
||||
require(readCommand(r, 0x80, 256) == Bytes(256, 0xe5) && r.r(0x48) == 0,
|
||||
"Mixed-density DMK decodes doubled FM bytes and their CRC");
|
||||
r.w(0x4a, 1); r.w(0x48, 0xa0);
|
||||
for (unsigned i = 0; i < 256; ++i) r.w(0x4b, i);
|
||||
r.tick(10);
|
||||
for (unsigned i = 0; i < 256; ++i) data[1+i] = i;
|
||||
storeDoubled(200, data);
|
||||
require(r.fdc.image(0)->bytes() == bytes, "FM write updates both copies of each data and CRC byte");
|
||||
|
||||
// Actual protected disks may have tracks without readable IDs. Their raw
|
||||
// revolutions must survive and a corrupt pointer cannot alias the next track.
|
||||
bytes[16] = 0xff; bytes[17] = 0xbf;
|
||||
r.fdc.mount(0, DiskImage::load(bytes), true);
|
||||
r.w(0x4a, 1); r.w(0x48, 0x80); r.r(0x4b);
|
||||
require(r.r(0x48) == 0x10 && !r.fdc.image(0)->dirty(), "Invalid ID pointer fails safely");
|
||||
require(readCommand(r, 0xe0, 6272) == Bytes(bytes.begin()+144, bytes.end()),
|
||||
"Track bytes remain readable without valid IDs");
|
||||
bytes.pop_back();
|
||||
rejects([&] { DiskImage::load(bytes); }, "Truncated DMK track image is rejected");
|
||||
}
|
||||
void checkVdkTransfers() {
|
||||
Rig r;
|
||||
Bytes bytes(12 + 2 * 18 * 256, 0);
|
||||
bytes[0] = 'd'; bytes[1] = 'k'; bytes[2] = 12; bytes[4] = 0x10; bytes[5] = 0x10;
|
||||
bytes[8] = 1; bytes[9] = 2;
|
||||
const auto last = bytes.size() - 256;
|
||||
std::fill(bytes.begin()+last, bytes.end(), 0x3d);
|
||||
r.fdc.mount(0, DiskImage::load(bytes));
|
||||
r.w(0x40, 0x69); r.w(0x4a, 18);
|
||||
require(readCommand(r, 0x80, 256) == Bytes(256, 0x3d), "VDK second-side sector is addressed after its header");
|
||||
r.w(0x4a, 18); r.w(0x48, 0xa0);
|
||||
for (unsigned i = 0; i < 256; ++i) r.w(0x4b, 0x5c);
|
||||
r.tick(10);
|
||||
std::fill(bytes.begin()+last, bytes.end(), 0x5c);
|
||||
require(r.r(0x48) == 0 && bytes == r.fdc.image(0)->bytes(), "VDK write retains header and other sectors");
|
||||
r.w(0x48, 0xe0); r.r(0x4b);
|
||||
require(r.r(0x48) == 0x10, "VDK sector images do not fabricate raw track data");
|
||||
bytes[10] = 1;
|
||||
r.fdc.mount(0, DiskImage::load(bytes), true);
|
||||
r.w(0x48, 0xa0);
|
||||
require(r.r(0x48) == 0x50 && !r.fdc.image(0)->dirty(), "VDK header protects sector writes");
|
||||
|
||||
// Genuine VDKs may retain optional disk names/metadata after byte 12.
|
||||
bytes.insert(bytes.begin() + 12, {'C', 'O', 'C', 'O'});
|
||||
bytes[2] = 16;
|
||||
const auto extended = DiskImage::load(bytes);
|
||||
require(extended.bytes() == bytes && extended.readSector(0, 1, 18) == Bytes(256, 0x5c),
|
||||
"Extended VDK headers preserve bytes and offset sector data correctly");
|
||||
bytes[8] = 2;
|
||||
rejects([&] { DiskImage::load(bytes); }, "VDK cylinder count must match its payload");
|
||||
|
||||
bytes.erase(bytes.begin() + 12, bytes.begin() + 16);
|
||||
std::fill_n(bytes.begin(), 12, 0);
|
||||
bytes[9] = 2;
|
||||
const auto windows = DiskImage::load(bytes);
|
||||
require(windows.format() == DiskFormat::VDK && windows.geometry().tracks == 1 &&
|
||||
windows.readSector(0, 1, 18) == Bytes(256, 0x5c),
|
||||
"Windows VCC legacy VDK side-count-only header preserves payload offsets");
|
||||
}
|
||||
void checkCreatedTrackFormats() {
|
||||
for (auto kind : {DiskFormat::VDK, DiskFormat::DMK}) {
|
||||
const auto created = DiskImage::blank(DiskGeometry{}, kind);
|
||||
auto disk = DiskImage::load(created.bytes());
|
||||
require(disk.format() == kind && disk.geometry().tracks == 35 && disk.geometry().sides == 1 &&
|
||||
!disk.dirty(), "New VDK and DMK media export with recognized header and geometry");
|
||||
Rig r;
|
||||
r.fdc.mount(0, std::move(disk));
|
||||
r.w(0x40, 0x29);
|
||||
r.w(0x48, 0xf0);
|
||||
for (auto byte : trackStream(0, 0)) r.w(0x4b, byte);
|
||||
r.tick(10);
|
||||
const auto formatted = DiskImage::load(r.fdc.image(0)->bytes());
|
||||
require(r.r(0x48) == 0 && formatted.format() == kind &&
|
||||
formatted.readSector(0, 0, 1) == Bytes(256, 1) &&
|
||||
formatted.readSector(0, 0, 18) == Bytes(256, 18),
|
||||
"Guest formatting on a newly created disk produces readable sectors after reopening");
|
||||
}
|
||||
}
|
||||
}
|
||||
void CheckDiskImages() {
|
||||
checkCreatedTrackFormats();
|
||||
auto disk = fixture();
|
||||
require(disk.bytes().size() == 161280 && !disk.dirty(), "Standard 35-track headerless DSK size");
|
||||
auto signatureCollision = disk.bytes();
|
||||
signatureCollision[0] = 'd'; signatureCollision[1] = 'k';
|
||||
require(DiskImage::load(signatureCollision).format() == DiskFormat::JVC,
|
||||
"Headerless DSK first-sector data may begin with the VDK signature");
|
||||
auto reopened = DiskImage::load(disk.bytes());
|
||||
require(reopened.readSector(34, 0, 18) == disk.readSector(34, 0, 18), "Last sector survives export/reload");
|
||||
require(reopened.readSector(35, 0, 1).empty() && reopened.readSector(0, 1, 1).empty() &&
|
||||
reopened.readSector(0, 0, 0).empty() && reopened.readSector(0, 0, 19).empty(), "Out-of-geometry reads cannot alias adjacent tracks");
|
||||
for (unsigned size = 0; size <= 3; ++size) {
|
||||
auto image = fixture({3, 2, 9, size, 0});
|
||||
auto copy = DiskImage::load(image.bytes());
|
||||
require(copy.geometry().sides == 2 && copy.geometry().sectorBytes() == (128u << size) &&
|
||||
copy.readSector(2, 1, 8) == image.readSector(2, 1, 8), "JVC variable sector size, sides and first sector");
|
||||
}
|
||||
// One-, two- and three-byte JVC headers use defaults for absent fields.
|
||||
for (unsigned n = 1; n <= 3; ++n) {
|
||||
std::vector<std::uint8_t> bytes{18, 1, 1}; bytes.resize(n);
|
||||
bytes.insert(bytes.end(), disk.bytes().begin(), disk.bytes().end());
|
||||
require(DiskImage::load(bytes).geometry().tracks == 35, "Partial JVC header defaults");
|
||||
}
|
||||
auto os9 = DiskImage::blank({40, 2, 18, 1, 1}).bytes(); os9.erase(os9.begin(), os9.begin() + 4);
|
||||
os9[0] = 0; os9[1] = 5; os9[2] = 160; os9[3] = 18; os9[16] = 1; // 1,440 sectors
|
||||
require(DiskImage::load(os9).format() == DiskFormat::OS9 && DiskImage::load(os9).geometry().sides == 2,
|
||||
"OS-9 descriptor selects two sides only when total sectors match the file");
|
||||
for (auto bytes : {std::vector<std::uint8_t>{}, std::vector<std::uint8_t>(17),
|
||||
std::vector<std::uint8_t>(4607), std::vector<std::uint8_t>(161280 + 16)})
|
||||
rejects([&] { DiskImage::load(bytes); }, "Malformed or unsupported containers rejected");
|
||||
auto bad = DiskImage::blank({2, 2, 18, 1, 1}).bytes(); bad[2] = 255;
|
||||
rejects([&] { DiskImage::load(bad); }, "Invalid size code rejected before shifting");
|
||||
bad[2] = 1; bad[0] = 0;
|
||||
rejects([&] { DiskImage::load(bad); }, "Zero sector divisor rejected");
|
||||
rejects([&] { DiskImage::blank({257, 1, 18, 1, 1}); }, "Excessive tracks rejected");
|
||||
rejects([&] { DiskImage::blank({1, 1, 1, 0, 1}); }, "Ambiguous half-block JVC payload rejected");
|
||||
rejects([&] { DiskImage::load(std::vector<std::uint8_t>(DiskImage::maxBytes + 1)); }, "Oversized image rejected");
|
||||
auto readonly = DiskImage::load(disk.bytes(), true); auto original = readonly.bytes();
|
||||
require(!readonly.writeSector(0, 0, 1, std::vector<std::uint8_t>(256)) && readonly.bytes() == original && !readonly.dirty(),
|
||||
"Protected writes do not alter any byte");
|
||||
auto stream = trackStream(0, 0);
|
||||
auto malformed = stream; malformed.back() = 0xfe;
|
||||
require(!reopened.formatTrack(0, 0, malformed) && reopened.bytes() == disk.bytes(), "Malformed formatting is atomic");
|
||||
require(reopened.formatTrack(0, 0, stream) && reopened.dirty() &&
|
||||
reopened.readSector(0, 0, 18) == std::vector<std::uint8_t>(256, 18), "Valid write-track stream updates sectors");
|
||||
}
|
||||
void CheckFloppyCommands() {
|
||||
Rig r; r.fdc.mount(0, fixture()); r.w(0x40, 0x29);
|
||||
r.w(0x4b, 3); r.w(0x48, 0x10);
|
||||
r.tick(99); require(r.fdc.snapshot().head == 0 && r.fdc.snapshot().busy, "Seek honors settle and step delay");
|
||||
r.finish(); require(r.r(0x49) == 3 && r.fdc.snapshot().head == 3 && r.host.nmis == 1, "Seek and gated completion NMI");
|
||||
r.w(0x48, 0x40); r.finish();
|
||||
require(r.r(0x49) == 3 && r.fdc.snapshot().head == 4, "STEP IN without update keeps track register");
|
||||
r.w(0x48, 0x70); r.finish(); require(r.r(0x49) == 2 && r.fdc.snapshot().head == 3, "STEP OUT updates the register independently of physical position");
|
||||
r.w(0x48, 0); r.finish(); require(r.r(0x49) == 0 && (r.r(0x48) & 4), "RESTORE reports track zero");
|
||||
r.w(0x40, 1); r.w(0x4b, 2); r.w(0x48, 0x10); r.tick(500);
|
||||
require(r.fdc.snapshot().busy && r.fdc.snapshot().head == 0, "Motor-off freezes seek");
|
||||
const auto nmis = r.host.nmis; r.w(0x40, 9); r.finish();
|
||||
require(r.host.nmis == nmis && r.fdc.snapshot().head == 2, "Completion NMI disabled by density/control bit");
|
||||
r.w(0x48, 0xd8); require(r.host.nmis == nmis + 1, "Forced NMI bypasses control mask");
|
||||
r.w(0x48, 0xd0); require(r.host.nmis == nmis + 1, "Force termination without interrupt");
|
||||
r.w(0x40, 0x48); require(r.fdc.snapshot().drive == 3 && r.fdc.snapshot().side == 0, "Fourth single-sided drive select");
|
||||
r.w(0x40, 0x49); require(r.fdc.snapshot().drive == 0 && r.fdc.snapshot().side == 1, "Bit six selects side when another drive is selected");
|
||||
r.w(0x40, 0x0f); require(r.fdc.snapshot().drive == 2, "Upstream drive-select priority");
|
||||
r.w(0x40, 8); r.w(0x48, 0x80); require(r.r(0x48) == 0x10, "Absent drive returns record not found");
|
||||
}
|
||||
void CheckFloppyTransfers() {
|
||||
checkDmkTransfers();
|
||||
checkFmAndDamagedRecords();
|
||||
checkVdkTransfers();
|
||||
Rig r; auto disk = fixture({2, 2, 18, 1, 1});
|
||||
const auto expected = disk.readSector(0, 1, 18);
|
||||
r.fdc.mount(0, std::move(disk)); r.w(0x40, 0x69); r.w(0x4a, 18); r.w(0x48, 0x80);
|
||||
std::vector<std::uint8_t> got; for (unsigned i = 0; i < 256; ++i) got.push_back(r.r(0x4b));
|
||||
require(got == expected && r.host.nmis == 0, "Second-side sector data, completion deferred beyond last byte");
|
||||
r.r(0x4b); require(!r.fdc.snapshot().busy && r.host.nmis == 1 && r.r(0x48) == 0, "Read completion delivers one NMI");
|
||||
r.w(0x4a, 2); r.w(0x48, 0xa0); r.tick(5); require(r.r(0x48) & 2, "Write DRQ after initial delay");
|
||||
for (unsigned i = 0; i < 256; ++i) r.w(0x4b, i ^ 0xa5);
|
||||
r.tick(6);
|
||||
auto changed = r.fdc.image(0)->readSector(0, 1, 2);
|
||||
for (unsigned i = 0; i < 256; ++i) require(changed[i] == (i ^ 0xa5), "Written sector bytes");
|
||||
require(r.r(0x48) == 0 && r.fdc.image(0)->dirty(), "Completed write commits once without false lost-data flag");
|
||||
auto copy = DiskImage::load(r.fdc.image(0)->bytes()); require(copy.readSector(0, 1, 2) == changed, "Written sector reopens");
|
||||
r.w(0x4a, 17); r.w(0x48, 0x90);
|
||||
for (unsigned s = 17; s <= 18; ++s)
|
||||
for (unsigned i = 0; i < 256; ++i) require(r.r(0x4b) == copy.readSector(0, 1, s)[i], "Multi-sector data stream");
|
||||
r.r(0x4b); require(r.r(0x48) == 0x10 && r.r(0x4a) == 19, "Multi-sector terminates at track boundary without aliasing");
|
||||
r.w(0x4a, 17); r.w(0x48, 0xb0);
|
||||
for (unsigned i = 0; i < 512; ++i) r.w(0x4b, i < 256 ? 0xa5 : 0x5a);
|
||||
r.tick(10); require(r.r(0x48) == 0x10 && r.fdc.image(0)->readSector(0, 1, 18) == std::vector<std::uint8_t>(256, 0x5a),
|
||||
"Multi-sector write commits last valid sector then stops");
|
||||
require(r.fdc.image(0)->readSector(0, 1, 17) == std::vector<std::uint8_t>(256, 0xa5), "Multi-sector write preserves first sector payload");
|
||||
r.w(0x4a, 1); r.w(0x48, 0x80); r.finish();
|
||||
require(r.r(0x48) == 4, "Unserviced transfer reports lost data");
|
||||
r.w(0x48, 0xc0); std::vector<std::uint8_t> id;
|
||||
for (unsigned i = 0; i < 6; ++i) id.push_back(r.r(0x4b)); r.r(0x4b);
|
||||
require(id[0] == 0 && id[1] == 1 && id[2] >= 1 && id[2] <= 18 && id[3] == 1, "Read address returns valid geometry");
|
||||
r.w(0x40, 0x29); r.w(0x48, 0xf0);
|
||||
for (auto b : trackStream(0, 0)) r.w(0x4b, b); r.tick(10);
|
||||
require(r.r(0x48) == 0 && r.fdc.image(0)->readSector(0, 0, 1) == std::vector<std::uint8_t>(256, 1), "Write-track formats selected side");
|
||||
}
|
||||
void CheckFloppyProtection() {
|
||||
Rig r; auto disk = fixture(); const auto original = disk.bytes();
|
||||
r.fdc.mount(0, DiskImage::load(original, true)); r.w(0x40, 0x29); r.w(0x4a, 1);
|
||||
for (unsigned command : {0xa0, 0xb0, 0xf0}) {
|
||||
r.w(0x48, command); for (unsigned i = 0; i < 300; ++i) r.w(0x4b, 0);
|
||||
require(r.r(0x48) == 0x50 && r.fdc.image(0)->bytes() == original && !r.fdc.image(0)->dirty(), "Protected controller writes leave source intact");
|
||||
}
|
||||
r.fdc.mount(0, fixture()); r.w(0x4a, 1); r.w(0x48, 0xa0);
|
||||
for (unsigned i = 0; i < 100; ++i) r.w(0x4b, 0);
|
||||
rejects([&] { r.fdc.eject(0); }, "Busy eject rejected");
|
||||
r.w(0x48, 0xd0); require(r.fdc.image(0)->bytes() == original, "Force interrupt drops incomplete sector");
|
||||
r.w(0x48, 0xa0); r.w(0x4b, 0); r.w(0x40, 0x2a);
|
||||
require(r.r(0x48) == 0x10 && r.fdc.image(0)->bytes() == original, "Drive switch aborts buffered transfer");
|
||||
r.w(0x40, 0x29); r.w(0x4a, 0); r.w(0x48, 0xa0); r.w(0x4b, 0);
|
||||
require(r.r(0x48) == 0x10 && r.fdc.image(0)->bytes() == original, "Sector zero cannot overwrite image header");
|
||||
r.w(0x4a, 1); r.w(0x48, 0xa0); for (unsigned i = 0; i < 256; ++i) r.w(0x4b, 0x77); r.tick(10);
|
||||
rejects([&] { r.fdc.eject(0); }, "Dirty eject requires explicit discard");
|
||||
rejects([&] { r.fdc.mount(0, fixture()); }, "Dirty replacement requires explicit discard");
|
||||
const auto changed = r.fdc.image(0)->bytes(); r.fdc.reset();
|
||||
require(r.fdc.image(0)->bytes() == changed && r.fdc.image(0)->dirty() && !r.fdc.snapshot().motor, "Reset preserves dirty media and stops motor");
|
||||
r.fdc.markSaved(0); r.fdc.eject(0); require(!r.fdc.image(0), "Saved image can eject");
|
||||
r.fdc.mount(0, DiskImage::blank()); r.fdc.eject(0, true);
|
||||
rejects([&] { r.fdc.eject(4); }, "Invalid drive index rejected");
|
||||
for (unsigned drive = 0; drive < 4; ++drive) {
|
||||
auto image = fixture(); image.writeSector(0, 0, 1, std::vector<std::uint8_t>(256, drive + 10)); image.markSaved();
|
||||
r.fdc.mount(drive, std::move(image));
|
||||
}
|
||||
for (unsigned drive = 0; drive < 4; ++drive) {
|
||||
r.w(0x40, (drive == 3 ? 0x40 : 1u << drive) | 8); r.w(0x4a, 1); r.w(0x48, 0x80);
|
||||
require(r.r(0x4b) == drive + 10, "Four mounted drives route independently"); r.w(0x48, 0xd0);
|
||||
}
|
||||
// Arbitrary port/command sequences must stay bounded even without media.
|
||||
for (unsigned i = 0; i < 4096; ++i) { r.w(0x40 + i % 16, (i * 73) & 255); r.tick(); r.r(0x40 + i % 16); }
|
||||
}
|
||||
void CheckBuiltinDeviceBus() {
|
||||
Host first, second; CartridgeBus bus;
|
||||
require(bus.readMemory(0xc000) == 0xff && bus.readPort(0x48) == 0 && bus.audio() == 0, "Empty cartridge bus values");
|
||||
rejects([&] { bus.install(makeDevice(DeviceKind::FD502, {})); }, "Missing disk ROM rejected");
|
||||
bus.install(makeDevice(DeviceKind::FD502, std::vector<std::uint8_t>(8192, 0x55)));
|
||||
require(bus.readMemory(0xc000) == 0x55 && bus.readMemory(0xdfff) == 0x55 && bus.readMemory(0xe000) == 0xff, "ROM map and 16 KiB padding");
|
||||
bus.connect(&first); bus.writePort(0x48, 0xd8); require(first.nmis == 1, "Interrupt reaches current host");
|
||||
bus.connect(nullptr); bus.writePort(0x48, 0xd8); bus.horizontalSync(); require(first.nmis == 1, "Detach prevents callbacks into old host");
|
||||
bus.connect(&second); bus.writePort(0x48, 0xd8); require(second.nmis == 1 && first.nmis == 1, "Reconnection isolates host lifetime");
|
||||
for (unsigned port = 0; port < 256; ++port) {
|
||||
if (port == 0x40 || (port >= 0x48 && port <= 0x4b)) continue;
|
||||
bus.writePort(port, 0xff); require(bus.readPort(port) == 0, "Unowned ports remain inert");
|
||||
}
|
||||
Fd502Device other(std::vector<std::uint8_t>(8192));
|
||||
bus.writePort(0x49, 10); require(other.readPort(0x49, first) == 0, "Controllers have no shared mutable state");
|
||||
bus.install(nullptr); bus.writePort(0x48, 0xd8); require(second.nmis == 1, "Removal detaches device");
|
||||
}
|
||||
void CheckFloppySession() {
|
||||
using namespace VCC::Mac;
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
auto device = makeDevice(DeviceKind::FD502, std::vector<std::uint8_t>(8192, 0x42));
|
||||
auto* fdc = static_cast<Fd502Device*>(device.get()); fdc->mount(0, fixture());
|
||||
machine.cartridges().install(std::move(device));
|
||||
std::vector<std::uint8_t> rom(32768, 0x12);
|
||||
const std::uint8_t program[] = {0x10,0xce,0x70,0x00,0x20,0xfe}; // LDS #$7000; BRA self
|
||||
std::copy(std::begin(program), std::end(program), rom.begin());
|
||||
rom[0x100] = 0x7c; rom[0x101] = 0x40; rom[0x102] = 1; rom[0x103] = 0x3b; // INC $4001; RTI
|
||||
rom[0x7ffc] = 0x81; rom[0x7ffd] = 0; rom[0x7ffe] = 0x80; rom[0x7fff] = 0;
|
||||
machine.load(rom, cpu); machine.resume(); machine.advance();
|
||||
require(MemRead8(0xc000) == 0x42, "Mapped cartridge ROM reaches guest MMU");
|
||||
require(fdc->snapshot().ticks >= 262 && fdc->snapshot().ticks <= 263, "One controller tick per raster scanline");
|
||||
MemWrite8(0, 0x4001); MemWrite8(0x29, 0xff40); MemWrite8(1, 0xff4a); MemWrite8(0x80, 0xff48);
|
||||
for (unsigned i = 0; i < 256; ++i) require(MemRead8(0xff4b) == std::uint8_t(1 + i), "Mapped disk port data");
|
||||
MemRead8(0xff4b); machine.advance();
|
||||
require(MemRead8(0x4001) == 1, "Controller completion NMI serviced by both CPU engines");
|
||||
machine.pause(); const auto ticks = fdc->snapshot().ticks; machine.advance();
|
||||
require(fdc->snapshot().ticks == ticks, "Pause freezes controller timing");
|
||||
machine.softReset(); require(fdc->image(0) && !fdc->snapshot().busy && !fdc->snapshot().motor, "Soft reset retains media and cancels controller");
|
||||
machine.reset(); require(machine.cartridges().current() == fdc && fdc->image(0), "Cold reset retains device ownership and disk");
|
||||
CartridgeBus::Slots slots;
|
||||
slots[4] = makeDevice(DeviceKind::FD502, std::vector<std::uint8_t>(8192));
|
||||
slots[1] = makeDevice(DeviceKind::RamDisk, {});
|
||||
machine.cartridges().configure(slots, true, 4);
|
||||
machine.setDriveWireFactory([](const std::string&, std::uint16_t) -> std::unique_ptr<DriveWireTransport> {
|
||||
throw std::logic_error("DriveWire initialization must not open a socket");
|
||||
});
|
||||
MemWrite8(0x5a, 0xff42); MemWrite8(0, 0xff42); // DWINIT
|
||||
require(MemRead8(0xff41) == 2, "FD-502 exposes the pending Becker response");
|
||||
MemWrite8(0x30, 0xff7f); // ROM slot 4, I/O slot 1
|
||||
MemWrite8(3, 0xff42); MemWrite8(0xa6, 0xff43);
|
||||
require(MemRead8(0xff41) == 0 && MemRead8(0xff43) == 0xa6, "RAM disk owns its overlapping I/O addresses");
|
||||
MemWrite8(0x33, 0xff7f);
|
||||
require(MemRead8(0xff42) == 4, "Re-selecting the FD-502 returns the pending DriveWire response");
|
||||
MemWrite8(0x5a, 0xff42); MemWrite8(0, 0xff42);
|
||||
machine.setDriveWireFactory({}); require(MemRead8(0xff41) == 0, "Disabling networking drops pending replies");
|
||||
machine.shutdown(); machine.cartridges().writePort(0x48, 0xd8); // no dangling callback
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/JoystickState.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/core/MachineHost.h"
|
||||
#include "../../src/core/mc6821.h"
|
||||
#include "../../src/core/CpuMemory.h"
|
||||
#include "../../src/core/mc6809.h"
|
||||
#include "../../src/core/hd6309.h"
|
||||
extern int JS_Ramp_Clock;
|
||||
#include <stdexcept>
|
||||
using namespace VCC::Mac;
|
||||
namespace { void require(bool condition) { if (!condition) throw std::runtime_error("Joystick input contract failed"); } }
|
||||
void CheckJoystickComparator() {
|
||||
JoystickState state;
|
||||
state.set(0, 0, 16383, 3, 0); state.set(1, 1000, 2000, 3, 0);
|
||||
require(state.scan(0x7f, 0, 0, 0, false) == 0x70); // zero never compares high
|
||||
require(state.scan(0x7f, 1, 16383, 0, false) == 0xf0);
|
||||
require(state.scan(0x7f, 2, 1001, 0, false) == 0x70);
|
||||
require(state.scan(0x7f, 3, 2000, 0, false) == 0xf0);
|
||||
state.release(); require(state.scan(0x7f, 0, 8192, 0, false) == 0x7f);
|
||||
require(state.scan(0x7e, 0, 8191, 0, false) == 0xfe); // retain keyboard row
|
||||
state.set(0, 99999, 99999, 255, 99);
|
||||
require(state.ports[0].x == 16383 && state.ports[0].mode == 3 && state.ports[0].buttons == 3);
|
||||
}
|
||||
void CheckJoystickRamps() {
|
||||
for (bool fast : {false, true}) {
|
||||
JoystickState state; int clock = 123;
|
||||
state.set(0, 0, 16383, 0, 2);
|
||||
state.start(true, 1, 0, clock); require(clock == 123);
|
||||
state.start(true, 2, 0, clock); require(clock == 0);
|
||||
const int threshold = fast ? 1200 : 600;
|
||||
require(state.scan(0x7f, 0, 0, threshold, fast) == 0x7f);
|
||||
require(state.scan(0x7f, 0, 0, threshold + 1, fast) == 0xff);
|
||||
state.start(true, 2, 1, clock);
|
||||
const int max = (1200 + ((16383 * 37) >> 6)) / (fast ? 1 : 2);
|
||||
require(state.scan(0x7f, 1, 0, max, fast) == 0x7f);
|
||||
require(state.scan(0x7f, 1, 0, max + 1, fast) == 0xff);
|
||||
state.set(1, 0, 0, 0, 3); state.start(false, 0, 2, clock);
|
||||
require(state.scan(0x7f, 2, 0, 800, fast) == 0x7f);
|
||||
require(state.scan(0x7f, 2, 0, 801, fast) == 0xff);
|
||||
}
|
||||
}
|
||||
void CheckJoystickSession() {
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine; machine.loadDiagnostic(cpu); machine.resume();
|
||||
machine.setJoystick(0, 0, 0, 3, 0); machine.setJoystick(1, 0, 0, 3, 0);
|
||||
require(VCC::Machine().KeyboardScan(0xff) == 0x70);
|
||||
// Exercise the real PIA start/comparator and retained CPU cycle counter.
|
||||
MemWrite8(4, 0xff01); MemWrite8(4, 0xff03); MemWrite8(0xff, 0xff02);
|
||||
MemWrite8(4, 0xff21);
|
||||
// PA2..PA7 alone set the threshold, including at an exact six-bit boundary.
|
||||
machine.setJoystick(0, 26u << 8, 0, 0, 0);
|
||||
for (unsigned lowBits = 0; lowBits < 4; ++lowBits) {
|
||||
MemWrite8((26 << 2) | lowBits, 0xff20);
|
||||
require((MemRead8(0xff00) & 0x80) != 0);
|
||||
MemWrite8((27 << 2) | lowBits, 0xff20);
|
||||
require((MemRead8(0xff00) & 0x80) == 0);
|
||||
}
|
||||
machine.setJoystick(0, 0, 0, 0, 2);
|
||||
MemWrite8(2, 0xff20); require(JS_Ramp_Clock == 0);
|
||||
require((MemRead8(0xff00) & 0x80) == 0);
|
||||
// Authored RAM loop; neither CPU needs a proprietary ROM for this check.
|
||||
MemWrite8(0x20, 0x2000); MemWrite8(0xfe, 0x2001);
|
||||
if (cpu == Processor::MC6809) { MC6809ForcePC(0x2000); MC6809Exec(700); }
|
||||
else { HD6309ForcePC(0x2000); HD6309Exec(700); }
|
||||
require(JS_Ramp_Clock > 600 && (MemRead8(0xff00) & 0x80) != 0);
|
||||
machine.setJoystick(0, 0, 0, 0, 3); MemWrite8(0, 0xff00);
|
||||
require(JS_Ramp_Clock == 0 && (MemRead8(0xff00) & 0x80) == 0);
|
||||
JS_Ramp_Clock = 801; require((MemRead8(0xff00) & 0x80) != 0);
|
||||
machine.pause(); require((VCC::Machine().KeyboardScan(0xff) & 15) == 15);
|
||||
machine.setJoystick(0, 0, 0, 3, 0); require((VCC::Machine().KeyboardScan(0xff) & 15) == 15);
|
||||
machine.resume(); machine.setJoystick(0, 0, 0, 3, 0); machine.softReset();
|
||||
require((VCC::Machine().KeyboardScan(0xff) & 15) == 15);
|
||||
machine.setJoystick(0, 0, 0, 3, 0); machine.reset();
|
||||
require((VCC::Machine().KeyboardScan(0xff) & 15) == 15);
|
||||
|
||||
// Normal guest instructions configure the PIA and stop immediately
|
||||
// before reading it. Resume must apply the complete host input before
|
||||
// that first instruction, not one CPU slice later.
|
||||
const std::vector<uint8_t> code = {
|
||||
0x86,0x04, 0xb7,0xff,0x01, 0xb7,0xff,0x03, 0xb7,0xff,0x21,
|
||||
0x86,0xff, 0xb7,0xff,0x02, 0x86,0x80, 0xb7,0xff,0x20,
|
||||
0xb6,0xff,0x00, 0xb7,0x30,0x00, 0x20,0xfe
|
||||
};
|
||||
std::vector<uint8_t> binary = {0, 0, uint8_t(code.size()), 0x20, 0};
|
||||
binary.insert(binary.end(), code.begin(), code.end());
|
||||
binary.insert(binary.end(), {0xff, 0, 0, 0x20, 0});
|
||||
machine.debuggerLoadBinary(binary, std::vector<uint16_t>{0x2015, 0x201b});
|
||||
machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x2015);
|
||||
const std::array<JoystickInputSnapshot, 2> inputs = {{{16383, 1234, 1, 0}, {0, 8191, 2, 0}}};
|
||||
machine.resumeWithInput(1, inputs);
|
||||
const auto held = machine.snapshot();
|
||||
require(held.keyboardHeld && held.joysticks[0].x == 16383 && held.joysticks[0].y == 1234 &&
|
||||
held.joysticks[0].buttons == 1 && held.joysticks[1].buttons == 2);
|
||||
machine.advance();
|
||||
const auto stopped = machine.snapshot();
|
||||
require(stopped.state == RunState::Paused && stopped.cpu.PC == 0x201b);
|
||||
const auto readback = machine.debuggerSnapshot(0x3000, 1);
|
||||
require(readback.memoryAvailable[0] && (readback.memory[0] & 0x81) == 0x80);
|
||||
machine.releaseInputs();
|
||||
const auto released = machine.snapshot();
|
||||
require(!released.keyboardHeld && released.state == stopped.state && released.cpu.PC == stopped.cpu.PC &&
|
||||
released.frames == stopped.frames && released.cycles == stopped.cycles && released.generation == stopped.generation);
|
||||
for (const auto& port : released.joysticks) require(port.x == 8191 && port.y == 8191 && port.buttons == 0);
|
||||
require(held.keyboardHeld && held.joysticks[0].buttons == 1); // The prior snapshot is an immutable value.
|
||||
auto invalid = inputs; invalid[1].x = 16384;
|
||||
try { machine.resumeWithInput(0, invalid); require(false); } catch (const std::invalid_argument&) {}
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cycles == stopped.cycles);
|
||||
|
||||
// A pending interrupt can stop at a different breakpoint inside the
|
||||
// first resumed slice. Preserve the actual input applied before that
|
||||
// slice even though pausing correctly neutralizes the live controls.
|
||||
std::vector<uint8_t> rom(32768, 0x12);
|
||||
rom[0x7ff8] = 0x21; rom[0x7ff9] = 0; // IRQ vector -> authored RAM handler
|
||||
rom[0x7ffe] = 0x20; rom[0x7fff] = 0;
|
||||
machine.load(rom, cpu);
|
||||
const std::vector<uint8_t> interruptBinary = {
|
||||
0,0,9,0x20,0, 0x10,0xce,0x70,0,0x1c,0xaf,0x12,0x20,0xfe,
|
||||
0,0,1,0x21,0, 0x3b, 0xff,0,0,0x20,0
|
||||
};
|
||||
machine.debuggerLoadBinary(interruptBinary, std::vector<uint16_t>{0x2006, 0x2100});
|
||||
machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cpu.PC == 0x2006);
|
||||
VCC::Machine().AssertInterrupt(IS_GIME, INT_IRQ);
|
||||
const auto staged = machine.resumeWithInput(1, inputs);
|
||||
const auto interrupted = machine.snapshot();
|
||||
require(staged.state == RunState::Running && staged.keyboardHeld && staged.joysticks[0].buttons == 1 &&
|
||||
staged.joysticks[0].x == 16383 && staged.joysticks[1].buttons == 2);
|
||||
require(interrupted.state == RunState::Paused && interrupted.cpu.PC == 0x2100 && !interrupted.keyboardHeld);
|
||||
for (const auto& port : interrupted.joysticks) require(port.x == 8191 && port.y == 8191 && port.buttons == 0);
|
||||
VCC::Machine().ClearInterrupt(IS_GIME, INT_IRQ);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "TestMachine.h"
|
||||
using namespace VCCTest;
|
||||
|
||||
void CheckMmuMapping() {
|
||||
const unsigned sizes[] = {0x20000, 0x80000, 0x200000, 0x800000};
|
||||
const unsigned masks[] = {15, 63, 255, 1023};
|
||||
for (unsigned char config = 0; config < 4; ++config) {
|
||||
MachineFixture f(config);
|
||||
const auto base = config == 0 ? 8 : 56;
|
||||
auto state = GetMMUState();
|
||||
require(!state.Enabled && state.ActiveTask == 0 && state.Task0[0] == base &&
|
||||
state.Task1[7] == base + 7, "MMU reset maps upper 64 KiB for both tasks");
|
||||
for (unsigned p = 0; p < sizes[config] / 8192; ++p) {
|
||||
SetMem(p * 8192 + 0x123, p & 255);
|
||||
SetMem(p * 8192 + 0x124, p >> 8);
|
||||
}
|
||||
f.write(0xffdf, 0); // SAM all-RAM mode
|
||||
require(MemRead8(0x123) == base, "MMU disabled mapping");
|
||||
f.write(0xffa0, 5); f.write(0xffa8, 9); f.write(0xff90, 0x40);
|
||||
require(MemRead8(0x123) == 5, "MMU task zero mapping via GIME register");
|
||||
f.write(0xff91, 1);
|
||||
require(MemRead8(0x123) == 9, "MMU task one mapping via GIME register");
|
||||
f.write(0x123, 0x55);
|
||||
require(GetMem(9 * 8192 + 0x123) == 0x55 && GetMem(5 * 8192 + 0x123) == 5,
|
||||
"MMU tasks isolate physical writes");
|
||||
f.write(0xff91, 0); f.write(0xffa0, 0xff);
|
||||
require(GetMMUState().Task0[0] == (255 & masks[config]), "MMU installed RAM bank mask");
|
||||
f.write(0xff9b, 0x30); f.write(0xffa0, 0xab);
|
||||
const auto page = config == 3 ? 0x3ab : (0xab & masks[config]);
|
||||
require(GetMMUState().Task0[0] == page && MemRead8(0x123) == (page & 255) &&
|
||||
MemRead8(0x124) == (page >> 8), "MMU extended bank prefix");
|
||||
std::array<unsigned char, 8192> snapshot;
|
||||
GetMMUPage(page, snapshot);
|
||||
require(snapshot[0x123] == (page & 255), "MMU debugger physical page snapshot");
|
||||
f.write(0xff90, 0); // disabled mapping independent of selected task
|
||||
require(MemRead8(0x123) == base, "MMU disable restores fixed map");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckMmuRomAndVectors() {
|
||||
for (unsigned char config = 0; config < 4; ++config) {
|
||||
MachineFixture f(config);
|
||||
const auto vectorPage = config == 0 ? 15 : 63;
|
||||
const unsigned char expected[4][4] = {
|
||||
{0xa0,0xa1,0xc0,0xc1}, {0xa0,0xa1,0xc0,0xc1},
|
||||
{0xa0,0xa1,0xa2,0xa3}, {0xc2,0xc3,0xc0,0xc1}
|
||||
};
|
||||
for (unsigned char map = 0; map < 4; ++map) {
|
||||
f.write(0xff90, map);
|
||||
for (unsigned bank = 0; bank < 4; ++bank) {
|
||||
const auto address = 0x8000 + bank * 8192;
|
||||
require(MemRead8(address) == expected[map][bank], "MMU internal/cartridge ROM selection");
|
||||
f.write(address, 0x17);
|
||||
require(MemRead8(address) == expected[map][bank] && !MemCheckWrite(address), "MMU ROM writes are blocked");
|
||||
}
|
||||
require(MemRead16(0xfffe) == 0x4000, "SAM vectors always read internal ROM");
|
||||
}
|
||||
f.write(0xffdf, 0);
|
||||
f.write(0x8000, 0x17);
|
||||
require(MemRead8(0x8000) == 0x17 && MemCheckWrite(0x8000), "SAM all-RAM enables writes behind ROM");
|
||||
f.write(0xffde, 0);
|
||||
require(MemRead8(0x8000) == 0xc2, "SAM restores selected ROM overlay");
|
||||
f.write(0xffdf, 0); f.write(0xff90, 0x40); f.write(0xffa7, 1);
|
||||
SetMem(8192 + 0x1e00, 0x11); SetMem(vectorPage * 8192 + 0x1e00, 0x22);
|
||||
require(MemRead8(0xfe00) == 0x11, "FE00 follows mapped page with RAM vectors disabled");
|
||||
f.write(0xff90, 0x48);
|
||||
require(MemRead8(0xfe00) == 0x22, "RAM vector window bypasses MMU mapping");
|
||||
f.write(0xfe00, 0x33);
|
||||
require(GetMem(vectorPage * 8192 + 0x1e00) == 0x33 && GetMem(8192 + 0x1e00) == 0x11,
|
||||
"RAM vector write reaches fixed physical page");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckMmuLifecycle() {
|
||||
MachineFixture f;
|
||||
auto* original = Get_mem_pointer();
|
||||
require(original[0] == 255 && original[3] == 255 && original[4] == 0 && original[7] == 0,
|
||||
"MMU retains upstream power-on RAM pattern");
|
||||
require(!MmuInit(4) && Get_mem_pointer() == original, "MMU rejects invalid RAM size without losing machine");
|
||||
f.host.romFailure = true; f.host.rom.fill(0x17);
|
||||
require(!MmuInit(0) && Get_mem_pointer() == original && GetRamConfiguration() == 1,
|
||||
"MMU failed ROM load preserves prior allocation/configuration");
|
||||
LoadRom();
|
||||
require(Getint_rom_pointer()[0] == 0xa0, "Failed ROM reload leaves current ROM intact");
|
||||
std::array<unsigned char, 8192> page;
|
||||
GetMMUPage(std::numeric_limits<std::size_t>::max(), page);
|
||||
require(std::all_of(page.begin(), page.end(), [](auto v) { return v == 255; }), "Invalid debugger page is bounded");
|
||||
f.host.romFailure = false;
|
||||
require(MmuInit(0) && GetRamConfiguration() == 0, "MMU can reinitialize to another RAM size");
|
||||
require(MemRead8(0xfffe) == 0x17, "SAM reads replacement ROM without stale pointer");
|
||||
MmuShutdown(); MmuShutdown();
|
||||
require(!Get_mem_pointer() && !Getint_rom_pointer() && MemRead8(0) == 255 &&
|
||||
SafeMemRead8(0xff00) == 0 && GetMem(0) == 0 && !MemCheckWrite(0), "MMU teardown and inspection are safe");
|
||||
}
|
||||
|
||||
void CheckGimeRegisters() {
|
||||
MachineFixture f(1, true);
|
||||
f.write(0x4000, 0xc0); f.write(0x4001, 0x40);
|
||||
MC6809ForcePC(0x4001); HD6309ForcePC(0x4000);
|
||||
f.write(0xffa0, 5);
|
||||
require(MemRead8(0xffa0) == 0xc5, "GIME floating bus uses selected 6309, not inactive 6809");
|
||||
f.write(0xffb3, 0xff);
|
||||
require(MemRead8(0xffb3) == 0xff && std::get<0>(f.host.video.back()) == VCC::VideoRegister::Palette &&
|
||||
std::get<1>(f.host.video.back()) == 63 && std::get<2>(f.host.video.back()) == 3, "GIME palette masks data and forwards index");
|
||||
f.write(0xff95, 0x34); f.write(0xff94, 0xf2); f.write(0xff91, 0x20);
|
||||
require(f.host.timer == std::vector<std::pair<VCC::TimerRegister, unsigned int>>{
|
||||
{VCC::TimerRegister::Reload, 0x34}, {VCC::TimerRegister::Restart, 0x234},
|
||||
{VCC::TimerRegister::ClockSource, 0x20}}, "GIME timer reload/restart/source forwarding");
|
||||
f.write(0xff9d, 0x12); f.write(0xff9e, 0x34);
|
||||
require(std::get<0>(f.host.video.back()) == VCC::VideoRegister::Offset &&
|
||||
std::get<1>(f.host.video.back()) == 0x1234, "GIME video offset combines bytes");
|
||||
f.write(0xff96, 0xff); f.write(0xffd9, 0);
|
||||
require(f.host.turbo == 1 && f.host.speed == 1, "GIME/SAM speed outputs");
|
||||
f.write(0xffd8, 0); require(f.host.speed == 0, "SAM normal speed output");
|
||||
f.write(0xffc1, 0); f.write(0xffc5, 0); f.write(0xffc7, 0);
|
||||
require(VDG_Modes() == 5 && VDG_Offset() == 1, "SAM bit-addressed video controls");
|
||||
f.write(0xff40, 0x12);
|
||||
require(MemRead8(0xff40) == 0x5a && f.host.cartWrites == 1 && f.host.cartValue == 0x12,
|
||||
"Unowned I/O ports route to cartridge host");
|
||||
|
||||
f.write(0xff90, 0x30); f.write(0xff92, 8); f.write(0xff93, 16);
|
||||
GimeAssertVertInterupt(); GimeAssertHorzInterupt();
|
||||
require(f.host.lines[IS_GIME] == (Bit(INT_IRQ) | Bit(INT_FIRQ)), "GIME independently asserts IRQ and FIRQ");
|
||||
require(SafeMemRead8(0xff92) == 8 && (f.host.lines[IS_GIME] & Bit(INT_IRQ)), "Debugger GIME read does not acknowledge IRQ");
|
||||
require(MemRead8(0xff92) == 8 && f.host.lines[IS_GIME] == Bit(INT_FIRQ), "GIME IRQ read acknowledges only IRQ");
|
||||
require(MemRead8(0xff93) == 16 && !f.host.lines[IS_GIME], "GIME FIRQ read acknowledges FIRQ");
|
||||
GimeAssertVertInterupt(); GimeAssertHorzInterupt(); GimeRegistersReset();
|
||||
require(!f.host.lines[IS_GIME], "GIME reset clears asserted CPU lines");
|
||||
}
|
||||
|
||||
void CheckPiaRegisters() {
|
||||
MachineFixture f;
|
||||
f.write(0xff02, 0x0f); // PIA0 B direction
|
||||
require(MemRead8(0xff02) == 0x0f, "PIA direction register access");
|
||||
f.write(0xff03, 4); f.write(0xff02, 5); f.write(0xff01, 4);
|
||||
require(MemRead8(0xff00) == 0x7e && f.host.columns == 0xf5, "PIA keyboard scan respects output direction");
|
||||
f.write(0xff00, 0); require(f.host.joystickStarts == 1, "PIA starts CCMax joystick measurement");
|
||||
f.write(0xff20, 0xff); f.write(0xff21, 4); f.write(0xff23, 8);
|
||||
f.write(0xff20, 0xfe);
|
||||
require(f.host.printerBit == 1 && f.host.joystickStarts == 2, "PIA serial and Tandy outputs");
|
||||
require(DACState() == (63u << 8), "PIA six-bit DAC is at full scale with serial output high");
|
||||
require(GetDACSample() == ((126u * 128u) << 16 | (126u * 128u)), "PIA DAC stereo sample");
|
||||
f.write(0xff23, 0); f.write(0xff20, 0xfc);
|
||||
require(GetCasSample() == 0xfc, "PIA cassette output selection");
|
||||
f.write(0xff21, 12); require(f.host.motor == 1, "PIA cassette motor output");
|
||||
f.host.fastTape = true; f.host.tapeBit = 1;
|
||||
require((MemRead8(0xff20) & 1) == 1, "PIA fast cassette input");
|
||||
f.host.fastTape = false; SetCassetteSample(0);
|
||||
require((MemRead8(0xff20) & 1) == 0, "PIA sampled cassette input");
|
||||
f.write(0xff01, 12); f.write(0xff03, 12);
|
||||
require(GetMuxState() == 3, "PIA analog mux selection");
|
||||
}
|
||||
|
||||
void CheckPiaInterrupts() {
|
||||
MachineFixture f;
|
||||
f.write(0xff01, 5); f.write(0xff03, 7); // HS falling, VS rising
|
||||
irq_hs(RISING); require(!f.host.lines[IS_PIA0_HSYNC], "PIA ignores opposite HS edge");
|
||||
irq_hs(FALLING); irq_fs(RISING);
|
||||
require((MemRead8(0xff01) & 128) && (MemRead8(0xff03) & 128), "PIA control reads retain interrupt flags");
|
||||
require(f.host.lines[IS_PIA0_HSYNC] && f.host.lines[IS_PIA0_VSYNC], "PIA HS/VS IRQ sources coexist");
|
||||
(void)SafeMemRead8(0xff00);
|
||||
require(f.host.lines[IS_PIA0_HSYNC], "Debugger PIA read has no acknowledge side effect");
|
||||
(void)MemRead8(0xff00);
|
||||
require(!f.host.lines[IS_PIA0_HSYNC] && f.host.lines[IS_PIA0_VSYNC], "PIA data read acknowledges only its source");
|
||||
f.write(0xff23, 5); AssertCart();
|
||||
require(f.host.lines[IS_PIA1_CART] == Bit(INT_FIRQ), "PIA cartridge FIRQ");
|
||||
(void)MemRead8(0xff22); require(!f.host.lines[IS_PIA1_CART], "PIA cartridge data read acknowledges FIRQ");
|
||||
irq_hs(FALLING); AssertCart(); PiaReset();
|
||||
require(!f.host.lines[IS_PIA0_HSYNC] && !f.host.lines[IS_PIA0_VSYNC] && !f.host.lines[IS_PIA1_CART],
|
||||
"PIA reset clears its CPU interrupt sources");
|
||||
}
|
||||
|
||||
void CheckMappedCpuExecution() {
|
||||
for (bool use6309 : {false, true}) {
|
||||
MachineFixture f(1, use6309);
|
||||
const std::vector<unsigned char> program = {
|
||||
0x10,0xce,0x70,0x00, // LDS #$7000
|
||||
0x86,0x42,0xb7,0xff,0x90, // enable MMU, internal ROM
|
||||
0x86,0x05,0xb7,0xff,0xa0, // task 0 page 0 = physical page 5
|
||||
0x86,0xa5,0xb7,0x01,0x23, // write through task 0
|
||||
0x86,0x06,0xb7,0xff,0xa8, // task 1 page 0 = physical page 6
|
||||
0x86,0x01,0xb7,0xff,0x91, // select task 1
|
||||
0x86,0x5a,0xb7,0x01,0x23, // write through task 1
|
||||
0x86,0x00,0xb7,0xff,0x91, // select task 0
|
||||
0xb6,0x01,0x23, // read original task 0 value
|
||||
0x1c,0xaf,0x12 // unmask interrupts; NOP
|
||||
};
|
||||
for (unsigned i = 0; i < program.size(); ++i) f.write(0x4000+i, program[i]);
|
||||
const unsigned short stop = 0x4000 + program.size() - 3;
|
||||
auto exec = use6309 ? HD6309Exec : MC6809Exec;
|
||||
auto breakpoints = use6309 ? HD6309SetBreakpoints : MC6809SetBreakpoints;
|
||||
breakpoints({stop});
|
||||
const auto cycles = 1000 - exec(1000);
|
||||
require(f.debugger.halted && f.host.CpuState().PC == stop && f.host.CpuState().A == 0xa5 &&
|
||||
GetMem(5*8192+0x123) == 0xa5 && GetMem(6*8192+0x123) == 0x5a,
|
||||
"CPU executes guest bank switching through actual MMU/GIME/I/O");
|
||||
require(cycles > 0 && VCC::gEvents.GetClocks() == cycles*16u, "Mapped CPU advances scheduler");
|
||||
breakpoints({}); f.debugger.halted = false; exec(1); // ANDCC
|
||||
f.write(0x5000, 0x3b); // IRQ handler: RTI
|
||||
f.write(0xff95, 1); f.write(0xff90, 0x62); f.write(0xff92, 0x20);
|
||||
GimeAssertTimerInterupt(); breakpoints({0x5000}); exec(100);
|
||||
require(f.debugger.halted && f.host.CpuState().PC == 0x5000 && f.host.CpuState().S == 0x6ff4,
|
||||
"GIME IRQ reaches selected CPU through real SAM vector and mapped stack");
|
||||
require(MemRead8(0xff92) == 0x20, "Guest acknowledges GIME timer IRQ");
|
||||
breakpoints({}); f.debugger.halted = false; exec(1);
|
||||
require(f.host.CpuState().PC == stop+2 && f.host.CpuState().S == 0x7000,
|
||||
"CPU RTI restores guest after mapped IRQ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,787 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional integration check: user supplies the ROM; no ROM bytes live here.
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/devices/FD502/Fd502Device.h"
|
||||
#include "../../src/devices/HardDisk/HardDiskDevice.h"
|
||||
#include "../../src/devices/Orchestra90Device.h"
|
||||
#include "../../src/devices/SpeechSoundDevice.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <cstdio>
|
||||
namespace {
|
||||
void frames(VCC::Mac::MachineSession& machine, unsigned count) {
|
||||
while (count--) machine.advance();
|
||||
}
|
||||
std::string screen() {
|
||||
std::string text;
|
||||
for (unsigned i = 0; i < 512; ++i) {
|
||||
const unsigned c = SafeMemRead8(0x400 + i) & 0x3f;
|
||||
text += static_cast<char>(c < 32 ? c + 64 : c);
|
||||
if (i % 32 == 31) text += '\n';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
std::uint64_t key(char c) {
|
||||
unsigned bit;
|
||||
if (c >= 'A' && c <= 'Z') bit = c - '@';
|
||||
else if (c >= '0' && c <= '9') bit = 32 + c - '0';
|
||||
else if (c == ',') bit = 44;
|
||||
else if (c == '/') bit = 47;
|
||||
else if (c == '>') return (std::uint64_t{1} << 46) | (std::uint64_t{1} << 55);
|
||||
else if (c == '"') return (std::uint64_t{1} << 34) | (std::uint64_t{1} << 55);
|
||||
else if (c == ' ') bit = 31;
|
||||
else if (c == '\r') bit = 48;
|
||||
else if (c == '*') return (std::uint64_t{1} << 42) | (std::uint64_t{1} << 55);
|
||||
else throw std::logic_error("Unsupported authored probe character");
|
||||
return std::uint64_t{1} << bit;
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
void type(VCC::Mac::MachineSession& machine, const std::string& text) {
|
||||
for (char c : text) {
|
||||
machine.setKeyboard(key(c)); frames(machine, 4);
|
||||
machine.setKeyboard(0); frames(machine, 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
// Direct Run from either workspace must supply a callable entry and leave BASIC
|
||||
// responsive after RTS, including when rerunning from inside an earlier build.
|
||||
void checkWorkspaceReturn(VCC::Mac::MachineSession& machine) {
|
||||
const std::vector<std::uint8_t> program{0, 0, 2, 0x3f, 0, 0x12, 0x39, 0xff, 0, 0, 0x3f, 0}; // NOP, RTS
|
||||
const auto word = [](unsigned at) { return (SafeMemRead8(at) << 8) | SafeMemRead8(at + 1); };
|
||||
const auto stack = word(0x21) - 2;
|
||||
const auto before = machine.snapshot();
|
||||
machine.launchAssembly(program, {}, {}, true, false, before.generation, before.debuggerProgramRevision,
|
||||
before.debuggerMappingFingerprint);
|
||||
const auto entry = machine.snapshot();
|
||||
if (entry.cpu.PC != 0x3f00 || entry.cpu.S != stack || entry.cpu.DP || (entry.cpu.CC & 0x50) ||
|
||||
word(stack) != 0xac73)
|
||||
throw std::runtime_error("Assembly Direct Run did not establish the BASIC return frame");
|
||||
|
||||
machine.debuggerStep();
|
||||
if (machine.snapshot().cpu.PC != 0x3f01) throw std::runtime_error("Assembly Direct Run missed its next instruction");
|
||||
auto overlap = program;
|
||||
overlap.insert(overlap.end() - 5, {0, 0, 1, std::uint8_t(stack >> 8), std::uint8_t(stack), 0});
|
||||
try {
|
||||
machine.debuggerLoadBinary(overlap, 0x3f00);
|
||||
throw std::runtime_error("A development image overwrote BASIC's return frame");
|
||||
} catch (const std::invalid_argument&) {}
|
||||
if (word(stack) != 0xac73 || machine.snapshot().cpu.PC != 0x3f01 ||
|
||||
machine.snapshot().debuggerProgramRevision != entry.debuggerProgramRevision)
|
||||
throw std::runtime_error("Rejected development image changed the session");
|
||||
|
||||
machine.debuggerLoadBinary(program, 0x3f00);
|
||||
if (machine.snapshot().cpu.S != stack) throw std::runtime_error("Rerunning a development image nested its stack");
|
||||
machine.debuggerClearDevelopmentBreakpoints();
|
||||
machine.resume(); frames(machine, 60);
|
||||
type(machine, "PRINT 8*9\r"); frames(machine, 30);
|
||||
if (screen().find(" 72 ") == std::string::npos)
|
||||
throw std::runtime_error("BASIC did not accept a new command after the workspace program returned");
|
||||
}
|
||||
void pasteText(VCC::Mac::MachineSession& machine, const std::string& text) {
|
||||
std::vector<std::uint64_t> chords;
|
||||
for(char c:text) {
|
||||
if(c>='a' && c<='z') chords.push_back(key(c-'a'+'A'));
|
||||
else if(c>='A' && c<='Z') chords.push_back(key(c) | (std::uint64_t{1}<<55));
|
||||
else chords.push_back(key(c));
|
||||
}
|
||||
machine.paste(chords);
|
||||
for(unsigned n=0;machine.pasteRemaining() && n<20000;++n)machine.advance();
|
||||
if(machine.pasteRemaining())throw std::runtime_error("Paced text did not complete");
|
||||
}
|
||||
}
|
||||
void CheckRomBoot(const char* path) {
|
||||
std::ifstream file(path, std::ios::binary);
|
||||
std::vector<std::uint8_t> bytes(32769);
|
||||
file.read(reinterpret_cast<char*>(bytes.data()), bytes.size());
|
||||
if (file.gcount() != 32768) throw std::runtime_error("ROM check needs a readable 32 KiB system ROM");
|
||||
bytes.resize(32768);
|
||||
for (auto processor : {VCC::Mac::Processor::MC6809, VCC::Mac::Processor::HD6309}) {
|
||||
VCC::Mac::MachineSession machine; machine.load(bytes, processor); machine.resume(); frames(machine, 300);
|
||||
if (screen().find("OK") == std::string::npos) throw std::runtime_error("ROM did not reach BASIC");
|
||||
checkWorkspaceReturn(machine);
|
||||
type(machine, "10 PRINT 6*7\rRUN\r");
|
||||
frames(machine, 60);
|
||||
if (screen().find(" 42 ") == std::string::npos) throw std::runtime_error("BASIC keyboard/program check did not print 42");
|
||||
machine.pause(); const auto before = machine.snapshot(); frames(machine, 5);
|
||||
if (machine.snapshot().cycles != before.cycles) throw std::runtime_error("Paused ROM continued executing");
|
||||
machine.resume(); type(machine, "CLS\r");
|
||||
machine.softReset(); frames(machine, 300);
|
||||
type(machine, "LIST\r"); frames(machine, 20);
|
||||
if (screen().find("PRINT 6*7") == std::string::npos)
|
||||
throw std::runtime_error("Soft reset lost the BASIC program");
|
||||
type(machine, "CLS\rRUN\r"); frames(machine, 60);
|
||||
if (screen().find(" 42 ") == std::string::npos)
|
||||
throw std::runtime_error("Preserved BASIC program did not run after soft reset");
|
||||
machine.pause(); machine.softReset(); frames(machine, 5);
|
||||
if (machine.snapshot().cycles != 0 || machine.snapshot().state != VCC::Mac::RunState::Paused)
|
||||
throw std::runtime_error("Paused soft reset executed guest code");
|
||||
machine.resume(); frames(machine, 300); type(machine, "CLS\rRUN\r"); frames(machine, 60);
|
||||
if (screen().find(" 42 ") == std::string::npos)
|
||||
throw std::runtime_error("Paused soft reset lost the BASIC program");
|
||||
type(machine, "SOUND100,10\r");
|
||||
bool sound=false;
|
||||
for(unsigned i=0;i<120;++i) {
|
||||
machine.advance();
|
||||
for(auto sample:machine.takeAudio()) if(sample.left!=0 || sample.right!=0) sound=true;
|
||||
}
|
||||
if(!sound) throw std::runtime_error("BASIC SOUND produced no audio samples");
|
||||
for(auto format:{VCC::Mac::TapeFormat::CAS,VCC::Mac::TapeFormat::WAV}) {
|
||||
auto& tape=machine.cassette(); tape.record(format);
|
||||
type(machine, "CSAVE\"TEST\"\r"); frames(machine,1800);
|
||||
auto saved=tape.exportImage();
|
||||
if(saved.size()<100 || tape.snapshot().motor) throw std::runtime_error("BASIC CSAVE did not finish recording");
|
||||
tape.mount(saved,format); tape.setFast(false); tape.play();
|
||||
type(machine,"NEW\rCLS\rCLOAD\r"); frames(machine,2400);
|
||||
type(machine,"LIST\rRUN\r"); frames(machine,60);
|
||||
if(screen().find(" 42 ")==std::string::npos) {
|
||||
std::fprintf(stderr,"Tape load screen:\n%s\n",screen().c_str());
|
||||
throw std::runtime_error(format==VCC::Mac::TapeFormat::CAS ? "CAS round trip failed" : "WAV round trip failed");
|
||||
}
|
||||
if(format==VCC::Mac::TapeFormat::CAS) {
|
||||
tape.rewind(); tape.setFast(true); tape.play();
|
||||
type(machine,"NEW\rCLS\rCLOAD\r"); frames(machine,1200);
|
||||
type(machine,"RUN\r"); frames(machine,60);
|
||||
if(screen().find(" 42 ")==std::string::npos) throw std::runtime_error("Fast CAS round trip failed");
|
||||
}
|
||||
}
|
||||
std::printf("PASS: BASIC SOUND, CAS/WAV CSAVE/CLOAD, fast CAS (%s)\n",
|
||||
processor == VCC::Mac::Processor::MC6809 ? "6809" : "6309");
|
||||
machine.reset(); machine.resume(); frames(machine, 300);
|
||||
if (screen().find("OK") == std::string::npos || screen().find(" 42 ") != std::string::npos)
|
||||
throw std::runtime_error("Cold reset did not return to a clean BASIC prompt");
|
||||
std::printf("PASS: supplied ROM BASIC boot, keyboard program, pause, soft/cold reset (%s)\n",
|
||||
processor == VCC::Mac::Processor::MC6809 ? "6809" : "6309");
|
||||
// Two authored BIN data blocks: clear text RAM, then execute a program
|
||||
// that writes BIN OK to the display. No assembled binary is bundled.
|
||||
std::vector<std::uint8_t> binary{0,2,0,4,0}; binary.insert(binary.end(),512,0x60);
|
||||
std::vector<std::uint8_t> code;
|
||||
const std::string message = "BIN OK";
|
||||
for (unsigned i=0;i<message.size();++i)
|
||||
code.insert(code.end(),{0x86,std::uint8_t((message[i]&63)|64),0xb7,4,std::uint8_t(i)});
|
||||
code.insert(code.end(),{0x20,0xfe});
|
||||
binary.insert(binary.end(),{0,0,std::uint8_t(code.size()),0x30,0});
|
||||
binary.insert(binary.end(),code.begin(),code.end()); binary.insert(binary.end(),{255,0,0,0x30,0});
|
||||
const auto rawStack = machine.snapshot().cpu.S;
|
||||
machine.quickLoad(binary);
|
||||
if (machine.snapshot().cpu.S != rawStack) throw std::runtime_error("Raw BIN quickload changed the stack");
|
||||
frames(machine,10);
|
||||
if (screen().find(message)==std::string::npos) throw std::runtime_error("Quick-loaded BIN did not execute after BASIC boot");
|
||||
std::printf("PASS: supplied ROM with multi-block BIN quick-load (%s)\n",
|
||||
processor == VCC::Mac::Processor::MC6809 ? "6809" : "6309");
|
||||
}
|
||||
// Machine Settings matrix: a real ROM must also boot and run BASIC with
|
||||
// all retained RAM sizes. No media, generated captures, or ROM data is saved.
|
||||
for (auto processor : {VCC::Mac::Processor::MC6809, VCC::Mac::Processor::HD6309}) {
|
||||
for (unsigned ram = 0; ram < 4; ++ram) {
|
||||
VCC::Mac::MachineSession machine;
|
||||
VCC::Mac::MachineConfiguration settings;
|
||||
settings.processor = processor; settings.ram = ram; settings.frameInterval = 6;
|
||||
machine.configure(settings); machine.load(bytes, processor); machine.resume(); frames(machine, 300);
|
||||
if (screen().find("OK") == std::string::npos) throw std::runtime_error("Configured RAM did not boot BASIC");
|
||||
type(machine, "CLS\rPRINT 6*7\r"); frames(machine, 20);
|
||||
if (screen().find(" 42 ") == std::string::npos) throw std::runtime_error("Configured RAM did not run BASIC");
|
||||
std::printf("PASS: supplied ROM machine settings (%s, RAM choice %u, present every 6 frames)\n",
|
||||
processor == VCC::Mac::Processor::MC6809 ? "6809" : "6309", ram);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Optional disk BASIC integration. Both ROMs are supplied by the user; every
|
||||
// disk byte is authored here, and the source files are opened read-only.
|
||||
void CheckDiskRom(const char* systemPath, const char* diskPath) {
|
||||
using namespace VCC::Devices;
|
||||
auto readRom = [](const char* path, unsigned size) {
|
||||
std::ifstream file(path, std::ios::binary);
|
||||
std::vector<std::uint8_t> bytes(size + 1);
|
||||
file.read(reinterpret_cast<char*>(bytes.data()), bytes.size());
|
||||
if (file.gcount() != size) throw std::runtime_error("Disk check needs a 32 KiB system ROM and 8 KiB disk ROM");
|
||||
bytes.resize(size); return bytes;
|
||||
};
|
||||
const auto systemRom = readRom(systemPath, 32768), diskRom = readRom(diskPath, 8192);
|
||||
auto checkScreen = [](const char* expected, const char* operation) {
|
||||
const auto text = screen();
|
||||
if (text.find(expected) == std::string::npos || text.find("ERROR") != std::string::npos) {
|
||||
std::fprintf(stderr, "%s screen:\n%s\n", operation, text.c_str());
|
||||
throw std::runtime_error(operation);
|
||||
}
|
||||
};
|
||||
auto checkFormat = [&](auto cpu, DiskFormat format, const char* formatName) {
|
||||
VCC::Mac::MachineSession machine;
|
||||
auto device = makeDevice(DeviceKind::FD502, diskRom);
|
||||
auto* fdc = static_cast<Fd502Device*>(device.get());
|
||||
fdc->mount(0, DiskImage::blank({}, format));
|
||||
machine.cartridges().install(std::move(device)); machine.load(systemRom, cpu); machine.resume();
|
||||
frames(machine, 300); checkScreen("DISK EXTENDED", "Disk BASIC boot");
|
||||
type(machine, "CLS\rDSKINI0\r"); frames(machine, 6000);
|
||||
checkScreen("OK", "DSKINI formatting");
|
||||
if (fdc->snapshot().busy) throw std::runtime_error("DSKINI left the controller busy");
|
||||
type(machine, "10 PRINT 6*7\rSAVE\"TEST\"\r"); frames(machine, 1200);
|
||||
checkScreen("OK", "BASIC disk SAVE");
|
||||
type(machine, "CLS\rDIR\r"); frames(machine, 300); checkScreen("TEST", "Directory after SAVE");
|
||||
const auto saved = fdc->image(0)->bytes();
|
||||
fdc->markSaved(0); fdc->eject(0); fdc->mount(0, DiskImage::load(saved));
|
||||
machine.reset(); frames(machine, 300);
|
||||
type(machine, "CLS\rLOAD\"TEST\"\r"); frames(machine, 1200);
|
||||
type(machine, "LIST\rRUN\r"); frames(machine, 60);
|
||||
checkScreen("PRINT 6*7", "Reloaded disk program LIST"); checkScreen(" 42 ", "Reloaded disk program RUN");
|
||||
if (fdc->image(0)->bytes() != saved) throw std::runtime_error("Reading changed the disk image");
|
||||
fdc->mount(0, DiskImage::load(saved, true));
|
||||
type(machine, "CLS\rSAVE\"BLOCK\"\r"); frames(machine, 600);
|
||||
if (screen().find("?WP ERROR") == std::string::npos || fdc->image(0)->bytes() != saved)
|
||||
throw std::runtime_error("Write-protected SAVE must report WP ERROR and preserve disk bytes");
|
||||
std::printf("PASS: Disk BASIC DSKINI, SAVE, DIR, eject/reopen, cold boot, LOAD/LIST/RUN and write protection (%s, %s)\n",
|
||||
formatName,
|
||||
cpu == VCC::Mac::Processor::MC6809 ? "6809" : "6309");
|
||||
};
|
||||
for (auto cpu : {VCC::Mac::Processor::MC6809, VCC::Mac::Processor::HD6309}) {
|
||||
checkFormat(cpu, DiskFormat::JVC, "DSK");
|
||||
checkFormat(cpu, DiskFormat::DMK, "DMK");
|
||||
checkFormat(cpu, DiskFormat::VDK, "VDK");
|
||||
}
|
||||
}
|
||||
|
||||
// Optional reference-image check. All writes stay in an owned memory copy;
|
||||
// supplied system ROM, RGBDOS ROM and NitrOS-9 VHD are opened read-only.
|
||||
void CheckHardDiskRom(const char* systemPath, const char* rgbPath, const char* imagePath, const char* dataPath) {
|
||||
using namespace VCC::Devices;
|
||||
auto read = [](const char* path, std::size_t limit) {
|
||||
std::ifstream file(path, std::ios::binary | std::ios::ate);
|
||||
auto length = file.tellg();
|
||||
if (!file || length <= 0 || std::uint64_t(length) > limit) throw std::runtime_error("Invalid supplied hard-disk fixture");
|
||||
std::vector<std::uint8_t> bytes(static_cast<std::size_t>(length)); file.seekg(0);
|
||||
if (!file.read(reinterpret_cast<char*>(bytes.data()), bytes.size())) throw std::runtime_error("Unable to read supplied hard-disk fixture");
|
||||
return bytes;
|
||||
};
|
||||
const auto system = read(systemPath,32768), rgb = read(rgbPath,16384), original = read(imagePath,HardDiskImage::maxBytes);
|
||||
// Read a standard OS-9 RBF file descriptor and its segment list. Used only
|
||||
// for independent verification of the guest's on-disk result.
|
||||
auto fileBytes = [](const std::vector<std::uint8_t>& disk, std::uint32_t descriptor) {
|
||||
const auto fd = std::size_t(descriptor) * 256;
|
||||
if (fd + 256 > disk.size()) throw std::runtime_error("RBF descriptor outside image");
|
||||
std::uint32_t size = 0; for (unsigned i=9;i<13;++i) size = (size<<8)|disk[fd+i];
|
||||
if (size > HardDiskImage::maxBytes) throw std::runtime_error("RBF file size outside limit");
|
||||
std::vector<std::uint8_t> result;
|
||||
for (unsigned entry=16; entry+5<=256 && result.size()<size; entry+=5) {
|
||||
std::uint32_t sector = (disk[fd+entry]<<16)|(disk[fd+entry+1]<<8)|disk[fd+entry+2];
|
||||
unsigned count = (disk[fd+entry+3]<<8)|disk[fd+entry+4];
|
||||
if (!count) break;
|
||||
auto start=std::size_t(sector)*256, length=std::min(std::size_t(count)*256,std::size_t(size)-result.size());
|
||||
if (start+length > disk.size()) throw std::runtime_error("RBF segment outside image");
|
||||
result.insert(result.end(),disk.begin()+start,disk.begin()+start+length);
|
||||
}
|
||||
if (result.size()!=size) throw std::runtime_error("Incomplete RBF file");
|
||||
return result;
|
||||
};
|
||||
for (auto cpu : {VCC::Mac::Processor::MC6809,VCC::Mac::Processor::HD6309}) {
|
||||
VCC::Mac::MachineSession machine;
|
||||
auto hard = std::make_shared<HardDiskDevice>(); hard->mount(0,HardDiskImage(original));
|
||||
if (dataPath) hard->mount(1,HardDiskImage(read(dataPath,HardDiskImage::maxBytes)));
|
||||
auto floppy = std::make_shared<Fd502Device>(rgb);
|
||||
machine.cartridges().configure({nullptr,hard,nullptr,nullptr,floppy},true,4);
|
||||
machine.load(system,cpu);
|
||||
if (dataPath) machine.requestNitros9Boot();
|
||||
machine.resume();
|
||||
try { frames(machine,600); } catch (...) { std::fprintf(stderr,"Boot screen:\n%s\n",screen().c_str()); throw; }
|
||||
if (!dataPath && screen().find("HARD DISK BASIC")==std::string::npos) throw std::runtime_error("RGBDOS did not boot");
|
||||
if (!dataPath) type(machine,"DOS255\r");
|
||||
frames(machine,3600);
|
||||
if (machine.nitros9BootPending()) throw std::runtime_error("Automatic boot still pending");
|
||||
type(machine,"ECHO VCCPORTCHECK >/H0/VCCMACTEST\r"); frames(machine,600);
|
||||
const auto& result = hard->image(0)->bytes();
|
||||
auto root = (result[8]<<16)|(result[9]<<8)|result[10]; auto entries = fileBytes(result,root);
|
||||
bool found = false;
|
||||
for (std::size_t i=0;i+32<=entries.size();i+=32) {
|
||||
if (!entries[i]) continue;
|
||||
std::string name;
|
||||
for (unsigned j=0;j<29;++j) { auto c=entries[i+j]; name += char(c&127); if(c&128) break; }
|
||||
if (name!="vccmactest") continue;
|
||||
auto fd = (entries[i+29]<<16)|(entries[i+30]<<8)|entries[i+31];
|
||||
auto bytes = fileBytes(result,fd); auto text = std::string(bytes.begin(),bytes.end());
|
||||
if (text.find("vccportcheck")==std::string::npos) throw std::runtime_error("NitrOS-9 file contents mismatch");
|
||||
// Reopen the serialized image independently and read the same file.
|
||||
HardDiskImage reopened(result);
|
||||
if (fileBytes(reopened.bytes(),fd)!=bytes) throw std::runtime_error("Hard disk reopen mismatch");
|
||||
found = true; break;
|
||||
}
|
||||
if (!found || !hard->image(0)->dirty()) throw std::runtime_error("NitrOS-9 did not create its test file");
|
||||
if (dataPath) {
|
||||
pasteText(machine,"echo sharedportcheck >/h1/vccmactest\r"); frames(machine,600);
|
||||
// Interleave reads from HD0 with writes to HD1; this catches a
|
||||
// driver that selects a unit once instead of on every transfer.
|
||||
pasteText(machine,"dir /dd/games >/h1/catalog\r"); frames(machine,600);
|
||||
const auto shared = hard->image(1)->bytes();
|
||||
const auto before = read(dataPath,HardDiskImage::maxBytes);
|
||||
if (!std::equal(before.begin()+0x5a000*256,before.end(),shared.begin()+0x5a000*256))
|
||||
throw std::runtime_error("OS-9 write modified BASIC volumes");
|
||||
auto root1=(shared[8]<<16)|(shared[9]<<8)|shared[10]; auto directory=fileBytes(shared,root1);
|
||||
bool written=false, catalog=false;
|
||||
for (std::size_t i=0;i+32<=directory.size();i+=32) {
|
||||
if (!directory[i]) continue;
|
||||
std::string name;
|
||||
for(unsigned j=0;j<29;++j) { auto c=directory[i+j];name+=char(c&127);if(c&128)break; }
|
||||
if(name!="vccmactest" && name!="catalog")continue;
|
||||
auto fd=(directory[i+29]<<16)|(directory[i+30]<<8)|directory[i+31];
|
||||
auto bytes=fileBytes(shared,fd);
|
||||
if(name=="catalog") {
|
||||
std::string listing(bytes.begin(),bytes.end());
|
||||
std::transform(listing.begin(),listing.end(),listing.begin(),[](unsigned char c) { return c >= 'A' && c <= 'Z' ? c+32 : c; });
|
||||
catalog=listing.find("rogue")!=std::string::npos;
|
||||
continue;
|
||||
}
|
||||
if(std::string(bytes.begin(),bytes.end()).find("sharedportcheck")==std::string::npos)
|
||||
throw std::runtime_error("Shared HD1 write content mismatch");
|
||||
HardDiskImage reopened(shared);
|
||||
if(fileBytes(reopened.bytes(),fd)!=bytes)throw std::runtime_error("Shared HD1 reopen mismatch");
|
||||
written=true;
|
||||
}
|
||||
if(!written || !catalog)throw std::runtime_error("NitrOS-9 HD1 write or cross-drive catalogue read failed");
|
||||
std::printf("PASS: automatic DOS 255, shared OS-9 HD1 write/reopen, BASIC volumes unchanged\n");
|
||||
}
|
||||
std::printf("PASS: RGBDOS, NitrOS-9 boot, guest file creation and raw-image reopen (%s)\n",cpu==VCC::Mac::Processor::MC6809?"6809":"6309");
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
void installPlanetSource(VCC::Mac::MachineSession& machine) {
|
||||
// Packaging and the documented regeneration commands run from the checkout.
|
||||
std::ifstream file("examples/basic/planet.bas");
|
||||
if (!file) throw std::runtime_error("Cannot open examples/basic/planet.bas; run from the repository root");
|
||||
std::string source{std::istreambuf_iterator<char>(file), {}};
|
||||
machine.basicLoadSource(source, false);
|
||||
frames(machine, 30);
|
||||
}
|
||||
|
||||
void runPlanetStarter(VCC::Mac::MachineSession& machine, char choice) {
|
||||
type(machine, "CLS\rRUN\r");
|
||||
frames(machine, 30);
|
||||
type(machine, "3"); // An unrelated key leaves BASIC waiting at the menu.
|
||||
const auto menu = machine.copyScreenText();
|
||||
if (menu.find("What planet do you live on?\n1) Earth\n2) Mars") == std::string::npos ||
|
||||
menu.find("World!") != std::string::npos || menu.find("OK") != std::string::npos)
|
||||
throw std::runtime_error("Planet starter did not wait for a choice:\n" + menu);
|
||||
type(machine, std::string(1, choice));
|
||||
frames(machine, 30);
|
||||
const auto result = machine.copyScreenText();
|
||||
const auto greeting = result.find(choice == '1' ? "Hello Nice Blue Dot World!" : "Hello Cold Red Dot World!");
|
||||
if (greeting == std::string::npos || result.find("OK", greeting) == std::string::npos)
|
||||
throw std::runtime_error("Planet starter did not greet the player and return to BASIC:\n" + result);
|
||||
type(machine, "WIDTH 32\r"); // The disk command probes use the 32-column BASIC display.
|
||||
}
|
||||
}
|
||||
|
||||
// Reproducible starter media, authored through real BASIC and independently
|
||||
// reloaded on both CPUs. Only the caller-supplied output directory is written.
|
||||
void CreateStarterMedia(const char* systemPath, const char* diskPath, const char* output) {
|
||||
using namespace VCC::Devices;
|
||||
using namespace VCC::Mac;
|
||||
auto read = [](const char* path, std::size_t size) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
std::vector<std::uint8_t> data(size + 1);
|
||||
f.read(reinterpret_cast<char*>(data.data()), data.size());
|
||||
if (std::size_t(f.gcount()) != size) throw std::runtime_error("Starter media requires a 32 KiB system and 8 KiB disk ROM");
|
||||
data.resize(size); return data;
|
||||
};
|
||||
auto expect = [](const char* text) {
|
||||
if (screen().find(text) == std::string::npos || screen().find("ERROR") != std::string::npos)
|
||||
throw std::runtime_error(std::string("Starter verification failed: ") + text + "\n" + screen());
|
||||
};
|
||||
const auto system = read(systemPath,32768), rom = read(diskPath,8192);
|
||||
std::vector<std::uint8_t> disk, tape;
|
||||
{
|
||||
MachineSession m; auto fdc=std::make_shared<Fd502Device>(rom);
|
||||
fdc->mount(0,DiskImage::blank());
|
||||
m.cartridges().configure({nullptr,nullptr,nullptr,nullptr,fdc},true,4);
|
||||
m.load(system);m.resume();frames(m,300);expect("DISK EXTENDED");
|
||||
type(m,"CLS\rDSKINI0\r");frames(m,6000);expect("OK");
|
||||
installPlanetSource(m);
|
||||
type(m,"SAVE\"HELLO\"\r");frames(m,1200);expect("OK");
|
||||
type(m,"CLS\rDIR\r");frames(m,120);expect("HELLO");disk=fdc->image(0)->bytes();
|
||||
m.cassette().record(TapeFormat::CAS);type(m,"CSAVE\"HELLO\"\r");frames(m,1800);
|
||||
if(m.cassette().snapshot().motor) throw std::runtime_error("Starter CSAVE did not finish");
|
||||
tape=m.cassette().exportImage();
|
||||
}
|
||||
for(auto cpu:{Processor::MC6809,Processor::HD6309}) {
|
||||
MachineSession m;auto fdc=std::make_shared<Fd502Device>(rom);fdc->mount(0,DiskImage::load(disk));
|
||||
m.cartridges().configure({nullptr,nullptr,nullptr,nullptr,fdc},true,4);
|
||||
m.cassette().mount(tape,TapeFormat::CAS);m.load(system,cpu);m.resume();frames(m,300);
|
||||
expect("DISK EXTENDED");expect("OK");
|
||||
if(m.cassette().snapshot().mode!=TapeMode::Stopped || m.cassette().snapshot().position!=0)
|
||||
throw std::runtime_error("Starter cassette must remain stopped at launch");
|
||||
type(m,"CLS\rLIST\r");frames(m,60);
|
||||
if(!m.basicReadSource().empty())
|
||||
throw std::runtime_error("Starter program was loaded automatically");
|
||||
type(m,"LOAD\"HELLO\"\r");frames(m,1200);
|
||||
runPlanetStarter(m,'1');
|
||||
runPlanetStarter(m,'2');
|
||||
type(m,"NEW\rCLS\r");m.cassette().play();type(m,"CLOAD\"HELLO\"\r");frames(m,3600);
|
||||
runPlanetStarter(m,'1');
|
||||
runPlanetStarter(m,'2');
|
||||
if(fdc->image(0)->bytes()!=disk) throw std::runtime_error("Starter disk changed on read");
|
||||
std::printf("PASS: starter Disk BASIC, no auto-load, disk LOAD/RUN, cassette CLOAD/RUN (%s)\n",cpu==Processor::MC6809?"6809":"6309");
|
||||
}
|
||||
auto write=[&](const char* name,const std::vector<std::uint8_t>& data) {
|
||||
std::ofstream f(std::string(output)+"/"+name,std::ios::binary|std::ios::trunc);
|
||||
f.write(reinterpret_cast<const char*>(data.data()),data.size());
|
||||
if(!f)throw std::runtime_error("Could not write starter media");
|
||||
};
|
||||
write("Hello World.dsk",disk);write("Hello World.cas",tape);
|
||||
}
|
||||
|
||||
|
||||
// Authored BASIC-only hard-disk template. Reserved OS-9 space is zero-filled;
|
||||
// no downloaded disk contents or operating system are redistributed.
|
||||
void CreateHardBasicMedia(const char* systemPath, const char* rgbPath, const char* floppyPath, const char* output) {
|
||||
using namespace VCC::Devices;
|
||||
using namespace VCC::Mac;
|
||||
auto read=[](const char* path, std::size_t size) {
|
||||
std::ifstream f(path,std::ios::binary); std::vector<std::uint8_t> data(size+1);
|
||||
f.read(reinterpret_cast<char*>(data.data()),data.size());
|
||||
if(std::size_t(f.gcount())!=size) throw std::runtime_error("Unexpected hard BASIC input size");
|
||||
data.resize(size);return data;
|
||||
};
|
||||
auto expect=[](const char* text) {
|
||||
if(screen().find(text)==std::string::npos || screen().find("ERROR")!=std::string::npos)
|
||||
throw std::runtime_error(std::string("Hard BASIC verification failed: ")+text+"\n"+screen());
|
||||
};
|
||||
const auto system=read(systemPath,32768), rgb=read(rgbPath,8192), floppy=read(floppyPath,161280);
|
||||
constexpr std::size_t offset=0x5a000*256, volume=161280;
|
||||
std::vector<std::uint8_t> image(offset+256*volume,0), blank, hello;
|
||||
{
|
||||
MachineSession m;auto hd=std::make_shared<HardDiskDevice>();hd->mount(0,HardDiskImage(image));
|
||||
auto fd=std::make_shared<Fd502Device>(rgb);fd->mount(0,DiskImage::load(floppy));
|
||||
m.cartridges().configure({nullptr,hd,nullptr,nullptr,fd},true,4);
|
||||
m.load(system);m.resume();frames(m,600);expect("HARD DISK BASIC");
|
||||
type(m,"CLS\rDSKINI0\r");frames(m,60);type(m,"Y");frames(m,1200);expect("OK");
|
||||
const auto& formatted=hd->image(0)->bytes();
|
||||
blank.assign(formatted.begin()+offset,formatted.begin()+offset+volume);
|
||||
installPlanetSource(m);
|
||||
type(m,"SAVE\"HELLO\"\r");frames(m,1200);expect("OK");
|
||||
const auto& saved=hd->image(0)->bytes();
|
||||
hello.assign(saved.begin()+offset,saved.begin()+offset+volume);
|
||||
std::copy(hello.begin(),hello.end(),image.begin()+offset);
|
||||
for(unsigned i=1;i<256;++i) std::copy(blank.begin(),blank.end(),image.begin()+offset+i*volume);
|
||||
}
|
||||
for(auto cpu:{Processor::MC6809,Processor::HD6309}) {
|
||||
MachineSession m;auto hd=std::make_shared<HardDiskDevice>();hd->mount(0,HardDiskImage(image));
|
||||
auto fd=std::make_shared<Fd502Device>(rgb);fd->mount(0,DiskImage::load(floppy));
|
||||
m.cartridges().configure({nullptr,hd,nullptr,nullptr,fd},true,4);
|
||||
m.load(system,cpu);m.resume();frames(m,600);expect("HARD DISK BASIC");
|
||||
type(m,"CLS\rLIST\r");frames(m,60);expect("OK");
|
||||
if(!m.basicReadSource().empty())
|
||||
throw std::runtime_error("Hard BASIC must not load/run a program at boot");
|
||||
const auto hdReads = hd->readEvents(0);
|
||||
const auto fdReads = fd->readEvents(0);
|
||||
type(m,"DIR\rLOAD\"HELLO\"\r");frames(m,600);expect("OK");
|
||||
runPlanetStarter(m,'1');
|
||||
runPlanetStarter(m,'2');
|
||||
if(hd->readEvents(0)==hdReads || fd->readEvents(0)!=fdReads)
|
||||
throw std::runtime_error("RGBDOS did not read the starter from HD0");
|
||||
const auto afterHD = hd->readEvents(0);
|
||||
type(m,"NEW\rDRIVE OFF\rLOAD\"HELLO\"\r");frames(m,1200);expect("OK");
|
||||
runPlanetStarter(m,'1');
|
||||
if(fd->readEvents(0)==fdReads || hd->readEvents(0)!=afterHD)
|
||||
throw std::runtime_error("DRIVE OFF did not read the starter from FD0");
|
||||
const auto afterFD = fd->readEvents(0);
|
||||
type(m,"NEW\rDRIVE ON\rLOAD\"HELLO\"\r");frames(m,600);
|
||||
runPlanetStarter(m,'2');
|
||||
if(hd->readEvents(0)==afterHD || fd->readEvents(0)!=afterFD)
|
||||
throw std::runtime_error("DRIVE ON did not return to HD0");
|
||||
if(fd->image(0)->bytes()!=floppy || hd->image(0)->bytes()!=image)
|
||||
throw std::runtime_error("Reading starters altered their images");
|
||||
type(m,"CLS\rDRIVE255\rSAVE\"CHECK\"\r");frames(m,600);expect("OK");
|
||||
auto saved=hd->image(0)->bytes();hd->eject(0,true);hd->mount(0,HardDiskImage(saved));
|
||||
type(m,"NEW\rLOAD\"CHECK\"\r");frames(m,600);
|
||||
runPlanetStarter(m,'2');
|
||||
if(saved==image || !std::equal(image.begin(),image.begin()+offset+255*volume,saved.begin()))
|
||||
throw std::runtime_error("Last virtual disk SAVE altered other volumes");
|
||||
std::printf("PASS: Hard BASIC boot/no auto-load, HD/floppy LOAD/RUN, DRIVE OFF/ON, volume 255 SAVE/reopen (%s)\n",cpu==Processor::MC6809?"6809":"6309");
|
||||
}
|
||||
auto write=[&](const char* name,const std::vector<std::uint8_t>& data) {
|
||||
std::ofstream f(std::string(output)+"/"+name,std::ios::binary|std::ios::trunc);
|
||||
f.write(reinterpret_cast<const char*>(data.data()),data.size());
|
||||
if(!f)throw std::runtime_error("Could not write authored hard BASIC template");
|
||||
};
|
||||
write("Blank Disk.dsk",blank);write("Hello Hard Disk.dsk",hello);
|
||||
}
|
||||
|
||||
void CheckClipboardRom(const char* path) {
|
||||
std::ifstream file(path,std::ios::binary);
|
||||
std::vector<std::uint8_t> rom((std::istreambuf_iterator<char>(file)),{});
|
||||
for(auto cpu:{VCC::Mac::Processor::MC6809,VCC::Mac::Processor::HD6309}) {
|
||||
VCC::Mac::MachineSession m;m.load(rom,cpu);m.resume();frames(m,300);
|
||||
auto paste=[&](const std::string& text) {
|
||||
std::vector<std::uint64_t> keys;
|
||||
for(char c:text) {
|
||||
auto chord=key(c);
|
||||
if(c>='A' && c<='Z')chord|=std::uint64_t{1}<<55; // Native clipboard uppercase mapping.
|
||||
keys.push_back(chord);
|
||||
}
|
||||
m.paste(keys);
|
||||
for(unsigned n=0;m.pasteRemaining() && n<20000;++n)m.advance();
|
||||
if(m.pasteRemaining())throw std::runtime_error("Paste did not finish");
|
||||
frames(m,30);
|
||||
};
|
||||
paste("10 PRINT 6*7\r20 PRINT 7*7\r");
|
||||
paste("20 PRINT 8*8\rCLS\rRUN\r");
|
||||
auto text=m.copyScreenText();
|
||||
if(text.find(" 42")==std::string::npos || text.find(" 64")==std::string::npos || text.find(" 49")!=std::string::npos)
|
||||
throw std::runtime_error("BASIC merge/copy did not preserve or replace lines: "+text);
|
||||
paste("NEW\r10 PRINT 9*9\rCLS\rRUN\r");text=m.copyScreenText();
|
||||
if(text.find(" 81")==std::string::npos || text.find(" 42")!=std::string::npos)
|
||||
throw std::runtime_error("BASIC replacement/copy failed: "+text);
|
||||
// Verify the safe entry limit through the actual interpreter.
|
||||
std::string line="30 REM "+std::string(242,'A'); // exactly 249 characters
|
||||
paste(line+"\r");
|
||||
paste("CLS\rLIST 30\r");text=m.copyScreenText();
|
||||
if(text.find("30 REM")==std::string::npos || std::count(text.begin(),text.end(),'A')!=242)
|
||||
throw std::runtime_error("Boundary BASIC line failed: "+text);
|
||||
std::printf("PASS: paced BASIC merge/replace, 249-character boundary, copy screen (%s)\n",cpu==VCC::Mac::Processor::MC6809?"6809":"6309");
|
||||
}
|
||||
}
|
||||
|
||||
// Optional private-ROM integration; generated PCM is a local listening artifact.
|
||||
void CheckOrchestraRom(const char* systemPath, const char* orchestraPath, const char* outputPrefix) {
|
||||
auto read = [](const char* path, std::size_t size) {
|
||||
std::ifstream f(path, std::ios::binary); std::vector<std::uint8_t> b(size+1);
|
||||
f.read(reinterpret_cast<char*>(b.data()), b.size());
|
||||
if (std::size_t(f.gcount()) != size) throw std::runtime_error("Unexpected Orchestra reference ROM size");
|
||||
b.resize(size); return b;
|
||||
};
|
||||
auto system = read(systemPath,32768), rom = read(orchestraPath,8192);
|
||||
for (auto cpu : {VCC::Mac::Processor::MC6809, VCC::Mac::Processor::HD6309}) {
|
||||
VCC::Mac::MachineSession m;
|
||||
m.cartridges().configure({nullptr,std::make_shared<VCC::Devices::Orchestra90Device>(rom),nullptr,nullptr,nullptr},true,1);
|
||||
m.load(system,cpu); m.resume(); frames(m,300);
|
||||
type(m," "); frames(m,60); // Dismiss the copyright screen, per manual page 8.
|
||||
if (screen().find("WILLIAM TELL") == std::string::npos) {
|
||||
std::fprintf(stderr,"%s",screen().c_str()); throw std::runtime_error("Orchestra ROM did not reach its demonstration screen");
|
||||
}
|
||||
type(m,"S\r"); frames(m,600); m.takeAudio();
|
||||
type(m,"P\r"); m.takeAudio();
|
||||
std::vector<VCC::Mac::StereoSample> pcm;
|
||||
for (unsigned i=0;i<3600;++i) { m.advance(); auto part=m.takeAudio(); pcm.insert(pcm.end(),part.begin(),part.end()); }
|
||||
float minL=1,maxL=-1,minR=1,maxR=-1; unsigned different=0;
|
||||
for(auto v:pcm) { minL=std::min(minL,v.left);maxL=std::max(maxL,v.left);minR=std::min(minR,v.right);maxR=std::max(maxR,v.right);different+=v.left!=v.right; }
|
||||
if(maxL-minL<.05f || maxR-minR<.05f || different<1000) throw std::runtime_error("Demonstration did not produce independent stereo music");
|
||||
std::string path=std::string(outputPrefix)+(cpu==VCC::Mac::Processor::MC6809 ? "-6809.wav" : "-6309.wav");
|
||||
if (pcm.size() > (std::numeric_limits<std::uint32_t>::max() - 36u) / 4u)
|
||||
throw std::runtime_error("Listening capture exceeds the WAV size limit");
|
||||
const auto dataBytes = static_cast<std::uint32_t>(pcm.size() * 4u);
|
||||
std::ofstream out(path,std::ios::binary);
|
||||
auto word=[&](std::uint32_t v,unsigned n){while(n--){out.put(v&255);v>>=8;}};
|
||||
out.write("RIFF",4);word(36u+dataBytes,4);out.write("WAVEfmt ",8);word(16,4);word(1,2);word(2,2);
|
||||
word(44100,4);word(44100*4,4);word(4,2);word(16,2);out.write("data",4);word(dataBytes,4);
|
||||
for(auto v:pcm) {word(std::uint16_t(std::int16_t(v.left*32767)),2);word(std::uint16_t(std::int16_t(v.right*32767)),2);}
|
||||
if(!out)throw std::runtime_error("Could not write private listening capture");
|
||||
std::printf("Orchestra %s: %zu stereo samples, %u differing channels, ranges %.3f/%.3f; %s\n",cpu==VCC::Mac::Processor::MC6809 ? "6809" : "6309",pcm.size(),different,maxL-minL,maxR-minR,path.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Authored guest sends documented SSC command bytes, polling BUSY before each.
|
||||
void CheckSpeechSoundRom(const char* systemPath, const char* picPath, const char* speechPath, const char* outputPrefix) {
|
||||
using namespace VCC::Mac;
|
||||
auto read=[](const char* path,std::size_t size){
|
||||
std::ifstream f(path,std::ios::binary);std::vector<std::uint8_t> b(size+1);
|
||||
f.read(reinterpret_cast<char*>(b.data()),b.size());
|
||||
if(std::size_t(f.gcount())!=size)throw std::runtime_error("Unexpected Speech/Sound reference ROM size");
|
||||
b.resize(size);return b;
|
||||
};
|
||||
auto system=read(systemPath,32768),rom=read(picPath,4096),speech=read(speechPath,2048);
|
||||
rom.insert(rom.end(),speech.begin(),speech.end());
|
||||
for(auto cpu:{Processor::MC6809,Processor::HD6309}) {
|
||||
MachineSession m;auto device=std::make_shared<VCC::Devices::SpeechSoundDevice>(rom);
|
||||
m.cartridges().configure({nullptr,nullptr,device,nullptr,nullptr},true,4);
|
||||
m.load(system,cpu);m.resume();frames(m,60);m.takeAudio();
|
||||
auto send=[&](const std::vector<std::uint8_t>& bytes){
|
||||
const auto end=0x3040+bytes.size();
|
||||
// Authored guest explicitly selects cartridge SND and enables the
|
||||
// analog mux, just as physical Speech/Sound software must do.
|
||||
std::vector<std::uint8_t> code{0xb6,0xff,0x01,0x84,0xf7,0xb7,0xff,0x01,
|
||||
0xb6,0xff,0x03,0x8a,0x08,0xb7,0xff,0x03,
|
||||
0xb6,0xff,0x23,0x8a,0x08,0xb7,0xff,0x23,0x8e,0x30,0x40,0x8c,std::uint8_t(end>>8),std::uint8_t(end),
|
||||
0x27,12,0xe6,0x80,0xb6,0xff,0x7e,0x2a,0xfb,0xf7,0xff,0x7e,0x20,0xef,0x20,0xfe};
|
||||
code.resize(64,0x12);code.insert(code.end(),bytes.begin(),bytes.end());
|
||||
std::vector<std::uint8_t> binary{0,0,std::uint8_t(code.size()),0x30,0};
|
||||
binary.insert(binary.end(),code.begin(),code.end());binary.insert(binary.end(),{0xff,0,0,0x30,0});
|
||||
m.quickLoad(binary);
|
||||
};
|
||||
std::string phrase="HELLO FROM YOUR COLOR COMPUTER. \r";
|
||||
send({phrase.begin(),phrase.end()});
|
||||
std::vector<StereoSample> pcm;
|
||||
for(unsigned i=0;i<600;++i){m.advance();auto part=m.takeAudio();pcm.insert(pcm.end(),part.begin(),part.end());}
|
||||
if(device->diagnostics().CommandCount()!=phrase.size() || device->diagnostics().AldSpeechCount()<5 || device->diagnostics().CpuIllegalCount()!=0)
|
||||
throw std::runtime_error("Speech firmware failed command/phoneme execution");
|
||||
float low=1,high=-1;
|
||||
for(auto sample:pcm){low=std::min(low,sample.left);high=std::max(high,sample.left);if(sample.left!=sample.right)throw std::runtime_error("SSC must be mono on both output channels");}
|
||||
if(high-low<.05f)throw std::runtime_error("Speech produced no signal");
|
||||
std::string path=std::string(outputPrefix)+(cpu==Processor::MC6809?"-6809.wav":"-6309.wav");
|
||||
if (pcm.size() > (std::numeric_limits<std::uint32_t>::max() - 36u) / 4u)
|
||||
throw std::runtime_error("Listening capture exceeds the WAV size limit");
|
||||
const auto dataBytes = static_cast<std::uint32_t>(pcm.size() * 4u);
|
||||
std::ofstream out(path,std::ios::binary);
|
||||
auto word=[&](std::uint32_t v,unsigned n){while(n--){out.put(v&255);v>>=8;}};
|
||||
out.write("RIFF",4);word(36u+dataBytes,4);out.write("WAVEfmt ",8);word(16,4);word(1,2);word(2,2);
|
||||
word(44100,4);word(44100*4,4);word(4,2);word(16,2);out.write("data",4);word(dataBytes,4);
|
||||
// Capture the actual signed native PCM without introducing a DC offset.
|
||||
for(auto v:pcm){word(std::uint16_t(std::int16_t(std::clamp(v.left,-1.0f,1.0f)*32767)),2);word(std::uint16_t(std::int16_t(std::clamp(v.right,-1.0f,1.0f)*32767)),2);}
|
||||
if(!out)throw std::runtime_error("Could not write speech listening capture");
|
||||
const auto ay=device->diagnostics().AyWriteCount();
|
||||
send({0xaf,0,100,1,0,7,62,8,15,0xff});
|
||||
float musicLow=1,musicHigh=-1;
|
||||
for(unsigned i=0;i<60;++i){m.advance();for(auto v:m.takeAudio()){musicLow=std::min(musicLow,v.left);musicHigh=std::max(musicHigh,v.left);}}
|
||||
if(device->diagnostics().AyWriteCount()<ay+4 || musicHigh-musicLow<.05f)throw std::runtime_error("SSC music registers produced no tone");
|
||||
send({0});frames(m,30);
|
||||
std::printf("PASS SSC %s: %zu speech samples, %u phonemes, range %.3f; AY tone range %.3f; %s\n",cpu==Processor::MC6809?"6809":"6309",pcm.size(),device->diagnostics().AldSpeechCount(),high-low,musicHigh-musicLow,path.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Direct-memory BASIC transfers must match bytes produced by the ROM itself.
|
||||
void CheckBasicProgramRom(const char* systemPath, const char* diskPath) {
|
||||
auto read = [](const char* path) {
|
||||
std::ifstream stream(path, std::ios::binary);
|
||||
if (!stream) throw std::runtime_error("Unable to open BASIC integration ROM");
|
||||
return std::vector<std::uint8_t>((std::istreambuf_iterator<char>(stream)), {});
|
||||
};
|
||||
const auto system=read(systemPath), disk=read(diskPath);
|
||||
for (auto cpu : {VCC::Mac::Processor::MC6809,VCC::Mac::Processor::HD6309}) {
|
||||
VCC::Mac::MachineSession m;
|
||||
auto floppy = std::make_shared<VCC::Devices::Fd502Device>(disk);
|
||||
m.cartridges().configure({nullptr,nullptr,nullptr,nullptr,floppy},true,4);
|
||||
m.load(system,cpu);m.resume();frames(m,300);
|
||||
type(m,"10 PRINT 6*7\r20 END\r");frames(m,30);
|
||||
auto program = [&] {
|
||||
unsigned start=(SafeMemRead8(0x19)<<8)|SafeMemRead8(0x1a), end=(SafeMemRead8(0x1b)<<8)|SafeMemRead8(0x1c);
|
||||
std::vector<std::uint8_t> bytes;
|
||||
for(unsigned p=start;p<end;++p) bytes.push_back(SafeMemRead8(p));
|
||||
return bytes;
|
||||
};
|
||||
const auto oracle=program();
|
||||
m.pause();const auto before=m.snapshot();
|
||||
m.basicLoadSource("10 PRINT 6*7\n20 END\n",false);
|
||||
if(program()!=oracle || m.snapshot().cycles!=before.cycles || m.snapshot().state!=VCC::Mac::RunState::Paused)
|
||||
throw std::runtime_error("Direct BASIC bytes differ from ROM or paused load executed instructions");
|
||||
if(m.basicReadSource()!="10 PRINT 6*7\n20 END\n") throw std::runtime_error("BASIC source readback differs");
|
||||
m.basicLoadSource("10 PRINT 6*7\n20 END\n",true);frames(m,180);
|
||||
if(screen().find(" 42 ")==std::string::npos || m.pasteRemaining() || m.snapshot().generation!=before.generation)
|
||||
throw std::runtime_error("Direct BASIC Run did not execute without reset or paste");
|
||||
const auto exportBefore=m.snapshot();
|
||||
std::string exportSource="10 REM EXPORTED SOURCE\n20 PRINT 6*7\n30 END\n";
|
||||
for(unsigned line=40;line<240;line+=10)exportSource+=std::to_string(line)+" REM "+std::string(180,'X')+"\n";
|
||||
const auto exportedDisk=m.basicExportSource(exportSource,"HELLO",VCC::Mac::BasicExportFormat::Disk);
|
||||
const auto exportedTape=m.basicExportSource(exportSource,"HELLO",VCC::Mac::BasicExportFormat::Cassette);
|
||||
if(m.snapshot().cycles!=exportBefore.cycles || m.snapshot().cpu.PC!=exportBefore.cpu.PC || program()!=oracle)
|
||||
throw std::runtime_error("BASIC export changed running machine state");
|
||||
floppy->mount(0,VCC::Devices::DiskImage::load(exportedDisk));
|
||||
type(m,"NEW\rCLS\rLOAD\"HELLO\"\r");frames(m,1200);
|
||||
if(m.basicReadSource()!=exportSource) throw std::runtime_error("Exported DSK did not LOAD identical BASIC source: "+screen());
|
||||
type(m,"RUN\r");frames(m,60);
|
||||
if(screen().find(" 42 ")==std::string::npos)throw std::runtime_error("Exported DSK program did not execute");
|
||||
type(m,"NEW\rCLS\r");m.cassette().mount(exportedTape,VCC::Mac::TapeFormat::CAS);m.cassette().setFast(false);m.cassette().play();
|
||||
type(m,"CLOAD\"HELLO\"\r");frames(m,3600);
|
||||
if(m.basicReadSource()!=exportSource)throw std::runtime_error("Exported CAS did not CLOAD identical BASIC source: "+screen());
|
||||
type(m,"RUN\r");frames(m,60);
|
||||
if(screen().find(" 42 ")==std::string::npos)throw std::runtime_error("Exported CAS program did not execute");
|
||||
const auto stable=m.basicReadSource();
|
||||
bool rejected=false;
|
||||
try {m.basicLoadSource("10 PRINT1\n10 PRINT2",true);}catch(const std::exception&){rejected=true;}
|
||||
if(!rejected || m.basicReadSource()!=stable) throw std::runtime_error("Rejected BASIC source changed RAM");
|
||||
m.basicLoadSource("10 GOTO10",true);frames(m,10);
|
||||
rejected=false;try{m.basicLoadSource("10 END",true);}catch(const std::exception&){rejected=true;}
|
||||
if(!rejected || m.basicReadSource()!="10 GOTO10\n") throw std::runtime_error("Running BASIC program was replaced");
|
||||
std::printf("PASS: BASIC token oracle, paused Load/Read/Run, disk LOAD/cassette CLOAD multi-block exports, output, and atomic rejection (%s)\n",cpu==VCC::Mac::Processor::MC6809?"6809":"6309");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckGraphicsPreviewRom(const char* systemPath, const char* diskPath, const char* programPath) {
|
||||
using namespace VCC::Mac;
|
||||
using Mode = DebugGraphicsMode;
|
||||
auto read = [](const char* path) {
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
if (!input) throw std::runtime_error(std::string("Unable to open ") + path);
|
||||
return std::vector<std::uint8_t>((std::istreambuf_iterator<char>(input)), {});
|
||||
};
|
||||
const auto system = read(systemPath), disk = read(diskPath), sourceBytes = read(programPath);
|
||||
const std::string program(sourceBytes.begin(), sourceBytes.end());
|
||||
auto expect = [](bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
};
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
auto floppy = std::make_shared<VCC::Devices::Fd502Device>(disk);
|
||||
machine.cartridges().configure({nullptr, nullptr, nullptr, nullptr, floppy}, true, 4);
|
||||
machine.load(system, cpu);
|
||||
machine.resume();
|
||||
frames(machine, 300);
|
||||
machine.basicLoadSource(program, true, {40, 50, 60});
|
||||
auto stop = [&](int line) {
|
||||
for (unsigned i = 0; i < 300 && machine.snapshot().state == RunState::Running; ++i)
|
||||
machine.advance();
|
||||
const auto stopped = machine.snapshot();
|
||||
if (stopped.basicStoppedLine != line || stopped.state != RunState::Paused || !stopped.frame)
|
||||
throw std::runtime_error("Two-page program did not stop before line " + std::to_string(line));
|
||||
return stopped;
|
||||
};
|
||||
auto current = [&] { return machine.debuggerGraphicsPreview(true, false, 0, Mode::SG4); };
|
||||
// These are Disk BASIC's legacy pages 1 and 3 in the default memory map.
|
||||
// A PMODE 1 bitmap occupies two consecutive 1,536-byte pages.
|
||||
constexpr unsigned first = 0x0e00, second = 0x1a00;
|
||||
auto mapped = [&](unsigned address) { return machine.debuggerGraphicsPreview(false, false, address, Mode::PMODE1); };
|
||||
auto compareToFrame = [&](const DebugGraphicsPreview& preview, const Snapshot& stopped) {
|
||||
expect(preview.width == 128 && preview.height == 96 && preview.bytesPerRow == 32 &&
|
||||
preview.pixels.size() == 128*96 && preview.modeName == "PMODE 1", "Wrong active PMODE 1 layout");
|
||||
const auto& frame = *stopped.frame;
|
||||
const auto r = frame.activeArea;
|
||||
expect(r.width == 512 && r.height == 384, "Unexpected live PMODE raster geometry");
|
||||
for (unsigned y = 0; y < 96; ++y)
|
||||
for (unsigned x = 0; x < 128; ++x)
|
||||
expect(frame.pixels[(r.y+y*4)*Frame::width + r.x+x*4] == preview.pixels[y*128+x],
|
||||
"Current-page colors differ from the actual published video frame");
|
||||
};
|
||||
|
||||
const auto beforeDraw = stop(40);
|
||||
const auto front = current(), hiddenBlank = mapped(second);
|
||||
compareToFrame(front, beforeDraw);
|
||||
expect(front.physical && front.pixels == mapped(first).pixels && front.bytes == mapped(first).bytes,
|
||||
"Mapped page 1 does not match displayed RAM");
|
||||
expect(front.pixels[10*128+10] != front.pixels[0], "First page is missing its square");
|
||||
expect(std::all_of(hiddenBlank.bytes.begin(), hiddenBlank.bytes.end(), [](auto b) { return b == 0xff; }),
|
||||
"The selected drawing page should still be clear");
|
||||
|
||||
machine.basicContinue(program);
|
||||
const auto beforeFlip = stop(50);
|
||||
const auto stillFront = current(), hiddenDrawing = mapped(second);
|
||||
compareToFrame(stillFront, beforeFlip);
|
||||
expect(front.pixels == stillFront.pixels && front.address == stillFront.address &&
|
||||
beforeDraw.frame->pixels == beforeFlip.frame->pixels, "Drawing to hidden page affected the displayed screen");
|
||||
for (unsigned y = 0; y < 96; ++y) {
|
||||
for (unsigned x = 0; x < 128; ++x) {
|
||||
const bool changed = hiddenDrawing.pixels[y*128+x] != hiddenBlank.pixels[y*128+x];
|
||||
expect(changed == (x >= 80 && x < 112 && y >= 32 && y < 64),
|
||||
"The hidden square must occupy exactly its BASIC coordinates");
|
||||
}
|
||||
}
|
||||
const auto selected = hiddenDrawing.pixelInfo(81, 32);
|
||||
expect(hiddenDrawing.byteAddresses[selected.byteIndex] == 0x1e14 &&
|
||||
hiddenDrawing.bytes[selected.byteIndex] == 0xaa && selected.mask == 0x30,
|
||||
"Wrong mapped byte or bits for a pixel in the hidden drawing");
|
||||
expect(machine.snapshot().cycles == beforeFlip.cycles && machine.snapshot().cpu.PC == beforeFlip.cpu.PC,
|
||||
"Preview moved the stopped CPU");
|
||||
|
||||
machine.basicContinue(program);
|
||||
const auto afterFlip = stop(60);
|
||||
const auto displayed = current();
|
||||
compareToFrame(displayed, afterFlip);
|
||||
expect(displayed.address == front.address + second - first &&
|
||||
displayed.bytes == hiddenDrawing.bytes && displayed.pixels == hiddenDrawing.pixels &&
|
||||
mapped(first).pixels == front.pixels, "SCREEN did not reveal the untouched second page");
|
||||
std::printf("PASS: PMODE 1 two-page preview, 1,024 hidden changed pixels, $1E14 bits 5–4, "
|
||||
"and SCREEN page flip (%s)\n", cpu == Processor::MC6809 ? "6809" : "6309");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/MachineHost.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/core/Event.h"
|
||||
#include "../../src/core/KeyboardMatrix.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
#include "../../src/core/tcc1014registers.h"
|
||||
using namespace VCC::Mac;
|
||||
namespace {
|
||||
void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); }
|
||||
template<class F> void rejects(F operation, const char* message) {
|
||||
bool threw = false;
|
||||
try { operation(); } catch (const std::exception&) { threw = true; }
|
||||
require(threw, message);
|
||||
}
|
||||
}
|
||||
void CheckSessionLifecycle() {
|
||||
for (auto processor : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
require(machine.snapshot().state == RunState::Empty, "Session starts empty");
|
||||
machine.pause(); machine.advance(); machine.shutdown();
|
||||
rejects([&] { machine.resume(); }, "Empty session cannot run");
|
||||
rejects([&] { machine.reset(); }, "Empty session cannot reset");
|
||||
machine.loadDiagnostic(processor);
|
||||
auto initial = machine.snapshot();
|
||||
require(initial.state == RunState::Paused && initial.cpu.PC == 0x8000 && !initial.frame,
|
||||
"Load owns a paused machine at its ROM reset vector");
|
||||
machine.advance();
|
||||
require(machine.snapshot().cycles == 0, "Paused machine performs no execution");
|
||||
machine.resume(); machine.advance(); machine.pause();
|
||||
auto paused = machine.snapshot();
|
||||
require(paused.frames == 1 && paused.cycles > 0 && paused.frame, "One running frame is published");
|
||||
require(paused.cpu.PC == 0x8000 || paused.cpu.PC == 0x8003, "Authored ROM guest executes both CPU engines");
|
||||
machine.advance();
|
||||
require(machine.snapshot().cycles == paused.cycles, "Pause freezes machine clock");
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().frames == 2, "Resume continues the existing machine");
|
||||
machine.shutdown(); machine.shutdown();
|
||||
require(machine.snapshot().state == RunState::Empty && !Get_mem_pointer() && VCC::gEvents.GetSize() == 0,
|
||||
"Shutdown releases RAM and scheduled work");
|
||||
machine.loadDiagnostic(processor); machine.resume(); machine.advance();
|
||||
require(machine.snapshot().frames == 1, "Reload after shutdown starts cleanly");
|
||||
}
|
||||
}
|
||||
void CheckSessionReset() {
|
||||
MachineSession machine;
|
||||
machine.loadDiagnostic(); machine.resume(); machine.advance();
|
||||
const auto first = machine.snapshot();
|
||||
machine.reset();
|
||||
auto reset = machine.snapshot();
|
||||
require(reset.state == RunState::Running && reset.frames == 0 && reset.cycles == 0 && !reset.frame &&
|
||||
reset.generation > first.generation && reset.cpu.PC == 0x8000, "Cold reset invalidates frames and preserves running intent");
|
||||
machine.advance();
|
||||
require(machine.snapshot().frame->pixels == first.frame->pixels && machine.snapshot().cycles == first.cycles,
|
||||
"Cold reset reproduces the initial guest frame and cycles");
|
||||
machine.pause(); machine.reset();
|
||||
require(machine.snapshot().state == RunState::Paused, "Paused reset remains paused");
|
||||
}
|
||||
void CheckSessionFrameOwnership() {
|
||||
MachineSession machine;
|
||||
machine.loadDiagnostic(); machine.resume(); machine.advance();
|
||||
const auto saved = machine.snapshot().frame;
|
||||
const auto pixels = saved->pixels;
|
||||
require(saved->activeArea.x==0 && saved->activeArea.y==50 && saved->activeArea.width==640 && saved->activeArea.height==384,
|
||||
"Published diagnostic frame includes its active raster bounds");
|
||||
require(pixels.size() == 640 * 480 && pixels[50 * 640] == 0xff0000 && pixels[50 * 640 + 80] == 0x00ff00,
|
||||
"Published frame owns expected packed RGB pixels");
|
||||
machine.advance();
|
||||
require(machine.snapshot().frame != saved && saved->number == 1, "Publication creates a separate immutable frame");
|
||||
machine.reset(); machine.shutdown();
|
||||
require(saved->pixels == pixels && saved->activeArea.width==640 && saved->activeArea.height==384,
|
||||
"UI-retained pixels and bounds outlive reset and shutdown");
|
||||
}
|
||||
void CheckSessionExclusion() {
|
||||
MachineSession second;
|
||||
{
|
||||
MachineSession first; first.loadDiagnostic(); first.resume();
|
||||
rejects([&] { second.loadDiagnostic(); }, "Second machine cannot replace active global hosts");
|
||||
first.advance();
|
||||
require(first.snapshot().frames == 1 && second.snapshot().state == RunState::Empty,
|
||||
"Rejected ownership leaves first machine intact");
|
||||
}
|
||||
require(!Get_mem_pointer() && VCC::gEvents.GetSize() == 0, "Destructor tears down active machine");
|
||||
second.loadDiagnostic(); second.resume(); second.advance();
|
||||
require(second.snapshot().frames == 1, "Ownership is released on destruction");
|
||||
}
|
||||
void CheckSessionRomValidation() {
|
||||
MachineSession machine;
|
||||
machine.loadDiagnostic(); machine.resume(); machine.advance();
|
||||
const auto before = machine.snapshot();
|
||||
rejects([&] { machine.load({}); }, "Empty ROM is rejected");
|
||||
rejects([&] { machine.load(std::vector<std::uint8_t>(0x8001)); }, "Oversized ROM is rejected");
|
||||
require(machine.snapshot().frame == before.frame && machine.snapshot().state == RunState::Running,
|
||||
"Invalid input preserves loaded machine");
|
||||
std::vector<std::uint8_t> rom(0x8000, 0x12);
|
||||
rom[0] = 0x20; rom[1] = 0xfe; rom[0x7ffe] = 0x80; rom[0x7fff] = 0;
|
||||
machine.load(rom); rom[0] = 0; // The session must own the submitted bytes.
|
||||
machine.resume(); machine.advance();
|
||||
require(machine.snapshot().cpu.PC == 0x8000 && machine.snapshot().frames == 1,
|
||||
"Session copies caller-owned ROM bytes before execution");
|
||||
}
|
||||
|
||||
void CheckSessionKeyboard() {
|
||||
using VCC::Mac::ScanKeyboard;
|
||||
for (unsigned row = 0; row < 7; ++row)
|
||||
for (unsigned column = 0; column < 8; ++column) {
|
||||
const auto key = std::uint64_t{1} << (row * 8 + column);
|
||||
require(ScanKeyboard(key, ~(1 << column)) == (0x7f & ~(1 << row)), "Every key scans its own row/column");
|
||||
require(ScanKeyboard(key, 0xff) == 0x7f, "Deselected columns do not report keys");
|
||||
}
|
||||
MachineSession machine; machine.loadDiagnostic(); machine.resume();
|
||||
// Real PIA data-direction/control registers, then select CoCo column 1.
|
||||
MemWrite8(0xff, 0xff02); MemWrite8(4, 0xff03); MemWrite8(4, 0xff01); MemWrite8(0xfd, 0xff02);
|
||||
machine.setKeyboard(std::uint64_t{1} << 1); // A
|
||||
require((MemRead8(0xff00) & 0x7f) == 0x7e, "Native key reaches actual PIA scan");
|
||||
machine.pause();
|
||||
require((MemRead8(0xff00) & 0x7f) == 0x7f, "Pause releases keys");
|
||||
machine.setKeyboard(std::uint64_t{1} << 1); machine.resume();
|
||||
require((MemRead8(0xff00) & 0x7f) == 0x7f, "Paused input cannot become stuck on resume");
|
||||
machine.setKeyboard(std::uint64_t{1} << 1); machine.setKeyboard(0);
|
||||
require((MemRead8(0xff00) & 0x7f) == 0x7f, "Focus loss releases keys through the same input boundary");
|
||||
}
|
||||
|
||||
void CheckSessionSoftReset() {
|
||||
MachineSession empty;
|
||||
rejects([&] { empty.softReset(); }, "Empty session cannot soft reset");
|
||||
for (auto processor : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine; machine.loadDiagnostic(processor); machine.resume(); machine.advance();
|
||||
auto* ram = Get_mem_pointer();
|
||||
for (unsigned bank = 0; bank < 64; ++bank) ram[bank * 8192 + 1234] = bank ^ 0x5a;
|
||||
const std::vector<unsigned char> savedRAM(ram, ram + 0x80000);
|
||||
const auto saved = machine.snapshot();
|
||||
const auto savedPixels = saved.frame->pixels;
|
||||
machine.setKeyboard(std::uint64_t{1} << 1);
|
||||
GimeWrite(0x95, 1); GimeWrite(0x91, 0x20); // leave fast-timer callbacks pending
|
||||
Set_MmuEnabled(1); SetMmuRegister(0, 3);
|
||||
machine.softReset();
|
||||
const auto reset = machine.snapshot();
|
||||
require(Get_mem_pointer() == ram && std::equal(savedRAM.begin(), savedRAM.end(), ram),
|
||||
"Soft reset retains the complete RAM allocation byte-for-byte before guest execution");
|
||||
require(reset.state == RunState::Running && reset.cpu.PC == 0x8000 && (reset.cpu.CC & 0x50) == 0x50,
|
||||
"Soft reset restarts the selected CPU at its ROM vector with interrupts masked");
|
||||
require(reset.generation > saved.generation && reset.frames == 0 && reset.cycles == 0 && !reset.frame,
|
||||
"Soft reset invalidates published frames and restarts counters");
|
||||
require(!GetMMUState().Enabled && GetMMUState().Task0[0] == 56, "Soft reset restores default mapping");
|
||||
require(VCC::gEvents.GetSize() == 5, "Soft reset replaces raster/timer callbacks");
|
||||
require(saved.frame->pixels == savedPixels, "Retained display frame survives soft reset unchanged");
|
||||
MemWrite8(0xff, 0xff02); MemWrite8(4, 0xff03); MemWrite8(4, 0xff01); MemWrite8(0xfd, 0xff02);
|
||||
require((MemRead8(0xff00) & 0x7f) == 0x7f, "Soft reset releases keyboard state");
|
||||
machine.advance(); require(machine.snapshot().frames == 1, "Execution resumes after soft reset");
|
||||
machine.pause(); machine.softReset(); machine.advance();
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().cycles == 0,
|
||||
"Soft reset while paused does not execute guest code");
|
||||
machine.softReset();
|
||||
require(VCC::gEvents.GetSize() == 5, "Repeated soft resets do not duplicate scheduled work");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckSessionVideoOutput() {
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
machine.setVideoOutput(VideoOutput::Composite); // chosen before loading
|
||||
std::vector<std::uint8_t> rom(32768, 0x12);
|
||||
rom[0] = 0x20; rom[1] = 0xfe; rom[32766] = 0x80; rom[32767] = 0;
|
||||
machine.load(rom, cpu); machine.resume();
|
||||
auto pattern = [&] {
|
||||
std::fill_n(Get_mem_pointer(), 6144, 0x55);
|
||||
VCC::Machine().VideoWrite(VCC::VideoRegister::Compatibility, 1);
|
||||
VCC::Machine().VideoWrite(VCC::VideoRegister::Mode, 0);
|
||||
VCC::Machine().VideoWrite(VCC::VideoRegister::VdgMode, 7);
|
||||
VCC::Machine().VideoWrite(VCC::VideoRegister::VdgMode2, 31);
|
||||
};
|
||||
auto render = [&] { machine.advance(); machine.takeAudio(); machine.advance(); machine.takeAudio(); return machine.snapshot().frame; };
|
||||
auto colored = [](const auto& frame) {
|
||||
return std::any_of(frame->pixels.begin(), frame->pixels.end(), [](auto p) {
|
||||
return ((p >> 16) & 255) != ((p >> 8) & 255) || ((p >> 8) & 255) != (p & 255);
|
||||
});
|
||||
};
|
||||
pattern(); const auto composite = render();
|
||||
require(colored(composite), "Alternating PMODE 4 pixels produce NTSC artifact colors");
|
||||
machine.pause(); const auto before = machine.snapshot();
|
||||
machine.setVideoOutput(VideoOutput::RGB);
|
||||
const auto switched = machine.snapshot();
|
||||
require(switched.cycles == before.cycles && switched.frames == before.frames && switched.generation == before.generation &&
|
||||
switched.cpu.PC == before.cpu.PC && switched.state == RunState::Paused, "Changing display does not execute or reset the guest");
|
||||
machine.resume(); require(!colored(render()), "RGB keeps the same PMODE 4 pattern monochrome");
|
||||
machine.setVideoOutput(VideoOutput::CompositeAlternate); const auto alternate = render();
|
||||
require(colored(alternate) && alternate->pixels != composite->pixels, "Alternate phase changes artifact colors");
|
||||
VCC::Machine().VideoWrite(VCC::VideoRegister::Mode, 0x10);
|
||||
require(!colored(render()), "The guest monochrome bit still suppresses composite artifacts");
|
||||
VCC::Machine().VideoWrite(VCC::VideoRegister::Mode, 0x20);
|
||||
require(render()->pixels == alternate->pixels, "Guest phase writes do not undo an explicit phase selection");
|
||||
machine.setVideoOutput(VideoOutput::Composite); require(render()->pixels == composite->pixels, "Switching back reproduces the selected colors");
|
||||
machine.setVideoOutput(VideoOutput::CompositeAlternate);
|
||||
machine.softReset(); pattern(); require(render()->pixels == alternate->pixels, "Soft reset retains the color phase");
|
||||
machine.reset(); pattern(); require(render()->pixels == alternate->pixels, "Cold reset retains the color phase");
|
||||
machine.load(rom, cpu); machine.resume(); pattern(); require(render()->pixels == alternate->pixels, "ROM replacement retains display preferences");
|
||||
rejects([&] { machine.setVideoOutput(static_cast<VideoOutput>(99)); }, "Invalid display mode is rejected");
|
||||
require(machine.snapshot().videoOutput == VideoOutput::CompositeAlternate, "Invalid choice preserves current output");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckMachineMemorySettings() {
|
||||
const unsigned pages[] = {16, 64, 256, 1024};
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
for (unsigned ram = 0; ram < 4; ++ram) {
|
||||
MachineConfiguration config; config.processor = cpu; config.ram = ram;
|
||||
machine.configure(config); machine.loadDiagnostic(cpu);
|
||||
require(GetRamConfiguration() == ram, "Selected RAM reaches the retained MMU");
|
||||
// Exercise the first and last physical bank through the guest MMU,
|
||||
// including the extra prefix bits of the 8 MiB expansion.
|
||||
MmuSetMapType(1); Set_MmuEnabled(1); SetDistoRamBank(0); SetMmuRegister(0, 0);
|
||||
MemWrite8(0x39, 0x0100);
|
||||
SetDistoRamBank(ram == 3 ? 0x30 : 0);
|
||||
SetMmuRegister(0, static_cast<unsigned char>(pages[ram] - 1));
|
||||
MemWrite8(0xa6, 0x0100);
|
||||
require(Get_mem_pointer()[(pages[ram]-1)*8192+256] == 0xa6,
|
||||
"Highest supported bank is independently writable");
|
||||
SetDistoRamBank(0); SetMmuRegister(0, 0);
|
||||
require(MemRead8(0x0100) == 0x39, "Expanded bank writes must not alias the first bank");
|
||||
machine.softReset();
|
||||
require(Get_mem_pointer()[256] == 0x39 && machine.snapshot().configuration.ram == ram,
|
||||
"Soft reset preserves memory and configuration");
|
||||
machine.resume(); machine.advance(); machine.takeAudio();
|
||||
require(machine.snapshot().frames == 1, "Both CPUs render with every memory size");
|
||||
machine.reset();
|
||||
require(Get_mem_pointer()[256] != 0x39 && machine.snapshot().state == RunState::Running,
|
||||
"Cold reset clears RAM and preserves running state");
|
||||
}
|
||||
auto before = machine.snapshot();
|
||||
auto config = before.configuration;
|
||||
config.processor = cpu == Processor::MC6809 ? Processor::HD6309 : Processor::MC6809;
|
||||
machine.configure(config);
|
||||
require(machine.snapshot().generation == before.generation + 1 && machine.snapshot().cpu.PC == 0x8000,
|
||||
"CPU change restarts the selected engine at the reset vector");
|
||||
machine.pause(); before = machine.snapshot(); config.ram = 0; machine.configure(config);
|
||||
require(machine.snapshot().state == RunState::Paused && machine.snapshot().generation > before.generation,
|
||||
"RAM change preserves pause state");
|
||||
}
|
||||
}
|
||||
void CheckMachinePresentationSettings() {
|
||||
MachineSession machine; machine.loadDiagnostic(); machine.resume(); machine.advance();
|
||||
auto before = machine.snapshot(); const auto retained = before.frame; const auto pixels = retained->pixels;
|
||||
auto config = before.configuration; config.frameInterval = 6; config.overclock = 2;
|
||||
machine.configure(config);
|
||||
require(machine.snapshot().generation == before.generation && machine.snapshot().cycles == before.cycles,
|
||||
"Timing-only configuration does not reset or execute the CPU");
|
||||
unsigned samples = 0;
|
||||
// Change to a narrower mode while the UI still owns the preceding image.
|
||||
MemWrite8(0, 0xff99);
|
||||
for (unsigned frame = 2; frame <= 6; ++frame) {
|
||||
machine.advance(); samples += machine.takeAudio().size();
|
||||
require(machine.snapshot().frames == frame && machine.snapshot().frame == retained,
|
||||
"Skipped presentation retains a stable frame while guest frames advance");
|
||||
require(machine.snapshot().frame->activeArea.width == 640,
|
||||
"Skipped presentation retains bounds belonging to its pixels");
|
||||
}
|
||||
require(samples > 3600, "Every skipped display frame still produces audio");
|
||||
machine.advance(); machine.takeAudio();
|
||||
require(machine.snapshot().frame->number == 7 && retained->pixels == pixels,
|
||||
"Next presentation is published without mutating an earlier frame");
|
||||
require(machine.snapshot().frame->activeArea.x == 64 && machine.snapshot().frame->activeArea.width == 512,
|
||||
"New presentation uses only its own bounds, excluding skipped wider frames");
|
||||
before = machine.snapshot();
|
||||
for (unsigned bad : {0u, 7u, 999u}) {
|
||||
auto invalid = config; invalid.frameInterval = bad;
|
||||
rejects([&] { machine.configure(invalid); }, "Reject unsupported presentation intervals");
|
||||
}
|
||||
auto invalid = config; invalid.ram = 4;
|
||||
rejects([&] { machine.configure(invalid); }, "Reject unsupported RAM before resetting");
|
||||
invalid = config; invalid.processor = static_cast<Processor>(99);
|
||||
rejects([&] { machine.configure(invalid); }, "Reject unsupported CPU before resetting");
|
||||
for (unsigned bad : {0u, 17u, 999u}) {
|
||||
invalid = config; invalid.overclock = bad;
|
||||
rejects([&] { machine.configure(invalid); }, "Reject unsupported overclock before resetting");
|
||||
}
|
||||
require(machine.snapshot().generation == before.generation && machine.snapshot().frame == before.frame,
|
||||
"Rejected settings leave the machine intact");
|
||||
machine.pause(); machine.reset();
|
||||
require(machine.snapshot().configuration.frameInterval == 6 && machine.snapshot().configuration.overclock == 2,
|
||||
"Cold reset retains live timing settings");
|
||||
}
|
||||
|
||||
void CheckSessionAutomaticBoot() {
|
||||
MachineSession machine;
|
||||
rejects([&] { machine.requestNitros9Boot(); }, "Cannot boot an empty machine");
|
||||
machine.loadDiagnostic();machine.requestNitros9Boot();
|
||||
for(unsigned i=0;i<610;++i)machine.advance();
|
||||
require(machine.nitros9BootPending(), "Paused frames never consume boot deadline");
|
||||
machine.resume();machine.setKeyboard(0);
|
||||
require(machine.nitros9BootPending(), "Focus release does not cancel boot");
|
||||
machine.setKeyboard(1);
|
||||
require(!machine.nitros9BootPending(), "Real input cancels boot");
|
||||
machine.requestNitros9Boot();machine.softReset();
|
||||
require(!machine.nitros9BootPending(), "Soft reset cancels boot");
|
||||
machine.requestNitros9Boot();machine.reset();
|
||||
require(!machine.nitros9BootPending(), "Cold reset cancels boot");
|
||||
machine.requestNitros9Boot();
|
||||
rejects([&] { for(unsigned i=0;i<600;++i)machine.advance(); }, "Missing RGBDOS has a bounded boot timeout");
|
||||
require(!machine.nitros9BootPending() && machine.snapshot().state==RunState::Paused,
|
||||
"Failed boot releases keys and pauses without an injection retry");
|
||||
machine.requestNitros9Boot();machine.shutdown();
|
||||
require(!machine.nitros9BootPending(), "Shutdown cancels boot");
|
||||
}
|
||||
|
||||
void CheckSessionClipboard() {
|
||||
MachineSession m;
|
||||
rejects([&]{ m.paste({2}); }, "Empty machine rejects paste");
|
||||
rejects([&]{ m.copyScreenText(); }, "Empty machine rejects copy");
|
||||
m.loadDiagnostic();
|
||||
rejects([&]{ m.paste({2}); }, "Paused machine rejects paste");
|
||||
rejects([&]{ m.copyScreenText(); }, "Graphics cannot masquerade as text");
|
||||
m.resume();
|
||||
rejects([&]{ m.paste({0}); }, "Invalid chord rejected before typing");
|
||||
rejects([&]{ m.paste(std::vector<std::uint64_t>(65537,2)); }, "Bounded queue");
|
||||
m.paste({2,2,std::uint64_t{1}<<48});
|
||||
rejects([&]{ m.paste({4}); }, "Never append an unrelated paste");
|
||||
for(unsigned i=0;i<7;++i) { m.setKeyboard(0); m.advance(); }
|
||||
require(m.pasteRemaining()==3, "Focus releases do not truncate held keys");
|
||||
m.advance();require(m.pasteRemaining()==2,"Character includes release gap");
|
||||
for(unsigned i=0;i<8;++i)m.advance();
|
||||
for(unsigned i=0;i<35;++i)m.advance();
|
||||
require(m.pasteRemaining()==1,"Return gives interpreter processing time");
|
||||
m.advance();require(!m.pasteRemaining(),"Queue ends and releases keys");
|
||||
m.paste({2,4});m.setKeyboard(8);require(!m.pasteRemaining(),"Real input cancels paste");
|
||||
m.paste({2});m.pause();require(!m.pasteRemaining(),"Pause cancels remaining input");
|
||||
m.resume();m.paste({2});m.softReset();require(!m.pasteRemaining(),"Soft reset cancels paste");
|
||||
m.paste({2});m.reset();require(!m.pasteRemaining(),"Cold reset cancels paste");
|
||||
m.requestNitros9Boot();rejects([&]{m.paste({2});},"Boot input has exclusive ownership");
|
||||
m.setKeyboard(2);m.paste({2});m.cancelPaste();require(!m.pasteRemaining(),"Explicit cancellation");
|
||||
// A relocated, attributed, 80-column hardware text screen, independent of CPU mapping.
|
||||
MemWrite8(0,0xff90); MemWrite8(3,0xff98); MemWrite8(0x15,0xff99);
|
||||
MemWrite8(2,0xff9d); MemWrite8(0,0xff9e);
|
||||
auto* ram=Get_mem_pointer();std::fill(ram+0x1000,ram+0x2000,32);
|
||||
ram[0x1000]='A';ram[0x1001]=0xff;ram[0x1002]='B';
|
||||
m.advance();auto text=m.copyScreenText();
|
||||
require(text.rfind("AB",0)==0,"Copy uses physical video address and skips attributes");
|
||||
m.paste({2});m.shutdown();require(!m.pasteRemaining(),"Shutdown clears pending paste");
|
||||
}
|
||||
|
||||
void CheckGraphicsPreviewModes() {
|
||||
using Mode = DebugGraphicsMode;
|
||||
MachineSession machine;
|
||||
machine.loadDiagnostic();
|
||||
constexpr std::uint32_t base = 0x1000;
|
||||
// An authored ROM has no boot-time palette setup. Give its color indices
|
||||
// distinct values and ensure a capture picks up the pending register writes.
|
||||
for (unsigned i = 0; i < 16; ++i) GimeWrite(0xb0 + i, i * 4);
|
||||
// The same eight bits decode differently as one-, two- and four-bit pixels.
|
||||
machine.debuggerWriteMemory(base, {0x99, 0x00});
|
||||
struct Case { Mode mode; unsigned width, height, bits; };
|
||||
for (const Case test : {Case{Mode::PMODE0, 128, 96, 1}, {Mode::PMODE1, 128, 96, 2},
|
||||
{Mode::PMODE2, 128, 192, 1}, {Mode::PMODE3, 128, 192, 2}, {Mode::PMODE4, 256, 192, 1},
|
||||
{Mode::HSCREEN1, 320, 192, 2}, {Mode::HSCREEN2, 320, 192, 4},
|
||||
{Mode::HSCREEN3, 640, 192, 1}, {Mode::HSCREEN4, 640, 192, 2}}) {
|
||||
const auto page = machine.debuggerGraphicsPreview(false, false, base, test.mode);
|
||||
const unsigned perByte = 8 / test.bits, rowBytes = test.width / perByte;
|
||||
require(page.width == test.width && page.height == test.height &&
|
||||
page.pixels.size() == test.width * test.height, "Graphics preview dimensions");
|
||||
require(page.bytesPerRow == rowBytes && page.bytes.size() == rowBytes * test.height &&
|
||||
page.byteAddresses.size() == page.bytes.size(), "Graphics preview row pitch");
|
||||
const auto mask = (1u << test.bits) - 1;
|
||||
for (unsigned x = 0; x < perByte; ++x) {
|
||||
const auto pixel = page.pixelInfo(x, 0);
|
||||
require(pixel.byteIndex == 0 && page.bytes[pixel.byteIndex] == 0x99 &&
|
||||
pixel.mask == (mask << (8 - test.bits*(x+1))), "Graphics preview bit significance");
|
||||
}
|
||||
const auto corner = page.pixelInfo(test.width-1, test.height-1);
|
||||
require(page.byteAddresses[corner.byteIndex] == base + rowBytes*test.height - 1 &&
|
||||
corner.mask == mask, "Graphics preview bottom right address and mask");
|
||||
require(page.pixels[0] != page.pixels[perByte], "A set color index must change the rendered pixel");
|
||||
rejects([&] { page.pixelInfo(test.width, 0); }, "Out-of-range preview pixel accepted");
|
||||
}
|
||||
|
||||
// Semigraphics bytes share text RAM; see all four quadrants and the lower-right
|
||||
// corner of a character. Glyph pixels identify the whole character byte.
|
||||
machine.debuggerWriteMemory(base, {0x99, 0x41});
|
||||
const auto sg = machine.debuggerGraphicsPreview(false, false, base, Mode::SG4);
|
||||
require(sg.width == 256 && sg.height == 192 && sg.bytes.size() == 512 && sg.semigraphics,
|
||||
"SG4 mixes 32 by 16 character and graphics cells");
|
||||
require(sg.pixelInfo(1, 1).mask == 8 && sg.pixelInfo(5, 1).mask == 4 &&
|
||||
sg.pixelInfo(1, 7).mask == 2 && sg.pixelInfo(5, 7).mask == 1 &&
|
||||
sg.pixelInfo(7, 11).byteIndex == 0, "SG4 bit order and repeated scanlines");
|
||||
require(sg.pixels[1] == sg.pixels[7*256+5] && sg.pixels[1] != sg.pixels[5],
|
||||
"SG4 diagonal blocks follow their geometry");
|
||||
const auto glyph = sg.pixelInfo(9, 5);
|
||||
require(glyph.byteIndex == 1 && glyph.mask == 0xff, "Text glyph identifies its character byte");
|
||||
}
|
||||
|
||||
void CheckGraphicsPreviewColorSets() {
|
||||
using Register = VCC::VideoRegister;
|
||||
using Mode = DebugGraphicsMode;
|
||||
MachineSession machine;
|
||||
machine.setVideoOutput(VideoOutput::RGB);
|
||||
machine.loadDiagnostic();
|
||||
auto& host = VCC::Machine();
|
||||
host.VideoWrite(Register::Compatibility, 1);
|
||||
host.VideoWrite(Register::Mode, 0);
|
||||
// With all pixels at color index zero, the two CSS banks select blue and red.
|
||||
std::fill_n(Get_mem_pointer(), 6144, 0);
|
||||
for (auto i : {0, 8}) GimeWrite(0xb0 + i, 9);
|
||||
for (auto i : {4, 10}) GimeWrite(0xb0 + i, 36);
|
||||
machine.resume();
|
||||
struct Layout { Mode mode; unsigned sam, pia; };
|
||||
for (const Layout layout : {Layout{Mode::PMODE0, 3, 22}, {Mode::PMODE1, 4, 24},
|
||||
{Mode::PMODE2, 5, 26}, {Mode::PMODE3, 6, 28}, {Mode::PMODE4, 6, 30}}) {
|
||||
host.VideoWrite(Register::VdgMode, layout.sam);
|
||||
for (const bool alternate : {false, true, false}) {
|
||||
// A SCREEN color-set switch toggles only the PIA's CSS bit.
|
||||
host.VideoWrite(Register::VdgMode2, layout.pia | unsigned(alternate));
|
||||
machine.advance();
|
||||
machine.advance();
|
||||
const auto frame = machine.snapshot().frame;
|
||||
const auto area = frame->activeArea;
|
||||
require(area.x > 0 && area.width == 512, "Expected a border beside the active PMODE scanline");
|
||||
const unsigned offset = (area.y + area.height / 2) * Frame::width + area.x;
|
||||
require(frame->pixels[offset - 1] == (alternate ? 0xffffffu : 0x00ff00u),
|
||||
"CSS-only switch must update the live RGB border");
|
||||
const auto current = machine.debuggerGraphicsPreview(true, true, 0, layout.mode);
|
||||
const auto address = machine.debuggerGraphicsPreview(false, true, current.address, layout.mode, alternate);
|
||||
const unsigned expected = alternate ? 0xff0000 : 0x0000ff;
|
||||
require(frame->pixels[offset] == expected && current.pixels.front() == expected &&
|
||||
current.pixels == address.pixels, "CSS bank must agree in live RGB, current page, and address preview");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
#pragma once
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/MachineHost.h"
|
||||
#include "../../src/core/CpuHost.h"
|
||||
#include "../../src/core/CpuMemory.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include "../../src/core/tcc1014registers.h"
|
||||
#include "../../src/core/mc6821.h"
|
||||
#include "../../src/core/mc6809.h"
|
||||
#include "../../src/core/hd6309.h"
|
||||
#include "../../src/core/Event.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
|
||||
namespace VCCTest {
|
||||
inline void require(bool ok, const char* message) {
|
||||
if (!ok) throw std::runtime_error(message);
|
||||
}
|
||||
// Explicit test replacements for components not extracted yet. The real MMU,
|
||||
// port decoder, GIME/SAM and PIA implementations are linked from VCCCore.
|
||||
struct Host : VCC::MachineHost {
|
||||
bool use6309 = false, romFailure = false, fastTape = false;
|
||||
unsigned char keyboard = 0x7e, columns = 0, tapeBit = 1, motor = 0;
|
||||
unsigned char turbo = 0, speed = 0, printerBit = 0, cartPort = 0, cartValue = 0;
|
||||
unsigned short cartAudio = 0;
|
||||
unsigned joystickStarts = 0, cartReads = 0, cartWrites = 0;
|
||||
std::array<unsigned char, IS_MAX> lines{};
|
||||
std::array<unsigned char, 0x8000> rom{};
|
||||
std::vector<std::tuple<VCC::VideoRegister, unsigned int, unsigned char>> video;
|
||||
std::vector<std::pair<VCC::TimerRegister, unsigned int>> timer;
|
||||
Host() {
|
||||
for (unsigned page = 0; page < 4; ++page)
|
||||
std::fill_n(rom.begin() + page * 8192, 8192, 0xa0 + page);
|
||||
rom[0x7ffe] = 0x40; rom[0x7fff] = 0x00;
|
||||
rom[0x7ff8] = 0x50; rom[0x7ff9] = 0x00;
|
||||
}
|
||||
bool LoadInternalRom(unsigned char* dest, std::size_t size) override {
|
||||
require(size == rom.size(), "ROM provider capacity");
|
||||
std::copy(rom.begin(), rom.end(), dest);
|
||||
return !romFailure;
|
||||
}
|
||||
unsigned char CartridgeRead(unsigned short address) override { return 0xc0 + address / 8192; }
|
||||
unsigned char CartridgePortRead(unsigned char port) override { ++cartReads; cartPort = port; return 0x5a; }
|
||||
void CartridgePortWrite(unsigned char port, unsigned char value) override { ++cartWrites; cartPort = port; cartValue = value; }
|
||||
unsigned short CartridgeAudio() override { return cartAudio; }
|
||||
void VideoWrite(VCC::VideoRegister reg, unsigned int value, unsigned char index) override { video.emplace_back(reg, value, index); }
|
||||
void TimerWrite(VCC::TimerRegister reg, unsigned int value) override { timer.emplace_back(reg, value); }
|
||||
void SetTurbo(unsigned char value) override { turbo = value; }
|
||||
void SetCpuSpeed(unsigned char value) override { speed = value; }
|
||||
VCC::CPUState CpuState() override { return use6309 ? HD6309GetState() : MC6809GetState(); }
|
||||
void AssertInterrupt(InterruptSource source, Interrupt interrupt) override {
|
||||
lines[source] |= Bit(interrupt);
|
||||
if (use6309) HD6309AssertInterupt(source, interrupt); else MC6809AssertInterupt(source, interrupt);
|
||||
}
|
||||
void ClearInterrupt(InterruptSource source, Interrupt interrupt) override {
|
||||
lines[source] &= BitMask(interrupt);
|
||||
if (use6309) HD6309DeAssertInterupt(source, interrupt); else MC6809DeAssertInterupt(source, interrupt);
|
||||
}
|
||||
unsigned char KeyboardScan(unsigned char value) override { columns = value; return keyboard; }
|
||||
void JoystickStart(bool, unsigned char) override { ++joystickStarts; }
|
||||
bool TapeFastLoad() override { return fastTape; }
|
||||
unsigned char TapeInputBit() override { return tapeBit; }
|
||||
void TapeMotor(unsigned char value) override { motor = value; }
|
||||
void PrinterBit(unsigned char value) override { printerBit = value; }
|
||||
};
|
||||
struct Debugger final : VCC::CpuDebugHooks {
|
||||
bool halted = false;
|
||||
bool IsHalted() const override { return halted; }
|
||||
void Halt() override { halted = true; }
|
||||
};
|
||||
struct MachineFixture {
|
||||
Host host;
|
||||
Debugger debugger;
|
||||
explicit MachineFixture(unsigned char config = 1, bool use6309 = false) {
|
||||
host.use6309 = use6309;
|
||||
VCC::SetCpuMemoryBus(nullptr);
|
||||
VCC::SetMachineHost(&host);
|
||||
VCC::SetCpuDebugHooks(&debugger);
|
||||
MC6809Init(); HD6309Init();
|
||||
if (!MmuInit(config)) {
|
||||
VCC::SetMachineHost(nullptr); VCC::SetCpuDebugHooks(nullptr);
|
||||
throw std::runtime_error("Initialize synthetic machine ROM/RAM");
|
||||
}
|
||||
mc6883_reset(); GimeRegistersReset(); PiaReset();
|
||||
MC6809Reset(); HD6309Reset();
|
||||
MC6809SetBreakpoints({}); HD6309SetBreakpoints({});
|
||||
MC6809SetTraceTriggers({}); HD6309SetTraceTriggers({});
|
||||
VCC::gEvents.Reset();
|
||||
}
|
||||
~MachineFixture() {
|
||||
MC6809SetBreakpoints({}); HD6309SetBreakpoints({});
|
||||
MmuShutdown();
|
||||
VCC::SetCpuDebugHooks(nullptr); VCC::SetMachineHost(nullptr);
|
||||
VCC::gEvents.Reset();
|
||||
}
|
||||
void write(unsigned short address, unsigned char value) { MemWrite8(value, address); }
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include "../../src/core/FramePacing.h"
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
using namespace VCC::Mac;
|
||||
namespace {
|
||||
void require(bool value, const char* message) { if (!value) throw std::runtime_error(message); }
|
||||
}
|
||||
void CheckFramePacing() {
|
||||
using namespace std::chrono;
|
||||
FramePacer pacer;
|
||||
const auto origin = FramePacer::Clock::time_point{};
|
||||
// Irregular host callbacks for thirty simulated minutes; no wall-clock wait.
|
||||
auto elapsed = nanoseconds::zero();
|
||||
std::uint64_t frames = 0;
|
||||
for (unsigned i = 0; elapsed < minutes(30); ++i) {
|
||||
if (pacer.ready(origin + elapsed)) ++frames;
|
||||
elapsed += microseconds(1000 + (i % 7) * 500);
|
||||
}
|
||||
const double expected = duration<double>(elapsed).count() * masterClockHz / clocksPerFrame;
|
||||
require(std::abs(double(frames) - expected) < 1.1, "Irregular host ticks must not accumulate frame drift");
|
||||
auto late = origin + hours(1);
|
||||
require(pacer.ready(late) && !pacer.ready(late), "Long stall must not replay a backlog of frames");
|
||||
require(!pacer.ready(late + frameInterval - nanoseconds(1)) && pacer.ready(late + frameInterval),
|
||||
"Late wake establishes a full new frame interval");
|
||||
pacer.reset();
|
||||
require(pacer.ready(late) && !pacer.ready(late), "Resume resets stale deadlines without double execution");
|
||||
// Short lateness is caught up, preserving average speed rather than dropping time.
|
||||
pacer.reset(); pacer.ready(origin);
|
||||
unsigned catchup = 0;
|
||||
while (pacer.ready(origin + frameInterval * 3)) ++catchup;
|
||||
require(catchup == 3, "Short host jitter retains scheduled guest frames");
|
||||
}
|
||||
void CheckAudioProgress() {
|
||||
using namespace std::chrono;
|
||||
AudioProgress progress;
|
||||
const auto start = AudioProgress::Clock::time_point{};
|
||||
require(!progress.stalled(start, 0) && !progress.stalled(start + milliseconds(999), 0), "Audio startup has a bounded grace period");
|
||||
require(progress.stalled(start + seconds(1), 0), "A live graph with no consumption must be detected");
|
||||
require(!progress.stalled(start + seconds(2), 1), "Sample consumption clears a stalled interval");
|
||||
require(!progress.stalled(start + milliseconds(2999), 1) && progress.stalled(start + seconds(3), 1), "Watchdog follows the last progress, not graph age");
|
||||
progress.reset();
|
||||
require(!progress.stalled(start + hours(1), 1), "Pause/device restart discards the previous watchdog deadline");
|
||||
|
||||
AudioProgress startup;
|
||||
require(!startup.stalled(start, 0), "Prefill may precede the first output graph");
|
||||
// A slow host may spend longer than the watchdog interval creating its
|
||||
// first graph. That setup time cannot count as a stalled render callback.
|
||||
const auto graphReady = start + seconds(2);
|
||||
startup.reset();
|
||||
require(!startup.stalled(graphReady, 0), "A newly started graph gets its own progress deadline");
|
||||
require(!startup.stalled(graphReady + milliseconds(999), 0), "Slow startup retains the normal consumption grace period");
|
||||
require(startup.stalled(graphReady + seconds(1), 0), "Startup reset must not disable or extend the live-graph watchdog");
|
||||
require(!startup.stalled(graphReady + milliseconds(1100), 4410), "Real output consumption clears the startup stall");
|
||||
}
|
||||
void CheckAcceleratedTiming() {
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
// Authored BRA-to-self ROM gives an independently known three-cycle loop.
|
||||
std::vector<std::uint8_t> rom(32768, 0x12);
|
||||
rom[0] = 0x20; rom[1] = 0xfe; rom[0x7ffe] = 0x80; rom[0x7fff] = 0;
|
||||
machine.load(rom, cpu); machine.resume();
|
||||
for (unsigned multiplier : {1u, 2u, 4u, 2u, 1u}) {
|
||||
MemWrite8(multiplier == 4 ? 1 : 0, 0xff96);
|
||||
MemWrite8(0, multiplier == 1 ? 0xffd8 : 0xffd9);
|
||||
machine.advance(); machine.takeAudio(); // settle a transition within a scanline
|
||||
const auto before = machine.snapshot();
|
||||
unsigned samples = 0;
|
||||
for (unsigned frame = 0; frame < 60; ++frame) { machine.advance(); samples += machine.takeAudio().size(); }
|
||||
const auto after = machine.snapshot();
|
||||
const auto cycles = after.cycles - before.cycles;
|
||||
require(after.frames - before.frames == 60 && after.cpu.PC == 0x8000, "Accelerated guest must execute complete frames");
|
||||
require(std::abs(double(cycles) - 60.0 * clocksPerFrame / 16 * multiplier) <= 3,
|
||||
"Mapped normal/double/turbo switches must change CPU throughput by 1/2/4");
|
||||
require(samples > 44300 && samples < 44400, "CPU acceleration must not accelerate audio or raster time");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CheckConfiguredOverclock() {
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession machine;
|
||||
std::vector<std::uint8_t> rom(32768, 0x12);
|
||||
rom[0] = 0x20; rom[1] = 0xfe; rom[0x7ffe] = 0x80; rom[0x7fff] = 0;
|
||||
machine.load(rom, cpu); machine.resume();
|
||||
for (unsigned factor : {1u, 3u, 16u, 1u}) {
|
||||
auto config = machine.snapshot().configuration; config.overclock = factor;
|
||||
machine.configure(config);
|
||||
for (unsigned speed : {1u, 2u, 4u}) {
|
||||
MemWrite8(speed == 4 ? 1 : 0, 0xff96);
|
||||
MemWrite8(0, speed == 1 ? 0xffd8 : 0xffd9);
|
||||
machine.advance(); machine.takeAudio();
|
||||
const auto before = machine.snapshot(); unsigned samples = 0;
|
||||
for (unsigned i = 0; i < 6; ++i) { machine.advance(); samples += machine.takeAudio().size(); }
|
||||
const auto after = machine.snapshot();
|
||||
// Retained Windows timing uses 1/256 master-clock resolution;
|
||||
// non-power-of-two multipliers quantize the clock divider.
|
||||
const unsigned divider = speed == 1 ? 4096 : 2048 / (factor * (speed / 2));
|
||||
const auto expected = 6.0 * clocksPerFrame * 256 / divider;
|
||||
require(std::abs(double(after.cycles - before.cycles) - expected) <= 3,
|
||||
"Configured overclock matches Windows guest-gated throughput including turbo");
|
||||
require(samples >= 4432 && samples <= 4434 && after.frames - before.frames == 6,
|
||||
"Overclock preserves complete video frames and 44.1 kHz guest audio");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "TestMachine.h"
|
||||
#include "../../src/core/VideoHost.h"
|
||||
#include "../../src/core/VideoRegisters.h"
|
||||
#include "../../src/core/FrameRunner.h"
|
||||
#include "../../src/core/tcc1014graphics.h"
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
using namespace VCCTest;
|
||||
|
||||
namespace {
|
||||
constexpr unsigned width = 640, height = 480, guard = 16;
|
||||
constexpr unsigned sentinel = 0xdeadbeef;
|
||||
struct GraphicsHost final : Host, VCC::VideoHost {
|
||||
GimeGpu* gpu = nullptr;
|
||||
VCC::VideoState surface;
|
||||
std::vector<unsigned int> pixels = std::vector<unsigned int>(width * height + 2 * guard, sentinel);
|
||||
bool ntsc = false;
|
||||
VCC::VideoRect active;
|
||||
void ActiveVideoArea(int x,int y,int w,int h) override { active.include(x,y,w,h,surface.WindowSize); }
|
||||
unsigned horizontalFalls = 0, horizontalRises = 0;
|
||||
std::vector<std::pair<int, size_t>> vertical;
|
||||
GraphicsHost() {
|
||||
surface.BitDepth = 3;
|
||||
surface.PTRsurface32 = pixels.data() + guard;
|
||||
surface.SurfacePitch = width;
|
||||
surface.WindowSize = {width, height};
|
||||
ClearSurface();
|
||||
}
|
||||
VCC::VideoState& Surface() override { return surface; }
|
||||
void ClearSurface() override { std::fill_n(surface.PTRsurface32, width * height, 0); }
|
||||
bool UseNtscArtifacts() const override { return ntsc; }
|
||||
void VideoWrite(VCC::VideoRegister reg, unsigned int value, unsigned char index) override {
|
||||
VCC::ApplyVideoRegister(*gpu, reg, value, index);
|
||||
}
|
||||
void TimerWrite(VCC::TimerRegister reg, unsigned int value) override {
|
||||
VCC::ApplyTimerRegister(*gpu, reg, value);
|
||||
}
|
||||
unsigned int pixel(unsigned x, unsigned y) const { return pixels[guard + y*width + x]; }
|
||||
void checkGuards() const {
|
||||
require(std::all_of(pixels.begin(), pixels.begin()+guard, [](auto v) { return v == sentinel; }) &&
|
||||
std::all_of(pixels.end()-guard, pixels.end(), [](auto v) { return v == sentinel; }),
|
||||
"Renderer stays inside 640x480 surface");
|
||||
}
|
||||
};
|
||||
struct GraphicsFixture {
|
||||
GraphicsHost host;
|
||||
Debugger debugger;
|
||||
GimeGpu gpu;
|
||||
explicit GraphicsFixture(bool scheduled = false, bool use6309 = false) :
|
||||
gpu(scheduled ? GimeGpu::SyncFunction([this](int level) {
|
||||
if (level) ++host.horizontalRises; else ++host.horizontalFalls;
|
||||
irq_hs(level);
|
||||
}) : GimeGpu::SyncFunction{},
|
||||
scheduled ? GimeGpu::SyncFunction([this](int level) {
|
||||
host.vertical.emplace_back(level, VCC::gEvents.GetClocks()); irq_fs(level);
|
||||
}) : GimeGpu::SyncFunction{}) {
|
||||
host.gpu = &gpu; host.use6309 = use6309;
|
||||
VCC::SetMachineHost(&host); VCC::SetVideoHost(&host);
|
||||
VCC::SetCpuDebugHooks(&debugger); VCC::SetCpuMemoryBus(nullptr);
|
||||
VCC::gEvents.Reset();
|
||||
MC6809Init(); HD6309Init();
|
||||
require(MmuInit(1) != nullptr, "Graphics fixture RAM/ROM allocation");
|
||||
host.surface.RamBuffer = Get_mem_pointer();
|
||||
host.surface.WRamBuffer = reinterpret_cast<unsigned short*>(Get_mem_pointer());
|
||||
std::fill_n(Get_mem_pointer(), 0x80000, 0);
|
||||
GimeRegistersReset(); PiaReset(); mc6883_reset();
|
||||
MC6809Reset(); HD6309Reset();
|
||||
MC6809SetBreakpoints({}); HD6309SetBreakpoints({});
|
||||
gpu.GimeReset(); gpu.SetMonitorType(1); gpu.SetDefaultPalette();
|
||||
}
|
||||
~GraphicsFixture() {
|
||||
gpu.StopEvents(); VCC::gEvents.Reset(); MmuShutdown();
|
||||
MC6809SetBreakpoints({}); HD6309SetBreakpoints({});
|
||||
VCC::SetCpuDebugHooks(nullptr); VCC::SetVideoHost(nullptr); VCC::SetMachineHost(nullptr);
|
||||
}
|
||||
void clockTicks() { VCC::gEvents.SetClocksPerCycle(1); VCC::gEvents.Rebase(); }
|
||||
void renderLine(unsigned line = 0) {
|
||||
host.surface.LineCounter = line;
|
||||
gpu.UpdateScreen32(&host.surface);
|
||||
}
|
||||
void loopProgram() {
|
||||
MemWrite8(0x20, 0x4000); MemWrite8(0xfe, 0x4001); // BRA $4000
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
void CheckVideoPixels() {
|
||||
GraphicsFixture f;
|
||||
// 320-pixel, 4-bpp RGB graphics. Pixel pairs are doubled to 640 pixels.
|
||||
f.gpu.SetGimeVmode(0x80); f.gpu.SetGimeVres(0x1e);
|
||||
f.gpu.SetGimePalette(1, 36); // full red
|
||||
f.gpu.SetGimePalette(2, 18); // full green
|
||||
f.gpu.SetGimePalette(3, 9); // full blue
|
||||
f.gpu.SetGimePalette(4, 63); // white
|
||||
Get_mem_pointer()[0] = 0x12; Get_mem_pointer()[1] = 0x34;
|
||||
f.renderLine();
|
||||
const unsigned expected[] = {0xff0000,0xff0000,0x00ff00,0x00ff00,0x0000ff,0x0000ff,0xffffff,0xffffff};
|
||||
const auto y = f.gpu.VertCenter * 2;
|
||||
for (unsigned x = 0; x < 8; ++x)
|
||||
require(f.host.pixel(x,y) == expected[x] && f.host.pixel(x,y+1) == expected[x],
|
||||
"RGB pixel byte order, nibble order and 2x scaling");
|
||||
f.gpu.SetScanLines(1); f.renderLine();
|
||||
for (unsigned x = 0; x < 8; ++x)
|
||||
require(f.host.pixel(x,y) == expected[x] && f.host.pixel(x,y+1) == 0, "Scanline option leaves alternating row black");
|
||||
f.gpu.SetScanLines(0); f.gpu.SetGimeBoarderColor(63);
|
||||
f.gpu.SetGimeVres(0x18); // 128 bytes at 1 bpp derives an unsupported 1024-pixel row
|
||||
f.renderLine(10);
|
||||
require(std::all_of(f.host.pixels.begin()+guard, f.host.pixels.end()-guard,
|
||||
[](auto pixel) { return pixel == 0; }), "Unsupported wide layout leaves framebuffer intact");
|
||||
f.host.checkGuards();
|
||||
// Explicit raster metadata is independent of green/black content. Both
|
||||
// resolutions and a mixed-width frame are represented without clipping.
|
||||
for (unsigned resolution : {0u, 0x1eu, 0x3eu, 0x5eu}) {
|
||||
f.host.active = {}; f.gpu.SetGimeVmode(0x80); f.gpu.SetGimeVres(resolution);
|
||||
for (unsigned row=0;row<f.gpu.LinesperScreen;++row) f.renderLine(row);
|
||||
const auto area=f.host.active;
|
||||
require(area.x==f.gpu.HorzCenter && area.y==f.gpu.VertCenter*2 &&
|
||||
area.width==640-2*f.gpu.HorzCenter && area.height==f.gpu.LinesperScreen*2,
|
||||
"Published active raster follows resolution, not pixel colors");
|
||||
}
|
||||
f.host.active = {};f.gpu.SetGimeVres(0);f.renderLine(0);
|
||||
f.gpu.SetGimeVres(0x1e);f.renderLine(191);
|
||||
require(f.host.active.x==0 && f.host.active.width==640 && f.host.active.y==50 && f.host.active.height==384,
|
||||
"Mixed-width raster retains the union of active rows");
|
||||
}
|
||||
|
||||
void CheckVideoModes() {
|
||||
GraphicsFixture f;
|
||||
std::fill_n(Get_mem_pointer(), 0x80000, 0x55);
|
||||
// Sweep register combinations over every active row, including
|
||||
// legacy text/semigraphics, PMODE variants, CoCo 3 text and all depths.
|
||||
for (unsigned compat = 0; compat < 2; ++compat) {
|
||||
f.gpu.SetCompatMode(compat);
|
||||
const unsigned modes = compat ? 8 : 16;
|
||||
const unsigned resolutions = compat ? 32 : 128;
|
||||
for (unsigned mode = 0; mode < modes; ++mode) {
|
||||
if (compat) f.gpu.SetGimeVdgMode(mode);
|
||||
else f.gpu.SetGimeVmode((mode & 8 ? 0x80 : 0) | (mode & 7));
|
||||
for (unsigned res = 0; res < resolutions; ++res) {
|
||||
if (compat) f.gpu.SetGimeVdgMode2(res);
|
||||
else f.gpu.SetGimeVres(res);
|
||||
f.host.ClearSurface();
|
||||
for (unsigned line = 0; line < f.gpu.LinesperScreen; ++line) f.renderLine(line);
|
||||
f.host.checkGuards();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Exercise the composite artifact path separately from the RGB sweep.
|
||||
f.host.ntsc = true; f.gpu.SetMonitorType(0); f.gpu.SetCompatMode(1);
|
||||
f.gpu.SetGimeVdgMode(7); f.gpu.SetGimeVdgMode2(31);
|
||||
f.gpu.SetGimeBoarderColor(63); // Select the white-border composite artifact path.
|
||||
f.renderLine(); f.host.checkGuards();
|
||||
|
||||
// Exercise a 128 KiB address mask inside this 512 KiB test allocation.
|
||||
// The bytes beyond the mask retain 0x55, making an unwrapped read visible.
|
||||
constexpr unsigned mask = 0x1ffff, wrappedStart = mask - 7, contiguousStart = 0x400;
|
||||
f.gpu.SetVidMask(mask);
|
||||
auto* ram = Get_mem_pointer();
|
||||
for (unsigned i = 0; i < 160; ++i) {
|
||||
const auto value = static_cast<unsigned char>(i * 37 + 3);
|
||||
ram[(wrappedStart + i) & mask] = ram[contiguousStart + i] = value;
|
||||
}
|
||||
auto renderedRow = [&](unsigned start) {
|
||||
f.gpu.NewStartofVidram = start;
|
||||
f.renderLine();
|
||||
const auto* row = f.host.surface.PTRsurface32 + 2 * f.gpu.VertCenter * width;
|
||||
return std::vector<unsigned int>(row, row + width);
|
||||
};
|
||||
require(f.gpu.BoarderColor32 == 0xffffff && f.gpu.BytesperRow == 32 &&
|
||||
renderedRow(wrappedStart) == renderedRow(contiguousStart),
|
||||
"PMODE 4 composite row wraps individual RAM reads at the installed capacity");
|
||||
|
||||
// 80 columns with attributes: the fourth attribute is the last physical
|
||||
// byte, and the fifth character and attribute must both come from low RAM.
|
||||
f.gpu.SetCompatMode(0); f.gpu.SetGimeVmode(3); f.gpu.SetGimeVres(0x15);
|
||||
require(f.gpu.ExtendedText == 2 && f.gpu.BytesperRow == 80 &&
|
||||
renderedRow(wrappedStart) == renderedRow(contiguousStart),
|
||||
"CoCo 3 text and attribute pairs wrap at the installed RAM capacity");
|
||||
}
|
||||
|
||||
void CheckRasterTiming() {
|
||||
for (bool use6309 : {false,true}) {
|
||||
GraphicsFixture f(true, use6309);
|
||||
f.loopProgram();
|
||||
auto execute = use6309 ? HD6309Exec : MC6809Exec;
|
||||
auto first = VCC::RunFrame(f.gpu, execute, 20000);
|
||||
require(first.reason == VCC::FrameStop::Complete && first.cycles == 14994,
|
||||
"First raster frame completes after 263 lines with instruction overshoot");
|
||||
require(f.host.horizontalFalls == 263 && f.host.horizontalRises == 263,
|
||||
"Raster emits one HSYNC pulse per 912-clock line");
|
||||
auto second = VCC::RunFrame(f.gpu, execute, 20000);
|
||||
require(second.reason == VCC::FrameStop::Complete && second.cycles == 14991 &&
|
||||
f.host.horizontalFalls == 526, "Subsequent frame preserves 239856-clock period");
|
||||
require(f.host.vertical.size() >= 2 && f.host.vertical[0].first == 0 && f.host.vertical[1].first == 1 &&
|
||||
f.host.vertical[1].second - f.host.vertical[0].second == 4*912,
|
||||
"VSYNC pulse lasts four scanlines");
|
||||
f.host.checkGuards();
|
||||
}
|
||||
}
|
||||
|
||||
void CheckRasterPixels() {
|
||||
GraphicsFixture f(true);
|
||||
f.loopProgram();
|
||||
f.gpu.SetGimeVmode(0x80); f.gpu.SetGimeVres(0x1e);
|
||||
f.gpu.SetGimePalette(1, 36); f.gpu.SetGimePalette(2, 18);
|
||||
f.gpu.SetGimePalette(3, 9); f.gpu.SetGimePalette(4, 63);
|
||||
f.gpu.SetGimeBoarderColor(9);
|
||||
for (unsigned y = 0; y < 192; ++y)
|
||||
for (unsigned x = 0; x < 160; ++x) {
|
||||
const auto color = (x / 20) % 4 + 1;
|
||||
Get_mem_pointer()[y*160+x] = (color << 4) | color;
|
||||
}
|
||||
require(VCC::RunFrame(f.gpu, MC6809Exec, 20000).reason == VCC::FrameStop::Complete,
|
||||
"CPU-driven color-bar frame completes");
|
||||
const unsigned colors[] = {0xff0000,0x00ff00,0x0000ff,0xffffff};
|
||||
for (unsigned y = 50; y < 434; ++y)
|
||||
for (unsigned x = 0; x < 640; ++x)
|
||||
require(f.host.pixel(x,y) == colors[(x/80)%4], "Full raster RGB bars preserve placement and pixels");
|
||||
require(f.host.pixel(0,0) == 0x0000ff && f.host.pixel(639,477) == 0x0000ff,
|
||||
"Raster draws top and bottom border");
|
||||
|
||||
// The first scheduled frame established the mode and the red first bar.
|
||||
// A guest palette write is visible to a paused snapshot before HSYNC
|
||||
// consumes it for the live raster.
|
||||
const auto livePixels = f.host.pixels;
|
||||
const auto clock = VCC::gEvents.GetClocks();
|
||||
const auto lineClock = f.gpu.GetLineStartClock();
|
||||
const auto hsyncs = f.host.horizontalFalls;
|
||||
f.gpu.SetGimePalette(1, 54); // red + green = yellow
|
||||
require(f.gpu.Palette32Bit[1] == colors[0], "Palette write is queued for the beam");
|
||||
std::vector<std::uint32_t> snapshot;
|
||||
const auto area = f.gpu.RenderSnapshot32(f.host.surface, snapshot);
|
||||
require(snapshot.size() == width * height && area.x == 0 && area.y == 50 &&
|
||||
area.width == width && area.height == 384, "Detached color bars cover the established active raster");
|
||||
for (unsigned y : {50u, 433u}) {
|
||||
require(snapshot[y * width] == 0xffff00 && snapshot[y * width + 80] == colors[1],
|
||||
"Detached raster applies the queued palette to the whole bar");
|
||||
}
|
||||
require(f.host.pixels == livePixels && f.gpu.Palette32Bit[1] == colors[0],
|
||||
"Detached render preserves all live pixels and the pending palette write");
|
||||
require(VCC::gEvents.GetClocks() == clock && f.gpu.GetLineStartClock() == lineClock &&
|
||||
f.host.horizontalFalls == hsyncs, "Detached render leaves the scheduler and beam at the stop");
|
||||
|
||||
const auto next = VCC::RunFrame(f.gpu, MC6809Exec, 20000);
|
||||
require(next.reason == VCC::FrameStop::Complete && next.cycles == 14991 &&
|
||||
f.host.horizontalFalls == hsyncs + 263, "The next scheduled frame retains its normal period");
|
||||
require(f.gpu.Palette32Bit[1] == 0xffff00 && f.host.pixel(0, 50) == 0xffff00 &&
|
||||
f.host.pixel(0, 433) == 0xffff00, "Regular rendering consumes the queued write and redraws the bar");
|
||||
f.host.checkGuards();
|
||||
}
|
||||
|
||||
void CheckGimeTimers() {
|
||||
GraphicsFixture f(true);
|
||||
f.clockTicks();
|
||||
GimeWrite(0x90, 0x20); GimeWrite(0x95, 1); GimeWrite(0x92, 0x20);
|
||||
GimeWrite(0x91, 0x20); // fast clock; restart at +8, period (1+2)*4
|
||||
VCC::gEvents.Tick(36);
|
||||
require(!f.host.lines[IS_GIME], "Fast timer respects delayed IRQ and exclusive event boundary");
|
||||
VCC::gEvents.Tick(1);
|
||||
require(GimeRead(0x92) == 0x20, "Fast timer IRQ occurs after reload and issue delay");
|
||||
VCC::gEvents.Tick(12);
|
||||
require(GimeRead(0x92) == 0x20, "Short-period timer retains overlapping delayed IRQs");
|
||||
GimeWrite(0x94, 0); GimeWrite(0x95, 0); GimeWrite(0x94, 0);
|
||||
VCC::gEvents.Tick(100); (void)GimeRead(0x92);
|
||||
VCC::gEvents.Tick(100);
|
||||
require(GimeRead(0x92) == 0, "Zero timer stops retriggering");
|
||||
|
||||
// Reset and run the line-clock source, including the initial decrement.
|
||||
VCC::gEvents.Reset(); f.clockTicks(); f.gpu.GimeReset(); GimeRegistersReset();
|
||||
GimeWrite(0x90, 0x20); GimeWrite(0x95, 1); GimeWrite(0x94, 0); GimeWrite(0x92, 0x20);
|
||||
VCC::gEvents.Tick(2736);
|
||||
require(!f.host.lines[IS_GIME], "Line timer waits for the third decrement and next HSYNC");
|
||||
VCC::gEvents.Tick(1);
|
||||
require(GimeRead(0x92) == 0x20, "Line-clock timer fires at HSYNC after reaching zero");
|
||||
}
|
||||
|
||||
void CheckVideoLifecycle() {
|
||||
GraphicsFixture f(true);
|
||||
f.clockTicks();
|
||||
f.gpu.SetGimeBoarderColor(63);
|
||||
GimeWrite(0x95, 1); GimeWrite(0x91, 0x20);
|
||||
f.gpu.GimeReset();
|
||||
require(VCC::gEvents.GetSize() == 4, "GPU reset replaces callbacks instead of duplicating raster/timers");
|
||||
VCC::gEvents.Tick(913);
|
||||
require(f.host.horizontalFalls == 1, "Repeated GPU reset leaves a single raster clock");
|
||||
f.gpu.StopEvents();
|
||||
require(VCC::gEvents.GetSize() == 0, "GPU stop cancels all owned work");
|
||||
VCC::gEvents.Tick(10000);
|
||||
require(f.host.horizontalFalls == 1, "Stopped GPU produces no further callbacks");
|
||||
{
|
||||
GimeGpu transient([](int) {}, [](int) {});
|
||||
transient.GimeReset(); // deliberately rely on lifetime guard, not StopEvents
|
||||
}
|
||||
VCC::gEvents.Tick(10000);
|
||||
require(VCC::gEvents.GetSize() == 0, "Destroyed GPU callbacks expire without dereferencing it");
|
||||
}
|
||||
|
||||
void CheckFrameStops() {
|
||||
GraphicsFixture f(true);
|
||||
f.loopProgram();
|
||||
MC6809SetBreakpoints({0x4000});
|
||||
auto result = VCC::RunFrame(f.gpu, MC6809Exec, 20000);
|
||||
require(result.reason == VCC::FrameStop::Halted && result.cycles == 0,
|
||||
"Frame runner returns immediately when CPU hits a breakpoint");
|
||||
MC6809SetBreakpoints({}); f.debugger.halted = false;
|
||||
result = VCC::RunFrame(f.gpu, MC6809Exec, 100);
|
||||
require(result.reason == VCC::FrameStop::Budget && result.cycles == 102,
|
||||
"Frame runner bounds work with final instruction overshoot");
|
||||
result = VCC::RunFrame(f.gpu, MC6809Exec, 20000);
|
||||
require(result.reason == VCC::FrameStop::Complete && result.cycles == 14892,
|
||||
"Partial frame resumes without restarting the raster");
|
||||
result = VCC::RunFrame(f.gpu, [](int budget) { return budget; }, 100);
|
||||
require(result.reason == VCC::FrameStop::Stalled, "Frame runner detects a CPU that makes no progress");
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "CoreChecks.h"
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#include <cstring>
|
||||
int main(int argc, char** argv) {
|
||||
if (argc == 5 && std::strcmp(argv[1], "--graphics-rom") == 0) {
|
||||
try { CheckGraphicsPreviewRom(argv[2], argv[3], argv[4]); return 0; }
|
||||
catch (const std::exception& error) { std::fprintf(stderr, "FAIL: %s\n", error.what()); return 1; }
|
||||
}
|
||||
if (argc == 4 && std::strcmp(argv[1], "--basic-rom") == 0) {
|
||||
try { CheckBasicProgramRom(argv[2],argv[3]); return 0; }
|
||||
catch(const std::exception& e) { std::fprintf(stderr,"FAIL: %s\n",e.what()); return 1; }
|
||||
}
|
||||
if (argc == 6 && std::strcmp(argv[1], "--speech-rom") == 0) {
|
||||
try { CheckSpeechSoundRom(argv[2],argv[3],argv[4],argv[5]); return 0; }
|
||||
catch(const std::exception& e) { std::fprintf(stderr,"%s\n",e.what()); return 1; }
|
||||
}
|
||||
if (argc == 5 && std::strcmp(argv[1], "--orchestra-rom") == 0) {
|
||||
try { CheckOrchestraRom(argv[2],argv[3],argv[4]); return 0; }
|
||||
catch(const std::exception& error) { std::fprintf(stderr,"FAIL: %s\n",error.what()); return 1; }
|
||||
}
|
||||
if (argc == 3 && std::strcmp(argv[1], "--clipboard-rom") == 0) {
|
||||
try { CheckClipboardRom(argv[2]); return 0; }
|
||||
catch(const std::exception& error) { std::fprintf(stderr,"FAIL: %s\n",error.what()); return 1; }
|
||||
}
|
||||
if (argc == 6 && std::strcmp(argv[1], "--nitros9-profile") == 0) {
|
||||
try { CheckHardDiskRom(argv[2],argv[3],argv[4],argv[5]); return 0; }
|
||||
catch(const std::exception& error) { std::fprintf(stderr,"FAIL: %s\n",error.what()); return 1; }
|
||||
}
|
||||
if (argc == 6 && std::strcmp(argv[1], "--hard-basic-media") == 0) {
|
||||
try { CreateHardBasicMedia(argv[2],argv[3],argv[4],argv[5]); return 0; }
|
||||
catch(const std::exception& error) { std::fprintf(stderr,"FAIL: %s\n",error.what()); return 1; }
|
||||
}
|
||||
if (argc == 5 && std::strcmp(argv[1], "--starter-media") == 0) {
|
||||
try { CreateStarterMedia(argv[2],argv[3],argv[4]); return 0; }
|
||||
catch(const std::exception& error) { std::fprintf(stderr,"FAIL: %s\n",error.what()); return 1; }
|
||||
}
|
||||
if (argc != 1 && !(argc == 3 && std::strcmp(argv[1], "--rom") == 0) &&
|
||||
!(argc == 4 && std::strcmp(argv[1], "--disk-rom") == 0) &&
|
||||
!(argc == 5 && std::strcmp(argv[1], "--hard-disk") == 0)) {
|
||||
std::fprintf(stderr, "Usage: VCCCoreChecks [--rom /path/to/coco3.rom | --disk-rom /path/to/coco3.rom /path/to/disk11.rom | --hard-disk /path/to/coco3.rom /path/to/rgbdos.rom /path/to/NitrOS9.vhd]\n"); return 2;
|
||||
}
|
||||
const char* current = "startup";
|
||||
try {
|
||||
const struct { const char* name; void (*run)(); } checks[] = {
|
||||
{"DriveWireProtocol", CheckDriveWireProtocol},
|
||||
{"BasicProgramTokens", CheckBasicProgramTokens},
|
||||
{"BasicProgramValidation", CheckBasicProgramValidation},
|
||||
{"SessionClipboard", CheckSessionClipboard},
|
||||
{"FramePacing", CheckFramePacing},
|
||||
{"AudioProgress", CheckAudioProgress},
|
||||
{"AcceleratedTiming", CheckAcceleratedTiming},
|
||||
{"MachineMemorySettings", CheckMachineMemorySettings},
|
||||
{"MachinePresentationSettings", CheckMachinePresentationSettings},
|
||||
{"ConfiguredOverclock", CheckConfiguredOverclock},
|
||||
{"BinaryParsing", CheckBinaryParsing},
|
||||
{"BinaryValidation", CheckBinaryValidation},
|
||||
{"BinarySession", CheckBinarySession},
|
||||
{"BinaryMappedWrites", CheckBinaryMappedWrites},
|
||||
{"DiskImages", CheckDiskImages},
|
||||
{"FloppyCommands", CheckFloppyCommands},
|
||||
{"FloppyTransfers", CheckFloppyTransfers},
|
||||
{"FloppyProtection", CheckFloppyProtection},
|
||||
{"BuiltinDeviceBus", CheckBuiltinDeviceBus},
|
||||
{"FloppySession", CheckFloppySession},
|
||||
{"AudioBuffer", CheckAudioBuffer},
|
||||
{"AudioScheduling", CheckAudioScheduling},
|
||||
{"AudioRouting", CheckAudioRouting},
|
||||
{"CassetteImages", CheckCassetteImages},
|
||||
{"CassetteMachine", CheckCassetteMachine},
|
||||
{"SessionSoftReset", CheckSessionSoftReset},
|
||||
{"SessionKeyboard", CheckSessionKeyboard},
|
||||
{"SessionAutomaticBoot", CheckSessionAutomaticBoot},
|
||||
{"JoystickComparator", CheckJoystickComparator},
|
||||
{"JoystickRamps", CheckJoystickRamps},
|
||||
{"JoystickSession", CheckJoystickSession},
|
||||
{"SessionVideoOutput", CheckSessionVideoOutput},
|
||||
{"GraphicsPreviewModes", CheckGraphicsPreviewModes},
|
||||
{"GraphicsPreviewColorSets", CheckGraphicsPreviewColorSets},
|
||||
{"SessionLifecycle", CheckSessionLifecycle},
|
||||
{"SessionReset", CheckSessionReset},
|
||||
{"SessionFrameOwnership", CheckSessionFrameOwnership},
|
||||
{"SessionExclusion", CheckSessionExclusion},
|
||||
{"SessionRomValidation", CheckSessionRomValidation},
|
||||
{"VideoPixels", CheckVideoPixels},
|
||||
{"VideoModes", CheckVideoModes},
|
||||
{"RasterTiming", CheckRasterTiming},
|
||||
{"RasterPixels", CheckRasterPixels},
|
||||
{"GimeTimers", CheckGimeTimers},
|
||||
{"VideoLifecycle", CheckVideoLifecycle},
|
||||
{"FrameStops", CheckFrameStops},
|
||||
{"MmuMapping", CheckMmuMapping},
|
||||
{"MmuRomAndVectors", CheckMmuRomAndVectors},
|
||||
{"MmuLifecycle", CheckMmuLifecycle},
|
||||
{"GimeRegisters", CheckGimeRegisters},
|
||||
{"PiaRegisters", CheckPiaRegisters},
|
||||
{"PiaInterrupts", CheckPiaInterrupts},
|
||||
{"MappedCpuExecution", CheckMappedCpuExecution},
|
||||
{"6809 execution", Check6809Execution}, {"6309 execution", Check6309Execution},
|
||||
{"6809 interrupts", Check6809Interrupts}, {"6309 interrupts", Check6309Interrupts},
|
||||
{"6309 native mode", Check6309Native}, {"CPU debugger", CheckCpuDebugHooks},
|
||||
{"event scheduler", CheckEventScheduler}, {"RAM disk", CheckRamDisk},
|
||||
{"SSC microcontroller", CheckMicrocontroller}, {"SSC bus", CheckCartridgeBus}
|
||||
};
|
||||
for (const auto& check : checks) {
|
||||
current = check.name;
|
||||
check.run();
|
||||
std::printf("PASS: %s\n", current);
|
||||
}
|
||||
current = "existing SSC suites";
|
||||
if (smoke_cpu() || smoke_sp0256() || smoke_ay8913() || smoke_ssc_core()) return 1;
|
||||
std::printf("All %zu core checks passed.\n", sizeof(checks) / sizeof(checks[0]) + 4);
|
||||
if (argc == 5) { current = "supplied hard disk integration"; CheckHardDiskRom(argv[2], argv[3], argv[4]); }
|
||||
if (argc == 4) { current = "supplied disk ROM integration"; CheckDiskRom(argv[2], argv[3]); }
|
||||
if (argc == 3) { current = "supplied ROM integration"; CheckRomBoot(argv[2]); }
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr, "FAIL [%s]: %s\n", current, error.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Native accessibility probe for the opt-in Debug --interface-validation session.
|
||||
// Compile: swiftc InterfaceUIProbe.swift -o /tmp/vcc-ui-probe
|
||||
// Usage: vcc-ui-probe PID inspect | press LABEL | menu MENU ITEM |
|
||||
// click LABEL | hover LABEL | close WINDOW | resize WINDOW WIDTH HEIGHT |
|
||||
// capture WINDOW OUTPUT.png | type BASIC_COMMAND | set-text LABEL INPUT_FILE
|
||||
import AppKit
|
||||
import ApplicationServices
|
||||
|
||||
let arguments = Array(CommandLine.arguments.dropFirst())
|
||||
guard arguments.count >= 2, let pid = Int32(arguments[0]), AXIsProcessTrusted() else {
|
||||
fputs("Supply the validation PID and action; macOS Accessibility access is required.\n", stderr); exit(2)
|
||||
}
|
||||
let app = AXUIElementCreateApplication(pid)
|
||||
func value(_ element: AXUIElement, _ key: String) -> Any? {
|
||||
var result: CFTypeRef?
|
||||
return AXUIElementCopyAttributeValue(element,key as CFString,&result) == .success ? result : nil
|
||||
}
|
||||
func text(_ element: AXUIElement, _ key: String) -> String { value(element,key) as? String ?? "" }
|
||||
func children(_ element: AXUIElement) -> [AXUIElement] { value(element,kAXChildrenAttribute) as? [AXUIElement] ?? [] }
|
||||
func descendants(_ element: AXUIElement, depth: Int = 0) -> [AXUIElement] {
|
||||
guard depth < 14 else { return [] }
|
||||
return [element] + children(element).flatMap { descendants($0,depth:depth+1) }
|
||||
}
|
||||
func fail(_ message: String) -> Never { fputs(message+"\n",stderr);exit(1) }
|
||||
func window(_ title: String) -> AXUIElement {
|
||||
guard let w=(value(app,kAXWindowsAttribute) as? [AXUIElement])?.first(where: { text($0,kAXTitleAttribute)==title }) else { fail("Window unavailable: \(title)") };return w
|
||||
}
|
||||
func press(_ e: AXUIElement) {
|
||||
guard AXUIElementPerformAction(e,kAXPressAction as CFString) == .success else { fail("Control did not accept Press") }
|
||||
}
|
||||
// Require the authored validation media to be visible somewhere in the app.
|
||||
// The UITesting app always installs an isolated fixture, including real-media
|
||||
// opt-in validation. Refuse an ordinary user's VCC instance accidentally.
|
||||
let all=descendants(app)
|
||||
guard NSRunningApplication(processIdentifier: pid)?.bundleIdentifier == "com.brianholman.vccplus.oss.mac.uitesting" || all.contains(where: { e in
|
||||
[kAXTitleAttribute,kAXDescriptionAttribute,kAXValueAttribute].contains { text(e,$0).contains("Authored") || text(e,$0) == "VCC Startup Validation" }
|
||||
}) else { fail("Refusing a non-validation session: authored fixture not found") }
|
||||
NSRunningApplication(processIdentifier:pid)?.activate()
|
||||
switch arguments[1] {
|
||||
case "inspect":
|
||||
for e in all {
|
||||
let role=text(e,kAXRoleAttribute),label=text(e,kAXDescriptionAttribute),title=text(e,kAXTitleAttribute)
|
||||
if !label.isEmpty || !title.isEmpty || role == "AXStaticText" || role == "AXPopUpButton" {
|
||||
print("\(role) | \(label.isEmpty ? title : label) | \(value(e,kAXValueAttribute) ?? "")")
|
||||
}
|
||||
}
|
||||
case "press":
|
||||
guard arguments.count==3, let e=all.first(where: {
|
||||
["AXButton","AXCheckBox","AXRadioButton","AXMenuButton","AXDisclosureTriangle","AXMenuItem","AXLink","AXPopUpButton"].contains(text($0,kAXRoleAttribute)) &&
|
||||
(text($0,kAXDescriptionAttribute)==arguments[2] || text($0,kAXTitleAttribute)==arguments[2] || text($0,kAXValueAttribute)==arguments[2])
|
||||
}) else { fail("Control unavailable") };press(e)
|
||||
case "click", "hover":
|
||||
guard arguments.count == 3, let element = all.first(where: {
|
||||
text($0,kAXDescriptionAttribute) == arguments[2] || text($0,kAXTitleAttribute) == arguments[2] ||
|
||||
text($0,kAXValueAttribute) == arguments[2]
|
||||
}) else { fail("Control unavailable") }
|
||||
var point = CGPoint.zero, size = CGSize.zero
|
||||
guard let p = value(element,kAXPositionAttribute), let s = value(element,kAXSizeAttribute),
|
||||
AXValueGetValue(unsafeBitCast(p as CFTypeRef,to:AXValue.self),.cgPoint,&point),
|
||||
AXValueGetValue(unsafeBitCast(s as CFTypeRef,to:AXValue.self),.cgSize,&size),
|
||||
size.width > 0, size.height > 0 else { fail("Visible control geometry unavailable") }
|
||||
point.x += size.width/2; point.y += size.height/2
|
||||
CGWarpMouseCursorPosition(point)
|
||||
CGEvent(mouseEventSource:nil,mouseType:.mouseMoved,mouseCursorPosition:point,mouseButton:.left)?.postToPid(pid)
|
||||
if arguments[1] == "click" {
|
||||
CGEvent(mouseEventSource:nil,mouseType:.leftMouseDown,mouseCursorPosition:point,mouseButton:.left)?.postToPid(pid)
|
||||
CGEvent(mouseEventSource:nil,mouseType:.leftMouseUp,mouseCursorPosition:point,mouseButton:.left)?.postToPid(pid)
|
||||
}
|
||||
case "set-text":
|
||||
guard arguments.count == 4, let element = all.first(where: {
|
||||
["AXTextArea", "AXTextField", "AXComboBox"].contains(text($0,kAXRoleAttribute)) &&
|
||||
text($0,kAXDescriptionAttribute) == arguments[2]
|
||||
}) else { fail("Editable field unavailable") }
|
||||
let input = try String(contentsOfFile: arguments[3], encoding: .utf8)
|
||||
guard AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, input as CFString) == .success else { fail("Cannot set field text") }
|
||||
case "type":
|
||||
guard arguments.count == 3, let display = all.first(where: { text($0,kAXDescriptionAttribute) == "CoCo display" }) else { fail("CoCo display unavailable") }
|
||||
var point = CGPoint.zero, size = CGSize.zero
|
||||
guard let p = value(display,kAXPositionAttribute), let s = value(display,kAXSizeAttribute),
|
||||
AXValueGetValue(unsafeBitCast(p as CFTypeRef,to:AXValue.self),.cgPoint,&point),
|
||||
AXValueGetValue(unsafeBitCast(s as CFTypeRef,to:AXValue.self),.cgSize,&size) else { fail("Display geometry unavailable") }
|
||||
let center = CGPoint(x:point.x+size.width/2,y:point.y+size.height/2)
|
||||
CGEvent(mouseEventSource:nil,mouseType:.leftMouseDown,mouseCursorPosition:center,mouseButton:.left)?.post(tap:.cghidEventTap)
|
||||
CGEvent(mouseEventSource:nil,mouseType:.leftMouseUp,mouseCursorPosition:center,mouseButton:.left)?.post(tap:.cghidEventTap)
|
||||
Thread.sleep(forTimeInterval:0.15)
|
||||
for character in arguments[2] + "\r" {
|
||||
let code: CGKeyCode = character == "\r" ? 36 : 0
|
||||
for down in [true,false] {
|
||||
let event = CGEvent(keyboardEventSource:nil,virtualKey:code,keyDown:down)!
|
||||
let utf16 = Array(String(character).utf16)
|
||||
utf16.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength:$0.count,unicodeString:$0.baseAddress!) }
|
||||
event.postToPid(pid);Thread.sleep(forTimeInterval:0.08)
|
||||
}
|
||||
}
|
||||
case "menu":
|
||||
guard arguments.count==4,let bar=value(app,kAXMenuBarAttribute) else { fail("Menu unavailable") }
|
||||
let root=unsafeBitCast(bar as CFTypeRef,to:AXUIElement.self)
|
||||
guard let menu=children(root).first(where:{text($0,kAXTitleAttribute)==arguments[2]}),
|
||||
let item=descendants(menu).first(where:{text($0,kAXRoleAttribute)=="AXMenuItem" && text($0,kAXTitleAttribute)==arguments[3]}) else { fail("Menu item unavailable") }
|
||||
press(item)
|
||||
case "close":
|
||||
guard arguments.count==3,let button=value(window(arguments[2]),kAXCloseButtonAttribute) else { fail("Close unavailable") }
|
||||
press(unsafeBitCast(button as CFTypeRef,to:AXUIElement.self))
|
||||
case "resize":
|
||||
guard arguments.count==5,let width=Double(arguments[3]),let height=Double(arguments[4]) else { fail("Supply width and height") }
|
||||
var size=CGSize(width:width,height:height)
|
||||
guard AXUIElementSetAttributeValue(window(arguments[2]),kAXSizeAttribute as CFString,AXValueCreate(.cgSize,&size)!) == .success else { fail("Resize failed") }
|
||||
case "capture":
|
||||
guard arguments.count==4 else { fail("Supply window title and output PNG") }
|
||||
let windows=CGWindowListCopyWindowInfo([.optionOnScreenOnly,.excludeDesktopElements],kCGNullWindowID) as? [[String:Any]] ?? []
|
||||
guard let w=windows.first(where: { ($0[kCGWindowOwnerPID as String] as? Int32)==pid && ($0[kCGWindowName as String] as? String)==arguments[2] }),let number=w[kCGWindowNumber as String] as? Int else { fail("Visible window unavailable") }
|
||||
let process=Process();process.executableURL=URL(fileURLWithPath:"/usr/sbin/screencapture")
|
||||
process.arguments=["-x","-o","-l",String(number),arguments[3]]
|
||||
try process.run();process.waitUntilExit();if process.terminationStatus != 0 {fail("Capture failed")}
|
||||
default:fail("Unknown action")
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// A real AppKit file drag into an isolated VCC validation window.
|
||||
// swiftc MediaDragProbe.swift -o /tmp/vcc-media-drag
|
||||
// /tmp/vcc-media-drag PID /absolute/authored/file.dsk [accessibility label]
|
||||
import AppKit
|
||||
import ApplicationServices
|
||||
let args = CommandLine.arguments
|
||||
func fail(_ text: String) -> Never { fputs(text + "\n", stderr); exit(1) }
|
||||
guard args.count >= 3, let pid = Int32(args[1]), AXIsProcessTrusted() else { fail("Supply a validation PID and authored file; Accessibility access is required") }
|
||||
let targetApp = AXUIElementCreateApplication(pid)
|
||||
func value(_ e: AXUIElement, _ key: String) -> Any? { var v: CFTypeRef?; AXUIElementCopyAttributeValue(e,key as CFString,&v);return v }
|
||||
func elements(_ e: AXUIElement, _ depth: Int = 0) -> [AXUIElement] { depth > 15 ? [] : [e] + ((value(e,kAXChildrenAttribute) as? [AXUIElement]) ?? []).flatMap { elements($0,depth+1) } }
|
||||
let all=elements(targetApp)
|
||||
guard all.contains(where:{value($0,kAXTitleAttribute) as? String == "VCC Startup Validation" || value($0,kAXTitleAttribute) as? String == "VCC UI Tests"}) else { fail("Refusing a normal emulator session") }
|
||||
let label=args.count > 3 ? args[3] : "CoCo display"
|
||||
guard let target=all.first(where:{value($0,kAXDescriptionAttribute) as? String == label}), let position=value(target,kAXPositionAttribute),let size=value(target,kAXSizeAttribute) else {fail("Drop target unavailable")}
|
||||
var point=CGPoint.zero,extent=CGSize.zero
|
||||
AXValueGetValue(position as! AXValue,.cgPoint,&point);AXValueGetValue(size as! AXValue,.cgSize,&extent)
|
||||
let destination=CGPoint(x:point.x+extent.width/2,y:point.y+extent.height/2)
|
||||
let file=URL(fileURLWithPath:args[2])
|
||||
guard FileManager.default.fileExists(atPath:file.path) else {fail("Authored file missing")}
|
||||
class Source: NSView, NSDraggingSource {
|
||||
override func draw(_ dirtyRect: NSRect) { NSColor.windowBackgroundColor.setFill();bounds.fill();("Drag authored media" as NSString).draw(at:NSPoint(x:15,y:25),withAttributes:[.foregroundColor:NSColor.labelColor]) }
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
let item=NSDraggingItem(pasteboardWriter:file as NSURL)
|
||||
item.setDraggingFrame(NSRect(x:15,y:15,width:48,height:48),contents:NSWorkspace.shared.icon(forFile:file.path))
|
||||
beginDraggingSession(with:[item],event:event,source:self)
|
||||
}
|
||||
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { .copy }
|
||||
func draggingSession(_ session: NSDraggingSession, endedAt point: NSPoint, operation: NSDragOperation) {
|
||||
print(operation == .copy ? "PASS: native file drop accepted" : "Drop did not complete")
|
||||
DispatchQueue.main.asyncAfter(deadline:.now()+0.2) { NSApp.terminate(nil) }
|
||||
}
|
||||
}
|
||||
let app=NSApplication.shared;app.setActivationPolicy(.accessory)
|
||||
let window=NSWindow(contentRect:NSRect(x:20,y:40,width:210,height:80),styleMask:[.titled],backing:.buffered,defer:false)
|
||||
window.title="VCC Drag Probe";window.contentView=Source();window.makeKeyAndOrderFront(nil);app.activate(ignoringOtherApps:true)
|
||||
DispatchQueue.main.asyncAfter(deadline:.now()+0.5) {
|
||||
let screenHeight=NSScreen.screens[0].frame.height
|
||||
let origin=window.convertPoint(toScreen:NSPoint(x:60,y:35))
|
||||
let source=CGPoint(x:origin.x,y:screenHeight-origin.y)
|
||||
func event(_ type:CGEventType,_ point:CGPoint) { CGEvent(mouseEventSource:nil,mouseType:type,mouseCursorPosition:point,mouseButton:.left)?.post(tap:.cghidEventTap) }
|
||||
event(.mouseMoved,source);event(.leftMouseDown,source)
|
||||
for i in 1...24 {
|
||||
DispatchQueue.main.asyncAfter(deadline:.now()+Double(i)*0.04) {
|
||||
let f=Double(i)/24
|
||||
event(.leftMouseDragged,CGPoint(x:source.x+(destination.x-source.x)*f,y:source.y+(destination.y-source.y)*f))
|
||||
if i==24 {event(.leftMouseUp,destination)}
|
||||
}
|
||||
}
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline:.now()+12) { NSApp.terminate(nil) }
|
||||
app.run()
|
||||
@@ -0,0 +1,30 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Read-only maintainer probe using the native catalog parser, not a parallel schema.
|
||||
import Foundation
|
||||
|
||||
@main
|
||||
struct SoftwareLibraryOwnedRecordProbe {
|
||||
static func main() throws {
|
||||
guard CommandLine.arguments.count > 1 else {
|
||||
throw NSError(domain: "OwnedRecordProbe", code: 1,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Supply explicit local intake or portable publication-record JSON files."])
|
||||
}
|
||||
for path in CommandLine.arguments.dropFirst() {
|
||||
let url = URL(fileURLWithPath: path)
|
||||
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||||
guard values.isRegularFile == true, values.isSymbolicLink != true,
|
||||
let size = values.fileSize, size > 0, size <= 8 * 1024 * 1024 else {
|
||||
throw SoftwareLibraryCatalog.Failure.invalid("invalid local intake/receipt file")
|
||||
}
|
||||
let object = try JSONDecoder().decode(LibraryJSON.self, from: Data(contentsOf: url))
|
||||
let record = object["contract"] == .null ? object : object["contract"]
|
||||
guard let game = try SoftwareLibraryOwnedGame.parse(record) else {
|
||||
throw SoftwareLibraryCatalog.Failure.invalid("missing owned title contract")
|
||||
}
|
||||
print("PASS", game.gameID, "RAM", game.ramKiB, "CPU", game.processor,
|
||||
"project", game.source.projectDirectory, "configuration", game.source.buildConfiguration ?? "project default",
|
||||
"related source packages", game.source.companionPackages.count)
|
||||
}
|
||||
print("Read-only validation; no catalog, media, application or publication changed.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Opt-in real-time integration runner. Reads a user ROM, never mounts/writes media.
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "../../platforms/macos/Bridge/VCCMachineController.h"
|
||||
#include <mach/mach.h>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
using Clock = std::chrono::steady_clock;
|
||||
static void pump(double seconds) {
|
||||
const auto end = Clock::now() + std::chrono::duration<double>(seconds);
|
||||
while (Clock::now() < end) @autoreleasepool {
|
||||
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.005]];
|
||||
}
|
||||
}
|
||||
static VCCMachineSnapshot* command(void (^operation)(VCCMachineCompletion)) {
|
||||
__block VCCMachineSnapshot* result = nil;
|
||||
operation(^(VCCMachineSnapshot* snapshot) { result = snapshot; });
|
||||
const auto deadline = Clock::now() + std::chrono::seconds(10);
|
||||
while (!result && Clock::now() < deadline) pump(0.005);
|
||||
if (!result) throw std::runtime_error("Machine command timed out");
|
||||
if (result.errorMessage) throw std::runtime_error(result.errorMessage.UTF8String);
|
||||
return result;
|
||||
}
|
||||
static uint64_t key(char c) {
|
||||
if (c >= 'A' && c <= 'Z') return uint64_t(1) << (c - '@');
|
||||
if (c >= '0' && c <= '9') return uint64_t(1) << (32 + c - '0');
|
||||
if (c == ',') return uint64_t(1) << 44;
|
||||
if (c == ' ') return uint64_t(1) << 31;
|
||||
if (c == '\n') return uint64_t(1) << 48;
|
||||
throw std::runtime_error("Unsupported probe key");
|
||||
}
|
||||
static void type(VCCMachineController* machine, const std::string& text) {
|
||||
for (char c : text) { [machine setKeyboardMask:key(c)]; pump(0.10); [machine setKeyboardMask:0]; pump(0.10); }
|
||||
}
|
||||
static uint64_t residentBytes() {
|
||||
mach_task_basic_info_data_t info{}; mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
|
||||
if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&info), &count) != KERN_SUCCESS)
|
||||
throw std::runtime_error("Unable to read process memory usage");
|
||||
return info.resident_size;
|
||||
}
|
||||
int main(int argc, const char* argv[]) { @autoreleasepool {
|
||||
if (argc < 4 || argc > 5) {
|
||||
std::fprintf(stderr, "Usage: SustainedChecks ROM seconds 6809|6309 [silent]\n"); return 2;
|
||||
}
|
||||
auto machine = [VCCMachineController new];
|
||||
try {
|
||||
std::size_t parsed = 0;
|
||||
const double duration = std::stod(argv[2], &parsed);
|
||||
if (parsed != std::string(argv[2]).size()) throw std::runtime_error("Invalid duration");
|
||||
if (!std::isfinite(duration) || duration < 5 || duration > 86400) throw std::runtime_error("Duration must be 5–86400 seconds");
|
||||
const std::string cpu = argv[3];
|
||||
if (cpu != "6809" && cpu != "6309") throw std::runtime_error("Select 6809 or 6309");
|
||||
const bool audio = argc == 4;
|
||||
if (argc == 5 && std::string(argv[4]) != "silent") throw std::runtime_error("Unknown pacing mode");
|
||||
auto rom = [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:argv[1]] options:NSDataReadingMappedIfSafe error:nil];
|
||||
if (rom.length != 32768) throw std::runtime_error("Supply a readable 32 KiB CoCo 3 ROM");
|
||||
command(^(VCCMachineCompletion done) { [machine setAudioEnabled:audio volume:0 completion:done]; });
|
||||
command(^(VCCMachineCompletion done) { [machine loadROM:rom use6309:cpu == "6309" completion:done]; });
|
||||
command(^(VCCMachineCompletion done) { [machine resumeWithCompletion:done]; });
|
||||
pump(3);
|
||||
type(machine, "10 SOUND100,255\n20 PRINT 42\n30 GOTO10\nRUN\n");
|
||||
pump(5);
|
||||
auto baseline = command(^(VCCMachineCompletion done) { [machine snapshotWithCompletion:done]; });
|
||||
const auto start = Clock::now();
|
||||
const auto initialRSS = residentBytes(); uint64_t maximumRSS = initialRSS;
|
||||
double maxDrift = 0, maxAudioDrift = 0; unsigned polls = 0; uint64_t previousSignal = baseline.audioSignalSamples;
|
||||
std::printf("START cpu=%s audio=%d seconds=%.0f frames=%llu consumed=%llu rss=%llu\n",cpu.c_str(),audio,duration,baseline.frames,baseline.audioConsumed,initialRSS); std::fflush(stdout);
|
||||
VCCMachineSnapshot* latest = baseline;
|
||||
while (std::chrono::duration<double>(Clock::now() - start).count() < duration) {
|
||||
@autoreleasepool {
|
||||
pump(std::min(1.0, duration - std::chrono::duration<double>(Clock::now() - start).count()));
|
||||
latest = command(^(VCCMachineCompletion done) { [machine snapshotWithCompletion:done]; });
|
||||
const auto wall = std::chrono::duration<double>(Clock::now() - start).count();
|
||||
const double emulated = (latest.frames - baseline.frames) * (239856.0 / 14318180.0);
|
||||
const double consumed = (latest.audioConsumed - baseline.audioConsumed) / 44100.0;
|
||||
maximumRSS = std::max(maximumRSS, residentBytes());
|
||||
maxDrift = std::max(maxDrift, std::abs(emulated - wall));
|
||||
if (audio) maxAudioDrift = std::max(maxAudioDrift, std::abs(consumed - wall));
|
||||
if (latest.state != VCCMachineStateRunning || latest.generation != baseline.generation || latest.frames <= baseline.frames)
|
||||
throw std::runtime_error("Machine stopped, reset or failed to advance");
|
||||
if (++polls % 30 == 0 || wall >= duration) {
|
||||
if (audio && wall >= 30 && latest.audioSignalSamples == previousSignal)
|
||||
throw std::runtime_error("BASIC tone loop stopped producing a signal");
|
||||
previousSignal = latest.audioSignalSamples;
|
||||
std::printf("SAMPLE wall=%.3f emulated=%.3f audio=%.3f drift_ms=%.3f underruns=%llu overruns=%llu rss=%llu buffered=%llu starts=%llu signal=%llu max_request=%llu max_refill_gap_ms=%.3f\n",
|
||||
wall, emulated, consumed, (emulated-wall)*1000, latest.audioUnderruns-baseline.audioUnderruns,
|
||||
latest.audioOverruns-baseline.audioOverruns, residentBytes(), latest.audioBuffered, latest.audioStarts, latest.audioSignalSamples, latest.audioMaximumRequest, latest.audioMaximumRefillGapNanoseconds / 1000000.0); std::fflush(stdout);
|
||||
}
|
||||
}
|
||||
}
|
||||
auto paused = command(^(VCCMachineCompletion done) { [machine pauseWithCompletion:done]; });
|
||||
pump(0.25);
|
||||
auto still = command(^(VCCMachineCompletion done) { [machine snapshotWithCompletion:done]; });
|
||||
if (still.frames != paused.frames || still.audioConsumed != paused.audioConsumed) throw std::runtime_error("Pause did not stop execution/audio");
|
||||
command(^(VCCMachineCompletion done) { [machine shutdownWithCompletion:done]; });
|
||||
std::printf("RESULT seconds=%.3f max_frame_drift_ms=%.3f max_audio_drift_ms=%.3f rss_growth=%lld underruns=%llu overruns=%llu\n",
|
||||
std::chrono::duration<double>(Clock::now()-start).count(),maxDrift*1000,maxAudioDrift*1000,
|
||||
static_cast<long long>(maximumRSS-initialRSS),latest.audioUnderruns-baseline.audioUnderruns,latest.audioOverruns-baseline.audioOverruns);
|
||||
std::fflush(stdout);
|
||||
if (maxDrift > 0.25 || (audio && maxAudioDrift > 0.25) || maximumRSS > initialRSS + 64*1024*1024 ||
|
||||
latest.audioUnderruns != baseline.audioUnderruns || latest.audioOverruns != baseline.audioOverruns)
|
||||
throw std::runtime_error("Sustained timing/buffering/memory acceptance threshold exceeded");
|
||||
std::puts("PASS: sustained native controller run and pause stability"); return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr,"FAIL: %s\n",error.what());
|
||||
[machine shutdownWithCompletion:^(VCCMachineSnapshot*) {}]; pump(0.1); return 1;
|
||||
}
|
||||
} }
|
||||
@@ -0,0 +1,101 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional real-media qualification. All guest commands use the keyboard; the
|
||||
// source disk/ROMs are read-only inputs and guest writes stay in owned memory.
|
||||
#include "../toolchain/ssc/session.h"
|
||||
#include "../../src/core/mc6821.h"
|
||||
#include <iomanip>
|
||||
|
||||
static void capture(const fs::path& path, const std::vector<StereoSample>& pcm) {
|
||||
std::ofstream out(path, std::ios::binary);
|
||||
auto put = [&](unsigned value, unsigned count) { while (count--) { out.put(char(value)); value >>= 8; } };
|
||||
out.write("RIFF", 4); put(36 + unsigned(pcm.size()) * 4, 4); out.write("WAVEfmt ", 8);
|
||||
put(16, 4); put(1, 2); put(2, 2); put(44100, 4); put(176400, 4); put(4, 2); put(16, 2);
|
||||
out.write("data", 4); put(unsigned(pcm.size()) * 4, 4);
|
||||
for (const auto sample : pcm) for (float value : {sample.left, sample.right})
|
||||
put(static_cast<std::uint16_t>(std::clamp(std::lround(value * 32768), -32768l, 32767l)), 2);
|
||||
require(out.good(), "Could not save private audio capture");
|
||||
}
|
||||
static void screen(Session& guest, const fs::path& path) {
|
||||
const auto frame = guest.machine.snapshot().frame; require(bool(frame), "Missing framebuffer");
|
||||
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) {
|
||||
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 private guest capture");
|
||||
}
|
||||
static bool report(Session& guest, const std::string& label, const fs::path& output) {
|
||||
double sum = 0, square = 0, low = 1, high = -1; std::uint64_t edges = 0, nonzero = 0;
|
||||
float previous = 0;
|
||||
for (auto sample : guest.audio) {
|
||||
sum += sample.left; square += double(sample.left) * sample.left;
|
||||
low = std::min(low, double(sample.left)); high = std::max(high, double(sample.left));
|
||||
edges += sample.left != previous; previous = sample.left;
|
||||
nonzero += sample.left != 0 || sample.right != 0;
|
||||
}
|
||||
const double n = double(guest.audio.size()), mean = n ? sum/n : 0;
|
||||
const double ac = n ? std::sqrt(std::max(0.0, square/n - mean*mean)) : 0;
|
||||
const auto& bus = guest.machine.cartridges();
|
||||
std::cout << label << " frames=" << guest.audio.size() << " nonzero=" << nonzero
|
||||
<< " range=" << low << ":" << high << " mean=" << mean << " ac_rms=" << ac << " edges=" << edges
|
||||
<< " mux=" << unsigned(GetMuxState()) << " sound_enabled=" << GetPIASoundState().enabled
|
||||
<< " pc=" << guest.machine.snapshot().cpu.PC << " cartridge=" << bus.audio() << '\n';
|
||||
capture(output / (label + ".wav"), guest.audio); screen(guest, output / (label + ".ppm"));
|
||||
return nonzero == 0;
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
if (argc != 4 && argc != 5) throw std::runtime_error("Usage: audio-game-validation ROM_DIRECTORY DOS_BOOT_DISK OUTPUT_DIRECTORY [--expect-quiet]");
|
||||
const fs::path roms(argv[1]), output(argv[3]); const auto disk = readFile(argv[2]);
|
||||
require(argc == 4 || std::string(argv[4]) == "--expect-quiet", "Unknown validation option");
|
||||
const bool expectQuiet = argc == 5;
|
||||
fs::create_directories(output);
|
||||
auto chips = readFile(roms / "pic-7040-510.bin"), 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());
|
||||
bool quiet = true;
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) for (unsigned mode = 0; mode < 4; ++mode) {
|
||||
auto ssc = mode & 1 ? std::make_shared<SpeechSoundDevice>(chips) : nullptr;
|
||||
Session guest(cpu, readFile(roms / "coco3.rom"), readFile(roms / "disk11.rom"), ssc, false);
|
||||
// Match the normal Multi-Pak layout, including the optional music
|
||||
// ROM. It is retained while the FD-502 remains the startup device.
|
||||
auto orchestra = mode & 2 ? std::make_shared<Orchestra90Device>(readFile(roms / "orch90.rom")) : nullptr;
|
||||
require(guest.machine.snapshot().configuration.ram == 1, "This check requires 512 KiB");
|
||||
guest.machine.cartridges().configure({nullptr, ssc, orchestra, nullptr, guest.floppy}, true, 4);
|
||||
guest.machine.cassette().mount({0x55, 0x55, 0x3c}, TapeFormat::CAS); // mounted, stopped
|
||||
guest.machine.setJoystick(0, 8191, 8191, 0, 0); guest.machine.setJoystick(1, 8191, 8191, 0, 0);
|
||||
guest.floppy->mount(0, DiskImage::load(disk, false));
|
||||
guest.press('D'-'@'); guest.press('O'-'@'); guest.press('S'-'@'); guest.press(48);
|
||||
for (unsigned i = 0; i < 1800; ++i) guest.tick(); // disk boot + title settle
|
||||
guest.audio.clear();
|
||||
for (unsigned i = 0; i < 120; ++i) guest.tick();
|
||||
const std::string label = std::string(cpu == Processor::MC6809 ? "6809-" : "6309-") +
|
||||
std::array<const char*,4>{"disk", "speech", "orchestra", "both"}[mode];
|
||||
quiet = report(guest, label, output) && quiet;
|
||||
if (mode == 3) {
|
||||
// Start the unchanged game and exercise its standard event
|
||||
// effect through ordinary keyboard input, not guest memory.
|
||||
const auto title = guest.machine.snapshot().frame->pixels;
|
||||
guest.machine.setKeyboard(std::uint64_t{1} << 48);
|
||||
for (unsigned i = 0; i < 60; ++i) guest.tick();
|
||||
guest.machine.setKeyboard(0);
|
||||
for (unsigned i = 0; i < 480; ++i) guest.tick();
|
||||
require(guest.machine.snapshot().frame->pixels != title, "Start did not change the title framebuffer");
|
||||
guest.audio.clear(); guest.machine.setKeyboard(std::uint64_t{1} << 4); // D/right
|
||||
for (unsigned i = 0; i < 12; ++i) guest.tick();
|
||||
guest.machine.setKeyboard(0);
|
||||
for (unsigned i = 0; i < 108; ++i) guest.tick();
|
||||
report(guest, label + "-move", output);
|
||||
require(std::any_of(guest.audio.begin(), guest.audio.end(), [](auto sample) { return sample.left != 0 || sample.right != 0; }), "Movement effect was muted or did not run");
|
||||
if (expectQuiet) require(guest.audio.size() > 22050 && std::all_of(guest.audio.end()-22050, guest.audio.end(), [](auto sample) { return sample.left == 0 && sample.right == 0; }), "Movement did not return to silence");
|
||||
}
|
||||
require(guest.machine.cassette().snapshot().position == 0, "Stopped tape advanced");
|
||||
require(guest.floppy->readEvents(0) != 0, "Game disk was not read");
|
||||
guest.machine.pause(); guest.machine.takeAudio(); guest.machine.advance();
|
||||
require(guest.machine.takeAudio().empty(), "Pause generated new PCM");
|
||||
}
|
||||
require(readFile(argv[2]) == disk, "Source game disk changed");
|
||||
if (expectQuiet) require(quiet, "Expected silent idle title output in every cartridge configuration");
|
||||
} catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Capture actual secondary windows in an already-running isolated UI fixture.
|
||||
|
||||
Build InterfaceUIProbe.swift first. Launch the VCCUITests product with
|
||||
-VCCUITestAppearance light (or dark). The probe refuses normal emulator sessions.
|
||||
This script controls focus; run it only while the user has released the pointer.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--pid', required=True, type=int)
|
||||
parser.add_argument('--probe', required=True, type=Path)
|
||||
parser.add_argument('--output', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def probe(*command):
|
||||
subprocess.run([str(args.probe), str(args.pid), *map(str, command)], check=True)
|
||||
|
||||
def capture(title, filename, width, height):
|
||||
probe('resize', title, width, height)
|
||||
time.sleep(0.3)
|
||||
probe('capture', title, args.output / filename)
|
||||
|
||||
windows = [
|
||||
('Cartridge', 'Cartridges…', 'Cartridges', '01-cartridges.png', 740, 820),
|
||||
('Media', 'Floppy Disks…', 'Floppy Disks', '02-floppy.png', 760, 700),
|
||||
('Media', 'Virtual Hard Disks…', 'Virtual Hard Disks', '03-hard-disks.png', 780, 660),
|
||||
('Media', 'Cassette…', 'Cassette', '04-cassette.png', 800, 620),
|
||||
('Machine', 'Machine Settings…', 'Machine Settings', '05-machine.png', 600, 800),
|
||||
('Machine', 'Configuration Profiles…', 'Configuration Profiles', '06-profiles.png', 900, 760),
|
||||
('Input', 'Keyboard and Joysticks…', 'Keyboard and Joysticks', '07-input.png', 700, 800),
|
||||
('Display', 'Display Settings…', 'Display Settings', '08-display.png', 600, 660),
|
||||
('Help', 'About VCC Plus', 'About VCC Plus', '09-about.png', 760, 800),
|
||||
('Help', 'Keyboard & Shortcuts…', 'Keyboard & Shortcuts', '10-keyboard-help.png', 760, 760),
|
||||
('Help', 'Licenses & Notices…', 'Licenses & Notices', '11-licenses.png', 820, 700),
|
||||
]
|
||||
for menu, item, title, filename, width, height in windows:
|
||||
probe('menu', menu, item)
|
||||
time.sleep(0.3)
|
||||
capture(title, filename, width, height)
|
||||
probe('close', title)
|
||||
|
||||
probe('menu', 'Debug', 'Show Debugger')
|
||||
time.sleep(0.3)
|
||||
capture('Debugger', '12-debugger.png', 1120, 760)
|
||||
probe('press', 'Source')
|
||||
capture('Debugger', '15-source.png', 1120, 760)
|
||||
probe('press', 'Disassembly')
|
||||
probe('press', 'MMU')
|
||||
capture('Debugger', '16-mmu.png', 1120, 760)
|
||||
probe('press', 'Memory')
|
||||
for tab, filename in [('Memory Tools', '13-memory-tools.png'), ('Trace', '14-trace.png')]:
|
||||
probe('press', tab)
|
||||
probe('press', 'Disassemble' if tab == 'Memory Tools' else 'Start New')
|
||||
time.sleep(0.5)
|
||||
capture('Debugger', filename, 1120, 760)
|
||||
probe('close', 'Debugger')
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional catalog spot check using private local ROMs/media. No host UI or
|
||||
// source-media writes. Command is typed into the guest, never a host shell.
|
||||
// Usage: catalog-launch-probe SYSTEM_ROM DISK_ROM MEDIA COMMAND OUTPUT_PREFIX [cassette]
|
||||
// Link against the matching revision's libVCCCore.a; see catalog review notes.
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/devices/FD502/Fd502Device.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
using namespace VCC::Mac;
|
||||
using namespace VCC::Devices;
|
||||
static std::vector<std::uint8_t> read(const std::string& path) {
|
||||
std::ifstream stream(path, std::ios::binary);
|
||||
if (!stream) throw std::runtime_error("Cannot read input");
|
||||
return {std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()};
|
||||
}
|
||||
static std::uint64_t key(char c) {
|
||||
unsigned bit;
|
||||
if (c >= 'A' && c <= 'Z') bit = c - '@';
|
||||
else if (c >= '0' && c <= '9') bit = 32 + c - '0';
|
||||
else if (c == ':') bit = 42;
|
||||
else if (c == ',') bit = 44;
|
||||
else if (c == '.') bit = 46;
|
||||
else if (c == '/') bit = 47;
|
||||
else if (c == '"') return (std::uint64_t{1} << 34) | (std::uint64_t{1} << 55);
|
||||
else if (c == ' ') bit = 31;
|
||||
else if (c == '\r') bit = 48;
|
||||
else throw std::runtime_error("Unsupported guest input character");
|
||||
return std::uint64_t{1} << bit;
|
||||
}
|
||||
static void capture(MachineSession& machine, const std::string& prefix) {
|
||||
const auto frame = machine.snapshot().frame;
|
||||
if (!frame) throw std::runtime_error("No frame");
|
||||
std::ofstream out(prefix + ".ppm", std::ios::binary);
|
||||
out << "P6\n" << Frame::width << ' ' << Frame::height << "\n255\n";
|
||||
for (auto p : frame->pixels) { out.put(char(p >> 16)); out.put(char(p >> 8)); out.put(char(p)); }
|
||||
if (!out) throw std::runtime_error("Cannot write capture");
|
||||
try { std::cout << machine.copyScreenText() << '\n'; }
|
||||
catch (const std::logic_error&) { std::cout << "Graphics screen; inspect capture.\n"; }
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
if (argc != 6 && argc != 7) throw std::runtime_error("Expected system ROM, disk ROM, disk, guest command and output prefix");
|
||||
const bool cassette = argc == 7 && std::string(argv[6]) == "cassette";
|
||||
if (argc == 7 && !cassette) throw std::runtime_error("Unknown media mode");
|
||||
const auto original = read(argv[3]);
|
||||
MachineSession machine;
|
||||
auto disk = std::make_shared<Fd502Device>(read(argv[2]));
|
||||
if (!cassette) disk->mount(0, DiskImage::load(original, true));
|
||||
machine.cartridges().configure({nullptr, nullptr, nullptr, nullptr, disk}, true, 4);
|
||||
MachineConfiguration config; config.ram = 1; config.frameInterval = 6;
|
||||
machine.configure(config);
|
||||
machine.load(read(argv[1])); machine.resume();
|
||||
auto advance = [&](unsigned frames) { while (frames--) { machine.advance(); machine.takeAudio(); } };
|
||||
auto type = [&](const std::string& text) {
|
||||
for (char c : text) { machine.setKeyboard(key(c)); advance(4); machine.setKeyboard(0); advance(4); }
|
||||
};
|
||||
advance(300);
|
||||
if (machine.copyScreenText().find("OK") == std::string::npos) throw std::runtime_error("BASIC did not boot");
|
||||
if (cassette) {
|
||||
machine.cassette().mount(original, TapeFormat::CAS);
|
||||
machine.cassette().setFast(true); machine.cassette().play();
|
||||
}
|
||||
// Separate cassette load and execution. Never type EXEC while CLOADM
|
||||
// is still consuming the tape. The production recipe uses prompt waits.
|
||||
std::string command = argv[4];
|
||||
if (command.empty() || command.back() != '\r') command += '\r';
|
||||
std::size_t start = 0;
|
||||
while (start < command.size()) {
|
||||
const auto end = command.find('\r', start);
|
||||
type(command.substr(start, end - start + 1)); advance(1800);
|
||||
if (cassette && machine.cassette().snapshot().motor)
|
||||
throw std::runtime_error("Cassette is still loading at command boundary");
|
||||
start = end + 1;
|
||||
}
|
||||
capture(machine, std::string(argv[5]) + "-launch");
|
||||
// A single Enter gives text adventures an opportunity to advance past
|
||||
// their introduction. It does not establish gameplay completion.
|
||||
type("\r"); advance(180);
|
||||
capture(machine, std::string(argv[5]) + "-enter");
|
||||
const auto reads = cassette ? machine.cassette().snapshot().readEvents : disk->readEvents(0);
|
||||
const auto writes = cassette ? machine.cassette().snapshot().writeEvents : disk->writeEvents(0);
|
||||
const auto finalBytes = cassette ? machine.cassette().exportImage() : disk->image(0)->bytes();
|
||||
std::cout << "reads=" << reads << " writes=" << writes
|
||||
<< " frames=" << machine.snapshot().frames << '\n';
|
||||
if (!reads || writes || finalBytes != original || read(argv[3]) != original)
|
||||
throw std::runtime_error("Read-only media check failed");
|
||||
std::cout << "PASS: media was read, original bytes unchanged; visually review launch captures.\n";
|
||||
} catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional signed-policy fixture: compile once, copy, and sign the peers with
|
||||
// their edition's bundle identifiers and a contributor-supplied signing identity.
|
||||
// Supply the matching publisher team through VCC_TEST_COMPANION_TEAM_ID; this is
|
||||
// separate from the default ad-hoc app build and needs no maintainer credentials.
|
||||
import Foundation
|
||||
|
||||
@main struct SignedTransportPeer {
|
||||
static func main() async throws {
|
||||
let teamID = (ProcessInfo.processInfo.environment["VCC_TEST_COMPANION_TEAM_ID"] ?? "")
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !teamID.isEmpty else { throw CompanionTransport.Failure.untrustedPeer }
|
||||
let args = Array(CommandLine.arguments.dropFirst())
|
||||
guard args.count == 2 else { throw CompanionTransport.Failure.malformedFrame }
|
||||
if args[0] == "validate" {
|
||||
do {
|
||||
try CompanionTransport.validateApplication(at: URL(fileURLWithPath: args[1]),
|
||||
permittedBundleIDs: ["com.brianholman.vccplus.oss.mac"], teamID: teamID)
|
||||
print("PASS production application validation")
|
||||
} catch {
|
||||
print("DENIED application validation: \(error.localizedDescription)")
|
||||
exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
var configuration = CompanionTransport.Configuration.production
|
||||
configuration.teamID = teamID
|
||||
configuration.directory = URL(fileURLWithPath: args[1])
|
||||
configuration.timeout = 10
|
||||
if args[0] == "server" {
|
||||
let server = try CompanionTransport.Server(configuration: configuration) { method, payload in
|
||||
guard method == "signedEcho" else { throw CompanionTransport.Failure.malformedFrame }
|
||||
return payload
|
||||
}
|
||||
print("READY")
|
||||
fflush(stdout)
|
||||
try await Task.sleep(nanoseconds: 10_000_000_000)
|
||||
server.stop()
|
||||
} else {
|
||||
let input = Data("signed companion payload".utf8)
|
||||
let output = try await CompanionTransport.Client(configuration: configuration).request(method: "signedEcho", payload: input)
|
||||
guard output == input else { throw CompanionTransport.Failure.malformedFrame }
|
||||
print("PASS production same-team/bundle authentication and binary round-trip")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Standalone authored IPC fixtures. Compile with -D VCC_COMPANION_TESTING.
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
@main struct TransportChecks {
|
||||
actor Flag {
|
||||
var started = false
|
||||
var cancelled = false
|
||||
func start() { started = true }
|
||||
func cancel() { cancelled = true }
|
||||
}
|
||||
static func require(_ condition: Bool, _ message: String) throws {
|
||||
if !condition { throw NSError(domain: "TransportCheck", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) }
|
||||
}
|
||||
static func configuration(_ root: URL, name: String = "fixture.sock", timeout: TimeInterval = 3) -> CompanionTransport.Configuration {
|
||||
var config = CompanionTransport.Configuration(directory: root)
|
||||
config.socketName = name; config.timeout = timeout; config.allowUnsignedTestPeers = true
|
||||
return config
|
||||
}
|
||||
static func fixtureSocket(_ path: String, listening: Bool = false) throws -> Int32 {
|
||||
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
|
||||
guard fd >= 0 else { throw POSIXError(.EIO) }
|
||||
var address = sockaddr_un(); address.sun_family = sa_family_t(AF_UNIX)
|
||||
address.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
|
||||
let bytes = Array(path.utf8CString)
|
||||
guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { close(fd); throw POSIXError(.ENAMETOOLONG) }
|
||||
withUnsafeMutableBytes(of: &address.sun_path) { target in bytes.withUnsafeBytes { target.copyBytes(from: $0) } }
|
||||
let rc = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } }
|
||||
guard rc == 0, chmod(path, 0o600) == 0 else { close(fd); throw POSIXError(.EIO) }
|
||||
if listening { guard listen(fd, 2) == 0 else { close(fd); throw POSIXError(.EIO) } }
|
||||
return fd
|
||||
}
|
||||
static func main() async throws {
|
||||
let root = URL(fileURLWithPath: "/private/tmp/vcc-ipc-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let config = configuration(root)
|
||||
let server = try CompanionTransport.Server(configuration: config) { method, payload in
|
||||
if method == "error" { throw CompanionTransport.Failure.remote("Authored remote error") }
|
||||
return payload
|
||||
}
|
||||
defer { server.stop() }
|
||||
let client = CompanionTransport.Client(configuration: config)
|
||||
let bytes = Data((0..<(1024 * 1024)).map { UInt8($0 & 255) })
|
||||
let echoed = try await client.request(method: "echo", payload: bytes)
|
||||
try require(echoed == bytes, "Binary round-trip differs")
|
||||
print("PASS binary round-trip")
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
for n in 0..<4 {
|
||||
group.addTask {
|
||||
let expected = Data("request-\(n)".utf8)
|
||||
let actual = try await client.request(method: "echo", payload: expected)
|
||||
try require(actual == expected, "Concurrent response crossed request identities")
|
||||
}
|
||||
}
|
||||
try await group.waitForAll()
|
||||
}
|
||||
print("PASS concurrent request identities")
|
||||
do { _ = try await client.request(method: "error"); throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.remote(let message) { try require(message == "Authored remote error", "Remote error differs") }
|
||||
print("PASS remote errors")
|
||||
do { _ = try CompanionTransport.Server(configuration: config) { _, p in p }; throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.busy { }
|
||||
try require(try await client.request(method: "echo") == Data(), "Duplicate listener disrupted live endpoint")
|
||||
print("PASS duplicate listener preserves running service")
|
||||
var second = config; second.socketName = "second.sock"
|
||||
let other = try CompanionTransport.Server(configuration: second) { _, _ in Data("other".utf8) }
|
||||
try require(try await CompanionTransport.Client(configuration: second).request(method: "echo") == Data("other".utf8), "Second endpoint failed")
|
||||
other.stop()
|
||||
try require(try await client.request(method: "echo") == Data(), "Second endpoint stopped first service")
|
||||
print("PASS independent app endpoints")
|
||||
var signedOnly = config; signedOnly.allowUnsignedTestPeers = false
|
||||
do { _ = try await CompanionTransport.Client(configuration: signedOnly).request(method: "echo"); throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.untrustedPeer { }
|
||||
print("PASS unsigned peer rejected by production policy")
|
||||
do {
|
||||
try CompanionTransport.validateApplication(at: URL(fileURLWithPath: CommandLine.arguments[0]),
|
||||
permittedBundleIDs: ["com.brianholman.vccplus.oss.mac"])
|
||||
throw POSIXError(.EIO)
|
||||
} catch CompanionTransport.Failure.untrustedPeer { }
|
||||
print("PASS unsigned application rejected before launch")
|
||||
do { _ = try await client.request(method: "echo", payload: Data(count: CompanionTransport.maximumPayloadBytes + 1)); throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.tooLarge { }
|
||||
print("PASS oversized payload rejected")
|
||||
let flag = Flag()
|
||||
var waiting = config; waiting.socketName = "waiting.sock"
|
||||
let slow = try CompanionTransport.Server(configuration: waiting) { _, _ in
|
||||
await flag.start()
|
||||
do { try await Task.sleep(nanoseconds: 10_000_000_000) }
|
||||
catch { await flag.cancel(); throw error }
|
||||
return Data()
|
||||
}
|
||||
let task = Task { try await CompanionTransport.Client(configuration: waiting).request(method: "wait") }
|
||||
for _ in 0..<40 {
|
||||
if await flag.started { break }
|
||||
try await Task.sleep(nanoseconds: 25_000_000)
|
||||
}
|
||||
try require(await flag.started, "Handler did not start")
|
||||
task.cancel()
|
||||
do { _ = try await task.value; throw POSIXError(.EIO) } catch is CancellationError { }
|
||||
for _ in 0..<40 {
|
||||
if await flag.cancelled { break }
|
||||
try await Task.sleep(nanoseconds: 25_000_000)
|
||||
}
|
||||
try require(await flag.cancelled, "Client cancellation did not reach handler")
|
||||
slow.stop()
|
||||
print("PASS cancellation propagates to server work")
|
||||
var stale = config; stale.socketName = "stale.sock"
|
||||
close(try fixtureSocket(stale.socketPath))
|
||||
let recovered = try CompanionTransport.Server(configuration: stale) { _, p in p }
|
||||
recovered.stop()
|
||||
print("PASS owned stale socket recovery")
|
||||
var active = config; active.socketName = "active.sock"
|
||||
let foreign = try fixtureSocket(active.socketPath, listening: true)
|
||||
do { _ = try CompanionTransport.Server(configuration: active) { _, p in p }; throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.busy { }
|
||||
var activeInfo = stat(); try require(lstat(active.socketPath, &activeInfo) == 0, "Live foreign socket removed")
|
||||
close(foreign); unlink(active.socketPath)
|
||||
print("PASS live foreign socket preserved")
|
||||
var unsafe = config; unsafe.socketName = "unsafe.sock"
|
||||
let target = root.appendingPathComponent("retained.txt")
|
||||
try Data("retained".utf8).write(to: target)
|
||||
try FileManager.default.createSymbolicLink(atPath: unsafe.socketPath, withDestinationPath: target.path)
|
||||
do { _ = try CompanionTransport.Server(configuration: unsafe) { _, p in p }; throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.unsafeEndpoint { }
|
||||
try require(try Data(contentsOf: target) == Data("retained".utf8), "Symlink target changed")
|
||||
print("PASS symlink endpoint refused without modifying target")
|
||||
var replaced = config; replaced.socketName = "replaced.sock"
|
||||
let old = try CompanionTransport.Server(configuration: replaced) { _, p in p }
|
||||
unlink(replaced.socketPath)
|
||||
let replacement = try fixtureSocket(replaced.socketPath)
|
||||
old.stop()
|
||||
var replacementInfo = stat()
|
||||
try require(lstat(replaced.socketPath, &replacementInfo) == 0, "Replaced socket removed during stop")
|
||||
close(replacement); unlink(replaced.socketPath)
|
||||
print("PASS stop preserves replaced endpoint")
|
||||
var timing = config; timing.socketName = "timeout.sock"; timing.timeout = 0.2
|
||||
let hung = try CompanionTransport.Server(configuration: timing) { _, _ in
|
||||
try await Task.sleep(nanoseconds: 10_000_000_000); return Data()
|
||||
}
|
||||
do { _ = try await CompanionTransport.Client(configuration: timing).request(method: "wait"); throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.timedOut { }
|
||||
hung.stop()
|
||||
print("PASS bounded operation deadline")
|
||||
server.stop()
|
||||
do { _ = try await client.request(method: "echo"); throw POSIXError(.EIO) }
|
||||
catch CompanionTransport.Failure.unavailable { }
|
||||
print("PASS stopped service unavailable")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Foundation-only executable: the runner places it in authored fixture bundles.
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
@main struct ValidationChecks {
|
||||
static func require(_ value: Bool, _ message: String) throws {
|
||||
guard value else { throw NSError(domain: "CompanionValidationChecks", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) }
|
||||
}
|
||||
static func main() throws {
|
||||
let args = CommandLine.arguments
|
||||
let expectingEnabled = args.contains("--expect-enabled")
|
||||
if CompanionValidation.enabled != expectingEnabled {
|
||||
print("DIAGNOSTIC bundle=\(Bundle.main.bundleIdentifier ?? "nil") url=\(Bundle.main.bundleURL.path)")
|
||||
if let index = args.firstIndex(of: "--companion-validation-root"), args.indices.contains(index + 1) {
|
||||
let supplied = URL(fileURLWithPath: args[index + 1], isDirectory: true).standardizedFileURL
|
||||
var info = stat()
|
||||
let rc = lstat(supplied.path, &info)
|
||||
print("DIAGNOSTIC supplied=\(supplied.path) resolved=\(supplied.resolvingSymlinksInPath().path) lstat=\(rc) uid=\(info.st_uid)/\(geteuid()) mode=\(String(info.st_mode, radix: 8))")
|
||||
}
|
||||
do { _ = try CompanionValidation.configuration(forVCCPlus: true) }
|
||||
catch { print("DIAGNOSTIC \(error)") }
|
||||
fflush(stdout)
|
||||
}
|
||||
try require(CompanionValidation.enabled == expectingEnabled, "Unexpected validation availability")
|
||||
if expectingEnabled {
|
||||
let supplied = args[args.firstIndex(of: "--companion-validation-root")! + 1]
|
||||
let canonical = URL(fileURLWithPath: supplied).standardizedFileURL.resolvingSymlinksInPath()
|
||||
try require(CompanionValidation.root == canonical, "Validation root differs")
|
||||
let vcc = try CompanionValidation.configuration(forVCCPlus: true)
|
||||
let dw = try CompanionValidation.configuration(forVCCPlus: false)
|
||||
try require(vcc.directory == canonical && dw.directory == canonical, "Fixture escaped isolated root")
|
||||
try require(vcc.socketPath != dw.socketPath, "Fixture endpoints collide")
|
||||
try require(vcc.expectedServerBundleIDs == [CompanionValidation.vccPlusBundleID] &&
|
||||
vcc.expectedClientBundleIDs == [CompanionValidation.driveWireBundleID], "Wrong VCC fixture peer identities")
|
||||
try require(dw.expectedServerBundleIDs == [CompanionValidation.driveWireBundleID] &&
|
||||
dw.expectedClientBundleIDs == [CompanionValidation.vccPlusBundleID], "Wrong DriveWire fixture peer identities")
|
||||
try require(vcc.teamID.isEmpty && dw.teamID.isEmpty, "Authored fixture unexpectedly configured publisher trust")
|
||||
print("DIAGNOSTIC no publisher team is configured; signed companion authentication fails closed")
|
||||
do {
|
||||
try CompanionTransport.validateApplication(at: Bundle.main.bundleURL, permittedBundleIDs: [CompanionValidation.vccPlusBundleID])
|
||||
throw NSError(domain: "CompanionValidationChecks", code: 3, userInfo: [NSLocalizedDescriptionKey: "Unconfigured trust accepted a companion"])
|
||||
} catch CompanionTransport.Failure.untrustedPeer { }
|
||||
} else {
|
||||
try require(CompanionValidation.root == nil && CompanionValidation.vccApplicationURL == nil, "Disabled validation exposed fixture values")
|
||||
let fixtureIdentity = [CompanionValidation.vccPlusBundleID, CompanionValidation.driveWireBundleID].contains(Bundle.main.bundleIdentifier ?? "")
|
||||
if CompanionValidation.requested || fixtureIdentity {
|
||||
do {
|
||||
_ = try CompanionValidation.configuration(forVCCPlus: true)
|
||||
throw NSError(domain: "CompanionValidationChecks", code: 2, userInfo: [NSLocalizedDescriptionKey: "Invalid fixture fell through to production"])
|
||||
} catch CompanionTransport.Failure.unsafeEndpoint { }
|
||||
catch CompanionTransport.Failure.untrustedPeer { }
|
||||
} else {
|
||||
let config = try CompanionValidation.configuration(forVCCPlus: true)
|
||||
try require(config.socketPath == CompanionTransport.Configuration.production.socketPath, "Normal launch endpoint changed")
|
||||
}
|
||||
}
|
||||
print("PASS \(Bundle.main.bundleIdentifier ?? "unbundled") enabled=\(CompanionValidation.enabled) requested=\(CompanionValidation.requested)")
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/zsh
|
||||
set -euo pipefail
|
||||
repo_dir="${0:A:h:h:h:h}"
|
||||
check_dir="$(mktemp -d /private/tmp/vcc-transport-checks.XXXXXX)"
|
||||
trap 'rm -rf "$check_dir"' EXIT
|
||||
export DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}"
|
||||
xcrun swiftc -swift-version 6 -strict-concurrency=complete \
|
||||
-module-cache-path "$check_dir/module-cache" -D VCC_COMPANION_TESTING -parse-as-library \
|
||||
"$repo_dir/platforms/macos/Companion/CompanionTransport.swift" \
|
||||
"$repo_dir/tests/macos/companion/TransportChecks.swift" -o "$check_dir/checks"
|
||||
"$check_dir/checks"
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Authored Foundation-only bundle fixtures; no NSApplication, UI, sockets or personal data."""
|
||||
from pathlib import Path
|
||||
import os, plistlib, shutil, subprocess, tempfile
|
||||
|
||||
repo = Path(__file__).resolve().parents[3]
|
||||
with tempfile.TemporaryDirectory(prefix="vcc-cv-", dir="/private/tmp") as folder:
|
||||
work = Path(folder)
|
||||
env = dict(os.environ, DEVELOPER_DIR=os.environ.get("DEVELOPER_DIR", "/Applications/Xcode.app/Contents/Developer"))
|
||||
def compile(name, debug):
|
||||
target = work / name
|
||||
command = ["xcrun", "swiftc", "-swift-version", "6", "-strict-concurrency=complete", "-module-cache-path", str(work / "module-cache"), "-parse-as-library"]
|
||||
if debug: command += ["-D", "DEBUG"]
|
||||
command += [str(repo / "platforms/macos/Companion/CompanionTransport.swift"),
|
||||
str(repo / "platforms/macos/Companion/CompanionValidation.swift"),
|
||||
str(repo / "tests/macos/companion/ValidationChecks.swift"), "-o", str(target)]
|
||||
subprocess.run(command, env=env, check=True)
|
||||
return target
|
||||
debug, release = compile("debug", True), compile("release", False)
|
||||
def bundle(name, identifier, executable=debug):
|
||||
root = work / (name + ".app")
|
||||
contents = root / "Contents"
|
||||
(contents / "MacOS").mkdir(parents=True)
|
||||
(contents / "Info.plist").write_bytes(plistlib.dumps({"CFBundleIdentifier": identifier, "CFBundleExecutable": "check", "CFBundlePackageType": "APPL"}))
|
||||
shutil.copyfile(executable, contents / "MacOS/check")
|
||||
(contents / "MacOS/check").chmod(0o700)
|
||||
return root
|
||||
vcc = bundle("VCC", "com.brianholman.vccplus.oss.mac.uitesting")
|
||||
dw = bundle("DriveWire", "com.brianholman.vccplus.oss.drivewire.companionpreview")
|
||||
production = bundle("Production", "com.brianholman.vccplus.oss.mac")
|
||||
rel = bundle("Release", "com.brianholman.vccplus.oss.mac.uitesting", release)
|
||||
private = work / "private"; private.mkdir(mode=0o700)
|
||||
public = work / "public"; public.mkdir(mode=0o755)
|
||||
symlink = work / "linked"; symlink.symlink_to(private)
|
||||
base = ["--companion-validation-root", str(private)]
|
||||
def run(app, args): subprocess.run([str(app / "Contents/MacOS/check")] + args, check=True)
|
||||
run(vcc, base + ["--expect-enabled"])
|
||||
run(dw, base + ["--expect-enabled", "--companion-validation-peer", str(vcc)])
|
||||
run(vcc, [])
|
||||
run(production, [])
|
||||
run(production, base)
|
||||
run(rel, base)
|
||||
run(vcc, ["--companion-validation-root", str(public)])
|
||||
run(vcc, ["--companion-validation-root", str(symlink)])
|
||||
run(vcc, ["--companion-validation-root"])
|
||||
run(vcc, base + base)
|
||||
run(dw, base + ["--companion-validation-peer", str(production)])
|
||||
@@ -0,0 +1,100 @@
|
||||
// Replay encoded updates with the documented CoWin cursor, immediate wrapping
|
||||
// and insert-line behavior. A scroll on the last row is always a test failure.
|
||||
#include "DriveWireCoWin.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
|
||||
using namespace VCC::Mac;
|
||||
|
||||
struct GuestWindow {
|
||||
TerminalGrid cells{};
|
||||
int x = 0, y = 0;
|
||||
bool visible = true;
|
||||
|
||||
void receive(const std::vector<std::uint8_t>& bytes) {
|
||||
for (std::size_t i = 0; i < bytes.size(); ++i) {
|
||||
const auto ch = bytes.at(i);
|
||||
switch (ch) {
|
||||
case 0x0c:
|
||||
for (auto& row : cells) row.fill(' ');
|
||||
x = y = 0;
|
||||
break;
|
||||
case 0x02:
|
||||
x = bytes.at(++i) - 32;
|
||||
y = bytes.at(++i) - 32;
|
||||
assert(x >= 0 && x < 80 && y >= 0 && y < 24);
|
||||
break;
|
||||
case 0x05: {
|
||||
const auto mode = bytes.at(++i);
|
||||
assert(mode == 0x20 || mode == 0x21);
|
||||
visible = mode == 0x21;
|
||||
break;
|
||||
}
|
||||
case 0x1f:
|
||||
assert(bytes.at(++i) == 0x30);
|
||||
for (int r = 23; r > y; --r) cells[r] = cells[r - 1];
|
||||
cells[y].fill(' ');
|
||||
break;
|
||||
default:
|
||||
assert(ch >= 0x20 && ch <= 0x7e);
|
||||
cells.at(y).at(x++) = static_cast<char>(ch);
|
||||
if (x == 80) {
|
||||
x = 0;
|
||||
++y;
|
||||
assert(y < 24);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
DriveWireTerminalOutput display;
|
||||
GuestWindow guest;
|
||||
for (auto& row : guest.cells) row.fill('@'); // unknown console before vi
|
||||
TerminalGrid desired;
|
||||
for (auto& row : desired) row.fill(' ');
|
||||
auto roundTrip = [&](int x, int y, bool visible, bool clear = false) {
|
||||
std::vector<std::uint8_t> bytes;
|
||||
display.draw(desired, x, y, visible, clear, bytes);
|
||||
assert(bytes.size() <= DriveWireTerminalOutput::maxDrawBytes);
|
||||
guest.receive(bytes);
|
||||
assert(guest.cells == desired);
|
||||
assert(guest.x == x && guest.y == y && guest.visible == visible);
|
||||
return bytes.size();
|
||||
};
|
||||
roundTrip(0, 0, true, true);
|
||||
desired[0][0] = 'A';
|
||||
desired[22][79] = 'B';
|
||||
desired[23][79] = 'C';
|
||||
roundTrip(79, 23, false);
|
||||
assert(roundTrip(79, 23, false) == 0);
|
||||
assert(roundTrip(0, 0, false) == 3);
|
||||
assert(roundTrip(0, 0, true) == 2);
|
||||
desired[23][0] = 'D';
|
||||
assert(roundTrip(0, 0, true) == 7);
|
||||
|
||||
// Exercise runs separated by every possible small gap, dense repaints,
|
||||
// right-edge clearing and cursor-only changes.
|
||||
std::mt19937 random(789);
|
||||
for (int frame = 0; frame < 400; ++frame) {
|
||||
const int spacing = 1 + frame % 8;
|
||||
for (auto& row : desired) {
|
||||
for (int x = frame % spacing; x < 80; x += spacing) {
|
||||
row[x] = static_cast<char>(' ' + random() % 95);
|
||||
}
|
||||
}
|
||||
roundTrip(random() % 80, random() % 24, frame % 2 != 0, frame % 41 == 0);
|
||||
}
|
||||
|
||||
// A malformed parser cell must never inject Telnet IAC or a CoWin control.
|
||||
desired[0][0] = static_cast<char>(255);
|
||||
desired[0][1] = 27;
|
||||
std::vector<std::uint8_t> bytes;
|
||||
display.draw(desired, 0, 0, true, false, bytes);
|
||||
guest.receive(bytes);
|
||||
assert(guest.cells[0][0] == '?' && guest.cells[0][1] == '?');
|
||||
std::cout << "CoWin bounded differential output passed\n";
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Run the optional, isolated NitrOS-9 telnet probe against a local TCP service."""
|
||||
import argparse
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def receive_through(connection, marker):
|
||||
data = bytearray()
|
||||
while marker not in data:
|
||||
chunk = connection.recv(256)
|
||||
if not chunk or len(data) > 4096:
|
||||
raise RuntimeError(f"Guest failed to send {marker!r}: {bytes(data)!r}")
|
||||
data.extend(chunk)
|
||||
|
||||
|
||||
def serve(listener, task):
|
||||
# Poll so a failed guest boot can return immediately, even before accept.
|
||||
listener.settimeout(0.25)
|
||||
for session in (b"1", b"2"):
|
||||
while task.poll() is None:
|
||||
try:
|
||||
connection, _ = listener.accept()
|
||||
break
|
||||
except socket.timeout:
|
||||
continue
|
||||
else:
|
||||
raise RuntimeError("Guest exited without establishing both connections")
|
||||
with connection:
|
||||
connection.settimeout(25)
|
||||
receive_through(connection, b"localpayload" + session)
|
||||
connection.sendall(b"\r\nremoteack" + session + b"\r\n")
|
||||
receive_through(connection, b"goodbye" + session)
|
||||
|
||||
|
||||
def check(probe, resources, work):
|
||||
for processor in ("6809", "6309"):
|
||||
edit = work / ("edit" + processor)
|
||||
lines = [f"line{n:02d}" for n in range(1, 41)]
|
||||
edit.write_text("\n".join(lines) + "\n", encoding="ascii")
|
||||
with socket.socket() as listener, ThreadPoolExecutor(max_workers=1) as worker:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
with subprocess.Popen([probe, resources,
|
||||
str(listener.getsockname()[1]), processor, edit]) as child:
|
||||
result = worker.submit(serve, listener, child)
|
||||
try:
|
||||
if child.wait(timeout=160) != 0:
|
||||
raise SystemExit(f"{processor} guest probe failed")
|
||||
result.result()
|
||||
expected = "\n".join(lines[:-3] + ["lLRe38", "lDne39", "typedfromcoco", "final"]) + "\n"
|
||||
if edit.read_bytes() != expected.encode("ascii"):
|
||||
raise RuntimeError(f"{processor}: vi did not save the expected file")
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.kill()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("probe", type=Path)
|
||||
parser.add_argument("resources", type=Path, help="LocalResources containing private ROMs and Media")
|
||||
args = parser.parse_args()
|
||||
prepare = Path(__file__).resolve().parents[2] / "platforms/macos/Tools/prepare-nitros9.py"
|
||||
source = args.resources.resolve()
|
||||
image = Path("Media/NitrOS-9 L2 V3.3.0.vhd")
|
||||
with tempfile.TemporaryDirectory(prefix="vcc-drivewire-guest-") as temporary:
|
||||
resources = Path(temporary)
|
||||
(resources / "ROMs").symlink_to(source / "ROMs", target_is_directory=True)
|
||||
(resources / "Media").mkdir()
|
||||
subprocess.run([sys.executable, prepare, source / image, resources / image], check=True)
|
||||
with tempfile.TemporaryDirectory(prefix="vccvi", dir="/tmp") as scratch:
|
||||
check(args.probe.resolve(), resources, Path(scratch))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,204 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional real-ROM validation. Inputs remain read-only and HD0 writes are in memory.
|
||||
#include "MachineSession.h"
|
||||
#include "DriveWireEndpoint.h"
|
||||
#include "../devices/DriveWireTransport.h"
|
||||
#include "../devices/FD502/Fd502Device.h"
|
||||
#include "../devices/HardDisk/HardDiskDevice.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using VCC::Mac::MachineSession;
|
||||
|
||||
namespace {
|
||||
std::vector<std::uint8_t> load(const std::string& path) {
|
||||
std::ifstream file(path, std::ios::binary);
|
||||
if (!file) throw std::runtime_error("Could not open " + path);
|
||||
return {std::istreambuf_iterator<char>(file), {}};
|
||||
}
|
||||
|
||||
std::uint64_t key(char character) {
|
||||
unsigned position;
|
||||
if (character >= 'a' && character <= 'z') position = character - 'a' + 1;
|
||||
else if (character >= '0' && character <= '9') position = character - '0' + 32;
|
||||
else if (character >= 'A' && character <= 'Z')
|
||||
return (std::uint64_t{1} << 55) | (std::uint64_t{1} << (character - 'A' + 1));
|
||||
else if (character == '_') return (std::uint64_t{1} << 52) | (std::uint64_t{1} << 45);
|
||||
else if (character == '-') position = 45;
|
||||
else if (character == ':') position = 42;
|
||||
else if (character == '\x1b') position = 50; // Mac Escape selects CoCo Break.
|
||||
else if (character == '/') position = 47;
|
||||
else if (character == '.') position = 46;
|
||||
else if (character == ' ') position = 31;
|
||||
else if (character == '\r') position = 48;
|
||||
else throw std::runtime_error("Unsupported key in test input");
|
||||
return std::uint64_t{1} << position;
|
||||
}
|
||||
|
||||
void frames(MachineSession& machine, unsigned count) {
|
||||
while (count--) machine.advance();
|
||||
}
|
||||
|
||||
void press(MachineSession& machine, std::uint64_t keys) {
|
||||
machine.setKeyboard(keys);
|
||||
frames(machine, 4);
|
||||
machine.setKeyboard(0);
|
||||
frames(machine, 4);
|
||||
}
|
||||
|
||||
void typeText(MachineSession& machine, const std::string& text) {
|
||||
for (char c : text) press(machine, key(c));
|
||||
}
|
||||
|
||||
void typeLine(MachineSession& machine, const std::string& line) {
|
||||
typeText(machine, line + "\r");
|
||||
}
|
||||
|
||||
void waitFor(MachineSession& machine, const std::string& expected) {
|
||||
using namespace std::chrono;
|
||||
const auto deadline = steady_clock::now() + seconds(20);
|
||||
std::string text;
|
||||
do {
|
||||
frames(machine, 20);
|
||||
try { text = machine.copyScreenText(); } catch (const std::logic_error&) { /* Graphics during boot. */ }
|
||||
if (text.find(expected) != std::string::npos) return;
|
||||
std::this_thread::sleep_for(milliseconds(1));
|
||||
} while (steady_clock::now() < deadline);
|
||||
throw std::runtime_error("Timed out waiting for " + expected + "\nGuest display:\n" + text);
|
||||
}
|
||||
|
||||
void checkVi(MachineSession& machine, const std::string& path) {
|
||||
// This name is typed into the shell. Accept only the runner's private,
|
||||
// simple path so this test can never interpolate shell punctuation.
|
||||
if (path.rfind("/tmp/vccvi", 0) != 0 ||
|
||||
path.find_first_not_of("abcdefghijklmnopqrstuvwxyz0123456789/_") != std::string::npos ||
|
||||
path.size() > 55) throw std::invalid_argument("Unexpected vi test path");
|
||||
|
||||
typeLine(machine, "/usr/bin/vi -u NONE -i NONE -n " + path);
|
||||
waitFor(machine, "line01");
|
||||
typeText(machine, "G");
|
||||
waitFor(machine, "line40");
|
||||
if (machine.copyScreenText().find("line01") != std::string::npos)
|
||||
throw std::runtime_error("vi did not scroll the first line off the CoCo screen");
|
||||
|
||||
typeText(machine, "dd");
|
||||
typeText(machine, "kj0llhrx"); // vi cursor keys; change the i in line39 to x.
|
||||
waitFor(machine, "lxne39");
|
||||
// Option-Arrow on Mac uses the CoCo ALT key and a cursor-key position.
|
||||
const auto option = std::uint64_t{1} << 51;
|
||||
auto optionArrow = [&](unsigned position) {
|
||||
press(machine, option | (std::uint64_t{1} << position));
|
||||
};
|
||||
optionArrow(27); // Up one line, retaining the column.
|
||||
typeText(machine, "rU");
|
||||
optionArrow(30); // Right
|
||||
typeText(machine, "rR");
|
||||
optionArrow(29); // Left
|
||||
typeText(machine, "rL");
|
||||
optionArrow(28); // Down
|
||||
typeText(machine, "rD");
|
||||
typeText(machine, "otypedfromcoco\rfinal");
|
||||
waitFor(machine, "typedfromcoco\nfinal");
|
||||
std::cout << "vi edit on the CoCo screen:\n" << machine.copyScreenText() << std::flush;
|
||||
typeText(machine, "\x1b"); // the physical Mac Escape key via the CoCo keyboard
|
||||
typeLine(machine, ":wq");
|
||||
typeLine(machine, "echo editorsaved");
|
||||
waitFor(machine, "\neditorsaved\n");
|
||||
typeLine(machine, "clear");
|
||||
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(15);
|
||||
std::string screen;
|
||||
do {
|
||||
frames(machine, 20);
|
||||
screen = machine.copyScreenText();
|
||||
const auto first = screen.find_first_not_of(" \n");
|
||||
if (first != std::string::npos && screen.substr(first) == "$\n") {
|
||||
std::cout << "After clear: " << screen.substr(first) << std::flush;
|
||||
return;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
} while (std::chrono::steady_clock::now() < deadline);
|
||||
throw std::runtime_error("Expected only the shell prompt after clear:\n" + screen);
|
||||
}
|
||||
|
||||
void check(const std::string& local, const std::string& port, VCC::Mac::Processor processor,
|
||||
const std::string& viPath) {
|
||||
using namespace VCC::Devices;
|
||||
// A real shell, with startup scripts and history isolated from the developer.
|
||||
VCC::Mac::DriveWireShell shell(VCC::Mac::DriveWireShell::StartupFiles::isolatedTest);
|
||||
const DriveWireFactory endpoint = [&shell](const std::string& host, std::uint16_t port) {
|
||||
return VCC::Mac::openDriveWireEndpoint(shell, host, port);
|
||||
};
|
||||
MachineSession machine;
|
||||
auto hard = std::make_shared<HardDiskDevice>();
|
||||
hard->mount(0, HardDiskImage(load(local + "/Media/NitrOS-9 L2 V3.3.0.vhd")));
|
||||
auto floppy = std::make_shared<Fd502Device>(load(local + "/ROMs/rgbdos.rom"));
|
||||
machine.cartridges().configure({nullptr, hard, nullptr, nullptr, floppy}, true, 4);
|
||||
machine.load(load(local + "/ROMs/coco3.rom"), processor);
|
||||
const bool enabledAtStartup = processor == VCC::Mac::Processor::HD6309;
|
||||
if (enabledAtStartup) machine.setDriveWireFactory(endpoint);
|
||||
machine.requestNitros9Boot();
|
||||
machine.resume();
|
||||
waitFor(machine, "{Term|02}/DD:");
|
||||
if (machine.copyScreenText().find("ERROR #") != std::string::npos)
|
||||
throw std::runtime_error("OS-9 startup reported an error: " + machine.copyScreenText());
|
||||
if (!enabledAtStartup) machine.setDriveWireFactory(endpoint);
|
||||
for (auto session : {"1", "2"}) {
|
||||
const std::string suffix(session);
|
||||
// Give each connection its own screen so the previous prompt and
|
||||
// disconnect message cannot satisfy the next session's assertions.
|
||||
typeLine(machine, "display 0c");
|
||||
frames(machine, 100);
|
||||
typeLine(machine, "telnet 127.0.0.1 " + port);
|
||||
waitFor(machine, "Escape character");
|
||||
typeLine(machine, "localpayload" + suffix);
|
||||
waitFor(machine, "remoteack" + suffix);
|
||||
typeLine(machine, "goodbye" + suffix);
|
||||
waitFor(machine, "Connection closed by foreign host.");
|
||||
frames(machine, 100);
|
||||
}
|
||||
|
||||
typeLine(machine, "display 0c");
|
||||
frames(machine, 100);
|
||||
const bool startFromMac = processor == VCC::Mac::Processor::MC6809;
|
||||
if (startFromMac) shell.arm();
|
||||
typeLine(machine, "telnet macshell 2323");
|
||||
if (!startFromMac) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
|
||||
while (!shell.requestID() && std::chrono::steady_clock::now() < deadline) frames(machine, 20);
|
||||
if (!shell.decide(shell.requestID(), true))
|
||||
throw std::runtime_error("No guest-initiated Mac shell request to approve");
|
||||
}
|
||||
waitFor(machine, "Escape character");
|
||||
typeLine(machine, "/usr/bin/uname");
|
||||
waitFor(machine, "Darwin");
|
||||
checkVi(machine, viPath);
|
||||
typeLine(machine, "exit");
|
||||
waitFor(machine, "Connection closed by foreign host.\n{Term|02}/DD:");
|
||||
if (shell.status() != "idle")
|
||||
throw std::runtime_error("Mac shell invitation was still active after exit");
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) try {
|
||||
if (argc != 5 || (std::string(argv[3]) != "6809" && std::string(argv[3]) != "6309")) {
|
||||
std::cerr << "Usage: drivewire-guest LOCAL_RESOURCES ECHO_PORT 6809|6309 TEMPORARY_VI_FILE\n";
|
||||
return 2;
|
||||
}
|
||||
const auto processor = std::string(argv[3]) == "6809" ? VCC::Mac::Processor::MC6809 : VCC::Mac::Processor::HD6309;
|
||||
check(argv[1], argv[2], processor, argv[4]);
|
||||
std::cout << "PASS: stock NitrOS-9 telnet exchanged data, reconnected and edited and saved in vi on the Mac shell on " << argv[3] << '\n';
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Standalone native check; invokes an isolated shell without user startup files.
|
||||
#include "DriveWireShell.h"
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <signal.h>
|
||||
|
||||
using VCC::Mac::DriveWireShell;
|
||||
using Transport = VCC::Devices::DriveWireTransport;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
static void require(bool ok, const char* reason) {
|
||||
if (!ok) throw std::runtime_error(reason);
|
||||
}
|
||||
|
||||
template <class F> static void waitFor(F test, const char* reason) {
|
||||
auto deadline = std::chrono::steady_clock::now() + 8s;
|
||||
do {
|
||||
if (test()) return;
|
||||
std::this_thread::sleep_for(10ms);
|
||||
} while (std::chrono::steady_clock::now() < deadline);
|
||||
throw std::runtime_error(reason);
|
||||
}
|
||||
|
||||
static void send(Transport& channel, const std::string& text) {
|
||||
require(channel.write(reinterpret_cast<const std::uint8_t*>(text.data()), text.size()), "Shell write failed");
|
||||
}
|
||||
|
||||
static std::string readThrough(Transport& channel, const std::string& marker) {
|
||||
std::string text;
|
||||
waitFor([&]{
|
||||
std::uint8_t bytes[1024];
|
||||
auto count = channel.read(bytes, sizeof bytes);
|
||||
text.append(reinterpret_cast<const char*>(bytes), count);
|
||||
if (channel.state() == Transport::State::failed) throw std::runtime_error("Shell failed to start");
|
||||
return text.find(marker) != std::string::npos;
|
||||
}, "Shell output did not match");
|
||||
return text;
|
||||
}
|
||||
|
||||
int main() try {
|
||||
DriveWireShell shell(DriveWireShell::StartupFiles::isolatedTest);
|
||||
require(shell.status() == "idle", "Unexpected initial status");
|
||||
auto denied = shell.connect();
|
||||
auto id = shell.requestID();
|
||||
require(id && denied && shell.status() == "requested", "Missing permission request");
|
||||
require(denied->state() == Transport::State::connecting && !shell.connect(), "Unapproved session is usable");
|
||||
require(shell.decide(id, false) && denied->state() == Transport::State::failed, "Deny failed");
|
||||
|
||||
auto abandoned = shell.connect();
|
||||
auto abandonedId = shell.requestID();
|
||||
require(abandonedId != id && !shell.decide(id, true), "Stale decision accepted");
|
||||
abandoned.reset();
|
||||
require(shell.status() == "idle" && !shell.decide(abandonedId, true), "Disconnected request was actionable");
|
||||
|
||||
auto requested = shell.connect();
|
||||
require(shell.decide(shell.requestID(), true), "Approval failed");
|
||||
require(!shell.decide(abandonedId, true), "Old request revived");
|
||||
waitFor([&]{return requested->state() == Transport::State::connected;}, "Approved shell failed to start");
|
||||
send(*requested, "test -t 0 && test -t 1 && printf 'shell-pid=%d; cwd-test=%s; term=%s; tty=%s\\n' \"$$\" \"$(test \"$PWD\" = \"$HOME\" && echo yes)\" \"$TERM\" \"yes\"\r");
|
||||
auto output = readThrough(*requested, "; cwd-test=yes; term=vt100; tty=yes");
|
||||
auto pos = output.rfind("shell-pid=", output.rfind("; cwd-test=yes"));
|
||||
require(pos != std::string::npos, "Missing shell pid");
|
||||
pid_t child = std::stoi(output.substr(pos + 10));
|
||||
require(child > 1, "Invalid child pid");
|
||||
send(*requested,"printf 'terminal-%s\\n' \"$(tty </dev/tty)\"\r");
|
||||
readThrough(*requested,"terminal-/dev/tty");
|
||||
send(*requested, "printf 'style:\\033[31mred\\033[0m\\033]0;hide'; sleep 0.05; printf 'me\\007\\001\\342\\236\\234:ok\\n'\r");
|
||||
auto filtered = readThrough(*requested, "style:red?:ok");
|
||||
require(filtered.find('\x1b') == std::string::npos, "Mac terminal controls reached the CoCo");
|
||||
send(*requested, "printf 'dimensions-%s\\n' \"$(stty size)\"\r");
|
||||
readThrough(*requested, "dimensions-24 80");
|
||||
// Let the child fill the bounded PTY/output queues before draining them.
|
||||
send(*requested, "awk 'BEGIN {for (i=1;i<=8000;i++) print \"scroll-test\"; print \"drained-\" 8000}'\r");
|
||||
std::this_thread::sleep_for(100ms);
|
||||
readThrough(*requested, "drained-8000");
|
||||
const std::string excessive(65537, 'x');
|
||||
require(!requested->write(reinterpret_cast<const std::uint8_t*>(excessive.data()), excessive.size()),
|
||||
"Oversized guest input was accepted");
|
||||
send(*requested, "sh -c 'trap \"\" HUP; printf \"foreground-%d-active\\n\" \"$$\"; exec sleep 30'\r");
|
||||
std::string foregroundOutput;
|
||||
pid_t foreground = -1;
|
||||
waitFor([&]{
|
||||
std::uint8_t bytes[1024];
|
||||
foregroundOutput.append(reinterpret_cast<const char*>(bytes), requested->read(bytes, sizeof bytes));
|
||||
auto offset = foregroundOutput.rfind("foreground-");
|
||||
if (offset == std::string::npos || offset + 11 >= foregroundOutput.size()) return false;
|
||||
char* end = nullptr;
|
||||
auto candidate = std::strtol(foregroundOutput.c_str() + offset + 11, &end, 10);
|
||||
if (candidate <= 1 || std::string(end).rfind("-active", 0) != 0) return false;
|
||||
foreground = static_cast<pid_t>(candidate);
|
||||
return true;
|
||||
}, "Foreground job failed to start");
|
||||
shell.stop();
|
||||
require(shell.status() == "idle", "Stop did not revoke permission");
|
||||
waitFor([&]{return kill(child, 0) == -1 && errno == ESRCH;}, "Stopped shell was not reaped");
|
||||
waitFor([&]{return kill(foreground, 0) == -1 && errno == ESRCH;}, "Foreground job survived an explicit stop");
|
||||
shell.arm();
|
||||
require(shell.status() == "ready" && shell.requestID() == 0, "Manual start did not arm");
|
||||
auto explicitSession = shell.connect();
|
||||
waitFor([&]{return explicitSession->state() == Transport::State::connected;}, "Manual session failed to start");
|
||||
require(shell.status() == "connected" && !shell.connect(), "Multiple active sessions accepted");
|
||||
send(*explicitSession, "printf 'end-%s\\n' marker; exit\r");
|
||||
readThrough(*explicitSession, "end-marker");
|
||||
waitFor([&]{return explicitSession->state() == Transport::State::closed;}, "Logout did not close the PTY");
|
||||
require(shell.status() == "idle", "Shell did not release the session");
|
||||
auto later = shell.connect();
|
||||
require(later->state() == Transport::State::connecting && shell.status() == "requested", "Invitation reused");
|
||||
shell.stop();
|
||||
require(later->state() == Transport::State::failed, "Cancelled request did not fail");
|
||||
std::cout << "DriveWire shell permission lifetime, PTY, stop, logout and reaping passed.\n";
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Build from the project root with:
|
||||
// clang++ -std=c++17 -fobjc-arc -Isrc platforms/macos/Bridge/DriveWireTCP.mm \
|
||||
// tests/macos/drivewire-tcp-probe.mm -framework Network -framework Foundation -o /tmp/vcc-dw-tcp-probe
|
||||
// The listener below is a test fixture bound exclusively to IPv4 loopback.
|
||||
#include "devices/DriveWireTransport.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using namespace VCC::Devices;
|
||||
|
||||
static void require(bool condition, const char* description) {
|
||||
if (!condition) {
|
||||
std::fprintf(stderr, "Failure: %s\n", description);
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
template<class Check>
|
||||
static void waitFor(Check check, const char* description) {
|
||||
auto deadline = std::chrono::steady_clock::now() + 8s;
|
||||
while (!check()) {
|
||||
require(std::chrono::steady_clock::now() < deadline, description);
|
||||
std::this_thread::sleep_for(2ms);
|
||||
}
|
||||
}
|
||||
|
||||
static void sendAll(int client, const uint8_t* data, size_t size) {
|
||||
while (size) {
|
||||
auto written = send(client, data, size, 0);
|
||||
require(written > 0, "fixture could not send data");
|
||||
data += written;
|
||||
size -= written;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
require(listener >= 0, "create loopback socket");
|
||||
sockaddr_in address{};
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
require(bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0, "bind loopback");
|
||||
require(listen(listener, 2) == 0, "listen on loopback");
|
||||
socklen_t length = sizeof(address);
|
||||
require(getsockname(listener, reinterpret_cast<sockaddr*>(&address), &length) == 0, "get dynamic port");
|
||||
uint16_t port = ntohs(address.sin_port);
|
||||
std::vector<uint8_t> burst(160 * 1024);
|
||||
for (size_t i = 0; i < burst.size(); ++i) burst[i] = static_cast<uint8_t>(i * 37);
|
||||
const std::array<uint8_t, 4> message{0, 0xff, 'A', '\r'};
|
||||
|
||||
std::thread fixture([&] {
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
int client = accept(listener, nullptr, nullptr);
|
||||
require(client >= 0, "accept loopback connection");
|
||||
std::array<uint8_t, 4> received{};
|
||||
require(recv(client, received.data(), received.size(), MSG_WAITALL) == sizeof(received), "receive message");
|
||||
require(received == message, "order and binary transparency on write");
|
||||
sendAll(client, received.data(), received.size());
|
||||
if (pass == 1) sendAll(client, burst.data(), burst.size());
|
||||
close(client);
|
||||
}
|
||||
});
|
||||
|
||||
using State = DriveWireTransport::State;
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
auto stream = makeDriveWireTCPConnection("127.0.0.1", port);
|
||||
require(stream != nullptr, "construct stream");
|
||||
waitFor([&] { return stream->state() == State::connected; }, "connection becomes ready");
|
||||
require(!stream->write(burst.data(), burst.size()), "reject oversized write atomically");
|
||||
for (auto byte : message) require(stream->write(&byte, 1), "write guest byte");
|
||||
|
||||
if (!pass) waitFor([&] { return stream->state() == State::closed; }, "observe peer EOF before reading");
|
||||
std::vector<uint8_t> actual;
|
||||
std::array<uint8_t, 513> chunk{};
|
||||
std::vector<uint8_t> expected(message.begin(), message.end());
|
||||
if (pass) expected.insert(expected.end(), burst.begin(), burst.end());
|
||||
waitFor([&] {
|
||||
size_t count;
|
||||
while ((count = stream->read(chunk.data(), chunk.size()))) {
|
||||
actual.insert(actual.end(), chunk.begin(), chunk.begin() + count);
|
||||
}
|
||||
return stream->state() == State::closed && actual.size() == expected.size();
|
||||
}, "drain all buffered bytes and receive EOF");
|
||||
require(actual == expected, "echo and large response survive buffering and EOF");
|
||||
require(!stream->write(message.data(), message.size()), "writes fail after closure");
|
||||
}
|
||||
fixture.join();
|
||||
close(listener);
|
||||
auto refused = makeDriveWireTCPConnection("127.0.0.1", port);
|
||||
require(refused != nullptr, "construct refused connection");
|
||||
waitFor([&] { return refused->state() == State::failed; }, "asynchronous connection refusal");
|
||||
auto canceled = makeDriveWireTCPConnection("127.0.0.1", port);
|
||||
canceled.reset();
|
||||
std::puts("DriveWire outbound TCP: echo, backpressure, EOF, reconnect, refusal and cancellation passed");
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Receives the same byte stream that the stock NitrOS-9 telnet client writes.
|
||||
#include "DriveWireTerminal.h"
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
|
||||
namespace {
|
||||
using Bytes = std::vector<std::uint8_t>;
|
||||
using Grid = VCC::Mac::TerminalGrid;
|
||||
|
||||
struct CoWin {
|
||||
Grid lines;
|
||||
int x = 0, y = 0, clears = 0, chimes = 0;
|
||||
CoWin() { for (auto& line : lines) line.fill(' '); }
|
||||
std::string line(int row) const {
|
||||
return std::string(lines[row].begin(), lines[row].end());
|
||||
}
|
||||
void lf() {
|
||||
if (y < 23) ++y;
|
||||
else {
|
||||
std::move(lines.begin()+1, lines.end(), lines.begin());
|
||||
lines.back().fill(' ');
|
||||
}
|
||||
}
|
||||
void apply(const Bytes& bytes) {
|
||||
for (std::size_t i = 0; i < bytes.size(); ++i) {
|
||||
switch (int ch = bytes[i]) {
|
||||
case 2:
|
||||
x = bytes.at(++i)-32; y = bytes.at(++i)-32;
|
||||
assert(x >= 0 && x < 80 && y >= 0 && y < 24);
|
||||
break;
|
||||
case 4: std::fill(lines[y].begin()+x, lines[y].end(), ' '); break;
|
||||
case 5: assert(bytes.at(++i) == 0x21); break;
|
||||
case 6: if (x < 79) ++x; break;
|
||||
case 7: ++chimes; break;
|
||||
case 8: if (x > 0) --x; break;
|
||||
case 9: if (y > 0) --y; break;
|
||||
case 10: lf(); break;
|
||||
case 11:
|
||||
std::fill(lines[y].begin()+x, lines[y].end(), ' ');
|
||||
for (int row=y+1; row<24; ++row) lines[row].fill(' ');
|
||||
break;
|
||||
case 12: for (auto& row : lines) row.fill(' '); x=y=0; ++clears; break;
|
||||
case 13: x=0; break;
|
||||
case 0x1f:
|
||||
assert(bytes.at(++i) == 0x30);
|
||||
std::move_backward(lines.begin()+y, lines.end()-1, lines.end());
|
||||
lines[y].fill(' ');
|
||||
break;
|
||||
default:
|
||||
assert(ch >= 32 && ch <= 126);
|
||||
lines[y][x++] = static_cast<char>(ch);
|
||||
if (x == 80) { x=0; lf(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct Terminal {
|
||||
VCC::Mac::DriveWireTerminal host;
|
||||
CoWin guest;
|
||||
Bytes send(std::string_view source) {
|
||||
auto bytes = host.consume(reinterpret_cast<const std::uint8_t*>(source.data()), source.size());
|
||||
guest.apply(bytes);
|
||||
return bytes;
|
||||
}
|
||||
void fragmented(std::string_view source) {
|
||||
for (char ch : source) send(std::string_view(&ch,1));
|
||||
}
|
||||
};
|
||||
|
||||
void transcript() {
|
||||
Terminal t;
|
||||
t.guest.y = 8;
|
||||
t.guest.lines[3][0] = 'G';
|
||||
t.fragmented("Mac\x1b[31m shell\x1b[0m\r\n\t> ");
|
||||
assert(t.guest.clears == 0 && t.guest.lines[3][0]=='G');
|
||||
assert(t.guest.line(8).substr(0,9)=="Mac shell" && t.guest.line(9).substr(8,2)=="> ");
|
||||
t.fragmented("abc\b\b\x1b[Kx");
|
||||
assert(t.guest.line(9).substr(8,5)=="> ax ");
|
||||
t.fragmented("\x1b]0;private \xe2\x94\x9c title\x1b\\\x1bPignored\x1b\\\x1b[?2004h");
|
||||
t.fragmented("\xe2\x9e\x9c");
|
||||
assert(t.guest.line(9)[12]=='?');
|
||||
assert(t.send("\x1b[?25l").empty());
|
||||
t.fragmented("\x1b[?1h");
|
||||
assert(t.host.applicationCursor());
|
||||
t.fragmented("\x1b[?1l");
|
||||
assert(!t.host.applicationCursor());
|
||||
}
|
||||
|
||||
void editing() {
|
||||
Terminal t;
|
||||
t.fragmented("\x1b[2J\x1b[Habcde\x1b[1;2H\x1b[2@XY");
|
||||
assert(t.guest.line(0).substr(0,7)=="aXYbcde");
|
||||
t.send("\x1b[2P\x1b[X");
|
||||
assert(t.guest.line(0).substr(0,5)=="aXY e");
|
||||
t.send("\x1b[4h!\x1b[4l");
|
||||
assert(t.guest.line(0).substr(0,6)=="aXY! e");
|
||||
t.send("\x1b[1K");
|
||||
assert(t.guest.line(0).substr(0,6)==" e");
|
||||
t.send("\x1b[2K\x1b[2;2Hrow2\x1b[3;2Hrow3\x1b[4;2Hrow4");
|
||||
t.fragmented("\x1b[2;3r\x1b[3;1H\n");
|
||||
assert(t.guest.line(1).substr(1,4)=="row3" && t.guest.line(2)==std::string(80,' '));
|
||||
assert(t.guest.line(3).substr(1,4)=="row4");
|
||||
t.send("\x1b[2;1H\x1b[L");
|
||||
assert(t.guest.line(1)==std::string(80,' ') && t.guest.line(2).substr(1,4)=="row3");
|
||||
t.send("\x1b[M\x1b[?6h\x1b[1;1H*\x1b[6n");
|
||||
assert(t.guest.lines[1][0]=='*' && t.host.takeReply()=="\x1b[1;2R");
|
||||
t.send("\x1b[?6l\x1b[r\x1b[24;80H!\x1b[1;1HX");
|
||||
assert(t.guest.lines[0][0]=='X' && t.guest.lines[23][79]=='!');
|
||||
assert(t.send("\x1b[H" "X").empty()); // same contents and same final cursor
|
||||
}
|
||||
|
||||
void screens() {
|
||||
Terminal t;
|
||||
t.send("shell$ ");
|
||||
t.fragmented("\x1b[?1049h\x1b[24;1H-- INSERT --\x1b[HTitle\x1b" "7");
|
||||
assert(t.guest.line(0).substr(0,5)=="Title");
|
||||
assert(t.guest.line(23).substr(0,12)=="-- INSERT --");
|
||||
t.fragmented("\x1b[4;80HAZ\x1b" "8");
|
||||
assert(t.guest.lines[3][79]=='A' && t.guest.lines[4][0]=='Z');
|
||||
assert(t.guest.x==5 && t.guest.y==0);
|
||||
t.fragmented("\x1b[?7l\x1b[6;80HAB\x1b[?7h");
|
||||
assert(t.guest.lines[5][79]=='B' && t.guest.lines[6][0]==' ');
|
||||
t.send("\x1b[?1049l");
|
||||
assert(t.guest.line(0).substr(0,7)=="shell$ ");
|
||||
assert(t.guest.x==7 && t.guest.y==0);
|
||||
assert(t.send("pwd")==Bytes({'p','w','d'}));
|
||||
t.fragmented("\x1b[H\x1b)0\x0elqqk\x0f");
|
||||
assert(t.guest.line(0).substr(0,4)=="+--+");
|
||||
}
|
||||
|
||||
void malformed() {
|
||||
Terminal t;
|
||||
t.send("\x1b[H");
|
||||
t.send("\x1b[" + std::string(10000,'9') + "Hok");
|
||||
t.send("\x1b[" + std::string(10000,';') + "J");
|
||||
assert(t.guest.lines[23][0]=='o');
|
||||
t.send("\x1bP" + std::string(10000,'x') + "\x18!");
|
||||
assert(t.guest.lines[23][2]=='!');
|
||||
for (int i=0; i<1000; ++i) t.send("\x1b[5n");
|
||||
assert(t.host.takeReply().size() <= 128 && t.host.takeReply().empty());
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
transcript();
|
||||
editing();
|
||||
screens();
|
||||
malformed();
|
||||
std::cout << "DriveWire terminal transcript, screen edits, scrolling, alternate buffer, and fragmented input passed.\n";
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional real-ROM and disk check. Reads all host inputs without writing.
|
||||
// Supply a 256-byte sector whose absolute file offset was independently determined.
|
||||
// For example, use 17 1 109019 --dir SHAMUS with the original protected Shamus
|
||||
// DMK, or 17 3 157440 with S37H.VDK. The optional --fm-doubled flag describes
|
||||
// a single-density sector stored with two copies of each byte in a DMK track.
|
||||
// Link with the matching revision of libVCCCore.a, -Isrc -Isrc/core and
|
||||
// -Iplatforms/windows/libcommon, as with the other standalone guest probes.
|
||||
#include "MachineSession.h"
|
||||
#include "devices/FD502/Fd502Device.h"
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace VCC::Devices;
|
||||
using namespace VCC::Mac;
|
||||
using Bytes = std::vector<std::uint8_t>;
|
||||
|
||||
Bytes load(const char* path) {
|
||||
std::ifstream file(path, std::ios::binary);
|
||||
if (!file) throw std::runtime_error(std::string("Could not open ") + path);
|
||||
return Bytes(std::istreambuf_iterator<char>(file), {});
|
||||
}
|
||||
|
||||
void advance(MachineSession& machine, unsigned count) {
|
||||
while (count--) {
|
||||
machine.advance();
|
||||
machine.takeAudio();
|
||||
}
|
||||
}
|
||||
|
||||
void run(MachineSession& machine, const std::string& program, const std::string& expected) {
|
||||
machine.basicLoadSource("5 CLEAR 2048:CLS\n" + program, true);
|
||||
for (unsigned i = 0; i < 120; ++i) {
|
||||
advance(machine, 10);
|
||||
const auto text = machine.copyScreenText();
|
||||
if (text.find(expected) != std::string::npos && text.find("OK") != std::string::npos) {
|
||||
advance(machine, 10);
|
||||
return;
|
||||
}
|
||||
if (expected != "?WP ERROR" && text.find(" ERROR") != std::string::npos)
|
||||
throw std::runtime_error(text);
|
||||
}
|
||||
throw std::runtime_error("Timed out waiting for " + expected + ":\n" + machine.copyScreenText());
|
||||
}
|
||||
|
||||
void check(Processor cpu, const Bytes& systemROM, const Bytes& diskROM, const Bytes& original,
|
||||
const std::string& address, std::size_t offset, unsigned stride, const std::string& directoryEntry) {
|
||||
MachineSession machine;
|
||||
auto drive = std::make_shared<Fd502Device>(diskROM);
|
||||
drive->mount(0, DiskImage::load(original));
|
||||
machine.cartridges().configure({nullptr, nullptr, nullptr, nullptr, drive}, true, 4);
|
||||
MachineConfiguration config;
|
||||
config.frameInterval = 6;
|
||||
machine.configure(config);
|
||||
machine.load(systemROM, cpu);
|
||||
machine.resume();
|
||||
advance(machine, 300);
|
||||
if (machine.copyScreenText().find("OK") == std::string::npos)
|
||||
throw std::runtime_error("Disk BASIC did not boot");
|
||||
|
||||
const auto sectorBytes = 256 * stride;
|
||||
const auto storedBytes = sectorBytes + (drive->image(0)->format() == DiskFormat::DMK ? 2 * stride : 0);
|
||||
if (offset > original.size() || storedBytes > original.size() - offset)
|
||||
throw std::invalid_argument("Expected sector or CRC extends beyond the source");
|
||||
Bytes reference;
|
||||
for (unsigned i = 0; i < 256; ++i) reference.push_back(original[offset + i * stride]);
|
||||
const std::string read = "10 DSKI$ " + address + ",A$,B$\n"
|
||||
"20 FOR I=1 TO 128\n"
|
||||
"30 POKE 20479+I,ASC(MID$(A$,I,1))\n"
|
||||
"40 POKE 20607+I,ASC(MID$(B$,I,1))\n"
|
||||
"50 NEXT I\n60 PRINT \"READ COMPLETE\"\n";
|
||||
if (!directoryEntry.empty()) run(machine, "10 DIR\n", directoryEntry);
|
||||
run(machine, read, "READ COMPLETE");
|
||||
const auto fromGuest = machine.debuggerMemoryRange(20480, 256, false).bytes;
|
||||
if (fromGuest != reference)
|
||||
throw std::runtime_error("Disk BASIC read disagrees with the independently located file bytes");
|
||||
if (drive->image(0)->bytes() != original || !drive->readEvents(0))
|
||||
throw std::runtime_error("Guest read altered the source or bypassed the FD-502");
|
||||
|
||||
const std::string write = "10 A$=STRING$(128,65):B$=STRING$(128,66)\n"
|
||||
"20 DSKO$ " + address + ",A$,B$\n30 PRINT \"WRITE COMPLETE\"\n";
|
||||
if (drive->image(0)->writeProtected()) {
|
||||
run(machine, write, "?WP ERROR");
|
||||
if (drive->image(0)->bytes() != original || drive->writeEvents(0))
|
||||
throw std::runtime_error("Protected disk accepted a guest write");
|
||||
return;
|
||||
}
|
||||
run(machine, write, "WRITE COMPLETE");
|
||||
Bytes saved = drive->image(0)->bytes();
|
||||
if (saved.size() != original.size() || !drive->writeEvents(0))
|
||||
throw std::runtime_error("Guest write changed image length or bypassed the FD-502");
|
||||
Bytes expected(256, 'A');
|
||||
std::fill(expected.begin() + 128, expected.end(), 'B');
|
||||
for (unsigned i = 0; i < sectorBytes; ++i) {
|
||||
if (saved[offset + i] != expected[i / stride])
|
||||
throw std::runtime_error("Guest write missed the expected on-disk offset");
|
||||
}
|
||||
const auto after = offset + storedBytes;
|
||||
if (!std::equal(original.begin(), original.begin() + offset, saved.begin()) ||
|
||||
!std::equal(original.begin() + after, original.end(), saved.begin() + after))
|
||||
throw std::runtime_error("Guest write modified bytes outside the sector and its CRC");
|
||||
drive->markSaved(0);
|
||||
drive->eject(0);
|
||||
drive->mount(0, DiskImage::load(saved));
|
||||
run(machine, read, "READ COMPLETE");
|
||||
if (machine.debuggerMemoryRange(20480, 256, false).bytes != expected)
|
||||
throw std::runtime_error("Reopened disk did not contain the saved bytes");
|
||||
drive->setWriteProtected(0, true);
|
||||
const auto protectedBytes = drive->image(0)->bytes();
|
||||
run(machine, write, "?WP ERROR");
|
||||
if (drive->image(0)->bytes() != protectedBytes)
|
||||
throw std::runtime_error("Protected disk changed");
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) try {
|
||||
if (argc < 7) throw std::invalid_argument(
|
||||
"Usage: fd502-media-probe SYSTEM_ROM DISK_ROM IMAGE TRACK SECTOR FILE_OFFSET [--fm-doubled] [--dir ENTRY]");
|
||||
const auto systemROM = load(argv[1]);
|
||||
const auto diskROM = load(argv[2]);
|
||||
const auto original = load(argv[3]);
|
||||
const auto track = std::stoul(argv[4]), sector = std::stoul(argv[5]), offset = std::stoul(argv[6]);
|
||||
if (track > 255 || !sector || sector > 18)
|
||||
throw std::invalid_argument("Invalid Disk BASIC track or sector");
|
||||
std::string directoryEntry;
|
||||
unsigned stride = 1;
|
||||
for (int i = 7; i < argc; ++i) {
|
||||
const std::string option = argv[i];
|
||||
if (option == "--fm-doubled") stride = 2;
|
||||
else if (option == "--dir" && i + 1 < argc) directoryEntry = argv[++i];
|
||||
else throw std::invalid_argument("Invalid option: " + option);
|
||||
}
|
||||
const auto address = "0," + std::to_string(track) + "," + std::to_string(sector);
|
||||
for (auto cpu : {Processor::MC6809, Processor::HD6309}) {
|
||||
check(cpu, systemROM, diskROM, original, address, offset, stride, directoryEntry);
|
||||
std::cout << (cpu == Processor::MC6809 ? "6809" : "6309") << " passed Disk BASIC sector checks\n";
|
||||
}
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Optional private-ROM/game compatibility check; never changes input media.
|
||||
set -euo pipefail
|
||||
if [[ $# -lt 4 || $# -gt 5 ]]; then
|
||||
echo 'Usage: run-sdc-validation.sh SYSTEM_ROM SDC_ROM GAME_FOLDER OUTPUT_FOLDER [6809|6309|starter]' >&2
|
||||
exit 2
|
||||
fi
|
||||
repo_dir="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
build_dir="${VCC_SDC_BUILD_DIR:-${TMPDIR:-/tmp}/vcc-sdc-validation-build}"
|
||||
check_arch="${VCC_CHECK_ARCH:-$(uname -m)}"
|
||||
case "$check_arch" in arm64|x86_64) ;; *) echo 'VCC_CHECK_ARCH must be arm64 or x86_64' >&2; exit 2 ;; esac
|
||||
# Keep input/output references stable when changing to the repository.
|
||||
args=()
|
||||
for value in "$1" "$2" "$3" "$4"; do
|
||||
if [[ "$value" != /* ]]; then value="$PWD/$value"; fi
|
||||
args+=("$value")
|
||||
done
|
||||
if [[ $# == 5 ]]; then
|
||||
case "$5" in 6809|6309|starter) args+=("$5");; *) echo 'Mode must be 6809, 6309 or starter' >&2; exit 2;; esac
|
||||
fi
|
||||
mkdir -p "$build_dir"
|
||||
build_dir="$(cd "$build_dir" && pwd)"
|
||||
cd "$repo_dir"
|
||||
xcodebuild -project platforms/macos/VCC.xcodeproj -scheme VCCCoreChecks \
|
||||
-configuration Release -derivedDataPath "$build_dir" \
|
||||
SDK_STAT_CACHE_ENABLE=NO build > "$build_dir/build.log" 2>&1 || {
|
||||
tail -60 "$build_dir/build.log" >&2; exit 1;
|
||||
}
|
||||
xcrun clang++ -std=c++17 -O2 -arch "$check_arch" -mmacosx-version-min=14.0 \
|
||||
-Isrc/core -Isrc -Iplatforms/windows/libcommon tests/macos/sdc-validation.cpp \
|
||||
"$build_dir/Build/Products/Release/libVCCCore.a" \
|
||||
-o "$build_dir/sdc-validation"
|
||||
exec arch "-$check_arch" "$build_dir/sdc-validation" "${args[@]}"
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#!/bin/bash
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Opt-in: requires a legally supplied CoCo 3 ROM and a real Mac audio output.
|
||||
set -euo pipefail
|
||||
if [[ $# -lt 3 || $# -gt 4 ]]; then
|
||||
echo 'Usage: run-sustained-check.sh ROM seconds 6809|6309 [silent]' >&2
|
||||
exit 2
|
||||
fi
|
||||
repo_dir="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
build_dir="${VCC_CHECK_BUILD_DIR:-${TMPDIR:-/tmp}/vcc-sustained-build}"
|
||||
check_arch="${VCC_CHECK_ARCH:-$(uname -m)}"
|
||||
case "$check_arch" in arm64|x86_64) ;; *) echo 'VCC_CHECK_ARCH must be arm64 or x86_64' >&2; exit 2 ;; esac
|
||||
# Resolve a relative ROM before changing to the repository directory.
|
||||
rom_path="$1"
|
||||
if [[ "$rom_path" != /* ]]; then rom_path="$PWD/$rom_path"; fi
|
||||
shift
|
||||
mkdir -p "$build_dir"
|
||||
build_dir="$(cd "$build_dir" && pwd)"
|
||||
cd "$repo_dir"
|
||||
xcodebuild -project platforms/macos/VCC.xcodeproj -scheme VCCCoreChecks \
|
||||
-configuration Release -derivedDataPath "$build_dir" \
|
||||
SDK_STAT_CACHE_ENABLE=NO build > "$build_dir/build.log" 2>&1 || {
|
||||
tail -60 "$build_dir/build.log" >&2; exit 1;
|
||||
}
|
||||
xcrun clang++ -std=c++17 -O2 -fobjc-arc -arch arm64 -arch x86_64 \
|
||||
-mmacosx-version-min=14.0 -Isrc/core -Isrc -Iplatforms/windows/libcommon -Iplatforms/macos/Bridge \
|
||||
tests/macos/SustainedChecks.mm platforms/macos/Bridge/VCCMachineController.mm \
|
||||
platforms/macos/Bridge/MacAudioOutput.mm "$build_dir/Build/Products/Release/libVCCCore.a" \
|
||||
-framework Foundation -framework AVFoundation -framework AudioToolbox \
|
||||
-o "$build_dir/SustainedChecks"
|
||||
exec caffeinate -i arch "-$check_arch" "$build_dir/SustainedChecks" "$rom_path" "$@"
|
||||
@@ -0,0 +1,67 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional real-cartridge check; requires private system ROM and Scripsit II.
|
||||
// Usage: probe SYSTEM_ROM SCRIPSIT_CCC OUTPUT_PREFIX
|
||||
// No media writes or bundled copyrighted payloads. See CPU_CORE.md.
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/devices/RomCartridge.h"
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
using namespace VCC::Mac;
|
||||
static void require(bool ok, const char* message) {
|
||||
if (!ok) throw std::runtime_error(message);
|
||||
}
|
||||
static std::vector<std::uint8_t> read(const char* path) {
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
require(bool(in), "Cannot open ROM/cartridge");
|
||||
return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
require(argc == 4, "Supply system ROM, Scripsit II cartridge and output prefix");
|
||||
const auto rom = read(argv[1]), cartridge = read(argv[2]);
|
||||
for (auto processor : {Processor::MC6809, Processor::HD6309}) {
|
||||
MachineSession m;
|
||||
MachineConfiguration config; config.processor = processor;
|
||||
m.configure(config);
|
||||
m.cartridges().configure({nullptr, nullptr, nullptr, nullptr,
|
||||
std::make_shared<VCC::Devices::RomCartridge>(cartridge)}, true, 4);
|
||||
m.load(rom, processor); m.resume();
|
||||
auto frames = [&](unsigned count) { while (count--) { m.advance(); m.takeAudio(); } };
|
||||
auto press = [&](std::uint64_t keys) {
|
||||
m.setKeyboard(keys); frames(6); m.setKeyboard(0); frames(6);
|
||||
};
|
||||
frames(180);
|
||||
require(m.copyScreenText().find("COLOR SCRIPSIT II") != std::string::npos, "Scripsit menu did not boot");
|
||||
// This known cartridge's sync-poll return, not a production special case.
|
||||
m.debuggerSetBreakpoints({0x41f0});
|
||||
press(1ull << 5); // E: enter the editor's command mode.
|
||||
frames(180);
|
||||
require(m.snapshot().state == RunState::Paused && m.snapshot().cpu.PC == 0x41f0,
|
||||
"Editor is stuck polling VSYNC (TST/IRQ starvation)");
|
||||
m.debuggerSetBreakpoints({}); m.resume(); frames(60);
|
||||
press(1ull << 9); // I: insert mode (manual p. 11).
|
||||
const std::string text = "hello from vcc plus";
|
||||
for (char c : text) press(1ull << (c == ' ' ? 31 : c - 'a' + 1));
|
||||
frames(120);
|
||||
const auto memory = m.debuggerMemoryRange(0, 0x8000, false);
|
||||
require(std::search(memory.bytes.begin(), memory.bytes.end(), text.begin(), text.end()) != memory.bytes.end(),
|
||||
"Inserted text was not retained in guest memory");
|
||||
const std::string cpu = processor == Processor::MC6809 ? "6809" : "6309";
|
||||
const auto frame = m.snapshot().frame;
|
||||
require(bool(frame), "No video frame");
|
||||
std::ofstream out(std::string(argv[3]) + "-" + cpu + ".ppm", std::ios::binary);
|
||||
out << "P6\n640 480\n255\n";
|
||||
for (auto pixel : frame->pixels) { out.put(char(pixel >> 16)); out.put(char(pixel >> 8)); out.put(char(pixel)); }
|
||||
require(bool(out), "Cannot write frame capture");
|
||||
press(1ull << 50); // BREAK returns to command mode.
|
||||
press((1ull << 52) | (1ull << 50)); // CTRL+BREAK returns to main menu.
|
||||
frames(120);
|
||||
require(m.copyScreenText().find("E-EDIT") != std::string::npos, "Did not return to the main menu");
|
||||
press(1ull << 5); frames(120);
|
||||
require(m.copyScreenText().find("E-EDIT") == std::string::npos, "Could not re-enter the editor");
|
||||
std::cout << "PASS " << cpu << ": menu, sync-poll exit, insert text, return, re-enter\n";
|
||||
}
|
||||
} catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Optional local-media compatibility probe. No ROM or game bytes are bundled.
|
||||
// Usage: sdc-validation SYSTEM_ROM SDC_ROM GAME_FOLDER OUTPUT_FOLDER [6809|6309|starter]
|
||||
#include "../../src/core/MachineSession.h"
|
||||
#include "../../src/devices/SDCDevice.h"
|
||||
#include "../../src/core/tcc1014mmu.h"
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
using namespace VCC::Mac;
|
||||
using namespace VCC::Devices;
|
||||
namespace fs = std::filesystem;
|
||||
namespace {
|
||||
std::vector<std::uint8_t> read(const fs::path& path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
if (!f) throw std::runtime_error("Cannot read " + path.string());
|
||||
return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
|
||||
}
|
||||
std::uint64_t key(char c) {
|
||||
unsigned bit;
|
||||
if (c >= 'A' && c <= 'Z') bit = c - '@';
|
||||
else if (c >= '0' && c <= '9') bit = 32 + c - '0';
|
||||
else if (c == ',') bit = 44;
|
||||
else if (c == '.') bit = 46;
|
||||
else if (c == '/') bit = 47;
|
||||
else if (c == ':') bit = 42;
|
||||
else if (c == '"') return (std::uint64_t{1} << 34) | (std::uint64_t{1} << 55);
|
||||
else if (c == ' ') bit = 31;
|
||||
else if (c == '\r') bit = 48;
|
||||
else throw std::logic_error("Unsupported probe character");
|
||||
return std::uint64_t{1} << bit;
|
||||
}
|
||||
std::string screen() {
|
||||
std::string result;
|
||||
for (unsigned n=0;n<512;++n) {
|
||||
unsigned c=SafeMemRead8(0x400+n)&63;
|
||||
result+=char(c<32?c+64:c);
|
||||
if(n%32==31)result+='\n';
|
||||
}
|
||||
return result;
|
||||
}
|
||||
void picture(const MachineSession& machine,const fs::path& path) {
|
||||
const auto frame=machine.snapshot().frame;
|
||||
if(!frame)throw std::runtime_error("No rendered 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 screenshot");
|
||||
}
|
||||
struct Probe {
|
||||
MachineSession machine;
|
||||
std::shared_ptr<SDCDevice> device;
|
||||
std::set<std::string> seen;
|
||||
std::uint64_t audible=0;
|
||||
unsigned frames=0;
|
||||
void advance(unsigned count) {
|
||||
while(count--) {
|
||||
machine.advance();++frames;
|
||||
for(const auto sample:machine.takeAudio())if(sample.left!=0 || sample.right!=0)++audible;
|
||||
const auto state=device->snapshot();
|
||||
for(const auto& drive:state.drives)if(drive.mounted && seen.insert(drive.name).second)
|
||||
std::cout<<"MOUNT frame="<<frames<<" name="<<drive.name<<std::endl;
|
||||
}
|
||||
}
|
||||
void type(const std::string& text) {
|
||||
for(char c:text) { machine.setKeyboard(key(c));advance(4);machine.setKeyboard(0);advance(4); }
|
||||
}
|
||||
void press(std::uint64_t mask,unsigned count) { machine.setKeyboard(mask);advance(count);machine.setKeyboard(0);advance(4); }
|
||||
};
|
||||
void runStarter(const std::vector<std::uint8_t>& system,const std::vector<std::uint8_t>& rom,
|
||||
const fs::path& root,const fs::path& output,Processor cpu) {
|
||||
const std::string name=cpu==Processor::MC6809?"6809":"6309";
|
||||
Probe p;
|
||||
p.device=std::make_shared<SDCDevice>(rom,root.string(),true);
|
||||
p.machine.cartridges().configure({nullptr,nullptr,nullptr,nullptr,p.device},true,4);
|
||||
MachineConfiguration settings;settings.processor=cpu;settings.ram=1;settings.frameInterval=6;
|
||||
p.machine.configure(settings);
|
||||
p.machine.load(system,cpu);p.machine.resume();p.advance(300);
|
||||
if(screen().find("OK")==std::string::npos)throw std::runtime_error("Starter BASIC did not boot");
|
||||
if(!p.machine.basicReadSource().empty())throw std::runtime_error("Starter program ran automatically");
|
||||
if(p.device->snapshot().drives[0].name!="/HELLO.DSK")throw std::runtime_error("startup.cfg did not mount HELLO.DSK");
|
||||
p.type("DIR 0\r");p.advance(60);
|
||||
if(screen().find("HELLO")==std::string::npos)throw std::runtime_error("Starter directory did not list HELLO");
|
||||
picture(p.machine,output/(name+"-starter-directory.ppm"));
|
||||
p.type("LOAD \"HELLO:0\"\r");p.advance(60);
|
||||
for(char choice : {'1','2'}) {
|
||||
p.type("RUN\r");p.advance(60);
|
||||
if(p.machine.copyScreenText().find("What planet do you live on?\n1) Earth\n2) Mars")==std::string::npos)
|
||||
throw std::runtime_error("SDC starter did not display the planet menu");
|
||||
p.type(std::string(1, choice));p.advance(30);
|
||||
const auto greeting = p.machine.copyScreenText();
|
||||
const auto message = greeting.find(choice=='1' ? "Hello Nice Blue Dot World!" : "Hello Cold Red Dot World!");
|
||||
if(message==std::string::npos || greeting.find("OK",message)==std::string::npos)
|
||||
throw std::runtime_error("SDC starter did not greet the player and return to BASIC:\n"+greeting);
|
||||
picture(p.machine,output/(name+(choice=='1' ? "-starter-earth.ppm" : "-starter-mars.ppm")));
|
||||
}
|
||||
p.type("DRIVE 0,\"/HELLO.DSK\"\r");p.advance(60);
|
||||
const auto final=p.device->snapshot();
|
||||
if(!final.error.empty() || final.drives[0].name!="/HELLO.DSK")throw std::runtime_error("Starter remount command failed");
|
||||
if(!final.drives[0].reads || final.drives[0].writes)throw std::runtime_error("Unexpected starter transfer counts");
|
||||
std::cout<<"PASS "<<name<<": 512 KB, startup mount, DIR, LOAD, RUN and absolute-path remount; no autorun or writes.\n"<<p.machine.copyScreenText()<<std::endl;
|
||||
}
|
||||
void run(const std::vector<std::uint8_t>& system,const std::vector<std::uint8_t>& rom,
|
||||
const fs::path& root,const fs::path& output,Processor cpu) {
|
||||
const std::string name=cpu==Processor::MC6809?"6809":"6309";
|
||||
std::cout<<"BEGIN "<<name<<" RAM=2MB read-only card="<<root<<std::endl;
|
||||
Probe p;
|
||||
p.device=std::make_shared<SDCDevice>(rom,root.string(),true);
|
||||
p.machine.cartridges().configure({nullptr,nullptr,nullptr,nullptr,p.device},true,4);
|
||||
MachineConfiguration settings;settings.processor=cpu;settings.ram=2;settings.frameInterval=6;
|
||||
p.machine.configure(settings);p.machine.setVideoOutput(VideoOutput::RGB);
|
||||
p.machine.load(system,cpu);p.machine.resume();p.advance(300);
|
||||
std::cout<<"BOOT\n"<<screen()<<std::endl;
|
||||
picture(p.machine,output/(name+"-boot.ppm"));
|
||||
if(screen().find("OK")==std::string::npos)throw std::runtime_error(name+": BASIC did not boot");
|
||||
p.type("DRIVE 0,\"DDRAGON1.DSK\"\r");p.advance(60);
|
||||
if(!p.device->snapshot().drives[0].mounted)throw std::runtime_error(name+": DRIVE did not mount disk 1");
|
||||
p.type("RUN \"AUTOEXEC:0\"\r");
|
||||
bool graphics = false;
|
||||
for(unsigned elapsed=0;elapsed<30000;elapsed+=60) {
|
||||
p.advance(60);
|
||||
try { (void)p.machine.copyScreenText(); }
|
||||
catch(const std::logic_error&) { graphics=true;break; }
|
||||
if(elapsed%3000==0)std::cout<<"LOADING frame="<<p.frames<<"\n"<<screen()<<std::endl;
|
||||
}
|
||||
if(!graphics)throw std::runtime_error(name+": game never reached a graphics screen");
|
||||
p.advance(300);
|
||||
std::cout<<"AFTER LOAD\n"<<screen()<<std::endl;
|
||||
picture(p.machine,output/(name+"-title.ppm"));
|
||||
// Z starts the game. Movement and actions are ordinary emulated keys.
|
||||
p.press(key('Z'),12);p.advance(600);
|
||||
picture(p.machine,output/(name+"-gameplay.ppm"));
|
||||
for(unsigned n=0;n<12;++n) {
|
||||
p.press((std::uint64_t{1}<<30)|key('Z'),90); // CoCo right arrow and punch.
|
||||
p.press(key('X'),30);p.press(key('C'),30);
|
||||
}
|
||||
picture(p.machine,output/(name+"-after-input.ppm"));
|
||||
const auto final=p.device->snapshot();
|
||||
std::uint64_t reads=0,writes=0;
|
||||
for(const auto& drive:final.drives){reads+=drive.reads;writes+=drive.writes;}
|
||||
std::cout<<"RESULT "<<name<<" frames="<<p.frames<<" mounted-images="<<p.seen.size()
|
||||
<<" reads="<<reads<<" writes="<<writes<<" nonzero-audio-samples="<<p.audible
|
||||
<<" PC="<<std::hex<<p.machine.snapshot().cpu.PC<<std::dec<<" error="<<final.error<<std::endl;
|
||||
for(unsigned disk=1;disk<=9;++disk) {
|
||||
const auto expected = "DDRAGON"+std::to_string(disk)+".DSK";
|
||||
if(std::none_of(p.seen.begin(),p.seen.end(),[&](const auto& path){return fs::path(path).filename()==expected;}))
|
||||
throw std::runtime_error(name+": game did not mount "+expected);
|
||||
}
|
||||
if(writes)throw std::runtime_error(name+": read-only validation unexpectedly wrote media");
|
||||
if(p.audible==0)throw std::runtime_error(name+": game produced no audio");
|
||||
if(!final.error.empty())throw std::runtime_error(name+": SDC error: "+final.error);
|
||||
std::cout<<"PASS "<<name<<": boot, guest disk switching, audio and scripted input. Inspect captures for visual/gameplay correctness; this is not a full playthrough."<<std::endl;
|
||||
}
|
||||
}
|
||||
int main(int argc,char** argv) {
|
||||
try {
|
||||
if(argc<5 || argc>6)throw std::runtime_error("Usage: sdc-validation SYSTEM_ROM SDC_ROM GAME_FOLDER OUTPUT_FOLDER [6809|6309|starter]");
|
||||
if(argc==6 && std::string(argv[5])!="6809" && std::string(argv[5])!="6309" && std::string(argv[5])!="starter")throw std::runtime_error("Mode must be 6809, 6309 or starter");
|
||||
auto system=read(argv[1]),rom=read(argv[2]);
|
||||
if(system.size()!=32768 || (rom.size()!=8192 && rom.size()!=16384))throw std::runtime_error("Supply a 32 KiB system ROM and raw 8/16 KiB SDC ROM");
|
||||
const fs::path folder=fs::canonical(argv[3]),output=argv[4];fs::create_directories(output);
|
||||
std::map<fs::path,std::vector<std::uint8_t>> before;
|
||||
for(const auto& entry:fs::directory_iterator(folder))if(entry.is_regular_file())before.emplace(entry.path(),read(entry.path()));
|
||||
for(auto cpu:{Processor::MC6809,Processor::HD6309}) {
|
||||
if(argc==6 && std::string(argv[5])!="starter" && std::string(argv[5])!=(cpu==Processor::MC6809?"6809":"6309"))continue;
|
||||
if(argc==6 && std::string(argv[5])=="starter")runStarter(system,rom,folder,output,cpu);
|
||||
else run(system,rom,folder,output,cpu);
|
||||
}
|
||||
for(const auto& [path,bytes]:before)if(read(path)!=bytes)throw std::runtime_error("Source media changed: "+path.string());
|
||||
std::cout<<"PASS: all source media bytes unchanged"<<std::endl;
|
||||
return 0;
|
||||
}catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<std::endl;return 1;}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Exercise build isolation with synthetic inputs, never personal ROM files."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT=Path(__file__).resolve().parents[2]/'platforms/macos/Packaging/copy-development-starter.sh'
|
||||
class DevelopmentStarterTests(unittest.TestCase):
|
||||
def test_debug_opt_in_release_removal_and_invalid_inputs(self):
|
||||
with tempfile.TemporaryDirectory(prefix='VCC development ') as tmp:
|
||||
root=Path(tmp); source=root/'Source'; roms=source/'LocalResources/ROMs'
|
||||
examples=source/'Resources/StarterMedia';examples.mkdir(parents=True)
|
||||
for name in ['Hello World.dsk','Hello World.cas','Blank Disk.dsk','Hello Hard Disk.dsk','Blank OS9 Header.bin']: (examples/name).write_bytes(b'authored example')
|
||||
env=dict(os.environ,SRCROOT=str(source),TARGET_BUILD_DIR=str(root/'Build'),UNLOCALIZED_RESOURCES_FOLDER_PATH='VCC Plus.app/Contents/Resources',CONFIGURATION='Debug')
|
||||
kit=root/'Build/VCC Plus.app/Contents/Resources/StarterKit'
|
||||
def run(): return subprocess.run(['/bin/sh',str(SCRIPT)],env=env,capture_output=True,text=True)
|
||||
self.assertEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
roms.mkdir(parents=True)
|
||||
(roms/'coco3.rom').write_bytes(bytes(32768));(roms/'disk11.rom').write_bytes(bytes(8192))
|
||||
self.assertEqual(run().returncode,0)
|
||||
self.assertEqual(sorted(p.name for p in kit.iterdir()),['Blank Disk.dsk','Blank OS9 Header.bin','Hello Hard Disk.dsk','Hello World.cas','Hello World.dsk','coco3.rom','disk11.rom'])
|
||||
self.assertEqual((kit/'coco3.rom').read_bytes(),(roms/'coco3.rom').read_bytes())
|
||||
(roms/'rgbdos.rom').write_bytes(bytes(8192))
|
||||
self.assertEqual(run().returncode,0);self.assertTrue((kit/'rgbdos.rom').exists())
|
||||
(roms/'rgbdos.rom').write_bytes(b'bad')
|
||||
self.assertNotEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
(roms/'rgbdos.rom').unlink();self.assertEqual(run().returncode,0)
|
||||
(roms/'orch90.rom').write_bytes(bytes([0x12])*8192)
|
||||
self.assertEqual(run().returncode,0)
|
||||
self.assertEqual((kit/'orch90.rom').read_bytes(),(roms/'orch90.rom').read_bytes())
|
||||
(roms/'orch90.rom').write_bytes(b'bad')
|
||||
self.assertNotEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
(roms/'orch90.rom').write_bytes(bytes(8192));self.assertEqual(run().returncode,0)
|
||||
(roms/'pic-7040-510.bin').write_bytes(bytes(4096))
|
||||
self.assertNotEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
(roms/'sp0256-al2.bin').write_bytes(bytes(2048))
|
||||
self.assertEqual(run().returncode,0)
|
||||
self.assertEqual((kit/'pic-7040-510.bin').stat().st_size,4096)
|
||||
self.assertEqual((kit/'sp0256-al2.bin').stat().st_size,2048)
|
||||
for size in (8192,16384):
|
||||
(roms/'sdcdos.rom').write_bytes(bytes([0x12])*size)
|
||||
self.assertEqual(run().returncode,0)
|
||||
self.assertEqual((kit/'sdcdos.rom').read_bytes(),(roms/'sdcdos.rom').read_bytes())
|
||||
(roms/'sdcdos.rom').write_bytes(b'bad')
|
||||
self.assertNotEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
(roms/'sdcdos.rom').write_bytes(bytes(16384))
|
||||
env['CONFIGURATION']='UITesting';self.assertEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
env['CONFIGURATION']='Release';self.assertEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
env['CONFIGURATION']='Debug';self.assertEqual(run().returncode,0)
|
||||
(roms/'disk11.rom').write_bytes(b'bad')
|
||||
self.assertNotEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
(roms/'disk11.rom').write_bytes(bytes(8192));self.assertEqual(run().returncode,0)
|
||||
for rom in roms.iterdir():rom.unlink()
|
||||
roms.rmdir()
|
||||
self.assertEqual(run().returncode,0);self.assertFalse(kit.exists())
|
||||
def test_release_requires_the_private_orchestra_rom(self):
|
||||
import importlib.util
|
||||
spec=importlib.util.spec_from_file_location('vcc_release',SCRIPT.with_name('release.py'))
|
||||
release=importlib.util.module_from_spec(spec);spec.loader.exec_module(release)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root=Path(tmp); config={}
|
||||
for key,name,size in [('systemROM','system',32768),('diskROM','disk',8192),('hardDiskROM','hard',8192),('orchestraROM','orchestra',8192)]:
|
||||
path=root/name; data=bytearray(size)
|
||||
if key=='systemROM':data[-2:]=b'\x80\x00'
|
||||
path.write_bytes(data);config[key]=str(path)
|
||||
self.assertEqual(release.validate_roms(config)[3],root/'orchestra')
|
||||
config['speechPICROM']=str(root/'pic');(root/'pic').write_bytes(bytes(4096))
|
||||
with self.assertRaises(ValueError):release.validate_roms(config)
|
||||
config['speechAL2ROM']=str(root/'speech');(root/'speech').write_bytes(bytes(2048))
|
||||
self.assertEqual(release.validate_roms(config)[4:],(root/'pic',root/'speech',None))
|
||||
config['sdcROM']=str(root/'sdc')
|
||||
for size in (8192,16384):
|
||||
(root/'sdc').write_bytes(bytes(size))
|
||||
self.assertEqual(release.validate_roms(config)[6],root/'sdc')
|
||||
(root/'sdc').write_bytes(b'bad')
|
||||
with self.assertRaises(ValueError):release.validate_roms(config)
|
||||
del config['sdcROM']
|
||||
(root/'speech').write_bytes(b'bad')
|
||||
with self.assertRaises(ValueError):release.validate_roms(config)
|
||||
(root/'orchestra').write_bytes(b'bad')
|
||||
with self.assertRaises(ValueError):release.validate_roms(config)
|
||||
def test_invalid_destination_does_not_remove_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root=Path(tmp);kept=root/'StarterKit';kept.mkdir();(kept/'keep').write_text('keep')
|
||||
env=dict(os.environ,TARGET_BUILD_DIR=tmp,UNLOCALIZED_RESOURCES_FOLDER_PATH='.',CONFIGURATION='Release')
|
||||
result=subprocess.run(['/bin/sh',str(SCRIPT)],env=env,capture_output=True)
|
||||
self.assertNotEqual(result.returncode,0);self.assertEqual((kept/'keep').read_text(),'keep')
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Public authored-header checks; private image checks opt in through an env var."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
def module(name,file):
|
||||
spec=importlib.util.spec_from_file_location(name,ROOT/file)
|
||||
result=importlib.util.module_from_spec(spec);spec.loader.exec_module(result);return result
|
||||
PREP=module('prepare','platforms/macos/Tools/prepare-nitros9.py')
|
||||
FMT=module('header','platforms/macos/Tools/make-os9-data-header.py')
|
||||
class Nitros9MediaTests(unittest.TestCase):
|
||||
def test_authored_filesystem_allocation_and_basic_boundary(self):
|
||||
b=FMT.header();u=lambda o,n:int.from_bytes(b[o:o+n],'big')
|
||||
self.assertEqual(b,(ROOT/'platforms/macos/Resources/StarterMedia/Blank OS9 Header.bin').read_bytes())
|
||||
self.assertEqual(u(0,3),0x5a000);self.assertEqual(u(4,2)*8*u(6,2),u(0,3))
|
||||
allocated=[bit for bit in range(u(4,2)*8) if b[256+bit//8] & (128>>(bit%8))]
|
||||
self.assertEqual(allocated,[0,1,2,3])
|
||||
fd=u(8,3)*256;self.assertEqual(u(fd+9,4),64)
|
||||
first=u(fd+16,3);count=u(fd+19,2)
|
||||
self.assertEqual((first,count),(25,7));self.assertEqual((first+count)*256,len(b))
|
||||
self.assertEqual(u(first*256+29,3),24);self.assertEqual(u(first*256+61,3),24)
|
||||
def test_unknown_archive_rejected_without_overwriting_output(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src=Path(tmp)/'unknown.vhd';out=Path(tmp)/'keep.vhd'
|
||||
src.write_bytes(bytes(256));out.write_bytes(b'keep')
|
||||
result=subprocess.run(['python3',str(ROOT/'platforms/macos/Tools/prepare-nitros9.py'),str(src),str(out)],capture_output=True)
|
||||
self.assertNotEqual(result.returncode,0);self.assertEqual(out.read_bytes(),b'keep')
|
||||
@unittest.skipUnless(os.environ.get('VCC_NITROS9_IMAGE'),'explicit private archive input required')
|
||||
def test_private_boot_modules_and_unrelated_bytes_preserved(self):
|
||||
original=Path(os.environ['VCC_NITROS9_IMAGE']).read_bytes();prepared=PREP.prepare(original)
|
||||
self.assertEqual(len(prepared),len(original))
|
||||
allowed=set()
|
||||
for base in [0,(0x5a000+255*630)*256]:
|
||||
u=lambda o,n=3:int.from_bytes(original[base+o:base+o+n],'big')
|
||||
root=u(8)*256;entry=u(root+16)*256;size=u(root+9,4)
|
||||
fd=None
|
||||
for off in range(entry,entry+size,32):
|
||||
name=bytes(c&127 for c in original[base+off:base+off+29]).split(b'\0')[0].lower()
|
||||
if name==b'os9boot':fd=u(off+29)*256;break
|
||||
self.assertIsNotNone(fd)
|
||||
start=base+u(fd+16)*256;oldsize=u(fd+9,4)
|
||||
newsize=int.from_bytes(prepared[base+fd+9:base+fd+13],'big')
|
||||
self.assertEqual(newsize-oldsize,99)
|
||||
allowed.update(range(start,start+newsize));allowed.update(range(base+fd+9,base+fd+13));allowed.update(range(base+24,base+26))
|
||||
modules={};off=start
|
||||
while off<start+newsize:
|
||||
length=int.from_bytes(prepared[off+2:off+4],'big');m=prepared[off:off+length]
|
||||
parity=0
|
||||
for c in m[:9]:parity^=c
|
||||
self.assertEqual(parity,255)
|
||||
crc=0xffffff
|
||||
for c in m:
|
||||
crc^=c<<16
|
||||
for _ in range(8):crc=((crc<<1) ^ (0x800063 if crc&0x800000 else 0))&0xffffff
|
||||
self.assertEqual(crc,0x800fe3)
|
||||
no=int.from_bytes(m[4:6],'big');name=''
|
||||
for c in m[no:]:
|
||||
name+=chr(c&127)
|
||||
if c&128:break
|
||||
modules[name.lower()]=m;off+=length
|
||||
self.assertEqual(off,start+newsize);self.assertEqual(modules['h1'][0x13],1)
|
||||
self.assertEqual(modules['h0'][0x13],0);self.assertEqual(len(modules['emudsk']),240)
|
||||
# Check the new module pack via directory navigation, independently of
|
||||
# how the preparer chose an extent. Only these OS-9 sectors may change.
|
||||
def u(data, off, size):
|
||||
return int.from_bytes(data[off:off + size], 'big')
|
||||
|
||||
def record(data, fd):
|
||||
pos = fd * 256
|
||||
start = u(data, pos + 16, 3) * 256
|
||||
size = u(data, pos + 9, 4)
|
||||
return start, data[start:start + size]
|
||||
|
||||
def directory(data, fd):
|
||||
_, entries = record(data, fd)
|
||||
return {bytes(c & 127 for c in entries[i:i + 29]).split(b'\0')[0].lower():
|
||||
u(entries, i + 29, 3)
|
||||
for i in range(0, len(entries), 32) if entries[i]}
|
||||
|
||||
root = directory(original, u(original, 8, 3))
|
||||
folder = root[b'boot_with_beckerdw']
|
||||
old = directory(original, folder)
|
||||
new = directory(prepared, folder)
|
||||
pack_fd = new.pop(b'dwnet')
|
||||
self.assertEqual(old, new)
|
||||
payload = b''.join(record(original, old[n])[1] for n in (b'dwio', b'scdwv', b'n', b'n1'))
|
||||
start, contents = record(prepared, pack_fd)
|
||||
self.assertEqual(payload, contents)
|
||||
self.assertEqual(prepared[pack_fd * 256] & 0x05, 0x05)
|
||||
data_sectors = u(prepared, pack_fd * 256 + 19, 2)
|
||||
self.assertEqual(data_sectors, (len(payload) + 255) // 256)
|
||||
self.assertEqual(start, (pack_fd + 1) * 256)
|
||||
self.assertEqual(u(prepared, pack_fd * 256 + 21, 3), 0)
|
||||
allowed.update(range(pack_fd * 256, start + data_sectors * 256))
|
||||
|
||||
expected_map = bytearray(original[256:256 + u(original, 4, 2)])
|
||||
for sector in range(pack_fd, pack_fd + 1 + data_sectors):
|
||||
mask = 128 >> (sector % 8)
|
||||
self.assertFalse(expected_map[sector // 8] & mask)
|
||||
expected_map[sector // 8] |= mask
|
||||
allowed.add(256 + sector // 8)
|
||||
self.assertEqual(prepared[256:256 + len(expected_map)], expected_map)
|
||||
|
||||
directory_start, original_entries = record(original, folder)
|
||||
_, updated_entries = record(prepared, folder)
|
||||
self.assertEqual(updated_entries[:-32], original_entries)
|
||||
allowed.update(range(folder * 256 + 9, folder * 256 + 13))
|
||||
entry = directory_start + len(original_entries)
|
||||
allowed.update(range(entry, entry + 32))
|
||||
|
||||
startup = root[b'startup']
|
||||
start, old_script = record(original, startup)
|
||||
_, script = record(prepared, startup)
|
||||
addition = b'load /dd/boot_with_beckerdw/dwnet\r'
|
||||
self.assertEqual(script.count(addition), 1)
|
||||
self.assertEqual(script.replace(addition, b''), old_script)
|
||||
self.assertLess(script.index(addition), script.index(b'shell i='))
|
||||
allowed.update(range(start, start + len(script)))
|
||||
allowed.update(range(startup * 256 + 9, startup * 256 + 13))
|
||||
self.assertEqual(PREP.prepare(prepared), prepared)
|
||||
# Compare spans rather than iterating all 135 MB byte by byte.
|
||||
last=0
|
||||
for offset in sorted(allowed):
|
||||
if offset>last:self.assertEqual(prepared[last:offset],original[last:offset])
|
||||
last=offset+1
|
||||
self.assertEqual(prepared[last:],original[last:])
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user