// SPDX-License-Identifier: GPL-3.0-or-later import Foundation /// Read-only evidence from an owned, paused run. This deliberately has no caller /// supplied memory address: the only newly disclosed storage is [S, S + 64). enum CMOCOwnedCallContext { static func capture(map: CMOCProjectSourceMap, metadata: CMOCVariableDebug?, pc: UInt16, s: UInt16, u: UInt16, memory: Data, available: Data, physicalPages: [Int: Int], sharedPaths: Set) -> [String: Any] { func unavailable(_ reason: String) -> [String: Any] { ["status": "unavailable", "reason": reason] } guard memory.count == 65536, available.count == 65536 else { return unavailable("A complete immutable memory and availability snapshot is required.") } let start = Int(s), limit = start + 64 guard limit <= 0xfe00 else { return unavailable("The actual S window crosses protected memory or wraps.") } func ram(_ address: Int, _ count: Int) -> Bool { guard address >= 0, count > 0, address <= 0xfe00 - count else { return false } return (address / 8192...(address + count - 1) / 8192).allSatisfy { physicalPages[$0].map { (0..<1024).contains($0) } == true } } func readable(_ address: Int, _ count: Int) -> Bool { ram(address, count) && available[address..<(address + count)].allSatisfy { $0 != 0 } } guard readable(start, 64) else { return unavailable("Every byte of the actual S window must be available RAM with a physical mapping.") } let selected = map.projected(physicalPages: physicalPages, memory: memory, available: available) guard selected.verifiesRuntime(memory: memory, available: available), readable(Int(pc), 1) else { return unavailable("The current executable bytes or RAM mapping could not be verified.") } // Metadata must identify this same retained build. Use the supplied map's // current bank projection, never a metadata object's stale projection. let debug: CMOCVariableDebug? if let metadata, metadata.sourceMap.binarySHA256 == map.binarySHA256, metadata.sourceMap.linkMapSHA256 == map.linkMapSHA256, metadata.sourceMap.sourceHashes == map.sourceHashes, metadata.sourceMap.objectHashes == map.objectHashes, metadata.sourceMap.listingHashes == map.listingHashes { debug = CMOCVariableDebug(functions: metadata.functions, variables: metadata.variables, sourceMap: map).projected(physicalPages: physicalPages, memory: memory, available: available) } else { debug = nil } let function = debug?.entryFunction(containing: pc) let instruction = selected.instruction(at: pc) let mappedSource = instruction.map { sharedPaths.contains($0.sourcePath) && !$0.bytes.isEmpty && readable(Int(pc), $0.bytes.count) && Array(memory[Int(pc)..<(Int(pc) + $0.bytes.count)]) == $0.bytes } == true let functionSource = function.map { sharedPaths.contains($0.sourcePath) } == true let executableSource = selected.executableLocation(at: pc, memory: memory, available: available, sharedPaths: sharedPaths) != nil guard mappedSource || functionSource || executableSource else { return unavailable("The current PC has no verified executable identity in shared source.") } var spans: [[String: Any]] = [], cursor = start while cursor < limit { let end = min(limit, (cursor / 8192 + 1) * 8192) spans.append(["logical_address": cursor, "physical_address": physicalPages[cursor / 8192]! * 8192 + cursor % 8192, "count": end - cursor]) cursor = end } let words = stride(from: 0, to: 64, by: 2).map { offset -> [String: Any] in ["offset": offset, "address": start + offset, "value": Int(memory[start + offset]) * 256 + Int(memory[start + offset + 1])] } var result: [String: Any] = [ "status": "available", "stack_window": ["address": start, "count": 64, "bytes": Array(memory[start.. Bool { guard readable(address, bytes.count) else { return false } let guards: [(Int, [UInt8])] if let layout = selected.bankedLayout { guard let moduleID, selected.activeModuleIDs?.contains(moduleID) == true, let module = layout.module(id: moduleID) else { return false } guards = module.codeGuards.map { (Int($0.address), $0.bytes) } } else { guard moduleID == nil else { return false } guards = selected.flatCodeGuards.map { (Int($0.address), $0.bytes) } } return bytes.enumerated().allSatisfy { offset, byte in let location = address + offset return memory[location] == byte && guards.contains { begin, data in location >= begin && location - begin < data.count && data[location - begin] == byte } } } func normal(_ f: CMOCVariableDebug.Function) -> Bool { f.frame && f.entry >= 0 && f.body >= f.entry + 4 && f.body < f.end && f.end <= 0xfe00 - 4 && guarded(f.entry, [0x34, 0x40, 0x33, 0xe4], moduleID: f.moduleID) && guarded(f.end, [0x32, 0xc4, 0x35, 0xc0], moduleID: f.moduleID) } guard normal(function) else { return result } let frameBase: Int, returnAddress: Int, phase: String if Int(pc) == function.entry { frameBase = start - 2 // U after the proven, as-yet unexecuted PSHS U. returnAddress = start; phase = "function_entry" } else if Int(pc) >= function.body, Int(pc) < function.end, mappedSource, Int(u) >= start, Int(u) <= limit - 4 { frameBase = Int(u); returnAddress = frameBase + 2; phase = "mapped_body" } else { return result } // Only these two bytes, already inside the raw window, identify a // potential caller. Never search other stack words for return addresses. let returnPC = Int(memory[returnAddress]) * 256 + Int(memory[returnAddress + 1]) func target(_ i: CMOCProjectSourceMap.Instruction) -> Int? { let b = i.bytes, address = Int(i.address) switch b.count { case 2 where b[0] == 0x8d: return (address + 2 + Int(Int8(bitPattern: b[1]))) & 0xffff case 3 where b[0] == 0x17: return (address + 3 + Int(Int16(bitPattern: UInt16(b[1]) << 8 | UInt16(b[2])))) & 0xffff case 3 where b[0] == 0xbd: return Int(b[1]) * 256 + Int(b[2]) case 3 where b[0] == 0xad && b[1] == 0x8c: return (address + 3 + Int(Int8(bitPattern: b[2]))) & 0xffff case 4 where b[0] == 0xad && b[1] == 0x8d: return (address + 4 + Int(Int16(bitPattern: UInt16(b[2]) << 8 | UInt16(b[3])))) & 0xffff default: return nil // Indirect, tail, interrupt and guessed calls are unsupported. } } let calls = selected.instructions.filter { Int($0.address) + $0.bytes.count == returnPC && target($0) == function.entry } guard calls.count == 1, let call = calls.first, sharedPaths.contains(call.sourcePath), guarded(Int(call.address), call.bytes, moduleID: call.moduleID), let caller = debug.entryFunction(containing: call.address), normal(caller), sharedPaths.contains(caller.sourcePath), caller.moduleID == call.moduleID, caller.name.utf8.count <= 1024, caller.sourcePath.utf8.count <= 4096, Int(call.address) >= caller.body else { return result } result["caller"] = ["status": "available", "function": caller.name, "source_path": caller.sourcePath, "source_line": call.sourceLine, "call_address": Int(call.address), "return_address": returnPC, "evidence": "unique_verified_direct_call", "callee_phase": phase] let parameters = debug.variables.filter { $0.sourcePath == function.sourcePath && sharedPaths.contains($0.sourcePath) && $0.moduleID == function.moduleID && ($0.scopeModuleID == nil || $0.scopeModuleID == function.moduleID) && !$0.isStatic && $0.address == nil && $0.scope == (function.body..= 4 }.sorted { ($0.offset ?? 0) < ($1.offset ?? 0) } var items: [[String: Any]] = [], occupied = Set(), names = Set() for (index, parameter) in parameters.prefix(32).enumerated() { guard let offset = parameter.offset, offset <= 32767, !parameter.name.isEmpty, parameter.name.utf8.count <= 1024, parameters.filter({ $0.name == parameter.name }).count == 1, names.insert(parameter.name).inserted else { continue } let address = frameBase + offset, type = parameter.type guard type.kind == "integer", [1, 2, 4].contains(type.size), type.name.utf8.count <= 1024, let signed = type.signed, address >= start, address <= limit - type.size, !parameters.enumerated().contains(where: { otherIndex, other in guard otherIndex != index, let otherOffset = other.offset, otherOffset <= 32767, other.type.size > 0, other.type.size <= 65536 else { return false } return offset < otherOffset + other.type.size && otherOffset < offset + type.size }), (address..<(address + type.size)).allSatisfy({ !occupied.contains($0) }) else { continue } var value: Int64 = 0 for byte in memory[address..<(address + type.size)] { value = value * 256 + Int64(byte) } if signed && memory[address] & 0x80 != 0 { value -= Int64(1) << (type.size * 8) } occupied.formUnion(address..<(address + type.size)) items.append(["name": parameter.name, "type": type.name, "address": address, "frame_offset": offset, "byte_count": type.size, "value": value, "evidence": "compiler_location_and_normal_cmoc_abi"]) } result["arguments"] = ["status": items.isEmpty ? "unavailable" : "available", "items": items, "reason": "Only compiler-located integer parameters wholly inside the actual S window are interpreted; other values remain unavailable.", "all_recorded_parameters_available": !parameters.isEmpty && items.count == parameters.count, "recorded_parameter_count": parameters.count] return result } }