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,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()
|
||||
Reference in new issue
Block a user