// SPDX-License-Identifier: GPL-3.0-or-later import Foundation /// Read-only watches over one atomic, side-effect-free debugger snapshot. /// This is a deliberately bounded expression evaluator, not guest execution. struct CMOCWatchEvaluator { struct Context { let pc: UInt16 let u: UInt16 let memory: Data let available: Data init(pc: UInt16, u: UInt16, memory: Data, available: Data) { self.pc = pc; self.u = u // Foundation's NSData bridge may share mutable backing even when // the Swift value is let-bound. Verification is cached, so own the // snapshot bytes rather than relying on that bridge's copy-on-write. func owned(_ data: Data) -> Data { data.withUnsafeBytes { bytes in bytes.isEmpty ? Data() : Data(bytes: bytes.baseAddress!, count: bytes.count) } } self.memory = owned(memory); self.available = owned(available) } } struct Value: Identifiable { var id: String { name } let name: String let typeName: String let value: String let address: UInt16? let error: String? } enum Root: Hashable { case variable(String), watch(String) } enum Component: Hashable { case index(Int), member(String), pointee } struct TreePath: Hashable { let root: Root let components: [Component] init(root: Root, components: [Component] = []) { self.root = root; self.components = components } func appending(_ component: Component) -> TreePath { TreePath(root: root, components: components + [component]) } } struct TreeNode: Identifiable { var id: TreePath { path } let path: TreePath let name: String let typeName: String let value: String let address: UInt16? let error: String? let childCount: Int } struct TreePage { let nodes: [TreeNode] let totalCount: Int let nextOffset: Int? let error: String? } private final class VerificationCache { var result: Result? } // Copies share only immutable snapshot provenance. Each newly captured // evaluator gets a new cache; expanding 32 children must not rescan all code // 32 times. Frame availability is checked separately on every root resolve. private let verificationCache = VerificationCache() private struct Problem: Error { let message: String; init(_ message: String) { self.message = message } } private struct Operand { let type: CMOCVariableDebug.CType let address: Int? let immediate: Int64? } let metadata: CMOCVariableDebug let context: Context var frameLocalsAvailable = true private var function: CMOCVariableDebug.Function? { metadata.functions.first { $0.body <= Int(context.pc) && Int(context.pc) < $0.end } } // A verified assembly entry/prologue establishes file identity without // establishing a C frame. Keep stack-local eligibility on the body above. private var fileScopeFunction: CMOCVariableDebug.Function? { function ?? metadata.entryFunction(containing: context.pc) } private func verified() throws { if let result = verificationCache.result { return try result.get() } do { try verifySnapshot() verificationCache.result = .success(()) } catch { verificationCache.result = .failure(error) throw error } } private func verifySnapshot() throws { guard context.memory.count == 65536, context.available.count == 65536 else { throw Problem("A complete paused memory snapshot is required.") } guard metadata.sourceMap.verifiesRuntime(memory: context.memory, available: context.available) else { throw Problem("The running code no longer matches this build, or its memory is unavailable.") } } private func candidates(named name: String? = nil) -> [CMOCVariableDebug.Variable] { let location = metadata.sourceMap.location(at: context.pc) return metadata.variables.filter { variable in if let name, variable.name != name { return false } if let scope = variable.scope { guard scope.contains(Int(context.pc)), function != nil else { return false } // A block's stack reservation precedes its declarations. Do not // expose a later declaration (or shadow an outer name) early. if variable.offset != nil, let location, location.path == variable.sourcePath, location.line < variable.line { return false } } else if variable.isStatic, variable.sourcePath != fileScopeFunction?.sourcePath { return false } return true } } private func resolve(_ name: String) throws -> CMOCVariableDebug.Variable { let matches = candidates(named: name) let locals = matches.filter { $0.scope != nil }.sorted { $0.scope!.count < $1.scope!.count } if let first = locals.first { guard locals.count == 1 || locals[1].scope != first.scope else { throw Problem("The name ‘\(name)’ is ambiguous in this scope.") } return first } let sameFile = matches.filter { $0.sourcePath == fileScopeFunction?.sourcePath } let globals = sameFile.isEmpty ? matches : sameFile guard globals.count == 1, let variable = globals.first else { throw Problem(globals.isEmpty ? "‘\(name)’ is not available in the current C scope." : "The name ‘\(name)’ is ambiguous; stop in its source file.") } return variable } private func operand(_ variable: CMOCVariableDebug.Variable) throws -> Operand { if let address = variable.address { return Operand(type: variable.type, address: address, immediate: nil) } guard frameLocalsAvailable else { throw Problem("This frame’s local storage cannot be verified. Pause inside a supported unoptimized function body with a preserved frame pointer.") } guard let offset = variable.offset, function?.frame == true else { throw Problem("Local variables require an unoptimized, preserved frame pointer. Rebuild with -O0 -fno-omit-frame-pointer and pause inside the function body.") } let address = Int(context.u) + offset guard address >= 0, address + variable.type.size <= 65536 else { throw Problem("The variable's stack storage is outside logical memory.") } return Operand(type: variable.type, address: address, immediate: nil) } private func bytes(at address: Int, count: Int) throws -> [UInt8] { guard address >= 0, count >= 0, address <= 65536 - count, !(address..<(address + count)).contains(where: { context.available[$0] == 0 }) else { throw Problem("This memory is unavailable for inspection (including hardware I/O).") } return Array(context.memory[address..<(address + count)]) } private func integer(_ value: Operand) throws -> Int64 { if let immediate = value.immediate { return immediate } if value.type.kind == "floating" { throw Problem("Floating-point values can be inspected, but floating-point watch arithmetic is not supported.") } guard ["integer", "pointer"].contains(value.type.kind), let address = value.address else { throw Problem("This operation requires an integer or pointer value.") } let data = try bytes(at: address, count: value.type.size) var result: Int64 = 0 for byte in data { result = (result << 8) | Int64(byte) } if value.type.kind == "integer", value.type.signed == true, let first = data.first, first & 0x80 != 0 { result -= Int64(1) << (data.count * 8) } return result } private func floating(_ operand: Operand) throws -> String { guard let format = operand.type.floatingFormat else { throw Problem("This build does not identify its floating-point format. Rebuild with the current VCC Plus compiler.") } let expectedSize: Int switch format { case "coco-basic-40": expectedSize = 5 case "ieee754-binary32-be": expectedSize = 4 default: throw Problem("Unsupported floating-point format ‘\(format)’; inspect its bytes in Memory.") } guard operand.type.size == expectedSize, let address = operand.address else { throw Problem("The floating-point storage does not match its compiler-described format.") } let data = try bytes(at: address, count: expectedSize) let value: Double if format == "coco-basic-40" { // CMOC RealConstantExpr::getRepresentation and Color BASIC's packed // format: exponent byte, sign bit, 31 fraction bits; hidden leading 1. // Exponent zero represents zero regardless of the remaining bytes. if data[0] == 0 { return "0" } let fraction = (UInt32(data[1] & 0x7f) << 24) | (UInt32(data[2]) << 16) | (UInt32(data[3]) << 8) | UInt32(data[4]) let magnitude = ldexp(1 + Double(fraction) / 2147483648, Int32(data[0]) - 129) value = data[1] & 0x80 == 0 ? magnitude : -magnitude } else { // Decode the target byte order explicitly, independent of host CPU. let bits = data.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } value = Double(Float(bitPattern: bits)) } if value.isNaN { return "NaN" } if value.isInfinite { return value.sign == .minus ? "-Infinity" : "Infinity" } if value == 0 { return value.sign == .minus ? "-0" : "0" } // Enough significant decimal digits to distinguish adjacent target // values (32-bit significand for BASIC, 24-bit for IEEE binary32). return String(format: expectedSize == 5 ? "%.11g" : "%.9g", locale: Locale(identifier: "en_US_POSIX"), value) } private func describe(_ operand: Operand, depth: Int = 0) throws -> String { let type = operand.type switch type.kind { case "integer": return String(try integer(operand)) case "pointer": return String(format: "$%04llX", try integer(operand)) case "array": guard let address = operand.address, let element = type.element, let count = type.count else { throw Problem("Array layout is unavailable.") } if depth >= 2 { return "[\(count) elements]" } let values = try (0.. 8 ? ", …]" : "]") case "aggregate": guard let address = operand.address, let members = type.members else { throw Problem("Aggregate layout is unavailable.") } if depth >= 2 { return "{…}" } let values = try members.prefix(4).map { member in member.name + " = " + (try describe(Operand(type: member.type, address: address + member.offset, immediate: nil), depth: depth + 1)) } return "{" + values.joined(separator: ", ") + (members.count > 4 ? ", …}" : "}") case "floating": return try floating(operand) default: throw Problem("This compiler type is not supported by the watch evaluator.") } } func visibleVariables() -> [Value] { let names = Set(candidates().map(\.name)).sorted() let verificationError: Error? do { try verified(); verificationError = nil } catch { verificationError = error } return names.map { name in do { if let verificationError { throw verificationError } let variable = try resolve(name), value = try operand(variable) return Value(name: name, typeName: value.type.name, value: try describe(value), address: value.address.flatMap(UInt16.init(exactly:)), error: nil) } catch { let type = (try? resolve(name))?.type.name ?? "" return Value(name: name, typeName: type, value: "Unavailable", address: nil, error: message(error)) } } } func evaluate(_ expression: String) -> Value { do { try verified() var parser = try Parser(expression) let tree = try parser.parse() let result = try evaluate(tree, depth: 0) return Value(name: expression, typeName: result.type.name, value: try describe(result), address: result.address.flatMap(UInt16.init(exactly:)), error: nil) } catch { return Value(name: expression, typeName: "", value: "Unavailable", address: nil, error: message(error)) } } // Lazy tree access resolves typed paths from the current root and frame. // No stored node is a capability to read an address from an older snapshot. func variableRootPaths() -> [TreePath] { Set(candidates().map(\.name)).sorted().map { TreePath(root: .variable($0)) } } func variableRoots() -> [TreeNode] { variableRootPaths().map { treeNode(at: $0) } } func variableTreeRoots() -> [TreeNode] { variableRoots() } func watchRoot(_ expression: String) -> TreeNode { treeNode(at: .init(root: .watch(expression))) } func watchTreeRoot(_ expression: String) -> TreeNode { watchRoot(expression) } func treeNode(at path: TreePath) -> TreeNode { do { try verified() return try makeTreeNode(path: path, operand: treeOperand(at: path)) } catch { return treeError(path, error) } } func children(of path: TreePath, offset: Int = 0) -> TreePage { do { try verified() guard path.components.count < 12 else { throw Problem("The 12-level inspection limit has been reached.") } let parent = try treeOperand(at: path) let total = treeChildCount(parent.type) guard offset >= 0, offset <= total else { throw Problem("This child page is outside the declared bounds.") } let end = min(total, offset + 32) let nodes = (offset.. TreeNode in let component: Component switch parent.type.kind { case "array": component = .index(index) case "aggregate": component = .member(parent.type.members![index].name) default: component = .pointee } let child = path.appending(component) do { return try makeTreeNode(path: child, operand: treeOperand(at: child)) } catch { return treeError(child, error) } } return TreePage(nodes: nodes, totalCount: total, nextOffset: end < total ? end : nil, error: nil) } catch { return TreePage(nodes: [], totalCount: 0, nextOffset: nil, error: message(error)) } } private func treeName(_ path: TreePath) -> String { if let last = path.components.last { switch last { case .index(let i): return "[\(i)]"; case .member(let name): return name; case .pointee: return "Pointee" } } switch path.root { case .variable(let name), .watch(let name): return name } } private func treeError(_ path: TreePath, _ error: Error) -> TreeNode { TreeNode(path: path, name: treeName(path), typeName: "", value: "Unavailable", address: nil, error: message(error), childCount: 0) } private func treeChildCount(_ type: CMOCVariableDebug.CType) -> Int { switch type.kind { case "array": return min(max(type.count ?? 0, 0), 65535) case "aggregate": return min(type.members?.count ?? 0, 1024) case "pointer": return 1 // Explicit expansion explains null/unknown targets. default: return 0 } } private func makeTreeNode(path: TreePath, operand: Operand) throws -> TreeNode { let type = operand.type let count = treeChildCount(type) let summary: String // Aggregate rows do not read children. An unavailable member cannot // prevent expansion of its inspectable siblings. do { switch type.kind { case "array": summary = "[\(count) elements]" case "aggregate": summary = "{\(count) members}" default: summary = try describe(operand) } } catch { return TreeNode(path: path, name: treeName(path), typeName: type.name, value: "Unavailable", address: operand.address.flatMap(UInt16.init(exactly:)), error: message(error), childCount: 0) } let atLimit = path.components.count >= 12 && count > 0 return TreeNode(path: path, name: treeName(path), typeName: type.name, value: summary, address: operand.address.flatMap(UInt16.init(exactly:)), error: atLimit ? "The 12-level inspection limit has been reached." : nil, childCount: atLimit ? 0 : count) } private struct TreeVisit: Hashable { let address: Int let name: String let kind: String let size: Int } private func treeOperand(at path: TreePath) throws -> Operand { guard path.components.count <= 12 else { throw Problem("The 12-level inspection limit has been reached.") } var value: Operand switch path.root { case .variable(let name): value = try operand(resolve(name)) case .watch(let expression): var parser = try Parser(expression) value = try evaluate(parser.parse(), depth: 0) } var visited = Set() func visit(_ operand: Operand) -> TreeVisit? { operand.address.map { TreeVisit(address: $0, name: operand.type.name, kind: operand.type.kind, size: operand.type.size) } } if let root = visit(value) { visited.insert(root) } for component in path.components { switch component { case .index(let index): guard value.type.kind == "array", let count = value.type.count, let element = value.type.element, let first = value.address, index >= 0, index < count, element.size > 0 else { throw Problem("Array index is outside its declared bounds or its element layout is unavailable.") } let (displacement, overflow) = index.multipliedReportingOverflow(by: element.size) let (address, additionOverflow) = first.addingReportingOverflow(displacement) guard !overflow, !additionOverflow, address >= 0, element.size <= 65536, address <= 65536 - element.size else { throw Problem("Indexed address is outside logical memory.") } value = Operand(type: element, address: address, immediate: nil) case .member(let name): guard value.type.kind == "aggregate", let first = value.address, let member = value.type.members?.first(where: { $0.name == name }) else { throw Problem("No inspectable member named ‘\(name)’.") } let (address, overflow) = first.addingReportingOverflow(member.offset) guard !overflow, address >= 0, member.type.size >= 0, member.type.size <= 65536, address <= 65536 - member.type.size else { throw Problem("Member address is outside logical memory.") } value = Operand(type: member.type, address: address, immediate: nil) case .pointee: value = try dereference(value) if let next = visit(value), visited.contains(next) { throw Problem("Pointer cycle: this object already appears in the expanded path.") } } if let next = visit(value) { visited.insert(next) } } return value } private func message(_ error: Error) -> String { (error as? Problem)?.message ?? error.localizedDescription } private indirect enum Expr { case identifier(String), number(Int64), unary(String, Expr), binary(String, Expr, Expr), index(Expr, Expr), member(Expr, String, Bool) } private func evaluate(_ expression: Expr, depth: Int) throws -> Operand { guard depth <= 32 else { throw Problem("Watch expression is too deeply nested.") } func eval(_ value: Expr) throws -> Operand { try evaluate(value, depth: depth + 1) } func literal(_ value: Int64) -> Operand { Operand(type: .init(name: "watch integer (64-bit)", kind: "integer", size: 8, signed: true), address: nil, immediate: value) } switch expression { case .identifier(let name): return try operand(resolve(name)) case .number(let value): return literal(value) case .unary(let operation, let expression): let value = try eval(expression) if operation == "&" { guard let address = value.address else { throw Problem("Address-of requires stored data.") } return Operand(type: .init(name: value.type.name + " *", kind: "pointer", size: 2, element: value.type), address: nil, immediate: Int64(address)) } if operation == "*" { return try dereference(value) } let number = try integer(value) switch operation { case "+": return literal(number) case "-": guard number != Int64.min else { throw Problem("Integer overflow in watch.") }; return literal(-number) case "~": return literal(~number) case "!": return literal(number == 0 ? 1 : 0) default: throw Problem("Unsupported unary operation.") } case .index(let target, let index): let base = try eval(target), number = try integer(eval(index)) let element: CMOCVariableDebug.CType, address: Int64 if base.type.kind == "array", let next = base.type.element, let first = base.address, let count = base.type.count { guard number >= 0, number < count else { throw Problem("Array index is outside its declared bounds.") } element = next; address = Int64(first) } else if base.type.kind == "pointer", let next = base.type.element { element = next; address = try integer(base) } else { throw Problem("Indexing requires an array or pointer.") } guard element.size > 0, number >= -65536, number <= 65536 else { throw Problem("Invalid element size or index.") } let result = address + number * Int64(element.size) guard result >= 0, result + Int64(element.size) <= 65536 else { throw Problem("Indexed address is outside logical memory.") } return Operand(type: element, address: Int(result), immediate: nil) case .member(let target, let name, let pointer): let source = try eval(target), base = try pointer ? dereference(source) : source guard base.type.kind == "aggregate", let address = base.address, let member = base.type.members?.first(where: { $0.name == name }) else { throw Problem("No inspectable member named ‘\(name)’.") } return Operand(type: member.type, address: address + member.offset, immediate: nil) case .binary(let operation, let left, let right): let lhs = try eval(left) let a = try integer(lhs) if operation == "&&", a == 0 { return literal(0) } if operation == "||", a != 0 { return literal(1) } let rhs = try eval(right), b = try integer(rhs) if lhs.type.kind == "pointer", ["+", "-"].contains(operation), rhs.type.kind == "integer", let element = lhs.type.element { guard element.size > 0, b >= -65536, b <= 65536 else { throw Problem("Invalid pointer arithmetic.") } let address = a + (operation == "+" ? b : -b) * Int64(element.size) guard (0...65535).contains(address) else { throw Problem("Pointer arithmetic leaves logical memory.") } return Operand(type: lhs.type, address: nil, immediate: address) } switch operation { case "+": let (r,o) = a.addingReportingOverflow(b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r) case "-": let (r,o) = a.subtractingReportingOverflow(b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r) case "*": let (r,o) = a.multipliedReportingOverflow(by: b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r) case "/", "%": guard b != 0, !(a == Int64.min && b == -1) else { throw Problem("Invalid division in watch.") }; return literal(operation == "/" ? a / b : a % b) case "&": return literal(a & b) case "|": return literal(a | b) case "^": return literal(a ^ b) case "<<", ">>": guard (0...31).contains(b) else { throw Problem("Shift count must be between 0 and 31.") } if operation == ">>" { return literal(a >> b) } let (shifted, overflow) = a.multipliedReportingOverflow(by: Int64(1) << b) guard !overflow else { throw Problem("Integer overflow in watch.") }; return literal(shifted) case "==": return literal(a == b ? 1 : 0) case "!=": return literal(a != b ? 1 : 0) case "<": return literal(a < b ? 1 : 0) case "<=": return literal(a <= b ? 1 : 0) case ">": return literal(a > b ? 1 : 0) case ">=": return literal(a >= b ? 1 : 0) case "&&": return literal(a != 0 && b != 0 ? 1 : 0) case "||": return literal(a != 0 || b != 0 ? 1 : 0) default: throw Problem("Unsupported binary operation.") } } } private func dereference(_ value: Operand) throws -> Operand { guard value.type.kind == "pointer", let element = value.type.element, element.size > 0 else { throw Problem("Dereference requires a pointer to a known data type.") } let address = try integer(value) guard address > 0, address + Int64(element.size) <= 65536 else { throw Problem("Null or out-of-range pointer.") } return Operand(type: element, address: Int(address), immediate: nil) } private struct Parser { var tokens: [String] = [] var index = 0 init(_ text: String) throws { guard text.utf8.count <= 1024 else { throw Problem("Watch expression is too long.") } let chars = Array(text) var i = 0 while i < chars.count { let c = chars[i] if c.isWhitespace { i += 1; continue } if c.isASCII && (c.isLetter || c == "_" || c.isNumber) { let begin = i; i += 1 while i < chars.count, chars[i].isASCII && (chars[i].isLetter || chars[i].isNumber || chars[i] == "_") { i += 1 } tokens.append(String(chars[begin..", "==", "!=", "<=", ">=", "&&", "||", "<<", ">>"].contains(pair) { tokens.append(pair); i += 2; continue } guard "()+-*/%&|^~!<>[].".contains(c) else { throw Problem("Only read-only expressions are supported; assignments and function calls are unavailable.") } tokens.append(String(c)); i += 1 } guard !tokens.isEmpty, tokens.count <= 128 else { throw Problem("Enter a variable or a short read-only expression.") } } mutating func parse() throws -> Expr { let result = try binary(minimum: 0, depth: 0) guard index == tokens.count else { throw Problem("Unsupported expression syntax. Function calls and assignments are not evaluated.") } return result } func precedence(_ token: String) -> Int? { switch token { case "||": return 0 case "&&": return 1 case "|": return 2 case "^": return 3 case "&": return 4 case "==", "!=": return 5 case "<", "<=", ">", ">=": return 6 case "<<", ">>": return 7 case "+", "-": return 8 case "*", "/", "%": return 9 default: return nil } } mutating func binary(minimum: Int, depth: Int) throws -> Expr { guard depth <= 32 else { throw Problem("Watch expression is too deeply nested.") } var left = try unary(depth: depth + 1) while index < tokens.count, let p = precedence(tokens[index]), p >= minimum { let operation = tokens[index]; index += 1 left = .binary(operation, left, try binary(minimum: p + 1, depth: depth + 1)) } return left } mutating func unary(depth: Int) throws -> Expr { guard depth <= 32, index < tokens.count else { throw Problem("Incomplete or overly nested watch expression.") } let token = tokens[index]; index += 1 if ["*", "&", "+", "-", "~", "!"].contains(token) { return .unary(token, try unary(depth: depth + 1)) } var result: Expr if token == "(" { result = try binary(minimum: 0, depth: depth + 1); try expect(")") } else if token.first?.isNumber == true { let number: Int64? if token.lowercased().hasPrefix("0x") { number = Int64(token.dropFirst(2), radix: 16) } else { number = Int64(token, radix: 10) } guard let number else { throw Problem("Invalid integer literal.") }; result = .number(number) } else if token.first?.isLetter == true || token.first == "_" { result = .identifier(token) } else { throw Problem("Expected a variable, number or parenthesized expression.") } while index < tokens.count { if tokens[index] == "[" { index += 1; let subscriptValue = try binary(minimum: 0, depth: depth + 1); try expect("]") result = .index(result, subscriptValue) } else if [".", "->"].contains(tokens[index]) { let pointer = tokens[index] == "->"; index += 1 guard index < tokens.count, tokens[index].first?.isLetter == true || tokens[index].first == "_" else { throw Problem("Expected a member name.") } result = .member(result, tokens[index], pointer); index += 1 } else { break } } return result } mutating func expect(_ token: String) throws { guard index < tokens.count, tokens[index] == token else { throw Problem("Expected ‘\(token)’.") }; index += 1 } } }