Files
VCCPlusOSS/platforms/macos/App/MemoryToolsModel.swift
T

108 lines
5.7 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import Combine
@MainActor
final class MemoryToolsModel: ObservableObject {
enum Space: String, CaseIterable { case mapped = "Mapped CPU", physical = "Physical RAM" }
struct Row: Identifiable {
let id: Int
let location: UInt32
let logicalAddress: UInt16
let bytes: String
let mnemonic: String
let operand: String
}
let machine: MachineModel
@Published var space = Space.physical
@Published var startText = "000000"
@Published var endText = "0000FF"
@Published var logicalText = "0000"
@Published var os9 = false
@Published private(set) var pending = false
@Published private(set) var rows: [Row] = []
@Published private(set) var caption = "Capture memory to inspect it. The machine keeps its current running or paused state."
@Published var error: String?
@Published var saveMessage: String?
private(set) var capturedPhysical = true
private var subscriptions: Set<AnyCancellable> = []
init(machine: MachineModel) {
self.machine = machine
// Observe only command availability and RAM capacity, not the 60 Hz
// display publisher. A profile change must update range validation even
// while this tab retains an older, explicitly labeled capture.
let changes: [AnyPublisher<Void, Never>] = [
machine.$state.removeDuplicates().map { _ in () }.eraseToAnyPublisher(),
machine.$busy.removeDuplicates().map { _ in () }.eraseToAnyPublisher(),
machine.$diskSaving.removeDuplicates().map { _ in () }.eraseToAnyPublisher(),
machine.$settings.map(\.ram).removeDuplicates().map { _ in () }.eraseToAnyPublisher()
]
Publishers.MergeMany(changes).sink { [weak self] in self?.objectWillChange.send() }.store(in: &subscriptions)
}
var available: Bool { !pending && !machine.busy && !machine.diskSaving && (machine.state == .paused || machine.state == .running) }
var capacity: UInt32 { space == .mapped ? 65536 : [0x20000, 0x80000, 0x200000, 0x800000][min(3, max(0, machine.settings.ram))] }
static func range(start: String, end: String, capacity: UInt32) -> (UInt32, UInt32)? {
guard capacity > 0,
let first = DebuggerModel.hexadecimalAddress(start, maximum: capacity - 1),
let last = DebuggerModel.hexadecimalAddress(end, maximum: capacity - 1), last >= first else { return nil }
return (first, last - first + 1)
}
private func capture(decode: Bool) async -> VCCDebugMemoryCapture? {
guard available else { return nil }
guard let (start, length) = Self.range(start: startText, end: endText, capacity: capacity) else {
error = "Enter an inclusive hexadecimal range within 000000–\(DebuggerModel.hex(capacity - 1, width: 6)). The end must not precede the start."; return nil
}
let physical = space == .physical
guard let logical = decode && physical ? DebuggerModel.hexadecimal(logicalText) : 0 else {
error = "Enter a logical origin from 0000 to FFFF."; return nil
}
let interpretOS9 = os9
pending = true; error = nil; saveMessage = nil
defer { pending = false }
let capture: VCCDebugMemoryCapture? = await withCheckedContinuation { continuation in
machine.readDebuggerMemory(address: start, count: decode ? min(length, 4096) : length,
physical: physical, logicalAddress: logical, os9: interpretOS9, decode: decode) { continuation.resume(returning: $0) }
}
guard let capture else { error = "The machine is busy. Try again when its current operation finishes."; return nil }
guard capture.machine.errorMessage == nil else { error = capture.machine.errorMessage; return nil }
if decode {
capturedPhysical = physical
rows = capture.instructions.enumerated().map { index, instruction in
Row(id: index, location: capture.address + capture.instructionOffsets[index].uint32Value,
logicalAddress: instruction.address,
bytes: instruction.bytes.map { String(format: "%02X", $0) }.joined(separator: " "),
mnemonic: instruction.mnemonic, operand: instruction.operand)
}
caption = "\(physical ? "Physical RAM" : "Mapped CPU") capture at \(capture.machine.cycles.formatted()) cycles · \(rows.count) rows · \(capture.machine.use6309 ? "HD6309" : "MC6809")\(physical ? " · \(capture.capacity / 1024) KB captured RAM space" : "")\(interpretOS9 ? " · OS-9 interpretation" : "")"
}
return capture
}
func decode() async { _ = await capture(decode: true) }
func exportBytes() async -> Data? {
guard let result = await capture(decode: false) else { return nil }
guard !result.bytes.isEmpty, result.available.count == result.bytes.count,
result.available.allSatisfy({ $0 != 0 }) else {
error = "This range contains I/O that cannot be read without side effects. Choose a range excluding it, or export physical RAM. No file was written."
return nil
}
return result.bytes
}
func save(_ data: Data, to url: URL) async {
pending = true; error = nil
defer { pending = false }
do {
try await Task.detached {
let access = url.startAccessingSecurityScopedResource()
defer { if access { url.stopAccessingSecurityScopedResource() } }
try data.write(to: url, options: .atomic)
}.value
saveMessage = "Saved \(data.count.formatted()) raw bytes to \(url.lastPathComponent)."
} catch { self.error = error.localizedDescription }
}
}