Files
VCCPlusOSS/platforms/macos/Tests/CMOCVariableTreeIntegrationTests.swift
Brian Holman 5534005799 Sync VCC Plus 3.7.1 build 67 source
Refresh reviewed MCP output export, four-drive owned playtests, bounded BASIC readiness, and pinned CMOC 0.1.101 source/patches. Preserve independent source-edition identity, empty libraries, notices and privacy boundaries.

Validated 74 export/privacy checks, pinned dependency sources, and an independent unsigned universal Release build. A subsequent documentation-only correction removes an excluded qualification link; all build inputs remain identical.
2026-11-17 08:42:27 -07:00

211 lines
13 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
/// Qualifies expandable values against real CMOC output and current/caller frames.
final class CMOCVariableTreeIntegrationTests: XCTestCase {
private struct Fixture {
let root: URL
let artifact: CMOCBuildArtifact
let metadata: CMOCVariableDebug
let rom: Data
let sources: [String: String]
func line(_ marker: String, file: String) throws -> Int {
try XCTUnwrap(sources[file]?.components(separatedBy: "\n").firstIndex { $0.contains(marker) }) + 1
}
func address(_ marker: String, file: String) throws -> UInt16 {
try XCTUnwrap(metadata.sourceMap.addresses(forLine: line(marker, file: file), in: file).first, marker)
}
}
private func fixture() async throws -> Fixture {
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
let rom = resources.appendingPathComponent("ROMs/coco3.rom")
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
&& FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required")
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCVariableTree-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
do {
let project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
let sources = ["types.h": """
struct Point { int x; int y; };
struct Bag { struct Point point; unsigned int samples[40]; struct Point *pointer; };
""", "main.c": """
#include <cmoc.h>
#include <coco.h>
#include "types.h"
unsigned int result;
unsigned int inspect(struct Bag *parent);
int main(void)
{
struct Bag bag;
unsigned int i;
initCoCoSupport();
bag.point.x = -7;
bag.point.y = 11;
bag.pointer = &bag.point;
for (i = 0; i < 40; ++i) bag.samples[i] = 100 + i;
result = inspect(&bag); /* MAIN_CALL */
for (;;) ++result;
return 0;
}
""", "helper.c": """
#include "types.h"
extern unsigned int result;
struct Point *nullPoint = 0;
unsigned char *ioPointer = (unsigned char *)0xFF00;
unsigned int inspect(struct Bag *parent)
{
struct Bag local;
unsigned int i;
local.point.x = -17;
local.point.y = 21;
local.pointer = &local.point;
for (i = 0; i < 40; ++i) local.samples[i] = 200 + i;
result = local.samples[39]; /* LEAF_STOP */
return result + parent->samples[39];
}
"""]
for (name, source) in sources { try Data(source.utf8).write(to: project.directory.appendingPathComponent(name)) }
let makefile = """
CMOC ?= cmoc
build: main.bin
main.bin: main.o helper.o
\t"$(CMOC)" --coco --intermediate --org=2800 -o $@ main.o helper.o
main.o: main.c
\t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $<
helper.o: helper.c
\t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $<
"""
try Data(makefile.utf8).write(to: project.makefileURL)
let service = CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds"))
let artifact = try await service.build(project: project, overlays: [:])
let map = try CMOCProjectSourceMap.parse(artifact: artifact)
let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map)
return Fixture(root: root, artifact: artifact, metadata: metadata, rom: try Data(contentsOf: rom), sources: sources)
} catch { try? FileManager.default.removeItem(at: root); throw error }
}
@MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } }
}
@MainActor private func capture(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot {
await withCheckedContinuation { continuation in
controller.debuggerSnapshot(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) }
}
}
@MainActor private func withStoppedProcessors(_ fixture: Fixture,
body: (VCCMachineController, VCCDebuggerSnapshot) async throws -> Void) async throws {
for use6309 in [false, true] {
let controller = VCCMachineController()
do {
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
let loaded = await command { controller.loadROM(fixture.rom, use6309: use6309, completion: $0) }
XCTAssertNil(loaded.errorMessage)
_ = await command(controller.resume)
try await Task.sleep(nanoseconds: 1_500_000_000)
_ = await command(controller.pause)
let breakpoint = try fixture.address("LEAF_STOP", file: "helper.c")
var state = await command { controller.debuggerLoadBinary(fixture.artifact.binaryData, breakpoint: breakpoint, completion: $0) }
for _ in 0..<1000 where state.state == .running {
try await Task.sleep(nanoseconds: 5_000_000)
state = await command(controller.snapshot)
}
XCTAssertNil(state.errorMessage)
XCTAssertEqual(state.state, .paused)
XCTAssertEqual(state.programCounter, breakpoint)
try await body(controller, await capture(controller))
_ = await command(controller.shutdown)
} catch { _ = await command(controller.shutdown); throw error }
}
}
private func stack(_ fixture: Fixture, _ snapshot: VCCDebuggerSnapshot,
memory: Data? = nil, available: Data? = nil) throws -> CMOCCallStack {
CMOCCallStack.capture(metadata: fixture.metadata, pc: snapshot.machine.programCounter,
u: try XCTUnwrap(snapshot.registers["U"]?.uint16Value), s: try XCTUnwrap(snapshot.registers["S"]?.uint16Value),
memory: memory ?? snapshot.logicalMemory, available: available ?? snapshot.logicalMemoryAvailable)
}
private typealias TreePath = CMOCWatchEvaluator.TreePath
private func variable(_ name: String, _ components: [CMOCWatchEvaluator.Component] = []) -> TreePath {
TreePath(root: .variable(name), components: components)
}
@MainActor func testCompiledAggregatePagesAndPointersUseSelectedFrameWithoutGuestSideEffects() async throws {
let fixture = try await fixture()
defer { try? FileManager.default.removeItem(at: fixture.root) }
try await withStoppedProcessors(fixture) { controller, snapshot in
let originalMemory = Data(Array(snapshot.logicalMemory))
let frames = try stack(fixture, snapshot)
XCTAssertEqual(frames.frames.map(\.functionName), ["inspect", "main"], frames.termination)
guard frames.frames.count == 2 else { return }
func evaluator(_ frame: CMOCCallStack.Frame, memory: Data? = nil,
available: Data? = nil) -> CMOCWatchEvaluator {
CMOCWatchEvaluator(metadata: fixture.metadata,
context: .init(pc: frame.pc, u: frame.u, memory: memory ?? snapshot.logicalMemory,
available: available ?? snapshot.logicalMemoryAvailable),
frameLocalsAvailable: frame.localsInspectable)
}
let current = evaluator(frames.frames[0]), caller = evaluator(frames.frames[1])
let local = variable("local")
let roots = current.variableTreeRoots()
let localRoot = try XCTUnwrap(roots.first { $0.path == local })
XCTAssertNil(localRoot.error)
XCTAssertEqual(localRoot.childCount, 3)
XCTAssertEqual(current.children(of: local).nodes.count, 3)
XCTAssertNil(current.children(of: local).error)
for (engine, root, start, x, y) in [(current, "local", 200, "-17", "21"),
(caller, "bag", 100, "-7", "11")] {
let samples = variable(root, [.member("samples")])
let first = engine.children(of: samples)
XCTAssertNil(first.error)
XCTAssertEqual(first.totalCount, 40)
XCTAssertEqual(first.nodes.count, 32)
XCTAssertEqual(first.nextOffset, 32)
XCTAssertEqual(first.nodes.map(\.value), (0..<32).map { String(start + $0) })
let second = engine.children(of: samples, offset: 32)
XCTAssertNil(second.error)
XCTAssertEqual(second.nodes.count, 8)
XCTAssertNil(second.nextOffset)
XCTAssertEqual(second.nodes.map(\.value), (32..<40).map { String(start + $0) })
XCTAssertEqual(Set((first.nodes + second.nodes).map(\.path)).count, 40,
"Array children must keep distinct typed paths across pages")
XCTAssertEqual(engine.treeNode(at: variable(root, [.member("point"), .member("x")])).value, x)
XCTAssertEqual(engine.treeNode(at: variable(root, [.member("point"), .member("y")])).value, y)
let pointer = variable(root, [.member("pointer")])
XCTAssertEqual(engine.treeNode(at: pointer).childCount, 1)
XCTAssertEqual(engine.children(of: pointer).nodes.count, 1)
XCTAssertEqual(engine.treeNode(at: variable(root, [.member("pointer"), .pointee, .member("x")])).value, x)
}
// The leaf's pointer argument refers to the caller's real aggregate.
let parentSamples = variable("parent", [.pointee, .member("samples")])
XCTAssertEqual(current.children(of: parentSamples, offset: 32).nodes.map(\.value),
(132..<140).map(String.init))
let watch = current.watchTreeRoot("parent->point")
XCTAssertNil(watch.error)
XCTAssertEqual(watch.childCount, 2)
XCTAssertEqual(current.children(of: watch.path).nodes.map(\.value), ["-7", "11"])
// Pointer expansion is explicit and never invokes memory-mapped I/O.
for name in ["nullPoint", "ioPointer"] {
let root = current.treeNode(at: variable(name))
XCTAssertNil(root.error, "Reading a pointer value is different from dereferencing it")
let page = current.children(of: variable(name))
XCTAssertTrue(page.error != nil || page.nodes.contains { $0.error != nil },
"Unsafe pointees need an explicit explanation")
}
// Reusing a typed path must still revalidate the current snapshot.
// Force independent storage: mutating a directly bridged NSData
// value can also mutate the test snapshot's backing bytes.
var altered = Data(Array(originalMemory))
let instruction = try XCTUnwrap(fixture.metadata.sourceMap.instructions.first)
altered[Int(instruction.address)] ^= 1
let stale = evaluator(frames.frames[0], memory: altered)
XCTAssertNotNil(stale.treeNode(at: variable("local", [.member("samples"), .index(39)])).error)
XCTAssertNotNil(stale.children(of: local).error)
let after = await capture(controller)
XCTAssertEqual(after.machine.programCounter, snapshot.machine.programCounter)
XCTAssertEqual(after.machine.cycles, snapshot.machine.cycles)
XCTAssertEqual(after.registers, snapshot.registers)
XCTAssertEqual(snapshot.logicalMemory, originalMemory, "Inspection must not mutate its captured snapshot")
XCTAssertEqual(after.logicalMemory, originalMemory,
"Expanding current/caller values and pointer errors must not execute guest code or touch memory")
}
}
}