Files

168 lines
12 KiB
Swift

import Foundation
@MainActor
enum MCPCMOCGuest {
struct DebugInfo {
let map: CMOCProjectSourceMap
let variables: CMOCVariableDebug?
init(_ build: CMOCBuildArtifact) throws {
map = try CMOCProjectSourceMap.parse(artifact: build)
guard map.matches(sources: build.sources, binary: build.binaryData) else {
throw ProfileFailure.message("The C source and binary differ from their source map.")
}
variables = try? CMOCVariableDebug.parse(artifact: build, verifiedMap: map)
}
}
typealias SaveStop = @MainActor (VCCDebuggerSnapshot, DebugInfo, CMOCProjectSourceMap.Instruction) throws -> Void
static func run(model: CMOCDevelopmentModel, build: CMOCBuildArtifact,
isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> [String: Any] {
let (info, point, disk, expectedOutput) = try await Task.detached {
let info = try DebugInfo(build)
guard let disk = build.diskURL,
let entry = build.sources["main.c"].flatMap({ String(data: $0, encoding: .utf8) }),
let line = entry.components(separatedBy: "\n").firstIndex(where: { $0.contains("printf(\"DISK RESULT:") }),
let point = info.map.instructions.first(where: { $0.sourcePath == "main.c" && $0.sourceLine == line + 1 }) else {
throw ProfileFailure.message("The Hello Disk source stop could not be matched to this binary.")
}
let wordPath = "assets/words.txt"
let wordData = try Data(contentsOf: build.fileURL(wordPath))
guard CMOCProject.sha256(wordData) == build.fileHashes[wordPath],
let words = String(data: wordData, encoding: .utf8)?.split(whereSeparator: \.isNewline) else {
throw ProfileFailure.message("The word list changed after this disk was built.")
}
let lines = ["HELLO FROM A MULTI-FILE PROJECT", "WORDS READ FROM THE FLOPPY:"] + words.map(String.init) +
["", "DISK RESULT: 0", "GENERATED WORD COUNT: \(words.count)"]
return (info, point, try Data(contentsOf: disk), lines.joined(separator: "\n"))
}.value
let machine = model.machine
let initial = await machine.mcpMachineSnapshot()
let name = "Hello Disk " + UUID().uuidString + ".dsk"
let deadline = ContinuousClock.now.advanced(by: .seconds(25))
do {
let launched = try await launchAtStop(model, build: build, info: info, point: point, disk: disk, name: name,
initial: initial, deadline: deadline, isCurrent: isCurrent, saveStop: saveStop)
let continued = await machine.continueReviewedC(launched, name: name, stop: point.address, bytes: Data(point.bytes))
if let error = continued.errorMessage { throw ProfileFailure.message(error) }
while ContinuousClock.now < deadline {
let (screen, now) = await machine.reviewedCOutput()
guard isCurrent(), now.generation == launched.generation, now.debuggerProgramRevision == launched.debuggerProgramRevision,
now.disks.first?.name == name else { throw CancellationError() }
if let screen, let output = screen.range(of: expectedOutput + "\n", options: .backwards),
now.disks[0].readEvents > initial.disks[0].readEvents {
let receipt: [String: Any] = ["screen": String(screen[output]).trimmingCharacters(in: .newlines), "cpu": now.use6309 ? "6309" : "6809",
"source_stop": ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address),
"bytes": point.bytes.map { Int($0) }],
"disk_read_events": now.disks[0].readEvents - initial.disks[0].readEvents,
"disk_write_protected": now.disks[0].writeProtected, "artifact_id": build.id.uuidString]
await machine.ejectReviewedCDisk(name)
return receipt
}
try await Task.sleep(for: .milliseconds(50))
}
throw ProfileFailure.message("Hello Disk did not display its successful disk result and generated word count.")
} catch {
await machine.ejectReviewedCDisk(name)
throw error
}
}
static func runOrdinary(model: CMOCDevelopmentModel, build: CMOCBuildArtifact, play: Bool = false,
isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> [String: Any] {
let (info, point) = try await Task.detached {
let info = try DebugInfo(build)
guard info.map.bankedLayout == nil else {
throw ProfileFailure.message("This packed build requires its declared disk launch. Use the C workspace's Disk & Run, or grant disposable playtests for assistant execution.")
}
guard let main = info.variables?.functions.first(where: { $0.name == "main" && $0.sourcePath == build.entrySourcePath }),
let point = info.map.instructions.first(where: {
$0.sourcePath == main.sourcePath && main.body <= Int($0.address) && Int($0.address) < main.end
}) else { throw ProfileFailure.message("Build the Debug configuration with a mapped main function to run this shared project.") }
return (info, point)
}.value
let initial = await model.machine.mcpMachineSnapshot()
let state = try await launchAtStop(model, build: build, info: info, point: point, disk: nil, name: "",
initial: initial, deadline: .now.advanced(by: .seconds(25)),
isCurrent: isCurrent, saveStop: saveStop)
if play {
guard isCurrent() else { throw CancellationError() }
let continued = await model.machine.continueReviewedC(state, name: "", stop: point.address, bytes: Data(point.bytes))
if let error = continued.errorMessage { throw ProfileFailure.message(error) }
}
return ["artifact_id": build.id.uuidString, "status": play ? "continued_from_main" : "paused", "cpu": state.use6309 ? "6309" : "6809",
"source_stop": ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address),
"bytes": point.bytes.map(Int.init)] as [String: Any]]
}
private static func launchAtStop(_ model: CMOCDevelopmentModel, build: CMOCBuildArtifact, info: DebugInfo,
point: CMOCProjectSourceMap.Instruction, disk: Data?, name: String,
initial: VCCMachineSnapshot, deadline: ContinuousClock.Instant,
isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> VCCMachineSnapshot {
let machine = model.machine
var launched: VCCMachineSnapshot
repeat {
guard isCurrent() else { throw CancellationError() }
launched = await machine.startReviewedC(build.binaryData, disk: disk, name: name, stop: point.address, expected: initial)
if launched.errorMessage == nil { break }
if launched.errorMessage == "occupied_basic_program" { throw ProfileFailure.message(MCPMachineStatus.occupiedBASICGuidance) }
guard launched.errorMessage == "Waiting for an empty Disk BASIC prompt.", ContinuousClock.now < deadline else {
throw ProfileFailure.message(launched.errorMessage ?? "The CoCo could not start the reviewed binary.")
}
try await Task.sleep(for: .milliseconds(60))
} while true
var stopped = launched
while stopped.state != .paused && ContinuousClock.now < deadline {
guard isCurrent(), stopped.generation == launched.generation,
stopped.debuggerProgramRevision == launched.debuggerProgramRevision else { throw CancellationError() }
try await Task.sleep(for: .milliseconds(50))
stopped = await machine.mcpMachineSnapshot()
}
let capture = try await MCPDebuggerInspection.capture(machine)
guard isCurrent(), MCPDebuggerInspection.sameProgram(capture.machine, launched),
capture.machine.state == .paused, capture.machine.programCounter == point.address,
capture.machine.debuggerDevelopmentAttached, disk == nil || capture.machine.disks.first?.name == name,
capture.instructions.first?.bytes == Data(point.bytes) else {
throw ProfileFailure.message("The reviewed binary did not reach its verified C source stop.")
}
try saveStop(capture, info, point)
return capture.machine
}
static func inspection(runID: String, revision: Int, projectID: String, build: CMOCBuildArtifact,
capture: VCCDebuggerSnapshot, info: DebugInfo, point: CMOCProjectSourceMap.Instruction,
watches: [String], sharedPaths: Set<String>) throws -> MCPDebuggerInspection {
guard sharedPaths.contains(point.sourcePath) else { throw ProfileFailure.message("path_not_shared") }
let memory = capture.logicalMemory, available = capture.logicalMemoryAvailable
let ranges: [Range<Int>] = try info.map.instructions.compactMap { instruction in
let range = Int(instruction.address)..<(Int(instruction.address) + instruction.bytes.count)
guard range.upperBound <= min(memory.count, available.count), available[range].allSatisfy({ $0 != 0 }),
memory[range].elementsEqual(instruction.bytes) else { throw ProfileFailure.message("stale_run") }
return sharedPaths.contains(instruction.sourcePath) ? range : nil
}
var rows: [[String: String]] = [], status = "C watch metadata is unavailable for this build."
if let metadata = info.variables, let u = capture.registers["U"]?.uint16Value, let s = capture.registers["S"]?.uint16Value {
status = "available"
let frame = CMOCCallStack.capture(metadata: metadata, pc: point.address, u: u, s: s, memory: memory,
available: available, maximumFrames: 1).frames.first
let evaluator = CMOCWatchEvaluator(metadata: metadata, context: .init(pc: point.address, u: u, memory: memory, available: available),
frameLocalsAvailable: frame?.localsInspectable == true)
rows = watches.map { name in
// Only a locally configured named variable can cross the grant. Arbitrary dereferences can name unrelated memory.
guard name.range(of: #"^[A-Za-z_][A-Za-z_0-9]*$"#, options: .regularExpression) != nil else {
return ["name": name, "unavailable": "Only named C variables are shared."]
}
let value = evaluator.evaluate(name)
if let error = value.error { return ["name": name, "unavailable": error] }
return ["name": name, "type": value.typeName, "value": value.value]
}
}
return try MCPDebuggerInspection(runID: runID, capture: capture,
scope: ["project_id": projectID, "revision": revision, "artifact_id": build.id.uuidString, "observation": "captured_source_stop"],
sourceStop: ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address), "instruction_bytes": point.bytes.map(Int.init)],
watches: rows, watchStatus: status, ranges: ranges)
}
}