All files / src breakpoints.js

96.92% Statements 189/195
95.77% Branches 136/142
94.73% Functions 54/57
98.69% Lines 151/153

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385        137x 137x 137x 137x 137x           137x           137x             274x 10x 10x 93123x 93123x 93123x         137x           137x 4x         4x     5x 3x 64647x 28476x                                                                             327x 1x                   835x 835x   835x 835x 835x 3340x                 168x 168x 168x 168x 168x         4x                   20x 20x 20x 19x 19x       20x 20x 20x       1x 1x         177x       1x 1x         3073x 3073x         19984x         848x 848x         601x 601x       3113x 3113x 3111x       3092x       191x 191x 189x 25x 2x   164x 164x 164x 164x 161x   181x 3x 178x 177x 1x 176x 191x 1x 175x 175x 175x 175x 3x 172x 172x 171x                                             744x 186x       397x         888x 744x 744x 562x 562x 562x   182x 203x   182x     130624x     744x         141x 130633x                 10x 40x 92x   40x 9x 9x 9x 9x 13x 4x 4x   4x 4x   4x     10x         93414x 93414x               93426x 93426x 93420x 298x 298x 143x           130624x 130624x 93413x   93413x 93410x 93410x 93410x 93422x 131x 128x                 128x 128x 128x 128x 128x 93422x   93410x       137x 1x 1x 1x 1x         10x 9x     1x   10x 10x    
import { compileCondition } from "./conditions.js";
import { hexbyte, hexword } from "./hex.js";
import { requireBank } from "./paging.js";
 
const Actions = ["stop", "log"];
const AddressSpace = 0x10000;
const LastAddress = AddressSpace - 1;
export const BrkOpcode = 0x00;
const AccessesOfKind = new Map([
    ["execute", ["execute"]],
    ["read", ["read"]],
    ["write", ["write"]],
    ["access", ["read", "write"]],
]);
const HookOfAccess = new Map([
    ["execute", "debugInstruction"],
    ["read", "debugRead"],
    ["write", "debugWrite"],
    ["interrupt", "debugInterrupt"],
]);
const Accesses = [...HookOfAccess.keys()];
 
/**
 * Makes tests of whether `holds(cpu, entry)` has turned true since the last instruction tested, which the first never
 * has.
 */
function turns(holds) {
    return () => {
        let held = null;
        return (cpu, entry) => {
            const had = held;
            held = holds(cpu, entry);
            return held && had === false;
        };
    };
}
 
const takenIs = (cpu, entry, address, value, taken) => taken === entry.kind;
 
/**
 * The kinds with no address: each acts on the instructions, or the interrupts, its test picks out. `firesOn` makes
 * a fresh test, as a test that a change has happened keeps what it saw last.
 */
const EventKinds = new Map([
    ["brk", { access: "execute", firesOn: () => (cpu, entry, address, opcode) => opcode === BrkOpcode }],
    [
        "undocumented",
        {
            access: "execute",
            firesOn: () => (cpu, entry, address, opcode) => !cpu.disassembler.isDocumentedOpcode(opcode),
        },
    ],
    ["irq", { access: "interrupt", firesOn: () => takenIs }],
    ["nmi", { access: "interrupt", firesOn: () => takenIs }],
    ["vsync", { access: "execute", firesOn: turns((cpu) => cpu.video.beamPosition().inVSync) }],
    ["line", { access: "execute", firesOn: turns((cpu, entry) => cpu.video.beamPosition().line === entry.line) }],
]);
 
/**
 * @typedef {object} BreakpointSpec
 * @property {"execute" | "read" | "write" | "access" | "brk" | "undocumented" | "irq" | "nmi" | "vsync" | "line"} kind -
 * access is a read or a write. The rest have no address: brk and undocumented act before the CPU runs a BRK or an
 * undocumented opcode, irq and nmi as the CPU takes one, before the handler's first instruction, and vsync and line
 * before the first instruction after vsync starts or the beam reaches TV line `line`
 * @property {number} [start] - for an address kind
 * @property {number} [end] - the last address it covers; `start` if not given
 * @property {number} [bank] - only while this sideways bank is paged in where it is hit
 * @property {number} [line] - for a line breakpoint, the TV line, as the beam position counts them
 * @property {string} [condition]
 * @property {(address: number, value: number, pc: number) => boolean} [accepts] - a test of its own, after the
 * condition, for an owner whose rule a condition cannot say, such as a watch's
 * @property {number} [hitCount] - acts on this hit and every one after; 1 if not given
 * @property {boolean} [enabled] - true if not given
 * @property {"stop" | "log"} [action] - stop if not given
 * @property {string} [label]
 * @property {string} [owner] - "user" if not given
 * @property {(hit: BreakpointHit) => void} [onHit]
 */
 
/**
 * @typedef {object} BreakpointHit
 * @property {number} id
 * @property {BreakpointSpec["kind"]} kind
 * @property {"execute" | "read" | "write" | "interrupt"} access
 * @property {number} address - for an interrupt, its handler's
 * @property {number} [value] - the byte read or written
 * @property {number} [old] - the byte a write replaced
 * @property {number} [line] - a line breakpoint's
 * @property {number} pc - the instruction that made the access; for an interrupt, the one it returns to
 * @property {"stop" | "log"} action
 * @property {number} hits
 */
 
function requireAddress(what, address) {
    if (!Number.isInteger(address) || address < 0 || address >= AddressSpace)
        throw new Error(`Breakpoint ${what} ${address} is not an address from 0 to $ffff`);
}
 
/**
 * The CPU's breakpoints, as the debugger, the console and MachineSession all set them. While no enabled breakpoint
 * needs a kind of access, nothing is attached to the CPU's debug hook for it, so the CPU runs as fast as it does with
 * none. Reads include the CPU fetching instructions and their operands.
 */
export class Breakpoints {
    constructor(cpu) {
        this._cpu = cpu;
        this._nextId = 1;
        /** @type {Map<number, object>} */
        this._entries = new Map();
        this._changeListeners = new Set();
        this._hitListeners = new Set();
        this._watching = Object.fromEntries(Accesses.map((access) => [access, null]));
    }
 
    /**
     * Adds a breakpoint, returning its id. Throws, saying why, if `spec` does not describe one.
     * @param {BreakpointSpec} spec
     * @returns {number}
     */
    add(spec) {
        const checked = this._checked(spec);
        const id = this._nextId++;
        this._entries.set(id, { id, hits: 0, ...checked });
        this._changed();
        return id;
    }
 
    /** Throws, saying why, if `spec` does not describe a breakpoint this CPU can take. */
    check(spec) {
        this._checked(spec);
    }
 
    /**
     * Changes the fields `changes` gives of breakpoint `id`, keeping its hits. A new start without an end makes it
     * a single address.
     * @param {number} id
     * @param {Partial<BreakpointSpec>} changes
     */
    update(id, changes) {
        const entry = this._entry(id);
        const spec = { ...this._spec(entry), ...changes };
        if ("start" in changes && !("end" in changes)) spec.end = changes.start;
        this._entries.set(id, { id, hits: entry.hits, ...this._checked(spec) });
        this._changed();
    }
 
    remove(id) {
        this._entry(id);
        this._entries.delete(id);
        this._changed();
    }
 
    clear() {
        this._entries.clear();
        this._changed();
    }
 
    /** Starts each stop waiting for a change afresh, as the machine has jumped to a state it did not run into. */
    forgetSeen() {
        for (const entry of this._entries.values()) entry.fires = EventKinds.get(entry.kind)?.firesOn() ?? null;
    }
 
    resetHits() {
        for (const entry of this._entries.values()) entry.hits = 0;
        this._notify(this._changeListeners);
    }
 
    /** @returns {(BreakpointSpec & {id: number, hits: number})} */
    get(id) {
        const entry = this._entry(id);
        return { id, hits: entry.hits, ...this._spec(entry) };
    }
 
    /** @returns {(BreakpointSpec & {id: number, hits: number})[]} */
    list() {
        return [...this._entries.keys()].map((id) => this.get(id));
    }
 
    /** Calls `listener()` whenever a breakpoint is added, changed or removed; returns a function that stops it. */
    onChange(listener) {
        this._changeListeners.add(listener);
        return () => this._changeListeners.delete(listener);
    }
 
    /** Calls `listener(hit)` with each hit that stops or logs; returns a function that stops it. */
    onHit(listener) {
        this._hitListeners.add(listener);
        return () => this._hitListeners.delete(listener);
    }
 
    _entry(id) {
        const entry = this._entries.get(id);
        if (!entry) throw new Error(`No breakpoint with id ${id}`);
        return entry;
    }
 
    _spec({ kind, start, end, bank, line, condition, accepts, hitCount, enabled, action, label, owner, onHit }) {
        return { kind, start, end, bank, line, condition, accepts, hitCount, enabled, action, label, owner, onHit };
    }
 
    _checked({ kind, start, end, bank, line, condition, accepts, hitCount, enabled, action, label, owner, onHit }) {
        const event = EventKinds.get(kind);
        if (!event && !AccessesOfKind.has(kind)) throw new Error(`Unknown breakpoint type: ${kind}`);
        if (event) {
            if (start !== undefined || end !== undefined || bank !== undefined)
                throw new Error(`A breakpoint of kind ${kind} has no address`);
        } else {
            end ??= start;
            requireAddress("start", start);
            requireAddress("end", end);
            if (end < start) throw new Error(`Breakpoint end $${hexword(end)} is before its start $${hexword(start)}`);
            requireBank(bank, this._cpu.model);
        }
        if (kind === "line" && (!Number.isInteger(line) || line < 0))
            throw new Error(`Line ${line} is not a whole number from 0`);
        if (kind !== "line" && line !== undefined) throw new Error(`A breakpoint of kind ${kind} has no line`);
        if (condition !== undefined && typeof condition !== "string")
            throw new Error(`Breakpoint condition ${condition} is not text`);
        condition = condition?.trim() || undefined;
        if (enabled !== undefined && typeof enabled !== "boolean")
            throw new Error(`Breakpoint enabled ${enabled} is not true or false`);
        Iif (label !== undefined && typeof label !== "string") throw new Error(`Breakpoint label ${label} is not text`);
        Iif (owner !== undefined && typeof owner !== "string") throw new Error(`Breakpoint owner ${owner} is not text`);
        hitCount ??= 1;
        if (!Number.isInteger(hitCount) || hitCount < 1)
            throw new Error(`Hit count ${hitCount} is not a whole number from 1`);
        action ??= "stop";
        if (!Actions.includes(action)) throw new Error(`Breakpoint action ${action} is not stop or log`);
        return {
            kind,
            start,
            end,
            bank,
            line,
            accesses: event ? [event.access] : AccessesOfKind.get(kind),
            from: start ?? 0,
            to: end ?? LastAddress,
            fires: event?.firesOn() ?? null,
            condition,
            test: condition === undefined ? null : compileCondition(condition),
            hitCount,
            enabled: enabled ?? true,
            action,
            label,
            owner: owner ?? "user",
            accepts,
            onHit,
        };
    }
 
    _changed() {
        for (const access of Accesses) this._watch(access);
        this._notify(this._changeListeners);
    }
 
    _notify(listeners, ...args) {
        for (const listener of listeners) listener(...args);
    }
 
    /** Attaches the hook for `access` while an enabled breakpoint needs it, and only then. */
    _watch(access) {
        const entries = [...this._entries.values()].filter((entry) => entry.enabled && entry.accesses.includes(access));
        const watching = this._watching[access];
        if (!entries.length) {
            watching?.handler.remove();
            this._watching[access] = null;
            return;
        }
        const covered = new Uint8Array(AddressSpace);
        for (const { from, to } of entries) covered.fill(1, from, to + 1);
        const handler =
            watching?.handler ??
            this._cpu[HookOfAccess.get(access)].add(
                this._handler(access, (address, value, returnsTo, taken) =>
                    this._check(access, address, value, returnsTo, taken),
                ),
            );
        this._watching[access] = { handler, entries, covered };
    }
 
    /** A debug hook for `access` calling `check(address, value, returnsTo, taken)`. */
    _handler(access, check) {
        if (access === "interrupt") return (taken, returnsTo) => check(this._cpu.pc, 0, returnsTo, taken);
        return (address, value) => check(address, value & 0xff, undefined, undefined);
    }
 
    /**
     * Debug hooks, as `asReplay` takes them, that call `onHit(access, address)` wherever an enabled breakpoint that
     * stops would act in a replay, at every hit whatever its hit count, counting none and telling no one; null for
     * each kind of access none needs.
     */
    replayHooks(onHit) {
        const hook = (access) => {
            const entries = [...this._entries.values()].filter(
                (entry) => entry.enabled && entry.action === "stop" && entry.accesses.includes(access),
            );
            if (!entries.length) return null;
            const covered = new Uint8Array(AddressSpace);
            for (const { from, to } of entries) covered.fill(1, from, to + 1);
            const fires = new Map(entries.map((entry) => [entry, EventKinds.get(entry.kind)?.firesOn() ?? null]));
            return this._handler(access, (address, value, returnsTo, taken) => {
                if (!covered[address]) return;
                const { pc, old } = this._made(access, address, value, returnsTo);
                let acts = false;
                // Every entry is asked, so that each test for a change sees every instruction.
                for (const entry of entries) {
                    Eif (this._acts(entry, fires.get(entry), address, value, taken, pc, old)) acts = true;
                }
                Eif (acts) onHit(access, address);
            });
        };
        return { instruction: hook("execute"), read: hook("read"), write: hook("write"), interrupt: hook("interrupt") };
    }
 
    /** The instruction that made the access, for an interrupt the one it returns to, and the byte a write replaces. */
    _made(access, address, value, returnsTo) {
        const cpu = this._cpu;
        return {
            pc: { execute: address, interrupt: returnsTo }[access] ?? cpu.getPrevPc(0),
            old: access === "write" ? cpu.peekmem(address) : value,
        };
    }
 
    /** Whether `entry`, its change tested by `fires`, acts on the access, before its hit count is counted. */
    _acts(entry, fires, address, value, taken, pc, old) {
        const cpu = this._cpu;
        if (address < entry.from || address > entry.to) return false;
        if (fires && !fires(cpu, entry, address, value, taken)) return false;
        Iif (entry.bank !== undefined && !cpu.isBankPagedAt(entry.bank, address)) return false;
        if (entry.test && !entry.test(cpu, pc, value, old)) return false;
        return !entry.accepts || entry.accepts(address, value, pc);
    }
 
    /** `returnsTo` and `taken`, "irq" or "nmi", are an interrupt's. */
    _check(access, address, value, returnsTo, taken) {
        // A handler earlier in the same dispatch can remove the last breakpoint, detaching this one before its call.
        const watching = this._watching[access];
        if (!watching?.covered[address]) return false;
        const { entries } = watching;
        // An instruction a stop halted before runs on resuming; no execute breakpoint stops it a second time.
        if (access === "execute" && this._cpu.resumingFromStop) return false;
        const { pc, old } = this._made(access, address, value, returnsTo);
        let stop = false;
        for (const entry of entries) {
            if (!this._acts(entry, entry.fires, address, value, taken, pc, old)) continue;
            if (++entry.hits < entry.hitCount) continue;
            const hit = {
                id: entry.id,
                kind: entry.kind,
                access,
                address,
                pc,
                action: entry.action,
                hits: entry.hits,
            };
            if (access === "read" || access === "write") hit.value = value;
            if (access === "write") hit.old = old;
            if (entry.line !== undefined) hit.line = entry.line;
            if (entry.action === "stop") stop = true;
            entry.onHit?.(hit);
            this._notify(this._hitListeners, hit);
        }
        return stop;
    }
}
 
const EventPhrases = new Map([
    ["brk", () => "BRK"],
    ["undocumented", () => "undocumented opcode"],
    ["vsync", () => "vsync"],
    ["line", (line) => `line ${line}`],
]);
 
/** A line describing `hit`, as the console shows a logged one. */
export function describeHit({ id, kind, access, address, value, old, pc, line, hits }) {
    const what = {
        execute: () => EventPhrases.get(kind)?.(line) ?? `execute $${hexword(address)}`,
        read: () => `read $${hexbyte(value)} from $${hexword(address)}`,
        write: () => `write $${hexbyte(value)} (was $${hexbyte(old)}) to $${hexword(address)}`,
        interrupt: () => `${kind.toUpperCase()} to $${hexword(address)}`,
    }[access]();
    const at = access === "interrupt" ? "from" : "at";
    return `Breakpoint ${id}: ${what} ${at} pc $${hexword(pc)}, hit ${hits}`;
}