// SPDX-License-Identifier: GPL-3.0-or-later import XCTest /// Qualifies stack recovery against real CMOC output and live guest frames. final class CMOCCallStackIntegrationTests: 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(optimized: Bool = false) 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("CMOCCallStack-\(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 unsigned int result; unsigned int wrapper(unsigned int value); int main(void) { unsigned int mainLocal = 7; initCoCoSupport(); result = wrapper(mainLocal); /* MAIN_CALL */ for (;;) ++result; return 0; } """, "helper.c": """ extern unsigned int result; unsigned int recurse(unsigned int n) { unsigned int local = n + 10; if (n == 0) { result = local; /* LEAF_STOP */ return local; } return recurse(n - 1) + local; /* RECURSIVE_CALL */ } unsigned int wrapper(unsigned int value) { unsigned int local = value + 5; unsigned char byteLocal = 42; result = recurse(value - 4); /* WRAPPER_CALL */ return result + local + byteLocal; } """] 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 \(optimized ? "-O2" : "-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 func assertValue(_ expression: String, _ expected: String, frame: CMOCCallStack.Frame, fixture: Fixture, snapshot: VCCDebuggerSnapshot, file: StaticString = #filePath, line: UInt = #line) { let value = CMOCWatchEvaluator(metadata: fixture.metadata, context: .init(pc: frame.pc, u: frame.u, memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable)).evaluate(expression) XCTAssertNil(value.error, "\(expression): \(value.error ?? "")", file: file, line: line) XCTAssertEqual(value.value, expected, expression, file: file, line: line) } @MainActor func testRealRecursiveCallersNavigateAndInspectTheirOwnFramesOnBothCPUs() async throws { let fixture = try await fixture() defer { try? FileManager.default.removeItem(at: fixture.root) } try await withStoppedProcessors(fixture) { controller, snapshot in let recovered = try stack(fixture, snapshot) XCTAssertEqual(recovered.frames.map(\.functionName), ["recurse", "recurse", "recurse", "recurse", "wrapper", "main"], recovered.termination) guard recovered.frames.count == 6 else { return } XCTAssertTrue(recovered.frames.allSatisfy(\.localsInspectable)) XCTAssertEqual(Set(recovered.frames.map(\.u)).count, 6, "Every invocation needs its own saved frame pointer") for index in 0..<4 { let frame = recovered.frames[index] XCTAssertEqual(frame.sourcePath, "helper.c") XCTAssertEqual(frame.sourceLine, try fixture.line(index == 0 ? "LEAF_STOP" : "RECURSIVE_CALL", file: "helper.c")) assertValue("n", String(index), frame: frame, fixture: fixture, snapshot: snapshot) assertValue("local", String(index + 10), frame: frame, fixture: fixture, snapshot: snapshot) } let wrapper = recovered.frames[4] XCTAssertEqual(wrapper.sourceLine, try fixture.line("WRAPPER_CALL", file: "helper.c")) assertValue("value", "7", frame: wrapper, fixture: fixture, snapshot: snapshot) assertValue("local", "12", frame: wrapper, fixture: fixture, snapshot: snapshot) assertValue("byteLocal", "42", frame: wrapper, fixture: fixture, snapshot: snapshot) XCTAssertTrue(recovered.frames.contains { $0.u & 1 == 1 }, "A byte-sized local must not require word-aligned frames") let main = recovered.frames[5] XCTAssertEqual(main.sourcePath, "main.c") XCTAssertEqual(main.sourceLine, try fixture.line("MAIN_CALL", file: "main.c")) assertValue("mainLocal", "7", frame: main, fixture: fixture, snapshot: snapshot) let afterInspection = await capture(controller) XCTAssertEqual(afterInspection.machine.programCounter, snapshot.machine.programCounter) XCTAssertEqual(afterInspection.machine.cycles, snapshot.machine.cycles) XCTAssertEqual(afterInspection.logicalMemory, snapshot.logicalMemory, "Caller inspection cannot change execution or memory") XCTAssertEqual(afterInspection.registers, snapshot.registers) } } @MainActor func testLiveFramesStopAtCorruptUnavailableAndChangedCodeBoundaries() async throws { let fixture = try await fixture() defer { try? FileManager.default.removeItem(at: fixture.root) } try await withStoppedProcessors(fixture) { _, snapshot in let valid = try stack(fixture, snapshot) XCTAssertEqual(valid.frames.count, 6, valid.termination) let framePointer = Int(try XCTUnwrap(snapshot.registers["U"]?.uint16Value)) var corrupt = snapshot.logicalMemory corrupt[framePointer] = UInt8(framePointer >> 8) corrupt[framePointer + 1] = UInt8(framePointer & 255) let cycle = try stack(fixture, snapshot, memory: corrupt) XCTAssertLessThanOrEqual(cycle.frames.count, 1, "A self-referential saved U must not fabricate callers") XCTAssertFalse(cycle.termination.isEmpty) var unavailable = snapshot.logicalMemoryAvailable unavailable[framePointer + 2] = 0 let hiddenReturn = try stack(fixture, snapshot, available: unavailable) XCTAssertLessThanOrEqual(hiddenReturn.frames.count, 1) XCTAssertFalse(hiddenReturn.termination.isEmpty) var changedCode = snapshot.logicalMemory let instruction = try XCTUnwrap(fixture.metadata.sourceMap.instructions.first) changedCode[Int(instruction.address)] ^= 1 let invalid = try stack(fixture, snapshot, memory: changedCode) XCTAssertTrue(invalid.frames.isEmpty, "No frame should be attributed to stale executable metadata") XCTAssertFalse(invalid.termination.isEmpty) } } @MainActor func testOptimizedCompilerFrameReportsBoundaryInsteadOfInventingCallers() async throws { let fixture = try await fixture(optimized: true) defer { try? FileManager.default.removeItem(at: fixture.root) } XCTAssertTrue(fixture.metadata.functions.contains { $0.name == "recurse" && !$0.frame }) try await withStoppedProcessors(fixture) { _, snapshot in let recovered = try stack(fixture, snapshot) XCTAssertLessThanOrEqual(recovered.frames.count, 1) XCTAssertFalse(recovered.frames.contains(where: \.localsInspectable)) XCTAssertFalse(recovered.termination.isEmpty) } } }