// SPDX-License-Identifier: GPL-3.0-or-later import XCTest /// End-to-end qualification: actual compiler output and an executing CoCo, /// rather than handcrafted addresses or a second implementation of the mapper. final class CMOCSourceDebugTests: XCTestCase { private struct Fixture { let root: URL let artifact: CMOCBuildArtifact let map: CMOCProjectSourceMap let rom: Data let sources: [String: String] func line(_ marker: String, file: String = "main.c") throws -> Int { try XCTUnwrap(sources[file]?.components(separatedBy: "\n").firstIndex { $0.contains(marker) }) + 1 } func address(_ marker: String, file: String = "main.c") throws -> UInt16 { try XCTUnwrap(map.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 = 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("CMOCSourceDebug-\(UUID().uuidString)") try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) do { let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) let sources = ["main.c": """ #include #include #include "shared.h" unsigned int result; unsigned int progress; unsigned int values[3] = {11, 22, 33}; struct Pair pair = {4, 45}; unsigned int *pointer = &values[1]; int signedValue = -1234; unsigned char *ioPointer = (unsigned char *)0xFF00; int main(void) { unsigned int mainLocal = 7; initCoCoSupport(); result = transform(mainLocal); /* CALL_TRANSFORM */ progress = result; /* AFTER_TRANSFORM */ result = recurse(3); /* CALL_RECURSE */ progress = result; /* AFTER_RECURSE */ for (;;) ++progress; return 0; } """, "helper.c": """ #include "shared.h" unsigned int transform(unsigned int value) { unsigned int local = value + 5; { unsigned int value = 99; result = value; /* SHADOW_VALUE */ } result = local; /* OUTER_VALUE */ return local * 2; /* RETURN_TRANSFORM */ } unsigned int recurse(unsigned int n) { unsigned int local = n + 10; if (n == 0) return local; /* RECURSION_BASE */ return recurse(n - 1) + local; /* RECURSION_CALL */ } """, "shared.h": """ struct Pair { unsigned int left; unsigned int right; }; extern unsigned int result; unsigned int transform(unsigned int value); unsigned int recurse(unsigned int n); """] for (name, source) in sources { try Data(source.utf8).write(to: project.directory.appendingPathComponent(name)) } let makefile = """ CMOC ?= cmoc .PHONY: build clean build: main.bin main.bin: main.o helper.o \t"$(CMOC)" --coco --intermediate --org=2800 -o $@ main.o helper.o %.o: %.c shared.h \t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $< clean: \trm -f *.o *.bin *.s *.lst *.map *.link """ try Data(makefile.utf8).write(to: project.makefileURL) let artifact = try await CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds")) .build(project: project, overlays: [:]) let map = try CMOCProjectSourceMap.parse(artifact: artifact) XCTAssertEqual(Set(map.sourcePaths), Set(["main.c", "helper.c"])) return Fixture(root: root, artifact: artifact, map: map, 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 waitForStop(_ controller: VCCMachineController) async throws -> VCCDebuggerSnapshot { var state = await command(controller.snapshot) for _ in 0..<1000 where state.state == .running { try await Task.sleep(nanoseconds: 5_000_000) state = await command(controller.snapshot) } XCTAssertEqual(state.state, .paused, state.errorMessage ?? "Execution did not stop") XCTAssertNil(state.errorMessage) return await capture(controller) } @MainActor private func runTo(_ fixture: Fixture, controller: VCCMachineController, marker: String, file: String = "main.c") async throws -> VCCDebuggerSnapshot { let address = try fixture.address(marker, file: file) let result = await command { controller.debuggerLoadBinary(fixture.artifact.binaryData, breakpoint: address, completion: $0) } XCTAssertNil(result.errorMessage) let stopped = try await waitForStop(controller) XCTAssertEqual(stopped.machine.programCounter, address) return stopped } @MainActor private func startSourceStep(_ mode: Int, fixture: Fixture, controller: VCCMachineController, snapshot: VCCDebuggerSnapshot) async -> VCCMachineSnapshot { var identities: [CMOCProjectSourceMap.Location: UInt32] = [:] let ids = fixture.map.instructions.map { instruction -> NSNumber in let location = CMOCProjectSourceMap.Location(path: instruction.sourcePath, line: instruction.sourceLine) if identities[location] == nil { identities[location] = UInt32(identities.count + 1) } return NSNumber(value: identities[location]!) } return await command { controller.debuggerStepSource(mode: mode, addresses: fixture.map.instructions.map { NSNumber(value: $0.address) }, locations: ids, bytes: fixture.map.instructions.map { Data($0.bytes) }, generation: snapshot.machine.generation, programRevision: snapshot.machine.debuggerProgramRevision, mappingFingerprint: snapshot.machine.debuggerMappingFingerprint, programCounter: snapshot.machine.programCounter, completion: $0) } } @MainActor private func sourceStep(_ mode: Int, fixture: Fixture, controller: VCCMachineController) async throws -> VCCDebuggerSnapshot { let result = await startSourceStep(mode, fixture: fixture, controller: controller, snapshot: await capture(controller)) XCTAssertNil(result.errorMessage) return try await waitForStop(controller) } @MainActor private func withProcessors(_ fixture: Fixture, body: (VCCMachineController) 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) try await body(controller) _ = await command(controller.shutdown) } catch { _ = await command(controller.shutdown); throw error } } } @MainActor func testRealMultiFileStepIntoOverOutAndRecursiveFramesOnBothCPUs() async throws { let fixture = try await fixture() defer { try? FileManager.default.removeItem(at: fixture.root) } let metadata = try CMOCVariableDebug.parse(artifact: fixture.artifact, verifiedMap: fixture.map) try await withProcessors(fixture) { controller in let original = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") let over = try await sourceStep(1, fixture: fixture, controller: controller) XCTAssertEqual(fixture.map.location(at: over.machine.programCounter), .init(path: "main.c", line: try fixture.line("AFTER_TRANSFORM"))) XCTAssertEqual(over.machine.generation, original.machine.generation) XCTAssertEqual(over.machine.debuggerProgramRevision, original.machine.debuggerProgramRevision) XCTAssertEqual(over.breakpoints, original.breakpoints, "Temporary step targets must not replace permanent breakpoints") assertValue("result", "24", in: try evaluator(metadata, over)) _ = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") let into = try await sourceStep(0, fixture: fixture, controller: controller) XCTAssertEqual(fixture.map.location(at: into.machine.programCounter)?.path, "helper.c", "Into must enter the other translation unit") let out = try await sourceStep(2, fixture: fixture, controller: controller) XCTAssertEqual(fixture.map.location(at: out.machine.programCounter)?.path, "main.c", "Out must return to the caller") _ = try await runTo(fixture, controller: controller, marker: "CALL_RECURSE") var recursive = try await sourceStep(0, fixture: fixture, controller: controller) let callLine = try fixture.line("RECURSION_CALL", file: "helper.c") for _ in 0..<12 where fixture.map.location(at: recursive.machine.programCounter)?.line != callLine { recursive = try await sourceStep(0, fixture: fixture, controller: controller) } XCTAssertEqual(fixture.map.location(at: recursive.machine.programCounter), .init(path: "helper.c", line: callLine)) let outerU = recursive.registers["U"]?.uint16Value var nested = try await sourceStep(0, fixture: fixture, controller: controller) for _ in 0..<12 where fixture.map.location(at: nested.machine.programCounter)?.line != callLine { nested = try await sourceStep(0, fixture: fixture, controller: controller) } XCTAssertEqual(fixture.map.location(at: nested.machine.programCounter), .init(path: "helper.c", line: callLine)) XCTAssertNotEqual(nested.registers["U"]?.uint16Value, outerU, "Recursion must establish a distinct live frame") let returned = try await sourceStep(2, fixture: fixture, controller: controller) XCTAssertEqual(returned.registers["U"]?.uint16Value, outerU, "Out must leave exactly one recursive invocation") XCTAssertEqual(fixture.map.location(at: returned.machine.programCounter)?.path, "helper.c") _ = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") let calleePoint = try fixture.address("SHADOW_VALUE", file: "helper.c") _ = await command { controller.debuggerConfigureBreakpoints([NSNumber(value: calleePoint)], disabled: [0x7001], completion: $0) } let userStop = try await sourceStep(1, fixture: fixture, controller: controller) XCTAssertEqual(userStop.machine.programCounter, calleePoint, "Step Over must still honor an explicit breakpoint inside the call") XCTAssertEqual(userStop.breakpoints, [NSNumber(value: calleePoint)]) XCTAssertEqual(userStop.disabledBreakpoints, [0x7001]) } } @MainActor func testSourceStepRejectsEditedMemoryAndStalePausedPCWithoutExecuting() async throws { let fixture = try await fixture() defer { try? FileManager.default.removeItem(at: fixture.root) } try await withProcessors(fixture) { controller in var previous = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") _ = await command { controller.debuggerWriteMemory(address: 0x7000, data: Data([0x55]), completion: $0) } var before = await capture(controller) var rejected = await startSourceStep(0, fixture: fixture, controller: controller, snapshot: previous) XCTAssertNotNil(rejected.errorMessage, "An explicit memory edit invalidates the captured build connection") XCTAssertEqual(rejected.state, .paused) XCTAssertEqual(rejected.cycles, before.machine.cycles) XCTAssertEqual(rejected.programCounter, before.machine.programCounter) previous = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") _ = await command(controller.debuggerStep) before = await capture(controller) rejected = await startSourceStep(1, fixture: fixture, controller: controller, snapshot: previous) XCTAssertNotNil(rejected.errorMessage, "The worker must check expected PC at the command boundary") XCTAssertEqual(rejected.state, .paused) XCTAssertEqual(rejected.cycles, before.machine.cycles) XCTAssertEqual(rejected.programCounter, before.machine.programCounter) let after = await capture(controller) XCTAssertEqual(after.breakpoints, before.breakpoints) XCTAssertEqual(after.disabledBreakpoints, before.disabledBreakpoints) } } private func evaluator(_ metadata: CMOCVariableDebug, _ snapshot: VCCDebuggerSnapshot) throws -> CMOCWatchEvaluator { CMOCWatchEvaluator(metadata: metadata, context: .init(pc: snapshot.machine.programCounter, u: try XCTUnwrap(snapshot.registers["U"]?.uint16Value), memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable)) } private func assertValue(_ expression: String, _ expected: String, in evaluator: CMOCWatchEvaluator, file: StaticString = #filePath, line: UInt = #line) { let result = evaluator.evaluate(expression) XCTAssertNil(result.error, "\(expression): \(result.error ?? "")", file: file, line: line) XCTAssertEqual(result.value, expected, expression, file: file, line: line) } @MainActor func testLiveCompilerVariablesShadowingArraysPointersAndReadOnlyWatchesOnBothCPUs() async throws { let fixture = try await fixture() defer { try? FileManager.default.removeItem(at: fixture.root) } let metadata = try CMOCVariableDebug.parse(artifact: fixture.artifact, verifiedMap: fixture.map) XCTAssertTrue(metadata.functions.contains { $0.name == "transform" && $0.frame }) try await withProcessors(fixture) { controller in let nested = try await runTo(fixture, controller: controller, marker: "SHADOW_VALUE", file: "helper.c") let inner = try evaluator(metadata, nested) assertValue("value", "99", in: inner) assertValue("local", "12", in: inner) assertValue("result", "0", in: inner) assertValue("signedValue", "-1234", in: inner) assertValue("values[1]", "22", in: inner) assertValue("*pointer", "22", in: inner) assertValue("pointer[1]", "33", in: inner) assertValue("pair.right", "45", in: inner) assertValue("values[1] + local * 2", "46", in: inner) XCTAssertEqual(inner.visibleVariables().filter { $0.name == "value" }.count, 1, "Only the innermost shadow is visible") for expression in ["values[3]", "*ioPointer", "value = 5", "transform(1)", "++local", "1 / 0", "missing"] { XCTAssertNotNil(inner.evaluate(expression).error, expression) } let afterInspection = await capture(controller) XCTAssertEqual(afterInspection.logicalMemory, nested.logicalMemory, "Watch evaluation cannot write guest memory or read I/O for side effects") XCTAssertEqual(afterInspection.machine.cycles, nested.machine.cycles) let outer = try await sourceStep(0, fixture: fixture, controller: controller) XCTAssertEqual(fixture.map.location(at: outer.machine.programCounter), .init(path: "helper.c", line: try fixture.line("OUTER_VALUE", file: "helper.c"))) let outerValues = try evaluator(metadata, outer) assertValue("value", "7", in: outerValues) assertValue("local", "12", in: outerValues) assertValue("result", "99", in: outerValues) let returned = try await sourceStep(2, fixture: fixture, controller: controller) let caller = try evaluator(metadata, returned) assertValue("mainLocal", "7", in: caller) XCTAssertNotNil(caller.evaluate("local").error, "A callee's stack local is unavailable after return") _ = try await runTo(fixture, controller: controller, marker: "CALL_RECURSE") var recursive = try await sourceStep(0, fixture: fixture, controller: controller) let callLine = try fixture.line("RECURSION_CALL", file: "helper.c") for _ in 0..<12 where fixture.map.location(at: recursive.machine.programCounter)?.line != callLine { recursive = try await sourceStep(0, fixture: fixture, controller: controller) } assertValue("n", "3", in: try evaluator(metadata, recursive)) assertValue("local", "13", in: try evaluator(metadata, recursive)) var child = try await sourceStep(0, fixture: fixture, controller: controller) for _ in 0..<12 where fixture.map.location(at: child.machine.programCounter)?.line != callLine { child = try await sourceStep(0, fixture: fixture, controller: controller) } assertValue("n", "2", in: try evaluator(metadata, child)) assertValue("local", "12", in: try evaluator(metadata, child)) let parent = try await sourceStep(2, fixture: fixture, controller: controller) assertValue("n", "3", in: try evaluator(metadata, parent)) assertValue("local", "13", in: try evaluator(metadata, parent)) let code = try XCTUnwrap(fixture.map.instructions.first) _ = await command { controller.debuggerWriteMemory(address: code.address, data: Data([code.bytes[0] ^ 1]), completion: $0) } let changed = await capture(controller) XCTAssertNotNil(try evaluator(metadata, changed).evaluate("result").error, "Even apparently valid data must not be reported against changed executable bytes") } } }