// SPDX-License-Identifier: GPL-3.0-or-later import Foundation /// Conservative unwinding of CMOC's unoptimized, preserved-U calling convention. /// Never scans arbitrary stack words for plausible code addresses. An unknown /// boundary ends the chain instead of silently skipping an intervening frame. struct CMOCCallStack: Sendable { struct Frame: Identifiable, Sendable { let id: Int let functionName: String let sourcePath: String let sourceLine: Int? /// Current PC for frame zero; the actual calling instruction for callers. let pc: UInt16 let u: UInt16 let localsInspectable: Bool } let frames: [Frame] /// Why the verified chain ended. This is not necessarily the program root. let termination: String static func capture(metadata: CMOCVariableDebug, pc: UInt16, u: UInt16, s: UInt16, memory: Data, available: Data, maximumFrames: Int = 64) -> Self { guard memory.count == 65536, available.count == 65536 else { return Self(frames: [], termination: "A complete paused memory snapshot is required.") } guard metadata.sourceMap.verifiesRuntime(memory: memory, available: available) else { return Self(frames: [], termination: "Executable bytes changed or became unavailable; reconnect the build before inspecting its call stack.") } func readable(_ start: Int, _ count: Int) -> Bool { start >= 0 && count >= 0 && start <= 0xfe00 - count && available[start..<(start + count)].allSatisfy { $0 != 0 } } var verifiedBytes: [Int: UInt8] = [:] for instruction in metadata.sourceMap.instructions { let at = Int(instruction.address) guard readable(at, instruction.bytes.count), Array(memory[at..<(at + instruction.bytes.count)]) == instruction.bytes else { return Self(frames: [], termination: "Executable bytes changed or became unavailable; reconnect the build before inspecting its call stack.") } for (offset, byte) in instruction.bytes.enumerated() { verifiedBytes[at + offset] = byte } } func bytes(_ at: Int, _ expected: [UInt8]) -> Bool { readable(at, expected.count) && expected.enumerated().allSatisfy { verifiedBytes[at + $0.offset] == $0.element } } func word(_ at: Int) -> Int { Int(memory[at]) * 256 + Int(memory[at + 1]) } func function(at address: Int) -> CMOCVariableDebug.Function? { let matches = metadata.functions.filter { let epilogueSize = bytes($0.end, [0x32, 0xc4, 0x35, 0xc0]) ? 4 : (bytes($0.end, [0x32, 0xc4, 0x35, 0x40, 0x3b]) ? 5 : 0) return $0.entry <= address && address < $0.end + epilogueSize } return matches.count == 1 ? matches[0] : nil } func supported(_ function: CMOCVariableDebug.Function) -> Bool { // CMOC FunctionDef emits PSHS U; LEAU ,S before local allocation, // then LEAS ,U; PULS U,PC after its metadata end label. ISR epilogues // use PULS U; RTI and are intentionally not treated as normal calls. function.frame && bytes(function.entry, [0x34, 0x40, 0x33, 0xe4]) && bytes(function.end, [0x32, 0xc4, 0x35, 0xc0]) } func target(of instruction: CMOCProjectSourceMap.Instruction) -> Int? { let b = instruction.bytes, next = Int(instruction.address) + b.count if b.count == 3 && b[0] == 0x17 { // LBSR, signed relative displacement return (next + Int(Int16(bitPattern: UInt16(b[1]) << 8 | UInt16(b[2])))) & 0xffff } if b.count == 2 && b[0] == 0x8d { return (next + Int(Int8(bitPattern: b[1]))) & 0xffff } if b.count == 3 && b[0] == 0xbd { return Int(b[1]) * 256 + Int(b[2]) } // JSR n,PCR is statically resolvable; register/indirect calls aren't. if b.count == 3 && b[0] == 0xad && b[1] == 0x8c { return (next + Int(Int8(bitPattern: b[2]))) & 0xffff } if b.count == 4 && b[0] == 0xad && b[1] == 0x8d { return (next + Int(Int16(bitPattern: UInt16(b[2]) << 8 | UInt16(b[3])))) & 0xffff } return nil } var frames: [Frame] = [], currentPC = Int(pc), frameU = Int(u), visited = Set() var stackFloor = Int(s) let limit = min(max(maximumFrames, 1), 128) while frames.count < limit { guard let current = function(at: currentPC) else { return Self(frames: frames, termination: "The next location is outside an unambiguous verified C function; the remaining stack is unavailable.") } let location = metadata.sourceMap.location(at: UInt16(currentPC)) let inBody = current.body <= currentPC && currentPC < current.end && location != nil let validStorage = readable(frameU, 4) && stackFloor <= frameU && !visited.contains(frameU) let inspectable = supported(current) && inBody && validStorage frames.append(Frame(id: frames.count, functionName: current.name, sourcePath: location?.path ?? current.sourcePath, sourceLine: location?.line, pc: UInt16(currentPC), u: UInt16(frameU), localsInspectable: inspectable)) guard supported(current) else { return Self(frames: frames, termination: "This frame uses optimized, interrupt, assembly, or other unsupported stack code. Its locals and remaining callers are unavailable.") } guard inBody else { return Self(frames: frames, termination: "Stopped in a function prologue, epilogue, or unmapped instruction; its frame pointer cannot be assumed valid yet.") } guard validStorage else { return Self(frames: frames, termination: "The frame pointer is outside readable stack memory or repeats an earlier frame; unwinding stopped.") } visited.insert(frameU) let olderU = word(frameU), returnPC = word(frameU + 2) let calls = metadata.sourceMap.instructions.filter { Int($0.address) + $0.bytes.count == returnPC && target(of: $0) == current.entry } guard calls.count == 1, let call = calls.first, let caller = function(at: Int(call.address)), caller.body <= Int(call.address), Int(call.address) < caller.end else { return Self(frames: frames, termination: "The caller is outside verified C code or its call target cannot be proved. Runtime, indirect-call and unknown boundaries stop unwinding here.") } guard olderU >= frameU + 4, readable(olderU, 4), !visited.contains(olderU) else { return Self(frames: frames, termination: "The saved caller frame pointer is invalid, unavailable or non-increasing; unwinding stopped.") } stackFloor = frameU + 4 frameU = olderU currentPC = Int(call.address) } return Self(frames: frames, termination: "The call stack reached its \(limit)-frame inspection limit; additional callers are not shown.") } }