// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import Combine /// A window-owned inspector of the shared machine. It never owns another CPU /// and only asks for immutable captures on the machine's existing serial queue. @MainActor final class DebuggerModel: ObservableObject { let machine: MachineModel @Published private(set) var snapshot: VCCDebuggerSnapshot? @Published private(set) var changedRegisters: Set = [] @Published var followPC = true enum CodePane: String, CaseIterable { case disassembly = "Disassembly", source = "Source" } @Published var codePane = CodePane.disassembly @Published private(set) var listing: DebugSourceListing? @Published private(set) var listingLoading = false @Published var sourceFollowPC = true @Published var selectedSourceLine: Int? @Published var sourceSearch = "" @Published var sourceMessage: String? private var listingRequest = UUID() @Published var addressText = "8000" enum MemorySpace: String, CaseIterable { case mapped = "Mapped CPU", physical = "Physical RAM" } enum MemoryPane: String, CaseIterable { case memory = "Memory", mmu = "MMU" } @Published var memoryPane = MemoryPane.memory @Published private(set) var memorySpace = MemorySpace.mapped @Published var memoryAddressText = "0000" @Published var physicalAddressText = "000000" @Published var pcText = "" @Published var breakpointText = "" @Published var editAddressText = "" @Published var editByteText = "" @Published var validationMessage: String? @Published private(set) var commandPending = false private var address: UInt16 = 0x8000 @Published private(set) var highlightedByte: UInt32? private var memoryAddress: UInt16 = 0 private var physicalAddress: UInt32 = 0 private var readRequest: UUID? init(machine: MachineModel) { self.machine = machine } var paused: Bool { machine.state == .paused } var loaded: Bool { machine.state == .paused || machine.state == .running } var commandsAvailable: Bool { loaded && !machine.busy && !machine.diskSaving && !commandPending } var canEdit: Bool { commandsAvailable && paused } var breakpoints: [UInt16] { snapshot?.breakpoints.map { $0.uint16Value } ?? [] } var disabledBreakpoints: [UInt16] { snapshot?.disabledBreakpoints.map { $0.uint16Value } ?? [] } var allBreakpoints: [UInt16] { (breakpoints + disabledBreakpoints).sorted() } var programCounter: UInt16 { snapshot?.registers["PC"]?.uint16Value ?? 0 } var currentSourceLine: Int? { listing?.line(at: programCounter, preferring: selectedSourceLine) } var visibleSourceLine: Int? { sourceFollowPC ? currentSourceLine : selectedSourceLine } func loadListing(_ url: URL) async { let request = UUID(); listingRequest = request; listingLoading = true; sourceMessage = nil let result = await Task.detached(priority: .userInitiated) { Result { try DebugSourceListing.read(url) } }.value guard listingRequest == request else { return } listingLoading = false switch result { case .success(let listing): self.listing = listing; selectedSourceLine = nil; sourceFollowPC = true; codePane = .source case .failure(let error): sourceMessage = error.localizedDescription } } func unloadListing() { listingRequest = UUID(); listingLoading = false; listing = nil; selectedSourceLine = nil; sourceMessage = nil // Source breakpoints are the shared logical-address breakpoints. Closing // a document must not silently remove a user's execution controls. } func selectSourceLine(_ index: Int) { guard listing?.lines.indices.contains(index) == true else { return } selectedSourceLine = index; sourceFollowPC = false; sourceMessage = nil } func findSource() { guard let listing else { return } guard let index = listing.find(sourceSearch, after: selectedSourceLine) else { sourceMessage = sourceSearch.isEmpty ? "Enter text to find in the listing." : "No matching source line."; return } selectSourceLine(index) } func showDisassembly(at address: UInt16) { addressText = Self.hex(address); goToAddress(); codePane = .disassembly } var physical: Bool { memorySpace == .physical } var memory: [UInt8] { snapshot.map { Array(physical ? $0.physicalMemory : $0.memory) } ?? [] } var memoryAvailable: [UInt8] { physical ? Array(repeating: 1, count: memory.count) : snapshot.map { Array($0.memoryAvailable) } ?? [] } var displayedMemoryAddress: UInt32 { snapshot.map { physical ? $0.physicalAddress : UInt32($0.memoryAddress) } ?? 0 } var installedRAM: UInt32 { snapshot?.mmu.ramByteCount ?? 0 } var memoryAddressWidth: Int { physical ? 6 : 4 } var canEditMemory: Bool { canEdit && !physical } var canPreviousMemory: Bool { (physical ? physicalAddress : UInt32(memoryAddress)) > 0 } var canNextMemory: Bool { physical ? physicalAddress + 256 < installedRAM : UInt32(memoryAddress) + 256 < 65536 } func memoryLocation(offset: Int) -> UInt32 { let address = displayedMemoryAddress + UInt32(offset) return physical ? address : address & 0xffff } // A leading $ or 0x is accepted; all debugger addresses and byte values // are explicitly hexadecimal. Reject overflow instead of truncating it. static func hexadecimal(_ text: String, maximum: UInt32 = 0xffff) -> UInt16? { guard let value = hexadecimalAddress(text, maximum: min(maximum, 0xffff)) else { return nil } return UInt16(value) } static func hexadecimalAddress(_ text: String, maximum: UInt32) -> UInt32? { var value = text.trimmingCharacters(in: .whitespacesAndNewlines) if value.hasPrefix("$") { value.removeFirst() } else if value.lowercased().hasPrefix("0x") { value.removeFirst(2) } guard !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isHexDigit }), let parsed = UInt32(value, radix: 16), parsed <= maximum else { return nil } return parsed } static func hex(_ value: T, width: Int = 4) -> String { String(format: "%0*X", width, UInt32(truncatingIfNeeded: value)) } func poll() async { defer { // A queued immutable read can finish after the window disappears. // Discard that result, and permit a fresh capture on reopening. readRequest = nil commandPending = false } while !Task.isCancelled { refresh() do { try await Task.sleep(nanoseconds: 200_000_000) } catch { return } } } func refresh() { guard !commandPending else { return } capture() } private func capture(releasesCommand: Bool = false) { guard readRequest == nil, !machine.busy else { if releasesCommand { commandPending = false } return } let request = UUID() readRequest = request let requestedPhysicalAddress = physicalAddress let requestedPhysicalMemory = physical machine.readDebugger(address: address, followPC: followPC, memoryAddress: memoryAddress, physicalAddress: requestedPhysicalAddress, physicalMemory: requestedPhysicalMemory) { [weak self] capture in guard let self, self.readRequest == request else { return } self.readRequest = nil if releasesCommand { self.commandPending = false } guard let capture else { return } let registers = capture.registers if let previous = self.snapshot, previous.machine.generation == capture.machine.generation { let changes = Set(registers.compactMap { key, value in previous.registers[key] != value ? key : nil }) // Preserve the last instruction's highlights while paused; // repeated inspection is not another instruction. if !changes.isEmpty { self.changedRegisters = changes } } else { self.changedRegisters = [] } self.snapshot = capture // The bridge clamps an old physical location after a RAM-size // change. Preserve an unfinished text draft; only explicit Go // normalizes it to the newly accepted location. if requestedPhysicalMemory && self.physicalAddress == requestedPhysicalAddress { self.physicalAddress = capture.physicalAddress } } } private func perform(_ operation: (@escaping () -> Void) -> Void) { commandPending = true operation { [weak self] in guard let self else { return } // Do not accept a pre-command read or enable another breakpoint // mutation until its authoritative post-command list arrives. self.readRequest = nil self.capture(releasesCommand: true) } } func toggleExecution() { guard commandsAvailable else { return } validationMessage = nil if machine.state == .running { perform(machine.debuggerPause) } else { perform(machine.debuggerContinue) } } func step() { guard canEdit else { return } validationMessage = nil changedRegisters = [] perform(machine.debuggerStep) } func goToAddress() { guard let value = Self.hexadecimal(addressText) else { validationMessage = "Enter a hexadecimal address from 0000 to FFFF."; return } address = value; addressText = Self.hex(value); followPC = false validationMessage = nil; refresh() } func setMemorySpace(_ space: MemorySpace) { highlightedByte = nil; memorySpace = space; validationMessage = nil; refresh() } func showPhysicalMemory(at value: UInt32) { guard value < installedRAM else { validationMessage = "That physical address is outside installed RAM."; return } highlightedByte = nil physicalAddress = value & ~UInt32(15) physicalAddressText = Self.hex(physicalAddress, width: 6) memorySpace = .physical; memoryPane = .memory validationMessage = nil; refresh() } func pageMemory(forward: Bool) { guard forward ? canNextMemory : canPreviousMemory else { return } if physical { showPhysicalMemory(at: forward ? physicalAddress + 256 : physicalAddress >= 256 ? physicalAddress - 256 : 0) } else { showMemory(at: forward ? memoryAddress + 256 : memoryAddress >= 256 ? memoryAddress - 256 : 0) } } func showMemory(at value: UInt16) { memorySpace = .mapped; memoryPane = .memory highlightedByte = nil memoryAddress = value & 0xfff0 memoryAddressText = Self.hex(memoryAddress) validationMessage = nil; refresh() } func revealGraphicsByte(_ address: UInt32, physical: Bool) { if physical { showPhysicalMemory(at: address) } else if let logical = UInt16(exactly: address) { showMemory(at: logical) } highlightedByte = address } func goToMemory() { if physical { guard installedRAM > 0, let value = Self.hexadecimalAddress(physicalAddressText, maximum: installedRAM - 1) else { validationMessage = "Enter a physical RAM address from 000000 to \(Self.hex(installedRAM > 0 ? installedRAM - 1 : 0, width: 6))."; return } showPhysicalMemory(at: value); return } guard let value = Self.hexadecimal(memoryAddressText) else { validationMessage = "Enter a hexadecimal memory address from 0000 to FFFF."; return } showMemory(at: value) } func setPC() { guard canEdit else { return } guard let value = Self.hexadecimal(pcText) else { validationMessage = "Enter the new program counter in hexadecimal, from 0000 to FFFF."; return } setPC(to: value) } func setPC(to value: UInt16) { guard canEdit else { return } validationMessage = nil; pcText = Self.hex(value) perform { machine.debuggerSetPC(value, completion: $0) } } func addBreakpoint() { guard let value = Self.hexadecimal(breakpointText) else { validationMessage = "Enter a hexadecimal breakpoint address from 0000 to FFFF."; return } configureBreakpoints(Array(Set(breakpoints + [value])).sorted(), disabled: disabledBreakpoints.filter { $0 != value }) } func toggleBreakpoint(at value: UInt16) { if allBreakpoints.contains(value) { configureBreakpoints(breakpoints.filter { $0 != value }, disabled: disabledBreakpoints.filter { $0 != value }) } else { configureBreakpoints((breakpoints + [value]).sorted(), disabled: disabledBreakpoints) } } func setBreakpoint(_ value: UInt16, enabled: Bool) { guard allBreakpoints.contains(value) else { return } configureBreakpoints(enabled ? Array(Set(breakpoints + [value])).sorted() : breakpoints.filter { $0 != value }, disabled: enabled ? disabledBreakpoints.filter { $0 != value } : Array(Set(disabledBreakpoints + [value])).sorted()) } func removeAllBreakpoints() { configureBreakpoints([], disabled: []) } private func configureBreakpoints(_ addresses: [UInt16], disabled: [UInt16]) { guard commandsAvailable else { return } validationMessage = nil perform { machine.debuggerConfigureBreakpoints(addresses.map { NSNumber(value: $0) }, disabled: disabled.map { NSNumber(value: $0) }, completion: $0) } } func selectByte(offset: Int) { guard !physical, let snapshot, offset >= 0, offset < memory.count, offset < memoryAvailable.count, memoryAvailable[offset] != 0 else { return } highlightedByte = memoryLocation(offset: offset) editAddressText = Self.hex(snapshot.memoryAddress &+ UInt16(offset)) editByteText = Self.hex(UInt16(memory[offset]), width: 2) } func writeByte() { guard canEditMemory else { return } guard let target = Self.hexadecimal(editAddressText), let byte = Self.hexadecimal(editByteText, maximum: 0xff) else { validationMessage = "Enter a hexadecimal address (0000–FFFF) and byte (00–FF)."; return } validationMessage = nil perform { machine.debuggerWriteMemory(address: target, data: Data([UInt8(byte)]), completion: $0) } } }