diff --git a/doc/machine_code_monitor.md b/doc/machine_code_monitor.md new file mode 100644 index 000000000..983454045 --- /dev/null +++ b/doc/machine_code_monitor.md @@ -0,0 +1,756 @@ +# Machine Code Monitor + +The Machine Code Monitor is a keyboard-driven tool for inspecting and editing live or frozen C64 memory. + +It supports hexadecimal, ASCII, screen-code, binary, and assembly views, plus inline editing, bulk memory operations, file load/save, and execution from a selected address. + +You can also debug an assembly program by setting breakpoints, stepping through its execution, and observing its effects on memory and CPU state. + +## Entry and Exit + +`C=` denotes the Commodore key. For example, `C=+O` means: hold the Commodore key, then press `O`. + +To open the monitor, first open the device menu, then use one of the following: + +- Press `C=+O`. +- Press `F5`, open `Developer`, then select `Machine Code Monitor`. + +Open the built-in help with `F3` or `?`. + +While the monitor is open, `C=+X` resets / breaks the U64 from any monitor mode, including Help, Edit, Debug, and popups. + +To close the monitor: + +- Press `C=+O` again. +- Press `RUN/STOP` when no edit operation or popup is active. + +## Access Modes + +The machine code monitor can be opened in three ways: + +| Mode | C64 while monitor is open | Video stream | Use this when | +| -------------- | ------------------------- | ---------------------- | -------------------------------------------------------------------------------------------- | +| **UI Freeze Mode** | Frozen | Monitor is visible | You want full-screen monitor use, automatic freezing, or monitor output in the video stream. | +| **UI Overlay Mode** | Running, but can be frozen via `Z` shortcut or in debug mode | Monitor is invisible | You want to use the monitor while the C64 keeps running. | +| **Telnet** | Dito | Monitor is invisible | You want to use the monitor from another machine or in an automated way. | + +### Switching between UI Freeze and UI Overlay Modes + +Press `C=+I` to toggle between UI Freeze and UI Overlay mode. + +Toggling automatically closes the menu. The next time you open the menu, it uses the newly selected mode. + +## Screen Layout + +The machine code monitor screen has three fixed regions: header, body, and footer. + +```text ++--------------------------------------+ +|MONITOR ASM $E011 Undc Frz Pl Dbg Edit| +|... | +|CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000 | ++--------------------------------------+ +``` + +### Header + +The header shows the current monitor view, the cursor address, and any active mode indicators. + +Mode indicators may include any combination of the following: + +| Indicator | Meaning | +| --------- | -------------------------------- | +| `Undc` | Undocumented opcodes are decoded | +| `Frz` | Freeze is active | +| `Pl` | Polling is active | +| `Dbg` | Debug mode is active | +| `Edit` | Edit mode is active | + +### Body + +The body shows the memory region around the current cursor address. + +The active cursor position is highlighted in reverse. Depending on the current operation, the body may also show popups such as search results, load/save prompts, or bookmark lists. + +### Footer + +The footer shows the current memory-bank context and temporary status information. + +It includes: + +- The CPU memory configuration used by the monitor view. +- Any difference between the monitor view and the live CPU execution bank. +- The selected VIC bank and its base address. +- Temporary bookmark information after jumping to a bookmark. + +Common footer values include: + +| Value | Meaning | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `CPU0` to `CPU7` | The monitor view and live CPU execution bank match. | +| `CxOy` | The monitor view and live CPU execution bank differ. `Cx` is the live CPU execution bank. `Oy` is the monitor view bank selected with `O`. | +| `$A`, `$D`, `$E` | Show how the monitor view maps the main ROM/RAM regions. | +| `VIC0` to `VIC3` | Identify the selected VIC bank. The following address shows its base address. | + +For full details, see [CPU and VIC Bank Display](#cpu-and-vic-bank-display). + +## Views + +The monitor provides five primary views: + +| Key | View | ID | Purpose | +| --- | -------- | --- | ----------------------------- | +| `M` | Memory | HEX | Hexadecimal byte view | +| `A` | Assembly | ASM | (Dis)assembly with debug mode | +| `B` | Binary | BIN | Bit-level byte view | +| `I` | ASCII | ASC | ASCII byte view | +| `V` | Screen | SCR | Screen code view | + +### Memory / Hex View + +Memory view shows raw bytes in hexadecimal together with a compact printable-character preview. + +Example: + +```text ++--------------------------------------+ +|MONITOR HEX $0168 | +|00E0 85 85 85 85 85 85 86 86 ........ | +|00E8 86 86 86 86 86 87 87 87 ........ | +|00F0 87 87 87 F0 DB 00 00 00 ........ | +|00F8 00 00 00 00 00 00 00 20 ....... | +|0100 33 38 39 31 31 00 30 30 38911.00 | +|0108 30 30 00 00 10 10 35 02 00....5. | +|0110 00 00 10 10 35 02 00 00 ....5... | +|0118 1C 10 35 02 00 00 22 10 ..5...". | +|0120 35 02 00 00 28 10 35 02 5...(.5. | +|0128 00 10 35 02 00 00 32 10 ..5...2. | +|0130 35 02 00 00 38 10 35 02 5...8.5. | +|0138 00 00 3E 10 35 02 00 00 ..>.5... | +|0140 44 10 35 02 00 00 44 10 D.5...D. | +|0148 35 02 00 00 50 10 35 02 5...P.5. | +|0150 00 00 56 10 35 02 00 00 ..V.5... | +|0158 5C 10 35 02 00 00 62 10 \.5...b. | +|0160 35 02 00 00 68 10 35 02 5...h.5. | +|0168 00 00 6E 10 35 02 00 00 ..n.5... | +|CPU1 $A:RAM $D:CHR $E:RAM VIC0 $0000 | ++--------------------------------------+ +``` + +### Assembly View + +Assembly view shows decoded 6510 instructions, their instruction bytes, and the memory source used for each row. + +The highlighted address is the disassembly root: rows below it are decoded forward from that address, while rows above it are context only. Changing bytes before the highlighted address can refresh the context rows, but it will not silently change the instruction phase at the highlighted address. To inspect a different phase deliberately, move the root with the cursor keys or jump to the desired address. + +It also allows you to assemble instructions inline (in `E`dit mode) as well as debug code (in `D`ebug mode). + +Please see the **Edit Mode** respectively **Debug Mode** chapters below for more information. + +Example: + +```text ++--------------------------------------+ +|MONITOR ASM $E011 | +|DFF9 FF ??? [I/O]| +|DFFA 00 BRK [I/O]| +|DFFB 00 BRK [I/O]| +|DFFC FF ??? [I/O]| +|DFFD 00 BRK [I/O]| +|DFFE 00 BRK [I/O]| +|DFFF 00 BRK [I/O]| +|E000 85 56 STA $56 [KRN]| +|E002 20 0F BC JSR $BC0F [KRN]| +|E005 A5 61 LDA $61 [KRN]| +|E007 C9 88 CMP #$88 [KRN]| +|E009 90 03 BCC $E00E [KRN]| +|E00B 20 D4 BA JSR $BAD4 [KRN]| +|E00E 20 CC BC JSR $BCCC [KRN]| +|E011 A5 07 LDA $07 [KRN]| +|E013 18 CLC [KRN]| +|E014 69 81 ADC #$81 [KRN]| +|E016 F0 F3 BEQ $E00B [KRN]| +|CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000 | ++--------------------------------------+ +``` + +### Binary View + +Binary view shows each byte as eight bits, using `.` for a cleared bit and `*` for a set bit. It is useful for inspecting registers, character glyphs, sprite data, and other bit-oriented memory. + +Because C64 sprite data uses 3 bytes per row, binary view supports multiple `W`idth modes for viewing bytes in different groupings. + +The top status line shows the current byte address followed by the selected bit number, for example `$DC00/7`. Bit 7 is the most significant bit on the left, and bit 0 is the least significant bit on the right. + +Example: + +```text ++--------------------------------------+ +|MONITOR BIN $DC00/7 | +|DC00 ........ 00 | +|DC01 ******** FF | +|DC02 ******** FF | +|DC03 ........ 00 | +|DC04 *.*..*.* A5 | +|DC05 ...**.** 1B | +|DC06 ******** FF | +|DC07 ******** FF | +|DC08 ........ 00 | +|DC09 ........ 00 | +|DC0A ........ 00 | +|DC0B *..*...* 91 | +|DC0C ........ 00 | +|DC0D *......* 81 | +|DC0E .......* 01 | +|DC0F ....*... 08 | +|DC10 ........ 00 | +|DC11 ******** FF | +|CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000 | ++--------------------------------------+ +``` + +### ASCII View + +Use ASCII view when the bytes are intended to be printable ASCII rather than C64 screen codes. + +Behavior: + +- Bytes `$20-$7E` are shown as their normal ASCII characters. +- All other bytes are shown as `.`. +- Typing a printable ASCII character writes that character's byte value. +- Lowercase ASCII is preserved. + +Example: + +```text ++--------------------------------------+ +|MONITOR ASC $A000 | +|A000 .{.CBMBASIC0.A...................| +|A020 P........:..J.,.g.U.d...#....... | +|A040 U...j..}.....:Z.A.g.U.X...}...g. | +|A060 ....d.k......|.e..............g | +|A080 yi.yR.{*.{...z.p..F..}...Z..d.EN | +|A0A0 .FO.NEX.DATA.INPUT.DIM.REA.LE | +|A0C0 .GOT.RU.I.RESTOR.GOSU.RETUR.RE.S | +|A0E0 TO.O.WAI.LOA.SAVU.VERIF.DE.POK.PR| +|A100 INT.PRIN.CON.LIS.CLR.CM.SY.OPE.CL| +|A120 OS.GE.NE.TAB.T.F.SPC.THE.NO.STE. | +|A140 .....AN.O....SG.IN.AB.US.FR.PO.S | +|A160 Q.RN.LO.EX.CO.SI.TA.AT.PEE.LE.ST | +|A180 R.VA.AS.CHR.LEFT.RIGHT.MID.G..TO | +|A1A0 D.MANY FILE.FILE OPEN.FILE NOT OP| +|A1C0 E.FILE NOT FOUND.DEVICE NOT PRESE| +|A1E0 N.NOT INPUT FIL.NOT OUTPUT FIL.M | +|A200 ISSING FILE NAM.ILLEGAL DEVICE N | +|A220 UMBE.NEXT WITHOUT FO.SYNTA.RETUR | +|CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000 | ++--------------------------------------+ +``` + +### Screen View + +Use Screen view when the bytes represent C64 screen codes, for example when viewing screen RAM, which by default starts at `$0400`. + +Screen view is for screen-code bytes, not PETSCII text. + +The header shows the active screen charset mode: + +- `MONITOR SCR U/G $xxxx` for **Uppercase/Graphics** +- `MONITOR SCR L/U $xxxx` for **Lowercase/Uppercase** + +The active mode is changed with `U`; see [View Modifiers](#view-modifiers). + +#### Screen `U/G` + +- Displays `$00` as `@`. +- Displays `$01-$1A` as `A-Z`. +- Typing `A-Z` or `a-z` writes `$01-$1A`. + +#### Screen `L/U` + +- Displays `$01-$1A` as `a-z`. +- Displays `$41-$5A` as `A-Z`. +- Typing `a-z` writes `$01-$1A`. +- Typing `A-Z` writes `$41-$5A`. + +Example: + +```text ++--------------------------------------+ +|MONITOR SCR U/G $0400 | +|0400 █ | +|0420 ***** COMMODORE 64 BA | +|0440 SIC V3 ***** | +|0460 64K RAM | +|0480 SYSTEM 38911 BASIC BYTES FREE | +|04A0 | +|04C0 READY. | +|04E0 | +|0500 | +|0520 | +|0540 | +|0560 | +|0580 | +|05A0 | +|05C0 | +|05E0 | +|0600 | +|0620 | +|CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000 | ++--------------------------------------+ +``` + +Because the monitor is rendered with the firmware UI font rather than the live C64 character set, graphics bytes are shown with readable fallback glyphs instead of exact C64 glyph shapes. + +## View Modifiers + +Some keys modify the current view instead of switching to another view. + +### `U`: View-Specific Toggle + +`U` is context-sensitive: + +| View | `U` behavior | +| ----------- | ---------------------------------------------------------------- | +| Assembly | Toggles undocumented opcodes | +| Screen | Toggles the monitor-local screen charset between `U/G` and `L/U` | +| Other views | Ignored | + +In Assembly view, enabling undocumented opcodes affects how bytes are decoded and how assembly completion behaves. + +In Screen view, `U` changes only the monitor-local interpretation of screen codes. It does not change the live C64 character set. + +### `W`: Width Mode + +`W` is view-dependent: + +| View | `W` behavior | +| -------- | ------------------------------------ | +| Memory | Cycles `8 <-> 16` bytes per row | +| Binary | Cycles `1 -> 2 -> 3 -> 3S -> 4 -> 1` | +| ASCII | Fixed-width, 32 bytes per row | +| Screen | Fixed-width, 32 bytes per row | +| Assembly | Variable-width, 1 to 3 bytes | + +Binary width details: + +- `1`, `2`, and `3` show one, two, or three bytes as bit fields with a trailing hex preview. +- `3S` shows three bytes as one continuous 24-bit sprite-style row, with a hex preview. +- `4` shows four bytes as one continuous 32-bit row without a trailing hex preview. + +## Navigation and Context + +- `J`: jump to an address. +- `G`: exit the monitor and execute from an address. +- `F1` or `Shift+Space`: page up. +- `F7` or `Space`: page down. +- Assembly view, non-edit mode: `Up` / `Down` move to the previous / next instruction root; `Left` / `Right` move the decode root by one byte (`-1` / `+1`). +- `Enter`: in Assembly view, follow the target of a jumpable instruction, or return to the most recent saved source location when the current instruction is not jumpable and the follow stack is non-empty. +- `O`: cycle the monitor-view CPU port banking, `CPU0`..`CPU7`. This changes the monitor view only; it does not write `$0001`. +- `Shift+O`: cycle the VIC bank override. +- `Z`: toggle freeze when the backend supports it. +- `P`: toggle poll mode in the local monitor. Poll mode is unavailable over telnet. + +Addresses in command prompts are hexadecimal. + +### Follow/Return + +Follow code flow in the Assembly view: + +- `Enter` follows the resolved target when the cursor is on a jumpable instruction such as `JMP`, `JSR`, `BEQ`, `BNE`, `BCC`, `BCS`, `BMI`, `BPL`, `BVC`, or `BVS`. +- `Enter` returns to the most recent saved source location when the current Assembly instruction is not jumpable and the follow stack is non-empty. +- The follow stack holds up to 10 return locations. When it is full, the oldest entry is discarded and the newest 10 are kept. +- After each successful follow or return, the bottom row shows a compact zero-based follow-stack status for about 2 seconds, for example `F1 JMP $E000` and `F0 RET $A000`. + +### CPU and VIC Bank Display + +With the `O` and `Shift+O` keys, you can quickly toggle the CPU and VIC banks. + +#### CPU Banking + +The monitor shows two independent CPU banking states: + +- **CPU execution bank**: The live bank used by the running 6510 CPU. It is derived from the lowest three bits of `$0001`, the 6510 on-chip port register. This is the bank from which the CPU fetches and executes instructions. +- **Monitor view bank**: The bank selected in the machine code monitor with the `O` key. This controls which memory mapping the monitor displays while you browse the 64 KiB address space. + +When both banks are the same, the footer shows a single `CPUx` value, where `x` is a bank number from `0` to `7`: + +```text +CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000 +```` + +When the CPU execution bank and monitor view bank differ, the footer shows both values as `CxOy`: + +- `Cx` is the live CPU execution bank. +- `Oy` is the monitor view bank selected with the `O` key. + +Example: + +```text +C7O5 $A:RAM $D:I/O $E:RAM VIC0 $0000 +``` + +After a machine reset, the next fresh monitor open syncs its view bank to the live CPU execution bank, so +re-entry shows the memory the CPU is actually running. + +An ordinary monitor close/reopen with no reset in between still preserves a manually selected `O` view bank. + +In the normal no-cartridge configuration, the `$A`, `$D`, and `$E` fields describe how the selected monitor view maps the main ROM/RAM regions: + +| Field | Address range | Possible values | +| ----- | ------------- | ------------------- | +| `$A` | `$A000-$BFFF` | `BAS`, `RAM` | +| `$D` | `$D000-$DFFF` | `I/O`, `CHR`, `RAM` | +| `$E` | `$E000-$FFFF` | `KRN`, `RAM` | + +| Value | Meaning | +| ----- | --------------------------- | +| `BAS` | BASIC ROM | +| `I/O` | I/O registers and Color RAM | +| `CHR` | Character generator ROM | +| `KRN` | KERNAL ROM | +| `RAM` | RAM | + +Please note that cartridges can further affect the CPU-visible memory map through the expansion-port `GAME` and `EXROM` lines. + +#### VIC Banking + +`VIC0` to `VIC3` show the selected VIC bank, controlled by CIA 2 port A at `$DD00`: + +| Field | Address range | +| --------- | ------------ | +| `VIC0` | `$0000-$3FFF` | +| `VIC1` | `$4000-$7FFF` | +| `VIC2` | `$8000-$BFFF` | +| `VIC3` | `$C000-$FFFF` | + +Any change to the VIC bank selection is visible to the CPU and can affect a running program unless you are in freeze mode or stopped at a breakpoint. + +## Edit Mode + +All views support editing: + +- `E`: enter edit mode. +- `C=+E` or `RUN/STOP`: leave edit mode. + +Edit behavior is view-specific: + +| View | Edit behavior | +| -------- | --------------------------------------------------------------------------- | +| Memory | Type two hex nibbles to write one byte | +| ASCII | Type printable ASCII characters directly | +| Screen | Type screen characters using the active Screen charset mode | +| Binary | Type `0` or `Space` to clear the selected bit; type `1` or `*` to set it | +| Assembly | Edit instructions inline with mnemonic completion and direct operand typing | + +In edit mode, `Space` remains view-specific data entry and does not page. + +In Assembly edit mode, `Left` / `Right` move between editable parts of the current instruction. They do not change the disassembly root unless the cursor is already at the first or last editable part, where the existing row-to-row edit navigation applies. `Up` / `Down` move to the previous / next instruction row. + +`DEL` is logical delete, not raw backspace: + +| View | `DEL` behavior | +| ------------ | ----------------------------------------------- | +| Memory | Writes `$00` and advances | +| ASCII/Screen | Writes a space | +| Binary | Clears the selected bit | +| Assembly | Replaces the current instruction with `NOP` bytes | + +In Assembly view, if an inline edit is already active, `DEL` first cancels the current line edit state. + +## Selection and Clipboard + +- Copy the current byte with `C=+C`. +- Paste the clipboard at the cursor with `C=+V`. +- Toggle range mode with `R`. + +Range mode anchors the current address. The selected span runs from the anchor address to the current cursor address, inclusive. + +While range mode is active: + +- `C=+C` copies the selected span. +- Pressing `R` again also copies the selected span and exits range mode. + +## Number Tool + +- Open the number tool with `N`. + +The number tool is a compact base-conversion and overwrite popup for the current target. It shows the same value in these forms: + +- Hex +- Decimal +- Binary +- ASCII +- Screen code + +In Assembly view, the number tool targets the operand bytes of the current instruction when possible. + +The ASCII and Screen rows in the number tool use the same mappings as the ASCII and Screen views. + +### Calculator + +In the Number popup, press `+`, `-`, `*`, or `/` to open the calculator. The expression is initialized with the current value and the selected operator. + +Press `Return` or `=` to evaluate the expression. Press `RUN/STOP` to cancel. On success, the popup returns to the compact conversion layout and refreshes all rows with the result. + +Expressions may contain one or more values separated by `+`, `-`, `*`, or `/`. * and / are evaluated before + and -. Division is unsigned integer division and truncates toward zero. + +Examples: + +```text +42 +$1000+4 +$2000/16 +%1010*3 +1+2/3 +2+3*4 +```` + +Formal EBNF grammar: + +```ebnf +expr = term, { ("+" | "-"), term } ; +term = value, { ("*" | "/"), value } ; +value = hex | decimal | binary ; + +hex = "$", hex_digits ; +decimal = decimal_digits ; +binary = "%", binary_digits ; +``` + +## Memory Operations + +The monitor includes direct bulk memory commands: + +| Key | Command | Syntax | Result | +| --- | -------- | ---------------------------------------- | --------------------------------------------------------------------- | +| `F` | Fill | `start-end,value` | Fill an inclusive range with one byte | +| `T` | Transfer | `start-end,dest[,program-start-program-end]` | Copy a range; optional program range amends absolute operands that point into the moved range | +| `C` | Compare | `start-end,dest` | Compare a range against another location and list differing addresses | +| `H` | Hunt | `start-end,bytes` or `start-end,"text"` | Search for a byte sequence or quoted ASCII string | + +`Hunt` opens a result picker: + +`Transfer` normally copies bytes only. When the optional program range is +supplied, the monitor treats that range as 6502 code and amends every 16-bit +absolute operand whose value points into the moved source range so it points at +the destination copy. This applies to all absolute operands, not just `JMP` and +`JSR`. + +- `Return`: jump to the selected match. +- `RUN/STOP`: close the picker. + +## File I/O + +- `L`: load a file into memory. +- `S`: save memory to a file. + +Files may exist directly in the Ultimate filesystem or inside a disk image such as `.D64`. + +### Load + +Load is a two-step flow: + +1. Pick a file. +2. Enter load parameters. + +In the file picker, select an existing file by pressing `ENTER` on it, then choosing `Select` from the context-sensitive menu. + +Load syntax: + +```text +[PRG|AAAA],[Offset],[Len|AUTO] +```` + +Default: + +```text +PRG,0000,AUTO +``` + +This loads the whole file to the start address stored in its first two bytes. + +Fields: + +| Field | Meaning | +| --------------- | ------------------------------------------------------------------------------- | +| `PRG` or `AAAA` | Use the two-byte load address from the PRG file, or load to an explicit address | +| `Offset` | Number of bytes to skip after the PRG header | +| `Len` or `AUTO` | Load the automatically determined length, or load an explicit byte count | + +Examples: + +| Input | Meaning | +| ---------------- | ------------------------------------------------- | +| `PRG` | Load a PRG to its embedded load address | +| `0801` | Load to `$0801` | +| `PRG,1000` | Skip `$1000` bytes after the PRG header | +| `0801,0002,0010` | Load `$0010` bytes from offset `$0002` to `$0801` | + +### Save + +Save is a two-step flow: + +1. Enter the byte range to save. +2. Pick or create the destination file. + +Save syntax: + +```text +0800-9FFF +``` + +The range is inclusive. Save writes a normal PRG file with a two-byte load address header. + +In the file picker, choose one of the following: + +- Select an existing file by pressing `ENTER` on it, then choosing `Select` from the context-sensitive menu. +- Create a new file by selecting `<< Create new file >>`. + +## Bookmarks + +The monitor has 10 persistent bookmark slots. + +- List bookmarks with `C=+B`. +- Jump directly to a slot with `C=+0` .. `C=+9`. + +Each bookmark stores: + +- Label +- Address +- View ID +- View width or width mode where applicable +- CPU bank +- VIC bank + +Bookmark popup controls: + +| Key | Action | +| ----------- | ------------------------------------------------- | +| `Up`/`Down` | Select a slot | +| `Return` | Restore the selected slot | +| `S` | Store the current location into the selected slot | +| `L` | Edit the label | +| `DEL` | Reset the slot to its default | +| `0`..`9` | Jump directly to that slot | + +Default slots are aimed at common C64 locations: + +```text ++--------------------------------------+ +|BOOKMARKS | +| | +|0 ZERO $0000 HEX 8 CPU7 VIC0 | +|1 SCREEN $0400 SCR 32 CPU7 VIC0 | +|2 BASIC $0801 ASM CPU7 VIC0 | +|3 BASROM $A000 ASM CPU7 VIC0 | +|4 HIRAM $C000 ASM CPU7 VIC0 | +|5 VIC $D000 HEX 8 CPU7 VIC0 | +|6 SID $D400 HEX 8 CPU7 VIC0 | +|7 CIA1 $DC00 BIN 1 CPU7 VIC0 | +|8 CIA2 $DD00 BIN 1 CPU7 VIC0 | +|9 KERNAL $E000 ASM CPU7 VIC0 | +| | +|0-9/RET Jmp S Set L Label DEL Reset| ++--------------------------------------+ +``` + +## Debug Mode + +Debug is a modal state layered on the Assembly view. + +Entering Debug does not execute CPU instructions by itself; execution only happens when an explicit Debug command (`D` for Over, `T` for Trace, `U` for Out, `G` for Go) is pressed while Debug is active. + +| Key | Outside Debug | Inside Debug | +| --- | --- | --- | +| `D` | Enter Debug, no execution | Debug (aka Step Over) | +| `T` | Transfer memory | Trace (aka Step Into) | +| `U` | Undoc/Case toggle | Step Out | +| `O` | CPU bank cycle | CPU bank cycle | +| `G` | Go / execute | Go | +| `R` | Range mode | Toggle breakpoint | +| `C=+R` | (unassigned) | Breakpoint list | +| `RUN/STOP` | Normal monitor close | Leave Edit first, then Debug | +| `C=+D` | (unassigned) | Exit Debug | +| `C=+X` | Reset / break the machine | Reset / break the machine | +| `RETURN` | Assembly follow / return | Assembly follow / return | + +Notes: + +- Important distinction between `RETURN` vs. `T`/`U`: + - `RETURN` is non-executing subroutine navigation. This is to explore the code without executing it. + - `T` (step into) and `U` (step out) is executing subroutine navigation. This is to follow the CPU's call stack. +- Inside Debug, `U` is Step Out, overriding the Assembly-view undocumented-opcode toggle. `O` remains the monitor view CPU bank cycle so the view bank can still be changed while Debug is active. +- In Debug + Edit, `RUN/STOP` / `ESC` unwind one mode at a time: the first press leaves `Edit` and keeps `Dbg`, the second leaves `Dbg`. +- `B` keeps Binary view and `C=+B` keeps the bookmark overview. Neither is repurposed for breakpoints. +- Current-PC disassembly, branch or jump prediction, stepping, and temporary step breakpoints follow the live CPU bank from `$0001`, not the monitor view selected by `O`. + +### CPU footer + +The bottom two rows of the monitor are reserved for a fixed-position CPU state table while Debug is active: + +```text +PC AC XR YR SP NV-BDIZC IRQ NMI +C003 01 00 FF F7 00100100 C123 EA31 +``` + +| Field | Meaning | +| --- | --- | +| `PC` | Program counter from the captured debug context | +| `AC` / `XR` / `YR` | Accumulator and index registers | +| `SP` | Stack pointer | +| `NV-BDIZC` | Status register bits 7..0 as an 8-character binary string | +| `IRQ` | RAM IRQ vector at `$0314/$0315`, when valid | +| `NMI` | RAM NMI vector at `$0318/$0319`, when valid | + +Notes: + +- The values between program counter and status register (inclusive) are highlighted in the same color as the `Dbg` or `Edit` header flags to improve visibility. +- Unknown values render as blank spaces in their reserved fixed-width columns; they never appear as zeros, `?`, or placeholder text. Field positions stay put when values become known. + +### Breakpoints + +There are 10 breakpoint slots: + +- `R` toggles a breakpoint at the current Assembly address in the memory source enabled through `O`. +- Opcode rows with a breakpoint show `[BRKx]` immediately before the memory source marker, for example `[BRK0][BAS]`. +- Breakpoints are kept in volatile RAM. They survive a `C=+X` reset and an ordinary monitor close/reopen, but power-cycling the device clears them. +- Breakpoints refer to an address in a specific memory source. For example,`$E000 KRN` and `$E000 RAM` are distinct breakpoints and can coexist. +- A breakpoint can be valid but invisible to the live CPU. If you see the popup `BRK , CPU ; not mapped now`, it means the breakpoint was set in ``, but the running program must first activate the relevant bank so that the breakpoint will pause the CPU. +- On U64, breakpoints in BASIC, KERNAL, and character ROM use temporary patches in the volatile U64 ROM image, so ROM code remains step-capable without copying ROMs into C64 RAM or writing flash. +- RAM-under-KERNAL breakpoints work when KERNAL is banked out. + +`C=+R` opens the breakpoint list which offers these shortcuts (the popup help row uses abbreviated forms in parentheses to fit the line): + +| Key | Action | +| --- | --- | +| `Up` / `Down` | Select slot | +| `Return` | Jump to the selected slot | +| `0`-`9` | Jump directly to a slot (`Jmp`) | +| `S` | Store the current address into the selected slot (`Sto`) | +| `L` | Change the label, up to 4 chars (`Lab`) | +| `E` | Toggle slot enable / disable (`En`) | +| `DEL` | Reset the selected slot (`Res`) | +| `RUN/STOP` | Close the popup | + +### Help screen + +`F3` or `?` shows the Debug help screen while Debug is active. + +It keeps the normal help layout, replaces the keys Debug owns with Debug actions, and highlights those Debug shortcuts with the same accent color used for the `Dbg` and `Edit` header flags. + +`RETURN` remains non-executing follow / return navigation; `U` is executing step-out. `C=+X Reset` is the emergency reset / break shortcut. + +### Hardware support + +| Capability | U64 (Elite) | U2 / U2+ cartridge | +| --------------------------------------- | ----------- | ------------------ | +| Memory view, edit, fill, compare | Yes | Yes | +| `G` jump to address | Yes | Yes | +| BRK-based step / over / trace / out | Yes | Yes | +| Breakpoints in C64 RAM | Yes | Yes | +| Breakpoints in BASIC / KERNAL / CHAR ROM | Yes (volatile U64 ROM-image patch) | Not available - C64 ROM is read-only from the cartridge | +| Monitor-side CPU bank selection (`O`) | Yes | Not available - status line shows `CPU BANK N/A` | +| Monitor-side VIC bank selection (`SH+O`) | Yes | Not available - status line shows `VIC N/A` | +| Freeze toggle (`Z`) | Yes | Not available | +| REST `/v1/machine` memory API | Yes | Yes | diff --git a/software/components/indexed_list.h b/software/components/indexed_list.h index 9f0f12f2c..2e945ac05 100644 --- a/software/components/indexed_list.h +++ b/software/components/indexed_list.h @@ -98,6 +98,20 @@ class IndexedList LEAVE_SAFE_SECTION // printf("ed. El=%d. Size=%d\n", elements, size); } + + void prepend(T el) { + ENTER_SAFE_SECTION + if(elements == size) + expand(); + for(int i=elements; i>0; i--) { + element_array[i] = element_array[i-1]; + removal[i] = removal[i-1]; + } + element_array[0] = el; + removal[0] = 0; + elements++; + LEAVE_SAFE_SECTION + } int remove(T el) { ENTER_SAFE_SECTION diff --git a/software/infra/host.h b/software/infra/host.h index faee5e31b..d8c1849bd 100644 --- a/software/infra/host.h +++ b/software/infra/host.h @@ -41,6 +41,7 @@ class HostClient virtual ~HostClient() { } virtual void release_host() { } + virtual bool request_reset_reentry_after_c64_reset() { return false; } }; #endif diff --git a/software/io/c64/c64.cc b/software/io/c64/c64.cc index 7127953aa..5eb3c7402 100644 --- a/software/io/c64/c64.cc +++ b/software/io/c64/c64.cc @@ -39,6 +39,68 @@ #include "u64_machine.h" #endif +#if U64 +// Pristine FPGA ROM-image snapshot + dirty flag. The machine-code monitor's debug +// engine steps RAM-under-ROM and KERNAL/BASIC ROM by patching BRK traps directly +// into the FPGA ROM-image buffers (U64_*_BASE). If such a patch is not restored +// before a reset (e.g. a REST reset fired while the debug CPU is parked), the +// stale byte stays in the KERNAL image and the next C64 reset executes it during +// early boot, wedging the machine (blank screen, no READY, frozen jiffy) with no +// recovery short of a JTAG ROM reload. To make every reset self-healing we capture +// the authoritative ROM image once it is loaded (init_system_roms) and re-apply it +// on reset whenever the monitor has flagged the image dirty. +namespace { + uint8_t s_pristine_kernal[8192]; + uint8_t s_pristine_basic[8192]; + bool s_pristine_rom_valid = false; +} +extern "C" volatile bool g_u64_rom_image_dirty = false; +extern "C" void u64_mark_rom_image_dirty(void) { g_u64_rom_image_dirty = true; } + +// The FPGA ROM-image apertures must be copied byte-by-byte through volatile +// pointers (block memcpy reads back zeros here), matching the snapshot path in +// u64_memory_backend.cc. +static void copy_rom_aperture_in(uint8_t *dst, volatile uint8_t *src, unsigned len) +{ + for (unsigned i = 0; i < len; i++) dst[i] = src[i]; +} +static void copy_rom_aperture_out(volatile uint8_t *dst, const uint8_t *src, unsigned len) +{ + for (unsigned i = 0; i < len; i++) dst[i] = src[i]; +} +static bool buffer_all_zero(const uint8_t *p, unsigned len) +{ + for (unsigned i = 0; i < len; i++) if (p[i]) return false; + return true; +} + +static void capture_pristine_rom_image(void) +{ + // Only BASIC and KERNAL are healed: a stale debug BRK in those is executed + // during boot and wedges the machine. The CHAR ROM is never executed, so a + // leaked CHAR patch is at worst a cosmetic glyph and is left to the normal + // per-session restore; we deliberately do NOT snapshot/rewrite the CHAR + // aperture on reset (its base differs and a bad snapshot would render every + // glyph as garbage). + copy_rom_aperture_in(s_pristine_basic, (volatile uint8_t *)U64_BASIC_BASE, sizeof(s_pristine_basic)); + copy_rom_aperture_in(s_pristine_kernal, (volatile uint8_t *)U64_KERNAL_BASE, sizeof(s_pristine_kernal)); + // Only trust the snapshot if the KERNAL image actually read back (guards + // against a bad capture ever being restored as a zeroed, unbootable ROM). + s_pristine_rom_valid = !buffer_all_zero(s_pristine_kernal, sizeof(s_pristine_kernal)); + g_u64_rom_image_dirty = false; +} + +static void restore_pristine_rom_image(void) +{ + if (!s_pristine_rom_valid) { + return; + } + copy_rom_aperture_out((volatile uint8_t *)U64_BASIC_BASE, s_pristine_basic, sizeof(s_pristine_basic)); + copy_rom_aperture_out((volatile uint8_t *)U64_KERNAL_BASE, s_pristine_kernal, sizeof(s_pristine_kernal)); + g_u64_rom_image_dirty = false; +} +#endif + #ifndef CMD_IF_SLOT_BASE #define CMD_IF_SLOT_BASE *((volatile uint8_t *)(CMD_IF_BASE + 0x0)) #define CMD_IF_SLOT_ENABLE *((volatile uint8_t *)(CMD_IF_BASE + 0x1)) @@ -147,6 +209,7 @@ C64::C64() C64_STOP_MODE = STOP_COND_FORCE; C64_MODE = MODE_NORMAL; isFrozen = false; + frozen_mode = MODE_NORMAL; backupIsValid = false; buttonPushSeen = false; client = 0; @@ -584,6 +647,14 @@ void C64::resume(void) void C64::reset(void) { +#if U64 + // Heal any debug BRK patch the monitor left in the FPGA ROM image before the + // CPU starts executing the reset/boot code, so a leaked KERNAL/BASIC byte can + // never wedge the boot. The dirty flag is still maintained for diagnostics, + // but reset is the recovery chokepoint and must be robust even if a stale + // patch path failed to mark the image dirty. + restore_pristine_rom_image(); +#endif C64_MODE = MODE_NORMAL; C64_MODE = C64_MODE_RESET; ioWrite8(ITU_TIMER, 20); @@ -597,6 +668,107 @@ bool C64::is_in_reset(void) return (C64_MODE & C64_MODE_RESET); } +uint8_t C64::peek(uint16_t address) +{ + bool stopped_it = false; + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_mode = 0; + bool restore_mode = false; + uint8_t value; + + if (!is_stopped()) { + stop(false); + stopped_it = true; + } + + if (isFrozen && address >= 0x0400 && address < 0x0800) { + value = ((uint8_t *)screen_backup)[address - 0x0400]; + } else if (isFrozen && address >= 0x0800 && address < 0x1000) { + value = ((uint8_t *)ram_backup)[address - 0x0800]; + } else if (isFrozen && address >= 0xD800 && address < 0xDC00) { + value = ((uint8_t *)color_backup)[address - 0xD800]; + } else { + if (isFrozen && address >= 0x8000 && (address < 0xD000 || address >= 0xE000)) { + saved_mode = C64_MODE; + if ((saved_mode & C64_MODE_ULTIMAX) && (saved_mode != frozen_mode)) { + C64_MODE = frozen_mode; + restore_mode = true; + } + } + value = ram[address]; + if (restore_mode) { + C64_MODE = saved_mode; + } + } + + if (stopped_it) { + resume(); + } + return value; +} + +void C64::poke(uint16_t address, uint8_t value) +{ + bool stopped_it = false; + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_mode = 0; + bool restore_mode = false; + + if (!is_stopped()) { + stop(false); + stopped_it = true; + } + + if (isFrozen && address >= 0x0400 && address < 0x0800) { + ((uint8_t *)screen_backup)[address - 0x0400] = value; + } else if (isFrozen && address >= 0x0800 && address < 0x1000) { + ((uint8_t *)ram_backup)[address - 0x0800] = value; + } else if (isFrozen && address >= 0xD800 && address < 0xDC00) { + ((uint8_t *)color_backup)[address - 0xD800] = value; + } else { + if (isFrozen && address >= 0x8000 && (address < 0xD000 || address >= 0xE000)) { + saved_mode = C64_MODE; + if ((saved_mode & C64_MODE_ULTIMAX) && (saved_mode != frozen_mode)) { + C64_MODE = frozen_mode; + restore_mode = true; + } + } + ram[address] = value; + if (restore_mode) { + C64_MODE = saved_mode; + } + } + + if (stopped_it) { + resume(); + } +} + +bool C64::begin_stopped_session(void) +{ + bool wasStopped = is_stopped(); + if (!wasStopped) { + stop(false); + } + return !wasStopped; +} + +bool C64::begin_stopped_session(bool raster) +{ + bool wasStopped = is_stopped(); + if (!wasStopped) { + stop(raster); + } + return !wasStopped; +} + +void C64::end_stopped_session(bool stopped_it) +{ + if (stopped_it) { + resume(); + } +} + /* ------------------------------------------------------------------------------- freeze (split in subfunctions) @@ -719,6 +891,7 @@ void C64::freeze(void) if (!phi2_present()) return; + frozen_mode = C64_MODE; stop(true); backup_io(); init_io(); @@ -818,6 +991,10 @@ void C64::init_system_roms(void) memcpy((void *)U64_CHARROM_BASE, (void *)_default_chars_bin_start, 4096); } + // The ROM image is now authoritative (freshly loaded from config). Snapshot it + // so reset() can heal any debug BRK patch left in the FPGA ROM image. + capture_pristine_rom_image(); + #else uint8_t *temp = new uint8_t[8192]; FRESULT fres = FileManager :: getFileManager()->load_file(ROMS_DIRECTORY, cfg->get_string(CFG_C64_KERNFILE), temp, 8192, NULL); @@ -849,6 +1026,12 @@ void C64::unfreeze() isFrozen = false; } +void C64::refreeze(void) +{ + if (!isFrozen) + freeze(); +} + void C64 :: start_cartridge(void *vdef) { cart_def *def = (cart_def *) vdef; diff --git a/software/io/c64/c64.h b/software/io/c64/c64.h index 81d6e27ac..5efe092c4 100644 --- a/software/io/c64/c64.h +++ b/software/io/c64/c64.h @@ -33,6 +33,7 @@ #define MENU_MEASURE_TIMING_API 0x6413 #define MENU_C64_POWERCYCLE 0x6414 #define MENU_C64_CLEARMEM 0x6415 +#define MENU_C64_MONITOR 0x6416 #define C64_DMA_LOAD 0x6464 #define C64_DRIVE_LOAD 0x6465 @@ -292,6 +293,7 @@ class C64 : public GenericHost, ConfigurableObject uint8_t vic_irq; uint8_t vic_d011; uint8_t vic_d012; + uint8_t frozen_mode; bool backupIsValid; volatile bool buttonPushSeen; @@ -377,10 +379,17 @@ class C64 : public GenericHost, ConfigurableObject if (!cfg) return 0; return cfg->get_value(id); } - + + const char *get_cfg_string(uint8_t id) + { + if (!cfg) return ""; + return cfg->get_string(id); + } + /* C64 specifics */ void resetConfigInFlash(int page); void unfreeze(void); + void refreeze(void); void start_cartridge(void *def); void enable_kernal(uint8_t *rom); void set_rom_config(uint8_t idx, const char *fname); @@ -388,6 +397,20 @@ class C64 : public GenericHost, ConfigurableObject void reset(void); void start(void); bool is_in_reset(void); + virtual uint8_t peek(uint16_t address); + virtual void poke(uint16_t address, uint8_t value); + + // Atomic stopped-region helpers. Used by the machine code monitor to + // bracket multi-byte vector / trampoline installs so the live C64 sees a + // single consistent transition. Default forwards to stop()/resume(). + virtual bool begin_stopped_session(void); + // Variant that, when it actually stops a running machine, uses a raster-synced + // stop (do_raster=true) instead of the forced DMA stop. The matching resume() + // then re-clocks the VIC/CPU the way the freeze path does, which the monitor + // debugger needs so freshly armed high-memory BRKs are reliably observed by + // the live 6510 fetch on release. No-ops the stop if already stopped. + virtual bool begin_stopped_session(bool raster); + virtual void end_stopped_session(bool stopped_it); static void clear_cart_definition(cart_def *def) { def->custom_addr = 0; diff --git a/software/io/c64/c64_subsys.cc b/software/io/c64/c64_subsys.cc index c83506692..15a1e9c4e 100644 --- a/software/io/c64/c64_subsys.cc +++ b/software/io/c64/c64_subsys.cc @@ -14,6 +14,7 @@ #include "u64.h" #include "c1541.h" #include "endianness.h" +#include "monitor_init.h" #if U64 == 2 #include "wifi.h" #endif @@ -105,6 +106,9 @@ void C64_Subsys :: create_task_items(void) myActions.savemp3c = new Action("Save MP3 Drv C", SUBSYSID_C64, MENU_C64_SAVE_MP3_DRV_C); myActions.savemp3d = new Action("Save MP3 Drv D", SUBSYSID_C64, MENU_C64_SAVE_MP3_DRV_D); myActions.measure = new Action("Measure Cart Bus", SUBSYSID_C64, MENU_MEASURE_TIMING); +#if !U64 + myActions.monitor = register_c64_machine_monitor_task ? register_c64_machine_monitor_task(MENU_C64_MONITOR) : NULL; +#endif taskCategory->append(myActions.reset); taskCategory->append(myActions.reboot); @@ -207,11 +211,14 @@ SubsysResultCode_e C64_Subsys::executeCommand(SubsysCommand *cmd) } c64->unfreeze(); break; - case MENU_C64_RESET: - if (c64->client) { // we can't execute this yet - c64->client->release_host(); // disconnect from user interface - c64->client = 0; - } + case MENU_C64_RESET: + if (machine_monitor_request_global_reset_cancel) { + machine_monitor_request_global_reset_cancel(); + } + if (c64->client) { // we can't execute this yet + c64->client->release_host(); // disconnect from user interface + c64->client = 0; + } c64->unfreeze(); c64->reset(); break; @@ -636,7 +643,9 @@ int C64_Subsys :: dma_load(File *f, const uint8_t *buffer, const int bufferSize, if (run_code & RUNCODE_JUMP_BIT) { C64_POKE(C64_BOOTCRT_JUMPADDR, buffer[0]); C64_POKE(C64_BOOTCRT_JUMPADDR+1, buffer[1]); - load_buffer_dma(buffer+2, bufferSize-2, 0); + if (bufferSize > 2) { + load_buffer_dma(buffer+2, bufferSize-2, 0); + } } else { load_buffer_dma(buffer, bufferSize, 0); } @@ -724,6 +733,9 @@ int C64_Subsys :: load_file_dma(File *f, uint16_t reloc) int C64_Subsys :: load_buffer_dma(const uint8_t *buffer, const int bufferSize, uint16_t reloc) { + if (!buffer || bufferSize < 2) { + return 0; + } uint16_t load_address = 0; load_address = (uint16_t)buffer[0] | ((uint16_t)buffer[1]) << 8; diff --git a/software/io/c64/c64_subsys.h b/software/io/c64/c64_subsys.h index 9e2842e67..649041a62 100644 --- a/software/io/c64/c64_subsys.h +++ b/software/io/c64/c64_subsys.h @@ -39,11 +39,11 @@ class C64_Subsys : public SubSystem, ObjectWithMenu Action *savemp3c; Action *savemp3d; Action *measure; + Action *monitor; } myActions; static void poll(void *a); - - /* Subsystem */ + /* Subsystem */ const char *identify(void) { return "C64 Machine"; } SubsysResultCode_e executeCommand(SubsysCommand *cmd); diff --git a/software/io/c64/keyboard.h b/software/io/c64/keyboard.h index 4979f9aed..8e747f854 100644 --- a/software/io/c64/keyboard.h +++ b/software/io/c64/keyboard.h @@ -28,11 +28,35 @@ class Keyboard #define KEY_CTRL_HOME 0x14 #define KEY_CTRL_A 0x01 +#define KEY_CTRL_B 0x02 #define KEY_CTRL_C 0x03 -#define KEY_CTRL_N 0x0E -#define KEY_CTRL_V 0x16 +#define KEY_CTRL_D 0x04 +#define KEY_CTRL_E 0x05 +#define KEY_CTRL_I 0x09 #define KEY_CTRL_J 0x0A #define KEY_CTRL_L 0x0C +#define KEY_CTRL_N 0x0E +#define KEY_CTRL_O 0x0F +#define KEY_CTRL_V 0x16 +#define KEY_CTRL_X 0x18 + +// C=+R has no natural single-byte mapping on the C64 keyboard matrix because +// the historical PETSCII control encoding (0x12) collides with KEY_DOWN. +// Assign a distinct code in the non-conflicting 0xBA..0xBF range so the +// machine code monitor can wire `C=+R` to the breakpoint list without +// hijacking cursor-down. +#define KEY_CTRL_R 0xBA + +#define KEY_CTRL_0 0xB0 +#define KEY_CTRL_1 0xB1 +#define KEY_CTRL_2 0xB2 +#define KEY_CTRL_3 0xB3 +#define KEY_CTRL_4 0xB4 +#define KEY_CTRL_5 0xB5 +#define KEY_CTRL_6 0xB6 +#define KEY_CTRL_7 0xB7 +#define KEY_CTRL_8 0xB8 +#define KEY_CTRL_9 0xB9 #define KEY_A 0x61 #define KEY_S 0x73 @@ -68,6 +92,21 @@ class Keyboard #define KEY_SCRLOCK 0xA3 #define KEY_NUMLOCK 0xA4 +static inline bool key_is_ctrl_digit(int key) +{ + return key >= KEY_CTRL_0 && key <= KEY_CTRL_9; +} + +static inline int key_ctrl_digit_value(int key) +{ + return key_is_ctrl_digit(key) ? (key - KEY_CTRL_0) : -1; +} + +static inline int key_ctrl_digit(int digit) +{ + return (digit >= 0 && digit <= 9) ? (KEY_CTRL_0 + digit) : KEY_ERR; +} + // Specials #define KEY_MENU 0x1FE #define KEY_SEARCH 0x1FD diff --git a/software/io/c64/keyboard_c64.cc b/software/io/c64/keyboard_c64.cc index 501480098..ea52647fb 100644 --- a/software/io/c64/keyboard_c64.cc +++ b/software/io/c64/keyboard_c64.cc @@ -57,13 +57,13 @@ const uint8_t keymap_shifted[] = { const uint8_t keymap_control[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x17, 0x01, 0x00, 0x1a, 0x13, 0x05, 0x00, // 3, w, a, 4, z, s, e, empty - 0x00, 0x12, 0x04, 0x00, 0x03, 0x06, 0x14, 0x18, // 5, r, d, 6, c, f, t, x - 0x00, 0x19, 0x07, 0x00, 0x02, 0x08, 0x15, 0x16, // 7, y, g, 8, b, h, u, v - 0x00, 0x09, 0x0A, 0x00, 0x0D, 0x0B, 0x0F, 0x0E, // 9, i, j, 0, m, k, o, n + KEY_CTRL_3, 0x17, 0x01, KEY_CTRL_4, 0x1a, 0x13, 0x05, 0x00, // 3, w, a, 4, z, s, e, empty + KEY_CTRL_5, KEY_CTRL_R, 0x04, KEY_CTRL_6, 0x03, 0x06, 0x14, 0x18, // 5, r, d, 6, c, f, t, x + KEY_CTRL_7, 0x19, 0x07, KEY_CTRL_8, KEY_CTRL_B, 0x08, 0x15, 0x16, // 7, y, g, 8, b, h, u, v + KEY_CTRL_9, 0x09, 0x0A, KEY_CTRL_0, 0x0D, 0x0B, 0x0F, 0x0E, // 9, i, j, 0, m, k, o, n 0x00, 0x10, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, // +, p, l, -, ., :, @, , 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, // \, *, ;, Home , (empty), =, |, / - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, // 1, `, (empty), 2, SP, (empty), q, RunStop + KEY_CTRL_1, 0x00, 0x00, KEY_CTRL_2, 0x00, 0x00, 0x11, 0x00, // 1, `, (empty), 2, SP, (empty), q, RunStop 0x00 }; const uint8_t *keymaps[8] = { diff --git a/software/io/c64/screen.h b/software/io/c64/screen.h index af3f0edf3..4c99fbfc4 100644 --- a/software/io/c64/screen.h +++ b/software/io/c64/screen.h @@ -59,6 +59,7 @@ class Screen // for character mapped screens. Does not work for VT100. virtual void backup(void) { } + virtual bool prefers_full_refresh(void) { return false; } virtual void restore(void) { } // Static diff --git a/software/io/stream/keyboard_vt100.cc b/software/io/stream/keyboard_vt100.cc index 670ea4b0f..84e14ba6b 100644 --- a/software/io/stream/keyboard_vt100.cc +++ b/software/io/stream/keyboard_vt100.cc @@ -29,7 +29,9 @@ int Keyboard_VT100 :: getch() } else { charin = stream->get_char(); } - if (charin == '\e') + if (charin == 0x12) // Ctrl+R + ret = KEY_CTRL_R; + else if (charin == '\e') escape_state = e_esc_escape; else // -1 is also else ret = charin; @@ -44,6 +46,15 @@ int Keyboard_VT100 :: getch() } else if (charin == '[') { escape_state = e_esc_bracket; escape_value = 0; + } else if (charin >= '0' && charin <= '9') { + escape_state = e_esc_idle; + ret = key_ctrl_digit(charin - '0'); + } else if (charin == 'b' || charin == 'B') { + escape_state = e_esc_idle; + ret = KEY_CTRL_B; + } else if (charin == 'r' || charin == 'R') { + escape_state = e_esc_idle; + ret = KEY_CTRL_R; } else { if (charin != '\e') escape_state = e_esc_idle; diff --git a/software/io/stream/screen_vt100.h b/software/io/stream/screen_vt100.h index 9c31f6808..026fd97e7 100644 --- a/software/io/stream/screen_vt100.h +++ b/software/io/stream/screen_vt100.h @@ -42,6 +42,7 @@ class Screen_VT100: public Screen { // VT100 specific void restore_terminal(void); + bool prefers_full_refresh(void) { return true; } }; #endif /* IO_STREAM_SCREEN_VT100_H_ */ diff --git a/software/io/usb/keyboard_usb.cc b/software/io/usb/keyboard_usb.cc index da2fd299e..1ffa638c9 100644 --- a/software/io/usb/keyboard_usb.cc +++ b/software/io/usb/keyboard_usb.cc @@ -65,19 +65,19 @@ const uint8_t keymap_shifted[] = { KEY_UP, KEY_PAGEUP, KEY_INSERT, KEY_DELETE, 0x00 }; const uint8_t keymap_control[] = { - 0x00, KEY_ERR, KEY_ERR, KEY_ERR, 0x01, 0x02, 0x03, 0x04, + 0x00, KEY_ERR, KEY_ERR, KEY_ERR, 0x01, KEY_CTRL_B, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, - 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, - 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, '1', '2', - '3', '4', '5', '6', '7', '8', '9', '0', + 0x0D, 0x0E, 0x0F, 0x10, 0x11, KEY_CTRL_R, 0x13, 0x14, + 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, KEY_CTRL_1, KEY_CTRL_2, + KEY_CTRL_3, KEY_CTRL_4, KEY_CTRL_5, KEY_CTRL_6, KEY_CTRL_7, KEY_CTRL_8, KEY_CTRL_9, KEY_CTRL_0, KEY_RETURN, KEY_ESCAPE, KEY_BACK, KEY_TAB, ' ', '-', '=', '[', ']', '\\', 0x00, ';', '\'', '`', ',', '.', '/', KEY_CAPS, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_PRSCR, KEY_SCRLOCK, KEY_BREAK, KEY_INSERT, KEY_CTRL_HOME, KEY_PAGEUP, KEY_DELETE, KEY_END, KEY_PAGEDOWN, KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP, KEY_NUMLOCK, '/', '*', '-', '+', - KEY_RETURN, '1', '2', '3', '4', '5', '6', '7', - '8', '9', '0', '.', 0x00 }; + KEY_RETURN, KEY_CTRL_1, KEY_CTRL_2, KEY_CTRL_3, KEY_CTRL_4, KEY_CTRL_5, KEY_CTRL_6, KEY_CTRL_7, + KEY_CTRL_8, KEY_CTRL_9, KEY_CTRL_0, '.', 0x00 }; const uint8_t keymap_usb2matrix[] = { 0x0F, 0xFF, 0xFF, 0xFF, 0x0A, 0x1C, 0x14, 0x12, diff --git a/software/io/usb/tests/usb_keyboard_queue_test.cpp b/software/io/usb/tests/usb_keyboard_queue_test.cpp index d0cc1a36c..7947cee65 100644 --- a/software/io/usb/tests/usb_keyboard_queue_test.cpp +++ b/software/io/usb/tests/usb_keyboard_queue_test.cpp @@ -14,6 +14,48 @@ TEST(KeyboardUsbQueueTest, PushHeadPrependsInjectedKey) EXPECT_EQ(-1, keyboard.getch()); } +TEST(KeyboardUsbQueueTest, ControlBookmarkDigitsStayDistinctFromRecall) +{ + Keyboard_USB keyboard; + uint8_t recall_report[USB_DATA_SIZE] = { 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t set_slot_report[USB_DATA_SIZE] = { 0x01, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t release[USB_DATA_SIZE] = { 0x00 }; + uint8_t list_report[USB_DATA_SIZE] = { 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t edit_report[USB_DATA_SIZE] = { 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t brk_report[USB_DATA_SIZE] = { 0x01, 0x00, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + keyboard.process_data(recall_report); + EXPECT_EQ('1', keyboard.getch()); + keyboard.process_data(release); + + keyboard.process_data(set_slot_report); + EXPECT_EQ(KEY_CTRL_1, keyboard.getch()); + keyboard.process_data(release); + + keyboard.process_data(list_report); + EXPECT_EQ(KEY_CTRL_B, keyboard.getch()); + keyboard.process_data(release); + + keyboard.process_data(edit_report); + EXPECT_EQ(KEY_CTRL_E, keyboard.getch()); + keyboard.process_data(release); + + keyboard.process_data(brk_report); + EXPECT_EQ(KEY_CTRL_R, keyboard.getch()); +} + +TEST(KeyboardUsbQueueTest, CbmDigitDecodeRejectsInvalidKeys) +{ + EXPECT_TRUE(key_is_ctrl_digit(KEY_CTRL_0)); + EXPECT_TRUE(key_is_ctrl_digit(KEY_CTRL_9)); + EXPECT_FALSE(key_is_ctrl_digit('0')); + EXPECT_FALSE(key_is_ctrl_digit(KEY_CTRL_B)); + EXPECT_EQ(0, key_ctrl_digit_value(KEY_CTRL_0)); + EXPECT_EQ(9, key_ctrl_digit_value(KEY_CTRL_9)); + EXPECT_EQ(-1, key_ctrl_digit_value('0')); + EXPECT_EQ(-1, key_ctrl_digit_value(KEY_CTRL_B)); +} + TEST(KeyboardUsbQueueTest, PushHeadRepeatIsBounded) { Keyboard_USB keyboard; @@ -66,4 +108,4 @@ TEST(KeyboardUsbQueueTest, RemoveInjectedKeyDropsPendingDirection) EXPECT_EQ(0, keyboard.count_injected_key(KEY_DOWN)); EXPECT_EQ(KEY_UP, keyboard.getch()); EXPECT_EQ(-1, keyboard.getch()); -} \ No newline at end of file +} diff --git a/software/monitor/assembler_6502.cc b/software/monitor/assembler_6502.cc new file mode 100644 index 000000000..6f43b3175 --- /dev/null +++ b/software/monitor/assembler_6502.cc @@ -0,0 +1,412 @@ +#include "assembler_6502.h" + +extern "C" { +#include "small_printf.h" +} + +#include + +namespace { + +static bool is_hex(char c) +{ + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); +} + +static char up(char c) { return (c >= 'a' && c <= 'z') ? (char)(c - 32) : c; } + +static int hex_val(char c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +// Decode template -> AsmAddrMode. Mirrors the structure of opcode_templates +// in disassembler_6502.cc. +static AsmAddrMode template_to_mode(uint8_t opcode, const char *t) +{ + // Branches: B?? rel — except BRK/BIT. + if (t[0] == 'B' && t[1] != 'R' && t[1] != 'I') { + return AM_REL; + } + const char *spec = t + 4; + while (*spec == ' ') spec++; + if (*spec == 0) return AM_IMP; + if (spec[0] == 'A' && (spec[1] == ' ' || spec[1] == 0)) return AM_ACC; + if (!strncmp(spec, "rel", 3)) return AM_REL; + if (!strncmp(spec, "#", 1)) return AM_IMM; + if (!strncmp(spec, "($nn,X)", 7)) return AM_IZX; + if (!strncmp(spec, "($nn),Y", 7)) return AM_IZY; + if (!strncmp(spec, "($nnnn,X)", 9) || !strncmp(spec, "(ABS,X)", 7)) return AM_IAX; + if (!strncmp(spec, "($nnnn)", 7)) return AM_IND; + if (!strncmp(spec, "$nnnn,Y", 7)) return AM_ABY; + if (!strncmp(spec, "$nnnn,X", 7)) return AM_ABX; + if (!strncmp(spec, "$nnnn", 5)) return AM_ABS; + if (!strncmp(spec, "$nn,Y", 5)) return AM_ZPY; + if (!strncmp(spec, "$nn,X", 5)) return AM_ZPX; + if (!strncmp(spec, "$nn,S", 5)) return AM_ZPS; + if (!strncmp(spec, "$nn", 3)) return AM_ZP; + return AM_IMP; +} + +static uint8_t mode_length(AsmAddrMode m) +{ + switch (m) { + case AM_IMP: case AM_ACC: return 1; + case AM_IMM: case AM_ZP: case AM_ZPX: case AM_ZPY: case AM_ZPS: + case AM_IZX: case AM_IZY: case AM_REL: return 2; + case AM_ABS: case AM_ABX: case AM_ABY: case AM_IND: case AM_IAX: return 3; + default: return 1; + } +} + +static void canonicalize_mnem(uint8_t opcode, const char *t, char *m) +{ + m[0] = t[0]; m[1] = t[1]; m[2] = t[2]; m[3] = 0; + if (!strcmp(m, "HLT")) strcpy(m, "JAM"); + else if (!strcmp(m, "ASO")) strcpy(m, "SLO"); + else if (!strcmp(m, "LSE")) strcpy(m, "SRE"); + else if (!strcmp(m, "DCM")) strcpy(m, "DCP"); + else if (!strcmp(m, "INS")) strcpy(m, "ISC"); +} + +struct ReverseEntry { + uint8_t opcode; + uint8_t length; + bool illegal; + bool valid; +}; + +// One slot per (mnemonic-id, addressing-mode). Mnemonics deduplicated below. +// Size must be >= number of distinct mnemonics across all 256 opcodes +// (including illegal forms). Today this is ~75 entries. +#define REVERSE_MNEMONIC_MAX 96 +static char reverse_mnemonics[REVERSE_MNEMONIC_MAX][4]; +static int reverse_mnemonic_count = 0; +static ReverseEntry reverse_table[REVERSE_MNEMONIC_MAX][AM_COUNT]; +static bool reverse_built = false; + +static int find_or_add_mnem(const char *m) +{ + for (int i = 0; i < reverse_mnemonic_count; i++) { + if (!strcmp(reverse_mnemonics[i], m)) return i; + } + if (reverse_mnemonic_count >= REVERSE_MNEMONIC_MAX) return -1; + int i = reverse_mnemonic_count++; + strcpy(reverse_mnemonics[i], m); + return i; +} + +static void build_reverse(void) +{ + if (reverse_built) return; + memset(reverse_table, 0, sizeof(reverse_table)); + reverse_mnemonic_count = 0; + for (int op = 0; op < 256; op++) { + const char *t = disassembler_6502_template((uint8_t)op); + char m[4]; + canonicalize_mnem((uint8_t)op, t, m); + AsmAddrMode mode = template_to_mode((uint8_t)op, t); + int idx = find_or_add_mnem(m); + if (idx < 0) continue; + ReverseEntry &e = reverse_table[idx][mode]; + // Prefer non-illegal if a duplicate exists. + bool ill = disassembler_6502_is_illegal((uint8_t)op); + if (!e.valid || (e.illegal && !ill)) { + e.valid = true; + e.opcode = (uint8_t)op; + e.length = mode_length(mode); + e.illegal = ill; + } + } + reverse_built = true; +} + +static int find_mnem(const char *m) +{ + for (int i = 0; i < reverse_mnemonic_count; i++) { + if (!strcmp(reverse_mnemonics[i], m)) return i; + } + return -1; +} + +static uint8_t candidate_mode_rank(AsmAddrMode mode) +{ + switch (mode) { + case AM_IMP: return 0; + case AM_ACC: return 1; + case AM_IMM: return 2; + case AM_ZP: return 3; + case AM_ZPX: return 4; + case AM_ZPY: return 5; + case AM_ZPS: return 6; + case AM_IZX: return 7; + case AM_IZY: return 8; + case AM_ABS: return 9; + case AM_ABX: return 10; + case AM_ABY: return 11; + case AM_IND: return 12; + case AM_IAX: return 13; + case AM_REL: return 14; + default: return 15; + } +} + +static void skip_ws(const char *&p) { while (*p == ' ' || *p == '\t') p++; } + +// Parse a hex value of 1..4 nibbles. *digits returns nibble count. +static bool parse_hex_n(const char *&p, uint16_t *value, int *digits) +{ + int n = 0; + uint32_t v = 0; + while (is_hex(*p) && n < 4) { + v = (v << 4) | (uint32_t)hex_val(*p++); + n++; + } + *value = (uint16_t)v; + *digits = n; + return n > 0; +} + +// Parse operand starting at p, return mode + value. value is the raw 8/16-bit +// operand prior to PC-relative adjustment. +static bool parse_operand(const char *p, AsmAddrMode *mode, uint16_t *value) +{ + skip_ws(p); + if (*p == 0) { *mode = AM_IMP; *value = 0; return true; } + if ((*p == 'A' || *p == 'a') && (p[1] == 0 || p[1] == ' ' || p[1] == '\t')) { + const char *q = p + 1; skip_ws(q); + if (*q == 0) { *mode = AM_ACC; *value = 0; return true; } + } + if (*p == '#') { + p++; if (*p == '$') p++; + int d; if (!parse_hex_n(p, value, &d)) return false; + if (d > 2) return false; + skip_ws(p); if (*p) return false; + *mode = AM_IMM; return true; + } + if (*p == '(') { + p++; if (*p == '$') p++; + int d; uint16_t v; if (!parse_hex_n(p, &v, &d)) return false; + if (*p == ',') { + p++; skip_ws(p); + if (*p != 'X' && *p != 'x') return false; + p++; skip_ws(p); + if (*p != ')') return false; + p++; skip_ws(p); if (*p) return false; + *value = v; + *mode = (d <= 2) ? AM_IZX : AM_IAX; + return true; + } + if (*p != ')') return false; + p++; skip_ws(p); + if (*p == ',') { + p++; skip_ws(p); + if (*p != 'Y' && *p != 'y') return false; + p++; skip_ws(p); if (*p) return false; + if (d > 2) return false; + *value = v; *mode = AM_IZY; return true; + } + if (*p) return false; + *value = v; *mode = AM_IND; return true; + } + if (*p == '$') p++; + int d; uint16_t v; if (!parse_hex_n(p, &v, &d)) return false; + skip_ws(p); + if (*p == ',') { + p++; skip_ws(p); + char idx = up(*p); + if (idx != 'X' && idx != 'Y' && idx != 'S') return false; + p++; skip_ws(p); if (*p) return false; + *value = v; + if (idx == 'S') { *mode = AM_ZPS; return d <= 2; } + if (idx == 'X') { *mode = (d <= 2) ? AM_ZPX : AM_ABX; return true; } + *mode = (d <= 2) ? AM_ZPY : AM_ABY; return true; + } + if (*p) return false; + *value = v; + *mode = (d <= 2) ? AM_ZP : AM_ABS; + return true; +} + +} // namespace + +int monitor_collect_opcode_candidates(const char *prefix, bool illegal_enabled, + uint8_t *opcode_out, int max_candidates) +{ + struct Candidate { + uint8_t opcode; + char mnemonic[4]; + uint8_t mode_rank; + }; + + if (!opcode_out || max_candidates <= 0) { + return 0; + } + + build_reverse(); + + char want[4]; + int prefix_len = 0; + while (prefix && prefix[prefix_len] && prefix_len < 3) { + want[prefix_len] = up(prefix[prefix_len]); + prefix_len++; + } + want[prefix_len] = 0; + + Candidate candidates[256]; + int candidate_count = 0; + + for (int mnemonic_idx = 0; mnemonic_idx < reverse_mnemonic_count; mnemonic_idx++) { + const char *mnemonic = reverse_mnemonics[mnemonic_idx]; + bool match = true; + for (int i = 0; i < prefix_len; i++) { + if (mnemonic[i] != want[i]) { + match = false; + break; + } + } + if (!match) { + continue; + } + + for (int mode = 0; mode < AM_COUNT; mode++) { + const ReverseEntry &entry = reverse_table[mnemonic_idx][mode]; + if (!entry.valid) { + continue; + } + if (entry.illegal && !illegal_enabled) { + continue; + } + + Candidate candidate; + candidate.opcode = entry.opcode; + candidate.mnemonic[0] = mnemonic[0]; + candidate.mnemonic[1] = mnemonic[1]; + candidate.mnemonic[2] = mnemonic[2]; + candidate.mnemonic[3] = 0; + candidate.mode_rank = candidate_mode_rank((AsmAddrMode)mode); + + int insert_at = candidate_count; + while (insert_at > 0) { + const Candidate &prev = candidates[insert_at - 1]; + int mnemonic_cmp = strcmp(candidate.mnemonic, prev.mnemonic); + if (mnemonic_cmp > 0) { + break; + } + if (mnemonic_cmp == 0 && candidate.mode_rank > prev.mode_rank) { + break; + } + if (mnemonic_cmp == 0 && candidate.mode_rank == prev.mode_rank && + candidate.opcode >= prev.opcode) { + break; + } + candidates[insert_at] = candidates[insert_at - 1]; + insert_at--; + } + candidates[insert_at] = candidate; + candidate_count++; + } + } + + if (candidate_count > max_candidates) { + candidate_count = max_candidates; + } + for (int i = 0; i < candidate_count; i++) { + opcode_out[i] = candidates[i].opcode; + } + return candidate_count; +} + +bool monitor_lookup_opcode(const char *mnemonic, AsmAddrMode mode, + bool illegal_enabled, uint8_t *opcode, uint8_t *length) +{ + build_reverse(); + char m[4]; + int n = 0; + while (mnemonic[n] && n < 3) { m[n] = up(mnemonic[n]); n++; } + m[n] = 0; + if (n != 3) return false; + int idx = find_mnem(m); + if (idx < 0) return false; + const ReverseEntry &e = reverse_table[idx][mode]; + if (!e.valid) return false; + if (e.illegal && !illegal_enabled) return false; + *opcode = e.opcode; + *length = e.length; + return true; +} + +bool monitor_assemble_line(const char *text, bool illegal_enabled, uint16_t pc, + AsmInsn *out, MonitorError *err) +{ + build_reverse(); + if (err) *err = MONITOR_OK; + memset(out, 0, sizeof(*out)); + + const char *p = text; + skip_ws(p); + if (!*p) { if (err) *err = MONITOR_SYNTAX; return false; } + + char m[4]; int n = 0; + while (*p && *p != ' ' && *p != '\t' && n < 3) { m[n++] = up(*p++); } + m[n] = 0; + if (n != 3) { if (err) *err = MONITOR_SYNTAX; return false; } + + AsmAddrMode mode; uint16_t value = 0; + if (!parse_operand(p, &mode, &value)) { if (err) *err = MONITOR_SYNTAX; return false; } + + // Try direct match first. + uint8_t opcode = 0, length = 0; + bool ok = monitor_lookup_opcode(m, mode, illegal_enabled, &opcode, &length); + + // Branch promotion: ABS-form branches resolve to REL. + if (!ok && (mode == AM_ABS || mode == AM_ZP)) { + if (monitor_lookup_opcode(m, AM_REL, illegal_enabled, &opcode, &length)) { + int32_t delta = (int32_t)value - (int32_t)((uint16_t)(pc + 2)); + if (delta < -128 || delta > 127) { if (err) *err = MONITOR_RANGE; return false; } + out->bytes[0] = opcode; + out->bytes[1] = (uint8_t)(delta & 0xFF); + out->length = 2; + out->illegal = false; + return true; + } + // ZP can promote to ABS. + if (mode == AM_ZP) { + if (monitor_lookup_opcode(m, AM_ABS, illegal_enabled, &opcode, &length)) { + ok = true; mode = AM_ABS; + } + } + } + if (!ok) { + if (mode == AM_ZPX && monitor_lookup_opcode(m, AM_ABX, illegal_enabled, &opcode, &length)) { ok = true; mode = AM_ABX; } + else if (mode == AM_ZPY && monitor_lookup_opcode(m, AM_ABY, illegal_enabled, &opcode, &length)) { ok = true; mode = AM_ABY; } + } + if (!ok) { if (err) *err = MONITOR_SYNTAX; return false; } + + out->bytes[0] = opcode; + out->length = length; + out->illegal = disassembler_6502_is_illegal(opcode); + if (length == 2) { + if (mode == AM_REL) { + int32_t delta = (int32_t)value - (int32_t)((uint16_t)(pc + 2)); + if (delta < -128 || delta > 127) { if (err) *err = MONITOR_RANGE; return false; } + out->bytes[1] = (uint8_t)(delta & 0xFF); + } else { + if (value > 0xFF) { if (err) *err = MONITOR_VALUE; return false; } + out->bytes[1] = (uint8_t)value; + } + } else if (length == 3) { + out->bytes[1] = (uint8_t)(value & 0xFF); + out->bytes[2] = (uint8_t)((value >> 8) & 0xFF); + } + return true; +} + +void monitor_assembler_reset_caches(void) +{ + reverse_built = false; + reverse_mnemonic_count = 0; +} diff --git a/software/monitor/assembler_6502.h b/software/monitor/assembler_6502.h new file mode 100644 index 000000000..86cc02808 --- /dev/null +++ b/software/monitor/assembler_6502.h @@ -0,0 +1,59 @@ +#ifndef ASSEMBLER_6502_H +#define ASSEMBLER_6502_H + +#include "integer.h" +#include "disassembler_6502.h" +#include "machine_monitor.h" + +enum AsmAddrMode { + AM_IMP = 0, // implied: BRK, RTS, ... + AM_ACC, // accumulator: ASL A + AM_IMM, // immediate: LDA #$12 + AM_ZP, // zero page: LDA $12 + AM_ZPX, // zero page,X: LDA $12,X + AM_ZPY, // zero page,Y: LDX $12,Y + AM_ZPS, // illegal $nn,S: NOP* $nn,S + AM_IZX, // (zp,X): LDA ($12,X) + AM_IZY, // (zp),Y: LDA ($12),Y + AM_ABS, // absolute: LDA $1234 + AM_ABX, // absolute,X: LDA $1234,X + AM_ABY, // absolute,Y: LDA $1234,Y + AM_IND, // (absolute): JMP ($1234) + AM_IAX, // (absolute,X): JMP ($1234,X) (illegal-NOP) + AM_REL, // relative: BNE $1234 + AM_COUNT +}; + +struct AsmInsn { + uint8_t bytes[3]; + uint8_t length; + bool illegal; +}; + +// Returns true on success and fills *out. On failure, returns false and sets +// *err to a relevant MonitorError, *err_pos to the byte offset within `text` +// that triggered the failure (best-effort). +// +// pc is the address that the instruction will be written at (used to encode +// branch relative offsets). illegal_enabled gates illegal opcodes. +bool monitor_assemble_line(const char *text, bool illegal_enabled, uint16_t pc, + AsmInsn *out, MonitorError *err); + +// Resolve the opcode/length for a given mnemonic + addressing mode. Returns +// true iff the combination exists (and matches illegal_enabled). On success, +// *opcode and *length are filled. +bool monitor_lookup_opcode(const char *mnemonic, AsmAddrMode mode, + bool illegal_enabled, uint8_t *opcode, + uint8_t *length); + +// Collect opcode candidates whose canonical mnemonic matches `prefix` +// case-insensitively. Results are deterministic: candidates are ordered by +// mnemonic, then by addressing simplicity with operand-free variants first, +// then by opcode value as a final tiebreaker. +int monitor_collect_opcode_candidates(const char *prefix, bool illegal_enabled, + uint8_t *opcode_out, int max_candidates); + +// For HEX-host testing: reset assembler caches (no-op outside tests). +void monitor_assembler_reset_caches(void); + +#endif diff --git a/software/monitor/disassembler_6502.cc b/software/monitor/disassembler_6502.cc new file mode 100644 index 000000000..342489f97 --- /dev/null +++ b/software/monitor/disassembler_6502.cc @@ -0,0 +1,287 @@ +#include "disassembler_6502.h" + +extern "C" { +#include "small_printf.h" +} + +#include + +namespace { + +static const char *const opcode_templates[256] = { + "BRK ", "ORA ($nn,X) ", "HLT* ", "ASO*($nn,X) ", + "NOP*$nn ", "ORA $nn ", "ASL $nn ", "ASO*$nn ", + "PHP ", "ORA # ", "ASL A ", "ANC*# ", + "NOP*$nnnn ", "ORA $nnnn ", "ASL $nnnn ", "ASO*$nnnn ", + + "BPL rel ", "ORA ($nn),Y ", "HLT* ", "ASO*($nn),Y ", + "NOP*$nn,X ", "ORA $nn,X ", "ASL $nn,X ", "ASO*$nn,X ", + "CLC ", "ORA $nnnn,Y ", "NOP* ", "ASO*$nnnn,Y ", + "NOP*$nnnn,X ", "ORA $nnnn,X ", "ASL $nnnn,X ", "ASO*$nnnn,X ", + + "JSR $nnnn ", "AND ($nn,X) ", "HLT* ", "RLA*($nn,X) ", + "BIT $nn ", "AND $nn ", "ROL $nn ", "RLA*$nn ", + "PLP ", "AND # ", "ROL A ", "ANC*# ", + "BIT $nnnn ", "AND $nnnn ", "ROL $nnnn ", "RLA*$nnnn ", + + "BMI rel ", "AND ($nn),Y ", "HLT* ", "RLA*($nn),Y ", + "NOP*$nn,X ", "AND $nn,X ", "ROL $nn,X ", "RLA*$nn,X ", + "SEC ", "AND $nnnn,Y ", "NOP* ", "RLA*$nnnn,Y ", + "NOP*$nnnn,X ", "AND $nnnn,X ", "ROL $nnnn,X ", "RLA*$nnnn,X ", + + "RTI ", "EOR ($nn,X) ", "HLT* ", "LSE*($nn,X) ", + "NOP*$nn ", "EOR $nn ", "LSR $nn ", "LSE*$nn ", + "PHA ", "EOR # ", "LSR A ", "ALR*# ", + "JMP $nnnn ", "EOR $nnnn ", "LSR $nnnn ", "LSE*$nnnn ", + + "BVC rel ", "EOR ($nn),Y ", "HLT* ", "LSE*($nn),Y ", + "NOP $nn,X ", "EOR $nn,X ", "LSR $nn,X ", "LSE*$nn,X ", + "CLI ", "EOR $nnnn,Y ", "NOP* ", "LSE*$nnnn,Y ", + "NOP*$nnnn,X ", "EOR $nnnn,X ", "LSR $nnnn,X ", "LSE*$nnnn,X ", + + "RTS ", "ADC ($nn,X) ", "HLT* ", "RRA*($nn,X) ", + "NOP*$nn ", "ADC $nn ", "ROR $nn ", "RRA*$nn ", + "PLA ", "ADC # ", "ROR A ", "ARR*# ", + "JMP ($nnnn) ", "ADC $nnnn ", "ROR $nnnn ", "RRA*$nnnn ", + + "BVS rel ", "ADC ($nn),Y ", "HLT* ", "RRA*($nn),Y ", + "NOP $nn,X ", "ADC $nn,X ", "ROR $nn,X ", "RRA*$nn,X ", + "SEI ", "ADC $nnnn,Y ", "NOP* ", "RRA*$nnnn,Y ", + "NOP*$nnnn,X ", "ADC $nnnn,X ", "ROR $nnnn,X ", "RRA*$nnnn,X ", + + "NOP*# ", "STA ($nn,X) ", "NOP*# ", "SAX*($nn,X) ", + "STY $nn ", "STA $nn ", "STX $nn ", "SAX*$nn ", + "DEY ", "NOP*# ", "TXA ", "XAA*# ", + "STY $nnnn ", "STA $nnnn ", "STX $nnnn ", "SAX*$nnnn ", + + "BCC rel ", "STA ($nn),Y ", "HLT* ", "AHX*($nn),Y ", + "STY $nn,X ", "STA $nn,X ", "STX $nn,Y ", "SAX*$nn,Y ", + "TYA ", "STA $nnnn,Y ", "TXS ", "TAS*$nnnn,Y ", + "SHY*$nnnn,X ", "STA $nnnn,X ", "SHX*$nnnn,Y ", "AHX*$nnnn,Y ", + + "LDY # ", "LDA ($nn,X) ", "LDX # ", "LAX*($nn,X) ", + "LDY $nn ", "LDA $nn ", "LDX $nn ", "LAX*$nn ", + "TAY ", "LDA # ", "TAX ", "LAX*# ", + "LDY $nnnn ", "LDA $nnnn ", "LDX $nnnn ", "LAX*$nnnn ", + + "BCS rel ", "LDA ($nn),Y ", "HLT* ", "LAX*($nn),Y ", + "LDY $nn,X ", "LDA $nn,X ", "LDX $nn,Y ", "LAX*$nn,Y ", + "CLV ", "LDA $nnnn,Y ", "TSX ", "LAS*$nnnn,Y ", + "LDY $nnnn,X ", "LDA $nnnn,X ", "LDX $nnnn,Y ", "LAX*$nnnn,Y ", + + "CPY # ", "CMP ($nn,X) ", "NOP*# ", "DCM*($nn,X) ", + "CPY $nn ", "CMP $nn ", "DEC $nn ", "DCM*$nn ", + "INY ", "CMP # ", "DEX ", "AXS*# ", + "CPY $nnnn ", "CMP $nnnn ", "DEC $nnnn ", "DCM*$nnnn ", + + "BNE rel ", "CMP ($nn),Y ", "HLT* ", "DCM*($nn),Y ", + "NOP*$nn,X ", "CMP $nn,X ", "DEC $nn,X ", "DCM*$nn,X ", + "CLD ", "CMP $nnnn,Y ", "NOP* ", "DCM*$nnnn,Y ", + "NOP*$nnnn,X ", "CMP $nnnn,X ", "DEC $nnnn,X ", "DCM*$nnnn,X ", + + "CPX # ", "SBC ($nn,X) ", "NOP*# ", "INS*($nn,X) ", + "CPX $nn ", "SBC $nn ", "INC $nn ", "INS*$nn ", + "INX ", "SBC # ", "NOP ", "SBC*# ", + "CPX $nnnn ", "SBC $nnnn ", "INC $nnnn ", "INS*$nnnn ", + + "BEQ rel ", "SBC ($nn),Y ", "HLT* ", "INS*($nn),Y ", + "NOP*$nn,X ", "SBC $nn,X ", "INC $nn,X ", "INS*$nn,X ", + "SED ", "SBC $nnnn,Y ", "NOP* ", "INS*$nnnn,Y ", + "NOP*$nnnn,X ", "SBC $nnnn,X ", "INC $nnnn,X ", "INS*$nnnn,X " +}; + +static const uint16_t illegal_map[16] = { + 0x989C, 0x9C9C, 0x888C, 0x9C9C, + 0x889C, 0x9C9C, 0x889C, 0x9C9C, + 0x8A8D, 0xD88C, 0x8888, 0x888C, + 0x888C, 0x9C9C, 0x888C, 0x9C9C +}; + +bool is_illegal_opcode(uint8_t opcode) +{ + uint16_t row = illegal_map[opcode >> 4]; + return ((row >> (opcode & 0x0F)) & 1) != 0; +} + +void canonicalize_mnemonic(uint8_t opcode, const char *templ, char *mnemonic) +{ + mnemonic[0] = templ[0]; + mnemonic[1] = templ[1]; + mnemonic[2] = templ[2]; + mnemonic[3] = 0; + + if (!strcmp(mnemonic, "HLT")) { + strcpy(mnemonic, "JAM"); + } else if (!strcmp(mnemonic, "ASO")) { + strcpy(mnemonic, "SLO"); + } else if (!strcmp(mnemonic, "LSE")) { + strcpy(mnemonic, "SRE"); + } else if (!strcmp(mnemonic, "DCM")) { + strcpy(mnemonic, "DCP"); + } else if (!strcmp(mnemonic, "INS")) { + strcpy(mnemonic, "ISC"); + } +} + +const char *operand_spec(const char *templ) +{ + const char *spec = templ + 4; + + while (*spec == ' ') { + spec++; + } + return spec; +} + +uint8_t operand_length(const char *templ) +{ + const char *spec = operand_spec(templ); + + if (*spec == 0 || !strncmp(spec, "A", 1)) { + return 0; + } + if (!strncmp(spec, "rel", 3)) { + return 1; + } + if (!strncmp(spec, "($nnnn,X)", 9) || !strncmp(spec, "($nnnn)", 7) || + !strncmp(spec, "(ABS,X)", 7) || !strncmp(spec, "$nnnn,Y", 7) || + !strncmp(spec, "$nnnn,X", 7) || !strncmp(spec, "$nnnn", 5)) { + return 2; + } + if (!strncmp(spec, "($nn,X)", 7) || !strncmp(spec, "($nn),Y", 7) || + !strncmp(spec, "$nn,Y", 5) || !strncmp(spec, "$nn,X", 5) || + !strncmp(spec, "$nn", 3) || !strncmp(spec, "#", 1)) { + return 1; + } + return 0; +} + +uint8_t instruction_length(const char *templ) +{ + return (uint8_t)(1 + operand_length(templ)); +} + +void trim_operand(char *operand) +{ + int len = strlen(operand); + while (len > 0 && operand[len - 1] == ' ') { + operand[--len] = 0; + } +} + +void format_operand(uint8_t opcode, uint16_t pc, const uint8_t *bytes, uint8_t length, const char *templ, char *operand, bool *has_target, uint16_t *target) +{ + const char *spec = templ + 4; + + *has_target = false; + *target = 0; + operand[0] = 0; + + while (*spec == ' ') { + spec++; + } + if (*spec == 0) { + return; + } + if (!strncmp(spec, "A", 1)) { + strcpy(operand, "A"); + return; + } + if (!strncmp(spec, "rel", 3)) { + *has_target = true; + *target = (uint16_t)(pc + 2 + (int8_t)bytes[1]); + sprintf(operand, "$%04x", *target); + return; + } + if (!strncmp(spec, "#", 1)) { + if (length == 2) { + sprintf(operand, "#$%02x", bytes[1]); + } + return; + } + if (!strncmp(spec, "($nn,X)", 7)) { + sprintf(operand, "($%02x,X)", bytes[1]); + return; + } + if (!strncmp(spec, "($nn),Y", 7)) { + sprintf(operand, "($%02x),Y", bytes[1]); + return; + } + if (!strncmp(spec, "($nnnn)", 7)) { + sprintf(operand, "($%04x)", (uint16_t)(bytes[1] | (bytes[2] << 8))); + return; + } + if (!strncmp(spec, "($nnnn,X)", 9) || !strncmp(spec, "(ABS,X)", 7)) { + sprintf(operand, "($%04x,X)", (uint16_t)(bytes[1] | (bytes[2] << 8))); + return; + } + if (!strncmp(spec, "$nnnn,Y", 7)) { + sprintf(operand, "$%04x,Y", (uint16_t)(bytes[1] | (bytes[2] << 8))); + return; + } + if (!strncmp(spec, "$nnnn,X", 7)) { + sprintf(operand, "$%04x,X", (uint16_t)(bytes[1] | (bytes[2] << 8))); + return; + } + if (!strncmp(spec, "$nnnn", 5)) { + sprintf(operand, "$%04x", (uint16_t)(bytes[1] | (bytes[2] << 8))); + return; + } + if (!strncmp(spec, "$nn,Y", 5)) { + sprintf(operand, "$%02x,Y", bytes[1]); + return; + } + if (!strncmp(spec, "$nn,X", 5)) { + sprintf(operand, "$%02x,X", bytes[1]); + return; + } + if (!strncmp(spec, "$nn", 3)) { + sprintf(operand, "$%02x", bytes[1]); + return; + } + strncpy(operand, spec, 23); + operand[23] = 0; + trim_operand(operand); +} + +} + +void disassemble_6502(uint16_t pc, const uint8_t *bytes, bool illegal_enabled, Disassembled6502 *out) +{ + uint8_t opcode = bytes[0]; + const char *templ = opcode_templates[opcode]; + char mnemonic[4]; + char operand[24]; + + memset(out, 0, sizeof(Disassembled6502)); + out->valid = true; + out->illegal = is_illegal_opcode(opcode); + out->operand_bytes = operand_length(templ); + out->length = instruction_length(templ); + + if (out->illegal && !illegal_enabled) { + out->valid = false; + out->operand_bytes = 0; + strcpy(out->text, "???"); + out->length = 1; + return; + } + + canonicalize_mnemonic(opcode, templ, mnemonic); + format_operand(opcode, pc, bytes, out->length, templ, operand, &out->has_target, &out->target); + + if (operand[0]) { + sprintf(out->text, "%s %s", mnemonic, operand); + } else { + strcpy(out->text, mnemonic); + } +} +const char *disassembler_6502_template(uint8_t opcode) +{ + return opcode_templates[opcode]; +} + +bool disassembler_6502_is_illegal(uint8_t opcode) +{ + return is_illegal_opcode(opcode); +} diff --git a/software/monitor/disassembler_6502.h b/software/monitor/disassembler_6502.h new file mode 100644 index 000000000..7fbe6c13e --- /dev/null +++ b/software/monitor/disassembler_6502.h @@ -0,0 +1,24 @@ +#ifndef DISASSEMBLER_6502_H +#define DISASSEMBLER_6502_H + +#include "integer.h" + +struct Disassembled6502 +{ + uint8_t length; + uint8_t operand_bytes; + bool valid; + bool illegal; + bool has_target; + uint16_t target; + char text[32]; +}; + +void disassemble_6502(uint16_t pc, const uint8_t *bytes, bool illegal_enabled, Disassembled6502 *out); + +// Accessors used by the matching assembler so the encoder remains +// bit-aligned with the decoder by construction. +const char *disassembler_6502_template(uint8_t opcode); +bool disassembler_6502_is_illegal(uint8_t opcode); + +#endif diff --git a/software/monitor/machine_monitor.cc b/software/monitor/machine_monitor.cc new file mode 100644 index 000000000..379b5e3db --- /dev/null +++ b/software/monitor/machine_monitor.cc @@ -0,0 +1,8094 @@ +#include "machine_monitor.h" + +#include "assembler_6502.h" +#include "disassembler_6502.h" +#include "monitor_debug_predictor.h" +#include "monitor_debug_session.h" +#include "editor.h" +#include "userinterface.h" +#include "monitor_file_io.h" +#include "monitor_bookmarks.h" +#include "screen.h" +#include "keyboard.h" +#include "itu.h" + +extern "C" { +#include "dump_hex.h" +#include "small_printf.h" +} + +#include +#include + +int swap_interface_type(UserInterface *ui) __attribute__ ((weak)); + +namespace { + +#ifdef RUNS_ON_PC +static const uint8_t monitor_cursor_blink_idle_polls = 3; +#else +static const uint16_t monitor_cursor_blink_half_period_ms = 400; +#endif + +static const char *const monitor_help_lines[] = { + "", + "M Memory I ASCII V Screen", + "A Assembly B Binary U Undoc/Case", + "J Jump G Go D Debug", + "", + "E Edit F Fill T Transfer", + "C Compare H Hunt N Number", + "W Width R Range P Poll", + "Z Freeze O CPU Bank SH+O VIC", + "L Load S Save", + "", + "Bookmarks: C=+B List C=+0-9 Jump", + "", + "Monitor: C=+O Open/Close", + "Leave edit: C=+E/RSTOP", + "Copy/Paste: C=+C / C=+V", + "Reset/Follow: C=+X Reset / RETURN", + NULL +}; + +static const char monitor_help_paging_line[] = "Page Up/Down: F1/SH+SPACE / F7/SPACE"; +static const char monitor_debug_help_paging_line[] = "Page Up/Down: F1/SH+SPACE / F7/SPACE"; + +static bool monitor_saved_state_valid = false; +static MachineMonitorState monitor_saved_state = { + MONITOR_VIEW_HEX, + 0x0801, + 0x0801, + 0, + false, + MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS, + 0x07 +}; + +static bool monitor_reset_reopen_state_valid = false; +static MachineMonitorState monitor_reset_reopen_state; +static bool monitor_reset_reopen_debug_active = false; +// Set on every C64 hardware reset (REST / C=+X / RESET button). The next fresh +// monitor open syncs its view bank to the live CPU bank so re-entry decodes the +// memory the CPU actually sees (e.g. RAM-under-ROM when $01 low bits are 5), +// instead of carrying a stale exploratory view or a hardcoded ROM (bank 7) view. +// This does NOT touch ordinary close/reopen (no intervening reset), so manual +// O bank exploration still persists across those opens. +static bool monitor_sync_view_to_live_on_open = false; + +// Process-lifetime breakpoint storage. Survives monitor close/reopen, the +// C=+X reset reentry path, and Stop-Debugging cleanup, but is volatile RAM +// so power-off clears it. The MachineMonitor constructor copies from this +// into its local table; deinit() copies the local table back out. +static MonitorBreakpoints monitor_saved_breakpoints; + +static const char *monitor_debug_result_name(DebugSession::Result result); +static const char *monitor_view_name(MachineMonitorView view); +static void monitor_log(const char *action); +static void monitor_log_address(const char *action, uint16_t address); +static void monitor_log_value(const char *action, uint16_t address, uint16_t value); +static void monitor_log_byte(const char *action, uint16_t address, uint8_t value); +static void monitor_log_range(const char *action, uint16_t start, uint16_t end); +static void monitor_log_debug(const char *action, uint16_t pc, DebugSession::Result result); + +static MachineMonitorState monitor_reset_reentry_state(const MachineMonitorState &source) +{ + MachineMonitorState sanitized; + sanitized.view = source.view; + sanitized.current_addr = source.current_addr; + sanitized.base_addr = source.base_addr; + sanitized.disasm_offset = source.disasm_offset; + if (source.view == MONITOR_VIEW_ASM) { + sanitized.base_addr = source.current_addr; + sanitized.disasm_offset = 0; + } + sanitized.illegal_enabled = source.illegal_enabled; + sanitized.screen_charset = source.screen_charset; + sanitized.view_cpu_port = source.view_cpu_port; + return sanitized; +} + +// Persistent LOAD/SAVE/GO state (across monitor invocations within a single +// firmware run). Defaults match the spec: a "press L, RETURN, RETURN" sequence +// loads a PRG to its embedded address, "press S, RETURN, RETURN" saves the +// canonical $0800-$9FFF range, and GO pre-fills with the current cursor +// address (handled at the call site). +static bool monitor_last_load_use_prg = true; +static uint16_t monitor_last_load_start = 0x0801; +static uint16_t monitor_last_load_offset = 0x0000; +static bool monitor_last_load_length_auto = true; +static uint32_t monitor_last_load_length = 0; + +static uint16_t monitor_last_save_start = 0x0800; +static uint16_t monitor_last_save_end = 0x9FFF; +static char monitor_last_save_name[40] = ""; + +static bool monitor_last_go_valid = false; +static uint16_t monitor_last_go_addr = 0; + +// Persistent BINARY view configuration. Width is byte-based only; every byte +// renders as 8 bits. Packed 3-byte sprite mode (3S) uses +// MONITOR_BINARY_SPRITE_MODE_MARKER (0xFE) and renders 3 bytes. +static uint8_t monitor_memory_bytes_per_row = MONITOR_HEX_BYTES_PER_ROW; +static uint8_t monitor_binary_bytes_per_row = 1; + +static inline uint8_t monitor_memory_byte_stride(uint8_t bytes_per_row) +{ + return (bytes_per_row >= MONITOR_MEMORY_MAX_BYTES_PER_ROW) ? + MONITOR_MEMORY_MAX_BYTES_PER_ROW : MONITOR_MEMORY_MIN_BYTES_PER_ROW; +} + +static inline uint8_t monitor_binary_byte_stride(uint8_t bytes_per_row) +{ + uint8_t b = bytes_per_row; + // Sprite mode marker returns 3 bytes. + if (b == MONITOR_BINARY_SPRITE_MODE_MARKER) return 3; + if (b < MONITOR_BINARY_MIN_BYTES_PER_ROW) b = MONITOR_BINARY_MIN_BYTES_PER_ROW; + if (b > MONITOR_BINARY_MAX_BYTES_PER_ROW) b = MONITOR_BINARY_MAX_BYTES_PER_ROW; + return b; +} + +static inline bool monitor_binary_packed_bits(uint8_t bytes_per_row) +{ + return bytes_per_row == MONITOR_BINARY_SPRITE_MODE_MARKER || bytes_per_row == 4; +} + +static inline bool monitor_binary_shows_hex_preview(uint8_t bytes_per_row) +{ + return bytes_per_row != 4; +} + +static inline bool monitor_row_contains(uint16_t start, uint16_t length, uint16_t address) +{ + uint32_t end = (uint32_t)start + (uint32_t)(length ? length : 1); + + return ((uint32_t)address >= (uint32_t)start) && ((uint32_t)address < end); +} + +static inline uint8_t monitor_disasm_bytes_to_end(uint16_t address) +{ + uint32_t remaining = 0x10000UL - (uint32_t)address; + + if (remaining > 3UL) { + remaining = 3UL; + } + return (uint8_t)remaining; +} + +static inline void monitor_disasm_tail_cutover(uint16_t address, Disassembled6502 *decoded) +{ + if (decoded->length <= monitor_disasm_bytes_to_end(address)) { + return; + } + + decoded->valid = false; + decoded->illegal = false; + decoded->operand_bytes = 0; + decoded->has_target = false; + decoded->target = 0; + decoded->length = 1; + strcpy(decoded->text, "???"); +} + +static inline bool monitor_disasm_row_contains(uint16_t start, uint8_t length, uint16_t address) +{ + return monitor_row_contains(start, length, address); +} + +static int monitor_bookmark_main_slot_for_key(int key) +{ + return key_ctrl_digit_value(key); +} + +static int monitor_bookmark_popup_slot_for_key(int key) +{ + if (key >= '0' && key <= '9') { + return key - '0'; + } + return -1; +} + +static bool monitor_key_is_bookmark_popup(int key) +{ + return key == KEY_CTRL_B; +} + +static bool monitor_key_is_bookmark_action(int key) +{ + return monitor_key_is_bookmark_popup(key) || + (monitor_bookmark_main_slot_for_key(key) >= 0); +} + +static bool monitor_deadline_reached(uint16_t deadline, uint16_t now) +{ + return (int16_t)(now - deadline) >= 0; +} + +static bool is_hex_char(char c); +static char to_upper_char(char c); +static uint8_t normalize_screen_charset(uint8_t screen_charset); +static bool monitor_hunt_prompt_inside_quotes(const char *buffer, int cur); +static int monitor_hunt_prompt_transform_key(const char *buffer, int cur, int key); +static char monitor_ascii_display_byte(uint8_t value); +static char monitor_screen_display_byte(uint8_t value, uint8_t screen_charset); +static bool monitor_ascii_key_to_byte(int key, uint8_t *out); +static bool monitor_screen_key_to_code(int key, uint8_t screen_charset, uint8_t *out); +static void monitor_format_text_row_impl(uint16_t address, const uint8_t *bytes, int count, + bool screen_codes, uint8_t screen_charset, char *out); + +enum { + MONITOR_NUMBER_ROW_HEX = 0, + MONITOR_NUMBER_ROW_DECIMAL, + MONITOR_NUMBER_ROW_BINARY, + MONITOR_NUMBER_ROW_ASCII, + MONITOR_NUMBER_ROW_SCREEN, + MONITOR_NUMBER_ROW_COUNT, + MONITOR_NUMBER_EDIT_BUFFER_MAX = 16, + MONITOR_NUMBER_EXPR_BUFFER_MAX = 24, + MONITOR_NUMBER_POPUP_INNER_WIDTH = 28, + MONITOR_NUMBER_POPUP_INNER_HEIGHT = 7, + MONITOR_NUMBER_POPUP_WIDTH = MONITOR_NUMBER_POPUP_INNER_WIDTH + 2, + MONITOR_NUMBER_POPUP_HEIGHT = MONITOR_NUMBER_POPUP_INNER_HEIGHT + 2, + // Shared UI accent colour used by UserInterface::set_screen_title() and + // bottom-row help text via the historical "\eA" escape sequence. + MONITOR_UI_ACCENT_COLOR = 1, + MONITOR_RETURN_STACK_MAX = 10, +}; + +static const uint8_t monitor_number_row_max_input[MONITOR_NUMBER_ROW_COUNT] = { + 4, 5, 16, 2, 2 +}; + +static const char monitor_hex_chars[] = "0123456789ABCDEF"; + +static void dump_hex_byte(char *buf, int offset, uint8_t byte) +{ + buf[offset] = monitor_hex_chars[(byte >> 4) & 0x0F]; + buf[offset + 1] = monitor_hex_chars[byte & 0x0F]; +} + +static void dump_hex_word(char *buf, int offset, uint16_t word) +{ + dump_hex_byte(buf, offset, (word >> 8) & 0xFF); + dump_hex_byte(buf, offset + 2, word & 0xFF); +} + +static bool is_decimal_char(char c) +{ + return c >= '0' && c <= '9'; +} + +static bool is_binary_char(char c) +{ + return c == '0' || c == '1'; +} + +static bool monitor_number_parse_buffer(int row, const char *buffer, int length, + uint16_t *value, bool *word, + uint8_t screen_charset) +{ + uint32_t parsed = 0; + + if (length <= 0 || !buffer || !value || !word) { + return false; + } + + switch (row) { + case MONITOR_NUMBER_ROW_HEX: + if (length > 4) { + return false; + } + for (int i = 0; i < length; i++) { + char c = to_upper_char(buffer[i]); + if (!is_hex_char(c)) { + return false; + } + parsed <<= 4; + parsed |= (c <= '9') ? (uint32_t)(c - '0') : (uint32_t)(c - 'A' + 10); + } + *value = (uint16_t)parsed; + *word = length > 2; + return true; + + case MONITOR_NUMBER_ROW_DECIMAL: + if (length > 5) { + return false; + } + for (int i = 0; i < length; i++) { + if (!is_decimal_char(buffer[i])) { + return false; + } + parsed = parsed * 10 + (uint32_t)(buffer[i] - '0'); + if (parsed > 65535UL) { + return false; + } + } + *value = (uint16_t)parsed; + *word = parsed > 0xFFUL; + return true; + + case MONITOR_NUMBER_ROW_BINARY: + if (length > 16) { + return false; + } + for (int i = 0; i < length; i++) { + if (!is_binary_char(buffer[i])) { + return false; + } + parsed = (parsed << 1) | (uint32_t)(buffer[i] - '0'); + } + *value = (uint16_t)parsed; + *word = length > 8; + return true; + + case MONITOR_NUMBER_ROW_ASCII: + if (length > 2) { + return false; + } + for (int i = 0; i < length; i++) { + unsigned char c = (unsigned char)buffer[i]; + if (c < 32 || c > 126) { + return false; + } + parsed = (parsed << 8) | c; + } + *value = (uint16_t)parsed; + *word = length > 1; + return true; + + case MONITOR_NUMBER_ROW_SCREEN: + if (length > 2) { + return false; + } + for (int i = 0; i < length; i++) { + uint8_t code = monitor_screen_code_for_char(buffer[i], screen_charset); + if (code == 0xFF) { + return false; + } + parsed = (parsed << 8) | code; + } + *value = (uint16_t)parsed; + *word = length > 1; + return true; + + default: + break; + } + return false; +} + +static char monitor_number_screen_display_char(uint8_t value, uint8_t screen_charset) +{ + return monitor_screen_display_byte(value, screen_charset); +} + +static bool is_space_char(char c) +{ + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; +} + +static bool is_hex_char(char c) +{ + return ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')); +} + +static char to_upper_char(char c) +{ + if (c >= 'a' && c <= 'z') { + return c - 32; + } + return c; +} + +static uint8_t normalize_screen_charset(uint8_t screen_charset) +{ + return (screen_charset == MONITOR_SCREEN_CHARSET_LOWER_UPPER) ? + MONITOR_SCREEN_CHARSET_LOWER_UPPER : + MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS; +} + +static bool monitor_hunt_prompt_inside_quotes(const char *buffer, int cur) +{ + bool inside_quotes = false; + + for (int i = 0; i < cur && buffer[i]; i++) { + if (buffer[i] == '"') { + inside_quotes = !inside_quotes; + } + } + return inside_quotes; +} + +static int monitor_hunt_prompt_transform_key(const char *buffer, int cur, int key) +{ + if (key >= 'a' && key <= 'z' && !monitor_hunt_prompt_inside_quotes(buffer, cur)) { + return key - 'a' + 'A'; + } + return key; +} + +static void skip_spaces(const char *&cursor) +{ + while (*cursor && is_space_char(*cursor)) { + cursor++; + } +} + +static MonitorError parse_hex_digits(const char *&cursor, int min_digits, int max_digits, uint16_t max_value, uint16_t *value) +{ + int digits = 0; + uint32_t parsed = 0; + + skip_spaces(cursor); + if (*cursor == '$') { + cursor++; + } + while (is_hex_char(*cursor) && digits < max_digits) { + char c = to_upper_char(*cursor++); + parsed <<= 4; + if (c >= '0' && c <= '9') { + parsed |= (uint32_t)(c - '0'); + } else { + parsed |= (uint32_t)(c - 'A' + 10); + } + digits++; + } + if (digits < min_digits) { + return MONITOR_ADDR; + } + if (parsed > max_value) { + return (max_value == 0xFF) ? MONITOR_VALUE : MONITOR_ADDR; + } + *value = (uint16_t)parsed; + return MONITOR_OK; +} + +static MonitorError expect_separator(const char *&cursor, char sep, MonitorError error) +{ + skip_spaces(cursor); + if (*cursor != sep) { + return error; + } + cursor++; + return MONITOR_OK; +} + +static int append_text(char *out, int out_len, int pos, const char *text) +{ + while (*text && pos < (out_len - 1)) { + out[pos++] = *text++; + } + out[pos] = 0; + return pos; +} + +static int append_line_address(char *out, int out_len, int pos, uint16_t address) +{ + char line[8]; + sprintf(line, "$%04x\n", address); + return append_text(out, out_len, pos, line); +} + +static int parse_decimal(const char *cursor, uint16_t *value) +{ + uint32_t parsed = 0; + int digits = 0; + while (*cursor >= '0' && *cursor <= '9') { + parsed = parsed * 10 + (uint32_t)(*cursor - '0'); + cursor++; + digits++; + } + if (digits == 0 || *cursor) { + return 0; + } + if (parsed > 0xFFFF) { + return 0; + } + *value = (uint16_t)parsed; + return 1; +} + +static int parse_binary(const char *cursor, uint16_t *value) +{ + uint32_t parsed = 0; + int digits = 0; + while (*cursor == '0' || *cursor == '1') { + parsed = (parsed << 1) | (uint32_t)(*cursor - '0'); + cursor++; + digits++; + if (parsed > 0xFFFF) { + return 0; + } + } + if (digits == 0 || *cursor) { + return 0; + } + *value = (uint16_t)parsed; + return 1; +} + +static MonitorError parse_number_core(const char *text, uint16_t *value) +{ + char buffer[80]; + int pos = 0; + const char *cursor = text; + + while (*cursor && pos < 79) { + if (!is_space_char(*cursor)) { + buffer[pos++] = *cursor; + } + cursor++; + } + buffer[pos] = 0; + if (!buffer[0]) { + return MONITOR_SYNTAX; + } + if (buffer[0] == '$') { + const char *hex = buffer; + return parse_hex_digits(hex, 1, 4, 0xFFFF, value); + } + if (buffer[0] == '%') { + return parse_binary(buffer + 1, value) ? MONITOR_OK : MONITOR_SYNTAX; + } + return parse_decimal(buffer, value) ? MONITOR_OK : MONITOR_SYNTAX; +} + +static bool monitor_number_expr_operator(char c) +{ + return c == '+' || c == '-' || c == '*' || c == '/'; +} + +static bool monitor_number_expr_parse_value(const char *&cursor, uint32_t *value) +{ + char token[32]; + int len = 0; + uint16_t parsed = 0; + + skip_spaces(cursor); + while (*cursor && !is_space_char(*cursor) && !monitor_number_expr_operator(*cursor)) { + if (len >= (int)sizeof(token) - 1) { + return false; + } + token[len++] = *cursor++; + } + token[len] = 0; + if (len <= 0) { + return false; + } + if (parse_number_core(token, &parsed) != MONITOR_OK) { + return false; + } + *value = parsed; + return true; +} + +static MonitorError monitor_number_expr_parse_term(const char *&cursor, uint32_t *value) +{ + uint32_t result; + + if (!monitor_number_expr_parse_value(cursor, &result)) { + return MONITOR_SYNTAX; + } + while (true) { + uint32_t rhs; + char op; + + skip_spaces(cursor); + op = *cursor; + if (op != '*' && op != '/') { + break; + } + cursor++; + if (!monitor_number_expr_parse_value(cursor, &rhs)) { + return MONITOR_SYNTAX; + } + if (op == '*') { + if (rhs != 0 && result > 0xFFFFFFFFUL / rhs) { + return MONITOR_RANGE; + } + result *= rhs; + } else { + if (rhs == 0) { + return MONITOR_VALUE; + } + result /= rhs; + } + } + *value = result; + return MONITOR_OK; +} + +static MonitorError monitor_number_expr_evaluate(const char *text, uint16_t max_value, uint16_t *value) +{ + const char *cursor = text; + uint32_t result; + MonitorError error = monitor_number_expr_parse_term(cursor, &result); + + if (error != MONITOR_OK) { + return error; + } + while (true) { + uint32_t rhs; + char op; + + skip_spaces(cursor); + op = *cursor; + if (!op) { + break; + } + if (op != '+' && op != '-') { + return MONITOR_SYNTAX; + } + cursor++; + error = monitor_number_expr_parse_term(cursor, &rhs); + if (error != MONITOR_OK) { + return error; + } + if (op == '+') { + if (result > 0xFFFFFFFFUL - rhs) { + return MONITOR_RANGE; + } + result += rhs; + } else { + if (rhs > result) { + return MONITOR_RANGE; + } + result -= rhs; + } + } + if (result > max_value) { + return MONITOR_RANGE; + } + *value = (uint16_t)result; + return MONITOR_OK; +} + +static char monitor_ascii_display_byte(uint8_t value) +{ + if (value < 32 || value > 126) { + return '.'; + } + return (char)value; +} + +static char monitor_screen_display_byte(uint8_t value, uint8_t screen_charset) +{ + uint8_t base = (uint8_t)(value & 0x7F); + + screen_charset = normalize_screen_charset(screen_charset); + + if (base == 0x00) { + return '@'; + } + if (base >= 0x01 && base <= 0x1A) { + return (char)((screen_charset == MONITOR_SCREEN_CHARSET_LOWER_UPPER ? 'a' : 'A') + (base - 1)); + } + if (base == 0x1B) { + return '['; + } + if (base == 0x1C) { + return '#'; + } + if (base == 0x1D) { + return ']'; + } + if (base == 0x1E) { + return '^'; + } + if (base == 0x1F) { + return '<'; + } + if (base >= 0x20 && base <= 0x3F) { + return (char)base; + } + if (screen_charset == MONITOR_SCREEN_CHARSET_LOWER_UPPER && base >= 0x41 && base <= 0x5A) { + return (char)('A' + (base - 0x41)); + } + + switch (base) { + case 0x40: return CHR_HORIZONTAL_LINE; + case 0x41: return 'S'; + case 0x42: return '|'; + case 0x43: return CHR_HORIZONTAL_LINE; + case 0x44: return CHR_HORIZONTAL_LINE; + case 0x45: return CHR_HORIZONTAL_LINE; + case 0x46: return CHR_HORIZONTAL_LINE; + case 0x47: return '|'; + case 0x48: return '|'; + case 0x49: return CHR_ROUNDED_UPPER_RIGHT; + case 0x4A: return CHR_ROUNDED_LOWER_LEFT; + case 0x4B: return CHR_ROUNDED_LOWER_RIGHT; + case 0x4C: return CHR_SOLID_BAR_LOWER_7; + case 0x4D: return '\\'; + case 0x4E: return '/'; + case 0x4F: return CHR_SOLID_BAR_UPPER_7; + case 0x50: return CHR_SOLID_BAR_UPPER_7; + case 0x51: return '*'; + case 0x52: return CHR_HORIZONTAL_LINE; + case 0x53: return 'H'; + case 0x54: return '|'; + case 0x55: return CHR_ROUNDED_UPPER_LEFT; + case 0x56: return 'X'; + case 0x57: return 'O'; + case 0x58: return 'C'; + case 0x59: return '|'; + case 0x5A: return CHR_DIAMOND; + case 0x5B: return '+'; + case 0x5C: return '#'; + case 0x5D: return CHR_VERTICAL_LINE; + case 0x5E: return 'P'; + case 0x5F: return '^'; + default: return '.'; + } +} + +static bool monitor_ascii_key_to_byte(int key, uint8_t *out) +{ + if (!out || key < 32 || key >= 127) { + return false; + } + *out = (uint8_t)key; + return true; +} + +static bool monitor_screen_key_to_code(int key, uint8_t screen_charset, uint8_t *out) +{ + uint8_t code; + + if (!out || key < 32 || key >= 127) { + return false; + } + code = monitor_screen_code_for_char((char)key, screen_charset); + if (code == 0xFF) { + return false; + } + *out = code; + return true; +} + +static void monitor_format_text_row_impl(uint16_t address, const uint8_t *bytes, int count, + bool screen_codes, uint8_t screen_charset, char *out) +{ + memset(out, ' ', MONITOR_TEXT_ROW_CHARS); + dump_hex_word(out, 0, address); + out[4] = ' '; + for (int i = 0; i < count; i++) { + out[5 + i] = screen_codes ? + monitor_screen_display_byte(bytes[i], screen_charset) : + monitor_ascii_display_byte(bytes[i]); + } + out[MONITOR_TEXT_ROW_CHARS] = 0; +} + +static const char *monitor_source_indicator(const char *source) +{ + if (!source) { + return "RAM"; + } + if (!strcmp(source, "BASIC") || !strcmp(source, "BAS")) { + return "BAS"; + } + if (!strcmp(source, "KERNAL") || !strcmp(source, "KRN")) { + return "KRN"; + } + if (!strcmp(source, "CHAR") || !strcmp(source, "CHR")) { + return "CHR"; + } + if (!strcmp(source, "I/O") || !strcmp(source, "IO")) { + return "I/O"; + } + if (!strcmp(source, "RAM")) { + return "RAM"; + } + return source; +} + +static void draw_padded(Window *window, int y, const char *text, int len) +{ + int width = window->get_size_x(); + + if (len > width) { + len = width; + } + if (len < 0) { + len = 0; + } + + window->move_cursor(0, y); + if (len > 0) { + window->output_length(text, len); + } + window->repeat(' ', width - len); +} + +static void draw_with_highlight(Window *window, int y, const char *text, int len, int highlight_x, int highlight_len) +{ + int width = window->get_size_x(); + int before = highlight_x; + int after; + + if (len > width) { + len = width; + } + if (len < 0) { + len = 0; + } + if (highlight_x < 0 || highlight_len <= 0 || highlight_x >= len) { + draw_padded(window, y, text, len); + return; + } + if (before < 0) { + before = 0; + } + after = highlight_x + highlight_len; + if (after > len) { + after = len; + } + + window->move_cursor(0, y); + window->reverse_mode(0); + if (before > 0) { + window->output_length(text, before); + } + window->reverse_mode(1); + window->output_length(text + before, after - before); + window->reverse_mode(0); + if (after < len) { + window->output_length(text + after, len - after); + } + window->repeat(' ', width - len); +} + +static void draw_with_mask(Window *window, int y, const char *text, int len, const bool *mask) +{ + int width = window->get_size_x(); + bool reverse = false; + + if (len > width) { + len = width; + } + if (len < 0) { + len = 0; + } + + window->move_cursor(0, y); + window->reverse_mode(0); + for (int i = 0; i < len; i++) { + bool want = mask && mask[i]; + if (want != reverse) { + reverse = want; + window->reverse_mode(reverse ? 1 : 0); + } + window->output_length(text + i, 1); + } + if (reverse) { + window->reverse_mode(0); + } + window->repeat(' ', width - len); +} + +static void draw_with_style_mask(Window *window, int y, const char *text, int len, + const bool *reverse_mask, const bool *accent_mask, + int normal_color, int accent_color) +{ + int width = window->get_size_x(); + bool reverse = false; + int color = normal_color; + + if (len > width) { + len = width; + } + if (len < 0) { + len = 0; + } + + window->move_cursor(0, y); + window->set_color(normal_color); + window->reverse_mode(0); + for (int i = 0; i < len; i++) { + bool want_reverse = reverse_mask && reverse_mask[i]; + int want_color = (accent_mask && accent_mask[i]) ? accent_color : normal_color; + if (want_reverse != reverse) { + reverse = want_reverse; + window->reverse_mode(reverse ? 1 : 0); + } + if (want_color != color) { + color = want_color; + window->set_color(color); + } + window->output_length(text + i, 1); + } + if (reverse) { + window->reverse_mode(0); + } + window->set_color(normal_color); + window->repeat(' ', width - len); +} + +static bool monitor_debug_branch_taken(uint8_t opcode, uint8_t sr) +{ + switch (opcode) { + case 0x10: return (sr & 0x80) == 0; // BPL + case 0x30: return (sr & 0x80) != 0; // BMI + case 0x50: return (sr & 0x40) == 0; // BVC + case 0x70: return (sr & 0x40) != 0; // BVS + case 0x90: return (sr & 0x01) == 0; // BCC + case 0xB0: return (sr & 0x01) != 0; // BCS + case 0xD0: return (sr & 0x02) == 0; // BNE + case 0xF0: return (sr & 0x02) != 0; // BEQ + } + return false; +} + +static bool monitor_find_target_span(const char *text, int text_len, + int *span_start, int *span_len) +{ + if (!text || text_len <= 0 || !span_start || !span_len) { + return false; + } + for (int i = 0; i < text_len; i++) { + if (text[i] != '$') { + continue; + } + int hex_count = 0; + while (i + 1 + hex_count < text_len) { + char c = text[i + 1 + hex_count]; + bool digit = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || + (c >= 'a' && c <= 'f'); + if (!digit) { + break; + } + hex_count++; + } + if (hex_count >= 4) { + *span_start = i; + *span_len = hex_count + 1; + return true; + } + } + return false; +} + +static bool monitor_normalize_jump_input(char *buffer) +{ + int len = 0; + if (!buffer) { + return false; + } + while (buffer[len]) { + char c = buffer[len]; + if (c >= 'a' && c <= 'f') { + c = (char)(c - 'a' + 'A'); + buffer[len] = c; + } + if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'))) { + return false; + } + len++; + if (len > 4) { + return false; + } + } + return len > 0; +} + +struct MonitorCpuStatusFields { + const char *a000; + const char *d000; + const char *e000; +}; + +static const MonitorCpuStatusFields monitor_cpu_status_fields[8] = { + { "RAM", "RAM", "RAM" }, // CPU0 + { "RAM", "CHR", "RAM" }, // CPU1 + { "RAM", "CHR", "KRN" }, // CPU2 + { "BAS", "CHR", "KRN" }, // CPU3 + { "RAM", "RAM", "RAM" }, // CPU4 + { "RAM", "I/O", "RAM" }, // CPU5 + { "RAM", "I/O", "KRN" }, // CPU6 + { "BAS", "I/O", "KRN" }, // CPU7 +}; + +static const uint16_t monitor_vic_bank_bases[4] = { + 0x0000, 0x4000, 0x8000, 0xC000 +}; + +static uint8_t next_cpu_mode(uint8_t cpu_port) +{ + return (uint8_t)((cpu_port + 1) & 0x07); +} + +static uint8_t next_vic_bank(uint8_t vic_bank) +{ + return (uint8_t)((vic_bank + 1) & 0x03); +} + +static uint8_t normalize_cpu_mode(uint8_t cpu_port) +{ + return cpu_port & 0x07; +} + +static void format_status_line_impl(char *line, uint8_t view_cpu_port, + uint8_t live_cpu_port, uint8_t vic_bank) +{ + uint8_t monitor_bank = view_cpu_port & 0x07; + uint8_t cpu_bank = live_cpu_port & 0x07; + const MonitorCpuStatusFields *fields = &monitor_cpu_status_fields[monitor_bank]; + uint16_t vic_base; + int pos; + + vic_bank &= 0x03; + vic_base = monitor_vic_bank_bases[vic_bank]; + + if (cpu_bank == monitor_bank) { + sprintf(line, "CPU%c $A:%s $D:%s $E:%s VIC%c $", + (char)('0' + cpu_bank), + fields->a000, + fields->d000, + fields->e000, + (char)('0' + vic_bank)); + } else { + sprintf(line, "C%cO%c $A:%s $D:%s $E:%s VIC%c $", + (char)('0' + cpu_bank), + (char)('0' + monitor_bank), + fields->a000, + fields->d000, + fields->e000, + (char)('0' + vic_bank)); + } + pos = strlen(line); + dump_hex_word(line, pos, vic_base); + line[pos + 4] = 0; +} + +static bool inline_edit_view(MachineMonitorView view) +{ + return (view == MONITOR_VIEW_HEX) || (view == MONITOR_VIEW_ASCII) || + (view == MONITOR_VIEW_SCREEN) || (view == MONITOR_VIEW_ASM) || + (view == MONITOR_VIEW_BINARY); +} + +static uint16_t row_span_for_view(MachineMonitorView view, + uint8_t memory_bytes_per_row, + uint8_t binary_bytes_per_row) +{ + if (view == MONITOR_VIEW_ASCII || view == MONITOR_VIEW_SCREEN) { + return MONITOR_TEXT_BYTES_PER_ROW; + } + if (view == MONITOR_VIEW_BINARY) { + // Width is dynamic and configured on the fly by the W shortcut. + return monitor_binary_byte_stride(binary_bytes_per_row); + } + return monitor_memory_byte_stride(memory_bytes_per_row); +} + +} + +uint8_t monitor_screen_code_for_char(char c, uint8_t screen_charset) +{ + screen_charset = (screen_charset == MONITOR_SCREEN_CHARSET_LOWER_UPPER) ? + MONITOR_SCREEN_CHARSET_LOWER_UPPER : + MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS; + + if (c == '@') return 0x00; + if (c == ' ') return 0x20; + if (c >= '0' && c <= '9') return (uint8_t)c; + if (c >= '!' && c <= '?') return (uint8_t)c; + if (c >= 'a' && c <= 'z') return (uint8_t)(c - 'a' + 1); + if (c >= 'A' && c <= 'Z') { + if (screen_charset == MONITOR_SCREEN_CHARSET_LOWER_UPPER) { + return (uint8_t)c; + } + return (uint8_t)(c - 'A' + 1); + } + return 0xFF; +} + +void monitor_format_status_line(char *line, uint8_t view_cpu_port, uint8_t vic_bank) +{ + format_status_line_impl(line, view_cpu_port, view_cpu_port, vic_bank); +} + +void monitor_format_status_line(char *line, uint8_t view_cpu_port, + uint8_t live_cpu_port, uint8_t vic_bank) +{ + format_status_line_impl(line, view_cpu_port, live_cpu_port, vic_bank); +} + +void monitor_format_breakpoint_mismatch(char *out, int out_len, + MonitorBackingStore target, + MonitorBackingStore current) +{ + if (!out || out_len <= 0) { + return; + } + sprintf(out, "BRK %s, CPU %s; not mapped now", + monitor_backing_store_tag(target), + monitor_backing_store_tag(current)); + if ((int)strlen(out) >= out_len) { + out[out_len - 1] = 0; + } +} + +const char *monitor_error_text(MonitorError error) +{ + switch (error) { + case MONITOR_ADDR: return "?ADDR"; + case MONITOR_SYNTAX: return "?SYNTAX"; + case MONITOR_VALUE: return "?VALUE"; + case MONITOR_RANGE: return "?RANGE"; + default: return ""; + } +} + +void monitor_reset_saved_state(void) +{ + // Tests use this to put all persisted monitor state into a deterministic, + // known position. Production startup, by contrast, uses the static + // initializers which default to $0801 and the canonical command defaults. + monitor_saved_state_valid = true; + monitor_saved_state.view = MONITOR_VIEW_HEX; + monitor_saved_state.current_addr = 0; + monitor_saved_state.base_addr = 0; + monitor_saved_state.disasm_offset = 0; + monitor_saved_state.illegal_enabled = false; + monitor_saved_state.screen_charset = MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS; + monitor_saved_state.view_cpu_port = 0x07; + monitor_reset_reopen_state_valid = false; + monitor_reset_reopen_debug_active = false; + + monitor_last_load_use_prg = true; + monitor_last_load_start = 0x0801; + monitor_last_load_offset = 0x0000; + monitor_last_load_length_auto = true; + monitor_last_load_length = 0; + + monitor_last_save_start = 0x0800; + monitor_last_save_end = 0x9FFF; + monitor_last_save_name[0] = 0; + + monitor_last_go_valid = false; + monitor_last_go_addr = 0; + + monitor_memory_bytes_per_row = MONITOR_HEX_BYTES_PER_ROW; + monitor_binary_bytes_per_row = 1; + + monitor_saved_breakpoints.clear_all(); +} + +void monitor_invalidate_saved_state(void) +{ + monitor_saved_state_valid = false; + monitor_reset_reopen_state_valid = false; + monitor_reset_reopen_debug_active = false; +} + +void monitor_reset_saved_cpu_view(void) +{ + // Called on a C64 hardware reset. Rather than hardcoding CPU7 (which is only + // correct when the post-reset CPU actually banks ROM in, and otherwise leaves + // the monitor showing ROM while the live CPU runs RAM-under-ROM -> the C5O7 + // footer mismatch), request that the next fresh monitor open sync its view + // bank to the live CPU bank. 0x07 is kept as the persisted fallback for the + // case where the next open cannot read a live CPU port. + monitor_saved_state.view_cpu_port = 0x07; + if (monitor_reset_reopen_state_valid) { + monitor_reset_reopen_state.view_cpu_port = 0x07; + } + monitor_sync_view_to_live_on_open = true; +} + +void monitor_apply_go(MachineMonitorState *state, uint16_t address) +{ + uint16_t span = row_span_for_view(state->view, monitor_memory_bytes_per_row, + monitor_binary_bytes_per_row); + state->current_addr = address; + if (state->view == MONITOR_VIEW_BINARY) { + // Width is not necessarily a power of two; align using modular + // arithmetic so a row-aligned base remains a multiple of the span. + if (span == 0) span = 1; + state->base_addr = (uint16_t)(address - (address % span)); + } else { + state->base_addr = (uint16_t)(address & (uint16_t)(~(span - 1))); + } + if (state->view == MONITOR_VIEW_DISASM) { + state->base_addr = address; + } + state->disasm_offset = 0; +} + +void monitor_format_hex_row(uint16_t address, const uint8_t *bytes, char *out) +{ + int i; + + memset(out, ' ', MONITOR_HEX_ROW_CHARS); + dump_hex_word(out, 0, address); + for (i = 0; i < MONITOR_HEX_BYTES_PER_ROW; i++) { + dump_hex_byte(out, 5 + (3 * i), bytes[i]); + out[29 + i] = monitor_ascii_display_byte(bytes[i]); + } + out[MONITOR_HEX_ROW_CHARS] = 0; +} + +static void monitor_format_hex16_row(uint16_t address, const uint8_t *bytes, char *out) +{ + memset(out, ' ', MONITOR_MEMORY_ROW_16_CHARS); + dump_hex_word(out, 0, address); + out[4] = ' '; + for (int i = 0; i < 8; i++) { + dump_hex_byte(out, 5 + (2 * i), bytes[i]); + dump_hex_byte(out, 22 + (2 * i), bytes[8 + i]); + } + out[21] = ' '; + out[MONITOR_MEMORY_ROW_16_CHARS] = 0; +} + +void monitor_format_text_row(uint16_t address, const uint8_t *bytes, int count, bool screen_codes, char *out) +{ + monitor_format_text_row_impl(address, bytes, count, screen_codes, + MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS, out); +} + +MonitorError monitor_parse_address(const char *text, uint16_t *address) +{ + const char *cursor = text; + MonitorError error = parse_hex_digits(cursor, 1, 4, 0xFFFF, address); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + skip_spaces(cursor); + return *cursor ? MONITOR_ADDR : MONITOR_OK; +} + +MonitorError monitor_parse_expression(const char *text, uint16_t *value) +{ + return parse_number_core(text, value); +} + +MonitorError monitor_parse_byte_value(const char *text, uint8_t *value) +{ + const char *cursor = text; + uint16_t parsed = 0; + MonitorError error = parse_hex_digits(cursor, 1, 2, 0xFF, &parsed); + if (error != MONITOR_OK) { + return MONITOR_VALUE; + } + skip_spaces(cursor); + if (*cursor) { + return MONITOR_VALUE; + } + *value = (uint8_t)parsed; + return MONITOR_OK; +} + +MonitorError monitor_parse_fill(const char *text, uint16_t *start, uint16_t *end, uint8_t *value) +{ + const char *cursor = text; + uint16_t parsed = 0; + MonitorError error = parse_hex_digits(cursor, 1, 4, 0xFFFF, start); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + error = expect_separator(cursor, '-', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, end); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + if (*end < *start) { + return MONITOR_RANGE; + } + error = expect_separator(cursor, ',', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, &parsed); + if (error != MONITOR_OK) { + return MONITOR_VALUE; + } + if (parsed > 0xFF) { + return MONITOR_VALUE; + } + skip_spaces(cursor); + if (*cursor) { + return MONITOR_SYNTAX; + } + *value = (uint8_t)parsed; + return MONITOR_OK; +} + +MonitorError monitor_parse_transfer(const char *text, uint16_t *start, uint16_t *end, uint16_t *dest) +{ + bool relocate; + uint16_t reloc_start; + uint16_t reloc_end; + MonitorError error = monitor_parse_transfer_relocate(text, start, end, dest, + &relocate, &reloc_start, &reloc_end); + if (error != MONITOR_OK) { + return error; + } + return relocate ? MONITOR_SYNTAX : MONITOR_OK; +} + +MonitorError monitor_parse_transfer_relocate(const char *text, uint16_t *start, uint16_t *end, + uint16_t *dest, bool *relocate, + uint16_t *reloc_start, uint16_t *reloc_end) +{ + const char *cursor = text; + MonitorError error = parse_hex_digits(cursor, 1, 4, 0xFFFF, start); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + error = expect_separator(cursor, '-', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, end); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + if (*end <= *start) { + return MONITOR_RANGE; + } + error = expect_separator(cursor, ',', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, dest); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + skip_spaces(cursor); + if (*cursor == ',') { + cursor++; + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, reloc_start); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + error = expect_separator(cursor, '-', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, reloc_end); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + if (*reloc_end <= *reloc_start) { + return MONITOR_RANGE; + } + skip_spaces(cursor); + *relocate = true; + return *cursor ? MONITOR_SYNTAX : MONITOR_OK; + } + *relocate = false; + if (reloc_start) { + *reloc_start = 0; + } + if (reloc_end) { + *reloc_end = 0; + } + return *cursor ? MONITOR_SYNTAX : MONITOR_OK; +} + +MonitorError monitor_parse_compare(const char *text, uint16_t *start, uint16_t *end, uint16_t *dest) +{ + return monitor_parse_transfer(text, start, end, dest); +} + +MonitorError monitor_parse_hunt(const char *text, uint16_t *start, uint16_t *end, uint8_t *needle, int *needle_len) +{ + const char *cursor = text; + int count = 0; + MonitorError error = parse_hex_digits(cursor, 1, 4, 0xFFFF, start); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + error = expect_separator(cursor, '-', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, end); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + if (*end < *start) { + return MONITOR_RANGE; + } + error = expect_separator(cursor, ',', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + skip_spaces(cursor); + if (*cursor == '"') { + cursor++; + while (*cursor && *cursor != '"') { + if (count >= MONITOR_HUNT_NEEDLE_MAX) { + return MONITOR_RANGE; + } + needle[count++] = (uint8_t)*cursor++; + } + if (*cursor != '"') { + return MONITOR_SYNTAX; + } + cursor++; + } else { + while (*cursor) { + uint16_t parsed = 0; + error = parse_hex_digits(cursor, 1, 2, 0xFF, &parsed); + if (error != MONITOR_OK) { + return count ? MONITOR_SYNTAX : MONITOR_SYNTAX; + } + if (count >= MONITOR_HUNT_NEEDLE_MAX) { + return MONITOR_RANGE; + } + needle[count++] = (uint8_t)parsed; + skip_spaces(cursor); + } + } + skip_spaces(cursor); + if (*cursor) { + return MONITOR_SYNTAX; + } + if (count == 0) { + return MONITOR_SYNTAX; + } + *needle_len = count; + return MONITOR_OK; +} + +void monitor_fill_memory(MemoryBackend *backend, uint16_t start, uint16_t end, uint8_t value) +{ + uint16_t address = start; + do { + backend->write(address, value); + } while (address++ != end); +} + +void monitor_transfer_memory(MemoryBackend *backend, uint16_t start, uint16_t end, uint16_t dest) +{ + uint32_t length = (uint16_t)(end - start); + if (length == 0) { + return; + } + if (dest > start && dest < end) { + while (length) { + length--; + backend->write((uint16_t)(dest + length), backend->read((uint16_t)(start + length))); + } + } else { + uint32_t index; + for (index = 0; index < length; index++) { + backend->write((uint16_t)(dest + index), backend->read((uint16_t)(start + index))); + } + } +} + +static bool monitor_transfer_source_contains(uint16_t start, uint16_t end, uint16_t address) +{ + return address >= start && address < end; +} + +static uint16_t monitor_transfer_mapped_address(uint16_t start, uint16_t end, + uint16_t dest, uint16_t address) +{ + if (monitor_transfer_source_contains(start, end, address)) { + return (uint16_t)(dest + (uint16_t)(address - start)); + } + return address; +} + +static uint8_t monitor_transfer_read_code(MemoryBackend *backend, uint16_t start, uint16_t end, + uint16_t dest, uint16_t address) +{ + return backend->read(monitor_transfer_mapped_address(start, end, dest, address)); +} + +void monitor_transfer_memory_relocate(MemoryBackend *backend, uint16_t start, uint16_t end, + uint16_t dest, uint16_t reloc_start, uint16_t reloc_end) +{ + monitor_transfer_memory(backend, start, end, dest); + + uint16_t address = reloc_start; + while (address < reloc_end) { + uint8_t bytes[3]; + Disassembled6502 decoded; + uint8_t length; + + bytes[0] = monitor_transfer_read_code(backend, start, end, dest, address); + bytes[1] = monitor_transfer_read_code(backend, start, end, dest, (uint16_t)(address + 1)); + bytes[2] = monitor_transfer_read_code(backend, start, end, dest, (uint16_t)(address + 2)); + disassemble_6502(address, bytes, true, &decoded); + length = decoded.valid && decoded.length ? decoded.length : 1; + + if (decoded.valid && decoded.length == 3 && decoded.operand_bytes == 2 && + (uint16_t)(address + 2) < reloc_end) { + uint16_t operand = (uint16_t)(bytes[1] | ((uint16_t)bytes[2] << 8)); + if (monitor_transfer_source_contains(start, end, operand)) { + uint16_t relocated = (uint16_t)(dest + (uint16_t)(operand - start)); + uint16_t write_addr = monitor_transfer_mapped_address(start, end, dest, address); + backend->write((uint16_t)(write_addr + 1), (uint8_t)(relocated & 0xFF)); + backend->write((uint16_t)(write_addr + 2), (uint8_t)(relocated >> 8)); + } + } + address = (uint16_t)(address + length); + } +} + +int monitor_compare_memory(MemoryBackend *backend, uint16_t start, uint16_t end, uint16_t dest, char *out, int out_len) +{ + uint32_t length = (uint16_t)(end - start); + uint32_t index; + int count = 0; + int pos = 0; + + out[0] = 0; + for (index = 0; index < length; index++) { + if (backend->read((uint16_t)(start + index)) != backend->read((uint16_t)(dest + index))) { + pos = append_line_address(out, out_len, pos, (uint16_t)(start + index)); + count++; + } + } + if (!count) { + append_text(out, out_len, pos, "No differences\n"); + } + return count; +} + +int monitor_compare_collect(MemoryBackend *backend, uint16_t start, uint16_t end, uint16_t dest, uint16_t *out_addrs, int max_addrs) +{ + uint32_t length = (uint16_t)(end - start); + uint32_t index; + int count = 0; + + if (max_addrs <= 0) return 0; + for (index = 0; index < length; index++) { + if (backend->read((uint16_t)(start + index)) != backend->read((uint16_t)(dest + index))) { + if (count < max_addrs) { + out_addrs[count] = (uint16_t)(start + index); + } + count++; + } + } + return count; +} + +int monitor_hunt_collect(MemoryBackend *backend, uint16_t start, uint16_t end, const uint8_t *needle, int needle_len, uint16_t *out_addrs, int max_addrs) +{ + uint32_t limit; + uint32_t index; + int count = 0; + + if (max_addrs <= 0) { + return 0; + } + limit = (uint16_t)(end - start) + 1; + if ((uint32_t)needle_len > limit) { + return 0; + } + for (index = 0; index + (uint32_t)needle_len <= limit; index++) { + int matched = 1; + int i; + for (i = 0; i < needle_len; i++) { + if (backend->read((uint16_t)(start + index + i)) != needle[i]) { + matched = 0; + break; + } + } + if (matched) { + if (count < max_addrs) { + out_addrs[count] = (uint16_t)(start + index); + } + count++; + } + } + return count; +} + +int monitor_hunt_memory(MemoryBackend *backend, uint16_t start, uint16_t end, const uint8_t *needle, int needle_len, char *out, int out_len) +{ + uint32_t limit; + uint32_t index; + int count = 0; + int pos = 0; + + out[0] = 0; + limit = (uint16_t)(end - start) + 1; + if ((uint32_t)needle_len > limit) { + append_text(out, out_len, pos, "No matches\n"); + return 0; + } + for (index = 0; index + (uint32_t)needle_len <= limit; index++) { + int matched = 1; + int i; + for (i = 0; i < needle_len; i++) { + if (backend->read((uint16_t)(start + index + i)) != needle[i]) { + matched = 0; + break; + } + } + if (matched) { + pos = append_line_address(out, out_len, pos, (uint16_t)(start + index)); + count++; + } + } + if (!count) { + append_text(out, out_len, pos, "No matches\n"); + } + return count; +} + +MonitorError monitor_format_evaluate(const char *input, char *out, int out_len) +{ + uint16_t value = 0; + MonitorError error = monitor_parse_expression(input, &value); + if (error != MONITOR_OK) { + return error; + } + (void)out_len; + sprintf(out, "$%04x / %u / %B", value, value, value & 0xFF); + return MONITOR_OK; +} + +namespace { + +static const int c_monitor_confirmation_line_max = 38; + +static bool keyword_match(const char *&cursor, const char *keyword) +{ + int i; + for (i = 0; keyword[i]; i++) { + if (to_upper_char(cursor[i]) != keyword[i]) { + return false; + } + } + char follow = cursor[i]; + if (follow != 0 && follow != ' ' && follow != '\t' && follow != ',') { + return false; + } + cursor += i; + return true; +} + +// Parse 1..max_digits hex digits (no $ allowed; AUTO/PRG already filtered). +// Used internally for the length field which can hold up to 5 digits (0x10000). +static MonitorError parse_hex_unbounded(const char *&cursor, int max_digits, uint32_t max_value, uint32_t *value) +{ + uint32_t parsed = 0; + int digits = 0; + skip_spaces(cursor); + if (*cursor == '$') { + cursor++; + } + while (is_hex_char(*cursor) && digits < max_digits) { + char c = to_upper_char(*cursor++); + parsed <<= 4; + if (c >= '0' && c <= '9') { + parsed |= (uint32_t)(c - '0'); + } else { + parsed |= (uint32_t)(c - 'A' + 10); + } + digits++; + } + if (digits == 0) { + return MONITOR_VALUE; + } + if (parsed > max_value) { + return MONITOR_VALUE; + } + *value = parsed; + return MONITOR_OK; +} + +static void format_confirmation_name_line(char *out, const char *op, const char *name) +{ + int prefix_len = strlen(op) + 1; + int available = c_monitor_confirmation_line_max - prefix_len; + const char *source = name ? name : ""; + int name_len = strlen(source); + char trimmed[40]; + + if (available < 0) { + available = 0; + } + if (name_len <= available) { + strcpy(trimmed, source); + } else if (available > 3) { + strncpy(trimmed, source, available - 3); + trimmed[available - 3] = 0; + strcat(trimmed, "..."); + } else if (available > 0) { + strncpy(trimmed, source, available); + trimmed[available] = 0; + } else { + trimmed[0] = 0; + } + sprintf(out, "%s %s", op, trimmed); +} + +} + +// Parse the "[start],[offset],[length]" prompt that follows a LOAD file pick. +// All fields are optional, individually and as trailing omissions: +// "" -> PRG, 0000, AUTO (typical RETURN-only path) +// "PRG" -> PRG, 0000, AUTO +// "0801" -> 0801, 0000, AUTO +// "PRG,1000" -> PRG, 1000, AUTO +// "0801,0002,0010" -> 0801, 0002, length=0x10 +// ",,0010" -> PRG, 0000, length=0x10 +// Whitespace around fields is ignored. Empty fields take their default. +MonitorError monitor_parse_load_params(const char *text, bool *use_prg_addr, uint16_t *start_addr, + uint16_t *offset, bool *length_auto, uint32_t *length) +{ + *use_prg_addr = true; + *start_addr = 0; + *offset = 0; + *length_auto = true; + *length = 0; + + const char *cursor = text; + skip_spaces(cursor); + + // Field 1 — start address or PRG. + if (!*cursor) return MONITOR_OK; + if (*cursor != ',') { + if (keyword_match(cursor, "PRG")) { + *use_prg_addr = true; + *start_addr = 0; + } else { + *use_prg_addr = false; + MonitorError error = parse_hex_digits(cursor, 1, 4, 0xFFFF, start_addr); + if (error != MONITOR_OK) return MONITOR_ADDR; + } + skip_spaces(cursor); + } + if (!*cursor) return MONITOR_OK; + if (*cursor != ',') return MONITOR_SYNTAX; + cursor++; + skip_spaces(cursor); + + // Field 2 — offset (hex 0..FFFF), optional. + if (*cursor && *cursor != ',') { + MonitorError error = parse_hex_digits(cursor, 1, 4, 0xFFFF, offset); + if (error != MONITOR_OK) return MONITOR_ADDR; + skip_spaces(cursor); + } + if (!*cursor) return MONITOR_OK; + if (*cursor != ',') return MONITOR_SYNTAX; + cursor++; + skip_spaces(cursor); + + // Field 3 — length (hex 1..10000) or AUTO, optional. + if (*cursor) { + if (keyword_match(cursor, "AUTO")) { + *length_auto = true; + *length = 0; + } else { + uint32_t parsed = 0; + MonitorError error = parse_hex_unbounded(cursor, 5, 0x10000, &parsed); + if (error != MONITOR_OK) return MONITOR_VALUE; + if (parsed == 0) return MONITOR_VALUE; + *length_auto = false; + *length = parsed; + } + skip_spaces(cursor); + } + if (*cursor) return MONITOR_SYNTAX; + return MONITOR_OK; +} + +MonitorError monitor_parse_save_params(const char *text, uint16_t *start, uint16_t *end) +{ + const char *cursor = text; + MonitorError error = parse_hex_digits(cursor, 1, 4, 0xFFFF, start); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + error = expect_separator(cursor, '-', MONITOR_SYNTAX); + if (error != MONITOR_OK) { + return error; + } + error = parse_hex_digits(cursor, 1, 4, 0xFFFF, end); + if (error != MONITOR_OK) { + return MONITOR_ADDR; + } + if (*end < *start) { + return MONITOR_RANGE; + } + skip_spaces(cursor); + if (*cursor) { + return MONITOR_SYNTAX; + } + return MONITOR_OK; +} + +MonitorError monitor_validate_load_size(uint32_t file_size, uint32_t offset, bool length_auto, + uint32_t length, uint32_t *effective_len) +{ + if (offset > file_size) { + return MONITOR_RANGE; + } + if (offset == file_size) { + return MONITOR_RANGE; + } + uint32_t avail = file_size - offset; + uint32_t use; + if (length_auto) { + use = avail; + } else { + // Reject if the requested length exceeds what the file can supply: the + // user explicitly asked for that many bytes and silently truncating + // would mask the mistake. + if (length > avail) { + return MONITOR_RANGE; + } + use = length; + } + if (use == 0) { + return MONITOR_RANGE; + } + if (use > 65536) { + return MONITOR_RANGE; + } + *effective_len = use; + return MONITOR_OK; +} + +MachineMonitor :: MachineMonitor(UserInterface *ui, MemoryBackend *mem_backend) : UIObject(ui) +{ + backend = mem_backend; + restore_debug_after_reset = false; + if (monitor_reset_reopen_state_valid) { + state = monitor_reset_reopen_state; + restore_debug_after_reset = monitor_reset_reopen_debug_active; + monitor_saved_state = state; + monitor_saved_state_valid = true; + monitor_reset_reopen_state_valid = false; + } else if (monitor_saved_state_valid) { + state = monitor_saved_state; + } else { + state.view = MONITOR_VIEW_HEX; + state.current_addr = 0x0801; + state.base_addr = 0x0801; + state.disasm_offset = 0; + state.illegal_enabled = false; + state.screen_charset = MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS; + state.view_cpu_port = 0x07; + } + state.screen_charset = normalize_screen_charset(state.screen_charset); + last_load_use_prg = monitor_last_load_use_prg; + last_load_start = monitor_last_load_start; + last_load_offset = monitor_last_load_offset; + last_load_length_auto = monitor_last_load_length_auto; + last_load_length = monitor_last_load_length; + last_save_start = monitor_last_save_start; + last_save_end = monitor_last_save_end; + strncpy(last_save_name, monitor_last_save_name, sizeof(last_save_name) - 1); + last_save_name[sizeof(last_save_name) - 1] = 0; + last_go_valid = monitor_last_go_valid; + last_go_addr = monitor_last_go_addr; + go_pending = false; + go_pending_addr = 0; + go_pending_has_context = false; + debug_context_reset(&go_pending_context); + memory_bytes_per_row = monitor_memory_bytes_per_row; + binary_bytes_per_row = monitor_binary_bytes_per_row; + clipboard.data = NULL; + clipboard.length = 0; + screen = NULL; + keyboard = NULL; + window = NULL; + content_height = 0; + pending_hex_nibble = -1; + edit_mode = false; + poll_mode = false; + poll_deadline = 0; + poll_fraction = 0; + edit_cursor_visible = true; + help_visible = false; + range_mode = false; + range_anchor = state.current_addr; + number_picker_active = false; + number_selected = 0; + number_preview_value = 0; + number_base_bytes[0] = 0; + number_base_bytes[1] = 0; + number_word = false; + number_edit_length = 0; + number_edit_buffer[0] = 0; + number_expr_active = false; + number_expr_word = false; + number_expr_length = 0; + number_expr_buffer[0] = 0; + number_expr_status[0] = 0; + number_popup_x = 0; + number_popup_y = 1; + number_target_addr = 0; + number_target_bytes = 1; + number_target_locked = false; + hunt_picker_active = false; + hunt_count = 0; + hunt_selected = 0; + hunt_top = 0; + hunt_picker_label = "Hunt results"; + asm_edit_part = 0; + asm_edit_pending = 0; + asm_lane_valid = false; + asm_lane_view_cpu_port = 0; + asm_lane_illegal_enabled = false; + asm_lane_count = 0; + asm_lane_top = 0; + asm_lane_selected = 0; + memset((void *)asm_lane_lengths, 0, sizeof(asm_lane_lengths)); + memset((void *)asm_lane_forced_bytes, 0, sizeof(asm_lane_forced_bytes)); + asm_edit_hist_len = 0; + asm_edit_hist_anchor_addr = 0; + opcode_picker_active = false; + opcode_prefix[0] = 0; + opcode_prefix_len = 0; + opcode_candidate_count = 0; + opcode_selected = 0; + opcode_top = 0; + opcode_drawn_rows = 0; + opcode_operand[0] = 0; + opcode_operand_len = 0; + current_vic_bank = 0; + last_live_vic_bank = 0; + vic_bank_override = false; + bookmarks = new MonitorBookmarks(); + debug_session = NULL; + debug_cursor_override = false; + debug_entry_context_valid = false; + debug_context_reset(&debug_entry_context); + debug_entry_addr = state.current_addr; + debug_run_window_refreeze_enabled = false; + reset_exits_monitor = false; + reset_exit_pending = false; + release_host_after_exit = false; + reopen_after_reset = false; + reopen_on_debug_reset = true; + deferred_debug_go_pending = false; + debug_context_reset(&deferred_debug_go_context); + // Restore breakpoints from process-lifetime storage so they survive a + // C=+X reset reentry and an ordinary monitor close/reopen. Power-off + // clears `monitor_saved_breakpoints` because it lives in volatile RAM. + breakpoints = monitor_saved_breakpoints; + breakpoint_popup_active = false; + breakpoint_selected = 0; + bookmark_popup_active = false; + bookmark_selected = 0; + bookmark_status_text[0] = 0; + bookmark_status_visible = false; + bookmark_status_emphasis = false; + bookmark_status_deadline = 0; + return_stack_count = 0; + binary_bit_index = 7; +#ifdef RUNS_ON_PC + edit_blink_polls = monitor_cursor_blink_idle_polls; +#else + edit_blink_ms = 0; +#endif +} + +void MachineMonitor :: set_debug_run_window_refreeze_enabled(bool enabled) +{ + debug_run_window_refreeze_enabled = enabled; + if (debug_session) { + debug_session->set_run_window_refreeze_enabled(enabled); + } +} + +void MachineMonitor :: set_reset_exits_monitor(bool enabled) +{ + reset_exits_monitor = enabled; +} + +bool MachineMonitor :: consume_release_host_after_exit(void) +{ + bool ret = release_host_after_exit; + release_host_after_exit = false; + return ret; +} + +void MachineMonitor :: request_reopen_after_reset(void) +{ + monitor_reset_reopen_state = monitor_reset_reentry_state(state); + monitor_reset_reopen_state_valid = true; + monitor_reset_reopen_debug_active = debug.is_active(); + reopen_after_reset = true; + reopen_on_debug_reset = true; + if (debug_session) { + debug_session->request_reset_cancel(); + } +} + +void MachineMonitor :: request_debug_reset_cancel(void) +{ + // Cancels any in-flight debug sentinel wait without scheduling a monitor + // reopen. Used by the REST reset path so the debug engine tears down its + // BRK patches and handler before the machine reset pulse fires, without + // treating the REST reset as a user-initiated "C=+X while in the monitor" + // event that would cause the monitor to reopen. + reopen_after_reset = false; + reopen_on_debug_reset = false; + monitor_reset_reopen_state_valid = false; + monitor_reset_reopen_debug_active = false; + if (debug_session) { + debug_session->request_reset_cancel(); + } +} + +bool MachineMonitor :: consume_reopen_after_reset(void) +{ + bool ret = reopen_after_reset; + reopen_after_reset = false; + return ret; +} + +uint8_t MachineMonitor :: memory_byte_stride(void) const +{ + return monitor_memory_byte_stride(memory_bytes_per_row); +} + +uint8_t MachineMonitor :: binary_byte_stride(void) const +{ + return monitor_binary_byte_stride(binary_bytes_per_row); +} + +int MachineMonitor :: memory_row_chars(void) const +{ + return (memory_byte_stride() == MONITOR_MEMORY_MAX_BYTES_PER_ROW) ? + MONITOR_MEMORY_ROW_16_CHARS : MONITOR_MEMORY_ROW_8_CHARS; +} + +int MachineMonitor :: memory_hex_column(int byte_offset) const +{ + if (memory_byte_stride() == MONITOR_MEMORY_MAX_BYTES_PER_ROW) { + return 5 + (byte_offset * 2) + ((byte_offset >= 8) ? 1 : 0); + } + return 5 + (byte_offset * 3); +} + +void MachineMonitor :: apply_go_local(uint16_t address) +{ + uint16_t span = row_span(); + state.current_addr = address; + debug_cursor_override = true; + if (state.view == MONITOR_VIEW_BINARY) { + if (span == 0) span = 1; + state.base_addr = (uint16_t)(address - (address % span)); + } else { + state.base_addr = (uint16_t)(address & (uint16_t)(~(span - 1))); + } + if (state.view == MONITOR_VIEW_DISASM) { + state.base_addr = address; + } + state.disasm_offset = 0; + if (state.view == MONITOR_VIEW_ASM) { + disasm_lane_reset(address); + } else { + disasm_lane_invalidate(); + } +} + +bool MachineMonitor :: number_shortcut_allowed(void) const +{ + if (!edit_mode) { + return true; + } + if (state.view == MONITOR_VIEW_ASM) { + if (opcode_picker_active) { + return false; + } + return asm_edit_part > 0; + } + return state.view != MONITOR_VIEW_ASCII && + state.view != MONITOR_VIEW_SCREEN; +} + +bool MachineMonitor :: range_shortcut_allowed(void) const +{ + if (!edit_mode) { + return true; + } + if (state.view == MONITOR_VIEW_HEX || state.view == MONITOR_VIEW_BINARY) { + return true; + } + if (state.view == MONITOR_VIEW_ASM) { + return asm_edit_part > 0; + } + return false; +} + +bool MachineMonitor :: bookmark_shortcut_allowed(void) const +{ + return !help_visible && + !hunt_picker_active && + !opcode_picker_active && + !number_picker_active && + !bookmark_popup_active; +} + +bool MachineMonitor :: bookmark_set_shortcut_allowed(void) const +{ + return !help_visible && + !hunt_picker_active && + !opcode_picker_active && + !number_picker_active && + !bookmark_popup_active; +} + +uint8_t MachineMonitor :: canonical_read(uint16_t address) +{ + return backend->read(address); +} + +void MachineMonitor :: canonical_write(uint16_t address, uint8_t value) +{ + backend->write(address, value); + monitor_log_byte("write", address, value); +} + +void MachineMonitor :: read_row(uint16_t address, uint8_t *dst, uint16_t len) const +{ + uint16_t first = len; + if ((uint32_t)address + len > 0x10000UL) { + first = (uint16_t)(0x10000UL - address); + } + backend->read_block(address, dst, first); + if (first < len) { + backend->read_block(0, dst + first, (uint16_t)(len - first)); + } +} + +Cursor MachineMonitor :: active_cursor(void) const +{ + Cursor cursor; + cursor.address = state.current_addr; + cursor.bit_index = (binary_bit_index <= 7) ? binary_bit_index : 7; + return cursor; +} + +bool MachineMonitor :: range_contains(uint16_t address) const +{ + if (!range_mode) { + return false; + } + uint16_t start = range_anchor; + uint16_t end = state.current_addr; + if (state.view == MONITOR_VIEW_ASM) { + uint16_t anchor_end = (uint16_t)(range_anchor + disasm_length(range_anchor) - 1); + uint16_t current_end = (uint16_t)(state.current_addr + disasm_length(state.current_addr) - 1); + if (state.current_addr < range_anchor) { + start = state.current_addr; + end = anchor_end; + } else { + start = range_anchor; + end = current_end; + } + } + if (end < start) { + uint16_t tmp = start; + start = end; + end = tmp; + } + return address >= start && address <= end; +} + +bool MachineMonitor :: clipboard_copy_bytes(const uint8_t *data, size_t length) +{ + uint8_t *copy; + + if (!data || length == 0) { + return false; + } + copy = (uint8_t *)malloc(length); + if (!copy) { + return false; + } + memcpy(copy, data, length); + if (clipboard.data) { + free(clipboard.data); + } + clipboard.data = copy; + clipboard.length = length; + return true; +} + +bool MachineMonitor :: clipboard_copy_byte(uint8_t value) +{ + return clipboard_copy_bytes(&value, 1); +} + +bool MachineMonitor :: clipboard_copy_current(void) +{ + return clipboard_copy_byte(canonical_read(state.current_addr)); +} + +bool MachineMonitor :: clipboard_copy_range(void) +{ + uint16_t start = range_anchor; + uint16_t end = state.current_addr; + if (state.view == MONITOR_VIEW_ASM) { + uint16_t anchor_end = (uint16_t)(range_anchor + disasm_length(range_anchor) - 1); + uint16_t current_end = (uint16_t)(state.current_addr + disasm_length(state.current_addr) - 1); + if (state.current_addr < range_anchor) { + start = state.current_addr; + end = anchor_end; + } else { + start = range_anchor; + end = current_end; + } + } + if (end < start) { + uint16_t tmp = start; + start = end; + end = tmp; + } + + uint32_t length = (uint32_t)end - (uint32_t)start + 1; + uint8_t *data = (uint8_t *)malloc((size_t)length); + if (!data) { + return false; + } + for (uint32_t i = 0; i < length; i++) { + data[i] = canonical_read((uint16_t)(start + i)); + } + if (clipboard.data) { + free(clipboard.data); + } + clipboard.data = data; + clipboard.length = (size_t)length; + return true; +} + +bool MachineMonitor :: clipboard_paste(void) +{ + uint16_t asm_top = state.base_addr; + + if (!clipboard.data || clipboard.length == 0) { + return false; + } + for (size_t i = 0; i < clipboard.length; i++) { + canonical_write((uint16_t)(state.current_addr + i), clipboard.data[i]); + } + state.current_addr = (uint16_t)(state.current_addr + clipboard.length); + binary_bit_index = 7; + if (state.view == MONITOR_VIEW_ASM) { + uint16_t addr = asm_top; + for (int row = 0; row < content_height; row++) { + if (addr == state.current_addr) { + state.disasm_offset = (uint8_t)row; + break; + } + addr = disasm_next_addr(addr); + } + ensure_disasm_visible(); + } else { + ensure_current_visible(); + } + pending_hex_nibble = -1; + if (edit_mode) { + reset_edit_blink(); + } + return true; +} + +void MachineMonitor :: toggle_range_mode(void) +{ + if (!range_mode) { + range_anchor = state.current_addr; + range_mode = true; + monitor_log_address("range-start", range_anchor); + return; + } + if (!clipboard_copy_range()) { + get_ui()->popup("?MEM", BUTTON_OK); + redraw_full(); + return; + } + range_mode = false; + monitor_log_range("range-copy", range_anchor, state.current_addr); +} + +void MachineMonitor :: open_number_picker(void) +{ + help_visible = false; + if (number_selected < 0 || number_selected >= MONITOR_NUMBER_ROW_COUNT) { + number_selected = MONITOR_NUMBER_ROW_HEX; + } + number_picker_resolve_target(); + number_picker_reset_edit_buffer(); + number_picker_close_expression(); + number_picker_refresh_preview_from_memory(); + number_picker_place_popup(); + number_picker_active = true; + monitor_log_address("number-picker open", number_picker_current_addr()); +} + +void MachineMonitor :: number_picker_resolve_target(void) +{ + number_target_addr = state.current_addr; + number_target_bytes = 1; + number_target_locked = false; + + if (state.view != MONITOR_VIEW_ASM) { + return; + } + + uint8_t row_bytes[3]; + Disassembled6502 decoded; + + read_row(state.current_addr, row_bytes, 3); + disassemble_6502(state.current_addr, row_bytes, state.illegal_enabled, &decoded); + monitor_disasm_tail_cutover(state.current_addr, &decoded); + if (!decoded.valid) { + return; + } + + if (decoded.operand_bytes == 0) { + number_target_addr = (uint16_t)(state.current_addr + decoded.length); + number_target_bytes = 1; + number_target_locked = true; + return; + } + + number_target_addr = (uint16_t)(state.current_addr + 1); + number_target_bytes = decoded.operand_bytes >= 2 ? 2 : 1; + number_target_locked = true; +} + +uint16_t MachineMonitor :: number_picker_current_addr(void) const +{ + return number_target_addr; +} + +uint8_t MachineMonitor :: number_picker_current_bytes(void) const +{ + if (number_target_locked) { + return number_target_bytes; + } + return number_word ? 2 : 1; +} + +void MachineMonitor :: number_picker_reset_edit_buffer(void) +{ + number_edit_length = 0; + number_edit_buffer[0] = 0; +} + +void MachineMonitor :: number_picker_refresh_preview_from_memory(void) +{ + uint16_t target_addr = number_picker_current_addr(); + + number_base_bytes[0] = canonical_read(target_addr); + number_base_bytes[1] = canonical_read((uint16_t)(target_addr + 1)); + if (number_edit_length <= 0) { + if (number_target_locked && number_target_bytes == 2) { + number_preview_value = (uint16_t)(((uint16_t)number_base_bytes[1] << 8) | number_base_bytes[0]); + number_word = true; + } else { + number_preview_value = number_base_bytes[0]; + number_word = false; + } + return; + } + if (number_picker_current_bytes() == 2) { + number_preview_value = (uint16_t)(((uint16_t)number_base_bytes[1] << 8) | number_base_bytes[0]); + } else { + number_preview_value = number_base_bytes[0]; + } +} + +void MachineMonitor :: number_picker_update_preview_from_buffer(void) +{ + uint16_t value; + bool word; + + if (number_edit_length <= 0) { + number_preview_value = number_base_bytes[0]; + number_word = false; + return; + } + if (!monitor_number_parse_buffer(number_selected, number_edit_buffer, number_edit_length, + &value, &word, state.screen_charset)) { + return; + } + if (number_target_locked) { + if (number_target_bytes == 1) { + value &= 0x00FF; + word = false; + } else { + word = true; + } + } + number_preview_value = value; + number_word = word; +} + +void MachineMonitor :: number_picker_set_row(int row) +{ + if (row < 0) { + row = 0; + } + if (row >= MONITOR_NUMBER_ROW_COUNT) { + row = MONITOR_NUMBER_ROW_COUNT - 1; + } + if (row == number_selected) { + return; + } + number_selected = row; + number_picker_reset_edit_buffer(); +} + +void MachineMonitor :: number_picker_anchor(int *x, int *y) const +{ + uint16_t span = row_span(); + uint16_t row_addr = state.current_addr; + int row = 0; + int col = 0; + + if (span == 0) { + span = 1; + } + + switch (state.view) { + case MONITOR_VIEW_ASCII: + case MONITOR_VIEW_SCREEN: + row_addr = (uint16_t)(state.base_addr + (((uint16_t)(state.current_addr - state.base_addr)) / MONITOR_TEXT_BYTES_PER_ROW) * MONITOR_TEXT_BYTES_PER_ROW); + row = (uint16_t)(state.current_addr - state.base_addr) / MONITOR_TEXT_BYTES_PER_ROW; + col = 5 + (int)(state.current_addr - row_addr); + break; + + case MONITOR_VIEW_BINARY: { + int stride = binary_byte_stride(); + if (stride < 1) { + stride = 1; + } + row_addr = (uint16_t)(state.base_addr + (((uint16_t)(state.current_addr - state.base_addr)) / stride) * stride); + row = (uint16_t)(state.current_addr - state.base_addr) / stride; + + // Calculate column with proper spacing + int byte_offset = (int)(state.current_addr - row_addr); + uint8_t bit = (binary_bit_index <= 7) ? binary_bit_index : 7; + int bit_pos = 7 - bit; + + if (monitor_binary_packed_bits(binary_bytes_per_row)) { + col = 5 + (byte_offset * 8) + bit_pos; + } else if (stride == 1) { + col = 5 + bit_pos; + } else if (stride == 2) { + col = 5 + (byte_offset * 9) + bit_pos; // 8 bits + 1 space + } else if (stride == 3) { + col = 5 + (byte_offset * 9) + bit_pos; // 8 bits + 1 space + } else { + col = 5; + } + break; + } + + case MONITOR_VIEW_ASM: { + uint16_t addr = state.base_addr; + for (row = 0; row < content_height; row++) { + uint8_t len = disasm_length(addr); + if (len == 0) { + len = 1; + } + if (monitor_disasm_row_contains(addr, len, state.current_addr)) { + break; + } + addr = (uint16_t)(addr + len); + } + if (row >= content_height) { + row = 0; + } + col = MONITOR_DISASM_TEXT_COL; + break; + } + + case MONITOR_VIEW_HEX: + default: + { + int stride = memory_byte_stride(); + row_addr = (uint16_t)(state.base_addr + (((uint16_t)(state.current_addr - state.base_addr)) / stride) * stride); + row = (uint16_t)(state.current_addr - state.base_addr) / stride; + col = memory_hex_column((int)(state.current_addr - row_addr)); + } + break; + } + + if (row < 0) { + row = 0; + } + if (row >= content_height) { + row = content_height - 1; + } + if (col < 0) { + col = 0; + } + if (col >= window->get_size_x()) { + col = window->get_size_x() - 1; + } + if (x) { + *x = col; + } + if (y) { + *y = row + 1; + } +} + +void MachineMonitor :: number_picker_place_popup(void) +{ + int anchor_x = 0; + int anchor_y = 1; + int max_x; + int max_y; + int best_x = 0; + int best_y = 1; + int best_distance = 0x7FFFFFFF; + + enum PopupCorner { + POPUP_CORNER_TOP_LEFT = 0, + POPUP_CORNER_TOP_RIGHT, + POPUP_CORNER_BOTTOM_LEFT, + POPUP_CORNER_BOTTOM_RIGHT, + }; + struct PopupPlacement { + int raw_x; + int raw_y; + PopupCorner corner; + }; + static const PopupPlacement placements[] = { + { 1, 1, POPUP_CORNER_TOP_LEFT }, + { -MONITOR_NUMBER_POPUP_WIDTH, 1, POPUP_CORNER_TOP_RIGHT }, + { 1, -MONITOR_NUMBER_POPUP_HEIGHT, POPUP_CORNER_BOTTOM_LEFT }, + { -MONITOR_NUMBER_POPUP_WIDTH, -MONITOR_NUMBER_POPUP_HEIGHT, POPUP_CORNER_BOTTOM_RIGHT }, + }; + + number_picker_anchor(&anchor_x, &anchor_y); + + max_x = window->get_size_x() - MONITOR_NUMBER_POPUP_WIDTH; + if (max_x < 0) { + max_x = 0; + } + max_y = content_height - MONITOR_NUMBER_POPUP_HEIGHT + 1; + if (max_y < 1) { + max_y = 1; + } + + for (size_t i = 0; i < (sizeof(placements) / sizeof(placements[0])); i++) { + int x = anchor_x + placements[i].raw_x; + int y = anchor_y + placements[i].raw_y; + if (x >= 0 && x <= max_x && y >= 1 && y <= max_y) { + number_popup_x = x; + number_popup_y = y; + return; + } + } + + for (size_t i = 0; i < (sizeof(placements) / sizeof(placements[0])); i++) { + int x = anchor_x + placements[i].raw_x; + int y = anchor_y + placements[i].raw_y; + int corner_x; + int corner_y; + int distance; + + if (x < 0) { + x = 0; + } else if (x > max_x) { + x = max_x; + } + if (y < 1) { + y = 1; + } else if (y > max_y) { + y = max_y; + } + + if (anchor_x >= x && anchor_x < (x + MONITOR_NUMBER_POPUP_WIDTH) && + anchor_y >= y && anchor_y < (y + MONITOR_NUMBER_POPUP_HEIGHT)) { + continue; + } + + switch (placements[i].corner) { + case POPUP_CORNER_TOP_LEFT: + corner_x = x; + corner_y = y; + break; + case POPUP_CORNER_TOP_RIGHT: + corner_x = x + MONITOR_NUMBER_POPUP_WIDTH - 1; + corner_y = y; + break; + case POPUP_CORNER_BOTTOM_LEFT: + corner_x = x; + corner_y = y + MONITOR_NUMBER_POPUP_HEIGHT - 1; + break; + case POPUP_CORNER_BOTTOM_RIGHT: + default: + corner_x = x + MONITOR_NUMBER_POPUP_WIDTH - 1; + corner_y = y + MONITOR_NUMBER_POPUP_HEIGHT - 1; + break; + } + + distance = abs(corner_x - anchor_x) + abs(corner_y - anchor_y); + if (distance < best_distance) { + best_distance = distance; + best_x = x; + best_y = y; + } + } + + number_popup_x = best_x; + number_popup_y = best_y; +} + +void MachineMonitor :: number_picker_commit(void) +{ + uint8_t low = (uint8_t)(number_preview_value & 0xFF); + uint8_t high = (uint8_t)((number_preview_value >> 8) & 0xFF); + uint16_t target_addr = number_picker_current_addr(); + + canonical_write(target_addr, low); + if (number_picker_current_bytes() == 2) { + canonical_write((uint16_t)(target_addr + 1), high); + } + monitor_log_value("number-picker commit", target_addr, number_preview_value); + number_picker_refresh_preview_from_memory(); +} + +bool MachineMonitor :: number_picker_copy_preview(void) +{ + uint8_t bytes[2]; + + bytes[0] = (uint8_t)(number_preview_value & 0xFF); + bytes[1] = (uint8_t)((number_preview_value >> 8) & 0xFF); + return clipboard_copy_bytes(bytes, number_picker_current_bytes()); +} + +void MachineMonitor :: number_picker_open_expression(void) +{ + number_picker_open_expression(0); +} + +void MachineMonitor :: number_picker_open_expression(char op) +{ + uint8_t bytes = number_picker_current_bytes(); + + number_expr_active = true; + number_expr_word = bytes == 2; + number_expr_status[0] = 0; + if (number_selected == MONITOR_NUMBER_ROW_DECIMAL) { + sprintf(number_expr_buffer, "%u", (unsigned)number_preview_value); + } else if (number_selected == MONITOR_NUMBER_ROW_BINARY) { + int bits = number_expr_word ? 16 : 8; + number_expr_buffer[0] = '%'; + for (int i = 0; i < bits && i + 1 < MONITOR_NUMBER_EXPR_BUFFER_MAX; i++) { + int bit = bits - 1 - i; + number_expr_buffer[i + 1] = (number_preview_value & (uint16_t)(1u << bit)) ? '1' : '0'; + } + number_expr_buffer[bits + 1] = 0; + } else if (number_expr_word) { + sprintf(number_expr_buffer, "$%04X", (unsigned)number_preview_value); + } else { + sprintf(number_expr_buffer, "$%02X", (unsigned)(number_preview_value & 0xFF)); + } + number_expr_length = (int)strlen(number_expr_buffer); + if (op && number_expr_length < MONITOR_NUMBER_EXPR_BUFFER_MAX) { + number_expr_buffer[number_expr_length++] = op; + number_expr_buffer[number_expr_length] = 0; + } +} + +void MachineMonitor :: number_picker_close_expression(void) +{ + number_expr_active = false; + number_expr_word = false; + number_expr_length = 0; + number_expr_buffer[0] = 0; + number_expr_status[0] = 0; +} + +void MachineMonitor :: number_picker_expression_set_status(const char *status) +{ + strncpy(number_expr_status, status ? status : "", sizeof(number_expr_status) - 1); + number_expr_status[sizeof(number_expr_status) - 1] = 0; +} + +MonitorError MachineMonitor :: number_picker_evaluate_expression(uint16_t *value) const +{ + uint16_t max_value = number_expr_word ? 0xFFFF : 0x00FF; + + if (!value) { + return MONITOR_SYNTAX; + } + return monitor_number_expr_evaluate(number_expr_buffer, max_value, value); +} + +int MachineMonitor :: number_picker_handle_key(int key) +{ + if (number_expr_active) { + if (key == KEY_ESCAPE || key == KEY_BREAK) { + number_picker_close_expression(); + refresh_popup_overlay(); + return 0; + } + if (key == KEY_RETURN || key == '=') { + uint16_t value; + MonitorError error = number_picker_evaluate_expression(&value); + if (error == MONITOR_OK) { + number_preview_value = value; + number_word = number_expr_word; + number_picker_close_expression(); + } else { + number_picker_expression_set_status(error == MONITOR_VALUE ? "DIV/0" : + error == MONITOR_RANGE ? "RANGE" : "SYNTAX"); + } + refresh_popup_overlay(); + return 0; + } + if (key == KEY_BACK || key == KEY_DELETE) { + if (number_expr_length > 0) { + number_expr_length--; + number_expr_buffer[number_expr_length] = 0; + number_expr_status[0] = 0; + } + refresh_popup_overlay(); + return 0; + } + if (key >= 32 && key < 127 && number_expr_length < MONITOR_NUMBER_EXPR_BUFFER_MAX) { + char typed = (char)key; + if (typed >= 'a' && typed <= 'f') { + typed = (char)(typed - ('a' - 'A')); + } + if (is_decimal_char(typed) || is_hex_char(typed) || typed == '$' || + typed == '%' || + monitor_number_expr_operator(typed)) { + number_expr_buffer[number_expr_length++] = typed; + number_expr_buffer[number_expr_length] = 0; + number_expr_status[0] = 0; + refresh_popup_overlay(); + } + return 0; + } + return 0; + } + + if (key == KEY_ESCAPE || key == KEY_BREAK) { + number_picker_active = false; + draw(); + return 0; + } + if (key == KEY_CTRL_O) { + number_picker_active = false; + return 1; + } + if (key == KEY_UP) { + number_picker_set_row(number_selected - 1); + refresh_popup_overlay(); + return 0; + } + if (key == KEY_DOWN) { + number_picker_set_row(number_selected + 1); + refresh_popup_overlay(); + return 0; + } + if (key == KEY_CTRL_C) { + if (!number_picker_copy_preview()) { + get_ui()->popup("?MEM", BUTTON_OK); + redraw_full(); + return 0; + } + number_picker_active = false; + draw(); + return 0; + } + if (key == KEY_RETURN) { + number_picker_commit(); + draw(); + return 0; + } + if (key == '+' || key == '-' || key == '*' || key == '/') { + number_picker_open_expression((char)key); + refresh_popup_overlay(); + return 0; + } + if (key == KEY_BACK || key == KEY_DELETE) { + if (number_edit_length > 0) { + number_edit_length--; + number_edit_buffer[number_edit_length] = 0; + number_picker_update_preview_from_buffer(); + refresh_popup_overlay(); + } + return 0; + } + + char typed = (char)key; + char candidate[sizeof(number_edit_buffer)]; + uint16_t value; + bool word; + + if (number_edit_length >= monitor_number_row_max_input[number_selected]) { + return 0; + } + + memcpy(candidate, number_edit_buffer, (size_t)number_edit_length); + candidate[number_edit_length] = typed; + candidate[number_edit_length + 1] = 0; + if (!monitor_number_parse_buffer(number_selected, candidate, number_edit_length + 1, + &value, &word, state.screen_charset)) { + return 0; + } + if (number_target_locked && number_target_bytes == 1 && word) { + return 0; + } + + number_edit_buffer[number_edit_length++] = typed; + number_edit_buffer[number_edit_length] = 0; + number_picker_update_preview_from_buffer(); + refresh_popup_overlay(); + return 0; +} + +void MachineMonitor :: ensure_current_visible() +{ + if (state.view == MONITOR_VIEW_DISASM) { + return; + } + + uint16_t span = row_span(); + if (span == 0) span = 1; + uint16_t page_bytes = (uint16_t)(content_height * span); + uint16_t current_row; + if (state.view == MONITOR_VIEW_BINARY) { + current_row = (uint16_t)(state.current_addr - (state.current_addr % span)); + state.base_addr = (uint16_t)(state.base_addr - (state.base_addr % span)); + } else { + current_row = (uint16_t)(state.current_addr & (uint16_t)(~(span - 1))); + state.base_addr = (uint16_t)(state.base_addr & (uint16_t)(~(span - 1))); + } + + if (current_row < state.base_addr) { + state.base_addr = current_row; + return; + } + + if ((uint16_t)(current_row - state.base_addr) >= page_bytes) { + state.base_addr = (uint16_t)(current_row - (page_bytes - span)); + } +} + +void MachineMonitor :: set_view(MachineMonitorView view) +{ + state.view = view; + printf("MCM view %s\n", monitor_view_name(view)); + if (view == MONITOR_VIEW_ASM) { + if (debug.is_active() && debug.has_context()) { + debug_sync_cursor_to_context(); + } else { + disasm_lane_reset(state.current_addr); + } + } else { + ensure_current_visible(); + } + pending_hex_nibble = -1; + binary_bit_index = 7; +} + +bool MachineMonitor :: inline_edit_supported(void) const +{ + return inline_edit_view(state.view); +} + +uint16_t MachineMonitor :: row_span(void) const +{ + return row_span_for_view(state.view, memory_bytes_per_row, binary_bytes_per_row); +} + +void MachineMonitor :: move_current(int delta) +{ + commit_pending_hex_nibble(); + state.current_addr = (uint16_t)(state.current_addr + delta); + if (state.view == MONITOR_VIEW_ASM) { + disasm_lane_reset(state.current_addr); + } else { + ensure_current_visible(); + } + pending_hex_nibble = -1; + if (state.view != MONITOR_VIEW_BINARY) { + binary_bit_index = 7; + } + if (edit_mode) { + reset_edit_blink(); + } +} + +void MachineMonitor :: move_binary_bits(int delta) +{ + if (binary_bit_index > 7) { + binary_bit_index = 7; + } + while (delta > 0) { + if (binary_bit_index > 0) { + binary_bit_index--; + } else { + state.current_addr = (uint16_t)(state.current_addr + 1); + binary_bit_index = 7; + } + delta--; + } + while (delta < 0) { + if (binary_bit_index < 7) { + binary_bit_index++; + } else { + state.current_addr = (uint16_t)(state.current_addr - 1); + binary_bit_index = 0; + } + delta++; + } + ensure_current_visible(); + pending_hex_nibble = -1; + if (edit_mode) { + reset_edit_blink(); + } +} + +void MachineMonitor :: page_move(int lines) +{ + commit_pending_hex_nibble(); + uint16_t span = row_span(); + if (span == 0) span = 1; + uint16_t step = (uint16_t)(lines * span); + + state.current_addr = (uint16_t)(state.current_addr + step); + if (state.view == MONITOR_VIEW_ASM) { + ensure_disasm_visible(); + } else { + state.base_addr = (uint16_t)(state.base_addr + step); + if (state.view == MONITOR_VIEW_BINARY) { + state.base_addr = (uint16_t)(state.base_addr - (state.base_addr % span)); + } else { + state.base_addr = (uint16_t)(state.base_addr & (uint16_t)(~(span - 1))); + } + ensure_current_visible(); + } + pending_hex_nibble = -1; + if (edit_mode) { + reset_edit_blink(); + } +} + +bool MachineMonitor :: prompt_command(const char *title, char *buffer, int max_len, + bool template_mode, bool uppercase) +{ + return get_ui()->string_box(title, buffer, max_len, template_mode, uppercase) > 0; +} + +bool MachineMonitor :: prompt_hunt_command(const char *title, char *buffer, int max_len) +{ + UserInterface *ui = get_ui(); + Screen *screen = ui ? ui->get_screen() : NULL; + Keyboard *keyboard = ui ? ui->get_keyboard() : NULL; + Window *window = NULL; + int message_width = strlen(title); + int window_width = message_width; + int max_chars; + int x1; + int y1; + int x_m; + int len; + int cur; + int edit_offs = 0; + int key; + int i; + bool confirmed = false; + bool done = false; + + if (!ui || !screen || !keyboard) { + return false; + } + if (max_len > message_width) { + window_width = max_len; + } + window_width += 3; + if (window_width >= screen->get_size_x()) { + window_width = screen->get_size_x(); + } + max_chars = window_width - 2; + x1 = (screen->get_size_x() - window_width) / 2; + y1 = (screen->get_size_y() - 5) / 2; + x_m = (window_width - message_width) / 2; + + cur = strlen(buffer); + if (cur > max_len) { + buffer[max_len] = 0; + cur = max_len; + } + len = cur; + if (len > (max_chars - 1)) { + edit_offs = 1 + len - max_chars; + } + + screen->backup(); + window = new Window(screen, x1, y1, window_width, 5); + window->clear(); + window->draw_border(); + window->move_cursor(x_m, 0); + window->output(title); + window->move_cursor(0, 2); + window->output_length(buffer + edit_offs, (len < max_chars) ? len : max_chars); + window->move_cursor(cur - edit_offs, 2); + + keyboard->wait_free(); + screen->cursor_visible(1); + while (!done && (!ui->host || ui->host->exists())) { + key = keyboard->getch(); + if (key == -1) { + continue; + } + if (key == -2) { + done = true; + continue; + } + + switch (key) { + case KEY_RETURN: + buffer[len] = 0; + confirmed = true; + done = true; + break; + case KEY_LEFT: + if (cur > 0) { + cur--; + if (cur - 5 < edit_offs) { + edit_offs -= 5; + if (edit_offs < 0) { + edit_offs = 0; + } + window->move_cursor(0, 2); + window->output_length(buffer + edit_offs, max_chars); + } + window->move_cursor(cur - edit_offs, 2); + } + break; + case KEY_RIGHT: + if (cur < len) { + cur++; + if ((cur - edit_offs) > (max_chars - 1)) { + edit_offs++; + window->move_cursor(0, 2); + window->output_length(buffer + edit_offs, max_chars); + } + window->move_cursor(cur - edit_offs, 2); + } + break; + case KEY_BACK: + if (cur > 0) { + cur--; + len--; + for (i = cur; i < len; i++) { + buffer[i] = buffer[i + 1]; + } + buffer[i] = 0; + if (cur - 5 < edit_offs) { + edit_offs -= 5; + if (edit_offs < 0) { + edit_offs = 0; + } + window->move_cursor(0, 2); + window->output_length(buffer + edit_offs, max_chars); + window->move_cursor(cur - edit_offs, 2); + } else { + window->move_cursor(cur - edit_offs, 2); + window->output_length(buffer + cur, max_chars + edit_offs - cur); + window->move_cursor(cur - edit_offs, 2); + } + } + break; + case KEY_CLEAR: + buffer[0] = 0; + len = 0; + cur = 0; + edit_offs = 0; + window->move_cursor(0, 2); + window->output_length(buffer, max_chars); + window->move_cursor(0, 2); + break; + case KEY_DELETE: + if (cur < len) { + len--; + for (i = cur; i < len; i++) { + buffer[i] = buffer[i + 1]; + } + buffer[i] = 0; + window->move_cursor(cur - edit_offs, 2); + window->output_length(buffer + cur, max_chars + edit_offs - cur); + window->move_cursor(cur - edit_offs, 2); + } + break; + case KEY_HOME: + case KEY_UP: + cur = 0; + if (edit_offs) { + edit_offs = 0; + window->move_cursor(0, 2); + window->output_length(buffer, max_chars); + } + window->move_cursor(0, 2); + break; + case KEY_DOWN: + case KEY_END: + if (cur != len) { + cur = len; + if (cur >= (max_chars - 1)) { + edit_offs = 1 + cur - max_chars; + window->move_cursor(0, 2); + window->output_length(buffer + edit_offs, max_chars); + } + window->move_cursor(cur - edit_offs, 2); + } + break; + case KEY_BREAK: + case KEY_ESCAPE: + done = true; + break; + default: + if ((key < 32) || (key >= 127)) { + break; + } + key = monitor_hunt_prompt_transform_key(buffer, cur, key); + if (len < max_len) { + for (i = len; i >= cur; i--) { + buffer[i + 1] = buffer[i]; + } + buffer[cur] = (char)key; + cur++; + len++; + if (cur - edit_offs < max_chars) { + window->output_length(buffer + cur - 1, max_chars + edit_offs - cur); + window->move_cursor(cur - edit_offs, 2); + } else { + edit_offs++; + window->move_cursor(0, 2); + window->output_length(buffer + edit_offs, max_chars); + window->move_cursor(cur - edit_offs, 2); + } + } + break; + } + } + + screen->cursor_visible(0); + window->getScreen()->restore(); + delete window; + return confirmed; +} + +void MachineMonitor :: commit_pending_hex_nibble(void) +{ + if (!edit_mode || state.view != MONITOR_VIEW_HEX || pending_hex_nibble < 0) { + return; + } + canonical_write(state.current_addr, (uint8_t)pending_hex_nibble); + pending_hex_nibble = -1; +} + +void MachineMonitor :: toggle_help() +{ + help_visible = !help_visible; + monitor_log(help_visible ? "help on" : "help off"); +} + +void MachineMonitor :: dismiss_bookmark_status(void) +{ + bookmark_status_visible = false; +} + +bool MachineMonitor :: update_bookmark_status(void) +{ + if (!bookmark_status_visible) { + return false; + } + if (!monitor_deadline_reached(bookmark_status_deadline, getMsTimer())) { + return false; + } + bookmark_status_visible = false; + return true; +} + +void MachineMonitor :: show_bookmark_status(uint8_t slot, const MonitorBookmarkSlot *bookmark, int kind) +{ + MonitorBookmarkStatusKind status = (MonitorBookmarkStatusKind)kind; + + monitor_bookmark_format_status(bookmark_status_text, sizeof(bookmark_status_text), + slot, bookmark, status); + bookmark_status_visible = true; + bookmark_status_emphasis = monitor_bookmark_status_uses_emphasis(status, bookmark); + bookmark_status_deadline = (uint16_t)(getMsTimer() + 2000); +} + +void MachineMonitor :: show_navigation_status(uint8_t index, const char *kind, uint16_t address) +{ + sprintf(bookmark_status_text, "F%u %s $%04X", + (unsigned)index, kind ? kind : "", (unsigned)address); + bookmark_status_visible = true; + bookmark_status_emphasis = false; + bookmark_status_deadline = (uint16_t)(getMsTimer() + 2000); +} + +void MachineMonitor :: clear_bookmark_transient_state(void) +{ + pending_hex_nibble = -1; + help_visible = false; + range_mode = false; + bookmark_popup_active = false; + number_picker_active = false; + number_selected = 0; + number_word = false; + number_edit_length = 0; + number_edit_buffer[0] = 0; + number_picker_close_expression(); + number_target_locked = false; + opcode_picker_close(); + hunt_picker_close(); + asm_edit_part = 0; + asm_edit_pending = 0; + asm_edit_history_reset(state.current_addr); + binary_bit_index = 7; + edit_cursor_visible = true; + reset_edit_blink(); +} + +void MachineMonitor :: capture_bookmark(MonitorBookmarkSlot *bookmark) const +{ + Cursor cursor; + + if (!bookmark) { + return; + } + cursor = active_cursor(); + bookmark->address = cursor.address; + bookmark->view = (uint8_t)state.view; + bookmark->cpu_bank = (uint8_t)(state.view_cpu_port & 0x07); + bookmark->vic_bank = (uint8_t)(current_vic_bank & 0x03); + switch (state.view) { + case MONITOR_VIEW_HEX: + bookmark->view_width_mode = memory_byte_stride(); + break; + case MONITOR_VIEW_ASCII: + case MONITOR_VIEW_SCREEN: + bookmark->view_width_mode = MONITOR_BOOKMARK_WIDTH_TEXT; + break; + case MONITOR_VIEW_BINARY: + bookmark->view_width_mode = binary_bytes_per_row; + break; + case MONITOR_VIEW_ASM: + default: + bookmark->view_width_mode = MONITOR_BOOKMARK_WIDTH_NONE; + break; + } + bookmark->edit_mode = false; + bookmark->is_default = false; + bookmark->is_valid = true; + bookmark->label[0] = 0; +} + +bool MachineMonitor :: restore_location(const MonitorBookmarkSlot *bookmark) +{ + uint8_t requested_vic_bank; + + if (!bookmark || !monitor_bookmark_slot_is_valid(*bookmark)) { + return false; + } + + if (backend && backend->supports_cpu_banking()) { + state.view_cpu_port = (uint8_t)(bookmark->cpu_bank & 0x07); + backend->set_monitor_cpu_port(state.view_cpu_port); + } else if ((state.view_cpu_port & 0x07) != (bookmark->cpu_bank & 0x07)) { + return false; + } + + requested_vic_bank = (uint8_t)(bookmark->vic_bank & 0x03); + if (backend && backend->supports_vic_bank()) { + backend->set_live_vic_bank(requested_vic_bank); + last_live_vic_bank = backend->get_live_vic_bank(); + current_vic_bank = requested_vic_bank; + vic_bank_override = (last_live_vic_bank != current_vic_bank); + } else if ((current_vic_bank & 0x03) != requested_vic_bank) { + return false; + } + + clear_bookmark_transient_state(); + // Apply row widths before viewport calculation (set_view() and + // apply_go_local() both read row_span()). + if (bookmark->view == MONITOR_BOOKMARK_VIEW_HEX) { + memory_bytes_per_row = monitor_bookmark_normalize_width(bookmark->view, + bookmark->view_width_mode); + } else if (bookmark->view == MONITOR_BOOKMARK_VIEW_BINARY) { + binary_bytes_per_row = monitor_bookmark_normalize_width(bookmark->view, + bookmark->view_width_mode); + } + set_view((MachineMonitorView)bookmark->view); + apply_go_local(bookmark->address); + reset_edit_blink(); + asm_edit_history_reset(state.current_addr); + return true; +} + +bool MachineMonitor :: restore_return_location(const ReturnStackEntry *entry) +{ + if (!entry || !restore_location(&entry->location)) { + return false; + } + state.base_addr = entry->base_addr; + state.disasm_offset = entry->disasm_offset; + if (state.view == MONITOR_VIEW_ASM) { + ensure_disasm_visible(); + } else { + ensure_current_visible(); + } + return true; +} + +bool MachineMonitor :: restore_bookmark(uint8_t slot) +{ + const MonitorBookmarkSlot *bookmark = bookmarks ? bookmarks->get(slot) : NULL; + + if (!bookmark || !monitor_bookmark_slot_is_valid(*bookmark)) { + show_bookmark_status(slot, NULL, MONITOR_BOOKMARK_STATUS_EMPTY); + return false; + } + if (!restore_location(bookmark)) { + show_bookmark_status(slot, bookmark, MONITOR_BOOKMARK_STATUS_RESTORE_FAILED); + printf("MCM bookmark restore F%u failed\n", (unsigned)slot); + return false; + } + show_bookmark_status(slot, bookmark, MONITOR_BOOKMARK_STATUS_RESTORED); + printf("MCM bookmark restore F%u $%04X\n", (unsigned)slot, bookmark->address); + return true; +} + +uint8_t MachineMonitor :: return_stack_push_current(void) +{ + ReturnStackEntry entry; + uint8_t index; + + capture_bookmark(&entry.location); + entry.base_addr = state.base_addr; + entry.disasm_offset = state.disasm_offset; + if (return_stack_count >= MONITOR_RETURN_STACK_MAX) { + for (int i = 1; i < MONITOR_RETURN_STACK_MAX; i++) { + return_stack[i - 1] = return_stack[i]; + } + return_stack_count = MONITOR_RETURN_STACK_MAX - 1; + } + index = return_stack_count; + return_stack[return_stack_count++] = entry; + return index; +} + +bool MachineMonitor :: return_stack_pop(ReturnStackEntry *entry, uint8_t *index) +{ + if (!entry || !index || return_stack_count == 0) { + return false; + } + return_stack_count--; + *index = return_stack_count; + *entry = return_stack[return_stack_count]; + return true; +} + +bool MachineMonitor :: target_visible(uint16_t target) const +{ + int row = disasm_visible_row(target); + return row >= 0 && row < content_height; +} + +void MachineMonitor :: follow_to_target(uint16_t target) +{ + int row = disasm_visible_row(target); + + if (row >= 0 && row < content_height) { + state.disasm_offset = (uint8_t)row; + state.current_addr = target; + ensure_disasm_visible(); + asm_edit_history_reset(state.current_addr); + monitor_log_address("follow-visible", target); + return; + } + apply_go_local(target); +} + +bool MachineMonitor :: follow_target(uint16_t *target) +{ + if (!target || state.view != MONITOR_VIEW_ASM) { + return false; + } + { + uint16_t insn_addr = state.current_addr; + uint8_t bytes[3]; + Disassembled6502 decoded; + + read_row(insn_addr, bytes, 3); + disassemble_6502(insn_addr, bytes, state.illegal_enabled, &decoded); + monitor_disasm_tail_cutover(insn_addr, &decoded); + if (!decoded.valid) { + return false; + } + switch (bytes[0]) { + case 0x20: + case 0x4C: + if (decoded.length < 3) { + return false; + } + *target = (uint16_t)(bytes[1] | ((uint16_t)bytes[2] << 8)); + return true; + case 0x6C: + if (decoded.length < 3) { + return false; + } else { + uint16_t vector = (uint16_t)(bytes[1] | ((uint16_t)bytes[2] << 8)); + uint8_t low = canonical_read(vector); + uint8_t high = canonical_read((uint16_t)(vector + 1)); + *target = (uint16_t)(low | ((uint16_t)high << 8)); + return true; + } + case 0x10: case 0x30: case 0x50: case 0x70: + case 0x90: case 0xB0: case 0xD0: case 0xF0: + if (decoded.length < 2) { + return false; + } + *target = (uint16_t)(insn_addr + 2 + (int8_t)bytes[1]); + return true; + default: + break; + } + } + return false; +} + +bool MachineMonitor :: follow_current(void) +{ + uint16_t target; + uint8_t index; + + if (!follow_target(&target)) { + return false; + } + index = return_stack_push_current(); + follow_to_target(target); + show_navigation_status(index, "JMP", target); + monitor_log_address("follow", target); + return true; +} + +bool MachineMonitor :: return_current(void) +{ + ReturnStackEntry entry; + uint8_t index; + + if (!return_stack_pop(&entry, &index)) { + return false; + } + if (!restore_return_location(&entry)) { + return false; + } + show_navigation_status(index, "RET", entry.location.address); + monitor_log_address("return", entry.location.address); + return true; +} + +void MachineMonitor :: set_bookmark(uint8_t slot) +{ + MonitorBookmarkSlot bookmark; + bool saved; + + capture_bookmark(&bookmark); + saved = bookmarks ? bookmarks->set_target_preserve_label(slot, bookmark) : false; + if (saved) { + const MonitorBookmarkSlot *stored = bookmarks ? bookmarks->get(slot) : NULL; + show_bookmark_status(slot, stored ? stored : &bookmark, MONITOR_BOOKMARK_STATUS_SET); + printf("MCM bookmark set F%u $%04X\n", (unsigned)slot, bookmark.address); + } else { + show_bookmark_status(slot, &bookmark, MONITOR_BOOKMARK_STATUS_SAVE_FAILED); + printf("MCM bookmark set F%u failed\n", (unsigned)slot); + } +} + +void MachineMonitor :: edit_bookmark_label(uint8_t slot) +{ + char buffer[MONITOR_BOOKMARK_LABEL_STORAGE]; + char normalized[MONITOR_BOOKMARK_LABEL_STORAGE]; + const MonitorBookmarkSlot *current = bookmarks ? bookmarks->get(slot) : NULL; + bool confirmed; + + memset(buffer, 0, sizeof(buffer)); + if (current && current->is_valid && current->label[0]) { + size_t i = 0; + while (i < MONITOR_BOOKMARK_LABEL_MAX && current->label[i]) { + buffer[i] = current->label[i]; + i++; + } + buffer[i] = 0; + } + char title[16]; + sprintf(title, "Label BM%u", (unsigned)slot); + confirmed = prompt_command(title, buffer, MONITOR_BOOKMARK_LABEL_MAX); + if (confirmed) { + monitor_bookmark_normalize_label(normalized, sizeof(normalized), buffer); + bookmarks->set_label(slot, normalized); + const MonitorBookmarkSlot *updated = bookmarks->get(slot); + show_bookmark_status(slot, updated, MONITOR_BOOKMARK_STATUS_LABEL_SAVED); + printf("MCM bookmark label F%u\n", (unsigned)slot); + } else { + show_bookmark_status(slot, current, MONITOR_BOOKMARK_STATUS_LABEL_CANCEL); + printf("MCM bookmark label F%u cancelled\n", (unsigned)slot); + } + draw(); +} + +int MachineMonitor :: bookmark_popup_handle_key(int key) +{ + if (key == KEY_ESCAPE || key == KEY_BREAK || key == KEY_HELP || key == KEY_F3 || + key == '?' || monitor_key_is_bookmark_popup(key)) { + bookmark_popup_active = false; + monitor_log("bookmark popup close"); + redraw_full(); + return 0; + } + if (key == KEY_UP) { + bookmark_selected = (uint8_t)((bookmark_selected + MONITOR_BOOKMARK_SLOT_COUNT - 1) % + MONITOR_BOOKMARK_SLOT_COUNT); + refresh_popup_overlay(); + return 0; + } + if (key == KEY_DOWN) { + bookmark_selected = (uint8_t)((bookmark_selected + 1) % MONITOR_BOOKMARK_SLOT_COUNT); + refresh_popup_overlay(); + return 0; + } + if (key == KEY_RETURN) { + bookmark_popup_active = false; + restore_bookmark(bookmark_selected); + redraw_full(); + return 0; + } + if (key == 's' || key == 'S') { + set_bookmark(bookmark_selected); + refresh_popup_overlay(); + draw_status(); + if (screen) { + screen->sync(); + } + return 0; + } + if (key == 'l' || key == 'L') { + edit_bookmark_label(bookmark_selected); + return 0; + } + if (key == KEY_DELETE || key == KEY_BACK) { + if (bookmarks) { + bookmarks->reset_slot_to_default(bookmark_selected, + (uint8_t)(state.view_cpu_port & 0x07), + (uint8_t)(current_vic_bank & 0x03)); + const MonitorBookmarkSlot *reset = bookmarks->get(bookmark_selected); + show_bookmark_status(bookmark_selected, reset, MONITOR_BOOKMARK_STATUS_LABEL_RESET); + printf("MCM bookmark reset F%u\n", (unsigned)bookmark_selected); + } + refresh_popup_overlay(); + draw_status(); + if (screen) { + screen->sync(); + } + return 0; + } + if (monitor_bookmark_popup_slot_for_key(key) >= 0) { + bookmark_popup_active = false; + restore_bookmark((uint8_t)monitor_bookmark_popup_slot_for_key(key)); + redraw_full(); + return 0; + } + return 0; +} + +void MachineMonitor :: reset_edit_blink() +{ + edit_cursor_visible = true; +} + +bool MachineMonitor :: update_edit_blink() +{ + return false; +} + +uint16_t MachineMonitor :: next_poll_interval_ms(void) +{ + uint8_t hz = backend ? backend->monitor_poll_hz() : 50; + uint16_t interval; + uint16_t remainder; + + if (hz < 1) { + hz = 50; + } + interval = (uint16_t)(1000 / hz); + remainder = (uint16_t)(1000 % hz); + poll_fraction = (uint8_t)(poll_fraction + remainder); + if (poll_fraction >= hz) { + poll_fraction = (uint8_t)(poll_fraction - hz); + interval++; + } + if (interval < 1) { + interval = 1; + } + return interval; +} + +void MachineMonitor :: reset_poll_deadline(void) +{ + poll_fraction = 0; + poll_deadline = (uint16_t)(getMsTimer() + next_poll_interval_ms()); +} + +uint8_t MachineMonitor :: disasm_length(uint16_t address) const +{ + Disassembled6502 decoded; + uint8_t row_bytes[3]; + + read_row(address, row_bytes, 3); + disassemble_6502(address, row_bytes, state.illegal_enabled, &decoded); + monitor_disasm_tail_cutover(address, &decoded); + return decoded.length ? decoded.length : 1; +} + +void MachineMonitor :: disasm_lane_invalidate(void) +{ + asm_lane_valid = false; + asm_lane_count = 0; + asm_lane_top = 0; + asm_lane_selected = 0; +} + +void MachineMonitor :: disasm_lane_sync_state(void) +{ + if (!asm_lane_valid || asm_lane_count <= 0) { + return; + } + if (asm_lane_top < 0) asm_lane_top = 0; + if (asm_lane_top >= asm_lane_count) asm_lane_top = asm_lane_count - 1; + if (asm_lane_selected < 0) asm_lane_selected = 0; + if (asm_lane_selected >= asm_lane_count) asm_lane_selected = asm_lane_count - 1; + if (asm_lane_selected < asm_lane_top) asm_lane_top = asm_lane_selected; + if (content_height > 0 && asm_lane_selected >= asm_lane_top + content_height) { + asm_lane_top = asm_lane_selected - content_height + 1; + } + state.base_addr = asm_lane_rows[asm_lane_top]; + state.current_addr = asm_lane_rows[asm_lane_selected]; + state.disasm_offset = (uint8_t)(asm_lane_selected - asm_lane_top); +} + +void MachineMonitor :: disasm_lane_reset(uint16_t address) +{ + asm_lane_valid = true; + asm_lane_view_cpu_port = (uint8_t)(state.view_cpu_port & 0x07); + asm_lane_illegal_enabled = state.illegal_enabled; + asm_lane_rows[0] = address; + asm_lane_lengths[0] = 0; + asm_lane_forced_bytes[0] = 0; + asm_lane_count = 1; + asm_lane_top = 0; + asm_lane_selected = 0; + disasm_lane_sync_state(); +} + +uint8_t MachineMonitor :: disasm_lane_length_at(int index) const +{ + uint8_t len; + + if (index < 0 || index >= asm_lane_count) { + return 1; + } + len = asm_lane_lengths[index]; + if (!len) { + len = disasm_length(asm_lane_rows[index]); + } + return len ? len : 1; +} + +uint16_t MachineMonitor :: disasm_lane_next_addr_at(int index) const +{ + return (uint16_t)(asm_lane_rows[index] + disasm_lane_length_at(index)); +} + +void MachineMonitor :: disasm_lane_append(uint16_t address, uint8_t forced_length) const +{ + disasm_lane_ensure(); + if (asm_lane_count < ASM_LANE_MAX_ROWS) { + asm_lane_rows[asm_lane_count] = address; + asm_lane_lengths[asm_lane_count] = forced_length; + if (forced_length) { + read_row(address, &asm_lane_forced_bytes[asm_lane_count], 1); + } else { + asm_lane_forced_bytes[asm_lane_count] = 0; + } + asm_lane_count++; + return; + } + + for (int i = 0; i < ASM_LANE_MAX_ROWS - 1; i++) { + asm_lane_rows[i] = asm_lane_rows[i + 1]; + asm_lane_lengths[i] = asm_lane_lengths[i + 1]; + asm_lane_forced_bytes[i] = asm_lane_forced_bytes[i + 1]; + } + asm_lane_rows[ASM_LANE_MAX_ROWS - 1] = address; + asm_lane_lengths[ASM_LANE_MAX_ROWS - 1] = forced_length; + if (forced_length) { + read_row(address, &asm_lane_forced_bytes[ASM_LANE_MAX_ROWS - 1], 1); + } else { + asm_lane_forced_bytes[ASM_LANE_MAX_ROWS - 1] = 0; + } + if (asm_lane_top > 0) asm_lane_top--; + if (asm_lane_selected > 0) asm_lane_selected--; +} + +void MachineMonitor :: disasm_lane_extend_forward_to(int index) const +{ + if (index < 0) { + return; + } + if (index >= ASM_LANE_MAX_ROWS) { + index = ASM_LANE_MAX_ROWS - 1; + } + while (asm_lane_valid && asm_lane_count <= index && asm_lane_count < ASM_LANE_MAX_ROWS) { + disasm_lane_append(disasm_lane_next_addr_at(asm_lane_count - 1), 0); + } +} + +void MachineMonitor :: disasm_lane_ensure(void) const +{ + if (asm_lane_valid && + asm_lane_view_cpu_port == (uint8_t)(state.view_cpu_port & 0x07) && + asm_lane_illegal_enabled == state.illegal_enabled && + asm_lane_count > 0) { + return; + } + + asm_lane_valid = true; + asm_lane_view_cpu_port = (uint8_t)(state.view_cpu_port & 0x07); + asm_lane_illegal_enabled = state.illegal_enabled; + asm_lane_rows[0] = state.base_addr; + asm_lane_lengths[0] = 0; + asm_lane_forced_bytes[0] = 0; + asm_lane_count = 1; + asm_lane_top = 0; + asm_lane_selected = 0; + + int need = content_height; + if (need <= 0) need = 1; + if (state.disasm_offset + 1 > need) need = state.disasm_offset + 1; + if (need > ASM_LANE_MAX_ROWS) need = ASM_LANE_MAX_ROWS; + disasm_lane_extend_forward_to(need - 1); + for (int i = 0; i < asm_lane_count; i++) { + if (asm_lane_rows[i] == state.current_addr) { + asm_lane_selected = i; + return; + } + } + asm_lane_rows[0] = state.current_addr; + asm_lane_count = 1; + asm_lane_top = 0; + asm_lane_selected = 0; +} + +void MachineMonitor :: disasm_lane_prepend(uint16_t address, uint8_t forced_length) +{ + disasm_lane_ensure(); + if (asm_lane_count < ASM_LANE_MAX_ROWS) { + for (int i = asm_lane_count; i > 0; i--) { + asm_lane_rows[i] = asm_lane_rows[i - 1]; + asm_lane_lengths[i] = asm_lane_lengths[i - 1]; + asm_lane_forced_bytes[i] = asm_lane_forced_bytes[i - 1]; + } + asm_lane_count++; + } else { + for (int i = ASM_LANE_MAX_ROWS - 1; i > 0; i--) { + asm_lane_rows[i] = asm_lane_rows[i - 1]; + asm_lane_lengths[i] = asm_lane_lengths[i - 1]; + asm_lane_forced_bytes[i] = asm_lane_forced_bytes[i - 1]; + } + } + asm_lane_rows[0] = address; + asm_lane_lengths[0] = forced_length; + if (forced_length) { + read_row(address, &asm_lane_forced_bytes[0], 1); + } else { + asm_lane_forced_bytes[0] = 0; + } + if (asm_lane_top < ASM_LANE_MAX_ROWS - 1) asm_lane_top++; + if (asm_lane_selected < ASM_LANE_MAX_ROWS - 1) asm_lane_selected++; +} + +bool MachineMonitor :: disasm_lane_prepend_previous(void) +{ + uint16_t current; + uint16_t prev; + uint8_t forced_length = 0; + + disasm_lane_ensure(); + current = asm_lane_rows[0]; + if (!disasm_find_prev_addr(current, &prev)) { + if (current == 0x0000) { + return false; + } + prev = (uint16_t)(current - 1); + forced_length = 1; + } + disasm_lane_prepend(prev, forced_length); + return true; +} + +void MachineMonitor :: disasm_lane_rebuild_suffix_from_current(void) +{ + disasm_lane_ensure(); + for (int i = 0; i < asm_lane_count; i++) { + if (asm_lane_rows[i] == state.current_addr) { + asm_lane_selected = i; + asm_lane_count = i + 1; + if (asm_lane_top > asm_lane_selected) { + asm_lane_top = asm_lane_selected; + } + disasm_lane_sync_state(); + return; + } + } + disasm_lane_reset(state.current_addr); +} + +void MachineMonitor :: disasm_visible_addresses(uint16_t *rows, uint8_t *lengths, int count) const +{ + if (!rows || count <= 0) { + return; + } + + disasm_lane_ensure(); + disasm_lane_extend_forward_to(asm_lane_top + count - 1); + for (int row = 0; row < count; row++) { + int index = asm_lane_top + row; + if (index < asm_lane_count) { + rows[row] = asm_lane_rows[index]; + if (lengths) lengths[row] = asm_lane_lengths[index]; + } else { + uint16_t addr = asm_lane_rows[asm_lane_count - 1]; + for (int i = asm_lane_count - 1; i < index; i++) { + addr = disasm_lane_next_addr_at(i); + } + rows[row] = addr; + if (lengths) lengths[row] = 0; + } + } +} + +bool MachineMonitor :: disasm_same_source(uint16_t a, uint16_t b) const +{ + const char *sa = backend ? backend->source_name(a) : ""; + const char *sb = backend ? backend->source_name(b) : ""; + + return strcmp(sa ? sa : "", sb ? sb : "") == 0; +} + +bool MachineMonitor :: disasm_crosses_source_boundary(uint16_t start, uint16_t end) const +{ + uint16_t addr = start; + + while (addr != end) { + uint16_t next = (uint16_t)(addr + 1); + if (!disasm_same_source(addr, next)) { + return true; + } + addr = next; + } + return false; +} + +bool MachineMonitor :: disasm_is_io_source(uint16_t address) const +{ + const char *source = backend ? backend->source_name(address) : ""; + + return strcmp(source ? source : "", "IO") == 0; +} + +bool MachineMonitor :: disasm_explicitly_targets(uint16_t candidate, uint16_t address) const +{ + uint8_t bytes[3]; + + read_row(candidate, bytes, 3); + if (bytes[0] == 0x4C) { + uint16_t target = (uint16_t)(bytes[1] | ((uint16_t)bytes[2] << 8)); + return target == address; + } + switch (bytes[0]) { + case 0x10: case 0x30: case 0x50: case 0x70: + case 0x90: case 0xB0: case 0xD0: case 0xF0: + { + int8_t rel = (int8_t)bytes[1]; + uint16_t target = (uint16_t)(candidate + 2 + rel); + return target == address; + } + default: + break; + } + return false; +} + +uint16_t MachineMonitor :: disasm_next_addr(uint16_t address) const +{ + if (address == 0xFFFF) { + return 0x0000; + } + return (uint16_t)(address + disasm_length(address)); +} + +bool MachineMonitor :: asm_is_branch(uint16_t address) +{ + uint8_t op = canonical_read(address); + const char *templ = disassembler_6502_template(op); + if (!templ) return false; + // Mirror the disassembler's own rule (disassembler_6502.cc): any B* + // mnemonic other than BRK is a relative branch. Some templates spell + // out "rel" explicitly while others (BCC/BCS/BNE/BEQ) do not, so we + // test the leading mnemonic rather than relying on "rel" being present. + if (templ[0] == 'B' && templ[1] != 'R') return true; + return strstr(templ, "rel") != NULL; +} + +// Number of editable parts presented in the ASM edit cursor for the +// instruction at `address`. Branch instructions are encoded as opcode + +// 1-byte signed offset but are *displayed* as opcode + absolute 16-bit +// target, so we expose three editable parts (mnemonic, target high, target +// low) for branches and let the byte-edit path translate the typed target +// back into a relative offset. +uint8_t MachineMonitor :: asm_edit_part_count(uint16_t address) +{ + uint8_t len = disasm_length(address); + if (len == 0) len = 1; + if (asm_is_branch(address) && len == 2) return 3; + return len; +} + +bool MachineMonitor :: disasm_find_prev_addr(uint16_t address, uint16_t *previous) const +{ + uint16_t best = 0; + int best_score = -1; + + if (address == 0x0000) { + if (previous) *previous = 0xFFFF; + return true; + } + // Use a signed counter: a uint16_t loop variable would underflow from 0 + // back to 0xFFFF when the heuristic fails to find a matching instruction + // length, hanging the monitor in an infinite read loop. + for (int back = 3; back >= 1; back--) { + uint16_t candidate = (uint16_t)(address - back); + if (disasm_length(candidate) == (uint16_t)back) { + bool crosses_source = disasm_crosses_source_boundary(candidate, + address); + int score = 0; + + if (crosses_source && + (disasm_is_io_source(candidate) || disasm_is_io_source(address)) && + !disasm_explicitly_targets(candidate, address)) { + continue; + } + if (disasm_same_source(candidate, address)) { + score += 8; + } + if (!crosses_source) { + score += 4; + } + if (!disasm_is_io_source(candidate)) { + score += 2; + } + if (score > best_score) { + best_score = score; + best = candidate; + } + } + } + if (best_score < 0) { + return false; + } + if (previous) *previous = best; + return true; +} + +uint16_t MachineMonitor :: disasm_prev_addr(uint16_t address) const +{ + uint16_t previous; + + if (disasm_find_prev_addr(address, &previous)) { + return previous; + } + return (uint16_t)(address - 1); +} + +uint16_t MachineMonitor :: disasm_prev_visible_addr(uint16_t address) +{ + uint16_t rows[32]; + int count = content_height; + + if (count > (int)(sizeof(rows) / sizeof(rows[0]))) { + count = (int)(sizeof(rows) / sizeof(rows[0])); + } + if (count > 0) { + disasm_visible_addresses(rows, NULL, count); + for (int row = 1; row < count; row++) { + if (rows[row] == address) { + return rows[row - 1]; + } + } + } + return disasm_prev_addr(address); +} + +int MachineMonitor :: disasm_visible_row(uint16_t address) const +{ + uint16_t rows[32]; + int count = content_height; + + if (count <= 0) { + return -1; + } + if (count > (int)(sizeof(rows) / sizeof(rows[0]))) { + count = (int)(sizeof(rows) / sizeof(rows[0])); + } + disasm_visible_addresses(rows, NULL, count); + + for (int row = 0; row < count; row++) { + if (rows[row] == address) { + return row; + } + } + return -1; +} + +uint16_t MachineMonitor :: disasm_advance_rows(uint16_t address, int rows) +{ + while (rows > 0) { + address = disasm_next_addr(address); + rows--; + } + return address; +} + +uint16_t MachineMonitor :: disasm_rewind_rows(uint16_t address, int rows) +{ + while (rows > 0) { + address = disasm_prev_addr(address); + rows--; + } + return address; +} + +void MachineMonitor :: restore_disasm_cursor_row(int row) +{ + if (row < 0) { + ensure_disasm_visible(); + return; + } + if (content_height > 0 && row >= content_height) { + row = content_height - 1; + } + disasm_position_current_at_row(row); + ensure_disasm_visible(); +} + +void MachineMonitor :: disasm_position_current_at_row(int row) +{ + if (content_height <= 0) { + disasm_lane_reset(state.current_addr); + return; + } + if (row < 0) { + row = 0; + } + if (row >= content_height) { + row = content_height - 1; + } + + disasm_lane_reset(state.current_addr); + for (int i = 0; i < row; i++) { + if (!disasm_lane_prepend_previous()) { + break; + } + asm_lane_selected = i + 1; + } + asm_lane_top = 0; + disasm_lane_sync_state(); +} + +void MachineMonitor :: ensure_disasm_visible() +{ + if (state.view != MONITOR_VIEW_ASM) { + return; + } + if (content_height <= 0) { + disasm_lane_reset(state.current_addr); + return; + } + disasm_lane_ensure(); + for (int i = 0; i < asm_lane_count; i++) { + if (asm_lane_rows[i] == state.current_addr) { + asm_lane_selected = i; + if (asm_lane_selected < asm_lane_top) { + asm_lane_top = asm_lane_selected; + } else if (asm_lane_selected >= asm_lane_top + content_height) { + asm_lane_top = asm_lane_selected - content_height + 1; + } + disasm_lane_sync_state(); + return; + } + } + disasm_lane_reset(state.current_addr); +} + +void MachineMonitor :: step_disassembly(int lines) +{ + disasm_lane_ensure(); + while (lines < 0) { + if (asm_lane_selected > 0) { + asm_lane_selected--; + if (asm_lane_selected < asm_lane_top) { + asm_lane_top = asm_lane_selected; + } + } else { + uint16_t current = asm_lane_rows[0]; + uint16_t prev; + bool have_prev = disasm_find_prev_addr(current, &prev); + if (have_prev && prev > current) { + state.current_addr = prev; + disasm_position_current_at_row((content_height > 0) ? (content_height - 1) : 0); + } else { + if (!disasm_lane_prepend_previous()) { + break; + } + asm_lane_selected = 0; + asm_lane_top = 0; + } + } + lines++; + } + while (lines > 0) { + uint16_t current = asm_lane_rows[asm_lane_selected]; + uint16_t next = disasm_lane_next_addr_at(asm_lane_selected); + if (next < current) { + disasm_lane_reset(next); + lines--; + continue; + } + if (asm_lane_selected + 1 >= asm_lane_count) { + disasm_lane_append(disasm_lane_next_addr_at(asm_lane_selected), 0); + } else { + disasm_lane_extend_forward_to(asm_lane_selected + 1); + } + if (asm_lane_selected + 1 < asm_lane_count) { + asm_lane_selected++; + } + if (content_height > 0 && asm_lane_selected >= asm_lane_top + content_height) { + asm_lane_top = asm_lane_selected - content_height + 1; + } + lines--; + } + disasm_lane_sync_state(); + pending_hex_nibble = -1; + if (edit_mode) { + reset_edit_blink(); + } +} + +void MachineMonitor :: page_disassembly(int lines) +{ + int selected_row; + + disasm_lane_ensure(); + selected_row = asm_lane_selected - asm_lane_top; + if (lines > 0) { + while (lines > 0) { + if (asm_lane_selected + 1 >= asm_lane_count) { + disasm_lane_append(disasm_lane_next_addr_at(asm_lane_selected), 0); + } else { + disasm_lane_extend_forward_to(asm_lane_selected + 1); + } + if (asm_lane_selected + 1 < asm_lane_count) { + asm_lane_selected++; + } + lines--; + } + } else if (lines < 0) { + while (asm_lane_selected + lines < 0) { + if (!disasm_lane_prepend_previous()) { + break; + } + } + asm_lane_selected += lines; + if (asm_lane_selected < 0) { + asm_lane_selected = 0; + } + } + + asm_lane_top = asm_lane_selected - selected_row; + if (asm_lane_top < 0) asm_lane_top = 0; + disasm_lane_sync_state(); + pending_hex_nibble = -1; + if (edit_mode) { + reset_edit_blink(); + } +} + +void MachineMonitor :: draw_header() +{ + char line[64]; + int width = window->get_size_x(); + if (width >= (int)sizeof(line)) { + width = (int)sizeof(line) - 1; + } + + if (help_visible) { + strcpy(line, debug.is_active() ? "HELP ASM DEBUG" : "HELP"); + } else if (hunt_picker_active) { + sprintf(line, "%s %d/%d", hunt_picker_label ? hunt_picker_label : "RESULTS", + hunt_count ? (hunt_selected + 1) : 0, hunt_count); + } else { + const char *view_name = "HEX"; + switch (state.view) { + case MONITOR_VIEW_ASM: view_name = "ASM"; break; + case MONITOR_VIEW_ASCII: view_name = "ASC"; break; + case MONITOR_VIEW_SCREEN: view_name = "SCR"; break; + case MONITOR_VIEW_BINARY: view_name = "BIN"; break; + default: break; + } + if (state.view == MONITOR_VIEW_BINARY) { + Cursor cursor = active_cursor(); + sprintf(line, "MONITOR %s $%04X/%u", view_name, cursor.address, (unsigned)cursor.bit_index); + } else if (state.view == MONITOR_VIEW_SCREEN) { + sprintf(line, "MONITOR %s %s $%04X", view_name, + (state.screen_charset == MONITOR_SCREEN_CHARSET_LOWER_UPPER) ? "L/U" : "U/G", + state.current_addr); + } else { + sprintf(line, "MONITOR %s $%04X", view_name, state.current_addr); + } + } + + const char *right = NULL; + if (!help_visible) { + if (hunt_picker_active) right = "ENTER jumps RSTOP exits"; + else if (edit_mode) right = "Edit"; + } + bool show_dbg = debug.is_active(); + int dbg_slot = width - 8; + int edit_slot = width - 4; + if (right && (help_visible || hunt_picker_active)) { + int rlen = strlen(right); + int cur = strlen(line); + if (cur > width - rlen - 1) { + cur = width - rlen - 1; + if (cur < 0) cur = 0; + line[cur] = 0; + } + int pad = width - cur - rlen; + for (int i = 0; i < pad && cur < (int)sizeof(line) - 1; i++) { + line[cur++] = ' '; + } + line[cur] = 0; + strncat(line, right, sizeof(line) - cur - 1); + } else if (!help_visible && !hunt_picker_active) { + char fixed[64]; + int first_slot = width; + int flag_slot = width - 20; + int freeze_slot = width - 15; + int poll_slot = width - 11; + const char *undoc_label = "Undc"; + int undoc_label_len = 4; + const char *poll_label = "Pl"; + int poll_label_len = 2; + bool show_undoc = state.illegal_enabled && state.view == MONITOR_VIEW_ASM; + if (flag_slot < 0) flag_slot = width; + if (freeze_slot < 0) freeze_slot = width; + if (poll_slot < 0) poll_slot = width; + if (dbg_slot < 0) dbg_slot = width; + if (edit_slot < 0) edit_slot = width; + if ((range_mode || show_undoc) && flag_slot < first_slot) first_slot = flag_slot; + if (backend && backend->supports_freeze() && backend->is_frozen() && freeze_slot < first_slot) first_slot = freeze_slot; + if (poll_mode && poll_slot < first_slot) first_slot = poll_slot; + if (show_dbg && dbg_slot < first_slot) first_slot = dbg_slot; + if (edit_mode && edit_slot < first_slot) first_slot = edit_slot; + + memset(fixed, ' ', width); + fixed[width] = 0; + int left_len = strlen(line); + if (left_len > first_slot - 1) { + left_len = first_slot - 1; + } + if (left_len < 0) { + left_len = 0; + } + memcpy(fixed, line, left_len); + if (show_undoc && flag_slot + undoc_label_len <= width) { + memcpy(fixed + flag_slot, undoc_label, undoc_label_len); + } else if (range_mode && flag_slot + 5 <= width) { + memcpy(fixed + flag_slot, "Range", 5); + } + if (backend && backend->supports_freeze() && backend->is_frozen() && freeze_slot + 3 <= width) { + memcpy(fixed + freeze_slot, "Frz", 3); + } + if (poll_mode && poll_slot + poll_label_len <= width) { + memcpy(fixed + poll_slot, poll_label, poll_label_len); + } + if (show_dbg && dbg_slot + 3 <= width) { + memcpy(fixed + dbg_slot, "Dbg", 3); + } + memcpy(line, fixed, width + 1); + } + draw_padded(window, 0, line, strlen(line)); + if (!help_visible && !hunt_picker_active) { + if (strncmp(line, "MONITOR ", 8) == 0) { + window->set_color(get_ui()->color_fg); + window->move_cursor(8, 0); + window->output_length(line + 8, 3); + const char *dollar = strchr(line, '$'); + if (dollar) { + int ax = (int)(dollar - line); + window->move_cursor(ax, 0); + window->output_length(dollar, 5); // "$" + 4 hex digits + } + window->set_color(get_ui()->color_fg); + } + if (debug.is_active()) { + if (dbg_slot < 0) dbg_slot = 0; + window->move_cursor(dbg_slot, 0); + window->set_color(MONITOR_UI_ACCENT_COLOR); + window->output_length("Dbg", 3); + window->set_color(get_ui()->color_fg); + } + if (edit_mode) { + if (edit_slot < 0) { + edit_slot = 0; + } + window->move_cursor(edit_slot, 0); + window->set_color(MONITOR_UI_ACCENT_COLOR); + window->output_length("Edit", 4); + window->set_color(get_ui()->color_fg); + } + } +} + +void MachineMonitor :: draw_status() +{ + char line[40]; + + if (help_visible) { + const char *paging_line = debug.is_active() ? + monitor_debug_help_paging_line : monitor_help_paging_line; + draw_padded(window, window->get_size_y() - 1, paging_line, + (int)strlen(paging_line)); + return; + } + + if (!debug.is_active() && bookmark_status_visible) { + window->set_color(bookmark_status_emphasis ? MONITOR_UI_ACCENT_COLOR : get_ui()->color_fg); + draw_padded(window, window->get_size_y() - 1, bookmark_status_text, + (int)strlen(bookmark_status_text)); + window->set_color(get_ui()->color_fg); + return; + } + + if (backend && !backend->supports_cpu_banking() && !backend->supports_vic_bank()) { + strcpy(line, "CPU VIEW CPU BANK N/A VIC N/A"); + } else if (backend && !backend->supports_cpu_banking()) { + sprintf(line, "CPU VIEW VIC%d $%04X", current_vic_bank & 0x03, + monitor_vic_bank_bases[current_vic_bank & 0x03]); + } else if (backend && !backend->supports_vic_bank()) { + uint8_t live_cpu_port = backend ? backend->get_live_cpu_port() : state.view_cpu_port; + if ((state.view_cpu_port & 0x07) == (live_cpu_port & 0x07)) { + sprintf(line, "CPU%d VIC N/A", state.view_cpu_port & 0x07); + } else { + bool accent_mask[40]; + sprintf(line, "C%dO%d VIC N/A", live_cpu_port & 0x07, + state.view_cpu_port & 0x07); + memset(accent_mask, 0, sizeof(accent_mask)); + accent_mask[1] = true; + accent_mask[3] = true; + draw_with_style_mask(window, window->get_size_y() - 1, line, strlen(line), + NULL, accent_mask, + get_ui()->color_fg, MONITOR_UI_ACCENT_COLOR); + return; + } + } else { + uint8_t live_cpu_port = backend ? backend->get_live_cpu_port() : state.view_cpu_port; + bool accent_mask[40]; + monitor_format_status_line(line, state.view_cpu_port, live_cpu_port, current_vic_bank); + if ((state.view_cpu_port & 0x07) != (live_cpu_port & 0x07)) { + memset(accent_mask, 0, sizeof(accent_mask)); + accent_mask[1] = true; + accent_mask[3] = true; + draw_with_style_mask(window, window->get_size_y() - 1, line, strlen(line), + NULL, accent_mask, + get_ui()->color_fg, MONITOR_UI_ACCENT_COLOR); + return; + } + } + draw_padded(window, window->get_size_y() - 1, line, strlen(line)); +} + +void MachineMonitor :: debug_full_restore_screen(void) +{ + // After a freeze-mode debug step, the firmware chrome rows (UI title and + // border lines) are overwritten by the live BASIC screen during the + // temporary C64 unfreeze. Re-establish the chrome and redraw the monitor + // window so the user sees a correct display. No-op in overlay mode because + // overlay sessions disable freeze/refreeze run windows. + if (!debug_session || !debug_session->screen_render_target_invalidated()) { + return; + } + if (screen) { + get_ui()->set_screen_title(); + restore_underlying_status_row(); + } + redraw_full(); +} + +void MachineMonitor :: restore_underlying_status_row(void) +{ + if (!screen || !get_ui()) { + return; + } + UIObject *root = get_ui()->get_root_object(); + if (root) { + root->redraw(); + } + const char *help = "F3=HELP"; + int width = screen->get_size_x(); + int height = screen->get_size_y(); + int x = width - (int)strlen(help) - 1; + if (x < 0) { + x = 0; + } + screen->move_cursor(x, height - 1); + screen->output("\eA"); + screen->output(help); + screen->output("\eO"); +} + +void MachineMonitor :: draw_debug_footer() +{ + char header_row[40]; + char value_row[40]; + int width; + int draw_len; + bool header_accent[MonitorDebug::FOOTER_WIDTH]; + bool value_accent[MonitorDebug::FOOTER_WIDTH]; + const DebugContext &ctx = debug.context(); + const char *flags = "NV-BDIZC"; + + if (!window) { + return; + } + MonitorDebug::format_footer_header(header_row, sizeof(header_row)); + MonitorDebug::format_footer_values(debug.context(), value_row, sizeof(value_row)); + memset(header_accent, 0, sizeof(header_accent)); + memset(value_accent, 0, sizeof(value_accent)); + header_accent[MonitorDebug::FOOTER_POS_PC + 0] = true; + header_accent[MonitorDebug::FOOTER_POS_PC + 1] = true; + header_accent[MonitorDebug::FOOTER_POS_AC + 0] = true; + header_accent[MonitorDebug::FOOTER_POS_XR + 0] = true; + header_accent[MonitorDebug::FOOTER_POS_YR + 0] = true; + header_accent[MonitorDebug::FOOTER_POS_SP + 0] = true; + if (ctx.valid) { + for (int i = 0; i < 4; i++) { + value_accent[MonitorDebug::FOOTER_POS_PC + i] = true; + } + for (int i = 0; i < 2; i++) { + value_accent[MonitorDebug::FOOTER_POS_AC + i] = true; + value_accent[MonitorDebug::FOOTER_POS_XR + i] = true; + value_accent[MonitorDebug::FOOTER_POS_YR + i] = true; + value_accent[MonitorDebug::FOOTER_POS_SP + i] = true; + } + for (int i = 0; i < 8; i++) { + value_accent[MonitorDebug::FOOTER_POS_FLAGS + i] = true; + } + for (int i = 0; i < 8; i++) { + if (flags[i] == '-') { + continue; + } + if ((ctx.sr & (1 << (7 - i))) != 0) { + header_accent[MonitorDebug::FOOTER_POS_FLAGS + i] = true; + } + } + } + width = window->get_size_x(); + draw_len = width; + if (draw_len > MonitorDebug::FOOTER_WIDTH) { + draw_len = MonitorDebug::FOOTER_WIDTH; + } + window->set_color(get_ui()->color_fg); + draw_with_style_mask(window, window->get_size_y() - 3, header_row, draw_len, + 0, header_accent, get_ui()->color_fg, MONITOR_UI_ACCENT_COLOR); + draw_with_style_mask(window, window->get_size_y() - 2, value_row, draw_len, + 0, value_accent, get_ui()->color_fg, MONITOR_UI_ACCENT_COLOR); + window->set_color(get_ui()->color_fg); +} + +void MachineMonitor :: draw_help() +{ + int help_rows = window ? window->get_size_y() - 2 : content_height; + if (help_rows < 1) help_rows = 1; + if (debug.is_active()) { + // Debug help takes precedence in Debug mode (DBG-HELP-001). Defer the + // text definition to MonitorDebug so the help reflects the actual + // debug command model in one place. + const char *dbg_lines[20]; + int n = MonitorDebug::format_help_lines(dbg_lines, 20); + for (int line_idx = 0; line_idx < help_rows; line_idx++) { + if (line_idx >= n) { + draw_padded(window, line_idx + 1, "", 0); + } else { + draw_padded(window, line_idx + 1, dbg_lines[line_idx], + (int)strlen(dbg_lines[line_idx])); + } + } + return; + } + for (int line_idx = 0; line_idx < help_rows; line_idx++) { + const char *text = monitor_help_lines[line_idx]; + if (!text) { + for (int blank = line_idx; blank < help_rows; blank++) { + draw_padded(window, blank + 1, "", 0); + } + break; + } + draw_padded(window, line_idx + 1, text, strlen(text)); + } +} + +void MachineMonitor :: draw_popup_overlays() +{ + if (opcode_picker_active) { + draw_opcode_picker(); + } + if (number_picker_active) { + draw_number_picker(); + } + if (bookmark_popup_active) { + draw_bookmark_popup(); + } + if (breakpoint_popup_active) { + debug_render_breakpoint_popup(); + } +} + +void MachineMonitor :: draw_bookmark_popup() +{ + enum { + MONITOR_BOOKMARK_POPUP_INNER_WIDTH = 38, + MONITOR_BOOKMARK_POPUP_INNER_HEIGHT = 14, + MONITOR_BOOKMARK_POPUP_SLOT_FIRST_ROW = 2, + MONITOR_BOOKMARK_POPUP_HELP_ROW = 13, + }; + + char popup_lines[MONITOR_BOOKMARK_POPUP_INNER_HEIGHT][MONITOR_BOOKMARK_POPUP_INNER_WIDTH + 1]; + int screen_x; + int screen_y; + int popup_x; + int popup_y; + + if (!window || !screen) { + return; + } + + memset(popup_lines, 0, sizeof(popup_lines)); + strcpy(popup_lines[0], "BOOKMARKS"); + for (int i = 0; i < MONITOR_BOOKMARK_SLOT_COUNT; i++) { + monitor_bookmark_format_popup_line(popup_lines[MONITOR_BOOKMARK_POPUP_SLOT_FIRST_ROW + i], + sizeof(popup_lines[MONITOR_BOOKMARK_POPUP_SLOT_FIRST_ROW + i]), + (uint8_t)i, + bookmarks ? bookmarks->get((uint8_t)i) : NULL); + } + strcpy(popup_lines[MONITOR_BOOKMARK_POPUP_HELP_ROW], + "0-9/RET:Jmp S:Set L:Label DEL:Reset"); + + window->getOffsets(screen_x, screen_y); + popup_x = screen_x + ((window->get_size_x() - MONITOR_BOOKMARK_POPUP_INNER_WIDTH) / 2); + popup_y = screen_y + ((window->get_size_y() - MONITOR_BOOKMARK_POPUP_INNER_HEIGHT) / 2); + // A bordered 38-inner-width popup is 40 outer cols. The visible C64 screen + // is 40 cols wide so the popup must start at the screen's x=0 in that + // case, even when the underlying monitor window starts inside the border. + if (popup_x + (MONITOR_BOOKMARK_POPUP_INNER_WIDTH + 2) > 40) { + popup_x = 40 - (MONITOR_BOOKMARK_POPUP_INNER_WIDTH + 2); + } + if (popup_x < 0) { + popup_x = 0; + } + if (popup_y < screen_y) { + popup_y = screen_y; + } + + Window popup(screen, popup_x, popup_y, + MONITOR_BOOKMARK_POPUP_INNER_WIDTH + 2, + MONITOR_BOOKMARK_POPUP_INNER_HEIGHT + 2); + popup.set_color(get_ui()->color_fg); + popup.draw_border(); + popup.set_color(get_ui()->color_fg); + + for (int row = 0; row < MONITOR_BOOKMARK_POPUP_INNER_HEIGHT; row++) { + char line[MONITOR_BOOKMARK_POPUP_INNER_WIDTH + 1]; + int len = (int)strlen(popup_lines[row]); + int slot_row = row - MONITOR_BOOKMARK_POPUP_SLOT_FIRST_ROW; + bool selected = (slot_row >= 0 && slot_row < MONITOR_BOOKMARK_SLOT_COUNT && + slot_row == (int)bookmark_selected); + + if (len > MONITOR_BOOKMARK_POPUP_INNER_WIDTH) { + len = MONITOR_BOOKMARK_POPUP_INNER_WIDTH; + } + memset(line, ' ', MONITOR_BOOKMARK_POPUP_INNER_WIDTH); + if (len > 0) { + memcpy(line, popup_lines[row], (size_t)len); + } + line[MONITOR_BOOKMARK_POPUP_INNER_WIDTH] = 0; + if (selected) { + draw_with_highlight(&popup, row, line, MONITOR_BOOKMARK_POPUP_INNER_WIDTH, + 0, MONITOR_BOOKMARK_POPUP_INNER_WIDTH); + } else { + popup.move_cursor(0, row); + popup.output_length(line, MONITOR_BOOKMARK_POPUP_INNER_WIDTH); + } + } +} + +void MachineMonitor :: draw_number_picker() +{ + char popup_lines[MONITOR_NUMBER_POPUP_INNER_HEIGHT][MONITOR_NUMBER_POPUP_INNER_WIDTH + 1]; + char bits[18]; + char ascii_text[3]; + char screen_text[3]; + char hex_digits[5]; + uint16_t target_addr = number_picker_current_addr(); + bool display_word = number_picker_current_bytes() == 2; + uint8_t low = (uint8_t)(number_preview_value & 0xFF); + uint8_t high = (uint8_t)((number_preview_value >> 8) & 0xFF); + int screen_x; + int screen_y; + + if (!window || !screen) { + return; + } + + if (display_word) { + dump_hex_word(hex_digits, 0, number_preview_value); + hex_digits[4] = 0; + } else { + dump_hex_byte(hex_digits, 0, low); + hex_digits[2] = 0; + } + bits[0] = '%'; + for (int i = 0; i < (display_word ? 16 : 8); i++) { + int bit = display_word ? (15 - i) : (7 - i); + bits[i + 1] = (number_preview_value & (uint16_t)(1u << bit)) ? '1' : '0'; + } + bits[display_word ? 17 : 9] = 0; + + ascii_text[0] = display_word ? monitor_ascii_display_byte(high) : monitor_ascii_display_byte(low); + ascii_text[1] = display_word ? monitor_ascii_display_byte(low) : 0; + ascii_text[display_word ? 2 : 1] = 0; + screen_text[0] = display_word ? monitor_number_screen_display_char(high, state.screen_charset) : + monitor_number_screen_display_char(low, state.screen_charset); + screen_text[1] = display_word ? monitor_number_screen_display_char(low, state.screen_charset) : 0; + screen_text[display_word ? 2 : 1] = 0; + + sprintf(popup_lines[0], "MONITOR NUM $%04X %s", target_addr, display_word ? "WORD" : "BYTE"); + sprintf(popup_lines[1], "Hex $%s", hex_digits); + sprintf(popup_lines[2], "Decimal %u", (unsigned)number_preview_value); + sprintf(popup_lines[3], "Binary %s", bits); + sprintf(popup_lines[4], "ASCII %s", ascii_text); + sprintf(popup_lines[5], "Screen %s", screen_text); + strcpy(popup_lines[6], "Calc with +-*/ $Hex Dec %Bin"); + if (number_expr_active) { + const char *expr = number_expr_buffer; + int expr_len = (int)strlen(expr); + int expr_room = MONITOR_NUMBER_POPUP_INNER_WIDTH - 5; + if (number_expr_status[0]) { + sprintf(popup_lines[6], "Expr=%s", number_expr_status); + } else { + if (expr_len > expr_room) { + expr += expr_len - expr_room; + } + sprintf(popup_lines[6], "Expr=%s", expr); + } + } + + window->getOffsets(screen_x, screen_y); + screen_x += number_popup_x; + screen_y += number_popup_y; + + Window popup(screen, screen_x, screen_y, MONITOR_NUMBER_POPUP_WIDTH, MONITOR_NUMBER_POPUP_HEIGHT); + popup.set_color(get_ui()->color_fg); + popup.draw_border(); + + for (int row = 0; row < MONITOR_NUMBER_POPUP_INNER_HEIGHT; row++) { + char line[MONITOR_NUMBER_POPUP_INNER_WIDTH + 1]; + int len = (int)strlen(popup_lines[row]); + if (len > MONITOR_NUMBER_POPUP_INNER_WIDTH) { + len = MONITOR_NUMBER_POPUP_INNER_WIDTH; + } + memset(line, ' ', MONITOR_NUMBER_POPUP_INNER_WIDTH); + memcpy(line, popup_lines[row], (size_t)len); + line[MONITOR_NUMBER_POPUP_INNER_WIDTH] = 0; + draw_with_highlight(&popup, row, line, MONITOR_NUMBER_POPUP_INNER_WIDTH, + (number_expr_active && row == MONITOR_NUMBER_POPUP_INNER_HEIGHT - 1) ? 0 : + ((row >= 1 && row <= 5 && (row - 1) == number_selected) ? 0 : -1), + MONITOR_NUMBER_POPUP_INNER_WIDTH); + } +} + +void MachineMonitor :: refresh_popup_overlay() +{ + if (!window || !screen) { + return; + } + if (screen->prefers_full_refresh()) { + draw(); + return; + } + if (!help_visible && !hunt_picker_active) { + draw_popup_overlays(); + } + screen->sync(); +} + +void MachineMonitor :: draw_hex_row(int y, uint16_t addr, const uint8_t *bytes) +{ + char line[MONITOR_MEMORY_ROW_16_CHARS + 1]; + bool mask[MONITOR_MEMORY_ROW_16_CHARS]; + int stride = memory_byte_stride(); + int line_len = memory_row_chars(); + + if (stride == MONITOR_MEMORY_MAX_BYTES_PER_ROW) { + monitor_format_hex16_row(addr, bytes, line); + } else { + monitor_format_hex_row(addr, bytes, line); + } + memset(mask, 0, sizeof(mask)); + for (int i = 0; i < stride; i++) { + uint16_t cell = (uint16_t)(addr + i); + if (range_contains(cell)) { + int col = memory_hex_column(i); + mask[col] = true; + mask[col + 1] = true; + if (stride == MONITOR_MEMORY_MIN_BYTES_PER_ROW) { + mask[29 + i] = true; + } + } + } + if ((!edit_mode || edit_cursor_visible) && state.view == MONITOR_VIEW_HEX && + monitor_row_contains(addr, stride, state.current_addr)) { + int index = state.current_addr - addr; + int col = memory_hex_column(index); + mask[col] = true; + mask[col + 1] = true; + } + draw_with_mask(window, y, line, line_len, mask); +} + +void MachineMonitor :: draw_text_row(int y, uint16_t addr, const uint8_t *bytes, bool screen_codes) +{ + char line[MONITOR_TEXT_ROW_CHARS + 1]; + bool mask[MONITOR_TEXT_ROW_CHARS]; + + monitor_format_text_row_impl(addr, bytes, MONITOR_TEXT_BYTES_PER_ROW, screen_codes, + state.screen_charset, line); + memset(mask, 0, sizeof(mask)); + for (int i = 0; i < MONITOR_TEXT_BYTES_PER_ROW; i++) { + if (range_contains((uint16_t)(addr + i))) { + mask[5 + i] = true; + } + } + if ((!edit_mode || edit_cursor_visible) && + ((state.view == MONITOR_VIEW_ASCII && !screen_codes) || + (state.view == MONITOR_VIEW_SCREEN && screen_codes)) && + monitor_row_contains(addr, MONITOR_TEXT_BYTES_PER_ROW, state.current_addr)) { + mask[5 + (state.current_addr - addr)] = true; + } + draw_with_mask(window, y, line, MONITOR_TEXT_ROW_CHARS, mask); +} + +void MachineMonitor :: draw_hex() +{ + int stride = memory_byte_stride(); + int line_idx; + for (line_idx = 0; line_idx < content_height; line_idx++) { + uint16_t addr = (uint16_t)(state.base_addr + line_idx * stride); + uint8_t bytes[MONITOR_MEMORY_MAX_BYTES_PER_ROW]; + + read_row(addr, bytes, stride); + if (edit_mode && pending_hex_nibble >= 0 && monitor_row_contains(addr, stride, state.current_addr)) { + int index = state.current_addr - addr; + bytes[index] = (uint8_t)((pending_hex_nibble << 4) | (bytes[index] & 0x0F)); + } + draw_hex_row(line_idx + 1, addr, bytes); + } +} + +void MachineMonitor :: draw_ascii() +{ + int line_idx; + for (line_idx = 0; line_idx < content_height; line_idx++) { + uint16_t addr = (uint16_t)(state.base_addr + line_idx * MONITOR_TEXT_BYTES_PER_ROW); + uint8_t bytes[MONITOR_TEXT_BYTES_PER_ROW]; + + read_row(addr, bytes, MONITOR_TEXT_BYTES_PER_ROW); + draw_text_row(line_idx + 1, addr, bytes, false); + } +} + +void MachineMonitor :: draw_screen_codes() +{ + int line_idx; + for (line_idx = 0; line_idx < content_height; line_idx++) { + uint16_t addr = (uint16_t)(state.base_addr + line_idx * MONITOR_TEXT_BYTES_PER_ROW); + uint8_t bytes[MONITOR_TEXT_BYTES_PER_ROW]; + + read_row(addr, bytes, MONITOR_TEXT_BYTES_PER_ROW); + draw_text_row(line_idx + 1, addr, bytes, true); + } +} + +void MachineMonitor :: draw_binary_row(int y, uint16_t addr, const uint8_t *bytes, int byte_count) +{ + // Format depends on width: + // Width 1: "AAAA bbbbbbbb HH" (16 cols) + // Width 2: "AAAA bbbbbbbb bbbbbbbb HH HH" (28 cols) + // Width 3: "AAAA bbbbbbbb bbbbbbbb bbbbbbbb HHHHHH" (38 cols) + // Width 3S: "AAAA bbbbbbbbbbbbbbbbbbbbbbbb HH HH HH" (38 cols) + // Width 4: "AAAA bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" (37 cols) + enum { BIN_LINE_MAX = 38 }; + char line[BIN_LINE_MAX + 1]; + bool mask[BIN_LINE_MAX]; + int bits = byte_count * 8; + if (bits < 8) bits = 8; + if (bits > MONITOR_BINARY_MAX_BYTES_PER_ROW * 8) bits = MONITOR_BINARY_MAX_BYTES_PER_ROW * 8; + + memset(line, ' ', sizeof(line) - 1); + memset(mask, 0, sizeof(mask)); + dump_hex_word(line, 0, addr); + line[4] = ' '; + int pos = 5; + int hex_start = -1; + + bool packed_bits = monitor_binary_packed_bits(binary_bytes_per_row); + bool show_hex_preview = monitor_binary_shows_hex_preview(binary_bytes_per_row); + bool use_sprite_mode = (byte_count == 3) && (binary_bytes_per_row == MONITOR_BINARY_SPRITE_MODE_MARKER); + bool hex_bytes_spaced = use_sprite_mode || (byte_count == 2); + + if (packed_bits) { + for (int i = 0; i < bits; i++) { + int byte_off = i / 8; + int bit_in_byte = 7 - (i % 8); + if (byte_off >= byte_count) break; + line[pos++] = ((bytes[byte_off] >> bit_in_byte) & 1) ? '*' : '.'; + } + } else { + for (int byte_idx = 0; byte_idx < byte_count; byte_idx++) { + for (int bit = 7; bit >= 0; bit--) { + line[pos++] = ((bytes[byte_idx] >> bit) & 1) ? '*' : '.'; + } + if (byte_idx + 1 < byte_count) line[pos++] = ' '; + } + } + + if (show_hex_preview) { + line[pos++] = ' '; + hex_start = pos; + for (int i = 0; i < byte_count; i++) { + dump_hex_byte(line, pos, bytes[i]); + pos += 2; + if (hex_bytes_spaced && i + 1 < byte_count) line[pos++] = ' '; + } + } + + int total = pos; + if (total > (int)sizeof(line) - 1) total = (int)sizeof(line) - 1; + line[total] = 0; + + // Apply range highlighting + for (int i = 0; i < byte_count; i++) { + if (range_contains((uint16_t)(addr + i))) { + int first = 5; + // Calculate start position for this byte in the line + if (packed_bits) { + first = 5 + (i * 8); + } else if (byte_count == 1) { + first = 5; + } else if (byte_count == 2) { + first = 5 + (i * 9); // 8 bits + 1 space + } else if (byte_count == 3) { + first = 5 + (i * 9); // 8 bits + 1 space + } + for (int b = 0; b < 8 && first + b < total; b++) { + mask[first + b] = true; + } + } + } + + // Apply cursor highlighting + if ((!edit_mode || edit_cursor_visible) && + state.view == MONITOR_VIEW_BINARY && + monitor_row_contains(addr, byte_count, state.current_addr)) { + int byte_offset = state.current_addr - addr; + uint8_t bit = (binary_bit_index <= 7) ? binary_bit_index : 7; + int bit_pos_in_byte = 7 - bit; // bit position within byte (0-7) + + // Calculate column of the binary bit + int col = -1; + if (packed_bits) { + col = 5 + (byte_offset * 8) + bit_pos_in_byte; + } else if (byte_count == 1) { + col = 5 + bit_pos_in_byte; + } else if (byte_count == 2) { + col = 5 + (byte_offset * 9) + bit_pos_in_byte; + } else if (byte_count == 3) { + col = 5 + (byte_offset * 9) + bit_pos_in_byte; + } + + if (col >= 0 && col < total) { + mask[col] = true; + } + + // Highlight corresponding hex nibble + if (hex_start >= 0) { + int nibble_col = hex_start + (byte_offset * (hex_bytes_spaced ? 3 : 2)); + // High nibble (bits 7-4) = first hex digit; low nibble (bits 3-0) = second hex digit + // bit values: 7,6,5,4,3,2,1,0 + // For bits 3-0, add 1 to get second hex digit; for bits 7-4, use first hex digit (no add) + if (bit < 4) { + nibble_col++; // Low hex digit for low nibble + } + if (nibble_col >= 0 && nibble_col < total) { + mask[nibble_col] = true; + } + } + } + + draw_with_mask(window, y, line, total, mask); +} + +void MachineMonitor :: draw_binary() +{ + int stride = binary_byte_stride(); + if (stride < 1) stride = 1; + uint8_t bytes[MONITOR_BINARY_MAX_BYTES_PER_ROW]; + for (int line_idx = 0; line_idx < content_height; line_idx++) { + uint16_t addr = (uint16_t)(state.base_addr + line_idx * stride); + read_row(addr, bytes, (uint16_t)stride); + draw_binary_row(line_idx + 1, addr, bytes, stride); + } +} + +void MachineMonitor :: redraw_full() +{ + // Re-paint border + content after a sub-dialog (file picker, popup, + // confirmation) closed. Do NOT call set_screen_title() here: that would + // re-clear the chrome rows above/below the monitor and overwrite the + // application status row beneath us with horizontal-line glyphs. Popup- + // style sub-dialogs already backup/restore the screen on memory-mapped + // backends, and on VT100 the chrome rows sit outside the centered popup + // area, so the chrome is intact when we get here. + // + // Window::draw_border() permanently shrinks the window's effective area by + // one character on each side (it advances offset_x/y and reduces + // window_x/y by 2). So before redrawing the border we must reset the + // geometry, otherwise each popup nibbles another row+column off the + // monitor frame. + if (!window || !screen) return; + window->reset_border(); + window->draw_border(); + window->set_color(get_ui()->color_fg); + draw(); +} + +void MachineMonitor :: draw_disassembly() +{ + uint16_t row_addrs[32]; + uint8_t row_lengths[32]; + int row_count = content_height; + int line_idx; + + if (row_count > (int)(sizeof(row_addrs) / sizeof(row_addrs[0]))) { + row_count = (int)(sizeof(row_addrs) / sizeof(row_addrs[0])); + } + disasm_visible_addresses(row_addrs, row_lengths, row_count); + if (row_count > 0) { + state.base_addr = row_addrs[0]; + } + + for (line_idx = 0; line_idx < content_height; line_idx++) { + Disassembled6502 decoded; + char line[MONITOR_DISASM_ROW_CHARS + 1]; + uint8_t row_bytes[3]; + uint16_t addr = (line_idx < row_count) ? row_addrs[line_idx] : state.current_addr; + uint8_t row_len = (line_idx < row_count) ? row_lengths[line_idx] : 0; + int highlight = -1; + int text_limit; + int text_len; + const char *source; + int source_len; + int source_pos; + int bp_slot; + bool bp_enabled = false; + int bp_len = 0; + const char *bp_label = NULL; + int indicator_start; + int brk_pos = -1; + bool reverse_mask[MONITOR_DISASM_ROW_CHARS]; + bool accent_mask[MONITOR_DISASM_ROW_CHARS]; + bool debug_next_row = debug.is_active() && debug.has_context() && + debug.context().valid && addr == debug.context().pc; + + if (debug_next_row && debug_session && + debug_session->read_step_bytes(addr, row_bytes, 3)) { + // Execution-facing PC row: use the live $0001 mapping, not the + // monitor view selected by O. + row_len = 0; + } else if (row_len) { + int lane_index = asm_lane_top + line_idx; + memset(row_bytes, 0, sizeof(row_bytes)); + if (lane_index >= 0 && lane_index < asm_lane_count) { + row_bytes[0] = asm_lane_forced_bytes[lane_index]; + } + } else { + read_row(addr, row_bytes, 3); + } + memset(line, ' ', sizeof(line)); + line[MONITOR_DISASM_ROW_CHARS] = 0; + disassemble_6502(addr, row_bytes, state.illegal_enabled, &decoded); + monitor_disasm_tail_cutover(addr, &decoded); + if (row_len && decoded.length != row_len) { + decoded.valid = false; + decoded.illegal = false; + decoded.operand_bytes = 0; + decoded.has_target = false; + decoded.target = 0; + decoded.length = row_len; + strcpy(decoded.text, "???"); + } + if (!row_len) { + row_len = decoded.length ? decoded.length : 1; + } + // The next-to-execute instruction (the captured debug PC) is decorated + // independently of the movable cursor, so the user can scroll/move the + // cursor while still seeing what will run next. + debug_next_row = debug_next_row && row_len != 0; + // For an RTS on the debug PC row, render the return address inferred + // from the stack as "$XXXX" so it can be highlighted just like a + // JMP/JSR/branch target. rts_target_col is the column of the '$' within + // decoded.text, or -1 when this row is not such an RTS. + int rts_target_col = -1; + if (debug_next_row && decoded.valid && row_bytes[0] == 0x60 && + decoded.length == 1 && strcmp(decoded.text, "RTS") == 0) { + uint8_t sp = debug.context().sp; + char tgt[8]; + if (sp == 0xFF) { + // Stack empty: no return address to infer. + strcpy(tgt, "$????"); + } else { + uint16_t lo = (uint16_t)(0x0100 + ((sp + 1) & 0xFF)); + uint16_t hi = (uint16_t)(0x0100 + ((sp + 2) & 0xFF)); + uint16_t ret = (uint16_t)(backend->read(lo) | (backend->read(hi) << 8)); + // RTS pulls the return address and resumes at address + 1. + sprintf(tgt, "$%04x", (uint16_t)(ret + 1)); + } + rts_target_col = 4; // strlen("RTS ") + sprintf(decoded.text, "RTS %s", tgt); + } + dump_hex_word(line, 0, addr); + line[4] = ' '; + dump_hex_byte(line, 5, row_bytes[0]); + if (row_len >= 2) { + dump_hex_byte(line, 8, row_bytes[1]); + } + if (row_len >= 3) { + dump_hex_byte(line, 11, row_bytes[2]); + } + line[13] = ' '; + line[14] = ' '; + + MonitorBackingStore row_target = debug_next_row ? + breakpoint_target_for_live_cpu(addr) : breakpoint_target_for_view(addr); + bp_slot = breakpoints.find_at(addr, row_target); + source = debug_next_row ? + monitor_source_indicator(monitor_backing_store_source_name(row_target)) : + monitor_source_indicator(backend->source_name(addr)); + source_len = (int)strlen(source); + if (source_len > 3) { + source_len = 3; + } + source_pos = MONITOR_DISASM_ROW_CHARS - source_len - 2; + if (bp_slot >= 0) { + const MonitorBreakpointSlot *bp = breakpoints.get(bp_slot); + bp_enabled = bp && bp->enabled; + if (bp && bp->label[0]) { + bp_label = bp->label; + bp_len = (int)strlen(bp_label); + if (bp_len > MONITOR_BREAKPOINT_LABEL_MAX) { + bp_len = MONITOR_BREAKPOINT_LABEL_MAX; + } + } else { + bp_len = 4; + } + brk_pos = source_pos - (bp_len + 2); + if (brk_pos < MONITOR_DISASM_TEXT_COL) { + brk_pos = MONITOR_DISASM_TEXT_COL; + } + indicator_start = brk_pos; + } else { + indicator_start = source_pos; + } + + text_limit = indicator_start - 1 - MONITOR_DISASM_TEXT_COL; + if (text_limit < 0) { + text_limit = 0; + } + text_len = (int)strlen(decoded.text); + if (text_len > text_limit) { + text_len = text_limit; + } + memcpy(line + MONITOR_DISASM_TEXT_COL, decoded.text, text_len); + + if (bp_slot >= 0) { + line[brk_pos] = '['; + if (bp_label && bp_len > 0) { + memcpy(line + brk_pos + 1, bp_label, bp_len); + } else { + memcpy(line + brk_pos + 1, "BRK", 3); + line[brk_pos + 4] = (char)('0' + bp_slot); + } + line[brk_pos + 1 + bp_len] = ']'; + } + line[source_pos] = '['; + memcpy(line + source_pos + 1, source, source_len); + line[source_pos + 1 + source_len] = ']'; + + if (line_idx == state.disasm_offset && addr == state.current_addr) { + highlight = 0; + } + if (range_mode) { + uint8_t len = row_len ? row_len : 1; + for (uint8_t i = 0; i < len; i++) { + if (range_contains((uint16_t)(addr + i))) { + highlight = 0; + break; + } + } + } + int hl_x = 0; + int hl_len = MONITOR_DISASM_ROW_CHARS; + memset(reverse_mask, 0, sizeof(reverse_mask)); + memset(accent_mask, 0, sizeof(accent_mask)); + if (highlight == 0 && edit_mode && state.view == MONITOR_VIEW_ASM) { + uint8_t part = asm_edit_part; + uint8_t part_count = asm_edit_part_count(addr); + if (part >= part_count) part = 0; + // All asm-edit highlights live inside the decoded text region + // (never on the raw byte columns to the left). + if (part == 0) { + int mnem_len = 0; + while (mnem_len < text_len && decoded.text[mnem_len] != ' ') mnem_len++; + if (mnem_len == 0) mnem_len = (text_len > 0) ? text_len : 1; + hl_x = MONITOR_DISASM_TEXT_COL; + hl_len = mnem_len; + } else { + // Locate the operand hex digits inside decoded.text. + int dollar = -1; + for (int i = 0; i < text_len; i++) { + if (decoded.text[i] == '$') { dollar = i; break; } + } + int hexstart = (dollar >= 0) ? dollar + 1 : -1; + int hexcount = 0; + while (hexstart >= 0 && hexstart + hexcount < text_len) { + char c = decoded.text[hexstart + hexcount]; + bool digit = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); + if (!digit) break; + hexcount++; + } + bool branch = (decoded.length == 2) && asm_is_branch(addr); + if (hexstart >= 0 && hexcount >= 2) { + if ((decoded.length == 3 || branch) && hexcount >= 4) { + // part 1 -> first 2 hex chars (high byte, displayed first) + // part 2 -> next 2 hex chars (low byte, displayed second) + int off = (part == 1) ? 0 : 2; + hl_x = MONITOR_DISASM_TEXT_COL + hexstart + off; + hl_len = 2; + } else { + hl_x = MONITOR_DISASM_TEXT_COL + hexstart; + hl_len = 2; + } + } else { + // Fallback: highlight the mnemonic to avoid flashing the byte column. + int mnem_len = 0; + while (mnem_len < text_len && decoded.text[mnem_len] != ' ') mnem_len++; + if (mnem_len == 0) mnem_len = 1; + hl_x = MONITOR_DISASM_TEXT_COL; + hl_len = mnem_len; + } + } + } + if (highlight >= 0 && hl_len > 0) { + int reverse_start = hl_x; + int reverse_end = hl_x + hl_len; + if (reverse_start < 0) { + reverse_start = 0; + } + if (reverse_end > MONITOR_DISASM_ROW_CHARS) { + reverse_end = MONITOR_DISASM_ROW_CHARS; + } + for (int i = reverse_start; i < reverse_end; i++) { + reverse_mask[i] = true; + } + } + if (debug_next_row) { + int target_start = -1; + int target_len = 0; + if (rts_target_col >= 0) { + // RTS: highlight the inferred "$XXXX"/"$????" we appended above. + target_start = rts_target_col; + target_len = 5; + } else { + DebugPredictResult pred; + debug_predict(addr, row_bytes, state.illegal_enabled, &pred); + bool target_highlight = false; + if (pred.kind == DBG_PREDICT_JSR || pred.kind == DBG_PREDICT_JMP_ABS) { + target_highlight = pred.has_target; + } else if (pred.kind == DBG_PREDICT_BRANCH && pred.has_target) { + target_highlight = monitor_debug_branch_taken(row_bytes[0], debug.context().sr); + } + if (target_highlight) { + monitor_find_target_span(decoded.text, text_len, &target_start, &target_len); + } + } + if (target_start >= 0 && target_len > 0 && target_start < text_len) { + if (target_start + target_len > text_len) { + target_len = text_len - target_start; + } + int accent_start = MONITOR_DISASM_TEXT_COL + target_start; + int accent_end = accent_start + target_len; + if (accent_start < MONITOR_DISASM_ROW_CHARS) { + if (accent_end > MONITOR_DISASM_ROW_CHARS) { + accent_end = MONITOR_DISASM_ROW_CHARS; + } + for (int i = accent_start; i < accent_end; i++) { + accent_mask[i] = true; + } + } + } + // Bracket the next-to-execute instruction with > ... < placed in the + // whitespace immediately before the mnemonic and after the operand. + if (MONITOR_DISASM_TEXT_COL >= 1 && + line[MONITOR_DISASM_TEXT_COL - 1] == ' ') { + line[MONITOR_DISASM_TEXT_COL - 1] = '>'; + } + int close_col = MONITOR_DISASM_TEXT_COL + text_len; + if (close_col < MONITOR_DISASM_ROW_CHARS && line[close_col] == ' ') { + line[close_col] = '<'; + } + } + // Enabled breakpoints render in the same accent color as the Dbg / + // Edit header flags - but only while Debug mode is active. Disabled + // breakpoints, and any breakpoint shown when Debug is off, stay in + // the regular foreground color so the row reads as "armed and live" + // vs "remembered but quiet". + bool bp_accent = bp_slot >= 0 && bp_enabled && debug.is_active(); + if (bp_accent && brk_pos >= 0) { + int accent_end = brk_pos + bp_len + 2; + if (accent_end > MONITOR_DISASM_ROW_CHARS) { + accent_end = MONITOR_DISASM_ROW_CHARS; + } + for (int i = brk_pos; i < accent_end; i++) { + accent_mask[i] = true; + } + } + draw_with_style_mask(window, line_idx + 1, line, MONITOR_DISASM_ROW_CHARS, + reverse_mask, accent_mask, + get_ui()->color_fg, MONITOR_UI_ACCENT_COLOR); + } +} + +void MachineMonitor :: draw_hunt_picker() +{ + if (!window) { + return; + } + int rows = content_height; + if (rows <= 0) { + return; + } + if (hunt_selected < hunt_top) { + hunt_top = hunt_selected; + } else if (hunt_selected >= hunt_top + rows) { + hunt_top = hunt_selected - rows + 1; + } + if (hunt_top < 0) { + hunt_top = 0; + } + int width = window->get_size_x(); + char line[MONITOR_HEX_ROW_CHARS + 1]; + for (int r = 0; r < rows; r++) { + int idx = hunt_top + r; + memset(line, ' ', sizeof(line)); + line[MONITOR_HEX_ROW_CHARS] = 0; + int draw_len = MONITOR_HEX_ROW_CHARS; + if (idx < hunt_count) { + uint8_t bytes[MONITOR_HEX_BYTES_PER_ROW]; + read_row(hunt_addrs[idx], bytes, MONITOR_HEX_BYTES_PER_ROW); + monitor_format_hex_row(hunt_addrs[idx], bytes, line); + } else { + draw_padded(window, r + 1, line, 0); + continue; + } + if (draw_len > width) draw_len = width; + int hl = (idx == hunt_selected) ? 0 : -1; + draw_with_highlight(window, r + 1, line, draw_len, hl, draw_len); + } +} + +void MachineMonitor :: draw_opcode_picker() +{ + if (!window) return; + int width = window->get_size_x(); + // Anchor the overlay to the row that holds the current_addr in the + // disassembly view; if not visible, fall back to the top row. + int anchor_row = 1; + { + int visible_row = disasm_visible_row(state.current_addr); + if (visible_row >= 0) { + anchor_row = visible_row + 1; + } + } + // Box width: 18 chars (template up to 13 + small margin). Try to right-align + // beside the disassembly text. + int box_w = 18; + if (box_w > width - 2) box_w = width - 2; + int box_x = MONITOR_DISASM_TEXT_COL; + if (box_x + box_w > width) box_x = width - box_w; + if (box_x < 0) box_x = 0; + + int max_rows = content_height - anchor_row; + if (max_rows < 0) max_rows = 0; + int visible = opcode_candidate_count; + if (visible > max_rows) visible = max_rows; + if (visible < 0) visible = 0; + int rows_to_draw = opcode_drawn_rows; + if (rows_to_draw < visible) rows_to_draw = visible; + + // Adjust scroll window. + if (visible > 0) { + if (opcode_selected < opcode_top) opcode_top = opcode_selected; + if (opcode_selected >= opcode_top + visible) opcode_top = opcode_selected - visible + 1; + } else { + opcode_top = 0; + } + if (opcode_top < 0) opcode_top = 0; + + char line[40]; + // Header row: typed prefix (or "_" if empty) + operand buffer + match count. + memset(line, ' ', sizeof(line)); + line[box_w] = 0; + char prefix_show[6]; + int n = 0; + for (; n < opcode_prefix_len && n < 3; n++) prefix_show[n] = opcode_prefix[n]; + prefix_show[n++] = '_'; + prefix_show[n] = 0; + if (opcode_operand_len > 0) { + sprintf(line, " %s %s %d", prefix_show, opcode_operand, opcode_candidate_count); + } else { + sprintf(line, " %s %d", prefix_show, opcode_candidate_count); + } + int len = (int)strlen(line); + if (len < box_w) { memset(line + len, ' ', box_w - len); line[box_w] = 0; } + window->move_cursor(box_x, anchor_row); + window->reverse_mode(1); + window->output_length(line, box_w); + window->reverse_mode(0); + + // Candidate rows. + for (int r = 0; r < rows_to_draw; r++) { + int idx = opcode_top + r; + memset(line, ' ', sizeof(line)); + line[box_w] = 0; + if (r < visible && idx < opcode_candidate_count) { + uint8_t op = opcode_candidates[idx]; + const char *templ = disassembler_6502_template(op); + char buf[16]; + memset(buf, 0, sizeof(buf)); + // Copy template up to 13 chars, replacing leading '*' on the + // mnemonic with a space. + for (int i = 0; i < 13 && i < (int)sizeof(buf) - 1 && templ && templ[i]; i++) { + buf[i] = (templ[i] == '*') ? ' ' : templ[i]; + buf[i + 1] = 0; + } + // Canonicalise mnemonic (HLT->JAM, etc.). + char mnem[4]; + mnem[0] = buf[0]; mnem[1] = buf[1]; mnem[2] = buf[2]; mnem[3] = 0; + if (op == 0x5C || op == 0x7C) strcpy(mnem, "NOP"); + else if (!strcmp(mnem, "HLT")) strcpy(mnem, "JAM"); + else if (!strcmp(mnem, "ASO")) strcpy(mnem, "SLO"); + else if (!strcmp(mnem, "LSE")) strcpy(mnem, "SRE"); + else if (!strcmp(mnem, "DCM")) strcpy(mnem, "DCP"); + else if (!strcmp(mnem, "INS")) strcpy(mnem, "ISC"); + buf[0] = mnem[0]; buf[1] = mnem[1]; buf[2] = mnem[2]; + sprintf(line, " %s", buf); + int slen = (int)strlen(line); + if (slen < box_w) { memset(line + slen, ' ', box_w - slen); line[box_w] = 0; } + } + window->move_cursor(box_x, anchor_row + 1 + r); + if (r < visible && idx == opcode_selected && idx < opcode_candidate_count) { + window->reverse_mode(1); + window->output_length(line, box_w); + window->reverse_mode(0); + } else { + window->output_length(line, box_w); + } + } + opcode_drawn_rows = visible; +} + +void MachineMonitor :: hunt_picker_open(int count) +{ + hunt_picker_open_labeled(count, "Hunt results"); +} + +void MachineMonitor :: hunt_picker_open_labeled(int count, const char *label) +{ + hunt_count = count; + if (hunt_count > (int)(sizeof(hunt_addrs) / sizeof(hunt_addrs[0]))) { + hunt_count = (int)(sizeof(hunt_addrs) / sizeof(hunt_addrs[0])); + } + hunt_selected = 0; + hunt_top = 0; + hunt_picker_label = label ? label : "Results"; + hunt_picker_active = true; + printf("MCM results open %s %d\n", hunt_picker_label ? hunt_picker_label : "Results", hunt_count); +} + +void MachineMonitor :: hunt_picker_close() +{ + if (hunt_picker_active) { + monitor_log("results close"); + } + hunt_picker_active = false; +} + +void MachineMonitor :: hunt_picker_jump() +{ + if (hunt_count <= 0 || hunt_selected < 0 || hunt_selected >= hunt_count) { + return; + } + apply_go_local(hunt_addrs[hunt_selected]); + monitor_log_address("results jump", hunt_addrs[hunt_selected]); + hunt_picker_close(); +} + +int MachineMonitor :: hunt_picker_handle_key(int key) +{ + if (key == KEY_ESCAPE || key == KEY_BREAK || key == KEY_CTRL_O) { + hunt_picker_close(); + draw(); + return (key == KEY_CTRL_O) ? 1 : 0; + } + if (key == KEY_RETURN) { + hunt_picker_jump(); + draw(); + return 0; + } + if (key == KEY_DOWN) { + if (hunt_selected + 1 < hunt_count) hunt_selected++; + } else if (key == KEY_UP) { + if (hunt_selected > 0) hunt_selected--; + } else if (key == KEY_PAGEDOWN) { + hunt_selected += content_height > 0 ? content_height : 1; + if (hunt_selected >= hunt_count) hunt_selected = hunt_count - 1; + } else if (key == KEY_PAGEUP) { + hunt_selected -= content_height > 0 ? content_height : 1; + if (hunt_selected < 0) hunt_selected = 0; + } else if (key == KEY_HOME) { + hunt_selected = 0; + } else if (key == KEY_END) { + hunt_selected = hunt_count - 1; + } + draw(); + return 0; +} + +void MachineMonitor :: draw() +{ + bool draw_overlays = !help_visible && !hunt_picker_active; + + draw_header(); + if (help_visible) { + draw_help(); + } else if (hunt_picker_active) { + draw_hunt_picker(); + } else { + switch (state.view) { + case MONITOR_VIEW_DISASM: + draw_disassembly(); + break; + case MONITOR_VIEW_ASCII: + draw_ascii(); + break; + case MONITOR_VIEW_SCREEN: + draw_screen_codes(); + break; + case MONITOR_VIEW_BINARY: + draw_binary(); + break; + default: + draw_hex(); + break; + } + } + if (debug.is_active() && !help_visible) { + draw_debug_footer(); + } + draw_status(); + if (draw_overlays) { + draw_popup_overlays(); + } + if (screen) { + screen->sync(); + } +} + +void MachineMonitor :: apply_hex_digit(uint8_t value) +{ + if (pending_hex_nibble < 0) { + pending_hex_nibble = (int)value; + reset_edit_blink(); + } else { + uint8_t byte = (uint8_t)((pending_hex_nibble << 4) | value); + canonical_write(state.current_addr, byte); + pending_hex_nibble = -1; + move_current(1); + } +} + +void MachineMonitor :: apply_ascii_char(char value) +{ + canonical_write(state.current_addr, (uint8_t)value); + move_current(1); +} + +void MachineMonitor :: apply_screen_char(char value) +{ + canonical_write(state.current_addr, (uint8_t)value); + move_current(1); +} + +void MachineMonitor :: binary_apply_bit(uint8_t bit_value) +{ + if (binary_bit_index > 7) binary_bit_index = 7; + uint8_t byte = canonical_read(state.current_addr); + uint8_t mask = (uint8_t)(1u << binary_bit_index); + if (bit_value) byte |= mask; + else byte &= (uint8_t)~mask; + canonical_write(state.current_addr, byte); + move_binary_bits(1); + reset_edit_blink(); +} + +// Unified DEL behaviour shared by edit and non-edit mode. ASC/SCR clear +// the current cell to a space and step the cursor LEFT; HEX clears the +// current byte to 0x00 and steps RIGHT; BINARY clears only the selected +// bit to 0 and steps RIGHT by one bit; ASM replaces the current +// instruction with NOP(s) and steps to the next disassembled line. +void MachineMonitor :: apply_logical_delete() +{ + switch (state.view) { + case MONITOR_VIEW_HEX: { + canonical_write(state.current_addr, 0x00); + pending_hex_nibble = -1; + move_current(1); + break; + } + case MONITOR_VIEW_ASCII: { + canonical_write(state.current_addr, 0x20); + move_current(-1); + break; + } + case MONITOR_VIEW_SCREEN: { + canonical_write(state.current_addr, 0x20); + move_current(-1); + break; + } + case MONITOR_VIEW_BINARY: + binary_apply_bit(0); + break; + case MONITOR_VIEW_ASM: { + uint8_t len = disasm_length(state.current_addr); + for (uint8_t i = 0; i < len; i++) { + canonical_write((uint16_t)(state.current_addr + i), 0xEA); + } + disasm_lane_rebuild_suffix_from_current(); + step_disassembly(1); + break; + } + default: + break; + } +} + +void MachineMonitor :: asm_edit_history_reset(uint16_t anchor_addr) +{ + asm_edit_hist_len = 0; + asm_edit_hist_anchor_addr = anchor_addr; +} + +void MachineMonitor :: asm_edit_history_push(uint16_t addr, uint8_t prev_byte, uint8_t prev_part, uint8_t prev_pending) +{ + if (asm_edit_hist_len >= ASM_EDIT_HISTORY_MAX) { + // Drop the oldest entry to make room (FIFO eviction). The user's + // expected DEL undoes recent edits; very long edit chains beyond the + // buffer simply cannot be undone by the buffer entry that fell off. + for (int i = 1; i < ASM_EDIT_HISTORY_MAX; i++) { + asm_edit_hist_addr[i - 1] = asm_edit_hist_addr[i]; + asm_edit_hist_byte[i - 1] = asm_edit_hist_byte[i]; + asm_edit_hist_part[i - 1] = asm_edit_hist_part[i]; + asm_edit_hist_pending[i - 1] = asm_edit_hist_pending[i]; + } + asm_edit_hist_len = ASM_EDIT_HISTORY_MAX - 1; + } + asm_edit_hist_addr[asm_edit_hist_len] = addr; + asm_edit_hist_byte[asm_edit_hist_len] = prev_byte; + asm_edit_hist_part[asm_edit_hist_len] = prev_part; + asm_edit_hist_pending[asm_edit_hist_len] = prev_pending; + asm_edit_hist_len++; +} + +bool MachineMonitor :: asm_edit_history_pop() +{ + if (asm_edit_hist_len <= 0) return false; + asm_edit_hist_len--; + uint16_t addr = asm_edit_hist_addr[asm_edit_hist_len]; + uint8_t byte = asm_edit_hist_byte[asm_edit_hist_len]; + canonical_write(addr, byte); + state.current_addr = asm_edit_hist_anchor_addr; + asm_edit_part = asm_edit_hist_part[asm_edit_hist_len]; + asm_edit_pending = asm_edit_hist_pending[asm_edit_hist_len]; + return true; +} + +// Direct-typing path in the opcode picker uses the existing assembler so it +// accepts the same syntax as monitor_assemble_line ("LDA $1000", "LDA #$FF", +// "JMP ($1000)", "LDA ($10),Y", etc.). The picker collects the operand chars +// after the 3-letter mnemonic into opcode_operand[] and on commit asks the +// assembler to turn the full "MNEM operand" string into bytes. + +void MachineMonitor :: opcode_picker_open(char seed) +{ + opcode_picker_active = true; + monitor_log_address("opcode-picker open", state.current_addr); + opcode_drawn_rows = 0; + opcode_prefix_len = 0; + opcode_prefix[0] = 0; + opcode_operand_len = 0; + opcode_operand[0] = 0; + if (seed) { + char up = (seed >= 'a' && seed <= 'z') ? (char)(seed - 'a' + 'A') : seed; + if ((up >= 'A' && up <= 'Z')) { + opcode_prefix[0] = up; + opcode_prefix[1] = 0; + opcode_prefix_len = 1; + } + } + opcode_selected = 0; + opcode_top = 0; + opcode_picker_refilter(); +} + +void MachineMonitor :: opcode_picker_close() +{ + if (opcode_picker_active) { + monitor_log("opcode-picker close"); + } + opcode_picker_active = false; + opcode_drawn_rows = 0; + opcode_prefix_len = 0; + opcode_prefix[0] = 0; + opcode_operand_len = 0; + opcode_operand[0] = 0; +} + +void MachineMonitor :: opcode_picker_refilter() +{ + opcode_candidate_count = monitor_collect_opcode_candidates(opcode_prefix, + state.illegal_enabled, + opcode_candidates, + (int)sizeof(opcode_candidates)); + if (opcode_candidate_count <= 0) { + opcode_selected = 0; + opcode_top = 0; + return; + } + if (opcode_selected >= opcode_candidate_count) opcode_selected = opcode_candidate_count - 1; + if (opcode_selected < 0) opcode_selected = 0; + if (opcode_top > opcode_selected) opcode_top = opcode_selected; +} + +void MachineMonitor :: opcode_picker_commit() +{ + if (opcode_candidate_count <= 0) return; + if (opcode_selected < 0 || opcode_selected >= opcode_candidate_count) return; + uint8_t op = opcode_candidates[opcode_selected]; + // Capture the entire previous instruction (up to 3 bytes) so DEL can + // restore the original line wholesale. Push in reverse memory order so + // popping replays the bytes back in low->high order — but order of + // restoration does not matter since each entry is independent. + uint8_t prev_len = disasm_length(state.current_addr); + if (prev_len == 0) prev_len = 1; + if (prev_len > 3) prev_len = 3; + // Snapshot anchor part/pending only on the first entry; all subsequent + // bytes are tagged with part 0 / pending 0 — they're just memory restores + // and the cursor state will be set by the LAST popped (i.e., FIRST pushed) + // entry, which is the highest-offset byte. To keep it simple: only the + // first push (the opcode byte) carries the pre-commit cursor state. + asm_edit_history_push(state.current_addr, canonical_read(state.current_addr), asm_edit_part, asm_edit_pending); + for (uint8_t i = 1; i < prev_len; i++) { + uint16_t a = (uint16_t)(state.current_addr + i); + asm_edit_history_push(a, canonical_read(a), 0, 0); + } + canonical_write(state.current_addr, op); + monitor_log_byte("opcode-picker commit", state.current_addr, op); + uint8_t new_len = disasm_length(state.current_addr); + if (new_len == 0) new_len = 1; + opcode_picker_close(); + if (new_len > 1) { + // Leave the cursor on the (new) operand byte 1 so the user can type + // hex digits into it next. + asm_edit_part = 1; + asm_edit_pending = 0; + } else { + // No operand: advance to next instruction. + disasm_lane_rebuild_suffix_from_current(); + step_disassembly(1); + asm_edit_part = 0; + asm_edit_pending = 0; + asm_edit_history_reset(state.current_addr); + } + ensure_disasm_visible(); +} + +int MachineMonitor :: opcode_picker_handle_key(int key) +{ + if (key == KEY_ESCAPE || key == KEY_BREAK) { + opcode_picker_close(); + draw(); + return 0; + } + if (key == KEY_CTRL_O) { + opcode_picker_close(); + return 1; + } + if (key == KEY_RETURN) { + if (opcode_operand_len > 0) { + if (opcode_picker_commit_typed()) { + draw(); + return 0; + } + } + opcode_picker_commit(); + draw(); + return 0; + } + if (key == KEY_DOWN) { + if (opcode_selected + 1 < opcode_candidate_count) opcode_selected++; + refresh_popup_overlay(); + return 0; + } + if (key == KEY_UP) { + if (opcode_selected > 0) opcode_selected--; + refresh_popup_overlay(); + return 0; + } + if (key == KEY_BACK || key == KEY_DELETE) { + if (opcode_operand_len > 0) { + opcode_operand_len--; + opcode_operand[opcode_operand_len] = 0; + } else if (opcode_prefix_len > 0) { + opcode_prefix_len--; + opcode_prefix[opcode_prefix_len] = 0; + opcode_selected = 0; + opcode_top = 0; + opcode_picker_refilter(); + } else { + opcode_picker_close(); + } + if (opcode_picker_active) { + refresh_popup_overlay(); + } else { + draw(); + } + return 0; + } + + // Mnemonic accumulation: while we have fewer than 3 letters, treat any + // letter (including A-F) as part of the mnemonic prefix. Once the prefix + // is complete the picker switches to operand-typing mode. + bool is_letter = ((key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z')); + if (is_letter && opcode_prefix_len < 3) { + char up = (key >= 'a' && key <= 'z') ? (char)(key - 'a' + 'A') : (char)key; + opcode_prefix[opcode_prefix_len++] = up; + opcode_prefix[opcode_prefix_len] = 0; + opcode_selected = 0; + opcode_top = 0; + opcode_picker_refilter(); + if (opcode_picker_active) { + refresh_popup_overlay(); + } else { + draw(); + } + return 0; + } + + // Operand-typing mode: only available once the mnemonic is complete. + if (opcode_prefix_len == 3) { + if (key == ' ') { + if (opcode_operand_len > 0 && opcode_picker_commit_typed()) { + draw(); + return 0; + } + // SPACE before any operand chars is a no-op (allows "LDA 1000"). + return 0; + } + char up = (key >= 'a' && key <= 'z') ? (char)(key - 'a' + 'A') : (char)key; + bool is_hex = ((up >= '0' && up <= '9') || (up >= 'A' && up <= 'F')); + bool is_xy = (up == 'X' || up == 'Y'); + bool is_punct = (up == '#' || up == '$' || up == '(' || up == ')' || up == ','); + if (is_hex || is_xy || is_punct) { + if (opcode_operand_len < (int)sizeof(opcode_operand) - 1) { + opcode_operand[opcode_operand_len++] = up; + opcode_operand[opcode_operand_len] = 0; + } + refresh_popup_overlay(); + return 0; + } + } + return 0; +} + +bool MachineMonitor :: opcode_picker_commit_typed() +{ + if (opcode_prefix_len != 3) return false; + if (opcode_operand_len <= 0) return false; + + // Build "MNEM operand" string and ask the existing assembler to encode it. + char line[24]; + line[0] = opcode_prefix[0]; + line[1] = opcode_prefix[1]; + line[2] = opcode_prefix[2]; + line[3] = ' '; + int n = 4; + for (int i = 0; i < opcode_operand_len && n < (int)sizeof(line) - 1; i++) { + line[n++] = opcode_operand[i]; + } + line[n] = 0; + + AsmInsn insn; + MonitorError err = MONITOR_OK; + if (!monitor_assemble_line(line, state.illegal_enabled, state.current_addr, &insn, &err)) { + return false; + } + if (insn.length < 1 || insn.length > 3) return false; + + // Capture undo history for the whole previous instruction (up to 3 bytes). + uint8_t prev_len = disasm_length(state.current_addr); + if (prev_len == 0) prev_len = 1; + if (prev_len > 3) prev_len = 3; + asm_edit_history_push(state.current_addr, + canonical_read(state.current_addr), + asm_edit_part, asm_edit_pending); + for (uint8_t i = 1; i < prev_len; i++) { + uint16_t a = (uint16_t)(state.current_addr + i); + asm_edit_history_push(a, canonical_read(a), 0, 0); + } + + for (uint8_t i = 0; i < insn.length; i++) { + canonical_write((uint16_t)(state.current_addr + i), insn.bytes[i]); + } + printf("MCM opcode-typed commit $%04X len %u\n", state.current_addr, (unsigned)insn.length); + + opcode_picker_close(); + disasm_lane_rebuild_suffix_from_current(); + step_disassembly(1); + asm_edit_part = 0; + asm_edit_pending = 0; + asm_edit_history_reset(state.current_addr); + ensure_disasm_visible(); + return true; +} + +void MachineMonitor :: exit_edit_mode() +{ + if (edit_mode) { + monitor_log_address("edit exit", state.current_addr); + } + edit_mode = false; + edit_cursor_visible = true; + pending_hex_nibble = -1; + asm_edit_part = 0; + asm_edit_pending = 0; + asm_edit_history_reset(state.current_addr); +} + +void MachineMonitor :: enter_edit_mode() +{ + help_visible = false; + edit_mode = true; + monitor_log_address("edit enter", state.current_addr); + pending_hex_nibble = -1; + asm_edit_part = 0; + asm_edit_pending = 0; + asm_edit_history_reset(state.current_addr); + reset_edit_blink(); +} + +bool MachineMonitor :: debug_enter() +{ + if (debug.is_active()) { + return true; + } + monitor_log_address("debug enter", state.current_addr); + help_visible = false; + debug_entry_addr = state.current_addr; + DebugSession *session = ensure_debug_session(); + if (session && !session->claim_debug_ownership(screen && screen->prefers_full_refresh())) { + get_ui()->popup("DEBUG IN USE", BUTTON_OK); + redraw_full(); + return false; + } + debug.invalidate_context(); + debug.enter(); + if (restore_debug_after_reset) { + debug_cursor_override = true; + } + // Debug mode reserves two rows above the normal status footer for the CPU + // table. Recompute so all view drawers shrink uniformly. + if (window) { + content_height = window->get_size_y() - 4; + if (content_height < 1) content_height = 1; + } + // Best-effort capture: ask the backend for an immediate snapshot if it + // knows how. Keep an explicitly selected cursor address authoritative: + // the first execution command should run where the user navigated, not + // silently switch to an unrelated live PC snapshot. + DebugContext captured; + debug_entry_context_valid = false; + debug_context_reset(&debug_entry_context); + if (debug_cursor_override) { + debug.invalidate_context(); + } + bool skip_capture = debug_cursor_override && backend && + disassembler_6502_is_illegal(backend->read(state.current_addr)); + if (!restore_debug_after_reset && !skip_capture && debug_capture_context(&captured)) { + debug_entry_context = captured; + debug_entry_context_valid = captured.valid; + if (!debug_cursor_override) { + debug.set_context(captured); + debug_sync_cursor_to_context(); + } + } + return true; +} + +void MachineMonitor :: debug_leave() +{ + if (!debug.is_active()) { + return; + } + monitor_log("debug leave"); + clear_pending_go(); + debug.leave(); + if (restore_debug_after_reset) { + debug.invalidate_context(); + debug_entry_context_valid = false; + debug_context_reset(&debug_entry_context); + } + if (!restore_debug_after_reset) { + debug_cursor_override = false; + } + breakpoint_popup_active = false; + if (window) { + content_height = window->get_size_y() - 2; + if (content_height < 1) content_height = 1; + } + // Restore any patched BRKs / vectors but keep the session object alive + // for the rest of the monitor lifetime. The session destructor in + // deinit() takes care of final teardown. + if (debug_session) { + DebugContext cleanup_context; + const DebugContext *cleanup_target = NULL; + debug_context_reset(&cleanup_context); + if (debug.has_context()) { + cleanup_context = debug.context(); + cleanup_target = &cleanup_context; + } else if (debug_entry_context_valid) { + cleanup_target = &debug_entry_context; + } + debug_session->cleanup_to_context(cleanup_target); + debug_session->release_debug_ownership(); + debug_full_restore_screen(); + // Forget the cached PC so re-entering Debug starts from the monitor + // cursor (where the user navigated) instead of resuming the previous + // session's program counter. + debug_session->forget_context(); + } + // Drop the displayed register context too; re-entry recaptures only if the + // backend can snapshot afresh, otherwise the cursor position drives the + // first step. + debug.invalidate_context(); + debug_entry_context_valid = false; + debug_context_reset(&debug_entry_context); +} + +void MachineMonitor :: debug_sync_cursor_to_context(void) +{ + uint16_t old_addr; + uint16_t pc; + + if (!debug.is_active() || !debug.has_context()) { + return; + } + old_addr = state.current_addr; + pc = debug.context().pc; + if (state.view == MONITOR_VIEW_ASM) { + if (debug_entry_context_valid && pc == disasm_next_addr(debug_entry_context.pc)) { + int entry_row = disasm_visible_row(debug_entry_context.pc); + state.current_addr = pc; + if (entry_row >= 0 && content_height > 0) { + entry_row++; + if (entry_row >= content_height) { + entry_row = content_height - 1; + } + state.disasm_offset = (uint8_t)entry_row; + } + ensure_disasm_visible(); + return; + } + if (pc == disasm_next_addr(old_addr)) { + state.current_addr = pc; + if (content_height > 0 && state.disasm_offset < (uint8_t)(content_height - 1)) { + state.disasm_offset++; + } + ensure_disasm_visible(); + return; + } + if (pc == disasm_prev_addr(old_addr)) { + state.current_addr = pc; + if (state.disasm_offset > 0) { + state.disasm_offset--; + } + ensure_disasm_visible(); + return; + } + state.current_addr = pc; + ensure_debug_pc_visible(); + } else { + state.current_addr = pc; + ensure_current_visible(); + } +} + +void MachineMonitor :: restore_debug_mode_after_reset(void) +{ + if (!restore_debug_after_reset || debug.is_active()) { + return; + } + monitor_log_address("debug restore-after-reset", state.current_addr); + help_visible = false; + debug_entry_addr = state.current_addr; + DebugSession *session = ensure_debug_session(); + if (session && !session->claim_debug_ownership(screen && screen->prefers_full_refresh())) { + restore_debug_after_reset = false; + get_ui()->popup("DEBUG IN USE", BUTTON_OK); + redraw_full(); + return; + } + debug.enter(); + debug.invalidate_context(); + debug_cursor_override = true; + if (window) { + content_height = window->get_size_y() - 4; + if (content_height < 1) content_height = 1; + } +} + +DebugSession *MachineMonitor :: ensure_debug_session() +{ + if (debug_session) { + return debug_session; + } + if (!backend) { + return NULL; + } + debug_session = backend->create_debug_session(); + if (debug_session) { + debug_session->set_cancel_keyboard(keyboard); + debug_session->set_run_window_refreeze_enabled(debug_run_window_refreeze_enabled); + } + return debug_session; +} + +void MachineMonitor :: debug_cleanup_session() +{ + if (debug_session) { + debug_session->cleanup(); + debug_session->release_debug_ownership(); + delete debug_session; + debug_session = NULL; + } +} + +void MachineMonitor :: dispatch_deferred_debug_go(void) +{ + if (!deferred_debug_go_pending) { + return; + } + deferred_debug_go_pending = false; + if (debug_session) { + debug_session->cleanup_to_context(&deferred_debug_go_context); + delete debug_session; + debug_session = NULL; + } + debug_context_reset(&deferred_debug_go_context); + if (backend) { + backend->end_session(); + } +} + +bool MachineMonitor :: debug_capture_context(DebugContext *out) +{ + if (!out) { + return false; + } + debug_context_reset(out); + DebugSession *session = ensure_debug_session(); + if (!session) { + return false; + } + DebugSession::Result r = session->snapshot(out); + return r == DebugSession::DBG_OK; +} + +bool MachineMonitor :: debug_handle_terminal_result(DebugSession::Result result) +{ + if (result != DebugSession::DBG_RESET) { + return false; + } + monitor_log("debug reset-result"); + if (reopen_on_debug_reset) { + request_reopen_after_reset(); + } else { + reopen_after_reset = false; + monitor_reset_reopen_state_valid = false; + monitor_reset_reopen_debug_active = false; + } + clear_pending_go(); + restore_debug_after_reset = reopen_on_debug_reset && debug.is_active(); + if (restore_debug_after_reset) { + debug_cursor_override = true; + } + debug.invalidate_context(); + debug_cleanup_session(); + // Direct render targets (Freeze/Overlay) draw into the live C64 screen via + // `screen`. reset_machine() has just unfrozen + reset the C64, so it now owns + // its screen RAM again: redrawing the monitor here would paint the monitor + // chrome onto the booting C64 screen. These modes exit + reopen, and the + // reopen re-takes ownership before repainting, so skip the redraw here. + // Non-direct hosts (e.g. Telnet) keep their own screen and stay open, so they + // still need the refresh. + if (screen && !reset_exits_monitor) { + get_ui()->set_screen_title(); + redraw_full(); + } + reset_exit_pending = reopen_on_debug_reset ? reset_exits_monitor : true; + reopen_on_debug_reset = true; + return true; +} + +int MachineMonitor :: handle_reset_shortcut(void) +{ + monitor_log("reset shortcut"); + request_reopen_after_reset(); + clear_pending_go(); + help_visible = false; + hunt_picker_active = false; + opcode_picker_active = false; + number_picker_active = false; + bookmark_popup_active = false; + breakpoint_popup_active = false; + exit_edit_mode(); + restore_debug_after_reset = debug.is_active(); + if (restore_debug_after_reset) { + debug_cursor_override = true; + } + if (debug.is_active()) { + debug.invalidate_context(); + } + debug_cleanup_session(); + if (!backend || !backend->supports_reset() || !backend->reset_machine()) { + reopen_after_reset = false; + monitor_reset_reopen_state_valid = false; + get_ui()->popup("RESET UNAVAILABLE", BUTTON_OK); + redraw_full(); + return 0; + } + // See debug_handle_terminal_result(): for direct render targets the C64 owns + // its screen again immediately after reset_machine(), so a redraw here would + // smear the monitor onto the booting C64 screen. The exit + reopen repaints + // with ownership re-taken; only non-direct hosts (Telnet) need this refresh. + if (screen && !reset_exits_monitor) { + get_ui()->set_screen_title(); + redraw_full(); + } + reset_exit_pending = reset_exits_monitor; + return reset_exits_monitor ? MENU_EXIT : 0; +} + +namespace { +static const char *const monitor_debug_session_refused = "DEBUG NOT SUPPORTED"; +static const char *const monitor_debug_session_unsafe = "UNSAFE TARGET"; +static const char *const monitor_debug_session_unsupported_opcode = "UNSUPPORTED OPCODE"; +static const char *const monitor_debug_session_not_in_subroutine = "NOT IN SUBROUTINE"; +static const char *const monitor_debug_session_return_not_reached = "RETURN NOT REACHED"; +static const char *const monitor_debug_session_timeout = "DEBUG TIMEOUT"; +static const char *const monitor_debug_session_patch = "PATCH FAILED"; + +static const char *monitor_debug_result_name(DebugSession::Result result) +{ + switch (result) { + case DebugSession::DBG_OK: return "OK"; + case DebugSession::DBG_NOT_SUPPORTED: return "NOT_SUPPORTED"; + case DebugSession::DBG_REFUSED: return "UNSAFE_TARGET"; + case DebugSession::DBG_UNSUPPORTED_OPCODE: return "UNSUPPORTED_OPCODE"; + case DebugSession::DBG_NOT_IN_SUBROUTINE: return "NOT_IN_SUBROUTINE"; + case DebugSession::DBG_RETURN_NOT_REACHED: return "RETURN_NOT_REACHED"; + case DebugSession::DBG_TIMEOUT: return "TIMEOUT"; + case DebugSession::DBG_CANCELLED: return "CANCELLED"; + case DebugSession::DBG_RESET: return "RESET"; + case DebugSession::DBG_PATCH_FAILED: return "PATCH_FAILED"; + } + return "UNKNOWN"; +} + +static const char *monitor_view_name(MachineMonitorView view) +{ + switch (view) { + case MONITOR_VIEW_HEX: return "HEX"; + case MONITOR_VIEW_ASM: return "ASM"; + case MONITOR_VIEW_ASCII: return "ASCII"; + case MONITOR_VIEW_SCREEN: return "SCREEN"; + case MONITOR_VIEW_BINARY: return "BINARY"; + } + return "UNKNOWN"; +} + +static void monitor_log(const char *action) +{ + printf("MCM %s\n", action); +} + +static void monitor_log_address(const char *action, uint16_t address) +{ + printf("MCM %s $%04X\n", action, address); +} + +static void monitor_log_value(const char *action, uint16_t address, uint16_t value) +{ + printf("MCM %s $%04X=$%04X\n", action, address, value); +} + +static void monitor_log_byte(const char *action, uint16_t address, uint8_t value) +{ + printf("MCM %s $%04X=$%02X\n", action, address, value); +} + +static void monitor_log_range(const char *action, uint16_t start, uint16_t end) +{ + printf("MCM %s $%04X-$%04X\n", action, start, end); +} + +static void monitor_log_debug(const char *action, uint16_t pc, DebugSession::Result result) +{ + printf("MCM debug %s $%04X %s\n", action, pc, monitor_debug_result_name(result)); +} + +static void monitor_read_predict_bytes(DebugSession *session, MemoryBackend *backend, + uint16_t start_pc, uint8_t *bytes) +{ + if (!bytes) { + return; + } + bytes[0] = 0; + bytes[1] = 0; + bytes[2] = 0; + if (session && session->read_step_bytes(start_pc, bytes, 3)) { + return; + } + if (backend) { + for (int i = 0; i < 3; i++) { + bytes[i] = backend->read((uint16_t)(start_pc + i)); + } + } +} + +const char *monitor_debug_result_message(int result) +{ + switch (result) { + case DebugSession::DBG_NOT_SUPPORTED: return monitor_debug_session_refused; + case DebugSession::DBG_REFUSED: return monitor_debug_session_unsafe; + case DebugSession::DBG_UNSUPPORTED_OPCODE: return monitor_debug_session_unsupported_opcode; + case DebugSession::DBG_NOT_IN_SUBROUTINE: return monitor_debug_session_not_in_subroutine; + case DebugSession::DBG_RETURN_NOT_REACHED: return monitor_debug_session_return_not_reached; + case DebugSession::DBG_TIMEOUT: return monitor_debug_session_timeout; + case DebugSession::DBG_CANCELLED: return "DEBUG CANCELLED"; + case DebugSession::DBG_RESET: return NULL; + case DebugSession::DBG_PATCH_FAILED: return monitor_debug_session_patch; + default: return NULL; + } +} +} + +void MachineMonitor :: debug_request_over() +{ + DebugContext from = debug.context(); + bool have_context = from.valid; + uint16_t start_pc = have_context ? from.pc : state.current_addr; + if (!have_context && debug_cursor_override && backend && + disassembler_6502_is_illegal(backend->read(start_pc))) { + monitor_log_debug("over", start_pc, DebugSession::DBG_UNSUPPORTED_OPCODE); + debug.invalidate_context(); + get_ui()->popup(monitor_debug_session_unsupported_opcode, BUTTON_OK); + redraw_full(); + return; + } + DebugSession *session = ensure_debug_session(); + if (!session) { + monitor_log_debug("over", state.current_addr, DebugSession::DBG_NOT_SUPPORTED); + get_ui()->popup(monitor_debug_session_refused, BUTTON_OK); + redraw_full(); + return; + } + // Decode the current instruction so the session knows what to patch. + uint8_t bytes[3] = { 0, 0, 0 }; + monitor_read_predict_bytes(session, backend, start_pc, bytes); + if (disassembler_6502_is_illegal(bytes[0])) { + monitor_log_debug("over", start_pc, DebugSession::DBG_UNSUPPORTED_OPCODE); + debug.invalidate_context(); + debug_cleanup_session(); + get_ui()->popup(monitor_debug_session_unsupported_opcode, BUTTON_OK); + redraw_full(); + return; + } + DebugPredictResult pred; + debug_predict(start_pc, bytes, state.illegal_enabled, &pred); + if (pred.kind == DBG_PREDICT_UNSAFE || pred.kind == DBG_PREDICT_BRK) { + monitor_log_debug("over", start_pc, DebugSession::DBG_REFUSED); + get_ui()->popup(monitor_debug_session_unsafe, BUTTON_OK); + redraw_full(); + return; + } + DebugContext next; + DebugSession::Result r = have_context ? session->over(from, pred, &breakpoints, &next) + : session->over_at(start_pc, pred, &breakpoints, &next); + monitor_log_debug("over", start_pc, r); + debug_full_restore_screen(); + if (r == DebugSession::DBG_OK) { + if (state.view == MONITOR_VIEW_ASM) { + state.current_addr = start_pc; + } + debug.set_context(next); + debug_sync_cursor_to_context(); + } else { + if (debug_handle_terminal_result(r)) { + return; + } + const char *msg = monitor_debug_result_message(r); + if (msg) { + get_ui()->popup(msg, BUTTON_OK); + redraw_full(); + } + } +} + +void MachineMonitor :: debug_request_trace() +{ + DebugContext from = debug.context(); + bool have_context = from.valid; + uint16_t start_pc = have_context ? from.pc : state.current_addr; + if (!have_context && debug_cursor_override && backend && + disassembler_6502_is_illegal(backend->read(start_pc))) { + monitor_log_debug("trace", start_pc, DebugSession::DBG_UNSUPPORTED_OPCODE); + debug.invalidate_context(); + get_ui()->popup(monitor_debug_session_unsupported_opcode, BUTTON_OK); + redraw_full(); + return; + } + DebugSession *session = ensure_debug_session(); + if (!session) { + monitor_log_debug("trace", state.current_addr, DebugSession::DBG_NOT_SUPPORTED); + get_ui()->popup(monitor_debug_session_refused, BUTTON_OK); + redraw_full(); + return; + } + uint8_t bytes[3] = { 0, 0, 0 }; + monitor_read_predict_bytes(session, backend, start_pc, bytes); + if (disassembler_6502_is_illegal(bytes[0])) { + monitor_log_debug("trace", start_pc, DebugSession::DBG_UNSUPPORTED_OPCODE); + debug.invalidate_context(); + debug_cleanup_session(); + get_ui()->popup(monitor_debug_session_unsupported_opcode, BUTTON_OK); + redraw_full(); + return; + } + DebugPredictResult pred; + debug_predict(start_pc, bytes, state.illegal_enabled, &pred); + if (pred.kind == DBG_PREDICT_UNSAFE || pred.kind == DBG_PREDICT_BRK) { + monitor_log_debug("trace", start_pc, DebugSession::DBG_REFUSED); + get_ui()->popup(monitor_debug_session_unsafe, BUTTON_OK); + redraw_full(); + return; + } + DebugContext next; + DebugSession::Result r = have_context ? session->trace(from, pred, &next) + : session->trace_at(start_pc, pred, &next); + monitor_log_debug("trace", start_pc, r); + debug_full_restore_screen(); + if (r == DebugSession::DBG_OK) { + if (state.view == MONITOR_VIEW_ASM) { + state.current_addr = start_pc; + } + debug.set_context(next); + debug_sync_cursor_to_context(); + } else { + if (debug_handle_terminal_result(r)) { + return; + } + const char *msg = monitor_debug_result_message(r); + if (msg) { + get_ui()->popup(msg, BUTTON_OK); + redraw_full(); + } + } +} + +void MachineMonitor :: debug_request_out() +{ + DebugSession *session = ensure_debug_session(); + if (!session) { + monitor_log_debug("out", state.current_addr, DebugSession::DBG_NOT_SUPPORTED); + get_ui()->popup(monitor_debug_session_refused, BUTTON_OK); + redraw_full(); + return; + } + DebugContext from = debug.context(); + if (!from.valid) { + monitor_log_debug("out", state.current_addr, DebugSession::DBG_NOT_IN_SUBROUTINE); + get_ui()->popup(monitor_debug_session_not_in_subroutine, BUTTON_OK); + redraw_full(); + return; + } + DebugContext next; + DebugSession::Result r = session->step_out(from, &breakpoints, &next); + monitor_log_debug("out", from.pc, r); + debug_full_restore_screen(); + if (r == DebugSession::DBG_OK) { + if (state.view == MONITOR_VIEW_ASM) { + state.current_addr = from.pc; + } + debug.set_context(next); + debug_sync_cursor_to_context(); + } else { + if (debug_handle_terminal_result(r)) { + return; + } + const char *msg = monitor_debug_result_message(r); + if (msg) { + get_ui()->popup(msg, BUTTON_OK); + redraw_full(); + } + } +} + +void MachineMonitor :: debug_request_go() +{ + DebugContext from = debug.context(); + if (debug_cursor_override) { + debug_context_reset(&from); + } + if (!from.valid && !debug_cursor_override) { + DebugContext snap; + if (debug_capture_context(&snap)) { + debug.set_context(snap); + from = snap; + } + } + DebugSession *session = ensure_debug_session(); + if (!session) { + // Backend has no native debug session - fall back to the existing + // non-debug `G` semantics (release/jump) so users with a non-stepping + // backend can still resume from the captured / cursor address. + last_go_addr = from.valid ? from.pc : state.current_addr; + last_go_valid = true; + go_pending = true; + go_pending_addr = last_go_addr; + go_pending_has_context = false; + debug.invalidate_context(); + monitor_log_address("debug go fallback", last_go_addr); + return; + } + // Start PC for a fresh Go is the Assembly view cursor: this is what the + // user is looking at and where they expect execution to begin. If a + // captured context is already in hand, the session prefers `from.pc` + // and ignores this fallback. + uint16_t start_pc = state.current_addr; + if (debug_run_window_refreeze_enabled && + !debug_has_enabled_breakpoint() && + from.valid && + session->has_parked_context_handoff()) { + // Freeze-mode parked-context G must let the monitor fully tear down + // and release ownership before the BRK session hands execution back to + // the live machine. Defer that handoff to run_machine_monitor(), which + // calls cleanup_to_context() after deinit() and ownership release. + last_go_addr = from.pc; + last_go_valid = true; + deferred_debug_go_pending = true; + deferred_debug_go_context = from; + release_host_after_exit = true; + clear_pending_go(); + debug.invalidate_context(); + monitor_log_address("debug go deferred", last_go_addr); + return; + } + if ((debug_run_window_refreeze_enabled || reset_exits_monitor) && + !debug_has_enabled_breakpoint()) { + // Direct UI no-breakpoint Go uses the debug session's own parked-spin + // release path, then unwinds through run_machine_monitor() so Freeze + // releases freezer ownership and Overlay disables the render owner + // before execution continues at full speed. + last_go_addr = from.valid ? from.pc : start_pc; + last_go_valid = true; + DebugSession::Result result = session->go(from, &breakpoints, start_pc); + if (debug_handle_terminal_result(result)) { + return; + } + if (result != DebugSession::DBG_OK) { + printf("MCM debug go $%04X %s\n", last_go_addr, + monitor_debug_result_name(result)); + return; + } + release_host_after_exit = true; + clear_pending_go(); + debug.invalidate_context(); + monitor_log_address("debug go handoff", last_go_addr); + return; + } + // Invalidate up-front; G discards the captured context per the spec. + debug.invalidate_context(); + DebugSession::Result r = session->go(from, &breakpoints, start_pc); + monitor_log_debug("go", start_pc, r); + debug_full_restore_screen(); + if (r == DebugSession::DBG_OK) { + // If the session captured a fresh context (BRK fired during this + // Go), `snapshot` now returns it. Pull it back so the footer shows + // the real post-stop state on the next draw. + DebugContext captured; + if (session->snapshot(&captured) == DebugSession::DBG_OK && + captured.valid) { + debug.set_context(captured); + debug_cursor_override = false; + debug_sync_cursor_to_context(); + } + } else { + if (debug_handle_terminal_result(r)) { + return; + } + const char *msg = monitor_debug_result_message(r); + if (msg) { + get_ui()->popup(msg, BUTTON_OK); + redraw_full(); + } + } +} + +void MachineMonitor :: debug_request_cursor() +{ + DebugContext from = debug.context(); + if (!from.valid) { + DebugContext snap; + if (debug_capture_context(&snap)) { + debug.set_context(snap); + from = snap; + } + } + DebugSession *session = ensure_debug_session(); + if (!session) { + monitor_log_debug("cursor", state.current_addr, DebugSession::DBG_NOT_SUPPORTED); + get_ui()->popup(monitor_debug_session_refused, BUTTON_OK); + redraw_full(); + return; + } + uint16_t start_pc = from.valid ? from.pc : debug_entry_addr; + DebugContext next; + DebugSession::Result r = session->run_to(from, state.current_addr, &breakpoints, + start_pc, &next); + monitor_log_debug("cursor", state.current_addr, r); + debug_full_restore_screen(); + if (r == DebugSession::DBG_OK) { + debug.set_context(next); + debug_sync_cursor_to_context(); + } else { + if (debug_handle_terminal_result(r)) { + return; + } + const char *msg = monitor_debug_result_message(r); + if (msg) { + get_ui()->popup(msg, BUTTON_OK); + redraw_full(); + } + } +} + +bool MachineMonitor :: debug_has_breakpoint(void) const +{ + for (int i = 0; i < breakpoints.slot_count(); i++) { + const MonitorBreakpointSlot *bp = breakpoints.get(i); + if (bp && bp->used) { + return true; + } + } + return false; +} + +bool MachineMonitor :: debug_has_enabled_breakpoint(void) const +{ + for (int i = 0; i < breakpoints.slot_count(); i++) { + const MonitorBreakpointSlot *bp = breakpoints.get(i); + if (bp && bp->used && bp->enabled) { + return true; + } + } + return false; +} + +MonitorBackingStore MachineMonitor :: breakpoint_target_for_view(uint16_t address) const +{ + uint8_t view_cpu_port = state.view_cpu_port & 0x07; + + return backend ? backend->backing_store_for_cpu_port(address, view_cpu_port) : + monitor_backing_store_for_cpu_port(address, view_cpu_port); +} + +MonitorBackingStore MachineMonitor :: breakpoint_target_for_live_cpu(uint16_t address) const +{ + uint8_t live_cpu_port = backend ? backend->get_live_cpu_port() : state.view_cpu_port; + + return backend ? backend->backing_store_for_cpu_port(address, live_cpu_port) : + monitor_backing_store_for_cpu_port(address, live_cpu_port); +} + +void MachineMonitor :: show_breakpoint_mapping_note(uint16_t address, + MonitorBackingStore target) +{ + MonitorBackingStore current = breakpoint_target_for_live_cpu(address); + + if (target == current) { + return; + } + char msg[40]; + monitor_format_breakpoint_mismatch(msg, sizeof(msg), target, current); + get_ui()->popup(msg, BUTTON_OK); + redraw_full(); +} + +void MachineMonitor :: debug_toggle_breakpoint() +{ + uint16_t target = state.current_addr; + MonitorBackingStore backing_store = breakpoint_target_for_view(target); + int existing = breakpoints.find_at(target, backing_store); + if (existing >= 0) { + breakpoints.clear_slot(existing); + printf("MCM breakpoint clear %d $%04X\n", existing, target); + return; + } + int slot = breakpoints.allocate(target, (uint8_t)(state.view_cpu_port & 0x07), + backing_store); + if (slot < 0) { + get_ui()->popup("NO FREE BRK SLOT", BUTTON_OK); + redraw_full(); + return; + } + printf("MCM breakpoint set %d $%04X %s\n", slot, target, + monitor_backing_store_tag(backing_store)); + show_breakpoint_mapping_note(target, backing_store); +} + +void MachineMonitor :: debug_open_breakpoint_popup() +{ + breakpoint_popup_active = true; + monitor_log("breakpoint popup open"); + if (breakpoint_selected >= breakpoints.slot_count()) { + breakpoint_selected = 0; + } +} + +void MachineMonitor :: debug_close_breakpoint_popup() +{ + breakpoint_popup_active = false; + monitor_log("breakpoint popup close"); +} + +void MachineMonitor :: edit_breakpoint_label(uint8_t slot) +{ + const MonitorBreakpointSlot *bp = breakpoints.get(slot); + char buffer[MONITOR_BREAKPOINT_LABEL_STORAGE]; + char normalized[MONITOR_BREAKPOINT_LABEL_STORAGE]; + char title[16]; + + if (!bp || !bp->used) { + return; + } + strncpy(buffer, bp->label, sizeof(buffer) - 1); + buffer[sizeof(buffer) - 1] = 0; + sprintf(title, "Label BP%u", (unsigned)slot); + if (prompt_command(title, buffer, MONITOR_BREAKPOINT_LABEL_MAX, false, true)) { + MonitorBreakpoints::normalize_label(normalized, sizeof(normalized), buffer); + breakpoints.set_label(slot, normalized); + printf("MCM breakpoint label %u %s\n", (unsigned)slot, normalized); + } else { + printf("MCM breakpoint label %u cancelled\n", (unsigned)slot); + } +} + +int MachineMonitor :: debug_breakpoint_popup_handle_key(int key) +{ + if (key == KEY_ESCAPE || key == KEY_BREAK || key == KEY_CTRL_R) { + debug_close_breakpoint_popup(); + redraw_full(); + return 0; + } + if (key == KEY_CTRL_O) { + debug_close_breakpoint_popup(); + return 1; + } + if (key == KEY_UP) { + if (breakpoint_selected > 0) breakpoint_selected--; + refresh_popup_overlay(); + return 0; + } + if (key == KEY_DOWN) { + if (breakpoint_selected + 1 < (uint8_t)breakpoints.slot_count()) breakpoint_selected++; + refresh_popup_overlay(); + return 0; + } + if (key >= '0' && key <= '9') { + breakpoint_selected = (uint8_t)(key - '0'); + const MonitorBreakpointSlot *bp = breakpoints.get(breakpoint_selected); + if (bp && bp->used) { + state.view_cpu_port = (uint8_t)(bp->view_cpu_port & 0x07); + if (backend && backend->supports_cpu_banking()) { + backend->set_monitor_cpu_port(state.view_cpu_port); + } + apply_go_local(bp->address); + printf("MCM breakpoint jump %u $%04X\n", (unsigned)breakpoint_selected, bp->address); + debug_close_breakpoint_popup(); + redraw_full(); + } else { + refresh_popup_overlay(); + } + return 0; + } + if (key == KEY_RETURN) { + const MonitorBreakpointSlot *bp = breakpoints.get(breakpoint_selected); + if (bp && bp->used) { + state.view_cpu_port = (uint8_t)(bp->view_cpu_port & 0x07); + if (backend && backend->supports_cpu_banking()) { + backend->set_monitor_cpu_port(state.view_cpu_port); + } + state.current_addr = bp->address; + apply_go_local(bp->address); + printf("MCM breakpoint jump %u $%04X\n", (unsigned)breakpoint_selected, bp->address); + } + debug_close_breakpoint_popup(); + redraw_full(); + return 0; + } + if (key == 's' || key == 'S') { + MonitorBackingStore backing_store = breakpoint_target_for_view(state.current_addr); + breakpoints.store_slot(breakpoint_selected, state.current_addr, + (uint8_t)(state.view_cpu_port & 0x07), + backing_store); + printf("MCM breakpoint store %u $%04X %s\n", + (unsigned)breakpoint_selected, state.current_addr, + monitor_backing_store_tag(backing_store)); + show_breakpoint_mapping_note(state.current_addr, backing_store); + refresh_popup_overlay(); + return 0; + } + if (key == 'l' || key == 'L') { + edit_breakpoint_label(breakpoint_selected); + refresh_popup_overlay(); + return 0; + } + if (key == 'e' || key == 'E') { + const MonitorBreakpointSlot *bp = breakpoints.get(breakpoint_selected); + if (bp && bp->used) { + bool new_enabled = !bp->enabled; + breakpoints.set_enabled(breakpoint_selected, new_enabled); + printf("MCM breakpoint %s %u $%04X\n", new_enabled ? "enable" : "disable", + (unsigned)breakpoint_selected, bp->address); + } + refresh_popup_overlay(); + return 0; + } + if (key == KEY_DELETE || key == KEY_BACK) { + const MonitorBreakpointSlot *bp = breakpoints.get(breakpoint_selected); + if (bp && bp->used) { + printf("MCM breakpoint clear %u $%04X\n", (unsigned)breakpoint_selected, bp->address); + } + breakpoints.clear_slot(breakpoint_selected); + refresh_popup_overlay(); + return 0; + } + return 0; +} + +void MachineMonitor :: debug_render_breakpoint_popup() +{ + enum { + BRK_POPUP_INNER_WIDTH = 38, + BRK_POPUP_INNER_HEIGHT = 14, + BRK_POPUP_SLOT_FIRST_ROW = 2, + BRK_POPUP_HELP_ROW = 13 + }; + if (!window || !screen) { + return; + } + char popup_lines[BRK_POPUP_INNER_HEIGHT][BRK_POPUP_INNER_WIDTH + 1]; + memset(popup_lines, 0, sizeof(popup_lines)); + strcpy(popup_lines[0], "BREAKPOINTS"); + for (int i = 0; i < breakpoints.slot_count(); i++) { + MonitorBreakpoints::format_popup_row(popup_lines[BRK_POPUP_SLOT_FIRST_ROW + i], + sizeof(popup_lines[BRK_POPUP_SLOT_FIRST_ROW + i]), + i, + breakpoints.get(i)); + } + strcpy(popup_lines[BRK_POPUP_HELP_ROW], + "0-9/RET:Jmp S:Set L:Lbl E:Enbl DEL:Res"); + int screen_x, screen_y; + window->getOffsets(screen_x, screen_y); + int popup_x = screen_x + ((window->get_size_x() - BRK_POPUP_INNER_WIDTH) / 2); + int popup_y = screen_y + ((window->get_size_y() - BRK_POPUP_INNER_HEIGHT) / 2); + if (popup_x + (BRK_POPUP_INNER_WIDTH + 2) > 40) { + popup_x = 40 - (BRK_POPUP_INNER_WIDTH + 2); + } + if (popup_x < 0) popup_x = 0; + if (popup_y < screen_y) popup_y = screen_y; + Window popup(screen, popup_x, popup_y, + BRK_POPUP_INNER_WIDTH + 2, BRK_POPUP_INNER_HEIGHT + 2); + popup.set_color(get_ui()->color_fg); + popup.draw_border(); + popup.set_color(get_ui()->color_fg); + for (int row = 0; row < BRK_POPUP_INNER_HEIGHT; row++) { + char line[BRK_POPUP_INNER_WIDTH + 1]; + int len = (int)strlen(popup_lines[row]); + int slot_row = row - BRK_POPUP_SLOT_FIRST_ROW; + bool selected = (slot_row >= 0 && slot_row < breakpoints.slot_count() && + slot_row == (int)breakpoint_selected); + + if (len > BRK_POPUP_INNER_WIDTH) len = BRK_POPUP_INNER_WIDTH; + memset(line, ' ', BRK_POPUP_INNER_WIDTH); + if (len > 0) { + memcpy(line, popup_lines[row], (size_t)len); + } + line[BRK_POPUP_INNER_WIDTH] = 0; + if (selected) { + draw_with_highlight(&popup, row, line, BRK_POPUP_INNER_WIDTH, + 0, BRK_POPUP_INNER_WIDTH); + } else { + popup.move_cursor(0, row); + popup.output_length(line, BRK_POPUP_INNER_WIDTH); + } + } +} + +void MachineMonitor :: ensure_debug_pc_visible(void) +{ + enum { DEBUG_PC_MARGIN = 3 }; + int rows = content_height; + int margin = DEBUG_PC_MARGIN; + + if (state.view != MONITOR_VIEW_ASM) { + return; + } + if (rows <= 1) { + state.base_addr = state.current_addr; + state.disasm_offset = 0; + return; + } + if (margin * 2 >= rows) { + margin = (rows - 1) / 2; + } + state.disasm_offset = (uint8_t)margin; + ensure_disasm_visible(); +} + +int MachineMonitor :: debug_handle_key(int key) +{ + if (breakpoint_popup_active) { + return debug_breakpoint_popup_handle_key(key); + } + // Exit Debug shortcuts. ESC / RUN/STOP drop Debug only once Edit has + // already been left by the outer edit-mode handler. + if (key == KEY_ESCAPE || key == KEY_BREAK || key == KEY_CTRL_D) { + debug_leave(); + draw(); + return 0; + } + if (key == KEY_CTRL_O) { + // Leaving the monitor. debug_leave() -> session cleanup() hands the + // parked CPU back to the interrupted program (overlay: resumed live; + // freeze: staged for when the freezer menu unfreezes). No deferred + // go-handoff is scheduled, so the C64 is never left spinning. + debug_leave(); + return 1; + } + // RETURN remains Assembly subroutine navigation. We handle it here only + // to forward to the existing follow_current/return_current logic; the + // outer dispatcher will not see this key. + if (key == KEY_RETURN && state.view == MONITOR_VIEW_ASM && !edit_mode) { + if (follow_current() || return_current()) { + draw(); + } + return 0; + } + if (key == KEY_CTRL_R) { + debug_open_breakpoint_popup(); + draw(); + return 0; + } + if (key == 'r' || key == 'R') { + debug_toggle_breakpoint(); + draw(); + return 0; + } + if (key == 'd' || key == 'D') { + debug_request_over(); + if (reset_exit_pending) { + return MENU_EXIT; + } + draw(); + return 0; + } + if (key == 't' || key == 'T') { + debug_request_trace(); + if (reset_exit_pending) { + return MENU_EXIT; + } + draw(); + return 0; + } + if (key == 'u' || key == 'U') { + // Debug-mode Step Out. This deliberately overrides the Assembly-view + // undocumented-opcode toggle that 'U' performs outside Debug. 'O'/'o' + // are left to fall through to the normal dispatcher so the monitor + // view CPU bank can still be cycled while Debug is active. + debug_request_out(); + if (reset_exit_pending) { + return MENU_EXIT; + } + draw(); + return 0; + } + if (key == 'g' || key == 'G') { + debug_request_go(); + if (reset_exit_pending) { + return MENU_EXIT; + } + if (go_pending || release_host_after_exit) { + return 1; + } + draw(); + return 0; + } + if (key == 'k' || key == 'K') { + debug_request_cursor(); + if (reset_exit_pending) { + return MENU_EXIT; + } + draw(); + return 0; + } + // Any other key falls through to the normal monitor dispatcher so the + // user can still navigate, switch views, edit, etc. while Debug is on. + return -1; +} + +void MachineMonitor :: init(Screen *scr, Keyboard *keyb) +{ + int line_length; + int height; + + screen = scr; + keyboard = keyb; + + line_length = screen->get_size_x(); + height = screen->get_size_y() - 3; + + window = new Window(screen, 0, 2, line_length, height); + window->draw_border(); + window->set_color(get_ui()->color_fg); + content_height = window->get_size_y() - 2; + backend->begin_session(); + // After a C64 hardware reset, the next fresh open follows the live CPU bank so + // the user re-enters at the memory the CPU actually sees (RAM-under-ROM when + // $01 low bits are 5), not a stale/forced view -> fixes the C5O7 mismatch. + // Skipped when restoring an in-flight debug session, whose carried view bank + // is the authoritative debug-context bank. + if (monitor_sync_view_to_live_on_open) { + monitor_sync_view_to_live_on_open = false; + if (!restore_debug_after_reset && backend->supports_cpu_banking()) { + state.view_cpu_port = (uint8_t)(backend->get_live_cpu_port() & 0x07); + } + } + state.view_cpu_port = normalize_cpu_mode(state.view_cpu_port); + if (backend->supports_cpu_banking()) { + backend->set_monitor_cpu_port(state.view_cpu_port); + } + current_vic_bank = backend->supports_vic_bank() ? backend->get_live_vic_bank() : 0; + if (bookmarks) { + bookmarks->ensure_loaded((uint8_t)(state.view_cpu_port & 0x07), (uint8_t)(current_vic_bank & 0x03)); + } + last_live_vic_bank = current_vic_bank; + vic_bank_override = false; + apply_go_local(state.current_addr); + debug_cursor_override = false; + restore_debug_mode_after_reset(); + draw(); +} + +void MachineMonitor :: deinit(void) +{ + monitor_saved_state.view = state.view; + monitor_saved_state.current_addr = state.current_addr; + monitor_saved_state.base_addr = state.base_addr; + monitor_saved_state.disasm_offset = 0; + monitor_saved_state.illegal_enabled = state.illegal_enabled; + monitor_saved_state.screen_charset = normalize_screen_charset(state.screen_charset); + monitor_saved_state.view_cpu_port = state.view_cpu_port; + monitor_saved_state_valid = true; + monitor_last_load_use_prg = last_load_use_prg; + monitor_last_load_start = last_load_start; + monitor_last_load_offset = last_load_offset; + monitor_last_load_length_auto = last_load_length_auto; + monitor_last_load_length = last_load_length; + monitor_last_save_start = last_save_start; + monitor_last_save_end = last_save_end; + strncpy(monitor_last_save_name, last_save_name, sizeof(monitor_last_save_name) - 1); + monitor_last_save_name[sizeof(monitor_last_save_name) - 1] = 0; + monitor_last_go_valid = last_go_valid; + monitor_last_go_addr = last_go_addr; + monitor_memory_bytes_per_row = memory_bytes_per_row; + monitor_binary_bytes_per_row = binary_bytes_per_row; + // Persist breakpoints to process-lifetime storage so the next monitor + // open (including the C=+X reset reentry) recovers the same table. + // Power-off discards this because the storage is volatile RAM. + monitor_saved_breakpoints = breakpoints; + // Restore every patched byte / vector / trampoline before the backend + // session ends. Cleanup is idempotent so this is safe even if the user + // never used Debug mode. + if (!deferred_debug_go_pending) { + debug_cleanup_session(); + backend->end_session(); + } + if (clipboard.data) { + free(clipboard.data); + clipboard.data = NULL; + } + clipboard.length = 0; + if (window) { + delete window; + window = NULL; + } + if (bookmarks) { + delete bookmarks; + bookmarks = NULL; + } +} + +int MachineMonitor :: handle_key(int key) +{ + char buffer[96]; + char output[4096]; + uint16_t start, end, dest, address, value16; + uint8_t byte_value, needle[MONITOR_HUNT_NEEDLE_MAX]; + int needle_len; + MonitorError error; + + if (key == KEY_CTRL_X) { + return handle_reset_shortcut(); + } + if (key == KEY_CTRL_I) { + return swap_interface_type ? swap_interface_type(get_ui()) : MENU_NOP; + } + + if (hunt_picker_active) { + return hunt_picker_handle_key(key); + } + if (bookmark_popup_active) { + return bookmark_popup_handle_key(key); + } + if (opcode_picker_active) { + return opcode_picker_handle_key(key); + } + if (number_picker_active) { + return number_picker_handle_key(key); + } + if (breakpoint_popup_active) { + return debug_breakpoint_popup_handle_key(key); + } + + dismiss_bookmark_status(); + + if (key == KEY_HELP || key == KEY_F3) { + toggle_help(); + draw(); + return 0; + } + if (help_visible) { + // Any other key dismisses the help overlay first, then continues to + // execute as a normal monitor command (so e.g. pressing H from the + // help screen actually launches Hunt instead of leaving help open). + help_visible = false; + if (key == KEY_ESCAPE || monitor_key_is_bookmark_action(key)) { + draw(); + return 0; + } + } + + // Debug mode owns the D/T/O/G/R/C=+R/C=+D/ESC keys when active. RETURN + // routes through the debug controller too so subroutine navigation is + // preserved as documented. Anything the debug controller does not handle + // returns -1 so the main dispatcher can still service navigation / + // view-switch / file commands while Debug is on. + if (debug.is_active() && !edit_mode) { + int r = debug_handle_key(key); + if (r != -1) { + return r; + } + } else if (!edit_mode && (key == 'd' || key == 'D')) { + // D outside Debug mode enters Debug. In edit mode 'D' is a hex digit + // or part of an assembly mnemonic, so the gate above keeps edit-mode + // semantics intact. + if (state.view != MONITOR_VIEW_ASM) { + set_view(MONITOR_VIEW_ASM); + } + if (debug_enter()) { + draw(); + } + return 0; + } + if (!edit_mode && key == KEY_CTRL_R && debug_has_breakpoint()) { + debug_open_breakpoint_popup(); + draw(); + return 0; + } + + if (bookmark_shortcut_allowed()) { + if (monitor_bookmark_main_slot_for_key(key) >= 0) { + restore_bookmark((uint8_t)monitor_bookmark_main_slot_for_key(key)); + draw(); + return 0; + } + } + // The bookmark popup is its own navigation mode and is therefore reachable + // from both VIEW and EDIT mode of the underlying monitor view. + if (bookmark_set_shortcut_allowed() && monitor_key_is_bookmark_popup(key)) { + bookmark_popup_active = true; + bookmark_selected = 0; + monitor_log("bookmark popup open"); + draw(); + return 0; + } + if (key == KEY_CTRL_C) { + bool copied; + if (range_mode) { + copied = clipboard_copy_range(); + if (copied) { + range_mode = false; + } + } else { + copied = clipboard_copy_current(); + } + if (!copied) { + get_ui()->popup("?MEM", BUTTON_OK); + redraw_full(); + } + draw(); + return 0; + } + if (key == KEY_CTRL_V) { + if (!clipboard_paste()) { + get_ui()->popup("?CLIP", BUTTON_OK); + redraw_full(); + } + draw(); + return 0; + } + if ((key == 'r' || key == 'R') && range_shortcut_allowed()) { + help_visible = false; + toggle_range_mode(); + draw(); + return 0; + } + if (!edit_mode && (key == 'p' || key == 'P')) { + help_visible = false; + if (screen && screen->prefers_full_refresh()) { + get_ui()->popup("POLL MODE UNAVAILABLE OVER TELNET", BUTTON_OK); + redraw_full(); + return 0; + } + poll_mode = !poll_mode; + reset_poll_deadline(); + draw(); + return 0; + } + if ((key == 'n' || key == 'N') && number_shortcut_allowed()) { + open_number_picker(); + draw(); + return 0; + } + if (!edit_mode && state.view == MONITOR_VIEW_ASM && key == KEY_RETURN) { + if (follow_current() || return_current()) { + draw(); + } + return 0; + } + + if (edit_mode) { + if (key == KEY_CTRL_O) { + return 1; + } + if (debug.is_active() && key == KEY_CTRL_D) { + debug_leave(); + exit_edit_mode(); + draw(); + return 0; + } + if (debug.is_active() && (key == KEY_BREAK || key == KEY_ESCAPE)) { + exit_edit_mode(); + draw(); + return 0; + } + if (key == KEY_BREAK || key == KEY_ESCAPE || key == KEY_CTRL_E) { + exit_edit_mode(); + draw(); + return 0; + } + if (key == KEY_BACK || key == KEY_DELETE) { + // ASM: undo the last typed character on this line first; only + // when nothing has been typed on the current instruction does + // DEL fall through to the unified logical delete (NOP-replace + // and advance to the next line). + if (state.view == MONITOR_VIEW_ASM && asm_edit_history_pop()) { + draw(); + return 0; + } + // HEX: a half-typed nibble on the current byte is rolled back + // first; otherwise the byte itself is cleared. + if (state.view == MONITOR_VIEW_HEX && pending_hex_nibble >= 0) { + pending_hex_nibble = -1; + draw(); + return 0; + } + apply_logical_delete(); + if (state.view == MONITOR_VIEW_ASM) { + asm_edit_history_reset(state.current_addr); + } + draw(); + return 0; + } + if (state.view == MONITOR_VIEW_BINARY) { + // Sprite/character editing input mapping. `*` and `1` set a bit; + // `.`, `0`, and SPACE clear a bit. Anything else is ignored. + if (key == '1' || key == '*') { + binary_apply_bit(1); + draw(); + return 0; + } + if (key == '0' || key == '.' || key == ' ') { + binary_apply_bit(0); + draw(); + return 0; + } + } + if (state.view == MONITOR_VIEW_HEX && is_hex_char((char)key)) { + if (key >= '0' && key <= '9') { + apply_hex_digit((uint8_t)(key - '0')); + } else { + apply_hex_digit((uint8_t)(to_upper_char((char)key) - 'A' + 10)); + } + draw(); + return 0; + } + if (state.view == MONITOR_VIEW_ASCII) { + uint8_t value; + + if (monitor_ascii_key_to_byte(key, &value)) { + apply_ascii_char((char)value); + draw(); + return 0; + } + } + if (state.view == MONITOR_VIEW_SCREEN) { + uint8_t value; + + if (monitor_screen_key_to_code(key, state.screen_charset, &value)) { + apply_screen_char((char)value); + draw(); + return 0; + } + } + if (state.view == MONITOR_VIEW_ASM) { + uint8_t insn_len = disasm_length(state.current_addr); + if (insn_len == 0) insn_len = 1; + uint8_t part_count = asm_edit_part_count(state.current_addr); + bool branch = asm_is_branch(state.current_addr) && insn_len == 2; + if (asm_edit_part >= part_count) asm_edit_part = 0; + if (key == KEY_LEFT) { + if (asm_edit_part > 0) { + asm_edit_part--; + } else { + step_disassembly(-1); + uint8_t prev_parts = asm_edit_part_count(state.current_addr); + asm_edit_part = (prev_parts > 0) ? (uint8_t)(prev_parts - 1) : 0; + asm_edit_history_reset(state.current_addr); + } + asm_edit_pending = 0; + draw(); + return 0; + } + if (key == KEY_RIGHT) { + if (asm_edit_part + 1 < part_count) { + asm_edit_part++; + } else { + step_disassembly(1); + asm_edit_part = 0; + asm_edit_history_reset(state.current_addr); + } + asm_edit_pending = 0; + draw(); + return 0; + } + if (key == KEY_UP) { + step_disassembly(-1); + asm_edit_part = 0; + asm_edit_pending = 0; + asm_edit_history_reset(state.current_addr); + draw(); + return 0; + } + if (key == KEY_DOWN) { + step_disassembly(1); + asm_edit_part = 0; + asm_edit_pending = 0; + asm_edit_history_reset(state.current_addr); + draw(); + return 0; + } + if (asm_edit_part > 0 && is_hex_char((char)key)) { + uint8_t nib = (key >= '0' && key <= '9') ? (uint8_t)(key - '0') + : (uint8_t)(to_upper_char((char)key) - 'A' + 10); + uint8_t prev_part = asm_edit_part; + uint8_t prev_pending = asm_edit_pending; + if (branch) { + // Branch: virtual two-byte target ($hh$ll) backed by a + // single signed offset at mem+1. Compute the new target + // byte from the typed nibble, derive the new offset, and + // only write if it still fits in -128..127. + uint16_t rel_addr = (uint16_t)(state.current_addr + 1); + uint8_t prev_rel = canonical_read(rel_addr); + uint16_t target = (uint16_t)(state.current_addr + 2 + (int8_t)prev_rel); + uint8_t hi = (uint8_t)(target >> 8); + uint8_t lo = (uint8_t)(target & 0xFF); + uint8_t *byte = (asm_edit_part == 1) ? &hi : &lo; + if (asm_edit_pending == 0) { + *byte = (uint8_t)((nib << 4) | (*byte & 0x0F)); + } else { + *byte = (uint8_t)((*byte & 0xF0) | nib); + } + uint16_t new_target = (uint16_t)((hi << 8) | lo); + int32_t offset = (int32_t)new_target - (int32_t)(state.current_addr + 2); + if (offset < -128 || offset > 127) { + // Out of range — refuse the edit (do not corrupt the offset). + draw(); + return 0; + } + asm_edit_history_push(rel_addr, prev_rel, prev_part, prev_pending); + canonical_write(rel_addr, (uint8_t)(offset & 0xFF)); + if (asm_edit_pending == 0) { + asm_edit_pending = 1; + } else { + asm_edit_pending = 0; + if (asm_edit_part + 1 < part_count) { + asm_edit_part++; + } else { + step_disassembly(1); + asm_edit_part = 0; + asm_edit_history_reset(state.current_addr); + } + } + draw(); + return 0; + } + // Map display-order parts to memory-order offsets: + // 2-byte insn: part 1 -> +1 + // 3-byte insn: part 1 -> +2 (high byte, displayed first) + // part 2 -> +1 (low byte, displayed second) + uint8_t mem_off; + if (insn_len == 3) { + mem_off = (asm_edit_part == 1) ? 2 : 1; + } else { + mem_off = 1; + } + uint16_t byte_addr = (uint16_t)(state.current_addr + mem_off); + uint8_t prev_byte = canonical_read(byte_addr); + if (asm_edit_pending == 0) { + canonical_write(byte_addr, (uint8_t)((nib << 4) | (prev_byte & 0x0F))); + asm_edit_history_push(byte_addr, prev_byte, prev_part, prev_pending); + asm_edit_pending = 1; + } else { + canonical_write(byte_addr, (uint8_t)((prev_byte & 0xF0) | nib)); + asm_edit_history_push(byte_addr, prev_byte, prev_part, prev_pending); + asm_edit_pending = 0; + uint8_t new_parts = asm_edit_part_count(state.current_addr); + if (asm_edit_part + 1 < new_parts) { + asm_edit_part++; + } else { + step_disassembly(1); + asm_edit_part = 0; + asm_edit_history_reset(state.current_addr); + } + } + draw(); + return 0; + } + if (asm_edit_part == 0 && ((key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z'))) { + opcode_picker_open((char)key); + draw(); + return 0; + } + } + } + + if (!edit_mode) { + if (key == KEY_SPACE) { + key = KEY_F7; + } else if (key == KEY_SHIFT_SP) { + key = KEY_F1; + } + } + + switch (key) { + case KEY_BACK: + case KEY_DELETE: + apply_logical_delete(); + draw(); + return 0; + case KEY_LEFT: + if (state.view == MONITOR_VIEW_BINARY) { + move_binary_bits(-1); + } else { + move_current(-1); + } + draw(); + return 0; + case KEY_RIGHT: + if (state.view == MONITOR_VIEW_BINARY) { + move_binary_bits(1); + } else { + move_current(1); + } + draw(); + return 0; + case KEY_UP: + if (state.view == MONITOR_VIEW_DISASM) { + step_disassembly(-1); + draw(); + return 0; + } + move_current(-row_span()); + draw(); + return 0; + case KEY_DOWN: + if (state.view == MONITOR_VIEW_DISASM) { + step_disassembly(1); + draw(); + return 0; + } + move_current(row_span()); + draw(); + return 0; + case KEY_PAGEUP: + case KEY_F1: + case KEY_F2: + case KEY_CONFIG: + if (state.view == MONITOR_VIEW_DISASM) { + page_disassembly(-content_height); + draw(); + return 0; + } + page_move(-content_height); + draw(); + return 0; + case KEY_PAGEDOWN: + case KEY_F7: + if (state.view == MONITOR_VIEW_DISASM) { + page_disassembly(content_height); + draw(); + return 0; + } + page_move(content_height); + draw(); + return 0; + default: + break; + } + + switch (key) { + case 'm': case 'M': + help_visible = false; + set_view(MONITOR_VIEW_HEX); + break; + case 'i': case 'I': + help_visible = false; + set_view(MONITOR_VIEW_ASCII); + break; + case 'a': case 'A': + help_visible = false; + set_view(MONITOR_VIEW_ASM); + break; + case 's': case 'S': + help_visible = false; + handle_save_command(); + break; + case 'l': case 'L': + help_visible = false; + handle_load_command(); + break; + case 'v': case 'V': + help_visible = false; + set_view(MONITOR_VIEW_SCREEN); + break; + case 'b': case 'B': + help_visible = false; + set_view(MONITOR_VIEW_BINARY); + break; + case 'w': case 'W': + handle_width_command(); + break; + case 'z': case 'Z': + help_visible = false; + if (backend && backend->freeze_available()) { + backend->set_frozen(!backend->is_frozen()); + printf("MCM freeze %s\n", backend->is_frozen() ? "on" : "off"); + } else { + get_ui()->popup((backend && backend->supports_freeze()) ? + "FREEZE ONLY IN OVERLAY MODE" : "FREEZE UNAVAILABLE", BUTTON_OK); + redraw_full(); + } + break; + case 'o': { + int asm_row = (state.view == MONITOR_VIEW_ASM) ? disasm_visible_row(state.current_addr) : -1; + if (backend && !backend->supports_cpu_banking()) { + get_ui()->popup("CPU BANK UNAVAILABLE", BUTTON_OK); + redraw_full(); + break; + } + state.view_cpu_port = next_cpu_mode(state.view_cpu_port); + backend->set_monitor_cpu_port(state.view_cpu_port); + printf("MCM cpu-bank $%02X\n", state.view_cpu_port); + if (state.view == MONITOR_VIEW_ASM) { + restore_disasm_cursor_row(asm_row); + } + break; + } + case 'O': + { + uint8_t requested_vic_bank = next_vic_bank(current_vic_bank); + uint8_t live_vic_bank; + + if (backend && !backend->supports_vic_bank()) { + get_ui()->popup("VIC BANK UNAVAILABLE", BUTTON_OK); + redraw_full(); + break; + } + backend->set_live_vic_bank(requested_vic_bank); + live_vic_bank = backend->get_live_vic_bank(); + current_vic_bank = requested_vic_bank; + last_live_vic_bank = live_vic_bank; + vic_bank_override = (live_vic_bank != requested_vic_bank); + printf("MCM vic-bank %u live %u\n", (unsigned)requested_vic_bank, (unsigned)live_vic_bank); + break; + } + case 'u': case 'U': + if (state.view == MONITOR_VIEW_ASM) { + state.illegal_enabled = !state.illegal_enabled; + printf("MCM undoc %s\n", state.illegal_enabled ? "on" : "off"); + } else if (state.view == MONITOR_VIEW_SCREEN) { + state.screen_charset = (state.screen_charset == MONITOR_SCREEN_CHARSET_LOWER_UPPER) ? + MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS : + MONITOR_SCREEN_CHARSET_LOWER_UPPER; + printf("MCM screen-charset %u\n", (unsigned)state.screen_charset); + } else { + get_ui()->popup("UNDOC IN ASM, CASE IN SCR", BUTTON_OK); + redraw_full(); + } + break; + case '?': + toggle_help(); + break; + case 'x': case 'X': + case KEY_CTRL_O: + case KEY_BREAK: + case KEY_ESCAPE: + return 1; + case 'j': case 'J': + { + char jump_buffer[5]; + strcpy(jump_buffer, "AAAA"); + while (prompt_command("Jump AAAA", jump_buffer, 4, true)) { + if (!monitor_normalize_jump_input(jump_buffer)) { + get_ui()->popup("HEX 0-9/A-F ONLY", BUTTON_OK); + redraw_full(); + continue; + } + error = monitor_parse_address(jump_buffer, &address); + if (error == MONITOR_OK) { + apply_go_local(address); + monitor_log_address("jump", address); + } else { + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + } + break; + } + break; + } + case 'e': case 'E': + if (inline_edit_supported()) { + enter_edit_mode(); + } + break; + case 'f': case 'F': + { + char fill_buffer[13]; + strcpy(fill_buffer, "AAAA-BBBB,DD"); + if (prompt_command("Fill AAAA-BBBB,DD", fill_buffer, sizeof(fill_buffer), true)) { + error = monitor_parse_fill(fill_buffer, &start, &end, &byte_value); + if (error == MONITOR_OK) { + monitor_log_range("fill", start, end); + printf("MCM fill-value $%02X\n", byte_value); + monitor_fill_memory(backend, start, end, byte_value); + } else { + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + } + } + break; + } + case 't': case 'T': + { + char transfer_buffer[25]; + bool relocate = false; + uint16_t reloc_start = 0; + uint16_t reloc_end = 0; + strcpy(transfer_buffer, "AAAA-BBBB,CCCC"); + if (prompt_command("Transfer AAAA-BBBB,CCCC[,DDDD-EEEE]", transfer_buffer, sizeof(transfer_buffer), true)) { + error = monitor_parse_transfer_relocate(transfer_buffer, &start, &end, &dest, + &relocate, &reloc_start, &reloc_end); + if (error == MONITOR_OK) { + printf("MCM transfer $%04X-$%04X->$%04X\n", start, end, dest); + if (relocate) { + printf("MCM transfer-relocate $%04X-$%04X\n", reloc_start, reloc_end); + monitor_transfer_memory_relocate(backend, start, end, dest, reloc_start, reloc_end); + } else { + monitor_transfer_memory(backend, start, end, dest); + } + } else { + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + } + } + break; + } + case 'c': case 'C': + { + char compare_buffer[15]; + strcpy(compare_buffer, "AAAA-BBBB,CCCC"); + if (prompt_command("Compare AAAA-BBBB,CCCC", compare_buffer, sizeof(compare_buffer), true)) { + error = monitor_parse_compare(compare_buffer, &start, &end, &dest); + if (error == MONITOR_OK) { + int found = monitor_compare_collect(backend, start, end, dest, + hunt_addrs, (int)(sizeof(hunt_addrs) / sizeof(hunt_addrs[0]))); + printf("MCM compare $%04X-$%04X->$%04X found %d\n", start, end, dest, found); + if (found <= 0) { + get_ui()->popup("No differences", BUTTON_OK); + } else { + hunt_picker_open_labeled(found, "Compare results"); + } + } else { + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + } + } + break; + } + case 'h': case 'H': + strcpy(buffer, "0000-FFFF, "); + if (prompt_hunt_command("Hunt AAAA-BBBB,...", buffer, sizeof(buffer) - 1)) { + error = monitor_parse_hunt(buffer, &start, &end, needle, &needle_len); + if (error == MONITOR_OK) { + int found = monitor_hunt_collect(backend, start, end, needle, needle_len, + hunt_addrs, (int)(sizeof(hunt_addrs) / sizeof(hunt_addrs[0]))); + printf("MCM hunt $%04X-$%04X len %d found %d\n", start, end, needle_len, found); + if (found <= 0) { + get_ui()->popup("No matches", BUTTON_OK); + } else { + hunt_picker_open(found); + } + } else { + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + } + } + break; + case 'g': case 'G': + if (handle_go_command()) { + return 1; + } + break; + default: + break; + } + draw(); + return 0; +} + +int MachineMonitor :: poll(int) +{ + int key; + bool status_changed = false; + + if (reopen_after_reset && reset_exits_monitor) { + return MENU_EXIT; + } + if (!keyboard) { + return MENU_CLOSE; + } + key = keyboard->getch(); + key = get_ui()->keymapper(key, e_keymap_monitor); + if (key == -1) { + if (bookmark_popup_active || opcode_picker_active) { + return 0; + } + if (debug.is_active() && debug_session) { + debug_session->refresh_debug_ownership(); + } + uint16_t now = getMsTimer(); + bool redraw = false; + + status_changed = update_bookmark_status(); + if (update_edit_blink()) { + redraw = true; + } + if (poll_mode && monitor_deadline_reached(poll_deadline, now)) { + poll_deadline = (uint16_t)(now + next_poll_interval_ms()); + redraw = true; + } + if (backend->supports_vic_bank()) { + uint8_t vic_bank = backend->get_live_vic_bank(); + if (vic_bank != last_live_vic_bank) { + last_live_vic_bank = vic_bank; + if (!vic_bank_override || vic_bank == current_vic_bank) { + current_vic_bank = vic_bank; + vic_bank_override = false; + } + status_changed = true; + } + } + if (redraw) { + draw(); + } else if (status_changed) { + draw_status(); + if (screen) { + screen->sync(); + } + } + return 0; + } + if (key == -2) { + return MENU_CLOSE; + } + return handle_key(key); +} + +void MachineMonitor::handle_load_command() +{ + char path_buf[256] = ""; + char name_buf[64] = ""; + if (!monitor_io::pick_file(get_ui(), "LOAD: select file", path_buf, sizeof(path_buf), + name_buf, sizeof(name_buf), false)) { + redraw_full(); + return; + } + redraw_full(); + if (!name_buf[0]) { + return; + } + + // Default prompt is the canonical "PRG,0000,AUTO" — RETURN performs a + // standard PRG load. Last-used values are remembered if the user + // overrode anything in a previous invocation. Empty / partial entries + // fall back to defaults inside monitor_parse_load_params. + char buffer[40]; + if (last_load_use_prg) { + strcpy(buffer, "PRG,"); + } else { + sprintf(buffer, "%04X,", last_load_start); + } + char tail[24]; + sprintf(tail, "%04X,", last_load_offset); + strcat(buffer, tail); + if (last_load_length_auto) { + strcat(buffer, "AUTO"); + } else { + sprintf(tail, "%X", (unsigned)last_load_length); + strcat(buffer, tail); + } + if (!prompt_command("Load [PRG|AAAA],[Off],[Len|AUTO]", buffer, sizeof(buffer) - 1, true)) { + redraw_full(); + return; + } + + bool use_prg = true; + uint16_t start_addr = 0; + uint16_t offset = 0; + bool length_auto = true; + uint32_t length = 0; + MonitorError error = monitor_parse_load_params(buffer, &use_prg, &start_addr, + &offset, &length_auto, &length); + if (error != MONITOR_OK) { + redraw_full(); + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + redraw_full(); + return; + } + + last_load_use_prg = use_prg; + if (!use_prg) { + last_load_start = start_addr; + } + last_load_offset = offset; + last_load_length_auto = length_auto; + last_load_length = length; + printf("MCM load %s start $%04X offset $%04X len %u\n", + use_prg ? "PRG" : "RAW", start_addr, offset, (unsigned)length); + + const char *err = monitor_io::load_into_memory(path_buf, name_buf, backend, + start_addr, use_prg, + offset, length_auto, length, + &start_addr, &length); + redraw_full(); + if (err) { + printf("MCM load failed %s\n", err); + get_ui()->popup(err, BUTTON_OK); + redraw_full(); + return; + } + printf("MCM load ok $%04X len %u\n", start_addr, (unsigned)length); + show_io_confirmation("LOAD", name_buf, start_addr, length); + redraw_full(); +} + +void MachineMonitor::handle_save_command() +{ + // Prompt for the memory range FIRST, so the user is not left wondering + // what range the picker is about to write — and so we can short-circuit + // before opening the picker on an obviously invalid range. + char range_buf[16]; + sprintf(range_buf, "%04X-%04X", last_save_start, last_save_end); + if (!prompt_command("Save AAAA-BBBB", range_buf, sizeof(range_buf) - 1, true)) { + return; + } + uint16_t start = 0; + uint16_t end = 0; + MonitorError error = monitor_parse_save_params(range_buf, &start, &end); + if (error != MONITOR_OK) { + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + redraw_full(); + return; + } + last_save_start = start; + last_save_end = end; + monitor_log_range("save range", start, end); + + char path_buf[256] = ""; + char name_buf[64] = ""; + if (!monitor_io::pick_file(get_ui(), "SAVE: pick file/dir", path_buf, sizeof(path_buf), + name_buf, sizeof(name_buf), true)) { + redraw_full(); + return; + } + redraw_full(); + + if (!name_buf[0]) { + // Picker returned a directory-only save target; ask for the filename. + if (last_save_name[0]) { + strncpy(name_buf, last_save_name, sizeof(name_buf) - 1); + name_buf[sizeof(name_buf) - 1] = 0; + } else { + name_buf[0] = 0; + } + if (!prompt_command("Save as", name_buf, sizeof(name_buf) - 1, false)) { + return; + } + if (!name_buf[0]) { + return; + } + } + strncpy(last_save_name, name_buf, sizeof(last_save_name) - 1); + last_save_name[sizeof(last_save_name) - 1] = 0; + + const char *err = monitor_io::save_from_memory(get_ui(), path_buf, name_buf, backend, start, end); + redraw_full(); + if (err) { + printf("MCM save failed %s\n", err); + get_ui()->popup(err, BUTTON_OK); + redraw_full(); + return; + } + uint32_t bytes = (uint32_t)end - (uint32_t)start + 1; + printf("MCM save ok $%04X-$%04X len %u\n", start, end, (unsigned)bytes); + show_io_confirmation("SAVE", name_buf, start, bytes); + redraw_full(); +} + +void MachineMonitor::show_io_confirmation(const char *op, const char *name, + uint16_t start_addr, uint32_t bytes) +{ + char line1[40]; + char line2[40]; + char msg[96]; + uint32_t end_addr = (uint32_t)start_addr + (bytes ? bytes - 1 : 0); + if (end_addr > 0xFFFF) end_addr = 0xFFFF; + format_confirmation_name_line(line1, op, name); + sprintf(line2, "$%04X-$%04X (%u bytes)", + (unsigned)start_addr, (unsigned)end_addr, (unsigned)bytes); + sprintf(msg, "%s\n%s", line1, line2); + get_ui()->popup(msg, BUTTON_OK); +} + +void MachineMonitor::handle_width_command() +{ + if (state.view == MONITOR_VIEW_HEX) { + memory_bytes_per_row = (memory_byte_stride() == MONITOR_MEMORY_MIN_BYTES_PER_ROW) ? + MONITOR_MEMORY_MAX_BYTES_PER_ROW : MONITOR_MEMORY_MIN_BYTES_PER_ROW; + printf("MCM width memory %u\n", (unsigned)memory_bytes_per_row); + ensure_current_visible(); + draw(); + return; + } + if (state.view != MONITOR_VIEW_BINARY) { + get_ui()->popup("WIDTH ONLY IN MEMORY/BINARY VIEW", BUTTON_OK); + redraw_full(); + return; + } + + switch (binary_bytes_per_row) { + case 1: + binary_bytes_per_row = 2; + break; + case 2: + binary_bytes_per_row = 3; + break; + case 3: + binary_bytes_per_row = MONITOR_BINARY_SPRITE_MODE_MARKER; + break; + case MONITOR_BINARY_SPRITE_MODE_MARKER: + binary_bytes_per_row = 4; + break; + default: + binary_bytes_per_row = 1; + break; + } + + binary_bit_index = 7; + printf("MCM width binary %u\n", (unsigned)binary_bytes_per_row); + ensure_current_visible(); + draw(); +} + +bool MachineMonitor :: consume_pending_go(uint16_t *address, DebugContext *context, + bool *has_context) +{ + if (!go_pending) { + return false; + } + if (address) { + *address = go_pending_addr; + } + if (context) { + *context = go_pending_context; + } + if (has_context) { + *has_context = go_pending_has_context; + } + clear_pending_go(); + return true; +} + +void MachineMonitor :: clear_pending_go(void) +{ + go_pending = false; + go_pending_addr = 0; + go_pending_has_context = false; + debug_context_reset(&go_pending_context); +} + +bool MachineMonitor::handle_go_command() +{ + char buffer[8]; + uint16_t default_addr = last_go_valid ? last_go_addr : state.current_addr; + if (backend && !backend->supports_go()) { + get_ui()->popup("GO UNAVAILABLE", BUTTON_OK); + redraw_full(); + return false; + } + sprintf(buffer, "%04X", default_addr); + if (!prompt_command("Go AAAA", buffer, sizeof(buffer) - 1, true)) { + return false; + } + uint16_t address = 0; + MonitorError error = monitor_parse_address(buffer, &address); + if (error != MONITOR_OK) { + get_ui()->popup(monitor_error_text(error), BUTTON_OK); + return false; + } + last_go_addr = address; + last_go_valid = true; + // Reposition the cursor first (mirrors J), so the displayed address matches + // what we are about to execute. + apply_go_local(address); + go_pending = true; + go_pending_addr = address; + monitor_log_address("go", address); + return true; +} diff --git a/software/monitor/machine_monitor.h b/software/monitor/machine_monitor.h new file mode 100644 index 000000000..67d7017cf --- /dev/null +++ b/software/monitor/machine_monitor.h @@ -0,0 +1,497 @@ +#ifndef MACHINE_MONITOR_H +#define MACHINE_MONITOR_H + +#include + +#include "ui_elements.h" +#include "memory_backend.h" +#include "monitor_bookmarks.h" +#include "monitor_breakpoints.h" +#include "monitor_debug.h" +#include "monitor_debug_session.h" + +enum MonitorError { + MONITOR_OK = 0, + MONITOR_ADDR, + MONITOR_SYNTAX, + MONITOR_VALUE, + MONITOR_RANGE +}; + +enum MachineMonitorView { + MONITOR_VIEW_HEX = 0, + MONITOR_VIEW_ASM, + MONITOR_VIEW_ASCII, + MONITOR_VIEW_SCREEN, + MONITOR_VIEW_BINARY +}; + +enum MonitorScreenCharset { + MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS = 0, + MONITOR_SCREEN_CHARSET_LOWER_UPPER = 1 +}; + +enum { + MONITOR_MEMORY_MIN_BYTES_PER_ROW = 8, + MONITOR_MEMORY_MAX_BYTES_PER_ROW = 16, + MONITOR_BINARY_MIN_BYTES_PER_ROW = 1, + MONITOR_BINARY_MAX_BYTES_PER_ROW = 4, + MONITOR_BINARY_SPRITE_MODE_MARKER = 0xFE, +}; + +// Backwards-compat alias for prior internal code/tests. +#define MONITOR_VIEW_DISASM MONITOR_VIEW_ASM + +enum { + MONITOR_HEX_BYTES_PER_ROW = 8, + MONITOR_TEXT_BYTES_PER_ROW = 32, + MONITOR_MEMORY_ROW_8_CHARS = 37, + MONITOR_MEMORY_ROW_16_CHARS = 38, + MONITOR_HEX_ROW_CHARS = 37, + MONITOR_TEXT_ROW_CHARS = 4 + 1 + MONITOR_TEXT_BYTES_PER_ROW, + MONITOR_DISASM_ROW_CHARS = 38, + MONITOR_DISASM_SOURCE_COL = 30, + MONITOR_DISASM_TEXT_COL = 15, + MONITOR_HUNT_NEEDLE_MAX = 80, +}; + +struct MachineMonitorState +{ + MachineMonitorView view; + uint16_t current_addr; + uint16_t base_addr; + uint8_t disasm_offset; + bool illegal_enabled; + uint8_t screen_charset; + uint8_t view_cpu_port; +}; + +struct Clipboard { + uint8_t *data; + size_t length; +}; + +struct Cursor { + uint16_t address; + uint8_t bit_index; // 7 = MSB, 0 = LSB +}; + +const char *monitor_error_text(MonitorError error); +void monitor_reset_saved_state(void); +void monitor_invalidate_saved_state(void); +void monitor_reset_saved_cpu_view(void); +void monitor_apply_go(MachineMonitorState *state, uint16_t address); +void monitor_format_hex_row(uint16_t address, const uint8_t *bytes, char *out); +void monitor_format_text_row(uint16_t address, const uint8_t *bytes, int count, bool screen_codes, char *out); +void monitor_format_status_line(char *out, uint8_t view_cpu_port, uint8_t vic_bank); +void monitor_format_status_line(char *out, uint8_t view_cpu_port, uint8_t live_cpu_port, + uint8_t vic_bank); +void monitor_format_breakpoint_mismatch(char *out, int out_len, + MonitorBackingStore target, + MonitorBackingStore current); + +MonitorError monitor_parse_address(const char *text, uint16_t *address); +MonitorError monitor_parse_expression(const char *text, uint16_t *value); +MonitorError monitor_parse_byte_value(const char *text, uint8_t *value); +MonitorError monitor_parse_fill(const char *text, uint16_t *start, uint16_t *end, uint8_t *value); +MonitorError monitor_parse_transfer(const char *text, uint16_t *start, uint16_t *end, uint16_t *dest); +MonitorError monitor_parse_transfer_relocate(const char *text, uint16_t *start, uint16_t *end, + uint16_t *dest, bool *relocate, + uint16_t *reloc_start, uint16_t *reloc_end); +MonitorError monitor_parse_compare(const char *text, uint16_t *start, uint16_t *end, uint16_t *dest); +MonitorError monitor_parse_hunt(const char *text, uint16_t *start, uint16_t *end, uint8_t *needle, int *needle_len); + +// Convert a printable host character to its monitor screen-code representation. +// Returns the screen code, or 0xFF for chars that have no useful mapping. +uint8_t monitor_screen_code_for_char(char c, + uint8_t screen_charset = MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS); + +void monitor_fill_memory(MemoryBackend *backend, uint16_t start, uint16_t end, uint8_t value); +void monitor_transfer_memory(MemoryBackend *backend, uint16_t start, uint16_t end, uint16_t dest); +void monitor_transfer_memory_relocate(MemoryBackend *backend, uint16_t start, uint16_t end, + uint16_t dest, uint16_t reloc_start, uint16_t reloc_end); +int monitor_compare_memory(MemoryBackend *backend, uint16_t start, uint16_t end, uint16_t dest, char *out, int out_len); +int monitor_hunt_memory(MemoryBackend *backend, uint16_t start, uint16_t end, const uint8_t *needle, int needle_len, char *out, int out_len); +int monitor_hunt_collect(MemoryBackend *backend, uint16_t start, uint16_t end, const uint8_t *needle, int needle_len, uint16_t *out_addrs, int max_addrs); +int monitor_compare_collect(MemoryBackend *backend, uint16_t start, uint16_t end, uint16_t dest, uint16_t *out_addrs, int max_addrs); + +MonitorError monitor_format_evaluate(const char *input, char *out, int out_len); + +// LOAD/SAVE parameter parsers. Used by the monitor and exercised by host tests. +// Load template: "PRG,0000,AUTO" — field 1 is "PRG" (use embedded load address) +// or a 4-hex start address; field 2 is a 4-hex offset; field 3 is "AUTO" or a +// hex length up to 0x10000. +MonitorError monitor_parse_load_params(const char *text, bool *use_prg_addr, uint16_t *start_addr, + uint16_t *offset, bool *length_auto, uint32_t *length); + +// Save template: "0800-9FFF" — start-end hex range, inclusive. Range size must +// be in (0, 65536]. +MonitorError monitor_parse_save_params(const char *text, uint16_t *start, uint16_t *end); + +// Validate a requested load against the actual file size and the 64K limit. +// Returns the effective number of bytes to read in *effective_len. +MonitorError monitor_validate_load_size(uint32_t file_size, uint32_t offset, bool length_auto, + uint32_t length, uint32_t *effective_len); + +class UserInterface; +class Screen; +class Keyboard; +class Window; +class MonitorBookmarks; + +class MachineMonitor : public UIObject +{ + MemoryBackend *backend; + MachineMonitorState state; + bool last_load_use_prg; + uint16_t last_load_start; + uint16_t last_load_offset; + bool last_load_length_auto; + uint32_t last_load_length; + uint16_t last_save_start; + uint16_t last_save_end; + char last_save_name[40]; + bool last_go_valid; + uint16_t last_go_addr; + bool go_pending; + uint16_t go_pending_addr; + bool go_pending_has_context; + DebugContext go_pending_context; + uint8_t memory_bytes_per_row; + uint8_t binary_bytes_per_row; + Clipboard clipboard; + + Screen *screen; + Keyboard *keyboard; + Window *window; + int content_height; + int pending_hex_nibble; + bool edit_mode; + bool poll_mode; + uint16_t poll_deadline; + uint8_t poll_fraction; + bool edit_cursor_visible; + bool help_visible; + bool range_mode; + uint16_t range_anchor; + bool number_picker_active; + int number_selected; + uint16_t number_preview_value; + uint8_t number_base_bytes[2]; + bool number_word; + int number_edit_length; + char number_edit_buffer[17]; + bool number_expr_active; + bool number_expr_word; + int number_expr_length; + char number_expr_buffer[25]; + char number_expr_status[8]; + int number_popup_x; + int number_popup_y; + uint16_t number_target_addr; + uint8_t number_target_bytes; + bool number_target_locked; + bool hunt_picker_active; + int hunt_count; + int hunt_selected; + int hunt_top; + uint16_t hunt_addrs[256]; + const char *hunt_picker_label; + uint8_t asm_edit_part; + uint8_t asm_edit_pending; + enum { ASM_LANE_MAX_ROWS = 256 }; + mutable bool asm_lane_valid; + mutable uint8_t asm_lane_view_cpu_port; + mutable bool asm_lane_illegal_enabled; + mutable uint16_t asm_lane_rows[ASM_LANE_MAX_ROWS]; + mutable uint8_t asm_lane_lengths[ASM_LANE_MAX_ROWS]; + mutable uint8_t asm_lane_forced_bytes[ASM_LANE_MAX_ROWS]; + mutable int asm_lane_count; + mutable int asm_lane_top; + mutable int asm_lane_selected; + // Per-instruction undo trail used by DEL in ASM edit mode. Each slot + // captures the byte we are about to overwrite so DEL can restore it. + enum { ASM_EDIT_HISTORY_MAX = 16 }; + uint16_t asm_edit_hist_addr[ASM_EDIT_HISTORY_MAX]; + uint8_t asm_edit_hist_byte[ASM_EDIT_HISTORY_MAX]; + uint8_t asm_edit_hist_part[ASM_EDIT_HISTORY_MAX]; + uint8_t asm_edit_hist_pending[ASM_EDIT_HISTORY_MAX]; + int asm_edit_hist_len; + uint16_t asm_edit_hist_anchor_addr; + bool opcode_picker_active; + char opcode_prefix[4]; + int opcode_prefix_len; + uint8_t opcode_candidates[256]; + int opcode_candidate_count; + int opcode_selected; + int opcode_top; + int opcode_drawn_rows; + // Direct-typing operand buffer used while the picker is open. Allows + // power users to type "LDA 1000" or "LDA #FF" or "LDA (10),Y" without + // having to navigate the picker. Empty when not in operand-typing mode. + char opcode_operand[16]; + int opcode_operand_len; + uint8_t current_vic_bank; + uint8_t last_live_vic_bank; + bool vic_bank_override; + MonitorBookmarks *bookmarks; + MonitorDebug debug; + MonitorBreakpoints breakpoints; + class DebugSession *debug_session; + bool debug_cursor_override; + bool debug_entry_context_valid; + DebugContext debug_entry_context; + uint16_t debug_entry_addr; + bool debug_run_window_refreeze_enabled; + bool reset_exits_monitor; + bool reset_exit_pending; + bool release_host_after_exit; + bool reopen_after_reset; + bool reopen_on_debug_reset; + bool restore_debug_after_reset; + bool deferred_debug_go_pending; + DebugContext deferred_debug_go_context; + bool breakpoint_popup_active; + uint8_t breakpoint_selected; + bool bookmark_popup_active; + uint8_t bookmark_selected; + char bookmark_status_text[40]; + bool bookmark_status_visible; + bool bookmark_status_emphasis; + uint16_t bookmark_status_deadline; + struct ReturnStackEntry { + MonitorBookmarkSlot location; + uint16_t base_addr; + uint8_t disasm_offset; + }; + ReturnStackEntry return_stack[10]; + uint8_t return_stack_count; + // Cursor bit-position within the current byte in BINARY view. + // 7 = MSB (leftmost rendered bit), 0 = LSB. Horizontal navigation and + // typed 0/1 edits advance by one bit. + uint8_t binary_bit_index; +#ifdef RUNS_ON_PC + uint8_t edit_blink_polls; +#else + uint16_t edit_blink_ms; +#endif + + uint8_t canonical_read(uint16_t address); + void canonical_write(uint16_t address, uint8_t value); + void read_row(uint16_t address, uint8_t *dst, uint16_t len) const; + uint8_t memory_byte_stride(void) const; + uint8_t binary_byte_stride(void) const; + int memory_row_chars(void) const; + int memory_hex_column(int byte_offset) const; + void apply_go_local(uint16_t address); + bool number_shortcut_allowed(void) const; + bool range_shortcut_allowed(void) const; + bool bookmark_shortcut_allowed(void) const; + bool bookmark_set_shortcut_allowed(void) const; + void draw(); + void draw_header(); + void draw_status(); + void draw_help(); + void draw_popup_overlays(); + void draw_bookmark_popup(); + void draw_number_picker(); + void refresh_popup_overlay(); + void draw_hex(); + void draw_ascii(); + void draw_screen_codes(); + void draw_disassembly(); + void draw_binary(); + void draw_binary_row(int y, uint16_t addr, const uint8_t *bytes, int byte_count); + // Re-paint border + entire content. Used after a sub-dialog (file picker, + // confirmation popup, ...) that may have stomped over our window. + void redraw_full(); + void draw_hunt_picker(); + void hunt_picker_open(int count); + void hunt_picker_open_labeled(int count, const char *label); + void hunt_picker_close(); + void hunt_picker_jump(); + int hunt_picker_handle_key(int key); + void draw_opcode_picker(); + void opcode_picker_open(char seed); + void opcode_picker_close(); + void opcode_picker_refilter(); + void opcode_picker_commit(); + bool opcode_picker_commit_typed(); + int opcode_picker_handle_key(int key); + void draw_hex_row(int y, uint16_t address, const uint8_t *bytes); + void draw_text_row(int y, uint16_t address, const uint8_t *bytes, bool screen_codes); + void ensure_current_visible(); + void set_view(MachineMonitorView view); + void move_current(int delta); + void move_binary_bits(int delta); + void page_move(int lines); + Cursor active_cursor(void) const; + bool range_contains(uint16_t address) const; + bool clipboard_copy_bytes(const uint8_t *data, size_t length); + bool clipboard_copy_current(void); + bool clipboard_copy_range(void); + bool clipboard_copy_byte(uint8_t value); + bool clipboard_paste(void); + void toggle_range_mode(void); + void open_number_picker(void); + void number_picker_resolve_target(void); + void number_picker_reset_edit_buffer(void); + void number_picker_refresh_preview_from_memory(void); + void number_picker_update_preview_from_buffer(void); + void number_picker_set_row(int row); + void number_picker_place_popup(void); + void number_picker_anchor(int *x, int *y) const; + uint16_t number_picker_current_addr(void) const; + uint8_t number_picker_current_bytes(void) const; + void number_picker_commit(void); + bool number_picker_copy_preview(void); + void number_picker_open_expression(void); + void number_picker_open_expression(char op); + void number_picker_close_expression(void); + void number_picker_expression_set_status(const char *status); + MonitorError number_picker_evaluate_expression(uint16_t *value) const; + int number_picker_handle_key(int key); + bool prompt_command(const char *title, char *buffer, int max_len, + bool template_mode = false, bool uppercase = true); + bool prompt_hunt_command(const char *title, char *buffer, int max_len); + void toggle_help(); + bool debug_active(void) const { return debug.is_active(); } + bool debug_input_active(void) const { return debug.is_active() || breakpoint_popup_active; } + int debug_handle_key(int key); + bool debug_enter(void); + void debug_leave(void); + void debug_sync_cursor_to_context(void); + bool debug_handle_terminal_result(DebugSession::Result result); + void debug_request_over(void); + void debug_request_trace(void); + void debug_request_out(void); + void debug_request_go(void); + void debug_request_cursor(void); + bool debug_has_breakpoint(void) const; + bool debug_has_enabled_breakpoint(void) const; + MonitorBackingStore breakpoint_target_for_view(uint16_t address) const; + MonitorBackingStore breakpoint_target_for_live_cpu(uint16_t address) const; + void show_breakpoint_mapping_note(uint16_t address, MonitorBackingStore target); + void debug_toggle_breakpoint(void); + void debug_open_breakpoint_popup(void); + void edit_breakpoint_label(uint8_t slot); + int debug_breakpoint_popup_handle_key(int key); + void debug_close_breakpoint_popup(void); + void debug_render_breakpoint_popup(void); + void ensure_debug_pc_visible(void); + void debug_cleanup_session(void); + void restore_debug_mode_after_reset(void); + DebugSession *ensure_debug_session(void); + bool debug_capture_context(DebugContext *out); + int handle_reset_shortcut(void); + void clear_pending_go(void); + // After a freeze-mode debug step the firmware chrome rows (UI title and + // border lines) are overwritten by the live BASIC screen. Call this after + // any step that may have been in freeze mode: it re-establishes the chrome + // via set_screen_title() and redraws the monitor window via redraw_full() + // when the active debug session indicates the render target was invalidated. + // No-op in overlay mode because overlay sessions disable freeze/refreeze + // run windows. + void debug_full_restore_screen(void); + void restore_underlying_status_row(void); + void draw_debug_footer(void); + void dismiss_bookmark_status(void); + bool update_bookmark_status(void); + void show_bookmark_status(uint8_t slot, const MonitorBookmarkSlot *bookmark, int kind); + void show_navigation_status(uint8_t index, const char *kind, uint16_t address); + void clear_bookmark_transient_state(void); + void capture_bookmark(MonitorBookmarkSlot *bookmark) const; + bool restore_location(const MonitorBookmarkSlot *bookmark); + bool restore_return_location(const ReturnStackEntry *entry); + bool restore_bookmark(uint8_t slot); + uint8_t return_stack_push_current(void); + bool return_stack_pop(ReturnStackEntry *entry, uint8_t *index); + bool target_visible(uint16_t target) const; + void follow_to_target(uint16_t target); + bool follow_target(uint16_t *target); + bool follow_current(void); + bool return_current(void); + void set_bookmark(uint8_t slot); + void edit_bookmark_label(uint8_t slot); + int bookmark_popup_handle_key(int key); + int handle_key(int key); + void handle_load_command(); + void handle_save_command(); + // Display a confirmation overlay summarizing a completed LOAD/SAVE + // (filename, byte range, byte count) and wait for the user to dismiss it. + void show_io_confirmation(const char *op, const char *name, + uint16_t start_addr, uint32_t bytes); + // Returns true when the monitor should exit (e.g., GOTO has dispatched a + // DMA jump and the C64 must now resume executing user code). + bool handle_go_command(); + // Prompt to change the binary view's bytes-per-row (1..4) on the fly. + // No-op (with informative popup) outside of BINARY view. + void handle_width_command(); + // Apply a typed bit (0 or 1) to the byte at the cursor at binary_bit_index. + void binary_apply_bit(uint8_t bit_value); + void enter_edit_mode(); + void commit_pending_hex_nibble(void); + void apply_hex_digit(uint8_t value); + void apply_ascii_char(char value); + void apply_screen_char(char value); + void apply_logical_delete(); + void asm_edit_history_reset(uint16_t anchor_addr); + void asm_edit_history_push(uint16_t addr, uint8_t prev_byte, uint8_t prev_part, uint8_t prev_pending); + bool asm_edit_history_pop(); + void exit_edit_mode(); + void reset_edit_blink(); + bool update_edit_blink(); + uint16_t next_poll_interval_ms(void); + void reset_poll_deadline(void); + uint8_t disasm_length(uint16_t address) const; + void disasm_lane_invalidate(void); + void disasm_lane_reset(uint16_t address); + void disasm_lane_ensure(void) const; + void disasm_lane_extend_forward_to(int index) const; + void disasm_lane_sync_state(void); + uint8_t disasm_lane_length_at(int index) const; + uint16_t disasm_lane_next_addr_at(int index) const; + void disasm_lane_append(uint16_t address, uint8_t forced_length) const; + void disasm_lane_prepend(uint16_t address, uint8_t forced_length); + bool disasm_lane_prepend_previous(void); + void disasm_lane_rebuild_suffix_from_current(void); + void disasm_visible_addresses(uint16_t *rows, uint8_t *lengths, int count) const; + bool disasm_same_source(uint16_t a, uint16_t b) const; + bool disasm_crosses_source_boundary(uint16_t start, uint16_t end) const; + bool disasm_is_io_source(uint16_t address) const; + bool disasm_explicitly_targets(uint16_t candidate, uint16_t address) const; + bool disasm_find_prev_addr(uint16_t address, uint16_t *previous) const; + bool asm_is_branch(uint16_t address); + uint8_t asm_edit_part_count(uint16_t address); + void disasm_position_current_at_row(int row); + uint16_t disasm_next_addr(uint16_t address) const; + uint16_t disasm_prev_addr(uint16_t address) const; + uint16_t disasm_prev_visible_addr(uint16_t address); + int disasm_visible_row(uint16_t address) const; + uint16_t disasm_advance_rows(uint16_t address, int rows); + uint16_t disasm_rewind_rows(uint16_t address, int rows); + void restore_disasm_cursor_row(int row); + void step_disassembly(int lines); + void page_disassembly(int lines); + void ensure_disasm_visible(); + bool inline_edit_supported(void) const; + uint16_t row_span(void) const; + +public: + MachineMonitor(UserInterface *ui, MemoryBackend *backend); + void set_debug_run_window_refreeze_enabled(bool enabled); + void set_reset_exits_monitor(bool enabled); + bool consume_release_host_after_exit(void); + bool has_deferred_debug_go(void) const { return deferred_debug_go_pending; } + void dispatch_deferred_debug_go(void); + void request_reopen_after_reset(void); + void request_debug_reset_cancel(void); + bool consume_reopen_after_reset(void); + void init(Screen *screen, Keyboard *keyboard); + void deinit(void); + int poll(int); + bool consume_pending_go(uint16_t *address, DebugContext *context = 0, + bool *has_context = 0); +}; + +#endif diff --git a/software/monitor/memory_backend.h b/software/monitor/memory_backend.h new file mode 100644 index 000000000..487fa3a46 --- /dev/null +++ b/software/monitor/memory_backend.h @@ -0,0 +1,153 @@ +#ifndef MEMORY_BACKEND_H +#define MEMORY_BACKEND_H + +#include "integer.h" + +class DebugSession; + +enum MonitorBackingStore { + MONITOR_BACKING_RAM = 0, + MONITOR_BACKING_BASIC, + MONITOR_BACKING_KERNAL, + MONITOR_BACKING_IO, + MONITOR_BACKING_CHAR +}; + +static inline MonitorBackingStore monitor_backing_store_for_cpu_port(uint16_t address, uint8_t cpu_port) +{ + cpu_port &= 0x07; + + if (address >= 0xA000 && address <= 0xBFFF) { + return ((cpu_port & 0x03) == 0x03) ? + MONITOR_BACKING_BASIC : MONITOR_BACKING_RAM; + } + if (address >= 0xD000 && address <= 0xDFFF) { + if ((cpu_port & 0x03) == 0x00) { + return MONITOR_BACKING_RAM; + } + return (cpu_port & 0x04) ? MONITOR_BACKING_IO : MONITOR_BACKING_CHAR; + } + if (address >= 0xE000) { + return (cpu_port & 0x02) ? MONITOR_BACKING_KERNAL : MONITOR_BACKING_RAM; + } + return MONITOR_BACKING_RAM; +} + +static inline const char *monitor_backing_store_tag(MonitorBackingStore target) +{ + switch (target) { + case MONITOR_BACKING_BASIC: return "BAS"; + case MONITOR_BACKING_KERNAL: return "KRN"; + case MONITOR_BACKING_IO: return "I/O"; + case MONITOR_BACKING_CHAR: return "CHR"; + case MONITOR_BACKING_RAM: + default: return "RAM"; + } +} + +static inline const char *monitor_backing_store_source_name(MonitorBackingStore target) +{ + switch (target) { + case MONITOR_BACKING_BASIC: return "BASIC"; + case MONITOR_BACKING_KERNAL: return "KERNAL"; + case MONITOR_BACKING_IO: return "IO"; + case MONITOR_BACKING_CHAR: return "CHAR"; + case MONITOR_BACKING_RAM: + default: return "RAM"; + } +} + +static inline bool monitor_backing_store_is_visible_rom(MonitorBackingStore target) +{ + return target == MONITOR_BACKING_BASIC || + target == MONITOR_BACKING_KERNAL || + target == MONITOR_BACKING_CHAR; +} + +class MemoryBackend +{ + uint8_t monitor_cpu_port; +public: + MemoryBackend() : monitor_cpu_port(0x07) { } + virtual ~MemoryBackend() { } + + virtual uint8_t read(uint16_t address) = 0; + virtual void write(uint16_t address, uint8_t value) = 0; + virtual void begin_session(void) { } + virtual void end_session(void) { } + + virtual void read_block(uint16_t address, uint8_t *dst, uint16_t len) + { + while (len) { + *dst++ = read(address++); + len--; + } + } + + // Freeze / pause control. Backends that can hold the host machine in a + // stopped state across many reads/writes (so register/IO state is stable) + // override these. The monitor exposes a Z toggle to drive this. Default + // behaviour is a no-op so non-U64 backends remain unaffected. + virtual bool supports_freeze(void) const { return false; } + virtual bool freeze_available(void) const { return supports_freeze(); } + virtual bool is_frozen(void) const { return false; } + virtual void set_frozen(bool) { } + virtual bool supports_cpu_banking(void) const { return true; } + virtual bool supports_vic_bank(void) const { return true; } + virtual bool supports_go(void) const { return true; } + virtual bool supports_reset(void) const { return false; } + virtual bool reset_machine(void) { return false; } + virtual uint8_t monitor_poll_hz(void) const { return 50; } + + // Stepping / breakpoint / re-entry support. Backends that cannot + // resume-and-trap the live CPU return NULL; Debug-mode key handling then + // surfaces a clear refusal instead of silently faking results. The + // returned object is owned by the caller. + virtual DebugSession *create_debug_session(void) { return 0; } + + virtual void set_monitor_cpu_port(uint8_t value) + { + monitor_cpu_port = value & 0x07; + } + + virtual uint8_t get_monitor_cpu_port(void) const + { + return monitor_cpu_port & 0x07; + } + + virtual uint8_t get_live_cpu_port(void) + { + return read(0x0001) & 0x07; + } + + virtual MonitorBackingStore backing_store_for_cpu_port(uint16_t address, uint8_t cpu_port) const + { + return monitor_backing_store_for_cpu_port(address, cpu_port); + } + + virtual uint8_t get_live_vic_bank(void) + { + // CIA2 stores the VIC bank in inverted form; keep the monitor's + // user-facing VIC0..VIC3 numbering aligned with the visible base. + return (uint8_t)(3 - (read(0xDD00) & 0x03)); + } + + virtual void set_live_vic_bank(uint8_t vic_bank) + { + uint8_t saved_cpu_port = get_monitor_cpu_port(); + uint8_t dd00; + + set_monitor_cpu_port(0x07); + dd00 = read(0xDD00); + write(0xDD00, (uint8_t)((dd00 & 0xFC) | (uint8_t)(3 - (vic_bank & 0x03)))); + set_monitor_cpu_port(saved_cpu_port); + } + + virtual const char *source_name(uint16_t address) const + { + return monitor_backing_store_source_name( + backing_store_for_cpu_port(address, get_monitor_cpu_port())); + } +}; + +#endif diff --git a/software/monitor/monitor_bookmarks.cc b/software/monitor/monitor_bookmarks.cc new file mode 100644 index 000000000..151046533 --- /dev/null +++ b/software/monitor/monitor_bookmarks.cc @@ -0,0 +1,726 @@ +#include "monitor_bookmarks.h" +#include "config.h" + +extern "C" int sprintf(char *out, const char *fmt, ...); + +namespace { + +enum { + MONITOR_BOOKMARKS_STORE_ID = 0x4D424D4B, + MONITOR_BOOKMARKS_SCHEMA_VERSION = 1, + MONITOR_BOOKMARK_CFG_SCHEMA = 1, + MONITOR_BOOKMARK_CFG_SLOT0, + MONITOR_BOOKMARK_CFG_SLOT1, + MONITOR_BOOKMARK_CFG_SLOT2, + MONITOR_BOOKMARK_CFG_SLOT3, + MONITOR_BOOKMARK_CFG_SLOT4, + MONITOR_BOOKMARK_CFG_SLOT5, + MONITOR_BOOKMARK_CFG_SLOT6, + MONITOR_BOOKMARK_CFG_SLOT7, + MONITOR_BOOKMARK_CFG_SLOT8, + MONITOR_BOOKMARK_CFG_SLOT9, +}; + +struct MonitorBookmarkDefault { + uint16_t address; + uint8_t view; + const char *label; +}; + +static const MonitorBookmarkDefault kMonitorBookmarkDefaults[MONITOR_BOOKMARK_SLOT_COUNT] = { + { 0x0000, MONITOR_BOOKMARK_VIEW_HEX, "ZP" }, + { 0x0400, MONITOR_BOOKMARK_VIEW_SCREEN, "SCREEN" }, + { 0x0801, MONITOR_BOOKMARK_VIEW_ASM, "BASIC" }, + { 0xA000, MONITOR_BOOKMARK_VIEW_ASM, "BASROM" }, + { 0xC000, MONITOR_BOOKMARK_VIEW_ASM, "HIRAM" }, + { 0xD000, MONITOR_BOOKMARK_VIEW_HEX, "VIC" }, + { 0xD400, MONITOR_BOOKMARK_VIEW_HEX, "SID" }, + { 0xDC00, MONITOR_BOOKMARK_VIEW_BINARY, "CIA1" }, + { 0xDD00, MONITOR_BOOKMARK_VIEW_BINARY, "CIA2" }, + { 0xE000, MONITOR_BOOKMARK_VIEW_ASM, "KERNAL" }, +}; + +static const t_cfg_definition monitor_bookmark_cfg[] = { + { MONITOR_BOOKMARK_CFG_SCHEMA, CFG_TYPE_VALUE, "Schema", "%d", NULL, 0, MONITOR_BOOKMARKS_SCHEMA_VERSION, 0 }, + { MONITOR_BOOKMARK_CFG_SLOT0, CFG_TYPE_STRING, "BM0", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT1, CFG_TYPE_STRING, "BM1", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT2, CFG_TYPE_STRING, "BM2", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT3, CFG_TYPE_STRING, "BM3", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT4, CFG_TYPE_STRING, "BM4", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT5, CFG_TYPE_STRING, "BM5", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT6, CFG_TYPE_STRING, "BM6", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT7, CFG_TYPE_STRING, "BM7", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT8, CFG_TYPE_STRING, "BM8", "%s", NULL, 0, 47, (long)"" }, + { MONITOR_BOOKMARK_CFG_SLOT9, CFG_TYPE_STRING, "BM9", "%s", NULL, 0, 47, (long)"" }, + { CFG_TYPE_END, CFG_TYPE_END, "", "", NULL, 0, 0, 0 }, +}; + +static uint8_t monitor_bookmark_cfg_id_for_slot(uint8_t slot) +{ + return (uint8_t)(MONITOR_BOOKMARK_CFG_SLOT0 + slot); +} + +static void monitor_bookmark_copy(char *out, size_t out_len, const char *text) +{ + size_t index = 0; + + if (!out || !out_len) { + return; + } + if (!text) { + out[0] = 0; + return; + } + while (text[index] && index + 1 < out_len) { + out[index] = text[index]; + index++; + } + out[index] = 0; +} + +static char monitor_bookmark_normalize_char(char c) +{ + if (c >= 'a' && c <= 'z') { + c = (char)(c - 'a' + 'A'); + } + if ((c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c == '_' || c == '-') { + return c; + } + return '_'; +} + +static uint8_t monitor_bookmark_normalize_binary_width(uint8_t width) +{ + // Preserve sprite mode marker + if (width == MONITOR_BOOKMARK_BINARY_WIDTH_SPRITE) return MONITOR_BOOKMARK_BINARY_WIDTH_SPRITE; + if (width < MONITOR_BOOKMARK_BINARY_WIDTH_MIN) return MONITOR_BOOKMARK_BINARY_WIDTH_MIN; + if (width > MONITOR_BOOKMARK_BINARY_WIDTH_MAX) return MONITOR_BOOKMARK_BINARY_WIDTH_MAX; + return width; +} + +static bool monitor_bookmark_view_has_width(uint8_t view) +{ + return view != MONITOR_BOOKMARK_VIEW_ASM; +} + +static void monitor_bookmark_format_width2(char *out, size_t out_size, uint8_t view, uint8_t width) +{ + uint8_t normalized; + + if (!out || out_size == 0) { + return; + } + if (out_size < 3) { + out[0] = 0; + return; + } + if (!monitor_bookmark_view_has_width(view)) { + out[0] = ' '; + out[1] = ' '; + out[2] = 0; + return; + } + + normalized = monitor_bookmark_normalize_width(view, width); + if (view == MONITOR_BOOKMARK_VIEW_BINARY && normalized == MONITOR_BOOKMARK_BINARY_WIDTH_SPRITE) { + out[0] = '3'; + out[1] = 'S'; + out[2] = 0; + return; + } + if (normalized >= 10) { + sprintf(out, "%u", (unsigned)normalized); + } else { + out[0] = ' '; + out[1] = (char)('0' + normalized); + out[2] = 0; + } +} + +static void monitor_bookmark_format_status_width(char *out, size_t out_size, uint8_t view, uint8_t width) +{ + uint8_t normalized; + + if (!out || out_size == 0) { + return; + } + out[0] = 0; + if (!monitor_bookmark_view_has_width(view)) { + return; + } + + normalized = monitor_bookmark_normalize_width(view, width); + if (view == MONITOR_BOOKMARK_VIEW_BINARY && normalized == MONITOR_BOOKMARK_BINARY_WIDTH_SPRITE) { + monitor_bookmark_copy(out, out_size, "W3S"); + return; + } + sprintf(out, "W%u", (unsigned)normalized); +} + +static void monitor_bookmark_clear(MonitorBookmarkSlot *slot) +{ + if (!slot) { + return; + } + slot->address = 0; + slot->view = MONITOR_BOOKMARK_VIEW_HEX; + slot->cpu_bank = 0; + slot->vic_bank = 0; + slot->view_width_mode = MONITOR_BOOKMARK_WIDTH_NONE; + slot->edit_mode = false; + slot->is_default = false; + slot->is_valid = false; + slot->label[0] = 0; +} + +static int monitor_bookmark_parse_uint(const char *text, int *value) +{ + int parsed = 0; + + if (!text || !*text || !value) { + return 0; + } + while (*text) { + if (*text < '0' || *text > '9') { + return 0; + } + parsed = parsed * 10 + (*text - '0'); + text++; + } + *value = parsed; + return 1; +} + +static int monitor_bookmark_parse_slot(const char *text, MonitorBookmarkSlot *slot) +{ + char buffer[64]; + char *field; + char *cursor; + char *next; + int field_index = 0; + int values[7] = { 0, 0, 0, 0, 0, 0, 0 }; + const char *label_field = ""; + + if (!text || !*text || !slot) { + return 0; + } + + strncpy(buffer, text, sizeof(buffer) - 1); + buffer[sizeof(buffer) - 1] = 0; + cursor = buffer; + while (cursor && *cursor) { + next = strchr(cursor, ','); + field = cursor; + if (next) { + *next = 0; + cursor = next + 1; + } else { + cursor = NULL; + } + if (field_index < 7) { + if (!monitor_bookmark_parse_uint(field, &values[field_index])) { + return 0; + } + } else if (field_index == 7) { + label_field = field; + } else { + return 0; + } + field_index++; + } + if (field_index != 8) { + return 0; + } + + slot->address = (uint16_t)values[0]; + slot->view = (uint8_t)values[1]; + slot->cpu_bank = (uint8_t)values[2]; + slot->vic_bank = (uint8_t)values[3]; + slot->edit_mode = false; + slot->is_default = values[5] ? true : false; + slot->view_width_mode = monitor_bookmark_normalize_width(slot->view, (uint8_t)values[6]); + monitor_bookmark_normalize_label(slot->label, sizeof(slot->label), label_field); + slot->is_valid = true; + return monitor_bookmark_slot_is_valid(*slot) ? 1 : 0; +} + +static void monitor_bookmark_encode_slot(char *out, size_t out_len, const MonitorBookmarkSlot &slot) +{ + char buffer[48]; + char label_buffer[MONITOR_BOOKMARK_LABEL_STORAGE]; + + if (!out || !out_len) { + return; + } + if (!slot.is_valid) { + out[0] = 0; + return; + } + monitor_bookmark_normalize_label(label_buffer, sizeof(label_buffer), slot.label); + sprintf(buffer, "%u,%u,%u,%u,%u,%u,%u,%s", + (unsigned)slot.address, + (unsigned)slot.view, + (unsigned)slot.cpu_bank, + (unsigned)slot.vic_bank, + 0U, + slot.is_default ? 1U : 0U, + (unsigned)monitor_bookmark_normalize_width(slot.view, slot.view_width_mode), + label_buffer); + monitor_bookmark_copy(out, out_len, buffer); +} + +static void monitor_bookmark_assign_default(MonitorBookmarkSlot *slot, uint8_t index, + uint8_t default_cpu_bank, uint8_t default_vic_bank) +{ + (void)default_vic_bank; + slot->address = kMonitorBookmarkDefaults[index].address; + slot->view = kMonitorBookmarkDefaults[index].view; + slot->cpu_bank = (uint8_t)(default_cpu_bank & 0x07); + slot->vic_bank = 0; + slot->view_width_mode = monitor_bookmark_normalize_width(slot->view, MONITOR_BOOKMARK_WIDTH_NONE); + slot->edit_mode = false; + slot->is_default = true; + slot->is_valid = true; + monitor_bookmark_normalize_label(slot->label, sizeof(slot->label), + kMonitorBookmarkDefaults[index].label); +} + +} // namespace + +uint8_t monitor_bookmark_normalize_width(uint8_t view, uint8_t width) +{ + switch (view) { + case MONITOR_BOOKMARK_VIEW_HEX: + return (width >= MONITOR_BOOKMARK_WIDTH_MEMORY_16) ? + MONITOR_BOOKMARK_WIDTH_MEMORY_16 : MONITOR_BOOKMARK_WIDTH_MEMORY_8; + case MONITOR_BOOKMARK_VIEW_ASCII: + case MONITOR_BOOKMARK_VIEW_SCREEN: + return MONITOR_BOOKMARK_WIDTH_TEXT; + case MONITOR_BOOKMARK_VIEW_BINARY: + return monitor_bookmark_normalize_binary_width(width); + case MONITOR_BOOKMARK_VIEW_ASM: + default: + return MONITOR_BOOKMARK_WIDTH_NONE; + } +} + +const char *monitor_bookmark_default_label(uint8_t slot) +{ + if (slot >= MONITOR_BOOKMARK_SLOT_COUNT) { + return ""; + } + return kMonitorBookmarkDefaults[slot].label; +} + +const char *monitor_bookmark_view_name(uint8_t view) +{ + switch (view) { + case MONITOR_BOOKMARK_VIEW_ASM: return "ASM"; + case MONITOR_BOOKMARK_VIEW_ASCII: return "ASC"; + case MONITOR_BOOKMARK_VIEW_SCREEN: return "SCR"; + case MONITOR_BOOKMARK_VIEW_BINARY: return "BIN"; + default: return "HEX"; + } +} + +bool monitor_bookmark_slot_is_valid(const MonitorBookmarkSlot &slot) +{ + if (!slot.is_valid) { + return false; + } + if (slot.view > MONITOR_BOOKMARK_VIEW_MAX) { + return false; + } + if (slot.cpu_bank > 7) { + return false; + } + if (slot.vic_bank > 3) { + return false; + } + return true; +} + +bool monitor_bookmark_status_uses_emphasis(MonitorBookmarkStatusKind kind, const MonitorBookmarkSlot *slot) +{ + if (kind == MONITOR_BOOKMARK_STATUS_RESTORED) { + return !slot || slot->edit_mode; + } + return true; +} + +void monitor_bookmark_normalize_label(char *out, size_t out_size, const char *input) +{ + size_t written = 0; + + if (!out || out_size == 0) { + return; + } + if (out_size < 2) { + out[0] = 0; + return; + } + + if (input) { + for (size_t i = 0; input[i] && written < MONITOR_BOOKMARK_LABEL_MAX && + (written + 1) < out_size; i++) { + char c = input[i]; + if (c == ' ' || c == '\t') { + continue; + } + out[written++] = monitor_bookmark_normalize_char(c); + } + } + out[written] = 0; + + if (written == 0) { + const char *fallback = "USER"; + for (size_t i = 0; fallback[i] && (i + 1) < out_size; i++) { + out[i] = fallback[i]; + } + out[4] = 0; + } +} + +void monitor_bookmark_format_label6(char *out, size_t out_size, const char *label) +{ + size_t i = 0; + bool ended = (label == NULL); + + if (!out || out_size == 0) { + return; + } + if (out_size < MONITOR_BOOKMARK_LABEL_MAX + 1) { + out[0] = 0; + return; + } + while (i < MONITOR_BOOKMARK_LABEL_MAX) { + if (!ended && label[i] == 0) { + ended = true; + } + out[i] = ended ? ' ' : label[i]; + i++; + } + out[MONITOR_BOOKMARK_LABEL_MAX] = 0; +} + +void monitor_bookmark_format_view6(char *out, size_t out_size, uint8_t view, uint8_t view_width_mode) +{ + char buffer[MONITOR_BOOKMARK_VIEW_DISPLAY_MAX + 2]; + char width2[3]; + + if (!out || out_size == 0) { + return; + } + if (out_size < 7) { + out[0] = 0; + return; + } + monitor_bookmark_format_width2(width2, sizeof(width2), view, view_width_mode); + if (!monitor_bookmark_view_has_width(view)) { + const char *name = monitor_bookmark_view_name(view); + size_t i = 0; + while (name[i] && i < 6) { + out[i] = name[i]; + i++; + } + while (i < 6) { + out[i++] = ' '; + } + out[6] = 0; + return; + } + sprintf(buffer, "%s %s", monitor_bookmark_view_name(view), width2); + monitor_bookmark_copy(out, out_size, buffer); +} + +void monitor_bookmark_format_status(char *out, size_t out_len, uint8_t slot, + const MonitorBookmarkSlot *bookmark, + MonitorBookmarkStatusKind kind) +{ + char buffer[64]; + char label_buffer[MONITOR_BOOKMARK_LABEL_STORAGE]; + char width_token[4]; + + if (!out || !out_len) { + return; + } + out[0] = 0; + label_buffer[0] = 0; + width_token[0] = 0; + if (bookmark) { + monitor_bookmark_normalize_label(label_buffer, sizeof(label_buffer), bookmark->label); + monitor_bookmark_format_status_width(width_token, sizeof(width_token), + bookmark->view, bookmark->view_width_mode); + } + + switch (kind) { + case MONITOR_BOOKMARK_STATUS_EMPTY: + sprintf(buffer, "BM%u EMPTY", (unsigned)slot); + monitor_bookmark_copy(out, out_len, buffer); + return; + case MONITOR_BOOKMARK_STATUS_SAVE_FAILED: + if (bookmark && label_buffer[0]) { + sprintf(buffer, "BM%u %s SAVE FAILED", (unsigned)slot, label_buffer); + } else { + sprintf(buffer, "BM%u SAVE FAILED", (unsigned)slot); + } + monitor_bookmark_copy(out, out_len, buffer); + return; + case MONITOR_BOOKMARK_STATUS_RESTORE_FAILED: + if (bookmark && label_buffer[0]) { + sprintf(buffer, "BM%u %s RESTORE FAILED", (unsigned)slot, label_buffer); + } else { + sprintf(buffer, "BM%u RESTORE FAILED", (unsigned)slot); + } + monitor_bookmark_copy(out, out_len, buffer); + return; + case MONITOR_BOOKMARK_STATUS_RESET_DEFAULTS: + monitor_bookmark_copy(out, out_len, "BOOKMARKS RESET TO DEFAULTS"); + return; + case MONITOR_BOOKMARK_STATUS_RESET_FAILED: + monitor_bookmark_copy(out, out_len, "BOOKMARKS RESET FAILED"); + return; + case MONITOR_BOOKMARK_STATUS_LABEL_SAVED: + sprintf(buffer, "BM%u %s SAVED", (unsigned)slot, label_buffer); + monitor_bookmark_copy(out, out_len, buffer); + return; + case MONITOR_BOOKMARK_STATUS_LABEL_RESET: + sprintf(buffer, "BM%u %s RESET", (unsigned)slot, label_buffer); + monitor_bookmark_copy(out, out_len, buffer); + return; + case MONITOR_BOOKMARK_STATUS_LABEL_CANCEL: + sprintf(buffer, "BM%u %s CANCEL", (unsigned)slot, label_buffer); + monitor_bookmark_copy(out, out_len, buffer); + return; + default: + break; + } + + if (!bookmark || !monitor_bookmark_slot_is_valid(*bookmark)) { + sprintf(buffer, "BM%u RESTORE FAILED", (unsigned)slot); + monitor_bookmark_copy(out, out_len, buffer); + return; + } + + { + const char *suffix = (kind == MONITOR_BOOKMARK_STATUS_SET) ? " SET" : ""; + if (width_token[0]) { + sprintf(buffer, "BM%u %s $%04X %s %s CPU%u VIC%u%s", + (unsigned)slot, + label_buffer, + (unsigned)bookmark->address, + monitor_bookmark_view_name(bookmark->view), + width_token, + (unsigned)bookmark->cpu_bank, + (unsigned)bookmark->vic_bank, + suffix); + } else { + sprintf(buffer, "BM%u %s $%04X %s CPU%u VIC%u%s", + (unsigned)slot, + label_buffer, + (unsigned)bookmark->address, + monitor_bookmark_view_name(bookmark->view), + (unsigned)bookmark->cpu_bank, + (unsigned)bookmark->vic_bank, + suffix); + } + } + monitor_bookmark_copy(out, out_len, buffer); +} + +void monitor_bookmark_format_popup_line(char *out, size_t out_len, uint8_t slot, + const MonitorBookmarkSlot *bookmark) +{ + char buffer[64]; + char label_buffer[MONITOR_BOOKMARK_LABEL_STORAGE]; + char label6[MONITOR_BOOKMARK_LABEL_MAX + 1]; + char view6[MONITOR_BOOKMARK_VIEW_DISPLAY_MAX + 1]; + + if (!out || !out_len) { + return; + } + if (!bookmark || !monitor_bookmark_slot_is_valid(*bookmark)) { + const char *fallback = monitor_bookmark_default_label(slot); + monitor_bookmark_normalize_label(label_buffer, sizeof(label_buffer), fallback); + monitor_bookmark_format_label6(label6, sizeof(label6), label_buffer); + sprintf(buffer, "%u %s ----- ------ CPU- VIC-", + (unsigned)slot, label6); + monitor_bookmark_copy(out, out_len, buffer); + return; + } + + monitor_bookmark_normalize_label(label_buffer, sizeof(label_buffer), bookmark->label); + monitor_bookmark_format_label6(label6, sizeof(label6), label_buffer); + monitor_bookmark_format_view6(view6, sizeof(view6), bookmark->view, bookmark->view_width_mode); + + sprintf(buffer, "%u %s $%04X %s CPU%u VIC%u", + (unsigned)slot, + label6, + (unsigned)bookmark->address, + view6, + (unsigned)bookmark->cpu_bank, + (unsigned)bookmark->vic_bank); + monitor_bookmark_copy(out, out_len, buffer); +} + +MonitorBookmarks :: MonitorBookmarks() +{ + ConfigManager *manager = ConfigManager::getConfigManager(); + + cfg = NULL; + loaded = false; + if (manager) { + cfg = manager->find_store("Machine Monitor Bookmarks"); + if (!cfg) { + cfg = manager->register_store(MONITOR_BOOKMARKS_STORE_ID, + "Machine Monitor Bookmarks", + (t_cfg_definition *)monitor_bookmark_cfg, + (ConfigurableObject *)0); + } + if (cfg) { + cfg->hide(); + } + } + persistence_available = (cfg != NULL); + for (int i = 0; i < MONITOR_BOOKMARK_SLOT_COUNT; i++) { + monitor_bookmark_clear(&slots[i]); + } +} + +MonitorBookmarks :: ~MonitorBookmarks() +{ + cfg = NULL; +} + +void MonitorBookmarks :: set_defaults(uint8_t default_cpu_bank, uint8_t default_vic_bank) +{ + for (int i = 0; i < MONITOR_BOOKMARK_SLOT_COUNT; i++) { + monitor_bookmark_assign_default(&slots[i], (uint8_t)i, default_cpu_bank, default_vic_bank); + } +} + +bool MonitorBookmarks :: load_from_config(void) +{ + if (!cfg) { + return false; + } + if (cfg->get_value(MONITOR_BOOKMARK_CFG_SCHEMA) != MONITOR_BOOKMARKS_SCHEMA_VERSION) { + return false; + } + for (int i = 0; i < MONITOR_BOOKMARK_SLOT_COUNT; i++) { + MonitorBookmarkSlot parsed; + const char *encoded = cfg->get_string(monitor_bookmark_cfg_id_for_slot((uint8_t)i)); + monitor_bookmark_clear(&parsed); + if (!encoded || !monitor_bookmark_parse_slot(encoded, &parsed)) { + return false; + } + slots[i] = parsed; + } + return true; +} + +bool MonitorBookmarks :: save_to_config(void) +{ + char encoded[48]; + + if (!cfg) { + return false; + } + cfg->set_value(MONITOR_BOOKMARK_CFG_SCHEMA, MONITOR_BOOKMARKS_SCHEMA_VERSION); + for (int i = 0; i < MONITOR_BOOKMARK_SLOT_COUNT; i++) { + monitor_bookmark_encode_slot(encoded, sizeof(encoded), slots[i]); + cfg->set_string(monitor_bookmark_cfg_id_for_slot((uint8_t)i), encoded); + } + cfg->write(); + return true; +} + +bool MonitorBookmarks :: ensure_loaded(uint8_t default_cpu_bank, uint8_t default_vic_bank) +{ + if (loaded) { + return true; + } + if (!load_from_config()) { + set_defaults(default_cpu_bank, default_vic_bank); + save_to_config(); + } + loaded = true; + return true; +} + +const MonitorBookmarkSlot *MonitorBookmarks :: get(uint8_t slot) const +{ + if (slot >= MONITOR_BOOKMARK_SLOT_COUNT) { + return NULL; + } + return &slots[slot]; +} + +bool MonitorBookmarks :: set(uint8_t slot, const MonitorBookmarkSlot &bookmark) +{ + if (slot >= MONITOR_BOOKMARK_SLOT_COUNT || !monitor_bookmark_slot_is_valid(bookmark)) { + return false; + } + slots[slot] = bookmark; + slots[slot].is_valid = true; + slots[slot].edit_mode = false; + slots[slot].view_width_mode = monitor_bookmark_normalize_width(bookmark.view, bookmark.view_width_mode); + monitor_bookmark_normalize_label(slots[slot].label, sizeof(slots[slot].label), bookmark.label); + loaded = true; + return save_to_config(); +} + +bool MonitorBookmarks :: set_target_preserve_label(uint8_t slot, const MonitorBookmarkSlot &target) +{ + char preserved[MONITOR_BOOKMARK_LABEL_STORAGE]; + + if (slot >= MONITOR_BOOKMARK_SLOT_COUNT || !monitor_bookmark_slot_is_valid(target)) { + return false; + } + if (slots[slot].is_valid && slots[slot].label[0]) { + monitor_bookmark_normalize_label(preserved, sizeof(preserved), slots[slot].label); + } else { + const char *fallback = monitor_bookmark_default_label(slot); + monitor_bookmark_normalize_label(preserved, sizeof(preserved), fallback); + } + slots[slot] = target; + slots[slot].is_valid = true; + slots[slot].is_default = false; + slots[slot].edit_mode = false; + slots[slot].view_width_mode = monitor_bookmark_normalize_width(target.view, target.view_width_mode); + monitor_bookmark_copy(slots[slot].label, sizeof(slots[slot].label), preserved); + loaded = true; + return save_to_config(); +} + +bool MonitorBookmarks :: set_label(uint8_t slot, const char *label) +{ + if (slot >= MONITOR_BOOKMARK_SLOT_COUNT) { + return false; + } + if (!slots[slot].is_valid) { + return false; + } + monitor_bookmark_normalize_label(slots[slot].label, sizeof(slots[slot].label), label); + loaded = true; + return save_to_config(); +} + +bool MonitorBookmarks :: reset_slot_to_default(uint8_t slot, uint8_t default_cpu_bank, uint8_t default_vic_bank) +{ + if (slot >= MONITOR_BOOKMARK_SLOT_COUNT) { + return false; + } + monitor_bookmark_assign_default(&slots[slot], slot, default_cpu_bank, default_vic_bank); + loaded = true; + return save_to_config(); +} + +bool MonitorBookmarks :: reset_to_defaults(uint8_t default_cpu_bank, uint8_t default_vic_bank) +{ + set_defaults(default_cpu_bank, default_vic_bank); + loaded = true; + return save_to_config(); +} diff --git a/software/monitor/monitor_bookmarks.h b/software/monitor/monitor_bookmarks.h new file mode 100644 index 000000000..49c1ac009 --- /dev/null +++ b/software/monitor/monitor_bookmarks.h @@ -0,0 +1,94 @@ +#ifndef MONITOR_BOOKMARKS_H +#define MONITOR_BOOKMARKS_H + +#include +#include + +class ConfigStore; + +enum { + MONITOR_BOOKMARK_SLOT_COUNT = 10, + MONITOR_BOOKMARK_VIEW_HEX = 0, + MONITOR_BOOKMARK_VIEW_ASM, + MONITOR_BOOKMARK_VIEW_ASCII, + MONITOR_BOOKMARK_VIEW_SCREEN, + MONITOR_BOOKMARK_VIEW_BINARY, + MONITOR_BOOKMARK_VIEW_MAX = MONITOR_BOOKMARK_VIEW_BINARY, + MONITOR_BOOKMARK_LABEL_MAX = 6, + MONITOR_BOOKMARK_LABEL_STORAGE = MONITOR_BOOKMARK_LABEL_MAX + 1, + MONITOR_BOOKMARK_VIEW_DISPLAY_MAX = 9, + MONITOR_BOOKMARK_WIDTH_NONE = 0, + MONITOR_BOOKMARK_WIDTH_MEMORY_8 = 8, + MONITOR_BOOKMARK_WIDTH_MEMORY_16 = 16, + MONITOR_BOOKMARK_WIDTH_TEXT = 32, + MONITOR_BOOKMARK_BINARY_WIDTH_MIN = 1, + MONITOR_BOOKMARK_BINARY_WIDTH_MAX = 4, + MONITOR_BOOKMARK_BINARY_WIDTH_SPRITE = 0xFE, +}; + +struct MonitorBookmarkSlot +{ + uint16_t address; + uint8_t view; + uint8_t cpu_bank; + uint8_t vic_bank; + // Stores the bookmarked row-width mode for the active view. + uint8_t view_width_mode; + bool edit_mode; + bool is_default; + bool is_valid; + char label[MONITOR_BOOKMARK_LABEL_STORAGE]; +}; + +enum MonitorBookmarkStatusKind { + MONITOR_BOOKMARK_STATUS_RESTORED = 0, + MONITOR_BOOKMARK_STATUS_SET, + MONITOR_BOOKMARK_STATUS_EMPTY, + MONITOR_BOOKMARK_STATUS_SAVE_FAILED, + MONITOR_BOOKMARK_STATUS_RESTORE_FAILED, + MONITOR_BOOKMARK_STATUS_RESET_DEFAULTS, + MONITOR_BOOKMARK_STATUS_RESET_FAILED, + MONITOR_BOOKMARK_STATUS_LABEL_SAVED, + MONITOR_BOOKMARK_STATUS_LABEL_RESET, + MONITOR_BOOKMARK_STATUS_LABEL_CANCEL, +}; + +const char *monitor_bookmark_default_label(uint8_t slot); +const char *monitor_bookmark_view_name(uint8_t view); +uint8_t monitor_bookmark_normalize_width(uint8_t view, uint8_t width); +bool monitor_bookmark_slot_is_valid(const MonitorBookmarkSlot &slot); +bool monitor_bookmark_status_uses_emphasis(MonitorBookmarkStatusKind kind, const MonitorBookmarkSlot *slot); +void monitor_bookmark_normalize_label(char *out, size_t out_size, const char *input); +void monitor_bookmark_format_label6(char *out, size_t out_size, const char *label); +void monitor_bookmark_format_view6(char *out, size_t out_size, uint8_t view, uint8_t view_width_mode); +void monitor_bookmark_format_status(char *out, size_t out_len, uint8_t slot, + const MonitorBookmarkSlot *bookmark, + MonitorBookmarkStatusKind kind); +void monitor_bookmark_format_popup_line(char *out, size_t out_len, uint8_t slot, + const MonitorBookmarkSlot *bookmark); + +class MonitorBookmarks +{ + MonitorBookmarkSlot slots[MONITOR_BOOKMARK_SLOT_COUNT]; + ConfigStore *cfg; + bool loaded; + bool persistence_available; + + void set_defaults(uint8_t default_cpu_bank, uint8_t default_vic_bank); + bool load_from_config(void); + bool save_to_config(void); + +public: + MonitorBookmarks(); + ~MonitorBookmarks(); + + bool ensure_loaded(uint8_t default_cpu_bank, uint8_t default_vic_bank); + const MonitorBookmarkSlot *get(uint8_t slot) const; + bool set(uint8_t slot, const MonitorBookmarkSlot &bookmark); + bool set_target_preserve_label(uint8_t slot, const MonitorBookmarkSlot &target); + bool set_label(uint8_t slot, const char *label); + bool reset_slot_to_default(uint8_t slot, uint8_t default_cpu_bank, uint8_t default_vic_bank); + bool reset_to_defaults(uint8_t default_cpu_bank, uint8_t default_vic_bank); +}; + +#endif diff --git a/software/monitor/monitor_breakpoints.cc b/software/monitor/monitor_breakpoints.cc new file mode 100644 index 000000000..21f90d5c9 --- /dev/null +++ b/software/monitor/monitor_breakpoints.cc @@ -0,0 +1,187 @@ +#include "monitor_breakpoints.h" + +#include +#include + +static char monitor_breakpoint_normalize_char(char c) +{ + if (c >= 'a' && c <= 'z') { + return (char)(c - 'a' + 'A'); + } + return c; +} + +MonitorBreakpoints :: MonitorBreakpoints() +{ + clear_all(); +} + +void MonitorBreakpoints :: clear_all(void) +{ + for (int i = 0; i < MONITOR_BREAKPOINT_SLOT_COUNT; i++) { + slots[i].used = false; + slots[i].enabled = false; + slots[i].address = 0; + slots[i].view_cpu_port = 0x07; + slots[i].target = MONITOR_BACKING_RAM; + slots[i].label[0] = 0; + } +} + +int MonitorBreakpoints :: find_at(uint16_t address) const +{ + for (int i = 0; i < MONITOR_BREAKPOINT_SLOT_COUNT; i++) { + if (slots[i].used && slots[i].address == address) { + return i; + } + } + return -1; +} + +int MonitorBreakpoints :: find_at(uint16_t address, MonitorBackingStore target) const +{ + for (int i = 0; i < MONITOR_BREAKPOINT_SLOT_COUNT; i++) { + if (slots[i].used && slots[i].address == address && + slots[i].target == target) { + return i; + } + } + return -1; +} + +int MonitorBreakpoints :: allocate(uint16_t address, uint8_t cpu_port) +{ + return allocate(address, cpu_port, + monitor_backing_store_for_cpu_port(address, cpu_port)); +} + +int MonitorBreakpoints :: allocate(uint16_t address, uint8_t cpu_port, + MonitorBackingStore target) +{ + int existing = find_at(address, target); + if (existing >= 0) { + return existing; + } + for (int i = 0; i < MONITOR_BREAKPOINT_SLOT_COUNT; i++) { + if (!slots[i].used) { + slots[i].used = true; + slots[i].enabled = true; + slots[i].address = address; + slots[i].view_cpu_port = (uint8_t)(cpu_port & 0x07); + slots[i].target = target; + slots[i].label[0] = 0; + return i; + } + } + return -1; +} + +void MonitorBreakpoints :: store_slot(int slot, uint16_t address, uint8_t cpu_port) +{ + store_slot(slot, address, cpu_port, + monitor_backing_store_for_cpu_port(address, cpu_port)); +} + +void MonitorBreakpoints :: store_slot(int slot, uint16_t address, uint8_t cpu_port, + MonitorBackingStore target) +{ + if (slot < 0 || slot >= MONITOR_BREAKPOINT_SLOT_COUNT) { + return; + } + bool was_used = slots[slot].used; + slots[slot].used = true; + slots[slot].enabled = true; + slots[slot].address = address; + slots[slot].view_cpu_port = (uint8_t)(cpu_port & 0x07); + slots[slot].target = target; + if (!was_used) { + slots[slot].label[0] = 0; + } +} + +void MonitorBreakpoints :: clear_slot(int slot) +{ + if (slot < 0 || slot >= MONITOR_BREAKPOINT_SLOT_COUNT) { + return; + } + slots[slot].used = false; + slots[slot].enabled = false; + slots[slot].address = 0; + slots[slot].view_cpu_port = 0x07; + slots[slot].target = MONITOR_BACKING_RAM; + slots[slot].label[0] = 0; +} + +void MonitorBreakpoints :: set_enabled(int slot, bool enabled) +{ + if (slot < 0 || slot >= MONITOR_BREAKPOINT_SLOT_COUNT) { + return; + } + if (slots[slot].used) { + slots[slot].enabled = enabled; + } +} + +void MonitorBreakpoints :: set_label(int slot, const char *label) +{ + if (slot < 0 || slot >= MONITOR_BREAKPOINT_SLOT_COUNT) { + return; + } + if (slots[slot].used) { + normalize_label(slots[slot].label, sizeof(slots[slot].label), label); + } +} + +const MonitorBreakpointSlot *MonitorBreakpoints :: get(int slot) const +{ + if (slot < 0 || slot >= MONITOR_BREAKPOINT_SLOT_COUNT) { + return 0; + } + return &slots[slot]; +} + +void MonitorBreakpoints :: normalize_label(char *out, int out_len, const char *input) +{ + int written = 0; + + if (!out || out_len <= 0) { + return; + } + out[0] = 0; + if (out_len <= 1 || !input) { + return; + } + for (int i = 0; input[i] && written < MONITOR_BREAKPOINT_LABEL_MAX && + written + 1 < out_len; i++) { + char c = input[i]; + if (c == ' ' || c == '\t') { + continue; + } + out[written++] = monitor_breakpoint_normalize_char(c); + } + out[written] = 0; +} + +void MonitorBreakpoints :: format_popup_row(char *out, int out_len, int slot, + const MonitorBreakpointSlot *bp) +{ + if (!out || out_len <= 0) { + return; + } + if (!bp || !bp->used) { + sprintf(out, "%d EMPTY", slot); + return; + } + if (bp->label[0]) { + sprintf(out, "%d %s %-4s $%04X %s", slot, + bp->enabled ? "SET" : "OFF", + bp->label, + (unsigned)bp->address, + monitor_backing_store_tag(bp->target)); + } else { + sprintf(out, "%d %s $%04X %s", slot, + bp->enabled ? "SET" : "OFF", + (unsigned)bp->address, + monitor_backing_store_tag(bp->target)); + } +} diff --git a/software/monitor/monitor_breakpoints.h b/software/monitor/monitor_breakpoints.h new file mode 100644 index 000000000..870a4e730 --- /dev/null +++ b/software/monitor/monitor_breakpoints.h @@ -0,0 +1,62 @@ +#ifndef MONITOR_BREAKPOINTS_H +#define MONITOR_BREAKPOINTS_H + +#include "integer.h" +#include "memory_backend.h" + +// Non-persistent breakpoint table used by Assembly Debug mode. 10 slots, by +// design. Slot state stays in RAM only - we deliberately do not write through +// to bookmark storage, both because breakpoints have very different semantics +// and because the spec calls out "Prefer non-persistent breakpoint state". +#define MONITOR_BREAKPOINT_SLOT_COUNT 10 +#define MONITOR_BREAKPOINT_LABEL_MAX 4 +#define MONITOR_BREAKPOINT_LABEL_STORAGE (MONITOR_BREAKPOINT_LABEL_MAX + 1) + +struct MonitorBreakpointSlot { + bool used; + bool enabled; + uint16_t address; + // View CPU-port context captured at set-time. The backing-store target is + // the breakpoint identity; the port is the concrete route used to patch it. + uint8_t view_cpu_port; + MonitorBackingStore target; + char label[MONITOR_BREAKPOINT_LABEL_STORAGE]; +}; + +class MonitorBreakpoints +{ + MonitorBreakpointSlot slots[MONITOR_BREAKPOINT_SLOT_COUNT]; +public: + MonitorBreakpoints(); + + void clear_all(void); + + // Return slot index for an existing breakpoint at this address/target, + // else -1. The address-only overload is for callers that deliberately want + // any breakpoint at the address regardless of backing store. + int find_at(uint16_t address) const; + int find_at(uint16_t address, MonitorBackingStore target) const; + + // Allocate the lowest free slot for `address`. Returns the slot index or + // -1 if all slots are full. If a slot already exists at this + // address/target it is returned and not reallocated. + int allocate(uint16_t address, uint8_t cpu_port); + int allocate(uint16_t address, uint8_t cpu_port, MonitorBackingStore target); + + void store_slot(int slot, uint16_t address, uint8_t cpu_port); + void store_slot(int slot, uint16_t address, uint8_t cpu_port, MonitorBackingStore target); + void clear_slot(int slot); + void set_enabled(int slot, bool enabled); + void set_label(int slot, const char *label); + + int slot_count(void) const { return MONITOR_BREAKPOINT_SLOT_COUNT; } + const MonitorBreakpointSlot *get(int slot) const; + static void normalize_label(char *out, int out_len, const char *input); + + // Format a single slot row for the popup. `out` must hold at least 24 + // characters. Format: "0 SET LABL $C000 RAM" or "0 EMPTY". + static void format_popup_row(char *out, int out_len, int slot, + const MonitorBreakpointSlot *bp); +}; + +#endif diff --git a/software/monitor/monitor_debug.cc b/software/monitor/monitor_debug.cc new file mode 100644 index 000000000..a44967147 --- /dev/null +++ b/software/monitor/monitor_debug.cc @@ -0,0 +1,189 @@ +#include "monitor_debug.h" + +#include +#include + +namespace { + +// Column positions for the fixed footer layout. Header labels and value rows +// share these positions so values align under their labels regardless of +// whether the context is known. Positions are referenced explicitly by name +// to keep the layout obvious and to avoid creeping field reorderings. +enum { + FOOTER_POS_PC = MonitorDebug::FOOTER_POS_PC, + FOOTER_POS_AC = MonitorDebug::FOOTER_POS_AC, + FOOTER_POS_XR = MonitorDebug::FOOTER_POS_XR, + FOOTER_POS_YR = MonitorDebug::FOOTER_POS_YR, + FOOTER_POS_SP = MonitorDebug::FOOTER_POS_SP, + FOOTER_POS_FLAGS = MonitorDebug::FOOTER_POS_FLAGS, + FOOTER_POS_IRQ = MonitorDebug::FOOTER_POS_IRQ, + FOOTER_POS_NMI = MonitorDebug::FOOTER_POS_NMI, + FOOTER_WIDTH = MonitorDebug::FOOTER_WIDTH +}; + +static void blank_buffer(char *buf, int len) +{ + for (int i = 0; i < len; i++) { + buf[i] = ' '; + } + buf[len] = 0; +} + +static void copy_at(char *buf, int pos, const char *src) +{ + int n = (int)strlen(src); + memcpy(buf + pos, src, n); +} + +static void hex4_at(char *buf, int pos, uint16_t value) +{ + static const char hex[] = "0123456789ABCDEF"; + buf[pos + 0] = hex[(value >> 12) & 0x0F]; + buf[pos + 1] = hex[(value >> 8) & 0x0F]; + buf[pos + 2] = hex[(value >> 4) & 0x0F]; + buf[pos + 3] = hex[value & 0x0F]; +} + +static void hex2_at(char *buf, int pos, uint8_t value) +{ + static const char hex[] = "0123456789ABCDEF"; + buf[pos + 0] = hex[(value >> 4) & 0x0F]; + buf[pos + 1] = hex[value & 0x0F]; +} + +static void bin8_at(char *buf, int pos, uint8_t value) +{ + for (int i = 0; i < 8; i++) { + buf[pos + i] = ((value >> (7 - i)) & 1) ? '1' : '0'; + } +} + +} + +void debug_context_reset(DebugContext *ctx) +{ + if (!ctx) { + return; + } + ctx->valid = false; + ctx->pc = 0; + ctx->a = 0; + ctx->x = 0; + ctx->y = 0; + ctx->sr = 0; + ctx->sp = 0; + ctx->live_cpu_port_valid = false; + ctx->live_cpu_port = 0; + ctx->cpu_port_registers_valid = false; + ctx->cpu_ddr = 0; + ctx->cpu_port_latch = 0; + ctx->irq_valid = false; + ctx->irq_vec = 0; + ctx->nmi_valid = false; + ctx->nmi_vec = 0; +} + +MonitorDebug :: MonitorDebug() + : active(false) +{ + debug_context_reset(&ctx); +} + +void MonitorDebug :: enter(void) +{ + active = true; +} + +void MonitorDebug :: leave(void) +{ + active = false; + // Leaving Debug mode does not invalidate the cached context: returning to + // Debug should show the same numbers until execution resumes. +} + +void MonitorDebug :: invalidate_context(void) +{ + debug_context_reset(&ctx); +} + +void MonitorDebug :: set_context(const DebugContext &c) +{ + ctx = c; +} + +void MonitorDebug :: format_footer_header(char *out, int out_len) +{ + if (!out || out_len < FOOTER_WIDTH + 1) { + if (out && out_len > 0) { + out[0] = 0; + } + return; + } + blank_buffer(out, FOOTER_WIDTH); + copy_at(out, FOOTER_POS_PC, "PC"); + copy_at(out, FOOTER_POS_AC, "AC"); + copy_at(out, FOOTER_POS_XR, "XR"); + copy_at(out, FOOTER_POS_YR, "YR"); + copy_at(out, FOOTER_POS_SP, "SP"); + copy_at(out, FOOTER_POS_FLAGS, "NV-BDIZC"); + copy_at(out, FOOTER_POS_IRQ, "IRQ"); + copy_at(out, FOOTER_POS_NMI, "NMI"); +} + +void MonitorDebug :: format_footer_values(const DebugContext &ctx, + char *out, int out_len) +{ + if (!out || out_len < FOOTER_WIDTH + 1) { + if (out && out_len > 0) { + out[0] = 0; + } + return; + } + blank_buffer(out, FOOTER_WIDTH); + if (!ctx.valid) { + return; + } + hex4_at(out, FOOTER_POS_PC, ctx.pc); + hex2_at(out, FOOTER_POS_AC, ctx.a); + hex2_at(out, FOOTER_POS_XR, ctx.x); + hex2_at(out, FOOTER_POS_YR, ctx.y); + hex2_at(out, FOOTER_POS_SP, ctx.sp); + bin8_at(out, FOOTER_POS_FLAGS, ctx.sr); + if (ctx.irq_valid) { + hex4_at(out, FOOTER_POS_IRQ, ctx.irq_vec); + } + if (ctx.nmi_valid) { + hex4_at(out, FOOTER_POS_NMI, ctx.nmi_vec); + } +} + +int MonitorDebug :: format_help_lines(const char *lines[], int max_lines) +{ + static const char *const text[] = { + "", + "D Step Over T Step Into U Step Out", + "G Continue K Cont Crsr RET Follow", + "R Breakpt C=+R Brkpts C=+X Reset", + "", + "M Memory I ASCII V Screen", + "A Assembly B Binary O CPU Bank", + "J Jump P Poll N Number", + "E Edit F Fill W Width", + "C Compare H Hunt Z Freeze", + "L Load S Save", + "", + "Bookmarks: C=+B List C=+0-9 Jump", + "Monitor: C=+O Open/Close", + "Leave debug: C=+D/RSTOP", + "Leave edit: C=+E/RSTOP", + "Copy/Paste: C=+C / C=+V" + }; + int n = (int)(sizeof(text) / sizeof(text[0])); + if (n > max_lines) { + n = max_lines; + } + for (int i = 0; i < n; i++) { + lines[i] = text[i]; + } + return n; +} diff --git a/software/monitor/monitor_debug.h b/software/monitor/monitor_debug.h new file mode 100644 index 000000000..19d44006f --- /dev/null +++ b/software/monitor/monitor_debug.h @@ -0,0 +1,71 @@ +#ifndef MONITOR_DEBUG_H +#define MONITOR_DEBUG_H + +#include "integer.h" + +// Captured CPU state. The "valid" bit gates display of all registers/flags. +// IRQ/NMI vectors are gated separately because they live at memory locations +// the monitor may not have been able to read safely. +struct DebugContext { + bool valid; + uint16_t pc; + uint8_t a; + uint8_t x; + uint8_t y; + uint8_t sr; + uint8_t sp; + bool live_cpu_port_valid; + uint8_t live_cpu_port; + bool cpu_port_registers_valid; + uint8_t cpu_ddr; + uint8_t cpu_port_latch; + bool irq_valid; + uint16_t irq_vec; + bool nmi_valid; + uint16_t nmi_vec; +}; + +void debug_context_reset(DebugContext *ctx); + +// Modal Debug state. Pure data plus footer/help formatting helpers - no +// machine access. MachineMonitor instantiates one of these and routes Debug +// key presses through it. +class MonitorDebug +{ + bool active; + DebugContext ctx; +public: + enum { + FOOTER_POS_PC = 0, + FOOTER_POS_AC = 5, + FOOTER_POS_XR = 8, + FOOTER_POS_YR = 11, + FOOTER_POS_SP = 14, + FOOTER_POS_FLAGS = 17, + FOOTER_POS_IRQ = 26, + FOOTER_POS_NMI = 31, + FOOTER_WIDTH = 35 + }; + + MonitorDebug(); + + bool is_active(void) const { return active; } + void enter(void); + void leave(void); + + void invalidate_context(void); + void set_context(const DebugContext &c); + bool has_context(void) const { return ctx.valid; } + const DebugContext &context(void) const { return ctx; } + + // Footer formatting. Both buffers must hold at least 40 bytes (including + // NUL terminator); the footer body fits the monitor window's 38-column + // budget. + static void format_footer_header(char *out, int out_len); + static void format_footer_values(const DebugContext &ctx, char *out, int out_len); + + // Help screen lines. Returns number of lines written. + static int format_help_lines(const char *lines[], int max_lines); +}; + +#endif diff --git a/software/monitor/monitor_debug_brk_session.cc b/software/monitor/monitor_debug_brk_session.cc new file mode 100644 index 000000000..574994c3e --- /dev/null +++ b/software/monitor/monitor_debug_brk_session.cc @@ -0,0 +1,2012 @@ +#include "monitor_debug_brk_session.h" + +#include "keyboard.h" +#include "monitor_file_io.h" +#include "itu.h" + +#include + +namespace { + +// Cassette-buffer debug scratch layout. All debug stubs/stores occupy a single +// contiguous, top-aligned block ending at $03FB (the top of the C64 cassette +// buffer $033C-$03FB). The 4 "unused" bytes $03FC-$03FF are deliberately +// left free so programs that rely on them are not disturbed. The +// literal-referenced register stores ($03F0-$03FB) stay put; the code stubs are +// packed contiguously up to them, and the two constant-referenced hard-vector +// scratch bytes that previously spilled into $03FC-$03FE are relocated just +// below the store block. Layout: +// $0363-$0389 HANDLER (39 bytes; ends with the spin JMP at $0387) +// $038A-$03AF TRAMPOLINE (38 bytes) +// $03B0-$03C7 NMI_TRAMPOLINE(24 bytes reserved) +// $03C8-$03EC HARD_BRK_STUB (37 bytes; 35 bytes code + 2 bytes padding) +// $03ED STORE_HARD_CPU_PORT +// $03EE-$03EF HARD_BRK_ORIG_VECTOR (lo/hi) +// $03F0-$03FB STORE_Y .. STORE_HARD_CPU_DDR +static const uint16_t HANDLER_ADDR = 0x0363; +static const uint16_t STORE_Y = 0x03F0; +static const uint16_t STORE_X = 0x03F1; +static const uint16_t STORE_A = 0x03F2; +static const uint16_t STORE_SR = 0x03F3; +static const uint16_t STORE_PCLO = 0x03F4; +static const uint16_t STORE_PCHI = 0x03F5; +static const uint16_t STORE_SP = 0x03F6; +static const uint16_t SENTINEL_ADDR = 0x03F7; +static const uint16_t STORE_CPU_DDR = 0x03F8; +static const uint16_t STORE_CPU_PORT = 0x03F9; +static const uint16_t STORE_TRAP_MODE = 0x03FA; +static const uint16_t STORE_HARD_CPU_DDR = 0x03FB; +static const uint16_t STORE_HARD_CPU_PORT = 0x03ED; +static const uint16_t SPIN_JMP = 0x0387; +static const uint16_t SPIN_OPERAND_LO = 0x0388; +static const uint16_t SPIN_OPERAND_HI = 0x0389; +static const uint16_t TRAMPOLINE_ADDR = 0x038A; +static const uint16_t NMI_TRAMPOLINE_ADDR = 0x03B0; +static const uint16_t HARD_BRK_STUB_ADDR = 0x03C8; +static const uint16_t HARD_BRK_ORIG_VECTOR_LO = 0x03EE; +static const uint16_t BRK_VECTOR_LO = 0x0316; +static const uint16_t BRK_VECTOR_HI = 0x0317; +static const uint16_t IRQ_VECTOR_LO = 0x0314; +static const uint16_t NMI_VECTOR_LO = 0x0318; +static const uint16_t NMI_VECTOR_HI = 0x0319; +static const uint16_t HARD_NMI_VECTOR_LO = 0xFFFA; +static const uint16_t HARD_NMI_VECTOR_HI = 0xFFFB; +static const uint16_t HARD_VECTOR_LO = 0xFFFE; +static const uint16_t HARD_VECTOR_HI = 0xFFFF; +static const uint8_t HARD_VECTOR_RAM_CPU_PORT = 0x05; +static const uint8_t HARD_VECTOR_ROM_CPU_PORT = 0x07; +static const uint8_t HARD_VECTOR_DEFAULT_LO = 0x48; +static const uint8_t HARD_VECTOR_DEFAULT_HI = 0xFF; +static const uint16_t DEBUG_AREA_END = 0x03FB; + +// Max extra attempts to re-issue a patched launch when the live 6510 fetched past +// an installed BRK and ran away. The race is rare per launch, so keep it bounded. +static const int MAX_BREAKPOINT_RELAUNCH = 2; +static const int BREAKPOINT_WAIT_MS = 5000; +static const int HIGH_MEMORY_BREAKPOINT_WAIT_MS = 900; + +static const uint8_t HANDLER_BYTES[] = { + 0xBA, + 0xA0, 0x00, + // Copy $0101,X..$0106,X to STORE_Y..STORE_PCHI; X then equals saved SP. + 0xBD, 0x01, 0x01, + 0x99, (uint8_t)(STORE_Y & 0xFF), (uint8_t)(STORE_Y >> 8), + 0xE8, + 0xC8, + 0xC0, 0x06, + 0xD0, 0xF4, + 0x8E, (uint8_t)(STORE_SP & 0xFF), (uint8_t)(STORE_SP >> 8), + 0xA5, 0x00, + 0x8D, 0xF8, 0x03, + 0xA5, 0x01, + 0x8D, 0xF9, 0x03, + 0xA9, (uint8_t)(SPIN_JMP & 0xFF), + 0x8D, (uint8_t)(SPIN_OPERAND_LO & 0xFF), + (uint8_t)(SPIN_OPERAND_LO >> 8), + 0x8D, (uint8_t)(SENTINEL_ADDR & 0xFF), + (uint8_t)(SENTINEL_ADDR >> 8), + 0x4C, (uint8_t)(SPIN_JMP & 0xFF), (uint8_t)(SPIN_JMP >> 8) +}; + +static const uint8_t TRAMPOLINE_BYTES[] = { + 0xAD, (uint8_t)(STORE_CPU_DDR & 0xFF), + (uint8_t)(STORE_CPU_DDR >> 8), + 0x85, 0x00, + 0xAD, (uint8_t)(STORE_CPU_PORT & 0xFF), + (uint8_t)(STORE_CPU_PORT >> 8), + 0x85, 0x01, + 0x68, + 0x68, + 0x68, + 0xBA, + 0xA0, 0x00, + // Copy STORE_SR..STORE_PCHI to $0101,X..$0103,X for the final RTI. + 0xB9, (uint8_t)(STORE_SR & 0xFF), (uint8_t)(STORE_SR >> 8), + 0x9D, 0x01, 0x01, + 0xE8, + 0xC8, + 0xC0, 0x03, + 0xD0, 0xF4, + 0xAE, 0xF1, 0x03, + 0xAC, 0xF0, 0x03, + 0xAD, 0xF2, 0x03, + 0x40 +}; + +static const uint8_t HARD_BRK_STUB_BYTES[] = { + 0x48, + 0x8A, + 0x48, + 0xBA, + 0xBD, 0x03, 0x01, + 0x29, 0x10, + 0xD0, 0x06, + 0x68, + 0xAA, + 0x68, + 0x6C, (uint8_t)(HARD_BRK_ORIG_VECTOR_LO & 0xFF), + (uint8_t)(HARD_BRK_ORIG_VECTOR_LO >> 8), + 0x98, + 0x48, + 0xA5, 0x00, + 0x8D, (uint8_t)(STORE_HARD_CPU_DDR & 0xFF), + (uint8_t)(STORE_HARD_CPU_DDR >> 8), + 0xA5, 0x01, + 0x8D, (uint8_t)(STORE_HARD_CPU_PORT & 0xFF), + (uint8_t)(STORE_HARD_CPU_PORT >> 8), + 0xEE, (uint8_t)(STORE_TRAP_MODE & 0xFF), + (uint8_t)(STORE_TRAP_MODE >> 8), + 0x4C, (uint8_t)(HANDLER_ADDR & 0xFF), + (uint8_t)(HANDLER_ADDR >> 8), + 0xEA, + 0xEA +}; + +static const int HANDLER_BYTES_LEN = (int)sizeof(HANDLER_BYTES); +static const int TRAMPOLINE_BYTES_LEN = (int)sizeof(TRAMPOLINE_BYTES); +static const int NMI_TRAMPOLINE_BYTES_LEN = 24; +static const int HARD_BRK_STUB_BYTES_LEN = (int)sizeof(HARD_BRK_STUB_BYTES); +static const uint16_t DEBUG_OWNER_STALE_REMOTE_MS = 3000; + +static bool hard_vector_points_to_stub(uint8_t lo, uint8_t hi) +{ + return lo == (uint8_t)(HARD_BRK_STUB_ADDR & 0xFF) && + hi == (uint8_t)(HARD_BRK_STUB_ADDR >> 8); +} + +static bool patch_requires_visible_rom(MonitorBackingStore target) +{ + return monitor_backing_store_is_visible_rom(target); +} + +static bool address_is_banked_high_memory(uint16_t addr) +{ + return (addr >= 0xA000 && addr <= 0xBFFF) || addr >= 0xE000; +} + +static bool patch_verify_now(uint16_t addr, uint8_t live_cpu_port, + MonitorBackingStore target) +{ + if (!monitor_backing_store_is_visible_rom(target)) { + return true; + } + return monitor_backing_store_for_cpu_port(addr, live_cpu_port) == target; +} + +struct DebugOwnerState { + BrkDebugSession *owner; + bool remote; + uint16_t last_seen_ms; +}; + +static DebugOwnerState debug_owner = { 0, false, 0 }; + +} + +BrkDebugSession :: BrkDebugSession() + : cancel_keyboard(0), handler_installed(false), cpu_parked_in_spin(false), + run_window_depth(0), run_window_refreeze_enabled(true), + run_window_unfroze(false), screen_was_clobbered(false), + reset_cancel_requested(false), + nmi_trampoline_installed(false), hard_nmi_vector_installed(false), + hard_vector_installed(false), + hard_rom_vector_installed(false), has_last_context(false), + has_resume_context(false), + rom_bp_hit_pc_valid(false), rom_bp_hit_pc(0), + return_target_count(0) +{ + memset(patches, 0, sizeof(patches)); + memset(return_targets, 0, sizeof(return_targets)); + memset(saved_handler_bytes, 0, sizeof(saved_handler_bytes)); + memset(saved_nmi_trampoline_bytes, 0, sizeof(saved_nmi_trampoline_bytes)); + memset(saved_nmi_vector, 0, sizeof(saved_nmi_vector)); + memset(saved_brk_vector, 0, sizeof(saved_brk_vector)); + memset(saved_hard_nmi_vector, 0, sizeof(saved_hard_nmi_vector)); + memset(saved_hard_vector, 0, sizeof(saved_hard_vector)); + memset(saved_hard_rom_vector, 0, sizeof(saved_hard_rom_vector)); + memset(saved_hard_brk_stub_bytes, 0, sizeof(saved_hard_brk_stub_bytes)); + memset(saved_hard_brk_vector_ptr, 0, sizeof(saved_hard_brk_vector_ptr)); + debug_context_reset(&last_context); + debug_context_reset(&resume_context); +} + +BrkDebugSession :: ~BrkDebugSession() +{ + // Do NOT call cleanup() here: by the time the abstract base destructor + // runs, the concrete subclass (and its hardware hooks) are already gone, so + // a virtual cleanup() would dispatch to pure-virtual hooks and abort. The + // monitor always calls cleanup() explicitly before deleting the session, + // and each concrete leaf calls cleanup() from its own destructor while its + // vtable is still valid. +} + +bool BrkDebugSession :: free_run_no_breakpoint(uint16_t address) +{ + monitor_io::jump_to(address); + return true; +} + +uint8_t BrkDebugSession :: read_patch_byte(uint16_t address, uint8_t cpu_port) +{ + return peek_cpu(address, cpu_port); +} + +void BrkDebugSession :: write_patch_byte(uint16_t address, uint8_t byte, uint8_t cpu_port) +{ + poke_cpu(address, byte, cpu_port); +} + +void BrkDebugSession :: set_cancel_keyboard(Keyboard *keyboard) +{ + cancel_keyboard = keyboard; +} + +void BrkDebugSession :: set_run_window_refreeze_enabled(bool enabled) +{ + run_window_refreeze_enabled = enabled; +} + +void BrkDebugSession :: request_reset_cancel(void) +{ + // If we are inside an active run-window the CPU is running freely and + // wait_for_sentinel() is blocking. On FreeRTOS single-core the calling + // task owns the CPU while the UI task is in vTaskDelay, so it is safe to + // tear down patches and handler here before the machine reset pulse fires. + // Do NOT call these when the CPU is parked in the spin loop + // (run_window_depth == 0): uninstall_handler() would overwrite the spin + // loop code the CPU is executing, corrupting the parked debug state. Any BRK + // left in the FPGA ROM image while parked is healed by C64::reset() (it + // restores the pristine ROM image whenever the monitor flagged it dirty), so + // a leaked ROM-image trap can no longer wedge the next boot. + if (run_window_depth > 0) { + restore_patches(); + uninstall_handler(); + cpu_parked_in_spin = false; + has_last_context = false; + debug_context_reset(&last_context); + has_resume_context = false; + debug_context_reset(&resume_context); + rom_bp_hit_pc_valid = false; + } + reset_cancel_requested = true; +} + +bool BrkDebugSession :: claim_debug_ownership(bool remote) +{ + uint16_t now = getMsTimer(); + if (debug_owner.owner == this) { + debug_owner.remote = remote; + debug_owner.last_seen_ms = now; + return true; + } + if (debug_owner.owner) { + bool owner_is_stale = + (uint16_t)(now - debug_owner.last_seen_ms) >= DEBUG_OWNER_STALE_REMOTE_MS; + if (!owner_is_stale) { + return false; + } + BrkDebugSession *stale_owner = debug_owner.owner; + debug_owner.owner = 0; + debug_owner.remote = false; + debug_owner.last_seen_ms = now; + stale_owner->cleanup(); + stale_owner->forget_context(); + } + debug_owner.owner = this; + debug_owner.remote = remote; + debug_owner.last_seen_ms = now; + return true; +} + +void BrkDebugSession :: refresh_debug_ownership(void) +{ + if (debug_owner.owner == this) { + debug_owner.last_seen_ms = getMsTimer(); + } +} + +void BrkDebugSession :: release_debug_ownership(void) +{ + if (debug_owner.owner == this) { + debug_owner.owner = 0; + debug_owner.remote = false; + debug_owner.last_seen_ms = getMsTimer(); + } +} + +bool BrkDebugSession :: reserved_patch_address(uint16_t addr) const +{ + if (addr >= IRQ_VECTOR_LO && addr <= NMI_VECTOR_HI) { + return true; + } + return addr >= HANDLER_ADDR && addr <= DEBUG_AREA_END; +} + +void BrkDebugSession :: begin_run_window(void) +{ + // Outermost entry unfreezes only if this run window really started from + // freeze mode. Nested entries (e.g. go() -> step_with_predict -> perform_run) + // share the single unfreeze/refreeze pair. + if (run_window_depth++ == 0) { + screen_was_clobbered = false; + run_window_unfroze = run_window_refreeze_enabled && machine_is_frozen(); + if (run_window_unfroze) { + unfreeze_if_accessible(); + } + } +} + +void BrkDebugSession :: end_run_window(void) +{ + if (run_window_depth <= 0) { + return; + } + if (--run_window_depth == 0) { + // Re-freeze only if this window unfroze a frozen machine. This restores + // the freezer VIC/charset environment so the monitor renders into the + // firmware menu screen rather than the live C64 screen RAM. Overlay + // mode never unfreezes, so this is a no-op there. + if (run_window_unfroze) { + refreeze_machine(); + // Signal that the firmware chrome rows (UI title, border lines) + // were overwritten by the live BASIC screen during the unfreeze and + // must be redrawn by the caller before the user sees the result. + screen_was_clobbered = true; + } + run_window_unfroze = false; + } +} + +void BrkDebugSession :: save_and_install_handler(void) +{ + if (handler_installed) { + if (!hard_vector_installed) { + save_and_install_hard_vector(); + } + return; + } + bool stopped_it = begin_stopped_session(); + + for (int i = 0; i < HANDLER_BYTES_LEN; i++) { + saved_handler_bytes[i] = peek_visible((uint16_t)(HANDLER_ADDR + i)); + } + for (int i = 0; i < TRAMPOLINE_BYTES_LEN; i++) { + saved_handler_bytes[HANDLER_BYTES_LEN + i] = + peek_visible((uint16_t)(TRAMPOLINE_ADDR + i)); + } + + saved_brk_vector[0] = peek_visible(BRK_VECTOR_LO); + saved_brk_vector[1] = peek_visible(BRK_VECTOR_HI); + + for (int i = 0; i < HANDLER_BYTES_LEN; i++) { + poke_visible((uint16_t)(HANDLER_ADDR + i), HANDLER_BYTES[i]); + } + for (int i = 0; i < TRAMPOLINE_BYTES_LEN; i++) { + poke_visible((uint16_t)(TRAMPOLINE_ADDR + i), TRAMPOLINE_BYTES[i]); + } + poke_visible(SENTINEL_ADDR, 0x00); + poke_visible(STORE_TRAP_MODE, 0x00); + poke_visible(STORE_HARD_CPU_DDR, 0x00); + poke_visible(STORE_HARD_CPU_PORT, 0x00); + poke_visible(BRK_VECTOR_LO, (uint8_t)(HANDLER_ADDR & 0xFF)); + poke_visible(BRK_VECTOR_HI, (uint8_t)(HANDLER_ADDR >> 8)); + + end_stopped_session(stopped_it); + handler_installed = true; + save_and_install_hard_vector(); +} + +void BrkDebugSession :: save_and_install_hard_vector(void) +{ + restore_stale_visible_hard_vector(); + if (hard_vector_installed) { + return; + } + bool stopped_it = begin_stopped_session(); + + saved_hard_vector[0] = peek_cpu(HARD_VECTOR_LO, HARD_VECTOR_RAM_CPU_PORT); + saved_hard_vector[1] = peek_cpu(HARD_VECTOR_HI, HARD_VECTOR_RAM_CPU_PORT); + for (int i = 0; i < HARD_BRK_STUB_BYTES_LEN; i++) { + saved_hard_brk_stub_bytes[i] = peek_visible((uint16_t)(HARD_BRK_STUB_ADDR + i)); + } + saved_hard_brk_vector_ptr[0] = peek_visible(HARD_BRK_ORIG_VECTOR_LO); + saved_hard_brk_vector_ptr[1] = peek_visible((uint16_t)(HARD_BRK_ORIG_VECTOR_LO + 1)); + + for (int i = 0; i < HARD_BRK_STUB_BYTES_LEN; i++) { + poke_visible((uint16_t)(HARD_BRK_STUB_ADDR + i), HARD_BRK_STUB_BYTES[i]); + } + poke_visible(HARD_BRK_ORIG_VECTOR_LO, saved_hard_vector[0]); + poke_visible((uint16_t)(HARD_BRK_ORIG_VECTOR_LO + 1), saved_hard_vector[1]); + poke_cpu(HARD_VECTOR_LO, (uint8_t)(HARD_BRK_STUB_ADDR & 0xFF), + HARD_VECTOR_RAM_CPU_PORT); + poke_cpu(HARD_VECTOR_HI, (uint8_t)(HARD_BRK_STUB_ADDR >> 8), + HARD_VECTOR_RAM_CPU_PORT); + + end_stopped_session(stopped_it); + hard_vector_installed = true; +} + +void BrkDebugSession :: restore_stale_visible_hard_vector(void) +{ + if (hard_rom_vector_installed || !supports_visible_rom_patching()) { + return; + } + bool stopped_it = begin_stopped_session(); + uint8_t lo = peek_cpu(HARD_VECTOR_LO, HARD_VECTOR_ROM_CPU_PORT); + uint8_t hi = peek_cpu(HARD_VECTOR_HI, HARD_VECTOR_ROM_CPU_PORT); + if (hard_vector_points_to_stub(lo, hi)) { + poke_cpu(HARD_VECTOR_LO, HARD_VECTOR_DEFAULT_LO, + HARD_VECTOR_ROM_CPU_PORT); + poke_cpu(HARD_VECTOR_HI, HARD_VECTOR_DEFAULT_HI, + HARD_VECTOR_ROM_CPU_PORT); + } + end_stopped_session(stopped_it); +} + +void BrkDebugSession :: save_and_install_visible_hard_vector(void) +{ + if (hard_rom_vector_installed || !supports_visible_rom_patching()) { + return; + } + if (!hard_vector_installed) { + save_and_install_hard_vector(); + } + bool stopped_it = begin_stopped_session(); + saved_hard_rom_vector[0] = peek_cpu(HARD_VECTOR_LO, + HARD_VECTOR_ROM_CPU_PORT); + saved_hard_rom_vector[1] = peek_cpu(HARD_VECTOR_HI, + HARD_VECTOR_ROM_CPU_PORT); + if (hard_vector_points_to_stub(saved_hard_rom_vector[0], + saved_hard_rom_vector[1])) { + saved_hard_rom_vector[0] = HARD_VECTOR_DEFAULT_LO; + saved_hard_rom_vector[1] = HARD_VECTOR_DEFAULT_HI; + } + poke_cpu(HARD_VECTOR_LO, (uint8_t)(HARD_BRK_STUB_ADDR & 0xFF), + HARD_VECTOR_ROM_CPU_PORT); + poke_cpu(HARD_VECTOR_HI, (uint8_t)(HARD_BRK_STUB_ADDR >> 8), + HARD_VECTOR_ROM_CPU_PORT); + end_stopped_session(stopped_it); + hard_rom_vector_installed = true; +} + +void BrkDebugSession :: save_and_install_hard_nmi_vector(uint8_t cpu_port) +{ + if (monitor_backing_store_for_cpu_port(HARD_NMI_VECTOR_LO, cpu_port) != + MONITOR_BACKING_RAM) { + if (hard_nmi_vector_installed) { + uninstall_hard_nmi_vector(); + } + return; + } + if (!hard_nmi_vector_installed) { + saved_hard_nmi_vector[0] = peek_cpu(HARD_NMI_VECTOR_LO, + HARD_VECTOR_RAM_CPU_PORT); + saved_hard_nmi_vector[1] = peek_cpu(HARD_NMI_VECTOR_HI, + HARD_VECTOR_RAM_CPU_PORT); + hard_nmi_vector_installed = true; + } + poke_cpu(HARD_NMI_VECTOR_LO, (uint8_t)(NMI_TRAMPOLINE_ADDR & 0xFF), + HARD_VECTOR_RAM_CPU_PORT); + poke_cpu(HARD_NMI_VECTOR_HI, (uint8_t)(NMI_TRAMPOLINE_ADDR >> 8), + HARD_VECTOR_RAM_CPU_PORT); +} + +void BrkDebugSession :: uninstall_hard_nmi_vector(void) +{ + if (!hard_nmi_vector_installed) { + return; + } + poke_cpu(HARD_NMI_VECTOR_LO, saved_hard_nmi_vector[0], + HARD_VECTOR_RAM_CPU_PORT); + poke_cpu(HARD_NMI_VECTOR_HI, saved_hard_nmi_vector[1], + HARD_VECTOR_RAM_CPU_PORT); + hard_nmi_vector_installed = false; +} + +void BrkDebugSession :: uninstall_hard_vector(void) +{ + if (!hard_vector_installed) { + return; + } + poke_cpu(HARD_VECTOR_LO, saved_hard_vector[0], HARD_VECTOR_RAM_CPU_PORT); + poke_cpu(HARD_VECTOR_HI, saved_hard_vector[1], HARD_VECTOR_RAM_CPU_PORT); + if (hard_rom_vector_installed) { + poke_cpu(HARD_VECTOR_LO, saved_hard_rom_vector[0], + HARD_VECTOR_ROM_CPU_PORT); + poke_cpu(HARD_VECTOR_HI, saved_hard_rom_vector[1], + HARD_VECTOR_ROM_CPU_PORT); + hard_rom_vector_installed = false; + } + for (int i = 0; i < HARD_BRK_STUB_BYTES_LEN; i++) { + poke_visible_preserving_freeze_restore( + (uint16_t)(HARD_BRK_STUB_ADDR + i), + saved_hard_brk_stub_bytes[i]); + } + poke_visible_preserving_freeze_restore(HARD_BRK_ORIG_VECTOR_LO, + saved_hard_brk_vector_ptr[0]); + poke_visible_preserving_freeze_restore( + (uint16_t)(HARD_BRK_ORIG_VECTOR_LO + 1), + saved_hard_brk_vector_ptr[1]); + hard_vector_installed = false; +} + +void BrkDebugSession :: uninstall_handler(void) +{ + if (!handler_installed && !nmi_trampoline_installed && + !hard_nmi_vector_installed && !hard_vector_installed) { + return; + } + bool stopped_it = begin_stopped_session(); + uninstall_hard_nmi_vector(); + uninstall_hard_vector(); + if (handler_installed) { + poke_visible_preserving_freeze_restore(BRK_VECTOR_LO, + saved_brk_vector[0]); + poke_visible_preserving_freeze_restore(BRK_VECTOR_HI, + saved_brk_vector[1]); + for (int i = 0; i < HANDLER_BYTES_LEN; i++) { + poke_visible_preserving_freeze_restore( + (uint16_t)(HANDLER_ADDR + i), saved_handler_bytes[i]); + } + for (int i = 0; i < TRAMPOLINE_BYTES_LEN; i++) { + poke_visible_preserving_freeze_restore( + (uint16_t)(TRAMPOLINE_ADDR + i), + saved_handler_bytes[HANDLER_BYTES_LEN + i]); + } + } + if (nmi_trampoline_installed) { + poke_visible_preserving_freeze_restore(NMI_VECTOR_LO, + saved_nmi_vector[0]); + poke_visible_preserving_freeze_restore(NMI_VECTOR_HI, + saved_nmi_vector[1]); + for (int i = 0; i < NMI_TRAMPOLINE_BYTES_LEN; i++) { + poke_visible_preserving_freeze_restore( + (uint16_t)(NMI_TRAMPOLINE_ADDR + i), + saved_nmi_trampoline_bytes[i]); + } + nmi_trampoline_installed = false; + } + end_stopped_session(stopped_it); + handler_installed = false; +} + +int BrkDebugSession :: find_free_patch(void) +{ + for (int i = 0; i < MAX_PATCHES; i++) { + if (!patches[i].used) return i; + } + return -1; +} + +bool BrkDebugSession :: already_patched(uint16_t addr, MonitorBackingStore target) +{ + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used && patches[i].address == addr && + patches[i].target == target) { + return true; + } + } + return false; +} + +BrkDebugSession::PatchInstallResult BrkDebugSession :: install_brk_at( + uint16_t addr, uint8_t cpu_port) +{ + return install_brk_at(addr, cpu_port, + monitor_backing_store_for_cpu_port(addr, cpu_port)); +} + +BrkDebugSession::PatchInstallResult BrkDebugSession :: install_brk_at( + uint16_t addr, uint8_t cpu_port, MonitorBackingStore target) +{ + cpu_port &= 0x07; + if (reserved_patch_address(addr)) { + return PATCH_INSTALL_FAILED; + } + if (already_patched(addr, target)) { + return PATCH_INSTALL_OK; + } + int slot = find_free_patch(); + if (slot < 0) { + return PATCH_INSTALL_FAILED; + } + bool visible_rom_patch = patch_requires_visible_rom(target); + if (visible_rom_patch && !supports_visible_rom_patching()) { + return PATCH_INSTALL_NOT_SUPPORTED; + } + if (visible_rom_patch) { + save_and_install_visible_hard_vector(); + } + bool stopped_it = begin_stopped_session(); + uint8_t original = read_patch_byte(addr, cpu_port); + // A target may already contain BRK. Treat that as a valid trap location + // instead of failing the step command. + if (original != 0x00) { + write_patch_byte(addr, 0x00, cpu_port); + } + bool verify = patch_verify_now(addr, current_cpu_port(), target); + if (verify && read_patch_byte(addr, cpu_port) != 0x00) { + end_stopped_session(stopped_it); + return PATCH_INSTALL_FAILED; + } + end_stopped_session(stopped_it); + patches[slot].used = true; + patches[slot].address = addr; + patches[slot].original = original; + patches[slot].cpu_port = cpu_port; + patches[slot].target = target; + return PATCH_INSTALL_OK; +} + +BrkDebugSession::PatchInstallResult BrkDebugSession :: install_breakpoints( + const MonitorBreakpoints *bps, uint16_t skip_address, + MonitorBackingStore skip_target, bool skip_address_valid, + bool skip_all_at_address) +{ + if (!bps) { + return PATCH_INSTALL_OK; + } + for (int i = 0; i < bps->slot_count(); i++) { + const MonitorBreakpointSlot *bp = bps->get(i); + if (!bp || !bp->used || !bp->enabled) { + continue; + } + bool skipped = skip_address_valid && bp->address == skip_address && + (skip_all_at_address || bp->target == skip_target); + if (skipped) { + continue; + } + PatchInstallResult patched = install_brk_at(bp->address, bp->view_cpu_port, + bp->target); + if (patched != PATCH_INSTALL_OK) { + return patched; + } + } + return PATCH_INSTALL_OK; +} + +bool BrkDebugSession :: context_at_breakpoint( + const DebugContext &ctx, const MonitorBreakpoints *bps, + uint16_t skip_address, MonitorBackingStore skip_target, + bool skip_address_valid, bool skip_all_at_address) const +{ + if (!ctx.valid || !bps) { + return false; + } + for (int i = 0; i < bps->slot_count(); i++) { + const MonitorBreakpointSlot *bp = bps->get(i); + if (!bp || !bp->used || !bp->enabled) { + continue; + } + if (skip_address_valid && bp->address == skip_address && + (skip_all_at_address || bp->target == skip_target)) { + continue; + } + if (bp->address == ctx.pc && + bp->target == monitor_backing_store_for_cpu_port( + ctx.pc, execution_cpu_port(&ctx))) { + return true; + } + } + return false; +} + +void BrkDebugSession :: restore_patches(void) +{ + bool any = false; + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used) { any = true; break; } + } + if (!any) return; + + bool stopped_it = begin_stopped_session(); + bool restored_visible_rom = false; + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used) { + if (monitor_backing_store_is_visible_rom(patches[i].target)) { + restored_visible_rom = true; + } + write_patch_byte(patches[i].address, patches[i].original, + patches[i].cpu_port); + patches[i].used = false; + } + } + if (restored_visible_rom) { + settle_visible_rom_for_live_fetch(); + } + end_stopped_session(stopped_it); +} + +bool BrkDebugSession :: recommit_visible_rom_patches(void) +{ + // Re-write each installed visible-ROM BRK ($00) as the final memory write + // before the CPU is released to run. On U64 the FPGA ROM-image write made by + // install_brk_at is occasionally not yet observed by the LIVE 6510 fetch when + // the CPU executes the freshly-patched ROM byte immediately after the launch + // (overlay/Telnet, where the machine is DMA-stopped/resumed several times and + // the CPU runs between patch and launch). Committing the byte again here - + // inside the single stopped session that releases the CPU, with the backend's + // CPU-visible read-back barrier - closes that window. RAM patches are + // unaffected (RAM writes are always coherent), so only visible-ROM patches are + // re-committed to keep this cheap. + bool any = false; + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used && + monitor_backing_store_is_visible_rom(patches[i].target)) { + write_patch_byte(patches[i].address, 0x00, patches[i].cpu_port); + any = true; + } + } + return any; +} + +bool BrkDebugSession :: patch_installed_at(uint16_t addr, + MonitorBackingStore target) const +{ + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used && patches[i].address == addr && + patches[i].target == target) { + return true; + } + } + return false; +} + +bool BrkDebugSession :: recommit_visible_rom_fetch_byte(uint16_t addr, + uint8_t cpu_port) +{ + MonitorBackingStore target = monitor_backing_store_for_cpu_port(addr, + cpu_port); + if (!monitor_backing_store_is_visible_rom(target) || + patch_installed_at(addr, target)) { + return false; + } + write_patch_byte(addr, read_patch_byte(addr, cpu_port), cpu_port); + return true; +} + +bool BrkDebugSession :: has_any_patch(void) const +{ + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used) { + return true; + } + } + return false; +} + +bool BrkDebugSession :: has_banked_ram_patch(void) const +{ + // True for banked high-memory patches that do not use the visible-ROM image + // path. Visible ROM has its own live-fetch settle; RAM under BASIC/KERNAL + // needs the raster-synced clean stop/release. + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used && + address_is_banked_high_memory(patches[i].address) && + !monitor_backing_store_is_visible_rom(patches[i].target)) { + return true; + } + } + return false; +} + +bool BrkDebugSession :: has_high_memory_patch(void) const +{ + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used && + address_is_banked_high_memory(patches[i].address)) { + return true; + } + } + return false; +} + +bool BrkDebugSession :: begin_clean_stopped_session(void) +{ + // Default: same as a normal stopped session. Backends whose plain stop/resume + // is not reliable for immediate patched high-memory fetches override this with + // a raster-synced stop that mirrors the freeze path. + return begin_stopped_session(); +} + +bool BrkDebugSession :: captured_at_installed_patch(uint16_t *captured_brk_pc) +{ + // The BRK handler stores the trap return address (BRK location + 2) at + // STORE_PCLO/HI. A controlled launch is expected to trap at one of our + // installed BRK patches; a captured PC that matches no installed patch means + // the live 6510 ran past the expected target and tripped some unrelated $00. + bool stopped_it = begin_stopped_session(); + uint8_t lo = peek_visible(STORE_PCLO); + uint8_t hi = peek_visible(STORE_PCHI); + end_stopped_session(stopped_it); + uint16_t brk_pc = (uint16_t)((uint16_t)(lo | (hi << 8)) - 2); + if (captured_brk_pc) { + *captured_brk_pc = brk_pc; + } + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used && patches[i].address == brk_pc) { + return true; + } + } + return false; +} + +void BrkDebugSession :: reinstall_handler_bytes(void) +{ + // Re-write the BRK handler + restore trampoline scratch and the BRK soft + // vector WITHOUT re-saving the program's originals (handler_installed stays + // true; saved_* are preserved). Used only on the runaway-relaunch path to + // repair any cassette-buffer scratch a runaway may have overwritten before we + // re-park the CPU. A no-op-equivalent rewrite when the scratch is intact. + bool stopped_it = begin_stopped_session(); + for (int i = 0; i < HANDLER_BYTES_LEN; i++) { + poke_visible((uint16_t)(HANDLER_ADDR + i), HANDLER_BYTES[i]); + } + for (int i = 0; i < TRAMPOLINE_BYTES_LEN; i++) { + poke_visible((uint16_t)(TRAMPOLINE_ADDR + i), TRAMPOLINE_BYTES[i]); + } + poke_visible(BRK_VECTOR_LO, (uint8_t)(HANDLER_ADDR & 0xFF)); + poke_visible(BRK_VECTOR_HI, (uint8_t)(HANDLER_ADDR >> 8)); + end_stopped_session(stopped_it); +} + +void BrkDebugSession :: repark_running_cpu(uint8_t cpu_port) +{ + // Bring a CPU that is either free-running (launch timed out) or parked at the + // wrong PC (stray-$00 runaway capture) back into the controlled spin loop, so + // a clean parked relaunch can be retried. The NMI redirect target is the RAM + // self-loop (SPIN_JMP), so there is no ROM-fetch coherency race on the redirect + // itself. nmi_redirect_to() rewrites the NMI trampoline + vector, so it is + // self-repairing if a runaway clobbered them. + reinstall_handler_bytes(); + reset_spin_target(); + nmi_redirect_to(SPIN_JMP, cpu_port, false, false); + delay_ms(1); + cpu_parked_in_spin = true; +} + +DebugSession::Result BrkDebugSession :: relaunch_on_breakpoint_runaway( + DebugSession::Result waited, const DebugContext *launch_ctx, + bool nmi_launch_valid, uint16_t nmi_target, bool nmi_force_cpu_port, + uint8_t cpu_port, int wait_ms) +{ + // Self-heal a launch that missed an installed BRK patch. A miss either never + // traps (timeout) or traps at an unrelated $00 (captured at the wrong PC). + // On detection, re-park the CPU and re-issue the launch. Context launches use + // the parked restore path so registers are preserved. No-context monitor + // starts cannot synthesize registers, so they repeat the NMI redirect. + // Normal launches return immediately because captured_at_installed_patch() is + // true, so RAM single-step precision is untouched. + if ((!launch_ctx && !nmi_launch_valid) || !has_any_patch()) { + return waited; + } + for (int attempt = 0; attempt < MAX_BREAKPOINT_RELAUNCH; attempt++) { + bool runaway; + bool launch_byte_last = false; + if (waited == DBG_TIMEOUT) { + runaway = true; + } else if (waited == DBG_OK) { + uint16_t captured_brk_pc; + if (captured_at_installed_patch(&captured_brk_pc)) { + return waited; // legitimate trap at one of our BRKs + } + if (launch_ctx && launch_ctx->valid && + captured_brk_pc == launch_ctx->pc) { + launch_byte_last = true; + } + runaway = true; + } else { + return waited; // cancelled / reset / refused - never retry + } + if (!runaway) { + return waited; + } + repark_running_cpu(cpu_port); + if (launch_ctx && launch_byte_last) { + bool force_cpu_port = patch_requires_visible_rom( + monitor_backing_store_for_cpu_port(launch_ctx->pc, cpu_port)); + nmi_redirect_to(launch_ctx->pc, cpu_port, force_cpu_port, false); + } else if (launch_ctx) { + release_to_run(launch_ctx, launch_byte_last); + } else { + nmi_redirect_to(nmi_target, cpu_port, nmi_force_cpu_port, false); + } + waited = wait_for_sentinel(wait_ms); + } + return waited; +} + +void BrkDebugSession :: fill_vectors(DebugContext *ctx, uint8_t cpu_port) +{ + uint8_t lo, hi; + lo = peek_cpu(IRQ_VECTOR_LO, cpu_port); + hi = peek_cpu((uint16_t)(IRQ_VECTOR_LO + 1), cpu_port); + ctx->irq_vec = (uint16_t)(lo | (hi << 8)); + ctx->irq_valid = true; + lo = peek_cpu(NMI_VECTOR_LO, cpu_port); + hi = peek_cpu((uint16_t)(NMI_VECTOR_LO + 1), cpu_port); + ctx->nmi_vec = (uint16_t)(lo | (hi << 8)); + ctx->nmi_valid = true; +} + +void BrkDebugSession :: clear_return_targets(void) +{ + return_target_count = 0; +} + +void BrkDebugSession :: push_return_target(uint16_t target) +{ + if (return_target_count >= MAX_RETURN_TARGETS) { + for (int i = 1; i < MAX_RETURN_TARGETS; i++) { + return_targets[i - 1] = return_targets[i]; + } + return_target_count = MAX_RETURN_TARGETS - 1; + } + return_targets[return_target_count++] = target; +} + +bool BrkDebugSession :: peek_return_target(uint16_t *target) const +{ + if (!target || return_target_count == 0) { + return false; + } + *target = return_targets[return_target_count - 1]; + return true; +} + +void BrkDebugSession :: pop_return_target(uint16_t target) +{ + if (return_target_count > 0 && + return_targets[return_target_count - 1] == target) { + return_target_count--; + } +} + +uint8_t BrkDebugSession :: execution_cpu_port(const DebugContext *ctx) const +{ + if (ctx && ctx->valid && ctx->live_cpu_port_valid) { + return (uint8_t)(ctx->live_cpu_port & 0x07); + } + return current_cpu_port(); +} + +void BrkDebugSession :: drop_queued_execution_keys(void) +{ + if (!cancel_keyboard) { + return; + } + while (1) { + int key = cancel_keyboard->getch(); + if (key < 0) { + return; + } + if (key == 'd' || key == 'D' || + key == 't' || key == 'T' || + key == 'o' || key == 'O' || + key == 'g' || key == 'G' || + key == 'k' || key == 'K') { + continue; + } + cancel_keyboard->push_head(key); + return; + } +} + +DebugSession::Result BrkDebugSession :: wait_for_sentinel(int timeout_ms) +{ + int waited = 0; + while (waited < timeout_ms) { + refresh_debug_ownership(); + if (reset_cancel_requested) { + restore_patches(); + uninstall_handler(); + cpu_parked_in_spin = false; + has_last_context = false; + debug_context_reset(&last_context); + has_resume_context = false; + debug_context_reset(&resume_context); + return DBG_RESET; + } + if (peek_visible(SENTINEL_ADDR) != 0x00) { + drop_queued_execution_keys(); + return DBG_OK; + } + if (cancel_keyboard) { + int key = cancel_keyboard->getch(); + if (key == KEY_ESCAPE || key == KEY_BREAK || + key == KEY_CTRL_D || key == KEY_CTRL_O) { + return DBG_CANCELLED; + } + if (key == KEY_CTRL_X) { + restore_patches(); + uninstall_handler(); + cpu_parked_in_spin = false; + has_last_context = false; + debug_context_reset(&last_context); + has_resume_context = false; + debug_context_reset(&resume_context); + reset_cancel_requested = true; + reset_machine(); + return DBG_RESET; + } + } + delay_ms(5); + waited += 5; + } + return DBG_TIMEOUT; +} + +void BrkDebugSession :: read_captured_context(DebugContext *ctx, uint8_t cpu_port) +{ + bool stopped_it = begin_stopped_session(); + uint8_t y_val = peek_visible(STORE_Y); + uint8_t x_val = peek_visible(STORE_X); + uint8_t a_val = peek_visible(STORE_A); + uint8_t sr_val = peek_visible(STORE_SR); + uint8_t pc_lo = peek_visible(STORE_PCLO); + uint8_t pc_hi = peek_visible(STORE_PCHI); + uint8_t sp_val = peek_visible(STORE_SP); + uint8_t cpu_ddr_register = peek_visible(STORE_CPU_DDR); + uint8_t cpu_port_register = peek_visible(STORE_CPU_PORT); + uint8_t cpu_ddr = cpu_ddr_register & 0x07; + uint8_t cpu_port_latch = cpu_port_register & 0x07; + uint8_t trap_mode = peek_visible(STORE_TRAP_MODE); + uint8_t hard_cpu_ddr_register = peek_visible(STORE_HARD_CPU_DDR); + uint8_t hard_cpu_port_register = peek_visible(STORE_HARD_CPU_PORT); + uint8_t hard_cpu_ddr = hard_cpu_ddr_register & 0x07; + uint8_t hard_cpu_port_latch = hard_cpu_port_register & 0x07; + uint8_t live_cpu_port; + bool hard_trap = trap_mode != 0x00; + if (hard_trap && hard_cpu_ddr != 0x00) { + live_cpu_port = (uint8_t)(((hard_cpu_port_latch & hard_cpu_ddr) | + ((uint8_t)(~hard_cpu_ddr) & 0x07)) & 0x07); + } else if (hard_trap && cpu_ddr == 0x00) { + live_cpu_port = (uint8_t)(cpu_port & 0x07); + } else { + live_cpu_port = + (uint8_t)(((cpu_port_latch & cpu_ddr) | ((uint8_t)(~cpu_ddr) & 0x07)) & 0x07); + } + + debug_context_reset(ctx); + ctx->valid = true; + ctx->y = y_val; + ctx->x = x_val; + ctx->a = a_val; + ctx->sr = sr_val; + ctx->sp = sp_val; + ctx->live_cpu_port_valid = true; + ctx->live_cpu_port = live_cpu_port; + ctx->cpu_port_registers_valid = true; + if (hard_trap && hard_cpu_ddr != 0x00) { + ctx->cpu_ddr = hard_cpu_ddr_register; + ctx->cpu_port_latch = hard_cpu_port_register; + } else if (hard_trap && cpu_ddr == 0x00) { + ctx->cpu_ddr = (uint8_t)((hard_cpu_ddr_register & 0xF8) | 0x07); + ctx->cpu_port_latch = + (uint8_t)((hard_cpu_port_register & 0xF8) | (live_cpu_port & 0x07)); + } else { + ctx->cpu_ddr = cpu_ddr_register; + ctx->cpu_port_latch = cpu_port_register; + } + uint16_t captured_pc = (uint16_t)(pc_lo | (pc_hi << 8)); + ctx->pc = (uint16_t)(captured_pc - 2); + fill_vectors(ctx, live_cpu_port); + note_captured_cpu_port(live_cpu_port); + + poke_visible(SENTINEL_ADDR, 0x00); + poke_visible(STORE_TRAP_MODE, 0x00); + poke_visible(STORE_HARD_CPU_DDR, 0x00); + poke_visible(STORE_HARD_CPU_PORT, 0x00); + end_stopped_session(stopped_it); +} + +void BrkDebugSession :: restore_cpu_port_registers(const DebugContext &from) +{ + if (!from.valid || !from.cpu_port_registers_valid) { + return; + } + poke_visible_preserving_freeze_restore(STORE_CPU_DDR, from.cpu_ddr); + poke_visible_preserving_freeze_restore(STORE_CPU_PORT, + from.cpu_port_latch); +} + +void BrkDebugSession :: release_to_run(const DebugContext *from, + bool launch_byte_last) +{ + // Banked RAM-under-ROM launches use a raster-synced ("clean") stopped session + // so the BRK commit + CPU release happen the way the reliable freeze path does + // it. Visible-ROM patches use the ROM-image settle below instead; ordinary RAM + // single-steps keep the low-latency forced-stop path. + bool clean = has_banked_ram_patch(); + bool stopped_it = clean ? begin_clean_stopped_session() : begin_stopped_session(); + if (from && from->valid) { + restore_cpu_port_registers(*from); + poke_visible(STORE_Y, from->y); + poke_visible(STORE_X, from->x); + poke_visible(STORE_A, from->a); + poke_visible(STORE_SR, from->sr); + poke_visible(STORE_PCLO, (uint8_t)(from->pc & 0xFF)); + poke_visible(STORE_PCHI, (uint8_t)(from->pc >> 8)); + poke_visible(SPIN_OPERAND_LO, (uint8_t)(TRAMPOLINE_ADDR & 0xFF)); + poke_visible(SPIN_OPERAND_HI, (uint8_t)(TRAMPOLINE_ADDR >> 8)); + } + // Final ROM-image commits before the parked CPU is released back into the + // restore stub. Besides installed BRKs, re-commit the launch opcode itself + // when it lives in visible ROM: clearing a visible-ROM breakpoint restores the + // byte in the ROM image, but the live fetch path can still see the stale BRK + // unless the restored opcode is rewritten immediately before release. + bool visible_rom_recommitted = false; + if (!launch_byte_last && from && from->valid) { + visible_rom_recommitted = + recommit_visible_rom_fetch_byte(from->pc, execution_cpu_port(from)); + } + if (recommit_visible_rom_patches()) { + visible_rom_recommitted = true; + } + if (launch_byte_last && from && from->valid) { + visible_rom_recommitted = + recommit_visible_rom_fetch_byte(from->pc, execution_cpu_port(from)) || + visible_rom_recommitted; + } + // Only the first step resuming where a free-run breakpoint just trapped in + // visible ROM needs the sustained settle: that fetch line still holds the BRK + // and only a continuous run refreshes it. + bool sustained_settle = false; + if (from && from->valid && rom_bp_hit_pc_valid && + from->pc == rom_bp_hit_pc) { + sustained_settle = true; + rom_bp_hit_pc_valid = false; + } + // Settle ONLY for that re-trap. On a plain forward step the settle's extra + // stop/resume cycle frees the 6510 briefly and lets it run past the BRK; the + // recommit writes above already place the BRK in the stopped ROM image. + if (visible_rom_recommitted && sustained_settle) { + settle_visible_rom_for_live_fetch(sustained_settle); + } + poke_visible(SENTINEL_ADDR, 0x00); + poke_visible(STORE_TRAP_MODE, 0x00); + poke_visible(STORE_HARD_CPU_DDR, 0x00); + poke_visible(STORE_HARD_CPU_PORT, 0x00); + end_stopped_session(stopped_it); + if (from && from->valid) { + cpu_parked_in_spin = false; + } +} + +void BrkDebugSession :: resume_from_parked_context(const DebugContext &from) +{ + bool stopped_it = begin_stopped_session(); + restore_cpu_port_registers(from); + uint8_t resume_ddr = from.cpu_port_registers_valid ? from.cpu_ddr : 0x37; + uint8_t resume_port = from.cpu_port_registers_valid ? + from.cpu_port_latch : (uint8_t)(from.live_cpu_port & 0x07); + poke_visible_preserving_freeze_restore(0x0000, resume_ddr); + poke_visible_preserving_freeze_restore(0x0001, resume_port); + const uint8_t bytes[] = { + 0xA9, resume_ddr, + 0x85, 0x00, + 0xA9, resume_port, + 0x85, 0x01, + 0xA2, from.sp, + 0x9A, + 0xA9, (uint8_t)(from.pc >> 8), + 0x48, + 0xA9, (uint8_t)(from.pc & 0xFF), + 0x48, + 0xA9, from.sr, + 0x48, + 0xA0, from.y, + 0xA2, from.x, + 0xA9, from.a, + 0x40 + }; + for (unsigned i = 0; i < sizeof(bytes); i++) { + poke_visible_preserving_freeze_restore((uint16_t)(HANDLER_ADDR + i), + bytes[i]); + } + poke_visible_preserving_freeze_restore(SPIN_JMP, 0x4C); + poke_visible_preserving_freeze_restore(SPIN_OPERAND_LO, + (uint8_t)(HANDLER_ADDR & 0xFF)); + poke_visible_preserving_freeze_restore(SPIN_OPERAND_HI, + (uint8_t)(HANDLER_ADDR >> 8)); + // Restore the soft vectors the interrupted program needs once it resumes, + // inside this same stopped session so a live (overlay-mode) CPU sees them + // before it leaves the spin loop. The handler/trampoline scratch bytes in + // the cassette buffer are deliberately left in place: the CPU is about to + // execute the restore stub that lives there. Clearing handler_installed + // makes any later uninstall_handler() a no-op so it can never overwrite the + // stub the CPU may still be running. + if (handler_installed) { + poke_visible_preserving_freeze_restore(BRK_VECTOR_LO, + saved_brk_vector[0]); + poke_visible_preserving_freeze_restore(BRK_VECTOR_HI, + saved_brk_vector[1]); + handler_installed = false; + } + uninstall_hard_nmi_vector(); + uninstall_hard_vector(); + if (nmi_trampoline_installed) { + poke_visible_preserving_freeze_restore(NMI_VECTOR_LO, + saved_nmi_vector[0]); + poke_visible_preserving_freeze_restore(NMI_VECTOR_HI, + saved_nmi_vector[1]); + for (int i = 0; i < NMI_TRAMPOLINE_BYTES_LEN; i++) { + poke_visible_preserving_freeze_restore( + (uint16_t)(NMI_TRAMPOLINE_ADDR + i), + saved_nmi_trampoline_bytes[i]); + } + nmi_trampoline_installed = false; + } + end_stopped_session(stopped_it); +} + +void BrkDebugSession :: reset_spin_target(void) +{ + bool stopped_it = begin_stopped_session(); + poke_visible(SPIN_OPERAND_LO, (uint8_t)(SPIN_JMP & 0xFF)); + poke_visible(SPIN_OPERAND_HI, (uint8_t)(SPIN_JMP >> 8)); + end_stopped_session(stopped_it); +} + +void BrkDebugSession :: nmi_redirect_to(uint16_t target, uint8_t cpu_port, + bool force_cpu_port, bool staged, + bool sustained_settle) +{ + bool clean = has_banked_ram_patch(); + bool stopped_it = clean ? begin_clean_stopped_session() : begin_stopped_session(); + uint8_t old_nmi_lo = peek_visible(NMI_VECTOR_LO); + uint8_t old_nmi_hi = peek_visible(NMI_VECTOR_HI); + uint8_t restore_nmi_lo = old_nmi_lo; + uint8_t restore_nmi_hi = old_nmi_hi; + uint8_t bytes[24]; + int len = 0; + + if (nmi_trampoline_installed) { + restore_nmi_lo = saved_nmi_vector[0]; + restore_nmi_hi = saved_nmi_vector[1]; + } else { + saved_nmi_vector[0] = old_nmi_lo; + saved_nmi_vector[1] = old_nmi_hi; + for (int i = 0; i < NMI_TRAMPOLINE_BYTES_LEN; i++) { + saved_nmi_trampoline_bytes[i] = + peek_visible((uint16_t)(NMI_TRAMPOLINE_ADDR + i)); + } + nmi_trampoline_installed = true; + } + + // Taking the NMI pushes a 3-byte frame (PCH, PCL, SR) onto the stack. + // We resume with a JMP (not an RTI), so without discarding that frame + // the program's stack pointer would be left 3 bytes low for the rest of + // the run - every later push (e.g. a JSR return address) would then land + // 3 bytes below where an undebugged run puts it. Stepping stays + // self-consistent (a matching RTS still works) but the stack contents no + // longer match real execution. Pull the 3 frame bytes back off first so + // SP is exactly what it was before the NMI, then redirect to the target. + bytes[len++] = 0x68; + bytes[len++] = 0x68; + bytes[len++] = 0x68; + bytes[len++] = 0xA9; + bytes[len++] = restore_nmi_lo; + bytes[len++] = 0x8D; + bytes[len++] = (uint8_t)(NMI_VECTOR_LO & 0xFF); + bytes[len++] = (uint8_t)(NMI_VECTOR_LO >> 8); + bytes[len++] = 0xA9; + bytes[len++] = restore_nmi_hi; + bytes[len++] = 0x8D; + bytes[len++] = (uint8_t)(NMI_VECTOR_HI & 0xFF); + bytes[len++] = (uint8_t)(NMI_VECTOR_HI >> 8); + if (force_cpu_port) { + bytes[len++] = 0xA9; + bytes[len++] = 0x37; + bytes[len++] = 0x85; + bytes[len++] = 0x00; + bytes[len++] = 0xA9; + bytes[len++] = (uint8_t)(cpu_port & 0x07); + bytes[len++] = 0x85; + bytes[len++] = 0x01; + } + bytes[len++] = 0x4C; + bytes[len++] = (uint8_t)(target & 0xFF); + bytes[len++] = (uint8_t)(target >> 8); + + for (int i = 0; i < len; i++) { + poke_visible((uint16_t)(NMI_TRAMPOLINE_ADDR + i), bytes[i]); + } + poke_visible(NMI_VECTOR_LO, (uint8_t)(NMI_TRAMPOLINE_ADDR & 0xFF)); + poke_visible(NMI_VECTOR_HI, (uint8_t)(NMI_TRAMPOLINE_ADDR >> 8)); + save_and_install_hard_nmi_vector(cpu_port); + // Final ROM-image commits before the CPU is released (see method note): + // guarantees the live 6510 fetches the intended ROM byte rather than a stale + // pre-patch or pre-restore byte in the overlay/Telnet launch path. + bool visible_rom_recommitted = + recommit_visible_rom_fetch_byte(target, cpu_port); + if (recommit_visible_rom_patches()) { + visible_rom_recommitted = true; + } + // Settle only on the bp-hit re-trap (see release_to_run): on a plain launch + // the extra stop/resume frees the 6510 and lets it run past the BRK. + if (visible_rom_recommitted && sustained_settle) { + settle_visible_rom_for_live_fetch(sustained_settle); + } + // Clear the sentinel as the last act before releasing the CPU, while it is + // still stopped and therefore cannot set it. In freeze mode the run window + // unfreezes the whole machine, so between that unfreeze and this stopped + // session the live CPU free-runs from its frozen PC and - in a hot loop + // such as the BASIC FAC multiply at $B9A6 - can reach the BRK we already + // installed at the step target, fire the handler, and leave the sentinel + // set. Launching the controlled NMI run without clearing it first lets + // wait_for_sentinel() observe that stale $FF and return immediately with a + // context the engine never controlled, desyncing cpu_parked_in_spin from + // the real CPU state and producing the sporadic runaway-stepping loop. + // Clearing here guarantees the next sentinel comes only from this run. + poke_visible(SENTINEL_ADDR, 0x00); + poke_visible(STORE_TRAP_MODE, 0x00); + poke_visible(STORE_HARD_CPU_DDR, 0x00); + poke_visible(STORE_HARD_CPU_PORT, 0x00); + if (staged) { + end_stopped_session(stopped_it); + } else { + // The NMI request must be raised while the CPU is still stopped, then + // released during resume so the CPU observes the pending edge. The + // backend hook handles request+release+clear in one atomic operation. + pulse_nmi_and_release(stopped_it); + } + cpu_parked_in_spin = false; +} + +DebugSession::Result BrkDebugSession :: perform_run(const DebugContext *from, + uint16_t start_pc, + bool use_start_pc, + DebugContext *out, + uint8_t cpu_port) +{ + reset_cancel_requested = false; + refresh_debug_ownership(); + save_and_install_handler(); + // Relaunch metadata for the runaway retry. + const DebugContext *launch_ctx = 0; + DebugContext start_context; + bool nmi_launch_valid = false; + uint16_t nmi_launch_target = 0; + bool nmi_launch_force_cpu_port = false; + if (cpu_parked_in_spin && from && from->valid) { + launch_ctx = from; + begin_run_window(); + release_to_run(from); + } else if (cpu_parked_in_spin && use_start_pc && has_last_context) { + start_context = last_context; + start_context.pc = start_pc; + launch_ctx = &start_context; + begin_run_window(); + release_to_run(&start_context); + } else if (from && from->valid) { + launch_ctx = from; + bool staged = run_window_refreeze_enabled && machine_is_frozen(); + nmi_redirect_to(from->pc, cpu_port, false, staged); + if (staged) { + request_staged_nmi(); + } + begin_run_window(); + if (staged) { + clear_staged_nmi(); + } + } else if (use_start_pc) { + // Non-parked run-to/breakpoint launch. Provide captured registers when + // available; otherwise high-memory monitor starts retry through the same + // NMI redirect because there are no registers to synthesize. + if (has_any_patch()) { + if (has_last_context) { + start_context = last_context; + start_context.pc = start_pc; + launch_ctx = &start_context; + } else if (has_resume_context && resume_context.valid) { + start_context = resume_context; + start_context.pc = start_pc; + launch_ctx = &start_context; + } + } + bool staged = run_window_refreeze_enabled && machine_is_frozen(); + bool force_cpu_port = patch_requires_visible_rom( + monitor_backing_store_for_cpu_port(start_pc, cpu_port)); + if (!launch_ctx && has_high_memory_patch()) { + nmi_launch_valid = true; + nmi_launch_target = start_pc; + nmi_launch_force_cpu_port = force_cpu_port; + } + nmi_redirect_to(start_pc, cpu_port, + force_cpu_port, staged); + if (staged) { + request_staged_nmi(); + } + begin_run_window(); + if (staged) { + clear_staged_nmi(); + } + } else { + begin_run_window(); + release_to_run(0); + } + int wait_ms = has_high_memory_patch() ? + HIGH_MEMORY_BREAKPOINT_WAIT_MS : BREAKPOINT_WAIT_MS; + Result waited = wait_for_sentinel(wait_ms); + waited = relaunch_on_breakpoint_runaway( + waited, launch_ctx, nmi_launch_valid, nmi_launch_target, + nmi_launch_force_cpu_port, cpu_port, wait_ms); + if (waited != DBG_OK) { + restore_patches(); + uninstall_handler(); + cpu_parked_in_spin = false; + end_run_window(); + return waited; + } + read_captured_context(out, cpu_port); + restore_patches(); + reset_spin_target(); + cpu_parked_in_spin = true; + has_last_context = true; + last_context = *out; + end_run_window(); + return DBG_OK; +} + +DebugSession::Result BrkDebugSession :: step_with_predict( + const DebugContext *from, uint16_t start_pc, + const DebugPredictResult &pred, bool prefer_jsr_target, + DebugContext *out, uint8_t cpu_port, + const MonitorBreakpoints *bps, + uint16_t skip_breakpoint_address, + bool skip_breakpoint_address_valid) +{ + if (pred.kind == DBG_PREDICT_UNSAFE || pred.kind == DBG_PREDICT_BRK) { + return DBG_REFUSED; + } + uint16_t addrs[2]; + int n = 0; + switch (pred.kind) { + case DBG_PREDICT_LINEAR: + addrs[n++] = pred.fall_through; + break; + case DBG_PREDICT_JSR: + addrs[n++] = (prefer_jsr_target && pred.has_target) ? + pred.branch_target : pred.fall_through; + break; + case DBG_PREDICT_JMP_ABS: + if (pred.has_target) addrs[n++] = pred.branch_target; + break; + case DBG_PREDICT_BRANCH: + addrs[n++] = pred.fall_through; + if (pred.has_target) addrs[n++] = pred.branch_target; + break; + case DBG_PREDICT_JMP_IND: { + uint16_t op = (uint16_t)(read_patch_byte((uint16_t)(start_pc + 1), cpu_port) | + (read_patch_byte((uint16_t)(start_pc + 2), cpu_port) << 8)); + uint16_t op_hi = (uint16_t)((op & 0xFF00) | ((op + 1) & 0x00FF)); + uint16_t target = (uint16_t)(read_patch_byte(op, cpu_port) | + (read_patch_byte(op_hi, cpu_port) << 8)); + addrs[n++] = target; + break; + } + case DBG_PREDICT_RTS: { + uint16_t traced_target; + if (peek_return_target(&traced_target)) { + addrs[n++] = traced_target; + break; + } + if (!from || !from->valid) return DBG_REFUSED; + uint16_t sp1 = (uint16_t)(0x0100 + ((from->sp + 1) & 0xFF)); + uint16_t sp2 = (uint16_t)(0x0100 + ((from->sp + 2) & 0xFF)); + uint16_t ret = (uint16_t)(peek_cpu(sp1, cpu_port) | + (peek_cpu(sp2, cpu_port) << 8)); + // RTS is only meaningful for an active subroutine frame. Reject + // stale/forged stack targets early so Over/Trace report a clear + // "not in subroutine" outcome instead of a generic patch failure. + uint16_t caller = (uint16_t)(ret - 2); + if (read_patch_byte(caller, cpu_port) != 0x20) { + return DBG_NOT_IN_SUBROUTINE; + } + addrs[n++] = (uint16_t)(ret + 1); + break; + } + case DBG_PREDICT_RTI: { + if (!from || !from->valid) return DBG_REFUSED; + uint16_t sp2 = (uint16_t)(0x0100 + ((from->sp + 2) & 0xFF)); + uint16_t sp3 = (uint16_t)(0x0100 + ((from->sp + 3) & 0xFF)); + addrs[n++] = (uint16_t)(peek_cpu(sp2, cpu_port) | + (peek_cpu(sp3, cpu_port) << 8)); + break; + } + case DBG_PREDICT_BRK: + case DBG_PREDICT_UNSAFE: + default: + return DBG_REFUSED; + } + if (n <= 0) { + return DBG_REFUSED; + } + MonitorBackingStore skip_target = + monitor_backing_store_for_cpu_port(skip_breakpoint_address, cpu_port); + PatchInstallResult bp_patched = install_breakpoints( + bps, skip_breakpoint_address, skip_target, skip_breakpoint_address_valid, + true); + if (bp_patched != PATCH_INSTALL_OK) { + restore_patches(); + return (bp_patched == PATCH_INSTALL_NOT_SUPPORTED) ? + DBG_NOT_SUPPORTED : DBG_PATCH_FAILED; + } + for (int i = 0; i < n; i++) { + PatchInstallResult patched = install_brk_at(addrs[i], cpu_port); + if (patched != PATCH_INSTALL_OK) { + restore_patches(); + return (patched == PATCH_INSTALL_NOT_SUPPORTED) ? + DBG_NOT_SUPPORTED : DBG_PATCH_FAILED; + } + } + Result result = perform_run(from, start_pc, (!from || !from->valid), out, cpu_port); + if (result == DBG_OK && out && out->valid) { + if (pred.kind == DBG_PREDICT_JSR && prefer_jsr_target && + pred.has_target && out->pc == pred.branch_target) { + push_return_target(pred.fall_through); + } else if ((pred.kind == DBG_PREDICT_RTS || pred.kind == DBG_PREDICT_RTI)) { + pop_return_target(out->pc); + } + } + return result; +} + +DebugSession::Result BrkDebugSession :: snapshot(DebugContext *ctx) +{ + if (!ctx) return DBG_REFUSED; + if (has_last_context) { + *ctx = last_context; + return DBG_OK; + } + return DBG_NOT_SUPPORTED; +} + +DebugSession::Result BrkDebugSession :: over(const DebugContext &from, + const DebugPredictResult &pred, + DebugContext *ctx) +{ + return over(from, pred, 0, ctx); +} + +DebugSession::Result BrkDebugSession :: over(const DebugContext &from, + const DebugPredictResult &pred, + const MonitorBreakpoints *bps, + DebugContext *ctx) +{ + if (!backend_ready() || !ctx || !from.valid) return DBG_REFUSED; + uint8_t cpu_port = execution_cpu_port(&from); + return step_with_predict(&from, from.pc, pred, false, ctx, cpu_port, + bps, from.pc, true); +} + +DebugSession::Result BrkDebugSession :: over_at(uint16_t start_pc, + const DebugPredictResult &pred, + DebugContext *ctx) +{ + return over_at(start_pc, pred, 0, ctx); +} + +DebugSession::Result BrkDebugSession :: over_at(uint16_t start_pc, + const DebugPredictResult &pred, + const MonitorBreakpoints *bps, + DebugContext *ctx) +{ + if (!backend_ready() || !ctx) return DBG_REFUSED; + uint8_t cpu_port = current_cpu_port(); + return step_with_predict(0, start_pc, pred, false, ctx, cpu_port, + bps, start_pc, true); +} + +DebugSession::Result BrkDebugSession :: trace(const DebugContext &from, + const DebugPredictResult &pred, + DebugContext *ctx) +{ + if (!backend_ready() || !ctx || !from.valid) return DBG_REFUSED; + uint8_t cpu_port = execution_cpu_port(&from); + return step_with_predict(&from, from.pc, pred, true, ctx, cpu_port); +} + +DebugSession::Result BrkDebugSession :: trace_at(uint16_t start_pc, + const DebugPredictResult &pred, + DebugContext *ctx) +{ + if (!backend_ready() || !ctx) return DBG_REFUSED; + uint8_t cpu_port = current_cpu_port(); + return step_with_predict(0, start_pc, pred, true, ctx, cpu_port); +} + +DebugSession::Result BrkDebugSession :: step_out(const DebugContext &from, + DebugContext *ctx) +{ + return step_out(from, 0, ctx); +} + +DebugSession::Result BrkDebugSession :: step_out(const DebugContext &from, + const MonitorBreakpoints *bps, + DebugContext *ctx) +{ + if (!backend_ready() || !ctx || !from.valid) return DBG_REFUSED; + uint8_t cpu_port = execution_cpu_port(&from); + uint16_t target; + if (!peek_return_target(&target)) { + return DBG_NOT_IN_SUBROUTINE; + } + MonitorBackingStore from_target = + monitor_backing_store_for_cpu_port(from.pc, cpu_port); + PatchInstallResult bp_patched = install_breakpoints(bps, from.pc, + from_target, true, true); + if (bp_patched != PATCH_INSTALL_OK) { + restore_patches(); + return (bp_patched == PATCH_INSTALL_NOT_SUPPORTED) ? + DBG_NOT_SUPPORTED : DBG_PATCH_FAILED; + } + PatchInstallResult patched = install_brk_at(target, cpu_port); + if (patched != PATCH_INSTALL_OK) { + restore_patches(); + return (patched == PATCH_INSTALL_NOT_SUPPORTED) ? + DBG_NOT_SUPPORTED : DBG_PATCH_FAILED; + } + Result result = perform_run(&from, from.pc, false, ctx, cpu_port); + if (result == DBG_OK && ctx->valid && ctx->pc == target) { + pop_return_target(target); + } + if (result == DBG_OK && ctx->valid && + context_at_breakpoint(*ctx, bps, from.pc, from_target, true, true)) { + return DBG_OK; + } + if (result == DBG_OK && (!ctx->valid || ctx->pc != target)) { + return DBG_RETURN_NOT_REACHED; + } + return result; +} + +DebugSession::Result BrkDebugSession :: go(const DebugContext &from, + const MonitorBreakpoints *bps, + uint16_t start_pc) +{ + if (!backend_ready()) return DBG_REFUSED; + reset_cancel_requested = false; + uint8_t cpu_port = execution_cpu_port(&from); + bool skip_current_bp = false; + bool has_other_bp = false; + if (from.valid && bps) { + for (int i = 0; i < bps->slot_count(); i++) { + const MonitorBreakpointSlot *bp = bps->get(i); + if (!bp || !bp->used || !bp->enabled) { + continue; + } + if (bp->address == from.pc && + bp->target == monitor_backing_store_for_cpu_port(from.pc, cpu_port)) { + skip_current_bp = true; + } else { + has_other_bp = true; + } + } + } + + const DebugContext *resume_from = &from; + DebugContext step_ctx; + if (skip_current_bp && !has_other_bp) { + uint8_t bytes[3]; + for (int i = 0; i < 3; i++) { + bytes[i] = read_patch_byte((uint16_t)(from.pc + i), cpu_port); + } + DebugPredictResult pred; + debug_predict(from.pc, bytes, false, &pred); + Result skip = step_with_predict(&from, from.pc, pred, false, &step_ctx, cpu_port, + bps, from.pc, true); + if (skip != DBG_OK) { + return skip; + } + if (step_ctx.valid && step_ctx.pc == from.pc) { + return DBG_OK; + } + MonitorBackingStore from_target = + monitor_backing_store_for_cpu_port(from.pc, cpu_port); + if (context_at_breakpoint(step_ctx, bps, from.pc, from_target, true, true)) { + return DBG_OK; + } + DebugContext out; + return run_to(step_ctx, from.pc, 0, step_ctx.pc, &out); + } + + MonitorBackingStore from_target = + monitor_backing_store_for_cpu_port(from.pc, cpu_port); + PatchInstallResult bp_patched = install_breakpoints( + bps, from.pc, from_target, skip_current_bp, skip_current_bp); + if (bp_patched != PATCH_INSTALL_OK) { + restore_patches(); + return (bp_patched == PATCH_INSTALL_NOT_SUPPORTED) ? + DBG_NOT_SUPPORTED : DBG_PATCH_FAILED; + } + + bool any_bp = false; + for (int i = 0; i < MAX_PATCHES; i++) { + if (patches[i].used) { any_bp = true; break; } + } + if (!any_bp) { + // No breakpoints remain: hand the interrupted program back to free- + // running execution from its captured context. resume_from_parked + // _context() rebuilds a register-restore stub that the parked spin + // loop falls into and RTIs through, preserving the program's $0001 + // banking, and restores the soft BRK vector, the direct hard BRK + // vector (the KERNAL-out path), and the NMI trampoline in the same + // stopped session. This must be used instead of the NMI jump_to() + // fallback below: that fallback vectors through the KERNAL NMI + // handler, which is absent when the program runs with KERNAL banked + // out ($01 != $07), so it would hang/not execute under-ROM code. + // + // A plain G issued after single-stepping passes no freshly captured + // context (resume_from->valid == false), but we ARE parked in the spin + // loop with a valid last_context. Mirror the breakpoint path below + // (which already handles cpu_parked_in_spin && has_last_context) so the + // banking-preserving stub is used in that case too, instead of the + // KERNAL-dependent jump_to() fallback that silently fails to execute a + // RAM-under-ROM program. + const DebugContext *parked_ctx = NULL; + DebugContext start_context; + if (cpu_parked_in_spin && resume_from->valid) { + parked_ctx = resume_from; + } else if (cpu_parked_in_spin && has_last_context) { + start_context = last_context; + start_context.pc = resume_from->valid ? resume_from->pc : start_pc; + parked_ctx = &start_context; + } + if (parked_ctx) { + restore_patches(); + resume_context = *parked_ctx; + has_resume_context = parked_ctx->valid; + resume_from_parked_context(*parked_ctx); + cpu_parked_in_spin = false; + has_last_context = false; + debug_context_reset(&last_context); + return DBG_OK; + } + uint16_t go_pc = resume_from->valid ? resume_from->pc : start_pc; + uninstall_handler(); + has_last_context = false; + debug_context_reset(&last_context); + has_resume_context = false; + debug_context_reset(&resume_context); + free_run_no_breakpoint(go_pc); + return DBG_OK; + } + + save_and_install_handler(); + // Relaunch metadata for the runaway retry. + const DebugContext *launch_ctx = 0; + DebugContext go_start_context; + bool nmi_launch_valid = false; + uint16_t nmi_launch_target = 0; + bool nmi_launch_force_cpu_port = false; + if (resume_from->valid && cpu_parked_in_spin) { + launch_ctx = resume_from; + begin_run_window(); + release_to_run(resume_from); + } else if (cpu_parked_in_spin && has_last_context) { + go_start_context = last_context; + go_start_context.pc = resume_from->valid ? resume_from->pc : start_pc; + launch_ctx = &go_start_context; + begin_run_window(); + release_to_run(&go_start_context); + } else if (resume_from->valid) { + launch_ctx = resume_from; + bool staged = run_window_refreeze_enabled && machine_is_frozen(); + nmi_redirect_to(resume_from->pc, cpu_port, false, staged); + if (staged) { + request_staged_nmi(); + } + begin_run_window(); + if (staged) { + clear_staged_nmi(); + } + } else if (start_pc != 0) { + // Non-parked breakpoint-continue. Provide captured registers when + // available; otherwise high-memory monitor starts retry through the same + // NMI redirect because there are no registers to synthesize. + if (has_any_patch()) { + if (has_last_context) { + go_start_context = last_context; + go_start_context.pc = start_pc; + launch_ctx = &go_start_context; + } else if (has_resume_context && resume_context.valid) { + go_start_context = resume_context; + go_start_context.pc = start_pc; + launch_ctx = &go_start_context; + } + } + bool staged = run_window_refreeze_enabled && machine_is_frozen(); + bool force_cpu_port = patch_requires_visible_rom( + monitor_backing_store_for_cpu_port(start_pc, cpu_port)); + if (!launch_ctx && has_high_memory_patch()) { + nmi_launch_valid = true; + nmi_launch_target = start_pc; + nmi_launch_force_cpu_port = force_cpu_port; + } + nmi_redirect_to(start_pc, cpu_port, + force_cpu_port, staged); + if (staged) { + request_staged_nmi(); + } + begin_run_window(); + if (staged) { + clear_staged_nmi(); + } + } else { + begin_run_window(); + release_to_run(0); + } + + int wait_ms = has_high_memory_patch() ? + HIGH_MEMORY_BREAKPOINT_WAIT_MS : BREAKPOINT_WAIT_MS; + Result waited = wait_for_sentinel(wait_ms); + waited = relaunch_on_breakpoint_runaway( + waited, launch_ctx, nmi_launch_valid, nmi_launch_target, + nmi_launch_force_cpu_port, cpu_port, wait_ms); + if (waited != DBG_OK) { + restore_patches(); + uninstall_handler(); + cpu_parked_in_spin = false; + end_run_window(); + return waited; + } + DebugContext captured; + read_captured_context(&captured, cpu_port); + restore_patches(); + reset_spin_target(); + cpu_parked_in_spin = true; + last_context = captured; + has_last_context = true; + // A free-run breakpoint hit in visible ROM leaves the live fetch path holding + // the BRK for this PC. Flag it so the next step launched from here gets the + // one-shot sustained ROM-fetch settle (see release_to_run / the member note). + if (captured.valid && + monitor_backing_store_is_visible_rom( + monitor_backing_store_for_cpu_port(captured.pc, cpu_port))) { + rom_bp_hit_pc_valid = true; + rom_bp_hit_pc = captured.pc; + } + end_run_window(); + return DBG_OK; +} + +DebugSession::Result BrkDebugSession :: run_to(const DebugContext &from, + uint16_t target_pc, + const MonitorBreakpoints *bps, + uint16_t start_pc, + DebugContext *ctx) +{ + if (!backend_ready() || !ctx) { + return DBG_REFUSED; + } + + DebugContext resume_from = from; + bool have_context = from.valid; + uint16_t run_pc = have_context ? from.pc : start_pc; + uint8_t cpu_port = execution_cpu_port(have_context ? &from : 0); + + if (run_pc == target_pc) { + uint8_t bytes[3]; + for (int i = 0; i < 3; i++) { + bytes[i] = read_patch_byte((uint16_t)(run_pc + i), cpu_port); + } + DebugPredictResult pred; + debug_predict(run_pc, bytes, false, &pred); + DebugContext stepped; + // Escaping an immediate self-hit must execute the current instruction + // exactly once using real control flow. In particular, K Cursor on a + // current-row JSR must enter the callee before re-arming the transient + // cursor breakpoint, not step over to the fall-through address. + Result skip = step_with_predict(have_context ? &from : 0, run_pc, pred, true, + &stepped, cpu_port, bps, run_pc, true); + if (skip != DBG_OK) { + return skip; + } + resume_from = stepped; + have_context = stepped.valid; + run_pc = have_context ? stepped.pc : run_pc; + if (have_context && run_pc == target_pc) { + *ctx = stepped; + return DBG_OK; + } + } + + MonitorBackingStore target_store = + monitor_backing_store_for_cpu_port(target_pc, cpu_port); + PatchInstallResult bp_patched = install_breakpoints( + bps, target_pc, target_store, true); + if (bp_patched != PATCH_INSTALL_OK) { + restore_patches(); + return (bp_patched == PATCH_INSTALL_NOT_SUPPORTED) ? + DBG_NOT_SUPPORTED : DBG_PATCH_FAILED; + } + PatchInstallResult patched = install_brk_at(target_pc, cpu_port); + if (patched != PATCH_INSTALL_OK) { + restore_patches(); + return (patched == PATCH_INSTALL_NOT_SUPPORTED) ? + DBG_NOT_SUPPORTED : DBG_PATCH_FAILED; + } + return perform_run(have_context ? &resume_from : 0, + have_context ? resume_from.pc : start_pc, + !have_context, ctx, cpu_port); +} + +void BrkDebugSession :: cleanup(void) +{ + if (!backend_ready()) return; + clear_return_targets(); + bool resume_pending = cpu_parked_in_spin && has_last_context; + restore_patches(); + if (resume_pending) { + // The CPU is parked in the spin loop: live and looping at SPIN_JMP in + // overlay mode, halted there in freeze mode. Hand it back to the + // interrupted program by redirecting the spin loop into the + // register-restore stub (and restoring the soft vectors) in a single + // stopped session. We must NOT run uninstall_handler() first: it would + // restore the original bytes under the spin loop and, in overlay mode, + // drop the live CPU straight into them before the resume stub is staged. + resume_context = last_context; + has_resume_context = last_context.valid; + resume_from_parked_context(last_context); + } else { + has_resume_context = false; + debug_context_reset(&resume_context); + uninstall_handler(); + } + cpu_parked_in_spin = false; + release_debug_ownership(); +} + +void BrkDebugSession :: cleanup_to_context(const DebugContext *ctx) +{ + if (!backend_ready()) return; + clear_return_targets(); + bool resume_pending = cpu_parked_in_spin && has_last_context; + restore_patches(); + if (resume_pending && ctx && ctx->valid) { + resume_context = *ctx; + has_resume_context = true; + resume_from_parked_context(*ctx); + } else if (resume_pending) { + resume_context = last_context; + has_resume_context = last_context.valid; + resume_from_parked_context(last_context); + } else { + has_resume_context = false; + debug_context_reset(&resume_context); + uninstall_handler(); + } + cpu_parked_in_spin = false; + release_debug_ownership(); +} + +bool BrkDebugSession :: has_parked_context_handoff(void) const +{ + return cpu_parked_in_spin && has_last_context; +} + +bool BrkDebugSession :: read_step_bytes(uint16_t address, uint8_t *dst, uint8_t len) +{ + if (!backend_ready() || !dst) { + return false; + } + uint8_t cpu_port = current_cpu_port(); + for (uint8_t i = 0; i < len; i++) { + dst[i] = read_patch_byte((uint16_t)(address + i), cpu_port); + } + return true; +} + +void BrkDebugSession :: forget_context(void) +{ + // Drop the cached CPU context so the next snapshot() reports "no context". + // The next execution command then starts from the monitor cursor rather + // than the previous session's PC. Keep resume_context hidden from snapshot(); + // it is only a retry seed if a no-context launch with installed patches runs + // away. Patch/handler teardown is cleanup()'s job. + has_last_context = false; + debug_context_reset(&last_context); + clear_return_targets(); +} diff --git a/software/monitor/monitor_debug_brk_session.h b/software/monitor/monitor_debug_brk_session.h new file mode 100644 index 000000000..172b97854 --- /dev/null +++ b/software/monitor/monitor_debug_brk_session.h @@ -0,0 +1,241 @@ +#ifndef MONITOR_DEBUG_BRK_SESSION_H +#define MONITOR_DEBUG_BRK_SESSION_H + +#include "monitor_debug_session.h" +#include "monitor_debug_predictor.h" + +class Keyboard; + +class BrkDebugSession : public DebugSession +{ +protected: + virtual bool backend_ready(void) const = 0; + virtual uint8_t current_cpu_port(void) const = 0; + virtual bool begin_stopped_session(void) = 0; + virtual void end_stopped_session(bool stopped_it) = 0; + virtual uint8_t peek_cpu(uint16_t address, uint8_t cpu_port) = 0; + virtual void poke_cpu(uint16_t address, uint8_t byte, uint8_t cpu_port) = 0; + virtual uint8_t peek_visible(uint16_t address) = 0; + virtual void poke_visible(uint16_t address, uint8_t byte) = 0; + virtual void poke_visible_preserving_freeze_restore(uint16_t address, + uint8_t byte) + { + poke_visible(address, byte); + } + virtual void unfreeze_if_accessible(void) = 0; + // Freeze-mode render-target preservation. A debug step must temporarily + // unfreeze the C64 to run the live CPU; if the machine was frozen, it must + // be re-frozen before control returns to the monitor so the monitor keeps + // rendering into the firmware/menu screen instead of the live C64 screen. + // Default no-op keeps backends without a freeze concept unaffected. + virtual bool machine_is_frozen(void) const { return false; } + virtual void refreeze_machine(void) { } + virtual bool reset_machine(void) = 0; + // Pulse NMI on the live CPU and release the stopped session. The pulse + // MUST occur while the CPU is still stopped so the request bit is + // observed when the CPU resumes; clearing the pulse only happens after + // the resume. Implementations therefore bracket the resume with the + // request/clear pair. + virtual void pulse_nmi_and_release(bool stopped_it) = 0; + virtual void request_staged_nmi(void) { } + virtual void clear_staged_nmi(void) { } + // Begin a stopped session suitable for immediate patched high-memory release. + // The default is a normal stopped session; the U64 backend overrides it with a + // raster-synced ("clean") stop so the live 6510 reliably observes the patch. + virtual bool begin_clean_stopped_session(void); + // Let the live CPU clock briefly so the FPGA commits a freshly-written + // visible-ROM BRK to the live instruction-fetch path before we launch into + // it. Only meaningful when the machine is running (overlay/Telnet); the + // freeze path already restarts the CPU cleanly on unfreeze. Default no-op. + virtual void settle_visible_rom_for_live_fetch(bool sustained = false) { (void)sustained; } + virtual void delay_ms(int ms) = 0; + virtual bool free_run_no_breakpoint(uint16_t address); + virtual uint8_t read_patch_byte(uint16_t address, uint8_t cpu_port); + virtual void write_patch_byte(uint16_t address, uint8_t byte, uint8_t cpu_port); + virtual void note_captured_cpu_port(uint8_t) { } + +public: + BrkDebugSession(); + virtual ~BrkDebugSession(); + + virtual void set_cancel_keyboard(Keyboard *keyboard); + virtual void set_run_window_refreeze_enabled(bool enabled); + virtual void request_reset_cancel(void); + virtual Result snapshot(DebugContext *ctx); + virtual Result over(const DebugContext &from, + const DebugPredictResult &pred, + DebugContext *ctx); + virtual Result over(const DebugContext &from, + const DebugPredictResult &pred, + const MonitorBreakpoints *breakpoints, + DebugContext *ctx); + virtual Result over_at(uint16_t start_pc, + const DebugPredictResult &pred, + DebugContext *ctx); + virtual Result over_at(uint16_t start_pc, + const DebugPredictResult &pred, + const MonitorBreakpoints *breakpoints, + DebugContext *ctx); + virtual Result trace(const DebugContext &from, + const DebugPredictResult &pred, + DebugContext *ctx); + virtual Result trace_at(uint16_t start_pc, + const DebugPredictResult &pred, + DebugContext *ctx); + virtual Result step_out(const DebugContext &from, DebugContext *ctx); + virtual Result step_out(const DebugContext &from, + const MonitorBreakpoints *breakpoints, + DebugContext *ctx); + virtual Result go(const DebugContext &from, + const MonitorBreakpoints *breakpoints, + uint16_t start_pc); + virtual Result run_to(const DebugContext &from, + uint16_t target_pc, + const MonitorBreakpoints *breakpoints, + uint16_t start_pc, + DebugContext *ctx); + virtual void cleanup(void); + virtual void cleanup_to_context(const DebugContext *ctx); + virtual bool has_parked_context_handoff(void) const; + virtual bool read_step_bytes(uint16_t address, uint8_t *dst, uint8_t len); + virtual void forget_context(void); + virtual bool screen_render_target_invalidated(void) const { return screen_was_clobbered; } + virtual bool claim_debug_ownership(bool remote); + virtual void refresh_debug_ownership(void); + virtual void release_debug_ownership(void); + +private: + enum PatchInstallResult { + PATCH_INSTALL_OK = 0, + PATCH_INSTALL_NOT_SUPPORTED, + PATCH_INSTALL_FAILED + }; + + struct Patch { + bool used; + uint16_t address; + uint8_t original; + uint8_t cpu_port; + MonitorBackingStore target; + }; + + enum { + MAX_PATCHES = 16, + MAX_RETURN_TARGETS = 8 + }; + + Keyboard *cancel_keyboard; + Patch patches[MAX_PATCHES]; + bool handler_installed; + bool cpu_parked_in_spin; + // A free-run (G) breakpoint hit in visible ROM leaves the live 6510 + // instruction-fetch ROM line for that PC holding the BRK ($00). Restoring it + // updates the DMA-visible image immediately, but the fetch path only refreshes + // after sustained continuous core execution. The very next step launched from + // that exact PC therefore needs the sustained ROM-fetch settle once; ordinary + // forward stepping does not. Tracked here and consumed by release_to_run(). + bool rom_bp_hit_pc_valid; + uint16_t rom_bp_hit_pc; + // Nesting-safe CPU-run window. When enabled, begin_run_window() unfreezes a + // frozen machine once; end_run_window() re-freezes it on the outermost exit + // so a frozen monitor's render target survives the step. + int run_window_depth; + bool run_window_refreeze_enabled; + bool run_window_unfroze; + // Set by end_run_window() when it actually refreezes the machine. Callers + // can read this via screen_render_target_invalidated() to know whether the + // firmware chrome rows need restoring before the next visible redraw. + bool screen_was_clobbered; + volatile bool reset_cancel_requested; + uint8_t saved_handler_bytes[128]; + uint8_t saved_nmi_trampoline_bytes[24]; + bool nmi_trampoline_installed; + uint8_t saved_nmi_vector[2]; + uint8_t saved_brk_vector[2]; + uint8_t saved_hard_nmi_vector[2]; + uint8_t saved_hard_vector[2]; + uint8_t saved_hard_rom_vector[2]; + uint8_t saved_hard_brk_stub_bytes[48]; + uint8_t saved_hard_brk_vector_ptr[2]; + bool hard_nmi_vector_installed; + bool hard_vector_installed; + bool hard_rom_vector_installed; + bool has_last_context; + DebugContext last_context; + bool has_resume_context; + DebugContext resume_context; + uint16_t return_targets[MAX_RETURN_TARGETS]; + uint8_t return_target_count; + + bool reserved_patch_address(uint16_t addr) const; + void begin_run_window(void); + void end_run_window(void); + void save_and_install_handler(void); + void save_and_install_hard_vector(void); + void save_and_install_visible_hard_vector(void); + void restore_stale_visible_hard_vector(void); + void save_and_install_hard_nmi_vector(uint8_t cpu_port); + void uninstall_hard_nmi_vector(void); + void uninstall_hard_vector(void); + void uninstall_handler(void); + int find_free_patch(void); + bool already_patched(uint16_t addr, MonitorBackingStore target); + PatchInstallResult install_brk_at(uint16_t addr, uint8_t cpu_port); + PatchInstallResult install_brk_at(uint16_t addr, uint8_t cpu_port, + MonitorBackingStore target); + PatchInstallResult install_breakpoints(const MonitorBreakpoints *breakpoints, + uint16_t skip_address, + MonitorBackingStore skip_target, + bool skip_address_valid, + bool skip_all_at_address = false); + bool context_at_breakpoint(const DebugContext &ctx, + const MonitorBreakpoints *breakpoints, + uint16_t skip_address, + MonitorBackingStore skip_target, + bool skip_address_valid, + bool skip_all_at_address = false) const; + void restore_patches(void); + bool recommit_visible_rom_patches(void); + bool patch_installed_at(uint16_t addr, MonitorBackingStore target) const; + bool recommit_visible_rom_fetch_byte(uint16_t addr, uint8_t cpu_port); + bool has_banked_ram_patch(void) const; + bool has_high_memory_patch(void) const; + bool has_any_patch(void) const; + bool captured_at_installed_patch(uint16_t *captured_brk_pc = 0); + void reinstall_handler_bytes(void); + void repark_running_cpu(uint8_t cpu_port); + Result relaunch_on_breakpoint_runaway(Result waited, + const DebugContext *launch_ctx, + bool nmi_launch_valid, + uint16_t nmi_target, + bool nmi_force_cpu_port, + uint8_t cpu_port, + int wait_ms); + void fill_vectors(DebugContext *ctx, uint8_t cpu_port); + void clear_return_targets(void); + void push_return_target(uint16_t target); + bool peek_return_target(uint16_t *target) const; + void pop_return_target(uint16_t target); + uint8_t execution_cpu_port(const DebugContext *ctx) const; + void drop_queued_execution_keys(void); + Result wait_for_sentinel(int timeout_ms); + void read_captured_context(DebugContext *ctx, uint8_t cpu_port); + void restore_cpu_port_registers(const DebugContext &from); + void release_to_run(const DebugContext *from, bool launch_byte_last = false); + void resume_from_parked_context(const DebugContext &from); + void reset_spin_target(void); + void nmi_redirect_to(uint16_t target, uint8_t cpu_port, + bool force_cpu_port, bool staged = false, + bool sustained_settle = false); + Result perform_run(const DebugContext *from, uint16_t start_pc, + bool use_start_pc, DebugContext *out, uint8_t cpu_port); + Result step_with_predict(const DebugContext *from, uint16_t start_pc, + const DebugPredictResult &pred, + bool prefer_jsr_target, + DebugContext *out, uint8_t cpu_port, + const MonitorBreakpoints *breakpoints = 0, + uint16_t skip_breakpoint_address = 0, + bool skip_breakpoint_address_valid = false); +}; + +#endif diff --git a/software/monitor/monitor_debug_predictor.cc b/software/monitor/monitor_debug_predictor.cc new file mode 100644 index 000000000..43f659c2b --- /dev/null +++ b/software/monitor/monitor_debug_predictor.cc @@ -0,0 +1,96 @@ +#include "monitor_debug_predictor.h" +#include "disassembler_6502.h" + +#include + +void debug_predict(uint16_t pc, const uint8_t *bytes, bool illegal_enabled, + DebugPredictResult *out) +{ + if (!out) { + return; + } + out->kind = DBG_PREDICT_UNSAFE; + out->length = 0; + out->fall_through = pc; + out->has_target = false; + out->branch_target = 0; + + if (!bytes) { + return; + } + + uint8_t opcode = bytes[0]; + + // Fast classification for explicit control flow before we hand off to the + // disassembler for fall-through addresses. Doing this here keeps the + // predictor independent of the disassembler's text template. + switch (opcode) { + case 0x00: // BRK + out->kind = DBG_PREDICT_BRK; + out->length = 1; + out->fall_through = (uint16_t)(pc + 1); + return; + case 0x20: // JSR abs + out->kind = DBG_PREDICT_JSR; + out->length = 3; + out->fall_through = (uint16_t)(pc + 3); + out->branch_target = (uint16_t)(bytes[1] | (bytes[2] << 8)); + out->has_target = true; + return; + case 0x4C: // JMP abs + out->kind = DBG_PREDICT_JMP_ABS; + out->length = 3; + out->fall_through = (uint16_t)(pc + 3); + out->branch_target = (uint16_t)(bytes[1] | (bytes[2] << 8)); + out->has_target = true; + return; + case 0x6C: // JMP (ind) + out->kind = DBG_PREDICT_JMP_IND; + out->length = 3; + out->fall_through = (uint16_t)(pc + 3); + return; + case 0x60: // RTS + out->kind = DBG_PREDICT_RTS; + out->length = 1; + out->fall_through = (uint16_t)(pc + 1); + return; + case 0x40: // RTI + out->kind = DBG_PREDICT_RTI; + out->length = 1; + out->fall_through = (uint16_t)(pc + 1); + return; + case 0x10: case 0x30: case 0x50: case 0x70: // BPL/BMI/BVC/BVS + case 0x90: case 0xB0: case 0xD0: case 0xF0: // BCC/BCS/BNE/BEQ + { + int8_t off = (int8_t)bytes[1]; + uint16_t taken = (uint16_t)(pc + 2 + off); + out->kind = DBG_PREDICT_BRANCH; + out->length = 2; + out->fall_through = (uint16_t)(pc + 2); + out->branch_target = taken; + out->has_target = true; + return; + } + default: + break; + } + + // Fall through: lean on the disassembler for length. + Disassembled6502 d; + disassemble_6502(pc, bytes, illegal_enabled, &d); + if (!d.valid && !illegal_enabled) { + out->kind = DBG_PREDICT_UNSAFE; + out->length = 0; + return; + } + if (d.length == 0 || d.length > 3) { + out->kind = DBG_PREDICT_UNSAFE; + out->length = 0; + return; + } + out->kind = DBG_PREDICT_LINEAR; + out->length = d.length; + out->fall_through = (uint16_t)(pc + d.length); + out->has_target = d.has_target; + out->branch_target = d.target; +} diff --git a/software/monitor/monitor_debug_predictor.h b/software/monitor/monitor_debug_predictor.h new file mode 100644 index 000000000..6d855c824 --- /dev/null +++ b/software/monitor/monitor_debug_predictor.h @@ -0,0 +1,32 @@ +#ifndef MONITOR_DEBUG_PREDICTOR_H +#define MONITOR_DEBUG_PREDICTOR_H + +#include "integer.h" + +// Classification of a 6502 instruction for Debug-mode stepping. +// Pure logic; no firmware/memory access. The caller supplies up to three +// instruction bytes at the current PC. +enum DebugPredictKind { + DBG_PREDICT_LINEAR, // Falls through: install BRK at PC + length. + DBG_PREDICT_JSR, // Step-over target is PC + 3. + DBG_PREDICT_JMP_ABS, // PC := operand word; install BRK at branch_target. + DBG_PREDICT_JMP_IND, // PC := (operand word); target unresolved here. + DBG_PREDICT_BRANCH, // Conditional: falls through OR jumps to target. + DBG_PREDICT_RTS, // Pops PC from stack + 1; target unresolved here. + DBG_PREDICT_RTI, // Pops SR + PC; target unresolved here. + DBG_PREDICT_BRK, // Refuse: cannot patch over a BRK. + DBG_PREDICT_UNSAFE // Illegal or undecodable; refuse. +}; + +struct DebugPredictResult { + DebugPredictKind kind; + uint8_t length; // Instruction length (1..3); 0 on UNSAFE. + uint16_t fall_through; // PC + length (only meaningful for non-UNSAFE). + bool has_target; + uint16_t branch_target; // Absolute target for JMP/JSR/branch when known. +}; + +void debug_predict(uint16_t pc, const uint8_t *bytes, bool illegal_enabled, + DebugPredictResult *out); + +#endif diff --git a/software/monitor/monitor_debug_session.h b/software/monitor/monitor_debug_session.h new file mode 100644 index 000000000..32de73119 --- /dev/null +++ b/software/monitor/monitor_debug_session.h @@ -0,0 +1,187 @@ +#ifndef MONITOR_DEBUG_SESSION_H +#define MONITOR_DEBUG_SESSION_H + +#include "integer.h" +#include "monitor_debug.h" +#include "monitor_breakpoints.h" + +// Backend-provided executing layer for Debug mode. Implementations own the +// BRK trampoline / vector hook lifecycle and are responsible for restoring +// every patched byte and vector on success, failure, cancel, and destruction. +// +// MachineMonitor creates a session lazily on first Debug execution command +// and destroys it on monitor close or debug-off. The session must remain a +// thin orchestrator on top of the existing MemoryBackend; it does not own +// keyboard or UI state. +class DebugSession +{ +public: + enum Result { + DBG_OK = 0, // Stopped cleanly, *ctx populated. + DBG_NOT_SUPPORTED, // Backend cannot perform this operation. + DBG_REFUSED, // Unsafe target (BRK, unsupported insn, ...). + DBG_UNSUPPORTED_OPCODE, // Opcode can be decoded but not debug-stepped. + DBG_NOT_IN_SUBROUTINE, // Step Out requested without a traced JSR frame. + DBG_RETURN_NOT_REACHED, // Step Out ran but did not trap at its return target. + DBG_TIMEOUT, // Trap did not fire within the wait window. + DBG_CANCELLED, // User pressed RUN/STOP / Telnet ESC during wait. + DBG_RESET, // User forced a machine reset; context is no longer truthful. + DBG_PATCH_FAILED // Could not safely install or restore a patch. + }; + + virtual ~DebugSession() { } + + // Optional non-owning cancel source for implementations that block while + // waiting for a trap. Default keeps host tests and unsupported backends + // independent of UI/input plumbing. + virtual void set_cancel_keyboard(class Keyboard *) { } + + // True only when the active monitor UI renders through the C64 freezer + // screen. Overlay and remote monitor sessions must leave this disabled so + // stepping cannot enter the C64 freeze/refreeze ownership path. + virtual void set_run_window_refreeze_enabled(bool) { } + + // External machine reset is a hard cancellation boundary for any blocking + // debug wait. Implementations that poll for traps should return DBG_RESET + // promptly after this is requested. + virtual void request_reset_cancel(void) { } + + // Best-effort initial context. May return DBG_NOT_SUPPORTED on backends + // that cannot snapshot CPU state without first performing a step. The + // context is also responsible for filling irq_valid / nmi_valid honestly: + // never fabricate vector contents. + virtual Result snapshot(DebugContext *ctx) = 0; + + // Step over: install BRK at fall_through, resume, wait, restore. JSR is + // handled identically (BRK at PC + 3). Backends that support active + // breakpoints during the run may override the breakpoint-table overload. + virtual Result over(const DebugContext &from, + const struct DebugPredictResult &pred, + DebugContext *ctx) = 0; + virtual Result over(const DebugContext &from, + const struct DebugPredictResult &pred, + const MonitorBreakpoints *breakpoints, + DebugContext *ctx) { + (void)breakpoints; + return over(from, pred, ctx); + } + virtual Result over_at(uint16_t start_pc, + const struct DebugPredictResult &pred, + DebugContext *ctx) { + (void)start_pc; (void)pred; (void)ctx; + return DBG_NOT_SUPPORTED; + } + virtual Result over_at(uint16_t start_pc, + const struct DebugPredictResult &pred, + const MonitorBreakpoints *breakpoints, + DebugContext *ctx) { + (void)breakpoints; + return over_at(start_pc, pred, ctx); + } + + // Step into: BRK at the predicted next PC. For JSR this enters the + // subroutine. For RTS / RTI the session must read the stack itself. + virtual Result trace(const DebugContext &from, + const struct DebugPredictResult &pred, + DebugContext *ctx) = 0; + virtual Result trace_at(uint16_t start_pc, + const struct DebugPredictResult &pred, + DebugContext *ctx) { + (void)start_pc; (void)pred; (void)ctx; + return DBG_NOT_SUPPORTED; + } + + // Step out: install BRK at the caller-side resume point inferred from + // the captured SP. Returns DBG_REFUSED when stack context is unsafe. + virtual Result step_out(const DebugContext &from, + DebugContext *ctx) = 0; + virtual Result step_out(const DebugContext &from, + const MonitorBreakpoints *breakpoints, + DebugContext *ctx) { + (void)breakpoints; + return step_out(from, ctx); + } + + // Resume execution honouring active breakpoints. Invalidates the context + // on the calling side. When `from.valid` is false (no prior capture), + // `start_pc` provides the address the CPU should jump to in order to + // start hitting breakpoints. Backends that can perform the start may + // honour it; a zero `start_pc` means "do not redirect" (the CPU keeps + // running wherever it is). + virtual Result go(const DebugContext &from, + const MonitorBreakpoints *breakpoints, + uint16_t start_pc) = 0; + + // Run until `target_pc` is hit, using a temporary non-visible breakpoint + // alongside the visible breakpoint table. If `from.valid` is false, the + // backend should start from `start_pc`. + virtual Result run_to(const DebugContext &from, + uint16_t target_pc, + const MonitorBreakpoints *breakpoints, + uint16_t start_pc, + DebugContext *ctx) + { + (void)from; (void)target_pc; (void)breakpoints; (void)start_pc; (void)ctx; + return DBG_NOT_SUPPORTED; + } + + // Restore every patched byte / vector / trampoline state. MUST be safe + // to call at any time (success, failure, mode change, destructor) and + // must be idempotent. + virtual void cleanup(void) = 0; + + // Stop Debugging without continuing the debug target. Backends with a + // parked CPU may use the supplied pre-debug context as the live resume + // context instead of resuming the most recent target debug PC. + virtual void cleanup_to_context(const DebugContext *ctx) + { + (void)ctx; + cleanup(); + } + + // True only when the backend currently owns a parked debug context that can + // be handed back to live execution later via cleanup_to_context(). This lets + // the monitor defer a no-breakpoint Freeze-mode G handoff until after UI + // teardown and ownership release, while leaving overlay and non-parked + // backends on the existing immediate path. + virtual bool has_parked_context_handoff(void) const { return false; } + + // True only when the backend can patch bytes in currently visible ROM + // windows (e.g. U64 volatile BASIC/KERNAL/CHAR images). Backends that + // cannot must leave this false so the shared BRK engine refuses visible + // ROM breakpoints before scribbling into the RAM underneath the ROM. + virtual bool supports_visible_rom_patching(void) const { return false; } + + // Fetch instruction bytes for step prediction from the live execution + // domain the debug session controls. This lets ROM-capable backends decode + // BASIC/KERNAL/CHAR instructions without changing the monitor's normal + // memory-view semantics. Returns false when the backend has no special + // source and the caller should fall back to regular backend reads. + virtual bool read_step_bytes(uint16_t address, uint8_t *dst, uint8_t len) + { + (void)address; (void)dst; (void)len; + return false; + } + + // Forget any cached CPU context so the next snapshot() reports "no context". + // Called when the user leaves Debug mode so re-entering starts the debugger + // from the current cursor position instead of the previous session's PC. + // Does not patch or run the machine; cleanup() still owns patch teardown. + virtual void forget_context(void) { } + + // Returns true when the most recent CPU-run window temporarily unfroze a + // frozen machine and subsequently refroze it. The firmware chrome rows (UI + // title and border lines) are overwritten by the live BASIC screen during + // the temporary unfreeze; callers that need a correct display must restore + // the chrome (e.g. via UserInterface::set_screen_title()) and redraw the + // monitor window before the user sees the result. + // Cleared at the start of the next CPU-run window. Always false in overlay + // mode because overlay sessions disable freeze/refreeze run windows. + virtual bool screen_render_target_invalidated(void) const { return false; } + + virtual bool claim_debug_ownership(bool remote) { (void)remote; return true; } + virtual void refresh_debug_ownership(void) { } + virtual void release_debug_ownership(void) { } +}; + +#endif diff --git a/software/monitor/monitor_debug_u2.cc b/software/monitor/monitor_debug_u2.cc new file mode 100644 index 000000000..c829f40af --- /dev/null +++ b/software/monitor/monitor_debug_u2.cc @@ -0,0 +1,125 @@ +// U2 (cartridge) Debug session. +// +// Thin subclass on top of BrkDebugSession. The shared base owns the BRK +// capture engine, the cassette-buffer trampoline layout, breakpoint patch +// tracking, and the sentinel polling loop. U2 supplies hardware hooks that +// drive the connected C64 through the cartridge: +// - begin/end stopped session bracket atomic vector/trampoline installs +// so the live C64 sees a single consistent transition +// - peek/poke use C64::peek / C64::poke (DMA into C64 RAM) +// - reset uses C64::reset +// - NMI pulse uses the cartridge C64_MODE_NMI register +// U2 does NOT support visible ROM patching, so BASIC/KERNAL stepping is only +// available when the code is actually executing from writable RAM (for +// example after an explicit RAM shadow copy or with the ROM banked out). + +#include "monitor_debug_u2.h" + +#if !defined(RUNS_ON_PC) + +#include "monitor_debug_brk_session.h" +#include "u2_memory_backend.h" +#include "c64.h" +#include "monitor_file_io.h" +#include "FreeRTOS.h" +#include "task.h" + +namespace { + +class U2DebugSession : public BrkDebugSession +{ + U2MemoryBackend *backend; + C64 *machine; + +protected: + virtual bool backend_ready(void) const { return machine != 0 && machine->exists(); } + virtual uint8_t current_cpu_port(void) const + { + return backend ? backend->get_live_cpu_port() : (uint8_t)0x07; + } + virtual bool begin_stopped_session(void) { return machine->begin_stopped_session(); } + virtual void end_stopped_session(bool stopped_it) { machine->end_stopped_session(stopped_it); } + virtual uint8_t peek_cpu(uint16_t address, uint8_t) + { + return machine->peek(address); + } + virtual void poke_cpu(uint16_t address, uint8_t byte, uint8_t) + { + machine->poke(address, byte); + } + virtual uint8_t peek_visible(uint16_t address) + { + return machine->peek(address); + } + virtual void poke_visible(uint16_t address, uint8_t byte) + { + machine->poke(address, byte); + } + virtual void unfreeze_if_accessible(void) + { + if (machine && machine->is_accessible()) { + machine->unfreeze(); + } + } + virtual bool machine_is_frozen(void) const + { + return machine ? machine->is_accessible() : false; + } + virtual void refreeze_machine(void) + { + if (machine) { + machine->refreeze(); + } + } + virtual bool reset_machine(void) + { + machine->reset(); + return true; + } + virtual void pulse_nmi_and_release(bool stopped_it) + { + // Same ordering as U64: NMI request raised while stopped, stopped + // session released so the CPU resumes and observes the edge, then + // the request cleared. + C64_MODE = C64_MODE_NMI; + machine->end_stopped_session(stopped_it); + C64_MODE = MODE_NORMAL; + } + virtual void delay_ms(int ms) + { + vTaskDelay(ms / portTICK_PERIOD_MS); + } + virtual bool free_run_no_breakpoint(uint16_t address) + { + monitor_io::jump_to(address); + return true; + } + +public: + explicit U2DebugSession(U2MemoryBackend *b) + : BrkDebugSession(), backend(b), machine(0) + { + machine = C64::getMachine(); + } + + // Restore patches/handler while this subclass' hooks are still live. The + // abstract base destructor must not call cleanup() (its hooks are pure by + // then), so the leaf owns the final safety-net cleanup. + virtual ~U2DebugSession() { cleanup(); } +}; + +} + +DebugSession *create_u2_debug_session(U2MemoryBackend *backend) +{ + return new U2DebugSession(backend); +} + +#else + +DebugSession *create_u2_debug_session(class U2MemoryBackend *) +{ + return 0; +} + +#endif diff --git a/software/monitor/monitor_debug_u2.h b/software/monitor/monitor_debug_u2.h new file mode 100644 index 000000000..ac8e740bb --- /dev/null +++ b/software/monitor/monitor_debug_u2.h @@ -0,0 +1,14 @@ +#ifndef MONITOR_DEBUG_U2_H +#define MONITOR_DEBUG_U2_H + +#include "monitor_debug_session.h" + +class U2MemoryBackend; + +// U2 (cartridge) Debug session implementation. Shares the BRK capture engine +// with the U64 backend through BrkDebugSession; U2 only supplies the +// hardware hooks. Lives in a separate file so host test builds do not pull +// in c64.h. +DebugSession *create_u2_debug_session(U2MemoryBackend *backend); + +#endif diff --git a/software/monitor/monitor_debug_u64.cc b/software/monitor/monitor_debug_u64.cc new file mode 100644 index 000000000..5310cb3f5 --- /dev/null +++ b/software/monitor/monitor_debug_u64.cc @@ -0,0 +1,339 @@ +// U64 Debug session. +// +// Thin subclass on top of BrkDebugSession. The shared base owns the BRK +// capture engine, the cassette-buffer trampoline layout, breakpoint patch +// tracking, and the sentinel polling loop. U64 only supplies hardware hooks +// (stopped-session bracketing, peek/poke, reset, NMI pulse) and the +// volatile-ROM patch override for BASIC/KERNAL/CHAR stepping. + +#include "monitor_debug_u64.h" + +#if !defined(RUNS_ON_PC) + +#include "monitor_debug_brk_session.h" +#include "u64_memory_backend.h" +#include "u64_machine.h" +#include "u64.h" +#include "monitor_file_io.h" +#include "itu.h" +#include "FreeRTOS.h" +#include "task.h" + +// Defined in c64.cc: flags the FPGA ROM image as patched so C64::reset() heals it +// before the booting CPU can execute a stale BRK left in KERNAL/BASIC ROM. +extern "C" void u64_mark_rom_image_dirty(void) __attribute__((weak)); + +namespace { + +class U64DebugSession : public BrkDebugSession +{ + U64MemoryBackend *backend; + U64Machine *machine; + struct RomPatchShadow { + bool used; + uint16_t address; + uint8_t cpu_port; + uint8_t byte; + }; + RomPatchShadow rom_patch_shadow[16]; + uint8_t rom_patch_shadow_next; + + // U64 BASIC/KERNAL/CHAR ROMs are served from volatile image buffers in + // U64_BASIC_BASE/U64_KERNAL_BASE/U64_CHARROM_BASE. Patch those buffers + // directly instead of copying ROMs into C64 RAM. No flash/config/file + // storage is touched, so a device reboot or ROM reload always restores + // the configured images even if a debug session dies before cleanup. + volatile uint8_t *rom_patch_ptr(uint16_t addr, uint8_t cpu_port) + { + cpu_port &= 0x07; + if (addr >= 0xA000 && addr <= 0xBFFF && ((cpu_port & 0x03) == 0x03)) { + return (volatile uint8_t *)(U64_BASIC_BASE + (addr - 0xA000)); + } + if (addr >= 0xD000 && addr <= 0xDFFF && + ((cpu_port & 0x03) != 0x00) && ((cpu_port & 0x04) == 0x00)) { + return (volatile uint8_t *)(U64_CHARROM_BASE + (addr - 0xD000)); + } + if (addr >= 0xE000 && (cpu_port & 0x02)) { + return (volatile uint8_t *)(U64_KERNAL_BASE + (addr - 0xE000)); + } + return 0; + } + + int find_rom_patch_shadow(uint16_t addr, uint8_t cpu_port) const + { + cpu_port &= 0x07; + for (int i = 0; i < (int)(sizeof(rom_patch_shadow) / sizeof(rom_patch_shadow[0])); i++) { + if (rom_patch_shadow[i].used && + rom_patch_shadow[i].address == addr && + rom_patch_shadow[i].cpu_port == cpu_port) { + return i; + } + } + return -1; + } + + void remember_rom_patch_shadow(uint16_t addr, uint8_t byte, uint8_t cpu_port) + { + cpu_port &= 0x07; + int slot = find_rom_patch_shadow(addr, cpu_port); + if (slot < 0) { + for (int i = 0; i < (int)(sizeof(rom_patch_shadow) / sizeof(rom_patch_shadow[0])); i++) { + if (!rom_patch_shadow[i].used) { + slot = i; + break; + } + } + } + if (slot < 0) { + slot = rom_patch_shadow_next; + rom_patch_shadow_next = (uint8_t)((rom_patch_shadow_next + 1) % + (sizeof(rom_patch_shadow) / sizeof(rom_patch_shadow[0]))); + } + rom_patch_shadow[slot].used = true; + rom_patch_shadow[slot].address = addr; + rom_patch_shadow[slot].cpu_port = cpu_port; + rom_patch_shadow[slot].byte = byte; + } + + void wait_for_cpu_visible_rom_byte(uint16_t addr, uint8_t cpu_port, uint8_t byte) + { + for (int i = 0; i < 8; i++) { + if (machine->peek_cpu(addr, cpu_port) == byte) { + return; + } + vTaskDelay(1); + } + } + +protected: + virtual bool backend_ready(void) const { return machine != 0; } + virtual uint8_t current_cpu_port(void) const + { + return u64_debug_step_cpu_port(backend); + } + virtual void note_captured_cpu_port(uint8_t cpu_port) + { + if (backend) { + backend->set_observed_live_cpu_port(cpu_port); + } + } + virtual bool begin_stopped_session(void) { return machine->begin_stopped_session(); } + virtual void end_stopped_session(bool stopped_it) { machine->end_stopped_session(stopped_it); } + virtual uint8_t peek_cpu(uint16_t address, uint8_t cpu_port) + { + volatile uint8_t *rom = rom_patch_ptr(address, cpu_port); + if (rom) { + // The U64 ROM image buffers are write targets, not authoritative + // read sources on every core. Read through the CPU-visible aperture + // so verification sees the byte the 6510 will fetch. + return machine->peek_cpu(address, cpu_port); + } + if (monitor_backing_store_for_cpu_port(address, cpu_port) == MONITOR_BACKING_IO) { + return machine->peek_visible(address); + } + return machine->peek_raw(address); + } + virtual void poke_cpu(uint16_t address, uint8_t byte, uint8_t cpu_port) + { + volatile uint8_t *rom = rom_patch_ptr(address, cpu_port); + if (rom) { + *rom = byte; + if (u64_mark_rom_image_dirty) u64_mark_rom_image_dirty(); + remember_rom_patch_shadow(address, byte, cpu_port); + wait_for_cpu_visible_rom_byte(address, cpu_port, byte); + return; + } + if (monitor_backing_store_for_cpu_port(address, cpu_port) == MONITOR_BACKING_IO) { + machine->poke_visible(address, byte); + return; + } + machine->poke_raw(address, byte); + } + virtual uint8_t peek_visible(uint16_t address) + { + return machine->peek_visible(address); + } + virtual void poke_visible(uint16_t address, uint8_t byte) + { + machine->poke_visible(address, byte); + } + virtual void poke_visible_preserving_freeze_restore(uint16_t address, + uint8_t byte) + { + machine->poke_visible_preserving_freeze_restore(address, byte); + } + virtual void unfreeze_if_accessible(void) + { + if (machine && machine->is_accessible()) { + machine->unfreeze(); + } + } + virtual bool machine_is_frozen(void) const + { + return machine ? machine->is_accessible() : false; + } + virtual void refreeze_machine(void) + { + if (machine) { + machine->refreeze(); + } + } + virtual bool reset_machine(void) + { + return backend ? backend->reset_machine() : false; + } + virtual void pulse_nmi_and_release(bool stopped_it) + { + // Raise the NMI request while the CPU is still stopped, release the + // stop so the CPU resumes and observes the pending edge, then clear + // the request. This order is required: clearing before the release + // would let the CPU exit the stopped session without ever seeing the + // NMI edge. + C64_MODE = C64_MODE_NMI; + machine->end_stopped_session(stopped_it); + C64_MODE = MODE_NORMAL; + } + virtual bool begin_clean_stopped_session(void) + { + // Patched high-memory release path. A raster-synced stop pairs the launch + // with the mode-1 resume used by the reliable freeze path, so the live CPU + // observes freshly armed high-memory BRKs on release. + return machine->begin_stopped_session(true); + } + virtual void settle_visible_rom_for_live_fetch(bool sustained) + { + // Overlay/Telnet only. A visible-ROM byte has just been (re)written into + // the FPGA ROM image while the machine is stopped. The CPU-visible DMA + // aperture can read the new byte before the live instruction-fetch path + // observes it, so clock the CPU, then stop again for the controlled + // launch. The caller clears any stale sentinel afterwards. + // + // Two regimes: + // - Default (short): a freshly INSTALLED BRK or an ordinary forward + // single-step launch byte. A brief clock is enough and keeps stepping + // responsive; a long continuous run here destabilises forward stepping. + // - Sustained (long): a RESTORED launch opcode that the live 6510 keeps + // re-trapping on. The CPU instruction-fetch ROM copy refreshes from + // the image buffer only during sustained continuous core execution - + // NOT from the image write alone, and NOT from fragmented brief + // settles (six 500us settles across the relaunch budget failed + // deterministically because each stop/start aborts the refresh). One + // longer continuous run reliably lands the restored byte in the fetch + // path. Used only on the re-trap relaunch, so the cost is paid only + // when actually needed. + if (!machine || machine->is_accessible()) { + return; + } + machine->end_stopped_session(true); + wait_10us(sustained ? 5000 : 50); + machine->begin_stopped_session(); + } + virtual void request_staged_nmi(void) + { + C64_MODE = C64_MODE_NMI; + } + virtual void clear_staged_nmi(void) + { + wait_10us(1); + C64_MODE = MODE_NORMAL; + } + virtual void delay_ms(int ms) + { + vTaskDelay(ms / portTICK_PERIOD_MS); + } + virtual bool free_run_no_breakpoint(uint16_t address) + { + if (backend) { + backend->clear_observed_live_cpu_port(); + } + monitor_io::jump_to(address); + return true; + } + + // U64 ROM-image patching: route patch reads/writes through the volatile + // ROM image buffers for BASIC/KERNAL/CHAR ranges so we can step KERNAL + // code without copying ROMs into C64 RAM. + virtual bool supports_visible_rom_patching(void) const { return true; } + virtual uint8_t read_patch_byte(uint16_t addr, uint8_t cpu_port) + { + volatile uint8_t *rom = rom_patch_ptr(addr, cpu_port); + if (rom) { + // Keep reads aligned with actual 6510 fetches. The volatile ROM + // image pointer remains the write target only. + return machine->peek_cpu(addr, cpu_port); + } + if (monitor_backing_store_for_cpu_port(addr, cpu_port) == MONITOR_BACKING_IO) { + return machine->peek_visible(addr); + } + return machine->peek_raw(addr); + } + virtual bool read_step_bytes(uint16_t address, uint8_t *dst, uint8_t len) + { + if (!dst) { + return false; + } + uint8_t cpu_port = current_cpu_port(); + for (uint8_t i = 0; i < len; i++) { + uint16_t current = (uint16_t)(address + i); + if (backend && backend->get_monitor_cpu_port() == cpu_port && + monitor_backing_store_is_visible_rom( + monitor_backing_store_for_cpu_port(current, cpu_port))) { + dst[i] = backend->read(current); + } else { + dst[i] = read_patch_byte(current, cpu_port); + } + } + return true; + } + virtual void write_patch_byte(uint16_t addr, uint8_t byte, uint8_t cpu_port) + { + volatile uint8_t *rom = rom_patch_ptr(addr, cpu_port); + if (rom) { + *rom = byte; + if (u64_mark_rom_image_dirty) u64_mark_rom_image_dirty(); + remember_rom_patch_shadow(addr, byte, cpu_port); + wait_for_cpu_visible_rom_byte(addr, cpu_port, byte); + return; + } + if (monitor_backing_store_for_cpu_port(addr, cpu_port) == MONITOR_BACKING_IO) { + machine->poke_visible(addr, byte); + return; + } + machine->poke_raw(addr, byte); + } + +public: + explicit U64DebugSession(U64MemoryBackend *b) + : BrkDebugSession(), backend(b), machine(0) + { + machine = (U64Machine *)C64::getMachine(); + rom_patch_shadow_next = 0; + for (int i = 0; i < (int)(sizeof(rom_patch_shadow) / sizeof(rom_patch_shadow[0])); i++) { + rom_patch_shadow[i].used = false; + rom_patch_shadow[i].address = 0; + rom_patch_shadow[i].cpu_port = 0; + rom_patch_shadow[i].byte = 0; + } + } + + // Restore patches/handler while this subclass' hooks are still live. The + // abstract base destructor must not call cleanup() (its hooks are pure by + // then), so the leaf owns the final safety-net cleanup. + virtual ~U64DebugSession() { cleanup(); } +}; + +} + +DebugSession *create_u64_debug_session(U64MemoryBackend *backend) +{ + return new U64DebugSession(backend); +} + +#else + +DebugSession *create_u64_debug_session(class U64MemoryBackend *) +{ + return 0; +} + +#endif diff --git a/software/monitor/monitor_debug_u64.h b/software/monitor/monitor_debug_u64.h new file mode 100644 index 000000000..3dd057d6c --- /dev/null +++ b/software/monitor/monitor_debug_u64.h @@ -0,0 +1,18 @@ +#ifndef MONITOR_DEBUG_U64_H +#define MONITOR_DEBUG_U64_H + +#include "memory_backend.h" +#include "monitor_debug_session.h" + +class U64MemoryBackend; + +static inline uint8_t u64_debug_step_cpu_port(MemoryBackend *backend) +{ + return backend ? backend->get_live_cpu_port() : (uint8_t)0x07; +} + +// U64-specific Debug session implementation. Lives in a separate file so the +// host test build does not pull in `c64.h` / `u64_machine.h`. +DebugSession *create_u64_debug_session(U64MemoryBackend *backend); + +#endif diff --git a/software/monitor/monitor_file_io.cc b/software/monitor/monitor_file_io.cc new file mode 100644 index 000000000..ab78295e0 --- /dev/null +++ b/software/monitor/monitor_file_io.cc @@ -0,0 +1,464 @@ +// Firmware-only implementation of the monitor file/jump helpers. +// Included from userinterface.cc so it shares the same translation unit. +// Host-test builds supply a stub instead — see software/test/monitor/. + +#include "monitor_file_io.h" +#include "machine_monitor.h" +#include "userinterface.h" +#include "tree_browser.h" +#include "tree_browser_state.h" +#include "browsable_root.h" +#include "monitor_save_browsable.h" +#include "user_file_interaction.h" +#include "filemanager.h" +#include "file.h" +#include "mystring.h" +#include "host.h" +#include "memory_backend.h" +#ifndef RECOVERYAPP +#ifndef UPDATER +#include "c64.h" +#include "subsys.h" +#if defined(U64) && (U64) +#include "u64_machine.h" +#include "itu.h" +#endif +#endif +#endif + +namespace { + +// Persistent path used to resume the monitor's file picker in the directory +// last seen across LOAD/SAVE invocations. File-scope to avoid touching the +// MachineMonitorState header that's shared with the host test. +mstring s_monitor_browse_path("/"); + +static const uint16_t c_monitor_nmi_vector = 0x0318; +static const uint16_t c_monitor_jump_trampoline = 0x033C; +static const uint16_t c_monitor_cpu_ddr = 0x0000; +static const uint16_t c_monitor_cpu_port = 0x0001; +static const uint16_t c_monitor_hard_nmi_vector = 0xFFFA; +static const uint8_t c_monitor_hard_nmi_cpu_port = 0x05; + +#if !defined(RECOVERYAPP) && !defined(UPDATER) && defined(U64) && (U64) +static uint8_t monitor_effective_cpu_port(const DebugContext *context) +{ + if (context && context->valid) { + if (context->live_cpu_port_valid) { + return (uint8_t)(context->live_cpu_port & 0x07); + } + if (context->cpu_port_registers_valid) { + return (uint8_t)(((context->cpu_port_latch & context->cpu_ddr) | + ((uint8_t)(~context->cpu_ddr) & 0x07)) & 0x07); + } + } + return 0x07; +} + +static bool monitor_cpu_port_maps_kernal_ram(uint8_t cpu_port) +{ + return (cpu_port & 0x02) == 0; +} + +static void monitor_append_lda_sta_abs(uint8_t *bytes, unsigned *pos, + uint16_t address, uint8_t value) +{ + bytes[(*pos)++] = 0xA9; + bytes[(*pos)++] = value; + bytes[(*pos)++] = 0x8D; + bytes[(*pos)++] = (uint8_t)(address & 0xFF); + bytes[(*pos)++] = (uint8_t)(address >> 8); +} + +static void monitor_append_lda_sta_zp(uint8_t *bytes, unsigned *pos, + uint8_t address, uint8_t value) +{ + bytes[(*pos)++] = 0xA9; + bytes[(*pos)++] = value; + bytes[(*pos)++] = 0x85; + bytes[(*pos)++] = address; +} + +static bool run_u64_nmi_trampoline(U64Machine *machine, + const uint8_t *body, unsigned body_len, + const DebugContext *context = 0, + bool pulse_nmi = true) +{ + if (!machine || !body) { + return false; + } + if (!pulse_nmi && !machine->is_stopped()) { + return false; + } + + bool stopped_it = machine->begin_stopped_session(); + uint8_t old_nmi_lo = machine->peek_visible(c_monitor_nmi_vector + 0); + uint8_t old_nmi_hi = machine->peek_visible(c_monitor_nmi_vector + 1); + bool restore_cpu_port = context && context->valid && + context->cpu_port_registers_valid; + uint8_t effective_cpu_port = monitor_effective_cpu_port(context); + bool install_hard_nmi = context && context->valid && + monitor_cpu_port_maps_kernal_ram(effective_cpu_port); + uint8_t old_hard_nmi_lo = 0; + uint8_t old_hard_nmi_hi = 0; + uint8_t trampoline[64]; + unsigned pos = 0; + + monitor_append_lda_sta_abs(trampoline, &pos, c_monitor_nmi_vector + 0, + old_nmi_lo); + monitor_append_lda_sta_abs(trampoline, &pos, c_monitor_nmi_vector + 1, + old_nmi_hi); + + if (install_hard_nmi) { + old_hard_nmi_lo = machine->peek_cpu(c_monitor_hard_nmi_vector + 0, + c_monitor_hard_nmi_cpu_port); + old_hard_nmi_hi = machine->peek_cpu(c_monitor_hard_nmi_vector + 1, + c_monitor_hard_nmi_cpu_port); + monitor_append_lda_sta_abs(trampoline, &pos, + c_monitor_hard_nmi_vector + 0, + old_hard_nmi_lo); + monitor_append_lda_sta_abs(trampoline, &pos, + c_monitor_hard_nmi_vector + 1, + old_hard_nmi_hi); + } + + if (restore_cpu_port) { + monitor_append_lda_sta_zp(trampoline, &pos, + (uint8_t)c_monitor_cpu_ddr, + context->cpu_ddr); + monitor_append_lda_sta_zp(trampoline, &pos, + (uint8_t)c_monitor_cpu_port, + context->cpu_port_latch); + } + + if (pos + body_len > sizeof(trampoline)) { + machine->end_stopped_session(stopped_it); + return false; + } + for (unsigned i = 0; i < body_len; i++) { + trampoline[pos++] = body[i]; + } + + for (unsigned i = 0; i < pos; i++) { + machine->poke_visible_preserving_freeze_restore( + (uint16_t)(c_monitor_jump_trampoline + i), trampoline[i]); + } + machine->poke_visible_preserving_freeze_restore( + c_monitor_nmi_vector + 0, + (uint8_t)(c_monitor_jump_trampoline & 0xFF)); + machine->poke_visible_preserving_freeze_restore( + c_monitor_nmi_vector + 1, + (uint8_t)(c_monitor_jump_trampoline >> 8)); + if (install_hard_nmi) { + machine->poke_cpu(c_monitor_hard_nmi_vector + 0, + (uint8_t)(c_monitor_jump_trampoline & 0xFF), + c_monitor_hard_nmi_cpu_port); + machine->poke_cpu(c_monitor_hard_nmi_vector + 1, + (uint8_t)(c_monitor_jump_trampoline >> 8), + c_monitor_hard_nmi_cpu_port); + } + + if (pulse_nmi) { + C64_MODE = C64_MODE_NMI; + } + machine->end_stopped_session(stopped_it); + if (pulse_nmi) { + C64_MODE = MODE_NORMAL; + } + return true; +} +#endif + +} // namespace + +bool monitor_io::pick_file(UserInterface *ui, const char *title, + char *path_out, int path_max, + char *name_out, int name_max, + bool save_mode) +{ + (void)title; + + if (path_out && path_max > 0) path_out[0] = 0; + if (name_out && name_max > 0) name_out[0] = 0; + + if (!ui) { + return false; + } + + Browsable *root = save_mode ? static_cast(new MonitorSaveBrowsableRoot()) + : static_cast(new BrowsableRoot()); + TreeBrowser *browser = new TreeBrowser(ui, root); + browser->allow_exit = true; + browser->use_ui_focus_stack = false; + browser->pick_mode = save_mode ? TreeBrowser::PICK_SAVE : TreeBrowser::PICK_LOAD; + browser->init(); + if (s_monitor_browse_path.length() > 1) { + browser->cd(s_monitor_browse_path.c_str()); + } + + int ret = 0; + GenericHost *h = ui->host; + while (!ret && (!h || h->exists())) { + ret = browser->poll(0); + } + + bool picked = browser->picked; + if (picked) { + if (path_out) { + strncpy(path_out, browser->picked_path.c_str(), path_max - 1); + path_out[path_max - 1] = 0; + } + if (name_out) { + strncpy(name_out, browser->picked_name.c_str(), name_max - 1); + name_out[name_max - 1] = 0; + } + s_monitor_browse_path = browser->picked_path; + } + + browser->deinit(); + delete browser; + delete root; + return picked; +} + +const char *monitor_io::load_into_memory(const char *path, const char *name, + MemoryBackend *backend, uint16_t start_addr, + bool use_prg_addr, uint32_t offset, + bool length_auto, uint32_t length, + uint16_t *out_start_addr, uint32_t *out_bytes) +{ + FileManager *fm = FileManager::getFileManager(); + File *f = NULL; + FRESULT res = fm->fopen(path, name, FA_READ, &f); + if (res != FR_OK || !f) { + return "OPEN FAILED"; + } + uint32_t size = f->get_size(); + uint32_t header_skip = 0; + if (use_prg_addr) { + if (size < 2) { + fm->fclose(f); + return "NOT A PRG"; + } + uint8_t hdr[2]; + uint32_t got = 0; + if (f->read(hdr, 2, &got) != FR_OK || got != 2) { + fm->fclose(f); + return "READ FAILED"; + } + start_addr = (uint16_t)(hdr[0] | (hdr[1] << 8)); + header_skip = 2; + size -= 2; + } + uint32_t effective = 0; + MonitorError verr = monitor_validate_load_size(size, offset, length_auto, length, &effective); + if (verr == MONITOR_RANGE && !length_auto && length > 65536) { + fm->fclose(f); + return "LOAD TOO LARGE (>64K)"; + } + if (verr == MONITOR_RANGE && length_auto && size > offset && (size - offset) > 65536) { + fm->fclose(f); + return "LOAD TOO LARGE (>64K)"; + } + if (verr != MONITOR_OK) { + fm->fclose(f); + return monitor_error_text(verr); + } + // Reject loads that would wrap past $FFFF — silently corrupting low memory + // (zero page, stack) is a far worse outcome than an explicit error. + if ((uint32_t)start_addr + effective > 0x10000) { + fm->fclose(f); + return "LOAD WRAPS PAST $FFFF"; + } + if (f->seek(header_skip + offset) != FR_OK) { + fm->fclose(f); + return "SEEK FAILED"; + } + + uint8_t buf[512]; + uint32_t remaining = effective; + uint32_t mem_pos = 0; + backend->begin_session(); + while (remaining > 0) { + uint32_t want = remaining > sizeof(buf) ? sizeof(buf) : remaining; + uint32_t got = 0; + if (f->read(buf, want, &got) != FR_OK || got == 0) { + break; + } + for (uint32_t i = 0; i < got; i++) { + backend->write((uint16_t)(start_addr + mem_pos + i), buf[i]); + } + mem_pos += got; + remaining -= got; + } + // BASIC PRG fix-up: when loading into the BASIC text area at $0801, refresh + // the runtime pointers so RUN/LIST do not walk into garbage. Without this + // the C64 routinely crashes when the user runs a freshly-loaded PRG — + // which in turn can take down the application hosting the monitor. + if (start_addr == 0x0801 && mem_pos > 0) { + uint32_t end_addr32 = (uint32_t)start_addr + mem_pos; + if (end_addr32 > 0x10000) end_addr32 = 0x10000; + uint16_t end_addr = (uint16_t)end_addr32; + uint8_t lo = (uint8_t)(end_addr & 0xFF); + uint8_t hi = (uint8_t)((end_addr >> 8) & 0xFF); + backend->write(0x002D, lo); backend->write(0x002E, hi); // VARTAB + backend->write(0x002F, lo); backend->write(0x0030, hi); // ARYTAB + backend->write(0x0031, lo); backend->write(0x0032, hi); // STREND + backend->write(0x00AE, lo); backend->write(0x00AF, hi); // last load addr + } + backend->end_session(); + fm->fclose(f); + if (remaining > 0) { + return "READ FAILED"; + } + if (out_start_addr) *out_start_addr = start_addr; + if (out_bytes) *out_bytes = mem_pos; + return NULL; +} + +const char *monitor_io::save_from_memory(UserInterface *ui, const char *path, const char *name, + MemoryBackend *backend, + uint16_t start, uint16_t end) +{ + FileManager *fm = FileManager::getFileManager(); + File *f = NULL; + FRESULT res = create_file_ask_if_exists(fm, ui, path, name, &f); + if (res != FR_OK || !f) { + return "CREATE FAILED"; + } + // Write a standard C64 PRG header: little-endian start address. This makes + // the file round-trip correctly through LOAD with PRG-address mode. + uint8_t hdr[2]; + hdr[0] = (uint8_t)(start & 0xFF); + hdr[1] = (uint8_t)((start >> 8) & 0xFF); + { + uint32_t written = 0; + if (f->write(hdr, 2, &written) != FR_OK || written != 2) { + fm->fclose(f); + return "WRITE FAILED"; + } + } + uint8_t buf[512]; + uint32_t total = (uint32_t)end - (uint32_t)start + 1; + uint32_t pos = 0; + backend->begin_session(); + while (pos < total) { + uint32_t want = total - pos; + if (want > sizeof(buf)) want = sizeof(buf); + for (uint32_t i = 0; i < want; i++) { + buf[i] = backend->read((uint16_t)(start + pos + i)); + } + uint32_t written = 0; + if (f->write(buf, want, &written) != FR_OK || written != want) { + backend->end_session(); + fm->fclose(f); + return "WRITE FAILED"; + } + pos += want; + } + backend->end_session(); + fm->fclose(f); + return NULL; +} + +void monitor_io::jump_to(uint16_t address) +{ +#if !defined(RECOVERYAPP) && !defined(UPDATER) +#if defined(U64) && (U64) + U64Machine *machine = static_cast(C64::getMachine()); + const uint8_t body[] = { + 0x4C, (uint8_t)(address & 0xFF), (uint8_t)(address >> 8) + }; + run_u64_nmi_trampoline(machine, body, sizeof(body)); +#else + uint8_t jump_buffer[2] = { + (uint8_t)(address & 0xFF), + (uint8_t)(address >> 8) + }; + + SubsysCommand *cmd = new SubsysCommand(NULL, SUBSYSID_C64, C64_DMA_BUFFER, + RUNCODE_DMALOAD_JUMP, + jump_buffer, sizeof(jump_buffer)); + cmd->execute(); +#endif +#else + (void)address; +#endif +} + +void monitor_io::resume_to_context(const DebugContext &context) +{ +#if !defined(RECOVERYAPP) && !defined(UPDATER) +#if defined(U64) && (U64) + U64Machine *machine = static_cast(C64::getMachine()); + const uint8_t body[] = { + 0xA2, context.sp, + 0x9A, + 0xA9, (uint8_t)(context.pc >> 8), + 0x48, + 0xA9, (uint8_t)(context.pc & 0xFF), + 0x48, + 0xA9, context.sr, + 0x48, + 0xA0, context.y, + 0xA2, context.x, + 0xA9, context.a, + 0x40 + }; + run_u64_nmi_trampoline(machine, body, sizeof(body), &context); +#else + jump_to(context.pc); +#endif +#else + (void)context; +#endif +} + +bool monitor_io::stage_jump_to(uint16_t address) +{ +#if !defined(RECOVERYAPP) && !defined(UPDATER) && defined(U64) && (U64) + U64Machine *machine = static_cast(C64::getMachine()); + const uint8_t body[] = { + 0x4C, (uint8_t)(address & 0xFF), (uint8_t)(address >> 8) + }; + return run_u64_nmi_trampoline(machine, body, sizeof(body), 0, false); +#else + (void)address; + return false; +#endif +} + +bool monitor_io::stage_resume_to_context(const DebugContext &context) +{ +#if !defined(RECOVERYAPP) && !defined(UPDATER) && defined(U64) && (U64) + U64Machine *machine = static_cast(C64::getMachine()); + const uint8_t body[] = { + 0xA2, context.sp, + 0x9A, + 0xA9, (uint8_t)(context.pc >> 8), + 0x48, + 0xA9, (uint8_t)(context.pc & 0xFF), + 0x48, + 0xA9, context.sr, + 0x48, + 0xA0, context.y, + 0xA2, context.x, + 0xA9, context.a, + 0x40 + }; + return run_u64_nmi_trampoline(machine, body, sizeof(body), &context, + false); +#else + (void)context; + return false; +#endif +} + +void monitor_io::pulse_staged_nmi(void) +{ +#if !defined(RECOVERYAPP) && !defined(UPDATER) && defined(U64) && (U64) + C64_MODE = C64_MODE_NMI; + wait_10us(1); + C64_MODE = MODE_NORMAL; +#endif +} diff --git a/software/monitor/monitor_file_io.h b/software/monitor/monitor_file_io.h new file mode 100644 index 000000000..993b6cd87 --- /dev/null +++ b/software/monitor/monitor_file_io.h @@ -0,0 +1,59 @@ +#ifndef MONITOR_FILE_IO_H +#define MONITOR_FILE_IO_H + +#include + +class UserInterface; +class MemoryBackend; +struct DebugContext; + +// Glue layer between the machine code monitor and shared infrastructure +// (TreeBrowser, FileManager, SubsysCommand). These helpers exist so that +// monitor-specific wiring does not bloat the UserInterface class. Host-test +// builds provide stub implementations. +namespace monitor_io { + +// Open the standard TreeBrowser in pick mode and return the user's selection. +// `save_mode` switches between LOAD and SAVE picker semantics. SAVE mode can +// return the current directory with an empty filename so the caller can prompt +// for a new filename, while existing-file selection comes back as path + name. +// Returns true if the user picked something, false on ESC / cancel. +bool pick_file(UserInterface *ui, const char *title, + char *path_out, int path_max, + char *name_out, int name_max, + bool save_mode); + +// Read the file at / into the C64 address space via the supplied +// memory backend. When `use_prg_addr` is true the first two bytes of the file +// are consumed as the load address and override `start_addr`. `offset` and +// `length` (in bytes; `length_auto` means "until end of file") describe the +// range of the file to load. When non-NULL, `out_start_addr` and `out_bytes` +// receive the actual destination start address (after PRG-header resolution) +// and the number of bytes that were written into memory — used by the caller +// to render a confirmation overlay. Returns NULL on success, or a static +// error string suitable for popup display. +const char *load_into_memory(const char *path, const char *name, + MemoryBackend *backend, uint16_t start_addr, + bool use_prg_addr, uint32_t offset, + bool length_auto, uint32_t length, + uint16_t *out_start_addr, uint32_t *out_bytes); + +// Save the C64 memory range [start..end] to /. The shared overwrite +// helper (`create_file_ask_if_exists`) is used, hence the UI parameter. +// Returns NULL on success, otherwise a static error string. +const char *save_from_memory(UserInterface *ui, const char *path, const char *name, + MemoryBackend *backend, + uint16_t start, uint16_t end); + +// Instruct the FPGA C64 to commence execution at `address` once the monitor +// (and freezer) is left. U64 uses a KERNAL RAM NMI trampoline; cartridge +// targets reuse the existing boot-cartridge DMA jump handoff. +void jump_to(uint16_t address); +void resume_to_context(const DebugContext &context); +bool stage_jump_to(uint16_t address); +bool stage_resume_to_context(const DebugContext &context); +void pulse_staged_nmi(void); + +} // namespace monitor_io + +#endif diff --git a/software/monitor/monitor_init.cc b/software/monitor/monitor_init.cc new file mode 100644 index 000000000..3bb11544f --- /dev/null +++ b/software/monitor/monitor_init.cc @@ -0,0 +1,77 @@ +/* + * monitor_init.cc + * + * Created on: May 1, 2026 + */ + +#include "monitor_init.h" + +#include "c64.h" +#include "subsys.h" +#include "tasks_collection.h" +#include "userinterface.h" +#if U64 +#include "u64_machine.h" +#include "u64_memory_backend.h" +#elif !defined(RECOVERYAPP) +#include "u2_memory_backend.h" +#endif + +namespace { +static Action *machine_monitor_actions[256]; + +#if U64 +static SubsysResultCode_e u64_run_machine_monitor(SubsysCommand *cmd) +{ + if (!cmd->user_interface) { + return SSRET_NO_USER_INTERFACE; + } + + U64MemoryBackend monitor_backend((U64Machine *)C64::getMachine()); + cmd->user_interface->run_machine_monitor(&monitor_backend); + return SSRET_OK; +} +#elif !defined(RECOVERYAPP) +static SubsysResultCode_e c64_run_machine_monitor(SubsysCommand *cmd) +{ + if (!cmd->user_interface) { + return SSRET_NO_USER_INTERFACE; + } + + U2MemoryBackend monitor_backend(C64::getMachine()); + cmd->user_interface->run_machine_monitor(&monitor_backend); + return SSRET_OK; +} +#endif +} + +Action *register_machine_monitor_task(int subsys_id, actionFunction_t callback, int function_id) +{ + Action *monitor = new Action("Machine Code Monitor", callback, function_id); + TaskCategory *dev = TasksCollection::getCategory("Developer", SORT_ORDER_DEVELOPER); + dev->prepend(monitor); + if ((subsys_id >= 0) && (subsys_id < 256)) { + machine_monitor_actions[subsys_id] = monitor; + } + return monitor; +} + +Action *get_machine_monitor_task(int subsys_id) +{ + if ((subsys_id < 0) || (subsys_id >= 256)) { + return NULL; + } + return machine_monitor_actions[subsys_id]; +} + +#if U64 +Action *register_u64_machine_monitor_task(int function_id) +{ + return register_machine_monitor_task(SUBSYSID_U64, u64_run_machine_monitor, function_id); +} +#elif !defined(RECOVERYAPP) +Action *register_c64_machine_monitor_task(int function_id) +{ + return register_machine_monitor_task(SUBSYSID_C64, c64_run_machine_monitor, function_id); +} +#endif diff --git a/software/monitor/monitor_init.h b/software/monitor/monitor_init.h new file mode 100644 index 000000000..715ae5201 --- /dev/null +++ b/software/monitor/monitor_init.h @@ -0,0 +1,18 @@ +/* + * monitor_init.h + * + * Created on: May 1, 2026 + */ + +#ifndef MONITOR_INIT_H_ +#define MONITOR_INIT_H_ + +#include "action.h" + +Action *register_machine_monitor_task(int subsys_id, actionFunction_t callback, int function_id) __attribute__((weak)); +Action *get_machine_monitor_task(int subsys_id) __attribute__((weak)); +Action *register_u64_machine_monitor_task(int function_id) __attribute__((weak)); +Action *register_c64_machine_monitor_task(int function_id) __attribute__((weak)); +extern "C" bool machine_monitor_request_global_reset_cancel(void) __attribute__((weak)); + +#endif /* MONITOR_INIT_H_ */ diff --git a/software/monitor/monitor_save_browsable.h b/software/monitor/monitor_save_browsable.h new file mode 100644 index 000000000..c75f50950 --- /dev/null +++ b/software/monitor/monitor_save_browsable.h @@ -0,0 +1,90 @@ +#ifndef MONITOR_SAVE_BROWSABLE_H +#define MONITOR_SAVE_BROWSABLE_H + +#include "browsable.h" +#include "browsable_root.h" +#include "filemanager.h" +#include "small_printf.h" + +class MonitorSaveSelectFolderEntry : public Browsable +{ +public: + MonitorSaveSelectFolderEntry() { selectable = true; } + + const char *getName() { return "<< Create new file >>"; } + + void getDisplayString(char *buffer, int width) + { + getDisplayString(buffer, width, 0); + } + + void getDisplayString(char *buffer, int width, int squeeze_option) + { + (void)squeeze_option; + if (width <= 0) return; + const char *label = getName(); + int len = (int)strlen(label); + if (len > width - 1) len = width - 1; + memcpy(buffer, label, len); + buffer[len] = 0; + } + + bool pickAsCurrentPath() { return true; } +}; + +static inline void monitor_save_prepend_synthetic(IndexedList &children) +{ + children.append(new MonitorSaveSelectFolderEntry()); + for (int i = children.get_elements() - 1; i > 0; i--) { + children.swap(i, i - 1); + } +} + +class MonitorSaveDirEntry : public BrowsableDirEntry +{ +public: + MonitorSaveDirEntry(Path *pp, Browsable *parent, FileInfo *info, bool sel) + : BrowsableDirEntry(pp, parent, info, sel) {} + +protected: + Browsable *makeChildEntry(Path *parent_path, FileInfo *info, bool selectable) + { + return new MonitorSaveDirEntry(parent_path, this, info, selectable); + } + +public: + IndexedList *getSubItems(int &error) + { + IndexedList *list = BrowsableDirEntry::getSubItems(error); + // Inject the synthetic "<< Create new file >>" entry on any successful + // listing — covers + // ordinary directories AND mountable disk images (D64/T64/G64/D81/...) + // since FileManager surfaces their contents through get_directory(). + // Plain non-mountable files have error<0 here, so they're skipped. + if (error == 0 && list) { + bool already = false; + for (int i = 0; i < list->get_elements() && !already; i++) { + Browsable *b = (*list)[i]; + if (b && b->pickAsCurrentPath()) already = true; + } + if (!already) { + monitor_save_prepend_synthetic(*list); + } + } + return list; + } +}; + +// Root listing only injects the typed children — no synthetic save entry. +// The root holds mount points (USB, Flash, Temp, network), none of which is a +// writable destination on its own; offering "save here" there would mislead. +class MonitorSaveBrowsableRoot : public BrowsableRoot +{ +protected: + Browsable *makeChildEntry(Path *parent_path, FileInfo *info, bool selectable) + { + return new MonitorSaveDirEntry(parent_path, this, info, selectable); + } +}; + +#endif // MONITOR_SAVE_BROWSABLE_H diff --git a/software/monitor/run_machine_monitor.cc b/software/monitor/run_machine_monitor.cc new file mode 100644 index 000000000..25dd6f1f4 --- /dev/null +++ b/software/monitor/run_machine_monitor.cc @@ -0,0 +1,173 @@ +#include "userinterface.h" +#include "machine_monitor.h" +#include "monitor_file_io.h" +#if !defined(RUNS_ON_PC) +#include "c64.h" +#endif + +namespace { +static MachineMonitor *active_reset_monitor = 0; +} + +void UserInterface :: run_machine_monitor(MemoryBackend *backend) +{ + bool reopen_after_reset; + do { + MachineMonitor *monitor = new MachineMonitor(this, backend); + uint16_t go_address = 0; + DebugContext go_context; + bool go_has_context = false; + bool direct_render_target = false; + reopen_after_reset = false; +#if !defined(RUNS_ON_PC) + C64 *debug_render_machine = C64::getMachine(); + // After a C=+X reset the C64 is running again, so the firmware + // overlay it was rendering into has lost ownership of screen RAM: + // the live BASIC start-up writes are clobbering everything the new + // monitor draws. Re-take ownership before init() so the firmware + // gets the screen back, then redraw the chrome (title bar + border + // separators) so the new monitor sees a clean canvas. The first-ever + // monitor entry from the freezer menu already has is_accessible() + // true, so this is a no-op there; non-C64-hosted UIs (telnet) skip + // it because host != machine. + if (debug_render_machine && host == debug_render_machine && + !debug_render_machine->is_accessible()) { + debug_render_machine->take_ownership(this); + if (screen) { + set_screen_title(); + } + } + bool c64_render_target = debug_render_machine && host == debug_render_machine && + debug_render_machine->is_accessible(); + direct_render_target = debug_render_machine && screen && + !screen->prefers_full_refresh(); + monitor->set_debug_run_window_refreeze_enabled(c64_render_target); + monitor->set_reset_exits_monitor( + direct_render_target || + (debug_render_machine && + (host == debug_render_machine || (host && host->is_permanent())))); +#else + monitor->set_debug_run_window_refreeze_enabled(false); + monitor->set_reset_exits_monitor(false); +#endif + active_machine_monitor = monitor; + active_reset_monitor = monitor; + monitor->init(screen, keyboard); + int ret = 0; + while(!ret && host->exists()) { + ret = monitor->poll(0); + } + bool exit_ui = ret == MENU_EXIT; + // C=+I inside the monitor routes to swap_interface_type(), which toggles + // the persisted UI mode and returns MENU_HIDE. Unlike a normal monitor + // exit (which returns to the launching menu) the user expects the whole + // monitor + menu/browser UI to close so they land back on the live + // machine and the next monitor open uses the new mode. Escalate MENU_HIDE + // to a full UI teardown (mirrors the browser's own C=+I handler). + bool swap_close = ret == MENU_HIDE; + bool do_go = monitor->consume_pending_go(&go_address, &go_context, + &go_has_context); + bool release_after_exit = monitor->consume_release_host_after_exit(); + bool deferred_debug_go = monitor->has_deferred_debug_go(); + reopen_after_reset = monitor->consume_reopen_after_reset(); + monitor->deinit(); + active_machine_monitor = NULL; + active_reset_monitor = NULL; + if (deferred_debug_go && release_after_exit) { +#if defined(U64) && (U64) && !defined(RUNS_ON_PC) + C64 *machine = C64::getMachine(); + if (machine && machine->is_accessible()) { + release_host(); + machine->release_ownership(); + } else if (host) { + release_host(); + host->release_ownership(); + } +#else + release_host(); +#endif + release_after_exit = false; + } + if (deferred_debug_go) { + monitor->dispatch_deferred_debug_go(); + } + delete monitor; + if (exit_ui && !reopen_after_reset) { + menu_response_to_action = MENU_EXIT; + } + if (swap_close) { + // Do not reopen after an interface swap, and tell the launching + // menu/browser to hide (close + release host) so the entire UI + // surface tears down and the file browser is never left visible. + reopen_after_reset = false; + menu_response_to_action = MENU_HIDE; + } + if (do_go) { +#if defined(U64) && (U64) && !defined(RUNS_ON_PC) + C64 *machine = C64::getMachine(); + bool staged_nmi = false; + if (machine && machine->is_accessible()) { + staged_nmi = go_has_context ? + monitor_io::stage_resume_to_context(go_context) : + monitor_io::stage_jump_to(go_address); + release_host(); + machine->release_ownership(); + if (staged_nmi) { + monitor_io::pulse_staged_nmi(); + } + } + if (!staged_nmi && direct_render_target && host) { + release_host(); + host->release_ownership(); + } + if (!staged_nmi) +#endif + { + if (go_has_context) { + monitor_io::resume_to_context(go_context); + } else { + monitor_io::jump_to(go_address); + } + } + } + if (release_after_exit) { +#if defined(U64) && (U64) && !defined(RUNS_ON_PC) + C64 *machine = C64::getMachine(); + if (machine && machine->is_accessible()) { + release_host(); + machine->release_ownership(); + } else if (host) { + release_host(); + host->release_ownership(); + } +#else + release_host(); +#endif + } + } while (reopen_after_reset && host->exists()); +} + +extern "C" bool machine_monitor_request_reset_reentry(void *monitor) +{ + if (!monitor) { + return false; + } + ((MachineMonitor *)monitor)->request_reopen_after_reset(); + return true; +} + +extern "C" bool machine_monitor_request_global_reset_cancel(void) +{ + // On every C64 hardware reset, reset the saved CPU view to CPU7 so the + // next fresh monitor open reflects the post-reset banking state rather + // than any stale CPU5/RAM view from a previous debug session. + monitor_reset_saved_cpu_view(); + if (!active_reset_monitor) { + return false; + } + // Only cancel the in-flight debug wait. Do NOT call request_reopen_after_reset() + // here: that would save stale monitor state and schedule a spurious reopen + // on every REST/menu reset that happens to fire while the monitor is visible. + active_reset_monitor->request_debug_reset_cancel(); + return true; +} diff --git a/software/monitor/u2_memory_backend.cc b/software/monitor/u2_memory_backend.cc new file mode 100644 index 000000000..12b3b9473 --- /dev/null +++ b/software/monitor/u2_memory_backend.cc @@ -0,0 +1,56 @@ +#include "u2_memory_backend.h" +#include "monitor_debug_u2.h" + +#include "c64.h" + +uint8_t U2MemoryBackend :: read(uint16_t address) +{ + if (!machine || !machine->exists()) { + return 0; + } + return machine->peek(address); +} + +void U2MemoryBackend :: write(uint16_t address, uint8_t value) +{ + if (!machine || !machine->exists()) { + return; + } + machine->poke(address, value); +} + +void U2MemoryBackend :: read_block(uint16_t address, uint8_t *dst, uint16_t len) +{ + if (!machine || !machine->exists()) { + while (len) { + *dst++ = 0; + len--; + } + return; + } + while (len) { + *dst++ = machine->peek(address++); + len--; + } +} + +const char *U2MemoryBackend :: source_name(uint16_t) const +{ + // U2 reads the current CPU-visible aperture directly. Without ROM shadow + // snapshots or monitor-selected banking, this is not guaranteed to be RAM. + return "CPU"; +} + +bool U2MemoryBackend :: reset_machine(void) +{ + if (!machine) { + return false; + } + machine->reset(); + return true; +} + +DebugSession *U2MemoryBackend :: create_debug_session(void) +{ + return create_u2_debug_session(this); +} diff --git a/software/monitor/u2_memory_backend.h b/software/monitor/u2_memory_backend.h new file mode 100644 index 000000000..d0d9f2fa8 --- /dev/null +++ b/software/monitor/u2_memory_backend.h @@ -0,0 +1,26 @@ +#ifndef U2_MEMORY_BACKEND_H +#define U2_MEMORY_BACKEND_H + +#include "memory_backend.h" + +class C64; + +class U2MemoryBackend : public MemoryBackend +{ + C64 *machine; +public: + explicit U2MemoryBackend(C64 *machine) : machine(machine) { } + + virtual uint8_t read(uint16_t address); + virtual void write(uint16_t address, uint8_t value); + virtual void read_block(uint16_t address, uint8_t *dst, uint16_t len); + virtual bool supports_cpu_banking(void) const { return false; } + virtual bool supports_vic_bank(void) const { return false; } + virtual bool supports_go(void) const { return true; } + virtual bool supports_reset(void) const { return true; } + virtual bool reset_machine(void); + virtual const char *source_name(uint16_t address) const; + virtual DebugSession *create_debug_session(void); +}; + +#endif diff --git a/software/monitor/u64_memory_backend.cc b/software/monitor/u64_memory_backend.cc new file mode 100644 index 000000000..c14dc08f7 --- /dev/null +++ b/software/monitor/u64_memory_backend.cc @@ -0,0 +1,259 @@ +#include "u64_memory_backend.h" +#include "monitor_debug_u64.h" +#include "u64_machine.h" +#include "u64.h" +#include "filemanager.h" + +#include + +extern uint8_t _basic_bin_start[8192]; +extern uint8_t _default_kernal_65_start[8192]; +extern uint8_t _default_chars_bin_start[4096]; + +namespace { + +static uint8_t monitor_basic_rom[8192]; +static uint8_t monitor_kernal_rom[8192]; +static uint8_t monitor_char_rom[4096]; + +static void snapshot_u64_rom(volatile uint8_t *src, uint8_t *dst, uint16_t len) +{ + for (uint16_t i = 0; i < len; i++) { + dst[i] = src[i]; + } +} + +static bool rom_is_all_zero(const uint8_t *data, uint16_t len) +{ + for (uint16_t i = 0; i < len; i++) { + if (data[i] != 0) { + return false; + } + } + return true; +} + +} + +void U64MemoryBackend :: load_monitor_char_rom_cache(C64 *machine) +{ + FRESULT fres = FR_NOT_READY; + if (machine) { + fres = FileManager :: getFileManager()->load_file(ROMS_DIRECTORY, + machine->get_cfg_string(CFG_C64_CHARFILE), + monitor_char_rom, + sizeof(monitor_char_rom), + NULL); + } + if (fres != FR_OK) { + memcpy(monitor_char_rom, _default_chars_bin_start, sizeof(monitor_char_rom)); + } +} + +static void load_monitor_kernal_rom_cache(C64 *machine) +{ + FRESULT fres = FR_NOT_READY; + if (machine) { + fres = FileManager :: getFileManager()->load_file(ROMS_DIRECTORY, + machine->get_cfg_string(CFG_C64_KERNFILE), + monitor_kernal_rom, + sizeof(monitor_kernal_rom), + NULL); + } + if (fres != FR_OK) { + memcpy(monitor_kernal_rom, _default_kernal_65_start, sizeof(monitor_kernal_rom)); + } +} + +void U64MemoryBackend :: load_monitor_rom_cache(C64 *machine) +{ + snapshot_u64_rom((volatile uint8_t *)U64_BASIC_BASE, monitor_basic_rom, sizeof(monitor_basic_rom)); + snapshot_u64_rom((volatile uint8_t *)U64_KERNAL_BASE, monitor_kernal_rom, sizeof(monitor_kernal_rom)); + + if (rom_is_all_zero(monitor_basic_rom, sizeof(monitor_basic_rom))) { + memcpy(monitor_basic_rom, _basic_bin_start, sizeof(monitor_basic_rom)); + } + if (rom_is_all_zero(monitor_kernal_rom, sizeof(monitor_kernal_rom))) { + load_monitor_kernal_rom_cache(machine); + } + load_monitor_char_rom_cache(machine); +} + +enum CpuRegionMapping { + MAP_RAM = 0, + MAP_BASIC, + MAP_CHAR, + MAP_IO, + MAP_KERNAL, +}; + +static CpuRegionMapping cpu_region_mapping(uint16_t address, uint8_t cpu_port) +{ + cpu_port &= 0x07; + + if (address >= 0xA000 && address <= 0xBFFF) { + return ((cpu_port & 0x03) == 0x03) ? MAP_BASIC : MAP_RAM; + } + if (address >= 0xD000 && address <= 0xDFFF) { + if ((cpu_port & 0x03) == 0x00) { + return MAP_RAM; + } + return (cpu_port & 0x04) ? MAP_IO : MAP_CHAR; + } + if (address >= 0xE000) { + return (cpu_port & 0x02) ? MAP_KERNAL : MAP_RAM; + } + return MAP_RAM; +} + +bool U64MemoryBackend :: freeze_available(void) const +{ + return machine && !machine->is_accessible(); +} + +bool U64MemoryBackend :: read_monitor_rom_byte(uint16_t address, uint8_t cpu_port, uint8_t *value) const +{ + switch (cpu_region_mapping(address, cpu_port)) { + case MAP_BASIC: + *value = monitor_basic_rom[address - 0xA000]; + return true; + case MAP_CHAR: + *value = monitor_char_rom[address - 0xD000]; + return true; + case MAP_KERNAL: + *value = monitor_kernal_rom[address - 0xE000]; + return true; + default: + return false; + } +} + +void U64MemoryBackend :: begin_session(void) +{ + // Do NOT freeze the C64 by default — per-access DMA stops handle the + // brief pauses required to read/write memory. The user can opt in via + // the monitor's Z (freeze) toggle, which calls set_frozen(true). + stopped_machine_for_session = false; + load_monitor_rom_cache(machine); +} + +void U64MemoryBackend :: end_session(void) +{ + if (machine && stopped_machine_for_session) { + machine->end_stopped_session(stopped_machine_for_session); + stopped_machine_for_session = false; + } +} + +void U64MemoryBackend :: set_frozen(bool on) +{ + if (!machine) { + return; + } + + if (on && !stopped_machine_for_session) { + stopped_machine_for_session = machine->begin_stopped_session(); + load_monitor_rom_cache(machine); + } else if (!on && stopped_machine_for_session) { + machine->end_stopped_session(stopped_machine_for_session); + stopped_machine_for_session = false; + } +} + +bool U64MemoryBackend :: reset_machine(void) +{ + if (!machine) { + return false; + } + clear_observed_live_cpu_port(); + if (stopped_machine_for_session) { + machine->end_stopped_session(stopped_machine_for_session); + stopped_machine_for_session = false; + } + if (machine->is_accessible()) { + machine->unfreeze(); + } + machine->reset(); + load_monitor_rom_cache(machine); + return true; +} + +uint8_t U64MemoryBackend :: read(uint16_t address) +{ + if (!machine) { + return 0; + } + + uint8_t cpu_port = get_monitor_cpu_port(); + uint8_t rom_value = 0; + + if (read_monitor_rom_byte(address, cpu_port, &rom_value)) { + return rom_value; + } + if (cpu_region_mapping(address, cpu_port) == MAP_IO) { + return machine->peek_visible(address); + } + return machine->peek_raw(address); +} + +void U64MemoryBackend :: write(uint16_t address, uint8_t value) +{ + if (!machine) { + return; + } + + uint8_t cpu_port = get_monitor_cpu_port(); + + if (cpu_region_mapping(address, cpu_port) == MAP_IO) { + machine->poke_visible(address, value); + return; + } + machine->poke_raw(address, value); +} + +void U64MemoryBackend :: read_block(uint16_t address, uint8_t *dst, uint16_t len) +{ + while (len) { + *dst++ = read(address++); + len--; + } +} + +uint8_t U64MemoryBackend :: get_live_cpu_port(void) +{ + if (observed_live_cpu_port_valid) { + return observed_live_cpu_port & 0x07; + } + return machine ? machine->get_cpu_port() : 0; +} + +void U64MemoryBackend :: set_observed_live_cpu_port(uint8_t cpu_port) +{ + observed_live_cpu_port = cpu_port & 0x07; + observed_live_cpu_port_valid = true; +} + +void U64MemoryBackend :: clear_observed_live_cpu_port(void) +{ + observed_live_cpu_port_valid = false; +} + +uint8_t U64MemoryBackend :: get_live_vic_bank(void) +{ + if (!machine) { + return 0; + } + + uint8_t dd00 = machine->peek_visible(0xDD00); + return (uint8_t)(3 - (dd00 & 0x03)); +} + +uint8_t U64MemoryBackend :: monitor_poll_hz(void) const +{ + return (C64_VIDEOFORMAT & VIDEO_FMT_60_HZ) ? 60 : 50; +} + +DebugSession *U64MemoryBackend :: create_debug_session(void) +{ + return create_u64_debug_session(this); +} diff --git a/software/monitor/u64_memory_backend.h b/software/monitor/u64_memory_backend.h new file mode 100644 index 000000000..9ba20ab22 --- /dev/null +++ b/software/monitor/u64_memory_backend.h @@ -0,0 +1,43 @@ +#ifndef U64_MEMORY_BACKEND_H +#define U64_MEMORY_BACKEND_H + +#include "memory_backend.h" + +class C64; +class U64Machine; + +class U64MemoryBackend : public MemoryBackend +{ + U64Machine *machine; + bool stopped_machine_for_session; + bool observed_live_cpu_port_valid; + uint8_t observed_live_cpu_port; + + void load_monitor_char_rom_cache(C64 *machine); + void load_monitor_rom_cache(C64 *machine); + bool read_monitor_rom_byte(uint16_t address, uint8_t cpu_port, uint8_t *value) const; +public: + explicit U64MemoryBackend(U64Machine *machine) + : machine(machine), stopped_machine_for_session(false), + observed_live_cpu_port_valid(false), observed_live_cpu_port(0x07) { } + virtual uint8_t read(uint16_t address); + virtual void write(uint16_t address, uint8_t value); + virtual void read_block(uint16_t address, uint8_t *dst, uint16_t len); + virtual uint8_t get_live_cpu_port(void); + virtual uint8_t get_live_vic_bank(void); + virtual uint8_t monitor_poll_hz(void) const; + virtual void begin_session(void); + virtual void end_session(void); + + virtual bool supports_freeze(void) const { return true; } + virtual bool freeze_available(void) const; + virtual bool is_frozen(void) const { return stopped_machine_for_session; } + virtual void set_frozen(bool on); + virtual bool supports_reset(void) const { return true; } + virtual bool reset_machine(void); + virtual DebugSession *create_debug_session(void); + void set_observed_live_cpu_port(uint8_t cpu_port); + void clear_observed_live_cpu_port(void); +}; + +#endif diff --git a/software/test/monitor/machine_monitor_bookmarks_test.cc b/software/test/monitor/machine_monitor_bookmarks_test.cc new file mode 100644 index 000000000..e69fe034a --- /dev/null +++ b/software/test/monitor/machine_monitor_bookmarks_test.cc @@ -0,0 +1,1299 @@ +#include +#include + +#include "keyboard_usb.h" +#include "machine_monitor_test_support.h" +#include "monitor_bookmarks.h" + +enum { + TEST_BOOKMARK_CFG_SCHEMA = 1, + TEST_BOOKMARK_CFG_SLOT0, +}; + +Keyboard_USB::Keyboard_USB() +{ +} + +Keyboard_USB::~Keyboard_USB() +{ +} + +void Keyboard_USB::process_data(uint8_t *) +{ +} + +int Keyboard_USB::getch(void) +{ + return -1; +} + +void Keyboard_USB::push_head(int) +{ +} + +void Keyboard_USB::push_head_repeat(int, int) +{ +} + +int Keyboard_USB::count_injected_key(int) const +{ + return 0; +} + +bool Keyboard_USB::has_injected_key(int) const +{ + return false; +} + +void Keyboard_USB::remove_injected_key(int) +{ +} + +void Keyboard_USB::wait_free(void) +{ +} + +void Keyboard_USB::clear_buffer(void) +{ +} + +void Keyboard_USB::setMatrix(volatile uint8_t *) +{ +} + +void Keyboard_USB::enableMatrix(bool) +{ +} + +Keyboard_USB system_usb_keyboard; + +namespace monitor_io { + +bool pick_file(UserInterface *, const char *, char *, int, char *, int, bool) +{ + return false; +} + +const char *load_into_memory(const char *, const char *, MemoryBackend *, + uint16_t, bool, uint32_t, bool, uint32_t, + uint16_t *, uint32_t *) +{ + return "UNUSED"; +} + +const char *save_from_memory(UserInterface *, const char *, const char *, + MemoryBackend *, uint16_t, uint16_t) +{ + return "UNUSED"; +} + +void jump_to(uint16_t) +{ +} + +} // namespace monitor_io + +static void reset_bookmark_test_state(void) +{ + monitor_reset_saved_state(); + reset_fake_config_manager_state(); + set_fake_ms_timer(0); +} + +static void get_monitor_header(const CaptureScreen &screen, char *out) +{ + screen.get_slice(1, 3, 38, out); +} + +static void get_monitor_status(const CaptureScreen &screen, char *out) +{ + screen.get_slice(1, 22, 38, out); +} + +static int expect_monitor_border_restored(const CaptureScreen &screen) +{ + for (int y = 3; y <= 22; y++) { + if (expect((unsigned char)screen.chars[y][0] == CHR_VERTICAL_LINE, + "Monitor left border must be restored after the bookmark popup closes.")) return 1; + if (expect((unsigned char)screen.chars[y][39] == CHR_VERTICAL_LINE, + "Monitor right border must be restored after the bookmark popup closes.")) return 1; + } + return 0; +} + +static void seed_bookmark_full(uint8_t slot, uint16_t address, uint8_t view, + uint8_t cpu_bank, uint8_t vic_bank, bool edit_mode, + uint8_t view_width_mode, const char *label) +{ + MonitorBookmarks bookmarks; + MonitorBookmarkSlot bookmark; + + bookmarks.ensure_loaded(7, vic_bank); + memset(&bookmark, 0, sizeof(bookmark)); + bookmark.address = address; + bookmark.view = view; + bookmark.cpu_bank = cpu_bank; + bookmark.vic_bank = vic_bank; + bookmark.view_width_mode = view_width_mode; + bookmark.edit_mode = edit_mode; + bookmark.is_default = false; + bookmark.is_valid = true; + if (label) { + size_t i = 0; + while (i < MONITOR_BOOKMARK_LABEL_MAX && label[i]) { + bookmark.label[i] = label[i]; + i++; + } + bookmark.label[i] = 0; + } else { + bookmark.label[0] = 0; + } + bookmarks.set(slot, bookmark); +} + +static void seed_bookmark(uint8_t slot, uint16_t address, uint8_t view, + uint8_t cpu_bank, uint8_t vic_bank, bool edit_mode) +{ + seed_bookmark_full(slot, address, view, cpu_bank, vic_bank, edit_mode, 1, NULL); +} + +struct BookmarkTestBackend : public FakeFrozenVicBackend +{ + BookmarkTestBackend() + { + frozen = false; + reported_vic_bank = 2; + requested_vic_bank = 2; + } +}; + +static int test_bookmark_addendum_default_table(void) +{ + static const struct { + uint16_t address; + uint8_t view; + const char *label; + } expected[MONITOR_BOOKMARK_SLOT_COUNT] = { + { 0x0000, MONITOR_BOOKMARK_VIEW_HEX, "ZP" }, + { 0x0400, MONITOR_BOOKMARK_VIEW_SCREEN, "SCREEN" }, + { 0x0801, MONITOR_BOOKMARK_VIEW_ASM, "BASIC" }, + { 0xA000, MONITOR_BOOKMARK_VIEW_ASM, "BASROM" }, + { 0xC000, MONITOR_BOOKMARK_VIEW_ASM, "HIRAM" }, + { 0xD000, MONITOR_BOOKMARK_VIEW_HEX, "VIC" }, + { 0xD400, MONITOR_BOOKMARK_VIEW_HEX, "SID" }, + { 0xDC00, MONITOR_BOOKMARK_VIEW_BINARY, "CIA1" }, + { 0xDD00, MONITOR_BOOKMARK_VIEW_BINARY, "CIA2" }, + { 0xE000, MONITOR_BOOKMARK_VIEW_ASM, "KERNAL" }, + }; + + reset_bookmark_test_state(); + + MonitorBookmarks bookmarks; + if (expect(bookmarks.ensure_loaded(7, 2), "Bookmark defaults should load on empty config.")) return 1; + + for (int i = 0; i < MONITOR_BOOKMARK_SLOT_COUNT; i++) { + const MonitorBookmarkSlot *slot = bookmarks.get((uint8_t)i); + if (expect(slot != NULL, "Bookmark default slot must exist.")) return 1; + if (expect(slot->address == expected[i].address, "Bookmark default address mismatch.")) return 1; + if (expect(slot->view == expected[i].view, "Bookmark default view mismatch.")) return 1; + if (expect(strcmp(slot->label, expected[i].label) == 0, + "Bookmark default label mismatch.")) return 1; + if (expect(slot->cpu_bank == 7 && slot->vic_bank == 0, "Default CPU/VIC bank mismatch.")) return 1; + if (expect(!slot->edit_mode && slot->is_default, "Default mode/flags mismatch.")) return 1; + if (slot->view == MONITOR_BOOKMARK_VIEW_HEX) { + if (expect(slot->view_width_mode == MONITOR_BOOKMARK_WIDTH_MEMORY_8, + "Default memory bookmarks must store width 8.")) return 1; + } else if (slot->view == MONITOR_BOOKMARK_VIEW_ASCII || + slot->view == MONITOR_BOOKMARK_VIEW_SCREEN) { + if (expect(slot->view_width_mode == MONITOR_BOOKMARK_WIDTH_TEXT, + "Default text/screen bookmarks must store width 32.")) return 1; + } else if (slot->view == MONITOR_BOOKMARK_VIEW_ASM) { + if (expect(slot->view_width_mode == MONITOR_BOOKMARK_WIDTH_NONE, + "Default ASM bookmarks must omit width.")) return 1; + } else if (expect(slot->view_width_mode == 1, "Default binary width must be W1.")) return 1; + } + + // Spot-check rationale items called out by the addendum. + if (expect(strcmp(bookmarks.get(6)->label, "SID") == 0, "$D400 must be labelled SID.")) return 1; + if (expect(strcmp(bookmarks.get(4)->label, "HIRAM") == 0, "$C000 must be labelled HIRAM.")) return 1; + if (expect(bookmarks.get(1)->view_width_mode == MONITOR_BOOKMARK_WIDTH_TEXT, + "$0400 screen bookmark must default to width 32.")) return 1; + if (expect(bookmarks.get(7)->view == MONITOR_BOOKMARK_VIEW_BINARY && + bookmarks.get(7)->view_width_mode == 1, + "CIA1 must default to BIN W1.")) return 1; + if (expect(bookmarks.get(8)->view == MONITOR_BOOKMARK_VIEW_BINARY && + bookmarks.get(8)->view_width_mode == 1, + "CIA2 must default to BIN W1.")) return 1; + return 0; +} + +static int test_bookmark_label_normalize_helper(void) +{ + char buf[MONITOR_BOOKMARK_LABEL_STORAGE]; + + monitor_bookmark_normalize_label(buf, sizeof(buf), ""); + if (expect(strcmp(buf, "USER") == 0, "Empty label must normalize to USER.")) return 1; + + monitor_bookmark_normalize_label(buf, sizeof(buf), NULL); + if (expect(strcmp(buf, "USER") == 0, "NULL label must normalize to USER.")) return 1; + + monitor_bookmark_normalize_label(buf, sizeof(buf), "sprite"); + if (expect(strcmp(buf, "SPRITE") == 0, "Lowercase label must normalize to uppercase.")) return 1; + + monitor_bookmark_normalize_label(buf, sizeof(buf), "abc!@#"); + if (expect(strcmp(buf, "ABC___") == 0, "Unsupported chars must normalize deterministically.")) return 1; + + monitor_bookmark_normalize_label(buf, sizeof(buf), "TOOLONGLABEL"); + if (expect(strcmp(buf, "TOOLON") == 0, "Overlong label must truncate to 6 chars.")) return 1; + + monitor_bookmark_normalize_label(buf, sizeof(buf), "A_B-1"); + if (expect(strcmp(buf, "A_B-1") == 0, "Allowed chars (A-Z 0-9 _ -) must pass through.")) return 1; + return 0; +} + +static int test_bookmark_corrupt_config_falls_back_to_defaults(void) +{ + reset_bookmark_test_state(); + { + MonitorBookmarks bookmarks; + ConfigStore *cfg; + + bookmarks.ensure_loaded(7, 1); + cfg = ConfigManager::getConfigManager()->find_store("Machine Monitor Bookmarks"); + if (expect(cfg != NULL, "Bookmark config store should exist after default creation.")) return 1; + cfg->set_value(TEST_BOOKMARK_CFG_SCHEMA, 1); + cfg->set_string(TEST_BOOKMARK_CFG_SLOT0, "bogus"); + cfg->write(); + } + + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 3); + const MonitorBookmarkSlot *slot0 = reopened.get(0); + + if (expect(slot0 && slot0->address == 0x0000 && slot0->cpu_bank == 7 && slot0->vic_bank == 0, + "Corrupt bookmark config should recreate defaults with VIC0.")) return 1; + if (expect(strcmp(slot0->label, "ZP") == 0, + "Corrupt config should restore the default label.")) return 1; + return 0; +} + +static int test_bookmark_old_six_field_falls_back(void) +{ + reset_bookmark_test_state(); + { + MonitorBookmarks bookmarks; + ConfigStore *cfg; + + bookmarks.ensure_loaded(7, 0); + cfg = ConfigManager::getConfigManager()->find_store("Machine Monitor Bookmarks"); + if (expect(cfg != NULL, "Config store must exist for malformed-string test.")) return 1; + cfg->set_value(TEST_BOOKMARK_CFG_SCHEMA, 1); + // Old pre-addendum encoding: six fields (no width mode, no label). + cfg->set_string(TEST_BOOKMARK_CFG_SLOT0, "2049,1,7,0,0,0"); + cfg->write(); + } + + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 0); + const MonitorBookmarkSlot *slot0 = reopened.get(0); + if (expect(slot0 && slot0->is_default && slot0->address == 0x0000 && + strcmp(slot0->label, "ZP") == 0, + "Old six-field strings must fall back to addendum defaults.")) return 1; + return 0; +} + +static int test_bookmark_persists_label_and_width_mode(void) +{ + reset_bookmark_test_state(); + + MonitorBookmarks bookmarks; + MonitorBookmarkSlot custom; + bookmarks.ensure_loaded(7, 0); + memset(&custom, 0, sizeof(custom)); + custom.address = 0x2000; + custom.view = MONITOR_BOOKMARK_VIEW_BINARY; + custom.cpu_bank = 3; + custom.vic_bank = 1; + custom.view_width_mode = 3; + custom.edit_mode = true; + custom.is_default = false; + custom.is_valid = true; + strcpy(custom.label, "SPRITE"); + if (expect(bookmarks.set(7, custom), "Custom bookmark set should save immediately.")) return 1; + + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 0); + const MonitorBookmarkSlot *slot7 = reopened.get(7); + + if (expect(slot7 && slot7->address == 0x2000 && slot7->view == MONITOR_BOOKMARK_VIEW_BINARY && + slot7->cpu_bank == 3 && slot7->vic_bank == 1 && !slot7->edit_mode && + slot7->view_width_mode == 3 && strcmp(slot7->label, "SPRITE") == 0, + "Reopen should preserve label and width mode without persisting edit mode.")) return 1; + return 0; +} + +static int test_bookmark_set_preserves_label(void) +{ + reset_bookmark_test_state(); + + MonitorBookmarks bookmarks; + MonitorBookmarkSlot custom; + bookmarks.ensure_loaded(7, 0); + memset(&custom, 0, sizeof(custom)); + custom.address = 0x2000; + custom.view = MONITOR_BOOKMARK_VIEW_BINARY; + custom.cpu_bank = 7; + custom.vic_bank = 0; + custom.view_width_mode = 1; + custom.is_valid = true; + strcpy(custom.label, "MYLBL"); + bookmarks.set(7, custom); + + MonitorBookmarkSlot updated; + memset(&updated, 0, sizeof(updated)); + updated.address = 0x9000; + updated.view = MONITOR_BOOKMARK_VIEW_HEX; + updated.cpu_bank = 5; + updated.vic_bank = 2; + updated.view_width_mode = 2; + updated.is_valid = true; + // No label provided in the captured target. + bookmarks.set_target_preserve_label(7, updated); + + const MonitorBookmarkSlot *slot7 = bookmarks.get(7); + if (expect(slot7 && slot7->address == 0x9000 && slot7->view == MONITOR_BOOKMARK_VIEW_HEX && + slot7->cpu_bank == 5 && slot7->vic_bank == 2 && + strcmp(slot7->label, "MYLBL") == 0, + "set_target_preserve_label must preserve the previous label.")) return 1; + return 0; +} + +static int test_bookmark_label_edit_changes_only_label(void) +{ + reset_bookmark_test_state(); + + MonitorBookmarks bookmarks; + MonitorBookmarkSlot custom; + bookmarks.ensure_loaded(7, 0); + memset(&custom, 0, sizeof(custom)); + custom.address = 0xC100; + custom.view = MONITOR_BOOKMARK_VIEW_ASM; + custom.cpu_bank = 4; + custom.vic_bank = 1; + custom.view_width_mode = 1; + custom.is_valid = true; + strcpy(custom.label, "OLD"); + bookmarks.set(2, custom); + + bookmarks.set_label(2, "new"); + + const MonitorBookmarkSlot *slot2 = bookmarks.get(2); + if (expect(slot2 && slot2->address == 0xC100 && slot2->view == MONITOR_BOOKMARK_VIEW_ASM && + slot2->cpu_bank == 4 && slot2->vic_bank == 1 && + strcmp(slot2->label, "NEW") == 0, + "set_label must only update the label (uppercased) and keep target state.")) return 1; + return 0; +} + +static int test_bookmark_selected_reset_restores_default(void) +{ + reset_bookmark_test_state(); + + MonitorBookmarks bookmarks; + bookmarks.ensure_loaded(7, 0); + bookmarks.set_label(7, "CUSTOM"); + { + MonitorBookmarkSlot redirect; + memset(&redirect, 0, sizeof(redirect)); + redirect.address = 0x4000; + redirect.view = MONITOR_BOOKMARK_VIEW_HEX; + redirect.cpu_bank = 0; + redirect.vic_bank = 3; + redirect.view_width_mode = 4; + redirect.is_valid = true; + strcpy(redirect.label, "CUSTOM"); + bookmarks.set(7, redirect); + } + + if (expect(bookmarks.reset_slot_to_default(7, 7, 0), "reset_slot_to_default should succeed.")) return 1; + const MonitorBookmarkSlot *slot7 = bookmarks.get(7); + if (expect(slot7 && slot7->address == 0xDC00 && slot7->view == MONITOR_BOOKMARK_VIEW_BINARY && + slot7->cpu_bank == 7 && slot7->vic_bank == 0 && slot7->view_width_mode == 1 && + slot7->is_default && strcmp(slot7->label, "CIA1") == 0, + "reset_slot_to_default should restore default target state and label.")) return 1; + + // Ensure other slots are NOT affected. + const MonitorBookmarkSlot *slot4 = bookmarks.get(4); + if (expect(slot4 && strcmp(slot4->label, "HIRAM") == 0, + "reset_slot_to_default must not touch other slots.")) return 1; + return 0; +} + +static int test_bookmark_status_message_formatting(void) +{ + char line[40]; + MonitorBookmarkSlot bookmark; + + // ASM apply omits width, includes label. + memset(&bookmark, 0, sizeof(bookmark)); + bookmark.address = 0x0801; + bookmark.view = MONITOR_BOOKMARK_VIEW_ASM; + bookmark.cpu_bank = 7; + bookmark.vic_bank = 0; + bookmark.view_width_mode = 1; + bookmark.is_valid = true; + strcpy(bookmark.label, "BASIC"); + monitor_bookmark_format_status(line, sizeof(line), 2, &bookmark, MONITOR_BOOKMARK_STATUS_RESTORED); + if (expect(strcmp(line, "BM2 BASIC $0801 ASM CPU7 VIC0") == 0, + "Non-binary apply message must omit Wn and MODE and include the label.")) return 1; + if (expect(strstr(line, "MODE") == NULL && strstr(line, "VIEW") == NULL, + "Apply messages must not include MODE.")) return 1; + if (expect((int)strlen(line) <= 38, "Apply message must fit in 38 columns.")) return 1; + + // Memory set includes W16. + bookmark.address = 0x2000; + bookmark.view = MONITOR_BOOKMARK_VIEW_HEX; + bookmark.view_width_mode = MONITOR_BOOKMARK_WIDTH_MEMORY_16; + strcpy(bookmark.label, "SPRITE"); + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_SET); + if (expect(strcmp(line, "BM7 SPRITE $2000 HEX W16 CPU7 VIC0 SET") == 0, + "Memory set message must include the stored width.")) return 1; + if (expect((int)strlen(line) <= 38, "Memory set message must fit in 38 columns.")) return 1; + + // Binary apply with Wn. + bookmark.address = 0xDC00; + bookmark.view = MONITOR_BOOKMARK_VIEW_BINARY; + bookmark.view_width_mode = 1; + strcpy(bookmark.label, "CIA1"); + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_RESTORED); + if (expect(strcmp(line, "BM7 CIA1 $DC00 BIN W1 CPU7 VIC0") == 0, + "Binary apply message must include Wn and label.")) return 1; + if (expect((int)strlen(line) <= 38, "Binary apply message must fit in 38 columns.")) return 1; + + bookmark.view_width_mode = MONITOR_BOOKMARK_BINARY_WIDTH_SPRITE; + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_RESTORED); + if (expect(strcmp(line, "BM7 CIA1 $DC00 BIN W3S CPU7 VIC0") == 0, + "Binary packed 3-byte mode must display as W3S.")) return 1; + + bookmark.view_width_mode = 4; + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_RESTORED); + if (expect(strcmp(line, "BM7 CIA1 $DC00 BIN W4 CPU7 VIC0") == 0, + "Binary width 4 must display as W4.")) return 1; + + // Binary set with 6-char label and W1. + bookmark.address = 0x2000; + bookmark.view_width_mode = 1; + strcpy(bookmark.label, "SPRITE"); + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_SET); + if (expect(strcmp(line, "BM7 SPRITE $2000 BIN W1 CPU7 VIC0 SET") == 0, + "Binary set message must include label and Wn and SET.")) return 1; + if (expect((int)strlen(line) <= 38, "Binary set with 6-char label must fit in 38 columns.")) return 1; + + // Saved/Reset/Cancel. + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_LABEL_SAVED); + if (expect(strcmp(line, "BM7 SPRITE SAVED") == 0, "Saved message must be compact.")) return 1; + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_LABEL_RESET); + if (expect(strcmp(line, "BM7 SPRITE RESET") == 0, "Reset message must be compact.")) return 1; + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_LABEL_CANCEL); + if (expect(strcmp(line, "BM7 SPRITE CANCEL") == 0, "Cancel message must be compact.")) return 1; + + monitor_bookmark_format_status(line, sizeof(line), 1, NULL, MONITOR_BOOKMARK_STATUS_EMPTY); + if (expect(strcmp(line, "BM1 EMPTY") == 0, "EMPTY message formatting is incorrect.")) return 1; + + monitor_bookmark_format_status(line, sizeof(line), 0, NULL, MONITOR_BOOKMARK_STATUS_RESET_DEFAULTS); + if (expect(strcmp(line, "BOOKMARKS RESET TO DEFAULTS") == 0, + "Reset-defaults message formatting is incorrect.")) return 1; + return 0; +} + +static int test_bookmark_popup_line_formatting(void) +{ + char line[64]; + MonitorBookmarkSlot bookmark; + + memset(&bookmark, 0, sizeof(bookmark)); + bookmark.is_valid = true; + bookmark.address = 0xE000; + bookmark.view = MONITOR_BOOKMARK_VIEW_ASM; + bookmark.cpu_bank = 7; + bookmark.vic_bank = 0; + bookmark.view_width_mode = 1; + strcpy(bookmark.label, "KERNAL"); + monitor_bookmark_format_popup_line(line, sizeof(line), 9, &bookmark); + if (expect(strcmp(line, "9 KERNAL $E000 ASM CPU7 VIC0") == 0, + "Non-binary popup row must use LABEL6 + padded VIEW6 without a mode column.")) return 1; + if (expect((int)strlen(line) <= 38, "Popup row must fit in 38 columns.")) return 1; + + bookmark.address = 0xDC00; + bookmark.view = MONITOR_BOOKMARK_VIEW_BINARY; + bookmark.view_width_mode = 1; + strcpy(bookmark.label, "CIA1"); + monitor_bookmark_format_popup_line(line, sizeof(line), 7, &bookmark); + if (expect(strcmp(line, "7 CIA1 $DC00 BIN 1 CPU7 VIC0") == 0, + "Binary popup row must use the 2-character width column.")) return 1; + if (expect((int)strlen(line) <= 38, "Binary popup row must fit in 38 columns.")) return 1; + + bookmark.edit_mode = true; + monitor_bookmark_format_popup_line(line, sizeof(line), 7, &bookmark); + if (expect(strcmp(line, "7 CIA1 $DC00 BIN 1 CPU7 VIC0") == 0, + "Popup row must ignore edit mode because bookmarks no longer store it.")) return 1; + + bookmark.view_width_mode = MONITOR_BOOKMARK_BINARY_WIDTH_SPRITE; + monitor_bookmark_format_popup_line(line, sizeof(line), 7, &bookmark); + if (expect(strcmp(line, "7 CIA1 $DC00 BIN 3S CPU7 VIC0") == 0, + "Binary packed 3-byte popup row must display as 3S.")) return 1; + + bookmark.view_width_mode = 4; + monitor_bookmark_format_popup_line(line, sizeof(line), 7, &bookmark); + if (expect(strcmp(line, "7 CIA1 $DC00 BIN 4 CPU7 VIC0") == 0, + "Binary width 4 popup row must display as 4.")) return 1; + + bookmark.address = 0x0400; + bookmark.view = MONITOR_BOOKMARK_VIEW_SCREEN; + bookmark.cpu_bank = 7; + bookmark.vic_bank = 0; + bookmark.view_width_mode = MONITOR_BOOKMARK_WIDTH_TEXT; + strcpy(bookmark.label, "SCREEN"); + monitor_bookmark_format_popup_line(line, sizeof(line), 1, &bookmark); + if (expect(strcmp(line, "1 SCREEN $0400 SCR 32 CPU7 VIC0") == 0, + "SCREEN popup row must fit the widened view column without corruption.")) return 1; + return 0; +} + +static int test_bookmark_default_popup_alignment(void) +{ + reset_bookmark_test_state(); + MonitorBookmarks bookmarks; + bookmarks.ensure_loaded(7, 0); + + int reference_cpu_col = -1; + for (int i = 0; i < MONITOR_BOOKMARK_SLOT_COUNT; i++) { + char line[64]; + monitor_bookmark_format_popup_line(line, sizeof(line), (uint8_t)i, bookmarks.get((uint8_t)i)); + if (expect((int)strlen(line) <= 38, "Default popup row must fit in 38 columns.")) return 1; + const char *cpu = strstr(line, "CPU"); + if (expect(cpu != NULL, "Default popup row must contain CPU column.")) return 1; + int col = (int)(cpu - line); + if (reference_cpu_col < 0) { + reference_cpu_col = col; + } + if (expect(col == reference_cpu_col, + "CPU column must align across all default popup rows.")) return 1; + } + return 0; +} + +static int test_bookmark_popup_instruction_line(void) +{ + const char *expected = "0-9/RET:Jmp S:Set L:Label DEL:Reset"; + if (expect((int)strlen(expected) == 38, + "Instruction line must be 38 chars (within the 38-column popup).")) return 1; + if (expect((int)strlen(expected) <= 38, "Instruction line must fit in 38 columns.")) return 1; + if (expect(strstr(expected, "Jmp") != NULL && strstr(expected, "Set") != NULL && + strstr(expected, "Label") != NULL && strstr(expected, "Reset") != NULL, + "Instruction line must document Jmp/Set/Label/Reset.")) return 1; + return 0; +} + +static int test_bookmark_six_char_custom_label_fits(void) +{ + char line[40]; + MonitorBookmarkSlot bookmark; + + memset(&bookmark, 0, sizeof(bookmark)); + bookmark.is_valid = true; + bookmark.address = 0x2000; + bookmark.view = MONITOR_BOOKMARK_VIEW_BINARY; + bookmark.view_width_mode = 1; + bookmark.cpu_bank = 7; + bookmark.vic_bank = 0; + strcpy(bookmark.label, "SPRITE"); + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_SET); + if (expect(strcmp(line, "BM7 SPRITE $2000 BIN W1 CPU7 VIC0 SET") == 0, + "Binary set with 6-char label produces canonical message.")) return 1; + if (expect((int)strlen(line) <= 38, "Binary set with 6-char label must fit in 38 columns.")) return 1; + + bookmark.view = MONITOR_BOOKMARK_VIEW_HEX; + bookmark.view_width_mode = MONITOR_BOOKMARK_WIDTH_MEMORY_8; + monitor_bookmark_format_status(line, sizeof(line), 7, &bookmark, MONITOR_BOOKMARK_STATUS_SET); + if (expect(strcmp(line, "BM7 SPRITE $2000 HEX W8 CPU7 VIC0 SET") == 0, + "Memory set with 6-char label must include the width.")) return 1; + if (expect((int)strlen(line) <= 38, "Non-binary 6-char label set must fit in 38 columns.")) return 1; + return 0; +} + +static int test_bookmark_overlong_persisted_label_truncates_for_display(void) +{ + reset_bookmark_test_state(); + { + MonitorBookmarks bookmarks; + ConfigStore *cfg; + + bookmarks.ensure_loaded(7, 0); + cfg = ConfigManager::getConfigManager()->find_store("Machine Monitor Bookmarks"); + if (expect(cfg != NULL, "Config store must exist for overlong label test.")) return 1; + cfg->set_value(TEST_BOOKMARK_CFG_SCHEMA, 1); + // Inject a malformed slot string with an overlong label. The parser + // normalizes this into the fixed-size storage slot. + cfg->set_string(TEST_BOOKMARK_CFG_SLOT0, + "0,0,7,0,0,0,1,VERYLONGLABEL"); + cfg->write(); + } + + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 0); + const MonitorBookmarkSlot *slot0 = reopened.get(0); + if (expect(slot0 && (int)strlen(slot0->label) <= MONITOR_BOOKMARK_LABEL_MAX, + "Overlong persisted label must truncate to <=6 chars.")) return 1; + if (expect(strcmp(slot0->label, "VERYLO") == 0, + "Overlong persisted label must truncate deterministically.")) return 1; + return 0; +} + +static int test_monitor_bookmark_capture_restore_includes_width_mode(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + char status[39]; + char header[39]; + + reset_bookmark_test_state(); + seed_bookmark_full(7, 0xDC00, MONITOR_BOOKMARK_VIEW_BINARY, 7, 2, false, 1, "CIA1"); + + const int keys[] = { KEY_CTRL_7, KEY_BREAK }; + FakeKeyboard keyboard(keys, 2); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bookmark restore for binary-width test failed.")) return 1; + get_monitor_status(screen, status); + if (expect(strstr(status, "BM7 CIA1 $DC00 BIN W1 CPU7 VIC2") == status, + "Restore status must report BIN W1.")) return 1; + get_monitor_header(screen, header); + if (expect(strstr(header, "MONITOR BIN $DC00") == header, + "Restore must apply binary view and address.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_restore_applies_width_w3(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + char status[39]; + + reset_bookmark_test_state(); + seed_bookmark_full(5, 0x1000, MONITOR_BOOKMARK_VIEW_BINARY, 7, 2, false, 3, "WIDE"); + + const int keys[] = { KEY_CTRL_5, KEY_BREAK }; + FakeKeyboard keyboard(keys, 2); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bookmark W3 restore failed.")) return 1; + get_monitor_status(screen, status); + if (expect(strstr(status, "BIN W3") != NULL, + "Restore must apply the stored width mode to the running view.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_capture_restore_includes_memory_width(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + char status[39]; + char row[39]; + + reset_bookmark_test_state(); + seed_bookmark_full(4, 0x2000, MONITOR_BOOKMARK_VIEW_HEX, 7, 2, false, + MONITOR_BOOKMARK_WIDTH_MEMORY_16, "DATA"); + for (int i = 0; i < 16; i++) { + backend.ram[0x2000 + i] = (uint8_t)i; + } + + const int keys[] = { KEY_CTRL_4, KEY_BREAK }; + FakeKeyboard keyboard(keys, 2); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bookmark restore for memory-width test failed.")) return 1; + get_monitor_status(screen, status); + if (expect(strstr(status, "BM4 DATA $2000 HEX W16 CPU7 VIC2") == status, + "Restore status must report HEX W16.")) return 1; + screen.get_slice(1, 4, 38, row); + if (expect(strcmp(row, "2000 0001020304050607 08090A0B0C0D0E0F") == 0, + "Restore must apply the stored memory width to rendering.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_set_captures_memory_width(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + + reset_bookmark_test_state(); + const int keys[] = { 'W', KEY_CTRL_B, 'S', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Memory-width capture test: width cycle failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Memory-width capture test: popup open failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Memory-width capture test: popup set failed.")) return 1; + + monitor.deinit(); + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 2); + const MonitorBookmarkSlot *slot0 = reopened.get(0); + if (expect(slot0 && slot0->view == MONITOR_BOOKMARK_VIEW_HEX && + slot0->view_width_mode == MONITOR_BOOKMARK_WIDTH_MEMORY_16, + "Bookmark capture must store the active memory width.")) return 1; + return 0; +} + +static int test_monitor_bookmark_capture_no_memory_write(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + char status[39]; + const int keys[] = { 'J', 'A', 'e', KEY_CTRL_B, KEY_DOWN, 'S', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 8); + + reset_bookmark_test_state(); + backend.ram[0xC000] = 0xA9; + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("C000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Goto C000 failed for capture test.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM view switch failed for capture test.")) return 1; + if (expect(monitor.poll(0) == 0, "Edit-entry failed for capture test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup open failed for capture test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup selection failed for capture test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup set failed for capture test.")) return 1; + get_monitor_status(screen, status); + if (expect(strstr(status, "BM1 ") == status, "Set status must start with BMn label.")) return 1; + if (expect(strstr(status, " SET") != NULL, "Set status must include SET.")) return 1; + if (expect(backend.ram[0xC000] == 0xA9, "Capture must not write target memory.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_set_preserves_label(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + char status[39]; + + reset_bookmark_test_state(); + seed_bookmark_full(3, 0xC000, MONITOR_BOOKMARK_VIEW_HEX, 7, 2, false, 1, "OLDLBL"); + + const int keys[] = { 'J', 'A', KEY_CTRL_B, KEY_DOWN, KEY_DOWN, KEY_DOWN, 'S', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 9); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("9000", 1); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Goto failed for set-preserves-label test.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM view switch failed for set-preserves-label test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup open failed for set-preserves-label test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup down 1 failed for set-preserves-label test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup down 2 failed for set-preserves-label test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup down 3 failed for set-preserves-label test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup set failed for set-preserves-label test.")) return 1; + get_monitor_status(screen, status); + if (expect(strstr(status, "OLDLBL") != NULL, + "Set must preserve the existing label OLDLBL.")) return 1; + monitor.deinit(); + + // Reopen to ensure the label survived persistence as well. + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 2); + const MonitorBookmarkSlot *slot3 = reopened.get(3); + if (expect(slot3 && strcmp(slot3->label, "OLDLBL") == 0 && slot3->address == 0x9000, + "Persisted set must keep the original label.")) return 1; + return 0; +} + +static int test_monitor_bookmark_popup_render(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[64]; + int left = 0, top = 0, right = 0, bottom = 0; + const int keys[] = { KEY_CTRL_B, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 3); + + reset_bookmark_test_state(); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bookmark popup open failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bookmark popup should draw a bordered overlay.")) return 1; + int inner_w = right - left - 1; + if (expect(inner_w == 38, "Bookmark popup must have 38 inner columns.")) return 1; + + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strncmp(line, "BOOKMARKS", strlen("BOOKMARKS")) == 0, + "Popup header line must be BOOKMARKS.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strspn(line, " ") == strlen(line), + "Popup must separate the header from the bookmarks with a blank line.")) return 1; + + // Verify a few specific row formats. + get_popup_line(screen, 2, line, sizeof(line)); + if (expect(strncmp(line, "0 ZP $0000 HEX 8 CPU", + strlen("0 ZP $0000 HEX 8 CPU")) == 0, + "Default popup slot 0 must be ZP HEX width 8.")) return 1; + get_popup_line(screen, 9, line, sizeof(line)); + if (expect(strncmp(line, "7 CIA1 $DC00 BIN 1 CPU", + strlen("7 CIA1 $DC00 BIN 1 CPU")) == 0, + "Default popup slot 7 must be CIA1 BIN width 1.")) return 1; + get_popup_line(screen, 11, line, sizeof(line)); + if (expect(strncmp(line, "9 KERNAL $E000 ASM CPU", + strlen("9 KERNAL $E000 ASM CPU")) == 0, + "Default popup slot 9 must be KERNAL ASM (padded VIEW6).")) return 1; + get_popup_line(screen, 12, line, sizeof(line)); + if (expect(strspn(line, " ") == strlen(line), + "Popup must separate bookmarks from the help line with a blank line.")) return 1; + get_popup_line(screen, 13, line, sizeof(line)); + if (expect(strncmp(line, "0-9/RET:Jmp S:Set L:Label DEL:Reset", + strlen("0-9/RET:Jmp S:Set L:Label DEL:Reset")) == 0, + "Popup instruction line must match addendum text.")) return 1; + + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_popup_opens_in_edit_mode(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int left = 0, top = 0, right = 0, bottom = 0; + + reset_bookmark_test_state(); + const int keys[] = { 'e', KEY_CTRL_B, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Edit-mode entry before popup open failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup open from edit mode failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bookmark popup must open even when monitor is in EDIT mode.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_popup_close_restores_full_width_border(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int left = 0, top = 0, right = 0, bottom = 0; + const int keys[] = { KEY_CTRL_B, KEY_CTRL_B, KEY_BREAK }; + FakeKeyboard keyboard(keys, 3); + + reset_bookmark_test_state(); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bookmark popup open failed (border cleanup test).")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bookmark popup should draw a full-width bordered overlay.")) return 1; + if (expect(left == 0 && right == 39, + "Bookmark popup border cleanup test requires a full-width overlay.")) return 1; + + if (expect(monitor.poll(0) == 0, "Bookmark popup close failed (border cleanup test).")) return 1; + if (expect(find_popup_rect(screen, NULL, NULL, NULL, NULL) == false, + "Bookmark popup must be gone after closing.")) return 1; + if (expect_monitor_border_restored(screen)) return 1; + + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_popup_navigation_keys(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + char status[39]; + int left = 0, top = 0, right = 0, bottom = 0; + const int keys[] = { KEY_CTRL_B, KEY_DOWN, KEY_DOWN, KEY_RETURN, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + + reset_bookmark_test_state(); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bookmark popup open failed (navigation test).")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bookmark popup rect must be found before navigation.")) return 1; + screen.reset_write_counts(); + if (expect(monitor.poll(0) == 0, "DOWN navigation 1 failed.")) return 1; + if (expect(screen.count_writes_outside_rect(left, top, right, bottom) == 0, + "Bookmark popup navigation must not redraw the underlying monitor view.")) return 1; + if (expect(monitor.poll(0) == 0, "DOWN navigation 2 failed.")) return 1; + if (expect(monitor.poll(0) == 0, "RETURN apply on selected row failed.")) return 1; + get_monitor_status(screen, status); + // Two DOWNs from default selected=0 -> slot 2 (BASIC ASM $0801). + if (expect(strstr(status, "BM2 BASIC $0801 ASM") == status, + "RETURN on selected row must apply that bookmark.")) return 1; + if (expect_monitor_border_restored(screen)) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_popup_pauses_poll_mode(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int left = 0, top = 0, right = 0, bottom = 0; + const int keys[] = { 'P', KEY_CTRL_B }; + FakeKeyboard keyboard(keys, 2); + + reset_bookmark_test_state(); + ui.screen = &screen; + ui.keyboard = &keyboard; + backend.write(0x0000, 0x11); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Poll mode enable failed before popup test.")) return 1; + if (expect(monitor.poll(0) == 0, "Bookmark popup open failed with poll mode enabled.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bookmark popup must be visible before polling pause is checked.")) return 1; + + screen.reset_write_counts(); + backend.write(0x0000, 0x22); + set_fake_ms_timer(20); + if (expect(monitor.poll(0) == 0, "Idle poll while bookmark popup is active failed.")) return 1; + if (expect(find_popup_rect(screen, NULL, NULL, NULL, NULL), + "Bookmark popup must remain open while idle polling is paused.")) return 1; + if (expect(screen.count_writes_outside_rect(left, top, right, bottom) == 0, + "Poll mode must not redraw the monitor outside the bookmark popup while the popup is active.")) return 1; + + monitor.deinit(); + return 0; +} + +static int test_monitor_bookmark_popup_set_preserves_label(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + char status[39]; + + reset_bookmark_test_state(); + seed_bookmark_full(2, 0x0801, MONITOR_BOOKMARK_VIEW_ASM, 7, 2, false, 1, "BASIC"); + + const int keys[] = { 'J', 'A', KEY_CTRL_B, KEY_DOWN, KEY_DOWN, 'S', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 8); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("9000", 1); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Goto for popup set test failed.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM view switch for popup set test failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Popup open for popup set test failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Down 1 for popup set test failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Down 2 for popup set test failed.")) return 1; + if (expect(monitor.poll(0) == 0, "S in popup failed.")) return 1; + + monitor.deinit(); + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 2); + const MonitorBookmarkSlot *slot2 = reopened.get(2); + if (expect(slot2 && slot2->address == 0x9000 && strcmp(slot2->label, "BASIC") == 0, + "Popup S must update target but preserve label.")) return 1; + (void)status; + return 0; +} + +static int test_monitor_bookmark_popup_del_resets_selected(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + + reset_bookmark_test_state(); + seed_bookmark_full(2, 0x9000, MONITOR_BOOKMARK_VIEW_HEX, 0, 1, false, 4, "MYLBL"); + + const int keys[] = { KEY_CTRL_B, KEY_DOWN, KEY_DOWN, KEY_DELETE, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Popup open failed (DEL test).")) return 1; + if (expect(monitor.poll(0) == 0, "Down 1 failed (DEL test).")) return 1; + if (expect(monitor.poll(0) == 0, "Down 2 failed (DEL test).")) return 1; + if (expect(monitor.poll(0) == 0, "DEL on selected slot failed.")) return 1; + + monitor.deinit(); + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 2); + const MonitorBookmarkSlot *slot2 = reopened.get(2); + if (expect(slot2 && slot2->address == 0x0801 && slot2->view == MONITOR_BOOKMARK_VIEW_ASM && + strcmp(slot2->label, "BASIC") == 0, + "DEL on selected slot must restore default target and label.")) return 1; + return 0; +} + +static int test_monitor_bookmark_label_edit(void) +{ + TestUserInterface ui; + CaptureScreen screen; + BookmarkTestBackend backend; + + reset_bookmark_test_state(); + seed_bookmark_full(0, 0x0000, MONITOR_BOOKMARK_VIEW_HEX, 7, 2, false, 1, "ZP"); + + const int keys[] = { KEY_CTRL_B, 'L', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("abc!@#123xyz", 1); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Popup open failed (label edit test).")) return 1; + if (expect(monitor.poll(0) == 0, "L key for label edit failed.")) return 1; + if (expect(ui.last_prompt_maxlen == MONITOR_BOOKMARK_LABEL_MAX, + "Label edit prompt must allow at most 6 characters.")) return 1; + + monitor.deinit(); + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 2); + const MonitorBookmarkSlot *slot0 = reopened.get(0); + if (expect(slot0 && strcmp(slot0->label, "ABC___") == 0 && + slot0->address == 0x0000 && slot0->view == MONITOR_BOOKMARK_VIEW_HEX, + "Label edit must clamp to 6 chars, normalize illegal chars, and preserve target state.")) return 1; + return 0; +} + +static int test_monitor_bookmark_shortcut_routing(void) +{ + char header[39]; + + reset_bookmark_test_state(); + seed_bookmark_full(1, 0xC000, MONITOR_BOOKMARK_VIEW_ASM, 7, 2, false, 1, "T1"); + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'e', '1', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + + ui.screen = &screen; + ui.keyboard = &keyboard; + monitor_reset_saved_state(); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Hex edit entry failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Digit routing in edit mode failed.")) return 1; + get_monitor_header(screen, header); + if (expect(strstr(header, "MONITOR HEX $0000") == header, + "Digit restore should not trigger while editing.")) return 1; + monitor.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'e', KEY_CTRL_1, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + + ui.screen = &screen; + ui.keyboard = &keyboard; + monitor_reset_saved_state(); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Hex edit entry before bookmark jump failed.")) return 1; + if (expect(monitor.poll(0) == 0, "CBM+1 bookmark jump should work in edit mode.")) return 1; + get_monitor_header(screen, header); + if (expect(strstr(header, "MONITOR ASM $C000") == header && strstr(header, "Edit") != NULL, + "Bookmark jumps must stay enabled in edit mode and preserve edit state.")) return 1; + monitor.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'N', '1', KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + + ui.screen = &screen; + ui.keyboard = &keyboard; + monitor_reset_saved_state(); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Number popup open failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Digit while number popup is open should stay in the popup.")) return 1; + if (expect(find_popup_rect(screen, NULL, NULL, NULL, NULL), + "Number popup should remain open when digits are typed into it.")) return 1; + monitor.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { '1', KEY_BREAK }; + FakeKeyboard keyboard(keys, 2); + + ui.screen = &screen; + ui.keyboard = &keyboard; + monitor_reset_saved_state(); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bare digit in main view should remain a normal key.")) return 1; + get_monitor_header(screen, header); + if (expect(strstr(header, "$C000") == NULL, + "Bare digits in main monitor views must not jump to bookmarks.")) return 1; + monitor.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { KEY_CTRL_1, KEY_BREAK }; + FakeKeyboard keyboard(keys, 2); + + ui.screen = &screen; + ui.keyboard = &keyboard; + monitor_reset_saved_state(); + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "CBM+1 bookmark jump failed.")) return 1; + get_monitor_header(screen, header); + if (expect(strstr(header, "MONITOR ASM $C000") == header, + "CBM+digits in main monitor views must jump to bookmarks.")) return 1; + monitor.deinit(); + } + + MonitorBookmarks reopened; + reopened.ensure_loaded(7, 2); + const MonitorBookmarkSlot *slot1 = reopened.get(1); + if (expect(slot1 && slot1->address == 0xC000 && strcmp(slot1->label, "T1") == 0, + "CBM+digits in main monitor views must not overwrite bookmark targets.")) return 1; + + return 0; +} + +static int test_monitor_bookmark_status_dismissal(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char status[39]; + const int keys[] = { KEY_CTRL_1, KEY_RIGHT, KEY_BREAK }; + FakeKeyboard keyboard(keys, 3); + + reset_bookmark_test_state(); + // Model the real C64 power-on 6510 port ($01 = $37 -> live bank 7) so the + // live CPU bank matches the restored monitor view bank (7). Otherwise the + // live bank reads 0 from the zeroed backend and the normal footer renders a + // live/view mismatch (C0O7) instead of the expected CPU7. + backend.write(0x0001, 0x37); + seed_bookmark_full(1, 0x0801, MONITOR_BOOKMARK_VIEW_ASM, 7, 2, false, 1, "BASIC"); + ui.screen = &screen; + ui.keyboard = &keyboard; + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Bookmark restore for status dismissal test failed.")) return 1; + get_monitor_status(screen, status); + if (expect(strstr(status, "BM1 BASIC $0801 ASM CPU7 VIC2") == status, + "Bookmark restore status message should appear immediately.")) return 1; + if (expect(monitor.poll(0) == 0, "Next user action should dismiss bookmark status.")) return 1; + get_monitor_status(screen, status); + if (expect(strstr(status, "CPU7") == status, + "Next user action should restore the normal bottom status row.")) return 1; + monitor.deinit(); + return 0; +} + +int main() +{ + if (test_bookmark_addendum_default_table()) return 1; + if (test_bookmark_label_normalize_helper()) return 1; + if (test_bookmark_corrupt_config_falls_back_to_defaults()) return 1; + if (test_bookmark_old_six_field_falls_back()) return 1; + if (test_bookmark_persists_label_and_width_mode()) return 1; + if (test_bookmark_set_preserves_label()) return 1; + if (test_bookmark_label_edit_changes_only_label()) return 1; + if (test_bookmark_selected_reset_restores_default()) return 1; + if (test_bookmark_status_message_formatting()) return 1; + if (test_bookmark_popup_line_formatting()) return 1; + if (test_bookmark_default_popup_alignment()) return 1; + if (test_bookmark_popup_instruction_line()) return 1; + if (test_bookmark_six_char_custom_label_fits()) return 1; + if (test_bookmark_overlong_persisted_label_truncates_for_display()) return 1; + if (test_monitor_bookmark_capture_restore_includes_width_mode()) return 1; + if (test_monitor_bookmark_restore_applies_width_w3()) return 1; + if (test_monitor_bookmark_capture_restore_includes_memory_width()) return 1; + if (test_monitor_bookmark_set_captures_memory_width()) return 1; + if (test_monitor_bookmark_capture_no_memory_write()) return 1; + if (test_monitor_bookmark_set_preserves_label()) return 1; + if (test_monitor_bookmark_popup_render()) return 1; + if (test_monitor_bookmark_popup_opens_in_edit_mode()) return 1; + if (test_monitor_bookmark_popup_close_restores_full_width_border()) return 1; + if (test_monitor_bookmark_popup_navigation_keys()) return 1; + if (test_monitor_bookmark_popup_pauses_poll_mode()) return 1; + if (test_monitor_bookmark_popup_set_preserves_label()) return 1; + if (test_monitor_bookmark_popup_del_resets_selected()) return 1; + if (test_monitor_bookmark_label_edit()) return 1; + if (test_monitor_bookmark_shortcut_routing()) return 1; + if (test_monitor_bookmark_status_dismissal()) return 1; + + puts("machine_monitor_bookmarks_test: OK"); + return 0; +} diff --git a/software/test/monitor/machine_monitor_debug_test.cc b/software/test/monitor/machine_monitor_debug_test.cc new file mode 100644 index 000000000..4212ea476 --- /dev/null +++ b/software/test/monitor/machine_monitor_debug_test.cc @@ -0,0 +1,6964 @@ +// Host tests for Assembly Debug mode (DBG-MODE-001 ... DBG-TEST-001). +// +// These tests exercise the modal state, key routing, header flag composition, +// fixed CPU footer layout, breakpoint table, and patch cleanup paths without +// needing a real 6510 to run against. A stub DebugSession wired through a +// derived backend lets us verify Over/Trace/Out/Go dispatch and that cleanup +// is invoked on monitor close and debug-off. + +#include +#include +#include +#include + +#include "machine_monitor.h" +#include "monitor_breakpoints.h" +#include "monitor_debug.h" +#include "monitor_debug_session.h" +#include "monitor_debug_brk_session.h" +#include "monitor_debug_u64.h" +#include "monitor_file_io.h" +#include "monitor_debug_predictor.h" +#include "machine_monitor_test_support.h" + +// Host stubs for monitor_io. The Debug-mode tests do not exercise file IO +// or the live `G` handoff, but MachineMonitor still pulls these symbols in. + +static int g_swap_interface_type_calls = 0; + +int swap_interface_type(UserInterface *ui) +{ + (void)ui; + g_swap_interface_type_calls++; + return MENU_HIDE; +} +namespace monitor_io { +bool pick_file(UserInterface *, const char *, char *, int, char *, int, bool) { + return false; +} +const char *load_into_memory(const char *, const char *, MemoryBackend *, + uint16_t, bool, uint32_t, bool, uint32_t, + uint16_t *, uint32_t *) { + return "NOT SUPPORTED"; +} +const char *save_from_memory(UserInterface *, const char *, const char *, + MemoryBackend *, uint16_t, uint16_t) { + return "NOT SUPPORTED"; +} +void jump_to(uint16_t) { } +void resume_to_context(const DebugContext &) { } +} + +namespace { + +struct StubDebugSession : public DebugSession +{ + int over_calls; + int over_at_calls; + int over_breakpoint_calls; + int over_at_breakpoint_calls; + int trace_calls; + int trace_at_calls; + int out_calls; + int out_breakpoint_calls; + int go_calls; + int run_to_calls; + int cleanup_calls; + int cleanup_to_context_calls; + int snapshot_calls; + int claim_calls; + int refresh_calls; + int release_calls; + uint16_t last_start_pc; + uint16_t last_run_to_target; + bool last_go_from_valid; + uint16_t last_go_from_pc; + DebugContext cleanup_target_ctx; + DebugContext next_ctx; + bool predict_bytes_valid; + uint8_t predict_bytes[3]; + Result over_result; + Result trace_result; + Result out_result; + Result go_result; + Result run_to_result; + Result snapshot_result; + bool claim_allowed; + bool go_produces_snapshot; + bool parked_context_handoff_supported; + + StubDebugSession() + : over_calls(0), over_at_calls(0), + over_breakpoint_calls(0), over_at_breakpoint_calls(0), + trace_calls(0), trace_at_calls(0), + out_calls(0), out_breakpoint_calls(0), + go_calls(0), run_to_calls(0), cleanup_calls(0), + cleanup_to_context_calls(0), + snapshot_calls(0), claim_calls(0), + refresh_calls(0), release_calls(0), + last_start_pc(0), last_run_to_target(0), + last_go_from_valid(false), last_go_from_pc(0), + predict_bytes_valid(false), + over_result(DBG_OK), trace_result(DBG_OK), + out_result(DBG_OK), go_result(DBG_OK), run_to_result(DBG_OK), + snapshot_result(DBG_OK), claim_allowed(true), + go_produces_snapshot(false), + parked_context_handoff_supported(false) + { + debug_context_reset(&cleanup_target_ctx); + debug_context_reset(&next_ctx); + next_ctx.valid = true; + next_ctx.pc = 0xC003; + next_ctx.sp = 0xF7; + next_ctx.a = 0x01; + next_ctx.x = 0x00; + next_ctx.y = 0xFF; + next_ctx.sr = 0x24; + next_ctx.irq_valid = true; + next_ctx.irq_vec = 0xC123; + next_ctx.nmi_valid = true; + next_ctx.nmi_vec = 0xEA31; + predict_bytes[0] = 0; + predict_bytes[1] = 0; + predict_bytes[2] = 0; + } + + virtual Result snapshot(DebugContext *ctx) { + snapshot_calls++; + if (snapshot_result == DBG_OK && ctx) { + *ctx = next_ctx; + } + return snapshot_result; + } + virtual Result over(const DebugContext &, const DebugPredictResult &, DebugContext *ctx) { + over_calls++; + if (over_result == DBG_OK && ctx) { + *ctx = next_ctx; + } + return over_result; + } + virtual Result over(const DebugContext &from, const DebugPredictResult &pred, + const MonitorBreakpoints *, DebugContext *ctx) { + over_breakpoint_calls++; + return over(from, pred, ctx); + } + virtual Result over_at(uint16_t start_pc, const DebugPredictResult &, DebugContext *ctx) { + over_at_calls++; + last_start_pc = start_pc; + if (over_result == DBG_OK && ctx) { + *ctx = next_ctx; + } + return over_result; + } + virtual Result over_at(uint16_t start_pc, const DebugPredictResult &pred, + const MonitorBreakpoints *, DebugContext *ctx) { + over_at_breakpoint_calls++; + return over_at(start_pc, pred, ctx); + } + virtual Result trace(const DebugContext &, const DebugPredictResult &, DebugContext *ctx) { + trace_calls++; + if (trace_result == DBG_OK && ctx) { + *ctx = next_ctx; + } + return trace_result; + } + virtual Result trace_at(uint16_t start_pc, const DebugPredictResult &, DebugContext *ctx) { + trace_at_calls++; + last_start_pc = start_pc; + if (trace_result == DBG_OK && ctx) { + *ctx = next_ctx; + } + return trace_result; + } + virtual Result step_out(const DebugContext &, DebugContext *ctx) { + out_calls++; + if (out_result == DBG_OK && ctx) { + *ctx = next_ctx; + } + return out_result; + } + virtual Result step_out(const DebugContext &from, + const MonitorBreakpoints *, DebugContext *ctx) { + out_breakpoint_calls++; + return step_out(from, ctx); + } + virtual Result go(const DebugContext &from, const MonitorBreakpoints *, uint16_t start_pc) { + go_calls++; + last_start_pc = start_pc; + last_go_from_valid = from.valid; + last_go_from_pc = from.pc; + // Model the real session's semantic: Go invalidates the previous + // capture. If a stop happens during this Go, a real session would + // refresh `next_ctx`; the stub simulates "no stop happened" by + // marking snapshot unavailable until the next over/trace/out call + // explicitly captures something. + if (snapshot_result == DBG_OK && !go_produces_snapshot) { + snapshot_result = DBG_NOT_SUPPORTED; + } + return go_result; + } + virtual Result run_to(const DebugContext &, uint16_t target_pc, + const MonitorBreakpoints *, uint16_t start_pc, + DebugContext *ctx) { + run_to_calls++; + last_run_to_target = target_pc; + last_start_pc = start_pc; + if (run_to_result == DBG_OK && ctx) { + *ctx = next_ctx; + } + return run_to_result; + } + virtual void cleanup(void) { + cleanup_calls++; + } + virtual void cleanup_to_context(const DebugContext *ctx) { + cleanup_calls++; + cleanup_to_context_calls++; + if (ctx) { + cleanup_target_ctx = *ctx; + } else { + debug_context_reset(&cleanup_target_ctx); + } + } + virtual bool has_parked_context_handoff(void) const { + return parked_context_handoff_supported; + } + virtual bool read_step_bytes(uint16_t, uint8_t *dst, uint8_t len) { + if (!predict_bytes_valid || !dst || len == 0) { + return false; + } + for (uint8_t i = 0; i < len && i < 3; i++) { + dst[i] = predict_bytes[i]; + } + return true; + } + virtual bool claim_debug_ownership(bool) { + claim_calls++; + return claim_allowed; + } + virtual void refresh_debug_ownership(void) { + refresh_calls++; + } + virtual void release_debug_ownership(void) { + release_calls++; + } +}; + +// Singleton stub session shared with FakeDebugBackend so tests can both +// install canned outputs ahead of time and assert call counts afterwards. +struct DebugBackendController +{ + StubDebugSession session; + bool refuse_session; + int session_creations; + + DebugBackendController() : refuse_session(false), session_creations(0) {} +}; + +struct FakeDebugBackend : public FakeMemoryBackend +{ + DebugBackendController *ctrl; + FakeDebugBackend(DebugBackendController *c) : ctrl(c) {} + + virtual DebugSession *create_debug_session(void) { + if (!ctrl || ctrl->refuse_session) { + return NULL; + } + ctrl->session_creations++; + // Return a fresh instance so MachineMonitor's `delete debug_session` + // is safe; copy the controller's canned state into it. + StubDebugSession *s = new StubDebugSession(); + *s = ctrl->session; + // Reset counters owned by this instance (we keep the controller's + // session as the truth for asserting after destruction would lose + // them, so we forward call counts on cleanup via an out param). + return s; + } +}; + +// Like FakeDebugBackend but exposes the session so tests can introspect. +// MachineMonitor owns the lifetime, so we keep a raw pointer via the +// controller and update its `last_session` whenever a new session is created. +struct TrackingDebugBackend : public FakeMemoryBackend +{ + StubDebugSession *last_session; + int session_creations; + bool refuse_session; + int reset_calls; + int nmi_pulses; + bool allow_reset; + DebugContext canned_snapshot; + bool canned_snapshot_set; + DebugSession::Result snapshot_result; + bool session_claim_allowed; + bool go_produces_snapshot; + bool parked_context_handoff_supported; + + TrackingDebugBackend() : last_session(NULL), session_creations(0), + refuse_session(false), reset_calls(0), + allow_reset(true), canned_snapshot_set(false), + snapshot_result(DebugSession::DBG_OK), + session_claim_allowed(true), + go_produces_snapshot(false), + parked_context_handoff_supported(false) + { + debug_context_reset(&canned_snapshot); + } + + virtual DebugSession *create_debug_session(void) { + if (refuse_session) { + return NULL; + } + session_creations++; + last_session = new StubDebugSession(); + if (canned_snapshot_set) { + last_session->next_ctx = canned_snapshot; + } + last_session->snapshot_result = snapshot_result; + last_session->claim_allowed = session_claim_allowed; + last_session->go_produces_snapshot = go_produces_snapshot; + last_session->parked_context_handoff_supported = parked_context_handoff_supported; + return last_session; + } + + virtual bool supports_reset(void) const { return allow_reset; } + + virtual bool reset_machine(void) { + if (!allow_reset) { + return false; + } + reset_calls++; + return true; + } +}; + +struct SourceLabelDebugBackend : public TrackingDebugBackend +{ + virtual const char *source_name(uint16_t address) const { + switch (address) { + case 0x1000: return "RAM"; + case 0x1001: return "BASIC"; + case 0x1002: return "KERNAL"; + case 0x1003: return "CHAR"; + case 0x1004: return "IO"; + default: break; + } + if (address >= 0xD000 && address <= 0xDFFF) { + return "IO"; + } + if (address >= 0xE000) { + return "RAM"; + } + return "RAM"; + } +}; + +// Direct render-target regression harness for the BRK debug engine. +// +// FakeFreezeMachine implements the BrkDebugSession hardware hooks over a flat +// 64K RAM array plus a `frozen` flag that mirrors C64::isFrozen. It models the +// freeze-mode invariant the production fix enforces: a debug step temporarily +// unfreezes the machine to run the live CPU, then MUST re-freeze before control +// returns so the monitor keeps rendering into the firmware/menu screen instead +// of the live C64 screen RAM. The reserved sentinel byte is set on the first +// delay() call to simulate the BRK trampoline firing. +namespace { + +static const uint16_t FAKE_SENTINEL_ADDR = 0x03F7; // mirrors SENTINEL_ADDR +static const uint16_t FAKE_SCREEN_BASE = 0x0400; // C64 screen RAM aperture +static const uint16_t FAKE_STORE_Y = 0x03F0; +static const uint16_t FAKE_STORE_X = 0x03F1; +static const uint16_t FAKE_STORE_A = 0x03F2; +static const uint16_t FAKE_STORE_SR = 0x03F3; +static const uint16_t FAKE_STORE_PCLO = 0x03F4; +static const uint16_t FAKE_STORE_PCHI = 0x03F5; +static const uint16_t FAKE_STORE_SP = 0x03F6; +static const uint16_t FAKE_STORE_CPU_DDR = 0x03F8; +static const uint16_t FAKE_STORE_CPU_PORT = 0x03F9; +static const uint16_t FAKE_STORE_TRAP_MODE = 0x03FA; +static const uint16_t FAKE_STORE_HARD_CPU_DDR = 0x03FB; +static const uint16_t FAKE_STORE_HARD_CPU_PORT = 0x03ED; +static const uint16_t FAKE_HARD_BRK_ORIG_VECTOR_LO = 0x03EE; +static const uint16_t FAKE_DEBUG_AREA_START = 0x033C; +static const uint16_t FAKE_DEBUG_AREA_END = 0x03FB; +static const uint16_t FAKE_HANDLER_ADDR = 0x0363; +static const uint16_t FAKE_HANDLER_LEN = 39; +static const uint16_t FAKE_SPIN_JMP = 0x0387; +static const uint16_t FAKE_SPIN_LO = 0x0388; +static const uint16_t FAKE_SPIN_HI = 0x0389; +static const uint16_t FAKE_RESUME_TRAMP = FAKE_HANDLER_ADDR; +static const uint16_t FAKE_TRAMPOLINE = 0x038A; +static const uint16_t FAKE_TRAMPOLINE_LEN = 38; +static const uint16_t FAKE_NMI_VECTOR_HI = 0x0319; // mirrors NMI_VECTOR_HI +static const uint16_t FAKE_NMI_TRAMP = 0x03B0; // mirrors NMI_TRAMPOLINE_ADDR +static const uint16_t FAKE_NMI_TRAMP_LEN = 24; +static const uint16_t FAKE_HARD_BRK_STUB = 0x03C8; // mirrors HARD_BRK_STUB_ADDR +static const uint16_t FAKE_HARD_BRK_STUB_LEN = 37; +static const uint16_t FAKE_HARD_NMI_VECTOR_LO = 0xFFFA; +static const uint16_t FAKE_HARD_NMI_VECTOR_HI = 0xFFFB; +static const uint16_t FAKE_HARD_VECTOR_LO = 0xFFFE; +static const uint16_t FAKE_HARD_VECTOR_HI = 0xFFFF; + +class FakeFreezeMachine : public BrkDebugSession +{ +public: + enum { MAX_RECORDED_BRK_PATCHES = 32 }; + enum { MAX_RECORDED_FREEZE_RESTORE_POKES = 160 }; + + uint8_t ram[65536]; + bool frozen; + bool accessible_when_unfrozen; + bool break_on_unfrozen_unfreeze_attempt; + int unfreeze_attempts; + int unfreeze_calls; + int refreeze_calls; + int reset_calls; + int nmi_pulses; + int staged_nmi_requests; + int staged_nmi_clears; + int brk_patch_writes; + int delay_calls; + int pokes_at_cancel; + uint16_t last_brk_patch_addr; + uint16_t brk_patch_addrs[MAX_RECORDED_BRK_PATCHES]; + int freeze_restore_pokes; + uint16_t freeze_restore_addrs[MAX_RECORDED_FREEZE_RESTORE_POKES]; + uint8_t freeze_restore_bytes[MAX_RECORDED_FREEZE_RESTORE_POKES]; + // When false, delay_ms() does NOT raise the sentinel, so wait_for_sentinel + // runs to its full timeout. Lets a test force the DBG_TIMEOUT path and then + // re-arm to prove the run-window state (depth, freeze bracketing) recovered. + bool sentinel_armed; + // Test hook: model the freeze-mode "gap free-run" race. When set, the live + // CPU is treated as having reached the already-installed step BRK while the + // controlled NMI launch is still being set up, so the sentinel goes high + // mid-setup (as the NMI vector high byte is written). A correct launch must + // clear that stale sentinel before releasing the CPU. + bool stale_sentinel_during_nmi_setup; + bool nmi_from_spin_times_out; + bool reset_cancel_on_delay; + bool monitor_reset_cancel_on_delay; + MachineMonitor *monitor_reset_cancel_target; + bool capture_override_armed; + uint16_t capture_override_pc; + uint8_t capture_override_sp; + uint8_t capture_override_a; + uint8_t capture_override_x; + uint8_t capture_override_y; + uint8_t capture_override_sr; + uint8_t capture_override_trap_mode; + uint8_t capture_override_hard_cpu_ddr; + uint8_t capture_override_hard_cpu_port; + + FakeFreezeMachine(bool start_frozen) + : frozen(start_frozen), accessible_when_unfrozen(false), + break_on_unfrozen_unfreeze_attempt(false), unfreeze_attempts(0), + unfreeze_calls(0), refreeze_calls(0), reset_calls(0), nmi_pulses(0), + staged_nmi_requests(0), staged_nmi_clears(0), + brk_patch_writes(0), delay_calls(0), pokes_at_cancel(0), + last_brk_patch_addr(0), + freeze_restore_pokes(0), + sentinel_armed(true), stale_sentinel_during_nmi_setup(false), + nmi_from_spin_times_out(false), reset_cancel_on_delay(false), + monitor_reset_cancel_on_delay(false), + monitor_reset_cancel_target(NULL), + capture_override_armed(false), + capture_override_pc(0), capture_override_sp(0), + capture_override_a(0), capture_override_x(0), capture_override_y(0), + capture_override_sr(0), capture_override_trap_mode(0), + capture_override_hard_cpu_ddr(0), capture_override_hard_cpu_port(0) + { + memset(ram, 0, sizeof(ram)); + memset(brk_patch_addrs, 0, sizeof(brk_patch_addrs)); + memset(freeze_restore_addrs, 0, sizeof(freeze_restore_addrs)); + memset(freeze_restore_bytes, 0, sizeof(freeze_restore_bytes)); + } + + // Leaf cleanup while the fake hooks are still live (the abstract base + // destructor intentionally does not call cleanup()). + virtual ~FakeFreezeMachine() { cleanup(); } + + // Stamp a recognizable BASIC-like pattern into the C64 screen RAM so a test + // can prove monitor redraws never reach it. + void stamp_screen_sentinel(uint8_t value, int len) + { + for (int i = 0; i < len; i++) { + ram[FAKE_SCREEN_BASE + i] = value; + } + } + bool screen_sentinel_intact(uint8_t value, int len) const + { + for (int i = 0; i < len; i++) { + if (ram[FAKE_SCREEN_BASE + i] != value) { + return false; + } + } + return true; + } + + void reset_freeze_restore_pokes(void) + { + freeze_restore_pokes = 0; + memset(freeze_restore_addrs, 0, sizeof(freeze_restore_addrs)); + memset(freeze_restore_bytes, 0, sizeof(freeze_restore_bytes)); + } + + bool recorded_freeze_restore_poke(uint16_t address, uint8_t byte) const + { + int n = freeze_restore_pokes; + if (n > MAX_RECORDED_FREEZE_RESTORE_POKES) { + n = MAX_RECORDED_FREEZE_RESTORE_POKES; + } + for (int i = 0; i < n; i++) { + if (freeze_restore_addrs[i] == address && + freeze_restore_bytes[i] == byte) { + return true; + } + } + return false; + } + + void arm_capture_context(uint16_t pc, uint8_t sp, uint8_t a, + uint8_t x, uint8_t y, uint8_t sr) + { + capture_override_armed = true; + capture_override_pc = pc; + capture_override_sp = sp; + capture_override_a = a; + capture_override_x = x; + capture_override_y = y; + capture_override_sr = sr; + capture_override_trap_mode = 0; + capture_override_hard_cpu_ddr = 0; + capture_override_hard_cpu_port = 0; + } + + void arm_hard_vector_capture_context(uint16_t pc, uint8_t sp, uint8_t a, + uint8_t x, uint8_t y, uint8_t sr, + uint8_t cpu_ddr, uint8_t cpu_port) + { + arm_capture_context(pc, sp, a, x, y, sr); + capture_override_trap_mode = 0xA5; + capture_override_hard_cpu_ddr = cpu_ddr; + capture_override_hard_cpu_port = cpu_port; + } + +protected: + virtual bool backend_ready(void) const { return true; } + virtual uint8_t current_cpu_port(void) const { return 0x07; } + virtual bool begin_stopped_session(void) { return false; } + virtual void end_stopped_session(bool) { } + virtual uint8_t peek_cpu(uint16_t a, uint8_t) { return ram[a]; } + virtual void poke_cpu(uint16_t a, uint8_t b, uint8_t) + { + if (b == 0x00 && + a != FAKE_HARD_NMI_VECTOR_LO && + a != FAKE_HARD_NMI_VECTOR_HI && + a != FAKE_HARD_VECTOR_LO && + a != FAKE_HARD_VECTOR_HI) { + if (brk_patch_writes < MAX_RECORDED_BRK_PATCHES) { + brk_patch_addrs[brk_patch_writes] = a; + } + brk_patch_writes++; + last_brk_patch_addr = a; + } + ram[a] = b; + } + virtual uint8_t peek_visible(uint16_t a) { return ram[a]; } + virtual void poke_visible(uint16_t a, uint8_t b) + { + ram[a] = b; + // nmi_redirect_to() writes the NMI vector while the CPU is stopped, just + // before releasing it. Fire the modelled gap free-run BRK hit here so a + // correct launch must still clear the sentinel afterwards. + if (stale_sentinel_during_nmi_setup && a == FAKE_NMI_VECTOR_HI) { + ram[FAKE_SENTINEL_ADDR] = 0xFF; + } + } + virtual void poke_visible_preserving_freeze_restore(uint16_t a, uint8_t b) + { + if (freeze_restore_pokes < MAX_RECORDED_FREEZE_RESTORE_POKES) { + freeze_restore_addrs[freeze_restore_pokes] = a; + freeze_restore_bytes[freeze_restore_pokes] = b; + } + freeze_restore_pokes++; + poke_visible(a, b); + } + virtual void unfreeze_if_accessible(void) + { + bool accessible = frozen || accessible_when_unfrozen; + if (!accessible) { + return; + } + unfreeze_attempts++; + if (frozen) { + frozen = false; + unfreeze_calls++; + } else if (break_on_unfrozen_unfreeze_attempt) { + sentinel_armed = false; + } + } + virtual bool machine_is_frozen(void) const { return frozen; } + virtual void refreeze_machine(void) + { + if (!frozen) { + frozen = true; + refreeze_calls++; + } + } + virtual bool reset_machine(void) { reset_calls++; return true; } + virtual void pulse_nmi_and_release(bool) + { + nmi_pulses++; + if (nmi_from_spin_times_out && + nmi_pulses > 1 && + ram[FAKE_SPIN_LO] == (uint8_t)(FAKE_SPIN_JMP & 0xFF) && + ram[FAKE_SPIN_HI] == (uint8_t)(FAKE_SPIN_JMP >> 8)) { + sentinel_armed = false; + } + } + virtual void request_staged_nmi(void) + { + nmi_pulses++; + staged_nmi_requests++; + } + virtual void clear_staged_nmi(void) + { + staged_nmi_clears++; + } + virtual void delay_ms(int) + { + delay_calls++; + if (monitor_reset_cancel_on_delay && monitor_reset_cancel_target) { + monitor_reset_cancel_target->request_debug_reset_cancel(); + pokes_at_cancel = freeze_restore_pokes; + monitor_reset_cancel_on_delay = false; + return; + } + if (reset_cancel_on_delay) { + request_reset_cancel(); + pokes_at_cancel = freeze_restore_pokes; + reset_cancel_on_delay = false; + return; + } + // Model the BRK trampoline reaching the spin loop: the sentinel becomes + // non-zero so the next wait_for_sentinel poll returns DBG_OK. When the + // test disarms the sentinel, leave it clear so the engine runs to its + // DBG_TIMEOUT. + if (sentinel_armed) { + if (capture_override_armed) { + ram[FAKE_STORE_Y] = capture_override_y; + ram[FAKE_STORE_X] = capture_override_x; + ram[FAKE_STORE_A] = capture_override_a; + ram[FAKE_STORE_SR] = capture_override_sr; + ram[FAKE_STORE_PCLO] = (uint8_t)((capture_override_pc + 2) & 0xFF); + ram[FAKE_STORE_PCHI] = (uint8_t)((capture_override_pc + 2) >> 8); + ram[FAKE_STORE_SP] = capture_override_sp; + ram[FAKE_STORE_TRAP_MODE] = capture_override_trap_mode; + ram[FAKE_STORE_HARD_CPU_DDR] = capture_override_hard_cpu_ddr; + ram[FAKE_STORE_HARD_CPU_PORT] = capture_override_hard_cpu_port; + capture_override_trap_mode = 0; + capture_override_hard_cpu_ddr = 0; + capture_override_hard_cpu_port = 0; + capture_override_armed = false; + } + ram[FAKE_SENTINEL_ADDR] = 0xFF; + } + } +}; + +class FakeVisibleRomMachine : public FakeFreezeMachine +{ +public: + uint8_t basic_rom[8192]; + uint8_t kernal_rom[8192]; + uint8_t char_rom[4096]; + uint8_t cpu_port; + bool allow_visible_rom_patching; + bool force_raw_peek_brk; + uint16_t force_raw_peek_brk_addr; + int rom_patch_writes; + uint16_t last_rom_patch_addr; + int ram_patch_writes; + uint16_t last_ram_patch_addr; + bool switch_cpu_port_on_delay; + uint8_t cpu_port_after_delay; + + FakeVisibleRomMachine(bool start_frozen) + : FakeFreezeMachine(start_frozen), cpu_port(0x07), + allow_visible_rom_patching(false), force_raw_peek_brk(false), + force_raw_peek_brk_addr(0), rom_patch_writes(0), last_rom_patch_addr(0), + ram_patch_writes(0), last_ram_patch_addr(0), + switch_cpu_port_on_delay(false), cpu_port_after_delay(0x07) + { + memset(basic_rom, 0, sizeof(basic_rom)); + memset(kernal_rom, 0, sizeof(kernal_rom)); + memset(char_rom, 0, sizeof(char_rom)); + } + +protected: + volatile uint8_t *rom_patch_ptr(uint16_t addr, uint8_t patch_cpu_port) + { + patch_cpu_port &= 0x07; + if (addr >= 0xA000 && addr <= 0xBFFF && + ((patch_cpu_port & 0x03) == 0x03)) { + return &basic_rom[addr - 0xA000]; + } + if (addr >= 0xD000 && addr <= 0xDFFF && + ((patch_cpu_port & 0x03) != 0x00) && + ((patch_cpu_port & 0x04) == 0x00)) { + return &char_rom[addr - 0xD000]; + } + if (addr >= 0xE000 && (patch_cpu_port & 0x02)) { + return &kernal_rom[addr - 0xE000]; + } + return 0; + } + + virtual uint8_t current_cpu_port(void) const { return cpu_port; } + virtual bool supports_visible_rom_patching(void) const + { + return allow_visible_rom_patching; + } + virtual uint8_t peek_cpu(uint16_t a, uint8_t patch_cpu_port) + { + patch_cpu_port &= 0x07; + if (force_raw_peek_brk && a == force_raw_peek_brk_addr) { + return 0x00; + } + if (a >= 0xA000 && a <= 0xBFFF && ((patch_cpu_port & 0x03) == 0x03)) { + return basic_rom[a - 0xA000]; + } + if (a >= 0xD000 && a <= 0xDFFF && + ((patch_cpu_port & 0x03) != 0x00) && + ((patch_cpu_port & 0x04) == 0x00)) { + return char_rom[a - 0xD000]; + } + if (a >= 0xE000 && (patch_cpu_port & 0x02)) { + return kernal_rom[a - 0xE000]; + } + return ram[a]; + } + virtual void poke_cpu(uint16_t a, uint8_t b, uint8_t patch_cpu_port) + { + volatile uint8_t *rom = rom_patch_ptr(a, patch_cpu_port); + if (rom && allow_visible_rom_patching) { + *rom = b; + return; + } + ram[a] = b; + } + virtual uint8_t read_patch_byte(uint16_t a, uint8_t patch_cpu_port) + { + volatile uint8_t *rom = rom_patch_ptr(a, patch_cpu_port); + if (rom && allow_visible_rom_patching) { + return *rom; + } + return peek_cpu(a, patch_cpu_port); + } + virtual void write_patch_byte(uint16_t a, uint8_t b, uint8_t patch_cpu_port) + { + volatile uint8_t *rom = rom_patch_ptr(a, patch_cpu_port); + if (rom && allow_visible_rom_patching) { + if (b == 0x00) { + if (brk_patch_writes < MAX_RECORDED_BRK_PATCHES) { + brk_patch_addrs[brk_patch_writes] = a; + } + brk_patch_writes++; + last_brk_patch_addr = a; + } + *rom = b; + rom_patch_writes++; + last_rom_patch_addr = a; + return; + } + if (b == 0x00) { + ram_patch_writes++; + last_ram_patch_addr = a; + } + poke_cpu(a, b, patch_cpu_port); + } + virtual void delay_ms(int ms) + { + if (switch_cpu_port_on_delay) { + cpu_port = (uint8_t)(cpu_port_after_delay & 0x07); + switch_cpu_port_on_delay = false; + } + FakeFreezeMachine::delay_ms(ms); + } +}; + +class FakeCpuPortBackend : public MemoryBackend +{ +public: + uint8_t live_cpu_port; + int live_reads; + + FakeCpuPortBackend() + : live_cpu_port(0x05), live_reads(0) + { + } + + virtual uint8_t read(uint16_t address) + { + if (address == 0x0001) { + live_reads++; + return live_cpu_port; + } + return 0; + } + virtual void write(uint16_t, uint8_t) { } +}; + +static void fake_seed_nop_run(FakeFreezeMachine &m, uint16_t addr); +static void fake_seed_captured_context(FakeFreezeMachine &m, uint16_t pc, + uint8_t sp, uint8_t a, + uint8_t x, uint8_t y, uint8_t sr); + +class BrkSessionBackend : public FakeMemoryBackend +{ +public: + FakeFreezeMachine *last_session; + bool start_frozen; + + BrkSessionBackend(bool frozen = false) + : last_session(NULL), start_frozen(frozen) + { + } + + virtual DebugSession *create_debug_session(void) + { + last_session = new FakeFreezeMachine(start_frozen); + fake_seed_nop_run(*last_session, 0x0801); + fake_seed_captured_context(*last_session, 0x0802, 0xFE, 0x11, 0x22, 0x33, 0x20); + return last_session; + } +}; + +// Build a one-byte NOP "program" at addr so the predictor classifies it as a +// linear step and install_brk_at has a non-zero byte to overwrite. +static void fake_seed_nop_run(FakeFreezeMachine &m, uint16_t addr) +{ + m.ram[addr] = 0xEA; // NOP at PC + m.ram[addr + 1] = 0xEA; // fall-through target (BRK lands here; must be != 0) + m.ram[addr + 2] = 0xEA; +} + +static void fake_seed_rom_nop_run(FakeVisibleRomMachine &m, uint16_t addr) +{ + if (addr >= 0xA000 && addr <= 0xBFFF) { + m.basic_rom[addr - 0xA000] = 0xEA; + m.basic_rom[addr - 0xA000 + 1] = 0xEA; + m.basic_rom[addr - 0xA000 + 2] = 0xEA; + return; + } + if (addr >= 0xE000) { + m.kernal_rom[addr - 0xE000] = 0xEA; + m.kernal_rom[addr - 0xE000 + 1] = 0xEA; + m.kernal_rom[addr - 0xE000 + 2] = 0xEA; + } +} + +static void fake_seed_captured_context(FakeFreezeMachine &m, uint16_t pc, + uint8_t sp, uint8_t a, + uint8_t x, uint8_t y, uint8_t sr) +{ + m.ram[FAKE_STORE_Y] = y; + m.ram[FAKE_STORE_X] = x; + m.ram[FAKE_STORE_A] = a; + m.ram[FAKE_STORE_SR] = sr; + m.ram[FAKE_STORE_PCLO] = (uint8_t)((pc + 2) & 0xFF); + m.ram[FAKE_STORE_PCHI] = (uint8_t)((pc + 2) >> 8); + m.ram[FAKE_STORE_SP] = sp; + m.ram[FAKE_STORE_CPU_DDR] = 0x07; + m.ram[FAKE_STORE_CPU_PORT] = 0x07; +} + +static bool fake_recorded_brk_patch(const FakeFreezeMachine &m, uint16_t addr) +{ + int n = m.brk_patch_writes; + if (n > FakeFreezeMachine::MAX_RECORDED_BRK_PATCHES) { + n = FakeFreezeMachine::MAX_RECORDED_BRK_PATCHES; + } + for (int i = 0; i < n; i++) { + if (m.brk_patch_addrs[i] == addr) { + return true; + } + } + return false; +} + +static bool fake_nmi_trampoline_stores_cpu_port(const FakeFreezeMachine &m, + uint8_t cpu_port) +{ + for (int i = 0; i <= 20; i++) { + if (m.ram[FAKE_NMI_TRAMP + i] == 0xA9 && + m.ram[FAKE_NMI_TRAMP + i + 1] == (uint8_t)(cpu_port & 0x07) && + m.ram[FAKE_NMI_TRAMP + i + 2] == 0x85 && + m.ram[FAKE_NMI_TRAMP + i + 3] == 0x01) { + return true; + } + } + return false; +} + +struct Mini6510 { + uint8_t a; + uint8_t x; + uint8_t y; + uint8_t sp; + uint8_t sr; + uint16_t pc; + bool zero; + bool rti; +}; + +static uint16_t mini_abs(const uint8_t *mem, uint16_t pc) +{ + return (uint16_t)(mem[pc] | (mem[(uint16_t)(pc + 1)] << 8)); +} + +static void mini_set_zn(Mini6510 &cpu, uint8_t value) +{ + cpu.zero = (value == 0); +} + +static void mini_push(uint8_t *mem, Mini6510 &cpu, uint8_t value) +{ + mem[(uint16_t)(0x0100 | cpu.sp)] = value; + cpu.sp--; +} + +static uint8_t mini_pull(uint8_t *mem, Mini6510 &cpu) +{ + cpu.sp++; + return mem[(uint16_t)(0x0100 | cpu.sp)]; +} + +static bool mini_run(uint8_t *mem, Mini6510 &cpu, uint16_t stop_pc, int max_steps) +{ + for (int steps = 0; steps < max_steps; steps++) { + if (steps > 0 && cpu.pc == stop_pc) { + return true; + } + uint8_t op = mem[cpu.pc++]; + switch (op) { + case 0x29: + cpu.a &= mem[cpu.pc++]; + mini_set_zn(cpu, cpu.a); + break; + case 0x40: + cpu.sr = mini_pull(mem, cpu); + cpu.pc = mini_pull(mem, cpu); + cpu.pc = (uint16_t)(cpu.pc | (mini_pull(mem, cpu) << 8)); + cpu.rti = true; + return true; + case 0x48: + mini_push(mem, cpu, cpu.a); + break; + case 0x4C: + cpu.pc = mini_abs(mem, cpu.pc); + break; + case 0x68: + cpu.a = mini_pull(mem, cpu); + mini_set_zn(cpu, cpu.a); + break; + case 0x6C: { + uint16_t ptr = mini_abs(mem, cpu.pc); + cpu.pc = (uint16_t)(mem[ptr] | (mem[(uint16_t)(ptr + 1)] << 8)); + break; + } + case 0x85: + mem[mem[cpu.pc++]] = cpu.a; + break; + case 0x8A: + cpu.a = cpu.x; + mini_set_zn(cpu, cpu.a); + break; + case 0x8D: { + uint16_t addr = mini_abs(mem, cpu.pc); + cpu.pc = (uint16_t)(cpu.pc + 2); + mem[addr] = cpu.a; + break; + } + case 0x8E: { + uint16_t addr = mini_abs(mem, cpu.pc); + cpu.pc = (uint16_t)(cpu.pc + 2); + mem[addr] = cpu.x; + break; + } + case 0x98: + cpu.a = cpu.y; + mini_set_zn(cpu, cpu.a); + break; + case 0x99: { + uint16_t addr = (uint16_t)(mini_abs(mem, cpu.pc) + cpu.y); + cpu.pc = (uint16_t)(cpu.pc + 2); + mem[addr] = cpu.a; + break; + } + case 0x9D: { + uint16_t addr = (uint16_t)(mini_abs(mem, cpu.pc) + cpu.x); + cpu.pc = (uint16_t)(cpu.pc + 2); + mem[addr] = cpu.a; + break; + } + case 0xA0: + cpu.y = mem[cpu.pc++]; + mini_set_zn(cpu, cpu.y); + break; + case 0xA5: + cpu.a = mem[mem[cpu.pc++]]; + mini_set_zn(cpu, cpu.a); + break; + case 0xA9: + cpu.a = mem[cpu.pc++]; + mini_set_zn(cpu, cpu.a); + break; + case 0xAA: + cpu.x = cpu.a; + mini_set_zn(cpu, cpu.x); + break; + case 0xAC: { + uint16_t addr = mini_abs(mem, cpu.pc); + cpu.pc = (uint16_t)(cpu.pc + 2); + cpu.y = mem[addr]; + mini_set_zn(cpu, cpu.y); + break; + } + case 0xAD: { + uint16_t addr = mini_abs(mem, cpu.pc); + cpu.pc = (uint16_t)(cpu.pc + 2); + cpu.a = mem[addr]; + mini_set_zn(cpu, cpu.a); + break; + } + case 0xAE: { + uint16_t addr = mini_abs(mem, cpu.pc); + cpu.pc = (uint16_t)(cpu.pc + 2); + cpu.x = mem[addr]; + mini_set_zn(cpu, cpu.x); + break; + } + case 0xB9: { + uint16_t addr = (uint16_t)(mini_abs(mem, cpu.pc) + cpu.y); + cpu.pc = (uint16_t)(cpu.pc + 2); + cpu.a = mem[addr]; + mini_set_zn(cpu, cpu.a); + break; + } + case 0xBA: + cpu.x = cpu.sp; + mini_set_zn(cpu, cpu.x); + break; + case 0xBD: { + uint16_t addr = (uint16_t)(mini_abs(mem, cpu.pc) + cpu.x); + cpu.pc = (uint16_t)(cpu.pc + 2); + cpu.a = mem[addr]; + mini_set_zn(cpu, cpu.a); + break; + } + case 0xC0: + cpu.zero = (cpu.y == mem[cpu.pc++]); + break; + case 0xC8: + cpu.y++; + mini_set_zn(cpu, cpu.y); + break; + case 0xD0: { + int8_t rel = (int8_t)mem[cpu.pc++]; + if (!cpu.zero) { + cpu.pc = (uint16_t)(cpu.pc + rel); + } + break; + } + case 0xE8: + cpu.x++; + mini_set_zn(cpu, cpu.x); + break; + case 0xEE: { + uint16_t addr = mini_abs(mem, cpu.pc); + cpu.pc = (uint16_t)(cpu.pc + 2); + mem[addr]++; + mini_set_zn(cpu, mem[addr]); + break; + } + default: + return false; + } + } + return false; +} + +static bool fake_install_debug_stubs(FakeFreezeMachine &m, uint16_t addr) +{ + fake_seed_nop_run(m, addr); + fake_seed_captured_context(m, (uint16_t)(addr + 1), 0xF8, + 0x11, 0x22, 0x33, 0x24); + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(addr, bytes, false, &pred); + DebugContext ctx; + return m.trace_at(addr, pred, &ctx) == DebugSession::DBG_OK; +} + +} // namespace + +static int trim_end(const char *s) +{ + int n = (int)strlen(s); + while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\0')) n--; + return n; +} + +static int expect_help_token_not_accented(CaptureScreen &screen, const char *needle, + const char *message) +{ + char row[40]; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + const char *at = strstr(row, needle); + if (at) { + int x = 1 + (int)(at - row); + int n = (int)strlen(needle); + for (int i = 0; i < n; i++) { + if (screen.colors[y][x + i] == 1) { + return expect(false, message); + } + } + return 0; + } + } + return expect(false, message); +} + +static int find_row_with_address(CaptureScreen &screen, const char *address) +{ + char row[40]; + + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strncmp(row, address, 4) == 0) { + return y; + } + } + return -1; +} + +static int debug_visible_disasm_exists(CaptureScreen &screen, + const char *prefix, + const char *needle) +{ + char row[40]; + + for (int y = 4; y <= 22; y++) { + screen.get_slice(1, y, 38, row); + if ((!prefix || strstr(row, prefix) == row) && + (!needle || strstr(row, needle) != NULL)) { + return 1; + } + } + return 0; +} + +static int expect_debug_visible_disasm(CaptureScreen &screen, + const char *prefix, + const char *needle, + const char *message) +{ + return expect(debug_visible_disasm_exists(screen, prefix, needle), message); +} + +static int expect_breakpoint_label_only_accent(CaptureScreen &screen, int row_y, + const char *label, + uint8_t normal_color, + uint8_t accent_color, + const char *message) +{ + char row[40]; + screen.get_slice(1, row_y, 38, row); + const char *at = strstr(row, label); + if (expect(at != NULL, message)) return 1; + + int label_start = (int)(at - row); + int label_len = (int)strlen(label); + for (int i = 0; i < 38; i++) { + bool label_cell = (i >= label_start && i < label_start + label_len); + uint8_t expected = label_cell ? accent_color : normal_color; + if (screen.colors[row_y][1 + i] != expected) { + char detail[160]; + sprintf(detail, "%s color at row column %d", message, i); + return expect(false, detail); + } + } + return 0; +} + +static int test_predictor_classifies_control_flow() +{ + DebugPredictResult p; + + uint8_t jsr[3] = { 0x20, 0x34, 0x12 }; + debug_predict(0x1000, jsr, false, &p); + if (expect(p.kind == DBG_PREDICT_JSR, "JSR should classify as JSR")) return 1; + if (expect(p.length == 3, "JSR length should be 3")) return 1; + if (expect(p.fall_through == 0x1003, "JSR fall-through should be PC+3")) return 1; + if (expect(p.has_target && p.branch_target == 0x1234, "JSR target should decode")) return 1; + + uint8_t jmp[3] = { 0x4C, 0x34, 0x12 }; + debug_predict(0x1800, jmp, false, &p); + if (expect(p.kind == DBG_PREDICT_JMP_ABS, "JMP should classify as absolute jump")) return 1; + if (expect(p.has_target && p.branch_target == 0x1234, "JMP target should decode")) return 1; + + uint8_t branch[2] = { 0xD0, 0x02 }; // BNE +2 + debug_predict(0x2000, branch, false, &p); + if (expect(p.kind == DBG_PREDICT_BRANCH, "BNE should classify as BRANCH")) return 1; + if (expect(p.fall_through == 0x2002, "BNE fall-through should be PC+2")) return 1; + if (expect(p.has_target && p.branch_target == 0x2004, "BNE target should decode")) return 1; + + uint8_t brk_bytes[1] = { 0x00 }; + debug_predict(0x3000, brk_bytes, false, &p); + if (expect(p.kind == DBG_PREDICT_BRK, "BRK should classify as BRK")) return 1; + + uint8_t rts[1] = { 0x60 }; + debug_predict(0x4000, rts, false, &p); + if (expect(p.kind == DBG_PREDICT_RTS, "RTS should classify as RTS")) return 1; + + uint8_t linear[2] = { 0xA9, 0x42 }; // LDA #$42 + debug_predict(0x5000, linear, false, &p); + if (expect(p.kind == DBG_PREDICT_LINEAR, "LDA imm should classify as LINEAR")) return 1; + if (expect(p.length == 2 && p.fall_through == 0x5002, "LDA imm length/fall-through")) return 1; + + return 0; +} + +static int test_breakpoint_slots_allocate_clear_and_format() +{ + MonitorBreakpoints bps; + if (expect(bps.find_at(0xC000) < 0, "Empty table must not find $C000")) return 1; + int s0 = bps.allocate(0xC000, 0x07); + if (expect(s0 == 0, "First allocation must use slot 0")) return 1; + int s1 = bps.allocate(0xC100, 0x07); + if (expect(s1 == 1, "Second allocation must use slot 1")) return 1; + int dup = bps.allocate(0xC000, 0x07); + if (expect(dup == 0, "Allocating an existing address returns its slot")) return 1; + int krn = bps.allocate(0xE000, 0x07); + if (expect(krn == 2, "KERNAL breakpoint must allocate a distinct slot")) return 1; + int ram = bps.allocate(0xE000, 0x05); + if (expect(ram == 3, "RAM-under-KERNAL breakpoint at same address must coexist")) return 1; + if (expect(bps.find_at(0xE000, MONITOR_BACKING_KERNAL) == krn, + "KERNAL breakpoint lookup must use the target backing store")) return 1; + if (expect(bps.find_at(0xE000, MONITOR_BACKING_RAM) == ram, + "RAM breakpoint lookup must use the target backing store")) return 1; + bps.set_enabled(krn, false); + if (expect(!bps.get(krn)->enabled && bps.get(ram)->enabled, + "Disabling one same-address target must not disable the other")) return 1; + bps.set_enabled(krn, true); + + for (int i = 4; i < MONITOR_BREAKPOINT_SLOT_COUNT; i++) { + bps.allocate((uint16_t)(0xD000 + i), 0x07); + } + int full = bps.allocate(0xE000, 0x07); + if (expect(full == krn, "Full table should still return an existing same-target slot")) return 1; + full = bps.allocate(0xE100, 0x07); + if (expect(full < 0, "Allocation must fail when all slots are used")) return 1; + + char row[40]; + MonitorBreakpoints::format_popup_row(row, sizeof(row), 0, bps.get(0)); + if (expect(strcmp(row, "0 SET $C000 RAM") == 0, + "Slot 0 popup row should include the RAM target tag")) return 1; + bps.set_enabled(0, false); + MonitorBreakpoints::format_popup_row(row, sizeof(row), 0, bps.get(0)); + if (expect(strcmp(row, "0 OFF $C000 RAM") == 0, + "Disabled slot should keep the target tag")) return 1; + bps.set_label(0, "readc"); + if (expect(strcmp(bps.get(0)->label, "READ") == 0, + "Breakpoint labels must normalize to four uppercase chars")) return 1; + MonitorBreakpoints::format_popup_row(row, sizeof(row), 0, bps.get(0)); + if (expect(strcmp(row, "0 OFF READ $C000 RAM") == 0, + "Breakpoint popup row should include label and target tag")) return 1; + MonitorBreakpoints::format_popup_row(row, sizeof(row), krn, bps.get(krn)); + if (expect(strcmp(row, "2 SET $E000 KRN") == 0, + "KERNAL breakpoint popup row must show KRN target tag")) return 1; + MonitorBreakpoints::format_popup_row(row, sizeof(row), ram, bps.get(ram)); + if (expect(strcmp(row, "3 SET $E000 RAM") == 0, + "Same-address RAM breakpoint popup row must remain distinguishable")) return 1; + + bps.clear_slot(0); + MonitorBreakpoints::format_popup_row(row, sizeof(row), 0, bps.get(0)); + if (expect(strcmp(row, "0 EMPTY") == 0, "Cleared slot must format as EMPTY")) return 1; + return 0; +} + +static int test_footer_layout_blanks_unknown_fields() +{ + DebugContext ctx; + debug_context_reset(&ctx); + char header[40]; + char values[40]; + MonitorDebug::format_footer_header(header, sizeof(header)); + MonitorDebug::format_footer_values(ctx, values, sizeof(values)); + + if (expect(strncmp(header + 0, "PC", 2) == 0, "PC label position")) return 1; + if (expect(strncmp(header + 5, "AC", 2) == 0, "AC label position")) return 1; + if (expect(strncmp(header + 8, "XR", 2) == 0, "XR label position")) return 1; + if (expect(strncmp(header + 11, "YR", 2) == 0, "YR label position")) return 1; + if (expect(strncmp(header + 14, "SP", 2) == 0, "SP label position")) return 1; + if (expect(strncmp(header + 17, "NV-BDIZC", 8) == 0, "Flags label position")) return 1; + if (expect(strncmp(header + 26, "IRQ", 3) == 0, "IRQ label position")) return 1; + if (expect(strncmp(header + 31, "NMI", 3) == 0, "NMI label position")) return 1; + + // Unknown-value row must contain only spaces in the 35-column footer area + // (no zeroes, no question marks, no placeholder text). + for (int i = 0; i < 35; i++) { + if (expect(values[i] == ' ', "Unknown footer value must be a blank")) return 1; + } + if (expect(strchr(values, '?') == NULL, "Unknown footer must not show '?'")) return 1; + if (expect(strstr(values, "??") == NULL, "Unknown footer must not show question marks")) return 1; + + ctx.valid = true; + ctx.pc = 0xC003; + ctx.sp = 0xF7; + ctx.a = 0x01; + ctx.x = 0x00; + ctx.y = 0xFF; + ctx.sr = 0x24; + ctx.irq_valid = true; + ctx.irq_vec = 0xC123; + ctx.nmi_valid = true; + ctx.nmi_vec = 0xEA31; + MonitorDebug::format_footer_values(ctx, values, sizeof(values)); + if (expect(strncmp(values + 0, "C003", 4) == 0, "PC hex must align under label")) return 1; + if (expect(strncmp(values + 5, "01", 2) == 0, "AC hex must align under label")) return 1; + if (expect(strncmp(values + 8, "00", 2) == 0, "XR hex must align under label")) return 1; + if (expect(strncmp(values + 11, "FF", 2) == 0, "YR hex must align under label")) return 1; + if (expect(strncmp(values + 14, "F7", 2) == 0, "SP hex must align under label")) return 1; + if (expect(strncmp(values + 17, "00100100", 8) == 0, "Flags must render as NV-BDIZC binary string")) return 1; + if (expect(strncmp(values + 26, "C123", 4) == 0, "IRQ vector hex position")) return 1; + if (expect(strncmp(values + 31, "EA31", 4) == 0, "NMI vector hex position")) return 1; + + ctx.nmi_valid = false; + MonitorDebug::format_footer_values(ctx, values, sizeof(values)); + for (int i = 31; i < 35; i++) { + if (expect(values[i] == ' ', "NMI must blank when context says vector is unknown")) return 1; + } + return 0; +} + +static int test_debug_footer_sits_above_normal_status() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Switch ASM ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + + char values[40]; + char row[40]; + int label_y = -1; + int status_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strstr(row, "PC") != NULL && strstr(row, "NV-BDIZC") != NULL) { + label_y = y; + } + if (((strstr(row, "CPU") != NULL) || (strstr(row, "C") == row && strstr(row, "O") != NULL)) && + strstr(row, "VIC") != NULL) { + status_y = y; + } + } + if (expect(label_y >= 0, "Debug label row must be visible")) return 1; + if (expect(status_y >= 0, "Normal CPU/VIC status footer must remain visible in Debug mode")) return 1; + if (expect(status_y == label_y + 2, + "Debug labels/values must occupy the two rows immediately above normal status")) return 1; + screen.get_slice(1, label_y + 1, 38, values); + bool values_blank = true; + for (int i = 0; i < 35; i++) { + if (values[i] != ' ') { + values_blank = false; + break; + } + } + if (expect(values_blank, "Unknown Debug value row must be directly above normal status")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_d_enters_debug_without_executing() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Switch to ASM view should succeed")) return 1; + int before_creations = backend.session_creations; + int before_calls = backend.last_session ? backend.last_session->over_calls : 0; + if (expect(monitor.poll(0) == 0, "D should enter Debug mode and not exit")) return 1; + if (expect(backend.last_session != NULL || backend.session_creations >= before_creations, + "Entering Debug may create a session for snapshot, but must not call Over")) return 1; + if (expect(backend.last_session == NULL || backend.last_session->over_calls == before_calls, + "D entry must not execute (Over count unchanged)")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM") != NULL, + "Header must still read MONITOR ASM, not MONITOR DBG")) return 1; + if (expect(strstr(header, "Dbg") != NULL, + "Dbg flag must appear in the header status area")) return 1; + if (expect(monitor.poll(0) == 0, "ESC inside Debug must not exit the monitor")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") == NULL, + "Dbg flag must clear after leaving Debug")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + if (expect(backend.last_session == NULL || backend.session_creations > 0, + "Sanity check: session lifecycle ran")) return 1; + return 0; +} + +static int test_d_inside_debug_performs_over() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + // The session's canned PC is $C003; populate a benign LDA #$00 there so + // the predictor classifies it as LINEAR rather than BRK. + backend.write(0xC003, 0xA9); + backend.write(0xC004, 0x00); + backend.write(0xC005, 0xEA); + + const int keys[] = { 'A', 'D', 'D', KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 5; i++) { + int r = monitor.poll(0); + if (i < 4) { + if (expect(r == 0, "Non-exit polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP should exit")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->over_calls >= 1, "D inside Debug should call Over")) return 1; + if (expect(backend.last_session->over_breakpoint_calls >= 1, + "D inside Debug must pass active breakpoints to Over")) return 1; + monitor.deinit(); + return 0; +} + +static int test_d_inside_debug_without_context_overs_from_cursor() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x1000, 0xA9); + backend.write(0x1001, 0x77); + backend.write(0x1002, 0xEA); + + const int keys[] = { 'J', 'A', 'D', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("1000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + int r = monitor.poll(0); + if (i < 5) { + if (expect(r == 0, "No-context Over setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->over_calls == 0, + "No-context D must not call context-based Over")) return 1; + if (expect(backend.last_session->over_at_calls == 1, + "No-context D in Debug must execute Over from the cursor")) return 1; + if (expect(backend.last_session->over_at_breakpoint_calls == 1, + "No-context D must pass active breakpoints to cursor Over")) return 1; + if (expect(backend.last_session->last_start_pc == 0x1000, + "No-context Over must start at the Assembly cursor address")) return 1; + if (expect(ui.popup_count == 0 || strstr(ui.last_popup, "NO CONTEXT") == NULL, + "No-context Over must not show NO CONTEXT")) return 1; + monitor.deinit(); + return 0; +} + +static int test_d_inside_debug_without_context_goto_keeps_cursor_authoritative() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x1000, 0xA9); + backend.write(0x1001, 0x11); + backend.write(0x1002, 0xEA); + backend.write(0x2000, 0xA9); + backend.write(0x2001, 0x22); + backend.write(0x2002, 0xEA); + + const int keys[] = { 'J', 'A', 'D', 'J', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 7); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("1000", 1); + ui.set_prompt("2000", 3); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 7; i++) { + int r = monitor.poll(0); + if (i < 6) { + if (expect(r == 0, "No-context Debug goto polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->over_calls == 0, + "No-context Debug goto must not fall back to captured context")) return 1; + if (expect(backend.last_session->over_at_calls == 1, + "No-context Debug goto must execute Over from cursor")) return 1; + if (expect(backend.last_session->last_start_pc == 0x2000, + "No-context Debug goto must keep the new cursor address authoritative")) return 1; + monitor.deinit(); + return 0; +} + +static int test_d_refuses_undocumented_opcode_with_specific_warning() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x1000, 0x1A); + backend.write(0x1001, 0xEA); + + const int keys[] = { 'J', 'A', 'U', 'D', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 7); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("1000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 7; i++) { + int r = monitor.poll(0); + if (i < 6) { + if (expect(r == 0, "Undocumented opcode refusal polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(ui.popup_count > 0 && strcmp(ui.last_popup, "UNSUPPORTED OPCODE") == 0, + "Undocumented opcode refusal must use UNSUPPORTED OPCODE")) return 1; + monitor.deinit(); + return 0; +} + +static int test_debug_predictor_uses_session_bytes_over_backend_reads() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.write(0xA000, 0x00); + backend.write(0xA001, 0x00); + backend.write(0xA002, 0x00); + + const int keys[] = { 'J', 'A', 'D', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("A000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Goto A000 should stay in monitor")) return 1; + if (expect(monitor.poll(0) == 0, "Switch to ASM should stay in monitor")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug should stay in monitor")) return 1; + + if (expect(backend.last_session != NULL, "Debug session must exist before stepping")) return 1; + backend.last_session->predict_bytes_valid = true; + backend.last_session->predict_bytes[0] = 0xEA; + backend.last_session->predict_bytes[1] = 0xEA; + backend.last_session->predict_bytes[2] = 0xEA; + + if (expect(monitor.poll(0) == 0, + "Debug over at A000 should use session bytes instead of unsafe backend BRK bytes")) return 1; + if (expect((backend.last_session->over_calls + backend.last_session->over_at_calls) == 1, + "Debug over should dispatch through the session when session bytes decode safely")) return 1; + if (expect(ui.popup_count == 0 || strstr(ui.last_popup, "UNSAFE TARGET") == NULL, + "Valid ROM step bytes must not surface UNSAFE TARGET")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_debug_pc_disassembly_uses_session_live_bytes_over_view() +{ + TestUserInterface ui; + CaptureScreen screen; + DebugBackendController ctrl; + FakeDebugBackend backend(&ctrl); + monitor_reset_saved_state(); + + ctrl.session.next_ctx.valid = true; + ctrl.session.next_ctx.pc = 0xE000; + ctrl.session.next_ctx.sp = 0xF7; + ctrl.session.next_ctx.sr = 0x24; + ctrl.session.predict_bytes_valid = true; + ctrl.session.predict_bytes[0] = 0xA9; + ctrl.session.predict_bytes[1] = 0x42; + ctrl.session.predict_bytes[2] = 0xEA; + backend.write(0x0001, 0x05); + backend.set_monitor_cpu_port(0x07); + + // The monitor view would decode BRK from the backing memory. The active + // Debug PC row must instead use the session's execution-facing bytes, + // which are supplied by the live CPU-bank route. + backend.write(0xE000, 0x00); + backend.write(0xE001, 0x00); + backend.write(0xE002, 0x00); + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Switch to ASM should stay in monitor")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug should stay in monitor")) return 1; + + char row[40]; + int row_y = find_row_with_address(screen, "E000"); + if (expect(row_y >= 0, "Debug PC row must be visible")) return 1; + screen.get_slice(1, row_y, 38, row); + if (expect(strstr(row, ">LDA #$42<") != NULL, + "Debug PC row must decode live session bytes instead of monitor-view BRK")) return 1; + if (expect(strstr(row, ">BRK<") == NULL, + "Debug PC row must not display monitor-view BRK bytes")) return 1; + if (expect(strstr(row, "[RAM]") != NULL, + "Debug PC row source marker must describe the live CPU backing store")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_t_traces_and_o_outs_inside_debug() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.write(0xC003, 0xA9); + backend.write(0xC004, 0x00); + backend.write(0xC005, 0xEA); + + const int keys[] = { 'A', 'D', 'T', 'U', KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + int r = monitor.poll(0); + if (i < 5) { + if (expect(r == 0, "Non-exit polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP should exit")) return 1; + } + } + if (expect(backend.last_session->trace_calls == 1, "T should call trace exactly once")) return 1; + if (expect(backend.last_session->out_calls == 1, "U should call step-out exactly once")) return 1; + if (expect(backend.last_session->over_calls == 0, "Neither T nor U should call Over")) return 1; + monitor.deinit(); + return 0; +} + +static int test_debug_o_does_not_step_out() +{ + // Debug-mode Step Out moved from 'O' to 'U'. 'O'/'o' must no longer invoke + // step-out; they fall through to the normal monitor dispatcher so the + // monitor view CPU/VIC bank can still be cycled while Debug is active. + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'O', 'o', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(backend.last_session != NULL, "Debug session must exist")) return 1; + if (expect(monitor.poll(0) == 0, "Debug 'O' must stay in monitor")) return 1; + if (expect(monitor.poll(0) == 0, "Debug 'o' must stay in monitor")) return 1; + if (expect(backend.last_session->out_calls == 0, + "Debug-mode O/o must not invoke Step Out")) return 1; + if (expect(backend.last_session->trace_calls == 0 && + backend.last_session->over_calls == 0, + "Debug-mode O/o must not invoke any stepping command")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_o_without_traced_jsr_reports_not_in_subroutine() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_OK; + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x2003; + backend.canned_snapshot.sp = 0xFA; + backend.canned_snapshot.sr = 0x24; + + const int keys[] = { 'A', 'D', 'U', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(backend.last_session != NULL, "Debug session must exist")) return 1; + backend.last_session->out_result = DebugSession::DBG_NOT_IN_SUBROUTINE; + if (expect(monitor.poll(0) == 0, "Step Out refusal stays in monitor")) return 1; + if (expect(strstr(ui.last_popup, "NOT IN SUBROUTINE") != NULL, + "Step Out without a traced JSR must say NOT IN SUBROUTINE")) return 1; + if (expect(strstr(ui.last_popup, "UNSAFE TARGET") == NULL, + "Step Out without a traced JSR must not say UNSAFE TARGET")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_o_without_context_reports_not_in_subroutine() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + + const int keys[] = { 'A', 'D', 'U', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Step Out without context stays in monitor")) return 1; + if (expect(strstr(ui.last_popup, "NOT IN SUBROUTINE") != NULL, + "Step Out without context must say NOT IN SUBROUTINE")) return 1; + if (expect(strstr(ui.last_popup, "NO CONTEXT") == NULL, + "Step Out without context must not say NO CONTEXT")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_t_inside_debug_without_context_traces_from_cursor() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x2000, 0x20); + backend.write(0x2001, 0x00); + backend.write(0x2002, 0x30); + + const int keys[] = { 'J', 'A', 'D', 'T', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("2000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + int r = monitor.poll(0); + if (i < 5) { + if (expect(r == 0, "No-context Trace setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->trace_calls == 0, + "No-context T must not call context-based Trace")) return 1; + if (expect(backend.last_session->trace_at_calls == 1, + "No-context T in Debug must execute Trace from the cursor")) return 1; + if (expect(backend.last_session->last_start_pc == 0x2000, + "No-context Trace must start at the Assembly cursor address")) return 1; + monitor.deinit(); + return 0; +} + +static int test_t_after_goto_ignores_successful_stale_snapshot() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + DebugContext stale; + debug_context_reset(&stale); + stale.valid = true; + stale.pc = 0x0000; + stale.sp = 0xE4; + stale.sr = 0x36; + backend.canned_snapshot = stale; + backend.canned_snapshot_set = true; + backend.snapshot_result = DebugSession::DBG_OK; + backend.write(0xE000, 0x85); + backend.write(0xE001, 0x56); + backend.write(0xE002, 0xEA); + backend.write(0x0000, 0xEA); + backend.write(0x0001, 0xEA); + + const int keys[] = { 'J', 'A', 'D', 'T', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + int r = monitor.poll(0); + if (i < 5) { + if (expect(r == 0, "Stale-snapshot Trace setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->trace_calls == 0, + "Cursor-authoritative Debug entry must ignore a successful stale snapshot")) return 1; + if (expect(backend.last_session->trace_at_calls == 1, + "Cursor-authoritative Debug entry must Trace from the cursor")) return 1; + if (expect(backend.last_session->last_start_pc == 0xE000, + "Trace after J E000 must start at the cursor, not stale PC $0000")) return 1; + monitor.deinit(); + return 0; +} + +static int test_g_after_goto_ignores_successful_stale_snapshot() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + DebugContext stale; + debug_context_reset(&stale); + stale.valid = true; + stale.pc = 0x0000; + stale.sp = 0xE4; + stale.sr = 0x36; + backend.canned_snapshot = stale; + backend.canned_snapshot_set = true; + backend.snapshot_result = DebugSession::DBG_OK; + backend.write(0xE000, 0x85); + backend.write(0xE001, 0x56); + backend.write(0xE002, 0xEA); + + const int keys[] = { 'J', 'A', 'D', 'G', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + int r = monitor.poll(0); + if (i < 5) { + if (expect(r == 0, "Stale-snapshot Go setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->go_calls == 1, + "G must invoke the debug session Go path")) return 1; + if (expect(backend.last_session->last_start_pc == 0xE000, + "G after J E000 must start at the cursor, not stale PC $0000")) return 1; + monitor.deinit(); + return 0; +} + +static int test_g_after_cursor_stop_uses_captured_context() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + DebugContext stopped; + debug_context_reset(&stopped); + stopped.valid = true; + stopped.pc = 0xE003; + stopped.sp = 0xE4; + stopped.sr = 0x36; + backend.canned_snapshot = stopped; + backend.canned_snapshot_set = true; + backend.snapshot_result = DebugSession::DBG_OK; + backend.go_produces_snapshot = true; + backend.write(0xE000, 0x85); + backend.write(0xE001, 0x56); + backend.write(0xE002, 0xEA); + backend.write(0xE003, 0xEA); + + const int keys[] = { 'J', 'A', 'D', 'G', 'G', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 7); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 7; i++) { + int r = monitor.poll(0); + if (i < 6) { + if (expect(r == 0, "Two-Go cursor/context setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->go_calls == 2, + "Two G commands must invoke the debug session twice")) return 1; + if (expect(backend.last_session->last_go_from_valid, + "Second G after a captured stop must use the captured context")) return 1; + if (expect(backend.last_session->last_go_from_pc == 0xE003, + "Second G must resume from the captured PC, not the cursor override")) return 1; + monitor.deinit(); + return 0; +} + +static int test_g_after_goto_with_active_context_uses_cursor() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.write(0x1000, 0xEA); + backend.write(0xE000, 0x85); + backend.write(0xE001, 0x56); + backend.write(0xE002, 0xEA); + + const int keys[] = { 'J', 'A', 'D', 'D', 'J', 'G', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 8); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("1000", 1); + ui.push_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 8; i++) { + int r = monitor.poll(0); + if (i < 7) { + if (expect(r == 0, "Active-context Goto/Go setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->go_calls == 1, + "G after active-context J must invoke Go once")) return 1; + if (expect(!backend.last_session->last_go_from_valid, + "G after active-context J must ignore the previous captured context")) return 1; + if (expect(backend.last_session->last_start_pc == 0xE000, + "G after active-context J must start from the cursor address")) return 1; + monitor.deinit(); + return 0; +} + +static int test_g_invalidates_context() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'G', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Switch ASM ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "G performs Go and stays in monitor")) return 1; + if (expect(backend.last_session != NULL && backend.last_session->go_calls == 1, + "G should call go() exactly once")) return 1; + char values[40]; + char row[40]; + int label_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strstr(row, "PC") != NULL && strstr(row, "NV-BDIZC") != NULL) { + label_y = y; + break; + } + } + if (expect(label_y >= 0, "G invalidation test must find Debug footer labels")) return 1; + screen.get_slice(1, label_y + 1, 38, values); + // After G the captured context is invalidated: values row should be blanks. + bool all_blank = true; + for (int i = 0; i < 35; i++) if (values[i] != ' ') { all_blank = false; break; } + if (expect(all_blank, "G must invalidate the captured context (footer blank)")) return 1; + monitor.deinit(); + return 0; +} + +static int test_return_remains_non_executing_navigation() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + // Set up a JSR at the cursor so RETURN can follow it without executing. + backend.write(0x1000, 0x20); + backend.write(0x1001, 0x00); + backend.write(0x1002, 0x20); + + const int keys[] = { 'J', 'A', 'D', KEY_RETURN, KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("1000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + int r = monitor.poll(0); + if (i < 5) { + if (expect(r == 0, "Pre-exit polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP should exit")) return 1; + } + } + if (expect(backend.last_session == NULL || + (backend.last_session->over_calls == 0 && + backend.last_session->trace_calls == 0 && + backend.last_session->out_calls == 0 && + backend.last_session->go_calls == 0), + "RETURN must not invoke any execution path")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_d_leaves_debug_only() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', KEY_CTRL_D, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 4; i++) { + int r = monitor.poll(0); + if (i < 3) { + if (expect(r == 0, "C=+D should leave Debug but stay in monitor")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") == NULL, "C=+D must clear the Dbg flag")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_d_from_edit_clears_edit_for_redebug() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x2000, 0xEA); + backend.write(0x2001, 0xEA); + backend.write(0x2002, 0xEA); + + const int keys[] = { 'A', 'D', 'E', KEY_CTRL_D, 'J', 'D', 'D', + KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 9); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.color_fg = 12; + ui.set_prompt("2000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Edit ok")) return 1; + if (expect(monitor.poll(0) == 0, "C=+D should leave Debug and Edit")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") == NULL && strstr(header, "Edit") == NULL, + "C=+D in Debug+Edit must clear both Dbg and Edit")) return 1; + if (expect(monitor.poll(0) == 0, "J after C=+D must be a monitor command")) return 1; + if (expect(ui.prompt_index == 1, "J after C=+D must consume the jump prompt")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $2000") != NULL, + "Jump after C=+D must move the Assembly cursor")) return 1; + if (expect(monitor.poll(0) == 0, "Re-enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Step after re-enter ok")) return 1; + if (expect(backend.last_session != NULL, "Re-entered Debug must have a session")) return 1; + if (expect(backend.last_session->over_at_calls == 1, + "Re-entered no-context Debug must step from the cursor")) return 1; + if (expect(backend.last_session->last_start_pc == 0x2000, + "Re-entered no-context Debug must use the post-C=+D jump target")) return 1; + if (expect(monitor.poll(0) == 0, "First RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_escape_leaves_edit_before_debug() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'E', KEY_ESCAPE, KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Edit ok")) return 1; + if (expect(monitor.poll(0) == 0, "First ESC should leave Edit only")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") != NULL && strstr(header, "Edit") == NULL, + "ESC in Debug+Edit must leave Dbg active while clearing Edit")) return 1; + if (expect(monitor.poll(0) == 0, "Second ESC should leave Debug")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") == NULL && strstr(header, "Edit") == NULL, + "Second ESC must clear the remaining Dbg flag")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_runstop_leaves_edit_before_debug() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'E', KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Edit ok")) return 1; + if (expect(monitor.poll(0) == 0, "First RUN/STOP should leave Edit only")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") != NULL && strstr(header, "Edit") == NULL, + "RUN/STOP in Debug+Edit must leave Dbg active while clearing Edit")) return 1; + if (expect(monitor.poll(0) == 0, "Second RUN/STOP should leave Debug")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") == NULL && strstr(header, "Edit") == NULL, + "Second RUN/STOP must clear the remaining Dbg flag")) return 1; + if (expect(monitor.poll(0) == 1, "Third RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_step_from_memory_view_recenters_asm_on_debug_pc() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xC100; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.a = 0x01; + backend.canned_snapshot.x = 0x00; + backend.canned_snapshot.y = 0xFF; + backend.canned_snapshot.sr = 0x24; + backend.canned_snapshot.irq_valid = true; + backend.canned_snapshot.irq_vec = 0xC123; + backend.canned_snapshot.nmi_valid = true; + backend.canned_snapshot.nmi_vec = 0xEA31; + + const int keys[] = { 'A', 'D', 'M', KEY_RIGHT, 'D', 'A', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 8); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Switch to memory view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Move away from debug address ok")) return 1; + if (expect(monitor.poll(0) == 0, "Debug step from memory view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Return to ASM view ok")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C100") != NULL, + "Returning to ASM in Debug must snap back to the current debug PC")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_x_resets_and_keeps_debug_open() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x0801, 0xEA); + + const int keys[] = { 'A', 'D', KEY_CTRL_X, 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "CTRL+X reset ok")) return 1; + if (expect(backend.reset_calls == 1, + "CTRL+X must issue one backend reset while the monitor stays open")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") != NULL, + "CTRL+X in Debug must keep Debug mode active")) return 1; + char values[40]; + char row[40]; + int label_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strstr(row, "PC") != NULL && strstr(row, "NV-BDIZC") != NULL) { + label_y = y; + break; + } + } + if (expect(label_y >= 0, "Debug footer label row must remain visible after reset")) return 1; + screen.get_slice(1, label_y + 1, 38, values); + bool values_blank = true; + for (int i = 0; i < 35; i++) { + if (values[i] != ' ') { + values_blank = false; + break; + } + } + if (expect(values_blank, + "CTRL+X reset in Debug must clear the stale register footer")) return 1; + if (expect(monitor.poll(0) == 0, "Stepping after reset should still work")) return 1; + if (expect(backend.session_creations == 2, + "Stepping after reset must recreate the debug session")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_x_local_reset_exits_monitor() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x0801, 0xEA); + + const int keys[] = { 'A', 'D', KEY_CTRL_X }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_reset_exits_monitor(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == MENU_EXIT, + "Local UI CTRL+X reset must exit the monitor so host ownership is released")) return 1; + if (expect(backend.reset_calls == 1, + "Local UI CTRL+X reset must issue one backend reset")) return 1; + if (expect(monitor.consume_reopen_after_reset(), + "Local UI CTRL+X reset while monitor is open must request monitor re-entry")) return 1; + if (expect(!monitor.consume_release_host_after_exit(), + "Local UI CTRL+X reset must not take the host-release exit path")) return 1; + monitor.deinit(); + + const int reentry_keys[] = { KEY_BREAK, KEY_BREAK }; + FakeKeyboard reentry_keyboard(reentry_keys, 2); + ui.keyboard = &reentry_keyboard; + BackendMachineMonitor reentered(&ui, &backend); + reentered.set_reset_exits_monitor(true); + reentered.init(&screen, &reentry_keyboard); + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $0000") != NULL, + "Reset re-entry must restore the monitor view and address")) return 1; + if (expect(strstr(header, "Dbg") != NULL, + "Reset re-entry must restore Debug mode when reset happened in Debug")) return 1; + if (expect(reentered.poll(0) == 0, "RUN/STOP leaves restored Debug")) return 1; + if (expect(reentered.poll(0) == 1, "Second RUN/STOP exits restored monitor")) return 1; + reentered.deinit(); + return 0; +} + +static int test_external_reset_during_debug_wait_exits_without_reopen() +{ + TestUserInterface ui; + CaptureScreen screen; + BrkSessionBackend backend(false); + monitor_reset_saved_state(); + + const int keys[] = { 'J', 'A', 'D', 'T' }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("0801", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_reset_exits_monitor(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Jump setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + if (expect(backend.last_session != NULL, + "Debug entry must create the BRK debug session before trace starts")) return 1; + backend.last_session->monitor_reset_cancel_target = &monitor; + backend.last_session->monitor_reset_cancel_on_delay = true; + if (expect(monitor.poll(0) == MENU_EXIT, + "External reset during an active debug wait must unwind out of the monitor")) return 1; + if (expect(backend.last_session != NULL, + "Active trace must create the BRK debug session")) return 1; + if (expect(backend.last_session->freeze_restore_pokes > 0, + "External reset during debug wait must clean up the active session")) return 1; + if (expect(backend.last_session->reset_calls == 0, + "External reset during debug wait must not issue a second machine reset")) return 1; + if (expect(!monitor.consume_reopen_after_reset(), + "External reset during debug wait must not request monitor re-entry")) return 1; + monitor.deinit(); + return 0; +} + +static void seed_kernal_out_reset_decode_bytes(SourceLabelDebugBackend &backend) +{ + backend.write(0xDFFE, 0x21); + backend.write(0xDFFF, 0xD0); + backend.write(0xE000, 0xEE); + backend.write(0xE001, 0x21); + backend.write(0xE002, 0xD0); + backend.write(0xE003, 0xE8); + backend.write(0xE004, 0x88); + backend.write(0xE005, 0x98); + backend.write(0xE006, 0x4C); + backend.write(0xE007, 0x00); + backend.write(0xE008, 0xE0); + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xE000; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.sr = 0x24; + backend.canned_snapshot.live_cpu_port_valid = true; + backend.canned_snapshot.live_cpu_port = 0x05; + backend.canned_snapshot.cpu_port_registers_valid = true; + backend.canned_snapshot.cpu_ddr = 0x37; + backend.canned_snapshot.cpu_port_latch = 0x35; + backend.canned_snapshot_set = true; +} + +static int test_ctrl_x_reset_reentry_anchors_asm_at_source_boundary() +{ + TestUserInterface ui; + CaptureScreen screen; + SourceLabelDebugBackend backend; + monitor_reset_saved_state(); + + seed_kernal_out_reset_decode_bytes(backend); + + const int keys[] = { 'A', 'D', KEY_CTRL_X }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_reset_exits_monitor(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug at RAM-under-KERNAL PC ok")) return 1; + if (expect(monitor.poll(0) == MENU_EXIT, + "CTRL+X reset from direct UI must exit for re-entry")) return 1; + if (expect(monitor.consume_reopen_after_reset(), + "CTRL+X reset must request monitor re-entry")) return 1; + monitor.deinit(); + + const int reentry_keys[] = { KEY_BREAK, KEY_BREAK }; + FakeKeyboard reentry_keyboard(reentry_keys, 2); + ui.keyboard = &reentry_keyboard; + BackendMachineMonitor reentered(&ui, &backend); + reentered.set_reset_exits_monitor(true); + reentered.init(&screen, &reentry_keyboard); + + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $E000") != NULL, + "Reset re-entry must anchor ASM at the captured $E000 PC")) return 1; + int row_y = find_row_with_address(screen, "E000"); + if (expect(row_y == 4, + "Reset re-entry must not prepend $DFFE/$DFFF before $E000")) return 1; + char row[40]; + screen.get_slice(1, row_y, 38, row); + if (expect(strstr(row, "EE 21 D0") != NULL && + strstr(row, "INC $D021") != NULL, + "Reset re-entry must decode the $E000 INC $D021 instruction")) return 1; + if (expect(find_row_with_address(screen, "DFFE") < 0 && + find_row_with_address(screen, "DFFF") < 0, + "ASM context rows must not cross the IO/RAM source boundary")) return 1; + + if (expect(reentered.poll(0) == 0, "RUN/STOP leaves restored Debug")) return 1; + if (expect(reentered.poll(0) == 1, "Second RUN/STOP exits restored monitor")) return 1; + reentered.deinit(); + return 0; +} + +static int test_ctrl_x_reenters_monitor_without_debug_when_not_debugging() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', KEY_CTRL_X }; + FakeKeyboard keyboard(keys, 2); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_reset_exits_monitor(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == MENU_EXIT, + "Local UI CTRL+X reset must exit the current monitor instance")) return 1; + if (expect(monitor.consume_reopen_after_reset(), + "Local UI CTRL+X reset outside Debug must request monitor re-entry")) return 1; + monitor.deinit(); + + const int reentry_keys[] = { KEY_BREAK }; + FakeKeyboard reentry_keyboard(reentry_keys, 1); + ui.keyboard = &reentry_keyboard; + BackendMachineMonitor reentered(&ui, &backend); + reentered.set_reset_exits_monitor(true); + reentered.init(&screen, &reentry_keyboard); + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $0000") != NULL, + "Reset re-entry outside Debug must restore the monitor view and address")) return 1; + if (expect(strstr(header, "Dbg") == NULL, + "Reset re-entry outside Debug must not enter Debug mode")) return 1; + if (expect(reentered.poll(0) == 1, "RUN/STOP exits restored non-Debug monitor")) return 1; + reentered.deinit(); + return 0; +} + +static int test_breakpoints_survive_ctrl_x_reset_reentry() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xC000, 0xEA); + + // J $A000 -> A (asm) -> D (debug on) -> R (BP at A000) -> C=+X (reset). + const int keys[] = { 'J', 'A', 'D', 'R', KEY_CTRL_X }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("A000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_reset_exits_monitor(true); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 4; i++) { + if (expect(monitor.poll(0) == 0, "Breakpoint setup before reset")) return 1; + } + if (expect(monitor.poll(0) == MENU_EXIT, + "C=+X must exit the current monitor instance so it can re-enter")) return 1; + if (expect(monitor.consume_reopen_after_reset(), + "C=+X must request a monitor re-entry")) return 1; + monitor.deinit(); + + // Re-enter the monitor. The reset-reentry path constructs a fresh + // MachineMonitor; breakpoints must come back from process-lifetime storage. + const int reentry_keys[] = { 'A', KEY_BREAK, KEY_BREAK }; + FakeKeyboard reentry_keyboard(reentry_keys, 3); + ui.keyboard = &reentry_keyboard; + BackendMachineMonitor reentered(&ui, &backend); + reentered.set_reset_exits_monitor(true); + reentered.init(&screen, &reentry_keyboard); + if (expect(reentered.poll(0) == 0, "Switch back to Assembly view after reset")) return 1; + + char row[40]; + int target_row = find_row_with_address(screen, "A000"); + if (expect(target_row >= 0, "Re-entered monitor must show $A000 row")) return 1; + screen.get_slice(1, target_row, 38, row); + if (expect(strstr(row, "[BRK0]") != NULL, + "Breakpoint stored before C=+X must reappear after reset reentry")) return 1; + + if (expect(reentered.poll(0) == 0, "RUN/STOP leaves restored Debug")) return 1; + if (expect(reentered.poll(0) == 1, "Second RUN/STOP exits")) return 1; + reentered.deinit(); + return 0; +} + +static int test_breakpoints_survive_normal_close_reopen() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xA000, 0xEA); + + // J $A000 -> A -> D -> R -> BREAK (leave Debug) -> BREAK (exit monitor). + const int keys[] = { 'J', 'A', 'D', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("A000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 5; i++) { + if (expect(monitor.poll(0) == 0, "Breakpoint setup before close")) return 1; + } + if (expect(monitor.poll(0) == 1, "Final RUN/STOP closes the monitor")) return 1; + monitor.deinit(); + + // Reopen later with no reset in between. The persisted table must come + // back so the user does not have to re-create their breakpoints. + const int reopen_keys[] = { KEY_BREAK }; + FakeKeyboard reopen_keyboard(reopen_keys, 1); + ui.keyboard = &reopen_keyboard; + BackendMachineMonitor reopened(&ui, &backend); + reopened.init(&screen, &reopen_keyboard); + + char row[40]; + int target_row = find_row_with_address(screen, "A000"); + if (expect(target_row >= 0, "Reopened monitor must show $A000 row")) return 1; + screen.get_slice(1, target_row, 38, row); + if (expect(strstr(row, "[BRK0]") != NULL, + "Breakpoint must survive a normal close+reopen")) return 1; + if (expect(reopened.poll(0) == 1, "RUN/STOP exits the reopened monitor")) return 1; + reopened.deinit(); + return 0; +} + +static int test_monitor_reset_saved_state_clears_breakpoints() +{ + // Seed the persisted table with a breakpoint by opening + closing once. + { + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xA000, 0xEA); + + const int keys[] = { 'J', 'A', 'D', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("A000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 5; i++) { + if (expect(monitor.poll(0) == 0, "Seed monitor setup")) return 1; + } + if (expect(monitor.poll(0) == 1, "Seed monitor exit")) return 1; + monitor.deinit(); + } + + // monitor_reset_saved_state() simulates a fresh process boot in tests; the + // persisted breakpoint table must be empty after it runs. + monitor_reset_saved_state(); + + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xA000, 0xEA); + + const int keys[] = { 'J', 'A', KEY_BREAK }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("A000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Jump to A000")) return 1; + if (expect(monitor.poll(0) == 0, "Switch to Assembly")) return 1; + + char row[40]; + int target_row = find_row_with_address(screen, "A000"); + if (expect(target_row >= 0, "Fresh-process monitor must show $A000 row")) return 1; + screen.get_slice(1, target_row, 38, row); + if (expect(strstr(row, "[BRK") == NULL, + "monitor_reset_saved_state must clear the persisted breakpoint table")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exits the fresh monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_breakpoint_toggle_via_r() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + // RUN/STOP first leaves Debug, then a second RUN/STOP exits the monitor. + const int keys[] = { 'A', 'D', 'R', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + int popups_before = ui.popup_count; + if (expect(monitor.poll(0) == 0, "R toggles breakpoint and stays in monitor")) return 1; + if (expect(ui.popup_count == popups_before, "Toggle-on must not show a success popup")) return 1; + if (expect(monitor.poll(0) == 0, "Second R clears the same address")) return 1; + if (expect(ui.popup_count == popups_before, "Toggle-off must not show a success popup")) return 1; + if (expect(monitor.poll(0) == 0, "First RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_breakpoint_mismatch_message_uses_view_target_and_live_cpu() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x0001, 0x07); // live CPU sees KERNAL at $E000 + backend.write(0xE000, 0xEA); + + int keys[14]; + int n = 0; + keys[n++] = 'J'; + keys[n++] = 'A'; + for (int i = 0; i < 6; i++) { + keys[n++] = 'o'; // monitor view CPU7 -> CPU5, RAM under KERNAL + } + keys[n++] = 'D'; + keys[n++] = 'R'; + keys[n++] = KEY_BREAK; + keys[n++] = KEY_BREAK; + FakeKeyboard keyboard(keys, n); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < n - 2; i++) { + if (expect(monitor.poll(0) == 0, + "Mismatch breakpoint setup should stay in monitor")) return 1; + } + if (expect(strcmp(ui.last_popup, "BRK RAM, CPU KRN; not mapped now") == 0, + "Mismatch popup must describe breakpoint target and live CPU mapping")) return 1; + if (expect((int)strlen(ui.last_popup) <= 38, + "Mismatch popup must fit one 38-column line")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + + TestUserInterface matched_ui; + CaptureScreen matched_screen; + TrackingDebugBackend matched_backend; + monitor_reset_saved_state(); + matched_backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + matched_backend.write(0x0001, 0x07); + matched_backend.write(0xE000, 0xEA); + const int matched_keys[] = { 'J', 'A', 'D', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard matched_keyboard(matched_keys, 6); + matched_ui.screen = &matched_screen; + matched_ui.keyboard = &matched_keyboard; + matched_ui.set_prompt("E000", 1); + BackendMachineMonitor matched_monitor(&matched_ui, &matched_backend); + matched_monitor.init(&matched_screen, &matched_keyboard); + for (int i = 0; i < 4; i++) { + if (expect(matched_monitor.poll(0) == 0, + "Matched breakpoint setup should stay in monitor")) return 1; + } + if (expect(matched_ui.popup_count == 0, + "No mismatch popup should appear when target is currently mapped")) return 1; + if (expect(matched_monitor.poll(0) == 0, "RUN/STOP leaves matched Debug")) return 1; + if (expect(matched_monitor.poll(0) == 1, "Second RUN/STOP exits matched monitor")) return 1; + matched_monitor.deinit(); + + const MonitorBackingStore tags[] = { + MONITOR_BACKING_RAM, + MONITOR_BACKING_BASIC, + MONITOR_BACKING_KERNAL, + MONITOR_BACKING_IO, + MONITOR_BACKING_CHAR + }; + char msg[40]; + for (unsigned i = 0; i < sizeof(tags) / sizeof(tags[0]); i++) { + for (unsigned j = 0; j < sizeof(tags) / sizeof(tags[0]); j++) { + monitor_format_breakpoint_mismatch(msg, sizeof(msg), tags[i], tags[j]); + if (expect((int)strlen(msg) <= 38, + "All mismatch tag combinations must fit the footer width")) return 1; + if (expect(strstr(msg, "BRK ") == msg && strstr(msg, ", CPU ") != NULL && + strstr(msg, "; not mapped now") != NULL, + "Mismatch formatter must keep the required template")) return 1; + } + } + return 0; +} + +static int test_breakpoint_popup_store_reuses_selected_slot() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.write(0x1000, 0xEA); + backend.write(0x1100, 0xEA); + + const int keys[] = { + 'J', 'A', 'D', 'R', + 'J', KEY_CTRL_R, 'S', KEY_ESCAPE, KEY_BREAK, KEY_BREAK + }; + FakeKeyboard keyboard(keys, 10); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("1000", 1); + ui.push_prompt("1100", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 7; i++) { + if (expect(monitor.poll(0) == 0, "Breakpoint store setup should stay in monitor")) return 1; + } + + char row[42]; + bool found = false; + for (int y = 0; y < 25 && !found; y++) { + screen.get_slice(0, y, 40, row); + if (strstr(row, "0 SET $1100") != NULL) { + found = true; + } + } + if (expect(found, "S must store the current address into the selected slot")) return 1; + + if (expect(monitor.poll(0) == 0, "ESC closes the breakpoint popup")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_breakpoint_popup_digit_jumps_to_slot() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.write(0x1000, 0xEA); + backend.write(0x1100, 0xEA); + backend.write(0x1200, 0xEA); + + const int keys[] = { + 'J', 'A', 'D', 'R', + 'J', 'R', + 'J', KEY_CTRL_R, '1', + KEY_BREAK, KEY_BREAK + }; + FakeKeyboard keyboard(keys, 11); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("1000", 1); + ui.push_prompt("1100", 1); + ui.push_prompt("1200", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 9; i++) { + if (expect(monitor.poll(0) == 0, "Breakpoint digit-jump setup should stay in monitor")) return 1; + } + + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "$1100") != NULL, + "Digit shortcut in breakpoint popup must jump directly to that slot")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_breakpoint_row_indicator_and_color() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xC000, 0xAD); + backend.write(0xC001, 0x34); + backend.write(0xC002, 0x12); + + const int keys[] = { 'J', 'A', 'D', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("C000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 4; i++) { + if (expect(monitor.poll(0) == 0, "Breakpoint visual setup should stay in monitor")) return 1; + } + + char row[40]; + screen.get_slice(1, 4, 38, row); + if (expect(strstr(row, "C000") != NULL, "Breakpoint row should show the target address")) return 1; + if (expect(strstr(row, "LDA $1234") != NULL, + "Breakpoint row should show mnemonic and operand text")) return 1; + if (expect(strstr(row, "[BRK0][RAM]") != NULL, + "Breakpoint row must show [BRKx] before normalized source")) return 1; + if (expect(strstr(row, "[RAM]") != NULL, + "Assembly source indicator must use the 3-character RAM label")) return 1; + + // Enabled breakpoint + Debug active: only the complete breakpoint label is + // accented; address, bytes, mnemonic, source, and row fill remain normal. + if (expect_breakpoint_label_only_accent(screen, 4, "[BRK0]", + ui.color_fg, 1, + "Enabled breakpoint should accent only its label")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + screen.get_slice(1, 4, 38, row); + if (expect(strstr(row, "[BRK0][RAM]") != NULL, + "Row still shows the stored breakpoint after Debug exits")) return 1; + // Debug off: every breakpoint row reverts to the regular foreground color. + for (int x = 1; x <= 38; x++) { + if (expect(screen.colors[4][x] == ui.color_fg, + "Breakpoint row must use color_fg once Debug mode is off")) return 1; + } + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_disabled_breakpoint_row_uses_regular_color() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xA000, 0xEA); + + // J A000 -> A (asm) -> D (debug on) -> R (toggle BP on) -> C=+R (open popup) + // -> E (disable selected slot) -> ESC (close popup) -> BREAK -> BREAK + const int keys[] = { + 'J', 'A', 'D', 'R', KEY_CTRL_R, 'E', KEY_ESCAPE, KEY_BREAK, KEY_BREAK + }; + FakeKeyboard keyboard(keys, 9); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("A000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 7; i++) { + if (expect(monitor.poll(0) == 0, "Disabled-BP setup should stay in monitor")) return 1; + } + + char row[40]; + screen.get_slice(1, 4, 38, row); + if (expect(strstr(row, "[BRK0][BAS]") != NULL, + "Disabled breakpoint still shows [BRKx] on the opcode row")) return 1; + // Disabled breakpoint, even while Debug mode is still active, must stay + // in the regular foreground color so the user sees it as quiet. + for (int x = 1; x <= 38; x++) { + if (expect(screen.colors[4][x] == ui.color_fg, + "Disabled breakpoint row must render in color_fg, not accent")) return 1; + } + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_breakpoint_label_replaces_row_indicator() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xC000, 0xEA); + + const int keys[] = { + 'J', 'A', 'D', 'R', KEY_CTRL_R, 'L', KEY_ESCAPE, KEY_BREAK, KEY_BREAK + }; + FakeKeyboard keyboard(keys, 9); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("C000", 1); + ui.push_prompt("readc", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + if (expect(monitor.poll(0) == 0, "Breakpoint label setup should stay in monitor")) return 1; + } + + char popup_row[42]; + get_popup_line(screen, 2, popup_row, sizeof(popup_row)); + if (expect(strstr(popup_row, "0 SET READ $C000") == popup_row, + "Breakpoint popup row must show the assigned label")) return 1; + + if (expect(monitor.poll(0) == 0, "ESC closes labelled breakpoint popup")) return 1; + char row[40]; + screen.get_slice(1, 4, 38, row); + if (expect(strstr(row, "[READ][RAM]") != NULL, + "Assembly row must show the breakpoint label instead of [BRKx]")) return 1; + if (expect(strstr(row, "[BRK0]") == NULL, + "Labelled breakpoint row must not also show [BRK0]")) return 1; + if (expect_breakpoint_label_only_accent(screen, 4, "[READ]", + ui.color_fg, 1, + "Labelled breakpoint should accent the whole bracketed label only")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_source_indicators_are_three_chars() +{ + TestUserInterface ui; + CaptureScreen screen; + SourceLabelDebugBackend backend; + monitor_reset_saved_state(); + + for (int i = 0; i < 5; i++) { + backend.write((uint16_t)(0x1000 + i), 0xEA); + } + + const int keys[] = { 'J', 'A', KEY_BREAK }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("1000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Goto source label area")) return 1; + if (expect(monitor.poll(0) == 0, "Switch to ASM view")) return 1; + + const char *expected[] = { "[RAM]", "[BAS]", "[KRN]", "[CHR]", "[I/O]" }; + for (int y = 0; y < 5; y++) { + char row[40]; + screen.get_slice(1, 4 + y, 38, row); + if (expect(strstr(row, expected[y]) != NULL, + "Assembly row must normalize memory source indicators")) return 1; + if (expect(strstr(row, "BASIC") == NULL && strstr(row, "KERNAL") == NULL && + strstr(row, "CHAR ") == NULL && strstr(row, "[IO]") == NULL, + "Assembly row must not show legacy long source labels")) return 1; + } + + if (expect(monitor.poll(0) == 1, "RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_r_opens_breakpoint_popup() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', KEY_CTRL_R, KEY_ESCAPE, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 3; i++) { + if (expect(monitor.poll(0) == 0, "Setup polls should return 0")) return 1; + } + // After C=+R the breakpoint popup should be visible somewhere on the + // screen: the title "BREAKPOINTS" appears in the popup body. + char row[42]; + bool found = false; + for (int y = 0; y < 25 && !found; y++) { + screen.get_slice(0, y, 40, row); + if (strstr(row, "BREAKPOINTS") != NULL) { found = true; } + } + if (expect(found, "C=+R must open the breakpoint list popup")) return 1; + int left = 0, top = 0, right = 0, bottom = 0; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Breakpoint popup must draw a complete border")) return 1; + if (expect(right - left - 1 == 38, + "Breakpoint popup must have 38 inner columns")) return 1; + if (expect(bottom == top + 15, + "Breakpoint popup must match the Bookmark popup height")) return 1; + if (expect(screen.colors[top + 1][left + 1] == ui.color_fg, + "Breakpoint popup title must use the normal popup foreground color")) return 1; + get_popup_line(screen, 2, row, sizeof(row)); + if (expect(strncmp(row, "0 EMPTY", strlen("0 EMPTY")) == 0, + "Breakpoint popup must show slot 0")) return 1; + get_popup_line(screen, 11, row, sizeof(row)); + if (expect(strncmp(row, "9 EMPTY", strlen("9 EMPTY")) == 0, + "Breakpoint popup must show slot 9 without scrolling")) return 1; + get_popup_line(screen, 12, row, sizeof(row)); + if (expect(strspn(row, " ") == strlen(row), + "Breakpoint popup must separate slots from the help row")) return 1; + get_popup_line(screen, 13, row, sizeof(row)); + if (expect(strncmp(row, "0-9/RET:Jmp S:Set L:Lbl E:Enbl DEL:Res", + strlen("0-9/RET:Jmp S:Set L:Lbl E:Enbl DEL:Res")) == 0, + "Breakpoint popup help row must list jump/store/label/enable/reset")) return 1; + int slot_y = top + 1 + 2; + for (int x = left + 1; x < right; x++) { + if (expect(screen.colors[slot_y][x] == ui.color_fg, + "Breakpoint popup selected row must use normal popup foreground color")) return 1; + if (expect(screen.colors[slot_y][x] != 1, + "Breakpoint popup selected row must not use white accent color")) return 1; + if (expect(screen.reverse_chars[slot_y][x], + "Breakpoint popup selected row must use reverse highlight")) return 1; + } + if (expect(monitor.poll(0) == 0, "ESC closes the popup")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug first")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_r_opens_breakpoint_popup_outside_debug() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'R', KEY_BREAK, KEY_CTRL_R, KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 7); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Breakpoint toggle should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 0, "C=+R outside Debug should stay in monitor")) return 1; + + char row[42]; + bool found = false; + for (int y = 0; y < 25 && !found; y++) { + screen.get_slice(0, y, 40, row); + if (strstr(row, "BREAKPOINTS") != NULL) { + found = true; + } + } + if (expect(found, "C=+R outside Debug must open the breakpoint popup when breakpoints exist")) return 1; + get_popup_line(screen, 13, row, sizeof(row)); + if (expect(strncmp(row, "0-9/RET:Jmp S:Set L:Lbl E:Enbl DEL:Res", + strlen("0-9/RET:Jmp S:Set L:Lbl E:Enbl DEL:Res")) == 0, + "Non-Debug breakpoint popup must use the requested help row")) return 1; + if (expect(monitor.poll(0) == 0, "ESC closes the non-Debug breakpoint popup")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_breakpoint_popup_navigation_redraws_only_popup() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { + 'A', 'D', KEY_CTRL_R, KEY_DOWN, KEY_ESCAPE, KEY_BREAK, KEY_BREAK + }; + FakeKeyboard keyboard(keys, 7); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 3; i++) { + if (expect(monitor.poll(0) == 0, "Setup should open breakpoint popup")) return 1; + } + + int left = 0, top = 0, right = 0, bottom = 0; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Breakpoint popup rect should be discoverable")) return 1; + + screen.reset_write_counts(); + if (expect(monitor.poll(0) == 0, "DOWN should navigate inside breakpoint popup")) return 1; + if (expect(screen.count_writes_outside_rect(left, top, right, bottom) == 0, + "Breakpoint popup navigation must not redraw monitor content or frame")) return 1; + + screen.reset_write_counts(); + if (expect(monitor.poll(0) == 0, "ESC should close breakpoint popup")) return 1; + char row[42]; + bool title_found = false; + for (int y = 0; y < 25 && !title_found; y++) { + screen.get_slice(0, y, 40, row); + if (strstr(row, "BREAKPOINTS") != NULL) title_found = true; + } + if (expect(!title_found, "Closing breakpoint popup must remove its title")) return 1; + if (expect(!find_popup_rect(screen, NULL, NULL, NULL, NULL), + "Closing breakpoint popup must not leave stale popup border corners")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug first")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_debug_pc_viewport_keeps_context_margin() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + for (int i = 0; i < 32; i++) { + backend.write((uint16_t)(0xC000 + i), 0xEA); + } + backend.canned_snapshot_set = true; + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xC003; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.sr = 0x24; + + const int keys[] = { 'J', 'A', 'D', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("C000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Goto viewport program")) return 1; + if (expect(monitor.poll(0) == 0, "Switch to ASM")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug and sync to PC")) return 1; + + int row_c003 = find_row_with_address(screen, "C003"); + int row_c000 = find_row_with_address(screen, "C000"); + if (expect(row_c003 > row_c000, "Current PC must not be pinned to the first ASM row")) return 1; + if (expect(row_c003 - row_c000 >= 3, + "Current PC should preserve three instruction rows above where possible")) return 1; + + if (expect(backend.last_session != NULL, "Debug session should exist before stepping")) return 1; + backend.last_session->next_ctx.pc = 0xC004; + if (expect(monitor.poll(0) == 0, "Over should step to next current PC")) return 1; + int row_c004 = find_row_with_address(screen, "C004"); + if (expect(row_c004 == row_c003 + 1, + "Linear stepping should move the highlighted PC down naturally")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_breakpoint_popup_blocks_debug_execution_keys() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { + 'A', 'D', KEY_CTRL_R, 'D', 'T', 'U', 'G', 'R', + KEY_ESCAPE, KEY_BREAK, KEY_BREAK + }; + FakeKeyboard keyboard(keys, 11); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 11; i++) { + int r = monitor.poll(0); + if (i < 10) { + if (expect(r == 0, "Breakpoint popup/modal polls should stay in monitor")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits the monitor")) return 1; + } + } + StubDebugSession *sess = backend.last_session; + if (expect(sess != NULL, "Entering Debug should create a session")) return 1; + if (expect(sess->over_calls == 0 && sess->trace_calls == 0 && + sess->over_at_calls == 0 && sess->trace_at_calls == 0 && + sess->out_calls == 0 && sess->go_calls == 0, + "Breakpoint popup must block Debug execution commands")) return 1; + monitor.deinit(); + return 0; +} + +static int test_unsupported_session_emits_refusal() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + backend.refuse_session = true; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'T', KEY_RETURN, KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 6; i++) { + int r = monitor.poll(0); + if (i < 5) { + if (expect(r == 0, "Setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(ui.popup_count >= 1, "Unsupported Trace must surface a refusal popup")) return 1; + if (expect(strstr(ui.last_popup, "NOT SUPPORTED") != NULL, + "Refusal message must be explicit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_b_keeps_binary_view_in_debug() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'B', KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 5; i++) { + int r = monitor.poll(0); + if (i < 4) { + if (expect(r == 0, "Setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + if (i == 2) { + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN") != NULL, + "B must switch to Binary view while Debug is active")) return 1; + } + } + monitor.deinit(); + return 0; +} + +static int test_ctrl_b_keeps_bookmark_popup_in_debug() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', KEY_CTRL_B, KEY_ESCAPE, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 3; i++) { + if (expect(monitor.poll(0) == 0, "Setup polls should return 0")) return 1; + } + char row[42]; + bool found = false; + for (int y = 0; y < 25 && !found; y++) { + screen.get_slice(0, y, 40, row); + if (strstr(row, "BOOKMARKS") != NULL) { found = true; } + } + if (expect(found, "C=+B must open the bookmark popup while Debug is active")) return 1; + int left = 0, top = 0, right = 0, bottom = 0; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bookmark popup border must remain intact above the Debug footer")) return 1; + if (expect(right - left - 1 == 38, + "Bookmark popup must keep its 38-column body in Debug mode")) return 1; + if (expect(backend.last_session == NULL || + (backend.last_session->over_calls == 0 && + backend.last_session->trace_calls == 0 && + backend.last_session->over_at_calls == 0 && + backend.last_session->trace_at_calls == 0 && + backend.last_session->out_calls == 0 && + backend.last_session->go_calls == 0), + "C=+B must not be treated as a Debug execution command")) return 1; + get_popup_line(screen, 13, row, sizeof(row)); + if (expect(strncmp(row, "0-9/RET:Jmp S:Set L:Label DEL:Reset", + strlen("0-9/RET:Jmp S:Set L:Label DEL:Reset")) == 0, + "Bookmark popup help row must use the requested wording")) return 1; + if (expect(monitor.poll(0) == 0, "ESC closes the bookmark popup")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exits the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_cleanup_runs_on_deinit() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.write(0xC003, 0xA9); + backend.write(0xC004, 0x00); + backend.write(0xC005, 0xEA); + const int keys[] = { 'A', 'D', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 5; i++) { + int r = monitor.poll(0); + if (i < 4) { + if (expect(r == 0, "Setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + StubDebugSession *sess = backend.last_session; + if (expect(sess != NULL, "Session must have been created")) return 1; + // First BREAK left Debug mode, which already calls cleanup() to restore + // any in-flight BRK patches. The session itself stays alive until deinit. + int cleanup_during_lifetime = sess->cleanup_calls; + if (expect(cleanup_during_lifetime >= 1, + "Leaving Debug must invoke session cleanup at least once")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_o_after_debug_step_closes_without_go_handoff() +{ + // CTRL+O closing the monitor after a debug step must NOT schedule a deferred + // go-handoff. The session's cleanup() (driven by debug_leave) hands the + // parked CPU back to the interrupted program directly, so run_machine_monitor + // must not also release ownership and NMI-redirect into a torn-down spin + // loop - that double path is what left the C64 frozen on hardware. + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.write(0xC003, 0xA9); + backend.write(0xC004, 0x00); + backend.write(0xC005, 0xEA); + const int keys[] = { 'A', 'D', 'D', KEY_CTRL_O }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM switch should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug step should return 0")) return 1; + + StubDebugSession *sess = backend.last_session; + if (expect(sess != NULL, "Session must have been created")) return 1; + + if (expect(monitor.poll(0) == 1, + "CTRL+O after a debug step should close the monitor")) return 1; + if (expect(sess->cleanup_calls >= 1, + "CTRL+O close must run session cleanup to resume the parked CPU")) return 1; + + DebugContext go_ctx; + bool has_ctx = true; + uint16_t go_addr = 0; + if (expect(!monitor.consume_pending_go(&go_addr, &go_ctx, &has_ctx), + "CTRL+O close must NOT schedule a deferred go-handoff")) return 1; + monitor.deinit(); + return 0; +} + +static int test_stop_debugging_clears_stale_go_handoff() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x2000; + backend.canned_snapshot.sp = 0xF2; + backend.canned_snapshot.a = 0x11; + backend.canned_snapshot.x = 0x22; + backend.canned_snapshot.y = 0x33; + backend.canned_snapshot.sr = 0x24; + backend.write(0x2000, 0xEE); + backend.write(0x2001, 0x21); + backend.write(0x2002, 0xD0); + backend.write(0x2003, 0x4C); + backend.write(0x2004, 0x00); + backend.write(0x2005, 0x20); + + const int keys[] = { 'A', 'D', 'G', KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_debug_run_window_refreeze_enabled(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM switch should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug should return 0")) return 1; + if (expect(monitor.poll(0) == 1, + "Freeze-mode G without breakpoints should schedule a handoff")) return 1; + + if (expect(monitor.poll(0) == 0, + "Stop Debugging after a pending handoff should stay in monitor")) return 1; + + DebugContext go_ctx; + bool has_ctx = true; + uint16_t go_addr = 0; + if (expect(!monitor.consume_pending_go(&go_addr, &go_ctx, &has_ctx), + "Stop Debugging must clear any stale pending Go handoff")) return 1; + if (expect(backend.read(0x2000) == 0xEE && backend.read(0x2001) == 0x21 && + backend.read(0x2002) == 0xD0 && backend.read(0x2003) == 0x4C && + backend.read(0x2004) == 0x00 && backend.read(0x2005) == 0x20, + "Stop Debugging must not leave a stale BRK patch in the $2000 loop")) return 1; + monitor.deinit(); + return 0; +} + +static int test_stop_debugging_resumes_current_debug_context() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xC123; + backend.canned_snapshot.sp = 0xEF; + backend.canned_snapshot.a = 0x44; + backend.canned_snapshot.x = 0x55; + backend.canned_snapshot.y = 0x66; + backend.canned_snapshot.sr = 0x24; + backend.write(0x2000, 0xEE); + backend.write(0x2001, 0x21); + backend.write(0x2002, 0xD0); + backend.write(0x2003, 0x4C); + backend.write(0x2004, 0x00); + backend.write(0x2005, 0x20); + + const int keys[] = { 'J', 'A', 'D', 'D', KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("2000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Goto $2000 should stay in monitor")) return 1; + if (expect(monitor.poll(0) == 0, "ASM switch should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug should return 0")) return 1; + StubDebugSession *sess = backend.last_session; + if (expect(sess != NULL, "Session must have been created")) return 1; + sess->next_ctx.valid = true; + sess->next_ctx.pc = 0x2003; + sess->next_ctx.sp = 0xEC; + sess->next_ctx.a = 0x45; + sess->next_ctx.x = 0x56; + sess->next_ctx.y = 0x67; + sess->next_ctx.sr = 0x25; + if (expect(monitor.poll(0) == 0, "Step from target cursor should return 0")) return 1; + + if (expect(sess->over_at_calls == 1 && sess->last_start_pc == 0x2000, + "Step must execute from the displayed $2000 target")) return 1; + + if (expect(monitor.poll(0) == 0, "RUN/STOP should stop Debug")) return 1; + if (expect(sess->cleanup_to_context_calls >= 1, + "Stop Debugging must clean up toward a CPU context")) return 1; + if (expect(sess->cleanup_target_ctx.valid && sess->cleanup_target_ctx.pc == 0x2003 && + sess->cleanup_target_ctx.sp == 0xEC && sess->cleanup_target_ctx.a == 0x45 && + sess->cleanup_target_ctx.x == 0x56 && sess->cleanup_target_ctx.y == 0x67 && + sess->cleanup_target_ctx.sr == 0x25, + "Stop Debugging cleanup target must be the current post-step context")) return 1; + if (expect(sess->cleanup_target_ctx.pc != 0xC123, + "Stop Debugging must not discard post-step state by restoring entry PC")) return 1; + if (expect(backend.reset_calls == 0, + "Stop Debugging must never reset the machine")) return 1; + monitor.deinit(); + return 0; +} + +static int test_help_screen_shows_debug_commands() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', KEY_HELP, KEY_ESCAPE, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "help test: ASM switch should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "help test: Debug entry should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "help test: opening help should return 0")) return 1; + + const char *lines[20]; + int n = MonitorDebug::format_help_lines(lines, 20); + static const char *expected_lines[] = { + "", + "D Step Over T Step Into U Step Out", + "G Continue K Cont Crsr RET Follow", + "R Breakpt C=+R Brkpts C=+X Reset", + "", + "M Memory I ASCII V Screen", + "A Assembly B Binary O CPU Bank", + "J Jump P Poll N Number", + "E Edit F Fill W Width", + "C Compare H Hunt Z Freeze", + "L Load S Save", + "", + "Bookmarks: C=+B List C=+0-9 Jump", + "Monitor: C=+O Open/Close", + "Leave debug: C=+D/RSTOP", + "Leave edit: C=+E/RSTOP", + "Copy/Paste: C=+C / C=+V", + }; + if (expect(n == (int)(sizeof(expected_lines) / sizeof(expected_lines[0])), + "Debug help line count must match the requested layout")) return 1; + for (int i = 0; i < n; i++) { + if (expect(strcmp(lines[i], expected_lines[i]) == 0, + "Debug help text did not match the requested layout")) return 1; + if (expect((int)strlen(lines[i]) <= 38, + "Debug help line must fit within 38 columns")) return 1; + if (expect(strstr(lines[i], "SH+O") == NULL, + "Debug help must not show SH+O")) return 1; + if (expect(strstr(lines[i], "ESC") == NULL, + "Debug help must show RSTOP rather than ESC")) return 1; + } + char row[40]; + screen.get_slice(1, 3, 38, row); + if (expect(strstr(row, "HELP ASM DEBUG") == row, + "Debug help header must identify the ASM debug help screen")) return 1; + for (int i = 0; i < n; i++) { + screen.get_slice(1, 4 + i, 38, row); + if (expect(strncmp(row, expected_lines[i], strlen(expected_lines[i])) == 0, + "Rendered debug help text did not match the requested layout")) return 1; + } + screen.get_slice(1, 22, 38, row); + if (expect(strstr(row, "Page Up/Down: F1/SH+SPACE / F7/SPACE") == row, + "Debug help must show the requested paging footer")) return 1; + if (expect_help_token_not_accented(screen, "D Step Over", + "D Step Over must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "T Step Into", + "T Step Into must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "U Step Out", + "U Step Out must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "G Continue", + "G Continue must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "K Cont Crsr", + "K Cont Crsr must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "R Breakpt", + "R Breakpt must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "C=+R Brkpts", + "C=+R Brkpts must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "C=+X Reset", + "C=+X Reset must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "RET Follow", + "RET Follow must not use a distinct debug help colour")) return 1; + if (expect_help_token_not_accented(screen, "C=+D/RSTOP", + "C=+D/RSTOP must not use a distinct debug help colour")) return 1; + if (expect(monitor.poll(0) == 0, "help test: ESC should close help")) return 1; + if (expect(monitor.poll(0) == 0, "help test: RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 1, "help test: final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_k_runs_to_cursor() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'A', 'D', 'J', 'K', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("C123", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + if (expect(backend.last_session != NULL, "Debug entry must create a session")) return 1; + backend.last_session->next_ctx.pc = 0xC123; + if (expect(monitor.poll(0) == 0, "Jump should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "K Cursor should return 0")) return 1; + if (expect(backend.last_session->run_to_calls == 1, + "K Cursor must use the dedicated run-to-cursor session path")) return 1; + if (expect(backend.last_session->last_run_to_target == 0xC123, + "K Cursor must use the current cursor address as its target")) return 1; + if (expect(backend.last_session->last_start_pc == 0xC003, + "K Cursor must continue from the captured debug PC")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_k_without_context_runs_from_debug_entry_to_cursor() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0xE000, 0x85); + backend.write(0xE001, 0x56); + backend.write(0xE002, 0x20); + backend.write(0xE003, 0x0F); + backend.write(0xE004, 0xBC); + + const int keys[] = { 'J', 'A', 'D', 'J', 'K', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 7); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + ui.push_prompt("E002", 3); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + for (int i = 0; i < 7; i++) { + int r = monitor.poll(0); + if (i < 6) { + if (expect(r == 0, "No-context K setup polls should return 0")) return 1; + } else { + if (expect(r == 1, "Final RUN/STOP exits")) return 1; + } + } + if (expect(backend.last_session != NULL, "Backend should have created a debug session")) return 1; + if (expect(backend.last_session->run_to_calls == 1, + "No-context K must use run-to-cursor")) return 1; + if (expect(backend.last_session->last_start_pc == 0xE000, + "No-context K must continue from the debug entry address, not the moved cursor")) return 1; + if (expect(backend.last_session->last_run_to_target == 0xE002, + "No-context K must target the current cursor address")) return 1; + monitor.deinit(); + return 0; +} + +static int test_ctrl_i_swaps_interface_in_monitor() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + g_swap_interface_type_calls = 0; + + const int keys[] = { KEY_CTRL_I }; + FakeKeyboard keyboard(keys, 1); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == MENU_HIDE, + "C=+I in the monitor must route through swap_interface_type")) return 1; + if (expect(g_swap_interface_type_calls == 1, + "C=+I must invoke swap_interface_type exactly once")) return 1; + monitor.deinit(); + return 0; +} + +// Locate the rendered "CPUx ... VICy" / "CxOy ... VICy" monitor status footer +// (it begins at screen column 1). Returns true and fills `out` when found. +static bool capture_status_footer(CaptureScreen &screen, char *out, int out_len) +{ + char row[40]; + out[0] = 0; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strstr(row, "VIC") != NULL && + (strncmp(row, "CPU", 3) == 0 || + (row[0] == 'C' && row[2] == 'O'))) { + strncpy(out, row, out_len - 1); + out[out_len - 1] = 0; + return true; + } + } + return false; +} + +// Issue 1: after a C64 hardware reset, a fresh monitor open must follow the live +// CPU bank so re-entry decodes the memory the CPU actually sees (RAM-under-ROM +// when $01 low bits are 5), not a stale/forced view. Without the fix the reset +// hook forces the saved view to 7 and the footer shows the C5O7 mismatch. +static int test_reset_reentry_view_follows_live_cpu_bank() +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + monitor_reset_saved_state(); + ui.screen = &screen; + + // A C64 hardware reset fires the global reset hook (sets view -> 7 fallback + // and arms the sync-to-live request for the next open). + monitor_reset_saved_cpu_view(); + + // After the reset the live CPU is running RAM-under-ROM: $01 low bits = 5. + backend.live_cpu_port = 0x05; + + const int nokeys[] = { 0 }; + FakeKeyboard kb(nokeys, 0); + ui.keyboard = &kb; + MachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &kb); + + char footer[40]; + if (expect(capture_status_footer(screen, footer, sizeof(footer)), + "Status footer must be visible after reset re-entry")) { monitor.deinit(); return 1; } + // Matched form "CPU5" proves the view followed the live bank; the erroneous + // "C5O7" mismatch must not appear. + if (expect(strncmp(footer, "CPU5", 4) == 0, + "Reset re-entry must follow live CPU bank (footer CPU5, not C5O7)")) { + printf(" footer was: '%s'\n", footer); + monitor.deinit(); + return 1; + } + monitor.deinit(); + return 0; +} + +// Invariant #2: an ordinary monitor close/reopen WITHOUT an intervening reset +// must preserve a manually selected (O) exploratory view bank, i.e. the +// sync-to-live behaviour is gated strictly to the post-reset open. +static int test_reopen_without_reset_preserves_manual_cpu_view() +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + monitor_reset_saved_state(); + ui.screen = &screen; + backend.live_cpu_port = 0x05; // live CPU banks RAM under ROM + + // Session 1: manually cycle the view bank with 'o'. From the default 7 the + // sequence is 7 -> 0 -> 1 -> 2 -> 3, so four presses select view bank 3. + { + const int keys[] = { 'o', 'o', 'o', 'o' }; + FakeKeyboard kb(keys, 4); + ui.keyboard = &kb; + MachineMonitor m(&ui, &backend); + m.init(&screen, &kb); + for (int i = 0; i < 4; i++) { + if (expect(m.poll(0) == 0, "cycle CPU bank ok")) { m.deinit(); return 1; } + } + m.deinit(); // persists manual view bank 3 + } + + // Session 2: reopen with NO reset hook in between -> manual view preserved. + const int nokeys[] = { 0 }; + FakeKeyboard kb(nokeys, 0); + ui.keyboard = &kb; + MachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &kb); + + char footer[40]; + if (expect(capture_status_footer(screen, footer, sizeof(footer)), + "Status footer must be visible on ordinary reopen")) { monitor.deinit(); return 1; } + if (expect(strncmp(footer, "C5O3", 4) == 0, + "Ordinary reopen must preserve the manual O view bank (footer C5O3)")) { + printf(" footer was: '%s'\n", footer); + monitor.deinit(); + return 1; + } + monitor.deinit(); + return 0; +} + +static int test_jump_rejects_non_hex_input_and_uppercases() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + const int keys[] = { 'J', KEY_BREAK }; + FakeKeyboard keyboard(keys, 2); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.push_prompt("G123", 1); + ui.push_prompt("c0de", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Jump command should return 0")) return 1; + if (expect(strcmp(ui.last_popup, "HEX 0-9/A-F ONLY") == 0, + "Jump must reject non-hex input with a monitor-local validation popup")) return 1; + if (expect(ui.last_prompt_maxlen == 4, + "Jump prompt must limit input to four characters")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "$C0DE") != NULL, + "Jump must normalize lowercase hex input to uppercase")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP should exit the monitor")) return 1; + monitor.deinit(); + return 0; +} + +static int test_edit_and_debug_compose_in_header() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + // Use ASCII view because hex edit needs nibble input the keymap doesn't + // intercept here. Sequence: switch to ASM, enter Debug, then E for edit. + const int keys[] = { 'A', 'D', 'E', KEY_CTRL_E, KEY_ESCAPE, KEY_BREAK }; + FakeKeyboard keyboard(keys, 6); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Edit ok")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") != NULL && strstr(header, "Edit") != NULL, + "Header must show both Dbg and Edit when both modes are active")) return 1; + if (expect(monitor.poll(0) == 0, "C=+E drops Edit first")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Dbg") != NULL && strstr(header, "Edit") == NULL, + "C=+E in Debug+Edit must keep Dbg and clear Edit")) return 1; + if (expect(monitor.poll(0) == 0, "ESC drops Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +// --- Freeze-mode render-target regression (temporary-BRK step-over et al.) --- +// +// These tests drive the real BrkDebugSession engine through FakeFreezeMachine. +// The invariant under test: after any debug run that temporarily unfroze the +// machine, the engine must re-freeze it before returning, so the monitor's +// render target (the firmware/menu screen) is preserved instead of leaking into +// the live C64 screen RAM. Before the fix the engine unfroze and never +// re-froze, so `frozen` would be false here and the C64 screen sentinel would +// later be overwritten by monitor redraws. + +static int test_freeze_step_over_refreezes_and_preserves_screen() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2000); + m.stamp_screen_sentinel(0x55, 40); // BASIC-like content in $0400 + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0x2000, pred, &ctx); + + if (expect(r == DebugSession::DBG_OK, "freeze step-over must complete")) return 1; + if (expect(m.frozen, + "freeze step-over must re-freeze the C64 before returning to the monitor")) return 1; + if (expect(m.unfreeze_calls == 1, + "freeze step-over must unfreeze exactly once to run the step")) return 1; + if (expect(m.refreeze_calls == 1, + "freeze step-over must re-freeze exactly once after the step")) return 1; + if (expect(m.screen_sentinel_intact(0x55, 40), + "freeze step-over must not write monitor UI into C64 screen RAM")) return 1; + if (expect(m.screen_render_target_invalidated(), + "freeze step-over must set screen_render_target_invalidated so caller can restore chrome")) return 1; + return 0; +} + +// Regression for the sporadic freeze-mode runaway-stepping loop seen around the +// BASIC FAC multiply loop at $B9A6. The freeze-mode run window unfreezes the +// whole machine, so the live CPU free-runs from its frozen PC before the +// controlled NMI single-step is set up. In a hot tight loop it can reach the +// step BRK we already installed during that gap, fire the handler, and leave +// the sentinel set with a context the engine never controlled (a "$4Cxx"-style +// junk PC was observed). nmi_redirect_to() must clear the sentinel as the last +// act of the controlled launch so wait_for_sentinel() only ever observes the +// result of THIS run. Without the clear, the engine returns the stale context +// and desyncs cpu_parked_in_spin from the real CPU, which is what produced the +// runaway loop. +static int test_freeze_nmi_step_ignores_stale_sentinel() +{ + FakeVisibleRomMachine m(true); // freeze mode, BASIC ROM range like $B9A6 + m.allow_visible_rom_patching = true; + m.cpu_port = 0x07; + m.basic_rom[0xB9A6 - 0xA000] = 0xEA; // NOP at $B9A6 + m.basic_rom[0xB9A7 - 0xA000] = 0xEA; // fall-through / step BRK target + m.basic_rom[0xB9A8 - 0xA000] = 0xEA; + + // Model the gap free-run hitting the installed BRK while the NMI launch is + // being set up: the sentinel goes high mid-setup, with STORE_* holding a + // stale junk PC the engine never asked to stop at ($4C27 was observed). + m.stale_sentinel_during_nmi_setup = true; + m.ram[FAKE_STORE_PCLO] = (uint8_t)((0x4C27 + 2) & 0xFF); + m.ram[FAKE_STORE_PCHI] = (uint8_t)((0x4C27 + 2) >> 8); + // The controlled run captures the real next PC on the next delay_ms tick. + m.arm_capture_context(0xB9A7, 0xFF, 0, 0, 0, 0); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; // NOP at $B9A6, fall-through $B9A7 + DebugPredictResult pred; + debug_predict(0xB9A6, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xB9A6, pred, &ctx); // first step -> NMI launch + if (expect(r == DebugSession::DBG_OK, "freeze NMI step must complete")) return 1; + if (expect(m.nmi_pulses == 1, + "freeze first step must launch via exactly one NMI redirect")) return 1; + if (expect(ctx.valid && ctx.pc == 0xB9A7, + "freeze NMI step must report the controlled run's PC, not the stale gap hit")) return 1; + if (expect(m.ram[FAKE_SENTINEL_ADDR] == 0x00, + "freeze NMI step must leave the sentinel cleared")) return 1; + return 0; +} + +static int test_freeze_step_over_with_context_refreezes() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2000); + m.stamp_screen_sentinel(0x41, 40); + + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0x2000; + from.sp = 0xFF; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over(from, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, "freeze step-over (with context) must complete")) return 1; + if (expect(m.frozen, "freeze step-over (with context) must re-freeze")) return 1; + if (expect(m.screen_sentinel_intact(0x41, 40), + "freeze step-over (with context) must not touch C64 screen RAM")) return 1; + return 0; +} + +static int test_cleanup_to_context_without_entry_context_never_resets() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + m.ram[0x1234] = 0x5A; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Step without entry context must still complete")) return 1; + + m.cleanup_to_context(NULL); + if (expect(m.reset_calls == 0, + "Leaving Debug without an entry context must never reset the machine")) return 1; + if (expect(m.ram[0x1234] == 0x5A, + "Leaving Debug must preserve unrelated memory changes")) return 1; + return 0; +} + +static int test_freeze_step_into_refreezes() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2000); + m.stamp_screen_sentinel(0x42, 40); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, "freeze step-into must complete")) return 1; + if (expect(m.frozen, "freeze step-into must re-freeze")) return 1; + if (expect(m.unfreeze_attempts == 1, "freeze step-into must call the unfreeze hook once")) return 1; + if (expect(m.refreeze_calls == 1, "freeze step-into must re-freeze once")) return 1; + if (expect(m.screen_sentinel_intact(0x42, 40), + "freeze step-into must not touch C64 screen RAM")) return 1; + if (expect(m.screen_render_target_invalidated(), + "freeze step-into must set render-target invalidation after refreeze")) return 1; + return 0; +} + +static int test_freeze_step_out_refreezes() +{ + FakeFreezeMachine m(true); + m.stamp_screen_sentinel(0x43, 40); + + m.ram[0x2001] = 0x20; + m.ram[0x2002] = 0x00; + m.ram[0x2003] = 0x30; + m.ram[0x2004] = 0xEA; + m.ram[0x3000] = 0xEA; + + uint8_t jsr[3] = { 0x20, 0x00, 0x30 }; + DebugPredictResult pred; + debug_predict(0x2001, jsr, false, &pred); + fake_seed_captured_context(m, 0x3000, 0xFB, 0, 0, 0, 0x24); + DebugContext from; + if (expect(m.trace_at(0x2001, pred, &from) == DebugSession::DBG_OK, + "freeze trace into JSR must prepare a Step Out target")) return 1; + m.unfreeze_attempts = 0; + m.unfreeze_calls = 0; + m.refreeze_calls = 0; + m.ram[FAKE_SENTINEL_ADDR] = 0x00; + m.arm_capture_context(0x2004, 0xFD, 0, 0, 0, 0x24); + + DebugContext ctx; + DebugSession::Result r = m.step_out(from, &ctx); + if (expect(r == DebugSession::DBG_OK, "freeze step-out must complete")) return 1; + if (expect(m.frozen, "freeze step-out must re-freeze")) return 1; + if (expect(m.unfreeze_attempts == 1, "freeze step-out must call the unfreeze hook once")) return 1; + if (expect(m.refreeze_calls == 1, "freeze step-out must re-freeze once")) return 1; + if (expect(m.screen_sentinel_intact(0x43, 40), + "freeze step-out must not touch C64 screen RAM")) return 1; + if (expect(m.screen_render_target_invalidated(), + "freeze step-out must set render-target invalidation after refreeze")) return 1; + return 0; +} + +static int test_step_out_uses_traced_jsr_target_even_when_target_is_above_pc() +{ + FakeVisibleRomMachine m(false); + m.allow_visible_rom_patching = true; + + m.kernal_rom[0x0021] = 0x20; + m.kernal_rom[0x0022] = 0x00; + m.kernal_rom[0x0023] = 0xE2; + m.kernal_rom[0x0024] = 0xEA; + m.kernal_rom[0x0200] = 0xEA; + + // Older stack data that must not be selected; Step Out is driven by the + // return target recorded by the actual Trace-Into operation. + m.ram[0x01FA] = 0x03; + m.ram[0x01FB] = 0xC1; + m.ram[0xC101] = 0x20; + m.ram[0xC102] = 0x00; + m.ram[0xC103] = 0xC0; + m.ram[0xC104] = 0xEA; + + uint8_t jsr[3] = { 0x20, 0x00, 0xE2 }; + DebugPredictResult pred; + debug_predict(0xE021, jsr, false, &pred); + fake_seed_captured_context(m, 0xE200, 0xF7, 0, 0, 0, 0x24); + DebugContext from; + if (expect(m.trace_at(0xE021, pred, &from) == DebugSession::DBG_OK, + "KERNAL trace must prepare the Step Out return target")) return 1; + from.pc = 0xE100; + m.ram[FAKE_SENTINEL_ADDR] = 0x00; + m.arm_capture_context(0xE024, 0xF9, 0, 0, 0, 0x24); + + DebugContext ctx; + DebugSession::Result r = m.step_out(from, &ctx); + if (expect(r == DebugSession::DBG_OK, + "KERNAL Step Out must accept the traced JSR return target")) return 1; + if (expect(m.last_rom_patch_addr == 0xE024, + "KERNAL Step Out must patch the nearest KERNAL return target")) return 1; + if (expect(m.last_brk_patch_addr != 0xC104, + "KERNAL Step Out must not fall back to an older RAM caller")) return 1; + return 0; +} + +static int test_step_out_ignores_nearby_rts_and_patches_after_traced_jsr() +{ + FakeFreezeMachine m(false); + + // Active trace: $C6A0 JSR $C6E0 records return address $C6A3, so + // Step Out must install its temporary BRK at $C6A3. The current PC is + // deliberately below the JSR target to catch the old target<=PC heuristic. + m.ram[0xC6A0] = 0x20; + m.ram[0xC6A1] = 0xE0; + m.ram[0xC6A2] = 0xC6; + m.ram[0xC6A3] = 0xEA; + m.ram[0xC6E0] = 0xEA; + + // Decoy RTS opcodes near both the JSR entry and current helper body. A + // nearby-RTS implementation would patch one of these instead of $C6A3. + m.ram[0xC6D2] = 0x60; + m.ram[0xC6D5] = 0x60; + m.ram[0xC6E1] = 0x60; + + uint8_t jsr[3] = { 0x20, 0xE0, 0xC6 }; + DebugPredictResult pred; + debug_predict(0xC6A0, jsr, false, &pred); + fake_seed_captured_context(m, 0xC6E0, 0xFD, 0, 0, 0, 0x24); + DebugContext from; + if (expect(m.trace_at(0xC6A0, pred, &from) == DebugSession::DBG_OK, + "RAM trace must prepare the Step Out return target")) return 1; + from.pc = 0xC6D0; + m.ram[FAKE_SENTINEL_ADDR] = 0x00; + m.arm_capture_context(0xC6A3, 0xFF, 0, 0, 0, 0x24); + + DebugContext ctx; + DebugSession::Result r = m.step_out(from, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Step Out must use the active JSR stack frame")) return 1; + if (expect(m.last_brk_patch_addr == 0xC6A3, + "Step Out must patch the opcode immediately after the active JSR")) return 1; + if (expect(m.last_brk_patch_addr != 0xC6D2 && + m.last_brk_patch_addr != 0xC6D5 && + m.last_brk_patch_addr != 0xC6E1, + "Step Out must not patch nearby RTS opcodes")) return 1; + return 0; +} + +static int test_step_out_refuses_stale_far_stack_frame() +{ + FakeFreezeMachine m(false); + + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0x2003; + from.sp = 0xF7; + + // Stale interpreter frame left on the C64 stack while the user is debugging + // an arbitrary loop at $2000. It is a real JSR-looking frame, but it cannot + // be the active caller of the current program counter. + m.ram[0x01F8] = 0x03; + m.ram[0x01F9] = 0xC1; + m.ram[0xC101] = 0x20; + m.ram[0xC102] = 0x00; + m.ram[0xC103] = 0xC0; + m.ram[0xC104] = 0xEA; + + DebugContext ctx; + DebugSession::Result r = m.step_out(from, &ctx); + if (expect(r == DebugSession::DBG_NOT_IN_SUBROUTINE, + "Step Out must report that no traced subroutine is active")) return 1; + if (expect(m.brk_patch_writes == 0, + "Refused Step Out must not install a temporary BRK")) return 1; + if (expect(m.ram[FAKE_SENTINEL_ADDR] == 0x00, + "Refused Step Out must not start execution")) return 1; + return 0; +} + +static int test_over_rts_refuses_non_jsr_stack_target() +{ + FakeFreezeMachine m(false); + m.ram[0xE042] = 0x60; // RTS at cursor + m.ram[0xE043] = 0xEA; + m.ram[0xE044] = 0xEA; + + // Forge an RTS return target whose recorded caller is not a JSR. + // RTS pops 0x21FF and jumps to 0x2200. + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0xE042; + from.sp = 0xFC; + m.ram[0x01FD] = 0xFF; + m.ram[0x01FE] = 0x21; + m.ram[0x21FD] = 0xEA; // caller opcode at ret-2 (not JSR) + + uint8_t rts[3] = { 0x60, 0x00, 0x00 }; + DebugPredictResult pred; + debug_predict(0xE042, rts, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over(from, pred, &ctx); + if (expect(r == DebugSession::DBG_NOT_IN_SUBROUTINE, + "Over on RTS with a non-JSR stack target must report not-in-subroutine")) return 1; + if (expect(m.brk_patch_writes == 0, + "Refused RTS Over must not install a temporary BRK")) return 1; + if (expect(m.ram[FAKE_SENTINEL_ADDR] == 0x00, + "Refused RTS Over must not start execution")) return 1; + return 0; +} + +static int test_traced_rts_uses_recorded_return_target_when_stack_is_unreliable() +{ + FakeFreezeMachine m(true); + + m.ram[0x2000] = 0x20; // JSR $3000 + m.ram[0x2001] = 0x00; + m.ram[0x2002] = 0x30; + m.ram[0x2003] = 0xEA; + m.ram[0x3000] = 0xEA; + m.ram[0x3005] = 0x60; // RTS + + uint8_t jsr[3] = { 0x20, 0x00, 0x30 }; + DebugPredictResult pred; + debug_predict(0x2000, jsr, false, &pred); + fake_seed_captured_context(m, 0x3000, 0xF8, 0, 0, 0, 0x24); + + DebugContext traced; + if (expect(m.trace_at(0x2000, pred, &traced) == DebugSession::DBG_OK, + "Trace Into must record the JSR fall-through return target")) return 1; + + traced.pc = 0x3005; + traced.sp = 0xF8; + m.ram[0x01F9] = 0x44; + m.ram[0x01FA] = 0x44; + m.ram[0x4442] = 0xEA; // stack-derived caller is deliberately not JSR + m.ram[FAKE_SENTINEL_ADDR] = 0x00; + m.arm_capture_context(0x2003, 0xFA, 0, 0, 0, 0x24); + + uint8_t rts[3] = { 0x60, 0x00, 0x00 }; + debug_predict(0x3005, rts, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace(traced, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "RTS after Trace Into must use the recorded return target")) return 1; + if (expect(ctx.valid && ctx.pc == 0x2003, + "RTS must stop at the recorded JSR fall-through")) return 1; + if (expect(m.last_brk_patch_addr == 0x2003, + "RTS must patch the recorded return target, not stale stack data")) return 1; + if (expect(m.frozen, "Freeze-mode RTS step must refreeze before returning")) return 1; + return 0; +} + +static int test_traced_kernal_to_basic_step_out_patches_kernal_return() +{ + FakeVisibleRomMachine m(false); + m.allow_visible_rom_patching = true; + + m.kernal_rom[0x000B] = 0x20; + m.kernal_rom[0x000C] = 0xD4; + m.kernal_rom[0x000D] = 0xBA; + m.kernal_rom[0x000E] = 0x20; + m.basic_rom[0x1AD4] = 0xEA; + + uint8_t jsr[3] = { 0x20, 0xD4, 0xBA }; + DebugPredictResult pred; + debug_predict(0xE00B, jsr, false, &pred); + + fake_seed_captured_context(m, 0xBAD4, 0xF8, 0x00, 0xFF, 0xCF, 0x37); + DebugContext traced; + DebugSession::Result r = m.trace_at(0xE00B, pred, &traced); + if (expect(r == DebugSession::DBG_OK, + "Trace Into KERNAL JSR $BAD4 must complete")) return 1; + if (expect(traced.pc == 0xBAD4, + "Trace Into must capture the BASIC target PC")) return 1; + + fake_seed_captured_context(m, 0xE00E, 0xFA, 0x00, 0xFF, 0xCF, 0x37); + m.arm_capture_context(0xE00E, 0xFA, 0x00, 0xFF, 0xCF, 0x37); + DebugContext out; + r = m.step_out(traced, &out); + if (expect(r == DebugSession::DBG_OK, + "Step Out from traced BASIC helper must complete")) return 1; + if (expect(m.last_rom_patch_addr == 0xE00E, + "Step Out must patch the KERNAL return target")) return 1; + if (expect(m.kernal_rom[0x000E] == 0x20, + "Step Out must restore the KERNAL return byte")) return 1; + return 0; +} + +static int test_freeze_go_breakpoint_refreezes() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2000); + m.ram[0x2005] = 0xEA; // breakpoint target byte (non-zero) + m.stamp_screen_sentinel(0x44, 40); + + MonitorBreakpoints bps; + bps.allocate(0x2005, 0x07); + + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0x2000; + from.sp = 0xFF; + + DebugSession::Result r = m.go(from, &bps, 0x2000); + if (expect(r == DebugSession::DBG_OK, "freeze Go-to-breakpoint must complete")) return 1; + if (expect(m.frozen, + "freeze Go/continue to breakpoint must re-freeze before returning")) return 1; + if (expect(m.unfreeze_attempts == 1, "freeze Go must call the unfreeze hook once")) return 1; + if (expect(m.refreeze_calls == 1, "freeze Go must re-freeze once")) return 1; + if (expect(m.screen_sentinel_intact(0x44, 40), + "freeze Go must not touch C64 screen RAM")) return 1; + if (expect(m.screen_render_target_invalidated(), + "freeze Go must set render-target invalidation after refreeze")) return 1; + return 0; +} + +static int test_go_from_current_breakpoint_stops_at_callee_breakpoint() +{ + FakeFreezeMachine m(false); + m.ram[0x2000] = 0x20; // JSR $3000 + m.ram[0x2001] = 0x00; + m.ram[0x2002] = 0x30; + m.ram[0x2003] = 0xEA; + m.ram[0x3000] = 0xEA; + + MonitorBreakpoints bps; + bps.allocate(0x2000, 0x07); + bps.allocate(0x3000, 0x07); + + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0x2000; + from.sp = 0xFF; + + m.arm_capture_context(0x3000, 0xFD, 0, 0, 0, 0x24); + DebugSession::Result r = m.go(from, &bps, 0x2000); + if (expect(r == DebugSession::DBG_OK, + "G from a breakpoint must stop at an enabled breakpoint in the callee")) return 1; + + DebugContext stopped; + if (expect(m.snapshot(&stopped) == DebugSession::DBG_OK, + "G callee breakpoint must leave a captured context")) return 1; + if (expect(stopped.valid && stopped.pc == 0x3000, + "G callee breakpoint must be the captured stop PC")) return 1; + if (expect(m.brk_patch_writes == 1, + "G must keep the current breakpoint masked for the whole continue run")) return 1; + if (expect(fake_recorded_brk_patch(m, 0x3000), + "G must arm the callee breakpoint while the current one stays masked")) return 1; + return 0; +} + +static int test_go_from_current_visible_rom_breakpoint_uses_patch_aware_bytes() +{ + FakeVisibleRomMachine m(true); + m.allow_visible_rom_patching = true; + m.basic_rom[0x1C9B] = 0xEA; + m.basic_rom[0x1C9C] = 0xEA; + m.basic_rom[0x1CF2] = 0xEA; + m.force_raw_peek_brk = true; + m.force_raw_peek_brk_addr = 0xBC9B; + + MonitorBreakpoints bps; + bps.allocate(0xBC9B, 0x07); + bps.allocate(0xBCF2, 0x07); + + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0xBC9B; + from.sp = 0xF7; + + m.arm_capture_context(0xBCF2, 0xF5, 0, 0, 0, 0x24); + DebugSession::Result r = m.go(from, &bps, 0xE000); + if (expect(r == DebugSession::DBG_OK, + "G from a visible-ROM breakpoint must not classify raw BRK as the opcode")) return 1; + if (expect(fake_recorded_brk_patch(m, 0xBCF2), + "G must arm the next BASIC ROM breakpoint after skipping the current one")) return 1; + + DebugContext stopped; + if (expect(m.snapshot(&stopped) == DebugSession::DBG_OK, + "G must leave a captured context at the next breakpoint")) return 1; + if (expect(stopped.valid && stopped.pc == 0xBCF2, + "G must stop at the requested next BASIC breakpoint")) return 1; + if (expect(m.frozen, "Freeze-mode visible-ROM G must refreeze before returning")) return 1; + return 0; +} + +static int test_step_over_stops_at_callee_breakpoint() +{ + FakeFreezeMachine m(false); + m.ram[0x2000] = 0x20; // JSR $3000 + m.ram[0x2001] = 0x00; + m.ram[0x2002] = 0x30; + m.ram[0x2003] = 0xEA; + m.ram[0x3000] = 0xEA; + + uint8_t jsr[3] = { 0x20, 0x00, 0x30 }; + DebugPredictResult pred; + debug_predict(0x2000, jsr, false, &pred); + + MonitorBreakpoints bps; + bps.allocate(0x3000, 0x07); + + m.arm_capture_context(0x3000, 0xFD, 0, 0, 0, 0x24); + DebugContext ctx; + DebugSession::Result r = m.over_at(0x2000, pred, &bps, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Step Over must stop at an enabled breakpoint in the callee")) return 1; + if (expect(ctx.valid && ctx.pc == 0x3000, + "Step Over callee breakpoint must be the captured stop PC")) return 1; + if (expect(fake_recorded_brk_patch(m, 0x3000), + "Step Over must arm active breakpoints before running")) return 1; + if (expect(fake_recorded_brk_patch(m, 0x2003), + "Step Over must still patch the JSR fall-through")) return 1; + return 0; +} + +static int test_visible_basic_step_uses_rom_patch_support() +{ + FakeVisibleRomMachine m(false); + fake_seed_rom_nop_run(m, 0xA000); + m.allow_visible_rom_patching = true; + m.ram[0xA001] = 0x5A; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xA000, bytes, false, &pred); + + // Model a trap at the installed fall-through BRK ($A001) so the relaunch + // backstop sees a legitimate capture and does not relaunch. Use the dynamic + // override (a static seed is wiped by the handler install). + m.arm_capture_context(0xA001, 0xF8, 0x11, 0x22, 0x33, 0x24); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0xA000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Visible BASIC step must succeed when ROM patching is supported")) return 1; + if (expect(m.basic_rom[1] == 0xEA, + "Visible BASIC patch byte must be restored after the step")) return 1; + if (expect(m.ram[0xA001] == 0x5A, + "Visible BASIC patching must not scribble into underlying RAM")) return 1; + // 4 ROM-image writes: install BRK + recommit launch-PC fetch byte + recommit + // BRK + restore. The two recommits guard the live 6510 against a stale fetch. + if (expect(m.rom_patch_writes == 4, + "Visible BASIC step must patch, recommit launch byte + BRK, and restore the ROM image")) return 1; + // The BRK ($00) is written twice for the single step: once by install_brk_at + // and once by recommit_visible_rom_patches() in the launch's stopped session. + if (expect(m.brk_patch_writes == 2, + "Visible BASIC step must re-commit the ROM BRK as the final pre-launch write")) return 1; + return 0; +} + +static int test_visible_rom_step_bytes_use_cpu_visible_mapping() +{ + FakeVisibleRomMachine m(false); + uint8_t bytes[3] = { 0, 0, 0 }; + + m.allow_visible_rom_patching = false; + m.cpu_port = 0x07; + m.kernal_rom[0] = 0x85; + m.kernal_rom[1] = 0x56; + m.kernal_rom[2] = 0xEA; + m.ram[0xE000] = 0x00; + m.ram[0xE001] = 0x00; + m.ram[0xE002] = 0x00; + + if (expect(m.read_step_bytes(0xE000, bytes, 3), + "Visible KERNAL read_step_bytes must succeed")) return 1; + if (expect(bytes[0] == 0x85 && bytes[1] == 0x56 && bytes[2] == 0xEA, + "Visible KERNAL read_step_bytes must use ROM bytes, not RAM under ROM")) return 1; + + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + if (expect(pred.kind != DBG_PREDICT_BRK && pred.kind != DBG_PREDICT_UNSAFE, + "Visible KERNAL ROM bytes must not be classified from RAM-under-ROM BRK")) return 1; + + m.cpu_port = 0x05; + if (expect(m.read_step_bytes(0xE000, bytes, 3), + "Hidden KERNAL read_step_bytes must also succeed")) return 1; + if (expect(bytes[0] == 0x00 && bytes[1] == 0x00 && bytes[2] == 0x00, + "Hidden KERNAL read_step_bytes must fall back to RAM under ROM")) return 1; + + m.cpu_port = 0x07; + m.basic_rom[0] = 0x18; + m.basic_rom[1] = 0xEA; + m.basic_rom[2] = 0xEA; + m.ram[0xA000] = 0x00; + m.ram[0xA001] = 0x00; + m.ram[0xA002] = 0x00; + if (expect(m.read_step_bytes(0xA000, bytes, 3), + "Visible BASIC read_step_bytes must succeed")) return 1; + if (expect(bytes[0] == 0x18 && bytes[1] == 0xEA && bytes[2] == 0xEA, + "Visible BASIC read_step_bytes must use ROM bytes, not RAM under ROM")) return 1; + + return 0; +} + +static int test_u64_debug_cpu_port_uses_live_cpu_bank() +{ + FakeCpuPortBackend backend; + + backend.set_monitor_cpu_port(0x07); + backend.live_cpu_port = 0x05; + if (expect(u64_debug_step_cpu_port(&backend) == 0x05, + "U64 Debug stepping must use the live CPU bank")) return 1; + if (expect(backend.live_reads == 1, + "U64 Debug stepping must sample $0001 for the live CPU bank")) return 1; + + backend.set_monitor_cpu_port(0x05); + backend.live_cpu_port = 0x07; + if (expect(u64_debug_step_cpu_port(&backend) == 0x07, + "U64 Debug stepping must ignore monitor-bank changes")) return 1; + if (expect(backend.live_reads == 2, + "U64 Debug stepping must re-sample live bank changes")) return 1; + if (expect(u64_debug_step_cpu_port(0) == 0x07, + "U64 Debug stepping must default to all ROMs visible without a backend")) return 1; + + return 0; +} + +static int test_brk_debug_cassette_layout_is_compact_and_top_aligned() +{ + if (expect(FAKE_HANDLER_ADDR >= FAKE_DEBUG_AREA_START, + "BRK debug handler must stay inside the cassette buffer")) return 1; + if (expect(FAKE_HANDLER_LEN == 39, + "BRK debug handler byte count must stay compact")) return 1; + if (expect(FAKE_TRAMPOLINE_LEN == 38, + "BRK debug trampoline byte count must stay compact")) return 1; + if (expect(FAKE_NMI_TRAMP_LEN == 24, + "NMI trampoline reservation must remain 24 bytes")) return 1; + if (expect(FAKE_HARD_BRK_STUB_LEN == 37, + "Hard BRK stub reservation must preserve the validated hardware entry address")) return 1; + if (expect(FAKE_HANDLER_ADDR + FAKE_HANDLER_LEN == FAKE_TRAMPOLINE, + "Handler and trampoline must be contiguous")) return 1; + if (expect(FAKE_TRAMPOLINE + FAKE_TRAMPOLINE_LEN == FAKE_NMI_TRAMP, + "Trampoline and NMI trampoline reservation must be contiguous")) return 1; + if (expect(FAKE_NMI_TRAMP + FAKE_NMI_TRAMP_LEN == FAKE_HARD_BRK_STUB, + "NMI reservation and hard BRK stub must be contiguous")) return 1; + if (expect(FAKE_HARD_BRK_STUB + FAKE_HARD_BRK_STUB_LEN == FAKE_STORE_HARD_CPU_PORT, + "Code stubs must pack directly below the fixed scratch block")) return 1; + if (expect(FAKE_STORE_HARD_CPU_PORT == 0x03ED && + FAKE_STORE_HARD_CPU_DDR == FAKE_DEBUG_AREA_END, + "Fixed scratch bytes must still end at DEBUG_AREA_END $03FB")) return 1; + if (expect(FAKE_DEBUG_AREA_END == 0x03FB, + "DEBUG_AREA_END must remain $03FB so $03FC-$03FF stay free")) return 1; + if (expect(FAKE_HARD_BRK_STUB + FAKE_HARD_BRK_STUB_LEN <= 0x03FC, + "Debug stubs must not reserve $03FC-$03FF")) return 1; + if (expect((FAKE_SPIN_JMP >> 8) == 0x03 && + (FAKE_TRAMPOLINE >> 8) == 0x03 && + (FAKE_HANDLER_ADDR >> 8) == 0x03, + "All spin targets must stay on page $03")) return 1; + return 0; +} + +static int test_brk_handler_bytes_preserve_stack_and_port_capture_semantics() +{ + FakeFreezeMachine m(false); + if (expect(fake_install_debug_stubs(m, 0x2000), + "Installing debug stubs for handler byte test must succeed")) return 1; + + const uint8_t sp = 0x80; + const uint8_t frame[6] = { 0x33, 0x22, 0x11, 0xA4, 0x34, 0x12 }; + for (int i = 0; i < 6; i++) { + m.ram[(uint16_t)(0x0101 + sp + i)] = frame[i]; + } + m.ram[0x0000] = 0x37; + m.ram[0x0001] = 0x35; + m.ram[FAKE_SENTINEL_ADDR] = 0x00; + m.ram[FAKE_SPIN_LO] = 0x00; + m.ram[FAKE_SPIN_HI] = (uint8_t)(FAKE_SPIN_JMP >> 8); + + Mini6510 cpu = { 0, 0, 0, sp, 0, FAKE_HANDLER_ADDR, false, false }; + if (expect(mini_run(m.ram, cpu, FAKE_SPIN_JMP, 100), + "Optimized handler bytes must reach the self-spin JMP")) return 1; + if (expect(m.ram[FAKE_STORE_Y] == 0x33 && + m.ram[FAKE_STORE_X] == 0x22 && + m.ram[FAKE_STORE_A] == 0x11 && + m.ram[FAKE_STORE_SR] == 0xA4 && + m.ram[FAKE_STORE_PCLO] == 0x34 && + m.ram[FAKE_STORE_PCHI] == 0x12, + "Optimized handler loop must preserve the old stack-frame mapping")) return 1; + if (expect(m.ram[FAKE_STORE_SP] == (uint8_t)(sp + 6), + "Optimized handler loop must preserve saved SP semantics")) return 1; + if (expect(m.ram[FAKE_STORE_CPU_DDR] == 0x37 && + m.ram[FAKE_STORE_CPU_PORT] == 0x35, + "Optimized handler must capture $00/$01 through zero-page loads")) return 1; + if (expect(m.ram[FAKE_SENTINEL_ADDR] != 0x00 && + m.ram[FAKE_SPIN_LO] == (uint8_t)(FAKE_SPIN_JMP & 0xFF) && + m.ram[FAKE_SPIN_HI] == (uint8_t)(FAKE_SPIN_JMP >> 8), + "Optimized handler must mark sentinel nonzero and restore self-spin")) return 1; + return 0; +} + +static int test_brk_trampoline_bytes_preserve_rti_restore_semantics() +{ + FakeFreezeMachine m(false); + if (expect(fake_install_debug_stubs(m, 0x2100), + "Installing debug stubs for trampoline byte test must succeed")) return 1; + + m.ram[FAKE_STORE_CPU_DDR] = 0x37; + m.ram[FAKE_STORE_CPU_PORT] = 0x35; + m.ram[FAKE_STORE_SR] = 0xA5; + m.ram[FAKE_STORE_PCLO] = 0x78; + m.ram[FAKE_STORE_PCHI] = 0x56; + m.ram[FAKE_STORE_Y] = 0x44; + m.ram[FAKE_STORE_X] = 0x55; + m.ram[FAKE_STORE_A] = 0x66; + + Mini6510 cpu = { 0x10, 0x20, 0x30, 0xF0, 0x00, FAKE_TRAMPOLINE, false, false }; + m.ram[0x01F1] = 0xDE; + m.ram[0x01F2] = 0xAD; + m.ram[0x01F3] = 0xBE; + if (expect(mini_run(m.ram, cpu, 0, 100), + "Optimized trampoline bytes must reach RTI")) return 1; + if (expect(cpu.rti && cpu.pc == 0x5678 && cpu.sr == 0xA5, + "Optimized trampoline must rebuild the RTI frame from stored SR/PC")) return 1; + if (expect(m.ram[0x01F4] == 0xA5 && + m.ram[0x01F5] == 0x78 && + m.ram[0x01F6] == 0x56, + "Optimized trampoline loop must write $0101,X..$0103,X after discarding the NMI frame")) return 1; + if (expect(cpu.sp == 0xF6, + "Optimized trampoline RTI must leave SP after the rebuilt frame")) return 1; + if (expect(m.ram[0x0000] == 0x37 && m.ram[0x0001] == 0x35, + "Optimized trampoline must restore $00/$01 before RTI")) return 1; + if (expect(cpu.a == 0x66 && cpu.x == 0x55 && cpu.y == 0x44, + "Optimized trampoline must restore A/X/Y before RTI")) return 1; + return 0; +} + +static int test_hard_brk_stub_bytes_preserve_irq_and_brk_paths() +{ + FakeFreezeMachine m(false); + if (expect(fake_install_debug_stubs(m, 0x2200), + "Installing debug stubs for hard-BRK byte test must succeed")) return 1; + + m.ram[FAKE_HARD_BRK_STUB + 19] = 0xA5; + m.ram[FAKE_HARD_BRK_STUB + 24] = 0xA5; + + m.ram[FAKE_HARD_BRK_STUB + 0] = 0x48; + m.ram[FAKE_HARD_BRK_STUB + 1] = 0x8A; + m.ram[FAKE_HARD_BRK_STUB + 2] = 0x48; + m.ram[FAKE_HARD_BRK_STUB + 3] = 0xBA; + if (expect(m.ram[FAKE_HARD_BRK_STUB + 19] == 0xA5 && + m.ram[FAKE_HARD_BRK_STUB + 24] == 0xA5, + "Hard BRK stub must use zero-page LDA $00/$01 opcodes")) return 1; + + m.ram[FAKE_HARD_BRK_ORIG_VECTOR_LO] = 0x34; + m.ram[(uint16_t)(FAKE_HARD_BRK_ORIG_VECTOR_LO + 1)] = 0x12; + m.ram[0x01FA] = 0x24; // B flag clear: non-BRK IRQ fallback. + Mini6510 irq = { 0xA5, 0x5A, 0xC3, 0xF9, 0, FAKE_HARD_BRK_STUB, false, false }; + if (expect(mini_run(m.ram, irq, 0x1234, 100), + "Hard BRK stub non-BRK path must jump through the original vector")) return 1; + if (expect(irq.pc == 0x1234 && irq.a == 0xA5 && irq.x == 0x5A && irq.sp == 0xF9, + "Hard BRK stub non-BRK path must restore A, X, and SP")) return 1; + + m.ram[FAKE_STORE_HARD_CPU_DDR] = 0x00; + m.ram[FAKE_STORE_HARD_CPU_PORT] = 0x00; + m.ram[FAKE_STORE_TRAP_MODE] = 0x00; + m.ram[0x0000] = 0x37; + m.ram[0x0001] = 0x35; + m.ram[0x01FA] = 0x34; // B flag set: BRK path. + m.ram[0x01FB] = 0x78; + m.ram[0x01FC] = 0x56; + Mini6510 brk = { 0xA5, 0x5A, 0xC3, 0xF9, 0, FAKE_HARD_BRK_STUB, false, false }; + if (expect(mini_run(m.ram, brk, FAKE_HANDLER_ADDR, 100), + "Hard BRK stub BRK path must jump to the soft handler")) return 1; + if (expect(brk.pc == FAKE_HANDLER_ADDR && brk.sp == 0xF6, + "Hard BRK stub BRK path must stack Y above saved X/A before handler entry")) return 1; + if (expect(m.ram[0x01F7] == 0xC3 && + m.ram[0x01F8] == 0x5A && + m.ram[0x01F9] == 0xA5, + "Hard BRK stub BRK path must preserve Y, X, and A on the stack")) return 1; + if (expect(m.ram[FAKE_STORE_HARD_CPU_DDR] == 0x37 && + m.ram[FAKE_STORE_HARD_CPU_PORT] == 0x35 && + m.ram[FAKE_STORE_TRAP_MODE] != 0x00, + "Hard BRK stub BRK path must capture $00/$01 and mark hard-trap mode")) return 1; + return 0; +} + +static int test_brk_capture_records_live_cpu_port() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + fake_seed_captured_context(m, 0x2001, 0xF8, 0x11, 0x22, 0x33, 0x24); + m.ram[FAKE_STORE_CPU_DDR] = 0x37; + m.ram[FAKE_STORE_CPU_PORT] = 0x35; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "BRK capture with live CPU port must complete")) return 1; + if (expect(ctx.valid && ctx.pc == 0x2001, + "BRK capture must keep the captured PC")) return 1; + if (expect(ctx.live_cpu_port_valid && ctx.live_cpu_port == 0x05, + "BRK capture must record the live $0001 execution bank")) return 1; + if (expect(ctx.cpu_port_registers_valid && ctx.cpu_ddr == 0x37 && + ctx.cpu_port_latch == 0x35, + "BRK capture must retain the full $00/$01 register bytes")) return 1; + + FakeFreezeMachine m2(false); + fake_seed_nop_run(m2, 0x2100); + fake_seed_captured_context(m2, 0x2101, 0xF8, 0x11, 0x22, 0x33, 0x24); + m2.ram[FAKE_STORE_CPU_DDR] = 0x04; + m2.ram[FAKE_STORE_CPU_PORT] = 0x00; + debug_predict(0x2100, bytes, false, &pred); + r = m2.trace_at(0x2100, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "BRK capture with input CPU-port bits must complete")) return 1; + if (expect(ctx.live_cpu_port_valid && ctx.live_cpu_port == 0x03, + "Input CPU-port bits must resolve high in the live bank")) return 1; + + FakeVisibleRomMachine m3(false); + m3.cpu_port = 0x05; + fake_seed_nop_run(m3, 0xE000); + fake_seed_captured_context(m3, 0xE001, 0xF8, 0x11, 0x22, 0x33, 0x24); + m3.ram[FAKE_STORE_CPU_DDR] = 0x00; + m3.ram[FAKE_STORE_CPU_PORT] = 0x00; + m3.arm_hard_vector_capture_context(0xE001, 0xF8, 0x11, 0x22, 0x33, 0x24, + 0x37, 0x35); + debug_predict(0xE000, bytes, false, &pred); + r = m3.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Hard-vector BRK capture must complete with hidden KERNAL")) return 1; + if (expect(ctx.live_cpu_port_valid && ctx.live_cpu_port == 0x05, + "Hard-vector BRK capture must keep the execution bank when DDR readback is empty")) return 1; + if (expect(ctx.cpu_port_registers_valid && ctx.cpu_ddr == 0x37 && + ctx.cpu_port_latch == 0x35, + "Hard-vector BRK capture must retain the full $00/$01 register bytes")) return 1; + + FakeVisibleRomMachine m4(false); + m4.cpu_port = 0x05; + fake_seed_nop_run(m4, 0xE100); + fake_seed_captured_context(m4, 0xE101, 0xF8, 0x11, 0x22, 0x33, 0x24); + m4.ram[FAKE_STORE_CPU_DDR] = 0x00; + m4.ram[FAKE_STORE_CPU_PORT] = 0x00; + m4.arm_hard_vector_capture_context(0xE101, 0xF8, 0x11, 0x22, 0x33, 0x24, + 0x00, 0x35); + debug_predict(0xE100, bytes, false, &pred); + r = m4.trace_at(0xE100, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Hard-vector BRK capture with unreadable DDR must complete")) return 1; + if (expect(ctx.live_cpu_port_valid && ctx.live_cpu_port == 0x05, + "Hard-vector BRK capture with unreadable DDR must keep the execution bank")) return 1; + if (expect(ctx.cpu_port_registers_valid && + (ctx.cpu_ddr & 0x07) == 0x07 && + (ctx.cpu_port_latch & 0x07) == 0x05, + "Hard-vector unreadable DDR fallback must resume in the captured execution bank")) return 1; + + return 0; +} + +static int test_parked_step_resume_restores_captured_cpu_port_registers() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + fake_seed_captured_context(m, 0x2001, 0xF8, 0x11, 0x22, 0x33, 0x24); + m.ram[FAKE_STORE_CPU_DDR] = 0x37; + m.ram[FAKE_STORE_CPU_PORT] = 0x35; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Initial step must park a captured context")) return 1; + if (expect(ctx.cpu_port_registers_valid && ctx.cpu_ddr == 0x37 && + ctx.cpu_port_latch == 0x35, + "Initial capture must retain the program CPU-port registers")) return 1; + + m.ram[0x0000] = 0x00; + m.ram[0x0001] = 0x07; + fake_seed_captured_context(m, 0x2002, 0xF8, 0x11, 0x22, 0x33, 0x24); + m.ram[FAKE_STORE_CPU_DDR] = 0x37; + m.ram[FAKE_STORE_CPU_PORT] = 0x35; + debug_predict(0x2001, bytes, false, &pred); + + DebugContext next; + r = m.over(ctx, pred, &next); + if (expect(r == DebugSession::DBG_OK, + "Parked Step Over must complete after a CPU-port clobber")) return 1; + if (expect(m.ram[FAKE_STORE_CPU_DDR] == 0x37 && + m.ram[FAKE_STORE_CPU_PORT] == 0x35, + "Parked step resume must stage captured $00/$01 for the trampoline")) return 1; + if (expect(m.ram[FAKE_TRAMPOLINE + 0] == 0xAD && + m.ram[FAKE_TRAMPOLINE + 1] == (uint8_t)(FAKE_STORE_CPU_DDR & 0xFF) && + m.ram[FAKE_TRAMPOLINE + 2] == (uint8_t)(FAKE_STORE_CPU_DDR >> 8) && + m.ram[FAKE_TRAMPOLINE + 3] == 0x85 && + m.ram[FAKE_TRAMPOLINE + 4] == 0x00 && + m.ram[FAKE_TRAMPOLINE + 5] == 0xAD && + m.ram[FAKE_TRAMPOLINE + 6] == (uint8_t)(FAKE_STORE_CPU_PORT & 0xFF) && + m.ram[FAKE_TRAMPOLINE + 7] == (uint8_t)(FAKE_STORE_CPU_PORT >> 8) && + m.ram[FAKE_TRAMPOLINE + 8] == 0x85 && + m.ram[FAKE_TRAMPOLINE + 9] == 0x01, + "Parked step trampoline must restore $00/$01 in CPU-executed code")) return 1; + return 0; +} + +static int test_no_breakpoint_continue_restores_captured_cpu_port_registers() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2100); + fake_seed_captured_context(m, 0x2101, 0xF8, 0x44, 0x55, 0x66, 0x24); + m.ram[FAKE_STORE_CPU_DDR] = 0x37; + m.ram[FAKE_STORE_CPU_PORT] = 0x35; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2100, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0x2100, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Initial step must park a context for continue")) return 1; + + m.ram[0x0000] = 0x00; + m.ram[0x0001] = 0x07; + r = m.go(ctx, 0, ctx.pc); + if (expect(r == DebugSession::DBG_OK, + "No-breakpoint continue must release the parked context")) return 1; + if (expect(m.ram[FAKE_RESUME_TRAMP + 0] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 1] == 0x37 && + m.ram[FAKE_RESUME_TRAMP + 2] == 0x85 && + m.ram[FAKE_RESUME_TRAMP + 3] == 0x00 && + m.ram[FAKE_RESUME_TRAMP + 4] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 5] == 0x35 && + m.ram[FAKE_RESUME_TRAMP + 6] == 0x85 && + m.ram[FAKE_RESUME_TRAMP + 7] == 0x01, + "No-breakpoint continue stub must restore $00/$01 in CPU-executed code")) return 1; + return 0; +} + +// Regression: a plain G issued after single-stepping passes NO freshly captured +// context (resume_from.valid == false); the session must still resume through +// the banking-preserving register-restore stub using its parked last_context, +// NOT fall back to free_run_no_breakpoint()/jump_to(). The latter vectors +// through the (absent) KERNAL NMI handler and silently fails to execute a +// program running with KERNAL banked out (RAM under ROM). See the no-breakpoint +// branch in BrkDebugSession::go(). +static int test_no_breakpoint_continue_after_step_without_passed_context() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2100); + fake_seed_captured_context(m, 0x2101, 0xF8, 0x44, 0x55, 0x66, 0x24); + m.ram[FAKE_STORE_CPU_DDR] = 0x37; + m.ram[FAKE_STORE_CPU_PORT] = 0x35; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2100, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0x2100, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Initial step must park a context for the no-context continue")) return 1; + + // Wipe the resume stub area so we can prove the Go rebuilds it. + for (int i = 0; i < 16; i++) m.ram[FAKE_RESUME_TRAMP + i] = 0x00; + m.ram[0x0000] = 0x00; + m.ram[0x0001] = 0x07; + + // Plain G with NO passed context: this is what the monitor sends when the + // user presses G after stepping (it relies on the session's parked context). + DebugContext empty; + debug_context_reset(&empty); + r = m.go(empty, 0, ctx.pc); + if (expect(r == DebugSession::DBG_OK, + "No-breakpoint continue without a passed context must succeed")) return 1; + if (expect(m.ram[FAKE_RESUME_TRAMP + 0] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 1] == 0x37 && + m.ram[FAKE_RESUME_TRAMP + 2] == 0x85 && + m.ram[FAKE_RESUME_TRAMP + 3] == 0x00 && + m.ram[FAKE_RESUME_TRAMP + 4] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 5] == 0x35 && + m.ram[FAKE_RESUME_TRAMP + 6] == 0x85 && + m.ram[FAKE_RESUME_TRAMP + 7] == 0x01, + "No-context continue after a step must resume via the banking-" + "preserving stub (parked last_context), not the KERNAL-NMI fallback")) return 1; + return 0; +} + +static int test_cursor_visible_rom_step_sets_monitor_cpu_port_before_jump() +{ + FakeVisibleRomMachine m(false); + fake_seed_rom_nop_run(m, 0xE000); + m.allow_visible_rom_patching = true; + m.cpu_port = 0x07; + m.ram[0x0001] = 0x05; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + m.arm_capture_context(0xE001, 0xFE, 0, 0, 0, 0x24); + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "No-context visible-ROM Step Into must complete")) return 1; + if (expect(ctx.valid && ctx.pc == 0xE001, + "No-context visible-ROM Step Into must capture the ROM fall-through")) return 1; + if (expect(fake_nmi_trampoline_stores_cpu_port(m, 0x07), + "No-context visible-ROM launch must select the monitor CPU bank before jumping")) return 1; + if (expect(m.last_rom_patch_addr == 0xE001, + "No-context visible-ROM Step Into must patch the monitor-bank ROM fall-through")) return 1; + return 0; +} + +static int test_visible_kernal_step_into_uses_rom_patch_support() +{ + FakeVisibleRomMachine m(false); + fake_seed_rom_nop_run(m, 0xE000); + m.allow_visible_rom_patching = true; + m.ram[0xE001] = 0x6C; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + // Model a trap at the installed fall-through BRK ($E001) (see arm_capture note). + m.arm_capture_context(0xE001, 0xF8, 0x11, 0x22, 0x33, 0x24); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Visible KERNAL Step Into must succeed when ROM patching is supported")) return 1; + if (expect(m.kernal_rom[1] == 0xEA, + "Visible KERNAL Step Into patch byte must be restored")) return 1; + if (expect(m.ram[0xE001] == 0x6C, + "Visible KERNAL Step Into must not patch RAM under ROM")) return 1; + // 4 ROM-image writes: install BRK + recommit launch-PC fetch byte ($E000 is + // visible ROM) + recommit BRK + restore. + if (expect(m.rom_patch_writes == 4, + "Visible KERNAL Step Into must patch, recommit launch byte + BRK, and restore the ROM image")) return 1; + if (expect(m.brk_patch_writes == 2, + "Visible KERNAL Step Into must re-commit the ROM BRK as the final pre-launch write")) return 1; + return 0; +} + +static int test_visible_kernal_step_over_jsr_patches_fallthrough_rom() +{ + FakeVisibleRomMachine m(false); + m.allow_visible_rom_patching = true; + m.kernal_rom[0] = 0x20; + m.kernal_rom[1] = 0x0F; + m.kernal_rom[2] = 0xBC; + m.kernal_rom[3] = 0xEA; + m.ram[0xE003] = 0x7B; + + uint8_t bytes[3] = { 0x20, 0x0F, 0xBC }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + // Step-over a 3-byte JSR places the BRK at the fall-through ($E003); model the + // trap there so the relaunch backstop sees a legitimate capture. + m.arm_capture_context(0xE003, 0xF8, 0x11, 0x22, 0x33, 0x24); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Visible KERNAL Step Over JSR must patch the ROM fall-through target")) return 1; + if (expect(m.kernal_rom[3] == 0xEA, + "Visible KERNAL Step Over JSR must restore fall-through ROM byte")) return 1; + if (expect(m.ram[0xE003] == 0x7B, + "Visible KERNAL Step Over JSR must not patch RAM under ROM")) return 1; + // patch fall-through BRK + launch-PC ($E000 JSR) fetch-byte recommit + BRK + // recommit + restore = 4 (launch PC is visible ROM, so its byte recommits too). + if (expect(m.rom_patch_writes == 4, + "Visible KERNAL Step Over JSR must patch, recommit launch byte + BRK, and restore ROM")) return 1; + return 0; +} + +static int test_visible_kernal_step_without_rom_patch_support_refuses_cleanly() +{ + FakeVisibleRomMachine m(false); + fake_seed_rom_nop_run(m, 0xE000); + m.allow_visible_rom_patching = false; + m.ram[0xE001] = 0x6C; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_NOT_SUPPORTED, + "Visible KERNAL step must report not-supported when ROM patching is unavailable")) return 1; + if (expect(m.kernal_rom[1] == 0xEA, + "Visible KERNAL step must leave the ROM byte untouched on refusal")) return 1; + if (expect(m.ram[0xE001] == 0x6C, + "Visible KERNAL refusal must not write into underlying RAM")) return 1; + if (expect(m.rom_patch_writes == 0, + "Visible KERNAL refusal must not attempt ROM patch writes")) return 1; + return 0; +} + +static int test_visible_rom_breakpoint_go_uses_same_capability_gate() +{ + FakeVisibleRomMachine m(false); + fake_seed_rom_nop_run(m, 0xE000); + m.allow_visible_rom_patching = false; + m.ram[0xE001] = 0x6C; + + MonitorBreakpoints bps; + bps.allocate(0xE001, 0x07); + DebugContext from; + debug_context_reset(&from); + + DebugSession::Result r = m.go(from, &bps, 0xC000); + if (expect(r == DebugSession::DBG_NOT_SUPPORTED, + "Visible ROM breakpoint Go must refuse before execution when ROM patching is unavailable")) return 1; + if (expect(m.kernal_rom[1] == 0xEA, + "Unsupported visible ROM breakpoint must leave ROM untouched")) return 1; + if (expect(m.ram[0xE001] == 0x6C, + "Unsupported visible ROM breakpoint must not patch RAM under ROM")) return 1; + if (expect(m.rom_patch_writes == 0, + "Unsupported visible ROM breakpoint must not attempt ROM writes")) return 1; + if (expect(m.ram[FAKE_SENTINEL_ADDR] == 0x00, + "Unsupported visible ROM breakpoint must refuse before starting execution")) return 1; + return 0; +} + +static int test_visible_rom_breakpoint_go_patches_rom_not_underlying_ram() +{ + FakeVisibleRomMachine m(false); + fake_seed_rom_nop_run(m, 0xE000); + m.allow_visible_rom_patching = true; + m.ram[0xE001] = 0x6C; + + MonitorBreakpoints bps; + bps.allocate(0xE001, 0x07); + DebugContext from; + debug_context_reset(&from); + + // Model the run trapping at the installed breakpoint ($E001) so the relaunch + // backstop recognises a legitimate capture (see test_visible_basic_step note). + fake_seed_captured_context(m, 0xE001, 0xF8, 0x11, 0x22, 0x33, 0x24); + + DebugSession::Result r = m.go(from, &bps, 0xC000); + if (expect(r == DebugSession::DBG_OK, + "Visible ROM breakpoint Go must run when ROM patching is supported")) return 1; + if (expect(m.kernal_rom[1] == 0xEA, + "Visible ROM breakpoint Go must restore the ROM byte")) return 1; + if (expect(m.ram[0xE001] == 0x6C, + "Visible ROM breakpoint Go must not use RAM under ROM as proof")) return 1; + if (expect(m.rom_patch_writes == 3, + "Visible ROM breakpoint Go must patch, recommit at launch, and restore the ROM image")) return 1; + return 0; +} + +static int test_mixed_kernal_and_ram_breakpoints_patch_distinct_backing_stores() +{ + FakeVisibleRomMachine m(false); + m.allow_visible_rom_patching = true; + m.cpu_port = 0x05; // live CPU has KERNAL banked out + m.ram[0xC000] = 0xEA; + m.kernal_rom[0] = 0x4C; + m.ram[0xE000] = 0xEA; + + MonitorBreakpoints bps; + int krn = bps.allocate(0xE000, 0x07); + int ram = bps.allocate(0xE000, 0x05); + if (expect(krn != ram && krn >= 0 && ram >= 0, + "KERNAL and RAM-under-KERNAL breakpoints must coexist")) return 1; + bps.set_enabled(krn, false); + if (expect(!bps.get(krn)->enabled && bps.get(ram)->enabled, + "Disabling KERNAL breakpoint must leave RAM breakpoint enabled")) return 1; + bps.set_enabled(krn, true); + + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0xC000; + from.sp = 0xF7; + from.sr = 0x24; + + m.arm_capture_context(0xE000, 0xF5, 0, 0, 0, 0x24); + DebugSession::Result r = m.go(from, &bps, 0xC000); + if (expect(r == DebugSession::DBG_OK, + "Mixed KERNAL/RAM breakpoints must run and trap")) return 1; + if (expect(m.last_rom_patch_addr == 0xE000 && m.rom_patch_writes == 3, + "KERNAL breakpoint must patch, recommit at launch, and restore the ROM image")) return 1; + if (expect(m.last_ram_patch_addr == 0xE000 && m.ram_patch_writes == 1, + "RAM-under-KERNAL breakpoint must patch hidden RAM")) return 1; + if (expect(m.kernal_rom[0] == 0x4C && m.ram[0xE000] == 0xEA, + "Mixed breakpoint cleanup must restore both backing stores")) return 1; + + char row[40]; + MonitorBreakpoints::format_popup_row(row, sizeof(row), krn, bps.get(krn)); + if (expect(strstr(row, "$E000 KRN") != NULL, + "Breakpoint popup must distinguish the KERNAL target")) return 1; + MonitorBreakpoints::format_popup_row(row, sizeof(row), ram, bps.get(ram)); + if (expect(strstr(row, "$E000 RAM") != NULL, + "Breakpoint popup must distinguish the RAM target")) return 1; + return 0; +} + +static int test_patch_restore_uses_recorded_destination_after_cpu_bank_changes() +{ + FakeVisibleRomMachine m(false); + fake_seed_rom_nop_run(m, 0xE000); + m.allow_visible_rom_patching = true; + m.cpu_port = 0x07; + m.ram[0xE001] = 0x6C; + m.switch_cpu_port_on_delay = true; + m.cpu_port_after_delay = 0x05; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Visible KERNAL step must complete while live bank changes before cleanup")) return 1; + if (expect(m.cpu_port == 0x05, + "Test must change the live CPU bank before patch restoration")) return 1; + if (expect(m.kernal_rom[1] == 0xEA, + "Patch restoration must use the recorded KERNAL destination")) return 1; + if (expect(m.ram[0xE001] == 0x6C, + "Patch restoration must not recompute and restore into hidden RAM")) return 1; + + m.cleanup(); + m.cleanup(); + if (expect(m.kernal_rom[1] == 0xEA && m.ram[0xE001] == 0x6C, + "Patch cleanup must be idempotent after the bank changed")) return 1; + return 0; +} + +static int test_kernal_out_hard_vector_installs_and_restores_on_cleanup() +{ + FakeVisibleRomMachine m(false); + m.cpu_port = 0x05; + m.ram[FAKE_HARD_VECTOR_LO] = 0x34; + m.ram[FAKE_HARD_VECTOR_HI] = 0x12; + m.ram[0xE000] = 0xEA; + m.ram[0xE001] = 0xEA; + m.ram[0xE002] = 0xEA; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "RAM-under-KERNAL step must trap without Debug Timeout")) return 1; + if (expect(m.ram[FAKE_HARD_VECTOR_LO] == (uint8_t)(FAKE_HARD_BRK_STUB & 0xFF) && + m.ram[FAKE_HARD_VECTOR_HI] == (uint8_t)(FAKE_HARD_BRK_STUB >> 8), + "KERNAL-out hard IRQ/BRK vector must point at the debug stub while parked")) return 1; + if (expect(m.ram_patch_writes == 1 && m.last_ram_patch_addr == 0xE001, + "RAM-under-KERNAL step must patch hidden RAM fall-through")) return 1; + if (expect(m.ram[0xE001] == 0xEA, + "RAM-under-KERNAL patch byte must be restored after the step")) return 1; + + m.cleanup(); + if (expect(m.ram[FAKE_HARD_VECTOR_LO] == 0x34 && + m.ram[FAKE_HARD_VECTOR_HI] == 0x12, + "Cleanup must restore hidden-RAM hard vector bytes")) return 1; + return 0; +} + +static int test_kernal_out_hard_vector_restores_on_timeout() +{ + FakeVisibleRomMachine m(false); + m.cpu_port = 0x05; + m.ram[FAKE_HARD_VECTOR_LO] = 0x78; + m.ram[FAKE_HARD_VECTOR_HI] = 0x56; + m.ram[0xE000] = 0xEA; + m.ram[0xE001] = 0xEA; + m.ram[0xE002] = 0xEA; + m.sentinel_armed = false; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_TIMEOUT, + "Debug Timeout must remain a failure result")) return 1; + if (expect(m.ram[FAKE_HARD_VECTOR_LO] == 0x78 && + m.ram[FAKE_HARD_VECTOR_HI] == 0x56, + "Timeout cleanup must restore hidden-RAM hard vector bytes")) return 1; + if (expect(m.ram[0xE001] == 0xEA, + "Timeout cleanup must restore RAM-under-KERNAL patch bytes")) return 1; + return 0; +} + +static int test_visible_kernal_hard_vector_installs_and_restores() +{ + FakeVisibleRomMachine m(false); + m.cpu_port = 0x07; + m.allow_visible_rom_patching = true; + m.kernal_rom[0x1FFE] = 0x66; + m.kernal_rom[0x1FFF] = 0xFE; + m.kernal_rom[0x0000] = 0xEA; + m.kernal_rom[0x0001] = 0xEA; + m.kernal_rom[0x0002] = 0xEA; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "Visible KERNAL step must trap through the direct hard vector")) return 1; + if (expect(m.kernal_rom[0x1FFE] == (uint8_t)(FAKE_HARD_BRK_STUB & 0xFF) && + m.kernal_rom[0x1FFF] == (uint8_t)(FAKE_HARD_BRK_STUB >> 8), + "Visible KERNAL hard IRQ/BRK vector must point at the debug stub while parked")) return 1; + if (expect(m.kernal_rom[0x0001] == 0xEA, + "Visible KERNAL patch byte must be restored after the step")) return 1; + + m.cleanup(); + if (expect(m.kernal_rom[0x1FFE] == 0x66 && + m.kernal_rom[0x1FFF] == 0xFE, + "Cleanup must restore visible KERNAL hard vector bytes")) return 1; + return 0; +} + +static int test_stale_visible_kernal_hard_vector_is_recovered() +{ + FakeVisibleRomMachine m(false); + m.cpu_port = 0x07; + m.allow_visible_rom_patching = true; + m.kernal_rom[0x1FFE] = (uint8_t)(FAKE_HARD_BRK_STUB & 0xFF); + m.kernal_rom[0x1FFF] = (uint8_t)(FAKE_HARD_BRK_STUB >> 8); + m.ram[0xC000] = 0xEA; + m.ram[0xC001] = 0xEA; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xC000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xC000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "RAM-only debug step must recover a stale visible KERNAL hard vector")) return 1; + if (expect(m.kernal_rom[0x1FFE] == 0x48 && + m.kernal_rom[0x1FFF] == 0xFF, + "Stale visible KERNAL hard vector must be restored before RAM-only stepping")) return 1; + + m.cleanup(); + if (expect(m.kernal_rom[0x1FFE] == 0x48 && + m.kernal_rom[0x1FFF] == 0xFF, + "Cleanup must not reinstall the stale visible KERNAL hard vector")) return 1; + return 0; +} + +static int test_run_to_current_visible_kernal_jsr_enters_callee_before_rearming_cursor_breakpoint() +{ + FakeVisibleRomMachine m(true); + m.allow_visible_rom_patching = true; + m.cpu_port = 0x07; + m.kernal_rom[0x0000] = 0x20; // JSR $BC0F + m.kernal_rom[0x0001] = 0x0F; + m.kernal_rom[0x0002] = 0xBC; + m.kernal_rom[0x0003] = 0xEA; + m.basic_rom[0x1C0F] = 0xEA; + fake_seed_captured_context(m, 0xBC0F, 0xFD, 0, 0, 0, 0x24); + + DebugContext from; + debug_context_reset(&from); + from.valid = true; + from.pc = 0xE000; + from.sp = 0xF7; + from.sr = 0x24; + + DebugContext ctx; + DebugSession::Result r = m.run_to(from, 0xE000, 0, 0xE000, &ctx); + if (expect(r == DebugSession::DBG_OK, + "K Cursor from the current visible KERNAL JSR must run successfully")) return 1; + if (expect(m.brk_patch_writes >= 2, + "K Cursor current-row JSR must patch the callee and then re-arm the cursor breakpoint")) return 1; + if (expect(m.brk_patch_addrs[0] == 0xBC0F, + "K Cursor current-row JSR must first arm the callee target, not the fall-through")) return 1; + if (expect(fake_recorded_brk_patch(m, 0xE000), + "K Cursor current-row JSR must re-arm the transient cursor breakpoint afterwards")) return 1; + if (expect(!fake_recorded_brk_patch(m, 0xE003), + "K Cursor current-row JSR must not step over to the fall-through address")) return 1; + return 0; +} + +static int test_overlay_step_over_never_freezes() +{ + // Overlay-mode non-regression: the machine is never frozen, so the engine + // must neither unfreeze nor re-freeze, and must still complete the step. + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, "overlay step-over must complete")) return 1; + if (expect(!m.frozen, "overlay step-over must leave the machine unfrozen")) return 1; + if (expect(m.unfreeze_attempts == 0, "overlay step-over must not call the unfreeze hook")) return 1; + if (expect(m.unfreeze_calls == 0, "overlay step-over must not unfreeze")) return 1; + if (expect(m.refreeze_calls == 0, "overlay step-over must not re-freeze")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay step-over must not set screen_render_target_invalidated")) return 1; + return 0; +} + +static int test_overlay_accessible_unfrozen_step_over_does_not_unfreeze() +{ + // Hardware overlay access is not the same as freeze ownership. Even if a + // backend reports that an unfreeze operation would be "accessible", the + // run-window must not invoke it unless machine_is_frozen() was true. + FakeFreezeMachine m(false); + m.accessible_when_unfrozen = true; + m.break_on_unfrozen_unfreeze_attempt = true; + fake_seed_nop_run(m, 0x2000); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "overlay step-over must complete even if the unfreeze hook would be accessible")) return 1; + if (expect(m.unfreeze_attempts == 0, + "overlay run-window must not call unfreeze_if_accessible when not frozen")) return 1; + if (expect(m.unfreeze_calls == 0 && m.refreeze_calls == 0, + "overlay accessible/unfrozen step must not change freeze state")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay accessible/unfrozen step must not invalidate the render target")) return 1; + return 0; +} + +static int test_overlay_render_target_disables_stale_frozen_unfreeze() +{ + // The overlay UI is not the C64 freezer render target. If C64 accessibility + // state is stale/true for any reason, the overlay run-window policy must + // still prevent freeze ownership calls. + FakeFreezeMachine m(true); + m.set_run_window_refreeze_enabled(false); + fake_seed_nop_run(m, 0x2000); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.over_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "overlay render-target policy must still allow the BRK run")) return 1; + if (expect(m.frozen, + "overlay render-target policy must not change stale frozen state")) return 1; + if (expect(m.unfreeze_attempts == 0, + "overlay render-target policy must not call unfreeze even if machine_is_frozen is true")) return 1; + if (expect(m.unfreeze_calls == 0 && m.refreeze_calls == 0, + "overlay render-target policy must not touch freeze state")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay render-target policy must not invalidate the screen")) return 1; + return 0; +} + +static int test_overlay_step_into_never_freezes() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext c1; + if (expect(m.trace_at(0x2000, pred, &c1) == DebugSession::DBG_OK, + "overlay step-into must complete")) return 1; + DebugContext c2; + if (expect(m.trace_at(0x2000, pred, &c2) == DebugSession::DBG_OK, + "overlay repeated step-into must complete")) return 1; + if (expect(m.unfreeze_attempts == 0, "overlay step-into must not call the unfreeze hook")) return 1; + if (expect(m.unfreeze_calls == 0 && m.refreeze_calls == 0, + "overlay step-into must never touch freeze state")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay step-into must not invalidate the render target")) return 1; + return 0; +} + +static int test_overlay_step_out_never_freezes() +{ + FakeFreezeMachine m(false); + + m.ram[0x2001] = 0x20; + m.ram[0x2002] = 0x00; + m.ram[0x2003] = 0x30; + m.ram[0x2004] = 0xEA; + m.ram[0x3000] = 0xEA; + + uint8_t jsr[3] = { 0x20, 0x00, 0x30 }; + DebugPredictResult pred; + debug_predict(0x2001, jsr, false, &pred); + fake_seed_captured_context(m, 0x3000, 0xFB, 0, 0, 0, 0x24); + DebugContext from; + if (expect(m.trace_at(0x2001, pred, &from) == DebugSession::DBG_OK, + "overlay trace into JSR must prepare a Step Out target")) return 1; + m.unfreeze_attempts = 0; + m.unfreeze_calls = 0; + m.refreeze_calls = 0; + m.ram[FAKE_SENTINEL_ADDR] = 0x00; + m.arm_capture_context(0x2004, 0xFD, 0, 0, 0, 0x24); + + DebugContext ctx; + DebugSession::Result r = m.step_out(from, &ctx); + if (expect(r == DebugSession::DBG_OK, "overlay step-out must complete for a valid JSR frame")) return 1; + if (expect(m.unfreeze_attempts == 0, "overlay step-out must not call the unfreeze hook")) return 1; + if (expect(m.unfreeze_calls == 0 && m.refreeze_calls == 0, + "overlay step-out must never touch freeze state")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay step-out must not invalidate the render target")) return 1; + return 0; +} + +static int test_overlay_go_breakpoint_never_freezes() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + + MonitorBreakpoints bps; + bps.allocate(0x2001, 0x07); + + DebugContext from; + debug_context_reset(&from); + + DebugSession::Result r = m.go(from, &bps, 0x2000); + if (expect(r == DebugSession::DBG_OK, "overlay Go-to-breakpoint must complete")) return 1; + if (expect(m.unfreeze_attempts == 0, "overlay Go must not call the unfreeze hook")) return 1; + if (expect(m.unfreeze_calls == 0 && m.refreeze_calls == 0, + "overlay Go must never touch freeze state")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay Go must not invalidate the render target")) return 1; + return 0; +} + +// Two consecutive overlay steps must each complete and must never touch the +// freeze bracketing. A leaked run-window depth or a stale run_window_unfroze +// from step 1 would change step 2's behaviour (or, in freeze mode, skip the +// unfreeze); proving both steps run with zero unfreeze/refreeze and a clean +// invalidated flag is the strongest overlay non-regression we can model. +static int test_overlay_two_consecutive_steps_never_freeze() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext c1; + if (expect(m.over_at(0x2000, pred, &c1) == DebugSession::DBG_OK, + "overlay step 1 must complete")) return 1; + DebugContext c2; + if (expect(m.over_at(0x2000, pred, &c2) == DebugSession::DBG_OK, + "overlay step 2 must complete (run-window depth recovered)")) return 1; + if (expect(!m.frozen, "overlay steps must leave the machine unfrozen")) return 1; + if (expect(m.unfreeze_attempts == 0, "overlay steps must never call the unfreeze hook")) return 1; + if (expect(m.unfreeze_calls == 0, "overlay steps must never unfreeze")) return 1; + if (expect(m.refreeze_calls == 0, "overlay steps must never re-freeze")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay steps must not invalidate the render target")) return 1; + return 0; +} + +static int test_overlay_cursor_step_from_parked_spin_uses_release_path() +{ + FakeFreezeMachine m(false); + m.nmi_from_spin_times_out = true; + m.ram[0x2000] = 0xEE; // INC $D020 + m.ram[0x2001] = 0x20; + m.ram[0x2002] = 0xD0; + m.ram[0x2003] = 0x4C; // JMP $2000 + m.ram[0x2004] = 0x00; + m.ram[0x2005] = 0x20; + + uint8_t inc_bytes[3] = { 0xEE, 0x20, 0xD0 }; + DebugPredictResult inc_pred; + debug_predict(0x2000, inc_bytes, false, &inc_pred); + m.arm_capture_context(0x2003, 0xF7, 0, 0, 0, 0x24); + DebugContext c1; + if (expect(m.over_at(0x2000, inc_pred, &c1) == DebugSession::DBG_OK, + "overlay INC step must park at JMP")) return 1; + if (expect(c1.valid && c1.pc == 0x2003, + "overlay INC step must capture $2003")) return 1; + + uint8_t jmp_bytes[3] = { 0x4C, 0x00, 0x20 }; + DebugPredictResult jmp_pred; + debug_predict(0x2003, jmp_bytes, false, &jmp_pred); + m.arm_capture_context(0x2000, 0xF7, 0, 0, 0, 0x24); + DebugContext c2; + if (expect(m.over_at(0x2003, jmp_pred, &c2) == DebugSession::DBG_OK, + "cursor-driven overlay step from parked spin must not NMI-timeout")) return 1; + if (expect(c2.valid && c2.pc == 0x2000, + "overlay JMP step must capture $2000")) return 1; + if (expect(!m.frozen, "overlay loop steps must leave the machine unfrozen")) return 1; + if (expect(m.unfreeze_calls == 0 && m.refreeze_calls == 0, + "overlay loop steps must never touch freeze state")) return 1; + return 0; +} + +// Two consecutive freeze steps must each unfreeze-then-refreeze exactly once. +// If step 1 leaked the run-window depth, step 2's outermost begin_run_window +// would not fire (depth != 0) and the second unfreeze/refreeze would be lost, +// dropping the counts below two. This pins the balance across steps. +static int test_freeze_two_consecutive_steps_rebalance() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2000); + m.stamp_screen_sentinel(0x55, 40); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext c1; + if (expect(m.over_at(0x2000, pred, &c1) == DebugSession::DBG_OK, + "freeze step 1 must complete")) return 1; + if (expect(m.frozen, "freeze step 1 must leave the machine re-frozen")) return 1; + DebugContext c2; + if (expect(m.over_at(0x2000, pred, &c2) == DebugSession::DBG_OK, + "freeze step 2 must complete")) return 1; + if (expect(m.frozen, "freeze step 2 must leave the machine re-frozen")) return 1; + if (expect(m.unfreeze_calls == 2, "two freeze steps must unfreeze twice")) return 1; + if (expect(m.refreeze_calls == 2, "two freeze steps must re-freeze twice")) return 1; + if (expect(m.screen_sentinel_intact(0x55, 40), + "freeze steps must never write into C64 screen RAM")) return 1; + return 0; +} + +// A timed-out overlay step must release control (DBG_TIMEOUT, not a hang) and +// leave the run-window depth at zero so a later step still works. It must also +// never freeze the machine on the failure path. +static int test_overlay_step_timeout_then_recovers() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + m.sentinel_armed = false; // force the wait loop to its timeout + DebugContext c1; + if (expect(m.over_at(0x2000, pred, &c1) == DebugSession::DBG_TIMEOUT, + "overlay step must return DBG_TIMEOUT, never hang")) return 1; + if (expect(!m.frozen, "overlay timeout must not freeze the machine")) return 1; + if (expect(m.unfreeze_attempts == 0, "overlay timeout must not call the unfreeze hook")) return 1; + if (expect(m.refreeze_calls == 0, "overlay timeout must not re-freeze")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay timeout must not invalidate the render target")) return 1; + + m.sentinel_armed = true; // engine recovers; depth must be back at zero + DebugContext c2; + if (expect(m.over_at(0x2000, pred, &c2) == DebugSession::DBG_OK, + "overlay step after timeout must complete (depth recovered)")) return 1; + if (expect(m.unfreeze_calls == 0 && m.refreeze_calls == 0, + "overlay timeout+recovery must never touch freeze state")) return 1; + if (expect(!m.screen_render_target_invalidated(), + "overlay timeout+recovery must leave render-target invalidation clear")) return 1; + return 0; +} + +// A timed-out freeze step must still re-freeze on the failure path (so the +// monitor render target is preserved) and recover its run-window depth so the +// next step unfreezes/refreezes again. +static int test_freeze_step_timeout_refreezes_and_recovers() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2000); + m.stamp_screen_sentinel(0x66, 40); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + m.sentinel_armed = false; // force timeout + DebugContext c1; + if (expect(m.over_at(0x2000, pred, &c1) == DebugSession::DBG_TIMEOUT, + "freeze step must return DBG_TIMEOUT, never hang")) return 1; + if (expect(m.frozen, + "freeze timeout must re-freeze before returning to the monitor")) return 1; + if (expect(m.unfreeze_attempts == 1 && m.unfreeze_calls == 1 && m.refreeze_calls == 1, + "freeze timeout must balance its unfreeze with a re-freeze")) return 1; + if (expect(m.screen_render_target_invalidated(), + "freeze timeout must invalidate the render target after refreeze")) return 1; + + m.sentinel_armed = true; + DebugContext c2; + if (expect(m.over_at(0x2000, pred, &c2) == DebugSession::DBG_OK, + "freeze step after timeout must complete (depth recovered)")) return 1; + if (expect(m.frozen, "freeze step after timeout must re-freeze")) return 1; + if (expect(m.unfreeze_calls == 2 && m.refreeze_calls == 2, + "freeze timeout+recovery must rebalance to two unfreeze/refreeze")) return 1; + if (expect(m.screen_sentinel_intact(0x66, 40), + "freeze timeout must never write into C64 screen RAM")) return 1; + return 0; +} + +static int test_cleanup_resume_trampoline_restores_full_context() +{ + FakeFreezeMachine m(false); + fake_seed_nop_run(m, 0x2000); + fake_seed_captured_context(m, 0x2001, 0xF9, 0x42, 0x17, 0x99, 0xA4); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext next; + if (expect(m.over_at(0x2000, pred, &next) == DebugSession::DBG_OK, + "Setup step must succeed before cleanup")) return 1; + + m.cleanup(); + + if (expect(m.ram[FAKE_SPIN_LO] == (uint8_t)(FAKE_RESUME_TRAMP & 0xFF) && + m.ram[FAKE_SPIN_HI] == (uint8_t)(FAKE_RESUME_TRAMP >> 8), + "Cleanup must retarget the parked CPU to the resume trampoline")) return 1; + if (expect(m.ram[FAKE_RESUME_TRAMP + 0] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 1] == 0x07 && + m.ram[FAKE_RESUME_TRAMP + 2] == 0x85 && + m.ram[FAKE_RESUME_TRAMP + 3] == 0x00 && + m.ram[FAKE_RESUME_TRAMP + 4] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 5] == 0x07 && + m.ram[FAKE_RESUME_TRAMP + 6] == 0x85 && + m.ram[FAKE_RESUME_TRAMP + 7] == 0x01, + "Cleanup trampoline must restore captured $00/$01 before returning")) return 1; + if (expect(m.ram[FAKE_RESUME_TRAMP + 8] == 0xA2 && + m.ram[FAKE_RESUME_TRAMP + 9] == 0xF9 && + m.ram[FAKE_RESUME_TRAMP + 10] == 0x9A, + "Cleanup trampoline must restore SP before returning")) return 1; + if (expect(m.ram[FAKE_RESUME_TRAMP + 11] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 12] == 0x20 && + m.ram[FAKE_RESUME_TRAMP + 14] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 15] == 0x01 && + m.ram[FAKE_RESUME_TRAMP + 17] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 18] == 0xA4, + "Cleanup trampoline must push PCH, PCL, then SR for RTI")) return 1; + if (expect(m.ram[FAKE_RESUME_TRAMP + 14] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 15] == 0x01, + "Cleanup trampoline must include the captured PC low byte")) return 1; + if (expect(m.ram[FAKE_RESUME_TRAMP + 20] == 0xA0 && + m.ram[FAKE_RESUME_TRAMP + 21] == 0x99 && + m.ram[FAKE_RESUME_TRAMP + 22] == 0xA2 && + m.ram[FAKE_RESUME_TRAMP + 23] == 0x17 && + m.ram[FAKE_RESUME_TRAMP + 24] == 0xA9 && + m.ram[FAKE_RESUME_TRAMP + 25] == 0x42 && + m.ram[FAKE_RESUME_TRAMP + 26] == 0x40, + "Cleanup trampoline must restore Y, X, A and finish with RTI")) return 1; + return 0; +} + +// Regression for the step-mode stack side effect: the NMI used to launch a run +// pushes a 3-byte frame (PCH/PCL/SR). Because we resume with a JMP, that frame +// must be pulled back off inside the trampoline so the program's SP - and hence +// every subsequent push such as a JSR return address - is exactly what an +// undebugged run would have. The trampoline must therefore begin with PLA x3 +// and end with a JMP to the launch target. +static int test_nmi_launch_trampoline_balances_stack() +{ + FakeFreezeMachine m(true); // freeze: first step launches via NMI + fake_seed_nop_run(m, 0x2000); // NOP at 0x2000, fall-through 0x2001 + m.arm_capture_context(0x2001, 0xF7, 0, 0, 0, 0); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, "NMI-launched step must complete")) return 1; + if (expect(m.nmi_pulses == 1, "First step must launch via exactly one NMI")) return 1; + + // PLA x3 up front discards the NMI frame so SP is left balanced. + if (expect(m.ram[FAKE_NMI_TRAMP + 0] == 0x68 && + m.ram[FAKE_NMI_TRAMP + 1] == 0x68 && + m.ram[FAKE_NMI_TRAMP + 2] == 0x68, + "NMI trampoline must pull its 3-byte frame to keep SP balanced")) return 1; + // The trampoline must still redirect to the launch target (JMP $2000). + if (expect(m.ram[FAKE_NMI_TRAMP + 13] == 0x4C && + m.ram[FAKE_NMI_TRAMP + 14] == 0x00 && + m.ram[FAKE_NMI_TRAMP + 15] == 0x20, + "NMI trampoline must JMP to the launch target after balancing SP")) return 1; + return 0; +} + +static int test_kernal_out_cold_nmi_launch_installs_hard_nmi_vector() +{ + FakeVisibleRomMachine m(false); + m.cpu_port = 0x05; + m.ram[FAKE_HARD_NMI_VECTOR_LO] = 0x34; + m.ram[FAKE_HARD_NMI_VECTOR_HI] = 0x12; + fake_seed_nop_run(m, 0xE000); + // Model the trap at the installed fall-through BRK $E001 (the relaunch backstop + // requires the captured PC to be at an installed BRK). + fake_seed_captured_context(m, 0xE001, 0xF0, 0x11, 0x22, 0x33, 0x24); + m.arm_hard_vector_capture_context(0xE001, 0xF0, 0x11, 0x22, 0x33, 0x24, + 0x37, 0x35); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_OK, + "KERNAL-out cold NMI launch must complete")) return 1; + if (expect(m.nmi_pulses == 1, + "Cold no-context KERNAL-out step must launch via NMI")) return 1; + if (expect(m.ram[FAKE_HARD_NMI_VECTOR_LO] == (uint8_t)(FAKE_NMI_TRAMP & 0xFF) && + m.ram[FAKE_HARD_NMI_VECTOR_HI] == (uint8_t)(FAKE_NMI_TRAMP >> 8), + "KERNAL-out NMI hard vector must point at the debug trampoline while parked")) return 1; + if (expect(ctx.valid && ctx.pc == 0xE001 && ctx.live_cpu_port == 0x05, + "KERNAL-out cold NMI launch must capture the RAM-under-KERNAL stop")) return 1; + + m.cleanup(); + if (expect(m.ram[FAKE_HARD_NMI_VECTOR_LO] == 0x34 && + m.ram[FAKE_HARD_NMI_VECTOR_HI] == 0x12, + "Cleanup must restore hidden-RAM NMI hard vector bytes")) return 1; + return 0; +} + +static int test_kernal_out_cold_nmi_launch_restores_hard_nmi_vector_on_timeout() +{ + FakeVisibleRomMachine m(false); + m.cpu_port = 0x05; + m.ram[FAKE_HARD_NMI_VECTOR_LO] = 0x78; + m.ram[FAKE_HARD_NMI_VECTOR_HI] = 0x56; + fake_seed_nop_run(m, 0xE000); + m.sentinel_armed = false; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0xE000, bytes, false, &pred); + + DebugContext ctx; + DebugSession::Result r = m.trace_at(0xE000, pred, &ctx); + if (expect(r == DebugSession::DBG_TIMEOUT, + "KERNAL-out cold NMI timeout must remain a failure")) return 1; + if (expect(m.ram[FAKE_HARD_NMI_VECTOR_LO] == 0x78 && + m.ram[FAKE_HARD_NMI_VECTOR_HI] == 0x56, + "Timeout cleanup must restore hidden-RAM NMI hard vector bytes")) return 1; + return 0; +} + +static int test_freeze_cleanup_after_step_allows_later_step() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2100); + fake_seed_captured_context(m, 0x2101, 0xF3, 0x33, 0x44, 0x55, 0x66); + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2100, bytes, false, &pred); + + DebugContext next; + if (expect(m.over_at(0x2100, pred, &next) == DebugSession::DBG_OK, + "Initial frozen step must succeed")) return 1; + + m.cleanup(); + + if (expect(m.unfreeze_calls == 1 && m.refreeze_calls == 1, + "Cleanup must preserve the balanced freeze run-window counts")) return 1; + if (expect(m.ram[FAKE_SPIN_LO] == (uint8_t)(FAKE_RESUME_TRAMP & 0xFF) && + m.ram[FAKE_SPIN_HI] == (uint8_t)(FAKE_RESUME_TRAMP >> 8), + "Frozen cleanup must stage a future resume path instead of leaving the spin loop stale")) return 1; + + fake_seed_nop_run(m, 0x2200); + fake_seed_captured_context(m, 0x2201, 0xF2, 0x11, 0x22, 0x33, 0x44); + debug_predict(0x2200, bytes, false, &pred); + if (expect(m.over_at(0x2200, pred, &next) == DebugSession::DBG_OK, + "A later frozen step must still work after cleanup")) return 1; + return 0; +} + +static int test_freeze_cleanup_preserves_resume_bytes_across_unfreeze_restore() +{ + FakeFreezeMachine m(true); + fake_seed_nop_run(m, 0x2100); + fake_seed_captured_context(m, 0x2101, 0xF3, 0x33, 0x44, 0x55, 0x66); + m.ram[FAKE_STORE_CPU_DDR] = 0x37; + m.ram[FAKE_STORE_CPU_PORT] = 0x35; + + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + debug_predict(0x2100, bytes, false, &pred); + + DebugContext next; + if (expect(m.over_at(0x2100, pred, &next) == DebugSession::DBG_OK, + "Initial frozen step with CPU5 context must succeed")) return 1; + + m.reset_freeze_restore_pokes(); + m.cleanup(); + + if (expect(m.recorded_freeze_restore_poke(FAKE_STORE_CPU_DDR, 0x37) && + m.recorded_freeze_restore_poke(FAKE_STORE_CPU_PORT, 0x35), + "Frozen cleanup must preserve captured CPU-port stores across unfreeze restore")) return 1; + if (expect(m.recorded_freeze_restore_poke(0x0000, 0x37) && + m.recorded_freeze_restore_poke(0x0001, 0x35), + "Frozen cleanup must preserve actual $00/$01 across unfreeze restore")) return 1; + if (expect(m.recorded_freeze_restore_poke(FAKE_RESUME_TRAMP + 0, 0xA9) && + m.recorded_freeze_restore_poke(FAKE_RESUME_TRAMP + 1, 0x37) && + m.recorded_freeze_restore_poke(FAKE_RESUME_TRAMP + 4, 0xA9) && + m.recorded_freeze_restore_poke(FAKE_RESUME_TRAMP + 5, 0x35), + "Frozen cleanup must preserve the CPU-executed $00/$01 restore stub")) return 1; + if (expect(m.recorded_freeze_restore_poke(FAKE_SPIN_LO, + (uint8_t)(FAKE_RESUME_TRAMP & 0xFF)) && + m.recorded_freeze_restore_poke(FAKE_SPIN_HI, + (uint8_t)(FAKE_RESUME_TRAMP >> 8)), + "Frozen cleanup must preserve the spin redirection across unfreeze restore")) return 1; + return 0; +} + +static int test_freeze_go_without_breakpoint_defers_handoff_until_after_exit() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_OK; + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xC123; + backend.canned_snapshot.sp = 0xF1; + backend.canned_snapshot.a = 0x11; + backend.canned_snapshot.x = 0x22; + backend.canned_snapshot.y = 0x33; + backend.canned_snapshot.sr = 0x44; + backend.parked_context_handoff_supported = true; + backend.write(0xC123, 0xEA); + + const int keys[] = { 'A', 'D', 'G' }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_debug_run_window_refreeze_enabled(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 1, + "Freeze-mode G without breakpoints must unwind out of the monitor")) return 1; + if (expect(backend.last_session && backend.last_session->go_calls == 0, + "Freeze no-breakpoint G must defer execution instead of calling session->go immediately")) return 1; + + if (expect(monitor.has_deferred_debug_go(), + "Freeze no-breakpoint G must mark a deferred debug handoff after exit")) return 1; + if (expect(!monitor.consume_pending_go(NULL, NULL, NULL), + "Freeze no-breakpoint G must not use the generic pending-Go handoff channel")) return 1; + if (expect(monitor.consume_release_host_after_exit(), + "Freeze no-breakpoint G must request host release after exit")) return 1; + if (expect(!monitor.consume_reopen_after_reset(), + "Freeze no-breakpoint G exit must not look like reset re-entry")) return 1; + monitor.dispatch_deferred_debug_go(); + if (expect(!monitor.has_deferred_debug_go(), + "Dispatching the deferred Freeze no-breakpoint G must clear the deferred-debug flag")) return 1; + monitor.deinit(); + return 0; +} + +static int test_direct_overlay_go_without_breakpoint_releases_context_and_exits() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_OK; + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xC123; + backend.canned_snapshot.sp = 0xF1; + backend.canned_snapshot.a = 0x11; + backend.canned_snapshot.x = 0x22; + backend.canned_snapshot.y = 0x33; + backend.canned_snapshot.sr = 0x44; + backend.write(0xC123, 0xEA); + + const int keys[] = { 'A', 'D', 'G' }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_reset_exits_monitor(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 1, + "Direct Overlay G without breakpoints must unwind out of the monitor")) return 1; + if (expect(backend.last_session && backend.last_session->go_calls == 1, + "Direct Overlay no-breakpoint G must release through the debug session")) return 1; + + DebugContext go_ctx; + bool has_ctx = false; + uint16_t go_addr = 0; + if (expect(!monitor.consume_pending_go(&go_addr, &go_ctx, &has_ctx), + "Direct Overlay no-breakpoint G must not schedule a second handoff")) return 1; + if (expect(monitor.consume_release_host_after_exit(), + "Direct Overlay no-breakpoint G must request host release after exit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_direct_go_exits_monitor_and_requests_host_release() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_OK; + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xE006; + backend.canned_snapshot.sp = 0xF1; + backend.canned_snapshot.sr = 0x44; + backend.canned_snapshot.live_cpu_port_valid = true; + backend.canned_snapshot.live_cpu_port = 0x05; + backend.write(0xE006, 0x4C); + backend.write(0xE007, 0x00); + backend.write(0xE008, 0xE0); + + const int keys[] = { 'A', 'D', 'G' }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_reset_exits_monitor(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 1, + "Direct G must unwind out of the monitor")) return 1; + if (expect(!monitor.consume_pending_go(NULL, NULL, NULL), + "Direct G must not schedule a second handoff")) return 1; + if (expect(monitor.consume_release_host_after_exit(), + "Direct G must request host release after exit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_freeze_go_with_breakpoint_still_uses_session_go() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.snapshot_result = DebugSession::DBG_NOT_SUPPORTED; + backend.write(0x0801, 0xEA); + + const int keys[] = { 'A', 'D', 'R', 'G' }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.set_debug_run_window_refreeze_enabled(true); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + if (expect(monitor.poll(0) == 0, "Toggle breakpoint ok")) return 1; + if (expect(monitor.poll(0) == 0, "Freeze G with breakpoint should stay in monitor")) return 1; + if (expect(backend.last_session && backend.last_session->go_calls == 1, + "Freeze G with a breakpoint must still run through session->go")) return 1; + if (expect(!monitor.consume_pending_go(NULL, NULL, NULL), + "Breakpoint Go must not schedule the no-breakpoint exit path")) return 1; + monitor.deinit(); + return 0; +} + +static int test_wait_for_sentinel_drops_execution_keys() +{ + TestUserInterface ui; + CaptureScreen screen; + BrkSessionBackend backend(false); + monitor_reset_saved_state(); + + const int keys[] = { 'J', 'A', 'D', 'T', 'T', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 7); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("0801", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Jump setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Initial trace should return 0")) return 1; + if (expect(backend.last_session != NULL, "Trace must create the BRK session")) return 1; + int brk_patches_after_trace = backend.last_session->brk_patch_writes; + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug after the trace")) return 1; + if (expect(backend.last_session->brk_patch_writes == brk_patches_after_trace, + "Trace wait must drop repeated execution keys instead of replaying them")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_wait_for_sentinel_aborts_immediately_on_reset_cancel() +{ + FakeFreezeMachine m(false); + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + DebugContext ctx; + + fake_seed_nop_run(m, 0x2000); + m.sentinel_armed = false; + m.reset_cancel_on_delay = true; + debug_predict(0x2000, bytes, false, &pred); + DebugSession::Result r = m.trace_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_RESET, + "Sentinel wait must return DBG_RESET when reset cancellation is requested")) return 1; + if (expect(m.delay_calls == 1, + "Reset cancellation must stop the wait immediately instead of running to timeout")) return 1; + if (expect(m.reset_calls == 0, + "External reset cancellation must not issue a second machine reset")) return 1; + return 0; +} + +static int test_request_reset_cancel_clears_state_and_makes_handler_pokes_during_delay() +{ + FakeFreezeMachine m(false); + uint8_t bytes[3] = { 0xEA, 0xEA, 0xEA }; + DebugPredictResult pred; + DebugContext ctx; + + // Arrange: a trace installs the BRK handler. The sentinel never fires, + // and the external-cancel signal is delivered inside delay_ms(), simulating + // the REST task calling request_reset_cancel() while the UI task is + // suspended in vTaskDelay on real FreeRTOS hardware. + fake_seed_nop_run(m, 0x2000); + m.sentinel_armed = false; + m.reset_cancel_on_delay = true; + debug_predict(0x2000, bytes, false, &pred); + int pokes_before = m.freeze_restore_pokes; + DebugSession::Result r = m.trace_at(0x2000, pred, &ctx); + if (expect(r == DebugSession::DBG_RESET, + "Sentinel wait must return DBG_RESET on external cancel")) return 1; + // With synchronous teardown in request_reset_cancel(), the handler is + // uninstalled (via poke_visible_preserving_freeze_restore) during the + // delay_ms() call itself, before the second uninstall attempt from + // wait_for_sentinel() (which becomes a no-op). The poke count must be + // non-zero, proving teardown occurred. + if (expect(m.freeze_restore_pokes > pokes_before, + "request_reset_cancel must uninstall the handler (poke_visible calls expected)")) return 1; + if (expect(m.pokes_at_cancel == m.freeze_restore_pokes, + "All handler pokes must complete inside request_reset_cancel before machine reset fires")) return 1; + if (expect(m.reset_calls == 0, + "External reset cancellation must not issue a second machine reset")) return 1; + if (expect(m.delay_calls == 1, + "Wait must stop after the first delay once cancel is signalled")) return 1; + return 0; +} + +static int test_debug_ownership_blocks_second_stakeholder_until_remote_expires() +{ + FakeFreezeMachine telnet_owner(false); + FakeFreezeMachine local_owner(false); + FakeFreezeMachine leaked_local_owner(false); + FakeFreezeMachine reclaiming_telnet_owner(false); + + set_fake_ms_timer(100); + if (expect(telnet_owner.claim_debug_ownership(true), + "Initial remote stakeholder must claim debug ownership")) return 1; + advance_fake_ms_timer(1000); + if (expect(!local_owner.claim_debug_ownership(false), + "A second stakeholder must be blocked while the remote owner is still fresh")) return 1; + advance_fake_ms_timer(2501); + if (expect(local_owner.claim_debug_ownership(false), + "A stale remote owner must expire so a new stakeholder can claim Debug")) return 1; + local_owner.release_debug_ownership(); + telnet_owner.release_debug_ownership(); + + set_fake_ms_timer(1000); + if (expect(leaked_local_owner.claim_debug_ownership(false), + "Initial local stakeholder must claim debug ownership")) return 1; + advance_fake_ms_timer(3501); + if (expect(reclaiming_telnet_owner.claim_debug_ownership(true), + "A stale local owner must expire so a later telnet session can claim Debug")) return 1; + reclaiming_telnet_owner.release_debug_ownership(); + leaked_local_owner.release_debug_ownership(); + return 0; +} + +static int test_monitor_refuses_debug_when_owner_is_busy() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + backend.session_claim_allowed = false; + + const int keys[] = { 'A', 'D', KEY_BREAK }; + FakeKeyboard keyboard(keys, 3); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Blocked Debug entry should stay in the monitor")) return 1; + if (expect(strcmp(ui.last_popup, "DEBUG IN USE") == 0, + "Busy debug ownership must surface a clear popup")) return 1; + if (expect(backend.last_session && backend.last_session->claim_calls == 1, + "Debug entry must attempt to claim ownership exactly once")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP should exit once Debug was refused")) return 1; + monitor.deinit(); + return 0; +} + +static int test_cursor_row_highlights_jsr_target() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + ui.color_fg = 12; + + backend.write(0x1000, 0x20); + backend.write(0x1001, 0x34); + backend.write(0x1002, 0x12); + backend.write(0x1003, 0xEA); + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x1000; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.a = 0x00; + backend.canned_snapshot.x = 0x00; + backend.canned_snapshot.y = 0x00; + backend.canned_snapshot.sr = 0x20; + + const int keys[] = { 'A', 'D', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Breakpoint on JSR row should return 0")) return 1; + + char row[40]; + int row_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strncmp(row, "1000", 4) == 0) { + row_y = y; + break; + } + } + if (expect(row_y >= 0, "Current JSR row must be visible")) return 1; + const char *target = strstr(row, "$1234"); + if (expect(target != NULL, "JSR row must display the target address")) return 1; + const char *label = strstr(row, "[BRK0]"); + if (expect(label != NULL, "JSR row with breakpoint must display the breakpoint label")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + const char *dbg = strstr(header, "Dbg"); + if (expect(dbg != NULL, "Header must show the Dbg badge")) return 1; + uint8_t accent = screen.colors[3][1 + (int)(dbg - header)]; + int x = 1 + (int)(target - row); + for (int i = 0; i < 5; i++) { + if (expect(screen.colors[row_y][x + i] == accent, + "Current JSR target must use the accent colour")) return 1; + } + x = 1 + (int)(label - row); + for (int i = 0; i < 6; i++) { + if (expect(screen.colors[row_y][x + i] == accent, + "Breakpoint label must remain accented on a highlighted JSR row")) return 1; + } + + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_cursor_row_highlights_jmp_target() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + ui.color_fg = 12; + + backend.write(0x1000, 0x4C); + backend.write(0x1001, 0x34); + backend.write(0x1002, 0x12); + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x1000; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.sr = 0x20; + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + + char row[40]; + int row_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strncmp(row, "1000", 4) == 0) { + row_y = y; + break; + } + } + if (expect(row_y >= 0, "Current JMP row must be visible")) return 1; + const char *target = strstr(row, "$1234"); + if (expect(target != NULL, "JMP row must display the target address")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + const char *dbg = strstr(header, "Dbg"); + if (expect(dbg != NULL, "Header must show the Dbg badge")) return 1; + uint8_t accent = screen.colors[3][1 + (int)(dbg - header)]; + int x = 1 + (int)(target - row); + for (int i = 0; i < 5; i++) { + if (expect(screen.colors[row_y][x + i] == accent, + "Current JMP target must use the accent colour")) return 1; + } + + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +static int test_cursor_row_highlights_taken_branch_target_only_when_taken() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + ui.color_fg = 12; + + backend.write(0x1000, 0xD0); + backend.write(0x1001, 0x05); + backend.write(0x1002, 0xEA); + backend.write(0x1007, 0xEA); + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x1000; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.a = 0x00; + backend.canned_snapshot.x = 0x00; + backend.canned_snapshot.y = 0x00; + backend.canned_snapshot.sr = 0x20; + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + + char row[40]; + int row_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strncmp(row, "1000", 4) == 0) { + row_y = y; + break; + } + } + if (expect(row_y >= 0, "Current branch row must be visible")) return 1; + const char *target = strstr(row, "$1007"); + if (expect(target != NULL, "Branch row must display the branch target")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + const char *dbg = strstr(header, "Dbg"); + if (expect(dbg != NULL, "Header must show the Dbg badge")) return 1; + uint8_t accent = screen.colors[3][1 + (int)(dbg - header)]; + int x = 1 + (int)(target - row); + for (int i = 0; i < 5; i++) { + if (expect(screen.colors[row_y][x + i] == accent, + "Taken branch target must use the accent colour")) return 1; + } + + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + + backend.canned_snapshot.sr = 0x22; + CaptureScreen not_taken_screen; + FakeKeyboard not_taken_keyboard(keys, 4); + ui.screen = ¬_taken_screen; + ui.keyboard = ¬_taken_keyboard; + BackendMachineMonitor not_taken_monitor(&ui, &backend); + not_taken_monitor.init(¬_taken_screen, ¬_taken_keyboard); + if (expect(not_taken_monitor.poll(0) == 0, "ASM setup (not taken) should return 0")) return 1; + if (expect(not_taken_monitor.poll(0) == 0, "Debug entry (not taken) should return 0")) return 1; + row_y = -1; + for (int y = 0; y < 25; y++) { + not_taken_screen.get_slice(1, y, 38, row); + if (strncmp(row, "1000", 4) == 0) { + row_y = y; + break; + } + } + if (expect(row_y >= 0, "Current branch row (not taken) must be visible")) return 1; + target = strstr(row, "$1007"); + if (expect(target != NULL, "Branch row (not taken) must display the target")) return 1; + x = 1 + (int)(target - row); + for (int i = 0; i < 5; i++) { + if (expect(not_taken_screen.colors[row_y][x + i] == ui.color_fg, + "Untaken branch target must stay in the normal foreground colour")) return 1; + } + if (expect(not_taken_monitor.poll(0) == 0, "RUN/STOP should leave Debug (not taken)")) return 1; + if (expect(not_taken_monitor.poll(0) == 1, "Final RUN/STOP should exit (not taken)")) return 1; + not_taken_monitor.deinit(); + return 0; +} + +// On the debug PC row, an RTS must show the return address inferred from the +// stack ($XXXX) and highlight it like any other jump/branch target. +static int test_debug_rts_shows_inferred_target() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + ui.color_fg = 12; + + backend.write(0x2000, 0x60); // RTS + backend.write(0x2001, 0xEA); + // Return frame on the stack: SP=0xFB, so RTS pulls $01FC/$01FD = $3322 and + // resumes at $3322 + 1 = $3323. + backend.write(0x01FC, 0x22); + backend.write(0x01FD, 0x33); + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x2000; + backend.canned_snapshot.sp = 0xFB; + backend.canned_snapshot.sr = 0x20; + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + + char row[40]; + int row_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strncmp(row, "2000", 4) == 0) { row_y = y; break; } + } + if (expect(row_y >= 0, "RTS row must be visible")) return 1; + if (expect(strstr(row, "RTS $3323") != NULL, + "RTS must show the inferred return target")) return 1; + char header[40]; + screen.get_slice(1, 3, 38, header); + const char *dbg = strstr(header, "Dbg"); + if (expect(dbg != NULL, "Header must show the Dbg badge")) return 1; + uint8_t accent = screen.colors[3][1 + (int)(dbg - header)]; + const char *target = strstr(row, "$3323"); + int x = 1 + (int)(target - row); + for (int i = 0; i < 5; i++) { + if (expect(screen.colors[row_y][x + i] == accent, + "RTS inferred target must use the accent colour")) return 1; + } + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +// With an empty stack (SP=0xFF) there is no return address to infer, so RTS +// shows $???? instead. +static int test_debug_rts_empty_stack_shows_unknown() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + ui.color_fg = 12; + + backend.write(0x2000, 0x60); // RTS + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x2000; + backend.canned_snapshot.sp = 0xFF; // empty stack + backend.canned_snapshot.sr = 0x20; + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + + char row[40]; + int row_y = -1; + for (int y = 0; y < 25; y++) { + screen.get_slice(1, y, 38, row); + if (strncmp(row, "2000", 4) == 0) { row_y = y; break; } + } + if (expect(row_y >= 0, "RTS row must be visible")) return 1; + if (expect(strstr(row, "RTS $????") != NULL, + "RTS with empty stack must show $????")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +// The next-to-execute instruction (debug PC) is bracketed with > ... <, the +// marker follows the PC (not the movable cursor), and it is removed when Debug +// is left. +static int test_debug_next_opcode_bracket_markers() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + ui.color_fg = 12; + + backend.write(0x2000, 0x84); // STY $70 + backend.write(0x2001, 0x70); + backend.write(0x2002, 0xEA); // NOP (next row, where the cursor will move) + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0x2000; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.sr = 0x20; + + const int keys[] = { 'A', 'D', KEY_DOWN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 5); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM setup should return 0")) return 1; + if (expect(monitor.poll(0) == 0, "Debug entry should return 0")) return 1; + + char row[40]; + + if (expect(find_row_with_address(screen, "2000") >= 0, "PC row must be visible")) return 1; + screen.get_slice(1, find_row_with_address(screen, "2000"), 38, row); + if (expect(strstr(row, ">STY $70<") != NULL, + "Debug PC row must bracket the next opcode with > and <")) return 1; + + // Move the cursor down; the marker must stay on the PC row, not follow it. + if (expect(monitor.poll(0) == 0, "Cursor down should return 0")) return 1; + if (expect(find_row_with_address(screen, "2000") >= 0, "PC row must still be visible")) return 1; + screen.get_slice(1, find_row_with_address(screen, "2000"), 38, row); + if (expect(strstr(row, ">STY $70<") != NULL, + "Marker must stay on the PC row after the cursor moves")) return 1; + if (expect(find_row_with_address(screen, "2002") >= 0, "Cursor row must be visible")) return 1; + screen.get_slice(1, find_row_with_address(screen, "2002"), 38, row); + if (expect(strchr(row, '>') == NULL && strchr(row, '<') == NULL, + "The moved cursor row must not be bracketed")) return 1; + + // Leaving Debug removes the markup. + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave Debug")) return 1; + if (expect(find_row_with_address(screen, "2000") >= 0, "PC row must be visible after leaving Debug")) return 1; + screen.get_slice(1, find_row_with_address(screen, "2000"), 38, row); + if (expect(strchr(row, '>') == NULL && strchr(row, '<') == NULL, + "Bracket markup must be removed when Debug is left")) return 1; + + if (expect(monitor.poll(0) == 1, "Final RUN/STOP should exit")) return 1; + monitor.deinit(); + return 0; +} + +// --- Debug header/footer colour --------------------------------------------- +// Header mode/address tokens and breakpoint rows use color_fg. +// In Debug footer labels, PC/A/X/Y/S and active flag letters use the primary +// accent; in the value row, PC/AC/XR/YR/SP and the SR bit string use the +// primary accent while IRQ/NMI stay in color_fg. + +static int test_debug_footer_value_highlight_policy() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + // Set a sentinel foreground (12) distinct from the primary accent so the + // assertions are meaningful. + ui.color_fg = 12; + backend.canned_snapshot_set = true; + debug_context_reset(&backend.canned_snapshot); + backend.canned_snapshot.valid = true; + backend.canned_snapshot.pc = 0xC003; + backend.canned_snapshot.sp = 0xF7; + backend.canned_snapshot.a = 0x01; + backend.canned_snapshot.x = 0x00; + backend.canned_snapshot.y = 0xFF; + backend.canned_snapshot.sr = 0x35; + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + + // The Dbg badge colour is the white primary accent; sample it so the + // assertions do not hard-code the accent constant. + char header[40]; + screen.get_slice(1, 3, 38, header); + const char *dbg = strstr(header, "Dbg"); + if (expect(dbg != NULL, "Header must show the Dbg badge")) return 1; + uint8_t accent = screen.colors[3][1 + (dbg - header)]; + + // Locate the footer label row (contains PC/SP/AC labels). + int label_y = -1; + for (int y = 0; y < 25; y++) { + char row[40]; + screen.get_slice(1, y, 38, row); + if (strstr(row, "PC") != NULL && strstr(row, "SP") != NULL && + strstr(row, "AC") != NULL && strstr(row, "NV-BDIZC") != NULL) { + label_y = y; + break; + } + } + if (expect(label_y >= 0, "Debug footer label row must be visible")) return 1; + + const int accent_positions[] = { + MonitorDebug::FOOTER_POS_PC + 0, + MonitorDebug::FOOTER_POS_PC + 1, + MonitorDebug::FOOTER_POS_AC + 0, + MonitorDebug::FOOTER_POS_XR + 0, + MonitorDebug::FOOTER_POS_YR + 0, + MonitorDebug::FOOTER_POS_SP + 0, + MonitorDebug::FOOTER_POS_FLAGS + 3, + MonitorDebug::FOOTER_POS_FLAGS + 5, + MonitorDebug::FOOTER_POS_FLAGS + 7, + }; + for (unsigned i = 0; i < sizeof(accent_positions) / sizeof(accent_positions[0]); i++) { + int x = 1 + accent_positions[i]; + if (expect(screen.colors[label_y][x] == accent, + "Requested Debug footer labels must use the accent")) return 1; + } + const int foreground_positions[] = { + MonitorDebug::FOOTER_POS_AC + 1, + MonitorDebug::FOOTER_POS_XR + 1, + MonitorDebug::FOOTER_POS_YR + 1, + MonitorDebug::FOOTER_POS_FLAGS + 0, + MonitorDebug::FOOTER_POS_FLAGS + 1, + MonitorDebug::FOOTER_POS_FLAGS + 2, + MonitorDebug::FOOTER_POS_FLAGS + 4, + MonitorDebug::FOOTER_POS_FLAGS + 6, + }; + for (unsigned i = 0; i < sizeof(foreground_positions) / sizeof(foreground_positions[0]); i++) { + int x = 1 + foreground_positions[i]; + if (expect(screen.colors[label_y][x] == ui.color_fg, + "Inactive flags and trailing register letters must stay in color_fg")) return 1; + } + for (int x = 1 + MonitorDebug::FOOTER_POS_IRQ; + x < 1 + MonitorDebug::FOOTER_POS_IRQ + 3; x++) { + if (expect(screen.colors[label_y][x] == ui.color_fg, + "IRQ label must stay in color_fg")) return 1; + } + for (int x = 1 + MonitorDebug::FOOTER_POS_NMI; + x < 1 + MonitorDebug::FOOTER_POS_NMI + 3; x++) { + if (expect(screen.colors[label_y][x] == ui.color_fg, + "NMI label must stay in color_fg")) return 1; + } + const int value_accent_ranges[][2] = { + { MonitorDebug::FOOTER_POS_PC, 4 }, + { MonitorDebug::FOOTER_POS_AC, 2 }, + { MonitorDebug::FOOTER_POS_XR, 2 }, + { MonitorDebug::FOOTER_POS_YR, 2 }, + { MonitorDebug::FOOTER_POS_SP, 2 }, + { MonitorDebug::FOOTER_POS_FLAGS, 8 }, + }; + for (unsigned i = 0; i < sizeof(value_accent_ranges) / sizeof(value_accent_ranges[0]); i++) { + int start = value_accent_ranges[i][0]; + int len = value_accent_ranges[i][1]; + for (int off = 0; off < len; off++) { + int x = 1 + start + off; + if (expect(screen.colors[label_y + 1][x] == accent, + "Requested Debug footer values must use the accent")) return 1; + } + } + for (int x = 1 + MonitorDebug::FOOTER_POS_IRQ; + x < 1 + MonitorDebug::FOOTER_POS_IRQ + 4; x++) { + if (screen.chars[label_y + 1][x] == ' ') continue; + if (expect(screen.colors[label_y + 1][x] == ui.color_fg, + "IRQ value must stay in color_fg")) return 1; + } + for (int x = 1 + MonitorDebug::FOOTER_POS_NMI; + x < 1 + MonitorDebug::FOOTER_POS_NMI + 4; x++) { + if (screen.chars[label_y + 1][x] == ' ') continue; + if (expect(screen.colors[label_y + 1][x] == ui.color_fg, + "NMI value must stay in color_fg")) return 1; + } + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +static int test_debug_header_mode_and_address_use_foreground_color() +{ + TestUserInterface ui; + CaptureScreen screen; + TrackingDebugBackend backend; + monitor_reset_saved_state(); + + // Set a sentinel foreground (12) distinct from the primary accent (1). + ui.color_fg = 12; + + const int keys[] = { 'A', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "ASM view ok")) return 1; + if (expect(monitor.poll(0) == 0, "Enter Debug ok")) return 1; + + char header[40]; + screen.get_slice(1, 3, 38, header); + // The Dbg badge uses the white primary accent; sample it as the reference. + const char *dbg = strstr(header, "Dbg"); + if (expect(dbg != NULL, "Header must still show the Dbg badge")) return 1; + uint8_t accent = screen.colors[3][1 + (dbg - header)]; + if (expect(accent != ui.color_fg, + "Primary accent and color_fg must be distinct")) return 1; + + // The view-mode token and the current-address token in the header use + // color_fg; only the Dbg badge uses the white primary accent. + const char *mode = strstr(header, "ASM"); + if (expect(mode != NULL, "Header must show the ASM mode token")) return 1; + const char *addr = strstr(header, "$"); + if (expect(addr != NULL, "Header must show the current address")) return 1; + + int mode_x = 1 + (int)(mode - header); + for (int i = 0; i < 3; i++) { + if (expect(screen.colors[3][mode_x + i] == ui.color_fg, + "Header mode text must use color_fg")) return 1; + if (expect(screen.colors[3][mode_x + i] != accent, + "Header mode text must not use the white primary accent")) return 1; + } + int addr_x = 1 + (int)(addr - header); + for (int i = 0; i < 5; i++) { + if (expect(screen.colors[3][addr_x + i] == ui.color_fg, + "Header address text must use color_fg")) return 1; + } + + if (expect(monitor.poll(0) == 0, "RUN/STOP leaves Debug")) return 1; + if (expect(monitor.poll(0) == 1, "Second RUN/STOP exits")) return 1; + monitor.deinit(); + return 0; +} + +} // namespace + +#define RUN(name) do { fprintf(stderr, "RUN " #name "\n"); if (name()) { fprintf(stderr, "FAIL " #name "\n"); return 1; } } while(0) + +int main() +{ + RUN(test_predictor_classifies_control_flow); + RUN(test_breakpoint_slots_allocate_clear_and_format); + RUN(test_footer_layout_blanks_unknown_fields); + RUN(test_debug_footer_sits_above_normal_status); + RUN(test_d_enters_debug_without_executing); + RUN(test_d_inside_debug_performs_over); + RUN(test_d_inside_debug_without_context_overs_from_cursor); + RUN(test_d_inside_debug_without_context_goto_keeps_cursor_authoritative); + RUN(test_d_refuses_undocumented_opcode_with_specific_warning); + RUN(test_debug_predictor_uses_session_bytes_over_backend_reads); + RUN(test_debug_pc_disassembly_uses_session_live_bytes_over_view); + RUN(test_t_traces_and_o_outs_inside_debug); + RUN(test_debug_o_does_not_step_out); + RUN(test_o_without_traced_jsr_reports_not_in_subroutine); + RUN(test_o_without_context_reports_not_in_subroutine); + RUN(test_t_inside_debug_without_context_traces_from_cursor); + RUN(test_t_after_goto_ignores_successful_stale_snapshot); + RUN(test_g_after_goto_ignores_successful_stale_snapshot); + RUN(test_g_after_cursor_stop_uses_captured_context); + RUN(test_g_after_goto_with_active_context_uses_cursor); + RUN(test_g_invalidates_context); + RUN(test_return_remains_non_executing_navigation); + RUN(test_ctrl_d_leaves_debug_only); + RUN(test_ctrl_d_from_edit_clears_edit_for_redebug); + RUN(test_escape_leaves_edit_before_debug); + RUN(test_runstop_leaves_edit_before_debug); + RUN(test_step_from_memory_view_recenters_asm_on_debug_pc); + RUN(test_ctrl_x_resets_and_keeps_debug_open); + RUN(test_ctrl_x_local_reset_exits_monitor); + RUN(test_external_reset_during_debug_wait_exits_without_reopen); + RUN(test_ctrl_x_reset_reentry_anchors_asm_at_source_boundary); + RUN(test_ctrl_x_reenters_monitor_without_debug_when_not_debugging); + RUN(test_breakpoints_survive_ctrl_x_reset_reentry); + RUN(test_breakpoints_survive_normal_close_reopen); + RUN(test_monitor_reset_saved_state_clears_breakpoints); + RUN(test_breakpoint_toggle_via_r); + RUN(test_breakpoint_mismatch_message_uses_view_target_and_live_cpu); + RUN(test_breakpoint_popup_store_reuses_selected_slot); + RUN(test_breakpoint_popup_digit_jumps_to_slot); + RUN(test_breakpoint_row_indicator_and_color); + RUN(test_disabled_breakpoint_row_uses_regular_color); + RUN(test_breakpoint_label_replaces_row_indicator); + RUN(test_source_indicators_are_three_chars); + RUN(test_ctrl_r_opens_breakpoint_popup); + RUN(test_ctrl_r_opens_breakpoint_popup_outside_debug); + RUN(test_breakpoint_popup_navigation_redraws_only_popup); + RUN(test_debug_pc_viewport_keeps_context_margin); + RUN(test_breakpoint_popup_blocks_debug_execution_keys); + RUN(test_unsupported_session_emits_refusal); + RUN(test_b_keeps_binary_view_in_debug); + RUN(test_ctrl_b_keeps_bookmark_popup_in_debug); + RUN(test_cleanup_runs_on_deinit); + RUN(test_ctrl_o_after_debug_step_closes_without_go_handoff); + RUN(test_stop_debugging_clears_stale_go_handoff); + RUN(test_stop_debugging_resumes_current_debug_context); + RUN(test_help_screen_shows_debug_commands); + RUN(test_k_runs_to_cursor); + RUN(test_k_without_context_runs_from_debug_entry_to_cursor); + RUN(test_ctrl_i_swaps_interface_in_monitor); + RUN(test_reset_reentry_view_follows_live_cpu_bank); + RUN(test_reopen_without_reset_preserves_manual_cpu_view); + RUN(test_jump_rejects_non_hex_input_and_uppercases); + RUN(test_edit_and_debug_compose_in_header); + RUN(test_freeze_step_over_refreezes_and_preserves_screen); + RUN(test_freeze_nmi_step_ignores_stale_sentinel); + RUN(test_freeze_step_over_with_context_refreezes); + RUN(test_cleanup_to_context_without_entry_context_never_resets); + RUN(test_freeze_step_into_refreezes); + RUN(test_freeze_step_out_refreezes); + RUN(test_step_out_uses_traced_jsr_target_even_when_target_is_above_pc); + RUN(test_step_out_ignores_nearby_rts_and_patches_after_traced_jsr); + RUN(test_step_out_refuses_stale_far_stack_frame); + RUN(test_over_rts_refuses_non_jsr_stack_target); + RUN(test_traced_rts_uses_recorded_return_target_when_stack_is_unreliable); + RUN(test_traced_kernal_to_basic_step_out_patches_kernal_return); + RUN(test_freeze_go_breakpoint_refreezes); + RUN(test_go_from_current_breakpoint_stops_at_callee_breakpoint); + RUN(test_go_from_current_visible_rom_breakpoint_uses_patch_aware_bytes); + RUN(test_step_over_stops_at_callee_breakpoint); + RUN(test_visible_basic_step_uses_rom_patch_support); + RUN(test_visible_rom_step_bytes_use_cpu_visible_mapping); + RUN(test_u64_debug_cpu_port_uses_live_cpu_bank); + RUN(test_brk_debug_cassette_layout_is_compact_and_top_aligned); + RUN(test_brk_handler_bytes_preserve_stack_and_port_capture_semantics); + RUN(test_brk_trampoline_bytes_preserve_rti_restore_semantics); + RUN(test_hard_brk_stub_bytes_preserve_irq_and_brk_paths); + RUN(test_brk_capture_records_live_cpu_port); + RUN(test_parked_step_resume_restores_captured_cpu_port_registers); + RUN(test_no_breakpoint_continue_restores_captured_cpu_port_registers); + RUN(test_no_breakpoint_continue_after_step_without_passed_context); + RUN(test_cursor_visible_rom_step_sets_monitor_cpu_port_before_jump); + RUN(test_visible_kernal_step_into_uses_rom_patch_support); + RUN(test_visible_kernal_step_over_jsr_patches_fallthrough_rom); + RUN(test_visible_kernal_step_without_rom_patch_support_refuses_cleanly); + RUN(test_visible_rom_breakpoint_go_uses_same_capability_gate); + RUN(test_visible_rom_breakpoint_go_patches_rom_not_underlying_ram); + RUN(test_mixed_kernal_and_ram_breakpoints_patch_distinct_backing_stores); + RUN(test_patch_restore_uses_recorded_destination_after_cpu_bank_changes); + RUN(test_kernal_out_hard_vector_installs_and_restores_on_cleanup); + RUN(test_kernal_out_hard_vector_restores_on_timeout); + RUN(test_visible_kernal_hard_vector_installs_and_restores); + RUN(test_stale_visible_kernal_hard_vector_is_recovered); + RUN(test_run_to_current_visible_kernal_jsr_enters_callee_before_rearming_cursor_breakpoint); + RUN(test_overlay_step_over_never_freezes); + RUN(test_overlay_accessible_unfrozen_step_over_does_not_unfreeze); + RUN(test_overlay_render_target_disables_stale_frozen_unfreeze); + RUN(test_overlay_step_into_never_freezes); + RUN(test_overlay_step_out_never_freezes); + RUN(test_overlay_go_breakpoint_never_freezes); + RUN(test_overlay_two_consecutive_steps_never_freeze); + RUN(test_overlay_cursor_step_from_parked_spin_uses_release_path); + RUN(test_freeze_two_consecutive_steps_rebalance); + RUN(test_overlay_step_timeout_then_recovers); + RUN(test_freeze_step_timeout_refreezes_and_recovers); + RUN(test_cleanup_resume_trampoline_restores_full_context); + RUN(test_nmi_launch_trampoline_balances_stack); + RUN(test_kernal_out_cold_nmi_launch_installs_hard_nmi_vector); + RUN(test_kernal_out_cold_nmi_launch_restores_hard_nmi_vector_on_timeout); + RUN(test_freeze_cleanup_after_step_allows_later_step); + RUN(test_freeze_cleanup_preserves_resume_bytes_across_unfreeze_restore); + RUN(test_freeze_go_without_breakpoint_defers_handoff_until_after_exit); + RUN(test_direct_overlay_go_without_breakpoint_releases_context_and_exits); + RUN(test_direct_go_exits_monitor_and_requests_host_release); + RUN(test_freeze_go_with_breakpoint_still_uses_session_go); + RUN(test_wait_for_sentinel_drops_execution_keys); + RUN(test_wait_for_sentinel_aborts_immediately_on_reset_cancel); + RUN(test_request_reset_cancel_clears_state_and_makes_handler_pokes_during_delay); + RUN(test_debug_ownership_blocks_second_stakeholder_until_remote_expires); + RUN(test_monitor_refuses_debug_when_owner_is_busy); + RUN(test_cursor_row_highlights_jsr_target); + RUN(test_cursor_row_highlights_jmp_target); + RUN(test_cursor_row_highlights_taken_branch_target_only_when_taken); + RUN(test_debug_rts_shows_inferred_target); + RUN(test_debug_rts_empty_stack_shows_unknown); + RUN(test_debug_next_opcode_bracket_markers); + RUN(test_debug_footer_value_highlight_policy); + RUN(test_debug_header_mode_and_address_use_foreground_color); + + puts("machine_monitor_debug_test: OK"); + return 0; +} diff --git a/software/test/monitor/machine_monitor_test.cc b/software/test/monitor/machine_monitor_test.cc new file mode 100644 index 000000000..9ba565aa3 --- /dev/null +++ b/software/test/monitor/machine_monitor_test.cc @@ -0,0 +1,7146 @@ +#include +#include + +#include "disassembler_6502.h" +#include "monitor_init.h" +#include "machine_monitor_test_support.h" +#include "menu.h" +#include "task_menu.h" +#include "tasks_collection.h" + +#define TEST_SORT_ORDER_DEVELOPER 999 +#define TEST_SUBSYSID_C64 1 +#define TEST_SUBSYSID_U64 9 + +namespace monitor_io { +void jump_to(uint16_t address); +} + +void UserInterface :: run_machine_monitor(MemoryBackend *backend) +{ + MachineMonitor *monitor = new MachineMonitor(this, backend); + uint16_t go_address = 0; + monitor->init(screen, keyboard); + int ret = 0; + while (!ret && (!host || host->exists())) { + ret = monitor->poll(0); + } + bool do_go = monitor->consume_pending_go(&go_address); + monitor->deinit(); + delete monitor; + if (do_go) { +#if defined(U64) && (U64) && !defined(RUNS_ON_PC) + C64 *machine = C64::getMachine(); + if (machine && machine->is_accessible()) { + release_host(); + machine->release_ownership(); + } +#endif + monitor_io::jump_to(go_address); + } +} + +namespace monitor_io { +struct FakeMonitorIOState { + bool pick_file_result; + char pick_path[256]; + char pick_name[64]; + int pick_file_calls; + bool last_pick_save_mode; + bool load_called; + char load_path[256]; + char load_name[64]; + uint16_t load_start_addr; + bool load_use_prg; + uint32_t load_offset; + bool load_length_auto; + uint32_t load_length; + const char *load_error; + uint8_t load_data[131072]; + uint32_t load_size; + + bool save_called; + char save_path[256]; + char save_name[64]; + uint16_t save_start; + uint16_t save_end; + const char *save_error; + uint8_t saved_data[131072]; + uint32_t saved_size; + + bool jump_called; + uint16_t jump_address; +}; + +} // namespace monitor_io + +static SubsysResultCode_e test_monitor_action_callback(SubsysCommand *) +{ + return SSRET_OK; +} + +static Action *g_test_machine_monitor_actions[256]; + +Action *register_machine_monitor_task(int subsys_id, actionFunction_t callback, int function_id) +{ + Action *monitor = new Action("Machine Code Monitor", callback, function_id); + TaskCategory *dev = TasksCollection::getCategory("Developer", TEST_SORT_ORDER_DEVELOPER); + dev->prepend(monitor); + if ((subsys_id >= 0) && (subsys_id < 256)) { + g_test_machine_monitor_actions[subsys_id] = monitor; + } + return monitor; +} + +Action *get_machine_monitor_task(int subsys_id) +{ + if ((subsys_id < 0) || (subsys_id >= 256)) { + return NULL; + } + return g_test_machine_monitor_actions[subsys_id]; +} + +namespace monitor_io { + +static FakeMonitorIOState g_monitor_io; + +static void reset_fake_monitor_io(void) +{ + memset(&g_monitor_io, 0, sizeof(g_monitor_io)); +} + +bool pick_file(UserInterface *, const char *, char *path_out, int path_max, char *name_out, int name_max, bool save_mode) +{ + g_monitor_io.pick_file_calls++; + g_monitor_io.last_pick_save_mode = save_mode; + if (!g_monitor_io.pick_file_result) { + return false; + } + if (path_out && path_max > 0) { + strncpy(path_out, g_monitor_io.pick_path, path_max - 1); + path_out[path_max - 1] = 0; + } + if (name_out && name_max > 0) { + strncpy(name_out, g_monitor_io.pick_name, name_max - 1); + name_out[name_max - 1] = 0; + } + return true; +} + +const char *load_into_memory(const char *path, const char *name, MemoryBackend *backend, + uint16_t start_addr, bool use_prg_addr, uint32_t offset, bool length_auto, uint32_t length, + uint16_t *out_start_addr, uint32_t *out_bytes) +{ + g_monitor_io.load_called = true; + strncpy(g_monitor_io.load_path, path ? path : "", sizeof(g_monitor_io.load_path) - 1); + g_monitor_io.load_path[sizeof(g_monitor_io.load_path) - 1] = 0; + strncpy(g_monitor_io.load_name, name ? name : "", sizeof(g_monitor_io.load_name) - 1); + g_monitor_io.load_name[sizeof(g_monitor_io.load_name) - 1] = 0; + g_monitor_io.load_start_addr = start_addr; + g_monitor_io.load_use_prg = use_prg_addr; + g_monitor_io.load_offset = offset; + g_monitor_io.load_length_auto = length_auto; + g_monitor_io.load_length = length; + if (g_monitor_io.load_error) { + return g_monitor_io.load_error; + } + + uint32_t header_skip = 0; + uint32_t size = g_monitor_io.load_size; + if (use_prg_addr) { + if (size < 2) { + return "NOT A PRG"; + } + start_addr = (uint16_t)(g_monitor_io.load_data[0] | (g_monitor_io.load_data[1] << 8)); + header_skip = 2; + size -= 2; + } + + uint32_t effective = 0; + MonitorError err = monitor_validate_load_size(size, offset, length_auto, length, &effective); + if (err != MONITOR_OK) { + return monitor_error_text(err); + } + + backend->begin_session(); + for (uint32_t i = 0; i < effective; i++) { + backend->write((uint16_t)(start_addr + i), g_monitor_io.load_data[header_skip + offset + i]); + } + backend->end_session(); + + if (out_start_addr) { + *out_start_addr = start_addr; + } + if (out_bytes) { + *out_bytes = effective; + } + return NULL; +} + +const char *save_from_memory(UserInterface *, const char *path, const char *name, MemoryBackend *backend, + uint16_t start, uint16_t end) +{ + g_monitor_io.save_called = true; + strncpy(g_monitor_io.save_path, path ? path : "", sizeof(g_monitor_io.save_path) - 1); + g_monitor_io.save_path[sizeof(g_monitor_io.save_path) - 1] = 0; + strncpy(g_monitor_io.save_name, name ? name : "", sizeof(g_monitor_io.save_name) - 1); + g_monitor_io.save_name[sizeof(g_monitor_io.save_name) - 1] = 0; + g_monitor_io.save_start = start; + g_monitor_io.save_end = end; + if (g_monitor_io.save_error) { + return g_monitor_io.save_error; + } + + uint32_t total = (uint32_t)end - (uint32_t)start + 1; + g_monitor_io.saved_data[0] = (uint8_t)(start & 0xFF); + g_monitor_io.saved_data[1] = (uint8_t)((start >> 8) & 0xFF); + backend->begin_session(); + for (uint32_t i = 0; i < total; i++) { + g_monitor_io.saved_data[2 + i] = backend->read((uint16_t)(start + i)); + } + backend->end_session(); + g_monitor_io.saved_size = total + 2; + return NULL; +} + +void jump_to(uint16_t address) +{ + g_monitor_io.jump_called = true; + g_monitor_io.jump_address = address; +} +} // namespace monitor_io + +class TaskActionProvider : public ObjectWithMenu +{ +public: + Action *monitor_action; + bool update_called; + bool last_writable; + + TaskActionProvider() : monitor_action(NULL), update_called(false), last_writable(false) + { + } + + void create_task_items(void) + { + monitor_action = register_machine_monitor_task(TEST_SUBSYSID_U64, test_monitor_action_callback, 12); + g_test_machine_monitor_actions[TEST_SUBSYSID_C64] = monitor_action; + } + + void update_task_items(bool writablePath) + { + update_called = true; + last_writable = writablePath; + } +}; + +static int test_disassembler(void) +{ + Disassembled6502 decoded; + + const uint8_t lda_imm[] = { 0xA9, 0x01, 0x00 }; + disassemble_6502(0xC000, lda_imm, false, &decoded); + if (expect(decoded.length == 2 && strcmp(decoded.text, "LDA #$01") == 0, "LDA immediate disassembly failed.")) return 1; + + const uint8_t jsr_abs[] = { 0x20, 0x0F, 0xBC }; + disassemble_6502(0xC000, jsr_abs, false, &decoded); + if (expect(decoded.length == 3 && strcmp(decoded.text, "JSR $BC0F") == 0, "JSR absolute disassembly failed.")) return 1; + + const uint8_t bne_rel[] = { 0xD0, 0x05, 0x00 }; + disassemble_6502(0x1000, bne_rel, false, &decoded); + if (expect(decoded.length == 2 && strcmp(decoded.text, "BNE $1007") == 0, "BNE branch target disassembly failed.")) return 1; + + const uint8_t brk[] = { 0x00, 0x00, 0x00 }; + disassemble_6502(0x2000, brk, false, &decoded); + if (expect(decoded.length == 1 && strcmp(decoded.text, "BRK") == 0, "BRK disassembly failed.")) return 1; + + const uint8_t illegal[] = { 0x07, 0x44, 0x00 }; + disassemble_6502(0x3000, illegal, false, &decoded); + if (expect(strcmp(decoded.text, "???") == 0, "Illegal opcode disable failed.")) return 1; + disassemble_6502(0x3000, illegal, true, &decoded); + if (expect(strcmp(decoded.text, "SLO $44") == 0, "Illegal opcode enable failed.")) return 1; + + const uint8_t lda_absy[] = { 0xB9, 0x99, 0xFF }; + disassemble_6502(0x9010, lda_absy, false, &decoded); + if (expect(decoded.valid && decoded.length == 3 && decoded.operand_bytes == 2 && strcmp(decoded.text, "LDA $FF99,Y") == 0, + "Absolute indexed disassembly must expose a 2-byte operand.")) return 1; + + const uint8_t asl_acc[] = { 0x0A, 0xEA, 0x00 }; + disassemble_6502(0x4000, asl_acc, false, &decoded); + if (expect(decoded.valid && decoded.length == 1 && decoded.operand_bytes == 0 && strcmp(decoded.text, "ASL A") == 0, + "Accumulator disassembly must remain a 1-byte no-operand instruction.")) return 1; + + const uint8_t illegal_zpx[] = { 0x54, 0x44, 0x00 }; + disassemble_6502(0x3000, illegal_zpx, true, &decoded); + if (expect(strcmp(decoded.text, "NOP $44,X") == 0, "Illegal zeropage,X disassembly failed.")) return 1; + + return 0; +} + +// Full-coverage check of all 256 opcodes against the c64ref 6502 description +// (https://github.com/mist64/c64ref). For each opcode the disassembler's +// rendered text and instruction length must match the reference addressing +// mode. This is the regression net for the "BIT mis-rendered as a relative +// branch" bug and the $8B/$CB/$F4 addressing-mode fixes. Mode codes: +// '-' implied 'A' accumulator 'i' #immediate +// 'z' zp 'x' zp,X 'y' zp,Y 'I' (zp,X) 'J' (zp),Y +// 'a' abs 'X' abs,X 'Y' abs,Y 'P' (abs) 'r' relative +// Illegal mnemonics use this codebase's established names (ALR/AXS/AHX/TAS), +// which alias the c64ref ASR/SBX/SHA/SHS for the same opcodes. +static int test_disassembler_all_opcodes_match_c64ref(void) +{ + struct OpRef { const char *mnem; char mode; }; + static const OpRef table[256] = { + {"BRK",'-'}, {"ORA",'I'}, {"JAM",'-'}, {"SLO",'I'}, + {"NOP",'z'}, {"ORA",'z'}, {"ASL",'z'}, {"SLO",'z'}, + {"PHP",'-'}, {"ORA",'i'}, {"ASL",'A'}, {"ANC",'i'}, + {"NOP",'a'}, {"ORA",'a'}, {"ASL",'a'}, {"SLO",'a'}, + {"BPL",'r'}, {"ORA",'J'}, {"JAM",'-'}, {"SLO",'J'}, + {"NOP",'x'}, {"ORA",'x'}, {"ASL",'x'}, {"SLO",'x'}, + {"CLC",'-'}, {"ORA",'Y'}, {"NOP",'-'}, {"SLO",'Y'}, + {"NOP",'X'}, {"ORA",'X'}, {"ASL",'X'}, {"SLO",'X'}, + {"JSR",'a'}, {"AND",'I'}, {"JAM",'-'}, {"RLA",'I'}, + {"BIT",'z'}, {"AND",'z'}, {"ROL",'z'}, {"RLA",'z'}, + {"PLP",'-'}, {"AND",'i'}, {"ROL",'A'}, {"ANC",'i'}, + {"BIT",'a'}, {"AND",'a'}, {"ROL",'a'}, {"RLA",'a'}, + {"BMI",'r'}, {"AND",'J'}, {"JAM",'-'}, {"RLA",'J'}, + {"NOP",'x'}, {"AND",'x'}, {"ROL",'x'}, {"RLA",'x'}, + {"SEC",'-'}, {"AND",'Y'}, {"NOP",'-'}, {"RLA",'Y'}, + {"NOP",'X'}, {"AND",'X'}, {"ROL",'X'}, {"RLA",'X'}, + {"RTI",'-'}, {"EOR",'I'}, {"JAM",'-'}, {"SRE",'I'}, + {"NOP",'z'}, {"EOR",'z'}, {"LSR",'z'}, {"SRE",'z'}, + {"PHA",'-'}, {"EOR",'i'}, {"LSR",'A'}, {"ALR",'i'}, + {"JMP",'a'}, {"EOR",'a'}, {"LSR",'a'}, {"SRE",'a'}, + {"BVC",'r'}, {"EOR",'J'}, {"JAM",'-'}, {"SRE",'J'}, + {"NOP",'x'}, {"EOR",'x'}, {"LSR",'x'}, {"SRE",'x'}, + {"CLI",'-'}, {"EOR",'Y'}, {"NOP",'-'}, {"SRE",'Y'}, + {"NOP",'X'}, {"EOR",'X'}, {"LSR",'X'}, {"SRE",'X'}, + {"RTS",'-'}, {"ADC",'I'}, {"JAM",'-'}, {"RRA",'I'}, + {"NOP",'z'}, {"ADC",'z'}, {"ROR",'z'}, {"RRA",'z'}, + {"PLA",'-'}, {"ADC",'i'}, {"ROR",'A'}, {"ARR",'i'}, + {"JMP",'P'}, {"ADC",'a'}, {"ROR",'a'}, {"RRA",'a'}, + {"BVS",'r'}, {"ADC",'J'}, {"JAM",'-'}, {"RRA",'J'}, + {"NOP",'x'}, {"ADC",'x'}, {"ROR",'x'}, {"RRA",'x'}, + {"SEI",'-'}, {"ADC",'Y'}, {"NOP",'-'}, {"RRA",'Y'}, + {"NOP",'X'}, {"ADC",'X'}, {"ROR",'X'}, {"RRA",'X'}, + {"NOP",'i'}, {"STA",'I'}, {"NOP",'i'}, {"SAX",'I'}, + {"STY",'z'}, {"STA",'z'}, {"STX",'z'}, {"SAX",'z'}, + {"DEY",'-'}, {"NOP",'i'}, {"TXA",'-'}, {"XAA",'i'}, + {"STY",'a'}, {"STA",'a'}, {"STX",'a'}, {"SAX",'a'}, + {"BCC",'r'}, {"STA",'J'}, {"JAM",'-'}, {"AHX",'J'}, + {"STY",'x'}, {"STA",'x'}, {"STX",'y'}, {"SAX",'y'}, + {"TYA",'-'}, {"STA",'Y'}, {"TXS",'-'}, {"TAS",'Y'}, + {"SHY",'X'}, {"STA",'X'}, {"SHX",'Y'}, {"AHX",'Y'}, + {"LDY",'i'}, {"LDA",'I'}, {"LDX",'i'}, {"LAX",'I'}, + {"LDY",'z'}, {"LDA",'z'}, {"LDX",'z'}, {"LAX",'z'}, + {"TAY",'-'}, {"LDA",'i'}, {"TAX",'-'}, {"LAX",'i'}, + {"LDY",'a'}, {"LDA",'a'}, {"LDX",'a'}, {"LAX",'a'}, + {"BCS",'r'}, {"LDA",'J'}, {"JAM",'-'}, {"LAX",'J'}, + {"LDY",'x'}, {"LDA",'x'}, {"LDX",'y'}, {"LAX",'y'}, + {"CLV",'-'}, {"LDA",'Y'}, {"TSX",'-'}, {"LAS",'Y'}, + {"LDY",'X'}, {"LDA",'X'}, {"LDX",'Y'}, {"LAX",'Y'}, + {"CPY",'i'}, {"CMP",'I'}, {"NOP",'i'}, {"DCP",'I'}, + {"CPY",'z'}, {"CMP",'z'}, {"DEC",'z'}, {"DCP",'z'}, + {"INY",'-'}, {"CMP",'i'}, {"DEX",'-'}, {"AXS",'i'}, + {"CPY",'a'}, {"CMP",'a'}, {"DEC",'a'}, {"DCP",'a'}, + {"BNE",'r'}, {"CMP",'J'}, {"JAM",'-'}, {"DCP",'J'}, + {"NOP",'x'}, {"CMP",'x'}, {"DEC",'x'}, {"DCP",'x'}, + {"CLD",'-'}, {"CMP",'Y'}, {"NOP",'-'}, {"DCP",'Y'}, + {"NOP",'X'}, {"CMP",'X'}, {"DEC",'X'}, {"DCP",'X'}, + {"CPX",'i'}, {"SBC",'I'}, {"NOP",'i'}, {"ISC",'I'}, + {"CPX",'z'}, {"SBC",'z'}, {"INC",'z'}, {"ISC",'z'}, + {"INX",'-'}, {"SBC",'i'}, {"NOP",'-'}, {"SBC",'i'}, + {"CPX",'a'}, {"SBC",'a'}, {"INC",'a'}, {"ISC",'a'}, + {"BEQ",'r'}, {"SBC",'J'}, {"JAM",'-'}, {"ISC",'J'}, + {"NOP",'x'}, {"SBC",'x'}, {"INC",'x'}, {"ISC",'x'}, + {"SED",'-'}, {"SBC",'Y'}, {"NOP",'-'}, {"ISC",'Y'}, + {"NOP",'X'}, {"SBC",'X'}, {"INC",'X'}, {"ISC",'X'}, + }; + + const uint8_t b1 = 0x66, b2 = 0xBD; + for (int op = 0; op < 256; op++) { + const uint8_t bytes[3] = { (uint8_t)op, b1, b2 }; + Disassembled6502 d; + disassemble_6502(0x1000, bytes, true, &d); + + char mode = table[op].mode; + uint8_t exp_len = (mode == '-' || mode == 'A') ? 1 : + (mode == 'a' || mode == 'X' || mode == 'Y' || mode == 'P') ? 3 : 2; + char exp[24]; + switch (mode) { + case '-': sprintf(exp, "%s", table[op].mnem); break; + case 'A': sprintf(exp, "%s A", table[op].mnem); break; + case 'i': sprintf(exp, "%s #$%02X", table[op].mnem, b1); break; + case 'z': sprintf(exp, "%s $%02X", table[op].mnem, b1); break; + case 'x': sprintf(exp, "%s $%02X,X", table[op].mnem, b1); break; + case 'y': sprintf(exp, "%s $%02X,Y", table[op].mnem, b1); break; + case 'I': sprintf(exp, "%s ($%02X,X)", table[op].mnem, b1); break; + case 'J': sprintf(exp, "%s ($%02X),Y", table[op].mnem, b1); break; + case 'a': sprintf(exp, "%s $%02X%02X", table[op].mnem, b2, b1); break; + case 'X': sprintf(exp, "%s $%02X%02X,X", table[op].mnem, b2, b1); break; + case 'Y': sprintf(exp, "%s $%02X%02X,Y", table[op].mnem, b2, b1); break; + case 'P': sprintf(exp, "%s ($%02X%02X)", table[op].mnem, b2, b1); break; + case 'r': sprintf(exp, "%s $%04X", table[op].mnem, + (uint16_t)(0x1000 + 2 + (int8_t)b1)); break; + default: exp[0] = 0; break; + } + if (d.length != exp_len) { + printf("opcode %02X: length %u != expected %u (%s)\n", + op, (unsigned)d.length, (unsigned)exp_len, exp); + return 1; + } + if (strcmp(d.text, exp) != 0) { + printf("opcode %02X: text '%s' != expected '%s'\n", op, d.text, exp); + return 1; + } + } + + // Direct guard for the reported bug: BIT zeropage ($24 $66) must render as + // a zero-page operand, never as a PC-relative branch target. + { + const uint8_t bit_zp[] = { 0x24, 0x66, 0x00 }; + Disassembled6502 d; + disassemble_6502(0xBCA2, bit_zp, false, &d); + if (expect(d.length == 2 && strcmp(d.text, "BIT $66") == 0, + "BIT zeropage must render as BIT $66, not a relative branch")) return 1; + } + return 0; +} + +static int test_memory_helpers(void) +{ + FakeMemoryBackend backend; + BackendMachineMonitor monitor(NULL, &backend); + char output[512]; + uint16_t value; + uint8_t needle[32]; + + monitor_fill_memory(&backend, 0xC000, 0xC00F, 0xAA); + if (expect(backend.read(0xC000) == 0xAA && backend.read(0xC00F) == 0xAA && backend.read(0xC010) == 0x00, + "Fill command memory range failed.")) return 1; + + for (value = 0; value < 16; value++) { + backend.write((uint16_t)(0xC100 + value), (uint8_t)value); + } + monitor_transfer_memory(&backend, 0xC100, 0xC110, 0xC101); + for (value = 0; value < 16; value++) { + if (expect(backend.read((uint16_t)(0xC101 + value)) == (uint8_t)value, "Transfer overlap-safe copy failed.")) return 1; + } + + // $C400 LDA $C408; $C403 STA $D020; $C406 JMP $C400 + // $C410 LDX $C408 (outside the moved block but inside the amend range) + backend.write(0xC400, 0xAD); + backend.write(0xC401, 0x08); + backend.write(0xC402, 0xC4); + backend.write(0xC403, 0x8D); + backend.write(0xC404, 0x20); + backend.write(0xC405, 0xD0); + backend.write(0xC406, 0x4C); + backend.write(0xC407, 0x00); + backend.write(0xC408, 0xC4); + backend.write(0xC409, 0x60); + backend.write(0xC410, 0xAE); + backend.write(0xC411, 0x08); + backend.write(0xC412, 0xC4); + monitor_transfer_memory_relocate(&backend, 0xC400, 0xC40A, 0xC500, 0xC400, 0xC413); + if (expect(backend.read(0xC501) == 0x08 && backend.read(0xC502) == 0xC5, + "Relocating transfer must amend copied absolute loads into the moved block.")) return 1; + if (expect(backend.read(0xC504) == 0x20 && backend.read(0xC505) == 0xD0, + "Relocating transfer must not amend absolute operands outside the moved block.")) return 1; + if (expect(backend.read(0xC507) == 0x00 && backend.read(0xC508) == 0xC5, + "Relocating transfer must amend copied JMP operands.")) return 1; + if (expect(backend.read(0xC411) == 0x08 && backend.read(0xC412) == 0xC5, + "Relocating transfer must amend absolute references in the full program range.")) return 1; + + backend.write(0xC200, 0x01); + backend.write(0xC201, 0x02); + backend.write(0xC300, 0x01); + backend.write(0xC301, 0x09); + monitor_compare_memory(&backend, 0xC200, 0xC202, 0xC300, output, sizeof(output)); + if (expect(strstr(output, "$C201") != NULL && strstr(output, "$C200") == NULL, "Compare differences output failed.")) return 1; + + backend.write(0xC400, 0xDE); + backend.write(0xC401, 0xAD); + backend.write(0xC410, 'T'); + backend.write(0xC411, 'E'); + backend.write(0xC412, 'S'); + backend.write(0xC413, 'T'); + needle[0] = 0xDE; + needle[1] = 0xAD; + monitor_hunt_memory(&backend, 0xC400, 0xC420, needle, 2, output, sizeof(output)); + if (expect(strstr(output, "$C400") != NULL, "Hunt byte sequence failed.")) return 1; + monitor_hunt_memory(&backend, 0xC400, 0xC420, (const uint8_t *)"TEST", 4, output, sizeof(output)); + if (expect(strstr(output, "$C410") != NULL, "Hunt string failed.")) return 1; + + return 0; +} + +static int test_parsers_and_formatters(void) +{ + FakeMemoryBackend backend; + char output[512]; + char row[MONITOR_HEX_ROW_CHARS + 1]; + char text_row[MONITOR_TEXT_ROW_CHARS + 1]; + char status_line[40]; + uint16_t value; + uint16_t start; + uint16_t end; + uint16_t dest; + uint8_t byte; + uint8_t needle[32]; + int needle_len; + MachineMonitorState state; + uint8_t ascii_bytes[MONITOR_TEXT_BYTES_PER_ROW]; + + if (expect(monitor_parse_expression("$1234", &value) == MONITOR_OK && value == 0x1234, "Hex expression parse failed.")) return 1; + if (expect(monitor_parse_expression("0x1234", &value) == MONITOR_SYNTAX, "0x-prefixed expressions must be rejected.")) return 1; + if (expect(monitor_parse_expression("4660", &value) == MONITOR_OK && value == 0x1234, "Decimal expression parse failed.")) return 1; + if (expect(monitor_parse_expression("%0001001000110100", &value) == MONITOR_OK && value == 0x1234, "Binary expression parse failed.")) return 1; + + state.view = MONITOR_VIEW_HEX; + state.current_addr = 0; + state.base_addr = 0; + state.disasm_offset = 2; + state.illegal_enabled = false; + state.screen_charset = MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS; + monitor_apply_go(&state, 0x1235); + if (expect(state.current_addr == 0x1235 && state.base_addr == 0x1230 && state.disasm_offset == 0, "Goto state alignment failed.")) return 1; + + if (expect(monitor_parse_address("XYZ", &value) == MONITOR_ADDR, "Address validator failure.")) return 1; + if (expect(monitor_parse_fill("C100-C000,00", &start, &end, &byte) == MONITOR_RANGE, "Range validator failure.")) return 1; + if (expect(monitor_parse_hunt("C100-C200, ", &start, &end, needle, &needle_len) == MONITOR_SYNTAX, "Hunt validator failure.")) return 1; + if (expect(monitor_parse_hunt("C100-C200,\"Hello\"", &start, &end, needle, &needle_len) == MONITOR_OK && + needle_len == 5 && memcmp(needle, "Hello", 5) == 0, + "Hunt quoted ASCII must preserve mixed-case bytes.")) return 1; + if (expect(monitor_parse_transfer("C000-C010,C100", &start, &end, &dest) == MONITOR_OK, "Transfer parser failed.")) return 1; + if (expect(start == 0xC000 && end == 0xC010 && dest == 0xC100, "Transfer parser values failed.")) return 1; + { + bool relocate = false; + uint16_t reloc_start = 0; + uint16_t reloc_end = 0; + if (expect(monitor_parse_transfer_relocate("C000-C010,C100,C000-C080", + &start, &end, &dest, + &relocate, &reloc_start, &reloc_end) == MONITOR_OK, + "Relocating transfer parser failed.")) return 1; + if (expect(start == 0xC000 && end == 0xC010 && dest == 0xC100 && + relocate && reloc_start == 0xC000 && reloc_end == 0xC080, + "Relocating transfer parser values failed.")) return 1; + if (expect(monitor_parse_transfer("C000-C010,C100,C000-C080", &start, &end, &dest) == MONITOR_SYNTAX, + "Non-relocating transfer parser must reject the optional amend range.")) return 1; + if (expect(monitor_parse_transfer_relocate("C000-C010,C100,C080-C000", + &start, &end, &dest, + &relocate, &reloc_start, &reloc_end) == MONITOR_RANGE, + "Relocating transfer parser must reject inverted amend ranges.")) return 1; + } + if (expect(monitor_parse_transfer("C000-C000,C100", &start, &end, &dest) == MONITOR_RANGE, + "Transfer parser should reject zero-length ranges.")) return 1; + if (expect(monitor_parse_compare("C000-C000,C100", &start, &end, &dest) == MONITOR_RANGE, + "Compare parser should reject zero-length ranges.")) return 1; + + if (expect(monitor_format_evaluate("$00ff", output, sizeof(output)) == MONITOR_OK && output[0] == '$', + "Evaluate formatter failed.")) return 1; + + { + const uint8_t hex_bytes[MONITOR_HEX_BYTES_PER_ROW] = { 0x41, 0x00, 0x7A, 0x1F, 0x20, 0x30, 0x31, 0x32 }; + monitor_format_hex_row(0x0000, hex_bytes, row); + if (expect(strcmp(row, "0000 41 00 7A 1F 20 30 31 32 A.z. 012") == 0, "Hex row format mismatch.")) return 1; + } + + { + for (int i = 0; i < MONITOR_TEXT_BYTES_PER_ROW; i++) { + ascii_bytes[i] = (uint8_t)('A' + (i % 26)); + } + monitor_format_text_row(0x1000, ascii_bytes, MONITOR_TEXT_BYTES_PER_ROW, false, text_row); + if (expect(strcmp(text_row, "1000 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEF") == 0, "ASCII row format mismatch.")) return 1; + monitor_format_text_row(0x1000, ascii_bytes, MONITOR_TEXT_BYTES_PER_ROW, true, text_row); + if (expect((int)strlen(text_row) == MONITOR_TEXT_ROW_CHARS, "Screen-code row width mismatch.")) return 1; + } + + { + const uint8_t printable_ascii[MONITOR_TEXT_BYTES_PER_ROW] = { + 0x41, 0x61, 0x20, 0x7E, 0x1F, 0x80 + }; + monitor_format_text_row(0x1100, printable_ascii, 6, false, text_row); + if (expect(strncmp(text_row, "1100 Aa ~..", 11) == 0, + "ASCII row formatter must preserve case and dot non-printables.")) return 1; + } + + { + const uint8_t screen_bytes[MONITOR_TEXT_BYTES_PER_ROW] = { + 0x00, 0x01, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, + 0x20, 0x21, 0x2A, 0x2B, 0x30, 0x3A, 0x3F, 0x40, + 0x49, 0x4A, 0x4B, 0x55, 0x5A, 0x5B, 0x5D, 0x60, + 0x7F, 0x80, 0x81, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E + }; + monitor_format_text_row(0x2000, screen_bytes, MONITOR_TEXT_BYTES_PER_ROW, true, text_row); + if (expect(strncmp(text_row, "2000 ", 5) == 0, "Screen-code row prefix mismatch.")) return 1; + if (expect(text_row[5] == '@', "Screen code $00 should map to '@'.")) return 1; + if (expect(text_row[6] == 'A', "Screen code $01 should map to 'A'.")) return 1; + if (expect(text_row[7] == 'Z', "Screen code $1A should map to 'Z'.")) return 1; + if (expect(text_row[8] == '[', "Screen code $1B should map to '['.")) return 1; + if (expect(text_row[9] == '#', "Screen code $1C should map to the pound-sign fallback.")) return 1; + if (expect(text_row[10] == ']', "Screen code $1D should map to ']'.")) return 1; + if (expect(text_row[11] == '^', "Screen code $1E should map to the up-arrow fallback.")) return 1; + if (expect(text_row[12] == '<', "Screen code $1F should map to the left-arrow fallback.")) return 1; + if (expect(text_row[13] == ' ' && text_row[14] == '!' && text_row[15] == '*' && text_row[16] == '+', + "Printable screen-code punctuation mapping is incorrect.")) return 1; + if (expect(text_row[17] == '0' && text_row[18] == ':' && text_row[19] == '?', + "Screen-code digit/punctuation positions are incorrect.")) return 1; + if (expect((unsigned char)text_row[20] == CHR_HORIZONTAL_LINE, "Screen code $40 should map to the horizontal-line glyph.")) return 1; + if (expect((unsigned char)text_row[21] == CHR_ROUNDED_UPPER_RIGHT, "Screen code $49 should map to the upper-right rounded corner glyph.")) return 1; + if (expect((unsigned char)text_row[22] == CHR_ROUNDED_LOWER_LEFT, "Screen code $4A should map to the lower-left rounded corner glyph.")) return 1; + if (expect((unsigned char)text_row[23] == CHR_ROUNDED_LOWER_RIGHT, "Screen code $4B should map to the lower-right rounded corner glyph.")) return 1; + if (expect((unsigned char)text_row[24] == CHR_ROUNDED_UPPER_LEFT, "Screen code $55 should map to the upper-left rounded corner glyph.")) return 1; + if (expect((unsigned char)text_row[25] == CHR_DIAMOND, "Screen code $5A should map to the diamond glyph.")) return 1; + if (expect(text_row[26] == '+' && (unsigned char)text_row[27] == CHR_VERTICAL_LINE, + "Screen-code cross/vertical-line mapping is incorrect.")) return 1; + if (expect(text_row[28] == '.' && text_row[29] == '.', + "Non-space screen-code range $60-$7F should render as visible placeholders.")) return 1; + if (expect(text_row[30] == '@' && text_row[31] == 'A' && text_row[32] == 'Z' && text_row[33] == '[', + "Reverse screen codes should map to the same visible glyph positions as their base codes.")) return 1; + if (expect(text_row[34] == '#' && text_row[35] == ']' && text_row[36] == '^', + "Reverse punctuation/arrow screen-code mapping is incorrect.")) return 1; + } + + { + static const struct { + uint8_t port01; + const char *expected_cpu; + } cpu_cases[] = { + { 0x00, "CPU0 $A:RAM $D:RAM $E:RAM" }, + { 0x01, "CPU1 $A:RAM $D:CHR $E:RAM" }, + { 0x02, "CPU2 $A:RAM $D:CHR $E:KRN" }, + { 0x03, "CPU3 $A:BAS $D:CHR $E:KRN" }, + { 0x04, "CPU4 $A:RAM $D:RAM $E:RAM" }, + { 0x05, "CPU5 $A:RAM $D:I/O $E:RAM" }, + { 0x06, "CPU6 $A:RAM $D:I/O $E:KRN" }, + { 0x07, "CPU7 $A:BAS $D:I/O $E:KRN" }, + }; + + for (unsigned int i = 0; i < sizeof(cpu_cases) / sizeof(cpu_cases[0]); i++) { + monitor_format_status_line(status_line, cpu_cases[i].port01, 0); + if (expect(strncmp(status_line, cpu_cases[i].expected_cpu, strlen(cpu_cases[i].expected_cpu)) == 0, + "CPU status formatter mapping mismatch.")) return 1; + } + } + + { + static const struct { + uint8_t vic_bank; + const char *expected_vic; + } vic_cases[] = { + { 0, "VIC0 $0000" }, + { 1, "VIC1 $4000" }, + { 2, "VIC2 $8000" }, + { 3, "VIC3 $C000" }, + }; + + for (unsigned int i = 0; i < sizeof(vic_cases) / sizeof(vic_cases[0]); i++) { + const char *vic_text; + + monitor_format_status_line(status_line, 0x07, vic_cases[i].vic_bank); + vic_text = strstr(status_line, "VIC"); + if (expect(vic_text != NULL && strcmp(vic_text, vic_cases[i].expected_vic) == 0, + "VIC status formatter mapping mismatch.")) return 1; + } + } + + { + static const struct { + uint8_t port01; + uint8_t vic_bank; + const char *expected; + } combined_cases[] = { + { 0x07, 0, "CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000" }, + { 0x00, 3, "CPU0 $A:RAM $D:RAM $E:RAM VIC3 $C000" }, + { 0x01, 1, "CPU1 $A:RAM $D:CHR $E:RAM VIC1 $4000" }, + { 0x06, 2, "CPU6 $A:RAM $D:I/O $E:KRN VIC2 $8000" }, + { 0x05, 0, "CPU5 $A:RAM $D:I/O $E:RAM VIC0 $0000" }, + }; + + for (unsigned int i = 0; i < sizeof(combined_cases) / sizeof(combined_cases[0]); i++) { + monitor_format_status_line(status_line, combined_cases[i].port01, combined_cases[i].vic_bank); + if (expect(strcmp(status_line, combined_cases[i].expected) == 0, + "Combined CPU/VIC status formatter mismatch.")) return 1; + } + } + + { + char bank_28[40]; + char bank_30[40]; + char bank_29[40]; + char bank_31[40]; + char bank_27[40]; + char bank_37[40]; + + monitor_format_status_line(bank_28, 0x28, 0); + monitor_format_status_line(bank_30, 0x30, 0); + if (expect(strcmp(bank_28, "CPU0 $A:RAM $D:RAM $E:RAM VIC0 $0000") == 0, + "Port $28 should map to effective CPU bank 0.")) return 1; + if (expect(strcmp(bank_28, bank_30) == 0, + "High-bit differences must not change the displayed CPU0 map.")) return 1; + + monitor_format_status_line(bank_29, 0x29, 0); + monitor_format_status_line(bank_31, 0x31, 0); + if (expect(strcmp(bank_29, "CPU1 $A:RAM $D:CHR $E:RAM VIC0 $0000") == 0, + "Port $29 should map to effective CPU bank 1.")) return 1; + if (expect(strcmp(bank_29, bank_31) == 0, + "High-bit differences must not change the displayed CPU1 map.")) return 1; + + monitor_format_status_line(bank_27, 0x27, 0); + monitor_format_status_line(bank_37, 0x37, 0); + if (expect(strcmp(bank_27, "CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000") == 0, + "Port $27 should map to effective CPU bank 7.")) return 1; + if (expect(strcmp(bank_27, bank_37) == 0, + "High-bit differences must not change the displayed CPU7 map.")) return 1; + } + + { + monitor_format_status_line(status_line, 0x05, 0x07, 0); + if (expect(strcmp(status_line, "C7O5 $A:RAM $D:I/O $E:RAM VIC0 $0000") == 0, + "Differing live/view CPU banks must render CPU-first CnOo status.")) return 1; + if (expect(strncmp(status_line, "C7O5", 4) == 0, + "Differing CPU field must be exactly four chars.")) return 1; + if (expect(strstr(status_line, "$A:RAM $D:I/O $E:RAM") != NULL, + "Differing CPU status labels must describe the monitor view bank.")) return 1; + } + + for (uint8_t cpu_bank = 0; cpu_bank < 8; cpu_bank++) { + for (uint8_t vic_bank = 0; vic_bank < 4; vic_bank++) { + monitor_format_status_line(status_line, cpu_bank, vic_bank); + if (expect(strlen(status_line) <= 38, "Status line width exceeded 38 characters.")) return 1; + if (expect(strchr(status_line, '|') == NULL, "Status line must not contain a pipe separator.")) return 1; + monitor_format_status_line(status_line, cpu_bank, (uint8_t)(cpu_bank ^ 0x07), vic_bank); + if (expect(strlen(status_line) <= 38, "Split CPU/VIC status line width exceeded 38 characters.")) return 1; + if (expect(strchr(status_line, '|') == NULL, "Split status line must not contain a pipe separator.")) return 1; + } + } + + return 0; +} + +static int test_banked_backend(void) +{ + FakeBankedMemoryBackend backend; + + backend.ram[0xA000] = 0xA1; + backend.ram[0xD000] = 0xD1; + backend.ram[0xE000] = 0xE1; + backend.basic[0] = 0xBA; + backend.charrom[0] = 0xC3; + backend.kernal[0] = 0x4E; + backend.io[0] = 0x10; + + backend.set_monitor_cpu_port(0x07); + if (expect(backend.read(0xA000) == 0xBA, "BASIC ROM read mapping failed.")) return 1; + if (expect(backend.read(0xD000) == 0x10, "I/O read mapping failed.")) return 1; + if (expect(backend.read(0xE000) == 0x4E, "KERNAL ROM read mapping failed.")) return 1; + + backend.set_monitor_cpu_port(0x03); + if (expect(backend.read(0xD000) == 0xC3, "CHAR ROM read mapping failed.")) return 1; + + backend.set_monitor_cpu_port(0x00); + if (expect(backend.read(0xA000) == 0xA1 && backend.read(0xD000) == 0xD1 && backend.read(0xE000) == 0xE1, + "RAM read mapping failed.")) return 1; + + backend.set_monitor_cpu_port(0x07); + backend.write(0xA000, 0x55); + backend.write(0xE000, 0x66); + if (expect(backend.ram[0xA000] == 0x55 && backend.basic[0] == 0xBA, "Write-under-BASIC semantics failed.")) return 1; + if (expect(backend.ram[0xE000] == 0x66 && backend.kernal[0] == 0x4E, "Write-under-KERNAL semantics failed.")) return 1; + + backend.set_monitor_cpu_port(0x03); + backend.write(0xD000, 0x77); + if (expect(backend.ram[0xD000] == 0x77 && backend.charrom[0] == 0xC3, "Write-under-CHAR semantics failed.")) return 1; + + backend.set_monitor_cpu_port(0x07); + backend.write(0xD000, 0x88); + if (expect(backend.io[0] == 0x88 && backend.ram[0xD000] == 0x77, "I/O write semantics failed.")) return 1; + if (expect(backend.get_live_vic_bank() == 2, "Live VIC bank calculation failed.")) return 1; + backend.live_dd00 = 0xA9; + backend.set_monitor_cpu_port(0x00); + backend.set_live_vic_bank(1); + if (expect(backend.live_dd00 == 0xAA, "set_live_vic_bank must preserve unrelated CIA-2 bits while updating VIC bank bits.")) return 1; + if (expect(backend.get_monitor_cpu_port() == 0x00, "set_live_vic_bank must restore the selected monitor CPU bank after touching DD00.")) return 1; + backend.set_monitor_cpu_port(0x07); + if (expect(strcmp(backend.source_name(0xA000), "BASIC") == 0, "BASIC source name failed.")) return 1; + if (expect(strcmp(backend.source_name(0xD000), "IO") == 0, "I/O source name failed.")) return 1; + if (expect(strcmp(backend.source_name(0xE000), "KERNAL") == 0, "KERNAL source name failed.")) return 1; + + backend.set_monitor_cpu_port(0x00); + if (expect(strcmp(backend.source_name(0xA000), "RAM") == 0, "A000 RAM source name failed.")) return 1; + if (expect(strcmp(backend.source_name(0xD000), "RAM") == 0, "D000 RAM source name failed.")) return 1; + if (expect(strcmp(backend.source_name(0xE000), "RAM") == 0, "E000 RAM source name failed.")) return 1; + + return 0; +} + +static int test_frozen_banked_backend(void) +{ + // Mirrors the freeze-mode invariants from + // doc/research/machine-monitor/freeze-support/plan.md §Tests: + // monitor_cpu_port is authoritative; ROM overlays and write-under-ROM + // behave correctly; $0400-$0FFF reads from the freezer backup region; + // reads are stable across redraws; IO remains reachable when the bank + // exposes it. + FakeBankedMemoryBackend backend; + + backend.frozen = true; + backend.live_cpu_port = 0x00; // Live latch is unobservable while frozen — must not influence routing. + backend.live_cpu_ddr = 0x00; + + backend.basic[0] = 0xBA; + backend.kernal[0] = 0x4E; + backend.kernal[1] = 0x22; + backend.charrom[0] = 0xC3; + backend.io[0xD020 - 0xD000] = 0x00; + backend.ram[0xA000] = 0xAA; + backend.ram[0xE000] = 0x11; + backend.ram[0xE001] = 0x22; + backend.screen_backup[0x20] = 0x42; // $0420 sentinel — proves backup redirect is used. + backend.ram[0x0420] = 0xFF; // Underlying DRAM differs to guarantee the redirect fired. + + // (1) KERNAL visible at $E000 when (monitor_cpu_port & 0x02). + backend.set_monitor_cpu_port(0x07); + if (expect(backend.read(0xE000) == 0x4E, "Frozen: KERNAL must be visible at $E000 with port=$07.")) return 1; + + // (1b) RAM otherwise. + backend.set_monitor_cpu_port(0x05); // & 0x02 == 0 -> KERNAL hidden. + if (expect(backend.read(0xE000) == 0x11, "Frozen: $E000 must read RAM when KERNAL is hidden.")) return 1; + + // (2) BASIC visible at $A000 when (port & 0x03) == 0x03. + backend.set_monitor_cpu_port(0x07); + if (expect(backend.read(0xA000) == 0xBA, "Frozen: BASIC must be visible at $A000 with port=$07.")) return 1; + backend.set_monitor_cpu_port(0x06); // & 0x03 != 0x03 -> BASIC hidden. + if (expect(backend.read(0xA000) == 0xAA, "Frozen: $A000 must read RAM when BASIC is hidden.")) return 1; + + // (3) $0400-$0FFF returns the screen_backup byte, not live DRAM. + if (expect(backend.read(0x0420) == 0x42, "Frozen: $0420 must come from the screen_backup region.")) return 1; + + // (4) Two consecutive reads at $E000 return the same byte. + backend.set_monitor_cpu_port(0x07); + uint8_t first_read = backend.read(0xE000); + uint8_t second_read = backend.read(0xE000); + if (expect(first_read == second_read, "Frozen: two consecutive $E000 reads must agree (no scroll drift).")) return 1; + + // (5) Write at $E000 while KERNAL is visible, switch to RAM-only bank, + // read $E000 returns the written byte. + backend.set_monitor_cpu_port(0x07); + backend.write(0xE000, 0x99); + if (expect(backend.kernal[0] == 0x4E, "Frozen: write under KERNAL must not modify ROM.")) return 1; + backend.set_monitor_cpu_port(0x05); // KERNAL hidden. + if (expect(backend.read(0xE000) == 0x99, "Frozen: write-under-ROM must persist as RAM and survive bank switch.")) return 1; + + // (6) Frozen + IO-selected bank: source_name reports IO and IO is reachable. + backend.set_monitor_cpu_port(0x07); + if (expect(strcmp(backend.source_name(0xD020), "IO") == 0, + "Frozen: source_name($D020) must remain IO with IO bank selected.")) return 1; + backend.write(0xD020, 0x05); + if (expect(backend.io[0xD020 - 0xD000] == 0x05, "Frozen: IO write must reach the IO region.")) return 1; + if (expect(backend.read(0xD020) == 0x05, "Frozen: IO read must return the freshly written byte.")) return 1; + + return 0; +} + +static const uint8_t asm_kernal_stability_bytes[] = { + 0x85, 0x56, 0x20, 0x0F, 0xBC, 0xA5, 0x61, 0xC9, + 0x88, 0x90, 0x03, 0x20, 0xD4, 0xBA, 0x20, 0xCC, + 0xBC, 0xA5, 0x07, 0x18, 0x69, 0x81, 0xF0, 0xF3, + 0x38, 0xE9, 0x01, 0x48, 0xA2, 0x05, 0xB5, 0x69, + 0xB4, 0x61 +}; + +static const struct { + const char *prefix; + const char *text; +} asm_kernal_stability_rows[] = { + { "E000 85 56", "STA $56" }, + { "E002 20 0F BC", "JSR $BC0F" }, + { "E005 A5 61", "LDA $61" }, + { "E007 C9 88", "CMP #$88" }, + { "E009 90 03", "BCC $E00E" }, + { "E00B 20 D4 BA", "JSR $BAD4" }, + { "E00E 20 CC BC", "JSR $BCCC" }, + { "E011 A5 07", "LDA $07" }, + { "E013 18", "CLC" }, +}; + +static void install_kernal_stability_bytes(FakeBankedMemoryBackend *backend) +{ + memcpy(backend->kernal, asm_kernal_stability_bytes, sizeof(asm_kernal_stability_bytes)); + memcpy(backend->ram + 0xE000, asm_kernal_stability_bytes, sizeof(asm_kernal_stability_bytes)); +} + +static int expect_line_contains(const CaptureScreen &screen, int y, + const char *prefix, const char *needle, + const char *message) +{ + char line[MONITOR_DISASM_ROW_CHARS + 1]; + + screen.get_slice(1, y, MONITOR_DISASM_ROW_CHARS, line); + if (prefix && expect(strstr(line, prefix) == line, message)) return 1; + if (needle && expect(strstr(line, needle) != NULL, message)) return 1; + return 0; +} + +static int expect_visible_disasm(const CaptureScreen &screen, + const char *prefix, const char *needle, + const char *message) +{ + char line[MONITOR_DISASM_ROW_CHARS + 1]; + + for (int y = 4; y <= 22; y++) { + screen.get_slice(1, y, MONITOR_DISASM_ROW_CHARS, line); + if ((!prefix || strstr(line, prefix) == line) && + (!needle || strstr(line, needle) != NULL)) { + return 0; + } + } + return fail(message); +} + +static int visible_disasm_exists(const CaptureScreen &screen, + const char *prefix, const char *needle) +{ + char line[MONITOR_DISASM_ROW_CHARS + 1]; + + for (int y = 4; y <= 22; y++) { + screen.get_slice(1, y, MONITOR_DISASM_ROW_CHARS, line); + if ((!prefix || strstr(line, prefix) == line) && + (!needle || strstr(line, needle) != NULL)) { + return 1; + } + } + return 0; +} + +static int highlighted_disasm_row_count(const CaptureScreen &screen) +{ + int count = 0; + + for (int y = 4; y <= 22; y++) { + bool row_highlighted = false; + for (int x = 0; x < 40; x++) { + if (screen.reverse_chars[y][x]) { + row_highlighted = true; + break; + } + } + if (row_highlighted) { + count++; + } + } + return count; +} + +static int expect_highlighted_disasm(const CaptureScreen &screen, + const char *prefix, const char *needle, + const char *message) +{ + int row = -1; + + if (expect(find_highlighted_cell(screen, NULL, &row), message)) return 1; + if (expect(highlighted_disasm_row_count(screen) == 1, + "ASM view must have exactly one highlighted instruction row.")) return 1; + return expect_line_contains(screen, row, prefix, needle, message); +} + +static int copy_highlighted_disasm_line(const CaptureScreen &screen, char *out, const char *message) +{ + int row = -1; + + if (expect(find_highlighted_cell(screen, NULL, &row), message)) return 1; + if (expect(highlighted_disasm_row_count(screen) == 1, + "ASM view must have exactly one highlighted instruction row.")) return 1; + screen.get_slice(1, row, MONITOR_DISASM_ROW_CHARS, out); + return 0; +} + +static int expect_canonical_kernal_lane(const CaptureScreen &screen, + const char *highlight_prefix, + const char *highlight_text, + const char *message) +{ + char line[MONITOR_DISASM_ROW_CHARS + 1]; + + for (unsigned i = 0; i < sizeof(asm_kernal_stability_rows) / sizeof(asm_kernal_stability_rows[0]); i++) { + screen.get_slice(1, 4 + (int)i, MONITOR_DISASM_ROW_CHARS, line); + if (expect(strstr(line, asm_kernal_stability_rows[i].prefix) == line, message)) return 1; + if (expect(strstr(line, asm_kernal_stability_rows[i].text) != NULL, message)) return 1; + } + if (expect(!visible_disasm_exists(screen, "E001 ", NULL), + "Canonical KERNAL lane must not re-phase to E001 after IO-prefix changes.")) return 1; + if (expect(!visible_disasm_exists(screen, "E010 ", NULL), + "Canonical KERNAL lane must not show the overlapping E010 candidate.")) return 1; + if (expect_highlighted_disasm(screen, highlight_prefix, highlight_text, message)) return 1; + return 0; +} + +static int test_kernal_disassembly_mapping(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char line[39]; + monitor_reset_saved_state(); + + const uint8_t kernal_bytes[] = { + 0x85, 0x56, 0x20, 0x0F, 0xBC, 0xA5, 0x61, 0xC9, + 0x88, 0x90, 0x03, 0x20, 0xD4, 0xBA, 0x20, 0xCC, + 0xBC, 0xA5, 0x07 + }; + const uint8_t ram_bytes[] = { + 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, + 0x18, 0x00, 0x00 + }; + // 'A' switches to disassembly view without entering Debug mode; 'D' now + // enters Debug per DBG-CMD-001 and would intercept the following 'o' as + // step-out rather than cycling the CPU bank. + const int keys[] = { 'J', 'A', 'o', KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + + memset(backend.ram + 0xE000, 0x00, 0x40); + memcpy(backend.kernal, kernal_bytes, sizeof(kernal_bytes)); + memcpy(backend.ram + 0xE000, ram_bytes, sizeof(ram_bytes)); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Goto to E000 failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Disassembly view switch failed.")) return 1; + + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "E000 85 56") == line, "Visible KERNAL bytes at E000 are incorrect.")) return 1; + if (expect(strstr(line, "STA $56") != NULL, "Visible KERNAL disassembly at E000 is incorrect.")) return 1; + if (expect(strstr(line, "[KRN]") != NULL, "Visible KERNAL source annotation missing.")) return 1; + if (expect(screen.reverse_chars[4][1], "Disassembly view did not highlight the selected instruction.")) return 1; + + screen.get_slice(1, 5, 38, line); + if (expect(strstr(line, "E002 20 0F BC") == line, "Visible KERNAL bytes at E002 are incorrect.")) return 1; + if (expect(strstr(line, "JSR $BC0F") != NULL, "Visible KERNAL disassembly at E002 is incorrect.")) return 1; + if (expect(strstr(line, "[KRN]") != NULL, "E002 KERNAL source annotation missing.")) return 1; + + screen.get_slice(1, 6, 38, line); + if (expect(strstr(line, "E005 A5 61") == line, "Visible KERNAL bytes at E005 are incorrect.")) return 1; + if (expect(strstr(line, "LDA $61") != NULL, "Visible KERNAL disassembly at E005 is incorrect.")) return 1; + + screen.get_slice(1, 7, 38, line); + if (expect(strstr(line, "E007 C9 88") == line, "Visible KERNAL bytes at E007 are incorrect.")) return 1; + if (expect(strstr(line, "CMP #$88") != NULL, "Visible KERNAL disassembly at E007 is incorrect.")) return 1; + + screen.get_slice(1, 8, 38, line); + if (expect(strstr(line, "E009 90 03") == line, "Visible KERNAL bytes at E009 are incorrect.")) return 1; + if (expect(strstr(line, "BCC $E00E") != NULL, "Visible KERNAL disassembly at E009 is incorrect.")) return 1; + + screen.get_slice(1, 9, 38, line); + if (expect(strstr(line, "E00B 20 D4 BA") == line, "Visible KERNAL bytes at E00B are incorrect.")) return 1; + if (expect(strstr(line, "JSR $BAD4") != NULL, "Visible KERNAL disassembly at E00B is incorrect.")) return 1; + + screen.get_slice(1, 10, 38, line); + if (expect(strstr(line, "E00E 20 CC BC") == line, "Visible KERNAL bytes at E00E are incorrect.")) return 1; + if (expect(strstr(line, "JSR $BCCC") != NULL, "Visible KERNAL disassembly at E00E is incorrect.")) return 1; + + screen.get_slice(1, 11, 38, line); + if (expect(strstr(line, "E011 A5 07") == line, "Visible KERNAL bytes at E011 are incorrect.")) return 1; + if (expect(strstr(line, "LDA $07") != NULL, "Visible KERNAL disassembly at E011 is incorrect.")) return 1; + + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU0 failed.")) return 1; + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "E000 00") == line, "RAM-under-ROM bytes at E000 are incorrect.")) return 1; + if (expect(strstr(line, "BRK") != NULL, "RAM-under-ROM disassembly at E000 is incorrect.")) return 1; + if (expect(strstr(line, "[RAM]") != NULL, "RAM-under-ROM source annotation missing.")) return 1; + + if (expect(monitor.poll(0) == 1, "RUN/STOP exit failed after KERNAL mapping test.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_asm_root_stable_with_cpu7_io_context(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + const int keys[] = { 'J', 'A', 'P' }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + monitor_reset_saved_state(); + + install_kernal_stability_bytes(&backend); + backend.io[0x0FFD] = 0xA9; + backend.io[0x0FFE] = 0x00; + backend.io[0x0FFF] = 0xEA; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "CPU7 IO stability test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU7 IO stability test: ASM view failed.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU7 IO stability test: poll mode failed.")) return 1; + + if (expect_canonical_kernal_lane(screen, "E000 85 56", "STA $56", + "CPU7 IO stability test: initial canonical KERNAL lane missing.")) return 1; + + backend.io[0x0FFD] = 0x4C; + backend.io[0x0FFE] = 0x00; + backend.io[0x0FFF] = 0xE0; + advance_fake_ms_timer(1000); + if (expect(monitor.poll(0) == 0, "CPU7 IO stability test: redraw after IO JMP mutation failed.")) return 1; + if (expect_canonical_kernal_lane(screen, "E000 85 56", "STA $56", + "CPU7 IO JMP-to-E000 prefix must not re-phase the canonical KERNAL lane.")) return 1; + + backend.io[0x0FFD] = 0x20; + backend.io[0x0FFE] = 0x00; + backend.io[0x0FFF] = 0xE0; + advance_fake_ms_timer(1000); + if (expect(monitor.poll(0) == 0, "CPU7 IO stability test: redraw after IO JSR mutation failed.")) return 1; + if (expect_canonical_kernal_lane(screen, "E000 85 56", "STA $56", + "CPU7 IO JSR-prefix mutation must not move or re-phase the E000 root.")) return 1; + + monitor.deinit(); + return 0; +} + +static int test_asm_root_stable_with_continuous_ram_context(void) +{ + for (uint8_t bank = 0; bank <= 4; bank += 4) { + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + int keys[12]; + int n = 0; + monitor_reset_saved_state(); + + keys[n++] = 'J'; + keys[n++] = 'A'; + for (uint8_t i = 0; i <= bank; i++) { + keys[n++] = 'o'; + } + keys[n++] = 'P'; + FakeKeyboard keyboard(keys, n); + + install_kernal_stability_bytes(&backend); + backend.ram[0xDFFE] = 0xA9; + backend.ram[0xDFFF] = 0x00; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "CPU0/4 RAM stability test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU0/4 RAM stability test: ASM view failed.")) return 1; + for (uint8_t i = 0; i <= bank; i++) { + if (expect(monitor.poll(0) == 0, "CPU0/4 RAM stability test: CPU bank cycle failed.")) return 1; + } + if (expect(monitor.poll(0) == 0, "CPU0/4 RAM stability test: poll mode failed.")) return 1; + if (expect_highlighted_disasm(screen, "E000 85 56", "STA $56", + "CPU0/4 RAM stability test: E000 root row incorrect.")) return 1; + + backend.ram[0xDFFE] = 0x20; + backend.ram[0xDFFF] = 0x00; + advance_fake_ms_timer(1000); + if (expect(monitor.poll(0) == 0, "CPU0/4 RAM stability test: redraw after RAM mutation failed.")) return 1; + if (expect_highlighted_disasm(screen, "E000 85 56", "STA $56", + "CPU0/4 RAM mutation must not re-phase an explicit E000 root.")) return 1; + monitor.deinit(); + } + return 0; +} + +static int test_asm_explicit_root_can_cross_continuous_ram_boundary(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + const int keys[] = { 'J', 'A', 'o', KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + monitor_reset_saved_state(); + + backend.ram[0xDFFE] = 0x20; + backend.ram[0xDFFF] = 0x00; + backend.ram[0xE000] = 0xE0; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("DFFE", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Explicit RAM-crossing test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Explicit RAM-crossing test: ASM view failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Explicit RAM-crossing test: CPU0 bank cycle failed.")) return 1; + if (expect_highlighted_disasm(screen, "DFFE 20 00 E0", "JSR $E000", + "Explicit DFFE root must be allowed to decode across DFFF/E000 in CPU0 RAM.")) return 1; + if (expect(monitor.poll(0) == 1, "Explicit RAM-crossing test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_asm_left_right_decode_root_control(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char header[39]; + const int keys[] = { 'J', 'A', KEY_RIGHT, KEY_RIGHT, KEY_LEFT, KEY_RIGHT, KEY_LEFT, KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + monitor_reset_saved_state(); + + install_kernal_stability_bytes(&backend); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Left/right root test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Left/right root test: ASM view failed.")) return 1; + if (expect_highlighted_disasm(screen, "E000 85 56", "STA $56", + "Left/right root test: initial root incorrect.")) return 1; + + if (expect(monitor.poll(0) == 0, "Left/right root test: first right failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $E001") == header, + "Right must move ASM root by one byte to E001.")) return 1; + if (expect_highlighted_disasm(screen, "E001 56 20", NULL, + "Right to E001 must intentionally re-phase from E001.")) return 1; + + if (expect(monitor.poll(0) == 0, "Left/right root test: second right failed.")) return 1; + if (expect_highlighted_disasm(screen, "E002 20 0F BC", "JSR $BC0F", + "Second Right must move ASM root to E002.")) return 1; + if (expect(monitor.poll(0) == 0, "Left/right root test: first left failed.")) return 1; + if (expect_highlighted_disasm(screen, "E001 56 20", NULL, + "Left must move ASM root back to E001.")) return 1; + if (expect(monitor.poll(0) == 0, "Left/right root test: repeated right failed.")) return 1; + if (expect_highlighted_disasm(screen, "E002 20 0F BC", "JSR $BC0F", + "Repeated Right must be deterministic.")) return 1; + if (expect(monitor.poll(0) == 0, "Left/right root test: repeated left failed.")) return 1; + if (expect_highlighted_disasm(screen, "E001 56 20", NULL, + "Repeated Left must be deterministic.")) return 1; + if (expect(monitor.poll(0) == 1, "Left/right root test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_asm_ambiguous_predecessor_is_stable(void) +{ + for (int pass = 0; pass < 2; pass++) { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'J', 'A', KEY_UP, KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + monitor_reset_saved_state(); + + backend.write(0xC000, 0x20); + backend.write(0xC001, 0xA9); + backend.write(0xC002, 0x00); + backend.write(0xC003, 0xEA); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("C003", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Ambiguous predecessor test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Ambiguous predecessor test: ASM view failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Ambiguous predecessor test: Up failed.")) return 1; + if (expect_highlighted_disasm(screen, "C000 20 A9 00", "JSR $00A9", + "Ambiguous predecessor must use the deterministic longest fallback.")) return 1; + if (expect(monitor.poll(0) == 1, "Ambiguous predecessor test: exit failed.")) return 1; + monitor.deinit(); + } + return 0; +} + +static int test_asm_edit_left_right_does_not_rephase_root(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'J', 'A', 'E', KEY_RIGHT, KEY_LEFT, KEY_LEFT, KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + monitor_reset_saved_state(); + + backend.write(0xBFFE, 0xEA); + backend.write(0xBFFF, 0xEA); + backend.write(0xC000, 0xA9); + backend.write(0xC001, 0x12); + backend.write(0xC002, 0xEA); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("C000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "ASM edit isolation test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM edit isolation test: ASM view failed.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM edit isolation test: edit entry failed.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM edit isolation test: right failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C000") == header, + "ASM edit Right must not change the root address within the row.")) return 1; + if (expect_highlighted_disasm(screen, "C000 A9 12", "LDA #$12", + "ASM edit Right must not re-phase the current row.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM edit isolation test: left within row failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C000") == header, + "ASM edit Left within the row must not change the root address.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM edit isolation test: left boundary failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $BFFF") == header, + "ASM edit Left at the first editable part must be the only inter-row movement.")) return 1; + if (expect(monitor.poll(0) == 0, "ASM edit isolation test: leave edit failed.")) return 1; + if (expect(monitor.poll(0) == 1, "ASM edit isolation test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_asm_self_modification_root_rules(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'J', 'A', 'P' }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + monitor_reset_saved_state(); + + backend.write(0xE002, 0xA9); + backend.write(0xE003, 0x00); + backend.write(0xE004, 0xEA); + backend.write(0xE005, 0xA5); + backend.write(0xE006, 0x61); + backend.write(0xE007, 0xEA); + backend.write(0xE008, 0xEA); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E005", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "Self-mod root test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Self-mod root test: ASM view failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Self-mod root test: poll mode failed.")) return 1; + if (expect_highlighted_disasm(screen, "E005 A5 61", "LDA $61", + "Self-mod root test: initial E005 root incorrect.")) return 1; + + backend.write(0xE002, 0x20); + backend.write(0xE003, 0x05); + backend.write(0xE004, 0xE0); + advance_fake_ms_timer(1000); + if (expect(monitor.poll(0) == 0, "Self-mod root test: redraw after pre-root mutation failed.")) return 1; + if (expect_highlighted_disasm(screen, "E005 A5 61", "LDA $61", + "Self-modification before root must not re-phase E005.")) return 1; + + backend.write(0xE005, 0xA9); + backend.write(0xE006, 0x42); + advance_fake_ms_timer(1000); + if (expect(monitor.poll(0) == 0, "Self-mod root test: redraw after root mutation failed.")) return 1; + if (expect_highlighted_disasm(screen, "E005 A9 42", "LDA #$42", + "Self-modification at root must re-decode the current row.")) return 1; + + backend.write(0xE007, 0x60); + advance_fake_ms_timer(1000); + if (expect(monitor.poll(0) == 0, "Self-mod root test: redraw after later mutation failed.")) return 1; + if (expect_visible_disasm(screen, "E007 60", "RTS", + "Self-modification after root must re-decode the affected later row.")) return 1; + + monitor.deinit(); + return 0; +} + +static int test_asm_cpu_bank_invalidation_for_root(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + int keys[16]; + int n = 0; + monitor_reset_saved_state(); + + keys[n++] = 'J'; + keys[n++] = 'A'; + keys[n++] = 'o'; + for (int i = 0; i < 7; i++) { + keys[n++] = 'o'; + } + keys[n++] = KEY_BREAK; + FakeKeyboard keyboard(keys, n); + + install_kernal_stability_bytes(&backend); + backend.ram[0xE000] = 0x00; + backend.ram[0xE001] = 0xEA; + backend.ram[0xE002] = 0xEA; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "CPU-bank invalidation test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU-bank invalidation test: ASM view failed.")) return 1; + if (expect_highlighted_disasm(screen, "E000 85 56", "STA $56", + "CPU-bank invalidation test: CPU7 KERNAL row missing.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU-bank invalidation test: switch to CPU0 failed.")) return 1; + if (expect_highlighted_disasm(screen, "E000 00", "BRK", + "Switching to CPU0 must re-read RAM instead of reusing CPU7 KERNAL rows.")) return 1; + for (int i = 0; i < 7; i++) { + if (expect(monitor.poll(0) == 0, "CPU-bank invalidation test: switch back to CPU7 failed.")) return 1; + } + if (expect_highlighted_disasm(screen, "E000 85 56", "STA $56", + "Switching back to CPU7 must restore the KERNAL decode.")) return 1; + if (expect(monitor.poll(0) == 1, "CPU-bank invalidation test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_asm_all_cpu_banks_keep_explicit_root(void) +{ + for (uint8_t bank = 0; bank < 8; bank++) { + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + int keys[16]; + int n = 0; + monitor_reset_saved_state(); + + keys[n++] = 'J'; + keys[n++] = 'A'; + for (uint8_t i = 0; i <= bank && bank != 7; i++) { + keys[n++] = 'o'; + } + keys[n++] = 'P'; + FakeKeyboard keyboard(keys, n); + + backend.ram[0xE000] = 0xA9; + backend.ram[0xE001] = bank; + backend.kernal[0] = 0xEA; + backend.ram[0xDFFE] = 0x20; + backend.ram[0xDFFF] = 0x00; + backend.io[0x0FFE] = 0x20; + backend.io[0x0FFF] = 0x00; + backend.charrom[0x0FFE] = 0x20; + backend.charrom[0x0FFF] = 0x00; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "All-bank root test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "All-bank root test: ASM view failed.")) return 1; + for (uint8_t i = 0; i <= bank && bank != 7; i++) { + if (expect(monitor.poll(0) == 0, "All-bank root test: CPU bank cycle failed.")) return 1; + } + if (expect(monitor.poll(0) == 0, "All-bank root test: poll mode failed.")) return 1; + + if (bank & 0x02) { + if (expect_highlighted_disasm(screen, "E000 EA", "NOP", + "All-bank root test: KERNAL-visible bank must decode KERNAL at E000.")) return 1; + } else { + if (expect_highlighted_disasm(screen, "E000 A9", NULL, + "All-bank root test: RAM-visible bank must decode RAM at E000.")) return 1; + } + advance_fake_ms_timer(1000); + if (expect(monitor.poll(0) == 0, "All-bank root test: redraw failed.")) return 1; + if (bank & 0x02) { + if (expect_highlighted_disasm(screen, "E000 EA", "NOP", + "All-bank root test: redraw must preserve KERNAL root phase.")) return 1; + } else { + if (expect_highlighted_disasm(screen, "E000 A9", NULL, + "All-bank root test: redraw must preserve RAM root phase.")) return 1; + } + monitor.deinit(); + } + return 0; +} + +static int test_disassembly_instruction_stepping(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char line[39]; + char header[39]; + static const struct { + const char *header; + const char *row; + const char *text; + } down_steps[] = { + { "MONITOR ASM $E002", "E002 20 0F BC", "JSR $BC0F" }, + { "MONITOR ASM $E005", "E005 A5 61", "LDA $61" }, + { "MONITOR ASM $E007", "E007 C9 88", "CMP #$88" }, + { "MONITOR ASM $E009", "E009 90 03", "BCC $E00E" }, + { "MONITOR ASM $E00B", "E00B 20 D4 BA", "JSR $BAD4" }, + { "MONITOR ASM $E00E", "E00E 20 CC BC", "JSR $BCCC" }, + { "MONITOR ASM $E011", "E011 A5 07", "LDA $07" }, + { "MONITOR ASM $E013", "E013 18", "CLC" }, + }; + monitor_reset_saved_state(); + + const int keys[] = { + 'J', 'A', + KEY_DOWN, KEY_DOWN, KEY_DOWN, KEY_DOWN, + KEY_DOWN, KEY_DOWN, KEY_DOWN, KEY_DOWN, + KEY_UP, KEY_UP, KEY_BREAK + }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + + install_kernal_stability_bytes(&backend); + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Goto to E000 failed for disassembly stepping test.")) return 1; + if (expect(monitor.poll(0) == 0, "Disassembly view switch failed for stepping test.")) return 1; + + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR ASM $E000") == line, "Disassembly view must start at the goto address.")) return 1; + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "E000 85 56") == line, "Initial disassembly row mismatch at E000.")) return 1; + if (expect_highlighted_disasm(screen, "E000 85 56", "STA $56", + "Initial highlighted ASM row must be E000.")) return 1; + + backend.io[0x0FFD] = 0x4C; + backend.io[0x0FFE] = 0x00; + backend.io[0x0FFF] = 0xE0; + + for (unsigned i = 0; i < sizeof(down_steps) / sizeof(down_steps[0]); i++) { + if (expect(monitor.poll(0) == 0, "Disassembly down-step failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, down_steps[i].header) == header, + "Disassembly header must follow the selected canonical instruction.")) return 1; + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "E000 85 56") == line, + "Ordinary ASM Down must keep the E000 viewport top while the selected row is visible.")) return 1; + if (expect(!visible_disasm_exists(screen, "E001 ", NULL), + "Ordinary ASM Down must not re-phase the KERNAL lane to E001.")) return 1; + if (expect_highlighted_disasm(screen, down_steps[i].row, down_steps[i].text, + "ASM Down must select the next row in the established KERNAL lane.")) return 1; + } + + if (expect(monitor.poll(0) == 0, "First disassembly up-step from E013 failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $E011") == header, + "ASM Up from E013 must select the cached E011 predecessor, not E010.")) return 1; + if (expect_highlighted_disasm(screen, "E011 A5 07", "LDA $07", + "ASM Up from E013 highlighted the wrong predecessor.")) return 1; + if (expect(!visible_disasm_exists(screen, "E010 ", NULL), + "The canonical E000 lane must not show the overlapping E010 candidate.")) return 1; + + if (expect(monitor.poll(0) == 0, "Second disassembly up-step from E011 failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $E00E") == header, + "ASM Up from E011 must select E00E.")) return 1; + if (expect_highlighted_disasm(screen, "E00E 20 CC BC", "JSR $BCCC", + "ASM Up from E011 highlighted the wrong predecessor.")) return 1; + if (expect(!visible_disasm_exists(screen, "E010 ", NULL), + "The screen must not contain the stale overlapping E010 row after moving up to E00E.")) return 1; + + if (expect(monitor.poll(0) == 1, "RUN/STOP exit failed after disassembly stepping test.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_disassembly_reverse_navigation_reuses_cached_lane(void) +{ + enum { STEPS = 24 }; + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char expected[STEPS + 1][MONITOR_DISASM_ROW_CHARS + 1]; + char actual[MONITOR_DISASM_ROW_CHARS + 1]; + int keys[64]; + int key_count = 0; + + monitor_reset_saved_state(); + keys[key_count++] = 'J'; + keys[key_count++] = 'A'; + for (int i = 0; i < STEPS; i++) keys[key_count++] = KEY_DOWN; + for (int i = 0; i < STEPS + 1; i++) keys[key_count++] = KEY_UP; + keys[key_count++] = KEY_BREAK; + FakeKeyboard keyboard(keys, key_count); + + install_kernal_stability_bytes(&backend); + for (uint16_t addr = 0xE000 + sizeof(asm_kernal_stability_bytes); addr < 0xE080; addr++) { + backend.kernal[addr - 0xE000] = 0xEA; + backend.ram[addr] = 0xEA; + } + backend.io[0x0FFD] = 0x4C; + backend.io[0x0FFE] = 0x00; + backend.io[0x0FFF] = 0xE0; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Reverse lane test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Reverse lane test: ASM view failed.")) return 1; + if (copy_highlighted_disasm_line(screen, expected[0], + "Reverse lane test: initial highlighted row missing.")) return 1; + + for (int i = 1; i <= STEPS; i++) { + if (expect(monitor.poll(0) == 0, "Reverse lane test: down navigation failed.")) return 1; + if (copy_highlighted_disasm_line(screen, expected[i], + "Reverse lane test: highlighted row missing while moving down.")) return 1; + if (expect(!visible_disasm_exists(screen, "E001 ", NULL), + "Reverse lane test: down navigation must not expose E001 rephase.")) return 1; + if (expect(!visible_disasm_exists(screen, "E003 ", NULL), + "Reverse lane test: down navigation must not expose E003 rephase.")) return 1; + if (expect(!visible_disasm_exists(screen, "E010 ", NULL), + "Reverse lane test: down navigation must not expose E010 overlap.")) return 1; + } + + for (int i = STEPS - 1; i >= 0; i--) { + if (expect(monitor.poll(0) == 0, "Reverse lane test: up navigation failed.")) return 1; + if (copy_highlighted_disasm_line(screen, actual, + "Reverse lane test: highlighted row missing while moving up.")) return 1; + if (expect(strcmp(actual, expected[i]) == 0, + "Reverse lane test: upward navigation must highlight the exact row seen during downward navigation.")) return 1; + if (expect(!visible_disasm_exists(screen, "E001 ", NULL), + "Reverse lane test: up navigation must not expose E001 rephase.")) return 1; + if (expect(!visible_disasm_exists(screen, "E003 ", NULL), + "Reverse lane test: up navigation must not expose E003 rephase.")) return 1; + if (expect(!visible_disasm_exists(screen, "E010 ", NULL), + "Reverse lane test: up navigation must not expose E010 overlap.")) return 1; + } + + if (expect(monitor.poll(0) == 0, "Reverse lane test: up beyond E000 failed.")) return 1; + if (expect_highlighted_disasm(screen, "DFFD 4C 00 E0", "JMP $E000", + "Reverse lane test: up beyond E000 must prepend the IO prefix row without redecoding E000.")) return 1; + if (expect_visible_disasm(screen, "E000 85 56", "STA $56", + "Reverse lane test: E000 row must remain canonical after prepending context.")) return 1; + if (expect(!visible_disasm_exists(screen, "E001 ", NULL), + "Reverse lane test: up beyond E000 must not re-phase to E001.")) return 1; + if (expect(!visible_disasm_exists(screen, "E003 ", NULL), + "Reverse lane test: up beyond E000 must not re-phase to E003.")) return 1; + + if (expect(monitor.poll(0) == 1, "Reverse lane test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_disassembly_reverse_navigation_refuses_overlapping_predecessor(void) +{ + enum { STEPS = 8 }; + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + int keys[32]; + int key_count = 0; + + monitor_reset_saved_state(); + keys[key_count++] = 'J'; + keys[key_count++] = 'A'; + for (int i = 0; i < STEPS; i++) keys[key_count++] = KEY_DOWN; + for (int i = 0; i < STEPS + 1; i++) keys[key_count++] = KEY_UP; + keys[key_count++] = KEY_BREAK; + FakeKeyboard keyboard(keys, key_count); + + install_kernal_stability_bytes(&backend); + backend.io[0x0FFD] = 0xEA; + backend.io[0x0FFE] = 0xEA; + backend.io[0x0FFF] = 0x8D; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Reverse overlap test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Reverse overlap test: ASM view failed.")) return 1; + for (int i = 0; i < STEPS; i++) { + if (expect(monitor.poll(0) == 0, "Reverse overlap test: down navigation failed.")) return 1; + } + for (int i = 0; i < STEPS + 1; i++) { + if (expect(monitor.poll(0) == 0, "Reverse overlap test: up navigation failed.")) return 1; + } + + if (expect_highlighted_disasm(screen, "DFFF 8D", "???", + "Reverse overlap test: ambiguous predecessor must use a one-byte boundary row.")) return 1; + if (expect(!visible_disasm_exists(screen, "DFFF 8D 85 56", NULL), + "Reverse overlap test: invalid DFFF predecessor must not be prepended.")) return 1; + if (expect_visible_disasm(screen, "E000 85 56", "STA $56", + "Reverse overlap test: E000 row must remain canonical below the boundary row.")) return 1; + if (expect(!visible_disasm_exists(screen, "E001 ", NULL), + "Reverse overlap test: invalid predecessor must not re-phase to E001.")) return 1; + if (expect(monitor.poll(0) == 1, "Reverse overlap test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_disassembly_sliding_lane_scrolls_beyond_cache(void) +{ + enum { STEPS = 300 }; + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int keys[STEPS * 2 + 4]; + int key_count = 0; + + monitor_reset_saved_state(); + keys[key_count++] = 'J'; + keys[key_count++] = 'A'; + for (int i = 0; i < STEPS; i++) keys[key_count++] = KEY_UP; + for (int i = 0; i < STEPS; i++) keys[key_count++] = KEY_DOWN; + keys[key_count++] = KEY_BREAK; + FakeKeyboard keyboard(keys, key_count); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("C300", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Sliding lane test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Sliding lane test: ASM view failed.")) return 1; + for (int i = 0; i < STEPS; i++) { + if (expect(monitor.poll(0) == 0, "Sliding lane test: upward navigation failed.")) return 1; + } + if (expect_highlighted_disasm(screen, "C1D4 ", NULL, + "Sliding lane test: upward scrolling must continue beyond the cache window.")) return 1; + for (int i = 0; i < STEPS; i++) { + if (expect(monitor.poll(0) == 0, "Sliding lane test: downward navigation failed.")) return 1; + } + if (expect_highlighted_disasm(screen, "C300 ", NULL, + "Sliding lane test: downward scrolling must rebuild rows after tail eviction.")) return 1; + if (expect(monitor.poll(0) == 1, "Sliding lane test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_disassembly_boundary_cutover(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char line[39]; + int keys[32]; + int key_count = 0; + int row_before_wrap = -1; + int row_after_wrap = -1; + int row_before_up = -1; + int row_after_up = -1; + + keys[key_count++] = 'J'; + keys[key_count++] = 'A'; + for (int i = 0; i < 17; i++) { + keys[key_count++] = KEY_DOWN; + } + keys[key_count++] = KEY_DOWN; + keys[key_count++] = KEY_UP; + keys[key_count++] = KEY_BREAK; + FakeKeyboard keyboard(keys, key_count); + + monitor_reset_saved_state(); + memset(backend.memory, 0xEA, sizeof(backend.memory)); + for (uint32_t address = 0xFFEE; address <= 0xFFFF; address++) { + backend.write((uint16_t)address, 0xEA); + } + backend.write(0xFFFE, 0x48); + backend.write(0xFFFF, 0x4C); + backend.write(0x0000, 0xEA); + backend.write(0x0001, 0xEA); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("FFEE", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Disassembly boundary test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Disassembly boundary test: ASM view switch failed.")) return 1; + + for (int i = 0; i < 17; i++) { + if (expect(monitor.poll(0) == 0, "Disassembly boundary test: step toward $FFFF failed.")) return 1; + } + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $FFFF") == header, + "Scrolling down near the boundary must land on $FFFF before cutover.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_before_wrap), + "Disassembly boundary test: highlighted row not found at $FFFF.")) return 1; + if (expect(row_before_wrap == 21, + "The $FFFF line must appear on the bottom visible row before cutover.")) return 1; + screen.get_slice(1, row_before_wrap, 38, line); + if (expect(strstr(line, "FFFF 4C") == line, + "The $FFFF row must render only the local tail byte before cutover.")) return 1; + if (expect(strstr(line, "???") != NULL, + "The $FFFF row must not decode across the $FFFF/$0000 boundary.")) return 1; + + if (expect(monitor.poll(0) == 0, "Disassembly boundary test: forward cutover failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $0000") == header, + "Stepping past $FFFF must cut over to $0000.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_after_wrap), + "Disassembly boundary test: highlighted row not found after forward cutover.")) return 1; + if (expect(row_after_wrap == 4, + "Forward cutover must redraw with $0000 on the first visible row.")) return 1; + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "0000 EA") == line, + "The first visible row after forward cutover must start at $0000.")) return 1; + + if (expect(find_highlighted_cell(screen, NULL, &row_before_up), + "Disassembly boundary test: highlighted row not found before reverse cutover.")) return 1; + if (expect(row_before_up == 4, + "Reverse cutover must start from the first visible row at $0000.")) return 1; + + if (expect(monitor.poll(0) == 0, "Disassembly boundary test: reverse cutover failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $FFFF") == header, + "Stepping up from $0000 must cut over to $FFFF.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_after_up), + "Disassembly boundary test: highlighted row not found after reverse cutover.")) return 1; + if (expect(row_after_up == 21, + "Reverse cutover must redraw with $FFFF on the bottom visible row.")) return 1; + screen.get_slice(1, row_after_up, 38, line); + if (expect(strstr(line, "FFFF 4C") == line, + "Reverse cutover must restore the $FFFF tail row at the bottom.")) return 1; + + if (expect(monitor.poll(0) == 1, "RUN/STOP exit failed after disassembly boundary test.")) return 1; + monitor.deinit(); + + return 0; +} + +static int test_disassembly_reverse_cutover_keeps_ffff_at_bottom(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char line[39]; + int row = -1; + const int keys[] = { 'A', 'J', KEY_UP, KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + + monitor_reset_saved_state(); + memset(backend.memory, 0xEA, sizeof(backend.memory)); + for (uint16_t address = 0xFFEE; address <= 0xFFFC; address = (uint16_t)(address + 3)) { + backend.write(address, 0x20); + backend.write((uint16_t)(address + 1), 0x00); + backend.write((uint16_t)(address + 2), 0x00); + } + backend.write(0xFFFD, 0xEA); + backend.write(0xFFFE, 0x48); + backend.write(0xFFFF, 0x4C); + backend.write(0x0000, 0xEA); + backend.write(0x0001, 0xEA); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("0000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Disassembly reverse boundary test: ASM view switch failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Disassembly reverse boundary test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Disassembly reverse boundary test: step up failed.")) return 1; + + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $FFFF") == header, + "Reverse cutover from $0000 must land on $FFFF in ASM view.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row), + "Disassembly reverse boundary test: highlighted row not found after wrap.")) return 1; + if (expect(row == 21, + "ASM reverse cutover must keep $FFFF on the bottom visible row even when earlier rows are multi-byte instructions.")) return 1; + + screen.get_slice(1, 19, 38, line); + if (expect(strstr(line, "FFFD EA") == line, + "ASM reverse cutover must keep the tail byte rows directly above $FFFF.")) return 1; + screen.get_slice(1, 20, 38, line); + if (expect(strstr(line, "FFFE 48") == line, + "ASM reverse cutover must show $FFFE immediately above $FFFF.")) return 1; + screen.get_slice(1, 21, 38, line); + if (expect(strstr(line, "FFFF 4C") == line, + "ASM reverse cutover must leave $FFFF on the bottom row without drawing wrapped rows below it.")) return 1; + + if (expect(monitor.poll(0) == 1, "Disassembly reverse boundary test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_hex_reverse_wrap_keeps_tail_row_at_bottom(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char line[39]; + int row = -1; + const int keys[] = { 'J', KEY_LEFT, KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + + monitor_reset_saved_state(); + memset(backend.memory, 0xEA, sizeof(backend.memory)); + backend.write(0xFFFF, 0x4C); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("0000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "HEX reverse wrap test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "HEX reverse wrap test: left wrap failed.")) return 1; + + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $FFFF") == header, + "HEX reverse wrap must land on $FFFF.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row), + "HEX reverse wrap test: highlighted cell not found after wrap.")) return 1; + if (expect(row == 21, + "HEX reverse wrap must keep the tail memory row on the bottom of the screen.")) return 1; + screen.get_slice(1, 21, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "FFF8") == line, + "HEX reverse wrap must show the final memory row at the bottom after wrapping to $FFFF.")) return 1; + + if (expect(monitor.poll(0) == 1, "HEX reverse wrap test: exit failed.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_last_address_row_highlight(void) +{ + struct ViewHighlightCase { + const char *name; + const char *expected_header; + const int *keys; + int key_count; + }; + + static const int hex_keys[] = { 'J', KEY_BREAK }; + static const int ascii_keys[] = { 'I', 'J', KEY_BREAK }; + static const int screen_keys[] = { 'V', 'J', KEY_BREAK }; + static const int binary_keys[] = { 'B', 'J', KEY_BREAK }; + static const int asm_keys[] = { 'A', 'J', KEY_BREAK }; + static const ViewHighlightCase cases[] = { + { "HEX", "MONITOR HEX $FFFF", hex_keys, (int)(sizeof(hex_keys) / sizeof(hex_keys[0])) }, + { "ASC", "MONITOR ASC $FFFF", ascii_keys, (int)(sizeof(ascii_keys) / sizeof(ascii_keys[0])) }, + { "SCR", "MONITOR SCR U/G $FFFF", screen_keys, (int)(sizeof(screen_keys) / sizeof(screen_keys[0])) }, + { "BIN", "MONITOR BIN $FFFF/7", binary_keys, (int)(sizeof(binary_keys) / sizeof(binary_keys[0])) }, + { "ASM", "MONITOR ASM $FFFF", asm_keys, (int)(sizeof(asm_keys) / sizeof(asm_keys[0])) }, + }; + + char message[128]; + char header[39]; + + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + FakeKeyboard keyboard(cases[i].keys, cases[i].key_count); + int row = 0; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("FFFF", 1); + + monitor_reset_saved_state(); + backend.write(0xFFFF, 0x4C); + backend.write(0x0000, 0xEA); + backend.write(0x0001, 0xEA); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + for (int step = 0; step < cases[i].key_count - 1; step++) { + sprintf(message, "%s $FFFF highlight test: command step %d failed.", cases[i].name, step + 1); + if (expect(monitor.poll(0) == 0, message)) return 1; + } + + screen.get_slice(1, 3, 38, header); + sprintf(message, "%s $FFFF highlight test: header must stay on the active address.", cases[i].name); + if (expect(strstr(header, cases[i].expected_header) == header, message)) return 1; + sprintf(message, "%s $FFFF highlight test: highlighted cell not found.", cases[i].name); + if (expect(find_highlighted_cell(screen, NULL, &row), message)) return 1; + sprintf(message, "%s $FFFF highlight test: highlight must remain on the first visible row after goto.", cases[i].name); + if (expect(row == 4, message)) return 1; + + sprintf(message, "%s $FFFF highlight test: exit failed.", cases[i].name); + if (expect(monitor.poll(0) == 1, message)) return 1; + monitor.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'J', 'e', KEY_BREAK, KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + int row = 0; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("FFFF", 1); + + monitor_reset_saved_state(); + backend.write(0xFFFF, 0x4C); + backend.write(0x0000, 0xEA); + backend.write(0x0001, 0xEA); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(monitor.poll(0) == 0, "HEX edit $FFFF cursor test: goto failed.")) return 1; + if (expect(monitor.poll(0) == 0, "HEX edit $FFFF cursor test: edit mode entry failed.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row), + "HEX edit $FFFF cursor test: highlighted cell not found.")) return 1; + if (expect(row == 4, + "HEX edit $FFFF cursor test: highlighted byte must remain visible on the first row.")) return 1; + if (expect(screen.reverse_chars[4][27] && screen.reverse_chars[4][28], + "HEX edit $FFFF cursor test: both digits of the active byte must stay highlighted.")) return 1; + if (expect(monitor.poll(0) == 0, "HEX edit $FFFF cursor test: first RUN/STOP should leave edit mode.")) return 1; + if (expect(monitor.poll(0) == 1, "HEX edit $FFFF cursor test: second RUN/STOP should exit the monitor.")) return 1; + monitor.deinit(); + } + + return 0; +} + +static int test_template_cursor(void) +{ + char template_buffer[8] = "AAAA"; + const int keys[] = { 'E', KEY_RETURN }; + FakeKeyboard keyboard(keys, 2); + CaptureScreen screen; + CaptureWindow window(&screen, 8); + UIStringEdit edit(template_buffer, 7, true); + + edit.init(&window, &keyboard, 0, 0, 8); + if (expect(window.last_x == 0 && window.last_y == 0, "Template cursor did not start at first editable character.")) return 1; + if (expect(edit.poll(0) == 0, "Template edit returned early.")) return 1; + if (expect(strcmp(template_buffer, "E") == 0, "Template input did not replace placeholder immediately.")) return 1; + if (expect(edit.poll(0) == 1, "Template edit did not accept return.")) return 1; + return 0; +} + +static int test_task_action_lookup(void) +{ + TaskActionProvider provider; + + TaskMenu::ensure_task_actions_created(true); + if (expect(provider.update_called && provider.last_writable, "Task action update hook was not called.")) return 1; + if (expect(provider.monitor_action != NULL, "Task action provider did not create the monitor action.")) return 1; + if (expect(provider.monitor_action->isPersistent(), "Task action should be made persistent.")) return 1; + if (expect(get_machine_monitor_task(TEST_SUBSYSID_U64) == provider.monitor_action, + "U64 task action lookup failed.")) return 1; + if (expect(get_machine_monitor_task(TEST_SUBSYSID_C64) == provider.monitor_action, + "C64 task action lookup failed.")) return 1; + return 0; +} + +static int test_monitor_renders_window_border(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { KEY_BREAK }; + FakeKeyboard keyboard(keys, 1); + monitor_reset_saved_state(); + + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + if (expect(backend.session_begin_count == 1, "Monitor must begin a backend session when it opens.")) return 1; + if (expect((unsigned char)screen.chars[2][0] == BORD_LOWER_RIGHT_CORNER, "Monitor must draw the same shared upper-left border corner as the hex editor.")) return 1; + if (expect((unsigned char)screen.chars[2][39] == BORD_LOWER_LEFT_CORNER, "Monitor must draw the same shared upper-right border corner as the hex editor.")) return 1; + if (expect((unsigned char)screen.chars[23][0] == BORD_UPPER_RIGHT_CORNER, "Monitor must draw the shared lower-left border corner.")) return 1; + if (expect((unsigned char)screen.chars[23][39] == BORD_UPPER_LEFT_CORNER, "Monitor must draw the shared lower-right border corner.")) return 1; + for (int y = 3; y < 23; y++) { + if (expect((unsigned char)screen.chars[y][0] == CHR_VERTICAL_LINE, "Monitor left border must be drawn for every row inside the frame.")) return 1; + if (expect((unsigned char)screen.chars[y][39] == CHR_VERTICAL_LINE, "Monitor right border must be drawn for every row inside the frame.")) return 1; + } + if (expect(monitor.poll(0) == 1, "Monitor must close on RUN/STOP after border verification.")) return 1; + monitor.deinit(); + if (expect(backend.session_end_count == 1, "Monitor must end the backend session when it closes.")) return 1; + return 0; +} + +static int test_monitor_byte_to_address_invariant(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + monitor_reset_saved_state(); + + for (uint32_t addr = 0; addr < 0x10000; addr++) { + backend.write((uint16_t)addr, (uint8_t)((addr >> 3) & 0xFF)); + } + + const int keys[] = { KEY_PAGEDOWN, KEY_PAGEDOWN, KEY_PAGEDOWN, KEY_BREAK }; + FakeKeyboard keyboard(keys, 4); + + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + for (int step = 0; step < 3; step++) { + if (expect(monitor.poll(0) == 0, "Page-down failed during byte-to-address invariant scan.")) return 1; + for (int row = 0; row < 16; row++) { + char line[MONITOR_HEX_ROW_CHARS + 1]; + screen.get_slice(1, 4 + row, MONITOR_HEX_ROW_CHARS, line); + uint16_t row_addr = 0; + for (int n = 0; n < 4; n++) { + char c = line[n]; + uint16_t digit = 0; + if (c >= '0' && c <= '9') digit = (uint16_t)(c - '0'); + else if (c >= 'a' && c <= 'f') digit = (uint16_t)(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') digit = (uint16_t)(c - 'A' + 10); + row_addr = (uint16_t)((row_addr << 4) | digit); + } + for (int b = 0; b < MONITOR_HEX_BYTES_PER_ROW; b++) { + int hi_pos = 5 + (3 * b); + int lo_pos = hi_pos + 1; + char hi = line[hi_pos]; + char lo = line[lo_pos]; + uint8_t parsed = 0; + uint8_t hi_v = (hi >= '0' && hi <= '9') ? (hi - '0') : ((hi >= 'a' && hi <= 'f') ? (hi - 'a' + 10) : (hi - 'A' + 10)); + uint8_t lo_v = (lo >= '0' && lo <= '9') ? (lo - '0') : ((lo >= 'a' && lo <= 'f') ? (lo - 'a' + 10) : (lo - 'A' + 10)); + parsed = (uint8_t)((hi_v << 4) | lo_v); + uint16_t cell_addr = (uint16_t)(row_addr + b); + uint8_t expected = backend.read(cell_addr); + if (expect(parsed == expected, "DISPLAY(addr) must equal CANONICAL_READ(addr) for every visible cell.")) return 1; + } + } + } + if (expect(monitor.poll(0) == 1, "Monitor must close on RUN/STOP after byte invariant scan.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_cursor_header_and_scroll(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + enum { visible_rows = 18 }; + char before_rows[visible_rows][MONITOR_HEX_ROW_CHARS + 1]; + char after_rows[visible_rows][MONITOR_HEX_ROW_CHARS + 1]; + char header[39]; + int keys[visible_rows + 1]; + monitor_reset_saved_state(); + + for (uint32_t addr = 0; addr < 0x10000; addr++) { + backend.write((uint16_t)addr, (uint8_t)((addr >> 3) & 0xFF)); + } + for (int i = 0; i < visible_rows; i++) { + keys[i] = KEY_DOWN; + } + keys[visible_rows] = KEY_BREAK; + + FakeKeyboard keyboard(keys, visible_rows + 1); + ui.screen = &screen; + ui.keyboard = &keyboard; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $0000") == header, "Header must report the active cursor address.")) return 1; + + for (int i = 0; i < visible_rows - 1; i++) { + if (expect(monitor.poll(0) == 0, "Down navigation failed before viewport scroll.")) return 1; + } + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $0088") == header, "Header must follow the cursor before the viewport scrolls.")) return 1; + for (int row = 0; row < visible_rows; row++) { + screen.get_slice(1, 4 + row, MONITOR_HEX_ROW_CHARS, before_rows[row]); + } + if (expect(strstr(before_rows[visible_rows - 1], "0088 ") == before_rows[visible_rows - 1] || + strstr(before_rows[visible_rows - 1], "0088") == before_rows[visible_rows - 1], + "Hex view should use the reclaimed row above the CPU/VIC status line.")) return 1; + + if (expect(monitor.poll(0) == 0, "Down navigation failed at the viewport boundary.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $0090") == header, "Header must follow the cursor when the viewport scrolls.")) return 1; + for (int row = 0; row < visible_rows; row++) { + screen.get_slice(1, 4 + row, MONITOR_HEX_ROW_CHARS, after_rows[row]); + } + for (int row = 1; row < visible_rows; row++) { + if (expect(strcmp(after_rows[row - 1], before_rows[row]) == 0, + "Scrolling down must shift each rendered row up by exactly one row span.")) return 1; + } + if (expect(monitor.poll(0) == 1, "Monitor must close on RUN/STOP after viewport scroll verification.")) return 1; + monitor.deinit(); + return 0; +} + +static int test_monitor_interaction(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + FakeBankedMemoryBackend banked_backend; + char line[MONITOR_DISASM_ROW_CHARS + 1]; + char status[39]; + static const char *expected_help_lines[] = { + "", + "M Memory I ASCII V Screen", + "A Assembly B Binary U Undoc/Case", + "J Jump G Go D Debug", + "", + "E Edit F Fill T Transfer", + "C Compare H Hunt N Number", + "W Width R Range P Poll", + "Z Freeze O CPU Bank SH+O VIC", + "L Load S Save", + "", + "Bookmarks: C=+B List C=+0-9 Jump", + "", + "Monitor: C=+O Open/Close", + "Leave edit: C=+E/RSTOP", + "Copy/Paste: C=+C / C=+V", + "Reset/Follow: C=+X Reset / RETURN", + NULL + }; + monitor_reset_saved_state(); + + for (int i = 0; i < MONITOR_TEXT_BYTES_PER_ROW * 18; i++) { + backend.write((uint16_t)i, (uint8_t)('A' + ((i / MONITOR_TEXT_BYTES_PER_ROW) % 26))); + } + + banked_backend.basic[0] = 0xBA; + banked_backend.ram[0xA000] = 0xAA; + banked_backend.io[0xD000 - 0xD000] = 0x10; + banked_backend.kernal[0] = 0x4C; + + const int help_keys[] = { 'J', 'o', 'o', KEY_F3, KEY_F3, KEY_BREAK }; + FakeKeyboard help_keyboard(help_keys, 6); + ui.screen = &screen; + ui.keyboard = &help_keyboard; + ui.set_prompt("A000", 1); + + BackendMachineMonitor help_monitor(&ui, &banked_backend); + help_monitor.init(&screen, &help_keyboard); + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR HEX $0000") == line && strstr(line, "CPU MAP") == NULL, + "Header must show only the view type and cursor address.")) return 1; + if (expect(screen.reverse_chars[4][6] && screen.reverse_chars[4][7], "Hex view did not highlight the selected byte.")) return 1; + if (expect(help_monitor.poll(0) == 0, "Goto to A000 failed.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR HEX $A000") == line && strstr(line, "CPU MAP") == NULL, + "Goto must update the header to the cursor address without CPU map text.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 ba", 7) == 0 || strncmp(line, "A000 BA", 7) == 0, "CPU banked BASIC view mismatch.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU7 $A:BAS $D:I/O $E:KRN VIC2 $8000") == status, + "Initial CPU/VIC status line mismatch.")) return 1; + + if (expect(help_monitor.poll(0) == 0, "CPU bank cycle to CPU0 failed.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 aa", 7) == 0 || strncmp(line, "A000 AA", 7) == 0, "CPU0 should expose RAM at A000.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C7O0 $A:RAM $D:RAM $E:RAM VIC2 $8000") == status, + "CPU0 monitor-view status did not update after O.")) return 1; + + if (expect(help_monitor.poll(0) == 0, "CPU bank cycle to CPU1 failed.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 aa", 7) == 0 || strncmp(line, "A000 AA", 7) == 0, "CPU1 should keep A000 in RAM.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C7O1 $A:RAM $D:CHR $E:RAM VIC2 $8000") == status, + "CPU1 monitor-view status did not update after O.")) return 1; + + if (expect(help_monitor.poll(0) == 0, "F3 help open failed.")) return 1; + screen.get_slice(1, 3, 38, status); + if (expect(strstr(status, "HELP") == status, "Help header should replace the normal view header.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "Page Up/Down: F1/SH+SPACE / F7/SPACE") == status, + "Help view should show the paging shortcuts on the footer row.")) return 1; + { + for (int i = 0; expected_help_lines[i]; i++) { + screen.get_slice(1, 4 + i, 38, line); + if (expect(strncmp(line, expected_help_lines[i], strlen(expected_help_lines[i])) == 0, + "Help view text did not match the requested layout.")) return 1; + } + } + + if (expect(help_monitor.poll(0) == 0, "F3 help close failed.")) return 1; + screen.get_slice(1, 3, 38, status); + if (expect(strstr(status, "MONITOR HEX $A000") == status, "Closing help should restore the normal header.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 aa", 7) == 0 || strncmp(line, "A000 AA", 7) == 0, "Help toggle did not restore the monitor view.")) return 1; + + { + const int esc_help_keys[] = { KEY_F3, KEY_ESCAPE, KEY_ESCAPE }; + FakeKeyboard esc_help_keyboard(esc_help_keys, 3); + ui.keyboard = &esc_help_keyboard; + screen.clear(); + monitor_reset_saved_state(); + + BackendMachineMonitor esc_help_monitor(&ui, &backend); + esc_help_monitor.init(&screen, &esc_help_keyboard); + if (expect(esc_help_monitor.poll(0) == 0, "F3 should open help before ESC handling is tested.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "Page Up/Down: F1/SH+SPACE / F7/SPACE") == status, + "Help must show the paging shortcuts before ESC closes it.")) return 1; + for (int i = 0; expected_help_lines[i]; i++) { + screen.get_slice(1, 4 + i, 38, line); + if (expect(strncmp(line, expected_help_lines[i], strlen(expected_help_lines[i])) == 0, + "Help must be visible before ESC closes it.")) return 1; + } + if (expect(esc_help_monitor.poll(0) == 0, "ESC should close help without exiting the monitor.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR HEX $0000") == line, "ESC should restore the normal monitor header after closing help.")) return 1; + if (expect(esc_help_monitor.poll(0) == 1, "ESC should exit the monitor only after help is already closed.")) return 1; + esc_help_monitor.deinit(); + } + + ui.set_prompt("E013", 1); + const int goto_disasm_keys[] = { 'J', 'A', KEY_BREAK }; + FakeKeyboard goto_disasm_keyboard(goto_disasm_keys, 3); + ui.keyboard = &goto_disasm_keyboard; + screen.clear(); + monitor_reset_saved_state(); + + BackendMachineMonitor goto_disasm_monitor(&ui, &banked_backend); + goto_disasm_monitor.init(&screen, &goto_disasm_keyboard); + if (expect(goto_disasm_monitor.poll(0) == 0, "Goto to E013 failed for disassembly anchoring test.")) return 1; + if (expect(goto_disasm_monitor.poll(0) == 0, "Disassembly view switch failed for E013 anchoring test.")) return 1; + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "E013 18") != line, "Disassembly view should anchor the top row at the goto address.")) return 1; + if (expect(goto_disasm_monitor.poll(0) == 1, "RUN/STOP exit failed after disassembly anchoring test.")) return 1; + goto_disasm_monitor.deinit(); + + if (expect(help_monitor.poll(0) == 1, "RUN/STOP exit failed.")) return 1; + help_monitor.deinit(); + + { + FakeKeyboard idle_keyboard(NULL, 0); + ui.keyboard = &idle_keyboard; + screen.clear(); + banked_backend.live_cpu_port = 0x00; + banked_backend.live_cpu_ddr = 0x07; + banked_backend.live_dd00 = 0x01; + monitor_reset_saved_state(); + + BackendMachineMonitor vic_monitor(&ui, &banked_backend); + vic_monitor.init(&screen, &idle_keyboard); + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C0O7 $A:BAS $D:I/O $E:KRN VIC2 $8000") == status, + "Idle VIC refresh test should show live CPU0 and monitor CPU7 separately.")) return 1; + banked_backend.live_dd00 = 0x00; + if (expect(vic_monitor.poll(0) == 0, "VIC idle refresh poll failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C0O7 $A:BAS $D:I/O $E:KRN VIC3 $C000") == status, + "VIC status did not refresh after DD00 change.")) return 1; + vic_monitor.deinit(); + } + + { + const int live_bank_keys[] = { 'J' }; + FakeKeyboard live_bank_keyboard(live_bank_keys, 1); + ui.keyboard = &live_bank_keyboard; + ui.set_prompt("A000", 1); + screen.clear(); + banked_backend.live_cpu_port = 0x01; + banked_backend.live_cpu_ddr = 0x00; + banked_backend.live_dd00 = 0x01; + monitor_reset_saved_state(); + + BackendMachineMonitor live_bank_monitor(&ui, &banked_backend); + live_bank_monitor.init(&screen, &live_bank_keyboard); + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU7 $A:BAS $D:I/O $E:KRN VIC2 $8000") == status, + "Fresh monitor sessions should still default to CPU7 even when the live machine is banked differently.")) return 1; + if (expect(live_bank_monitor.poll(0) == 0, "Goto to A000 failed for default CPU7 test.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 ba", 7) == 0 || strncmp(line, "A000 BA", 7) == 0, + "Default CPU7 should keep BASIC visible at A000.")) return 1; + live_bank_monitor.deinit(); + } + + const int blink_keys[] = { 'I', 'e' }; + FakeKeyboard blink_keyboard(blink_keys, 2); + ui.keyboard = &blink_keyboard; + screen.clear(); + monitor_reset_saved_state(); + + BackendMachineMonitor blink_monitor(&ui, &backend); + blink_monitor.init(&screen, &blink_keyboard); + if (expect(blink_monitor.poll(0) == 0, "ASCII view command failed for blink test.")) return 1; + if (expect(blink_monitor.poll(0) == 0, "ASCII edit mode entry via 'e' failed.")) return 1; + if (expect(screen.reverse_chars[4][6], "ASCII edit did not initially show the active cursor.")) return 1; + if (expect(blink_monitor.poll(0) == 0 && blink_monitor.poll(0) == 0 && blink_monitor.poll(0) == 0, + "Idle highlight polling failed.")) return 1; + if (expect(screen.reverse_chars[4][6], "ASCII edit highlight should stay deterministic during idle redraws.")) return 1; + blink_monitor.deinit(); + + const int view_keys[] = { 'I', KEY_DOWN, KEY_UP, 'e', 'Z', KEY_LEFT, 'Y', KEY_BREAK, KEY_BREAK }; + FakeKeyboard view_keyboard(view_keys, 9); + ui.keyboard = &view_keyboard; + ui.popup_count = 0; + ui.navmode = 1; + screen.clear(); + monitor_reset_saved_state(); + + BackendMachineMonitor view_monitor(&ui, &backend); + view_monitor.init(&screen, &view_keyboard); + + if (expect(view_monitor.poll(0) == 0, "ASCII view command failed.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR ASC $0000") == line, "ASCII header must start at the cursor address.")) return 1; + screen.get_slice(1, 4, MONITOR_TEXT_ROW_CHARS, line); + if (expect(strcmp(line, "0000 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") == 0, "ASCII first-row rendering mismatch.")) return 1; + screen.get_slice(1, 12, MONITOR_TEXT_ROW_CHARS, line); + if (expect(strcmp(line, "0100 IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII") == 0, "ASCII later-row rendering mismatch.")) return 1; + screen.get_slice(1, 21, MONITOR_TEXT_ROW_CHARS, line); + if (expect(strcmp(line, "0220 RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR") == 0, "ASCII bottom-row rendering should use the reclaimed rows.")) return 1; + if (expect((unsigned char)screen.chars[4][39] == CHR_VERTICAL_LINE, "ASCII view overwrote the right border.")) return 1; + + if (expect(view_monitor.poll(0) == 0, "ASCII down navigation failed.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR ASC $0020") == line, "ASCII header must follow the cursor within the viewport.")) return 1; + if (expect(screen.reverse_chars[5][6], "ASCII down should move the cursor one 32-byte row without scrolling.")) return 1; + if (expect(view_monitor.poll(0) == 0, "ASCII up navigation failed.")) return 1; + if (expect(screen.reverse_chars[4][6], "ASCII up should move the cursor back one 32-byte row without scrolling.")) return 1; + + if (expect(view_monitor.poll(0) == 0, "ASCII edit mode entry via 'e' failed.")) return 1; + if (expect(screen.reverse_chars[4][6], "ASCII edit did not highlight the active character.")) return 1; + + if (expect(view_monitor.poll(0) == 0, "ASCII edit write failed.")) return 1; + if (expect(backend.read(0x0000) == 'Z', "ASCII edit did not write memory.")) return 1; + if (expect(screen.reverse_chars[4][7], "ASCII edit did not advance the highlighted cursor.")) return 1; + + if (expect(view_monitor.poll(0) == 0, "ASCII left-arrow should navigate without leaving edit mode.")) return 1; + if (expect(backend.read(0x0001) == 'A', "ASCII left-arrow should not be written as data.")) return 1; + if (expect(screen.reverse_chars[4][6], "ASCII left-arrow must move the edit cursor to the previous byte.")) return 1; + if (expect(view_monitor.poll(0) == 0, "ASCII edit must remain active after left-arrow navigation.")) return 1; + if (expect(backend.read(0x0000) == 'Y', "ASCII edit should keep writing after moving left in edit mode.")) return 1; + if (expect(screen.reverse_chars[4][7], "ASCII edit should continue to advance after writing post-left-arrow.")) return 1; + if (expect(view_monitor.poll(0) == 0, "RUN/STOP should leave ASCII edit mode before closing the monitor.")) return 1; + if (expect(view_monitor.poll(0) == 1, "RUN/STOP monitor exit failed after ASCII edit navigation.")) return 1; + view_monitor.deinit(); + + const int hex_keys[] = { 'e', 'A', 'B', KEY_LEFT, 'C', 'D', KEY_BREAK, KEY_BREAK }; + FakeKeyboard hex_keyboard(hex_keys, 8); + ui.keyboard = &hex_keyboard; + screen.clear(); + backend.write(0x0000, 0x00); + monitor_reset_saved_state(); + + BackendMachineMonitor hex_monitor(&ui, &backend); + hex_monitor.init(&screen, &hex_keyboard); + if (expect(hex_monitor.poll(0) == 0, "Hex edit mode entry via 'e' failed.")) return 1; + if (expect(screen.reverse_chars[4][6] && screen.reverse_chars[4][7], "Hex edit did not highlight both byte digits.")) return 1; + if (expect(hex_monitor.poll(0) == 0, "First hex nibble failed.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "0000 a0") == line || strstr(line, "0000 A0") == line, + "First hex nibble did not update the visible byte immediately.")) return 1; + if (expect(backend.read(0x0000) == 0x00, "First hex nibble should not commit memory yet.")) return 1; + if (expect(hex_monitor.poll(0) == 0, "Second hex nibble failed.")) return 1; + if (expect(backend.read(0x0000) == 0xAB, "Hex edit did not write the byte.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "0000 ab") == line || strstr(line, "0000 AB") == line, + "Hex edit did not redraw the changed byte immediately.")) return 1; + if (expect(screen.reverse_chars[4][9] && screen.reverse_chars[4][10], "Hex edit did not advance to the next byte.")) return 1; + if (expect(hex_monitor.poll(0) == 0, "Left-arrow should navigate inside hex edit mode.")) return 1; + if (expect(screen.reverse_chars[4][6] && screen.reverse_chars[4][7], "Hex left-arrow must move the edit cursor back to the previous byte.")) return 1; + if (expect(hex_monitor.poll(0) == 0, "Hex edit must remain active after left-arrow navigation.")) return 1; + if (expect(hex_monitor.poll(0) == 0, "Hex edit second byte write after left-arrow failed.")) return 1; + if (expect(backend.read(0x0000) == 0xCD, "Hex edit should keep writing after moving left in edit mode.")) return 1; + if (expect(hex_monitor.poll(0) == 0, "RUN/STOP should leave hex edit mode before closing the monitor.")) return 1; + if (expect(hex_monitor.poll(0) == 1, "RUN/STOP exit after hex edit failed.")) return 1; + hex_monitor.deinit(); + + { + const int rom_write_keys[] = { 'J', 'e', '5', '5', KEY_BREAK, KEY_BREAK }; + FakeKeyboard rom_write_keyboard(rom_write_keys, 6); + ui.keyboard = &rom_write_keyboard; + ui.set_prompt("A000", 1); + screen.clear(); + banked_backend.basic[0] = 0xBA; + banked_backend.ram[0xA000] = 0xAA; + banked_backend.set_monitor_cpu_port(0x07); + monitor_reset_saved_state(); + + BackendMachineMonitor rom_write_monitor(&ui, &banked_backend); + rom_write_monitor.init(&screen, &rom_write_keyboard); + if (expect(rom_write_monitor.poll(0) == 0, "Goto to A000 failed for ROM-visible write test.")) return 1; + if (expect(rom_write_monitor.poll(0) == 0, "ROM-visible edit mode entry failed.")) return 1; + if (expect(rom_write_monitor.poll(0) == 0, "ROM-visible first nibble failed.")) return 1; + if (expect(rom_write_monitor.poll(0) == 0, "ROM-visible second nibble failed.")) return 1; + if (expect(banked_backend.ram[0xA000] == 0x55, "ROM-visible write must update the underlying RAM just like the canonical backend path.")) return 1; + if (expect(banked_backend.basic[0] == 0xBA, "ROM-visible write must not overwrite BASIC ROM content.")) return 1; + if (expect(rom_write_monitor.poll(0) == 0, "RUN/STOP should leave edit mode after ROM-visible write.")) return 1; + if (expect(rom_write_monitor.poll(0) == 1, "RUN/STOP exit failed after ROM-visible write test.")) return 1; + rom_write_monitor.deinit(); + } + + { + const int exit_keys[] = { 'e', KEY_F3, KEY_F3, 'A', 'B', KEY_BREAK, KEY_BREAK }; + FakeKeyboard exit_keyboard(exit_keys, 7); + ui.keyboard = &exit_keyboard; + screen.clear(); + backend.write(0x0000, 0x00); + monitor_reset_saved_state(); + + BackendMachineMonitor exit_monitor(&ui, &backend); + exit_monitor.init(&screen, &exit_keyboard); + if (expect(exit_monitor.poll(0) == 0, "F3 edit-help setup via 'e' failed.")) return 1; + if (expect(exit_monitor.poll(0) == 0, "F3 should toggle help while keeping edit mode.")) return 1; + for (int i = 0; expected_help_lines[i]; i++) { + screen.get_slice(1, 4 + i, 38, line); + if (expect(strncmp(line, expected_help_lines[i], strlen(expected_help_lines[i])) == 0, + "F3 did not open help while editing.")) return 1; + } + if (expect(exit_monitor.poll(0) == 0, "F3 should close help while keeping edit mode.")) return 1; + if (expect(exit_monitor.poll(0) == 0, "F3-preserved edit mode first nibble failed.")) return 1; + if (expect(exit_monitor.poll(0) == 0, "F3-preserved edit mode second nibble failed.")) return 1; + if (expect(backend.read(0x0000) == 0xAB, "F3 terminated edit mode instead of preserving it.")) return 1; + if (expect(exit_monitor.poll(0) == 0, "RUN/STOP should exit edit mode before monitor.")) return 1; + if (expect(exit_monitor.poll(0) == 1, "RUN/STOP monitor exit failed after edit-exit checks.")) return 1; + exit_monitor.deinit(); + } + + { + const int nav_keys[] = { + KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, + KEY_PAGEUP, KEY_PAGEDOWN, KEY_F2, KEY_F7, + KEY_F3, KEY_LEFT, KEY_PAGEUP, KEY_PAGEDOWN, + KEY_BREAK + }; + FakeKeyboard nav_keyboard(nav_keys, 13); + ui.keyboard = &nav_keyboard; + screen.clear(); + monitor_reset_saved_state(); + + BackendMachineMonitor nav_monitor(&ui, &backend); + nav_monitor.init(&screen, &nav_keyboard); + for (int i = 0; i < 12; i++) { + if (expect(nav_monitor.poll(0) == 0, "Global navigation key exited the monitor.")) return 1; + } + if (expect(nav_monitor.poll(0) == 1, "RUN/STOP exit failed after global navigation checks.")) return 1; + nav_monitor.deinit(); + } + + { + const int toggle_keys[] = { KEY_CTRL_O }; + FakeKeyboard toggle_keyboard(toggle_keys, 1); + ui.keyboard = &toggle_keyboard; + screen.clear(); + monitor_reset_saved_state(); + + BackendMachineMonitor toggle_monitor(&ui, &backend); + toggle_monitor.init(&screen, &toggle_keyboard); + if (expect(toggle_monitor.poll(0) == 1, "CBM+O should close the monitor directly.")) return 1; + toggle_monitor.deinit(); + } + + // 'A' switches to disassembly without entering Debug mode. 'R' is no + // longer a candidate "ignored" key because the spec routes it to the + // range toggle outside Debug and to breakpoint toggle inside Debug. + const int ignored_keys[] = { 'A', '.', ':', 'Q', 'P', KEY_BREAK }; + FakeKeyboard ignored_keyboard(ignored_keys, 6); + ui.keyboard = &ignored_keyboard; + screen.clear(); + ui.popup_count = 0; + backend.write(0x0000, 0x00); + monitor_reset_saved_state(); + + BackendMachineMonitor ignored_monitor(&ui, &backend); + ignored_monitor.init(&screen, &ignored_keyboard); + if (expect(ignored_monitor.poll(0) == 0, "Disassembly view command failed before ignored-key checks.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR ASM $0000") == line, "Disassembly header setup failed before ignored-key checks.")) return 1; + if (expect(ignored_monitor.poll(0) == 0, "'.' should be ignored now that left/right already handle byte stepping.")) return 1; + screen.get_slice(1, 3, 38, status); + if (expect(strstr(status, "MONITOR ASM $0000") == status, "'.' should not change the disassembly viewport.")) return 1; + if (expect(ignored_monitor.poll(0) == 0, "':' should be ignored after 'E' takes over edit entry.")) return 1; + if (expect(ignored_monitor.poll(0) == 0, "Q should be ignored while not editing.")) return 1; + if (expect(ignored_monitor.poll(0) == 0, "P should be ignored, not handled as a command.")) return 1; + if (expect(ui.popup_count == 0, "Removed peek/poke commands should not show popups.")) return 1; + if (expect(backend.read(0x0000) == 0x00, "Removed edit commands should not write memory.")) return 1; + if (expect(ignored_monitor.poll(0) == 1, "RUN/STOP exit failed on ignored-command monitor.")) return 1; + ignored_monitor.deinit(); + + for (int y = 3; y < 23; y++) { + if (expect((unsigned char)screen.chars[y][39] == CHR_VERTICAL_LINE, "Monitor output overwrote the right border.")) return 1; + } + + return 0; +} + +static int test_monitor_default_cpu_bank_and_vic_shortcuts(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char line[MONITOR_HEX_ROW_CHARS + 1]; + char status[39]; + const int keys[] = { + 'J', + 'o', '.', + 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', + 'O', 'O', 'O', 'O', + KEY_BREAK + }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + static const char *cpu_cycle_status[] = { + "C0O1 $A:RAM $D:CHR $E:RAM VIC2 $8000", + "C0O2 $A:RAM $D:CHR $E:KRN VIC2 $8000", + "C0O3 $A:BAS $D:CHR $E:KRN VIC2 $8000", + "C0O4 $A:RAM $D:RAM $E:RAM VIC2 $8000", + "C0O5 $A:RAM $D:I/O $E:RAM VIC2 $8000", + "C0O6 $A:RAM $D:I/O $E:KRN VIC2 $8000", + "C0O7 $A:BAS $D:I/O $E:KRN VIC2 $8000", + "CPU0 $A:RAM $D:RAM $E:RAM VIC2 $8000", + }; + static const char *vic_cycle_status[] = { + "CPU0 $A:RAM $D:RAM $E:RAM VIC3 $C000", + "CPU0 $A:RAM $D:RAM $E:RAM VIC0 $0000", + "CPU0 $A:RAM $D:RAM $E:RAM VIC1 $4000", + "CPU0 $A:RAM $D:RAM $E:RAM VIC2 $8000", + }; + static const uint8_t vic_cycle_dd00[] = { + 0xA8, 0xAB, 0xAA, 0xA9, + }; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("A000", 1); + monitor_io::reset_fake_monitor_io(); + monitor_reset_saved_state(); + monitor_invalidate_saved_state(); + + backend.live_cpu_port = 0x00; + backend.live_cpu_ddr = 0x07; + backend.live_dd00 = 0xA9; + backend.basic[0] = 0xBA; + backend.ram[0xA000] = 0xAA; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C0O7 $A:BAS $D:I/O $E:KRN VIC2 $8000") == status, + "Fresh monitor sessions must display live CPU0 and monitor CPU7 separately.")) return 1; + + if (expect(monitor.poll(0) == 0, "Jump command failed for CPU/VIC shortcut test.")) return 1; + if (expect(!monitor_io::g_monitor_io.jump_called, "J must change the monitor address without executing code.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 ba", 7) == 0 || strncmp(line, "A000 BA", 7) == 0, + "Default CPU7 must show BASIC at A000.")) return 1; + + ui.popup_count = 0; + if (expect(monitor.poll(0) == 0, "CPU bank cycle from CPU7 to CPU0 failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU0 $A:RAM $D:RAM $E:RAM VIC2 $8000") == status, + "Plain O must cycle from CPU7 to CPU0.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 aa", 7) == 0 || strncmp(line, "A000 AA", 7) == 0, + "CPU0 must expose RAM at A000.")) return 1; + if (expect(ui.popup_count == 0, "Plain O must not open a popup.")) return 1; + + if (expect(monitor.poll(0) == 0, "Unmapped key should be ignored after plain O.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU0 $A:RAM $D:RAM $E:RAM VIC2 $8000") == status, + "Unmapped keys must not be captured for CPU bank selection.")) return 1; + if (expect(ui.popup_count == 0, "Unmapped keys must not trigger CPU bank popups.")) return 1; + + for (unsigned int i = 0; i < sizeof(cpu_cycle_status) / sizeof(cpu_cycle_status[0]); i++) { + if (expect(monitor.poll(0) == 0, "Ascending CPU bank cycle failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, cpu_cycle_status[i]) == status, "CPU bank cycle order must be CPU0..CPU7 in ascending order.")) return 1; + } + + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "a000 aa", 7) == 0 || strncmp(line, "A000 AA", 7) == 0, + "CPU0 must remain distinct and re-reachable after a full cycle.")) return 1; + + for (unsigned int i = 0; i < sizeof(vic_cycle_status) / sizeof(vic_cycle_status[0]); i++) { + if (expect(monitor.poll(0) == 0, "Shift+O VIC bank cycle failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, vic_cycle_status[i]) == status, "Shift+O must cycle VIC0..VIC3 in ascending order.")) return 1; + if (expect(backend.live_dd00 == vic_cycle_dd00[i], "Shift+O must write the actual DD00 VIC bank bits without clobbering unrelated CIA-2 state.")) return 1; + } + + if (expect(monitor.poll(0) == 1, "RUN/STOP exit failed after CPU/VIC shortcut test.")) return 1; + monitor.deinit(); + monitor_reset_saved_state(); + return 0; +} + +static int test_monitor_split_cpu_status_highlights_digits_only() +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + const int keys[] = { KEY_BREAK }; + FakeKeyboard keyboard(keys, 1); + char status[39]; + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.color_fg = 12; + monitor_reset_saved_state(); + + backend.live_cpu_port = 0x05; + backend.live_cpu_ddr = 0x07; + backend.live_dd00 = 0x01; + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C5O7 $A:BAS $D:I/O $E:KRN VIC2 $8000") == status, + "Split CPU status must show live CPU first and monitor view second")) return 1; + if (expect(screen.colors[22][1] == ui.color_fg && + screen.colors[22][2] == 1 && + screen.colors[22][3] == ui.color_fg && + screen.colors[22][4] == 1, + "Split CPU status must highlight only the two numeric bank values")) return 1; + if (expect(screen.colors[22][5] == ui.color_fg, + "Split CPU status letters must stay in the normal foreground color")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exit failed after split CPU status test")) return 1; + monitor.deinit(); + monitor_reset_saved_state(); + return 0; +} + +static int test_monitor_freeze_mode_vic_shortcut_override(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeFrozenVicBackend backend; + char status[39]; + const int keys[] = { 'O', 'O', 'O', 'O', KEY_BREAK }; + FakeKeyboard keyboard(keys, sizeof(keys) / sizeof(keys[0])); + static const char *vic_cycle_status[] = { + "CPU7 $A:BAS $D:I/O $E:KRN VIC1 $4000", + "CPU7 $A:BAS $D:I/O $E:KRN VIC2 $8000", + "CPU7 $A:BAS $D:I/O $E:KRN VIC3 $C000", + "CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000", + }; + static const uint8_t requested_vic_bank[] = { 1, 2, 3, 0 }; + + ui.screen = &screen; + ui.keyboard = &keyboard; + monitor_reset_saved_state(); + monitor_invalidate_saved_state(); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU7 $A:BAS $D:I/O $E:KRN VIC0 $0000") == status, + "Freeze-mode VIC shortcut test must start from the freezer's VIC0 bank.")) return 1; + + for (unsigned int i = 0; i < sizeof(vic_cycle_status) / sizeof(vic_cycle_status[0]); i++) { + if (expect(monitor.poll(0) == 0, "Freeze-mode Shift+O VIC bank cycle failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, vic_cycle_status[i]) == status, + "Freeze-mode Shift+O must keep rotating through the requested VIC banks even when live readback stays pinned.")) return 1; + if (expect(backend.requested_vic_bank == requested_vic_bank[i], + "Freeze-mode Shift+O must still request the next VIC bank from the backend.")) return 1; + if (expect(backend.set_live_vic_bank_calls == (int)i + 1, + "Freeze-mode Shift+O must invoke set_live_vic_bank on every keypress.")) return 1; + if (expect(backend.get_live_vic_bank() == 0, + "Freeze-mode VIC override test assumes the backend readback remains pinned to VIC0.")) return 1; + } + + if (expect(monitor.poll(0) == 1, "RUN/STOP exit failed after freeze-mode VIC shortcut test.")) return 1; + monitor.deinit(); + monitor_reset_saved_state(); + return 0; +} + +static int test_monitor_reopen_restores_state(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[MONITOR_DISASM_ROW_CHARS + 1]; + char status[39]; + + monitor_reset_saved_state(); + + backend.write(0xC123, 0x07); + backend.write(0xC124, 0x44); + backend.write(0xC125, 0x00); + + { + const int first_keys[] = { 'J', 'A', 'U', 'o', KEY_BREAK }; + FakeKeyboard first_keyboard(first_keys, 5); + ui.screen = &screen; + ui.keyboard = &first_keyboard; + ui.set_prompt("C123", 1); + + BackendMachineMonitor first_monitor(&ui, &backend); + first_monitor.init(&screen, &first_keyboard); + if (expect(first_monitor.poll(0) == 0, "First monitor goto failed for reopen-state test.")) return 1; + if (expect(first_monitor.poll(0) == 0, "First monitor view switch failed for reopen-state test.")) return 1; + if (expect(first_monitor.poll(0) == 0, "First monitor undocumented-op toggle failed for reopen-state test.")) return 1; + if (expect(first_monitor.poll(0) == 0, "First monitor CPU-bank cycle failed for reopen-state test.")) return 1; + if (expect(first_monitor.poll(0) == 1, "First monitor exit failed for reopen-state test.")) return 1; + first_monitor.deinit(); + } + + screen.clear(); + + { + const int second_keys[] = { KEY_BREAK }; + FakeKeyboard second_keyboard(second_keys, 1); + ui.keyboard = &second_keyboard; + + BackendMachineMonitor second_monitor(&ui, &backend); + second_monitor.init(&screen, &second_keyboard); + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR ASM $C123") == line, "Reopened monitor did not restore the disassembly view and address.")) return 1; + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "C123 07 44") == line, "Reopened monitor did not restore the saved current address.")) return 1; + if (expect(strstr(line, "SLO $44") != NULL, "Reopened monitor did not restore the illegal-opcodes setting.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU0 ") == status, "Reopened monitor did not restore the selected CPU bank.")) return 1; + if (expect(second_monitor.poll(0) == 1, "Second monitor exit failed for reopen-state test.")) return 1; + second_monitor.deinit(); + } + + monitor_reset_saved_state(); + return 0; +} + +static int test_monitor_kernal_bank_switch_and_ram_interaction(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char line[MONITOR_HEX_ROW_CHARS + 1]; + char status[39]; + + monitor_reset_saved_state(); + + backend.kernal[0] = 0x4E; + backend.kernal[1] = 0x22; + backend.ram[0xE000] = 0xAA; + backend.ram[0xE001] = 0xBB; + + const int keys[] = { + 'J', 'e', '5', '5', KEY_BREAK, + 'o', 'o', 'o', 'o', 'o', 'o', + 'e', '6', '6', KEY_BREAK, + 'o', 'o', + KEY_BREAK + }; + FakeKeyboard keyboard(keys, 18); + + ui.screen = &screen; + ui.keyboard = &keyboard; + ui.set_prompt("E000", 1); + + BackendMachineMonitor monitor(&ui, &backend); + monitor.init(&screen, &keyboard); + + if (expect(monitor.poll(0) == 0, "Goto to E000 failed for KERNAL banking test.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "e000 4e 22") == line || strstr(line, "E000 4E 22") == line, + "Initial KERNAL-visible bytes at E000 are incorrect.")) return 1; + + if (expect(monitor.poll(0) == 0, "Edit mode entry failed for KERNAL-visible RAM write test.")) return 1; + if (expect(monitor.poll(0) == 0, "First KERNAL-visible nibble failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Second KERNAL-visible nibble failed.")) return 1; + if (expect(backend.ram[0xE000] == 0x55, "KERNAL-visible write did not update underlying RAM at E000.")) return 1; + if (expect(backend.kernal[0] == 0x4E, "KERNAL-visible write incorrectly modified KERNAL ROM content.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "e000 4e 22") == line || strstr(line, "E000 4E 22") == line, + "KERNAL-visible monitor view should still show ROM after write-under-ROM.")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave edit mode after KERNAL-visible write.")) return 1; + + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU0 failed for KERNAL banking test.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU1 failed for KERNAL banking test.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU2 failed for KERNAL banking test.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU3 failed for KERNAL banking test.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU4 failed for KERNAL banking test.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU5 failed for KERNAL banking test.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C7O5 $A:RAM $D:I/O $E:RAM VIC2 $8000") == status, + "CPU5 monitor-view status did not expose RAM at E000.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "e000 55 bb") == line || strstr(line, "E000 55 BB") == line, + "Bank switching to RAM did not reveal the underlying bytes at E000.")) return 1; + + if (expect(monitor.poll(0) == 0, "Edit mode entry failed for RAM-visible write test.")) return 1; + if (expect(monitor.poll(0) == 0, "First RAM-visible nibble failed.")) return 1; + if (expect(monitor.poll(0) == 0, "Second RAM-visible nibble failed.")) return 1; + if (expect(backend.ram[0xE001] == 0x66, "RAM-visible write did not update underlying RAM at E001.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "e000 55 66") == line || strstr(line, "E000 55 66") == line, + "RAM-visible monitor view did not redraw the edited underlying RAM byte.")) return 1; + if (expect(monitor.poll(0) == 0, "RUN/STOP should leave edit mode after RAM-visible write.")) return 1; + + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU6 failed for KERNAL restore test.")) return 1; + if (expect(monitor.poll(0) == 0, "CPU bank cycle to CPU7 failed for KERNAL restore test.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU7 $A:BAS $D:I/O $E:KRN VIC2 $8000") == status, + "CPU7 status did not restore KERNAL visibility.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "e000 4e 22") == line || strstr(line, "E000 4E 22") == line, + "Switching back to KERNAL did not restore the ROM-visible bytes at E000.")) return 1; + if (expect(monitor.poll(0) == 1, "RUN/STOP exit failed after KERNAL banking interaction test.")) return 1; + monitor.deinit(); + + return 0; +} + +#include "assembler_6502.h" + +static int test_assembler_encoding(void) +{ + AsmInsn insn; + MonitorError err = MONITOR_OK; + + if (expect(monitor_assemble_line("LDA #$12", false, 0xC000, &insn, &err), "LDA #$12 must encode")) return 1; + if (expect(insn.length == 2 && insn.bytes[0] == 0xA9 && insn.bytes[1] == 0x12, "LDA #$12 -> A9 12")) return 1; + + if (expect(monitor_assemble_line("JMP $C000", false, 0xC000, &insn, &err), "JMP $C000 must encode")) return 1; + if (expect(insn.length == 3 && insn.bytes[0] == 0x4C && insn.bytes[1] == 0x00 && insn.bytes[2] == 0xC0, "JMP $C000 -> 4C 00 C0")) return 1; + + if (expect(monitor_assemble_line("BNE $C005", false, 0xC000, &insn, &err), "BNE $C005 must encode")) return 1; + if (expect(insn.length == 2 && insn.bytes[0] == 0xD0 && insn.bytes[1] == 0x03, "BNE $C005 from $C000 -> D0 03")) return 1; + + if (expect(monitor_assemble_line("NOP", false, 0xC000, &insn, &err), "NOP must encode")) return 1; + if (expect(insn.length == 1 && insn.bytes[0] == 0xEA, "NOP -> EA")) return 1; + + if (expect(monitor_assemble_line("STA $0400,X", false, 0xC000, &insn, &err), "STA $0400,X must encode")) return 1; + if (expect(insn.length == 3 && insn.bytes[0] == 0x9D && insn.bytes[1] == 0x00 && insn.bytes[2] == 0x04, "STA $0400,X -> 9D 00 04")) return 1; + + // Illegal opcode rejected when toggle off. + if (expect(!monitor_assemble_line("SLO $12", false, 0xC000, &insn, &err), "SLO must be rejected when illegal=OFF")) return 1; + // ...accepted when on. + if (expect(monitor_assemble_line("SLO $12", true, 0xC000, &insn, &err), "SLO $12 must encode when illegal=ON")) return 1; + if (expect(insn.length == 2 && insn.bytes[0] == 0x07 && insn.bytes[1] == 0x12, "SLO $12 -> 07 12")) return 1; + + return 0; +} + +static int test_screen_code_reverse(void) +{ + if (expect(monitor_screen_code_for_char('A') == 0x01, "screen-code 'A' must be 0x01")) return 1; + if (expect(monitor_screen_code_for_char('Z') == 0x1A, "screen-code 'Z' must be 0x1A")) return 1; + if (expect(monitor_screen_code_for_char('@') == 0x00, "screen-code '@' must be 0x00")) return 1; + if (expect(monitor_screen_code_for_char(' ') == 0x20, "screen-code ' ' must be 0x20")) return 1; + if (expect(monitor_screen_code_for_char('1') == 0x31, "screen-code '1' must be 0x31")) return 1; + if (expect(monitor_screen_code_for_char('a') == 0x01, "lowercase 'a' must map to uppercase 'A' screen code")) return 1; + if (expect(monitor_screen_code_for_char('A', MONITOR_SCREEN_CHARSET_LOWER_UPPER) == 0x41, + "L/U screen-code 'A' must be 0x41")) return 1; + if (expect(monitor_screen_code_for_char('Z', MONITOR_SCREEN_CHARSET_LOWER_UPPER) == 0x5A, + "L/U screen-code 'Z' must be 0x5A")) return 1; + if (expect(monitor_screen_code_for_char('#', MONITOR_SCREEN_CHARSET_LOWER_UPPER) == 0x23, + "Screen-code '#' must remain literal in L/U mode")) return 1; + if (expect(monitor_screen_code_for_char('<', MONITOR_SCREEN_CHARSET_LOWER_UPPER) == 0x3C, + "Screen-code '<' must remain literal in L/U mode")) return 1; + if (expect(monitor_screen_code_for_char('[', MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS) == 0xFF, + "Display aliases must not be accepted as screen-code input.")) return 1; + return 0; +} + +static int test_logical_delete_per_view(void) +{ + // HEX: DEL on a non-zero byte must clear it to 0x00 and step cursor RIGHT. + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + backend.write(0x0400, 0xAB); + backend.write(0x0401, 0xCD); + const int keys[] = { 'J', 'E', KEY_DELETE, KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys)/sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys)/sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + // First DEL clears 0400 and moves to 0401; second DEL clears 0401. + if (expect(backend.read(0x0400) == 0x00 && backend.read(0x0401) == 0x00, + "HEX DEL must clear current byte to 0x00 and advance cursor RIGHT")) return 1; + } + + // ASC: DEL on byte must set to 0x20 and step cursor LEFT. + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + backend.write(0x03FF, 0xAA); + backend.write(0x0400, 0xBB); + const int keys[] = { 'J', 'I', 'E', KEY_DELETE, KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys)/sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys)/sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + // First DEL clears 0400 and moves to 03FF; second DEL clears 03FF. + if (expect(backend.read(0x0400) == 0x20 && backend.read(0x03FF) == 0x20, + "ASC DEL must clear byte to 0x20 and advance cursor LEFT")) return 1; + } + + // SCR: DEL on byte must set to screen-code space (0x20) and step cursor LEFT. + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + backend.write(0x03FF, 0x11); + backend.write(0x0400, 0x55); + const int keys[] = { 'J', 'V', 'E', KEY_DELETE, KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys)/sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys)/sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0x0400) == 0x20 && backend.read(0x03FF) == 0x20, + "SCR DEL must clear byte to screen-code space and advance cursor LEFT")) return 1; + } + + // ASM: DEL on $C000 = A9 12 (LDA #$12, 2 bytes) must fill EA EA. + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + backend.write(0xC000, 0xA9); + backend.write(0xC001, 0x12); + const int keys[] = { 'J', 'A', 'E', KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys)/sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys)/sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0xC000) == 0xEA && backend.read(0xC001) == 0xEA, + "ASM DEL must replace LDA #$12 (2 bytes) with EA EA")) return 1; + } + + // DEL must also work in non-edit mode for HEX/ASC/SCR/ASM. + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + backend.write(0x0400, 0xAB); + const int keys[] = { 'J', KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys)/sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys)/sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0x0400) == 0x00, + "HEX DEL must work outside edit mode too")) return 1; + } + return 0; +} + +static int test_scr_edit_writes_screen_code(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + monitor_reset_saved_state(); + backend.write(0x0400, 0x00); + const int keys[] = { 'J', 'V', 'E', 'A', KEY_BREAK }; + FakeKeyboard kb(keys, 5); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 5; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0x0400) == 0x01, "SCR edit: typing 'A' must write screen code 0x01 in U/G")) return 1; + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + monitor_reset_saved_state(); + backend.write(0x0400, 0x00); + const int keys[] = { 'J', 'V', 'U', 'E', 'A', KEY_BREAK }; + FakeKeyboard kb(keys, 6); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 6; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0x0400) == 0x41, "SCR edit: typing 'A' must write screen code 0x41 in L/U")) return 1; + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + monitor_reset_saved_state(); + backend.write(0x0400, 0x00); + backend.write(0x0401, 0x00); + backend.write(0x0402, 0x00); + backend.write(0x0403, 0x00); + const int keys[] = { 'J', 'V', 'E', 'a', 'A', '#', '<', KEY_BREAK }; + FakeKeyboard kb(keys, 8); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 8; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0x0400) == 0x01, "SCR edit: typing 'a' must write screen code 0x01")) return 1; + if (expect(backend.read(0x0401) == 0x01, "SCR edit: typing 'A' must write screen code 0x01 in U/G")) return 1; + if (expect(backend.read(0x0402) == 0x23, "SCR edit: typing '#' must write literal screen code 0x23")) return 1; + if (expect(backend.read(0x0403) == 0x3C, "SCR edit: typing '<' must write literal screen code 0x3C")) return 1; + } + + return 0; +} + +static int test_screen_charset_toggle_and_header(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'V', 'U', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Screen charset header test: Screen view switch failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR SCR U/G $0000") == header, + "Screen view header must show U/G by default.")) return 1; + if (expect(mon.poll(0) == 0, "Screen charset header test: toggle failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR SCR L/U $0000") == header, + "Screen view header must show L/U after toggle.")) return 1; + if (expect(mon.poll(0) == 1, "Screen charset header test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'A', 'U', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0x0000, 0x07); + backend.write(0x0001, 0x44); + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM U test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM U test: undocumented toggle failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Undc") != NULL, + "ASM U must keep toggling undocumented opcodes.")) return 1; + if (expect(mon.poll(0) == 1, "ASM U test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'M', 'U', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.popup_count = 0; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Memory U test: Memory view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Memory U test: popup branch failed.")) return 1; + if (expect(ui.popup_count == 1 && strcmp(ui.last_popup, "UNDOC IN ASM, CASE IN SCR") == 0, + "U outside ASM/SCR must show the refined invalid-context popup.")) return 1; + if (expect(mon.poll(0) == 1, "Memory U test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_screen_charset_display_and_memory_ascii_pane(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[MONITOR_TEXT_ROW_CHARS + 1]; + char row[MONITOR_HEX_ROW_CHARS + 1]; + const int keys[] = { 'V', 'U', 'M', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0x0000, 0x01); + backend.write(0x0001, 0x1A); + backend.write(0x0002, 0x41); + backend.write(0x0003, 0x5A); + backend.write(0x0004, 0x20); + backend.write(0x0005, 0x61); + backend.write(0x0006, 0x80); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "Screen display test: Screen view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen display test: charset toggle failed.")) return 1; + screen.get_slice(1, 4, MONITOR_TEXT_ROW_CHARS, line); + if (expect(strncmp(line, "0000 azAZ .@", 12) == 0, + "L/U Screen view must show lowercase for $01-$1A, uppercase for $41-$5A, visible placeholders for non-space unmapped codes, and base-glyph rendering for high-bit values.")) return 1; + + if (expect(mon.poll(0) == 0, "Screen display test: Memory view switch failed.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, row); + if (expect(strcmp(row, "0000 01 1A 41 5A 20 61 80 00 ..AZ a..") == 0, + "Memory view ASCII pane must stay literal ASCII and ignore Screen charset mode.")) return 1; + if (expect(mon.poll(0) == 1, "Screen display test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_number_shortcut_routing(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[19]; + const int keys[] = { 'A', 'E', 'N', KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM N-routing test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM N-routing test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM N-routing test: typing N failed.")) return 1; + if (expect(!find_popup_rect(screen, NULL, NULL, NULL, NULL), + "ASM edit N must not open the framed Number popup.")) return 1; + screen.get_slice(16, 4, 18, line); + if (expect(strstr(line, " N_") == line, + "ASM edit N must be routed into mnemonic entry instead of Number.")) return 1; + if (expect(mon.poll(0) == 0, "ASM N-routing test: RUN/STOP should close the opcode picker first.")) return 1; + if (expect(mon.poll(0) == 0, "ASM N-routing test: RUN/STOP should leave edit mode next.")) return 1; + if (expect(mon.poll(0) == 1, "ASM N-routing test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'J', 'A', 'E', KEY_RIGHT, 'N', KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0xC000, 0xA9); + backend.write(0xC001, 0x12); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM operand N test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM operand N test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM operand N test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM operand N test: moving to operand failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM operand N test: Number popup open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $C001 BYTE") == line, + "ASM operand context must open Number on the operand byte without leaving edit mode.")) return 1; + if (expect(mon.poll(0) == 0, "ASM operand N test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM operand N test: exit edit mode failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM operand N test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[19]; + const int keys[] = { 'J', 'A', 'E', 'L', 'N', KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C100", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM popup N-routing test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM popup N-routing test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM popup N-routing test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM popup N-routing test: first mnemonic letter failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM popup N-routing test: second mnemonic letter failed.")) return 1; + if (expect(!find_popup_rect(screen, NULL, NULL, NULL, NULL), + "Opcode completion popup must keep N as mnemonic input instead of opening Number.")) return 1; + screen.get_slice(16, 4, 18, line); + if (expect(strstr(line, " LN_") == line, + "While the opcode picker is active, N must continue editing the mnemonic prefix.")) return 1; + if (expect(mon.poll(0) == 0, "ASM popup N-routing test: RUN/STOP should close the picker first.")) return 1; + if (expect(mon.poll(0) == 0, "ASM popup N-routing test: RUN/STOP should leave edit mode next.")) return 1; + if (expect(mon.poll(0) == 1, "ASM popup N-routing test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'J', 'A', 'E', 'L', 'D', 'A', KEY_RETURN, 'N', KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C200", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 7; i++) { + if (expect(mon.poll(0) == 0, "ASM post-opcode N test: mnemonic commit failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "ASM post-opcode N test: Number popup open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $C201 BYTE") == line, + "After opcode entry advances to operand context, N must open Number without leaving edit mode.")) return 1; + if (expect(mon.poll(0) == 0, "ASM post-opcode N test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM post-opcode N test: exit edit mode failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM post-opcode N test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'I', 'E', 'N', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASCII N-routing test: ASCII view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII N-routing test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII N-routing test: typing N failed.")) return 1; + if (expect(backend.read(0x0000) == 'N', + "ASCII edit N must write the typed character instead of opening Number.")) return 1; + if (expect(!find_popup_rect(screen, NULL, NULL, NULL, NULL), + "ASCII edit N must not open the framed Number popup.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII N-routing test: RUN/STOP should leave edit mode first.")) return 1; + if (expect(mon.poll(0) == 1, "ASCII N-routing test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'V', 'E', 'N', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Screen N-routing test: Screen view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen N-routing test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen N-routing test: typing N failed.")) return 1; + if (expect(backend.read(0x0000) == monitor_screen_code_for_char('N'), + "Screen edit N must write the typed screen code instead of opening Number.")) return 1; + if (expect(!find_popup_rect(screen, NULL, NULL, NULL, NULL), + "Screen edit N must not open the framed Number popup.")) return 1; + if (expect(mon.poll(0) == 0, "Screen N-routing test: RUN/STOP should leave edit mode first.")) return 1; + if (expect(mon.poll(0) == 1, "Screen N-routing test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'A', 'N', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM non-edit N test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM non-edit N test: Number popup open failed.")) return 1; + if (expect(find_popup_rect(screen, NULL, NULL, NULL, NULL), + "ASM non-edit N must still open the framed Number popup.")) return 1; + if (expect(mon.poll(0) == 0, "ASM non-edit N test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM non-edit N test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'E', 'N', KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "HEX edit N test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "HEX edit N test: Number popup open failed.")) return 1; + if (expect(find_popup_rect(screen, NULL, NULL, NULL, NULL), + "HEX edit N must keep opening the framed Number popup.")) return 1; + if (expect(mon.poll(0) == 0, "HEX edit N test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 0, "HEX edit N test: RUN/STOP should leave edit mode first.")) return 1; + if (expect(mon.poll(0) == 1, "HEX edit N test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_range_shortcut_routing(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'I', 'E', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASCII R-routing test: ASCII view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII R-routing test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII R-routing test: typing R failed.")) return 1; + if (expect(backend.read(0x0000) == 'R', + "ASCII edit R must write the typed character instead of toggling Range.")) return 1; + screen.get_slice(1, 22, 38, header); + if (expect(strstr(header, "Range") == NULL, + "ASCII edit R must not enable range mode.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII R-routing test: RUN/STOP should leave edit mode first.")) return 1; + if (expect(mon.poll(0) == 1, "ASCII R-routing test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'V', 'E', 'R', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Screen R-routing test: Screen view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen R-routing test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen R-routing test: typing R failed.")) return 1; + if (expect(backend.read(0x0000) == monitor_screen_code_for_char('R'), + "Screen edit R must write the typed screen code instead of toggling Range.")) return 1; + screen.get_slice(1, 22, 38, header); + if (expect(strstr(header, "Range") == NULL, + "Screen edit R must not enable range mode.")) return 1; + if (expect(mon.poll(0) == 0, "Screen R-routing test: RUN/STOP should leave edit mode first.")) return 1; + if (expect(mon.poll(0) == 1, "Screen R-routing test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[19]; + char header[39]; + const int keys[] = { 'A', 'E', 'R', KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM R-routing test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM R-routing test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM R-routing test: typing R failed.")) return 1; + if (expect(!find_popup_rect(screen, NULL, NULL, NULL, NULL), + "ASM edit R must not open a framed popup.")) return 1; + screen.get_slice(16, 4, 18, line); + if (expect(strstr(line, " R_") == line, + "ASM edit R must be routed into mnemonic entry instead of Range.")) return 1; + screen.get_slice(1, 22, 38, header); + if (expect(strstr(header, "Range") == NULL, + "ASM mnemonic edit R must not enable range mode.")) return 1; + if (expect(mon.poll(0) == 0, "ASM R-routing test: RUN/STOP should close the picker first.")) return 1; + if (expect(mon.poll(0) == 0, "ASM R-routing test: RUN/STOP should leave edit mode next.")) return 1; + if (expect(mon.poll(0) == 1, "ASM R-routing test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_asm_number_popup_targets_operands(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'J', 'A', 'N', '1', '2', '3', '4', KEY_RETURN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0x9010, 0xB9); + backend.write(0x9011, 0x99); + backend.write(0x9012, 0xFF); + backend.write(0x9013, 0xEA); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("9010", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM word Number test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM word Number test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM word Number test: Number popup open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $9011 WORD") == line, + "ASM Number popup must target the two-byte operand, not the opcode byte.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $FF99") == line, + "ASM Number popup must preload the operand word value.")) return 1; + get_popup_line(screen, 6, line, sizeof(line)); + if (expect(strncmp(line, "Calc with +-*/ $Hex Dec %Bin", 28) == 0, + "ASM Number popup must show the compact calculator legend after removing redundant rows.")) return 1; + for (int i = 0; i < 5; i++) { + if (expect(mon.poll(0) == 0, "ASM word Number test: editing/commit failed.")) return 1; + } + if (expect(backend.read(0x9010) == 0xB9, + "ASM word Number commit must leave the opcode byte unchanged.")) return 1; + if (expect(backend.read(0x9011) == 0x34 && backend.read(0x9012) == 0x12, + "ASM word Number commit must rewrite only the operand bytes in little-endian order.")) return 1; + if (expect(backend.read(0x9013) == 0xEA, + "ASM word Number commit must not overrun beyond the operand bytes.")) return 1; + if (expect(mon.poll(0) == 0, "ASM word Number test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM word Number test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'J', 'A', 'N', '3', '4', KEY_RETURN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0xC000, 0xA9); + backend.write(0xC001, 0x12); + backend.write(0xC002, 0xEA); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM byte Number test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM byte Number test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM byte Number test: Number popup open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $C001 BYTE") == line, + "ASM Number popup must target the one-byte operand address.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $12") == line, + "ASM Number popup must preload the one-byte operand value.")) return 1; + for (int i = 0; i < 3; i++) { + if (expect(mon.poll(0) == 0, "ASM byte Number test: editing/commit failed.")) return 1; + } + if (expect(backend.read(0xC000) == 0xA9, + "ASM byte Number commit must leave the opcode byte unchanged.")) return 1; + if (expect(backend.read(0xC001) == 0x34, + "ASM byte Number commit must rewrite the one-byte operand.")) return 1; + if (expect(backend.read(0xC002) == 0xEA, + "ASM byte Number commit must not touch the following byte.")) return 1; + if (expect(mon.poll(0) == 0, "ASM byte Number test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM byte Number test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'J', 'A', 'N', '4', '2', KEY_RETURN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0xC100, 0x60); + backend.write(0xC101, 0xEA); + backend.write(0xC102, 0x99); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C100", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM no-operand Number test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM no-operand Number test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM no-operand Number test: Number popup open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $C101 BYTE") == line, + "No-operand ASM Number popup must fall back to the byte after the instruction.")) return 1; + for (int i = 0; i < 3; i++) { + if (expect(mon.poll(0) == 0, "ASM no-operand Number test: editing/commit failed.")) return 1; + } + if (expect(backend.read(0xC100) == 0x60, + "No-operand ASM Number popup must not overwrite the opcode.")) return 1; + if (expect(backend.read(0xC101) == 0x42, + "No-operand ASM Number popup must write to the deterministic fallback address.")) return 1; + if (expect(backend.read(0xC102) == 0x99, + "No-operand ASM Number popup must not overrun past the fallback byte.")) return 1; + if (expect(mon.poll(0) == 0, "ASM no-operand Number test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM no-operand Number test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_asm_number_popup_illegal_and_invalid_rows(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'J', 'A', 'N', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0xC300, 0x07); + backend.write(0xC301, 0x44); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C300", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM invalid-row Number test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM invalid-row Number test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM invalid-row Number test: Number popup open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $C300 BYTE") == line, + "Disabled undocumented opcodes must fall back to the safe current-byte Number target.")) return 1; + if (expect(mon.poll(0) == 0, "ASM invalid-row Number test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM invalid-row Number test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'J', 'A', 'U', 'N', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0xC320, 0x07); + backend.write(0xC321, 0x44); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C320", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM undocumented Number test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM undocumented Number test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM undocumented Number test: undocumented toggle failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM undocumented Number test: Number popup open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $C321 BYTE") == line, + "Enabled undocumented opcodes must still target the decoded operand byte.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $44") == line, + "Enabled undocumented-opcode Number popup must preload the decoded operand value.")) return 1; + if (expect(mon.poll(0) == 0, "ASM undocumented Number test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASM undocumented Number test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_asm_edit_assemble_at_cursor(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + // ASM edit no longer goes through string_box. Pressing a letter on the + // mnemonic part opens the in-monitor opcode picker; further letters + // filter, UP/DOWN navigate, ENTER selects. After selection the cursor + // moves to the operand byte and hex digits write it directly. + // + // J / "C000" / enter -- jump to $C000 + // A -- switch to ASM + // E -- enter edit mode + // L D A -- open picker, narrow to LDA variants + // ENTER -- deterministic ordering now places the + // simplest LDA form first + // 4 2 -- type the operand byte at $C001 + const int keys[] = { + 'J', 'A', 'E', 'L', 'D', 'A', KEY_RETURN, '4', '2', KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0xC000) == 0xA9 && backend.read(0xC001) == 0x42, + "ASM edit must write A9 42 for LDA # via opcode picker")) return 1; + return 0; +} + +static int test_asm_edit_direct_typing(void) +{ + // Power-user direct-typing path: type the full instruction without + // navigating the picker. "LDA $1000" -> AD 00 10 (absolute). + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + // J / "C000" / enter -- jump to $C000 + // A -- switch to ASM + // E -- enter edit mode + // L D A SPACE 1 0 0 0 ENTER -- type the whole instruction + const int keys[] = { + 'J', 'A', 'E', 'L', 'D', 'A', KEY_SPACE, '1', '0', '0', '0', KEY_RETURN, KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0xC000) == 0xAD && backend.read(0xC001) == 0x00 && backend.read(0xC002) == 0x10, + "ASM direct typing 'LDA 1000' must encode AD 00 10")) return 1; + return 0; +} + +static int test_space_edit_behavior_preserved(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + CaptureScreen snapshot; + FakeMemoryBackend backend; + const int keys[] = { 'E', KEY_SPACE }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + backend.write(0x0000, 0xAB); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "HEX edit Space test: edit-mode entry failed.")) return 1; + snapshot = screen; + if (expect(mon.poll(0) == 0, "HEX edit Space test: space handling failed.")) return 1; + if (expect_screens_equal(snapshot, screen, + "HEX edit Space must remain a non-paging no-op.")) return 1; + if (expect(backend.read(0x0000) == 0xAB, + "HEX edit Space must not modify the current byte.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'I', 'E', KEY_SPACE }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + backend.write(0x0000, 'A'); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASCII edit Space test: view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII edit Space test: edit-mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII edit Space test: typing space failed.")) return 1; + if (expect(backend.read(0x0000) == ' ', + "ASCII edit Space must keep writing a literal space.")) return 1; + if (expect(screen.reverse_chars[4][7], + "ASCII edit Space must advance to the next character instead of paging.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'V', 'E', KEY_SPACE }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + backend.write(0x0000, 0x01); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Screen edit Space test: view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen edit Space test: edit-mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen edit Space test: typing space failed.")) return 1; + if (expect(backend.read(0x0000) == monitor_screen_code_for_char(' ', MONITOR_SCREEN_CHARSET_UPPER_GRAPHICS), + "Screen edit Space must keep writing a screen-code space.")) return 1; + if (expect(screen.reverse_chars[4][7], + "Screen edit Space must advance to the next character instead of paging.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'J', 'B', 'E', KEY_SPACE }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + backend.write(0x0400, 0xAA); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary edit Space test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary edit Space test: view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary edit Space test: edit-mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary edit Space test: typing space failed.")) return 1; + if (expect(backend.read(0x0400) == 0x2A, + "Binary edit Space must keep clearing the selected bit.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0400/6") == header, + "Binary edit Space must advance exactly one bit instead of paging.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_shift_space_does_not_page_in_edit_mode(void) +{ + static const struct { + int view_key; + const char *message; + } cases[] = { + { 0, "Shift+Space must not page up in Memory edit mode." }, + { 'I', "Shift+Space must not page up in ASCII edit mode." }, + { 'V', "Shift+Space must not page up in Screen edit mode." }, + { 'B', "Shift+Space must not page up in Binary edit mode." }, + { 'A', "Shift+Space must not page up in Assembly edit mode." }, + }; + + for (unsigned int i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + TestUserInterface ui; + CaptureScreen screen; + CaptureScreen snapshot; + FakeMemoryBackend backend; + int keys[4]; + int key_count = 0; + + for (uint32_t addr = 0; addr < 0x10000UL; addr++) { + backend.write((uint16_t)addr, (uint8_t)(addr & 0xFF)); + } + + keys[key_count++] = 'J'; + if (cases[i].view_key) { + keys[key_count++] = cases[i].view_key; + } + keys[key_count++] = 'E'; + keys[key_count++] = KEY_SHIFT_SP; + FakeKeyboard kb(keys, key_count); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("4000", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int step = 0; step < key_count - 1; step++) { + if (expect(mon.poll(0) == 0, "Shift+Space edit test setup failed.")) return 1; + } + snapshot = screen; + if (expect(mon.poll(0) == 0, "Shift+Space edit test key handling failed.")) return 1; + if (expect_screens_equal(snapshot, screen, cases[i].message)) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_asm_edit_direct_typing_immediate(void) +{ + // Direct typing with immediate addressing: "LDA #FF" -> A9 FF. + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { + 'J', 'A', 'E', 'L', 'D', 'A', '#', 'F', 'F', KEY_RETURN, KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0xC000) == 0xA9 && backend.read(0xC001) == 0xFF, + "ASM direct typing 'LDA #FF' must encode A9 FF")) return 1; + return 0; +} + +static int test_asm_edit_branch_two_parts(void) +{ + // Branch instructions encode opcode + 1-byte signed offset but render + // opcode + 4-hex absolute target. The asm-edit cursor must expose both + // halves of the displayed target as separately editable parts and + // translate the typed value back into a relative offset. + // + // Memory at $C000: F0 10 -> BEQ $C012 + // J / "C000" / enter -- jump to $C000 + // A -- switch to ASM + // E -- enter edit mode + // RIGHT -- move cursor to high byte ($C0) + // C 0 -- type $C0 (no change to high byte) + // RIGHT(implicit) -- after 2nd nibble, advances to low + // 2 0 -- type $20 -> target $C020 + // BREAK + // Expected: rel offset = $C020 - ($C000 + 2) = $1E -> memory F0 1E. + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + backend.write(0xC000, 0xF0); + backend.write(0xC001, 0x10); + const int keys[] = { + 'J', 'A', 'E', KEY_RIGHT, 'C', '0', '2', '0', KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])) - 1; i++) { + (void)mon.poll(0); + } + if (expect(backend.read(0xC000) == 0xF0 && backend.read(0xC001) == 0x1E, + "ASM branch edit must rewrite rel offset to land on typed target")) return 1; + return 0; +} + +static int test_asm_edit_ram_2000_program_readback(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[MONITOR_MEMORY_ROW_16_CHARS + 1]; + const int keys[] = { + 'J', 'A', 'E', + 'L', 'D', 'A', '#', '$', '0', '1', KEY_RETURN, + 'S', 'T', 'A', '$', 'D', '0', '2', '0', KEY_RETURN, + 'I', 'N', 'C', '$', 'D', '0', '2', '0', KEY_RETURN, + 'J', 'M', 'P', '$', '2', '0', '0', '5', KEY_RETURN, + KEY_BREAK, + 'M', + KEY_BREAK + }; + static const uint8_t expected[] = { + 0xA9, 0x01, + 0x8D, 0x20, 0xD0, + 0xEE, 0x20, 0xD0, + 0x4C, 0x05, 0x20, + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + for (uint16_t addr = 0x2000; addr < 0x2010; addr++) { + backend.write(addr, 0xFF); + } + if (expect(strcmp(backend.source_name(0x2000), "RAM") == 0, + "$2000 must be classified as RAM.")) return 1; + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("2000", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 38; i++) { + if (expect(mon.poll(0) == 0, "ASM $2000 edit program setup failed.")) return 1; + } + + for (unsigned int i = 0; i < sizeof(expected); i++) { + if (expect(backend.read((uint16_t)(0x2000 + i)) == expected[i], + "ASM $2000 edit did not write expected RAM bytes.")) return 1; + if (expect(backend.read((uint16_t)(0x2000 + i)) != 0xFF, + "ASM $2000 edit left an edited byte at $FF.")) return 1; + } + + screen.get_slice(1, 4, MONITOR_DISASM_ROW_CHARS, line); + if (expect(strstr(line, "2000 A9 01 LDA #$01") == line && + strstr(line, "[RAM]") != NULL, + "ASM $2000 readback must disassemble LDA #$01 as RAM.")) return 1; + screen.get_slice(1, 5, MONITOR_DISASM_ROW_CHARS, line); + if (expect(strstr(line, "2002 8D 20 D0 STA $D020") == line && + strstr(line, "[RAM]") != NULL, + "ASM $2000 readback must disassemble STA $D020 as RAM.")) return 1; + screen.get_slice(1, 6, MONITOR_DISASM_ROW_CHARS, line); + if (expect(strstr(line, "2005 EE 20 D0 INC $D020") == line && + strstr(line, "[RAM]") != NULL, + "ASM $2000 readback must disassemble INC $D020 as RAM.")) return 1; + screen.get_slice(1, 7, MONITOR_DISASM_ROW_CHARS, line); + if (expect(strstr(line, "2008 4C 05 20 JMP $2005") == line && + strstr(line, "[RAM]") != NULL, + "ASM $2000 readback must disassemble JMP $2005 as RAM.")) return 1; + + if (expect(mon.poll(0) == 0, "ASM $2000 edit test: RUN/STOP should leave edit mode.")) return 1; + if (expect(mon.poll(0) == 0, "ASM $2000 edit test: Hex view switch failed.")) return 1; + screen.get_slice(1, 4, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "2000 A9 01 8D 20 D0 EE 20 D0") == line, + "Hex $2000 readback must show the first eight edited bytes.")) return 1; + screen.get_slice(1, 5, MONITOR_HEX_ROW_CHARS, line); + if (expect(strstr(line, "2008 4C 05 20") == line, + "Hex $2008 readback must show the final edited JMP bytes.")) return 1; + if (expect(mon.poll(0) == 1, "ASM $2000 edit test: monitor exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_asm_cpu_bank_cycle_preserves_screen_row(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char header[39]; + char status[39]; + int row_before = -1; + int row_after = -1; + const int keys[] = { 'J', 'A', KEY_DOWN, KEY_DOWN, 'o', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.basic[0] = 0x20; + backend.basic[1] = 0x34; + backend.basic[2] = 0x12; + backend.basic[3] = 0x20; + backend.basic[4] = 0x78; + backend.basic[5] = 0x56; + backend.basic[6] = 0xEA; + backend.basic[7] = 0xEA; + for (uint16_t addr = 0xA000; addr < 0xA010; addr++) { + backend.ram[addr] = 0xEA; + } + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("A000", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM bank-anchor test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM bank-anchor test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM bank-anchor test: first down failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM bank-anchor test: second down failed.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_before), + "ASM bank-anchor test: highlighted row not found before CPU bank cycle.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $A006") == header, + "ASM bank-anchor test must land on the third visible instruction before cycling banks.")) return 1; + + if (expect(mon.poll(0) == 0, "ASM bank-anchor test: CPU bank cycle failed.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_after), + "ASM bank-anchor test: highlighted row not found after CPU bank cycle.")) return 1; + if (expect(row_after == row_before, + "CPU bank cycling in ASM view must preserve the visible cursor row.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $A006") == header, + "CPU bank cycling in ASM view must preserve the logical cursor address when possible.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "C7O0 ") == status, + "CPU bank cycling test must advance the monitor CPU bank while live CPU stays separate.")) return 1; + if (expect(mon.poll(0) == 1, "ASM bank-anchor test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_asm_page_up_keeps_screen_row(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int keys[16]; + int key_count = 0; + int row_before = -1; + int row_after = -1; + uint16_t addr = 0xC000; + + for (int i = 0; i < 96; i++) { + if ((i % 3) == 0) { + backend.write(addr++, 0x20); + backend.write(addr++, 0x00); + backend.write(addr++, 0x10); + } else if ((i % 3) == 1) { + backend.write(addr++, 0xA9); + backend.write(addr++, 0x01); + } else { + backend.write(addr++, 0xEA); + } + } + + keys[key_count++] = 'J'; + keys[key_count++] = 'A'; + for (int i = 0; i < 5; i++) keys[key_count++] = KEY_DOWN; + keys[key_count++] = KEY_PAGEDOWN; + keys[key_count++] = KEY_PAGEUP; + keys[key_count++] = KEY_BREAK; + FakeKeyboard kb(keys, key_count); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM page-up test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM page-up test: ASM view switch failed.")) return 1; + for (int i = 0; i < 5; i++) { + if (expect(mon.poll(0) == 0, "ASM page-up test: initial down navigation failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "ASM page-up test: page-down failed.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_before), + "ASM page-up test: highlighted row not found before page-up.")) return 1; + if (expect(mon.poll(0) == 0, "ASM page-up test: page-up failed.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_after), + "ASM page-up test: highlighted row not found after page-up.")) return 1; + if (expect(row_after == row_before, + "ASM page-up must preserve the visible cursor row like page-down.")) return 1; + if (expect(mon.poll(0) == 1, "ASM page-up test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_space_shortcuts_match_existing_paging(void) +{ + static const struct { + int view_key; + const char *page_down_message; + const char *page_up_message; + } cases[] = { + { 0, "Space must match F7 page-down behavior in Memory view.", + "Shift+Space must match F1 page-up behavior in Memory view." }, + { 'I', "Space must match F7 page-down behavior in ASCII view.", + "Shift+Space must match F1 page-up behavior in ASCII view." }, + { 'V', "Space must match F7 page-down behavior in Screen view.", + "Shift+Space must match F1 page-up behavior in Screen view." }, + { 'B', "Space must match F7 page-down behavior in Binary view.", + "Shift+Space must match F1 page-up behavior in Binary view." }, + { 'A', "Space must match F7 page-down behavior in Assembly view.", + "Shift+Space must match F1 page-up behavior in Assembly view." }, + }; + + for (unsigned int i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + for (int direction = 0; direction < 2; direction++) { + TestUserInterface ui_a; + TestUserInterface ui_b; + CaptureScreen screen_a; + CaptureScreen screen_b; + FakeMemoryBackend backend_a; + FakeMemoryBackend backend_b; + int keys_a[4]; + int keys_b[4]; + int key_count = 0; + const int page_key = direction ? KEY_F1 : KEY_F7; + const int shortcut_key = direction ? KEY_SHIFT_SP : KEY_SPACE; + const char *message = direction ? cases[i].page_up_message : cases[i].page_down_message; + + for (uint32_t addr = 0; addr < 0x10000UL; addr++) { + uint8_t value = (uint8_t)((addr >> 8) ^ addr); + backend_a.write((uint16_t)addr, value); + backend_b.write((uint16_t)addr, value); + } + + keys_a[key_count] = 'J'; + keys_b[key_count++] = 'J'; + if (cases[i].view_key) { + keys_a[key_count] = cases[i].view_key; + keys_b[key_count++] = cases[i].view_key; + } + keys_a[key_count] = page_key; + keys_b[key_count++] = shortcut_key; + + FakeKeyboard kb_a(keys_a, key_count); + FakeKeyboard kb_b(keys_b, key_count); + ui_a.screen = &screen_a; + ui_a.keyboard = &kb_a; + ui_a.set_prompt("4000", 1); + ui_b.screen = &screen_b; + ui_b.keyboard = &kb_b; + ui_b.set_prompt("4000", 1); + + monitor_reset_saved_state(); + BackendMachineMonitor mon_a(&ui_a, &backend_a); + mon_a.init(&screen_a, &kb_a); + for (int step = 0; step < key_count; step++) { + if (expect(mon_a.poll(0) == 0, "Paging parity test setup A failed.")) return 1; + } + + monitor_reset_saved_state(); + BackendMachineMonitor mon_b(&ui_b, &backend_b); + mon_b.init(&screen_b, &kb_b); + for (int step = 0; step < key_count; step++) { + if (expect(mon_b.poll(0) == 0, "Paging parity test setup B failed.")) return 1; + } + + if (expect_screens_equal(screen_a, screen_b, message)) return 1; + mon_a.deinit(); + mon_b.deinit(); + } + } + + return 0; +} + +static int test_opcode_picker_refilters_live(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[39]; + const int keys[] = { 'A', 'E', 'J', 'S', KEY_DELETE, KEY_BREAK, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Opcode picker refilter test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker refilter test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker refilter test: first letter failed.")) return 1; + screen.get_slice(1, 6, 38, line); + if (expect(strstr(line, "JMP") != NULL || strstr(line, "JSR") != NULL || strstr(line, "JAM") != NULL, + "Opcode picker refilter test must start with multiple visible suggestions for prefix J.")) return 1; + + if (expect(mon.poll(0) == 0, "Opcode picker refilter test: second letter failed.")) return 1; + screen.get_slice(1, 5, 38, line); + if (expect(strstr(line, "JSR") != NULL, + "Opcode picker must immediately shrink to the matching mnemonic list as the prefix narrows.")) return 1; + screen.get_slice(1, 6, 38, line); + if (expect(strstr(line, "JSR") == NULL && strstr(line, "JMP") == NULL && strstr(line, "JAM") == NULL, + "Opcode picker must clear stale suggestion rows when the candidate list shrinks.")) return 1; + + if (expect(mon.poll(0) == 0, "Opcode picker refilter test: delete failed.")) return 1; + screen.get_slice(1, 6, 38, line); + if (expect(strstr(line, "JSR") != NULL || strstr(line, "JMP") != NULL || strstr(line, "JAM") != NULL, + "Opcode picker must expand the suggestion list again when the prefix is deleted.")) return 1; + + if (expect(mon.poll(0) == 0, "Opcode picker refilter test: RUN/STOP should close the picker first.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker refilter test: RUN/STOP should leave edit mode next.")) return 1; + if (expect(mon.poll(0) == 1, "Opcode picker refilter test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_opcode_picker_filters_orders_and_commits_on_enter(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char first_row[39]; + char second_row[39]; + const int keys[] = { 'J', 'A', 'E', 'N', 'O', 'P', KEY_RETURN }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 6; i++) { + if (expect(mon.poll(0) == 0, "Opcode picker NOP test: command sequence failed before ENTER.")) return 1; + } + screen.get_slice(1, 5, 38, first_row); + screen.get_slice(1, 6, 38, second_row); + if (expect(strstr(first_row, "NOP") != NULL, + "Documented-only NOP completion must offer the documented NOP variant.")) return 1; + if (expect(strstr(second_row, "NOP") == NULL, + "Documented-only NOP completion must not show undocumented NOP variants.")) return 1; + if (expect(backend.read(0xC000) == 0x00, + "Typing a mnemonic in the opcode picker must not write memory before ENTER.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker NOP test: ENTER commit failed.")) return 1; + if (expect(backend.read(0xC000) == 0xEA, + "ENTER on documented-only NOP completion must encode the documented $EA NOP.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char first_row[39]; + char second_row[39]; + const int keys[] = { 'J', 'A', 'U', 'E', 'N', 'O', 'P', KEY_RETURN }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C100", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 7; i++) { + if (expect(mon.poll(0) == 0, "Opcode picker illegal NOP test: command sequence failed before ENTER.")) return 1; + } + screen.get_slice(1, 5, 38, first_row); + screen.get_slice(1, 6, 38, second_row); + if (expect(strstr(first_row, "NOP") != NULL && strstr(first_row, "$") == NULL && strstr(first_row, "#") == NULL, + "Undocumented-enabled NOP completion must place the no-operand NOP first.")) return 1; + if (expect(strstr(second_row, "NOP") != NULL, + "Undocumented-enabled NOP completion must still expose additional NOP variants.")) return 1; + if (expect(backend.read(0xC100) == 0x00, + "Undocumented-enabled picker typing must still wait for ENTER before writing memory.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker illegal NOP test: ENTER commit failed.")) return 1; + if (expect(backend.read(0xC100) == 0xEA, + "ENTER must default to the first no-operand NOP variant when undocumented opcodes are enabled.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char first_row[39]; + const int keys[] = { 'J', 'A', 'E', 'L', 'S', 'R', KEY_RETURN }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C200", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 6; i++) { + if (expect(mon.poll(0) == 0, "Opcode picker LSR test: command sequence failed before ENTER.")) return 1; + } + screen.get_slice(1, 5, 38, first_row); + if (expect(strstr(first_row, "LSR A") != NULL, + "Mnemonic variants with an addressing-free form must list that simplest variant first.")) return 1; + if (expect(backend.read(0xC200) == 0x00, + "Typing LSR in the picker must not write memory before ENTER.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker LSR test: ENTER commit failed.")) return 1; + if (expect(backend.read(0xC200) == 0x4A, + "ENTER must commit the first accumulator/implied variant when it is the simplest form.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_opcode_picker_browsing_does_not_mutate_frozen_charset_backup(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + const int keys[] = { 'J', 'A', 'E', 'C', 'L', 'D', KEY_DELETE, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + const uint8_t sentinel[] = { 0x54, 0x18, 0xEA, 0x18, 0x18, 0x58, 0x00, 0x00 }; + + backend.set_frozen(true); + for (int i = 0; i < (int)sizeof(sentinel); i++) { + backend.ram_backup[0x10 + i] = sentinel[i]; + } + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0810", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])); i++) { + if (expect(mon.poll(0) == 0 || i == (int)(sizeof(keys) / sizeof(keys[0])) - 1, + "Freeze charset safety test: command sequence failed.")) return 1; + } + for (int i = 0; i < (int)sizeof(sentinel); i++) { + if (expect(backend.ram_backup[0x10 + i] == sentinel[i], + "Browsing and filtering opcode suggestions in freeze mode must not mutate the active charset backup bytes.")) return 1; + } + mon.deinit(); + return 0; +} + +static int test_opcode_picker_near_bottom_refresh_stays_inside_content(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int keys[32]; + int n = 0; + + for (uint16_t addr = 0x0801; addr < 0x0820; addr++) { + backend.write(addr, 0xEA); + } + + keys[n++] = 'A'; + keys[n++] = 'E'; + for (int i = 0; i < 16; i++) keys[n++] = KEY_DOWN; + keys[n++] = 'L'; + keys[n++] = 'D'; + keys[n++] = KEY_BREAK; + keys[n++] = KEY_BREAK; + + FakeKeyboard kb(keys, n); + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Lower-border popup bounds test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Lower-border popup bounds test: edit mode entry failed.")) return 1; + for (int i = 0; i < 16; i++) { + if (expect(mon.poll(0) == 0, "Lower-border popup bounds test: cursor movement failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "Lower-border popup bounds test: popup open failed.")) return 1; + + screen.reset_write_counts(); + if (expect(mon.poll(0) == 0, "Lower-border popup bounds test: popup refilter failed.")) return 1; + if (expect(screen.count_writes_outside_rect(1, 4, 38, 21) == 0, + "Lower-border opcode popup refresh must stay inside the monitor content area.")) return 1; + + if (expect(mon.poll(0) == 0, "Lower-border popup bounds test: RUN/STOP should close the picker first.")) return 1; + if (expect(mon.poll(0) == 0, "Lower-border popup bounds test: RUN/STOP should leave edit mode next.")) return 1; + mon.deinit(); + return 0; +} + +static int test_opcode_picker_selection_near_bottom_preserves_live_charset_page(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char header[39]; + const char *addr_text = NULL; + unsigned int current_addr = 0; + int keys[48]; + int n = 0; + + backend.set_frozen(true); + for (uint16_t addr = 0x0801; addr < 0x0820; addr++) { + backend.ram_backup[addr - 0x0800] = 0xEA; + backend.ram[addr] = 0x40; + } + + keys[n++] = 'J'; + keys[n++] = 'A'; + keys[n++] = 'E'; + for (int i = 0; i < 15; i++) keys[n++] = KEY_DOWN; + keys[n++] = 'J'; + keys[n++] = 'S'; + keys[n++] = 'R'; + keys[n++] = KEY_RETURN; + keys[n++] = KEY_BREAK; + + FakeKeyboard kb(keys, n); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0801", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Lower-border freeze write test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Lower-border freeze write test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Lower-border freeze write test: edit mode entry failed.")) return 1; + for (int i = 0; i < 15; i++) { + if (expect(mon.poll(0) == 0, "Lower-border freeze write test: cursor movement failed.")) return 1; + } + screen.get_slice(1, 3, 38, header); + addr_text = strchr(header, '$'); + if (expect(addr_text != NULL && sscanf(addr_text + 1, "%x", ¤t_addr) == 1, + "Lower-border freeze write test must expose the current ASM address in the header.")) return 1; + if (expect(current_addr >= 0x0801 && current_addr < 0x0820, + "Lower-border freeze write test must stay inside the frozen $0800 page.")) return 1; + for (int i = 0; i < 3; i++) { + if (expect(mon.poll(0) == 0, "Lower-border freeze write test: popup interaction failed before commit.")) return 1; + } + if (expect(mon.poll(0) == 0, "Lower-border freeze write test: opcode commit failed.")) return 1; + + if (expect(backend.read((uint16_t)current_addr) == 0x20, + "Lower-border popup selection must still commit the selected opcode to the intended frozen RAM address.")) return 1; + if (expect(backend.ram_backup[current_addr - 0x0800] == 0x20, + "Frozen opcode selection must update the saved RAM buffer for the selected address.")) return 1; + if (expect(backend.ram[current_addr] == 0x40, + "Frozen opcode selection near the lower border must not overwrite the live $0800 charset page.")) return 1; + + if (expect(mon.poll(0) == 0, "Lower-border freeze write test: exit edit mode failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_opcode_picker_pauses_poll_mode(void) +{ + TestUserInterface ui; + CaptureScreen screen; + CaptureScreen snapshot; + FakeMemoryBackend backend; + char line[19]; + int total_writes = 0; + const int keys[] = { 'A', 'P', 'E', 'N' }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + set_fake_ms_timer(0); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Opcode picker poll test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker poll test: poll mode enable failed.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker poll test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Opcode picker poll test: picker open failed.")) return 1; + screen.get_slice(16, 4, 18, line); + if (expect(strstr(line, " N_") == line, + "Opcode picker poll test must open the mnemonic overlay before idle polling.")) return 1; + + snapshot = screen; + screen.reset_write_counts(); + set_fake_ms_timer(20); + if (expect(mon.poll(0) == 0, "Opcode picker poll test: idle poll failed.")) return 1; + for (int y = 0; y < 25; y++) { + for (int x = 0; x < 40; x++) { + total_writes += screen.write_counts[y][x]; + } + } + if (expect(total_writes == 0, + "Poll mode must not redraw the opcode picker overlay while it is open.")) return 1; + if (expect_screens_equal(snapshot, screen, + "Idle poll must leave the opcode picker overlay screen unchanged.")) return 1; + + mon.deinit(); + return 0; +} + +static int test_cross_view_sync(void) +{ + // Edit in HEX, view memory unchanged; Edit in SCR via 'A' key should be visible + // through a direct memory read (which represents what every other view renders). + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'J', 'V', 'E', 'B', KEY_BREAK }; + FakeKeyboard kb(keys, 5); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 5; i++) (void)mon.poll(0); + // Now switch to HEX and verify the same byte reads back. + if (expect(backend.read(0x0400) == 0x02, "Cross-view: SCR 'B' edit must store 0x02 visible to all views")) return 1; + return 0; +} + +static int test_binary_bit_navigation_and_width(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char row[38]; + const int keys[] = { + 'J', 'B', + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, + KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + backend.write(0x0400, 0x80); + backend.write(0x0401, 0x01); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary bit test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary bit test: view switch failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0400/7") == header, + "Binary header must show cursor address and MSB bit index.")) return 1; + screen.get_slice(1, 4, 13, row); + if (expect(strcmp(row, "0400 *.......") == 0, + "Binary width=1 must render exactly 8 bits per row.")) return 1; + if (expect(screen.reverse_chars[4][6] && !screen.reverse_chars[4][7], + "Binary cursor must select exactly one bit at MSB.")) return 1; + + for (int i = 0; i < 7; i++) { + if (expect(mon.poll(0) == 0, "Binary bit test: right navigation failed before byte boundary.")) return 1; + } + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0400/0") == header, + "Binary cursor must reach LSB as bit index 0.")) return 1; + if (expect(screen.reverse_chars[4][13] && !screen.reverse_chars[4][12], + "Binary cursor must select exactly one bit at LSB.")) return 1; + + if (expect(mon.poll(0) == 0, "Binary bit test: right navigation across byte boundary failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0401/7") == header, + "Binary cursor must cross to next byte at MSB.")) return 1; + if (expect(screen.reverse_chars[5][6], + "Binary cursor must move to the next row's MSB after crossing byte boundary.")) return 1; + if (expect(mon.poll(0) == 1, "Binary bit test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char row[40]; + const int keys[] = { 'B', 'W', 'W', 'W', 'W', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + backend.write(0x0000, 0x80); + backend.write(0x0001, 0x01); + backend.write(0x0002, 0xFF); + backend.write(0x0003, 0x55); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary width test: view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary width test: cycle to width 2 failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary width test: cycle to width 3 failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary width test: cycle to width 3S failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary width test: cycle to width 4 failed.")) return 1; + screen.get_slice(1, 4, 37, row); + if (expect(strcmp(row, "0000 *..............*********.*.*.*.*") == 0, + "Binary width cycling must reach width 4 without a hex preview.")) return 1; + if (expect(strstr(row, "80") == NULL && strstr(row, "01") == NULL && + strstr(row, "FF") == NULL && strstr(row, "55") == NULL, + "Binary width 4 must omit the trailing hex bytes.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "W=") == NULL && strstr(header, "bits") == NULL, + "Binary width must not be displayed in the header.")) return 1; + if (expect(mon.poll(0) == 1, "Binary width test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_binary_row_formats(void) +{ + static const struct { + int width_presses; + const char *expected_row; + int expected_len; + } cases[] = { + { 0, "0000 ...*..*. 12", 16 }, + { 1, "0000 ...*..*. ..**.*.. 12 34", 28 }, + { 2, "0000 ...*..*. ..**.*.. .*.*.**. 123456", 38 }, + { 3, "0000 ...*..*...**.*...*.*.**. 12 34 56", 38 }, + { 4, "0000 ...*..*...**.*...*.*.**..****...", 37 }, + }; + + for (unsigned int i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char row[40]; + int keys[6]; + int key_count = 0; + + backend.write(0x0000, 0x12); + backend.write(0x0001, 0x34); + backend.write(0x0002, 0x56); + backend.write(0x0003, 0x78); + monitor_reset_saved_state(); + + keys[key_count++] = 'B'; + for (int press = 0; press < cases[i].width_presses; press++) { + keys[key_count++] = 'W'; + } + keys[key_count++] = KEY_BREAK; + FakeKeyboard kb(keys, key_count); + ui.screen = &screen; + ui.keyboard = &kb; + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary row format test: binary view switch failed.")) return 1; + for (int press = 0; press < cases[i].width_presses; press++) { + if (expect(mon.poll(0) == 0, "Binary row format test: width cycling failed.")) return 1; + } + screen.get_slice(1, 4, cases[i].expected_len, row); + if (expect(strcmp(row, cases[i].expected_row) == 0, + "Binary row format test: rendered row mismatch.")) return 1; + if (expect((int)strlen(row) == cases[i].expected_len, + "Binary row format test: rendered row length mismatch.")) return 1; + if (expect(cases[i].expected_len <= 38, + "Binary row format test: row must fit within 38 columns.")) return 1; + if (expect(mon.poll(0) == 1, "Binary row format test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_memory_row_width_cycle(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char row8[38]; + char row16[39]; + const int keys[] = { 'W', 'I', 'M', 'W', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + for (int i = 0; i < 16; i++) { + backend.write((uint16_t)i, (uint8_t)i); + } + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + screen.get_slice(1, 4, 37, row8); + if (expect(strcmp(row8, "0000 00 01 02 03 04 05 06 07 ........") == 0, + "Memory view must default to width 8 with ASCII on the right.")) return 1; + + if (expect(mon.poll(0) == 0, "Memory width test: cycle to width 16 failed.")) return 1; + screen.get_slice(1, 4, 38, row16); + if (expect(strcmp(row16, "0000 0001020304050607 08090A0B0C0D0E0F") == 0, + "Memory width cycling must render the packed 16-byte row.")) return 1; + + if (expect(mon.poll(0) == 0, "Memory width test: ASCII view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Memory width test: return to memory view failed.")) return 1; + screen.get_slice(1, 4, 38, row16); + if (expect(strcmp(row16, "0000 0001020304050607 08090A0B0C0D0E0F") == 0, + "Memory view must remember the chosen width when re-entering the view.")) return 1; + + if (expect(mon.poll(0) == 0, "Memory width test: cycle back to width 8 failed.")) return 1; + screen.get_slice(1, 4, 37, row8); + if (expect(strcmp(row8, "0000 00 01 02 03 04 05 06 07 ........") == 0, + "Memory width cycling must wrap back to width 8.")) return 1; + + if (expect(mon.poll(0) == 1, "Memory width test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_binary_delete_behavior(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char row[14]; + const int keys[] = { 'J', 'B', KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + backend.write(0x0400, 0xAA); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary DEL set-bit test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL set-bit test: view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL set-bit test: delete failed.")) return 1; + if (expect(backend.read(0x0400) == 0x2A, + "Binary DEL must clear only the selected set bit.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0400/6") == header, + "Binary DEL must advance the cursor by exactly one bit.")) return 1; + screen.get_slice(1, 4, 13, row); + if (expect(strcmp(row, "0400 ..*.*.*.") == 0, + "Binary DEL must render the cleared bit as '.' without changing the other bits.")) return 1; + if (expect(screen.reverse_chars[4][7] && !screen.reverse_chars[4][6], + "Binary DEL must leave the highlight on the next bit, not the original one.")) return 1; + if (expect(mon.poll(0) == 1, "Binary DEL set-bit test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char row[14]; + const int keys[] = { 'J', 'B', 'E', KEY_DELETE, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + backend.write(0x0400, 0x2A); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary DEL clear-bit test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL clear-bit test: view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL clear-bit test: edit entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL clear-bit test: delete failed.")) return 1; + if (expect(backend.read(0x0400) == 0x2A, + "Binary DEL on an already-clear bit must leave the byte unchanged.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0400/6") == header, + "Binary DEL must still advance one bit while in edit mode.")) return 1; + screen.get_slice(1, 4, 13, row); + if (expect(strcmp(row, "0400 ..*.*.*.") == 0, + "Binary DEL on a clear bit must preserve the rendered binary row.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL clear-bit test: leave edit mode failed.")) return 1; + if (expect(mon.poll(0) == 1, "Binary DEL clear-bit test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'J', 'B', KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0400", 1); + backend.write(0x0400, 0x01); + backend.write(0x0401, 0x80); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary DEL boundary test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL boundary test: view switch failed.")) return 1; + for (int i = 0; i < 7; i++) { + if (expect(mon.poll(0) == 0, "Binary DEL boundary test: cursor advance to bit 0 failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "Binary DEL boundary test: delete failed.")) return 1; + if (expect(backend.read(0x0400) == 0x00, + "Binary DEL must clear the final bit in the byte without touching the next byte.")) return 1; + if (expect(backend.read(0x0401) == 0x80, + "Binary DEL byte-boundary advance must not modify the next byte.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0401/7") == header, + "Binary DEL must advance to the next byte's MSB after bit 0.")) return 1; + if (expect(screen.reverse_chars[5][6], + "Binary DEL across a byte boundary must highlight the next row's first bit.")) return 1; + if (expect(mon.poll(0) == 1, "Binary DEL boundary test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char row[14]; + const int keys[] = { 'J', 'B', KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, KEY_DELETE, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("FFFF", 1); + backend.write(0xFFFF, 0x01); + backend.write(0x0000, 0x80); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Binary DEL wrap test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary DEL wrap test: view switch failed.")) return 1; + for (int i = 0; i < 7; i++) { + if (expect(mon.poll(0) == 0, "Binary DEL wrap test: cursor advance to bit 0 failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "Binary DEL wrap test: delete failed.")) return 1; + if (expect(backend.read(0xFFFF) == 0x00, + "Binary DEL must clear the selected bit at $FFFF before wrapping.")) return 1; + if (expect(backend.read(0x0000) == 0x80, + "Binary DEL wraparound must not modify the wrapped-to byte.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR BIN $0000/7") == header, + "Binary DEL at $FFFF bit 0 must wrap to $0000 bit 7.")) return 1; + screen.get_slice(1, 4, 13, row); + if (expect(strcmp(row, "0000 *.......") == 0, + "Binary DEL wraparound must render the wrapped-to byte using the existing binary row layout.")) return 1; + if (expect(mon.poll(0) == 1, "Binary DEL wrap test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_clipboard_number_and_range(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + int keys[16]; + int n = 0; + keys[n++] = 'N'; + keys[n++] = KEY_DOWN; // Decimal representation. + keys[n++] = KEY_CTRL_C; + keys[n++] = 'B'; + for (int i = 0; i < 8; i++) keys[n++] = KEY_RIGHT; + keys[n++] = KEY_CTRL_V; + keys[n++] = KEY_BREAK; + FakeKeyboard kb(keys, n); + ui.screen = &screen; + ui.keyboard = &kb; + backend.write(0x0000, 65); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Number inspector did not open.")) return 1; + if (expect(mon.poll(0) == 0, "Number inspector decimal navigation failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Number inspector must open as a framed popup inside the monitor content area.")) return 1; + if (expect(screen.reverse_chars[top + 3][left + 1], + "Number inspector must allow navigating to the decimal representation.")) return 1; + if (expect(mon.poll(0) == 0, "Number inspector CBM-C copy failed.")) return 1; + if (expect(mon.poll(0) == 0, "Binary view switch after number copy failed.")) return 1; + for (int i = 0; i < 8; i++) { + if (expect(mon.poll(0) == 0, "Binary cursor move before paste failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "CBM-V paste into binary mode failed.")) return 1; + if (expect(backend.read(0x0001) == 65, + "Number clipboard paste must write canonical byte value in binary mode.")) return 1; + if (expect(mon.poll(0) == 1, "Number clipboard test exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { + 'R', KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, + KEY_CTRL_C, KEY_RIGHT, KEY_CTRL_V, KEY_CTRL_V, KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + for (int i = 0; i < 4; i++) { + backend.write((uint16_t)i, (uint8_t)(0xA0 + i)); + } + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Range mode entry failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Range") != NULL, + "Header must show Range while range mode is active.")) return 1; + if (expect(mon.poll(0) == 0 && mon.poll(0) == 0 && mon.poll(0) == 0, + "Range cursor movement failed.")) return 1; + if (expect(screen.reverse_chars[4][6] && screen.reverse_chars[4][9] && + screen.reverse_chars[4][12] && screen.reverse_chars[4][15], + "Range selection must visibly invert every selected byte.")) return 1; + if (expect(mon.poll(0) == 0, "Range CBM-C copy failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Range") == NULL, + "CBM-C must exit range mode after copying.")) return 1; + if (expect(mon.poll(0) == 0, "Range paste target movement failed.")) return 1; + if (expect(mon.poll(0) == 0, "Range paste failed.")) return 1; + for (int i = 0; i < 4; i++) { + if (expect(backend.read((uint16_t)(4 + i)) == (uint8_t)(0xA0 + i), + "Range paste must reproduce copied bytes sequentially.")) return 1; + } + if (expect(mon.poll(0) == 0, "Repeat range paste failed.")) return 1; + for (int i = 0; i < 4; i++) { + if (expect(backend.read((uint16_t)(8 + i)) == (uint8_t)(0xA0 + i), + "Repeated CBM-V must duplicate the last copied content.")) return 1; + } + if (expect(mon.poll(0) == 1, "Range clipboard test exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_asm_range_copy_paste(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'J', 'A', 'R', KEY_DOWN, KEY_CTRL_C, 'J', KEY_CTRL_V, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + const uint8_t expected[] = { 0xA9, 0x12, 0x8D, 0x00, 0x04 }; + + backend.write(0xC000, 0xA9); + backend.write(0xC001, 0x12); + backend.write(0xC002, 0x8D); + backend.write(0xC003, 0x00); + backend.write(0xC004, 0x04); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + ui.push_prompt("C100", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])) - 1; i++) { + if (expect(mon.poll(0) == 0, "ASM range test command failed.")) return 1; + } + + for (int i = 0; i < (int)sizeof(expected); i++) { + if (expect(backend.read((uint16_t)(0xC100 + i)) == expected[i], + "ASM range copy/paste must include every byte of the final selected instruction.")) return 1; + } + if (expect(backend.read(0xC105) == 0x00, + "ASM range copy/paste must not overrun past the selected instructions.")) return 1; + if (expect(mon.poll(0) == 1, "ASM range test exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_asm_paste_keeps_viewport_position(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[39]; + int keys[32]; + int n = 0; + const uint8_t expected[] = { 0xA9, 0x12, 0x8D, 0x00, 0x04 }; + + keys[n++] = 'J'; + keys[n++] = 'A'; + keys[n++] = 'R'; + keys[n++] = KEY_DOWN; + keys[n++] = KEY_CTRL_C; + keys[n++] = 'J'; + for (int i = 0; i < 8; i++) { + keys[n++] = KEY_DOWN; + } + keys[n++] = KEY_CTRL_V; + keys[n++] = KEY_BREAK; + + backend.write(0xC000, 0xA9); + backend.write(0xC001, 0x12); + backend.write(0xC002, 0x8D); + backend.write(0xC003, 0x00); + backend.write(0xC004, 0x04); + for (uint16_t addr = 0xC100; addr < 0xC120; addr++) { + backend.write(addr, 0xEA); + } + + FakeKeyboard kb(keys, n); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + ui.push_prompt("C100", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM paste viewport test: goto source failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM paste viewport test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM paste viewport test: range mode failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM paste viewport test: range extension failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM paste viewport test: copy failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASM paste viewport test: goto target failed.")) return 1; + for (int i = 0; i < 8; i++) { + if (expect(mon.poll(0) == 0, "ASM paste viewport test: target navigation failed.")) return 1; + } + + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "C100 EA") == line, + "ASM paste viewport test must start with the original top row still visible.")) return 1; + + if (expect(mon.poll(0) == 0, "ASM paste viewport test: paste failed.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "MONITOR ASM $C10D") == line, + "ASM paste must leave the cursor on the byte immediately after the pasted region.")) return 1; + screen.get_slice(1, 4, 38, line); + if (expect(strstr(line, "C100 EA") == line, + "ASM paste must keep the current viewport anchored instead of snapping the pasted region to the top.")) return 1; + for (int i = 0; i < (int)sizeof(expected); i++) { + if (expect(backend.read((uint16_t)(0xC108 + i)) == expected[i], + "ASM paste viewport test must write the copied bytes at the current cursor position.")) return 1; + } + + if (expect(mon.poll(0) == 1, "ASM paste viewport test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_illegal_mode_header_label(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[39]; + const int keys[] = { 'A', '*', 'U', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Illegal mode label test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Illegal mode label test: '*' should now be ignored.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "UndocOp") == NULL, + "Disabled undocumented-opcode mode must not show the UndocOp label.")) return 1; + if (expect(strstr(line, "IllOp") == NULL, + "Visible monitor UI must no longer show the old IllOp label.")) return 1; + if (expect(mon.poll(0) == 0, "Illegal mode label test: U toggle failed.")) return 1; + screen.get_slice(1, 3, 38, line); + if (expect(strstr(line, "Undc") != NULL, + "Enabled undocumented-opcode mode must show the compact Undc label in the header.")) return 1; + if (expect(strstr(line, "Illegal:ON") == NULL, + "Illegal opcode mode must no longer show the old long header text.")) return 1; + if (expect(mon.poll(0) == 1, "Illegal mode label test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_hunt_and_compare_picker_navigation(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char row[38]; + const int keys[] = { 'H', 'D', 'E', KEY_RETURN, KEY_PAGEDOWN, KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + for (uint16_t addr = 0xC000; addr <= 0xC013; addr++) { + backend.write(addr, 0xDE); + } + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Hunt picker test: hunt command failed.")) return 1; + screen.get_slice(1, 4, 37, row); + if (expect(strstr(row, "C000 DE") == row, "Hunt picker must show the first match at the top initially.")) return 1; + if (expect(mon.poll(0) == 0, "Hunt picker test: page-down failed.")) return 1; + if (expect(mon.poll(0) == 0, "Hunt picker test: RETURN jump failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $C012") == header, + "Hunt picker RETURN must jump to the paged selection.")) return 1; + if (expect(mon.poll(0) == 1, "Hunt picker test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char row[38]; + const int keys[] = { 'C', KEY_DOWN, KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + backend.write(0xC100, 0x10); + backend.write(0xC101, 0x11); + backend.write(0xC102, 0x12); + backend.write(0xC103, 0x13); + backend.write(0xC200, 0x10); + backend.write(0xC201, 0x91); + backend.write(0xC202, 0x92); + backend.write(0xC203, 0x13); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C100-C103,C200", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Compare picker test: compare command failed.")) return 1; + screen.get_slice(1, 4, 37, row); + if (expect(strstr(row, "C101 11") == row, "Compare picker must list the first differing address first.")) return 1; + if (expect(mon.poll(0) == 0, "Compare picker test: DOWN failed.")) return 1; + if (expect(mon.poll(0) == 0, "Compare picker test: RETURN jump failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $C102") == header, + "Compare picker RETURN must jump to the selected difference.")) return 1; + if (expect(mon.poll(0) == 1, "Compare picker test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_hunt_prompt_typed_input(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'H', 'd', 'e', KEY_RETURN, KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + backend.write(0xC004, 0xDE); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "Typed Hunt test: lowercase hex prompt failed.")) return 1; + if (expect(mon.poll(0) == 0, "Typed Hunt test: lowercase hex RETURN failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $C004") == header, + "Typed Hunt must accept lowercase hex input in the Hunt popup.")) return 1; + if (expect(mon.poll(0) == 1, "Typed Hunt test: lowercase hex exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'H', '"', 'H', 'e', 'l', 'l', 'o', '"', KEY_RETURN, KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + const char hello[] = "Hello"; + const char upper_hello[] = "HELLO"; + + for (unsigned int i = 0; i < sizeof(hello) - 1; i++) { + backend.write((uint16_t)(0xC000 + i), (uint8_t)hello[i]); + backend.write((uint16_t)(0xC008 + i), (uint8_t)upper_hello[i]); + } + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "Typed Hunt test: quoted ASCII prompt failed.")) return 1; + if (expect(mon.poll(0) == 0, "Typed Hunt test: quoted ASCII RETURN failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $C000") == header, + "Typed Hunt must preserve quoted mixed-case ASCII bytes.")) return 1; + if (expect(mon.poll(0) == 1, "Typed Hunt test: quoted ASCII exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_number_popup_edit_and_commit(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'N', 'F', 'A', 'E', '1', KEY_DELETE, KEY_DELETE, KEY_RETURN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "Number popup test: open failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $0000 BYTE") == line, + "Number popup must open in BYTE mode with the current address in the framed header.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: typing first hex digit failed.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $0F") == line, + "Number popup must zero-pad one-digit hex input as a BYTE preview.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: typing second hex digit failed.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $FA") == line, + "Number popup must keep two-digit hex input in BYTE mode.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: typing third hex digit failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $0000 WORD") == line, + "Number popup must switch to WORD mode on the third hex digit.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $0FAE") == line, + "Number popup must preserve leading zeroes when hex input grows to WORD width.")) return 1; + get_popup_line(screen, 3, line, sizeof(line)); + if (expect(strstr(line, "Binary %0000111110101110") == line, + "Number popup WORD binary preview must show all 16 bits with the percent prefix.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: typing fourth hex digit failed.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $FAE1") == line, + "Number popup must show the full four-digit hex WORD preview.")) return 1; + get_popup_line(screen, 3, line, sizeof(line)); + if (expect(strstr(line, "Binary %1111101011100001") == line, + "Number popup must show the full 16-bit WORD binary preview for $FAE1.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: first delete failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $0000 WORD") == line, + "Deleting from four to three hex digits must keep the Number popup in WORD mode.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $0FAE") == line, + "Deleting one hex digit must keep the remaining WORD preview intact.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: second delete failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $0000 BYTE") == line, + "Deleting from three to two hex digits must fall back to BYTE mode.")) return 1; + get_popup_line(screen, 1, line, sizeof(line)); + if (expect(strstr(line, "Hex $FA") == line, + "Deleting back to two hex digits must preserve the BYTE preview value.")) return 1; + get_popup_line(screen, 3, line, sizeof(line)); + if (expect(strstr(line, "Binary %11111010") == line && line[18] == ' ', + "Number popup BYTE binary preview must remain 8 bits wide with the percent prefix.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: Enter commit failed.")) return 1; + if (expect(backend.read(0x0000) == 0xFA && backend.read(0x0001) == 0x00, + "Number popup Enter must commit the current BYTE preview without touching the next byte.")) return 1; + + if (expect(mon.poll(0) == 0, "Number popup test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "Number popup test: exit failed.")) return 1; + mon.deinit(); + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'N', '+', 'a', 'f', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor expr_mon(&ui, &backend); + expr_mon.init(&screen, &kb); + + int r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup test: open failed.")) return 1; + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup test: open-expression failed.")) return 1; + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup test: first lowercase hex digit failed.")) return 1; + get_popup_line(screen, 6, line, sizeof(line)); + if (expect(strstr(line, "Expr=$00+A") == line, + "Expression Number popup must uppercase lowercase hex digits as they are typed.")) return 1; + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup test: second lowercase hex digit failed.")) return 1; + get_popup_line(screen, 6, line, sizeof(line)); + if (expect(strstr(line, "Expr=$00+AF") == line, + "Expression Number popup must keep uppercasing subsequent lowercase hex digits.")) return 1; + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup test: expression close failed.")) return 1; + expr_mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + static const int invalid_keys[] = { 'x', 'g', '!' }; + const int keys[] = { 'N', '+', '0', 'x', 'g', '!', '1', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor expr_mon(&ui, &backend); + expr_mon.init(&screen, &kb); + + int r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup invalid-char test: open failed.")) return 1; + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup invalid-char test: open-expression failed.")) return 1; + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup invalid-char test: zero digit failed.")) return 1; + get_popup_line(screen, 6, line, sizeof(line)); + if (expect(strstr(line, "Expr=$00+0") == line, + "Expression Number popup must accept the leading zero digit.")) return 1; + for (unsigned int i = 0; i < sizeof(invalid_keys) / sizeof(invalid_keys[0]); i++) { + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup invalid-char test: invalid key handling failed.")) return 1; + get_popup_line(screen, 6, line, sizeof(line)); + if (expect(strstr(line, "Expr=$00+0") == line, + "Expression Number popup must ignore disallowed printable characters.")) return 1; + } + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup invalid-char test: trailing digit failed.")) return 1; + get_popup_line(screen, 6, line, sizeof(line)); + if (expect(strstr(line, "Expr=$00+01") == line, + "Expression Number popup must keep parsing with valid digits after rejecting disallowed characters.")) return 1; + r = expr_mon.poll(0); + if (expect(r == 0, "Expression Number popup invalid-char test: expression close failed.")) return 1; + expr_mon.deinit(); + } + + return 0; +} + +static int test_number_popup_word_commit_and_sticky_row(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + const int keys[] = { + 'N', KEY_DOWN, KEY_DOWN, KEY_DOWN, 'A', 'B', KEY_RETURN, + KEY_ESCAPE, KEY_RIGHT, 'N', 'C', KEY_RETURN, KEY_BREAK, KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "ASCII Number popup test: open failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: first row navigation failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: second row navigation failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: third row navigation failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Number popup ASCII-row test must keep the popup framed.")) return 1; + if (expect(screen.reverse_chars[top + 5][left + 1], + "Number popup must allow selecting the ASCII row.")) return 1; + + if (expect(mon.poll(0) == 0, "ASCII Number popup test: first character failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: second character failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $0000 WORD") == line, + "Two ASCII characters must switch the Number popup into WORD mode.")) return 1; + get_popup_line(screen, 4, line, sizeof(line)); + if (expect(strstr(line, "ASCII AB") == line, + "ASCII Number popup preview must show both typed characters without extra annotations.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: Enter commit failed.")) return 1; + if (expect(backend.read(0x0000) == 0x42 && backend.read(0x0001) == 0x41, + "ASCII WORD commit must write low/high bytes in little-endian order.")) return 1; + + if (expect(mon.poll(0) == 0, "ASCII Number popup test: close after commit failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: move to next address failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: reopen failed.")) return 1; + get_popup_line(screen, 0, line, sizeof(line)); + if (expect(strstr(line, "MONITOR NUM $0001 BYTE") == line, + "Reopening the Number popup must use the current address and a fresh BYTE preview.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Number popup reopen test must keep the popup framed.")) return 1; + if (expect(screen.reverse_chars[top + 5][left + 1], + "The Number popup must remember the selected row across close and reopen in one monitor session.")) return 1; + + if (expect(mon.poll(0) == 0, "ASCII Number popup test: repeated-entry character failed.")) return 1; + if (expect(mon.poll(0) == 0, "ASCII Number popup test: repeated-entry Enter failed.")) return 1; + if (expect(backend.read(0x0001) == 0x43 && backend.read(0x0002) == 0x00, + "Reopened Number popup must start with a fresh ASCII edit buffer at the new address.")) return 1; + + if (expect(mon.poll(0) == 0, "ASCII Number popup test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "ASCII Number popup test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'N', KEY_DOWN, KEY_DOWN, KEY_DOWN, KEY_DOWN, 'A', 'B', KEY_RETURN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "Screen Number popup test: open failed.")) return 1; + for (int i = 0; i < 4; i++) { + if (expect(mon.poll(0) == 0, "Screen Number popup test: row navigation failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "Screen Number popup test: first character failed.")) return 1; + if (expect(mon.poll(0) == 0, "Screen Number popup test: second character failed.")) return 1; + get_popup_line(screen, 5, line, sizeof(line)); + if (expect(strstr(line, "Screen AB") == line, + "Screen Number popup preview must show screen characters without redundant hex suffixes.")) return 1; + if (expect(strchr(line, '(') == NULL, + "Screen Number popup must not append per-byte hex annotations.")) return 1; + if (expect(mon.poll(0) == 0, "Screen Number popup test: Enter commit failed.")) return 1; + if (expect(backend.read(0x0000) == 0x02 && backend.read(0x0001) == 0x01, + "Screen WORD commit must use screen-code values written in little-endian order.")) return 1; + + if (expect(mon.poll(0) == 0, "Screen Number popup test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "Screen Number popup test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char line[32]; + const int keys[] = { 'V', 'U', 'N', KEY_DOWN, KEY_DOWN, KEY_DOWN, KEY_DOWN, 'A', KEY_RETURN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "L/U Screen Number popup test: Screen view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "L/U Screen Number popup test: charset toggle failed.")) return 1; + if (expect(mon.poll(0) == 0, "L/U Screen Number popup test: popup open failed.")) return 1; + for (int i = 0; i < 4; i++) { + if (expect(mon.poll(0) == 0, "L/U Screen Number popup test: row navigation failed.")) return 1; + } + if (expect(mon.poll(0) == 0, "L/U Screen Number popup test: character entry failed.")) return 1; + get_popup_line(screen, 5, line, sizeof(line)); + if (expect(strstr(line, "Screen A") == line, + "Screen Number popup preview must use the active Screen charset display.")) return 1; + if (expect(mon.poll(0) == 0, "L/U Screen Number popup test: commit failed.")) return 1; + if (expect(backend.read(0x0000) == 0x41, + "Screen Number popup input must use the active Screen charset input mapping.")) return 1; + if (expect(mon.poll(0) == 0, "L/U Screen Number popup test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "L/U Screen Number popup test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_number_popup_placement_and_overlay_redraw(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int cursor_x = 0; + int cursor_y = 0; + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + const int keys[] = { 'N', '1', KEY_DOWN, KEY_DELETE, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(find_highlighted_cell(screen, &cursor_x, &cursor_y), + "Placement test: initial cursor highlight not found.")) return 1; + if (expect(mon.poll(0) == 0, "Placement test: open failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Placement test: framed popup not found.")) return 1; + if (expect(left == cursor_x + 1 && top == cursor_y + 1, + "Top-left Number popup must be diagonally down-right from the invoking cursor when space allows.")) return 1; + if (expect(!(cursor_x >= left && cursor_x <= right && cursor_y >= top && cursor_y <= bottom), + "Number popup must not cover the invoking cursor cell.")) return 1; + if (expect(screen.reverse_chars[cursor_y][cursor_x], + "The invoking cursor cell must remain visible after opening the Number popup.")) return 1; + + screen.reset_write_counts(); + if (expect(mon.poll(0) == 0, "Placement test: typing should keep popup open.")) return 1; + if (expect(screen.count_writes_outside_rect(left, top, right, bottom) == 0, + "Typing inside the Number popup must not redraw uncovered monitor cells.")) return 1; + screen.reset_write_counts(); + if (expect(mon.poll(0) == 0, "Placement test: row navigation should keep popup open.")) return 1; + if (expect(screen.count_writes_outside_rect(left, top, right, bottom) == 0, + "Popup row navigation must not redraw uncovered monitor cells.")) return 1; + screen.reset_write_counts(); + if (expect(mon.poll(0) == 0, "Placement test: delete should keep popup open.")) return 1; + if (expect(screen.count_writes_outside_rect(left, top, right, bottom) == 0, + "Deleting inside the Number popup must not redraw uncovered monitor cells.")) return 1; + + if (expect(mon.poll(0) == 0, "Placement test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "Placement test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int cursor_x = 0; + int cursor_y = 0; + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + int keys[32]; + int n = 0; + keys[n++] = 'I'; + for (int i = 0; i < 22; i++) keys[n++] = KEY_RIGHT; + keys[n++] = 'N'; + keys[n++] = KEY_BREAK; + keys[n++] = KEY_BREAK; + FakeKeyboard kb(keys, n); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Top-right placement test: ASCII view switch failed.")) return 1; + for (int i = 0; i < 22; i++) { + if (expect(mon.poll(0) == 0, "Top-right placement test: cursor movement failed.")) return 1; + } + if (expect(find_highlighted_cell(screen, &cursor_x, &cursor_y), + "Top-right placement test: cursor highlight not found.")) return 1; + if (expect(mon.poll(0) == 0, "Top-right placement test: open failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Top-right placement test: framed popup not found.")) return 1; + if (expect(top == cursor_y + 1, + "Top-right Number popup must stay below the invoking cursor when space allows.")) return 1; + if (expect(!(cursor_x >= left && cursor_x <= right && cursor_y >= top && cursor_y <= bottom), + "Top-right Number popup must not cover the invoking cursor cell.")) return 1; + if (expect(mon.poll(0) == 0, "Top-right placement test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "Top-right placement test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int cursor_x = 0; + int cursor_y = 0; + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + int keys[32]; + int n = 0; + for (int i = 0; i < 17; i++) keys[n++] = KEY_DOWN; + keys[n++] = 'N'; + keys[n++] = KEY_BREAK; + keys[n++] = KEY_BREAK; + FakeKeyboard kb(keys, n); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int i = 0; i < 17; i++) { + if (expect(mon.poll(0) == 0, "Bottom-left placement test: cursor movement failed.")) return 1; + } + if (expect(find_highlighted_cell(screen, &cursor_x, &cursor_y), + "Bottom-left placement test: cursor highlight not found.")) return 1; + if (expect(mon.poll(0) == 0, "Bottom-left placement test: open failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bottom-left placement test: framed popup not found.")) return 1; + if (expect(left == cursor_x + 1 && bottom == cursor_y - 1, + "Bottom-left Number popup must be diagonally up-right from the invoking cursor when space allows.")) return 1; + if (expect(mon.poll(0) == 0, "Bottom-left placement test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "Bottom-left placement test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int cursor_x = 0; + int cursor_y = 0; + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + int keys[64]; + int n = 0; + keys[n++] = 'I'; + for (int i = 0; i < 17; i++) keys[n++] = KEY_DOWN; + for (int i = 0; i < 22; i++) keys[n++] = KEY_RIGHT; + keys[n++] = 'N'; + keys[n++] = KEY_BREAK; + keys[n++] = KEY_BREAK; + FakeKeyboard kb(keys, n); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Bottom-right placement test: ASCII view switch failed.")) return 1; + for (int i = 0; i < 39; i++) { + if (expect(mon.poll(0) == 0, "Bottom-right placement test: cursor movement failed.")) return 1; + } + if (expect(find_highlighted_cell(screen, &cursor_x, &cursor_y), + "Bottom-right placement test: cursor highlight not found.")) return 1; + if (expect(mon.poll(0) == 0, "Bottom-right placement test: open failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Bottom-right placement test: framed popup not found.")) return 1; + if (expect(bottom == cursor_y - 1, + "Bottom-right Number popup must stay above the invoking cursor when space allows.")) return 1; + if (expect(!(cursor_x >= left && cursor_x <= right && cursor_y >= top && cursor_y <= bottom), + "Bottom-right Number popup must not cover the invoking cursor cell.")) return 1; + if (expect(mon.poll(0) == 0, "Bottom-right placement test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "Bottom-right placement test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int cursor_x = 0; + int cursor_y = 0; + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + int keys[40]; + int n = 0; + keys[n++] = 'I'; + for (int i = 0; i < 8; i++) keys[n++] = KEY_DOWN; + for (int i = 0; i < 22; i++) keys[n++] = KEY_RIGHT; + keys[n++] = 'N'; + keys[n++] = KEY_BREAK; + keys[n++] = KEY_BREAK; + FakeKeyboard kb(keys, n); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Center placement test: ASCII view switch failed.")) return 1; + for (int i = 0; i < 30; i++) { + if (expect(mon.poll(0) == 0, "Center placement test: cursor movement failed.")) return 1; + } + if (expect(find_highlighted_cell(screen, &cursor_x, &cursor_y), + "Center placement test: cursor highlight not found.")) return 1; + if (expect(mon.poll(0) == 0, "Center placement test: open failed.")) return 1; + if (expect(find_popup_rect(screen, &left, &top, &right, &bottom), + "Center placement test: framed popup not found.")) return 1; + if (expect(!(cursor_x >= left && cursor_x <= right && cursor_y >= top && cursor_y <= bottom), + "Mid-row Number popup placement must keep the invoking cursor visible.")) return 1; + if (expect(left > 0 && top > 2 && right < 39 && bottom < 22, + "Mid-row Number popup placement must stay inside the monitor content bounds.")) return 1; + if (expect(mon.poll(0) == 0, "Center placement test: popup close failed.")) return 1; + if (expect(mon.poll(0) == 1, "Center placement test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_disassembly_up_keeps_screen_row(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int row_before = -1; + int row_after = -1; + const int keys[] = { 'A', 'J', KEY_DOWN, KEY_DOWN, KEY_UP, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + backend.write(0x0000, 0x4C); + backend.write(0x0001, 0x00); + backend.write(0x0002, 0xEA); + backend.write(0x0003, 0xEA); + backend.write(0x0004, 0xEA); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0001", 1); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "Disassembly row test: ASM view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "Disassembly row test: goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Disassembly row test: first step down failed.")) return 1; + if (expect(mon.poll(0) == 0, "Disassembly row test: second step down failed.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_before), + "Disassembly row test: highlighted current line not found before stepping up.")) return 1; + if (expect(row_before > 4, + "Disassembly row test must place the cursor away from the top row before stepping up.")) return 1; + if (expect(mon.poll(0) == 0, "Disassembly row test: step up failed.")) return 1; + if (expect(find_highlighted_cell(screen, NULL, &row_after), + "Disassembly row test: highlighted current line not found after stepping up.")) return 1; + if (expect(row_after == row_before - 1, + "Stepping upward in Assembly view must move the highlighted line up by one row without snapping it to the top.")) return 1; + if (expect(mon.poll(0) == 1, "Disassembly row test: exit failed.")) return 1; + mon.deinit(); + return 0; +} + +static int test_fixed_prompt_widths(void) +{ + struct PromptCase { + int key; + const char *message; + int maxlen; + } cases[] = { + { 'F', "Fill AAAA-BBBB,DD", 13 }, + { 'T', "Transfer AAAA-BBBB,CCCC[,DDDD-EEEE]", 25 }, + { 'C', "Compare AAAA-BBBB,CCCC", 15 }, + }; + + for (unsigned int i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + int keys[] = { cases[i].key, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("", 0); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Fixed prompt width test: command key failed.")) return 1; + if (expect(strcmp(ui.last_prompt_message, cases[i].message) == 0, + "Fixed prompt width test: monitor used the wrong prompt template.")) return 1; + if (expect(ui.last_prompt_maxlen == cases[i].maxlen, + "Fixed prompt width test: prompt width did not match the expected bounded template length.")) return 1; + if (expect(mon.poll(0) == 1, "Fixed prompt width test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_prompt_cancel_and_empty_clipboard(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'F', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("", 0); + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Prompt cancel test: fill command should stay in the monitor.")) return 1; + if (expect(backend.read(0x0000) == 0x00 && ui.popup_count == 0, + "Canceled prompt must not mutate memory or raise an error popup.")) return 1; + if (expect(mon.poll(0) == 1, "Prompt cancel test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { KEY_CTRL_V, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Empty clipboard test: paste should not exit.")) return 1; + if (expect(ui.popup_count == 1 && strcmp(ui.last_popup, "?CLIP") == 0, + "Pasting with an empty clipboard must raise ?CLIP.")) return 1; + if (expect(mon.poll(0) == 1, "Empty clipboard test: exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_load_save_and_goto_command_flow(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'L', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("PRG,0001,2", 1); + monitor_reset_saved_state(); + monitor_io::reset_fake_monitor_io(); + monitor_io::g_monitor_io.pick_file_result = true; + strcpy(monitor_io::g_monitor_io.pick_path, "/tmp"); + strcpy(monitor_io::g_monitor_io.pick_name, "demo.prg"); + monitor_io::g_monitor_io.load_data[0] = 0x01; + monitor_io::g_monitor_io.load_data[1] = 0x08; + monitor_io::g_monitor_io.load_data[2] = 0xAA; + monitor_io::g_monitor_io.load_data[3] = 0xBB; + monitor_io::g_monitor_io.load_data[4] = 0xCC; + monitor_io::g_monitor_io.load_size = 5; + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "LOAD command flow test failed.")) return 1; + if (expect(monitor_io::g_monitor_io.load_called && monitor_io::g_monitor_io.pick_file_calls == 1 && + strcmp(monitor_io::g_monitor_io.load_path, "/tmp") == 0 && + strcmp(monitor_io::g_monitor_io.load_name, "demo.prg") == 0, + "LOAD command must invoke the monitor I/O shim with the picked file.")) return 1; + if (expect(backend.read(0x0801) == 0xBB && backend.read(0x0802) == 0xCC, + "LOAD command must honour PRG header, file offset, and length.")) return 1; + if (expect(ui.popup_count == 1 && strcmp(ui.last_popup, "LOAD demo.prg\n$0801-$0802 (2 bytes)") == 0, + "LOAD command must show a two-line confirmation popup with the effective byte range.")) return 1; + if (expect(mon.poll(0) == 1, "LOAD command flow test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'S', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + backend.write(0x0801, 0xA9); + backend.write(0x0802, 0x42); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0801-0802", 1); + monitor_reset_saved_state(); + monitor_io::reset_fake_monitor_io(); + monitor_io::g_monitor_io.pick_file_result = true; + strcpy(monitor_io::g_monitor_io.pick_path, "/tmp"); + strcpy(monitor_io::g_monitor_io.pick_name, "save.prg"); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "SAVE command flow test failed.")) return 1; + if (expect(monitor_io::g_monitor_io.save_called && monitor_io::g_monitor_io.last_pick_save_mode, + "SAVE command must invoke the monitor save shim in save-pick mode.")) return 1; + if (expect(monitor_io::g_monitor_io.saved_size == 4 && + monitor_io::g_monitor_io.saved_data[0] == 0x01 && + monitor_io::g_monitor_io.saved_data[1] == 0x08 && + monitor_io::g_monitor_io.saved_data[2] == 0xA9 && + monitor_io::g_monitor_io.saved_data[3] == 0x42, + "SAVE command must emit a PRG header followed by the selected bytes.")) return 1; + if (expect(ui.popup_count == 1 && strcmp(ui.last_popup, "SAVE save.prg\n$0801-$0802 (2 bytes)") == 0, + "SAVE command must show a two-line confirmation popup with the saved range.")) return 1; + if (expect(mon.poll(0) == 1, "SAVE command flow test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'S', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + backend.write(0x0801, 0xA9); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("0801-0801", 1); + monitor_reset_saved_state(); + monitor_io::reset_fake_monitor_io(); + monitor_io::g_monitor_io.pick_file_result = true; + strcpy(monitor_io::g_monitor_io.pick_path, "/tmp"); + strcpy(monitor_io::g_monitor_io.pick_name, "THIS-IS-A-VERY-LONG-FILENAME-FOR-CONFIRMATION-TESTING.PRG"); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Long confirmation filename test failed.")) return 1; + if (expect(ui.popup_count == 1, + "Long confirmation filename test must produce one confirmation popup.")) return 1; + if (expect(popup_longest_line(ui.last_popup) <= 38, + "Every line in the LOAD/SAVE confirmation popup must stay within 38 characters.")) return 1; + if (expect(strstr(ui.last_popup, "SAVE ") == ui.last_popup, + "Long confirmation filename test must still label the operation on the first line.")) return 1; + if (expect(strstr(ui.last_popup, "\n$0801-$0801 (1 bytes)") != NULL, + "Long confirmation filename test must keep the effective range on the second line.")) return 1; + if (expect(mon.poll(0) == 1, "Long confirmation filename test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'G' }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C123", 1); + monitor_reset_saved_state(); + monitor_io::reset_fake_monitor_io(); + + BackendMachineMonitor monitor(&ui, &backend); + ui.run_machine_monitor(&backend); + if (expect(monitor_io::g_monitor_io.jump_called && monitor_io::g_monitor_io.jump_address == 0xC123, + "Go command must dispatch the requested jump address.")) return 1; + } + + return 0; +} + +static int test_hex_single_nibble_commits_on_navigation(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'E', 'E', KEY_RIGHT, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + backend.write(0x0000, 0xFF); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Hex nibble cursor-right test: enter edit mode failed.")) return 1; + if (expect(mon.poll(0) == 0, "Hex nibble cursor-right test: typing nibble failed.")) return 1; + if (expect(mon.poll(0) == 0, "Hex nibble cursor-right test: moving right failed.")) return 1; + if (expect(backend.read(0x0000) == 0x0E, + "Leaving a half-typed hex nibble with cursor-right must commit it as 0x0N.")) return 1; + if (expect(mon.poll(0) == 0, "Hex nibble cursor-right test: edit-mode exit failed.")) return 1; + if (expect(mon.poll(0) == 1, "Hex nibble cursor-right test: monitor exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'E', 'E', KEY_PAGEDOWN, KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + backend.write(0x0000, 0xFF); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Hex nibble page-move test: enter edit mode failed.")) return 1; + if (expect(mon.poll(0) == 0, "Hex nibble page-move test: typing nibble failed.")) return 1; + if (expect(mon.poll(0) == 0, "Hex nibble page-move test: page down failed.")) return 1; + if (expect(backend.read(0x0000) == 0x0E, + "Leaving a half-typed hex nibble with page movement must commit it as 0x0N.")) return 1; + if (expect(mon.poll(0) == 0, "Hex nibble page-move test: edit-mode exit failed.")) return 1; + if (expect(mon.poll(0) == 1, "Hex nibble page-move test: monitor exit failed.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_header_invariants_and_parity(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char header[39]; + const int keys[] = { 'E', 'R', 'Z', KEY_BREAK, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Header test: edit mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Header test: range mode entry failed.")) return 1; + if (expect(mon.poll(0) == 0, "Header test: freeze toggle failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Edit Mode") == NULL, + "Header must show Edit, not Edit Mode.")) return 1; + // Per the Debug-mode spec, the Edit indicator is always written as + // mixed-case `Edit` so it can compose with `Dbg` cleanly. + if (expect(strncmp(header + 34, "Edit", 4) == 0, + "Edit indicator must be fixed at top-right.")) return 1; + if (expect(screen.colors[3][35] == 1 && screen.colors[3][36] == 1 && + screen.colors[3][37] == 1 && screen.colors[3][38] == 1, + "Edit must use the shared UI accent colour used for the help/title text.")) return 1; + if (expect(strncmp(header + 18, "Range", 5) == 0, + "Range indicator must use its fixed slot.")) return 1; + if (expect(strncmp(header + 23, "Frz", 3) == 0, + "Freeze indicator must use its compact fixed slot.")) return 1; + if (expect(strstr(header, "W=") == NULL, + "Header must not display binary width.")) return 1; + if (expect(mon.poll(0) == 0, "Header test: RUN/STOP should leave edit mode first.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "Edit") == NULL, + "Leaving edit mode must clear the far-right Edit indicator area.")) return 1; + if (expect(mon.poll(0) == 1, "Header test: exit failed.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui_a; + TestUserInterface ui_b; + CaptureScreen screen_a; + CaptureScreen screen_b; + FakeMemoryBackend backend_a; + FakeMemoryBackend backend_b; + const int keys_a[] = { 'B', KEY_RIGHT, KEY_RIGHT, 'E', '1' }; + const int keys_b[] = { 'B', KEY_RIGHT, KEY_RIGHT, 'E', '1' }; + FakeKeyboard kb_a(keys_a, sizeof(keys_a) / sizeof(keys_a[0])); + FakeKeyboard kb_b(keys_b, sizeof(keys_b) / sizeof(keys_b[0])); + for (int i = 0; i < 16; i++) { + backend_a.write((uint16_t)i, (uint8_t)(0x10 + i)); + backend_b.write((uint16_t)i, (uint8_t)(0x10 + i)); + } + + ui_a.screen = &screen_a; + ui_a.keyboard = &kb_a; + ui_b.screen = &screen_b; + ui_b.keyboard = &kb_b; + monitor_reset_saved_state(); + BackendMachineMonitor mon_a(&ui_a, &backend_a); + mon_a.init(&screen_a, &kb_a); + for (int i = 0; i < (int)(sizeof(keys_a) / sizeof(keys_a[0])); i++) { + if (expect(mon_a.poll(0) == 0, "Parity render A command failed.")) return 1; + } + + monitor_reset_saved_state(); + BackendMachineMonitor mon_b(&ui_b, &backend_b); + mon_b.init(&screen_b, &kb_b); + for (int i = 0; i < (int)(sizeof(keys_b) / sizeof(keys_b[0])); i++) { + if (expect(mon_b.poll(0) == 0, "Parity render B command failed.")) return 1; + } + if (expect_screens_equal(screen_a, screen_b, + "Two monitor frontends using the shared renderer must produce byte-identical screens.")) return 1; + mon_a.deinit(); + mon_b.deinit(); + } + + return 0; +} + +static int test_poll_mode_refreshes_visible_ram(void) +{ + struct FakeNtscMemoryBackend : public FakeMemoryBackend { + virtual uint8_t monitor_poll_hz(void) const { return 60; } + }; + + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + char line[9]; + const int keys[] = { 'P' }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + set_fake_ms_timer(0); + backend.write(0x0000, 0x11); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Poll mode test: P toggle failed.")) return 1; + + screen.get_slice(1, 3, 38, header); + if (expect(strncmp(header + 27, "Pl", 2) == 0, + "Poll indicator must appear in the top-right flag area.")) return 1; + + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "0000 11", 7) == 0, + "Poll mode test setup must render the original byte.")) return 1; + + backend.write(0x0000, 0x22); + set_fake_ms_timer(19); + if (expect(mon.poll(0) == 0, "Poll mode test: early idle poll failed.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "0000 11", 7) == 0, + "Poll mode must not refresh before the PAL frame interval elapses.")) return 1; + + advance_fake_ms_timer(1); + if (expect(mon.poll(0) == 0, "Poll mode test: timed idle poll failed.")) return 1; + screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "0000 22", 7) == 0, + "Poll mode must refresh the displayed RAM at PAL frame rate.")) return 1; + + mon.deinit(); + + { + TestUserInterface ntsc_ui; + CaptureScreen ntsc_screen; + FakeNtscMemoryBackend ntsc_backend; + const int ntsc_keys[] = { 'P' }; + FakeKeyboard ntsc_kb(ntsc_keys, sizeof(ntsc_keys) / sizeof(ntsc_keys[0])); + + ntsc_ui.screen = &ntsc_screen; + ntsc_ui.keyboard = &ntsc_kb; + monitor_reset_saved_state(); + set_fake_ms_timer(0); + ntsc_backend.write(0x0000, 0x11); + + BackendMachineMonitor ntsc_mon(&ntsc_ui, &ntsc_backend); + ntsc_mon.init(&ntsc_screen, &ntsc_kb); + if (expect(ntsc_mon.poll(0) == 0, "NTSC poll mode test: P toggle failed.")) return 1; + + ntsc_backend.write(0x0000, 0x22); + set_fake_ms_timer(15); + if (expect(ntsc_mon.poll(0) == 0, "NTSC poll mode test: early first poll failed.")) return 1; + ntsc_screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "0000 11", 7) == 0, + "NTSC poll mode must not refresh before the first 16 ms frame slice.")) return 1; + + advance_fake_ms_timer(1); + if (expect(ntsc_mon.poll(0) == 0, "NTSC poll mode test: first frame poll failed.")) return 1; + ntsc_screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "0000 22", 7) == 0, + "NTSC poll mode must refresh on the first 16 ms frame slice.")) return 1; + + ntsc_backend.write(0x0000, 0x33); + set_fake_ms_timer(32); + if (expect(ntsc_mon.poll(0) == 0, "NTSC poll mode test: early second poll failed.")) return 1; + ntsc_screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "0000 22", 7) == 0, + "NTSC poll mode must carry the 60 Hz fractional frame interval.")) return 1; + + advance_fake_ms_timer(1); + if (expect(ntsc_mon.poll(0) == 0, "NTSC poll mode test: second frame poll failed.")) return 1; + ntsc_screen.get_slice(1, 4, 8, line); + if (expect(strncmp(line, "0000 33", 7) == 0, + "NTSC poll mode must average to 60 Hz with 16/17 ms frame slices.")) return 1; + ntsc_mon.deinit(); + } + return 0; +} + +static int test_edit_indicator_layout_across_views(void) +{ + static const int hex_keys[] = { 'E' }; + static const int asm_keys[] = { 'A', 'E' }; + static const int asc_keys[] = { 'I', 'E' }; + static const int scr_keys[] = { 'S', 'E' }; + static const int bin_keys[] = { 'B', 'E' }; + struct ViewCase { + const int *keys; + int key_count; + } cases[] = { + { hex_keys, 1 }, + { asm_keys, 2 }, + { asc_keys, 2 }, + { scr_keys, 2 }, + { bin_keys, 2 }, + }; + + for (unsigned int i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + FakeKeyboard kb(cases[i].keys, cases[i].key_count); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int step = 0; step < cases[i].key_count; step++) { + if (expect(mon.poll(0) == 0, "Edit indicator cross-view test: command sequence failed.")) return 1; + } + screen.get_slice(1, 3, 38, header); + if (expect(strncmp(header + 34, "Edit", 4) == 0, + "Edit must remain far-right aligned in every edit-capable view.")) return 1; + if (expect(screen.colors[3][35] == 1 && screen.colors[3][36] == 1 && + screen.colors[3][37] == 1 && screen.colors[3][38] == 1, + "Edit must keep the shared UI accent colour in every edit-capable view.")) return 1; + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeBankedMemoryBackend backend; + char header[39]; + const int keys[] = { 'A', 'U', 'Z', 'P', 'E' }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + for (int step = 0; step < (int)(sizeof(keys) / sizeof(keys[0])); step++) { + if (expect(mon.poll(0) == 0, "Edit indicator layout test: ASM/freeze sequence failed.")) return 1; + } + screen.get_slice(1, 3, 38, header); + if (expect(strncmp(header + 18, "Undc", 4) == 0, + "Undc must remain visible to the left of Frz, Pl, and Edit.")) return 1; + if (expect(strncmp(header + 23, "Frz", 3) == 0, + "Frz must remain visible to the left of Pl and Edit.")) return 1; + if (expect(strncmp(header + 27, "Pl", 2) == 0, + "Pl must appear immediately to the left of Dbg/Edit.")) return 1; + if (expect(strncmp(header + 34, "Edit", 4) == 0, + "Edit must remain fixed at the far right when Undc, Frz, and Pl are active.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_poll_mode_disabled_on_full_refresh_screen(void) +{ + struct FullRefreshCaptureScreen : public CaptureScreen { + virtual bool prefers_full_refresh(void) { return true; } + }; + + TestUserInterface ui; + FullRefreshCaptureScreen screen; + FakeMemoryBackend backend; + char header[39]; + const int keys[] = { 'P', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Telnet poll-mode guard: P command failed.")) return 1; + if (expect(ui.popup_count == 1, + "Poll mode on full-refresh screens must raise one warning popup.")) return 1; + if (expect(strstr(ui.last_popup, "TELNET") != NULL, + "Poll mode warning must mention the telnet restriction.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strncmp(header + 27, "Pl", 2) != 0, + "Poll indicator must stay disabled on full-refresh screens.")) return 1; + if (expect(mon.poll(0) == 1, "Telnet poll-mode guard: exit failed.")) return 1; + mon.deinit(); + return 0; +} + + +static int test_load_save_param_parsers(void) +{ + bool use_prg = false; + uint16_t start = 0, off16 = 0, end = 0; + bool len_auto = false; + uint32_t length = 0; + uint32_t effective = 0; + + // LOAD: standard "RETURN, RETURN" path: PRG keyword + AUTO length. + if (expect(monitor_parse_load_params("PRG,0000,AUTO", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser failed for PRG,0000,AUTO.")) return 1; + if (expect(use_prg && off16 == 0 && len_auto, "LOAD PRG defaults parsed wrong.")) return 1; + + // LOAD: explicit start address & explicit length. + if (expect(monitor_parse_load_params("0801,0002,1FFE", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser failed for explicit form.")) return 1; + if (expect(!use_prg && start == 0x0801 && off16 == 0x0002 && !len_auto && length == 0x1FFE, + "LOAD explicit parser values wrong.")) return 1; + + // LOAD: 5-digit length up to 0x10000 inclusive is permitted. + if (expect(monitor_parse_load_params("C000,0000,10000", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser must accept 64K length.")) return 1; + if (expect(length == 0x10000, "LOAD 64K length parsed wrong.")) return 1; + + // LOAD: zero length must be rejected. + if (expect(monitor_parse_load_params("0801,0000,0", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_VALUE, + "LOAD parser must reject zero length.")) return 1; + + // LOAD: garbage in fields must be rejected. + if (expect(monitor_parse_load_params("XYZ,00,AUTO", &use_prg, &start, &off16, &len_auto, &length) != MONITOR_OK, + "LOAD parser must reject garbage.")) return 1; + + // LOAD: empty input -> all defaults (PRG, offset 0, AUTO length). + use_prg = false; start = 0xDEAD; off16 = 0xDEAD; len_auto = false; length = 0xDEADBEEF; + if (expect(monitor_parse_load_params("", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser must accept empty input.")) return 1; + if (expect(use_prg && off16 == 0 && len_auto, "LOAD empty defaults wrong.")) return 1; + + // LOAD: PRG only -> defaults for offset and length. + if (expect(monitor_parse_load_params("PRG", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser must accept 'PRG' alone.")) return 1; + if (expect(use_prg && off16 == 0 && len_auto, "LOAD PRG-only defaults wrong.")) return 1; + + // LOAD: address only -> offset 0, length AUTO. + if (expect(monitor_parse_load_params("0801", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser must accept address alone.")) return 1; + if (expect(!use_prg && start == 0x0801 && off16 == 0 && len_auto, "LOAD addr-only defaults wrong.")) return 1; + + // LOAD: address + offset, length defaults to AUTO. + if (expect(monitor_parse_load_params("0801,1000", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser must accept addr,off form.")) return 1; + if (expect(!use_prg && start == 0x0801 && off16 == 0x1000 && len_auto, "LOAD addr,off defaults wrong.")) return 1; + + // LOAD: empty fields between commas -> defaults take over. + if (expect(monitor_parse_load_params(",,0010", &use_prg, &start, &off16, &len_auto, &length) == MONITOR_OK, + "LOAD parser must accept ,,len form.")) return 1; + if (expect(use_prg && off16 == 0 && !len_auto && length == 0x10, "LOAD ,,len defaults wrong.")) return 1; + + // SAVE: canonical form. + if (expect(monitor_parse_save_params("0800-9FFF", &start, &end) == MONITOR_OK, + "SAVE parser failed for 0800-9FFF.")) return 1; + if (expect(start == 0x0800 && end == 0x9FFF, "SAVE parser values wrong.")) return 1; + + // SAVE: inverted range must be rejected. + if (expect(monitor_parse_save_params("9FFF-0800", &start, &end) == MONITOR_RANGE, + "SAVE parser must reject inverted range.")) return 1; + + // Validate load size: AUTO, file fits. + if (expect(monitor_validate_load_size(100, 0, true, 0, &effective) == MONITOR_OK && effective == 100, + "Validate AUTO small file failed.")) return 1; + + // Validate load size: AUTO, >64K. + if (expect(monitor_validate_load_size(0x20000, 0, true, 0, &effective) == MONITOR_RANGE, + "Validate must reject AUTO over 64K.")) return 1; + + // Validate load size: AUTO, partial window keeps within 64K. + if (expect(monitor_validate_load_size(0x20000, 0x10000, true, 0, &effective) == MONITOR_OK && effective == 0x10000, + "Validate AUTO partial window failed.")) return 1; + + // Validate load size: explicit length over 64K rejected. + if (expect(monitor_validate_load_size(0x30000, 0, false, 0x10001, &effective) == MONITOR_RANGE, + "Validate must reject explicit length over 64K.")) return 1; + + // Validate load size: offset past end rejected. + if (expect(monitor_validate_load_size(100, 100, true, 0, &effective) == MONITOR_RANGE, + "Validate must reject offset==filesize.")) return 1; + + // Validate load size: requested length larger than what's left in the file. + if (expect(monitor_validate_load_size(100, 50, false, 100, &effective) == MONITOR_RANGE, + "Validate must reject length beyond EOF.")) return 1; + + return 0; +} + +extern int g_set_screen_title_call_count; + +// Regression: pressing 'W' in fixed-width views, 'Z' when freeze is unavailable, +// and 'U' outside ASM view must show a bounded warning popup, but the +// post-popup redraw must NOT call UserInterface::set_screen_title(). That +// helper repaints the screen chrome (including a horizontal-line glyph row +// just below the monitor) and would clobber the application info row, +// producing the reported "row of horizontal lines" symptom. +static int test_warning_popups_preserve_status_row(void) +{ + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'I', 'W', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.popup_count = 0; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + g_set_screen_title_call_count = 0; + if (expect(mon.poll(0) == 0, "ASCII view switch before W warning test failed.")) return 1; + if (expect(mon.poll(0) == 0, "W in ASCII view should not exit the monitor.")) return 1; + if (expect(ui.popup_count == 1, "W outside Memory/Binary view must raise exactly one warning popup.")) return 1; + if (expect(strstr(ui.last_popup, "MEMORY") != NULL && strstr(ui.last_popup, "BINARY") != NULL, + "W warning must mention the MEMORY/BINARY view requirement.")) return 1; + if (expect(g_set_screen_title_call_count == 0, + "W warning popup must not trigger set_screen_title (would erase the row below the monitor with horizontal lines).")) return 1; + mon.poll(0); + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeFreezeControlBackend backend(false); + const int keys[] = { 'Z', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.popup_count = 0; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + g_set_screen_title_call_count = 0; + if (expect(mon.poll(0) == 0, "Z outside overlay mode should not exit.")) return 1; + if (expect(ui.popup_count == 1, "Z outside overlay mode must raise exactly one warning popup.")) return 1; + if (expect(strstr(ui.last_popup, "FREEZE") != NULL && strstr(ui.last_popup, "OVERLAY") != NULL, + "Z warning must explain that freeze is only available in overlay mode.")) return 1; + if (expect(backend.set_frozen_calls == 0 && !backend.frozen, + "Invalid-context Z must not change freeze state or call set_frozen.")) return 1; + if (expect(g_set_screen_title_call_count == 0, + "Z warning popup must not trigger set_screen_title.")) return 1; + mon.poll(0); + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeFreezeControlBackend backend(true); + const int keys[] = { 'Z', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.popup_count = 0; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Z in overlay mode should not exit.")) return 1; + if (expect(ui.popup_count == 0, "Z in overlay mode must not raise a warning popup.")) return 1; + if (expect(backend.set_frozen_calls == 1 && backend.frozen, + "Z in overlay mode must still perform the freeze toggle.")) return 1; + mon.poll(0); + mon.deinit(); + } + + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'U', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.popup_count = 0; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + g_set_screen_title_call_count = 0; + if (expect(mon.poll(0) == 0, "U outside ASM view should not exit.")) return 1; + if (expect(ui.popup_count == 1, "U outside ASM view must raise exactly one warning popup.")) return 1; + if (expect(strcmp(ui.last_popup, "UNDOC IN ASM, CASE IN SCR") == 0, + "U warning must explain the Assembly undocumented-op toggle and the Screen case toggle.")) return 1; + if (expect(g_set_screen_title_call_count == 0, + "U warning popup must not trigger set_screen_title.")) return 1; + mon.poll(0); + mon.deinit(); + } + + // Sanity: U in ASM view still toggles silently (no warning popup). + { + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + const int keys[] = { 'A', 'U', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.popup_count = 0; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "ASM view switch failed in U-in-ASM sanity test.")) return 1; + if (expect(mon.poll(0) == 0, "U in ASM view should toggle silently.")) return 1; + if (expect(ui.popup_count == 0, "U inside ASM view must not raise a warning popup.")) return 1; + mon.poll(0); + mon.deinit(); + } + + return 0; +} + +static int test_asm_follow_and_return_navigation(void) +{ + // Memory layout: + // $C000: JMP $C100 4C 00 C1 + // $C100: JSR $C204 20 04 C2 + // $C200: BNE $C204 D0 02 + // $C202: NOP EA + // $C204: RTS 60 + TestUserInterface ui; + CaptureScreen screen; + FakeMemoryBackend backend; + char header[40]; + char status[39]; + + backend.write(0xC000, 0x4C); backend.write(0xC001, 0x00); backend.write(0xC002, 0xC1); + backend.write(0xC100, 0x20); backend.write(0xC101, 0x04); backend.write(0xC102, 0xC2); + backend.write(0xC200, 0xD0); backend.write(0xC201, 0x02); + backend.write(0xC202, 0xEA); + backend.write(0xC204, 0x60); + + // Test 1: RETURN follows JMP. + { + const int keys[] = { 'J', 'A', KEY_RETURN }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C000", 1); + monitor_reset_saved_state(); + set_fake_ms_timer(0); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Follow JMP: J goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Follow JMP: A view switch failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C000") == header, + "Follow JMP: must start at $C000.")) return 1; + if (expect(mon.poll(0) == 0, "Follow JMP: RETURN follow failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C100") == header, + "Follow JMP: RETURN must follow JMP to $C100.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 JMP $C100") == status, + "Follow JMP: first follow must show F0 with the target address.")) return 1; + if (expect(strchr(status, ':') == NULL, + "Follow JMP: follow-stack status must not contain a colon.")) return 1; + set_fake_ms_timer(1999); + if (expect(mon.poll(0) == 0, "Follow JMP: status hold poll failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 JMP $C100") == status, + "Follow JMP: follow-stack status must stay visible before 2 seconds.")) return 1; + advance_fake_ms_timer(1); + if (expect(mon.poll(0) == 0, "Follow JMP: status expiry poll failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU") == status || strstr(status, "C0O7") == status, + "Follow JMP: follow-stack status must clear after its timeout.")) return 1; + mon.deinit(); + } + + // Test 2: RETURN follows JSR; RETURN at the non-followable target returns. + { + const int keys[] = { 'J', 'A', KEY_RETURN, KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C100", 1); + monitor_reset_saved_state(); + set_fake_ms_timer(0); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Follow JSR: J goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Follow JSR: A view switch failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C100") == header, + "Follow JSR: must start at $C100.")) return 1; + if (expect(mon.poll(0) == 0, "Follow JSR: RETURN follow failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C204") == header, + "Follow JSR: RETURN must follow JSR to $C204.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 JMP $C204") == status, + "Follow JSR: follow status must show F0 and the jumped-to target.")) return 1; + if (expect(mon.poll(0) == 0, "Follow JSR: RETURN back failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C100") == header, + "Follow JSR: RETURN at RTS must return to $C100.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 RET $C100") == status, + "Follow JSR: return status must show F0 and the restored address.")) return 1; + mon.deinit(); + } + + // Test 3: RETURN at a non-followable instruction (RTS) returns to origin. + { + const int keys[] = { 'J', 'A', KEY_RETURN, KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C200", 1); + monitor_reset_saved_state(); + set_fake_ms_timer(0); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Follow/Back: J goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Follow/Back: A view switch failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C200") == header, + "Follow/Back: must start at $C200.")) return 1; + if (expect(mon.poll(0) == 0, "Follow/Back: RETURN follow BNE failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C204") == header, + "Follow/Back: RETURN must follow BNE to $C204.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 JMP $C204") == status, + "Follow/Back: branch follow must use the follow-stack status format.")) return 1; + if (expect(mon.poll(0) == 0, "Follow/Back: RETURN back at RTS failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C200") == header, + "Follow/Back: RETURN must return to $C200 from non-followable RTS.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 RET $C200") == status, + "Follow/Back: return status must use the restored address.")) return 1; + mon.deinit(); + } + + // Test 4: RETURN at stack bottom on a non-followable line is a no-op. + { + const int keys[] = { 'J', 'A', KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C204", 1); + monitor_reset_saved_state(); + set_fake_ms_timer(0); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Empty stack: J goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Empty stack: A view switch failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C204") == header, + "Empty stack: must start at $C204.")) return 1; + if (expect(mon.poll(0) == 0, "Empty stack: RETURN at RTS failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C204") == header, + "Empty stack: RETURN at RTS with an empty stack must be a no-op.")) return 1; + if (expect(mon.poll(0) == 1, "Empty stack: exit failed.")) return 1; + mon.deinit(); + } + + // Test 5: RETURN outside ASM view does not consume the follow stack. + { + const int keys[] = { 'J', 'A', KEY_RETURN, 'M', KEY_RETURN, 'A', KEY_RETURN, KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C200", 1); + monitor_reset_saved_state(); + set_fake_ms_timer(0); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "HEX no-op: J goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "HEX no-op: A view switch failed.")) return 1; + if (expect(mon.poll(0) == 0, "HEX no-op: RETURN follow failed.")) return 1; + if (expect(mon.poll(0) == 0, "HEX no-op: switch to HEX failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX $C204") == header, + "HEX no-op: must switch to HEX at the followed target.")) return 1; + if (expect(mon.poll(0) == 0, "HEX no-op: RETURN in HEX failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR HEX") == header, + "HEX no-op: RETURN outside ASM must not change view.")) return 1; + if (expect(mon.poll(0) == 0, "HEX no-op: switch back to ASM failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C204") == header, + "HEX no-op: switching back to ASM must keep the followed target selected.")) return 1; + if (expect(mon.poll(0) == 0, "HEX no-op: RETURN back in ASM failed.")) return 1; + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $C200") == header, + "HEX no-op: RETURN in ASM must still return after the HEX no-op.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 RET $C200") == status, + "HEX no-op: returning back in ASM must still show follow-stack status.")) return 1; + mon.deinit(); + } + + // Test 6: the follow stack keeps only the newest 10 entries. + { + int keys[32]; + int n = 0; + + for (int i = 0; i < 11; i++) { + uint16_t src = (uint16_t)(0xD000 + i * 4); + uint16_t dst = (uint16_t)(src + 4); + backend.write(src, 0x4C); + backend.write((uint16_t)(src + 1), (uint8_t)(dst & 0xFF)); + backend.write((uint16_t)(src + 2), (uint8_t)(dst >> 8)); + backend.write((uint16_t)(src + 3), 0xEA); + } + backend.write(0xD02C, 0xEA); + + keys[n++] = 'J'; + keys[n++] = 'A'; + for (int i = 0; i < 11; i++) { + keys[n++] = KEY_RETURN; + } + keys[n++] = KEY_RETURN; + for (int i = 0; i < 9; i++) { + keys[n++] = KEY_DOWN; + keys[n++] = KEY_RETURN; + } + + FakeKeyboard kb(keys, n); + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("D000", 1); + monitor_reset_saved_state(); + set_fake_ms_timer(0); + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + if (expect(mon.poll(0) == 0, "Follow stack limit: J goto failed.")) return 1; + if (expect(mon.poll(0) == 0, "Follow stack limit: A view switch failed.")) return 1; + for (int i = 0; i < 11; i++) { + if (expect(mon.poll(0) == 0, "Follow stack limit: RETURN follow failed.")) return 1; + } + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $D02C") == header, + "Follow stack limit: the chained follows must reach the final target.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F9 JMP $D02C") == status, + "Follow stack limit: the eleventh follow must report slot F9 after discarding the oldest entry.")) return 1; + if (expect(mon.poll(0) == 0, "Follow stack limit: first RETURN failed.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F9 RET $D028") == status, + "Follow stack limit: the newest return entry must pop from slot F9.")) return 1; + for (int i = 0; i < 9; i++) { + if (expect(mon.poll(0) == 0, "Follow stack limit: move to non-jumpable row failed.")) return 1; + if (expect(mon.poll(0) == 0, "Follow stack limit: draining RETURN failed.")) return 1; + } + screen.get_slice(1, 3, 38, header); + if (expect(strstr(header, "MONITOR ASM $D004") == header, + "Follow stack limit: after ten returns the oldest discarded origin must not reappear.")) return 1; + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "F0 RET $D004") == status, + "Follow stack limit: the oldest retained entry must return from slot F0.")) return 1; + mon.deinit(); + } + + return 0; +} + +static int test_restricted_backend_guards_platform_features(void) +{ + TestUserInterface ui; + CaptureScreen screen; + FakeRestrictedMemoryBackend backend; + const int keys[] = { 'o', 'O', 'Z', 'G', KEY_BREAK }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + char status[39]; + uint16_t go_addr = 0; + + ui.screen = &screen; + ui.keyboard = &kb; + ui.set_prompt("C123", 1); + monitor_reset_saved_state(); + monitor_io::reset_fake_monitor_io(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + screen.get_slice(1, 22, 38, status); + if (expect(strstr(status, "CPU VIEW") == status && strstr(status, "CPU BANK N/A") != NULL && strstr(status, "VIC N/A") != NULL, + "Restricted backend status must describe the current CPU-visible map.")) return 1; + if (expect(backend.set_monitor_cpu_port_calls == 0, + "Restricted backend init must not receive a fake CPU-bank selection.")) return 1; + + ui.popup_count = 0; + if (expect(mon.poll(0) == 0, "Restricted CPU-bank shortcut should not exit.")) return 1; + if (expect(ui.popup_count == 1 && strcmp(ui.last_popup, "CPU BANK UNAVAILABLE") == 0, + "Restricted CPU-bank shortcut must warn clearly.")) return 1; + if (expect(backend.set_monitor_cpu_port_calls == 0, + "Restricted CPU-bank shortcut must leave backend bank state unchanged.")) return 1; + + if (expect(mon.poll(0) == 0, "Restricted VIC-bank shortcut should not exit.")) return 1; + if (expect(ui.popup_count == 2 && strcmp(ui.last_popup, "VIC BANK UNAVAILABLE") == 0, + "Restricted VIC-bank shortcut must warn clearly.")) return 1; + if (expect(backend.set_live_vic_bank_calls == 0, + "Restricted VIC-bank shortcut must not write DD00.")) return 1; + + if (expect(mon.poll(0) == 0, "Restricted freeze shortcut should not exit.")) return 1; + if (expect(ui.popup_count == 3 && strcmp(ui.last_popup, "FREEZE UNAVAILABLE") == 0, + "Restricted freeze shortcut must warn clearly.")) return 1; + + if (expect(mon.poll(0) == 1, "Restricted GO command should exit after queueing a jump.")) return 1; + if (expect(ui.popup_count == 3, + "Restricted GO command must not warn when a backend exposes CPU-view execution.")) return 1; + if (expect(mon.consume_pending_go(&go_addr) && go_addr == 0xC123, + "Restricted GO command must queue the requested jump address.")) return 1; + mon.deinit(); + monitor_reset_saved_state(); + return 0; +} + +struct ResetShortcutBackend : public FakeMemoryBackend +{ + int reset_calls; + + ResetShortcutBackend() : reset_calls(0) { } + virtual bool supports_reset(void) const { return true; } + virtual bool reset_machine(void) { reset_calls++; return true; } +}; + +static int test_reset_shortcut_is_global(void) +{ + TestUserInterface ui; + CaptureScreen screen; + ResetShortcutBackend backend; + const int keys[] = { + KEY_HELP, + KEY_CTRL_X, + 'E', + KEY_CTRL_X, + KEY_CTRL_X, + KEY_BREAK + }; + FakeKeyboard kb(keys, sizeof(keys) / sizeof(keys[0])); + + ui.screen = &screen; + ui.keyboard = &kb; + monitor_reset_saved_state(); + + BackendMachineMonitor mon(&ui, &backend); + mon.init(&screen, &kb); + + if (expect(mon.poll(0) == 0, "F3 should show help before reset shortcut test.")) return 1; + if (expect(mon.poll(0) == 0, "CTRL+X from help should reset without exiting monitor.")) return 1; + if (expect(backend.reset_calls == 1, + "CTRL+X must reset even while help is visible.")) return 1; + + if (expect(mon.poll(0) == 0, "E should enter edit mode before reset shortcut test.")) return 1; + if (expect(mon.poll(0) == 0, "CTRL+X from edit should reset without exiting monitor.")) return 1; + if (expect(backend.reset_calls == 2, + "CTRL+X must reset even while edit mode is active.")) return 1; + + if (expect(mon.poll(0) == 0, "CTRL+X from view mode should reset without exiting monitor.")) return 1; + if (expect(backend.reset_calls == 3, + "CTRL+X must reset from normal monitor view mode.")) return 1; + + if (expect(mon.poll(0) == 1, "RUN/STOP should still close monitor after reset shortcut test.")) return 1; + mon.deinit(); + monitor_reset_saved_state(); + return 0; +} + +int main() +{ + if (test_disassembler()) return 1; + if (test_disassembler_all_opcodes_match_c64ref()) return 1; + if (test_memory_helpers()) return 1; + if (test_parsers_and_formatters()) return 1; + if (test_hunt_prompt_typed_input()) return 1; + if (test_load_save_param_parsers()) return 1; + if (test_banked_backend()) return 1; + if (test_frozen_banked_backend()) return 1; + if (test_kernal_disassembly_mapping()) return 1; + if (test_asm_root_stable_with_cpu7_io_context()) return 1; + if (test_asm_root_stable_with_continuous_ram_context()) return 1; + if (test_asm_explicit_root_can_cross_continuous_ram_boundary()) return 1; + if (test_asm_left_right_decode_root_control()) return 1; + if (test_asm_ambiguous_predecessor_is_stable()) return 1; + if (test_asm_edit_left_right_does_not_rephase_root()) return 1; + if (test_asm_self_modification_root_rules()) return 1; + if (test_asm_cpu_bank_invalidation_for_root()) return 1; + if (test_asm_all_cpu_banks_keep_explicit_root()) return 1; + if (test_disassembly_instruction_stepping()) return 1; + if (test_disassembly_reverse_navigation_reuses_cached_lane()) return 1; + if (test_disassembly_reverse_navigation_refuses_overlapping_predecessor()) return 1; + if (test_disassembly_sliding_lane_scrolls_beyond_cache()) return 1; + if (test_disassembly_boundary_cutover()) return 1; + if (test_disassembly_reverse_cutover_keeps_ffff_at_bottom()) return 1; + if (test_hex_reverse_wrap_keeps_tail_row_at_bottom()) return 1; + if (test_last_address_row_highlight()) return 1; + if (test_template_cursor()) return 1; + if (test_task_action_lookup()) return 1; + if (test_monitor_renders_window_border()) return 1; + if (test_monitor_byte_to_address_invariant()) return 1; + if (test_monitor_cursor_header_and_scroll()) return 1; + if (test_monitor_interaction()) return 1; + if (test_monitor_default_cpu_bank_and_vic_shortcuts()) return 1; + if (test_monitor_split_cpu_status_highlights_digits_only()) return 1; + if (test_monitor_freeze_mode_vic_shortcut_override()) return 1; + if (test_monitor_reopen_restores_state()) return 1; + if (test_monitor_kernal_bank_switch_and_ram_interaction()) return 1; + if (test_assembler_encoding()) return 1; + if (test_screen_code_reverse()) return 1; + if (test_screen_charset_toggle_and_header()) return 1; + if (test_screen_charset_display_and_memory_ascii_pane()) return 1; + if (test_logical_delete_per_view()) return 1; + if (test_scr_edit_writes_screen_code()) return 1; + if (test_number_shortcut_routing()) return 1; + if (test_range_shortcut_routing()) return 1; + if (test_asm_number_popup_targets_operands()) return 1; + if (test_asm_number_popup_illegal_and_invalid_rows()) return 1; + if (test_asm_edit_assemble_at_cursor()) return 1; + if (test_asm_edit_direct_typing()) return 1; + if (test_asm_edit_direct_typing_immediate()) return 1; + if (test_asm_edit_branch_two_parts()) return 1; + if (test_asm_edit_ram_2000_program_readback()) return 1; + if (test_asm_cpu_bank_cycle_preserves_screen_row()) return 1; + if (test_asm_page_up_keeps_screen_row()) return 1; + if (test_space_shortcuts_match_existing_paging()) return 1; + if (test_opcode_picker_refilters_live()) return 1; + if (test_opcode_picker_filters_orders_and_commits_on_enter()) return 1; + if (test_opcode_picker_browsing_does_not_mutate_frozen_charset_backup()) return 1; + if (test_opcode_picker_near_bottom_refresh_stays_inside_content()) return 1; + if (test_opcode_picker_selection_near_bottom_preserves_live_charset_page()) return 1; + if (test_opcode_picker_pauses_poll_mode()) return 1; + if (test_cross_view_sync()) return 1; + if (test_space_edit_behavior_preserved()) return 1; + if (test_shift_space_does_not_page_in_edit_mode()) return 1; + if (test_binary_row_formats()) return 1; + if (test_binary_bit_navigation_and_width()) return 1; + if (test_memory_row_width_cycle()) return 1; + if (test_binary_delete_behavior()) return 1; + if (test_clipboard_number_and_range()) return 1; + if (test_number_popup_edit_and_commit()) return 1; + if (test_number_popup_word_commit_and_sticky_row()) return 1; + if (test_number_popup_placement_and_overlay_redraw()) return 1; + if (test_fixed_prompt_widths()) return 1; + if (test_asm_range_copy_paste()) return 1; + if (test_asm_paste_keeps_viewport_position()) return 1; + if (test_disassembly_up_keeps_screen_row()) return 1; + if (test_illegal_mode_header_label()) return 1; + if (test_hunt_and_compare_picker_navigation()) return 1; + if (test_prompt_cancel_and_empty_clipboard()) return 1; + if (test_load_save_and_goto_command_flow()) return 1; + if (test_hex_single_nibble_commits_on_navigation()) return 1; + if (test_header_invariants_and_parity()) return 1; + if (test_poll_mode_refreshes_visible_ram()) return 1; + if (test_poll_mode_disabled_on_full_refresh_screen()) return 1; + if (test_edit_indicator_layout_across_views()) return 1; + if (test_warning_popups_preserve_status_row()) return 1; + if (test_asm_follow_and_return_navigation()) return 1; + if (test_restricted_backend_guards_platform_features()) return 1; + if (test_reset_shortcut_is_global()) return 1; + + puts("machine_monitor_test: OK"); + return 0; +} diff --git a/software/test/monitor/machine_monitor_test_support.cc b/software/test/monitor/machine_monitor_test_support.cc new file mode 100644 index 000000000..88e75c95c --- /dev/null +++ b/software/test/monitor/machine_monitor_test_support.cc @@ -0,0 +1,1257 @@ +#include "machine_monitor_test_support.h" + +#include +#include +#include + +#include "menu.h" + +#ifdef getch +#undef getch +#endif + +namespace { + +enum { + FAKE_CONFIG_MAX_STORES = 8, + FAKE_CONFIG_MAX_ITEMS = 32, + FAKE_CONFIG_MAX_STRING = 64, +}; + +struct FakePersistedStore { + bool used; + uint32_t page_id; + char name[64]; + const t_cfg_definition *defs; + int item_count; + int values[FAKE_CONFIG_MAX_ITEMS]; + char strings[FAKE_CONFIG_MAX_ITEMS][FAKE_CONFIG_MAX_STRING]; +}; + +struct FakeRuntimeStore { + ConfigStore *store; + FakePersistedStore *persisted; + const t_cfg_definition *defs; + int item_count; + int values[FAKE_CONFIG_MAX_ITEMS]; + char strings[FAKE_CONFIG_MAX_ITEMS][FAKE_CONFIG_MAX_STRING]; +}; + +static FakePersistedStore g_fake_persisted_stores[FAKE_CONFIG_MAX_STORES]; +static FakeRuntimeStore g_fake_runtime_stores[FAKE_CONFIG_MAX_STORES]; +static uint16_t g_fake_ms_timer = 0; + +static int fake_cfg_count_items(const t_cfg_definition *defs) +{ + int count = 0; + + while (defs && defs[count].type != CFG_TYPE_END && count < FAKE_CONFIG_MAX_ITEMS) { + count++; + } + return count; +} + +static int fake_cfg_find_index(const t_cfg_definition *defs, int item_count, uint8_t id) +{ + for (int i = 0; i < item_count; i++) { + if (defs[i].id == id) { + return i; + } + } + return -1; +} + +static void fake_cfg_apply_defaults(FakeRuntimeStore *runtime) +{ + if (!runtime) { + return; + } + for (int i = 0; i < runtime->item_count; i++) { + runtime->values[i] = (int)runtime->defs[i].def; + runtime->strings[i][0] = 0; + if (runtime->defs[i].type == CFG_TYPE_STRING || + runtime->defs[i].type == CFG_TYPE_STRFUNC || + runtime->defs[i].type == CFG_TYPE_STRPASS || + runtime->defs[i].type == CFG_TYPE_INFO) { + const char *def = (const char *)runtime->defs[i].def; + if (def) { + strncpy(runtime->strings[i], def, FAKE_CONFIG_MAX_STRING - 1); + runtime->strings[i][FAKE_CONFIG_MAX_STRING - 1] = 0; + } + } + } +} + +static FakePersistedStore *fake_cfg_find_persisted(uint32_t page_id) +{ + for (int i = 0; i < FAKE_CONFIG_MAX_STORES; i++) { + if (g_fake_persisted_stores[i].used && g_fake_persisted_stores[i].page_id == page_id) { + return &g_fake_persisted_stores[i]; + } + } + return NULL; +} + +static FakePersistedStore *fake_cfg_ensure_persisted(uint32_t page_id, const char *name, const t_cfg_definition *defs) +{ + FakePersistedStore *persisted = fake_cfg_find_persisted(page_id); + + if (persisted) { + return persisted; + } + for (int i = 0; i < FAKE_CONFIG_MAX_STORES; i++) { + if (!g_fake_persisted_stores[i].used) { + persisted = &g_fake_persisted_stores[i]; + memset(persisted, 0, sizeof(*persisted)); + persisted->used = true; + persisted->page_id = page_id; + persisted->defs = defs; + persisted->item_count = fake_cfg_count_items(defs); + strncpy(persisted->name, name ? name : "", sizeof(persisted->name) - 1); + FakeRuntimeStore runtime; + memset(&runtime, 0, sizeof(runtime)); + runtime.defs = defs; + runtime.item_count = persisted->item_count; + fake_cfg_apply_defaults(&runtime); + for (int item = 0; item < persisted->item_count; item++) { + persisted->values[item] = runtime.values[item]; + strncpy(persisted->strings[item], runtime.strings[item], FAKE_CONFIG_MAX_STRING - 1); + persisted->strings[item][FAKE_CONFIG_MAX_STRING - 1] = 0; + } + return persisted; + } + } + return NULL; +} + +static FakeRuntimeStore *fake_cfg_find_runtime(ConfigStore *store) +{ + for (int i = 0; i < FAKE_CONFIG_MAX_STORES; i++) { + if (g_fake_runtime_stores[i].store == store) { + return &g_fake_runtime_stores[i]; + } + } + return NULL; +} + +static FakeRuntimeStore *fake_cfg_attach_runtime(ConfigStore *store, FakePersistedStore *persisted, const t_cfg_definition *defs) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(store); + + if (runtime) { + return runtime; + } + for (int i = 0; i < FAKE_CONFIG_MAX_STORES; i++) { + if (!g_fake_runtime_stores[i].store) { + runtime = &g_fake_runtime_stores[i]; + memset(runtime, 0, sizeof(*runtime)); + runtime->store = store; + runtime->persisted = persisted; + runtime->defs = defs; + runtime->item_count = fake_cfg_count_items(defs); + if (persisted) { + for (int item = 0; item < runtime->item_count; item++) { + runtime->values[item] = persisted->values[item]; + strncpy(runtime->strings[item], persisted->strings[item], FAKE_CONFIG_MAX_STRING - 1); + runtime->strings[item][FAKE_CONFIG_MAX_STRING - 1] = 0; + } + } else { + fake_cfg_apply_defaults(runtime); + } + return runtime; + } + } + return NULL; +} + +static void fake_cfg_detach_runtime(ConfigStore *store) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(store); + + if (!runtime) { + return; + } + memset(runtime, 0, sizeof(*runtime)); +} + +static void fake_cfg_commit(FakeRuntimeStore *runtime) +{ + if (!runtime || !runtime->persisted) { + return; + } + for (int item = 0; item < runtime->item_count; item++) { + runtime->persisted->values[item] = runtime->values[item]; + strncpy(runtime->persisted->strings[item], runtime->strings[item], FAKE_CONFIG_MAX_STRING - 1); + runtime->persisted->strings[item][FAKE_CONFIG_MAX_STRING - 1] = 0; + } +} + +} // namespace + +void outbyte(int b) +{ + char c = (char)b; + fwrite(&c, 1, 1, stdout); +} + +extern "C" uint16_t getMsTimer() +{ + return g_fake_ms_timer; +} + +extern "C" void wait_ms(int) +{ +} + +void reset_fake_config_manager_state(void) +{ + IndexedList *stores = ConfigManager::getConfigManager()->getStores(); + + while (stores->get_elements() > 0) { + ConfigStore *store = (*stores)[0]; + stores->remove_idx(0); + delete store; + } + memset(g_fake_persisted_stores, 0, sizeof(g_fake_persisted_stores)); + memset(g_fake_runtime_stores, 0, sizeof(g_fake_runtime_stores)); +} + +void set_fake_ms_timer(uint16_t value) +{ + g_fake_ms_timer = value; +} + +void advance_fake_ms_timer(uint16_t delta) +{ + g_fake_ms_timer = (uint16_t)(g_fake_ms_timer + delta); +} + +ConfigManager :: ConfigManager() : stores(4, NULL), pages(4, NULL), flash(NULL), num_pages(0), safeMode(false) +{ +} + +ConfigManager :: ~ConfigManager() +{ +} + +ConfigStore *ConfigManager :: register_store(uint32_t page_id, const char *name, t_cfg_definition *defs, ConfigurableObject *ob) +{ + ConfigStore *existing; + FakePersistedStore *persisted; + + for (int i = 0; i < stores.get_elements(); i++) { + existing = stores[i]; + if (existing && strcmp(existing->get_store_name(), name) == 0) { + if (ob) { + existing->addObject(ob); + } + return existing; + } + } + + existing = new ConfigStore(NULL, name, defs, ob); + persisted = fake_cfg_ensure_persisted(page_id, name, defs); + fake_cfg_attach_runtime(existing, persisted, defs); + stores.append(existing); + return existing; +} + +ConfigStore *ConfigManager :: find_store(const char *storename) +{ + for (int i = 0; i < stores.get_elements(); i++) { + ConfigStore *store = stores[i]; + if (store && strcmp(store->get_store_name(), storename) == 0) { + return store; + } + } + return NULL; +} + +ConfigStore *ConfigManager :: find_store(uint32_t) +{ + return NULL; +} + +void ConfigManager :: remove_store(ConfigStore *store) +{ + stores.remove(store); +} + +ConfigStore :: ConfigStore(ConfigPage *cfg_page, const char *name, + t_cfg_definition *, ConfigurableObject *obj) + : sort_order(0), objects(4, NULL), hook_obj(NULL), store_name(name ? name : ""), + alt_name(""), page(cfg_page), staleEffect(false), staleFlash(false), hidden(false), items(4, NULL) +{ + if (obj) { + objects.append(obj); + } +} + +ConfigStore :: ~ConfigStore() +{ + fake_cfg_detach_runtime(this); +} + +void ConfigStore :: addObject(ConfigurableObject *obj) +{ + if (obj) { + objects.append(obj); + } +} + +int ConfigStore :: unregister(ConfigurableObject *obj) +{ + if (obj) { + objects.remove(obj); + } + return objects.get_elements(); +} + +void ConfigStore :: reset(void) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(this); + + if (!runtime) { + return; + } + fake_cfg_apply_defaults(runtime); + fake_cfg_commit(runtime); +} + +void ConfigStore :: read(bool) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(this); + + if (!runtime) { + return; + } + if (runtime->persisted) { + for (int item = 0; item < runtime->item_count; item++) { + runtime->values[item] = runtime->persisted->values[item]; + strncpy(runtime->strings[item], runtime->persisted->strings[item], FAKE_CONFIG_MAX_STRING - 1); + runtime->strings[item][FAKE_CONFIG_MAX_STRING - 1] = 0; + } + } +} + +void ConfigStore :: write(void) +{ + fake_cfg_commit(fake_cfg_find_runtime(this)); +} + +void ConfigStore :: at_open_config(void) +{ +} + +void ConfigStore :: effectuate(void) +{ +} + +ConfigItem *ConfigStore :: find_item(uint8_t) +{ + return NULL; +} + +ConfigItem *ConfigStore :: find_item(const char *) +{ + return NULL; +} + +int ConfigStore :: get_value(uint8_t id) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(this); + int index; + + if (!runtime) { + return 0; + } + index = fake_cfg_find_index(runtime->defs, runtime->item_count, id); + return (index >= 0) ? runtime->values[index] : 0; +} + +const char *ConfigStore :: get_string(uint8_t id) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(this); + int index; + + if (!runtime) { + return ""; + } + index = fake_cfg_find_index(runtime->defs, runtime->item_count, id); + return (index >= 0) ? runtime->strings[index] : ""; +} + +void ConfigStore :: set_value(uint8_t id, int value) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(this); + int index; + + if (!runtime) { + return; + } + index = fake_cfg_find_index(runtime->defs, runtime->item_count, id); + if (index >= 0) { + runtime->values[index] = value; + } +} + +void ConfigStore :: set_string(uint8_t id, const char *text) +{ + FakeRuntimeStore *runtime = fake_cfg_find_runtime(this); + int index; + + if (!runtime) { + return; + } + index = fake_cfg_find_index(runtime->defs, runtime->item_count, id); + if (index >= 0) { + strncpy(runtime->strings[index], text ? text : "", FAKE_CONFIG_MAX_STRING - 1); + runtime->strings[index][FAKE_CONFIG_MAX_STRING - 1] = 0; + } +} + +UserInterface :: UserInterface(const char *ui_title, bool use_logo) : title(ui_title) +{ + initialized = false; + doBreak = false; + available = true; + status_box = NULL; + for (int i = 0; i < MAX_UI_OBJECTS; i++) { + ui_objects[i] = NULL; + } + color_border = 0; + color_bg = 0; + color_fg = 15; + color_sel = 0; + color_sel_bg = 0; + reverse_sel = 0; + color_status = 0; + color_inactive = 0; + config_save = 0; + filename_overflow_squeeze = 0; + navmode = 0; + logo = use_logo; + host = NULL; + keyboard = NULL; + screen = NULL; + focus = -1; + menu_response_to_action = MENU_NOP; +} + +UserInterface :: ~UserInterface() +{ +} + +void UserInterface :: effectuate_settings(void) +{ +} + +void UserInterface :: release_host() +{ +} + +bool UserInterface :: is_available(void) +{ + return available; +} + +void UserInterface :: run() +{ +} + +void UserInterface :: run_once() +{ +} + +void UserInterface :: run_remote() +{ +} + +int UserInterface :: pollInactive() +{ + return 0; +} + +int UserInterface :: keymapper(int c, keymap_options_t map) +{ + if ((navmode == 1) && (map != e_keymap_monitor)) { + if (c >= 'A' && c <= 'Z') { + c |= 0x20; + } else { + switch (c) { + case 'w': c = KEY_UP; break; + case 'a': c = KEY_LEFT; break; + case 's': c = KEY_DOWN; break; + case 'd': c = KEY_RIGHT; break; + } + } + } + switch (c) { + case KEY_F1: c = KEY_PAGEUP; break; + case KEY_F3: c = KEY_HELP; break; + case KEY_F5: c = KEY_TASKS; break; + case KEY_F7: c = KEY_PAGEDOWN; break; + case KEY_F2: c = KEY_CONFIG; break; + case KEY_F4: c = KEY_SYSINFO; break; + case KEY_F6: c = KEY_SEARCH; break; + } + return c; +} + +int UserInterface :: popup(const char *, uint8_t) +{ + return 0; +} + +int UserInterface :: popup(const char *, int, const char **, const char *) +{ + return 0; +} + +int UserInterface :: choice(const char *, const char **, int) +{ + return 0; +} + +int UserInterface :: string_box(const char *, char *, int) +{ + return 0; +} + +int UserInterface :: string_box(const char *, char *, int, bool) +{ + return 0; +} + +int UserInterface :: string_box(const char *, char *, int, bool, bool) +{ + return 0; +} + +int UserInterface :: string_edit(char *, int, Window *, int, int) +{ + return 0; +} + +void UserInterface :: show_progress(const char *, int) +{ +} + +void UserInterface :: update_progress(const char *, int) +{ +} + +void UserInterface :: hide_progress(void) +{ +} + +void UserInterface :: init(GenericHost *h) +{ + host = h; +} + +void UserInterface :: appear(void) +{ +} + +void UserInterface :: set_screen(Screen *s) +{ + screen = s; +} + +int g_set_screen_title_call_count = 0; + +void UserInterface :: set_screen_title(void) +{ + g_set_screen_title_call_count++; +} + +int UserInterface :: activate_uiobject(UIObject *) +{ + return 0; +} + +bool UserInterface :: has_focus(UIObject *) +{ + return true; +} + +int UserInterface :: getPreferredType(void) +{ + return 0; +} + +void UserInterface :: help() +{ +} + +void UserInterface :: run_editor(const char *, int) +{ +} + +void UserInterface :: run_hex_editor(const char *, int) +{ +} + +void UserInterface :: swapDisk(void) +{ +} + +void UserInterface :: send_keystroke(int) +{ +} + +bool UserInterface :: anyMenuActive(void) +{ + return true; +} + +void UserInterface :: postMessage(const char *) +{ +} + +mstring *UserInterface :: getMessage() +{ + return NULL; +} + +FakeMemoryBackend :: FakeMemoryBackend() +{ + memset(memory, 0, sizeof(memory)); + session_begin_count = 0; + session_end_count = 0; +} + +uint8_t FakeMemoryBackend :: read(uint16_t address) +{ + return memory[address]; +} + +void FakeMemoryBackend :: write(uint16_t address, uint8_t value) +{ + memory[address] = value; +} + +void FakeMemoryBackend :: read_block(uint16_t address, uint8_t *dst, uint16_t len) +{ + for (uint16_t i = 0; i < len; i++) { + dst[i] = memory[(uint16_t)(address + i)]; + } +} + +void FakeMemoryBackend :: begin_session(void) +{ + session_begin_count++; +} + +void FakeMemoryBackend :: end_session(void) +{ + session_end_count++; +} + +FakeBankedMemoryBackend :: FakeBankedMemoryBackend() : frozen(false), live_cpu_port(0x07), live_cpu_ddr(0x07), live_dd00(0x01) +{ + memset(ram, 0, sizeof(ram)); + memset(basic, 0, sizeof(basic)); + memset(kernal, 0, sizeof(kernal)); + memset(charrom, 0, sizeof(charrom)); + memset(io, 0, sizeof(io)); + memset(screen_backup, 0, sizeof(screen_backup)); + memset(ram_backup, 0, sizeof(ram_backup)); + session_begin_count = 0; + session_end_count = 0; + set_monitor_cpu_port(live_cpu_port); +} + +uint8_t FakeBankedMemoryBackend :: read(uint16_t address) +{ + uint8_t cpu_port = get_monitor_cpu_port(); + + if (address >= 0xA000 && address <= 0xBFFF) { + if ((cpu_port & 0x03) == 0x03) { + return basic[address - 0xA000]; + } + return ram[address]; + } + if (address >= 0xD000 && address <= 0xDFFF) { + if ((cpu_port & 0x03) == 0x00) { + return ram[address]; + } + if (cpu_port & 0x04) { + if (address == 0xDD00) { + return live_dd00; + } + return io[address - 0xD000]; + } + return charrom[address - 0xD000]; + } + if (address >= 0xE000) { + if (cpu_port & 0x02) { + return kernal[address - 0xE000]; + } + return ram[address]; + } + if (frozen && address >= 0x0400 && address < 0x0800) { + return screen_backup[address - 0x0400]; + } + if (frozen && address >= 0x0800 && address < 0x1000) { + return ram_backup[address - 0x0800]; + } + if (address == 0x0001) { + return (ram[address] & 0xF8) | live_cpu_port; + } + if (address == 0x0000) { + return (ram[address] & 0xF8) | live_cpu_ddr; + } + return ram[address]; +} + +void FakeBankedMemoryBackend :: write(uint16_t address, uint8_t value) +{ + uint8_t cpu_port = get_monitor_cpu_port(); + + if (address >= 0xD000 && address <= 0xDFFF && (cpu_port & 0x03) != 0x00 && (cpu_port & 0x04)) { + io[address - 0xD000] = value; + if (address == 0xDD00) { + live_dd00 = value; + } + return; + } + if (frozen && address >= 0x0400 && address < 0x0800) { + screen_backup[address - 0x0400] = value; + return; + } + if (frozen && address >= 0x0800 && address < 0x1000) { + ram_backup[address - 0x0800] = value; + return; + } + ram[address] = value; + if (address == 0x0000) { + live_cpu_ddr = value & 0x07; + } + if (address == 0x0001) { + live_cpu_port = value & 0x07; + } +} + +uint8_t FakeBankedMemoryBackend :: get_live_cpu_port(void) +{ + return (uint8_t)(((live_cpu_port & live_cpu_ddr) | ((uint8_t)(~live_cpu_ddr) & 0x07)) & 0x07); +} + +uint8_t FakeBankedMemoryBackend :: get_live_vic_bank(void) +{ + return (uint8_t)(3 - (live_dd00 & 0x03)); +} + +void FakeBankedMemoryBackend :: begin_session(void) +{ + session_begin_count++; +} + +void FakeBankedMemoryBackend :: end_session(void) +{ + session_end_count++; +} + +bool FakeBankedMemoryBackend :: supports_freeze(void) const +{ + return true; +} + +bool FakeBankedMemoryBackend :: is_frozen(void) const +{ + return frozen; +} + +void FakeBankedMemoryBackend :: set_frozen(bool on) +{ + frozen = on; +} + +FakeFreezeControlBackend :: FakeFreezeControlBackend(bool available_now, bool frozen_now) + : available(available_now), frozen(frozen_now), set_frozen_calls(0) +{ +} + +bool FakeFreezeControlBackend :: supports_freeze(void) const +{ + return true; +} + +bool FakeFreezeControlBackend :: freeze_available(void) const +{ + return available; +} + +bool FakeFreezeControlBackend :: is_frozen(void) const +{ + return frozen; +} + +void FakeFreezeControlBackend :: set_frozen(bool on) +{ + set_frozen_calls++; + frozen = on; +} + +FakeFrozenVicBackend :: FakeFrozenVicBackend() : reported_vic_bank(0), requested_vic_bank(0), set_live_vic_bank_calls(0) +{ + frozen = true; +} + +uint8_t FakeFrozenVicBackend :: get_live_vic_bank(void) +{ + return reported_vic_bank & 0x03; +} + +void FakeFrozenVicBackend :: set_live_vic_bank(uint8_t vic_bank) +{ + requested_vic_bank = (uint8_t)(vic_bank & 0x03); + set_live_vic_bank_calls++; +} + +FakeRestrictedMemoryBackend :: FakeRestrictedMemoryBackend() : set_monitor_cpu_port_calls(0), set_live_vic_bank_calls(0) +{ +} + +void FakeRestrictedMemoryBackend :: set_monitor_cpu_port(uint8_t) +{ + set_monitor_cpu_port_calls++; +} + +bool FakeRestrictedMemoryBackend :: supports_cpu_banking(void) const +{ + return false; +} + +bool FakeRestrictedMemoryBackend :: supports_vic_bank(void) const +{ + return false; +} + +void FakeRestrictedMemoryBackend :: set_live_vic_bank(uint8_t) +{ + set_live_vic_bank_calls++; +} + +const char *FakeRestrictedMemoryBackend :: source_name(uint16_t) const +{ + return "CPU"; +} + +FakeKeyboard :: FakeKeyboard(const int *k, int c) + : keys(k), count(c), index(0), pushed(false), pushed_key(-1) +{ +} + +int FakeKeyboard :: getch(void) +{ + if (pushed) { + pushed = false; + return pushed_key; + } + if (index >= count) { + return -1; + } + return keys[index++]; +} + +void FakeKeyboard :: push_head(int key) +{ + pushed = true; + pushed_key = key; +} + +CaptureScreen :: CaptureScreen() : width(40), height(25), cursor_x(0), cursor_y(0), color(0), reverse_mode_on(false), clear_calls(0) +{ + clear(); +} + +void CaptureScreen :: set_background(int) +{ +} + +void CaptureScreen :: set_color(int c) +{ + color = c; +} + +int CaptureScreen :: get_color() +{ + return color; +} + +void CaptureScreen :: reverse_mode(int enabled) +{ + reverse_mode_on = enabled != 0; +} + +int CaptureScreen :: get_size_x(void) +{ + return width; +} + +int CaptureScreen :: get_size_y(void) +{ + return height; +} + +void CaptureScreen :: backup(void) +{ +} + +void CaptureScreen :: restore(void) +{ +} + +void CaptureScreen :: clear() +{ + clear_calls++; + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + chars[y][x] = ' '; + colors[y][x] = 0; + reverse_chars[y][x] = false; + write_counts[y][x] = 0; + } + } + cursor_x = 0; + cursor_y = 0; + reverse_mode_on = false; +} + +void CaptureScreen :: move_cursor(int x, int y) +{ + cursor_x = x; + cursor_y = y; + if (cursor_x < 0) cursor_x = 0; + if (cursor_y < 0) cursor_y = 0; + if (cursor_x >= width) cursor_x = width - 1; + if (cursor_y >= height) cursor_y = height - 1; +} + +int CaptureScreen :: output(char c) +{ + if (c == '\n') { + cursor_x = 0; + if (cursor_y < height - 1) { + cursor_y++; + } + return 1; + } + if (cursor_x < width && cursor_y < height) { + chars[cursor_y][cursor_x] = c; + colors[cursor_y][cursor_x] = (uint8_t)color; + reverse_chars[cursor_y][cursor_x] = reverse_mode_on; + write_counts[cursor_y][cursor_x]++; + } + if (cursor_x < width - 1) { + cursor_x++; + } + return 1; +} + +int CaptureScreen :: output(const char *string) +{ + int written = 0; + while (*string) { + written += output(*string++); + } + return written; +} + +void CaptureScreen :: repeat(char c, int rep) +{ + for (int i = 0; i < rep; i++) { + output(c); + } +} + +void CaptureScreen :: output_fixed_length(const char *string, int, int width_to_write) +{ + for (int i = 0; i < width_to_write; i++) { + if (string[i]) { + output(string[i]); + } else { + output(' '); + } + } +} + +void CaptureScreen :: get_slice(int x, int y, int len, char *out) const +{ + for (int i = 0; i < len; i++) { + out[i] = chars[y][x + i]; + } + out[len] = 0; +} + +void CaptureScreen :: reset_write_counts() +{ + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + write_counts[y][x] = 0; + } + } +} + +int CaptureScreen :: count_writes_outside_rect(int left, int top, int right, int bottom) const +{ + int writes = 0; + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (x >= left && x <= right && y >= top && y <= bottom) { + continue; + } + writes += write_counts[y][x]; + } + } + return writes; +} + +CaptureWindow :: CaptureWindow(Screen *screen, int window_width) + : Window(screen, 0, 0, window_width, 1), width(window_width), last_x(-1), last_y(-1) +{ +} + +void CaptureWindow :: move_cursor(int x, int y) +{ + last_x = x; + last_y = y; +} + +void CaptureWindow :: output_length(const char *, int) +{ +} + +void CaptureWindow :: repeat(char, int) +{ +} + +int CaptureWindow :: get_size_x(void) +{ + return width; +} + +TestUserInterface :: TestUserInterface() + : UserInterface("test", false), popup_count(0), last_prompt_maxlen(0), prompt_count(0), prompt_index(0) +{ + last_popup[0] = 0; + last_prompt_message[0] = 0; +} + +void TestUserInterface :: set_prompt(const char *text, int result) +{ + prompt_count = 0; + prompt_index = 0; + push_prompt(text, result); +} + +void TestUserInterface :: push_prompt(const char *text, int result) +{ + if (prompt_count >= (int)(sizeof(prompt_texts) / sizeof(prompt_texts[0]))) { + return; + } + strncpy(prompt_texts[prompt_count], text ? text : "", sizeof(prompt_texts[prompt_count]) - 1); + prompt_texts[prompt_count][sizeof(prompt_texts[prompt_count]) - 1] = 0; + prompt_results[prompt_count] = result; + prompt_count++; +} + +int TestUserInterface :: popup(const char *msg, uint8_t) +{ + popup_count++; + strncpy(last_popup, msg ? msg : "", sizeof(last_popup) - 1); + last_popup[sizeof(last_popup) - 1] = 0; + return BUTTON_OK; +} + +int TestUserInterface :: string_box(const char *msg, char *buffer, int maxlen) +{ + int copied = 0; + + strncpy(last_prompt_message, msg ? msg : "", sizeof(last_prompt_message) - 1); + last_prompt_message[sizeof(last_prompt_message) - 1] = 0; + last_prompt_maxlen = maxlen; + if (prompt_index >= prompt_count) { + return 0; + } + int result = prompt_results[prompt_index]; + if (result > 0) { + while (prompt_texts[prompt_index][copied] && copied < maxlen) { + buffer[copied] = prompt_texts[prompt_index][copied]; + copied++; + } + buffer[copied] = 0; + } + prompt_index++; + return result; +} + +int TestUserInterface :: string_box(const char *msg, char *buffer, int maxlen, bool) +{ + return string_box(msg, buffer, maxlen); +} + +int TestUserInterface :: string_box(const char *msg, char *buffer, int maxlen, bool, bool) +{ + return string_box(msg, buffer, maxlen); +} + +int fail(const char *message) +{ + puts(message); + return 1; +} + +int expect(int condition, const char *message) +{ + if (!condition) { + return fail(message); + } + return 0; +} + +int popup_longest_line(const char *msg) +{ + int longest = 0; + int current = 0; + + while (msg && *msg) { + if (*msg == '\n') { + if (current > longest) longest = current; + current = 0; + } else if (*msg != '\r') { + current++; + } + msg++; + } + if (current > longest) longest = current; + return longest; +} + +int expect_screens_equal(const CaptureScreen &a, const CaptureScreen &b, const char *message) +{ + for (int y = 0; y < 25; y++) { + for (int x = 0; x < 40; x++) { + if (a.chars[y][x] != b.chars[y][x] || + a.reverse_chars[y][x] != b.reverse_chars[y][x]) { + return fail(message); + } + } + } + return 0; +} + +bool find_popup_rect(const CaptureScreen &screen, int *left, int *top, int *right, int *bottom) +{ + int best_left = -1; + int best_top = -1; + int best_right = -1; + int best_bottom = -1; + int best_area = 0; + + for (int y = 0; y < 25; y++) { + for (int x = 0; x < 40; x++) { + if ((unsigned char)screen.chars[y][x] != BORD_LOWER_RIGHT_CORNER) { + continue; + } + for (int xr = x + 2; xr < 40; xr++) { + if ((unsigned char)screen.chars[y][xr] != BORD_LOWER_LEFT_CORNER) { + continue; + } + for (int yb = y + 2; yb < 25; yb++) { + int width = xr - x + 1; + int height = yb - y + 1; + if (width > 40 || height >= 23) { + continue; + } + // Skip the surrounding monitor frame: it spans nearly the + // full screen. The bookmark popup is shorter. + if (width >= 38 && height >= 22) { + continue; + } + if ((unsigned char)screen.chars[yb][x] == BORD_UPPER_RIGHT_CORNER && + (unsigned char)screen.chars[yb][xr] == BORD_UPPER_LEFT_CORNER) { + int area = width * height; + if (best_area == 0 || area < best_area) { + best_area = area; + best_left = x; + best_top = y; + best_right = xr; + best_bottom = yb; + } + } + } + } + } + } + if (best_area == 0) { + return false; + } + if (left) *left = best_left; + if (top) *top = best_top; + if (right) *right = best_right; + if (bottom) *bottom = best_bottom; + return true; +} + +int find_highlighted_cell(const CaptureScreen &screen, int *x, int *y) +{ + for (int row = 0; row < 25; row++) { + for (int col = 0; col < 40; col++) { + if (screen.reverse_chars[row][col]) { + if (x) *x = col; + if (y) *y = row; + return 1; + } + } + } + return 0; +} + +void get_popup_line(const CaptureScreen &screen, int row, char *out, int out_len) +{ + int left = 0; + int top = 0; + int right = 0; + int bottom = 0; + int width; + + if (!find_popup_rect(screen, &left, &top, &right, &bottom)) { + if (out_len > 0) { + out[0] = 0; + } + return; + } + + width = right - left - 1; + if (width < 0) { + width = 0; + } + if (width > out_len - 1) { + width = out_len - 1; + } + screen.get_slice(left + 1, top + 1 + row, width, out); +} + +int popup_corner_diagonal_distance(int popup_left, int popup_top, int popup_right, int popup_bottom, + int cursor_x, int cursor_y) +{ + int distances[4]; + int best; + + distances[0] = abs(popup_left - cursor_x) + abs(popup_top - cursor_y); + distances[1] = abs(popup_right - cursor_x) + abs(popup_top - cursor_y); + distances[2] = abs(popup_left - cursor_x) + abs(popup_bottom - cursor_y); + distances[3] = abs(popup_right - cursor_x) + abs(popup_bottom - cursor_y); + best = distances[0]; + for (int i = 1; i < 4; i++) { + if (distances[i] < best) { + best = distances[i]; + } + } + return best; +} \ No newline at end of file diff --git a/software/test/monitor/machine_monitor_test_support.h b/software/test/monitor/machine_monitor_test_support.h new file mode 100644 index 000000000..4eb267576 --- /dev/null +++ b/software/test/monitor/machine_monitor_test_support.h @@ -0,0 +1,191 @@ +#ifndef MACHINE_MONITOR_TEST_SUPPORT_H +#define MACHINE_MONITOR_TEST_SUPPORT_H + +#include + +#include "machine_monitor.h" +#include "screen.h" +#include "ui_elements.h" +#include "userinterface.h" + +typedef MachineMonitor BackendMachineMonitor; + +void reset_fake_config_manager_state(void); +void set_fake_ms_timer(uint16_t value); +void advance_fake_ms_timer(uint16_t delta); + +extern int g_set_screen_title_call_count; + +struct FakeMemoryBackend : public MemoryBackend +{ + uint8_t memory[65536]; + int session_begin_count; + int session_end_count; + + FakeMemoryBackend(); + virtual uint8_t read(uint16_t address); + virtual void write(uint16_t address, uint8_t value); + virtual void read_block(uint16_t address, uint8_t *dst, uint16_t len); + virtual void begin_session(void); + virtual void end_session(void); +}; + +struct FakeBankedMemoryBackend : public MemoryBackend +{ + uint8_t ram[65536]; + uint8_t basic[8192]; + uint8_t kernal[8192]; + uint8_t charrom[4096]; + uint8_t io[4096]; + uint8_t screen_backup[1024]; + uint8_t ram_backup[2048]; + bool frozen; + uint8_t live_cpu_port; + uint8_t live_cpu_ddr; + uint8_t live_dd00; + int session_begin_count; + int session_end_count; + + FakeBankedMemoryBackend(); + virtual uint8_t read(uint16_t address); + virtual void write(uint16_t address, uint8_t value); + virtual uint8_t get_live_cpu_port(void); + virtual uint8_t get_live_vic_bank(void); + virtual void begin_session(void); + virtual void end_session(void); + virtual bool supports_freeze(void) const; + virtual bool is_frozen(void) const; + virtual void set_frozen(bool on); +}; + +struct FakeFreezeControlBackend : public FakeMemoryBackend +{ + bool available; + bool frozen; + int set_frozen_calls; + + FakeFreezeControlBackend(bool available_now, bool frozen_now = false); + virtual bool supports_freeze(void) const; + virtual bool freeze_available(void) const; + virtual bool is_frozen(void) const; + virtual void set_frozen(bool on); +}; + +struct FakeFrozenVicBackend : public FakeBankedMemoryBackend +{ + uint8_t reported_vic_bank; + uint8_t requested_vic_bank; + int set_live_vic_bank_calls; + + FakeFrozenVicBackend(); + virtual uint8_t get_live_vic_bank(void); + virtual void set_live_vic_bank(uint8_t vic_bank); +}; + +struct FakeRestrictedMemoryBackend : public FakeMemoryBackend +{ + int set_monitor_cpu_port_calls; + int set_live_vic_bank_calls; + + FakeRestrictedMemoryBackend(); + virtual void set_monitor_cpu_port(uint8_t); + virtual bool supports_cpu_banking(void) const; + virtual bool supports_vic_bank(void) const; + virtual void set_live_vic_bank(uint8_t); + virtual const char *source_name(uint16_t) const; +}; + +class FakeKeyboard : public Keyboard +{ + const int *keys; + int count; + int index; + bool pushed; + int pushed_key; +public: + FakeKeyboard(const int *k, int c); + int getch(void); + void push_head(int key); +}; + +class CaptureScreen : public Screen +{ + int width; + int height; + int cursor_x; + int cursor_y; + int color; +public: + char chars[25][40]; + uint8_t colors[25][40]; + bool reverse_chars[25][40]; + int write_counts[25][40]; + bool reverse_mode_on; + int clear_calls; + + CaptureScreen(); + void set_background(int); + void set_color(int c); + int get_color(); + void reverse_mode(int enabled); + int get_size_x(void); + int get_size_y(void); + void backup(void); + void restore(void); + void clear(); + void move_cursor(int x, int y); + int output(char c); + int output(const char *string); + void repeat(char c, int rep); + void output_fixed_length(const char *string, int, int width_to_write); + void get_slice(int x, int y, int len, char *out) const; + void reset_write_counts(); + int count_writes_outside_rect(int left, int top, int right, int bottom) const; +}; + +class CaptureWindow : public Window +{ + int width; +public: + int last_x; + int last_y; + + CaptureWindow(Screen *screen, int width); + void move_cursor(int x, int y); + void output_length(const char *, int); + void repeat(char, int); + int get_size_x(void); +}; + +class TestUserInterface : public UserInterface +{ +public: + int popup_count; + char last_popup[128]; + char last_prompt_message[128]; + int last_prompt_maxlen; + char prompt_texts[8][64]; + int prompt_results[8]; + int prompt_count; + int prompt_index; + + TestUserInterface(); + void set_prompt(const char *text, int result); + void push_prompt(const char *text, int result); + int popup(const char *msg, uint8_t); + int string_box(const char *msg, char *buffer, int maxlen); + int string_box(const char *msg, char *buffer, int maxlen, bool); + int string_box(const char *msg, char *buffer, int maxlen, bool, bool); +}; + +int fail(const char *message); +int expect(int condition, const char *message); +int popup_longest_line(const char *msg); +int expect_screens_equal(const CaptureScreen &a, const CaptureScreen &b, const char *message); +bool find_popup_rect(const CaptureScreen &screen, int *left, int *top, int *right, int *bottom); +int find_highlighted_cell(const CaptureScreen &screen, int *x, int *y); +void get_popup_line(const CaptureScreen &screen, int row, char *out, int out_len); +int popup_corner_diagonal_distance(int popup_left, int popup_top, int popup_right, int popup_bottom, + int cursor_x, int cursor_y); + +#endif diff --git a/software/test/stubs/userinterface.h b/software/test/stubs/userinterface.h index 4c83c3167..7aea67e59 100644 --- a/software/test/stubs/userinterface.h +++ b/software/test/stubs/userinterface.h @@ -69,6 +69,16 @@ class UserInterface return strlen(buffer); } // blocking + int string_box(const char *msg, char *buffer, int maxlen, bool) + { + return string_box(msg, buffer, maxlen); + } // blocking + + int string_box(const char *msg, char *buffer, int maxlen, bool, bool) + { + return string_box(msg, buffer, maxlen); + } // blocking + void show_progress(const char *msg, int steps) {} // not blocking void update_progress(const char *msg, int steps) {} // not blocking void hide_progress(void) {} // not blocking (of course) diff --git a/software/u64/u64_config.cc b/software/u64/u64_config.cc index fa29bab56..4a6de438e 100755 --- a/software/u64/u64_config.cc +++ b/software/u64/u64_config.cc @@ -40,6 +40,7 @@ extern "C" { #include "hdmi_scan.h" #include "usb_hid.h" #include "usb_hid_config.h" +#include "monitor_init.h" const uint8_t default_colors[16][3] = { { 0x00, 0x00, 0x00 }, @@ -79,7 +80,7 @@ static void init(void *_a, void *_b) } InitFunction u64_init_func("U64 Config", init, NULL, NULL, 1); -static void u64_update_usb_hid_info_items(ConfigStore *cfg); +static void u64_update_usb_hid_info_items(ConfigStore *cfg); // Semaphore set by interrupt static SemaphoreHandle_t resetSemaphore; @@ -1393,18 +1394,21 @@ int U64Config :: setSidEmuParams(ConfigItem *it) #define MENU_U64_POKE 8 #define MENU_U64_WIFI_ECHO 9 #define MENU_U64_UART_ECHO 10 - -void U64Config :: create_task_items(void) -{ - TaskCategory *dev = TasksCollection :: getCategory("Developer", SORT_ORDER_DEVELOPER); - myActions.poke = new Action("Poke", SUBSYSID_U64, MENU_U64_POKE); - myActions.saveedid = new Action("Save EDID to file", SUBSYSID_U64, MENU_U64_SAVEEDID); - myActions.siddetect = new Action("Detect SIDs", SUBSYSID_U64, MENU_U64_DETECT_SIDS); - myActions.esp32off = new Action("Disable ESP32", SUBSYSID_U64, MENU_U64_WIFI_DISABLE); +#define MENU_U64_MONITOR 12 + +void U64Config :: create_task_items(void) +{ + TaskCategory *dev = TasksCollection :: getCategory("Developer", SORT_ORDER_DEVELOPER); + myActions.poke = new Action("Poke", SUBSYSID_U64, MENU_U64_POKE); + myActions.monitor = register_u64_machine_monitor_task ? register_u64_machine_monitor_task(MENU_U64_MONITOR) : NULL; + myActions.saveedid = new Action("Save EDID to file", SUBSYSID_U64, MENU_U64_SAVEEDID); + myActions.siddetect = new Action("Detect SIDs", SUBSYSID_U64, MENU_U64_DETECT_SIDS); + myActions.esp32off = new Action("Disable ESP32", SUBSYSID_U64, MENU_U64_WIFI_DISABLE); myActions.esp32on = new Action("Enable ESP32", SUBSYSID_U64, MENU_U64_WIFI_ENABLE); myActions.esp32boot = new Action("Enable ESP32 Boot", SUBSYSID_U64, MENU_U64_WIFI_BOOT); dev->append(myActions.saveedid ); + #if DEVELOPER > 0 dev->append(myActions.poke ); dev->append(myActions.siddetect ); @@ -1512,7 +1516,7 @@ SubsysResultCode_e U64Config :: executeCommand(SubsysCommand *cmd) break; default: - printf("U64 does not know this command\n"); + printf("U64 does not know this command\n"); return SSRET_NOT_IMPLEMENTED; } return SSRET_OK; diff --git a/software/u64/u64_config.h b/software/u64/u64_config.h index aaa656c52..47d236d36 100755 --- a/software/u64/u64_config.h +++ b/software/u64/u64_config.h @@ -27,6 +27,7 @@ class U64Config : public ConfigurableObject, ObjectWithMenu, SubSystem { struct { Action *poke; + Action *monitor; Action *saveedid; Action *siddetect; Action *esp32off; @@ -133,7 +134,7 @@ class U64Config : public ConfigurableObject, ObjectWithMenu, SubSystem void create_task_items(void); void update_task_items(bool writablePath); SubsysResultCode_e executeCommand(SubsysCommand *cmd); - void effectuate_settings(); + void effectuate_settings(); void on_edit(); static int setPllOffset(ConfigItem *it); diff --git a/software/u64/u64_machine.cc b/software/u64/u64_machine.cc index c2701f79d..46c06513b 100644 --- a/software/u64/u64_machine.cc +++ b/software/u64/u64_machine.cc @@ -3,28 +3,404 @@ #include "FreeRTOS.h" #include -void U64Machine :: get_all_memory(uint8_t *pb) +namespace { + +static uint8_t read_frozen_byte(volatile uint8_t *ram, bool freezerMenu, uint32_t address, + uint32_t *screen_backup, uint32_t *ram_backup) +{ + if (freezerMenu) { + if ((address >= 1024) && (address < 2048)) { + return ((uint8_t *)screen_backup)[address - 1024]; + } + if ((address >= 2048) && (address < 4096)) { + return ((uint8_t *)ram_backup)[address - 2048]; + } + } + return ram[address]; +} + +static void write_frozen_byte(volatile uint8_t *ram, bool freezerMenu, uint32_t address, uint8_t value, + uint32_t *screen_backup, uint32_t *ram_backup) +{ + if (freezerMenu) { + if ((address >= 1024) && (address < 2048)) { + ((uint8_t *)screen_backup)[address - 1024] = value; + return; + } else if ((address >= 2048) && (address < 4096)) { + ((uint8_t *)ram_backup)[address - 2048] = value; + return; + } + } + ram[address] = value; +} + +static void override_cpu_port(volatile uint8_t *ram, bool freezerMenu, uint8_t cpu_port, + uint8_t *saved_ddr, uint8_t *saved_port, + uint32_t *screen_backup, uint32_t *ram_backup) +{ + *saved_ddr = read_frozen_byte(ram, freezerMenu, 0x0000, screen_backup, ram_backup); + *saved_port = read_frozen_byte(ram, freezerMenu, 0x0001, screen_backup, ram_backup); + write_frozen_byte(ram, freezerMenu, 0x0000, (uint8_t)((*saved_ddr & 0xF8) | 0x07), screen_backup, ram_backup); + write_frozen_byte(ram, freezerMenu, 0x0001, (uint8_t)((*saved_port & 0xF8) | (cpu_port & 0x07)), screen_backup, ram_backup); + ram[0x0001]; + ram[0x0001]; +} + +static void restore_cpu_port(volatile uint8_t *ram, bool freezerMenu, uint8_t saved_ddr, + uint8_t saved_port, uint32_t *screen_backup, uint32_t *ram_backup) +{ + write_frozen_byte(ram, freezerMenu, 0x0000, saved_ddr, screen_backup, ram_backup); + write_frozen_byte(ram, freezerMenu, 0x0001, saved_port, screen_backup, ram_backup); + ram[0x0001]; + ram[0x0001]; +} + +static uint8_t read_visible_byte(volatile uint8_t *ram, bool freezerMenu, uint32_t address, + uint32_t *screen_backup, uint32_t *ram_backup) +{ + uint8_t saved_memonly = C64_DMA_MEMONLY; + + C64_DMA_MEMONLY = 0; + uint8_t value = read_frozen_byte(ram, freezerMenu, address, screen_backup, ram_backup); + C64_DMA_MEMONLY = saved_memonly; + return value; +} + +static void write_visible_byte(volatile uint8_t *ram, bool freezerMenu, uint32_t address, uint8_t value, + uint32_t *screen_backup, uint32_t *ram_backup) +{ + uint8_t saved_memonly = C64_DMA_MEMONLY; + + C64_DMA_MEMONLY = 0; + write_frozen_byte(ram, freezerMenu, address, value, screen_backup, ram_backup); + C64_DMA_MEMONLY = saved_memonly; +} + +static uint8_t read_cpu_mapped_byte(volatile uint8_t *ram, bool freezerMenu, uint32_t address, uint8_t cpu_port, + uint32_t *screen_backup, uint32_t *ram_backup) +{ + uint8_t raw = read_frozen_byte(ram, freezerMenu, address, screen_backup, ram_backup); + + if (address == 0x0000) { + return (uint8_t)((raw & 0xF8) | 0x07); + } + if (address == 0x0001) { + return (uint8_t)((raw & 0xF8) | (cpu_port & 0x07)); + } + if (address >= 0xA000 && address <= 0xBFFF) { + if ((cpu_port & 0x03) == 0x03) { + return read_visible_byte(ram, freezerMenu, address, screen_backup, ram_backup); + } + return raw; + } + if (address >= 0xD000 && address <= 0xDFFF) { + if ((cpu_port & 0x03) == 0x00) { + return raw; + } + if (cpu_port & 0x04) { + return read_visible_byte(ram, freezerMenu, address, screen_backup, ram_backup); + } + return read_visible_byte(ram, freezerMenu, address, screen_backup, ram_backup); + } + if (address >= 0xE000) { + if (cpu_port & 0x02) { + return read_visible_byte(ram, freezerMenu, address, screen_backup, ram_backup); + } + return raw; + } + return raw; +} + +static void write_cpu_mapped_byte(volatile uint8_t *ram, bool freezerMenu, uint32_t address, uint8_t value, uint8_t cpu_port, + uint32_t *screen_backup, uint32_t *ram_backup) { + if (address >= 0xD000 && address <= 0xDFFF && (cpu_port & 0x03) != 0x00 && (cpu_port & 0x04)) { + write_visible_byte(ram, freezerMenu, address, value, screen_backup, ram_backup); + return; + } + write_frozen_byte(ram, freezerMenu, address, value, screen_backup, ram_backup); +} + +static void copy_raw_block(volatile uint8_t *ram, bool freezerMenu, uint32_t address, uint8_t *dst, uint32_t len, + uint32_t *screen_backup, uint32_t *ram_backup) +{ + memcpy(dst, (const void *)(ram + address), len); + + if (freezerMenu) { + uint32_t overlap; + if ((address < 2048) && ((address + len) > 1024)) { + uint32_t start = (address > 1024) ? address : 1024; + uint32_t end = 2048; + overlap = address + len - start; + if (overlap > (end - start)) { + overlap = end - start; + } + memcpy(dst + (start - address), ((uint8_t *)screen_backup) + (start - 1024), overlap); + } + if ((address < 4096) && ((address + len) > 2048)) { + uint32_t start = (address > 2048) ? address : 2048; + uint32_t end = 4096; + overlap = address + len - start; + if (overlap > (end - start)) { + overlap = end - start; + } + memcpy(dst + (start - address), ((uint8_t *)ram_backup) + (start - 2048), overlap); + } + } +} + +} + +bool U64Machine :: before_memory_access(bool memOnly, bool *stopped_it) { bool freezerMenu = isFrozen; + bool wasStopped = is_stopped(); - if (!freezerMenu) { + if (stopped_it) { + *stopped_it = (!freezerMenu && !wasStopped); + } + if (!freezerMenu && !wasStopped) { stop(false); } portENTER_CRITICAL(); - C64_DMA_MEMONLY = 1; - memcpy(pb, (uint8_t *)C64_MEMORY_BASE, 65536); + C64_DMA_MEMONLY = memOnly ? 1 : 0; + return freezerMenu; +} + +void U64Machine :: after_memory_access(uint8_t *pb, bool freezerMenu, bool stopped_it) { C64_DMA_MEMONLY = 0; portEXIT_CRITICAL(); - - if (!freezerMenu) { + if (!freezerMenu && stopped_it) { resume(); - } else { // if we were in freezer menu, the backup of the 1K-4K RAM should be used - // restore memory + } else if (pb) { + // if we were in freezer menu, the backup of the 1K-4K RAM should be used to restore memory memcpy(pb + 1024, screen_backup, 1024); memcpy(pb + 2048, ram_backup, 2048); } } +void U64Machine :: get_all_memory(uint8_t *pb) +{ + // Match the REST C64_DMA_RAW_READ path: stop the machine and read the visible C64 aperture directly. + bool stopped_it = false; + bool freezerMenu = before_memory_access(false, &stopped_it); + memcpy(pb, (uint8_t *)C64_MEMORY_BASE, 65536); + after_memory_access(pb, freezerMenu, stopped_it); +} + +void U64Machine :: read_block(uint16_t address, uint8_t *dst, uint32_t len) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(isFrozen, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + + copy_raw_block(ram, freezerMenu, address, dst, len, screen_backup, ram_backup); + + after_memory_access(0, freezerMenu, stopped_it); +} + +void U64Machine :: read_cpu_block(uint16_t address, uint8_t *dst, uint32_t len, uint8_t cpu_port) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(true, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_serve = C64_SERVE_CONTROL; + uint8_t saved_ddr = 0; + uint8_t saved_port = 0; + + C64_SERVE_CONTROL = saved_serve | SERVE_WHILE_STOPPED; + override_cpu_port(ram, freezerMenu, cpu_port, &saved_ddr, &saved_port, + screen_backup, ram_backup); + for (uint32_t offset = 0; offset < len; offset++) { + dst[offset] = read_cpu_mapped_byte(ram, freezerMenu, + (uint16_t)(address + offset), + cpu_port, screen_backup, + ram_backup); + } + restore_cpu_port(ram, freezerMenu, saved_ddr, saved_port, screen_backup, + ram_backup); + C64_SERVE_CONTROL = saved_serve; + after_memory_access(0, freezerMenu, stopped_it); +} + +void U64Machine :: read_visible_block(uint16_t address, uint8_t *dst, uint32_t len) +{ + bool freezerMenu = isFrozen; + bool wasStopped = is_stopped(); + uint8_t saved_memonly = C64_DMA_MEMONLY; + if (!freezerMenu && !wasStopped) { + stop(false); + } + portENTER_CRITICAL(); + C64_DMA_MEMONLY = 0; + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_serve = C64_SERVE_CONTROL; + + C64_SERVE_CONTROL = saved_serve | SERVE_WHILE_STOPPED; + + for (uint32_t offset = 0; offset < len; offset++) { + uint32_t current = address + offset; + uint8_t byte = ram[current]; + + if (freezerMenu) { + byte = read_frozen_byte(ram, true, current, screen_backup, ram_backup); + } + dst[offset] = byte; + } + + C64_SERVE_CONTROL = saved_serve; + C64_DMA_MEMONLY = saved_memonly; + portEXIT_CRITICAL(); + + if (!freezerMenu && !wasStopped) { + resume(); + } +} + +uint8_t U64Machine :: get_cpu_port(void) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(isFrozen, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_serve = C64_SERVE_CONTROL; + + C64_SERVE_CONTROL = saved_serve | SERVE_WHILE_STOPPED; + uint8_t ddr = read_frozen_byte(ram, freezerMenu, 0x0000, screen_backup, ram_backup) & 0x07; + uint8_t port = read_frozen_byte(ram, freezerMenu, 0x0001, screen_backup, ram_backup) & 0x07; + C64_SERVE_CONTROL = saved_serve; + + after_memory_access(0, freezerMenu, stopped_it); + return (uint8_t)(((port & ddr) | ((uint8_t)(~ddr) & 0x07)) & 0x07); +} + +uint8_t U64Machine :: peek(uint16_t address) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(isFrozen, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t byte = read_frozen_byte(ram, freezerMenu, address, screen_backup, ram_backup); + + after_memory_access(0, freezerMenu, stopped_it); + return byte; +} + +uint8_t U64Machine :: peek_raw(uint16_t address) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(true, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_serve = C64_SERVE_CONTROL; + + C64_SERVE_CONTROL = saved_serve | SERVE_WHILE_STOPPED; + uint8_t byte = read_frozen_byte(ram, freezerMenu, address, screen_backup, ram_backup); + C64_SERVE_CONTROL = saved_serve; + + after_memory_access(0, freezerMenu, stopped_it); + return byte; +} + +uint8_t U64Machine :: peek_cpu(uint16_t address, uint8_t cpu_port) +{ + uint8_t byte = 0; + read_cpu_block(address, &byte, 1, cpu_port); + return byte; +} + +uint8_t U64Machine :: peek_visible(uint16_t address) +{ + bool freezerMenu = isFrozen; + bool wasStopped = is_stopped(); + uint8_t saved_memonly = C64_DMA_MEMONLY; + if (!freezerMenu && !wasStopped) { + stop(false); + } + portENTER_CRITICAL(); + C64_DMA_MEMONLY = 0; + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_serve = C64_SERVE_CONTROL; + + C64_SERVE_CONTROL = saved_serve | SERVE_WHILE_STOPPED; + + uint8_t byte = ram[address]; + + if (freezerMenu) { + byte = read_frozen_byte(ram, true, address, screen_backup, ram_backup); + } + + C64_SERVE_CONTROL = saved_serve; + C64_DMA_MEMONLY = saved_memonly; + portEXIT_CRITICAL(); + + if (!freezerMenu && !wasStopped) { + resume(); + } + return byte; +} + +void U64Machine :: poke(uint16_t address, uint8_t byte) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(isFrozen, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + + write_frozen_byte(ram, freezerMenu, address, byte, screen_backup, ram_backup); + + after_memory_access(0, freezerMenu, stopped_it); +} + +void U64Machine :: poke_raw(uint16_t address, uint8_t byte) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(true, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_serve = C64_SERVE_CONTROL; + + C64_SERVE_CONTROL = saved_serve | SERVE_WHILE_STOPPED; + write_frozen_byte(ram, freezerMenu, address, byte, screen_backup, ram_backup); + C64_SERVE_CONTROL = saved_serve; + + after_memory_access(0, freezerMenu, stopped_it); +} + +void U64Machine :: poke_cpu(uint16_t address, uint8_t byte, uint8_t cpu_port) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(true, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + uint8_t saved_serve = C64_SERVE_CONTROL; + + C64_SERVE_CONTROL = saved_serve | SERVE_WHILE_STOPPED; + write_cpu_mapped_byte(ram, freezerMenu, address, byte, cpu_port, screen_backup, ram_backup); + C64_SERVE_CONTROL = saved_serve; + after_memory_access(0, freezerMenu, stopped_it); +} + +void U64Machine :: poke_visible(uint16_t address, uint8_t byte) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(false, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + + write_frozen_byte(ram, freezerMenu, address, byte, screen_backup, ram_backup); + + after_memory_access(0, freezerMenu, stopped_it); +} + +void U64Machine :: poke_visible_preserving_freeze_restore(uint16_t address, + uint8_t byte) +{ + bool stopped_it = false; + bool freezerMenu = before_memory_access(false, &stopped_it); + volatile uint8_t *ram = (volatile uint8_t *)C64_MEMORY_BASE; + + write_frozen_byte(ram, freezerMenu, address, byte, screen_backup, + ram_backup); + if (freezerMenu && address < 0x0400) { + ((uint8_t *)ram_backup)[address] = byte; + } + + after_memory_access(0, freezerMenu, stopped_it); +} + void U64Machine :: clear_ram() { #ifndef RECOVERYAPP @@ -50,4 +426,3 @@ void U64Machine :: clear_ram() } #endif } - diff --git a/software/u64/u64_machine.h b/software/u64/u64_machine.h index 3b75b3b0a..3d5a4d3a6 100644 --- a/software/u64/u64_machine.h +++ b/software/u64/u64_machine.h @@ -8,9 +8,26 @@ class U64Machine : public C64 { U64Machine() { } ~U64Machine() { } + + bool before_memory_access(bool memOnly, bool *stopped_it); + void after_memory_access(uint8_t *, bool, bool stopped_it); + void get_all_memory(uint8_t *pb); public: void clear_ram(); + uint8_t get_cpu_port(void); + uint8_t peek(uint16_t address); + uint8_t peek_raw(uint16_t address); + uint8_t peek_cpu(uint16_t address, uint8_t cpu_port); + uint8_t peek_visible(uint16_t address); + void poke(uint16_t address, uint8_t byte); + void poke_raw(uint16_t address, uint8_t byte); + void poke_cpu(uint16_t address, uint8_t byte, uint8_t cpu_port); + void poke_visible(uint16_t address, uint8_t byte); + void poke_visible_preserving_freeze_restore(uint16_t address, uint8_t byte); + void read_block(uint16_t address, uint8_t *dst, uint32_t len); + void read_cpu_block(uint16_t address, uint8_t *dst, uint32_t len, uint8_t cpu_port); + void read_visible_block(uint16_t address, uint8_t *dst, uint32_t len); friend class C64; }; diff --git a/software/userinterface/browsable.h b/software/userinterface/browsable.h index 0167407a4..d633c080f 100644 --- a/software/userinterface/browsable.h +++ b/software/userinterface/browsable.h @@ -10,13 +10,15 @@ #include "mystring.h" #include "action.h" -#include "small_printf.h" -#include "indexed_list.h" -#include "action.h" - -class Browsable -{ - bool selected; +#include "small_printf.h" +#include "indexed_list.h" +#include "action.h" + +class FileInfo; + +class Browsable +{ + bool selected; protected: bool selectable; public: @@ -59,11 +61,14 @@ class Browsable return 0; } - virtual void setSelection(bool s) { selected = s; } - virtual bool getSelection() { return selected; } - virtual bool isSelectable() { return selectable; } - virtual void allowSelectable(bool b) { selectable = b; } - virtual int getSortOrder(void) { return 0; } + virtual void setSelection(bool s) { selected = s; } + virtual bool getSelection() { return selected; } + virtual bool isSelectable() { return selectable; } + virtual void allowSelectable(bool b) { selectable = b; } + virtual FileInfo *getFileInfo() { return NULL; } + virtual bool pickAsCurrentPath() { return false; } + virtual bool isPathPickerWrapper() { return false; } + virtual int getSortOrder(void) { return 0; } static int compare_alphabetically(IndexedList*list, int a, int b) { diff --git a/software/userinterface/browsable_root.h b/software/userinterface/browsable_root.h index dbcd7cc5c..350c58575 100644 --- a/software/userinterface/browsable_root.h +++ b/software/userinterface/browsable_root.h @@ -83,6 +83,10 @@ class BrowsableDirEntry : public Browsable path->cd(info->lfname); } } +protected: + virtual Browsable *makeChildEntry(Path *parent_path, FileInfo *info, bool selectable) { + return new BrowsableDirEntry(parent_path, this, info, selectable); + } public: BrowsableDirEntry(Path *pp, Browsable *parent, FileInfo *info, bool sel) { this->info = info; @@ -109,6 +113,11 @@ class BrowsableDirEntry : public Browsable return this->info; } + FileInfo *getFileInfo() + { + return info; + } + Path *getPath(void) { return parent_path; } @@ -146,7 +155,7 @@ class BrowsableDirEntry : public Browsable if (inf->attrib & AM_DIR) { selectable = true; } - children.append(new BrowsableDirEntry(path, this, inf, selectable)); // pass ownership of the FileInfo to the browsable object + children.append(makeChildEntry(path, inf, selectable)); // pass ownership of the FileInfo to the browsable object } delete infos; // deletes the indexed list, but not the FileInfos } @@ -250,6 +259,12 @@ class BrowsableRoot : public Browsable // get parent function not implemented; there is no parent, see base class +protected: + virtual Browsable *makeChildEntry(Path *parent_path, FileInfo *info, bool selectable) { + return new BrowsableDirEntry(parent_path, this, info, selectable); + } + +public: virtual IndexedList *getSubItems(int &error) { if (children.get_elements() == 0) { IndexedList *infos = new IndexedList(8, NULL); @@ -257,7 +272,7 @@ class BrowsableRoot : public Browsable // printf("Root get sub items: get_directory of %s returned %d elements.\n", root->get_path(), infos->get_elements()); for(int i=0;iget_elements();i++) { FileInfo *inf = (*infos)[i]; - children.append(new BrowsableDirEntry(root, this, inf, true)); // pass ownership of the FileInfo to the browsable object + children.append(makeChildEntry(root, inf, true)); // pass ownership of the FileInfo to the browsable object } delete infos; // deletes the indexed list, but not the FileInfos diff --git a/software/userinterface/config_menu.cc b/software/userinterface/config_menu.cc index 4f8fbac0c..80732e0fd 100644 --- a/software/userinterface/config_menu.cc +++ b/software/userinterface/config_menu.cc @@ -8,6 +8,8 @@ extern "C" { #include "config.h" #include "config_menu.h" +int swap_interface_type(UserInterface *ui) __attribute__ ((weak)); + /************************/ /* ConfigBrowser Object */ /************************/ @@ -268,6 +270,9 @@ int ConfigBrowser :: handle_key(int c) state->refresh = true; user_interface->run_editor(helptext_ult, strlen(helptext_ult)); break; + case KEY_CTRL_I: + ret = swap_interface_type(user_interface); + break; case KEY_SPACE: // space = select case KEY_RETURN: // CR = select if(state->level==0) diff --git a/software/userinterface/context_menu.cc b/software/userinterface/context_menu.cc index 5fc04fa72..0bccf1204 100644 --- a/software/userinterface/context_menu.cc +++ b/software/userinterface/context_menu.cc @@ -12,11 +12,12 @@ ContextMenu :: ContextMenu(UserInterface *ui, TreeBrowserState *state, int initi this->when_done = when_done; if (state) contextable = state->under_cursor; - else - contextable = NULL; - - selectedAction = NULL; - context_state = e_new; + else + contextable = NULL; + + selectedAction = NULL; + pickAction = NULL; + context_state = e_new; screen = NULL; keyb = NULL; window = NULL; @@ -33,23 +34,35 @@ ContextMenu :: ContextMenu(UserInterface *ui, TreeBrowserState *state, int initi // y_offs = line above selected, relative to window // corner = line of selected, relative to window -ContextMenu :: ~ContextMenu(void) -{ - for(int i=0;iisPersistent())) { - delete act; - } +ContextMenu :: ~ContextMenu(void) +{ + if (window) { + delete window; + window = NULL; + } + for(int i=0;iisPersistent())) { + delete act; + } } } -int ContextMenu :: get_items(void) -{ - if(contextable) { - contextable->fetch_context_items(actions); - } - return actions.get_elements(); -} +int ContextMenu :: get_items(void) +{ + if(contextable) { + contextable->fetch_context_items(actions); + if (state && state->browser && state->browser->pick_mode != TreeBrowser::PICK_NONE && + state->browser->can_pick(contextable) && !contextable->pickAsCurrentPath()) { + pickAction = new Action("Select", (actionFunction_t)NULL, 0); + actions.append(pickAction); + for (int i = actions.get_elements() - 1; i > 0; i--) { + actions.swap(i, i - 1); + } + } + } + return actions.get_elements(); +} void ContextMenu :: init(Window *parwin, Keyboard *key) { @@ -103,12 +116,13 @@ void ContextMenu :: init(Window *parwin, Keyboard *key) redraw(); } -void ContextMenu :: deinit() -{ - if (window) { - window->reset_border(); - } -} +void ContextMenu :: deinit() +{ + if (window) { + delete window; + window = NULL; + } +} void ContextMenu :: help() { @@ -121,12 +135,15 @@ void ContextMenu :: help() } } -int ContextMenu :: executeSelected(const char *p) -{ - Action *act = getSelectedAction(); - if (act) { - printf("Action set was: %s\n", act->getName()); - Browsable *b = getContextable(); +int ContextMenu :: executeSelected(const char *p) +{ + Action *act = getSelectedAction(); + if (act && act == pickAction && state && state->browser) { + return state->browser->pick_current(); + } + if (act) { + printf("Action set was: %s\n", act->getName()); + Browsable *b = getContextable(); const char *filename = (b)?(b->getName()):""; SubsysCommand *cmd = new SubsysCommand(user_interface, act, p, filename); SubsysResultCode_t cmd_ret = cmd->execute(); @@ -140,22 +157,35 @@ int ContextMenu :: executeSelected(const char *p) return 0; } -int ContextMenu :: poll(int sub) -{ - int ret = 0; - int c; - - if (subContext) { - if (sub < 0) { - delete subContext; - subContext = NULL; - draw(); - return 0; - } else if (sub > 0) { - selectedAction = subContext->getSelectedAction(); - delete subContext; - subContext = NULL; - draw(); +int ContextMenu :: poll(int sub) +{ + int ret = 0; + int c; + bool use_focus_stack = !(state && state->browser && !state->browser->use_ui_focus_stack); + + if (subContext) { + if (!use_focus_stack) { + sub = subContext->poll(0); + if (!sub) { + return 0; + } + } + if (sub < 0) { + if (!use_focus_stack) { + subContext->deinit(); + } + delete subContext; + subContext = NULL; + draw(); + return 0; + } else if (sub > 0) { + selectedAction = subContext->getSelectedAction(); + if (!use_focus_stack) { + subContext->deinit(); + } + delete subContext; + subContext = NULL; + draw(); } return sub; } else if(sub < 0) { diff --git a/software/userinterface/context_menu.h b/software/userinterface/context_menu.h index cc3c0ab13..4bbbe7ce3 100644 --- a/software/userinterface/context_menu.h +++ b/software/userinterface/context_menu.h @@ -29,11 +29,12 @@ class ContextMenu : public UIObject // private functions: virtual int handle_key(int c); - UserInterface *user_interface; - TreeBrowserState *state; - Action *selectedAction; - Browsable *contextable; - ContextMenu *subContext; + UserInterface *user_interface; + TreeBrowserState *state; + Action *selectedAction; + Action *pickAction; + Browsable *contextable; + ContextMenu *subContext; Screen *screen; Window *window; diff --git a/software/userinterface/path_picker.cc b/software/userinterface/path_picker.cc new file mode 100644 index 000000000..7d5c1bb24 --- /dev/null +++ b/software/userinterface/path_picker.cc @@ -0,0 +1,616 @@ +/* + * path_picker.cc + * + * Modal path picker built on top of TreeBrowser, with text fallback. + */ +#include "path_picker.h" +#include "tree_browser.h" +#include "tree_browser_state.h" +#include "browsable_root.h" +#include "userinterface.h" +#include + +namespace { + +class PathPickerBrowsableWrapper; +static void path_picker_filter_children(IndexedList *children, + bool keep_nonfile_entries, + bool add_current_entry); +static bool path_picker_can_descend(Browsable *entry); +static bool path_picker_is_browser_key(int key); +static bool path_picker_hide_root_entry(Browsable *entry); + +static bool path_picker_is_container_extension(const char *extension) +{ + if (!extension || !extension[0]) { + return false; + } + return (strcmp(extension, "D64") == 0) || + (strcmp(extension, "D71") == 0) || + (strcmp(extension, "D81") == 0) || + (strcmp(extension, "DNP") == 0) || + (strcmp(extension, "G64") == 0) || + (strcmp(extension, "G71") == 0) || + (strcmp(extension, "T64") == 0) || + (strcmp(extension, "ISO") == 0) || + (strcmp(extension, "FAT") == 0); +} + +class PathPickerSelectFolderEntry : public Browsable +{ +public: + PathPickerSelectFolderEntry() + { + selectable = true; + } + + const char *getName() + { + return "<< Select this folder >>"; + } + + void getDisplayString(char *buffer, int width) + { + getDisplayString(buffer, width, 0); + } + + void getDisplayString(char *buffer, int width, int) + { + if (width <= 0) { + return; + } + const char *label = getName(); + int len = (int)strlen(label); + if (len > width - 1) len = width - 1; + memcpy(buffer, label, len); + buffer[len] = 0; + } + + bool pickAsCurrentPath() + { + return true; + } +}; + +class PathPickerBrowsableWrapper : public Browsable +{ + Browsable *wrapped; + +public: + PathPickerBrowsableWrapper(Browsable *entry) + : wrapped(entry) + { + selectable = entry ? entry->isSelectable() : false; + } + + ~PathPickerBrowsableWrapper() + { + delete wrapped; + } + + void setSelection(bool s) + { + if (wrapped) { + wrapped->setSelection(s); + } + } + + bool getSelection() + { + return wrapped ? wrapped->getSelection() : false; + } + + bool isSelectable() + { + return wrapped ? wrapped->isSelectable() : false; + } + + bool isPathPickerWrapper() + { + return true; + } + + void allowSelectable(bool b) + { + selectable = b; + if (wrapped) { + wrapped->allowSelectable(b); + } + } + + FileInfo *getFileInfo() + { + return wrapped ? wrapped->getFileInfo() : NULL; + } + + int getSortOrder(void) + { + return wrapped ? wrapped->getSortOrder() : 0; + } + + Browsable *getParent() + { + return wrapped ? wrapped->getParent() : NULL; + } + + const char *getName() + { + return wrapped ? wrapped->getName() : ""; + } + + void getDisplayString(char *buffer, int width) + { + if (wrapped) { + wrapped->getDisplayString(buffer, width); + } else if (width > 0) { + buffer[0] = 0; + } + } + + void getDisplayString(char *buffer, int width, int squeeze_option) + { + if (wrapped) { + wrapped->getDisplayString(buffer, width, squeeze_option); + } else if (width > 0) { + buffer[0] = 0; + } + } + + void fetch_context_items(IndexedList&items) + { + if (wrapped) { + wrapped->fetch_context_items(items); + } + } + + IndexedList *getSubItems(int &error) + { + IndexedList *list = wrapped ? wrapped->getSubItems(error) : NULL; + if (error == 0) { + path_picker_filter_children(list, false, true); + } + return list; + } +}; + +static void path_picker_filter_children(IndexedList *children, + bool keep_nonfile_entries, + bool add_current_entry) +{ + if (!children) { + return; + } + bool already_has_current = false; + for (int i = children->get_elements() - 1; i >= 0; i--) { + Browsable *entry = (*children)[i]; + if (!entry) { + continue; + } + if (entry->pickAsCurrentPath()) { + already_has_current = true; + continue; + } + FileInfo *info = entry->getFileInfo(); + if (!info) { + if (keep_nonfile_entries) { + if (!entry->isPathPickerWrapper()) { + children->replace_idx(i, new PathPickerBrowsableWrapper(entry)); + } + continue; + } + delete entry; + children->remove_idx(i); + continue; + } + if (!entry->isPathPickerWrapper()) { + children->replace_idx(i, new PathPickerBrowsableWrapper(entry)); + } + } + if (add_current_entry && !already_has_current) { + children->append(new PathPickerSelectFolderEntry()); + for (int i = children->get_elements() - 1; i > 0; i--) { + children->swap(i, i - 1); + } + } +} + +static bool path_picker_can_descend(Browsable *entry) +{ + if (!entry || entry->pickAsCurrentPath()) { + return false; + } + FileInfo *info = entry->getFileInfo(); + if (!info) { + return true; + } + if (path_picker_is_container_extension(info->extension)) { + return false; + } + return (info->attrib & AM_DIR) != 0; +} + +static bool path_picker_is_browser_key(int key) +{ + switch (key) { + case KEY_UP: + case KEY_DOWN: + case KEY_LEFT: + case KEY_RIGHT: + case KEY_PAGEUP: + case KEY_PAGEDOWN: + case KEY_HELP: + case KEY_BREAK: + case KEY_F8: + case KEY_F10: + case KEY_ESCAPE: + case KEY_SCRLOCK: + case KEY_MENU: + return true; + default: + return false; + } +} + +static bool path_picker_hide_root_entry(Browsable *entry) +{ + if (!entry) { + return false; + } + const char *name = entry->getName(); + if (!name || !name[0]) { + return false; + } + if ((strcmp(name, "ftp") == 0) || (strcmp(name, "FTP") == 0) || + (strcmp(name, "WiFi") == 0)) { + return true; + } + return (strncmp(name, "Net", 3) == 0); +} + +class PathPickerRoot : public BrowsableRoot +{ +public: + IndexedList *getSubItems(int &error) + { + IndexedList *list = BrowsableRoot::getSubItems(error); + if (error == 0) { + // Root entries are not always backed by FileInfo. The current branch + // uses network browsables there, and feature_ftp adds mounted FTP + // roots via BrowsableRoot extensions. Keep only the local filesystem + // roots in the FTP destination picker. + path_picker_filter_children(list, true, false); + for (int i = list->get_elements() - 1; i >= 0; i--) { + Browsable *entry = (*list)[i]; + if (path_picker_hide_root_entry(entry)) { + delete entry; + list->remove_idx(i); + } + } + } + return list; + } +}; + +class PathPickerTreeBrowser : public TreeBrowser +{ + Window *frame; + Keyboard *picker_keyboard; + +public: + PathPickerTreeBrowser(UserInterface *ui, Browsable *root, Window *parent, Keyboard *keyb) + : TreeBrowser(ui, root), frame(parent), picker_keyboard(keyb) {} + + void init() + { + int ox; + int oy; + + screen = frame->getScreen(); + keyb = picker_keyboard; + frame->getOffsets(ox, oy); + window = new Window(screen, ox + 1, oy + 1, frame->get_size_x() - 2, frame->get_size_y() - 4); + has_path = false; + has_border = false; + allow_exit = true; + use_ui_focus_stack = false; + pick_mode = PICK_SAVE; + state->reload(); + } + + void deinit(void) + { + if (window) { + delete window; + window = NULL; + } + } + + int handle_key(int c) + { + if (!state) { + return 0; + } + switch (c) { + case KEY_UP: + reset_quick_seek(); + state->up(1); + return 0; + case KEY_DOWN: + reset_quick_seek(); + state->down(1); + return 0; + case KEY_PAGEUP: + reset_quick_seek(); + state->up(window ? (window->get_size_y() / 2) : 1); + return 0; + case KEY_PAGEDOWN: + reset_quick_seek(); + state->down(window ? (window->get_size_y() / 2) : 1); + return 0; + case KEY_HELP: + reset_quick_seek(); + state->refresh = true; + user_interface->help(); + if (frame) { + frame->reset_border(); + frame->draw_border(); + frame->clear(); + frame->move_cursor(1, 0); + frame->output("Select destination:"); + } + if (window) { + window->clear(); + } + return 0; + case KEY_LEFT: + if (!state->previous && allow_exit) { + return MENU_CLOSE; + } + state->level_up(); + return 0; + case KEY_RIGHT: + case KEY_RETURN: + reset_quick_seek(); + if (!state->under_cursor) { + return 0; + } + if (state->under_cursor->pickAsCurrentPath()) { + return pick_current(); + } + if (path_picker_can_descend(state->under_cursor)) { + state->into2(); + } + return 0; + case KEY_BREAK: + case KEY_F8: + case KEY_F10: + case KEY_ESCAPE: + case KEY_SCRLOCK: + case KEY_MENU: + picked = false; + return MENU_CLOSE; + default: + return 0; + } + } +}; + +} // namespace + +UIPathPicker::UIPathPicker(UserInterface *ui, char *buf, int maxlen) + : UIObject(ui), edit(buf, maxlen) +{ + result_buf = buf; + result_max = maxlen; + window = NULL; + screen = NULL; + keyboard = NULL; + browser = NULL; + root = NULL; + tree_rows = 0; + tree_width = 0; + text_mode = false; +} + +UIPathPicker::~UIPathPicker() +{ + delete browser; + delete root; +} + +void UIPathPicker::init() +{ + screen = get_ui()->get_screen(); + keyboard = get_ui()->get_keyboard(); + + int sw = screen->get_size_x(); + int sh = screen->get_size_y(); + int ww = sw - 4; + int wh = sh - 4; + + if (ww < 20) ww = 20; + if (wh < 8) wh = 8; + + screen->backup(); + screen->cursor_visible(0); + window = new Window(screen, (sw - ww) / 2, (sh - wh) / 2, ww, wh); + window->clear(); + window->draw_border(); + + tree_rows = wh - 4; + tree_width = ww - 2; + + window->move_cursor(1, 0); + window->output("Select destination:"); + + root = new PathPickerRoot(); + browser = new PathPickerTreeBrowser(get_ui(), root, window, keyboard); + browser->init(); + if (result_buf && result_buf[0]) { + browser->cd(result_buf); + } + browser->checkFileManagerEvent(); + if (browser->state && browser->state->refresh) { + browser->state->do_refresh(); + } else { + browser->redraw(); + } + update_result_from_browser(); + draw_path_line(); +} + +void UIPathPicker::deinit() +{ + if (browser) { + browser->deinit(); + } + if (window) { + delete window; + window = NULL; + } + if (screen) { + screen->cursor_visible(0); + screen->restore(); + } +} + +void UIPathPicker::draw_path_line() +{ + int path_row = tree_rows + 1; + window->move_cursor(0, path_row); + window->reverse_mode(1); + window->output_length(result_buf, tree_width); + window->reverse_mode(0); +} + +void UIPathPicker::update_result_from_browser() +{ + const char *path = browser ? browser->getPath() : "/"; + strncpy(result_buf, path, result_max); + result_buf[result_max - 1] = 0; +} + +void UIPathPicker::enter_text_mode(int first_key) +{ + text_mode = true; + edit.init(window, keyboard, 0, tree_rows + 1, tree_width); + screen->cursor_visible(1); + + if (first_key >= 32 && first_key < 127) { + int len = strlen(result_buf); + if (len < result_max - 1) { + result_buf[len] = (char)first_key; + result_buf[len + 1] = 0; + } + edit.init(window, keyboard, 0, tree_rows + 1, tree_width); + } +} + +int UIPathPicker::poll(int dummy) +{ + (void)dummy; + + int raw = keyboard->getch(); + if (raw == -1) { + return 0; + } + if (raw == -2) { + screen->cursor_visible(0); + return -1; + } + int key = get_ui()->keymapper(raw, e_keymap_default); + + if (text_mode) { + if (path_picker_is_browser_key(key)) { + screen->cursor_visible(0); + text_mode = false; + if (browser && strcmp(browser->getPath(), result_buf) != 0) { + browser->cd(result_buf); + browser->checkFileManagerEvent(); + if (browser->state && browser->state->refresh) { + browser->state->do_refresh(); + } else { + browser->redraw(); + } + } + int ret = browser ? browser->handle_key(key) : 0; + if (browser && browser->state && browser->state->refresh) { + browser->state->do_refresh(); + } + update_result_from_browser(); + draw_path_line(); + if (ret == MENU_CLOSE) { + if (browser && browser->picked) { + strncpy(result_buf, browser->picked_path.c_str(), result_max); + result_buf[result_max - 1] = 0; + return 1; + } + return -1; + } + return 0; + } + + keyboard->push_head(key); + int ret = edit.poll(0); + if (ret == 1) { + screen->cursor_visible(0); + text_mode = false; + if (browser && strcmp(browser->getPath(), result_buf) != 0) { + browser->cd(result_buf); + browser->checkFileManagerEvent(); + if (browser->state && browser->state->refresh) { + browser->state->do_refresh(); + } else { + browser->redraw(); + } + } + update_result_from_browser(); + draw_path_line(); + return 0; + } + if (ret == -1) { + screen->cursor_visible(0); + text_mode = false; + update_result_from_browser(); + draw_path_line(); + if (browser) { + browser->redraw(); + } + return 0; + } + if (browser && strcmp(browser->getPath(), result_buf) != 0) { + browser->cd(result_buf); + browser->checkFileManagerEvent(); + if (browser->state && browser->state->refresh) { + browser->state->do_refresh(); + } else { + browser->redraw(); + } + edit.init(window, keyboard, 0, tree_rows + 1, tree_width); + screen->cursor_visible(1); + } + return 0; + } + if (key >= 32 && key < 127) { + enter_text_mode(key); + return 0; + } + + keyboard->push_head(raw); + int ret = browser ? browser->poll(0) : 0; + if (browser && browser->state && browser->state->refresh) { + browser->state->do_refresh(); + } + screen->cursor_visible(0); + update_result_from_browser(); + draw_path_line(); + if (ret == MENU_CLOSE) { + if (browser && browser->picked) { + strncpy(result_buf, browser->picked_path.c_str(), result_max); + result_buf[result_max - 1] = 0; + return 1; + } + return -1; + } + return 0; +} diff --git a/software/userinterface/path_picker.h b/software/userinterface/path_picker.h new file mode 100644 index 000000000..511ae18f8 --- /dev/null +++ b/software/userinterface/path_picker.h @@ -0,0 +1,48 @@ +/* + * path_picker.h + * + * Modal path picker: browse directories visually or type a path. + * Cursor keys navigate the tree; any printable key switches to text input. + */ +#ifndef PATH_PICKER_H +#define PATH_PICKER_H + +#include "ui_elements.h" + +class TreeBrowser; +class Browsable; + +class UIPathPicker : public UIObject +{ + // Result buffer (caller-owned) + char *result_buf; + int result_max; + + // UI elements + Window *window; + Screen *screen; + Keyboard *keyboard; + TreeBrowser *browser; + Browsable *root; + int tree_rows; + int tree_width; + + // Mode + bool text_mode; + UIStringEdit edit; + + // Internal helpers + void draw_path_line(void); + void enter_text_mode(int first_key); + void update_result_from_browser(void); + +public: + UIPathPicker(UserInterface *ui, char *buf, int maxlen); + ~UIPathPicker(); + + void init(); + void deinit(void); + int poll(int); +}; + +#endif diff --git a/software/userinterface/task_menu.cc b/software/userinterface/task_menu.cc index 084e05589..2d4be6c3a 100644 --- a/software/userinterface/task_menu.cc +++ b/software/userinterface/task_menu.cc @@ -1,9 +1,9 @@ #include #include "task_menu.h" #include +#include "tree_browser.h" #include "tree_browser_state.h" #include "filemanager.h" -bool TaskMenu :: actionsCreated = false; TaskMenu :: TaskMenu(UserInterface *ui, TreeBrowserState *state, Path *p) : ContextMenu(ui, state, 0, 0) { @@ -31,38 +31,12 @@ void TaskMenu :: init(Window *pwin, Keyboard *key) screen = pwin->getScreen(); keyb = key; - IndexedList *objects = ObjectWithMenu :: getObjectsWithMenu(); - - // We do this only once - if (!actionsCreated) { - for(int i=0;iget_elements();i++) { - (*objects)[i]->create_task_items(); - } - TasksCollection::sort(); - actionsCreated = true; - - // Set all actions that we collect here to persistent, so that they won't get cleaned up - IndexedList *categories = TasksCollection::getCategories(); - for (int i=0; i < categories->get_elements(); i++) { - TaskCategory *cat = (*categories)[i]; - IndexedList *catActions = cat->getActions(); - for (int j=0; j < catActions->get_elements(); j++) { - Action *a = (*catActions)[j]; - a->setPersistent(); - } - } - } - int len, max_len; int rows, size_y; bool writablePath = path ? FileManager :: getFileManager() -> is_path_writable(path) : false; + ensure_task_actions_created(writablePath); if(context_state == e_new) { - - for(int i=0;iget_elements();i++) { - (*objects)[i]->update_task_items(writablePath); // This should actually update them, according to the current state of each object - } - IndexedList *categories = TasksCollection::getCategories(); for (int i=0; i < categories->get_elements(); i++) { TaskCategory *cat = (*categories)[i]; @@ -140,7 +114,9 @@ int TaskMenu :: select_item(void) } subContext = new TaskSubMenu(user_interface, state, cat, first_selectable_sub_item, item_index); subContext->init(window, keyb); - user_interface->activate_uiobject(subContext); + if (!state || !state->browser || state->browser->use_ui_focus_stack) { + user_interface->activate_uiobject(subContext); + } return 0; } diff --git a/software/userinterface/task_menu.h b/software/userinterface/task_menu.h index 3599953d9..f00ecfd0c 100644 --- a/software/userinterface/task_menu.h +++ b/software/userinterface/task_menu.h @@ -1,6 +1,8 @@ #ifndef TASK_MENU_H #define TASK_MENU_H +#include + #include "menu.h" #include "browsable.h" #include "context_menu.h" @@ -10,7 +12,11 @@ class TreeBrowserState; class TaskMenu : public ContextMenu { - static bool actionsCreated; + static bool& task_actions_created() + { + static bool created = false; + return created; + } TreeBrowserState *state; Browsable *browsable; Path *path; @@ -18,9 +24,10 @@ class TaskMenu : public ContextMenu TaskMenu(UserInterface *ui, TreeBrowserState *state, Path *p); ~TaskMenu(void); - void init(Window *pwin, Keyboard *keyb); - int select_item(void); -}; + void init(Window *pwin, Keyboard *keyb); + int select_item(void); + static void ensure_task_actions_created(bool writablePath); +}; class TaskSubMenu : public ContextMenu { @@ -31,4 +38,31 @@ class TaskSubMenu : public ContextMenu int get_items(void); }; -#endif +inline void TaskMenu :: ensure_task_actions_created(bool writablePath) +{ + IndexedList *objects = ObjectWithMenu :: getObjectsWithMenu(); + + if (!task_actions_created()) { + for(int i=0;iget_elements();i++) { + (*objects)[i]->create_task_items(); + } + TasksCollection::sort(); + task_actions_created() = true; + + IndexedList *categories = TasksCollection::getCategories(); + for (int i=0; i < categories->get_elements(); i++) { + TaskCategory *cat = (*categories)[i]; + IndexedList *catActions = cat->getActions(); + for (int j=0; j < catActions->get_elements(); j++) { + Action *a = (*catActions)[j]; + a->setPersistent(); + } + } + } + + for(int i=0;iget_elements();i++) { + (*objects)[i]->update_task_items(writablePath); + } +} + +#endif diff --git a/software/userinterface/tasks_collection.h b/software/userinterface/tasks_collection.h index 1af01e1c4..3fd3d177f 100644 --- a/software/userinterface/tasks_collection.h +++ b/software/userinterface/tasks_collection.h @@ -27,6 +27,7 @@ class TaskCategory const char *getName(void) { return name.c_str(); } const int getOrder(void) { return sortOrder; } void append(Action *a) { actions.append(a); } + void prepend(Action *a) { actions.prepend(a); } IndexedList *getActions(void) { return &actions; } int countActive(void) { diff --git a/software/userinterface/tree_browser.cc b/software/userinterface/tree_browser.cc index 76846b7d9..cf5c17c2f 100644 --- a/software/userinterface/tree_browser.cc +++ b/software/userinterface/tree_browser.cc @@ -13,16 +13,21 @@ #include "editor.h" #include "userinterface.h" #include "browsable_root.h" -#include "keyboard_usb.h" -#include "home_directory.h" -#include "system_info.h" -#include "assembly_search.h" +#include "keyboard_usb.h" +#include "home_directory.h" +#include "system_info.h" +#include "assembly_search.h" +#include "monitor_init.h" +#include "subsys.h" #include "stream_textlog.h" extern StreamTextLog textLog; // the global log ClipBoard clipboard; // only one, and it's global and static int swap_joystick() __attribute__ ((weak)); +int swap_interface_type(UserInterface *ui) __attribute__ ((weak)); + +static const char c_help_footer_label[] = "F3=HELP"; /***********************/ /* Tree Browser Object */ @@ -47,6 +52,9 @@ TreeBrowser :: TreeBrowser(UserInterface *ui, Browsable *root) : UIObject(ui) observerQueue = new ObserverQueue("TreeBrowser"); fm->registerObserver(observerQueue); has_border = false; + use_ui_focus_stack = true; + pick_mode = PICK_NONE; + picked = false; if(!state) { state = new TreeBrowserState(root, this, 0); @@ -70,7 +78,7 @@ void TreeBrowser :: init() // call on root! this->screen = user_interface->get_screen(); this->keyb = user_interface->get_keyboard(); - screen->move_cursor(screen->get_size_x()-8, screen->get_size_y()-1); + screen->move_cursor(screen->get_size_x() - (int)strlen(c_help_footer_label) - 1, screen->get_size_y() - 1); screen->output("\eAF3=HELP\eO"); window = new Window(screen, 0, 2, screen->get_size_x(), screen->get_size_y()-3); @@ -103,8 +111,10 @@ void TreeBrowser :: context(int initial) //printf("Creating context menu for %s\n", state->under_cursor->getName()); contextMenu = new ContextMenu(user_interface, state, initial, state->selected_line); contextMenu->init(window, keyb); - user_interface->activate_uiobject(contextMenu); - // from this moment on, we loose focus.. polls will go directly to context menu! + if (use_ui_focus_stack) { + user_interface->activate_uiobject(contextMenu); + // from this moment on, we loose focus.. polls will go directly to context menu! + } } void TreeBrowser :: task_menu(void) @@ -114,8 +124,10 @@ void TreeBrowser :: task_menu(void) //printf("Creating task menu for %s\n", state->node->getName()); contextMenu = new TaskMenu(user_interface, state, path); contextMenu->init(window, keyb); - user_interface->activate_uiobject(contextMenu); - // from this moment on, we loose focus.. polls will go directly to menu! + if (use_ui_focus_stack) { + user_interface->activate_uiobject(contextMenu); + // from this moment on, we loose focus.. polls will go directly to menu! + } } void TreeBrowser :: test_editor(void) @@ -146,8 +158,17 @@ int TreeBrowser :: poll(int sub_returned) int ret = 0; if(contextMenu) { + if (!use_ui_focus_stack) { + sub_returned = contextMenu->poll(0); + if (!sub_returned) { + return 0; + } + } if(sub_returned < 0) { - delete contextMenu; + if (!use_ui_focus_stack) { + contextMenu->deinit(); + } + delete contextMenu; contextMenu = NULL; state->draw(); } else if(sub_returned > 0) { @@ -158,6 +179,9 @@ int TreeBrowser :: poll(int sub_returned) // with that immediately. state->draw(); ret = contextMenu->executeSelected(state->browser->getPath()); + if (!use_ui_focus_stack) { + contextMenu->deinit(); + } delete contextMenu; contextMenu = NULL; if (user_interface->has_focus(this)) { @@ -190,7 +214,7 @@ int TreeBrowser :: poll(int sub_returned) } if(c >= 0) { ret = handle_key(c); - if(ret < 0) { + if(ret < 0) { keyb->wait_free(); } } @@ -333,10 +357,51 @@ void TreeBrowser :: seek_char(int c) } } -int TreeBrowser :: handle_key(int c) -{ - int ret = 0; - +int TreeBrowser :: handle_key(int c) +{ + int ret = 0; + + if (pick_mode != PICK_NONE) { + switch (c) { + case KEY_RETURN: + reset_quick_seek(); + if (!state || !state->under_cursor) { + return 0; + } + if (state->under_cursor->pickAsCurrentPath()) { + return pick_current(); + } + context(0); + return 0; + case KEY_RIGHT: + reset_quick_seek(); + if (!state || !state->under_cursor) { + return 0; + } + if (state->under_cursor->pickAsCurrentPath()) { + return pick_current(); + } + state->into2(); + return 0; + case KEY_LEFT: + if (!state->previous && allow_exit) { + return MENU_CLOSE; + } + state->level_up(); + return 0; + case KEY_BREAK: + case KEY_F8: + case KEY_ESCAPE: + case KEY_F10: + case KEY_SCRLOCK: + case KEY_MENU: + picked = false; + return MENU_CLOSE; + default: + break; + } + } + switch(c) { case KEY_BREAK: // runstop ret = (allow_exit) ? MENU_CLOSE : MENU_HIDE; @@ -372,6 +437,27 @@ int TreeBrowser :: handle_key(int c) state->refresh = true; user_interface->help(); break; + case KEY_CTRL_I: + reset_quick_seek(); + ret = swap_interface_type(user_interface); + break; + case KEY_CTRL_O: + reset_quick_seek(); + state->refresh = true; + if (get_machine_monitor_task) { + TaskMenu::ensure_task_actions_created(path ? FileManager :: getFileManager()->is_path_writable(path) : false); + Action *monitorAction = get_machine_monitor_task(SUBSYSID_U64); + if (!monitorAction) { + monitorAction = get_machine_monitor_task(SUBSYSID_C64); + } + if (monitorAction) { + const char *currentPath = path ? path->get_path() : ""; + SubsysCommand *cmd = new SubsysCommand(user_interface, monitorAction, currentPath, ""); + cmd->execute(); + ret = (int)(user_interface->menu_response_to_action); + } + } + break; case KEY_CONFIG: // F2 -> config config(); break; @@ -479,7 +565,7 @@ bool TreeBrowser :: perform_quick_seek(void) int num_el = state->children->get_elements(); for(int i=0;ichildren)[i]; - if(pattern_match(quick_seek_string, t->getName(), false)) { + if(t && pattern_match(quick_seek_string, t->getName(), false)) { state->move_to_index(i); return true; } @@ -505,7 +591,7 @@ void TreeBrowser :: copy_selection(void) } if (clipboard.getNumberOfFiles() == 0) { Browsable *t = state->under_cursor; - if (t) { + if (t) { clipboard.addFile(t->getName()); } } @@ -595,8 +681,41 @@ void TreeBrowser :: cd(const char *dst) observerQueue->putEvent(new FileManagerEvent(eChangeDirectory, dst)); } -// private -void TreeBrowser :: cd_impl(const char *dst) +void TreeBrowser :: pick_result(const char *path, const char *name, bool dir_only) +{ + (void)dir_only; + picked = true; + picked_path = path ? path : ""; + picked_name = name ? name : ""; +} + +bool TreeBrowser :: can_pick(Browsable *entry) +{ + if (!entry || pick_mode == PICK_NONE) { + return false; + } + if (entry->pickAsCurrentPath()) { + return true; + } + FileInfo *info = entry->getFileInfo(); + return info && !(info->attrib & (AM_DIR | AM_VOL)); +} + +int TreeBrowser :: pick_current(void) +{ + if (!state || !state->under_cursor || !can_pick(state->under_cursor)) { + return 0; + } + if (state->under_cursor->pickAsCurrentPath()) { + pick_result(getPath(), "", true); + return MENU_CLOSE; + } + pick_result(getPath(), state->under_cursor->getName(), false); + return MENU_CLOSE; +} + +// private +void TreeBrowser :: cd_impl(const char *dst) { // get the destination path to navigate to Path *destination = fm->get_new_path("Tree Browser"); diff --git a/software/userinterface/tree_browser.h b/software/userinterface/tree_browser.h index 44c663827..c04d7efd0 100644 --- a/software/userinterface/tree_browser.h +++ b/software/userinterface/tree_browser.h @@ -53,11 +53,18 @@ class TreeBrowser : public UIObject void seek_char(int c); void cd_impl(const char *path); public: + enum PickMode { PICK_NONE = 0, PICK_LOAD = 1, PICK_SAVE = 2 }; + char quick_seek_string[MAX_SEARCH_LEN_TB]; int quick_seek_length; bool allow_exit; bool has_path; bool has_border; + bool use_ui_focus_stack; + PickMode pick_mode; + bool picked; + mstring picked_path; + mstring picked_name; FileManager *fm; UserInterface *user_interface; @@ -96,11 +103,14 @@ class TreeBrowser : public UIObject void config(void); void test_editor(void); void copy_selection(void); - void delete_selected(void); - void paste(void); - void cd(const char *path); - - void invalidate(const void *obj); + void delete_selected(void); + void paste(void); + void cd(const char *path); + bool can_pick(Browsable *entry); + int pick_current(void); + void pick_result(const char *path, const char *name, bool dir_only); + + void invalidate(const void *obj); const char *getPath(); }; #endif diff --git a/software/userinterface/ui_elements.cc b/software/userinterface/ui_elements.cc index 745b51426..eddd117da 100644 --- a/software/userinterface/ui_elements.cc +++ b/software/userinterface/ui_elements.cc @@ -21,6 +21,7 @@ UIPopup :: UIPopup(UserInterface *ui, const char *msg, uint8_t btns, int count, btns_active = 0; active_button = 0; // we can change this button_start_x = 0; + button_y = 2; window = 0; keyboard = 0; } @@ -29,9 +30,28 @@ void UIPopup :: init() { // first, determine how wide our popup needs to be int button_width = 0; - int message_width = message.length(); + int message_width = 0; + int message_lines = 1; keyboard = get_ui()->get_keyboard(); Screen *screen = get_ui()->get_screen(); + const char *msg = message.c_str(); + + int current_line_width = 0; + while (*msg) { + if (*msg == '\n') { + if (current_line_width > message_width) { + message_width = current_line_width; + } + current_line_width = 0; + message_lines++; + } else if (*msg != '\r') { + current_line_width++; + } + msg++; + } + if (current_line_width > message_width) { + message_width = current_line_width; + } uint8_t b = buttons; for(int i=0;i message_width) window_width = button_width; + int window_height = message_lines + 4; + int x1 = (screen->get_size_x() - window_width) / 2; - int y1 = (screen->get_size_y() - 5) / 2; - int x_m = (window_width - message_width) / 2; + int y1 = (screen->get_size_y() - window_height) / 2; int x_b = (window_width - button_width) / 2; button_start_x = x_b; + button_y = message_lines + 1; screen->backup(); - window = new Window(screen, x1, y1, window_width+2, 5); + window = new Window(screen, x1, y1, window_width+2, window_height); window->clear(); window->draw_border(); // window->no_scroll(); - window->move_cursor(x_m, 0); window->set_color(get_ui()->color_fg); - window->output(message.c_str()); + msg = message.c_str(); + int row = 0; + while (1) { + const char *line_end = msg; + while (*line_end && *line_end != '\n' && *line_end != '\r') { + line_end++; + } + int line_len = line_end - msg; + int x_m = (window_width - line_len) / 2; + window->move_cursor(x_m, row); + for (int i = 0; i < line_len; i++) { + window->output(msg[i]); + } + if (!*line_end) { + break; + } + while (*line_end == '\n' || *line_end == '\r') { + line_end++; + } + msg = line_end; + row++; + } active_button = 0; // we can change this keyboard->wait_free(); @@ -68,7 +110,7 @@ void UIPopup :: init() void UIPopup :: draw_buttons() { - window->move_cursor(button_start_x, 2); + window->move_cursor(button_start_x, button_y); int j=0; int b = buttons; for(int i=0;i max_len) { - buffer[cur]=0; + buffer[max_len]=0; cur = max_len; } len = cur; -/// Default to old string - if (len > (max_chars-1)) { + if (template_mode) { + cur = 0; + edit_offs = 0; + clear_template_on_input = (len > 0); + } else if (len > (max_chars-1)) { edit_offs = 1 + len - max_chars; } window->output_length(buffer+edit_offs, (len < max_chars)?len : max_chars); @@ -220,6 +268,28 @@ int UIStringEdit :: poll(int dummy) if (key == -2) // error return -1; + if (clear_template_on_input) { + if ((key >= 32) && (key < 127)) { + buffer[0] = 0; + len = 0; + cur = 0; + edit_offs = 0; + window->move_cursor(win_xoffs, win_yoffs); + window->repeat(' ', max_chars); + window->move_cursor(win_xoffs, win_yoffs); + clear_template_on_input = false; + } else if (key == KEY_CLEAR || key == KEY_DELETE) { + buffer[0] = 0; + len = 0; + cur = 0; + edit_offs = 0; + window->move_cursor(win_xoffs, win_yoffs); + window->repeat(' ', max_chars); + window->move_cursor(win_xoffs, win_yoffs); + clear_template_on_input = false; + } + } + switch(key) { case KEY_RETURN: // CR buffer[len] = 0; @@ -275,6 +345,7 @@ int UIStringEdit :: poll(int dummy) len = 0; cur = 0; edit_offs = 0; + clear_template_on_input = false; window->move_cursor(win_xoffs, win_yoffs); window->output_length(buffer+cur, max_chars+edit_offs-cur); window->move_cursor(win_xoffs, win_yoffs); @@ -320,6 +391,10 @@ int UIStringEdit :: poll(int dummy) printf("Unhandled key: %d\n", key); break; } + if (uppercase && key >= 'a' && key <= 'z') { + key = key - 'a' + 'A'; + } + clear_template_on_input = false; if (len < max_len) { for(i=len; i>=cur; i--) { // insert if necessary buffer[i+1] = buffer[i]; diff --git a/software/userinterface/ui_elements.h b/software/userinterface/ui_elements.h index 44572ab82..3afb51e6a 100644 --- a/software/userinterface/ui_elements.h +++ b/software/userinterface/ui_elements.h @@ -57,6 +57,7 @@ class UIPopup : public UIObject int btns_active; int active_button; int button_start_x; + int button_y; Window *window; Keyboard *keyboard; const char **button_names; @@ -89,13 +90,17 @@ class UIStringEdit // destination int max_len; char *buffer; + bool template_mode; + bool clear_template_on_input; + bool uppercase; public: - UIStringEdit(char *buf, int max); + UIStringEdit(char *buf, int max, bool template_mode = false); ~UIStringEdit() { } void init(Window *win, Keyboard *keyb, int x_offs, int y_offs, int max_chars); int poll(int); int get_max_len() { return max_len; } + void set_uppercase(bool b) { uppercase = b; } }; class UIStringBox : public UIObject @@ -105,12 +110,13 @@ class UIStringBox : public UIObject UIStringEdit edit; Window *window; public: - UIStringBox(UserInterface *ui, const char *msg, char *buf, int max); + UIStringBox(UserInterface *ui, const char *msg, char *buf, int max, bool template_mode = false); ~UIStringBox() { } void init(); void deinit(void); int poll(int a) { return edit.poll(a); } + void set_uppercase(bool b) { edit.set_uppercase(b); } }; class UIStatusBox : public UIObject diff --git a/software/userinterface/userinterface.cc b/software/userinterface/userinterface.cc index e7521b916..219632d09 100644 --- a/software/userinterface/userinterface.cc +++ b/software/userinterface/userinterface.cc @@ -1,6 +1,11 @@ #include "userinterface.h" #include +#if !defined(RUNS_ON_PC) && !defined(RECOVERYAPP) +#include "c64.h" +#include "subsys.h" +#endif + #ifndef NO_FILE_ACCESS #include "FreeRTOS.h" #include "task.h" @@ -33,6 +38,22 @@ volatile int active_user_interface_count = 0; } +int swap_interface_type(UserInterface *ui) +{ + if (!ui || !ui->cfg) { + return MENU_NOP; + } + + ConfigItem *item = ui->cfg->find_item(CFG_USERIF_ITYPE); + if (!item) { + return MENU_NOP; + } + + item->setValue(1 - item->getValue()); + ui->cfg->write(); + return MENU_HIDE; +} + extern "C" void u64_dispatch_usb_hid_status_refresh(void) __attribute__((weak)); /* Help */ @@ -127,6 +148,7 @@ UserInterface :: UserInterface(const char *title, bool use_logo) : title(title) host = NULL; keyboard = NULL; screen = NULL; + active_machine_monitor = NULL; doBreak = false; available = false; color_sel_bg = 0; @@ -291,6 +313,7 @@ void UserInterface :: run_once(void) } host->take_ownership(this); + menu_response_to_action = MENU_NOP; if (!host->is_permanent()) { appear(); } @@ -388,6 +411,17 @@ void UserInterface :: send_keystroke(int key) } } +bool UserInterface :: handle_global_reset_shortcut(void) +{ + menu_response_to_action = MENU_EXIT; + doBreak = true; +#if !defined(RUNS_ON_PC) && !defined(RECOVERYAPP) + SubsysCommand *cmd = new SubsysCommand(this, SUBSYSID_C64, MENU_C64_RESET, 0, NULL, 0); + cmd->execute(); +#endif + return true; +} + int UserInterface :: pollInactive(void) { return ui_objects[focus]->poll_inactive(); @@ -542,6 +576,9 @@ int UserInterface :: popup(const char *msg, uint8_t flags) ret = pop->poll(0); } pop->deinit(); + if ((ret > 0) && keyboard) { + keyboard->wait_free(); + } delete pop; return ret; } @@ -555,13 +592,27 @@ int UserInterface :: popup(const char *msg, int count, const char **names, cons ret = pop->poll(0); } pop->deinit(); + if ((ret > 0) && keyboard) { + keyboard->wait_free(); + } delete pop; return ret; } int UserInterface :: string_box(const char *msg, char *buffer, int maxlen) { - UIStringBox *box = new UIStringBox(this, msg, buffer, maxlen); + return string_box(msg, buffer, maxlen, false); +} + +int UserInterface :: string_box(const char *msg, char *buffer, int maxlen, bool template_mode) +{ + return string_box(msg, buffer, maxlen, template_mode, false); +} + +int UserInterface :: string_box(const char *msg, char *buffer, int maxlen, bool template_mode, bool uppercase) +{ + UIStringBox *box = new UIStringBox(this, msg, buffer, maxlen, template_mode); + box->set_uppercase(uppercase); box->init(); screen->cursor_visible(1); int ret = 0; @@ -674,7 +725,10 @@ mstring *UserInterface :: getMessage(void) int UserInterface :: keymapper(int c, keymap_options_t map) { - if (navmode == 1) { // WASD cursors enabled + if ((map != e_keymap_monitor) && (c == KEY_CTRL_X) && handle_global_reset_shortcut()) { + return -2; + } + if ((navmode == 1) && (map != e_keymap_monitor)) { // WASD cursors enabled if (c >= 'A' && c <= 'Z') { c |= 0x20; // make uppercase lowercase } else { diff --git a/software/userinterface/userinterface.h b/software/userinterface/userinterface.h index 78d554ab7..49cf848f2 100644 --- a/software/userinterface/userinterface.h +++ b/software/userinterface/userinterface.h @@ -46,6 +46,7 @@ typedef enum { e_keymap_default, + e_keymap_monitor, } keymap_options_t; @@ -54,6 +55,9 @@ typedef enum { class Editor; class HexEditor; +class MemoryBackend; +class MachineMonitor; +extern "C" bool machine_monitor_request_reset_reentry(void *) __attribute__((weak)); class UserInterface : public ConfigurableObject, public HostClient { private: @@ -66,8 +70,8 @@ class UserInterface : public ConfigurableObject, public HostClient mstring title; UIObject *ui_objects[MAX_UI_OBJECTS]; UIStatusBox *status_box; + MachineMonitor *active_machine_monitor; - void set_screen_title(void); void set_available(bool enable); int pollFocussed(void); void peel_off(void); @@ -76,6 +80,11 @@ class UserInterface : public ConfigurableObject, public HostClient public: int color_border, color_bg, color_fg, color_sel, color_sel_bg, reverse_sel; int color_status, color_inactive; + // Clears the screen and draws the title and chrome rows (title bar, border + // lines). Called on initial UI bring-up and may be called by UI objects + // that need to restore the chrome after temporarily clobbering it (e.g. + // after a freeze-mode debug step that restored the live C64 screen). + void set_screen_title(void); int config_save, filename_overflow_squeeze, navmode; bool logo; @@ -90,6 +99,11 @@ class UserInterface : public ConfigurableObject, public HostClient // from HostClient virtual void release_host(); + virtual bool request_reset_reentry_after_c64_reset() + { + return machine_monitor_request_reset_reentry ? + machine_monitor_request_reset_reentry(active_machine_monitor) : false; + } virtual bool is_available(void); virtual void run(); @@ -100,6 +114,8 @@ class UserInterface : public ConfigurableObject, public HostClient virtual int popup(const char *msg, int count, const char **names, const char *keys); // blocking, custom virtual int choice(const char *msg, const char **choices, int count); virtual int string_box(const char *msg, char *buffer, int maxlen); // blocking + virtual int string_box(const char *msg, char *buffer, int maxlen, bool template_mode); // blocking + virtual int string_box(const char *msg, char *buffer, int maxlen, bool template_mode, bool uppercase); // blocking virtual int string_edit(char *buffer, int maxlen, Window *w, int x, int y); virtual void show_progress(const char *msg, int steps); // not blocking virtual void update_progress(const char *msg, int steps); // not blocking @@ -119,8 +135,10 @@ class UserInterface : public ConfigurableObject, public HostClient void help(); void run_editor(const char *, int); void run_hex_editor(const char *, int); + void run_machine_monitor(MemoryBackend *backend); void swapDisk(void); void send_keystroke(int key); + bool handle_global_reset_shortcut(void); static bool anyMenuActive(void); UIObject *get_root_object(void) { return ui_objects[0]; } diff --git a/target/common/environment.mk b/target/common/environment.mk index a39853a5b..8e3ce97e0 100644 --- a/target/common/environment.mk +++ b/target/common/environment.mk @@ -49,6 +49,7 @@ VPATH = $(PATH_SW)/application \ $(PATH_SW)/components \ $(PATH_SW)/network \ $(PATH_SW)/userinterface \ + $(PATH_SW)/monitor \ $(PATH_SW)/io/stream \ $(PATH_SW)/io/c64 \ $(PATH_SW)/io/rtc \ @@ -104,4 +105,3 @@ OBJCOPY = $(CROSS)objcopy SIZE = $(CROSS)size .SUFFIXES: - diff --git a/target/pc/linux/machinemonitortest/Makefile b/target/pc/linux/machinemonitortest/Makefile new file mode 100644 index 000000000..ecd474f50 --- /dev/null +++ b/target/pc/linux/machinemonitortest/Makefile @@ -0,0 +1,87 @@ +SUITES := machinemonitortest machinemonitorbookmarkstest machinemonitordebugtest + +ifeq ($(SUITE),) + +.PHONY: all clean $(SUITES) + +all: $(SUITES) + +$(SUITES): + @$(MAKE) SUITE=$@ all + +clean: + @rm -rf output result + +else + +PRJ = $(SUITE) +FINAL = $(RESULT)/$(PRJ) +OUTPUT = output/$(SUITE) +RESULT = result + +include ../../../common/environment.mk + +VPATH += $(PATH_SW)/test/monitor + +CROSS = +CC = $(CROSS)gcc +CPP = $(CROSS)g++ +LD = $(CROSS)ld +OBJDUMP = $(CROSS)objdump +OBJCOPY = $(CROSS)objcopy +SIZE = $(CROSS)size + +.SUFFIXES: + +SRCS_C = dump_hex.c + +COMMON_SRCS_CC = small_printf.cc \ + mystring.cc \ + screen.cc \ + ui_elements.cc \ + monitor_bookmarks.cc \ + monitor_breakpoints.cc \ + monitor_debug.cc \ + monitor_debug_predictor.cc \ + machine_monitor.cc \ + disassembler_6502.cc \ + assembler_6502.cc \ + machine_monitor_test_support.cc + +ifeq ($(SUITE),machinemonitortest) +SRCS_CC = $(COMMON_SRCS_CC) \ + machine_monitor_test.cc +OPTIONS = -g -ffunction-sections -O0 -DRUNS_ON_PC -Wno-format -Wno-format-extra-args +else ifeq ($(SUITE),machinemonitorbookmarkstest) +SRCS_CC = $(COMMON_SRCS_CC) \ + keyboard_c64.cc \ + machine_monitor_bookmarks_test.cc +OPTIONS = -g -ffunction-sections -O0 -DNO_FILE_ACCESS -Wno-format -Wno-format-extra-args +else ifeq ($(SUITE),machinemonitordebugtest) +SRCS_CC = $(COMMON_SRCS_CC) \ + monitor_debug_brk_session.cc \ + machine_monitor_debug_test.cc +OPTIONS = -g -ffunction-sections -O0 -DRUNS_ON_PC -Wno-format -Wno-format-extra-args +else +$(error Unknown SUITE '$(SUITE)') +endif + +SRCS_ASM = +SRCS_6502 = +SRCS_BIN = +SRCS_IEC = +SRCS_NANO = + +PATH_INC = $(addprefix -I, $(VPATH)) +COPTIONS = $(OPTIONS) -std=c99 +CPPOPT = $(OPTIONS) -fno-exceptions -fno-rtti -fno-threadsafe-statics +LIBS = -lgcc +LFLAGS = --gc-sections + +include ../../../common/rules.mk + +$(RESULT)/$(PRJ): $(OBJS_C) $(OBJS_CC) $(OBJS_ASM) $(OBJS_6502) $(OBJS_BIN) $(OBJS_IEC) $(OBJS_NANO) + @echo Linking... + $(CPP) $(ALL_OBJS) $(LLIB) -o $(RESULT)/$(PRJ) $(LIBS) + +endif diff --git a/target/u2/riscv/ultimate/Makefile b/target/u2/riscv/ultimate/Makefile index b5bab7441..895255cee 100755 --- a/target/u2/riscv/ultimate/Makefile +++ b/target/u2/riscv/ultimate/Makefile @@ -89,7 +89,9 @@ SRCS_CC = small_printf.cc \ sdcard_manager.cc \ size_str.cc \ userinterface.cc \ + run_machine_monitor.cc \ ui_elements.cc \ + path_picker.cc \ user_file_interaction.cc \ editor.cc \ hex_editor.cc \ @@ -98,6 +100,18 @@ SRCS_CC = small_printf.cc \ config_menu.cc \ context_menu.cc \ task_menu.cc \ + monitor_init.cc \ + monitor_file_io.cc \ + monitor_bookmarks.cc \ + monitor_breakpoints.cc \ + monitor_debug.cc \ + monitor_debug_brk_session.cc \ + monitor_debug_predictor.cc \ + machine_monitor.cc \ + disassembler_6502.cc \ + assembler_6502.cc \ + u2_memory_backend.cc \ + monitor_debug_u2.cc \ audio_select.cc \ filetype_d64.cc \ filetype_g64.cc \ diff --git a/target/u2plus/nios/ultimate/Makefile b/target/u2plus/nios/ultimate/Makefile index a2e66caa2..5af3b60f4 100755 --- a/target/u2plus/nios/ultimate/Makefile +++ b/target/u2plus/nios/ultimate/Makefile @@ -90,7 +90,9 @@ SRCS_CC = u2p_init.cc \ filesystem_fat.cc \ size_str.cc \ userinterface.cc \ + run_machine_monitor.cc \ ui_elements.cc \ + path_picker.cc \ user_file_interaction.cc \ editor.cc \ hex_editor.cc \ @@ -99,6 +101,18 @@ SRCS_CC = u2p_init.cc \ config_menu.cc \ context_menu.cc \ task_menu.cc \ + monitor_init.cc \ + monitor_file_io.cc \ + monitor_bookmarks.cc \ + monitor_breakpoints.cc \ + monitor_debug.cc \ + monitor_debug_brk_session.cc \ + monitor_debug_predictor.cc \ + machine_monitor.cc \ + disassembler_6502.cc \ + assembler_6502.cc \ + u2_memory_backend.cc \ + monitor_debug_u2.cc \ audio_select.cc \ filetype_d64.cc \ filetype_g64.cc \ diff --git a/target/u2plus_L/riscv/ultimate/Makefile b/target/u2plus_L/riscv/ultimate/Makefile index a35e7eae8..54850811c 100755 --- a/target/u2plus_L/riscv/ultimate/Makefile +++ b/target/u2plus_L/riscv/ultimate/Makefile @@ -92,7 +92,9 @@ SRCS_CC = u2pl_init.cc \ filesystem_fat.cc \ size_str.cc \ userinterface.cc \ + run_machine_monitor.cc \ ui_elements.cc \ + path_picker.cc \ user_file_interaction.cc \ editor.cc \ hex_editor.cc \ @@ -101,6 +103,18 @@ SRCS_CC = u2pl_init.cc \ config_menu.cc \ context_menu.cc \ task_menu.cc \ + monitor_init.cc \ + monitor_file_io.cc \ + monitor_bookmarks.cc \ + monitor_breakpoints.cc \ + monitor_debug.cc \ + monitor_debug_brk_session.cc \ + monitor_debug_predictor.cc \ + machine_monitor.cc \ + disassembler_6502.cc \ + assembler_6502.cc \ + u2_memory_backend.cc \ + monitor_debug_u2.cc \ audio_select.cc \ filetype_d64.cc \ filetype_g64.cc \ diff --git a/target/u64/nios2/ultimate/Makefile b/target/u64/nios2/ultimate/Makefile index 1543dd5c8..b2f28d9c9 100755 --- a/target/u64/nios2/ultimate/Makefile +++ b/target/u64/nios2/ultimate/Makefile @@ -68,6 +68,7 @@ SRCS_CC = u2p_init.cc \ c64.cc \ c64_crt.cc \ u64_machine.cc \ + u64_memory_backend.cc \ c64_subsys.cc \ screen.cc \ keyboard_c64.cc \ @@ -95,6 +96,7 @@ SRCS_CC = u2p_init.cc \ filesystem_fat.cc \ size_str.cc \ userinterface.cc \ + run_machine_monitor.cc \ ui_elements.cc \ user_file_interaction.cc \ editor.cc \ @@ -104,6 +106,17 @@ SRCS_CC = u2p_init.cc \ config_menu.cc \ context_menu.cc \ task_menu.cc \ + monitor_init.cc \ + monitor_file_io.cc \ + monitor_bookmarks.cc \ + monitor_breakpoints.cc \ + monitor_debug.cc \ + monitor_debug_brk_session.cc \ + monitor_debug_u64.cc \ + monitor_debug_predictor.cc \ + machine_monitor.cc \ + disassembler_6502.cc \ + assembler_6502.cc \ filetype_d64.cc \ filetype_g64.cc \ filetype_t64.cc \ @@ -145,6 +158,7 @@ SRCS_CC = u2p_init.cc \ socket_dma.cc \ syslog.cc \ home_directory.cc \ + path_picker.cc \ reu_preloader.cc \ color_timings.cc \ hdmi_scan.cc \ diff --git a/target/u64/riscv/ultimate/Makefile b/target/u64/riscv/ultimate/Makefile index 2e613adf9..0d10468ed 100755 --- a/target/u64/riscv/ultimate/Makefile +++ b/target/u64/riscv/ultimate/Makefile @@ -62,6 +62,9 @@ SRCS_CC = u2p_init.cc \ c64.cc \ c64_crt.cc \ u64_machine.cc \ + u64_memory_backend.cc \ + monitor_debug_brk_session.cc \ + monitor_debug_u64.cc \ c64_subsys.cc \ screen.cc \ keyboard_c64.cc \ @@ -90,6 +93,7 @@ SRCS_CC = u2p_init.cc \ size_str.cc \ userinterface.cc \ ui_elements.cc \ + path_picker.cc \ user_file_interaction.cc \ editor.cc \ hex_editor.cc \ @@ -98,6 +102,15 @@ SRCS_CC = u2p_init.cc \ config_menu.cc \ context_menu.cc \ task_menu.cc \ + monitor_init.cc \ + monitor_file_io.cc \ + monitor_bookmarks.cc \ + monitor_breakpoints.cc \ + monitor_debug.cc \ + monitor_debug_predictor.cc \ + machine_monitor.cc \ + disassembler_6502.cc \ + assembler_6502.cc \ filetype_d64.cc \ filetype_g64.cc \ filetype_t64.cc \ diff --git a/target/u64ii/riscv/ultimate/Makefile b/target/u64ii/riscv/ultimate/Makefile index d9bd85b4f..b3d5684f9 100755 --- a/target/u64ii/riscv/ultimate/Makefile +++ b/target/u64ii/riscv/ultimate/Makefile @@ -71,6 +71,9 @@ SRCS_CC = u64ii_init.cc \ c64.cc \ c64_crt.cc \ u64_machine.cc \ + u64_memory_backend.cc \ + monitor_debug_brk_session.cc \ + monitor_debug_u64.cc \ c64_subsys.cc \ screen.cc \ keyboard_c64.cc \ @@ -101,7 +104,9 @@ SRCS_CC = u64ii_init.cc \ sdcard_manager.cc \ size_str.cc \ userinterface.cc \ + run_machine_monitor.cc \ ui_elements.cc \ + path_picker.cc \ user_file_interaction.cc \ editor.cc \ hex_editor.cc \ @@ -110,6 +115,15 @@ SRCS_CC = u64ii_init.cc \ config_menu.cc \ context_menu.cc \ task_menu.cc \ + monitor_init.cc \ + monitor_file_io.cc \ + monitor_bookmarks.cc \ + monitor_breakpoints.cc \ + monitor_debug.cc \ + monitor_debug_predictor.cc \ + machine_monitor.cc \ + disassembler_6502.cc \ + assembler_6502.cc \ filetype_d64.cc \ filetype_g64.cc \ filetype_t64.cc \ diff --git a/tools/developer/machine-code-monitor/README.md b/tools/developer/machine-code-monitor/README.md new file mode 100644 index 000000000..cb756e3ac --- /dev/null +++ b/tools/developer/machine-code-monitor/README.md @@ -0,0 +1,70 @@ +# Monitor Telnet Validation + +This directory contains the real-device machine monitor validation harness. + +## Service + +The firmware exposes the machine monitor through the standard telnet session on port `23`. +The validation harness connects to the normal remote-menu session and enters the monitor with `Ctrl+O`. + +## Run + +```bash +python3 tools/developer/machine-code-monitor/monitor_test.py --host u64 --port 23 +python3 tools/developer/machine-code-monitor/monitor_debug_test.py --host u64 --port 23 +python3 tools/developer/machine-code-monitor/monitor_debug_soak.py --host u64 --port 23 --duration 600 --copy-roms-to-ram --yes-copy-roms +``` + +For U2 cartridge hardware (no monitor-side CPU/VIC bank selection, no KERNAL +ROM snapshot in the monitor view) pass `--target u2`. The U2 firmware does +ship the same `v1/machine` REST API as U64, so REST-backed helpers continue +to work; the harness only skips when the API is genuinely unreachable. The +harness automatically enables keep-going mode in `u2` so every failure is +logged with full context (last command, terminal snapshot, exception type) +and the run continues. The end-of-run summary lists every skipped and failed +check so a remote operator can capture the entire console output and hand it +to an LLM for autonomous fixes: + +```bash +python3 tools/developer/machine-code-monitor/monitor_test.py --host --port 23 --target u2 +python3 tools/developer/machine-code-monitor/monitor_debug_test.py --host --port 23 --target u2 +``` + +Use `--keep-going` to enable the same behavior on U64 (useful for capturing +multiple regressions in one run rather than stopping at the first). + +Optional environment variables: + +- `U64_MONITOR_HOST` +- `U64_MONITOR_PORT` +- `U64_MONITOR_REST_HOST` +- `U64_MONITOR_PASSWORD` +- `U64_MONITOR_TIMEOUT` +- `U64_MONITOR_TARGET` (`u64` or `u2`) +- `U64_MONITOR_KEEP_GOING` (`1` to default-enable keep-going) + +## What It Checks + +- KERNAL memory visibility at `$E000` +- REST `v1/machine:readmem` consistency with monitor KERNAL bytes +- Disassembly byte-width formatting +- Screen stability after scrolling away and back +- ASCII row width +- Immediate inline edit visibility and commit +- Cursor vs scroll behavior in ASCII view +- CPU bank status changes and RAM-visible writes at `$A000` +- Combined CPU/VIC status line format +- Repeated finite `G 0810` execution using `LDA #$NN / STA $2000 / BRK` +- `G 0810` preserving visible VIC state while a finite `INC $D021 / BRK` program runs +- Bookmark jumping restoring memory-view width `16` +- Binary width cycling through `1 -> 2 -> 3 -> 3S -> 4` and bookmark restoration of width `4` +- Debug mode routing, footer layout, breakpoints, stepping, cleanup, and preserved Assembly navigation/bookmark shortcuts +- Debug soak coverage against BASIC/KERNAL ROM copies in RAM, with every supported step checked against an independent footer-state model + +The harness parses the VT100 telnet stream into a deterministic `40x25` screen buffer and compares the captured output against the expected snapshot fragments in `snapshots/expected_snapshots.json`. + +`monitor_debug_soak.py` is destructive: `--copy-roms-to-ram --yes-copy-roms` copies BASIC `$A000-$BFFF` and KERNAL `$E000-$FFFF` into the RAM underneath those ROM windows and forces the live C64 CPU port into all-RAM mode while it runs. Use `--yes-copy-roms` only on a disposable test session. + +The U64 debugger firmware additionally supports breakpoints in volatile U64 ROM +image memory (no flash writes, restored on reboot), so non-soak debug sessions +can step KERNAL/BASIC/CHAR ROM without the destructive RAM-shadow step. diff --git a/tools/developer/machine-code-monitor/issue_repro.py b/tools/developer/machine-code-monitor/issue_repro.py new file mode 100644 index 000000000..14b03cdc2 --- /dev/null +++ b/tools/developer/machine-code-monitor/issue_repro.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Focused real-device repros for the four current monitor merge blockers. + +Autonomous control/observation only (no human keypress/screen reading): + - key injection POST /v1/machine:input_ui + - RAM side effects GET/PUT /v1/machine:readmem|writemem + - UI text PUT /v1/machine:dump_ui_screen + textlog (logical frame) + - interface mode REST config (get/set Interface Type) + - liveness GET /v1/version, get_interface_type + +Each case prints a single PASS/FAIL line plus the evidence it used. +Run: python3 issue_repro.py --host u64 --case issue2-freeze +""" +import argparse +import sys +import time +import urllib.error + +import monitor_direct_test as mdt + + +def log(msg): + print(msg, flush=True) + + +OTHER = {"Freeze": "Overlay on HDMI", "Overlay on HDMI": "Freeze"} + + +def to_basic(session, mode): + mdt.switch_interface_type(session, mode, f"select {mode}") + mdt.wait_interface_type(session, mode, f"select {mode}") + session.reset() + mdt.wait_basic_ready(session) + time.sleep(0.5) + + +def reachable(session, tries=6, gap=0.5): + for _ in range(tries): + try: + session.get_interface_type() + return True + except (mdt.Failure, OSError, TimeoutError, urllib.error.URLError): + time.sleep(gap) + return False + + +def ui_state(session, tag="probe"): + """Return ('closed'|'monitor'|'browser'|'other', frame_or_None).""" + try: + frame = session.dump_ui_screen(tag) + except (mdt.Failure, OSError, TimeoutError, urllib.error.URLError): + return "closed", None + txt = frame.text() + if "MONITOR" in txt: + return "monitor", frame + if mdt.visible_ui(frame): + return "browser", frame + return "other", frame + + +def enter_monitor(session, capture, ocr, mode): + if mode == "Freeze": + session.start_video() + time.sleep(0.3) + return mdt.enter_visible_monitor(session, capture, ocr) + return mdt.enter_hidden_monitor(session) + + +# -------------------------------------------------------------------------- +# Issue 2: C=+I inside the monitor must toggle the UI mode AND close the whole +# monitor + menu/browser surface (never drop the user into the file browser). +# -------------------------------------------------------------------------- +def issue2(session, capture, ocr, start_mode): + other = OTHER[start_mode] + to_basic(session, start_mode) + enter_monitor(session, capture, ocr, start_mode) + state, _ = ui_state(session, "i2-pre") + if state != "monitor": + log(f"[Issue2/{start_mode}] WARN: monitor not confirmed up (state={state}); continuing") + before = session.get_interface_type() + log(f"[Issue2/{start_mode}] monitor up; interface before C=+I = {before!r}") + + session.input_ui(["ctrl_i"]) + time.sleep(1.5) + + after = session.get_interface_type() + toggled = (after == other) + # The whole UI must be gone: poll for a stable 'closed' (no UI dump) result. + final_state = "?" + for _ in range(8): + final_state, frame = ui_state(session, "i2-post") + if final_state == "closed": + break + time.sleep(0.4) + log(f"[Issue2/{start_mode}] after C=+I: interface={after!r} toggled={toggled} " + f"ui_state={final_state}") + + # Confirm next monitor open uses the NEW mode. + next_mode_ok = False + try: + enter_monitor(session, capture, ocr, after) + st, _ = ui_state(session, "i2-reenter") + next_mode_ok = (st == "monitor") + # leave cleanly + if after == "Freeze": + session.input_ui(["ctrl_o"]) + else: + session.input_ui(["ctrl_o"]) + time.sleep(0.5) + except mdt.Failure as exc: + log(f"[Issue2/{start_mode}] re-enter in new mode raised: {exc}") + log(f"[Issue2/{start_mode}] next monitor open in {after!r} mode: monitor_up={next_mode_ok}") + + ok = toggled and final_state == "closed" and next_mode_ok + if not toggled: + log(f"[Issue2/{start_mode}] FAIL: C=+I did not toggle interface ({before!r}->{after!r}).") + if final_state == "browser": + log(f"[Issue2/{start_mode}] FAIL: file browser/menu left visible after C=+I (the bug).") + elif final_state == "monitor": + log(f"[Issue2/{start_mode}] FAIL: monitor still open after C=+I.") + log(f"[Issue2/{start_mode}] {'PASS' if ok else 'FAIL'}") + return ok + + +# -------------------------------------------------------------------------- +# Issue 1: Freeze RAM-under-ROM debug, REST reset, re-enter monitor -> the view +# must follow the live CPU bank (CPU5), decoding the RAM-under-ROM bytes, not a +# C5O7 ROM view. +# -------------------------------------------------------------------------- +def issue1(session, capture, ocr): + bootstrap = 0xC000 + payload = 0xE000 + # SEI; LDA #$35; STA $01; JMP $E000 ($35 -> low bits 5: KERNAL RAM, char ROM) + boot = bytes([0x78, 0xA9, 0x35, 0x85, 0x01, 0x4C, 0x00, 0xE0]) + # Deterministic RAM-under-ROM payload with a recognisable first opcode: + # E000 INC $0250 ; E003 INC $0251 ; E006 JMP $E006 + pay = bytes([0xEE, 0x50, 0x02, 0xEE, 0x51, 0x02, 0x4C, 0x06, 0xE0]) + + to_basic(session, "Freeze") + session.start_video() + time.sleep(0.4) + mdt.enter_visible_monitor(session, capture, ocr) + log("[Issue1] entered Freeze monitor") + + session.write_memory(payload, pay) + session.write_memory(bootstrap, boot) + session.write_memory(0x0250, bytes([0, 0])) + + # Debug-step into $E000 (under ROM): SEI, LDA, STA, JMP -> park at $E000. + mdt.send_ui_text(session, "J%04X\n" % bootstrap, settle=0.5) + mdt.send_ui_text(session, "A", settle=0.5) + mdt.send_ui_text(session, "D", settle=0.7) + for _ in range(4): + mdt.send_ui_text(session, "D", settle=0.6) + # live $01 should now be $35 (low bits 5) + live01 = session.read_memory(0x0001, 1)[0] + log(f"[Issue1] parked at $E000 under ROM; live $01={live01:#04x} (low bits {live01 & 7})") + + # REST reset, then re-enter the monitor and inspect $E000 view. + session.reset() + time.sleep(1.5) + live01_after = session.read_memory(0x0001, 1)[0] + log(f"[Issue1] after REST reset: live $01={live01_after:#04x} (low bits {live01_after & 7})") + # re-enter + mdt.enter_visible_monitor(session, capture, ocr) + mdt.send_ui_text(session, "J%04X\n" % payload, settle=0.5) + mdt.send_ui_text(session, "A", settle=0.5) + frame = mdt.wait_stable_dump = session.dump_ui_screen("i1-reentry") + line = mdt.status_line(frame) + live, mon = mdt.parse_status_banks(line) + log(f"[Issue1] re-entry status line: {line!r} (live={live} monitor={mon})") + + # The re-entered view must follow the live CPU bank (no C5O7 mismatch). If the + # live CPU genuinely returned to 7 after reset, view 7 is also coherent; the + # invariant under test is live==monitor (matched, no spurious override). + matched = (live is not None and live == mon) + # When the under-ROM program's banking persists (live low bits 5), the view + # must be 5 and the disasm must show our payload ($EE = INC), not KERNAL ROM. + txt = frame.text() + shows_payload = ("INC $0250" in txt) or ("EE 50 02" in txt) or ("E000 EE" in txt) + log(f"[Issue1] matched(view==live)={matched} shows_payload_at_E000={shows_payload}") + log(f"[Issue1] frame:\n{txt}") + ok = matched + log(f"[Issue1] {'PASS' if ok else 'FAIL'} (no C5O7 mismatch on re-entry)") + return ok + + +# -------------------------------------------------------------------------- +# Issue 3: Overlay RAM-under-ROM debug + G, then C=+X reset; device must remain +# fully responsive (REST, interface, monitor re-entry + first step). +# -------------------------------------------------------------------------- +def issue3(session, capture, ocr): + bootstrap = 0xC000 + payload = 0xE000 + # $35 exposes RAM under BASIC/KERNAL while keeping I/O visible. + boot = bytes([0x78, 0xA9, 0x35, 0x85, 0x01, 0x4C, 0x00, 0xE0]) + pay = bytes([0xEE, 0x50, 0x02, 0xEE, 0x51, 0x02, 0x4C, 0x06, 0xE0]) + + to_basic(session, "Overlay on HDMI") + mdt.enter_hidden_monitor(session) + log("[Issue3] entered Overlay monitor") + + session.write_memory(payload, pay) + session.write_memory(bootstrap, boot) + session.write_memory(0x0250, bytes([0, 0])) + + mdt.send_ui_text(session, "J%04X\n" % bootstrap, settle=0.4) + mdt.send_ui_text(session, "A", settle=0.4) + mdt.send_ui_text(session, "D", settle=0.6) + for _ in range(4): + mdt.send_ui_text(session, "D", settle=0.5) + mdt.send_ui_text(session, "D", settle=0.6) # exec INC $0250 -> (1,0) + s_step = tuple(session.read_memory(0x0250, 2)) + log(f"[Issue3] after step into under-ROM: $0250..$0251={s_step}") + mdt.send_ui_text(session, "G", settle=0.6) # continue (under ROM) + time.sleep(2.0) + s_go = tuple(session.read_memory(0x0250, 2)) + log(f"[Issue3] after Overlay G: $0250..$0251={s_go}") + + # C=+X. After the G handoff the monitor has exited; C=+X is the global reset + # shortcut. Open the root menu first so the chord routes through the global + # handler (matches the reported user flow), then inject C=+X. + try: + mdt.open_overlay_menu(session, "issue3 root", settle=0.6) + except mdt.Failure as exc: + log(f"[Issue3] open root menu before C=+X raised: {exc}") + session.input_ui(["ctrl_x"]) + time.sleep(2.5) + + # ---- Liveness battery ---- + rest_ok = reachable(session) + log(f"[Issue3] after C=+X: REST/interface reachable={rest_ok}") + # keyboard/menu input liveness: inject a key, confirm the UI/menu responds by + # opening the root menu (screen delta) OR staying reachable. + menu_ok = False + try: + frame = mdt.open_overlay_menu(session, "issue3 post-reset menu", settle=0.8) + menu_ok = mdt.visible_ui(frame) + session.input_ui(["run_stop"]) # close menu + time.sleep(0.4) + except mdt.Failure as exc: + log(f"[Issue3] post-reset menu open raised: {exc}") + log(f"[Issue3] post-reset U64 menu input responsive={menu_ok}") + + # monitor re-entry + first debug step must not hang. + session.write_memory(0x0250, bytes([0, 0])) + session.write_memory(0x02A0, bytes([0xEE, 0x50, 0x02, 0x4C, 0xA0, 0x02])) + reentry_ok = False + step_effect = None + try: + mdt.enter_hidden_monitor(session) + mdt.send_ui_text(session, "J%04X\n" % 0x02A0, settle=0.4) + mdt.send_ui_text(session, "A", settle=0.4) + mdt.send_ui_text(session, "D", settle=0.6) + mdt.send_ui_text(session, "D", settle=0.7) + step_effect = session.read_memory(0x0250, 1)[0] + reentry_ok = reachable(session) + except mdt.Failure as exc: + log(f"[Issue3] re-entry/step raised: {exc}") + log(f"[Issue3] re-entry reachable={reentry_ok} first_step_sentinel=$0250={step_effect}") + + ok = rest_ok and reentry_ok and (step_effect == 1) + if not rest_ok: + log("[Issue3] FAIL: device unreachable after C=+X (wedge reproduced).") + if not reentry_ok or step_effect != 1: + log("[Issue3] FAIL: monitor re-entry / first step hung after C=+X.") + log(f"[Issue3] {'PASS' if ok else 'FAIL'}") + return ok + + +# -------------------------------------------------------------------------- +# [43]: KERNAL ROM Step Into from $E000, run twice without redeploy. The FPGA +# KERNAL ROM image must stay pristine across REST reset + monitor re-entry; the +# 2nd step-into must reach $E001/$E002 area, never misfire to ~$0002. +# We observe the FPGA KERNAL bytes at $E000 via REST (CPU bank 7) before/after. +# -------------------------------------------------------------------------- +def rom43(session, capture, ocr): + import os + # Read pristine KERNAL bytes at $E000 (bank 7) once for reference. + to_basic(session, "Freeze") + pristine = session.read_memory(0xE000, 8) + log(f"[43] pristine KERNAL $E000..$E007 = {pristine.hex().upper()}") + + def one_run(run_idx): + session.start_video() + time.sleep(0.3) + mdt.enter_visible_monitor(session, capture, ocr) + # Step into KERNAL at $E000: jump there, ASM, Debug, Step Into (T). + mdt.send_ui_text(session, "JE000\n", settle=0.5) + mdt.send_ui_text(session, "A", settle=0.5) + mdt.send_ui_text(session, "D", settle=0.7) + mdt.send_ui_text(session, "T", settle=0.8) # step into + # read footer PC + try: + frame = session.dump_ui_screen("rom43-%d" % run_idx) + txt = frame.text() + except mdt.Failure: + txt = "" + kernal_now = session.read_memory(0xE000, 8) + stale = (kernal_now != pristine) + log(f"[43] run {run_idx}: KERNAL $E000 now={kernal_now.hex().upper()} stale={stale}") + # leave debug + monitor, reset + mdt.send_ui_text(session, "\x1b", settle=0.3) + session.input_ui(["ctrl_o"]) + time.sleep(0.4) + session.reset() + time.sleep(1.2) + return kernal_now, txt + + k1, t1 = one_run(1) + k2, t2 = one_run(2) + after2 = session.read_memory(0xE000, 8) + log(f"[43] after 2 runs: KERNAL $E000 = {after2.hex().upper()} (pristine={pristine.hex().upper()})") + healthy = (after2 == pristine) and (k1 == pristine) and (k2 == pristine) + log(f"[43] {'PASS' if healthy else 'FAIL'}: KERNAL image stayed pristine across 2 runs={healthy}") + return healthy + + +def rom43b(session, capture, ocr): + """Isolate WHERE the KERNAL ROM-image BRK leak happens. Read $E002 (the step + target after $E000=STA $56) at: pristine, parked-after-step, after a REST reset + fired WHILE PARKED, and after leaving the monitor.""" + to_basic(session, "Freeze") + pristine = session.read_memory(0xE000, 4) + log(f"[43b] pristine $E000..$E003 = {pristine.hex().upper()}") + session.start_video() + time.sleep(0.3) + mdt.enter_visible_monitor(session, capture, ocr) + mdt.send_ui_text(session, "JE000\n", settle=0.5) + mdt.send_ui_text(session, "A", settle=0.5) + mdt.send_ui_text(session, "D", settle=0.7) + mdt.send_ui_text(session, "T", settle=0.9) # step into -> park at $E002 + parked = session.read_memory(0xE000, 4) + log(f"[43b] parked-after-step $E000..$E003 = {parked.hex().upper()} " + f"($E002={parked[2]:#04x})") + + # REST reset WHILE PARKED (request_reset_cancel path, run_window_depth==0). + # The decisive wedge check: a clean reset must boot the C64 to READY, not crash + # on a leaked KERNAL BRK. Wait for the boot to settle BEFORE reading the ROM + # image (reading during the boot transient returns zeros and is misleading). + session.reset() + ready = False + try: + mdt.wait_basic_ready(session) + ready = True + except mdt.Failure: + ready = False + time.sleep(0.5) + after_reset = session.read_memory(0xE000, 4) + log(f"[43b] after parked REST reset + settle: $E000..$E003 = {after_reset.hex().upper()} " + f"($E002={after_reset[2]:#04x}) basic_ready={ready}") + leak_at_reset = (after_reset[2] != pristine[2]) + + # Boot health: jiffy clock must advance (KERNAL IRQ running). + j0 = list(session.read_memory(0x00A0, 3)) + time.sleep(1.2) + j1 = list(session.read_memory(0x00A0, 3)) + boots = (j1 != j0) + log(f"[43b] post-reset jiffy {j0}->{j1} advancing={boots}") + + ok = (not leak_at_reset) and boots and ready + log(f"[43b] {'PASS' if ok else 'FAIL'}: no stale KERNAL BRK + C64 boots " + f"(leak={leak_at_reset} boots={boots} ready={ready})") + return ok + + +def _fresh_capture(capture): + import socket as _socket + capture.sock.setblocking(False) + try: + while True: + try: + capture.sock.recv(2048) + except (BlockingIOError, _socket.error): + break + finally: + capture.sock.setblocking(True) + time.sleep(0.2) + return capture.capture_image() + + +def _readability(frame): + """A readable C64 text screen (BASIC/menu) is space-dominated with few distinct + glyphs. A CHAR-ROM-corrupted screen renders as high-entropy random glyphs: the + OCR can't match them, so spaces collapse and distinct-glyph count explodes.""" + text = "".join(frame.lines) + spaces = sum(1 for c in text if c == " ") + distinct = len(set(text)) + return spaces, distinct, len(text) + + +def issue5(session, capture, ocr): + """Freeze mode must not render the C64/menu as random PETSCII (CHAR-ROM intact).""" + to_basic(session, "Freeze") + session.start_video() + time.sleep(0.6) + ok = True + for it in range(1, 5): + # BASIC screen readability after a reset + session.reset() + try: + mdt.wait_basic_ready(session) + except mdt.Failure: + pass + time.sleep(0.6) + f = ocr.decode(_fresh_capture(capture)) + sp, dist, ln = _readability(f) + readable = (sp >= 300 and dist <= 45) + txt = f.text() + has_basic = ("BASIC" in txt) or ("READY" in txt) or ("COMMODORE" in txt) + log(f"[Issue5] it{it} BASIC: spaces={sp} distinct={dist} readable={readable} basic_text={has_basic}") + if not readable and not has_basic: + ok = False + log(f"[Issue5] it{it} FAIL: BASIC screen looks like random PETSCII:\n{txt}") + # Enter monitor and back out (exercises Freeze render + restore) + try: + mdt.enter_visible_monitor(session, capture, ocr) + f2 = ocr.decode(_fresh_capture(capture)) + sp2, dist2, _ = _readability(f2) + mon_ok = ("MONITOR" in f2.text()) or (sp2 >= 300) + log(f"[Issue5] it{it} MONITOR: spaces={sp2} distinct={dist2} readable={mon_ok}") + if not mon_ok: + ok = False + log(f"[Issue5] it{it} FAIL: monitor screen looks like random PETSCII:\n{f2.text()}") + session.input_ui(["ctrl_o"]) + time.sleep(0.5) + except mdt.Failure as exc: + log(f"[Issue5] it{it} monitor entry flaked: {exc}") + log(f"[Issue5] {'PASS' if ok else 'FAIL'}: Freeze screens readable (no random PETSCII)") + return ok + + +CASES = { + "issue5": issue5, + "rom43b": rom43b, + "issue2-freeze": lambda s, c, o: issue2(s, c, o, "Freeze"), + "issue2-overlay": lambda s, c, o: issue2(s, c, o, "Overlay on HDMI"), + "issue1": issue1, + "issue3": issue3, + "rom43": rom43, +} + + +def restore_safe_cpu_port(session, label): + session.write_memory(0x0001, bytes([0x37])) + value = session.read_memory(0x0001, 1)[0] + log(f"[cleanup/{label}] $0001 readback={value:#04x}") + if (value & 0x07) != 0x07: + raise mdt.Failure(f"cleanup failed to restore safe $0001, got {value:#04x}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--host", default="u64") + ap.add_argument("--timeout", type=float, default=5.0) + ap.add_argument("--case", required=True, choices=sorted(CASES.keys())) + args = ap.parse_args() + session = mdt.RestSession(args.host, args.timeout) + capture = mdt.VicStreamCapture() + ocr = mdt.C64FrameOCR() + ok = False + cleanup_ok = True + try: + ok = CASES[args.case](session, capture, ocr) + finally: + try: + session.stop_video() + except Exception: + pass + try: + capture.close() + except Exception: + pass + try: + restore_safe_cpu_port(session, args.case) + session.reset() + except Exception as exc: + cleanup_ok = False + log(f"[cleanup/{args.case}] FAIL: {exc}") + return 0 if ok and cleanup_ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/developer/machine-code-monitor/monitor_debug_soak.py b/tools/developer/machine-code-monitor/monitor_debug_soak.py new file mode 100755 index 000000000..c8824e29d --- /dev/null +++ b/tools/developer/machine-code-monitor/monitor_debug_soak.py @@ -0,0 +1,883 @@ +#!/usr/bin/env python3 +"""Dynamic Telnet soak test for the U64 Machine Code Monitor Debugger. + +The deterministic ``monitor_debug_test.py`` suite proves specific edge cases. +This soak test keeps a Debug session alive for a configurable duration while it +repeatedly seeds controlled CPU state, enters selected BASIC/KERNAL routines, +single-steps instructions, and compares the Debug footer against a small local +6510 model for every supported instruction. + +The soak runs against the normal ROM mapping. It deliberately does not copy +BASIC/KERNAL into underlying RAM; ROM breakpoints must use the debugger's +backend-specific writable execution/shadow representation. +""" + +from __future__ import annotations + +import argparse +import os +import random +import re +import sys +import time +import urllib.error +from dataclasses import dataclass +from pathlib import Path +from typing import Callable, Optional + +sys.path.insert(0, str(Path(__file__).parent)) +import monitor_test as mt # type: ignore # noqa: E402 +import monitor_debug_test as dbg # type: ignore # noqa: E402 + + +BOOTSTRAP_ADDR = 0xC500 +SCRATCH_ADDR = 0xC5F0 +DEFAULT_DURATION = 600.0 + +FLAG_C = 0x01 +FLAG_Z = 0x02 +FLAG_I = 0x04 +FLAG_D = 0x08 +FLAG_B = 0x10 +FLAG_V = 0x40 +FLAG_N = 0x80 + +BRANCH_TAKEN = { + "BCC": lambda sr: (sr & FLAG_C) == 0, + "BCS": lambda sr: (sr & FLAG_C) != 0, + "BEQ": lambda sr: (sr & FLAG_Z) != 0, + "BMI": lambda sr: (sr & FLAG_N) != 0, + "BNE": lambda sr: (sr & FLAG_Z) == 0, + "BPL": lambda sr: (sr & FLAG_N) == 0, + "BVC": lambda sr: (sr & FLAG_V) == 0, + "BVS": lambda sr: (sr & FLAG_V) != 0, +} + +AUTONOMOUS_TRACE_PC_SEQUENCE = ( + 0xE002, + 0xBC0F, + 0xBC11, + 0xBC13, + 0xBC15, + 0xBC16, + 0xBC11, + 0xBC13, + 0xBC15, + 0xBC16, + 0xBC11, +) + + +@dataclass(frozen=True) +class Routine: + name: str + address: int + region: str + + +# High-value entry points from the C64 BASIC/KERNAL disassembly. These are not +# all safe to run forever, so the soak restarts often and steps only while the +# local model can validate the instruction exactly. +ROUTINES = [ + Routine("BASIC END", 0xA831, "BASIC"), + Routine("BASIC FOR", 0xA742, "BASIC"), + Routine("BASIC RUN", 0xA871, "BASIC"), + Routine("BASIC GOTO", 0xA8A0, "BASIC"), + Routine("BASIC GOSUB", 0xA883, "BASIC"), + Routine("BASIC RETURN", 0xA8D2, "BASIC"), + Routine("BASIC LET", 0xA9A5, "BASIC"), + Routine("BASIC PRINT", 0xAAA0, "BASIC"), + Routine("BASIC PEEK", 0xB80D, "BASIC"), + Routine("BASIC POKE", 0xB824, "BASIC"), + Routine("KERNAL FLOAT-JSR", 0xE002, "KERNAL"), + Routine("KERNAL FLOAT-CONT", 0xE013, "KERNAL"), + Routine("KERNAL FLOAT-SEC", 0xE018, "KERNAL"), + Routine("KERNAL LOAD", 0xE168, "KERNAL"), + Routine("KERNAL SAVE", 0xE156, "KERNAL"), + Routine("KERNAL SYS", 0xE12A, "KERNAL"), +] + + +@dataclass +class CpuState: + pc: int + sp: int + ac: int + xr: int + yr: int + sr: int + + @classmethod + def from_footer(cls, session: "mt.MonitorSession") -> "CpuState": + parsed = dbg._parse_footer_values(dbg._footer_value_line(session)) + missing = [name for name in ("pc", "sp", "ac", "xr", "yr", "sr") if not parsed[name]] + if missing: + raise mt.Failure(f"Debug footer has blank fields {missing}: {parsed!r}") + return cls( + pc=int(parsed["pc"], 16), + sp=int(parsed["sp"], 16), + ac=int(parsed["ac"], 16), + xr=int(parsed["xr"], 16), + yr=int(parsed["yr"], 16), + sr=int(parsed["sr"], 2), + ) + + def footer_dict(self) -> dict[str, str]: + return { + "pc": f"{self.pc:04X}", + "sp": f"{self.sp:02X}", + "ac": f"{self.ac:02X}", + "xr": f"{self.xr:02X}", + "yr": f"{self.yr:02X}", + "sr": f"{self.sr:08b}", + } + + +def _branch_target(row: str, sr: int) -> Optional[int]: + match = re.search(r"\b(BCC|BCS|BEQ|BMI|BNE|BPL|BVC|BVS) \$([0-9A-Fa-f]{4})", row) + if not match: + return None + mnemonic = match.group(1).upper() + if not BRANCH_TAKEN[mnemonic](sr): + return None + return int(match.group(2), 16) + + +def _jump_target(row: str) -> Optional[int]: + match = re.search(r"\b(?:JMP|JSR) \$([0-9A-Fa-f]{4})", row) + if not match: + return None + return int(match.group(1), 16) + + +def _predict_trace_target(pc: int, row: str, sr: Optional[int]) -> int: + branch_target = _branch_target(row, sr) if sr is not None else None + if branch_target is not None: + return branch_target + jump_target = _jump_target(row) + if jump_target is not None: + return jump_target + return _u16(pc + dbg._instruction_length_from_row(row)) + + +def _observed_debug_pc(snapshot: mt.Snapshot) -> Optional[int]: + for y in range(mt.HEIGHT): + line = snapshot.line(y) + if "PC" in line and "SP" in line and "NV-BDIZC" in line and y + 1 < mt.HEIGHT: + parsed = dbg._parse_footer_values(snapshot.line(y + 1)) + if parsed["pc"]: + return int(parsed["pc"], 16) + break + try: + line = mt.highlighted_line(snapshot) + except mt.Failure: + return None + match = re.match(r"^\|([0-9A-Fa-f]{4})\s", line) + if not match: + return None + return int(match.group(1), 16) + + +def _wait_for_observed_pc(session: "mt.MonitorSession", expected_pc: int, + timeout: float = 6.0) -> mt.Snapshot: + deadline = time.time() + timeout + last = None + while time.time() < deadline: + snap = session.capture() + last = snap + dbg._assert_no_debug_modal_snapshot(snap, f"Waiting for observed PC {expected_pc:04X}") + actual = _observed_debug_pc(snap) + if actual == expected_pc: + return snap + time.sleep(0.1) + raise mt.Failure( + f"Observed PC did not reach {expected_pc:04X}; " + f"last screen:\n{last.text() if last is not None else ''}") + + +def _assert_pc_stable(session: "mt.MonitorSession", expected_pc: int, + settle_time: float, context: str) -> None: + deadline = time.time() + settle_time + while time.time() < deadline: + snap = session.capture() + dbg._assert_no_debug_modal_snapshot(snap, context) + actual = _observed_debug_pc(snap) + if actual != expected_pc: + actual_text = "----" if actual is None else f"{actual:04X}" + raise mt.Failure( + f"{context}: PC replayed unexpectedly to " + f"${actual_text} after settling on ${expected_pc:04X}") + time.sleep(0.05) + + +def prove_no_autonomous_trace_replay(rest_host: str, session: "mt.MonitorSession", + runs: int, steps_per_run: int, + settle_time: float) -> None: + stable_sequence = AUTONOMOUS_TRACE_PC_SEQUENCE[1:] + if steps_per_run > len(stable_sequence): + raise mt.Failure( + f"autonomous trace soak only knows {len(stable_sequence)} " + f"validated PCs from $E002, got {steps_per_run} requested steps") + for run in range(runs): + context = f"autonomous trace replay soak run {run + 1}/{runs}" + dbg._enter_rom_debug_at(session, 0xE002, "KRN", context, "$E:KRN") + for step, expected_pc in enumerate(stable_sequence[:steps_per_run]): + snap = session.send_char("T") + dbg._assert_no_debug_modal_snapshot(snap, context) + snap = _wait_for_observed_pc(session, expected_pc) + _assert_pc_stable( + session, + expected_pc, + settle_time, + f"{context}, step {step + 1}/{steps_per_run}", + ) + actual_pc = _observed_debug_pc(snap) + if actual_pc != expected_pc: + actual_text = "----" if actual_pc is None else f"{actual_pc:04X}" + raise mt.Failure( + f"{context}: expected PC ${expected_pc:04X}, got " + f"${actual_text}") + dbg._leave_debug_and_reset(rest_host, session) + + +def _u8(value: int) -> int: + return value & 0xFF + + +def _u16(value: int) -> int: + return value & 0xFFFF + + +def _rel(pc: int, offset: int) -> int: + if offset & 0x80: + offset -= 0x100 + return _u16(pc + 2 + offset) + + +def _set_nz(sr: int, value: int) -> int: + sr &= ~(FLAG_N | FLAG_Z) + value &= 0xFF + if value == 0: + sr |= FLAG_Z + if value & 0x80: + sr |= FLAG_N + return sr + + +class UnsupportedEmulation(Exception): + pass + + +class Memory: + def __init__(self, rest_host: str) -> None: + self.rest_host = rest_host + self.cache: dict[int, int] = {} + + def read(self, address: int) -> int: + address = _u16(address) + # $0000/$0001 are 6510 CPU port registers. The REST raw-memory API is + # not an instruction-fetch/read oracle for those locations. + if address in (0x0000, 0x0001): + raise UnsupportedEmulation + if address not in self.cache: + self.cache[address] = mt.read_rest_memory(self.rest_host, address, 1)[0] + return self.cache[address] + + def read_word(self, address: int) -> int: + return self.read(address) | (self.read(address + 1) << 8) + + def read_word_6502_bug(self, address: int) -> int: + hi_addr = (address & 0xFF00) | ((address + 1) & 0x00FF) + return self.read(address) | (self.read(hi_addr) << 8) + + def note_write(self, address: int, value: int) -> None: + self.cache[_u16(address)] = _u8(value) + + +def _abs(bytes_: bytes) -> int: + return bytes_[1] | (bytes_[2] << 8) + + +def _zp(bytes_: bytes) -> int: + return bytes_[1] + + +def _operand_value(mem: Memory, state: CpuState, bytes_: bytes, mode: str) -> int: + if mode == "imm": + return bytes_[1] + if mode == "zp": + return mem.read(_zp(bytes_)) + if mode == "zpx": + return mem.read(_u8(_zp(bytes_) + state.xr)) + if mode == "zpy": + return mem.read(_u8(_zp(bytes_) + state.yr)) + if mode == "abs": + return mem.read(_abs(bytes_)) + if mode == "absx": + return mem.read(_abs(bytes_) + state.xr) + if mode == "absy": + return mem.read(_abs(bytes_) + state.yr) + if mode == "indx": + ptr = _u8(_zp(bytes_) + state.xr) + return mem.read(mem.read(ptr) | (mem.read(_u8(ptr + 1)) << 8)) + if mode == "indy": + ptr = _zp(bytes_) + return mem.read((mem.read(ptr) | (mem.read(_u8(ptr + 1)) << 8)) + state.yr) + raise mt.Failure(f"Unsupported operand mode {mode}") + + +def _store_address(mem: Memory, state: CpuState, bytes_: bytes, mode: str) -> int: + if mode == "zp": + return _zp(bytes_) + if mode == "zpx": + return _u8(_zp(bytes_) + state.xr) + if mode == "zpy": + return _u8(_zp(bytes_) + state.yr) + if mode == "abs": + return _abs(bytes_) + if mode == "absx": + return _u16(_abs(bytes_) + state.xr) + if mode == "absy": + return _u16(_abs(bytes_) + state.yr) + if mode == "indx": + ptr = _u8(_zp(bytes_) + state.xr) + return mem.read(ptr) | (mem.read(_u8(ptr + 1)) << 8) + if mode == "indy": + ptr = _zp(bytes_) + return _u16((mem.read(ptr) | (mem.read(_u8(ptr + 1)) << 8)) + state.yr) + raise mt.Failure(f"Unsupported store mode {mode}") + + +@dataclass +class StepPlan: + key: str + expected: CpuState + verify: list[tuple[int, int]] + + +def emulate(mem: Memory, state: CpuState) -> Optional[StepPlan]: + pc = state.pc + bytes_ = bytes(mem.read(pc + i) for i in range(3)) + op = bytes_[0] + s = CpuState(pc=pc, sp=state.sp, ac=state.ac, xr=state.xr, yr=state.yr, sr=state.sr) + verify: list[tuple[int, int]] = [] + key = "D" + + def advance(length: int) -> None: + s.pc = _u16(pc + length) + + def load(reg: str, value: int, length: int) -> None: + setattr(s, reg, _u8(value)) + s.sr = _set_nz(s.sr, getattr(s, reg)) + advance(length) + + def compare(reg_value: int, value: int, length: int) -> None: + result = _u8(reg_value - value) + s.sr &= ~(FLAG_C | FLAG_N | FLAG_Z) + if reg_value >= value: + s.sr |= FLAG_C + s.sr = _set_nz(s.sr, result) + advance(length) + + load_modes: dict[int, tuple[str, str, int]] = { + 0xA9: ("ac", "imm", 2), 0xA5: ("ac", "zp", 2), 0xB5: ("ac", "zpx", 2), + 0xAD: ("ac", "abs", 3), 0xBD: ("ac", "absx", 3), 0xB9: ("ac", "absy", 3), + 0xA1: ("ac", "indx", 2), 0xB1: ("ac", "indy", 2), + 0xA2: ("xr", "imm", 2), 0xA6: ("xr", "zp", 2), 0xB6: ("xr", "zpy", 2), + 0xAE: ("xr", "abs", 3), 0xBE: ("xr", "absy", 3), + 0xA0: ("yr", "imm", 2), 0xA4: ("yr", "zp", 2), 0xB4: ("yr", "zpx", 2), + 0xAC: ("yr", "abs", 3), 0xBC: ("yr", "absx", 3), + } + if op in load_modes: + reg, mode, length = load_modes[op] + load(reg, _operand_value(mem, state, bytes_, mode), length) + return StepPlan(key, s, verify) + + store_modes: dict[int, tuple[str, str, int]] = { + 0x85: ("ac", "zp", 2), 0x95: ("ac", "zpx", 2), 0x8D: ("ac", "abs", 3), + 0x9D: ("ac", "absx", 3), 0x99: ("ac", "absy", 3), 0x81: ("ac", "indx", 2), + 0x91: ("ac", "indy", 2), 0x86: ("xr", "zp", 2), 0x96: ("xr", "zpy", 2), + 0x8E: ("xr", "abs", 3), 0x84: ("yr", "zp", 2), 0x94: ("yr", "zpx", 2), + 0x8C: ("yr", "abs", 3), + } + if op in store_modes: + reg, mode, length = store_modes[op] + address = _store_address(mem, state, bytes_, mode) + value = getattr(state, reg) + mem.note_write(address, value) + verify.append((address, value)) + advance(length) + return StepPlan(key, s, verify) + + compare_modes: dict[int, tuple[str, str, int]] = { + 0xC9: ("ac", "imm", 2), 0xC5: ("ac", "zp", 2), 0xD5: ("ac", "zpx", 2), + 0xCD: ("ac", "abs", 3), 0xDD: ("ac", "absx", 3), 0xD9: ("ac", "absy", 3), + 0xC1: ("ac", "indx", 2), 0xD1: ("ac", "indy", 2), + 0xE0: ("xr", "imm", 2), 0xE4: ("xr", "zp", 2), 0xEC: ("xr", "abs", 3), + 0xC0: ("yr", "imm", 2), 0xC4: ("yr", "zp", 2), 0xCC: ("yr", "abs", 3), + } + if op in compare_modes: + reg, mode, length = compare_modes[op] + compare(getattr(state, reg), _operand_value(mem, state, bytes_, mode), length) + return StepPlan(key, s, verify) + + logic_modes: dict[int, tuple[str, int, Callable[[int, int], int]]] = { + 0x29: ("imm", 2, lambda a, b: a & b), 0x25: ("zp", 2, lambda a, b: a & b), + 0x2D: ("abs", 3, lambda a, b: a & b), 0x09: ("imm", 2, lambda a, b: a | b), + 0x05: ("zp", 2, lambda a, b: a | b), 0x0D: ("abs", 3, lambda a, b: a | b), + 0x49: ("imm", 2, lambda a, b: a ^ b), 0x45: ("zp", 2, lambda a, b: a ^ b), + 0x4D: ("abs", 3, lambda a, b: a ^ b), + } + if op in logic_modes: + mode, length, func = logic_modes[op] + s.ac = _u8(func(state.ac, _operand_value(mem, state, bytes_, mode))) + s.sr = _set_nz(s.sr, s.ac) + advance(length) + return StepPlan(key, s, verify) + + if op in (0x69, 0x65, 0x6D) and not (state.sr & FLAG_D): + mode, length = {0x69: ("imm", 2), 0x65: ("zp", 2), 0x6D: ("abs", 3)}[op] + value = _operand_value(mem, state, bytes_, mode) + carry = 1 if state.sr & FLAG_C else 0 + total = state.ac + value + carry + result = _u8(total) + s.sr &= ~(FLAG_C | FLAG_V | FLAG_N | FLAG_Z) + if total > 0xFF: + s.sr |= FLAG_C + if (~(state.ac ^ value) & (state.ac ^ result) & 0x80) != 0: + s.sr |= FLAG_V + s.ac = result + s.sr = _set_nz(s.sr, s.ac) + advance(length) + return StepPlan(key, s, verify) + + if op == 0x24: # BIT zp + value = mem.read(_zp(bytes_)) + s.sr &= ~(FLAG_N | FLAG_V | FLAG_Z) + s.sr |= value & (FLAG_N | FLAG_V) + if (state.ac & value) == 0: + s.sr |= FLAG_Z + advance(2) + return StepPlan(key, s, verify) + if op == 0x2C: # BIT abs + value = mem.read(_abs(bytes_)) + s.sr &= ~(FLAG_N | FLAG_V | FLAG_Z) + s.sr |= value & (FLAG_N | FLAG_V) + if (state.ac & value) == 0: + s.sr |= FLAG_Z + advance(3) + return StepPlan(key, s, verify) + + transfers = { + 0xAA: ("xr", state.ac), 0xA8: ("yr", state.ac), + 0x8A: ("ac", state.xr), 0x98: ("ac", state.yr), + 0xBA: ("xr", state.sp), + } + if op in transfers: + reg, value = transfers[op] + setattr(s, reg, _u8(value)) + s.sr = _set_nz(s.sr, getattr(s, reg)) + advance(1) + return StepPlan(key, s, verify) + if op == 0x9A: # TXS + s.sp = state.xr + advance(1) + return StepPlan(key, s, verify) + + incdec_reg = { + 0xE8: ("xr", 1), 0xC8: ("yr", 1), 0xCA: ("xr", -1), 0x88: ("yr", -1), + } + if op in incdec_reg: + reg, delta = incdec_reg[op] + setattr(s, reg, _u8(getattr(state, reg) + delta)) + s.sr = _set_nz(s.sr, getattr(s, reg)) + advance(1) + return StepPlan(key, s, verify) + + incdec_mem = { + 0xE6: ("zp", 2, 1), 0xF6: ("zpx", 2, 1), 0xEE: ("abs", 3, 1), + 0xFE: ("absx", 3, 1), 0xC6: ("zp", 2, -1), 0xD6: ("zpx", 2, -1), + 0xCE: ("abs", 3, -1), 0xDE: ("absx", 3, -1), + } + if op in incdec_mem: + mode, length, delta = incdec_mem[op] + address = _store_address(mem, state, bytes_, mode) + value = _u8(mem.read(address) + delta) + mem.note_write(address, value) + verify.append((address, value)) + s.sr = _set_nz(s.sr, value) + advance(length) + return StepPlan(key, s, verify) + + flag_ops = { + 0x18: (FLAG_C, False), 0x38: (FLAG_C, True), + 0x58: (FLAG_I, False), 0x78: (FLAG_I, True), + 0xD8: (FLAG_D, False), 0xF8: (FLAG_D, True), + 0xB8: (FLAG_V, False), + } + if op in flag_ops: + flag, enabled = flag_ops[op] + if enabled: + s.sr |= flag + else: + s.sr &= ~flag + advance(1) + return StepPlan(key, s, verify) + + branches = { + 0x10: not (state.sr & FLAG_N), 0x30: bool(state.sr & FLAG_N), + 0x50: not (state.sr & FLAG_V), 0x70: bool(state.sr & FLAG_V), + 0x90: not (state.sr & FLAG_C), 0xB0: bool(state.sr & FLAG_C), + 0xD0: not (state.sr & FLAG_Z), 0xF0: bool(state.sr & FLAG_Z), + } + if op in branches: + s.pc = _rel(pc, bytes_[1]) if branches[op] else _u16(pc + 2) + return StepPlan(key, s, verify) + + if op == 0xEA: + advance(1) + return StepPlan(key, s, verify) + if op == 0x4C: + s.pc = _abs(bytes_) + return StepPlan(key, s, verify) + if op == 0x6C: + ptr = _abs(bytes_) + s.pc = mem.read_word_6502_bug(ptr) + return StepPlan(key, s, verify) + if op == 0x20: + s.pc = _abs(bytes_) + s.sp = _u8(state.sp - 2) + key = "T" + return StepPlan(key, s, verify) + + return None + + +def assert_footer(session: "mt.MonitorSession", expected: CpuState, context: str) -> CpuState: + actual = CpuState.from_footer(session) + diffs = [] + if actual.pc != expected.pc: + diffs.append(f"PC expected {expected.pc:04X} got {actual.pc:04X}") + if actual.sp != expected.sp: + diffs.append(f"SP expected {expected.sp:02X} got {actual.sp:02X}") + if actual.ac != expected.ac: + diffs.append(f"AC expected {expected.ac:02X} got {actual.ac:02X}") + if actual.xr != expected.xr: + diffs.append(f"XR expected {expected.xr:02X} got {actual.xr:02X}") + if actual.yr != expected.yr: + diffs.append(f"YR expected {expected.yr:02X} got {actual.yr:02X}") + # BRK capture sets the B bit; compare the stable status bits we model. + mask = FLAG_N | FLAG_V | FLAG_D | FLAG_I | FLAG_Z | FLAG_C + if (actual.sr & mask) != (expected.sr & mask): + diffs.append(f"SR expected {expected.sr:08b} got {actual.sr:08b}") + if diffs: + raise mt.Failure(f"{context}: footer mismatch: {', '.join(diffs)}") + return actual + + +def assert_ux(session: "mt.MonitorSession", expected_pc: int, context: str) -> None: + header = dbg._header_line(session) + if "MONITOR ASM" not in header or "Dbg" not in header: + raise mt.Failure(f"{context}: expected ASM Debug header, got {header!r}") + if f"${expected_pc:04X}" not in header: + # The user may have intentionally jumped away in another view; returning + # to ASM must snap back to the current debug PC. + session.send_char("A") + header = dbg._header_line(session) + if f"${expected_pc:04X}" not in header: + raise mt.Failure(f"{context}: ASM header did not follow PC {expected_pc:04X}: {header!r}") + labels = dbg._footer_header_line(session) + for token in ("PC", "SP", "AC", "XR", "YR", "NV-BDIZC", "IRQ", "NMI"): + if token not in labels: + raise mt.Failure(f"{context}: footer label {token!r} missing: {labels!r}") + + +def dismiss_debug_cancelled(session: "mt.MonitorSession") -> None: + """Close the informational popup shown when G stops at a breakpoint.""" + if "DEBUG CANCELLED" not in session.capture().text(): + return + session.send_key("ENTER") + if "DEBUG CANCELLED" in session.capture().text(): + raise mt.Failure("Could not dismiss DEBUG CANCELLED popup") + + +def status_cpu(session: "mt.MonitorSession") -> int: + snap = session.capture() + for y in range(mt.HEIGHT): + match = re.search(r"CPU([0-7])", snap.line(y)) + if match: + return int(match.group(1)) + raise mt.Failure(f"No CPU status line found:\n{snap.text()}") + + +def set_cpu(session: "mt.MonitorSession", cpu: int) -> None: + dbg._ensure_no_debug(session) + for _ in range(8): + if status_cpu(session) == cpu: + return + session.send_char("o") + raise mt.Failure(f"Could not switch monitor CPU bank to CPU{cpu}") + + +def verify_rom_mapping(rest_host: str) -> None: + basic = mt.read_rest_memory(rest_host, 0xA000, 0x2000) + kernal = mt.read_rest_memory(rest_host, 0xE000, 0x2000) + if basic[0:2] != b"\x94\xE3": + raise mt.Failure(f"BASIC ROM signature mismatch at $A000: {basic[0:2].hex().upper()}") + if kernal[-6:] == b"\x00" * 6: + raise mt.Failure("KERNAL vector area read as all zeroes; ROM mapping is not usable") + + +def write_bootstrap(rest_host: str, target: int, seed: int) -> CpuState: + ac = (0x20 + seed * 17) & 0xFF + xr = (0x40 + seed * 29) & 0xFF + yr = (0x01 + seed * 7) & 0x7F + program = bytes([ + 0xD8, 0x18, 0x78, 0xB8, # CLD / CLC / SEI / CLV + 0xA2, 0xF8, 0x9A, # deterministic SP for footer checks + 0xA9, ac, 0xA2, xr, 0xA0, yr, # known registers + 0x4C, target & 0xFF, target >> 8, # JMP target + ]) + mt.write_rest_memory(rest_host, BOOTSTRAP_ADDR, program) + sr = FLAG_B | FLAG_I + sr = _set_nz(sr, yr) + return CpuState(pc=target, sp=0xF8, ac=ac, xr=xr, yr=yr, sr=sr) + + +def enter_routine(session: "mt.MonitorSession", rest_host: str, routine: Routine, + seed: int) -> CpuState: + expected = write_bootstrap(rest_host, routine.address, seed) + dbg._reopen_monitor(session) + set_cpu(session, 7) + session.goto(f"{routine.address:04X}") + session.send_char("A") + session.send_char("D") + dbg._clear_all_breakpoints(session, f"{routine.name} entry breakpoint cleanup") + session.goto(f"{routine.address:04X}") + dbg._ensure_breakpoint_at(session, routine.address, f"{routine.name} entry breakpoint set") + session.goto(f"{BOOTSTRAP_ADDR:04X}") + session.send_char("G") + dbg._wait_for_pc(session, f"{routine.address:04X}") + dismiss_debug_cancelled(session) + actual = assert_footer(session, expected, f"{routine.name} entry") + assert_ux(session, routine.address, f"{routine.name} entry") + return actual + + +def exercise_debug_ux(session: "mt.MonitorSession", current: CpuState, iteration: int) -> None: + if iteration % 11 == 0: + session.send_key("F3") + text = session.capture().text() + for token in ("D Step Over", "T Step Into", "U Step Out", "C=+X Reset", "RSTOP"): + if token not in text: + raise mt.Failure(f"Debug help missing {token!r} during soak:\n{text}") + session.send_key("ESC") + if iteration % 17 == 0: + session.send_char("M") + session.goto(f"{SCRATCH_ADDR:04X}") + session.send_char("A") + header = dbg._header_line(session) + if f"${current.pc:04X}" not in header: + raise mt.Failure(f"ASM did not return to debug PC {current.pc:04X}: {header!r}") + if iteration % 23 == 0: + session.last_command = "CTRL_R" + session.sock.sendall(b"\x12") + text = session.capture().text() + if "BREAKPOINTS" not in text: + raise mt.Failure(f"Breakpoint popup missing during soak:\n{text}") + session.send_key("ESC") + + +def rom_step_cycle(rest_host: str, session: "mt.MonitorSession", label: str) -> int: + """Run a bare ROM Step Into cycle that must move PC and show ROM mapping.""" + validations = 0 + + snap = dbg._enter_rom_debug_at(session, 0xE002, "KRN", + f"{label}: KERNAL ROM Step Into", "$E:KRN") + row = dbg._disassembly_row(snap, 0xE002) + expected_pc = 0xBC0F if "20 0F BC" in row else 0xE002 + dbg._instruction_length_from_row(row) + dbg._step_and_assert_pc(session, "T", expected_pc, f"{label}: KERNAL ROM Step Into") + validations += 1 + dbg._leave_debug_and_reset(rest_host, session) + + snap = dbg._enter_rom_debug_at(session, 0xA831, "BAS", + f"{label}: BASIC ROM Step Into", "$A:BAS") + row = dbg._disassembly_row(snap, 0xA831) + expected_pc = 0xA832 if "18" in row else 0xA831 + dbg._instruction_length_from_row(row) + dbg._step_and_assert_pc(session, "T", expected_pc, f"{label}: BASIC ROM Step Into") + validations += 1 + dbg._leave_debug_and_reset(rest_host, session) + + return validations + + +def run_soak(args: argparse.Namespace, rest_host: str, session: "mt.MonitorSession") -> None: + original_port = mt.read_rest_memory(rest_host, 0x0001, 1)[0] + + with mt.check("Debug soak: verify BASIC/KERNAL ROM mapping"): + verify_rom_mapping(rest_host) + + rng = random.Random(args.seed) + iteration = 0 + validated_steps = 0 + rom_validations = 0 + step_out_validations = 0 + cleanup_validations = 0 + trace_replay_validations = 0 + restarts = 0 + mem = Memory(rest_host) + + try: + with mt.check("Debug soak: no autonomous trace replay from $E002"): + prove_no_autonomous_trace_replay( + rest_host, + session, + args.autonomous_trace_runs, + args.autonomous_trace_steps, + args.autonomous_trace_settle, + ) + trace_replay_validations += args.autonomous_trace_runs + if args.autonomous_trace_only: + print(f"debug_soak_test: OK ({trace_replay_validations} autonomous-trace runs)") + return + + with mt.check("Debug soak: bare BASIC/KERNAL ROM Step Into cycle"): + rom_validations += rom_step_cycle(rest_host, session, "initial ROM cycle") + mem.cache.clear() + + with mt.check("Debug soak: Step Out active-JSR target proof"): + dbg.prove_step_out_breaks_after_active_jsr( + rest_host, session, "initial soak Step Out active-JSR proof") + step_out_validations += 1 + + with mt.check("Debug soak: RAM cleanup resume after monitor exit"): + dbg.prove_stop_debug_exit_resumes_current_context( + rest_host, session, "initial soak RAM cleanup resume proof") + cleanup_validations += 1 + mem.cache.clear() + + deadline = time.time() + args.duration + while time.time() < deadline: + if restarts > 0 and restarts % 6 == 0: + rom_validations += rom_step_cycle( + rest_host, session, f"periodic ROM cycle after {restarts} entries") + mem.cache.clear() + dbg.prove_step_out_breaks_after_active_jsr( + rest_host, session, f"periodic soak Step Out proof after {restarts} entries") + step_out_validations += 1 + dbg.prove_stop_debug_exit_resumes_current_context( + rest_host, session, f"periodic soak cleanup proof after {restarts} entries") + cleanup_validations += 1 + mem.cache.clear() + routine = rng.choice(ROUTINES) + restarts += 1 + state = enter_routine(session, rest_host, routine, restarts) + max_steps = rng.randint(4, args.max_steps_per_entry) + + for _ in range(max_steps): + if time.time() >= deadline: + break + iteration += 1 + exercise_debug_ux(session, state, iteration) + try: + plan = emulate(mem, state) + except UnsupportedEmulation: + plan = None + if plan is None: + break + session.send_char(plan.key) + dbg._wait_for_pc(session, f"{plan.expected.pc:04X}") + state = assert_footer( + session, plan.expected, + f"{routine.name} step {validated_steps + 1} via {plan.key}", + ) + assert_ux(session, state.pc, f"{routine.name} step {validated_steps + 1}") + for address, value in plan.verify: + actual = mt.read_rest_memory(rest_host, address, 1)[0] + if actual != value: + raise mt.Failure( + f"{routine.name}: memory ${address:04X} expected ${value:02X}, got ${actual:02X}") + validated_steps += 1 + + if validated_steps and validated_steps % args.progress_every == 0: + remaining = max(0.0, deadline - time.time()) + print( + f"soak progress: {validated_steps} validated steps, " + f"{restarts} entries, {remaining:.0f}s remaining", + flush=True, + ) + finally: + active_error = sys.exc_info()[1] + try: + dismiss_debug_cancelled(session) + dbg._ensure_no_debug(session) + except Exception as exc: + if active_error is None: + raise + print(f"cleanup warning: {mt.format_exception(exc)}", file=sys.stderr) + finally: + mt.write_rest_memory(rest_host, 0x0001, bytes([original_port])) + + if validated_steps < args.min_validated_steps: + raise mt.Failure( + f"Soak only validated {validated_steps} steps; expected at least {args.min_validated_steps}") + if rom_validations < 2: + raise mt.Failure( + f"Soak only validated {rom_validations} ROM debug steps; expected at least 2") + if step_out_validations < 1: + raise mt.Failure( + f"Soak only validated {step_out_validations} active-JSR Step Out cycles; expected at least 1") + if cleanup_validations < 1: + raise mt.Failure( + f"Soak only validated {cleanup_validations} RAM cleanup cycles; expected at least 1") + if trace_replay_validations < args.autonomous_trace_runs: + raise mt.Failure( + f"Soak only validated {trace_replay_validations} autonomous-trace runs; " + f"expected at least {args.autonomous_trace_runs}") + print(f"debug_soak_test: OK ({validated_steps} validated steps, " + f"{rom_validations} ROM debug steps, " + f"{step_out_validations} active-JSR Step Out cycles, " + f"{cleanup_validations} cleanup cycles, " + f"{trace_replay_validations} autonomous-trace runs across {restarts} entries)") + + +def main() -> int: + parser = argparse.ArgumentParser(description="Soak the U64 machine monitor debugger over Telnet") + parser.add_argument("--host", default=os.environ.get("U64_MONITOR_HOST", "u64")) + parser.add_argument("--port", type=int, default=int(os.environ.get("U64_MONITOR_PORT", "23"))) + parser.add_argument("--rest-host", default=os.environ.get("U64_MONITOR_REST_HOST")) + parser.add_argument("--password", default=os.environ.get("U64_MONITOR_PASSWORD")) + parser.add_argument("--timeout", type=float, default=float(os.environ.get("U64_MONITOR_TIMEOUT", "5.0"))) + parser.add_argument("--duration", type=float, default=float(os.environ.get("U64_MONITOR_SOAK_SECS", DEFAULT_DURATION))) + parser.add_argument("--seed", type=int, default=int(os.environ.get("U64_MONITOR_SOAK_SEED", "1541"))) + parser.add_argument("--max-steps-per-entry", type=int, default=24) + parser.add_argument("--min-validated-steps", type=int, default=50) + parser.add_argument("--progress-every", type=int, default=100) + parser.add_argument("--autonomous-trace-runs", type=int, default=5) + parser.add_argument("--autonomous-trace-steps", type=int, default=10) + parser.add_argument("--autonomous-trace-settle", type=float, default=0.35) + parser.add_argument("--autonomous-trace-only", action="store_true") + args = parser.parse_args() + + rest_host = args.rest_host or args.host + session: Optional[mt.MonitorSession] = None + try: + session = mt.MonitorSession(args.host, args.port, args.password, args.timeout) + run_soak(args, rest_host, session) + return 0 + except (mt.Failure, OSError, TimeoutError, urllib.error.URLError) as exc: + print(mt.format_exception(exc), file=sys.stderr) + if session is not None: + try: + print("\nFinal screen:", file=sys.stderr) + print(session.capture().text(), file=sys.stderr) + except Exception: + pass + return 1 + finally: + if session is not None: + session.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/developer/machine-code-monitor/monitor_debug_test.py b/tools/developer/machine-code-monitor/monitor_debug_test.py new file mode 100755 index 000000000..14fb8f292 --- /dev/null +++ b/tools/developer/machine-code-monitor/monitor_debug_test.py @@ -0,0 +1,2905 @@ +#!/usr/bin/env python3 +"""End-to-end test for Machine Code Monitor Debug mode (DBG-* feature IDs). + +Uses the same telnet entry point and CLI options as ``monitor_test.py`` so the +two suites are interchangeable. Verifies the full Debug mode stack: header/ +footer composition, key routing, breakpoint toggle and list popup, RETURN +navigation preservation, Edit+Debug composition, the BRK trampoline +orchestrator (Go, Over, Trace, Out), and patch hygiene on cleanup. + +CLI options mirror monitor_test.py exactly so the same automation hooks work. +""" + +from __future__ import annotations + +import argparse +import os +import re +import sys +import time +import urllib.request +from pathlib import Path + +# Reuse the existing telnet session helpers so both suites stay in lockstep. +sys.path.insert(0, str(Path(__file__).parent)) +import monitor_test as mt # type: ignore # noqa: E402 + +FLAG_BIT_INDEX = { + "N": 0, + "V": 1, + "B": 3, + "D": 4, + "I": 5, + "Z": 6, + "C": 7, +} + +FORBIDDEN_DEBUG_TEXT = ( + "UNSAFE TARGET", + "DEBUG TIMEOUT", + "TIMEOUT", + "PATCH FAILED", + "DEBUG NOT SUPPORTED", + "NO CONTEXT", + "ASSERT", + "ERROR", +) + +READY_SCREEN_TOKEN = bytes([0x12, 0x05, 0x01, 0x04, 0x19]) +SAFE_CPU_PORT_VALUE = 0x37 +SAFE_CPU_PORT_LOW_BITS = 0x07 + +# Optional suite chunking for diagnostics. The default is a true single-process full +# pass; use --chunk-size explicitly when investigating service-path slowdowns. +SUITE_CHUNK_SIZE = 0 +SUITE_CHUNK_COOLDOWN_SECONDS = 6.0 + +# Post-group hygiene recovery. The per-group cleanup resets the C64 and then probes +# the jiffy clock ($00A2) to prove the KERNAL IRQ is actually running. Under sustained +# full-suite load the debug-exit resume / reset can be sluggish, so that probe +# occasionally runs before the freshly-reset KERNAL IRQ has restarted ($A2 frozen for +# the whole probe window, then it recovers). Rather than aborting the entire suite on +# that transient, we cool down, hard-reset again, and retry the hygiene assertion up +# to this many times. A genuinely wedged machine stays frozen across every recovery +# and still raises. +HYGIENE_RECOVERY_ATTEMPTS = 3 + + +def _capture_lines(session: "mt.MonitorSession") -> list[str]: + snap = session.capture() + return [snap.line(y).rstrip() for y in range(mt.HEIGHT)] + + +def _find(lines: list[str], needle: str) -> bool: + return any(needle in line for line in lines) + + +def _header_line(session: "mt.MonitorSession") -> str: + snap = session.capture() + for y in range(mt.HEIGHT): + line = snap.line(y) + if "MONITOR" in line: + return line + raise mt.Failure("monitor header line not found") + + +def _footer_value_line(session: "mt.MonitorSession") -> str: + # Find the CPU label row by scanning, then the value row is the line + # directly below it. This is more robust than fixed indices, which vary + # depending on whether the screen renders the system status line at the + # bottom. + snap = session.capture() + for y in range(mt.HEIGHT): + line = snap.line(y) + if "PC" in line and "SP" in line and "NV-BDIZC" in line: + if y + 1 < mt.HEIGHT: + return snap.line(y + 1) + raise mt.Failure("CPU label row not found; cannot locate footer values") + + +def _footer_header_line(session: "mt.MonitorSession") -> str: + snap = session.capture() + for y in range(mt.HEIGHT): + line = snap.line(y) + if "PC" in line and "SP" in line and "NV-BDIZC" in line: + return line + raise mt.Failure("CPU label row not found") + + +def _debug_footer_row_indices(session: "mt.MonitorSession") -> tuple[int, int, int]: + snap = session.capture() + label_y = -1 + status_y = -1 + for y in range(mt.HEIGHT): + line = snap.line(y) + if "PC" in line and "SP" in line and "NV-BDIZC" in line: + label_y = y + if mt.STATUS_LINE_RE.search(line): + status_y = y + if label_y < 0: + raise mt.Failure("Debug footer label row not found") + if status_y < 0: + raise mt.Failure(f"Normal CPU/VIC footer not visible in Debug:\n{snap.text()}") + return label_y, label_y + 1, status_y + + +def _send_ctrl_d(session: "mt.MonitorSession") -> None: + session.last_command = "CTRL_D" + session.sock.sendall(b"\x04") + + +def _send_ctrl_x(session: "mt.MonitorSession") -> None: + session.last_command = "CTRL_X" + session.sock.sendall(b"\x18") + + +def _wait_for_screen_text(session: "mt.MonitorSession", needle: str, + timeout: float = 2.0) -> mt.Snapshot: + deadline = time.time() + timeout + last = None + while time.time() < deadline: + snap = session.capture() + last = snap + if needle in snap.text(): + return snap + time.sleep(0.1) + raise mt.Failure( + f"Timed out waiting for {needle!r} after {session.last_command}\n" + f"{last.text() if last is not None else ''}") + + +def _assert_no_debug_modal_snapshot(snap: mt.Snapshot, context: str) -> None: + text = snap.text() + for token in FORBIDDEN_DEBUG_TEXT: + if token in text: + raise mt.Failure(f"{context}: unexpected {token!r} after {snap.last_command}\n{text}") + + +def _assert_no_debug_modal(session: "mt.MonitorSession", context: str) -> None: + _assert_no_debug_modal_snapshot(session.capture(), context) + + +def _assert_snapshot_contains(snap: mt.Snapshot, token: str, context: str) -> None: + if token not in snap.text(): + raise mt.Failure(f"{context}: missing {token!r} after {snap.last_command}\n{snap.text()}") + + +def _assert_status_tokens(snap: mt.Snapshot, context: str, *tokens: str) -> None: + line_index = snap.find_status_line() + line = snap.line(line_index) + for token in tokens: + if token not in line: + raise mt.Failure(f"{context}: status line missing {token!r}: {line!r}\n{snap.text()}") + + +def _disassembly_row(snap: mt.Snapshot, address: int) -> str: + wanted = f"|{address:04X} " + for y in range(mt.HEIGHT): + line = snap.line(y) + if line.startswith(wanted): + return line + raise mt.Failure(f"Disassembly row ${address:04X} not visible after {snap.last_command}\n{snap.text()}") + + +def _memory_row(snap: mt.Snapshot, address: int) -> str: + wanted = f"|{address:04X} " + for y in range(mt.HEIGHT): + line = snap.line(y) + if line.startswith(wanted): + return line + raise mt.Failure(f"Memory row ${address:04X} not visible after {snap.last_command}\n{snap.text()}") + + +def _instruction_length_from_row(row: str) -> int: + fields = row[1:].split() + if not fields: + raise mt.Failure(f"Cannot parse disassembly row: {row!r}") + length = 0 + for token in fields[1:4]: + if len(token) == 2 and all(ch in "0123456789ABCDEFabcdef" for ch in token): + length += 1 + continue + break + if length <= 0: + raise mt.Failure(f"Cannot determine instruction length from row: {row!r}") + return length + + +def _jsr_target_from_row(row: str) -> int: + match = re.search(r"\bJSR \$([0-9A-Fa-f]{4})", row) + if not match: + raise mt.Failure(f"Expected JSR row, got: {row!r}") + return int(match.group(1), 16) + + +def _find_visible_jsr_row(snap: mt.Snapshot, marker: str) -> tuple[int, str]: + for y in range(mt.HEIGHT): + line = snap.line(y) + if f"[{marker}]" not in line or "JSR $" not in line: + continue + if len(line) >= 6 and line[0] == "|" and line[5] == " ": + addr_text = line[1:5] + if all(ch in "0123456789ABCDEFabcdef" for ch in addr_text): + return int(addr_text, 16), line + raise mt.Failure(f"No visible [{marker}] JSR row found after {snap.last_command}\n{snap.text()}") + + +def _dump_debug_scratch(rest_host: str, context: str) -> None: + """Print the RAM-resident BRK debug scratch + vectors for [43] diagnosis. + + All addresses are CPU-visible RAM read via REST DMA. The cassette buffer + ($0363-$03FB) holds the debug HANDLER/TRAMPOLINE/NMI_TRAMPOLINE/HARD_BRK_STUB + and register stores. Reset heals the FPGA ROM image but NOT this RAM, so a + stale launch-trampoline JMP target or stale vector here is the prime suspect + for the second-pass "$0002" capture. + """ + try: + regions = [ + ("zp0000", 0x0000, 8), + ("softvec_0314", 0x0314, 6), # IRQ/BRK/NMI soft vectors + ("handler_0363", 0x0363, 0x27), # HANDLER (ends spin JMP @ $0387) + ("tramp_038A", 0x038A, 0x26), # TRAMPOLINE + ("nmitramp_03B0", 0x03B0, 0x18), # NMI_TRAMPOLINE + ("hardstub_03C8", 0x03C8, 0x28), # HARD_BRK_STUB + orig vector + stores + ("hardnmi_FFFA", 0xFFFA, 2), # CPU-visible hard NMI vector + ] + print(f" ---- DEBUG SCRATCH DUMP ({context}) ----", flush=True) + for name, addr, length in regions: + data = mt.read_rest_memory(rest_host, addr, length) + hexs = " ".join(f"{b:02X}" for b in data) + print(f" {name} ${addr:04X}: {hexs}", flush=True) + print(" ---- END DEBUG SCRATCH DUMP ----", flush=True) + except Exception as exc: # noqa: BLE001 + print(f" [scratch dump failed: {exc!r}]", flush=True) + + +def _enter_rom_debug_at(session: "mt.MonitorSession", address: int, marker: str, + context: str, *status_tokens: str) -> mt.Snapshot: + _reopen_monitor(session) + mt.ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + _ensure_no_debug(session) + session.goto(f"{address:04X}") + session.send_char("A") + header = _header_line(session) + if "Dbg" not in header: + session.send_char("D") + snap = session.capture() + _assert_no_debug_modal_snapshot(snap, context) + _assert_snapshot_contains(snap, f"MONITOR ASM ${address:04X}", context) + _assert_snapshot_contains(snap, f"[{marker}]", context) + _assert_status_tokens(snap, context, "CPU7", *status_tokens) + row = _disassembly_row(snap, address) + if f"[{marker}]" not in row: + raise mt.Failure(f"{context}: row ${address:04X} missing [{marker}]: {row!r}\n{snap.text()}") + return snap + + +def _assert_debug_pc(session: "mt.MonitorSession", expected_pc: int, context: str) -> dict: + expected = f"{expected_pc:04X}" + parsed = _wait_for_pc(session, expected) + header = _header_line(session) + if f"MONITOR ASM ${expected}" not in header: + raise mt.Failure(f"{context}: header did not follow PC ${expected}: {header!r}") + snap = session.capture() + _disassembly_row(snap, expected_pc) + return parsed + + +def _step_and_assert_pc(session: "mt.MonitorSession", key: str, + expected_pc: int, context: str) -> dict: + snap = session.send_char(key) + _assert_no_debug_modal_snapshot(snap, context) + return _assert_debug_pc(session, expected_pc, context) + + +def _ensure_breakpoint_at(session: "mt.MonitorSession", address: int, + context: str) -> None: + row = _disassembly_row(session.capture(), address) + if "[BRK" in row: + return + session.send_char("R") + _assert_no_debug_modal(session, context) + row = _disassembly_row(session.capture(), address) + if "[BRK" not in row: + raise mt.Failure(f"{context}: breakpoint was not set at ${address:04X}: {row!r}") + + +def _clear_breakpoint_at(session: "mt.MonitorSession", address: int, + context: str) -> None: + session.goto(f"{address:04X}") + row = _disassembly_row(session.capture(), address) + if "[BRK" not in row: + return + session.send_char("R") + _assert_no_debug_modal(session, context) + row = _disassembly_row(session.capture(), address) + if "[BRK" in row: + raise mt.Failure(f"{context}: breakpoint was not cleared at ${address:04X}: {row!r}") + + +def _clear_all_breakpoints(session: "mt.MonitorSession", context: str) -> None: + session.last_command = "CTRL_R_CLEAR_ALL" + session.sock.sendall(b"\x12") + snap = session.capture() + if "BREAKPOINTS" not in snap.text(): + raise mt.Failure(f"{context}: breakpoint popup did not open:\n{snap.text()}") + + session.send_key_repeat("UP", 9) + for slot in range(10): + snap = session.capture() + line = next((snap.line(y) for y in range(mt.HEIGHT) + if re.match(rf"^\|{slot} ", snap.line(y))), "") + if not line: + raise mt.Failure(f"{context}: slot {slot} missing from breakpoint popup:\n{snap.text()}") + if "EMPTY" not in line: + snap = session.send_key("DEL") + if "BREAKPOINTS" not in snap.text(): + raise mt.Failure(f"{context}: DEL left the breakpoint popup unexpectedly:\n{snap.text()}") + if slot < 9: + session.send_key("DOWN") + + session.send_key("ESC") + + +def _leave_debug_and_reset(rest_host: str, session: "mt.MonitorSession") -> None: + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + + +def _wait_for_blank_debug_context(session: "mt.MonitorSession", + timeout: float = 4.0) -> None: + deadline = time.time() + timeout + while time.time() < deadline: + header = _header_line(session) + if "Dbg" not in header: + time.sleep(0.1) + continue + parsed = _parse_footer_values(_footer_value_line(session)) + if not any(parsed[field] for field in ("pc", "sp", "ac", "xr", "yr", "sr", "irq", "nmi")): + return + time.sleep(0.1) + raise mt.Failure(f"Debug footer did not clear after reset:\n{session.capture().text()}") + + +def _reset_c64_core(rest_host: str, timeout: float = 8.0) -> None: + url = f"http://{rest_host}/v1/machine:reset" + request = urllib.request.Request(url, data=b"", method="PUT") + try: + with urllib.request.urlopen(request, timeout=max(5.0, timeout)): + pass + except (OSError, TimeoutError, urllib.error.URLError) as exc: + # The firmware may reset the C64 and briefly starve the REST response path + # before the HTTP request is completed. Treat the response timeout as + # recoverable only if the deterministic READY proof below succeeds. + print(f"[info] reset response timed out, verifying READY anyway: {exc}", flush=True) + _wait_for_c64_ready(rest_host, timeout) + time.sleep(3.0) + + +def _chunk_boundary_recovery(rest_host: str, context: str, cooldown: float, + timeout: float = 8.0) -> None: + """Drain accumulated REST/USB service load at a suite chunk boundary. + + Called between blocks of SUITE_CHUNK_SIZE groups. A plain per-group soft reset + does not clear the gradual device slowdown that builds up over a long pass, so + here we additionally idle for `cooldown` seconds (letting the firmware service + path settle) and then issue one extra soft reset before the next block starts. + Deliberately avoids any full device reboot, which would drop the JTAG-loaded + firmware image. See WORKLOG.md Phase 3. + """ + if cooldown <= 0: + return + print(f"[info] chunk boundary ({context}): cooling down {cooldown:.0f}s + " + f"extra reset to drain accumulated load", flush=True) + time.sleep(cooldown) + _reset_c64_core(rest_host, timeout) + + +def _wait_for_c64_ready(rest_host: str, timeout: float = 8.0) -> None: + deadline = time.time() + timeout + stable_since = 0.0 + while time.time() < deadline: + screen = mt.read_rest_memory(rest_host, 0x0400, 1000) + if READY_SCREEN_TOKEN in screen: + now = time.time() + if stable_since == 0.0: + stable_since = now + elif now - stable_since >= 0.75: + return + else: + stable_since = 0.0 + time.sleep(0.1) + raise mt.Failure("C64 core reset did not reach READY prompt") + + +def _live_cpu_bank_from_status(status: str) -> int: + match = re.search(r"\bCPU([0-7])\b|\bC([0-7])O[0-7]\b", status) + if match is None: + raise mt.Failure(f"Could not read live CPU bank from status line: {status!r}") + value = match.group(1) if match.group(1) is not None else match.group(2) + return int(value) + + +def _assert_safe_banking_display_hygiene(rest_host: str, session: "mt.MonitorSession", + context: str) -> None: + screen = mt.read_rest_memory(rest_host, 0x0400, 1000) + if READY_SCREEN_TOKEN not in screen: + raise mt.Failure(f"{context}: C64 READY screen is not readable/deterministic") + + _reopen_monitor(session) + snap = session.capture() + line = snap.line(snap.find_status_line()) + live_bank = _live_cpu_bank_from_status(line) + if live_bank != SAFE_CPU_PORT_LOW_BITS: + raise mt.Failure( + f"{context}: live $0001 low bits are CPU{live_bank}, " + f"expected CPU{SAFE_CPU_PORT_LOW_BITS}: {line!r}\n{snap.text()}") + if "$D:I/O" not in line: + raise mt.Failure(f"{context}: I/O is not visible in status line: {line!r}\n{snap.text()}") + _assert_rest_byte_changes(rest_host, 0x00A2, f"{context}: jiffy clock responsiveness", + minimum_values=2) + + +def _force_safe_cpu_port(rest_host: str, context: str) -> None: + # Some destructive banking regressions deliberately run with $0001 low bits + # clear, which can keep KERNAL/I/O hidden across a raw C64 reset. Restore only + # the 6510 port latch through the same REST memory aperture used by the tests, + # then prove the low bits before issuing reset. + mt.write_rest_memory(rest_host, 0x0001, bytes([SAFE_CPU_PORT_VALUE])) + readback = mt.read_rest_memory(rest_host, 0x0001, 1)[0] + if (readback & 0x07) != SAFE_CPU_PORT_LOW_BITS: + raise mt.Failure( + f"{context}: failed to restore $0001 low bits, read ${readback:02X}") + + +def _restore_safe_banking_display_hygiene(rest_host: str, session: "mt.MonitorSession", + context: str) -> None: + # Reset + verify, but tolerate a transient load-degraded slow resume: if the + # hygiene assertion (notably the jiffy-clock responsiveness probe) misses, cool + # down, hard-reset again, and retry. Only a persistently wedged machine fails. + last_exc: "mt.Failure | None" = None + for attempt in range(HYGIENE_RECOVERY_ATTEMPTS): + _force_safe_cpu_port(rest_host, context) + _reset_c64_core(rest_host) + try: + _assert_safe_banking_display_hygiene(rest_host, session, context) + return + except mt.Failure as exc: + last_exc = exc + if attempt + 1 >= HYGIENE_RECOVERY_ATTEMPTS: + break + print(f"[info] {context}: hygiene miss ({exc}); load-degradation " + f"recovery {attempt + 1}/{HYGIENE_RECOVERY_ATTEMPTS - 1} " + f"(cool down {SUITE_CHUNK_COOLDOWN_SECONDS:.0f}s + reset)", + flush=True) + time.sleep(SUITE_CHUNK_COOLDOWN_SECONDS) + assert last_exc is not None + raise last_exc + + +def _reset_monitor_and_c64(rest_host: str, session: "mt.MonitorSession", + timeout: float = 8.0) -> None: + _reopen_monitor(session) + _send_ctrl_x(session) + _wait_for_c64_ready(rest_host, timeout) + # C=+X tears down the live Debug session, but the REST reset path is the + # deterministic core reset used by standalone hardware runs. + _reset_c64_core(rest_host, timeout) + try: + _wait_for_blank_debug_context(session, 2.0) + except mt.Failure: + pass + _reopen_monitor(session) + + +def run_debug_tests(rest_host: str, session: "mt.MonitorSession") -> None: + # Park the cursor at a known address so the screen is deterministic. + c050_breakpoint_slot = 0 + + with mt.check("Debug: setup at $C000"): + session.goto("C000") + header = _header_line(session) + if "$C000" not in header: + raise mt.Failure(f"goto $C000 did not update header: {header!r}") + + with mt.check("Debug: A switches to Assembly view"): + session.send_char("A") + header = _header_line(session) + if "ASM" not in header: + raise mt.Failure(f"A did not switch to ASM view: {header!r}") + if "Dbg" in header: + raise mt.Failure(f"Dbg flag must be absent before pressing D: {header!r}") + + with mt.check("Debug: D enters Debug mode without executing"): + session.send_char("D") + header = _header_line(session) + if "MONITOR ASM" not in header: + raise mt.Failure(f"Header must remain MONITOR ASM in Debug mode: {header!r}") + if "Dbg" not in header: + raise mt.Failure(f"Dbg flag must appear after D: {header!r}") + + with mt.check("Debug: clear stale breakpoint slots before exercising popup flows"): + _clear_all_breakpoints(session, "suite setup breakpoint cleanup") + + with mt.check("Debug: footer rows show CPU labels"): + labels = _footer_header_line(session) + for token in ("PC", "SP", "AC", "XR", "YR", "NV-BDIZC", "IRQ", "NMI"): + if token not in labels: + raise mt.Failure(f"Footer label {token!r} missing in row: {labels!r}") + + with mt.check("Debug: CPU table sits above normal CPU/VIC footer"): + label_y, value_y, status_y = _debug_footer_row_indices(session) + if status_y != value_y + 1: + snap = session.capture() + raise mt.Failure( + f"Debug footer must occupy rows n-2/n-1 above normal footer n; " + f"got label={label_y}, value={value_y}, status={status_y}\n{snap.text()}") + + with mt.check("Debug: unknown context renders blanks"): + values = _footer_value_line(session) + # Strip the window left/right border. With no captured context + # every CPU footer column must be blank - never zero or question marks. + inside = values.strip("| ") + if inside: + raise mt.Failure(f"Unknown footer must be blank, got: {values!r}") + + with mt.check("Debug: help keeps normal shortcuts and uses RSTOP labels"): + session.send_key("F3") + snap = session.capture() + joined = "\n".join(snap.line(y) for y in range(mt.HEIGHT)) + for token in ("M Memory", "A Assembly", "L Load", "S Save", + "C=+B List", "D Step Over", "T Step Into", "U Step Out", + "C=+R", "C=+D", "C=+X", "RSTOP"): + if token not in joined: + raise mt.Failure(f"Debug help missing {token!r}:\n{joined}") + if "ESC" in joined: + raise mt.Failure(f"Debug help must show RSTOP, not ESC:\n{joined}") + session.send_key("ESC") + + with mt.check("Debug: R toggles a breakpoint (set + clear)"): + before = session.capture().text() + session.send_char("R") + after_set = session.capture().text() + if "BRK" in after_set and "SET" in after_set and after_set != before: + raise mt.Failure("R must not show a redundant BRK SET popup") + session.send_char("R") + after_clear = session.capture().text() + if "BRK" in after_clear and "CLR" in after_clear and after_clear != after_set: + raise mt.Failure("Second R must not show a redundant BRK CLR popup") + + with mt.check("Debug: C=+R opens the breakpoint list popup"): + session.last_command = "CTRL_R" + session.sock.sendall(b"\x12") + snap = session.capture() + if not any("BREAKPOINTS" in snap.line(y) for y in range(mt.HEIGHT)): + raise mt.Failure("C=+R did not open the breakpoint list popup") + for ch in "DTOGR": + session.send_char(ch) + snap = session.capture() + if not any("BREAKPOINTS" in snap.line(y) for y in range(mt.HEIGHT)): + raise mt.Failure(f"Breakpoint popup did not block Debug key {ch!r}") + session.send_key("ESC") + + with mt.check("Debug: breakpoint opcode line shows [BRKx] before 3-char source"): + mt.write_rest_memory(rest_host, 0xC050, bytes([0xEA, 0xEA])) + session.goto("C050") + session.send_char("A") + if "Dbg" not in _header_line(session): + session.send_char("D") + _clear_breakpoint_at(session, 0xC050, "$C050 stale breakpoint clear") + session.goto("C050") + session.send_char("R") + lines = _capture_lines(session) + row = next((line for line in lines if line.startswith("|C050 ")), "") + if not re.search(r"\[BRK\d\]\[RAM\]", row): + raise mt.Failure(f"Breakpoint line must show [BRKx][RAM], got: {row!r}") + + with mt.check("Debug: C=+R shows the live breakpoint list"): + session.last_command = "CTRL_R_WITH_BREAKPOINT" + session.sock.sendall(b"\x12") + snap = session.capture() + joined = "\n".join(snap.line(y) for y in range(mt.HEIGHT)) + if "BREAKPOINTS" not in joined: + raise mt.Failure(f"C=+R did not open breakpoint list:\n{joined}") + if "$C050" not in joined or "SET" not in joined: + raise mt.Failure(f"Breakpoint list did not show the live breakpoint:\n{joined}") + if "0-9/RET:Jmp S:Set L:Lbl E:Enbl DEL:Res" not in joined: + raise mt.Failure(f"Breakpoint list help row did not list jump/store/label/enable/reset:\n{joined}") + slot_match = re.search(r"^\|?(\d) SET \$C050\b", joined, re.MULTILINE) + if not slot_match: + raise mt.Failure(f"Breakpoint list did not expose the $C050 slot number:\n{joined}") + c050_breakpoint_slot = int(slot_match.group(1)) + session.send_key_repeat("UP", 9) + if c050_breakpoint_slot > 0: + session.send_key_repeat("DOWN", c050_breakpoint_slot) + session.send_char("L") + snap = session.send_text("READ\r", "BP label READ") + text = snap.text() + if f"{c050_breakpoint_slot} SET READ" not in text or "$C050" not in text: + raise mt.Failure(f"Breakpoint label edit did not update the live slot:\n{text}") + session.send_key("ESC") + + with mt.check("Debug: breakpoint label replaces [BRKx] on the ASM page"): + lines = _capture_lines(session) + row = next((line for line in lines if line.startswith("|C050 ")), "") + if "[READ][RAM]" not in row: + raise mt.Failure(f"Labelled breakpoint line must show [READ][RAM], got: {row!r}") + if re.search(r"\[BRK\d\]", row): + raise mt.Failure(f"Labelled breakpoint line must not also show [BRKx], got: {row!r}") + session.send_char("R") + + with mt.check("Debug: visible memory source indicators are 3 chars"): + _ensure_no_debug(session) + mt.ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + session.send_char("D") + expected = { + "C000": "[RAM]", + "A000": "[BAS]", + "D000": "[I/O]", + "E000": "[KRN]", + } + for address, marker in expected.items(): + session.goto(address) + lines = _capture_lines(session) + row = next((line for line in lines if line.startswith(f"|{address} ")), "") + if marker not in row: + raise mt.Failure(f"{address} row missing {marker}: {row!r}") + for stale in ("[BASIC]", "[KERNAL]", "[CHAR]", "[IO]"): + if stale in row: + raise mt.Failure(f"{address} row used stale source label: {row!r}") + + with mt.check("Debug: RETURN preserves Assembly navigation"): + # RETURN must follow a jumpable instruction without executing. We + # simply verify the monitor stays in Debug mode and ASM view; the + # follow/return semantics are already exercised in monitor_test.py. + session.send_key("ENTER") + header = _header_line(session) + if "MONITOR ASM" not in header or "Dbg" not in header: + raise mt.Failure(f"RETURN must keep ASM + Dbg state: {header!r}") + + with mt.check("Debug: RETURN does not execute target code"): + # A JSR target that would mutate $C030 if executed. RETURN may follow + # the subroutine in the Assembly view, but must not run it. + program = bytes([0x20, 0x24, 0xC0, 0xEA, 0xEE, 0x30, 0xC0, 0x60]) + mt.write_rest_memory(rest_host, 0xC020, program) + mt.write_rest_memory(rest_host, 0xC030, bytes([0x44])) + session.goto("C020") + session.send_char("A") + if "Dbg" not in _header_line(session): + session.send_char("D") + session.send_key("ENTER") + after = mt.read_rest_memory(rest_host, 0xC030, 1)[0] + if after != 0x44: + raise mt.Failure(f"RETURN executed subroutine side effect; $C030=${after:02X}") + session.send_key("ENTER") + + with mt.check("Debug: ESC/RUNSTOP leaves Edit before Dbg so debugging can continue"): + _ensure_no_debug(session) + mt.write_rest_memory(rest_host, 0xC040, bytes([0xA9, 0x66, 0xEA, 0x4C, 0x42, 0xC0])) + session.goto("C040") + session.send_char("A") + session.send_char("D") + session.send_char("M") + session.send_char("E") + header = _header_line(session) + if "Dbg" not in header or "Edit" not in header: + raise mt.Failure(f"Header must show both Dbg and Edit: {header!r}") + session.send_key("ESC") + header = _header_line(session) + if "Dbg" not in header or "Edit" in header: + raise mt.Failure(f"ESC in Debug+Edit must keep Dbg and clear Edit: {header!r}") + session.send_char("A") + header = _header_line(session) + if "MONITOR ASM" not in header or "Dbg" not in header or "Edit" in header: + raise mt.Failure(f"Leaving Edit should keep Debug alive for ASM resume: {header!r}") + session.send_char("D") + parsed = _wait_for_pc(session, "C042") + if parsed["ac"] != "66": + raise mt.Failure(f"Debugging should continue after leaving Edit, got {parsed!r}") + _ensure_no_debug(session) + + with mt.check("Debug: C=+D from Debug+Edit clears both and allows re-debug"): + session.send_char("D") + session.send_char("E") + header = _header_line(session) + if "Dbg" not in header or "Edit" not in header: + raise mt.Failure(f"Header must show both Dbg and Edit: {header!r}") + # C=+D leaves both Debug and Edit so the next keystroke is a monitor + # command again. This mirrors the authoritative host regression + # test_ctrl_d_from_edit_clears_edit_for_redebug: the user can leave a + # debug+edit session with one key and immediately navigate/re-debug. + _send_ctrl_d(session) + header = _header_line(session) + if "Dbg" in header or "Edit" in header: + raise mt.Failure(f"C=+D in Debug+Edit must clear both Dbg and Edit: {header!r}") + # Prove Edit really cleared: J is consumed as a monitor jump command, + # not as edit-mode text input. + session.goto("C040") + session.send_char("A") + header = _header_line(session) + if "MONITOR ASM $C040" not in header or "Edit" in header: + raise mt.Failure(f"After C=+D, J must act as a monitor jump command: {header!r}") + # Re-enter Debug from the post-C=+D cursor and confirm a step runs. + session.send_char("D") + session.send_char("D") + parsed = _wait_for_pc(session, "C042") + if parsed["ac"] != "66": + raise mt.Failure(f"Re-entered Debug must step from the cursor, got {parsed!r}") + _ensure_no_debug(session) + + with mt.check("Debug: returning to ASM after stepping elsewhere follows the current debug PC"): + _reopen_monitor(session) + mt.write_rest_memory(rest_host, 0xC060, bytes([0xA9, 0x22, 0xEA, 0xEA])) + session.goto("C060") + session.send_char("A") + session.send_char("D") + session.send_char("D") + _wait_for_pc(session, "C062") + session.send_char("M") + session.goto("C180") + session.send_char("D") + _wait_for_pc(session, "C063") + session.send_char("A") + header = _header_line(session) + if "MONITOR ASM $C063" not in header: + raise mt.Failure(f"ASM view must snap back to the current debug PC: {header!r}") + lines = _capture_lines(session) + row = next((line for line in lines if line.startswith("|C063 ")), "") + if not row: + raise mt.Failure(f"Disassembly cursor did not return to $C063:\n{session.capture().text()}") + _ensure_no_debug(session) + + with mt.check("Debug: C=+X resets the machine and keeps Debug open with blank context"): + _reopen_monitor(session) + mt.write_rest_memory(rest_host, 0xC070, bytes([0xA9, 0x11, 0xEA])) + session.goto("C070") + session.send_char("A") + session.send_char("D") + session.send_char("D") + _wait_for_pc(session, "C072") + _send_ctrl_x(session) + _wait_for_blank_debug_context(session) + + with mt.check("Debug: C=+B opens bookmarks in Debug mode"): + session.last_command = "CBM_B" + session.sock.sendall(b"\x1bB") + snap = session.capture() + if not any("BOOKMARKS" in snap.line(y) for y in range(mt.HEIGHT)): + raise mt.Failure("C=+B must open bookmark popup while Debug is active") + session.send_key("ESC") + header = _header_line(session) + if "Dbg" not in header: + raise mt.Failure(f"Closing C=+B popup must keep Debug active: {header!r}") + + with mt.check("Debug: ESC leaves Debug mode"): + session.send_key("ESC") + header = _header_line(session) + if "Dbg" in header: + raise mt.Failure(f"ESC must clear Dbg: {header!r}") + + with mt.check("Debug: B retains Binary view (not stolen by breakpoint)"): + session.send_char("B") + header = _header_line(session) + if "BIN" not in header: + raise mt.Failure(f"B must switch to Binary view: {header!r}") + # Restore to ASM for any subsequent tests + session.send_char("A") + + with mt.check("Debug: C=+D leaves Debug mode"): + session.send_char("D") + _send_ctrl_d(session) + header = _header_line(session) + if "Dbg" in header: + raise mt.Failure(f"C=+D must clear Dbg: {header!r}") + + with mt.check("Debug: D over without captured context executes from cursor"): + _reopen_monitor(session) + mt.write_rest_memory(rest_host, 0xC040, bytes([0xA9, 0x66, 0xEA, 0x4C, 0x42, 0xC0])) + session.goto("C040") + session.send_char("A") + session.send_char("D") # Over from the restored Debug cursor, not live snapshot state + parsed = _wait_for_pc(session, "C042") + if parsed["ac"] != "66": + raise mt.Failure(f"No-context Over should execute LDA #$66, got {parsed!r}") + _ensure_no_debug(session) + + +# --------------------------------------------------------------------------- +# Helpers for the BRK orchestrator tests below. + +def _ensure_no_debug(session: "mt.MonitorSession") -> None: + """Leave Debug mode if currently active.""" + deadline = time.time() + 3.0 + sent = False + while time.time() < deadline: + header = _header_line(session) + if "Dbg" not in header: + if sent: + time.sleep(0.2) + return + if not sent: + _send_ctrl_d(session) + session.capture() + sent = True + time.sleep(0.1) + raise mt.Failure("Could not leave Debug mode") + + +def _reopen_monitor(session: "mt.MonitorSession") -> None: + try: + _ensure_no_debug(session) + except mt.Failure: + # The previous command may already have left the monitor. Continue + # with the same CTRL+O entry path used by the normal telnet harness. + pass + last_error = None + for _ in range(6): + try: + snap = session.send_key("CTRL_O") + snap.find_status_line() + return + except mt.Failure as exc: + last_error = exc + raise mt.Failure(f"Could not re-enter monitor: {last_error}") + + +def run_ram_edit_regression_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Prove ASM Edit at $2000 writes real RAM and refreshes ASM/Hex readback.""" + + base = 0x2000 + seed = bytes([0xFF] * 16) + program = bytes([ + 0xA9, 0x01, # LDA #$01 + 0x8D, 0x20, 0xD0, # STA $D020 + 0xEE, 0x20, 0xD0, # INC $D020 + 0x4C, 0x05, 0x20, # JMP $2005 + ]) + + with mt.check("Debug: ASM Edit at $2000 writes RAM and refreshes ASM/Hex"): + _reopen_monitor(session) + mt.write_rest_memory(rest_host, base, seed) + seeded = mt.read_rest_memory(rest_host, base, len(seed)) + if seeded != seed: + raise mt.Failure(f"$2000 seed did not round-trip before edit: {seeded.hex().upper()}") + + snap = session.goto(f"{base:04X}") + snap = session.send_char("A") + _assert_no_debug_modal_snapshot(snap, "$2000 RAM edit setup") + row = _disassembly_row(snap, base) + if "[RAM]" not in row or "[KRN]" in row or "[BAS]" in row or "[I/O]" in row: + raise mt.Failure(f"$2000 must be ordinary RAM before edit, got: {row!r}\n{snap.text()}") + + snap = session.send_char("E") + if "Edit" not in _header_line(session): + raise mt.Failure(f"$2000 ASM edit did not enter Edit mode:\n{snap.text()}") + + commands = ( + ("LDA#$01", "LDA #$01"), + ("STA$D020", "STA $D020"), + ("INC$D020", "INC $D020"), + ("JMP$2005", "JMP $2005"), + ) + for typed, label in commands: + for ch in typed: + snap = session.send_char(ch) + snap = session.send_key("ENTER") + _assert_no_debug_modal_snapshot(snap, f"$2000 ASM edit {label}") + + snap = session.send_key("ESC") + if "Edit" in _header_line(session): + raise mt.Failure(f"$2000 ASM edit did not leave Edit mode:\n{snap.text()}") + + readback = mt.read_rest_memory(rest_host, base, len(program)) + if readback != program: + raise mt.Failure( + "$2000 ASM Edit bytes are not in RAM:\n" + f" expected: {program.hex().upper()}\n" + f" actual: {readback.hex().upper()}\n" + f"{snap.text()}") + + snap = session.goto(f"{base:04X}") + snap = session.send_char("A") + _assert_no_debug_modal_snapshot(snap, "$2000 ASM edit ASM readback") + expected_rows = ( + (0x2000, "A9 01", "LDA #$01"), + (0x2002, "8D 20 D0", "STA $D020"), + (0x2005, "EE 20 D0", "INC $D020"), + (0x2008, "4C 05 20", "JMP $2005"), + ) + for address, raw, text in expected_rows: + row = _disassembly_row(snap, address) + if raw not in row or text not in row or "[RAM]" not in row: + raise mt.Failure( + f"$2000 ASM readback row ${address:04X} mismatch: {row!r}\n{snap.text()}") + if "FF" in row[:15]: + raise mt.Failure(f"$2000 ASM readback still shows FF in row: {row!r}\n{snap.text()}") + + snap = mt.ensure_hex_width(session, 8) + row0 = _memory_row(snap, base) + row8 = _memory_row(snap, base + 8) + monitor_bytes = mt.parse_memory_row(snap, base) + mt.parse_memory_row(snap, base + 8) + if monitor_bytes[:len(program)] != program: + raise mt.Failure( + "$2000 Hex view does not show the edited RAM bytes:\n" + f" row0: {row0!r}\n" + f" row8: {row8!r}\n" + f" expected: {program.hex().upper()}\n" + f" actual: {monitor_bytes[:len(program)].hex().upper()}\n" + f"{snap.text()}") + edited_tokens = (row0.split()[1:9] + row8.split()[1:4]) + if "FF" in edited_tokens: + raise mt.Failure( + f"$2000 Hex view still shows FF in edited bytes: {row0!r} / {row8!r}\n{snap.text()}") + + +def _parse_footer_values(values_line: str): + """Extract PC / AC / XR / YR / SP / SR-binary from the footer value row.""" + # Strip the window border. + body = values_line.lstrip("|+").rstrip("|+").rstrip() + # Positions inside the body track the firmware footer layout exactly. + fields = { + "pc": body[0:4], + "ac": body[5:7], + "xr": body[8:10], + "yr": body[11:13], + "sp": body[14:16], + "sr": body[17:25], + "irq": body[26:30], + "nmi": body[31:35], + } + return {k: v.strip() for k, v in fields.items()} + + +def _wait_for_pc(session: "mt.MonitorSession", expected_pc: str, + timeout: float = 6.0) -> dict: + """Poll the debug footer until PC matches `expected_pc`.""" + import time as _time + deadline = _time.time() + timeout + last = None + while _time.time() < deadline: + snap = session.capture() + _assert_no_debug_modal_snapshot(snap, f"Waiting for PC {expected_pc}") + values = _footer_value_line(session) + parsed = _parse_footer_values(values) + last = parsed + if parsed["pc"].upper() == expected_pc.upper(): + return parsed + _time.sleep(0.1) + raise mt.Failure(f"PC did not reach {expected_pc}; last footer={last!r} ({values!r})") + + +def _wait_for_pc_register(session: "mt.MonitorSession", expected_pc: str, + register: str, expected_value: str, + timeout: float = 6.0) -> dict: + """Poll until the footer reaches PC with a register value from the new stop.""" + import time as _time + deadline = _time.time() + timeout + last = None + register = register.lower() + while _time.time() < deadline: + snap = session.capture() + _assert_no_debug_modal_snapshot( + snap, f"Waiting for PC {expected_pc} {register.upper()}={expected_value}") + values = _footer_value_line(session) + parsed = _parse_footer_values(values) + last = parsed + if (parsed["pc"].upper() == expected_pc.upper() and + parsed.get(register, "").upper() == expected_value.upper()): + return parsed + _time.sleep(0.1) + raise mt.Failure( + f"PC/register did not reach {expected_pc} {register.upper()}={expected_value}; " + f"last footer={last!r} ({values!r})") + + +def _wait_for_pc_not(session: "mt.MonitorSession", previous_pc: str, + timeout: float = 6.0) -> dict: + import time as _time + deadline = _time.time() + timeout + last = None + while _time.time() < deadline: + snap = session.capture() + _assert_no_debug_modal_snapshot(snap, f"Waiting for PC to leave {previous_pc}") + values = _footer_value_line(session) + parsed = _parse_footer_values(values) + last = parsed + if parsed["pc"] and parsed["pc"].upper() != previous_pc.upper(): + return parsed + _time.sleep(0.1) + raise mt.Failure(f"PC did not advance from {previous_pc}; last footer={last!r}") + + +def _address_row_context(session: "mt.MonitorSession", pc: int, context: str) -> None: + snap = session.capture() + address_rows: list[tuple[int, str]] = [] + wanted = f"|{pc:04X} " + wanted_index = -1 + for y in range(mt.HEIGHT): + line = snap.line(y) + if (len(line) >= 6 and line[0] == "|" and "[" in line and + all(c in "0123456789ABCDEFabcdef" for c in line[1:5]) and + line[5] == " "): + if line.startswith(wanted): + wanted_index = len(address_rows) + address_rows.append((y, line)) + if wanted_index < 0: + raise mt.Failure(f"{context}: current PC row {pc:04X} not visible:\n{snap.text()}") + + +def _assert_flag_bits(label: str, parsed: dict, **expected: str) -> None: + sr = parsed["sr"] + if len(sr) != 8 or any(bit not in "01" for bit in sr): + raise mt.Failure(f"{label}: SR must be 8 binary digits, got {parsed!r}") + for flag, value in expected.items(): + actual = sr[FLAG_BIT_INDEX[flag]] + if actual != value: + raise mt.Failure( + f"{label}: expected {flag}={value}, got SR={sr} footer={parsed!r}") + + +def run_flag_control_flow_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Exercise flag capture and taken/not-taken control flow without duplication.""" + + # $C200: 18 CLC + # $C201: A9 00 LDA #$00 + # $C203: D0 02 BNE $C207 ; must fall through + # $C205: A9 80 LDA #$80 + # $C207: 10 02 BPL $C20B ; must fall through + # $C209: 38 SEC + # $C20A: 69 7F ADC #$7F + # $C20C: 30 02 BMI $C210 ; must fall through + # $C20E: B0 04 BCS $C214 ; must branch + # $C210: A9 EE LDA #$EE ; skipped when branch predictor is right + # $C212: EA NOP + # $C213: EA NOP + # $C214: EA NOP + # $C215: 4C 14 C2 JMP $C214 ; park live CPU after leaving Debug + program = bytes([ + 0x18, + 0xA9, 0x00, + 0xD0, 0x02, + 0xA9, 0x80, + 0x10, 0x02, + 0x38, + 0x69, 0x7F, + 0x30, 0x02, + 0xB0, 0x04, + 0xA9, 0xEE, + 0xEA, + 0xEA, + 0xEA, + 0x4C, 0x14, 0xC2, + ]) + + _reopen_monitor(session) + + with mt.check("Debug: flag/control-flow program loads at $C200"): + mt.write_rest_memory(rest_host, 0xC200, program) + readback = mt.read_rest_memory(rest_host, 0xC200, len(program)) + if readback != program: + raise mt.Failure(f"Flag/control-flow program readback mismatch: {readback.hex()}") + + with mt.check("Debug: flag capture and branch fall-through stay truthful across steps"): + session.goto("C200") + session.send_char("A") + session.send_char("D") + + session.send_char("D") + parsed = _wait_for_pc(session, "C201") + _assert_flag_bits("CLC", parsed, C="0") + + session.send_char("D") + parsed = _wait_for_pc(session, "C203") + _assert_flag_bits("LDA #$00", parsed, Z="1", N="0") + + session.send_char("D") + _wait_for_pc(session, "C205") + + session.send_char("D") + parsed = _wait_for_pc(session, "C207") + _assert_flag_bits("LDA #$80", parsed, Z="0", N="1") + + session.send_char("D") + _wait_for_pc(session, "C209") + + session.send_char("D") + parsed = _wait_for_pc(session, "C20A") + _assert_flag_bits("SEC", parsed, C="1") + + session.send_char("D") + parsed = _wait_for_pc(session, "C20C") + if parsed["ac"] != "00": + raise mt.Failure(f"ADC #$7F should wrap AC to $00, got {parsed!r}") + _assert_flag_bits("ADC #$7F", parsed, N="0", V="0", Z="1", C="1") + + session.send_char("D") + _wait_for_pc(session, "C20E") + + session.send_char("D") + parsed = _wait_for_pc(session, "C214") + if parsed["ac"] != "00": + raise mt.Failure(f"Taken BCS must skip LDA #$EE, got {parsed!r}") + _ensure_no_debug(session) + + +def run_refusal_and_return_edge_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Cover unsafe targets, undocumented-opcode gating, RTS, and RTI handoff.""" + + unsafe_program = bytes([0x00, 0x60, 0x40, 0x1A, 0xEA]) + rts_caller = bytes([0x20, 0x70, 0xC2, 0xEA, 0x4C, 0x64, 0xC2]) + rts_subroutine = bytes([0x60]) + rti_setup = bytes([ + 0xA9, 0xC2, + 0x48, + 0xA9, 0x90, + 0x48, + 0xA9, 0xA1, + 0x48, + 0x40, + ]) + rti_target = bytes([0xEA, 0x4C, 0x90, 0xC2]) + rts_non_jsr_stack = bytes([ + 0xA2, 0xFC, # $C2B0: LDX #$FC + 0x9A, # $C2B2: TXS + 0xA9, 0xFF, # $C2B3: LDA #$FF + 0x8D, 0xFD, 0x01, # $C2B5: STA $01FD + 0xA9, 0x21, # $C2B8: LDA #$21 + 0x8D, 0xFE, 0x01, # $C2BA: STA $01FE + 0x60, # $C2BD: RTS + 0xEA, # $C2BE: NOP + ]) + + _reopen_monitor(session) + + with mt.check("Debug: unsafe-target/refusal fixtures load at $C240/$C260/$C280"): + mt.write_rest_memory(rest_host, 0xC240, unsafe_program) + mt.write_rest_memory(rest_host, 0xC25F, bytes([0xEA])) + mt.write_rest_memory(rest_host, 0xC260, rts_caller) + mt.write_rest_memory(rest_host, 0xC270, rts_subroutine) + mt.write_rest_memory(rest_host, 0xC280, rti_setup) + mt.write_rest_memory(rest_host, 0xC290, rti_target) + mt.write_rest_memory(rest_host, 0xC2B0, rts_non_jsr_stack) + mt.write_rest_memory(rest_host, 0x21FD, bytes([0xEA])) + + with mt.check("Debug: BRK, RTS, and RTI refuse no-context Over without fabricating state"): + session.goto("C240") + session.send_char("A") + session.send_char("D") + for address in ("C240", "C241", "C242"): + session.goto(address) + session.send_char("D") + _wait_for_screen_text(session, "UNSAFE TARGET") + session.send_key("ENTER") + _wait_for_blank_debug_context(session) + _ensure_no_debug(session) + + with mt.check("Debug: O outside a traced subroutine says NOT IN SUBROUTINE"): + mt.write_rest_memory(rest_host, 0xC2A0, bytes([0xEE, 0x20, 0xD0, 0x4C, 0xA0, 0xC2])) + session.goto("C2A0") + session.send_char("A") + session.send_char("D") + session.send_char("U") + snap = _wait_for_screen_text(session, "NOT IN SUBROUTINE") + text = snap.text() + if "UNSAFE TARGET" in text: + raise mt.Failure(f"Invalid Step Out must not say UNSAFE TARGET:\n{text}") + session.send_key("ENTER") + _wait_for_blank_debug_context(session) + _ensure_no_debug(session) + + with mt.check("Debug: Over on RTS without active JSR frame says NOT IN SUBROUTINE (not PATCH FAILED)"): + _reopen_monitor(session) + session.goto("C2B0") + session.send_char("A") + session.send_char("D") + _wait_for_blank_debug_context(session) + for expected_pc in ("C2B2", "C2B3", "C2B5", "C2B8", "C2BA", "C2BD"): + session.send_char("D") + _wait_for_pc(session, expected_pc) + session.send_char("D") + snap = _wait_for_screen_text(session, "NOT IN SUBROUTINE") + text = snap.text() + if "PATCH FAILED" in text: + raise mt.Failure(f"RTS Over without active JSR must not say PATCH FAILED:\n{text}") + session.send_key("ENTER") + _ensure_no_debug(session) + + with mt.check("Debug: undocumented NOP is decoded by Undc but not debug-stepped"): + session.goto("C243") + session.send_char("A") + # The Undc display toggle is U OUTSIDE Debug only; inside Debug U is Step + # Out. Enable Undc here (before entering Debug) and verify $1A decodes as + # NOP, then enter Debug and confirm the undocumented opcode refuses to + # step regardless of the display flag. + if "Undc" not in _header_line(session): + session.send_char("U") + header = _header_line(session) + if "Undc" not in header: + raise mt.Failure(f"Undc flag must appear after U: {header!r}") + row = _disassembly_row(session.capture(), 0xC243) + if "NOP" not in row: + raise mt.Failure(f"Undc flag must decode $1A as NOP: {row!r}") + session.send_char("D") + session.send_char("D") + _wait_for_screen_text(session, "UNSUPPORTED OPCODE") + session.send_key("ENTER") + _wait_for_blank_debug_context(session) + _ensure_no_debug(session) + # Restore the Undc display toggle off (outside Debug). + if "Undc" in _header_line(session): + session.send_char("U") + + with mt.check("Debug: traced RTS lands on the caller continuation address"): + _reopen_monitor(session) + session.goto("C25F") + session.send_char("A") + session.send_char("D") + session.send_char("D") + _wait_for_pc(session, "C260") + session.send_char("T") + _wait_for_pc(session, "C270") + session.send_char("D") + _wait_for_pc(session, "C263") + _ensure_no_debug(session) + + with mt.check("Debug: RTI restores the stacked target PC and flags truthfully"): + _reopen_monitor(session) + session.goto("C280") + session.send_char("A") + session.send_char("D") + for expected_pc in ("C282", "C283", "C285", "C286", "C288", "C289"): + session.send_char("D") + _wait_for_pc(session, expected_pc) + session.send_char("D") + parsed = _wait_for_pc(session, "C290") + _assert_flag_bits("RTI", parsed, N="1", Z="0", C="1") + _ensure_no_debug(session) + + +def run_page_cross_and_indirect_jump_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Cover page-crossing branches and the 6502 indirect-JMP wrap quirk.""" + + branch_taken = bytes([ + 0xA9, 0x00, # $C1FC: LDA #$00 + 0xF0, 0x02, # $C1FE: BEQ $C202 (taken across page) + 0xA9, 0xEE, # $C200: LDA #$EE (must be skipped) + 0xEA, # $C202: NOP + 0x4C, 0x02, 0xC2, # $C203: JMP $C202 (stable cleanup loop) + ]) + branch_fallthrough = bytes([ + 0xA9, 0x01, # $C2FC: LDA #$01 + 0xF0, 0x02, # $C2FE: BEQ $C302 (not taken across page) + 0xA9, 0x44, # $C300: LDA #$44 (must execute) + 0xEA, # $C302: NOP + 0x4C, 0x02, 0xC3, # $C303: JMP $C302 (stable cleanup loop) + ]) + indirect_jmp = bytes([0x6C, 0xFF, 0xC4]) # JMP ($C4FF) + + _reopen_monitor(session) + + with mt.check("Debug: page-cross branch and indirect-JMP fixtures load"): + mt.write_rest_memory(rest_host, 0xC1FC, branch_taken) + mt.write_rest_memory(rest_host, 0xC2FC, branch_fallthrough) + mt.write_rest_memory(rest_host, 0xC320, indirect_jmp) + mt.write_rest_memory(rest_host, 0xC440, bytes([0x4C, 0x40, 0xC4])) # JMP $C440 + mt.write_rest_memory(rest_host, 0xC4FF, bytes([0x40])) + mt.write_rest_memory(rest_host, 0xC400, bytes([0xC4])) + mt.write_rest_memory(rest_host, 0xC500, bytes([0xC5])) + + with mt.check("Debug: taken branch across a page stops at the real target"): + session.goto("C1FC") + session.send_char("A") + session.send_char("D") + session.send_char("D") + _wait_for_pc(session, "C1FE") + session.send_char("D") + parsed = _wait_for_pc(session, "C202") + if parsed["ac"] != "00": + raise mt.Failure(f"Taken page-cross branch must skip LDA #$EE, got {parsed!r}") + _ensure_no_debug(session) + + with mt.check("Debug: not-taken branch across a page falls through correctly"): + _reopen_monitor(session) + session.goto("C2FC") + session.send_char("A") + session.send_char("D") + session.send_char("D") + _wait_for_pc(session, "C2FE") + session.send_char("D") + parsed = _wait_for_pc(session, "C300") + if parsed["ac"] != "01": + raise mt.Failure(f"Not-taken page-cross branch must preserve A=$01, got {parsed!r}") + session.send_char("D") + parsed = _wait_for_pc(session, "C302") + if parsed["ac"] != "44": + raise mt.Failure(f"Fall-through LDA #$44 did not execute after page-cross branch: {parsed!r}") + _ensure_no_debug(session) + + with mt.check("Debug: Over on JMP ($xxFF) follows the real 6502 page-wrap target"): + _reopen_monitor(session) + session.goto("C320") + session.send_char("A") + session.send_char("D") + session.send_char("D") + _wait_for_pc(session, "C440") + _ensure_no_debug(session) + + +def run_nested_out_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Prove Out unwinds the current stack frame, not just a trivial single-level call.""" + + main_program = bytes([ + 0xA9, 0x11, # $C360: LDA #$11 + 0x20, 0x80, 0xC3, # $C362: JSR $C380 + 0x8D, 0x91, 0xC1, # $C365: STA $C191 + 0x4C, 0x68, 0xC3, # $C368: JMP $C368 + ]) + outer_subroutine = bytes([ + 0x48, # $C380: PHA + 0xA9, 0x22, # $C381: LDA #$22 + 0x8D, 0x92, 0xC1, # $C383: STA $C192 + 0x20, 0xC0, 0xC3, # $C386: JSR $C3C0 + 0x68, # $C389: PLA + 0x60, # $C38A: RTS + ]) + inner_subroutine = bytes([ + 0xA9, 0x33, # $C3C0: LDA #$33 + 0x8D, 0x93, 0xC1, # $C3C2: STA $C193 + 0x60, # $C3C5: RTS + ]) + + _reopen_monitor(session) + + with mt.check("Debug: nested Out fixtures load with stack-changing outer frame"): + mt.write_rest_memory(rest_host, 0xC360, main_program) + mt.write_rest_memory(rest_host, 0xC380, outer_subroutine) + mt.write_rest_memory(rest_host, 0xC3C0, inner_subroutine) + mt.write_rest_memory(rest_host, 0xC191, bytes([0x00, 0x00, 0x00])) + + with mt.check("Debug: nested Out unwinds inner then outer caller frames truthfully"): + session.goto("C360") + session.send_char("A") + session.send_char("D") + session.send_char("D") + _wait_for_pc(session, "C362") + session.send_char("T") + _wait_for_pc(session, "C380") + session.send_char("D") + _wait_for_pc(session, "C381") + session.send_char("D") + _wait_for_pc(session, "C383") + session.send_char("D") + _wait_for_pc(session, "C386") + if mt.read_rest_memory(rest_host, 0xC192, 1)[0] != 0x22: + raise mt.Failure("Outer-frame side effect did not execute before entering the inner call") + session.send_char("T") + _wait_for_pc(session, "C3C0") + session.send_char("U") + parsed = _wait_for_pc(session, "C389") + if mt.read_rest_memory(rest_host, 0xC193, 1)[0] != 0x33: + raise mt.Failure(f"Inner Out did not execute the inner side effect: {parsed!r}") + if mt.read_rest_memory(rest_host, 0xC191, 1)[0] != 0x00: + raise mt.Failure("Inner Out must not run the caller-side store yet") + session.send_char("U") + parsed = _wait_for_pc(session, "C365") + session.send_char("D") + parsed = _wait_for_pc(session, "C368") + if mt.read_rest_memory(rest_host, 0xC191, 1)[0] != 0x11: + raise mt.Failure(f"Outer Out did not restore A for the caller-side store: {parsed!r}") + _ensure_no_debug(session) + + +def prove_step_out_breaks_after_active_jsr(rest_host: str, session: "mt.MonitorSession", + context: str) -> None: + """Hostile Step Out proof: decoy RTS opcodes must not influence the target.""" + + caller = bytes([ + 0x20, 0xE0, 0xC6, # $C6A0: JSR $C6E0 + 0x8D, 0xF0, 0xC6, # $C6A3: STA $C6F0 + 0x4C, 0xA6, 0xC6, # $C6A6: JMP $C6A6 + ]) + lower_helper = bytes([ + 0xEE, 0xF1, 0xC6, # $C6D0: INC $C6F1 + 0xA9, 0x44, # $C6D3: LDA #$44 + 0x60, # $C6D5: RTS (the actual return) + 0x60, # $C6D6: decoy RTS + 0xEA, # $C6D7: NOP padding + ]) + entry = bytes([ + 0x4C, 0xD0, 0xC6, # $C6E0: JMP $C6D0; current PC becomes < JSR target + 0x60, # $C6E3: decoy RTS + 0xEA, + 0x60, # $C6E5: decoy RTS + ]) + + _reopen_monitor(session) + + mt.write_rest_memory(rest_host, 0xC6A0, caller) + mt.write_rest_memory(rest_host, 0xC6D0, lower_helper) + mt.write_rest_memory(rest_host, 0xC6E0, entry) + mt.write_rest_memory(rest_host, 0xC6F0, bytes([0x00, 0x00])) + + if mt.read_rest_memory(rest_host, 0xC6A0, len(caller)) != caller: + raise mt.Failure(f"{context}: caller fixture did not round-trip") + if mt.read_rest_memory(rest_host, 0xC6D0, len(lower_helper)) != lower_helper: + raise mt.Failure(f"{context}: lower-helper fixture did not round-trip") + if mt.read_rest_memory(rest_host, 0xC6E0, len(entry)) != entry: + raise mt.Failure(f"{context}: entry fixture did not round-trip") + + session.goto("C6A0") + session.send_char("A") + session.send_char("D") + + session.send_char("T") + _wait_for_pc(session, "C6E0") + session.send_char("D") + _wait_for_pc(session, "C6D0") + + parsed = _step_and_assert_pc(session, "U", 0xC6A3, context) + side = mt.read_rest_memory(rest_host, 0xC6F0, 2) + if side != bytes([0x00, 0x01]): + raise mt.Failure( + f"{context}: Step Out must execute the actual subroutine body but " + f"stop before the caller-side STA; side={side.hex()} footer={parsed!r}") + if parsed["ac"] != "44": + raise mt.Failure(f"{context}: Step Out did not execute through the real RTS path: {parsed!r}") + + session.send_char("D") + _wait_for_pc(session, "C6A6") + if mt.read_rest_memory(rest_host, 0xC6F0, 1)[0] != 0x44: + raise mt.Failure(f"{context}: caller-side opcode after JSR did not execute after one Over") + _ensure_no_debug(session) + + +def prove_stop_debug_exit_resumes_current_context(rest_host: str, + session: "mt.MonitorSession", + context: str) -> None: + """Step the mandatory $2000 loop, stop Debug, exit, and prove it resumes.""" + + program = bytes.fromhex("EE21D04C0020") + + _reset_c64_core(rest_host) + _reopen_monitor(session) + mt.write_rest_memory(rest_host, 0x2000, program) + + session.goto("2000") + session.send_char("A") + session.send_char("D") + _step_and_assert_pc(session, "D", 0x2003, context) + + before_exit = mt.read_rest_memory(rest_host, 0xD021, 1)[0] + snap = session.send_key("ESC") + _assert_no_debug_modal_snapshot(snap, context) + if "Dbg" in _header_line(session): + raise mt.Failure(f"{context}: ESC did not leave Debug before monitor exit") + session.send_key("CTRL_O") + + after_exit = before_exit + deadline = time.time() + 2.0 + while time.time() < deadline: + time.sleep(0.1) + after_exit = mt.read_rest_memory(rest_host, 0xD021, 1)[0] + if after_exit != before_exit: + break + if after_exit == before_exit: + raise mt.Failure( + f"{context}: $D021 did not change after Stop Debugging + Exit; " + f"target did not resume from the current debug context") + if mt.read_rest_memory(rest_host, 0x2000, len(program)) != program: + raise mt.Failure(f"{context}: $2000 loop bytes changed after Stop Debugging") + + _reopen_monitor(session) + mt.write_rest_memory(rest_host, 0xC760, bytes([0xEA, 0xEA])) + session.goto("C760") + session.send_char("A") + session.send_char("D") + _step_and_assert_pc(session, "D", 0xC761, f"{context}: re-entry step") + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + + +def run_step_out_target_proof_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Dedicated E2E proof for stack-frame Step Out target selection.""" + + with mt.check("Debug: Step Out breaks after active JSR, not nearby RTS"): + prove_step_out_breaks_after_active_jsr( + rest_host, session, + "Step Out active-JSR target proof") + + +def run_cleanup_exit_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Hardware proof that Stop Debugging exits through the current CPU state.""" + + with mt.check("Debug: Stop Debugging + Exit resumes current $2000 context"): + prove_stop_debug_exit_resumes_current_context( + rest_host, session, + "Stop Debugging + Exit $2000 loop") + + +def run_breakpoint_reentry_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Ensure repeated Go from the current breakpoint re-arms cleanly.""" + + # $C300: EE 90 C1 INC $C190 + # $C303: AE 90 C1 LDX $C190 + # $C306: 4C 00 C3 JMP $C300 + program = bytes([ + 0xEE, 0x90, 0xC1, + 0xAE, 0x90, 0xC1, + 0x4C, 0x00, 0xC3, + ]) + + _reopen_monitor(session) + + with mt.check("Debug: breakpoint re-entry loop loads at $C300"): + mt.write_rest_memory(rest_host, 0xC300, program) + mt.write_rest_memory(rest_host, 0xC190, bytes([0x00])) + + with mt.check("Debug: repeated G from the current breakpoint skips once and re-arms cleanly"): + session.goto("C300") + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "breakpoint re-entry setup cleanup") + session.goto("C300") + _ensure_breakpoint_at(session, 0xC300, "$C300 re-entry breakpoint set") + + session.send_char("G") + _wait_for_pc(session, "C300") + if mt.read_rest_memory(rest_host, 0xC190, 1)[0] != 0x00: + raise mt.Failure("Initial breakpoint hit must stop before INC $C190 executes") + + session.send_char("G") + _wait_for_pc_register(session, "C300", "xr", "01") + if mt.read_rest_memory(rest_host, 0xC190, 1)[0] != 0x01: + raise mt.Failure("Second G from the active breakpoint must execute INC exactly once") + + _ensure_no_debug(session) + if mt.read_rest_memory(rest_host, 0xC300, 1)[0] != 0xEE: + raise mt.Failure("Breakpoint cleanup did not restore INC opcode at $C300") + + +def run_rom_single_step_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Exercise bare CPU-visible BASIC/KERNAL ROM stepping over Telnet.""" + + with mt.check("Debug: KERNAL ROM Step Into from $E000", u2=False, + u2_reason="U64 CPU-visible KERNAL ROM stepping is required"): + snap = _enter_rom_debug_at(session, 0xE000, "KRN", + "KERNAL Step Into $E000", "$E:KRN") + row = _disassembly_row(snap, 0xE000) + if "85 56" in row: + if "STA $56" not in row: + raise mt.Failure(f"Canonical $E000 bytes did not decode as STA $56: {row!r}") + expected_pc = 0xE002 + else: + expected_pc = 0xE000 + _instruction_length_from_row(row) + print(f"[info] non-canonical KERNAL $E000 row selected: {row}", flush=True) + try: + _step_and_assert_pc(session, "T", expected_pc, "KERNAL Step Into $E000") + except mt.Failure: + _dump_debug_scratch(rest_host, "KERNAL Step Into $E000 FAIL") + raise + _leave_debug_and_reset(rest_host, session) + + with mt.check("Debug: KERNAL ROM Step Over on visible JSR", u2=False, + u2_reason="U64 CPU-visible KERNAL ROM stepping is required"): + snap = _enter_rom_debug_at(session, 0xE002, "KRN", + "KERNAL Step Over JSR", "$E:KRN") + row = _disassembly_row(snap, 0xE002) + jsr_addr = 0xE002 + if "20 0F BC" in row: + if "JSR $BC0F" not in row: + raise mt.Failure(f"Canonical $E002 bytes did not decode as JSR $BC0F: {row!r}") + else: + jsr_addr, row = _find_visible_jsr_row(snap, "KRN") + session.goto(f"{jsr_addr:04X}") + print(f"[info] non-canonical KERNAL JSR row selected: {row}", flush=True) + expected_pc = jsr_addr + _instruction_length_from_row(row) + _step_and_assert_pc(session, "D", expected_pc, f"KERNAL Step Over ${jsr_addr:04X}") + _leave_debug_and_reset(rest_host, session) + + with mt.check("Debug: KERNAL ROM Step Into on visible JSR", u2=False, + u2_reason="U64 CPU-visible KERNAL ROM stepping is required"): + snap = _enter_rom_debug_at(session, 0xE002, "KRN", + "KERNAL Step Into JSR", "$E:KRN") + row = _disassembly_row(snap, 0xE002) + jsr_addr = 0xE002 + if "20 0F BC" in row: + if "JSR $BC0F" not in row: + raise mt.Failure(f"Canonical $E002 bytes did not decode as JSR $BC0F: {row!r}") + else: + jsr_addr, row = _find_visible_jsr_row(snap, "KRN") + session.goto(f"{jsr_addr:04X}") + print(f"[info] non-canonical KERNAL JSR row selected: {row}", flush=True) + target_pc = _jsr_target_from_row(row) + _step_and_assert_pc(session, "T", target_pc, f"KERNAL Step Into ${jsr_addr:04X}") + after = session.capture() + _assert_no_debug_modal_snapshot(after, "KERNAL Step Into JSR target") + if target_pc == 0xBC0F: + _assert_snapshot_contains(after, "[BAS]", "KERNAL Step Into JSR target") + _leave_debug_and_reset(rest_host, session) + + with mt.check("Debug: BASIC ROM Step Over on visible JSR", u2=False, + u2_reason="U64 CPU-visible BASIC ROM stepping is required"): + snap = _enter_rom_debug_at(session, 0xA800, "BAS", + "BASIC Step Over visible JSR", "$A:BAS") + jsr_addr, row = _find_visible_jsr_row(snap, "BAS") + if jsr_addr != 0xA800: + session.goto(f"{jsr_addr:04X}") + expected_pc = jsr_addr + _instruction_length_from_row(row) + _step_and_assert_pc(session, "D", expected_pc, f"BASIC Step Over ${jsr_addr:04X}") + _leave_debug_and_reset(rest_host, session) + + +def run_rom_breakpoint_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Prove BASIC/KERNAL ROM breakpoints patch, hit, clear, step, and restore.""" + + bootstrap_addr = 0xC540 + # Use actual executable ROM instructions with stable one-instruction + # stepping behavior. $A831 is BASIC END's CLC path, and $E018 is a KERNAL + # SEC instruction with enough surrounding instructions for viewport checks. + cases = ( + ("BASIC", 0xA831, "BAS"), + ("KERNAL", 0xE018, "KRN"), + ) + + for name, target, marker in cases: + with mt.check(f"Debug: {name} ROM breakpoint set/hit/remove/step", u2=False, + u2_reason="U64 volatile ROM-image patching is required"): + _reopen_monitor(session) + mt.ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + original = mt.read_rest_memory(rest_host, target, 1)[0] + if original == 0x00: + raise mt.Failure(f"{name} test address ${target:04X} already contains BRK") + bootstrap = bytes([ + 0x4C, target & 0xFF, target >> 8, # jump into the ROM target + ]) + mt.write_rest_memory(rest_host, bootstrap_addr, bootstrap) + + session.goto(f"{target:04X}") + session.send_char("A") + session.send_char("D") + lines = _capture_lines(session) + row = next((line for line in lines if line.startswith(f"|{target:04X} ")), "") + if f"[{marker}]" not in row: + raise mt.Failure(f"{name} row did not show ROM source marker [{marker}]: {row!r}") + + _clear_breakpoint_at(session, target, f"{name} stale ROM breakpoint clear") + _ensure_breakpoint_at(session, target, f"{name} ROM breakpoint set") + armed_row = _disassembly_row(session.capture(), target) + if "[BRK" not in armed_row: + raise mt.Failure(f"{name} ROM breakpoint row was not armed: {armed_row!r}") + session.goto(f"{bootstrap_addr:04X}") + session.send_char("G") + parsed = _wait_for_pc(session, f"{target:04X}") + _assert_no_debug_modal(session, f"{name} ROM breakpoint hit") + if parsed["pc"].upper() != f"{target:04X}": + raise mt.Failure(f"{name} ROM breakpoint did not hit target: {parsed!r}") + _address_row_context(session, target, f"{name} ROM breakpoint hit") + + session.send_char("R") + _assert_no_debug_modal(session, f"{name} ROM breakpoint clear") + session.last_command = f"CTRL_R_CLEAR_{name}" + session.sock.sendall(b"\x12") + text = session.capture().text() + if f"SET ${target:04X}" in text: + raise mt.Failure(f"{name} breakpoint remained in list after R clear:\n{text}") + session.send_key("ESC") + + session.send_char("D") + _assert_no_debug_modal(session, f"{name} ROM step after breakpoint") + stepped = _wait_for_pc_not(session, f"{target:04X}", timeout=20.0) + stepped_pc = int(stepped["pc"], 16) + if name == "BASIC" and not (0xA000 <= stepped_pc <= 0xBFFF): + raise mt.Failure(f"BASIC ROM step left BASIC unexpectedly: {stepped!r}") + if name == "KERNAL" and not (0xE000 <= stepped_pc <= 0xFFFF): + raise mt.Failure(f"KERNAL ROM step left KERNAL unexpectedly: {stepped!r}") + _address_row_context(session, stepped_pc, f"{name} ROM step") + + _ensure_no_debug(session) + restored = mt.read_rest_memory(rest_host, target, 1)[0] + if restored != original: + raise mt.Failure( + f"{name} ROM byte was not restored at ${target:04X}: " + f"expected ${original:02X}, got ${restored:02X}") + _restore_safe_banking_display_hygiene( + rest_host, session, f"{name} ROM breakpoint cleanup") + + +def run_kernal_basic_breakpoint_regression(rest_host: str, session: "mt.MonitorSession") -> None: + """Reproduce a KERNAL-to-BASIC ROM breakpoint continuation path.""" + + with mt.check("Debug: KERNAL $E002 G continues safely to BASIC $BC0F", u2=False, + u2_reason="U64 BASIC/KERNAL ROM breakpoints are required"): + _reset_c64_core(rest_host) + _reopen_monitor(session) + _ensure_no_debug(session) + mt.ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + + session.goto("BC0F") + session.send_char("A") + session.send_char("D") + for stale in (0xBC0F, 0xE005, 0xBC9B, 0xBCF2): + _clear_breakpoint_at(session, stale, f"${stale:04X} stale breakpoint clear") + session.goto("BC0F") + row = _disassembly_row(session.capture(), 0xBC0F) + if "[BAS]" not in row: + raise mt.Failure(f"$BC0F must be visible as BASIC ROM before breakpointing: {row!r}") + _ensure_breakpoint_at(session, 0xBC0F, "$BC0F breakpoint set") + + _enter_rom_debug_at(session, 0xE002, "KRN", "$E002 Go to $BC0F setup", "$E:KRN") + session.send_char("G") + parsed = _wait_for_pc(session, "BC0F") + _assert_no_debug_modal(session, "$E002 Go to $BC0F") + if parsed["pc"].upper() != "BC0F": + raise mt.Failure(f"$E002 Go did not stop at $BC0F: {parsed!r}") + + session.goto("BCF2") + row = _disassembly_row(session.capture(), 0xBCF2) + if "[BAS]" not in row: + raise mt.Failure(f"$BCF2 must be visible as BASIC ROM before breakpointing: {row!r}") + _ensure_breakpoint_at(session, 0xBCF2, "$BCF2 breakpoint set") + + session.send_char("G") + parsed = _wait_for_pc_not(session, "BC0F") + _assert_no_debug_modal(session, "$BC0F Go with $BCF2 armed") + if parsed["pc"].upper() == "BC0F": + raise mt.Failure(f"Continue from $BC0F did not advance: {parsed!r}") + + _clear_breakpoint_at(session, 0xBC0F, "$BC0F breakpoint clear") + _clear_breakpoint_at(session, 0xBCF2, "$BCF2 breakpoint clear") + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + + with mt.check("Debug: BASIC $BCF2 manual ROM breakpoint is reachable", u2=False, + u2_reason="U64 BASIC ROM breakpoints are required"): + _ensure_no_debug(session) + mt.write_rest_memory(rest_host, 0xC540, bytes([0x4C, 0xF2, 0xBC])) + session.goto("BCF2") + session.send_char("A") + session.send_char("D") + _clear_breakpoint_at(session, 0xBCF2, "$BCF2 stale breakpoint clear") + session.goto("BCF2") + row = _disassembly_row(session.capture(), 0xBCF2) + if "[BAS]" not in row: + raise mt.Failure(f"$BCF2 must be visible as BASIC ROM before breakpointing: {row!r}") + _ensure_breakpoint_at(session, 0xBCF2, "$BCF2 breakpoint set") + session.goto("C540") + session.send_char("G") + parsed = _wait_for_pc(session, "BCF2") + _assert_no_debug_modal(session, "$BCF2 manual breakpoint") + if parsed["pc"].upper() != "BCF2": + raise mt.Failure(f"Manual $BCF2 breakpoint did not hit: {parsed!r}") + _clear_breakpoint_at(session, 0xBCF2, "$BCF2 manual breakpoint clear") + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + + +def run_deep_kernal_basic_trace_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Trace a 4-deep RAM -> RAM -> KERNAL -> BASIC call chain over Telnet.""" + + main_program = bytes([ + 0xA9, 0x5A, # $C700: LDA #$5A + 0x20, 0x30, 0xC7, # $C702: JSR $C730 + 0x8D, 0xF0, 0xC7, # $C705: STA $C7F0 + 0x4C, 0x08, 0xC7, # $C708: JMP $C708 + ]) + outer_subroutine = bytes([ + 0x20, 0x50, 0xC7, # $C730: JSR $C750 + 0x60, # $C733: RTS + ]) + inner_subroutine = bytes([ + 0x48, # $C750: PHA + 0x20, 0x02, 0xE0, # $C751: JSR $E002 + 0x68, # $C754: PLA + 0x60, # $C755: RTS + ]) + + with mt.check("Debug: deep KERNAL/BASIC trace fixture loads at $C700", u2=False, + u2_reason="U64 BASIC/KERNAL ROM breakpoints are required"): + _reset_c64_core(rest_host) + _reopen_monitor(session) + mt.ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + mt.write_rest_memory(rest_host, 0xC700, main_program) + mt.write_rest_memory(rest_host, 0xC730, outer_subroutine) + mt.write_rest_memory(rest_host, 0xC750, inner_subroutine) + mt.write_rest_memory(rest_host, 0xC7F0, bytes([0x00])) + if mt.read_rest_memory(rest_host, 0xC700, len(main_program)) != main_program: + raise mt.Failure("Deep trace main fixture did not round-trip") + if mt.read_rest_memory(rest_host, 0xC730, len(outer_subroutine)) != outer_subroutine: + raise mt.Failure("Deep trace outer fixture did not round-trip") + if mt.read_rest_memory(rest_host, 0xC750, len(inner_subroutine)) != inner_subroutine: + raise mt.Failure("Deep trace inner fixture did not round-trip") + + with mt.check("Debug: deep trace uses D/T/G/O across RAM, KERNAL, and BASIC", u2=False, + u2_reason="U64 BASIC/KERNAL ROM breakpoints are required"): + session.goto("BC0F") + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "deep trace setup breakpoint cleanup") + session.goto("BC0F") + row = _disassembly_row(session.capture(), 0xBC0F) + if "[BAS]" not in row: + raise mt.Failure(f"$BC0F must be visible as BASIC ROM before breakpointing: {row!r}") + _ensure_breakpoint_at(session, 0xBC0F, "$BC0F BASIC breakpoint set") + + session.goto("C700") + session.send_char("D") + parsed = _wait_for_pc(session, "C702") + if parsed["ac"] != "5A": + raise mt.Failure(f"Deep trace LDA #$5A did not set AC: {parsed!r}") + session.send_char("T") + _wait_for_pc(session, "C730") + session.send_char("T") + _wait_for_pc(session, "C750") + session.send_char("D") + _wait_for_pc(session, "C751") + session.send_char("T") + _wait_for_pc(session, "E002") + row = _disassembly_row(session.capture(), 0xE002) + if "20 0F BC" not in row or "JSR $BC0F" not in row or "[KRN]" not in row: + raise mt.Failure(f"$E002 must be the canonical KERNAL JSR into BASIC: {row!r}") + + session.send_char("G") + parsed = _wait_for_pc(session, "BC0F") + _assert_no_debug_modal(session, "deep trace Go to BASIC breakpoint") + if parsed["pc"].upper() != "BC0F": + raise mt.Failure(f"Deep trace did not stop at BASIC breakpoint: {parsed!r}") + + session.goto("E005") + row = _disassembly_row(session.capture(), 0xE005) + if "[KRN]" not in row: + raise mt.Failure(f"$E005 must be visible as KERNAL ROM before breakpointing: {row!r}") + _ensure_breakpoint_at(session, 0xE005, "$E005 KERNAL return breakpoint set") + session.send_char("G") + _wait_for_pc(session, "E005") + _assert_no_debug_modal(session, "deep trace current BASIC breakpoint skip") + + session.send_char("U") + _wait_for_pc(session, "C754") + session.send_char("D") + parsed = _wait_for_pc(session, "C755") + if parsed["ac"] != "5A": + raise mt.Failure(f"PLA after KERNAL/BASIC return did not restore AC: {parsed!r}") + session.send_char("U") + _wait_for_pc(session, "C733") + session.send_char("U") + _wait_for_pc(session, "C705") + session.send_char("D") + _wait_for_pc(session, "C708") + if mt.read_rest_memory(rest_host, 0xC7F0, 1)[0] != 0x5A: + raise mt.Failure("Deep trace caller-side store did not execute after full unwind") + _clear_breakpoint_at(session, 0xBC0F, "$BC0F deep trace breakpoint clear") + _clear_breakpoint_at(session, 0xE005, "$E005 deep trace breakpoint clear") + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + + +def _banked_kernal_out_program(base: int, ready_addr: int) -> bytes: + payload = bytes([ + 0xEE, 0x20, 0xD0, # INC $D020 + 0x4C, 0x00, 0xE0, # JMP $E000 + ]) + payload_addr = base + 43 + program = bytes([ + 0x78, # SEI + 0xA9, 0x37, # LDA #$37 + 0x85, 0x00, # STA $00 + 0xA9, 0x35, # LDA #$35 + 0x85, 0x01, # STA $01 + 0xA2, 0x00, # LDX #$00 + 0xBD, payload_addr & 0xFF, payload_addr >> 8, + 0x9D, 0x00, 0xE0, # STA $E000,X + 0xE8, # INX + 0xE0, len(payload), # CPX #payload_end-payload + 0xD0, 0xF5, # BNE copy + 0xA9, 0xA5, # LDA #$A5 + 0x8D, ready_addr & 0xFF, ready_addr >> 8, + 0xEA, # ready: NOP + 0xEA, # NOP + 0xA9, 0x37, # LDA #$37 + 0x85, 0x00, # STA $00 + 0xA9, 0x35, # LDA #$35 + 0x85, 0x01, # STA $01 + 0xEA, # NOP + 0xEA, # NOP + 0xEA, # NOP + 0x4C, 0x00, 0xE0, # JMP $E000 + ]) + return program + payload + + +def _open_breakpoint_popup(session: "mt.MonitorSession", context: str) -> mt.Snapshot: + session.last_command = f"CTRL_R_{context}" + session.sock.sendall(b"\x12") + snap = session.capture() + if "BREAKPOINTS" not in snap.text(): + raise mt.Failure(f"{context}: breakpoint popup did not open:\n{snap.text()}") + return snap + + +def _assert_breakpoint_popup_contains(session: "mt.MonitorSession", + context: str, *patterns: str) -> mt.Snapshot: + snap = _open_breakpoint_popup(session, context) + text = snap.text() + for pattern in patterns: + if re.search(pattern, text, re.MULTILINE) is None: + raise mt.Failure(f"{context}: missing popup pattern {pattern!r}\n{text}") + return snap + + +def _select_monitor_view(session: "mt.MonitorSession", bank: int, + context: str) -> mt.Snapshot: + bank &= 0x07 + for _ in range(8): + snap = session.capture() + status = snap.line(snap.find_status_line()) + if f"CPU{bank}" in status or f"O{bank}" in status: + return snap + session.send_char("o") + snap = session.capture() + raise mt.Failure(f"{context}: could not select monitor view O{bank}\n{snap.text()}") + + +def _assert_rest_byte_changes(rest_host: str, address: int, context: str, + minimum_values: int = 3) -> None: + seen = set() + deadline = time.time() + 4.0 + while time.time() < deadline and len(seen) < minimum_values: + seen.add(mt.read_rest_memory(rest_host, address, 1)[0]) + time.sleep(0.05) + if len(seen) < minimum_values: + raise mt.Failure( + f"{context}: ${address:04X} did not keep changing; " + f"observed values={sorted(seen)!r}") + + +def _assert_rest_region_keeps_changing(rest_host: str, address: int, length: int, + context: str, minimum_cells: int = 2, + timeout: float = 4.0) -> None: + previous = mt.read_rest_memory(rest_host, address, length) + changed_cells: set[int] = set() + deadline = time.time() + timeout + while time.time() < deadline and len(changed_cells) < minimum_cells: + time.sleep(0.08) + current = mt.read_rest_memory(rest_host, address, length) + for offset, (before, after) in enumerate(zip(previous, current)): + if before != after: + changed_cells.add(offset) + previous = current + if len(changed_cells) < minimum_cells: + raise mt.Failure( + f"{context}: ${address:04X}-${address + length - 1:04X} did not keep " + f"changing in at least {minimum_cells} cells; changed={sorted(changed_cells)!r}") + + +def _assert_no_forced_cpu7_status(session: "mt.MonitorSession", context: str) -> mt.Snapshot: + snap = session.capture() + status = snap.line(snap.find_status_line()) + if "CPU7" in status or status.startswith("|C7") or " C7" in status: + raise mt.Failure(f"{context}: live CPU bank was forced to 7: {status!r}\n{snap.text()}") + if "CPU5" not in status and "C5O" not in status: + raise mt.Failure(f"{context}: expected live CPU5 status, got: {status!r}\n{snap.text()}") + return snap + + +def run_banked_breakpoint_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Prove monitor-view breakpoints and live $0001 execution stay separate.""" + + bootstrap_addr = 0xC880 + ready_addr = 0xC8F0 + capture_addr = bootstrap_addr + 27 + program = _banked_kernal_out_program(bootstrap_addr, ready_addr) + + with mt.check("Debug: KERNAL-out bank separation fixture reaches live CPU5", u2=False, + u2_reason="U64 CPU banking and volatile ROM-image breakpoints are required"): + _reset_c64_core(rest_host) + _reopen_monitor(session) + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "bank separation setup cleanup") + _ensure_no_debug(session) + _select_monitor_view(session, 7, "select KERNAL monitor view before bank capture") + mt.write_rest_memory(rest_host, ready_addr, bytes([0x00])) + mt.write_rest_memory(rest_host, bootstrap_addr, program) + session.goto(f"{capture_addr:04X}") + session.send_char("A") + session.send_char("D") + _clear_breakpoint_at(session, capture_addr, f"${capture_addr:04X} stale live-port breakpoint clear") + _ensure_breakpoint_at(session, capture_addr, f"${capture_addr:04X} live-port capture breakpoint set") + session.goto(f"{bootstrap_addr:04X}") + session.send_char("G") + _wait_for_pc(session, f"{capture_addr:04X}") + mt.wait_for_rest_byte(rest_host, ready_addr, 0xA5, timeout=4.0) + _clear_breakpoint_at(session, capture_addr, f"${capture_addr:04X} live-port capture breakpoint clear") + snap = mt.ensure_status(session, "C5O7 $A:BAS $D:I/O $E:KRN VIC") + status = snap.line(snap.find_status_line()) + if "C5O7" not in status or "$E:KRN" not in status: + raise mt.Failure(f"Footer must show live CPU5, monitor O7 KERNAL labels: {status!r}") + + with mt.check("Debug: KERNAL and RAM $E000 breakpoints coexist with target tags", u2=False, + u2_reason="U64 visible-ROM and RAM-under-KERNAL breakpoints are required"): + snap = session.goto("E000") + row = _disassembly_row(snap, 0xE000) + if "[KRN]" not in row or "STA $56" not in row: + raise mt.Failure(f"Monitor O7 view must still browse KERNAL at $E000: {row!r}") + header = _header_line(session) + if "Dbg" not in header: + session.send_char("D") + session.send_char("R") + _wait_for_screen_text(session, "BRK KRN, CPU RAM; not mapped now") + session.send_key("ENTER") + + _ensure_no_debug(session) + _select_monitor_view(session, 5, "select RAM-under-KERNAL monitor view") + mt.ensure_status(session, "CPU5 $A:RAM $D:I/O $E:RAM VIC") + session.goto("E000") + session.send_char("A") + row = _disassembly_row(session.capture(), 0xE000) + if "[RAM]" not in row or "INC $D020" not in row: + raise mt.Failure(f"Monitor O5 view must browse hidden RAM payload at $E000: {row!r}") + session.send_char("D") + session.send_char("R") + _assert_no_debug_modal(session, "$E000 RAM breakpoint set") + + snap = _assert_breakpoint_popup_contains( + session, + "mixed $E000 KRN/RAM breakpoint list", + r"^\|?\d SET\s+\$E000 KRN\b", + r"^\|?\d SET\s+\$E000 RAM\b", + ) + session.send_key_repeat("UP", 9) + session.send_char("E") + snap = session.capture() + if re.search(r"^\|?0 OFF\s+\$E000 KRN\b", snap.text(), re.MULTILINE) is None: + raise mt.Failure(f"Disabling KRN slot must retain its target tag:\n{snap.text()}") + session.send_char("E") + session.send_key("ESC") + + with mt.check("Debug: RAM-under-KERNAL breakpoint hits with KERNAL banked out", u2=False, + u2_reason="U64 live $0001 CPU5 breakpoint trapping is required"): + mt.ensure_status(session, "CPU5 $A:RAM $D:I/O $E:RAM VIC") + session.goto("E000") + if "Dbg" not in _header_line(session): + session.send_char("D") + session.send_char("G") + parsed = _wait_for_pc(session, "E000") + _assert_no_debug_modal(session, "$E000 RAM-under-KERNAL breakpoint hit") + if parsed["pc"].upper() != "E000": + raise mt.Failure(f"RAM-under-KERNAL breakpoint did not hit $E000: {parsed!r}") + row = _disassembly_row(session.capture(), 0xE000) + if "[RAM]" not in row or "INC $D020" not in row: + raise mt.Failure(f"Debug PC row must follow live RAM mapping: {row!r}") + + session.send_char("D") + parsed = _wait_for_pc(session, "E003") + _assert_no_debug_modal(session, "$E000 RAM-under-KERNAL step") + row = _disassembly_row(session.capture(), 0xE003) + if "[RAM]" not in row or "JMP $E000" not in row: + raise mt.Failure(f"Step from RAM-under-KERNAL must decode live bytes: {row!r}") + + with mt.check("Debug: mixed $E000 breakpoint cleanup restores both stores", u2=False, + u2_reason="U64 visible-ROM and hidden-RAM patch restoration are required"): + _clear_all_breakpoints(session, "bank separation final cleanup") + _ensure_no_debug(session) + mt.ensure_status(session, "CPU5 $A:RAM $D:I/O $E:RAM VIC") + session.goto("E000") + session.send_char("A") + row = _disassembly_row(session.capture(), 0xE000) + if "[BRK" in row or "INC $D020" not in row: + raise mt.Failure(f"Hidden RAM breakpoint byte was not restored: {row!r}") + + _ensure_no_debug(session) + _select_monitor_view(session, 7, "select KERNAL monitor view") + mt.ensure_status(session, "C5O7 $A:BAS $D:I/O $E:KRN VIC") + session.goto("E000") + session.send_char("A") + row = _disassembly_row(session.capture(), 0xE000) + if "[BRK" in row or "[KRN]" not in row or "STA $56" not in row: + raise mt.Failure(f"KERNAL ROM breakpoint byte was not restored: {row!r}") + _reset_c64_core(rest_host) + _reopen_monitor(session) + + +def _load_repeat_redebug_fixtures(rest_host: str) -> None: + hidden_bootstrap = bytes([ + 0x78, # SEI + 0xA2, 0x00, # LDX #$00 + 0xA9, 0x37, # LDA #$37 + 0x85, 0x00, # STA $00 + 0xA9, 0x35, # LDA #$35 + 0x85, 0x01, # STA $01 + 0x4C, 0x00, 0xE0, # JMP $E000 + ]) + hidden_payload = bytes([ + 0xFE, 0x00, 0x04, # INC $0400,X + 0xFE, 0x00, 0x05, # INC $0500,X + 0xE8, # INX + 0x8E, 0x21, 0xD0, # STX $D021 + 0x4C, 0x00, 0xE0, # JMP $E000 + ]) + ordinary_loop = bytes([ + 0xA2, 0x00, # LDX #$00 + 0xFE, 0x00, 0x06, # INC $0600,X + 0xFE, 0xE8, 0x06, # INC $06E8,X + 0xE8, # INX + 0x8E, 0x20, 0xD0, # STX $D020 + 0x4C, 0x02, 0xC3, # JMP $C302 + ]) + mt.write_rest_memory(rest_host, 0x0400, bytes([0x00]) * 0x3E8) + mt.write_rest_memory(rest_host, 0xC000, hidden_bootstrap) + mt.write_rest_memory(rest_host, 0xE000, hidden_payload) + mt.write_rest_memory(rest_host, 0xC300, ordinary_loop) + + +def _arm_loop_breakpoint_and_hit(session: "mt.MonitorSession", loop_addr: int, + start_addr: int, monitor_bank: int, + mapped_status: str, context: str) -> None: + _select_monitor_view(session, monitor_bank, f"{context}: select loop view") + session.goto(f"{loop_addr:04X}") + session.send_char("A") + header = _header_line(session) + if "Dbg" not in header: + session.send_char("D") + row = _disassembly_row(session.capture(), loop_addr) + if "[BRK" not in row: + session.send_char("R") + snap = session.capture() + if "not mapped now" in snap.text(): + session.send_key("ENTER") + _assert_no_debug_modal(session, f"{context}: loop breakpoint set") + session.goto(f"{start_addr:04X}") + session.send_char("G") + _wait_for_pc(session, f"{loop_addr:04X}") + mt.ensure_status(session, mapped_status) + _clear_breakpoint_at(session, loop_addr, f"{context}: clear initial loop breakpoint") + + +def _repeat_cancel_redebug_cycles(rest_host: str, session: "mt.MonitorSession", + label: str, loop_addr: int, monitor_bank: int, + mapped_status: str, evidence_addr: int, + evidence_len: int, first_pc: int, + second_pc: int, row_tokens: tuple[str, ...], + cycles: int = 3) -> None: + for cycle in range(1, cycles + 1): + _send_ctrl_d(session) + snap = session.capture() + if "Dbg" in _header_line(session): + raise mt.Failure(f"{label} cycle {cycle}: Ctrl-D did not leave Debug\n{snap.text()}") + _assert_rest_region_keeps_changing( + rest_host, evidence_addr, evidence_len, + f"{label} cycle {cycle} after cancelling Debug") + session.goto(f"{loop_addr:04X}") + session.send_char("A") + _select_monitor_view(session, monitor_bank, + f"{label} cycle {cycle}: restore loop monitor view") + session.send_char("D") + _assert_no_debug_modal(session, f"{label} cycle {cycle}: re-enter Debug") + if "CPU5" in mapped_status or mapped_status.startswith("C5"): + _assert_no_forced_cpu7_status(session, f"{label} cycle {cycle}: re-enter Debug") + else: + mt.ensure_status(session, mapped_status) + + session.send_char("D") + _wait_for_pc(session, f"{first_pc:04X}") + session.send_char("D") + _wait_for_pc(session, f"{second_pc:04X}") + row = _disassembly_row(session.capture(), second_pc) + for token in row_tokens: + if token not in row: + raise mt.Failure( + f"{label} cycle {cycle}: row ${second_pc:04X} missing {token!r}: " + f"{row!r}") + + +def _cancel_repeat_debug_and_reset(rest_host: str, session: "mt.MonitorSession", + label: str, evidence_addr: int, + evidence_len: int) -> None: + _send_ctrl_d(session) + snap = session.capture() + if "Dbg" in _header_line(session): + raise mt.Failure(f"{label}: Ctrl-D did not leave Debug\n{snap.text()}") + _assert_rest_region_keeps_changing( + rest_host, evidence_addr, evidence_len, + f"{label} after final Debug cancel") + _reset_monitor_and_c64(rest_host, session) + + +# Keep the former quarantine switch explicit and disabled so the repeated +# RAM-under-KERNAL redebug check remains part of every full-suite pass. +QUARANTINE_RAM_UNDER_KERNAL_REDEBUG_FLAKE = False + + +def run_repeat_redebug_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Repeat cancel/re-enter/step after Debug releases live looping code.""" + + with mt.check("Debug: repeated cancel/redebug ordinary RAM loop keeps running", + u2=False, + u2_reason="U64 repeated live Debug re-entry is required"): + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "repeat ordinary setup cleanup") + _ensure_no_debug(session) + _load_repeat_redebug_fixtures(rest_host) + _arm_loop_breakpoint_and_hit( + session, 0xC302, 0xC300, 7, + "CPU7 $A:BAS $D:I/O $E:KRN VIC", + "repeat ordinary") + _repeat_cancel_redebug_cycles( + rest_host, session, "ordinary RAM repeat redebug", + 0xC302, 7, "CPU7 $A:BAS $D:I/O $E:KRN VIC", + 0x0600, 0x1E8, 0xC305, 0xC308, ("[RAM]", "INX")) + _cancel_repeat_debug_and_reset( + rest_host, session, "ordinary RAM repeat redebug final cleanup", + 0x0600, 0x1E8) + + with mt.check("Debug: repeated cancel/redebug RAM-under-KERNAL loop keeps CPU5", + u2=False, + u2_reason="U64 RAM-under-KERNAL repeated live Debug re-entry is required"): + if QUARANTINE_RAM_UNDER_KERNAL_REDEBUG_FLAKE: + raise mt.SkipCheck( + "quarantined RAM-under-KERNAL repeated redebug check") + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "repeat RAM-under-KERNAL setup cleanup") + _ensure_no_debug(session) + _load_repeat_redebug_fixtures(rest_host) + _arm_loop_breakpoint_and_hit( + session, 0xE000, 0xC000, 5, + "CPU5 $A:RAM $D:I/O $E:RAM VIC", + "repeat RAM-under-KERNAL") + _repeat_cancel_redebug_cycles( + rest_host, session, "RAM-under-KERNAL repeat redebug", + 0xE000, 5, "CPU5 $A:RAM $D:I/O $E:RAM VIC", + 0x0400, 0x0200, 0xE003, 0xE006, ("[RAM]", "INX")) + _cancel_repeat_debug_and_reset( + rest_host, session, "RAM-under-KERNAL repeat redebug final cleanup", + 0x0400, 0x0200) + + +def run_banked_continue_no_breakpoints_tests(rest_host: str, + session: "mt.MonitorSession") -> None: + """Prove G/continue with no breakpoints keeps a KERNAL-out program running. + + Mandatory $01=$00 repro from the handover: + $C000: SEI; LDA #$00; STA $01; JMP $E000 (banks KERNAL out, bank 0) + $E000: INC $D021; JMP $E000 (RAM-under-KERNAL loop) + With $01=$00 the $D021 cell is plain RAM, so the live INC is observable as a + changing value through the raw REST memory path. Pressing G with no + persistent breakpoints must release the CPU back into this loop via the + register-restore stub (which preserves $0001 and does not depend on the + KERNAL NMI path), not via the KERNAL-dependent NMI trampoline that hangs + when KERNAL is banked out. + """ + + bootstrap = 0xC000 + payload = 0xE000 + boot = bytes([0x78, 0xA9, 0x00, 0x85, 0x01, 0x4C, 0x00, 0xE0]) + pay = bytes([0xEE, 0x21, 0xD0, 0x4C, 0x00, 0xE0]) + + with mt.check("Debug: $01=$00 continue repro reaches live CPU0 RAM-under-KERNAL", + u2=False, + u2_reason="U64 live $0001 CPU banking and RAM-under-KERNAL are required"): + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "continue-no-bp setup cleanup") + _ensure_no_debug(session) + # Write payload directly to RAM-under-KERNAL and the bootstrap (raw REST). + mt.write_rest_memory(rest_host, payload, pay) + mt.write_rest_memory(rest_host, bootstrap, boot) + # Monitor view 5 maps $E000 -> RAM, so the breakpoint targets RAM. The + # live execution bank will be 0, so the footer must show a C0O5 mismatch. + _select_monitor_view(session, 5, "select RAM view for $E000 breakpoint") + session.goto("E000") + session.send_char("A") + session.send_char("D") + # Setting a RAM-target breakpoint while the live CPU still maps $E000 as + # KERNAL (bank 7, before the program runs) raises the mismatch notice. + # This is expected; dismiss it. The breakpoint is still armed in RAM. + row = _disassembly_row(session.capture(), payload) + if "[BRK" not in row: + snap = session.send_char("R") + if "not mapped now" in snap.text(): + session.send_key("ENTER") + else: + _assert_no_debug_modal_snapshot(snap, "$01=$00 RAM breakpoint set") + row = _disassembly_row(session.capture(), payload) + if "[BRK" not in row: + raise mt.Failure(f"$01=$00 RAM breakpoint was not armed: {row!r}") + session.goto(f"{bootstrap:04X}") + session.send_char("G") + parsed = _wait_for_pc(session, "E000") + _assert_no_debug_modal(session, "$01=$00 $E000 breakpoint hit") + snap = session.capture() + status = snap.line(snap.find_status_line()) + if "C0O5" not in status: + raise mt.Failure( + f"Footer must show live CPU0 vs monitor view 5 mismatch (C0O5): {status!r}") + row = _disassembly_row(snap, payload) + if "[RAM]" not in row or "INC $D021" not in row: + raise mt.Failure(f"Debug PC row must follow live RAM mapping: {row!r}") + + with mt.check("Debug: G with no breakpoints keeps $01=$00 loop running", + u2=False, + u2_reason="U64 register-restore continue under non-standard banking is required"): + # Clear the breakpoint so G releases the CPU into free execution. + _clear_all_breakpoints(session, "continue-no-bp release cleanup") + # Seed $D021 (plain RAM at $01=$00) to a known low value, then continue. + mt.write_rest_memory(rest_host, 0xD021, bytes([0x00])) + session.send_char("G") + _assert_no_debug_modal(session, "$01=$00 continue G") + # The loop must increment $D021. Observe several raw reads change over a + # short window. A hang/forced-CPU7/lost-Telnet would leave it static. + _assert_rest_byte_changes( + rest_host, 0xD021, + "$01=$00 continue G (machine appears hung or forced back to CPU7)") + # $01=$00 deliberately hides I/O for this regression. Restore and prove + # safe display-compatible banking immediately after the destructive case. + _restore_safe_banking_display_hygiene(rest_host, session, "$01=$00 cleanup") + + with mt.check("Debug: $01=$35 continue with no breakpoints keeps I/O loop running", + u2=False, + u2_reason="U64 register-restore continue under KERNAL-out I/O banking is required"): + bootstrap_addr = 0xC880 + ready_addr = 0xC8F0 + capture_addr = bootstrap_addr + 27 + program = _banked_kernal_out_program(bootstrap_addr, ready_addr) + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "$01=$35 continue setup cleanup") + _ensure_no_debug(session) + _select_monitor_view(session, 5, "select RAM-under-KERNAL view for $01=$35 continue") + mt.write_rest_memory(rest_host, ready_addr, bytes([0x00])) + mt.write_rest_memory(rest_host, bootstrap_addr, program) + session.goto(f"{capture_addr:04X}") + session.send_char("A") + session.send_char("D") + _ensure_breakpoint_at(session, capture_addr, + f"${capture_addr:04X} $01=$35 payload-copy breakpoint set") + session.goto(f"{bootstrap_addr:04X}") + session.send_char("G") + _wait_for_pc(session, f"{capture_addr:04X}") + mt.wait_for_rest_byte(rest_host, ready_addr, 0xA5, timeout=4.0) + mt.ensure_status(session, "CPU5 $A:RAM $D:I/O $E:RAM VIC") + _clear_breakpoint_at(session, capture_addr, + f"${capture_addr:04X} $01=$35 payload-copy breakpoint clear") + session.goto("E000") + row = _disassembly_row(session.capture(), payload) + if "[RAM]" not in row or "INC $D020" not in row: + raise mt.Failure(f"$01=$35 payload copy did not install RAM loop: {row!r}") + _ensure_breakpoint_at(session, payload, "$01=$35 RAM-under-KERNAL breakpoint set") + session.send_char("G") + _wait_for_pc(session, "E000") + mt.ensure_status(session, "CPU5 $A:RAM $D:I/O $E:RAM VIC") + row = _disassembly_row(session.capture(), payload) + if "[RAM]" not in row or "INC $D020" not in row: + raise mt.Failure(f"$01=$35 Debug PC row must follow live RAM mapping: {row!r}") + _clear_all_breakpoints(session, "$01=$35 continue release cleanup") + mt.write_rest_memory(rest_host, 0xD020, bytes([0x00])) + session.send_char("G") + _assert_no_debug_modal(session, "$01=$35 continue G") + _assert_rest_byte_changes( + rest_host, 0xD020, + "$01=$35 continue G (machine appears hung or forced back to CPU7)") + _reset_c64_core(rest_host) + _reopen_monitor(session) + + with mt.check("Debug: $01=$37 continue with no breakpoints keeps baseline I/O loop running", + u2=False, + u2_reason="U64 register-restore continue under baseline banking is required"): + base = 0xC020 + ready = 0xC08F + loop = base + 14 + program = bytes([ + 0x78, # SEI + 0xA9, 0x37, # LDA #$37 + 0x85, 0x00, # STA $00 + 0xA9, 0x37, # LDA #$37 + 0x85, 0x01, # STA $01 + 0xA9, 0xA5, # LDA #$A5 + 0x8D, ready & 0xFF, ready >> 8, + 0xEE, 0x20, 0xD0, # INC $D020 + 0x4C, loop & 0xFF, loop >> 8, + ]) + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "$01=$37 continue setup cleanup") + _ensure_no_debug(session) + mt.write_rest_memory(rest_host, ready, bytes([0x00])) + mt.write_rest_memory(rest_host, base, program) + _select_monitor_view(session, 7, "select baseline view for $01=$37 continue") + session.goto(f"{loop:04X}") + session.send_char("A") + session.send_char("D") + _ensure_breakpoint_at(session, loop, f"${loop:04X} baseline loop breakpoint set") + session.goto(f"{base:04X}") + session.send_char("G") + _wait_for_pc(session, f"{loop:04X}") + mt.wait_for_rest_byte(rest_host, ready, 0xA5, timeout=4.0) + mt.ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + _clear_all_breakpoints(session, "$01=$37 continue release cleanup") + mt.write_rest_memory(rest_host, 0xD020, bytes([0x00])) + session.send_char("G") + _assert_no_debug_modal(session, "$01=$37 continue G") + _assert_rest_byte_changes( + rest_host, 0xD020, + "$01=$37 continue G (machine appears hung or forced out of CPU7)") + _reset_c64_core(rest_host) + _reopen_monitor(session) + + with mt.check("Debug: continue with breakpoints preserves live CPU5 backing store", + u2=False, + u2_reason="U64 concrete backing-store breakpoints under KERNAL-out banking are required"): + bootstrap_addr = 0xC880 + boot = bytes([ + 0x78, # SEI + 0xA9, 0x37, # LDA #$37 + 0x85, 0x00, # STA $00 + 0xA9, 0x35, # LDA #$35 + 0x85, 0x01, # STA $01 + 0x4C, 0x00, 0xE0, # JMP $E000 + ]) + pay = bytes([0xEE, 0x20, 0xD0, 0x4C, 0x00, 0xE0]) + _ensure_no_debug(session) + _reset_c64_core(rest_host) + _reopen_monitor(session) + session.send_char("A") + session.send_char("D") + _clear_all_breakpoints(session, "continue-with-bp setup cleanup") + _ensure_no_debug(session) + _select_monitor_view(session, 5, "select RAM view for continue-with-bp entry") + mt.write_rest_memory(rest_host, payload, pay) + mt.write_rest_memory(rest_host, bootstrap_addr, boot) + session.goto("E000") + row = _disassembly_row(session.capture(), payload) + if "[RAM]" not in row or "INC $D020" not in row: + raise mt.Failure(f"Continue-with-bp RAM payload was not visible: {row!r}") + _select_monitor_view(session, 5, "select RAM view for $E003 RAM breakpoint") + session.goto("E003") + session.send_char("A") + session.send_char("D") + session.send_char("R") + _wait_for_screen_text(session, "BRK RAM, CPU KRN; not mapped now") + session.send_key("ENTER") + row = _disassembly_row(session.capture(), 0xE003) + if "[BRK" not in row: + raise mt.Failure(f"$E003 RAM breakpoint was not set: {row!r}") + session.goto(f"{bootstrap_addr:04X}") + session.send_char("G") + _wait_for_pc(session, "E003") + mt.ensure_status(session, "CPU5 $A:RAM $D:I/O $E:RAM VIC") + row = _disassembly_row(session.capture(), 0xE003) + if "[RAM]" not in row or "JMP $E000" not in row: + raise mt.Failure( + f"Continue-with-breakpoints must hit RAM $E003, not KERNAL: {row!r}") + _clear_all_breakpoints(session, "continue-with-bp final cleanup") + _reset_monitor_and_c64(rest_host, session) + + +def run_brk_orchestrator_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Drive the live BRK trampoline through Over / Trace / Out / Go.""" + + # Layout in $C000-$C00F: a deterministic program we can step through. + # $C000: A9 AA LDA #$AA + # $C002: A2 BB LDX #$BB + # $C004: A0 CC LDY #$CC + # $C006: EA NOP + # $C007: 20 0D C0 JSR $C00D + # $C00A: 4C 0A C0 JMP $C00A ; infinite loop after RTS + # $C00D: A9 11 LDA #$11 ; called subroutine + # $C00F: 60 RTS + program = bytes([ + 0xA9, 0xAA, + 0xA2, 0xBB, + 0xA0, 0xCC, + 0xEA, + 0x20, 0x0D, 0xC0, + 0x4C, 0x0A, 0xC0, + 0xA9, 0x11, + 0x60, + ]) + _reopen_monitor(session) + + with mt.check("Debug: load test program at $C000 (via REST)"): + mt.write_rest_memory(rest_host, 0xC000, program) + # Sanity-read it back; the monitor REST endpoint occasionally needs a + # second tick to settle when poke / peek hit the same DMA aperture. + readback = mt.read_rest_memory(rest_host, 0xC000, len(program)) + if readback != program: + raise mt.Failure( + f"Test program did not round-trip via REST:\n" + f" wrote: {program.hex()}\n" + f" read: {readback.hex()}") + + with mt.check("Debug: G with BP at $C006 stops with A=$AA X=$BB Y=$CC"): + # Park the cursor at $C000 (G uses cursor as start PC when no + # captured context exists yet) and enter Debug mode. + session.goto("C000") + session.send_char("A") # ensure ASM view + session.send_char("D") # enter Debug + # Set a breakpoint at $C006 by parking the cursor there and pressing R. + session.send_char("J") + session.send_text("C006\r", "J C006") + _ensure_breakpoint_at(session, 0xC006, "$C006 orchestrator breakpoint set") + # Bring cursor back to $C000 so G's start_pc fallback runs from there. + session.send_char("J") + session.send_text("C000\r", "J C000") + # Go: NMI-jump to $C000, run, BRK at $C006, capture. + session.send_char("G") + parsed = _wait_for_pc(session, "C006") + if parsed["ac"] != "AA": + raise mt.Failure(f"AC expected AA, got {parsed!r}") + if parsed["xr"] != "BB": + raise mt.Failure(f"XR expected BB, got {parsed!r}") + if parsed["yr"] != "CC": + raise mt.Failure(f"YR expected CC, got {parsed!r}") + # SR must be a binary string with the B (break) bit set after BRK. + if len(parsed["sr"]) != 8 or any(c not in "01" for c in parsed["sr"]): + raise mt.Failure(f"SR must be 8 binary digits, got {parsed!r}") + + with mt.check("Debug: Over from $C006 steps NOP and stops at JSR ($C007)"): + # Cursor is at $C006 (the NOP). D = Over: execute the NOP, stop at C007 (JSR). + session.send_char("D") + parsed = _wait_for_pc(session, "C007") + + with mt.check("Debug: Trace into JSR enters subroutine at $C00D"): + # Trace at JSR: should land at the JSR target ($C00D). + session.send_char("T") + parsed = _wait_for_pc(session, "C00D") + + with mt.check("Debug: Out from inside the subroutine returns to $C00A"): + # We are inside the subroutine at $C00D. Out should run LDA #$11 + # then RTS and stop at the instruction after the JSR (i.e. $C00A). + session.send_char("U") + parsed = _wait_for_pc(session, "C00A") + if parsed["ac"] != "11": + raise mt.Failure(f"Subroutine should have set AC to $11, got {parsed!r}") + + with mt.check("Debug: cleanup restores user bytes at the breakpoint"): + _clear_breakpoint_at(session, 0xC006, "$C006 orchestrator breakpoint clear") + _ensure_no_debug(session) + # The byte at $C006 must be the original NOP again. + b = mt.read_rest_memory(rest_host, 0xC006, 1)[0] + if b != 0xEA: + raise mt.Failure( + f"BRK was not restored at $C006: read ${b:02X}, expected $EA") + # Vector $0316/$0317 must be the saved value, not pointing into our + # cassette-buffer trampoline. + vec = mt.read_rest_memory(rest_host, 0x0316, 2) + vec_addr = vec[0] | (vec[1] << 8) + if 0x033C <= vec_addr < 0x0400: + raise mt.Failure( + f"BRK vector still points into the debug trampoline area: ${vec_addr:04X}") + + +def run_side_effect_step_tests(rest_host: str, session: "mt.MonitorSession") -> None: + """Prove stepping executes real instructions by checking RAM side effects.""" + + # $C100: A9 10 LDA #$10 + # $C102: 8D 80 C1 STA $C180 + # $C105: 20 30 C1 JSR $C130 + # $C108: A9 00 LDA #$00 + # $C10A: F0 05 BEQ $C111 + # $C10C: A9 EE LDA #$EE ; skipped when branch is taken + # $C10E: 8D 82 C1 STA $C182 ; skipped when branch is taken + # $C111: 4C 18 C1 JMP $C118 + # $C114: EA NOP ; padding / should not execute + # $C115: EA NOP + # $C116: EA NOP + # $C117: EA NOP + # $C118: A9 44 LDA #$44 + # $C11A: 8D 83 C1 STA $C183 + # $C11D: 4C 1D C1 JMP $C11D + # $C130: EE 81 C1 INC $C181 + # $C133: 60 RTS + program = bytes([ + 0xA9, 0x10, + 0x8D, 0x80, 0xC1, + 0x20, 0x30, 0xC1, + 0xA9, 0x00, + 0xF0, 0x05, + 0xA9, 0xEE, + 0x8D, 0x82, 0xC1, + 0x4C, 0x18, 0xC1, + 0xEA, 0xEA, 0xEA, 0xEA, + 0xA9, 0x44, + 0x8D, 0x83, 0xC1, + 0x4C, 0x1D, 0xC1, + ]) + subroutine = bytes([0xEE, 0x81, 0xC1, 0x60]) + + _reopen_monitor(session) + + with mt.check("Debug: load side-effect stepping program"): + mt.write_rest_memory(rest_host, 0xC100, program) + mt.write_rest_memory(rest_host, 0xC130, subroutine) + mt.write_rest_memory(rest_host, 0xC180, bytes([0x00, 0x00, 0x00, 0x00])) + readback = mt.read_rest_memory(rest_host, 0xC100, len(program)) + if readback != program: + raise mt.Failure(f"Side-effect program readback mismatch: {readback.hex()}") + + with mt.check("Debug: Over STA writes $C180"): + session.goto("C100") + session.send_char("A") + session.send_char("D") + session.send_char("D") # LDA #$10 + _wait_for_pc(session, "C102") + session.send_char("D") # STA $C180 + _wait_for_pc(session, "C105") + side = mt.read_rest_memory(rest_host, 0xC180, 4) + if side != bytes([0x10, 0x00, 0x00, 0x00]): + raise mt.Failure(f"STA side effect missing after Over: {side.hex()}") + + with mt.check("Debug: Over JSR runs subroutine side effect and stops after call"): + session.send_char("D") + parsed = _wait_for_pc(session, "C108") + side = mt.read_rest_memory(rest_host, 0xC180, 4) + if side != bytes([0x10, 0x01, 0x00, 0x00]): + raise mt.Failure(f"JSR side effect missing after Over: footer={parsed!r} side={side.hex()}") + + with mt.check("Debug: Over taken branch skips skipped-store side effect"): + session.send_char("D") # LDA #$00, sets Z + _wait_for_pc(session, "C10A") + session.send_char("D") # BEQ $C111, taken + _wait_for_pc(session, "C111") + side = mt.read_rest_memory(rest_host, 0xC180, 4) + if side != bytes([0x10, 0x01, 0x00, 0x00]): + raise mt.Failure(f"Taken branch executed skipped store: {side.hex()}") + + with mt.check("Debug: Over JMP reaches target and later store mutates $C183"): + session.send_char("D") # JMP $C118 + _wait_for_pc(session, "C118") + session.send_char("D") # LDA #$44 + _wait_for_pc(session, "C11A") + session.send_char("D") # STA $C183 + _wait_for_pc(session, "C11D") + side = mt.read_rest_memory(rest_host, 0xC180, 4) + if side != bytes([0x10, 0x01, 0x00, 0x44]): + raise mt.Failure(f"JMP-target store side effect missing: {side.hex()}") + _ensure_no_debug(session) + + with mt.check("Debug: Trace JSR enters before subroutine side effect, then Over executes it"): + mt.write_rest_memory(rest_host, 0xC181, bytes([0x00])) + _reopen_monitor(session) + session.goto("C105") + session.send_char("A") + session.send_char("D") + session.send_char("T") # trace into JSR target, before INC executes + _wait_for_pc(session, "C130") + side = mt.read_rest_memory(rest_host, 0xC180, 4) + if side[1] != 0x00: + raise mt.Failure(f"Trace into JSR executed subroutine too early: {side.hex()}") + session.send_char("D") # Over INC $C181 + _wait_for_pc(session, "C133") + side = mt.read_rest_memory(rest_host, 0xC180, 4) + if side[1] != 0x01: + raise mt.Failure(f"Over inside traced subroutine did not execute INC: {side.hex()}") + _ensure_no_debug(session) + + # Stack side effects of step mode must match a real run: the NMI used to + # launch the first step must not leak its 3-byte frame onto the stack. Trace + # into the JSR (the first, NMI-launched step), confirm the real return + # address is on the stack at the SP-relative slot RTS will read, and confirm + # the JSR push / RTS pop balance the stack pointer exactly (+2 / -2). The + # precise 3-byte NMI-frame balance is pinned deterministically by the host + # unit test test_nmi_launch_trampoline_balances_stack. + with mt.check("Debug: step-mode JSR/RTS keep the stack balanced and return address correct"): + _reopen_monitor(session) + session.goto("C105") + session.send_char("A") + session.send_char("D") + session.send_char("T") # first step: NMI launch, Trace into JSR + into = _wait_for_pc(session, "C130") + sp_into = int(into["sp"], 16) + # JSR pushed the return address ($C105 + 2 = $C107): low byte at + # $0100+SP+1, high byte at $0100+SP+2 - exactly what RTS will pull. + stack = mt.read_rest_memory(rest_host, 0x0100, 256) + ret = stack[(sp_into + 1) & 0xFF] | (stack[(sp_into + 2) & 0xFF] << 8) + if ret != 0xC107: + raise mt.Failure( + f"JSR return address not on the stack at the SP slot RTS reads: " + f"got ${ret:04X}, SP=${sp_into:02X}") + session.send_char("D") # Over INC $C181 + _wait_for_pc(session, "C133") + out = _step_and_assert_pc(session, "D", 0xC108, + "step-mode JSR/RTS stack balance") # Over RTS + sp_back = int(out["sp"], 16) + if ((sp_back - sp_into) & 0xFF) != 2: + raise mt.Failure( + f"JSR/RTS did not balance the stack: SP ${sp_into:02X} -> ${sp_back:02X} " + f"(expected +2)") + _ensure_no_debug(session) + + +TEST_GROUPS = ( + ("ram-edit", run_ram_edit_regression_tests), + ("debug", run_debug_tests), + ("flags", run_flag_control_flow_tests), + ("refusal", run_refusal_and_return_edge_tests), + ("page-cross", run_page_cross_and_indirect_jump_tests), + ("nested-out", run_nested_out_tests), + ("step-out-target", run_step_out_target_proof_tests), + ("rom-single-step", run_rom_single_step_tests), + ("rom-breakpoints", run_rom_breakpoint_tests), + ("kernal-basic-breakpoint", run_kernal_basic_breakpoint_regression), + ("deep-trace", run_deep_kernal_basic_trace_tests), + ("banked-breakpoints", run_banked_breakpoint_tests), + ("repeat-redebug", run_repeat_redebug_tests), + ("banked-continue-no-breakpoints", run_banked_continue_no_breakpoints_tests), + ("brk-orchestrator", run_brk_orchestrator_tests), + ("side-effect-step", run_side_effect_step_tests), + ("cleanup-exit", run_cleanup_exit_tests), + ("breakpoint-reentry", run_breakpoint_reentry_tests), +) + + +def _parse_selected_tests(parser: argparse.ArgumentParser, + selected: list[str] | None) -> list[str] | None: + if not selected: + return None + names = [] + for raw in selected: + names.extend(name.strip() for name in raw.split(",") if name.strip()) + valid = {name for name, _runner in TEST_GROUPS} + unknown = sorted(set(names) - valid) + if unknown: + parser.error( + "unknown --test value(s): " + f"{', '.join(unknown)}; choose from {', '.join(sorted(valid))}") + return names + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Validate Machine Code Monitor Debug mode over the standard telnet service") + parser.add_argument("--host", default=os.environ.get("U64_MONITOR_HOST", "u64")) + parser.add_argument("--port", type=int, default=int(os.environ.get("U64_MONITOR_PORT", "23"))) + parser.add_argument("--rest-host", default=os.environ.get("U64_MONITOR_REST_HOST")) + parser.add_argument("--password", default=os.environ.get("U64_MONITOR_PASSWORD")) + parser.add_argument("--timeout", type=float, default=float(os.environ.get("U64_MONITOR_TIMEOUT", "5.0"))) + parser.add_argument("--target", choices=("u64", "u2"), + default=os.environ.get("U64_MONITOR_TARGET", "u64"), + help="Target hardware. 'u2' skips U64-only features (REST API, " + "BASIC/KERNAL ROM stepping, CPU bank cycling, VIC bank).") + parser.add_argument("--keep-going", action="store_true", + default=os.environ.get("U64_MONITOR_KEEP_GOING", "").lower() in ("1", "true", "yes"), + help="Continue after a check fails, logging verbose context per failure.") + parser.add_argument("-t", "--test", action="append", metavar="NAME[,NAME...]", + help="Run only the named test group(s). Repeat or comma-separate. " + f"Choices: {', '.join(name for name, _runner in TEST_GROUPS)}.") + parser.add_argument("--list-tests", action="store_true", + help="List available --test names and exit.") + parser.add_argument("--chunk-size", type=int, default=SUITE_CHUNK_SIZE, + help="Run the suite in chunks of this many groups, with a " + "cool-down + extra reset at each chunk boundary. " + "0 disables chunking.") + parser.add_argument("--chunk-cooldown", type=float, + default=SUITE_CHUNK_COOLDOWN_SECONDS, + help="Seconds to idle at each chunk boundary before the extra " + "reset.") + args = parser.parse_args() + selected_tests = _parse_selected_tests(parser, args.test) + if args.list_tests: + for name, _runner in TEST_GROUPS: + print(name) + return 0 + + mt.TestConfig.target = args.target + # In U2 mode the REST API is typically unreachable; default to keep-going + # so all failures land in the same console capture rather than stopping + # at the first connection error. + mt.TestConfig.keep_going = args.keep_going or args.target == "u2" + mt.TestConfig.failures = [] + mt.TestConfig.skipped = [] + + rest_host = args.rest_host or args.host + if args.target == "u2": + if not mt.rest_available(rest_host): + print(f"[info] target=u2 and REST unreachable on {rest_host}; " + f"REST-dependent checks will SKIP", flush=True) + else: + print(f"[info] target=u2 with REST reachable on {rest_host}", flush=True) + session = None + aborted = False + try: + runners = dict(TEST_GROUPS) + ordered_tests = selected_tests if selected_tests is not None else [ + name for name, _runner in TEST_GROUPS + ] + for idx, name in enumerate(ordered_tests): + if (args.chunk_size and idx > 0 + and idx % args.chunk_size == 0): + _chunk_boundary_recovery( + rest_host, f"before {name}", args.chunk_cooldown, args.timeout) + if session is not None: + session.close() + session = None + mt.TestConfig.session = None + if args.target == "u64": + _force_safe_cpu_port(rest_host, f"pre-{name} reset") + _reset_c64_core(rest_host) + mt.wait_for_monitor_ready(args.host, args.port, args.password, args.timeout) + session = mt.MonitorSession(args.host, args.port, args.password, args.timeout) + mt.TestConfig.session = session + try: + runners[name](rest_host, session) + finally: + if args.target == "u64": + _restore_safe_banking_display_hygiene( + rest_host, session, f"post-{name} cleanup") + if session is not None: + with mt.check("Debug: post-suite banking/display hygiene leaves $0001 safe and C64 readable", + u2=False, + u2_reason="U64 CPU banking/readability hygiene is required"): + _restore_safe_banking_display_hygiene(rest_host, session, "post-suite hygiene") + except mt.Failure as exc: + aborted = True + print(exc, file=sys.stderr) + if session is not None: + print("\nFinal screen:", file=sys.stderr) + print(session.capture().text(), file=sys.stderr) + # Fall through to summary so any prior keep-going state is still printed. + except Exception as exc: # noqa: BLE001 + aborted = True + print(f"E2E debug test failed: {exc}", file=sys.stderr) + # Fall through to summary so prior keep-going state is still printed. + finally: + if session is not None: + session.close() + mt.TestConfig.session = None + + _print_debug_summary() + # An abnormal abort (a Failure raised outside a check body, e.g. inter-group + # setup or post-group hygiene) must NOT be reported as green: it is not recorded + # in TestConfig.failures, so without this guard the run would print OK and exit 0 + # despite having stopped early. Treat any abort as a non-zero result. + if mt.TestConfig.failures or aborted: + if aborted and not mt.TestConfig.failures: + print("debug_e2e_test: ABORTED before completion (no check failed, but " + "the suite stopped early; see stderr above)", file=sys.stderr) + return 1 + print(f"debug_e2e_test: OK ({mt.CHECK_COUNT} checks, " + f"{len(mt.TestConfig.skipped)} skipped)") + return 0 + + +def _print_debug_summary() -> None: + passed = mt.CHECK_COUNT - len(mt.TestConfig.failures) - len(mt.TestConfig.skipped) + print("") + print("==== debug_e2e_test summary ====") + print(f" target : {mt.TestConfig.target}") + print(f" passed : {passed}") + print(f" skipped : {len(mt.TestConfig.skipped)}") + print(f" failed : {len(mt.TestConfig.failures)}") + if mt.TestConfig.skipped: + print("") + print("Skipped checks:") + for idx, label, reason in mt.TestConfig.skipped: + print(f" [{idx:02d}] {label} ({reason})") + if mt.TestConfig.failures: + print("") + print("Failed checks:") + for idx, label, _diag in mt.TestConfig.failures: + print(f" [{idx:02d}] {label}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/developer/machine-code-monitor/monitor_test.py b/tools/developer/machine-code-monitor/monitor_test.py new file mode 100755 index 000000000..5049a1c7f --- /dev/null +++ b/tools/developer/machine-code-monitor/monitor_test.py @@ -0,0 +1,1762 @@ +#!/usr/bin/env python3 +import argparse +import difflib +import json +import os +import re +import select +import socket +import subprocess +import sys +import time +import urllib.error +import urllib.request +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +WIDTH = 60 +HEIGHT = 24 +SNAPSHOT_FILE = Path(__file__).with_name("snapshots").joinpath("expected_snapshots.json") +REPO_ROOT = Path(__file__).resolve().parents[3] +REDEPLOY_SCRIPT = REPO_ROOT / "tooling" / "build_and_deploy_u64.sh" + +STATUS_LINE_RE = re.compile(r"(?:CPU[0-7]|C[0-7]O[0-7]) \$A:(?:RAM|BAS) \$D:(?:RAM|CHR|I/O) \$E:(?:RAM|KRN) VIC[0-3] \$[0-9A-F]{4}") +# U2 cartridge backend has no monitor-side CPU banking or VIC bank selection, +# so the status line collapses to a fixed "no banking" label. +U2_STATUS_LINE_RE = re.compile(r"CPU VIEW\s+CPU BANK N/A\s+VIC N/A") +MEMORY_ROW_RE = re.compile(r"^[0-9A-F]{4} ") +MEMORY_ROW_16_RE = re.compile(r"^[0-9A-F]{4} [0-9A-F]{16} [0-9A-F]{16}$") +CHECK_COUNT = 0 +ASM_CANONICAL_BYTES = bytes(( + 0x85, 0x56, 0x20, 0x0F, 0xBC, 0xA5, 0x61, 0xC9, + 0x88, 0x90, 0x03, 0x20, 0xD4, 0xBA, 0x20, 0xCC, + 0xBC, 0xA5, 0x07, 0x18, 0x69, 0x81, 0xF0, 0xF3, + 0x38, 0xE9, 0x01, 0x48, 0xA2, 0x05, 0xB5, 0x69, + 0xB4, 0x61, +)) +ASM_KERNAL_ROWS: Tuple[Tuple[str, str], ...] = ( + ("E000 85 56", "STA $56"), + ("E002 20 0F BC", "JSR $BC0F"), + ("E005 A5 61", "LDA $61"), + ("E007 C9 88", "CMP #$88"), + ("E009 90 03", "BCC $E00E"), + ("E00B 20 D4 BA", "JSR $BAD4"), + ("E00E 20 CC BC", "JSR $BCCC"), + ("E011 A5 07", "LDA $07"), + ("E013 18", "CLC"), +) + +ALT_CHARSET_MAP = { + "l": "+", + "k": "+", + "m": "+", + "j": "+", + "q": "-", + "x": "|", + "t": "+", + "u": "+", + "v": "+", + "w": "+", + "n": "+", +} + +KEYS = { + "UP": b"\x1b[A", + "DOWN": b"\x1b[B", + "RIGHT": b"\x1b[C", + "LEFT": b"\x1b[D", + "PGUP": b"\x1b[5~", + "PGDN": b"\x1b[6~", + "F5": b"\x1b[15~", + "F3": b"\x1b[13~", + "RUNSTOP": b"\x11", + "CTRL_B": b"\x02", + "CTRL_E": b"\x05", + "CTRL_O": b"\x0f", + "CBM_B": b"\x1bb", + "CBM_1": b"\x1b1", + "ESC": b"\x1bx", + "ENTER": b"\r", + "DEL": b"\x7f", +} + +VIEW_KEYS = { + "HEX ": "M", + "ASC ": "I", + "ASM ": "A", + "SCR ": "V", + "BIN ": "B", +} + + +class Failure(RuntimeError): + pass + + +class SkipCheck(Exception): + pass + + +# Test configuration. Set by main() before run_tests() so the check() helper and +# individual tests can branch on the target hardware (u64 vs u2) and on whether +# the run should accumulate failures rather than aborting on the first one. +class TestConfig: + target: str = "u64" + keep_going: bool = False + session: Optional["MonitorSession"] = None + failures: List[Tuple[int, str, str]] = [] + skipped: List[Tuple[int, str, str]] = [] + + +def is_u2() -> bool: + return TestConfig.target == "u2" + + +def is_u64() -> bool: + return TestConfig.target == "u64" + + +class _SkipCheckCtx: + """No-op context that suppresses every exception raised in the body. + + Used when a check is gated by ``u2=False`` and the active target is u2. + Python provides no zero-cost mechanism to suppress a `with` block from + its context manager, so the body still runs; suppressing all exceptions + keeps state changes intentional while preventing the run from aborting. + The skip is announced before the body executes. + """ + def __enter__(self): + return self + def __exit__(self, exc_type, exc, tb): + return True + + +class _ActiveCheckCtx: + def __init__(self, label: str, check_index: int): + self.label = label + self.check_index = check_index + def __enter__(self): + return self + def __exit__(self, exc_type, exc, tb): + if exc_type is None: + print("OK", flush=True) + return False + if exc_type is SkipCheck: + print(f"SKIP ({exc})", flush=True) + TestConfig.skipped.append((self.check_index, self.label, str(exc))) + return True + print("FAIL", flush=True) + diag = _diagnostic_block(self.label, exc) + print(diag, flush=True) + TestConfig.failures.append((self.check_index, self.label, diag)) + return bool(TestConfig.keep_going) + + +def check(label: str, *, u2: bool = True, u2_reason: str = ""): + """Return a context manager for a single check. + + Setting ``u2=False`` marks the check as U64-only; in U2 mode the check is + skipped with a clear reason printed to the console. When + ``TestConfig.keep_going`` is true, exceptions raised inside the check are + captured with full screen context and logged verbosely, but the run + continues so a remote operator can collect all failure evidence in a + single console capture. + """ + global CHECK_COUNT + CHECK_COUNT += 1 + print(f"[{CHECK_COUNT:02d}] {label} ... ", end="", flush=True) + if is_u2() and not u2: + reason = u2_reason or "U64-only feature (CPU banking / VIC bank / ROM patch / REST API)" + print(f"SKIP ({reason})", flush=True) + TestConfig.skipped.append((CHECK_COUNT, label, reason)) + return _SkipCheckCtx() + return _ActiveCheckCtx(label, CHECK_COUNT) + + +def _diagnostic_block(label: str, exc: BaseException) -> str: + """Render a verbose, LLM-friendly diagnostic block for a failed check. + + The block always includes the failing check label, the exception type, the + full exception message, the last command sent to the device, and the final + terminal snapshot (if any). The intent is that a remote operator can copy + the entire console output and an LLM can reason about each failure in + isolation without needing additional context. + """ + lines: List[str] = [] + lines.append(" ---- FAILURE CONTEXT BEGIN ----") + lines.append(f" check : {label}") + lines.append(f" target : {TestConfig.target}") + lines.append(f" exception : {type(exc).__name__}: {format_exception(exc)}") + session = TestConfig.session + if session is not None: + last_cmd = getattr(session, "last_command", "") + lines.append(f" last_cmd : {last_cmd!r}") + try: + snap = session.capture() + lines.append(" screen :") + for row in snap.text().splitlines(): + lines.append(f" | {row}") + except Exception as cap_exc: # noqa: BLE001 + lines.append(f" screen : ") + lines.append(" ---- FAILURE CONTEXT END ----") + return "\n".join(lines) + + +def format_exception(exc: BaseException) -> str: + if isinstance(exc, urllib.error.URLError) and getattr(exc, "reason", None) is not None: + return f"{exc} ({exc.reason})" + return str(exc) + + +def device_unavailable(exc: BaseException) -> bool: + text = format_exception(exc).lower() + markers = ( + "no route to host", + "network is unreachable", + "connection refused", + "timed out", + "temporary failure in name resolution", + ) + return any(marker in text for marker in markers) + + +def wait_for_port(host: str, port: int, timeout: float) -> None: + deadline = time.time() + timeout + last_error: Optional[BaseException] = None + + while time.time() < deadline: + try: + with socket.create_connection((host, port), timeout=2.0): + return + except (OSError, TimeoutError) as exc: + last_error = exc + time.sleep(1.0) + + if last_error is not None: + raise last_error + raise TimeoutError(f"Timed out waiting for {host}:{port} to become reachable") + + +def redeploy_u64(host: str, port: int, password: Optional[str], timeout: float) -> None: + if host != "u64": + raise Failure(f"Auto-redeploy is only supported for host 'u64', not {host!r}") + if not REDEPLOY_SCRIPT.is_file(): + raise Failure(f"Missing redeploy helper: {REDEPLOY_SCRIPT}") + + print("Device unavailable; redeploying U64 and retrying once", file=sys.stderr) + subprocess.run([str(REDEPLOY_SCRIPT)], cwd=REPO_ROOT, check=True) + wait_for_port(host, port, timeout=60.0) + wait_for_monitor_ready(host, port, password, timeout) + + +@dataclass +class Snapshot: + lines: List[str] + reverse_cells: List[Tuple[int, int]] + last_command: str + + def line(self, index: int) -> str: + return self.lines[index] + + def text(self) -> str: + return "\n".join(self.lines) + + def find_line_containing(self, expected: str) -> int: + for index, line in enumerate(self.lines): + if expected in line: + return index + raise Failure( + f"Snapshot mismatch after {self.last_command}: expected any line to contain\n" + f" {expected!r}\n" + f"actual:\n{self.text()}" + ) + + def find_status_line(self) -> int: + for index, line in enumerate(self.lines): + if STATUS_LINE_RE.search(line) or U2_STATUS_LINE_RE.search(line): + return index + raise Failure( + f"Snapshot mismatch after {self.last_command}: no CPU/VIC status line found\n{self.text()}" + ) + + +class VT100Screen: + def __init__(self, width: int = WIDTH, height: int = HEIGHT) -> None: + self.width = width + self.height = height + self.reset() + + def reset(self) -> None: + self.lines = [[" "] * self.width for _ in range(self.height)] + self.reverse = [[False] * self.width for _ in range(self.height)] + self.x = 0 + self.y = 0 + self.reverse_mode = False + self.alt_charset = False + self._esc = False + self._csi: Optional[str] = None + self._charset: Optional[str] = None + self._password_seen = False + self._text_tail = "" + + def feed(self, data: bytes) -> None: + i = 0 + while i < len(data): + byte = data[i] + if byte == 0xFF: + i = self._skip_telnet_iac(data, i) + continue + self._feed_byte(byte) + i += 1 + + def snapshot(self, last_command: str) -> Snapshot: + reverse_cells = [] + for y in range(self.height): + for x in range(self.width): + if self.reverse[y][x]: + reverse_cells.append((x, y)) + return Snapshot(["".join(row) for row in self.lines], reverse_cells, last_command) + + def signature(self) -> Tuple[Tuple[str, ...], Tuple[Tuple[bool, ...], ...]]: + return (tuple("".join(row) for row in self.lines), + tuple(tuple(row) for row in self.reverse)) + + def saw_password_prompt(self) -> bool: + return self._password_seen + + def _skip_telnet_iac(self, data: bytes, index: int) -> int: + if index + 1 >= len(data): + return index + 1 + command = data[index + 1] + if command in (0xFB, 0xFC, 0xFD, 0xFE): + return min(index + 3, len(data)) + if command == 0xFA: + end = data.find(b"\xff\xf0", index + 2) + return len(data) if end == -1 else end + 2 + return min(index + 2, len(data)) + + def _feed_byte(self, byte: int) -> None: + ch = chr(byte) + self._text_tail = (self._text_tail + ch)[-32:] + if "Password:" in self._text_tail: + self._password_seen = True + + if self._csi is not None: + if 0x40 <= byte <= 0x7E: + self._handle_csi(self._csi, ch) + self._csi = None + else: + self._csi += ch + return + + if self._charset is not None: + if ch == "0": + self.alt_charset = True + elif ch == "B": + self.alt_charset = False + self._charset = None + return + + if self._esc: + self._esc = False + if ch == "[": + self._csi = "" + elif ch == "(": + self._charset = "" + elif ch == "c": + self.reset() + return + + if byte == 0x1B: + self._esc = True + return + if ch == "\r": + self.x = 0 + return + if ch == "\n": + self.x = 0 + self.y = min(self.height - 1, self.y + 1) + return + if ch == "\b": + self.x = max(0, self.x - 1) + return + + if self.alt_charset: + ch = ALT_CHARSET_MAP.get(ch, ch) + self._put(ch) + + def _handle_csi(self, params: str, final: str) -> None: + if final == "H": + parts = [part for part in params.split(";") if part] + row = int(parts[0]) if parts else 1 + col = int(parts[1]) if len(parts) > 1 else 1 + self.y = max(0, min(self.height - 1, row - 1)) + self.x = max(0, min(self.width - 1, col - 1)) + return + if final == "m": + values = [int(part) for part in params.split(";") if part] + if not values: + values = [0] + for value in values: + if value in (0, 27): + self.reverse_mode = False + elif value == 7: + self.reverse_mode = True + return + if final == "J": + if params in ("", "2"): + self.lines = [[" "] * self.width for _ in range(self.height)] + self.reverse = [[False] * self.width for _ in range(self.height)] + self.x = 0 + self.y = 0 + return + if final == "r": + return + + def _put(self, ch: str) -> None: + if not (0 <= self.x < self.width and 0 <= self.y < self.height): + return + self.lines[self.y][self.x] = ch + self.reverse[self.y][self.x] = self.reverse_mode + self.x += 1 + if self.x >= self.width: + self.x = self.width - 1 + + +class MonitorSession: + def __init__(self, host: str, port: int, password: Optional[str], timeout: float) -> None: + self.sock = self._connect_with_retry(host, port, timeout) + self.sock.setblocking(False) + self.timeout = timeout + self.password = password + self.screen = VT100Screen() + self.last_command = "" + self._drain_until_idle(timeout=timeout) + if self.screen.saw_password_prompt(): + if password is None: + raise Failure("Telnet password prompt received but no password was provided") + self.send_text(password + "\r", "password") + self._drain_until_idle(timeout=timeout) + self.enter_monitor() + + def close(self) -> None: + try: + self.sock.close() + except OSError: + pass + + @staticmethod + def _connect_with_retry(host: str, port: int, timeout: float) -> socket.socket: + deadline = time.time() + max(timeout, 15.0) + last_error: Optional[BaseException] = None + + while time.time() < deadline: + try: + return socket.create_connection((host, port), timeout=timeout) + except (OSError, TimeoutError) as exc: + last_error = exc + time.sleep(0.5) + + if last_error is not None: + raise last_error + raise TimeoutError(f"Timed out connecting to {host}:{port}") + + def capture(self) -> Snapshot: + try: + self._drain_until_idle(timeout=self.timeout) + except TimeoutError: + pass + return self.screen.snapshot(self.last_command) + + def send_key(self, key: str) -> Snapshot: + payload = KEYS[key] + self.last_command = key + self.sock.sendall(payload) + return self.capture() + + def send_key_repeat(self, key: str, count: int) -> Snapshot: + payload = KEYS[key] + self.last_command = f"{key} x{count}" + self.sock.sendall(payload * count) + return self.capture() + + def send_char(self, ch: str) -> Snapshot: + self.last_command = ch + self.sock.sendall(ch.encode("ascii")) + return self.capture() + + def send_text(self, text: str, label: str) -> Snapshot: + self.last_command = label + self.sock.sendall(text.encode("ascii")) + return self.capture() + + def goto(self, address: str) -> Snapshot: + self.send_char("J") + return self.send_text(address + "\r", f"J {address}") + + def fill(self, expr: str) -> Snapshot: + self.send_char("F") + return self.send_text(expr + "\r", f"F {expr}") + + def compare(self, expr: str) -> Snapshot: + self.send_char("C") + return self.send_text(expr + "\r", f"C {expr}") + + def transfer(self, expr: str) -> Snapshot: + self.send_char("T") + return self.send_text(expr + "\r", f"T {expr}") + + def goto_run(self, address: str) -> Snapshot: + self.send_char("G") + return self.send_text(address + "\r", f"G {address}") + + def enter_monitor(self) -> Snapshot: + snapshot = self.send_key("CTRL_O") + try: + snapshot.find_status_line() + return snapshot + except Failure: + pass + + snapshot = self.send_key("F5") + snapshot = self.send_char("D") + snapshot = self.send_key("ENTER") + snapshot = self.send_key("DOWN") + snapshot = self.send_key("ENTER") + snapshot.find_status_line() + return snapshot + + def _drain_until_idle(self, timeout: float) -> None: + end = time.time() + timeout + last_data = time.time() + last_change = last_data + signature = self.screen.signature() + while time.time() < end: + wait = min(0.2, max(0.0, end - time.time())) + ready, _, _ = select.select([self.sock], [], [], wait) + if not ready: + if time.time() - last_data >= 0.2: + return + if time.time() - last_change >= 0.2: + return + continue + chunk = self.sock.recv(65536) + if not chunk: + return + self.screen.feed(chunk) + new_signature = self.screen.signature() + if new_signature != signature: + signature = new_signature + last_change = time.time() + last_data = time.time() + self.screen.snapshot(self.last_command).find_status_line() + + +def wait_for_monitor_ready(host: str, port: int, password: Optional[str], timeout: float) -> None: + deadline = time.time() + 90.0 + last_error: Optional[BaseException] = None + + while time.time() < deadline: + session = None + try: + session = MonitorSession(host, port, password, timeout) + before_snapshot = session.capture() + before = before_snapshot.line(before_snapshot.find_status_line()) + after_snapshot = session.send_char("O") + after = after_snapshot.line(after_snapshot.find_status_line()) + if before != after: + return + except (Failure, OSError, TimeoutError, urllib.error.URLError) as exc: + last_error = exc + finally: + if session is not None: + session.close() + time.sleep(2.0) + + if last_error is not None: + raise last_error + raise TimeoutError(f"Timed out waiting for {host}:{port} monitor readiness") + + +def load_snapshots() -> Dict[str, Dict[str, Dict[str, str]]]: + with SNAPSHOT_FILE.open("r", encoding="utf-8") as handle: + return json.load(handle) + + +def assert_contains(snapshot: Snapshot, line_index: int, expected: str) -> None: + actual = snapshot.line(line_index) + if expected not in actual: + raise Failure( + f"Snapshot mismatch after {snapshot.last_command}: expected line {line_index} to contain\n" + f" {expected!r}\n" + f"actual:\n {actual!r}" + ) + + +def assert_status_contains(snapshot: Snapshot, expected: str) -> None: + line_index = snapshot.find_status_line() + assert_contains(snapshot, line_index, expected) + + +def assert_line_contains_all(snapshot: Snapshot, values: Tuple[str, ...]) -> int: + for index, line in enumerate(snapshot.lines): + if all(value in line for value in values): + return index + raise Failure( + f"Snapshot mismatch after {snapshot.last_command}: expected one line to contain {values!r}\n" + f"actual:\n{snapshot.text()}" + ) + + +def assert_equal(label: str, expected: str, actual: str, command: str) -> None: + if expected != actual: + diff = "\n".join( + difflib.unified_diff( + expected.splitlines(), + actual.splitlines(), + fromfile="expected", + tofile="actual", + lineterm="", + ) + ) + raise Failure(f"{label} failed after {command}\n{diff}") + + +def assert_highlight(snapshot: Snapshot, expected_cells: List[Tuple[int, int]], command: str) -> None: + actual = sorted(snapshot.reverse_cells) + expected = sorted(expected_cells) + if actual != expected: + raise Failure( + f"Highlight mismatch after {command}: expected {expected}, actual {actual}\n" + f"Screen:\n{snapshot.text()}" + ) + + +def assert_line_lacks(snapshot: Snapshot, forbidden: str) -> None: + for line in snapshot.lines: + if forbidden in line: + raise Failure( + f"Snapshot after {snapshot.last_command} unexpectedly contained {forbidden!r}\n" + f"{snapshot.text()}" + ) + + +def assert_ascii_width(snapshot: Snapshot, row: int) -> None: + line = snapshot.line(row) + content = line[1:39] + payload = content[5:37] + if len(payload) != 32: + raise Failure(f"ASCII width mismatch after {snapshot.last_command}: expected 32, got {len(payload)}") + + +def find_memory_rows(snapshot: Snapshot) -> List[int]: + rows = [index for index, line in enumerate(snapshot.lines) if MEMORY_ROW_RE.match(line[1:] if line.startswith("|") else line)] + if not rows: + raise Failure(f"No memory rows found after {snapshot.last_command}\n{snapshot.text()}") + return rows + + +_REST_UNAVAILABLE: Dict[str, bool] = {} + + +def rest_available(host: str, timeout: float = 1.0) -> bool: + """Probe whether the REST API is reachable for `host`. + + Used by U2 (and other non-U64) targets to short-circuit dozens of + write_rest_memory / read_rest_memory calls into a single SkipCheck so the + test report shows one clear "REST not available" SKIP entry rather than + a wall of identical connection errors. + """ + cached = _REST_UNAVAILABLE.get(host) + if cached is not None: + return not cached + url = f"http://{host}/v1/machine:readmem?address=0000&length=1" + try: + with urllib.request.urlopen(url, timeout=timeout): + _REST_UNAVAILABLE[host] = False + return True + except Exception: # noqa: BLE001 - any failure means unreachable + _REST_UNAVAILABLE[host] = True + return False + + +def require_rest(host: str) -> None: + """Raise SkipCheck when REST is unavailable, so the current check is + cleanly skipped instead of producing a connection-error traceback. + """ + if not rest_available(host): + raise SkipCheck(f"REST API not reachable on {host}") + + +def read_rest_memory(host: str, address: int, length: int) -> bytes: + # Both U64 and U2/U2+ ship the REST `v1/machine` API (route_machine.cc + # is linked into all three target builds). Only fall back to SkipCheck + # when the API is actually unreachable, regardless of target type. + if not rest_available(host): + raise SkipCheck(f"REST API not reachable on {host}") + url = f"http://{host}/v1/machine:readmem?address={address:04X}&length={length}" + deadline = time.time() + 15.0 + last_error: Optional[BaseException] = None + + while time.time() < deadline: + try: + with urllib.request.urlopen(url, timeout=5.0) as response: + return response.read() + except (OSError, TimeoutError, urllib.error.URLError) as exc: + last_error = exc + time.sleep(0.5) + + if last_error is not None: + raise last_error + raise TimeoutError(f"Timed out reading REST memory from {url}") + + +def write_rest_memory(host: str, address: int, data: bytes) -> None: + if not data: + raise Failure("write_rest_memory requires at least one byte") + + if not rest_available(host): + raise SkipCheck(f"REST API not reachable on {host}") + + deadline = time.time() + 15.0 + last_error: Optional[BaseException] = None + + while time.time() < deadline: + try: + if len(data) <= 128: + url = f"http://{host}/v1/machine:writemem?address={address:04X}&data={data.hex().upper()}" + request = urllib.request.Request(url, data=b"", method="PUT") + else: + url = f"http://{host}/v1/machine:writemem?address={address:04X}" + request = urllib.request.Request( + url, + data=data, + method="POST", + headers={"Content-Type": "application/octet-stream"}, + ) + with urllib.request.urlopen(request, timeout=5.0): + return + except (OSError, TimeoutError, urllib.error.URLError) as exc: + last_error = exc + time.sleep(0.5) + + if last_error is not None: + raise last_error + raise TimeoutError(f"Timed out writing REST memory to {host} at ${address:04X}") + + +def wait_for_rest_byte(host: str, address: int, expected: int, timeout: float = 2.0) -> None: + deadline = time.time() + timeout + while time.time() < deadline: + value = read_rest_memory(host, address, 1)[0] + if value == expected: + return + time.sleep(0.05) + raise Failure(f"Memory at ${address:04X} did not become ${expected:02X}") + + +def assert_rest_matches_row(snapshot: Snapshot, line_index: int, address: int, rest_host: str) -> None: + monitor_bytes = parse_memory_row(snapshot, address, line_index=line_index) + rest_bytes = read_rest_memory(rest_host, address, len(monitor_bytes)) + if rest_bytes != monitor_bytes: + raise Failure( + f"REST/monitor mismatch at ${address:04X} after {snapshot.last_command}:\n" + f" monitor: {' '.join(f'{byte:02X}' for byte in monitor_bytes)}\n" + f" rest: {' '.join(f'{byte:02X}' for byte in rest_bytes)}" + ) + + +def parse_memory_row(snapshot: Snapshot, address: int, line_index: Optional[int] = None) -> bytes: + target = f"{address:04X}" + candidate_indexes = [line_index] if line_index is not None else range(len(snapshot.lines)) + + for index in candidate_indexes: + if index is None: + continue + actual = snapshot.line(index).strip() + if actual.startswith("|"): + actual = actual[1:] + if actual.endswith("|"): + actual = actual[:-1] + actual = actual.strip() + match = re.match(rf"^{target}((?: [0-9A-F]{{2}})+)", actual, re.IGNORECASE) + if match: + return bytes.fromhex(match.group(1)) + + raise Failure( + f"Unable to parse monitor memory row at ${address:04X} after {snapshot.last_command!r}:\n" + f"{snapshot.text()}" + ) + + +def parse_text_row(snapshot: Snapshot, address: int, line_index: Optional[int] = None) -> str: + target = f"{address:04X} " + candidate_indexes = [line_index] if line_index is not None else range(len(snapshot.lines)) + + for index in candidate_indexes: + if index is None: + continue + actual = snapshot.line(index) + if actual.startswith("|"): + actual = actual[1:] + if actual.startswith(target): + if len(actual) < 37: + raise Failure( + f"Text row at ${address:04X} after {snapshot.last_command!r} was too short:\n{snapshot.text()}" + ) + return actual[5:37] + + raise Failure( + f"Unable to parse monitor text row at ${address:04X} after {snapshot.last_command!r}:\n" + f"{snapshot.text()}" + ) + + +def ensure_status(session: MonitorSession, expected: str) -> Snapshot: + screen = session.capture() + for _ in range(8): + try: + line_index = screen.find_status_line() + except Failure: + line_index = -1 + if line_index >= 0 and expected in screen.line(line_index): + return screen + screen = session.send_char("o") + raise Failure( + f"Unable to reach expected CPU/VIC status {expected!r}; last status line was {screen.line(screen.find_status_line())!r}" + ) + + +def cycle_cpu_bank_from_cpu7(session: MonitorSession, target_status: str, steps: int) -> Snapshot: + screen = ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + + for _ in range(steps): + screen = session.send_char("o") + + assert_status_contains(screen, target_status) + return screen + + +def ensure_view(session: MonitorSession, expected: str) -> Snapshot: + key = VIEW_KEYS.get(expected) + if key is None: + raise Failure(f"Unsupported monitor view selector for {expected!r}") + screen = session.capture() + for _ in range(3): + try: + screen.find_line_containing(expected) + return screen + except Failure: + pass + screen = session.send_char(key) + raise Failure(f"Unable to reach expected monitor view {expected!r}; screen was\n{screen.text()}") + + +def ensure_screen_charset(session: MonitorSession, expected: str) -> Snapshot: + if expected not in ("U/G", "L/U"): + raise Failure(f"Unsupported screen charset request {expected!r}") + + screen = ensure_view(session, "SCR ") + header_row = screen.find_line_containing("MONITOR SCR") + if expected in screen.line(header_row): + return screen + + screen = session.send_char("U") + header_row = screen.find_line_containing("MONITOR SCR") + if expected not in screen.line(header_row): + raise Failure( + f"Unable to switch Screen view to {expected}; header was {screen.line(header_row)!r}" + ) + return screen + + +def ensure_hex_width(session: MonitorSession, expected_width: int) -> Snapshot: + if expected_width not in (8, 16): + raise Failure(f"Unsupported hex width request {expected_width}") + + screen = ensure_view(session, "HEX ") + rows = find_memory_rows(screen) + row_text = screen.line(rows[0]).strip() + if row_text.startswith("|"): + row_text = row_text[1:] + if row_text.endswith("|"): + row_text = row_text[:-1] + row_text = row_text.strip() + is_width_16 = MEMORY_ROW_16_RE.match(row_text) is not None + + if (expected_width == 16) != is_width_16: + screen = session.send_char("W") + return screen + + +def run_character_mapping_test(session: MonitorSession, rest_host: str) -> None: + ascii_view_addr = 0x3200 + ascii_edit_addr = 0x3220 + screen_view_addr = 0x3240 + screen_edit_ug_addr = 0x3260 + screen_edit_lu_addr = 0x3280 + + write_rest_memory(rest_host, ascii_view_addr, bytes((0x41, 0x61, 0x20, 0x7E, 0x1F, 0x80) + (0x20,) * 26)) + write_rest_memory(rest_host, ascii_edit_addr, b" ") + write_rest_memory(rest_host, screen_view_addr, bytes((0x01, 0x1A, 0x20, 0x23, 0x41, 0x42, 0x80) + (0x20,) * 25)) + write_rest_memory(rest_host, screen_edit_ug_addr, b" ") + write_rest_memory(rest_host, screen_edit_lu_addr, b" ") + + screen = ensure_view(session, "ASC ") + screen = session.goto(f"{ascii_view_addr:04X}") + ascii_payload = parse_text_row(screen, ascii_view_addr) + if ascii_payload[:6] != "Aa ~..": + raise Failure( + f"ASCII view mapping mismatch at ${ascii_view_addr:04X}: expected 'Aa ~..', got {ascii_payload[:6]!r}" + ) + + screen = session.goto(f"{ascii_edit_addr:04X}") + screen = session.send_char("E") + for ch in "aA# ": + screen = session.send_char(ch) + screen = session.send_key("CTRL_E") + if read_rest_memory(rest_host, ascii_edit_addr, 4) != b"aA# ": + raise Failure( + f"ASCII edit mapping mismatch at ${ascii_edit_addr:04X}: " + f"got {read_rest_memory(rest_host, ascii_edit_addr, 4).hex().upper()}" + ) + + screen = ensure_screen_charset(session, "U/G") + screen = session.goto(f"{screen_view_addr:04X}") + header_row = screen.find_line_containing("MONITOR SCR") + if "U/G" not in screen.line(header_row): + raise Failure(f"Screen U/G header mismatch: {screen.line(header_row)!r}") + screen_payload = parse_text_row(screen, screen_view_addr) + if screen_payload[:7] != "AZ #S|@": + raise Failure( + f"Screen U/G view mapping mismatch at ${screen_view_addr:04X}: expected 'AZ #S|@', got {screen_payload[:7]!r}" + ) + + screen = ensure_screen_charset(session, "L/U") + screen = session.goto(f"{screen_view_addr:04X}") + header_row = screen.find_line_containing("MONITOR SCR") + if "L/U" not in screen.line(header_row): + raise Failure(f"Screen L/U header mismatch: {screen.line(header_row)!r}") + screen_payload = parse_text_row(screen, screen_view_addr) + if screen_payload[:7] != "az #AB@": + raise Failure( + f"Screen L/U view mapping mismatch at ${screen_view_addr:04X}: expected 'az #AB@', got {screen_payload[:7]!r}" + ) + + screen = ensure_view(session, "ASC ") + screen = session.goto(f"{ascii_view_addr:04X}") + ascii_payload = parse_text_row(screen, ascii_view_addr) + if ascii_payload[:6] != "Aa ~..": + raise Failure( + f"ASCII view must stay literal after Screen charset toggles; got {ascii_payload[:6]!r}" + ) + + screen = ensure_screen_charset(session, "U/G") + screen = session.goto(f"{screen_edit_ug_addr:04X}") + screen = session.send_char("E") + for ch in "aA# ": + screen = session.send_char(ch) + screen = session.send_key("CTRL_E") + if read_rest_memory(rest_host, screen_edit_ug_addr, 4) != bytes((0x01, 0x01, 0x23, 0x20)): + raise Failure( + f"Screen U/G edit mapping mismatch at ${screen_edit_ug_addr:04X}: " + f"got {read_rest_memory(rest_host, screen_edit_ug_addr, 4).hex().upper()}" + ) + + screen = ensure_screen_charset(session, "L/U") + screen = session.goto(f"{screen_edit_lu_addr:04X}") + screen = session.send_char("E") + for ch in "aA# ": + screen = session.send_char(ch) + screen = session.send_key("CTRL_E") + if read_rest_memory(rest_host, screen_edit_lu_addr, 4) != bytes((0x01, 0x41, 0x23, 0x20)): + raise Failure( + f"Screen L/U edit mapping mismatch at ${screen_edit_lu_addr:04X}: " + f"got {read_rest_memory(rest_host, screen_edit_lu_addr, 4).hex().upper()}" + ) + + +def run_go_repeat_test(session: MonitorSession, rest_host: str) -> None: + sentinel = 0x5A + values = (0x42, 0x37, 0x99) + + for value in values: + write_rest_memory(rest_host, 0x0810, bytes((0xA9, value, 0x8D, 0x00, 0x20, 0x00))) + write_rest_memory(rest_host, 0x2000, bytes((sentinel,))) + + screen = ensure_view(session, "HEX ") + screen = session.goto("2000") + before = parse_memory_row(screen, 0x2000) + if before[0] != sentinel: + raise Failure( + f"G precondition failed for ${value:02X}: expected ${sentinel:02X} at $2000, got ${before[0]:02X}" + ) + + session.goto_run("0810") + wait_for_rest_byte(rest_host, 0x2000, value) + + session.enter_monitor() + screen = ensure_view(session, "HEX ") + screen = session.goto("2000") + after = parse_memory_row(screen, 0x2000) + if after[0] != value: + raise Failure( + f"G postcondition failed for ${value:02X}: expected ${value:02X} at $2000, got ${after[0]:02X}" + ) + + +def run_go_visible_state_test(session: MonitorSession, rest_host: str) -> None: + sentinel = 0xA5 + done = 0x5C + + pre_d011 = read_rest_memory(rest_host, 0xD011, 1)[0] + pre_d020 = read_rest_memory(rest_host, 0xD020, 1)[0] + + write_rest_memory(rest_host, 0x0810, bytes((0xEE, 0x21, 0xD0, 0xA9, done, 0x8D, 0x00, 0x20, 0x00))) + write_rest_memory(rest_host, 0x2000, bytes((sentinel,))) + session.goto_run("0810") + wait_for_rest_byte(rest_host, 0x2000, done) + + post_d011 = read_rest_memory(rest_host, 0xD011, 1)[0] + post_d020 = read_rest_memory(rest_host, 0xD020, 1)[0] + + if (post_d011 & 0x7F) != (pre_d011 & 0x7F): + raise Failure( + f"G visual-state check failed: $D011 changed from ${pre_d011:02X} to ${post_d011:02X}" + ) + if post_d020 != pre_d020: + raise Failure( + f"G visual-state check failed: $D020 changed from ${pre_d020:02X} to ${post_d020:02X}" + ) + + session.enter_monitor() + + +def run_bookmark_test(session: MonitorSession) -> None: + screen = ensure_view(session, "HEX ") + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + screen = session.send_key("DOWN") + screen = session.send_key("DEL") + assert_line_contains_all(screen, ("1 SCREEN", "$0400", "SCR 32")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR") + + screen = session.goto("C123") + screen.find_line_containing("MONITOR HEX $C123") + screen = session.send_char("W") + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + screen = session.send_key("DOWN") + screen = session.send_char("S") + assert_line_contains_all(screen, ("BM1 SCREEN $C123 HEX W16", "SET")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR HEX $C123") + + screen = session.goto("E000") + screen.find_line_containing("MONITOR HEX $E000") + screen = session.send_key("CBM_1") + screen.find_line_containing("MONITOR HEX $C123") + screen.find_line_containing("BM1 SCREEN $C123 HEX W16") + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + assert_line_contains_all(screen, ("1 SCREEN", "$C123", "HEX 16")) + screen.find_line_containing("0-9/RET:Jmp S:Set L:Label DEL:Reset") + + screen = session.send_key("DOWN") + screen = session.send_char("L") + screen = session.send_text("\b\b\b\b\b\bE2E\r", "bookmark label E2E") + assert_line_contains_all(screen, ("1 E2E", "$C123", "HEX 16")) + + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR HEX $C123") + screen = session.goto("E000") + screen.find_line_containing("MONITOR HEX $E000") + screen = session.send_key("CBM_1") + screen.find_line_containing("MONITOR HEX $C123") + screen.find_line_containing("BM1 E2E $C123 HEX W16") + + +def run_telnet_poll_guard_test(session: MonitorSession) -> None: + screen = ensure_view(session, "HEX ") + screen = session.send_char("P") + screen.find_line_containing("POLL MODE UNAVAILABLE OVE") + + screen = session.send_char("o") + screen.find_line_containing("MONITOR HEX") + assert_line_lacks(screen, "Poll") + + +def run_memory_bookmark_width_test(session: MonitorSession, rest_host: str) -> None: + write_rest_memory(rest_host, 0x3000, bytes(range(0x10))) + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + screen = session.send_key("DOWN") + screen = session.send_key("DEL") + assert_line_contains_all(screen, ("1 SCREEN", "$0400", "SCR 32")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR") + + screen = ensure_hex_width(session, 8) + screen = session.goto("3000") + screen.find_line_containing("3000 00 01 02 03 04 05 06 07") + + screen = session.send_char("W") + screen.find_line_containing("3000 0001020304050607 08090A0B0C0D0E0F") + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + screen = session.send_key("DOWN") + screen = session.send_char("S") + assert_line_contains_all(screen, ("BM1 SCREEN $3000 HEX W16", "SET")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR HEX $3000") + + screen = session.goto("E000") + screen.find_line_containing("MONITOR HEX $E000") + screen = session.send_key("CBM_1") + screen.find_line_containing("MONITOR HEX $3000") + screen.find_line_containing("BM1 SCREEN $3000 HEX W16") + screen.find_line_containing("3000 0001020304050607 08090A0B0C0D0E0F") + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + assert_line_contains_all(screen, ("1 SCREEN", "$3000", "HEX 16")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR HEX $3000") + + +def run_binary_bookmark_width_test(session: MonitorSession, rest_host: str) -> None: + write_rest_memory(rest_host, 0x3100, bytes((0x12, 0x34, 0x56, 0x78))) + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + screen = session.send_key("DOWN") + screen = session.send_key("DEL") + assert_line_contains_all(screen, ("1 SCREEN", "$0400", "SCR 32")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR") + + screen = ensure_view(session, "BIN ") + screen = session.goto("3100") + for _ in range(5): + try: + screen.find_line_containing("3100 ...*..*. 12") + break + except Failure: + screen = session.send_char("W") + screen.find_line_containing("3100 ...*..*. 12") + + screen = session.send_char("W") + screen.find_line_containing("3100 ...*..*. ..**.*.. 12 34") + + screen = session.send_char("W") + screen.find_line_containing("30FF ........ ...*..*. ..**.*.. 001234") + + screen = session.send_char("W") + screen.find_line_containing("30FF ...........*..*...**.*.. 00 12 34") + + screen = session.send_char("W") + screen.find_line_containing("3100 ...*..*...**.*...*.*.**..****...") + assert_line_lacks(screen, "12 34 56 78") + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + screen = session.send_key("DOWN") + screen = session.send_char("S") + assert_line_contains_all(screen, ("BM1 SCREEN $3100 BIN W4", "SET")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR BIN $3100") + + screen = session.goto("E000") + screen.find_line_containing("MONITOR BIN $E000") + screen = session.send_key("CBM_1") + screen.find_line_containing("MONITOR BIN $3100") + screen.find_line_containing("BM1 SCREEN $3100 BIN W4") + screen.find_line_containing("3100 ...*..*...**.*...*.*.**..****...") + assert_line_lacks(screen, "12 34 56 78") + + screen = session.send_key("CTRL_B") + screen.find_line_containing("BOOKMARKS") + assert_line_contains_all(screen, ("1 SCREEN", "$3100", "BIN 4")) + screen = session.send_key("CTRL_B") + screen.find_line_containing("MONITOR BIN $3100") + + +def run_follow_return_test(session: MonitorSession, rest_host: str) -> None: + # ASM view test data: + # $3340: JSR $3360 20 60 33 / NOP EA + # $3350: BNE $3354 D0 02 / NOP EA EA / RTS 60 + # $3360: RTS 60 / NOP EA EA + write_rest_memory(rest_host, 0x3340, bytes((0x20, 0x60, 0x33, 0xEA))) + write_rest_memory(rest_host, 0x3350, bytes((0xD0, 0x02, 0xEA, 0xEA, 0x60))) + write_rest_memory(rest_host, 0x3360, bytes((0x60, 0xEA, 0xEA))) + screen = ensure_view(session, "ASM ") + screen = session.goto("3340") + screen = ensure_view(session, "ASM ") + screen.find_line_containing("JSR $3360") + # ENTER follows JSR; ENTER at the non-followable target returns + screen = session.send_key("ENTER") + screen.find_line_containing("MONITOR ASM $3360") + screen.find_line_containing("F0 JMP $3360") + screen = session.send_key("ENTER") + screen.find_line_containing("MONITOR ASM $3340") + screen.find_line_containing("F0 RET $3340") + + # BNE branch follow; ENTER in HEX must not trigger Back + screen = session.goto("3350") + screen = ensure_view(session, "ASM ") + screen.find_line_containing("BNE $3354") + screen = session.send_key("ENTER") + screen.find_line_containing("MONITOR ASM $3354") + screen.find_line_containing("F0 JMP $3354") + screen = ensure_view(session, "HEX ") + screen.find_line_containing("MONITOR HEX $3354") + screen = session.send_key("ENTER") + screen.find_line_containing("MONITOR HEX $3354") + screen = ensure_view(session, "ASM ") + screen.find_line_containing("MONITOR ASM $3354") + screen = session.send_key("ENTER") + screen.find_line_containing("MONITOR ASM $3350") + screen.find_line_containing("F0 RET $3350") + + # RTS is not a static follow target + screen = session.goto("3360") + screen = ensure_view(session, "ASM ") + screen.find_line_containing("RTS") + screen = session.send_key("ENTER") + screen.find_line_containing("MONITOR ASM $3360") + assert_line_lacks(screen, "F0 JMP $") + +def run_number_arithmetic_test(session: MonitorSession, rest_host: str) -> None: + write_rest_memory(rest_host, 0x3370, bytes((0x20, 0x00, 0xC0, 0xEA))) + + screen = ensure_view(session, "ASM ") + screen = session.goto("3370") + screen = ensure_view(session, "ASM ") + screen.find_line_containing("JSR $C000") + screen = session.send_char("N") + screen.find_line_containing("MONITOR NUM $3371 WOR") + screen.find_line_containing("Calc with +-*/") + screen = session.send_char("+") + screen.find_line_containing("Expr=$C000+") + screen = session.send_text("$28=", "number expr +$28") + screen.find_line_containing("Hex $C028") + assert_line_lacks(screen, "Expr=") + screen.find_line_containing("Calc with +-*/") + + screen = session.send_char("/") + screen = session.send_text("0\r", "number expr div0") + screen.find_line_containing("Hex $C028") + screen.find_line_containing("DIV/0") + screen = session.send_key("ESC") + screen.find_line_containing("Calc with +-*/") + screen = session.send_key("ESC") + screen.find_line_containing("MONITOR ASM $3370") + + +def highlighted_line(snapshot: Snapshot) -> str: + if not snapshot.reverse_cells: + raise Failure(f"No highlighted cells after {snapshot.last_command}\n{snapshot.text()}") + row = snapshot.reverse_cells[0][1] + return snapshot.line(row) + + +def highlighted_row_count(snapshot: Snapshot) -> int: + return len({row for _, row in snapshot.reverse_cells}) + + +def assert_highlighted_line_contains(snapshot: Snapshot, values: Tuple[str, ...]) -> None: + count = highlighted_row_count(snapshot) + if count != 1: + raise Failure( + f"Expected exactly one highlighted row after {snapshot.last_command}, got {count}\n" + f"{snapshot.text()}" + ) + line = highlighted_line(snapshot) + if not all(value in line for value in values): + raise Failure( + f"Highlighted line after {snapshot.last_command} did not contain {values!r}\n" + f"line: {line!r}\n{snapshot.text()}" + ) + + +def wait_for_highlighted_line_contains(session: MonitorSession, values: Tuple[str, ...], + timeout: float = 5.0) -> Snapshot: + deadline = time.time() + timeout + last_snapshot: Optional[Snapshot] = None + + while time.time() < deadline: + snapshot = session.capture() + last_snapshot = snapshot + try: + assert_highlighted_line_contains(snapshot, values) + return snapshot + except Failure: + time.sleep(0.1) + + if last_snapshot is None: + raise Failure(f"Timed out waiting for highlighted line {values!r}") + assert_highlighted_line_contains(last_snapshot, values) + return last_snapshot + + +def assert_canonical_kernal_lane(snapshot: Snapshot, highlighted_values: Tuple[str, ...]) -> None: + top_row = snapshot.find_line_containing(ASM_KERNAL_ROWS[0][0]) + for offset, (address_bytes, disasm_text) in enumerate(ASM_KERNAL_ROWS): + row_index = top_row + offset + if row_index >= len(snapshot.lines): + raise Failure(f"KERNAL lane row {address_bytes} is below the captured screen\n{snapshot.text()}") + line = snapshot.line(row_index) + if address_bytes not in line or disasm_text not in line: + raise Failure( + f"KERNAL lane row mismatch after {snapshot.last_command}: expected {address_bytes!r} / {disasm_text!r} " + f"on line {row_index}\nactual: {line!r}\n{snapshot.text()}" + ) + assert_line_lacks(snapshot, "E001 56 20") + assert_line_lacks(snapshot, "E010 BC A5 07") + assert_highlighted_line_contains(snapshot, highlighted_values) + + +def run_asm_kernal_root_stability_test(session: MonitorSession) -> None: + ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + screen = session.goto("E000") + screen = ensure_view(session, "ASM ") + screen.find_line_containing("MONITOR ASM $E000") + assert_canonical_kernal_lane(screen, ("E000 85 56", "STA $56")) + + screen = session.fill("DFFD-DFFD,4C") + assert_canonical_kernal_lane(screen, ("E000 85 56", "STA $56")) + screen = session.fill("DFFE-DFFE,00") + assert_canonical_kernal_lane(screen, ("E000 85 56", "STA $56")) + screen = session.fill("DFFF-DFFF,E0") + screen.find_line_containing("MONITOR ASM $E000") + assert_canonical_kernal_lane(screen, ("E000 85 56", "STA $56")) + + screen = session.fill("DFFD-DFFD,20") + assert_canonical_kernal_lane(screen, ("E000 85 56", "STA $56")) + + +def run_asm_decode_offset_test(session: MonitorSession, rest_host: str) -> None: + address = 0x3400 if is_u2() else 0xE000 + if is_u2(): + write_rest_memory(rest_host, address, ASM_CANONICAL_BYTES) + + screen = session.goto(f"{address:04X}") + screen = ensure_view(session, "ASM ") + assert_highlighted_line_contains(screen, (f"{address:04X} 85 56", "STA $56")) + top_row = screen.find_line_containing(f"{address:04X} 85 56") + screen = session.send_key("RIGHT") + screen.find_line_containing(f"MONITOR ASM ${address + 1:04X}") + assert_highlighted_line_contains(screen, (f"{address + 1:04X}",)) + screen = session.send_key("RIGHT") + screen.find_line_containing(f"MONITOR ASM ${address + 2:04X}") + assert_highlighted_line_contains(screen, (f"{address + 2:04X} 20 0F BC", "JSR $BC0F")) + screen = session.send_key("LEFT") + screen.find_line_containing(f"MONITOR ASM ${address + 1:04X}") + screen = session.send_key("LEFT") + screen.find_line_containing(f"MONITOR ASM ${address:04X}") + screen = session.send_key("DOWN") + screen.find_line_containing(f"MONITOR ASM ${address + 2:04X}") + assert_highlighted_line_contains(screen, (f"{address + 2:04X} 20 0F BC", "JSR $BC0F")) + if f"{address:04X} 85 56" not in screen.line(top_row): + raise Failure(f"ASM Down to +2 moved the viewport top\n{screen.text()}") + + down_rows = ( + (0x0005, "A5 61", "LDA $61"), + (0x0007, "C9 88", "CMP #$88"), + (0x0009, "90 03", "BCC"), + (0x000B, "20 D4 BA", "JSR $BAD4"), + (0x000E, "20 CC BC", "JSR $BCCC"), + (0x0011, "A5 07", "LDA $07"), + (0x0013, "18", "CLC"), + ) + for offset, byte_text, disasm_text in down_rows: + screen = session.send_key("DOWN") + screen.find_line_containing(f"MONITOR ASM ${address + offset:04X}") + assert_highlighted_line_contains(screen, (f"{address + offset:04X} {byte_text}", disasm_text)) + if f"{address:04X} 85 56" not in screen.line(top_row): + raise Failure(f"ASM Down to +{offset:04X} moved the viewport top\n{screen.text()}") + assert_line_lacks(screen, f"{address + 1:04X} 56 20") + + screen = session.send_key("UP") + screen.find_line_containing(f"MONITOR ASM ${address + 0x0011:04X}") + assert_highlighted_line_contains(screen, (f"{address + 0x0011:04X} A5 07", "LDA $07")) + assert_line_lacks(screen, f"{address + 0x0010:04X} BC A5 07") + + sliding_start = 0x3600 + sliding_steps = 300 + write_rest_memory(rest_host, 0x3400, bytes((0xEA,)) * 0x400) + screen = session.goto(f"{sliding_start:04X}") + screen = ensure_view(session, "ASM ") + assert_highlighted_line_contains(screen, (f"{sliding_start:04X} EA", "NOP")) + session.send_key_repeat("UP", sliding_steps) + screen = wait_for_highlighted_line_contains(session, (f"{sliding_start - sliding_steps:04X} EA", "NOP")) + session.send_key_repeat("DOWN", sliding_steps) + screen = wait_for_highlighted_line_contains(session, (f"{sliding_start:04X} EA", "NOP")) + + +def run_asm_edit_navigation_test(session: MonitorSession, rest_host: str) -> None: + write_rest_memory(rest_host, 0x3410, bytes((0xA9, 0x12, 0xEA, 0xEA))) + screen = session.goto("3410") + screen = ensure_view(session, "ASM ") + screen.find_line_containing("LDA #$12") + screen = session.send_char("e") + screen = session.send_key("RIGHT") + screen.find_line_containing("MONITOR ASM $3410") + assert_highlighted_line_contains(screen, ("3410 A9 12", "LDA #$12")) + screen = session.send_key("LEFT") + screen.find_line_containing("MONITOR ASM $3410") + assert_highlighted_line_contains(screen, ("3410 A9 12", "LDA #$12")) + screen = session.send_key("DOWN") + screen.find_line_containing("MONITOR ASM $3412") + screen = session.send_key("UP") + screen.find_line_containing("MONITOR ASM $3410") + screen = session.send_key("ESC") + screen.find_line_containing("MONITOR ASM $3410") + + +def run_asm_cpu0_continuous_ram_test(session: MonitorSession) -> None: + ensure_status(session, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + screen = session.send_char("o") + assert_status_contains(screen, "C7O0 $A:RAM $D:RAM $E:RAM VIC") + session.fill("DFFE-DFFE,20") + session.fill("DFFF-DFFF,00") + session.fill("E000-E000,E0") + screen = session.goto("DFFE") + screen = ensure_view(session, "ASM ") + assert_highlighted_line_contains(screen, ("DFFE 20 00 E0", "JSR $E000")) + for _ in range(7): + screen = session.send_char("o") + assert_status_contains(screen, "CPU7 $A:BAS $D:I/O $E:KRN VIC") + + +def run_asm_self_modification_test(session: MonitorSession, rest_host: str) -> None: + write_rest_memory(rest_host, 0x3502, bytes((0xA9, 0x00, 0xEA, 0xA5, 0x61, 0xEA, 0xEA))) + screen = session.goto("3505") + screen = ensure_view(session, "ASM ") + assert_highlighted_line_contains(screen, ("3505 A5 61", "LDA $61")) + + session.fill("3502-3502,20") + session.fill("3503-3503,05") + screen = session.fill("3504-3504,35") + screen.find_line_containing("MONITOR ASM $3505") + assert_highlighted_line_contains(screen, ("3505 A5 61", "LDA $61")) + + session.fill("3505-3505,A9") + screen = session.fill("3506-3506,42") + assert_highlighted_line_contains(screen, ("3505 A9 42", "LDA #$42")) + screen = session.fill("3507-3507,60") + screen.find_line_containing("3507 60") + screen.find_line_containing("RTS") + + +def run_tests(session: MonitorSession, rest_host: str) -> None: + snapshots = load_snapshots() + + with check("initial CPU7/KERNAL monitor status", u2=False, + u2_reason="U2 reports 'CPU VIEW CPU BANK N/A VIC N/A' instead of CPU#/$A:.../VIC#"): + ensure_status(session, snapshots["status_cpu31"]["contains"]["22"]) + + with check("initial monitor status line is present"): + ensure_view(session, "HEX ") + snap = session.capture() + snap.find_status_line() + + with check("telnet blocks poll mode"): + run_telnet_poll_guard_test(session) + + with check("KERNAL $E000 hex view and REST match", u2=False, + u2_reason="U2 monitor does not snapshot KERNAL ROM into its own view, " + "so the expected text fragments differ from U64"): + ensure_hex_width(session, 8) + screen = session.goto("E000") + for row, expected in snapshots["kernal_hex_e000"]["contains"].items(): + assert_contains(screen, int(row), expected) + assert_rest_matches_row(screen, 4, 0xE000, rest_host) + + with check("paging away and back keeps memory view stable"): + ensure_view(session, "HEX ") + # Use a target address that is meaningful for both U64 (KERNAL view + # already at $E000) and U2 (no ROM snapshot, but RAM at $C000 is + # stable). Move there explicitly so the test does not depend on prior + # state set by KERNAL-specific tests that may have been skipped. + ref_addr = "E000" if is_u64() else "C000" + ref = session.goto(ref_addr) + initial_snapshot = ref.text() + session.send_key("PGDN") + back = session.send_key("PGUP") + assert_equal("Memory stability", initial_snapshot, back.text(), back.last_command) + + with check("KERNAL disassembly formatting", u2=False, + u2_reason="U2 does not snapshot KERNAL ROM into the monitor view"): + # Reposition explicitly so this test does not depend on prior cursor + # state. Previously this relied on the immediately-preceding check + # leaving the view at $E000. + screen = session.goto("E000") + screen = session.send_char("A") + for row, expected in snapshots["kernal_disasm_e000"]["contains"].items(): + assert_contains(screen, int(row), expected) + + screen = session.goto("E013") + screen = session.send_char("A") + for row, expected in snapshots["kernal_disasm_e013"]["contains"].items(): + assert_contains(screen, int(row), expected) + + with check("ASM root stable across volatile pre-root IO", u2=False, + u2_reason="U2 backend does not expose U64 CPU7 I/O/KERNAL banking"): + run_asm_kernal_root_stability_test(session) + + with check("ASM decode offset and instruction navigation"): + run_asm_decode_offset_test(session, rest_host) + + with check("ASM edit navigation keeps root stable"): + run_asm_edit_navigation_test(session, rest_host) + + with check("ASM CPU0 continuous RAM can cross DFFF/E000", u2=False, + u2_reason="U2 backend does not expose monitor-side CPU banking"): + run_asm_cpu0_continuous_ram_test(session) + + with check("ASM self-modification root rules"): + run_asm_self_modification_test(session, rest_host) + + with check("KERNAL $E010 REST match", u2=False, + u2_reason="U2 monitor does not snapshot KERNAL ROM, so monitor row text differs"): + screen = ensure_view(session, "HEX ") + screen = session.goto("E010") + assert_rest_matches_row(screen, 4, 0xE010, rest_host) + + with check("CPU6 RAM under BASIC write/read", u2=False, + u2_reason="U2 backend does not expose monitor-side CPU banking"): + screen = ensure_view(session, "HEX ") + session.goto("A000") + screen = cycle_cpu_bank_from_cpu7(session, snapshots["status_cpu30"]["contains"]["22"], 7) + session.fill("A000-A000,AA") + screen = session.goto("A000") + assert_contains(screen, 4, snapshots["ram_a000"]["contains"]["4"]) + + with check("CPU5 RAM under KERNAL status", u2=False, + u2_reason="U2 backend does not expose monitor-side CPU banking"): + session.goto("E000") + screen = cycle_cpu_bank_from_cpu7(session, snapshots["status_cpu29"]["contains"]["22"], 6) + + with check("ASCII view width and scrolling", u2=False, + u2_reason="Reference snapshot keys reference U64-specific CPU bank status"): + session.goto("C000") + for row_index in range(19): + start = 0xC000 + row_index * 0x20 + end = start + 0x1F + session.fill(f"{start:04X}-{end:04X},{0x41 + row_index:02X}") + + screen = ensure_view(session, "ASC ") + content_rows = find_memory_rows(screen) + first_content_row = content_rows[0] + last_content_row = content_rows[-1] + assert_ascii_width(screen, first_content_row) + assert_status_contains(screen, snapshots["status_cpu29"]["contains"]["22"]) + + screen = session.send_key("DOWN") + assert_highlight(screen, [(6, first_content_row + 1)], "DOWN") + assert_contains(screen, first_content_row, snapshots["ascii_top_row"]["contains"]["4"]) + + screen = session.send_key("UP") + assert_highlight(screen, [(6, first_content_row)], "UP") + + for _ in range(last_content_row - first_content_row): + screen = session.send_key("DOWN") + assert_highlight(screen, [(6, last_content_row)], "DOWN to last row") + assert_contains(screen, first_content_row, snapshots["ascii_top_row"]["contains"]["4"]) + + screen = session.send_key("DOWN") + assert_highlight(screen, [(6, last_content_row)], "DOWN past last row") + assert_contains(screen, first_content_row, snapshots["ascii_scrolled_top_row"]["contains"]["4"]) + + with check("ASCII and Screen mapping semantics", u2=False, + u2_reason="Helper writes via REST and asserts CPU/VIC status"): + run_character_mapping_test(session, rest_host) + + with check("HEX edit writes both nibbles"): + session.goto("C000") + session.fill("C000-C000,00") + screen = ensure_view(session, "HEX ") + screen = session.send_char("e") + assert_highlight(screen, [(6, 4), (7, 4)], "e") + screen = session.send_char("A") + assert_contains(screen, 4, snapshots["hex_first_nibble"]["contains"]["4"]) + screen = session.send_char("B") + assert_contains(screen, 4, snapshots["hex_second_nibble"]["contains"]["4"]) + session.send_key("ESC") + + with check("CPU bank cycling reaches CHAR and RAM mappings", u2=False, + u2_reason="U2 backend does not expose monitor-side CPU banking"): + session.goto("A000") + screen = ensure_status(session, snapshots["status_cpu27"]["contains"]["22"]) + assert_status_contains(screen, snapshots["status_cpu27"]["contains"]["22"]) + session.send_char("o") + session.send_char("o") + screen = session.send_char("o") + assert_status_contains(screen, snapshots["status_cpu30"]["contains"]["22"]) + + with check("COMPARE reports differing address"): + screen = ensure_view(session, "HEX ") + session.fill("C100-C103,10") + session.fill("C200-C203,10") + session.fill("C201-C201,91") + session.fill("C203-C203,93") + screen = session.compare("C100-C103,C200") + assert_contains(screen, 4, "C101") + session.send_key("ENTER") + + with check("TRANSFER relocates absolute operands", u2=False, + u2_reason="Helper writes via REST and asserts U64 RAM content"): + write_rest_memory(rest_host, 0xC400, bytes.fromhex("AD08C48D20D04C00C460")) + write_rest_memory(rest_host, 0xC410, bytes.fromhex("AE08C4")) + write_rest_memory(rest_host, 0xC500, bytes([0x00] * 0x13)) + session.transfer("C400-C40A,C500,C400-C413") + copied = read_rest_memory(rest_host, 0xC500, 0x0A) + outside = read_rest_memory(rest_host, 0xC410, 0x03) + assert_equal("Relocated copied code", "AD08C58D20D04C00C560", copied.hex().upper(), "T relocate copied") + assert_equal("Relocated external operand", "AE08C5", outside.hex().upper(), "T relocate external") + + with check("G executes finite loop and returns to monitor"): + # REST is available on U2 firmware too (route_machine.cc is linked + # into all three target builds); read_rest_memory/write_rest_memory + # will raise SkipCheck if the REST endpoint is genuinely unreachable. + write_rest_memory(rest_host, 0x1000, bytes.fromhex("A9008D0004A9018D00044C0010")) + write_rest_memory(rest_host, 0x0400, bytes([0x20])) + session.goto("1000") + session.goto_run("1000") + wait_for_rest_byte(rest_host, 0x0400, 0x01) + session.enter_monitor() + + with check("G repeated execution updates RAM sentinel"): + run_go_repeat_test(session, rest_host) + + with check("G handoff preserves stable VIC state"): + run_go_visible_state_test(session, rest_host) + + with check("bookmarks recall, set, list, and label edit"): + run_bookmark_test(session) + + with check("memory bookmark jump restores width 16"): + run_memory_bookmark_width_test(session, rest_host) + + with check("binary width cycling and bookmark jump restores width 4"): + run_binary_bookmark_width_test(session, rest_host) + + with check("follow and return navigation"): + run_follow_return_test(session, rest_host) + + with check("number popup arithmetic"): + run_number_arithmetic_test(session, rest_host) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Validate the machine monitor over the standard telnet service") + parser.add_argument("--host", default=os.environ.get("U64_MONITOR_HOST", "u64")) + parser.add_argument("--port", type=int, default=int(os.environ.get("U64_MONITOR_PORT", "23"))) + parser.add_argument("--rest-host", default=os.environ.get("U64_MONITOR_REST_HOST")) + parser.add_argument("--password", default=os.environ.get("U64_MONITOR_PASSWORD")) + parser.add_argument("--timeout", type=float, default=float(os.environ.get("U64_MONITOR_TIMEOUT", "5.0"))) + parser.add_argument("--target", choices=("u64", "u2"), + default=os.environ.get("U64_MONITOR_TARGET", "u64"), + help="Target hardware. 'u2' skips U64-only features (CPU banking, VIC bank, ROM patching, REST API).") + parser.add_argument("--keep-going", action="store_true", + default=os.environ.get("U64_MONITOR_KEEP_GOING", "").lower() in ("1", "true", "yes"), + help="Continue running after a check fails, logging verbose context for each failure.") + args = parser.parse_args() + + TestConfig.target = args.target + # U2 hardware does not expose the REST API, and dozens of tests are + # REST-dependent. Default to keep-going so a remote operator captures + # every failure in a single console run instead of stopping at the first. + TestConfig.keep_going = args.keep_going or args.target == "u2" + TestConfig.failures = [] + TestConfig.skipped = [] + rest_host = args.rest_host or args.host + if args.target == "u2": + if not rest_available(rest_host): + print(f"[info] target=u2 and REST unreachable on {rest_host}; " + f"REST-dependent checks will SKIP", flush=True) + else: + print(f"[info] target=u2 with REST reachable on {rest_host}; " + f"U64-only checks (CPU/VIC banking, KERNAL snapshot) still SKIP", flush=True) + + redeployed = False + while True: + session = None + try: + session = MonitorSession(args.host, args.port, args.password, args.timeout) + TestConfig.session = session + run_tests(session, rest_host) + break + except Failure as exc: + if (not redeployed) and is_u64() and device_unavailable(exc): + try: + redeploy_u64(args.host, args.port, args.password, args.timeout) + except (Failure, OSError, TimeoutError, urllib.error.URLError, subprocess.CalledProcessError) as redeploy_exc: + print(f"Connection failure: {format_exception(redeploy_exc)}", file=sys.stderr) + return 1 + redeployed = True + continue + print(exc, file=sys.stderr) + if session is not None: + snapshot = session.capture() + print("\nFinal screen:", file=sys.stderr) + print(snapshot.text(), file=sys.stderr) + break + except (OSError, TimeoutError, urllib.error.URLError, subprocess.CalledProcessError) as exc: + if (not redeployed) and is_u64() and device_unavailable(exc): + try: + redeploy_u64(args.host, args.port, args.password, args.timeout) + except (Failure, OSError, TimeoutError, urllib.error.URLError, subprocess.CalledProcessError) as redeploy_exc: + print(f"Connection failure: {format_exception(redeploy_exc)}", file=sys.stderr) + return 1 + redeployed = True + continue + print(f"Connection failure: {format_exception(exc)}", file=sys.stderr) + break + finally: + if session is not None: + session.close() + TestConfig.session = None + + _print_summary() + if TestConfig.failures: + return 1 + print(f"monitor_test: OK ({CHECK_COUNT} checks, " + f"{len(TestConfig.skipped)} skipped)") + return 0 + + +def _print_summary() -> None: + """End-of-run summary. Always prints skip+failure counts; lists every + failure in compact form so the operator can scan the console capture + quickly and an LLM can attach each diagnostic block to a fix plan. + """ + passed = CHECK_COUNT - len(TestConfig.failures) - len(TestConfig.skipped) + print("") + print("==== monitor_test summary ====") + print(f" target : {TestConfig.target}") + print(f" passed : {passed}") + print(f" skipped : {len(TestConfig.skipped)}") + print(f" failed : {len(TestConfig.failures)}") + if TestConfig.skipped: + print("") + print("Skipped checks:") + for idx, label, reason in TestConfig.skipped: + print(f" [{idx:02d}] {label} ({reason})") + if TestConfig.failures: + print("") + print("Failed checks:") + for idx, label, _diag in TestConfig.failures: + print(f" [{idx:02d}] {label}") + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/developer/machine-code-monitor/regression_repro.py b/tools/developer/machine-code-monitor/regression_repro.py new file mode 100644 index 000000000..74fd578b4 --- /dev/null +++ b/tools/developer/machine-code-monitor/regression_repro.py @@ -0,0 +1,598 @@ +#!/usr/bin/env python3 +"""Deterministic real-device repros for the four reported monitor regressions. + +Uses only autonomous control/observation: + - key injection via POST /v1/machine:input_ui + - logical screen capture via PUT /v1/machine:dump_ui_screen + GET textlog + - RAM side effects via GET/PUT /v1/machine:readmem|writemem + - interface mode via REST config (set_interface_type) + +Each repro prints a single PASS/FAIL line plus the RAM/state evidence it used. +Run: python3 regression_repro.py --host u64 --case C +""" +import argparse +import sys +import time + +import monitor_direct_test as mdt + + +def log(msg): + print(msg, flush=True) + + +def freeze_reader(session): + def read(): + last = None + for _ in range(6): + try: + return session.dump_ui_screen("rr") + except mdt.Failure as exc: + last = exc + time.sleep(0.3) + raise last + return read + + +def enter_freeze_monitor(session): + """F10 then Ctrl+O (x up to 4) until the MONITOR view is shown (logical dump).""" + reader = freeze_reader(session) + for attempt in range(5): + session.input_ui(["f10"]) + time.sleep(1.0) + session.input_ui(["ctrl_o"]) + time.sleep(1.0) + for _ in range(2): + try: + frame = reader() + if "MONITOR" in frame.text(): + return frame + except mdt.Failure: + pass + session.input_ui(["ctrl_o"]) + time.sleep(0.8) + raise mdt.Failure("could not enter Freeze monitor") + + +def to_basic(session, mode): + mdt.switch_interface_type(session, mode, f"select {mode}") + mdt.wait_interface_type(session, mode, f"select {mode}") + session.reset() + mdt.wait_basic_ready(session) + time.sleep(0.5) + + +def wait_stable_dump(session, needle, timeout=8.0): + """Wait until a logical dump_ui_screen frame contains needle (tolerates the + transitional 404s emitted while the C64 is briefly running).""" + deadline = time.time() + timeout + last = "" + while time.time() < deadline: + try: + frame = session.dump_ui_screen("rr") + last = frame.text() + if needle in last: + return frame + except mdt.Failure: + pass + time.sleep(0.3) + raise mdt.Failure(f"dump never contained {needle!r}; last=\n{last}") + + +def select_view(session, bank, reader): + """Cycle 'o' until monitor view == bank (parsed from the status line).""" + for _ in range(9): + frame = reader() + try: + _, current = mdt.parse_status_banks(mdt.status_line(frame)) + if current == bank: + return frame + except mdt.Failure: + pass + mdt.send_ui_text(session, "o", settle=0.25) + raise mdt.Failure(f"could not select monitor view O{bank}") + + +# -------------------------------------------------------------------------- +# Regression C: Freeze G of RAM-under-ROM must execute the underlying RAM code. +# Mirrors the proven Telnet banked-continue fixture, driven in Freeze mode. +# bootstrap $C000: SEI; LDA #$00; STA $01; JMP $E000 (banks KERNAL/I/O out) +# payload $E000: INC $0400 sentinel via RAM; here we use a counter at $02FF +# We prove execution by a deterministic RAM sentinel that is plain RAM in every +# banking mode ($02FF), incremented by the under-ROM loop. +# -------------------------------------------------------------------------- +def _s(session, n=3): + """Read the three page-2 sentinels $0250..$0252 as a tuple.""" + b = session.read_memory(0x0250, n) + return tuple(b[:n]) + + +def repro_C(session, capture, ocr): + """RAM-only proof of debug step + G for RAM-under-ROM in Freeze mode. + + No screen reads are needed: distinct per-instruction sentinels distinguish a + genuine single-step (one INC at a time) from free execution. + + bootstrap $C000 (visible RAM): SEI; LDA #$35; STA $01; JMP $E000 + payload $E000 (RAM under KERNAL): + INC $0250 ; INC $0251 ; INC $0252 ; JMP $E009 (halt, no more effects) + $0250..$0252 are plain RAM in every banking mode. + """ + bootstrap = 0xC000 + payload = 0xE000 + boot = bytes([0x78, 0xA9, 0x35, 0x85, 0x01, 0x4C, 0x00, 0xE0]) + pay = bytes([0xEE, 0x50, 0x02, # E000 INC $0250 + 0xEE, 0x51, 0x02, # E003 INC $0251 + 0xEE, 0x52, 0x02, # E006 INC $0252 + 0x4C, 0x09, 0xE0]) # E009 JMP $E009 (halt) + + to_basic(session, "Freeze") + session.start_video() + time.sleep(0.5) + mdt.enter_visible_monitor(session, capture, ocr) + log("[Reg C] entered Freeze monitor") + + session.write_memory(payload, pay) + session.write_memory(bootstrap, boot) + session.write_memory(0x0250, bytes([0x00, 0x00, 0x00])) + + # Enter debug at the bootstrap, then single-step (D) through the 4 bootstrap + # instructions (SEI, LDA, STA, JMP) so the parked PC lands at $E000 under ROM. + mdt.send_ui_text(session, "J%04X\n" % bootstrap, settle=0.6) + mdt.send_ui_text(session, "A", settle=0.6) + mdt.send_ui_text(session, "D", settle=0.8) # enter Debug + for _ in range(4): + mdt.send_ui_text(session, "D", settle=0.7) # step bootstrap -> $E000 + s_at_e000 = _s(session) + log(f"[Reg C] after stepping to $E000 (under ROM): $0250..$0252={s_at_e000}") + if s_at_e000 != (0, 0, 0): + log("[Reg C] WARN: bootstrap steps already touched payload sentinels " + f"(unexpected): {s_at_e000}") + + # ONE more single-step: must execute exactly INC $0250 under ROM. + mdt.send_ui_text(session, "D", settle=0.8) + s_step1 = _s(session) + log(f"[Reg C] after 1 debug-step under ROM: $0250..$0252={s_step1}") + step_ok = (s_step1[0] == 1 and s_step1[1] == 0 and s_step1[2] == 0) + + # Now G (no breakpoints): remaining INCs run then halt at $E009. + mdt.send_ui_text(session, "G", settle=0.5) + time.sleep(1.5) + s_go = _s(session) + time.sleep(1.0) + s_go2 = _s(session) + log(f"[Reg C] after Freeze G: $0250..$0252={s_go} then {s_go2}") + go_ran = (s_go[1] >= 1 and s_go[2] >= 1) + # Halt loop means values stabilise (each incremented exactly once total). + halted = (s_go == s_go2) + + ok = step_ok and go_ran + log(f"[Reg C] debug_step_under_ROM={step_ok} G_executed_under_ROM={go_ran} " + f"halted_stable={halted}") + if not go_ran: + log("[Reg C] FAIL: Freeze G did NOT execute the RAM-under-ROM payload " + "(regression reproduced).") + return False + if not step_ok: + log("[Reg C] PARTIAL: Freeze G executed under-ROM code but single-step " + "semantics under ROM look wrong (see sentinels).") + return False + log("[Reg C] PASS: Freeze debug single-step AND G both execute RAM-under-ROM.") + return True + + +def _reachable(session, tries=5, gap=0.5): + """Robust liveness: REST is up if ANY of several probes succeeds.""" + import urllib.error + for _ in range(tries): + try: + session.get_interface_type() + return True + except (mdt.Failure, OSError, TimeoutError, urllib.error.URLError): + time.sleep(gap) + return False + + +def _wait_basic_banner(session, timeout=8.0): + """Wait until the C64 screen shows the post-reset BASIC banner row.""" + deadline = time.time() + timeout + while time.time() < deadline: + try: + row = session.read_memory(0x0420, 24) # row 1, where the banner sits + # 'COMMODORE 64 BASIC' -> screen codes for letters are 0x01.. ; the + # word "BASIC" appears; we look for the screen-code 'BASIC' bytes. + # Simpler: the banner contains 0x42 0x01 0x13 0x09 0x03 ("BASIC"). + if bytes([0x42, 0x01, 0x13, 0x09, 0x03]) in row: + return True + except Exception: + pass + time.sleep(0.3) + return False + + +def repro_A(session, capture, ocr): + """Overlay: RAM-under-ROM debug + G, reset, then C=+X; plus re-entry step. + + Verifies (all without human action/observation): + 1. Overlay G executes RAM-under-ROM (RAM sentinel). + 2. C=+X (injected, monitor active) resets the C64 (BASIC banner returns) + and the device stays reachable. + 3. Re-entering the monitor and single-stepping does NOT hang the device + (REST stays reachable; a single-step has its RAM side effect). + """ + reader = lambda: session.dump_ui_screen("overlay") + bootstrap = 0xC000 + payload = 0xE000 + boot = bytes([0x78, 0xA9, 0x35, 0x85, 0x01, 0x4C, 0x00, 0xE0]) + pay = bytes([0xEE, 0x50, 0x02, 0xEE, 0x51, 0x02, 0x4C, 0x06, 0xE0]) # INC,INC,JMP self + + to_basic(session, "Overlay on HDMI") + mdt.enter_hidden_monitor(session) + log("[Reg A] entered Overlay monitor") + + session.write_memory(payload, pay) + session.write_memory(bootstrap, boot) + session.write_memory(0x0250, bytes([0x00, 0x00])) + + # Faithful to the report: debug-STEP into the RAM-under-ROM code, THEN G. + # Enter debug at the bootstrap and single-step through SEI/LDA/STA/JMP (4) so + # the parked PC is at $E000 under ROM, then one more step executes INC $0250. + mdt.send_ui_text(session, "J%04X\n" % bootstrap, settle=0.4) + mdt.send_ui_text(session, "A", settle=0.4) + mdt.send_ui_text(session, "D", settle=0.6) + for _ in range(4): + mdt.send_ui_text(session, "D", settle=0.5) # step to $E000 (under ROM) + mdt.send_ui_text(session, "D", settle=0.6) # step INC $0250 -> (1,0) + s_step = _s(session, 2) + log(f"[Reg A] after step into under-ROM: $0250..$0251={s_step}") + mdt.send_ui_text(session, "G", settle=0.6) # continue (exercises fixed path) + time.sleep(2.0) + s_go = _s(session, 2) + log(f"[Reg A] after Overlay G (RAM-under-ROM): $0250..$0251={s_go}") + if s_go[1] == 0: + log("[Reg A] FAIL: Overlay G did not continue the RAM-under-ROM payload.") + return False + + # Step 4: reset the machine (REST). Step 5: attempt C=+X afterwards. + session.reset() + time.sleep(2.0) + reach_after_reset = _reachable(session) + log(f"[Reg A] after REST reset: reachable={reach_after_reset}") + + # C=+X as the GLOBAL reset shortcut: it is only the global shortcut when the + # active keymap is NOT the monitor (userinterface.cc keymapper). So open the + # root MENU (F10), confirm a UI is up, dirty the BASIC banner, then C=+X. + session.input_ui(["f10"]) + time.sleep(1.0) + # Corrupt the banner row so a real RESET visibly restores it. + session.write_memory(0x0420, bytes([0x20] * 24)) + banner_before = _wait_basic_banner(session, timeout=1.0) + session.input_ui(["ctrl_x"]) + time.sleep(2.5) + reach_after_cbmx = _reachable(session) + banner = _wait_basic_banner(session, timeout=8.0) + log(f"[Reg A] after C=+X (global, banner_before_wipe={banner_before}): " + f"reachable={reach_after_cbmx} basic_banner_restored={banner}") + + # Step 6/7: re-enter monitor and single-step; must not hang. + session.write_memory(0x0250, bytes([0x00, 0x00])) + session.write_memory(0x02A0, bytes([0xEE, 0x50, 0x02, 0x4C, 0xA0, 0x02])) # INC $0250;JMP self + reentry_ok = False + step_effect = None + try: + mdt.enter_hidden_monitor(session) + mdt.send_ui_text(session, "J%04X\n" % 0x02A0, settle=0.4) + mdt.send_ui_text(session, "A", settle=0.4) + mdt.send_ui_text(session, "D", settle=0.6) # enter debug + mdt.send_ui_text(session, "D", settle=0.7) # one step -> INC $0250 + step_effect = _s(session, 1)[0] + reentry_ok = _reachable(session) + except mdt.Failure as exc: + log(f"[Reg A] re-entry/step raised: {exc}") + log(f"[Reg A] re-entry: reachable={reentry_ok} step_sentinel=$0250={step_effect}") + + ok = (s_go != (0, 0)) and reach_after_reset and reach_after_cbmx and reentry_ok + if not reach_after_cbmx: + log("[Reg A] FAIL: device unreachable after C=+X (hang reproduced).") + elif not banner: + log("[Reg A] NOTE: C=+X did not visibly reset to BASIC banner " + "(C=+X-resets-after-G regression may be present, device still alive).") + if not reentry_ok: + log("[Reg A] FAIL: device hung on monitor re-entry / first step " + "(Symptom B reproduced).") + log("[Reg A] PASS (no hang)" if ok else "[Reg A] see notes above") + return ok + + +# -------------------------------------------------------------------------- +# Freeze-mode coverage matrix: 4 debugger operations x {RAM, RAM-under-ROM}. +# All proofs are RAM-sentinel based (no screen dependency). Sentinels live at +# $0250..$0253 (plain RAM in every banking mode). Each payload is four 3-byte +# INC instructions followed by a 3-byte self-JMP halt, so cursor lines and PCs +# are perfectly regular: line N starts at base + 3*N. +# RAM case : payload runs directly at $C000 ($01 default, $C000 is RAM) +# RAM-under-ROM : bootstrap $C000 banks KERNAL/I/O out then JMP $E000 payload +# -------------------------------------------------------------------------- +PAYLOAD = bytes([ + 0xEE, 0x50, 0x02, # +0 INC $0250 + 0xEE, 0x51, 0x02, # +3 INC $0251 + 0xEE, 0x52, 0x02, # +6 INC $0252 + 0xEE, 0x53, 0x02, # +9 INC $0253 +]) +BOOT = bytes([0x78, 0xA9, 0x35, 0x85, 0x01, 0x4C, 0x00, 0xE0]) + + +def _halt_at(base): + return bytes([0x4C, base & 0xFF, base >> 8]) + + +def _sent4(session): + return tuple(session.read_memory(0x0250, 4)) + + +def _setup_payload(session, under_rom): + """Write the payload (+halt) and clear sentinels. Returns the debug-entry + address and the payload base address.""" + session.write_memory(0x0250, bytes([0, 0, 0, 0])) + if under_rom: + base = 0xE000 + session.write_memory(base, PAYLOAD + _halt_at(base + 12)) + session.write_memory(0xC000, BOOT) + return 0xC000, base, 4 # enter at bootstrap; 4 bootstrap steps reach $E000 + base = 0xC000 + session.write_memory(base, PAYLOAD + _halt_at(base + 12)) + return base, base, 0 + + +def _enter_debug_blind(session, addr): + mdt.send_ui_text(session, "J%04X\n" % addr, settle=0.5) + mdt.send_ui_text(session, "A", settle=0.5) + mdt.send_ui_text(session, "D", settle=0.7) + + +def _leave_debug(session): + session.input_ui(["ctrl_d"]); time.sleep(0.3) + session.input_ui(["escape"]); time.sleep(0.3) + + +def _step_to_payload(session, boot_steps): + """For the RAM-under-ROM case, single-step through the bootstrap so PC parks + at $E000.""" + for _ in range(boot_steps): + mdt.send_ui_text(session, "D", settle=0.6) + + +def freeze_matrix(session, capture, ocr): + to_basic(session, "Freeze") + session.start_video() + time.sleep(0.5) + log("[FZMTX] Freeze mode selected") + + results = {} + + def cell(name, under_rom, op): + # Fresh reset + monitor entry per cell: the firmware UI/debug state does + # not reliably survive a leave-debug + re-enter within one freeze, so we + # start each cell from a clean BASIC + monitor (proven reliable). Retry + # the whole cell once if monitor entry flakes (injected-key menu open is + # intermittently dropped). + last_exc = None + for attempt in range(2): + try: + session.reset() + mdt.wait_basic_ready(session) + time.sleep(0.4) + mdt.enter_visible_monitor(session, capture, ocr) + entry, base, boot_steps = _setup_payload(session, under_rom) + _enter_debug_blind(session, entry) + _step_to_payload(session, boot_steps) # park at payload base + got = op(base) + results[name] = got + log(f"[FZMTX] {name}: {got['verdict']} sentinels={got['sent']}") + return + except Exception as exc: # noqa + last_exc = exc + time.sleep(1.0) + results[name] = {"verdict": "ERROR:%s" % last_exc, "sent": None} + log(f"[FZMTX] {name}: ERROR {last_exc}") + + # --- debug single-step (D): exactly one payload instruction per press --- + def op_step(base): + mdt.send_ui_text(session, "D", settle=0.7) # one payload instruction + s = _sent4(session) + ok = (s == (1, 0, 0, 0)) + return {"verdict": "PASS" if ok else "FAIL", "sent": s} + + # --- run-to-cursor (K): move cursor down 2 lines (-> base+6), run there --- + def op_runcursor(base): + session.input_ui(["down", "down"]); time.sleep(0.3) + mdt.send_ui_text(session, "K", settle=1.2) + s = _sent4(session) + # executes instrs at base+0 and base+3 (stops AT base+6 before exec) + ok = (s == (1, 1, 0, 0)) + return {"verdict": "PASS" if ok else "FAIL", "sent": s} + + # --- go with breakpoint: step once to park (exec base+0), set BP at the + # next instruction (cursor follows PC -> down 1 = base+6), then G. --- + def op_go_bp(base): + mdt.send_ui_text(session, "D", settle=0.7) # step base+0 -> PC base+3 + session.input_ui(["down"]); time.sleep(0.3) # cursor -> base+6 + mdt.send_ui_text(session, "R", settle=0.4) # set breakpoint at base+6 + mdt.send_ui_text(session, "G", settle=1.5) # run; must stop at base+6 + s = _sent4(session) + ok = (s == (1, 1, 0, 0)) + return {"verdict": "PASS" if ok else "FAIL", "sent": s} + + # --- go without breakpoints: step once to park, then free-run to halt --- + def op_go_free(base): + mdt.send_ui_text(session, "D", settle=0.7) # step base+0 -> parked + mdt.send_ui_text(session, "G", settle=1.0) # free run remaining INCs + time.sleep(1.5) + s = _sent4(session) + ok = (s[0] >= 1 and s[1] >= 1 and s[2] >= 1 and s[3] >= 1) + return {"verdict": "PASS" if ok else "FAIL", "sent": s} + + cell("step/RAM", False, op_step) + cell("step/RAM-under-ROM", True, op_step) + cell("runcursor/RAM", False, op_runcursor) + cell("runcursor/RAM-under-ROM", True, op_runcursor) + cell("go+bp/RAM", False, op_go_bp) + cell("go+bp/RAM-under-ROM", True, op_go_bp) + cell("go-free/RAM", False, op_go_free) + cell("go-free/RAM-under-ROM", True, op_go_free) + + npass = sum(1 for v in results.values() if v["verdict"] == "PASS") + log(f"[FZMTX] SUMMARY {npass}/{len(results)} Freeze cells passed") + for k, v in results.items(): + log(f"[FZMTX] {k:26s} {v['verdict']:6s} {v['sent']}") + return npass == len(results) + + +def _frame_signature(frame): + """Coarse readability metric over a decoded VIC frame: count of the box-drawing + border cells and printable letters. A corrupted (wrong-charset) monitor screen + loses the regular border run and turns into high-entropy noise.""" + text = "".join(frame.lines) + border = sum(1 for c in text if c in "ABCDEF") # OCR maps the PETSCII border run to A-F bands + letters = sum(1 for c in text if c.isalpha()) + spaces = sum(1 for c in text if c == " ") + distinct = len(set(text)) + return {"len": len(text), "letters": letters, "spaces": spaces, + "distinct": distinct} + + +def _fresh_capture(capture): + """Drain the UDP socket's backlog so capture_image() returns a CURRENT frame, + not an old buffered one (the multicast socket queues many stale frames).""" + import socket as _socket + capture.sock.setblocking(False) + try: + while True: + try: + capture.sock.recv(2048) + except (BlockingIOError, _socket.error): + break + finally: + capture.sock.setblocking(True) + time.sleep(0.2) + return capture.capture_image() + + +def repro_B(session, capture, ocr): + """Freeze: set the debugged CPU port $01=$03 during stepping; the machine + monitor screen must remain readable (not turn into charset garbage). + + Proof strategy (visual, since this is a rendering claim): capture the Freeze + monitor VIC frame BEFORE and AFTER the debugged context has $01=$03, save + both screenshots, and compare a readability signature. A readable monitor is + dominated by spaces + a regular border/title; a charset-corrupted screen is + high-entropy noise (few spaces, many distinct glyphs). + """ + import os + evdir = "/home/chris/dev/c64/1541ultimate/evidence/20260602" + os.makedirs(evdir, exist_ok=True) + # $2000: LDA #$03 ; STA $01 ; NOP ; NOP ; JMP $2006 ($01=$03 then spin) + prog = bytes([0xA9, 0x03, 0x85, 0x01, 0xEA, 0xEA, 0x4C, 0x06, 0x20]) + + to_basic(session, "Freeze") + session.start_video(); time.sleep(0.5) + mdt.enter_visible_monitor(session, capture, ocr) + session.write_memory(0x2000, prog) + _enter_debug_blind(session, 0x2000) + log("[Reg B] entered debug at $2000") + + # Baseline screenshot (monitor readable, $01 still normal). + time.sleep(0.5) + img0 = _fresh_capture(capture); img0.save(os.path.join(evdir, "regB_before.png")) + f0 = ocr.decode(img0) + sig0 = _frame_signature(f0) + log(f"[Reg B] before $01=$03: sig={sig0}") + + # Step LDA #$03 then STA $01 -> debugged context now has $01=$03. + mdt.send_ui_text(session, "D", settle=0.7) # LDA #$03 + mdt.send_ui_text(session, "D", settle=0.7) # STA $01 (context $01 := $03) + # Continue stepping with $01=$03 in effect. + mdt.send_ui_text(session, "D", settle=0.7) # NOP + mdt.send_ui_text(session, "D", settle=0.7) # NOP + time.sleep(0.6) + img1 = _fresh_capture(capture); img1.save(os.path.join(evdir, "regB_after.png")) + f1 = ocr.decode(img1) + sig1 = _frame_signature(f1) + log(f"[Reg B] after $01=$03: sig={sig1}") + # Verify $01 actually became $03 in the executed context via RAM readback of + # the live value the program stored (it executed STA $01). + live01 = session.read_memory(0x0001, 1)[0] + log(f"[Reg B] live $01 readback={live01:#04x}") + + # Readability heuristic: a readable monitor frame is space-dominated; a + # charset-corrupted frame collapses spaces and inflates distinct glyphs. + readable = (sig1["spaces"] >= max(200, sig0["spaces"] * 0.6)) + log(f"[Reg B] screenshots saved: regB_before.png / regB_after.png") + if not readable: + log("[Reg B] FAIL: monitor screen lost its readable structure after " + f"$01=$03 (spaces {sig0['spaces']}->{sig1['spaces']}) - corruption reproduced.") + return False + log("[Reg B] PASS: monitor screen remained readable with $01=$03.") + return True + + +def repro_fzgobp(session, capture, ocr): + """Focused: Freeze go-with-breakpoint, RAM payload at $C000.""" + to_basic(session, "Freeze") + session.start_video(); time.sleep(0.5) + mdt.enter_visible_monitor(session, capture, ocr) + session.write_memory(0x0250, bytes([0, 0, 0, 0])) + session.write_memory(0xC000, PAYLOAD + _halt_at(0xC00C)) + _enter_debug_blind(session, 0xC000) + log("[FZGOBP] entered debug at $C000") + mdt.send_ui_text(session, "D", settle=0.7) # step $C000 -> PC $C003 + log(f"[FZGOBP] after 1 step: {_sent4(session)}") + session.input_ui(["down"]); time.sleep(0.3) # cursor -> $C006 + mdt.send_ui_text(session, "R", settle=0.4) # BP at $C006 + session.input_ui(["up"]); time.sleep(0.3) # cursor back to PC $C003 + mdt.send_ui_text(session, "G", settle=1.5) # continue from PC; stop at BP $C006 + s = _sent4(session) + log(f"[FZGOBP] after BP+G: {s} (expect (1,1,0,0))") + return s == (1, 1, 0, 0) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--host", default="u64") + ap.add_argument("--timeout", type=float, default=5.0) + ap.add_argument("--case", default="C", + choices=["C", "A", "B", "freeze-matrix", "fzgobp"]) + args = ap.parse_args() + session = mdt.RestSession(args.host, args.timeout) + capture = mdt.VicStreamCapture() + ocr = mdt.C64FrameOCR() + ok = False + cleanup_ok = True + try: + ok = {"C": repro_C, "A": repro_A, "B": repro_B, + "freeze-matrix": freeze_matrix, + "fzgobp": repro_fzgobp}[args.case](session, capture, ocr) + finally: + try: + session.stop_video() + except Exception: + pass + try: + capture.close() + except Exception: + pass + try: + session.write_memory(0x0001, bytes([0x37])) + value = session.read_memory(0x0001, 1)[0] + log(f"[cleanup/{args.case}] $0001 readback={value:#04x}") + if (value & 0x07) != 0x07: + raise mdt.Failure(f"cleanup failed to restore safe $0001, got {value:#04x}") + session.reset() + except Exception as exc: + cleanup_ok = False + log(f"[cleanup/{args.case}] FAIL: {exc}") + return 0 if ok and cleanup_ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/developer/machine-code-monitor/snapshots/expected_snapshots.json b/tools/developer/machine-code-monitor/snapshots/expected_snapshots.json new file mode 100644 index 000000000..751d30c21 --- /dev/null +++ b/tools/developer/machine-code-monitor/snapshots/expected_snapshots.json @@ -0,0 +1,68 @@ +{ + "kernal_hex_e000": { + "contains": { + "4": "E000 85 56 20 0F BC A5 61 C9" + } + }, + "kernal_disasm_e000": { + "contains": { + "4": "E000 85 56 STA $56", + "5": "E002 20 0F BC JSR $BC0F" + } + }, + "kernal_disasm_e013": { + "contains": { + "4": "E013 18 CLC" + } + }, + "status_cpu31": { + "contains": { + "22": "CPU7 $A:BAS $D:I/O $E:KRN VIC" + } + }, + "ascii_top_row": { + "contains": { + "4": "C000 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + } + }, + "ascii_scrolled_top_row": { + "contains": { + "4": "C020 BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + } + }, + "hex_first_nibble": { + "contains": { + "4": "C000 A0" + } + }, + "hex_second_nibble": { + "contains": { + "4": "C000 AB" + } + }, + "status_cpu27": { + "contains": { + "22": "C7O3 $A:BAS $D:CHR $E:KRN VIC" + } + }, + "status_cpu30": { + "contains": { + "22": "C7O6 $A:RAM $D:I/O $E:KRN VIC" + } + }, + "status_cpu26": { + "contains": { + "22": "C7O2 $A:RAM $D:CHR $E:KRN VIC" + } + }, + "status_cpu29": { + "contains": { + "22": "C7O5 $A:RAM $D:I/O $E:RAM VIC" + } + }, + "ram_a000": { + "contains": { + "4": "A000 AA" + } + } +}