@henols/c64-re-tools 2.2.1 → 2.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -99,12 +99,12 @@ The scripts refuse a step in the form of version 2.0, for example `{ "runUntil":
99
99
  2. Run `trace`. It gives the evidence from the run. `writtenThenExecuted` lists the ranges that the program wrote and then executed. Read `packing`:
100
100
  - `likely`: the program wrote code and then executed it. It unpacked, decrypted or moved code. `runningRange` is the written code that runs at the end of the trace. When the trace ends in ROM code, for example in an interrupt, it is the written code that runs next. Its `start` is code that runs after the unpacking. It is not always the entry point of the program. When no written code runs in 50 more frames, the result has no `runningRange` and no `suggestedUntil`.
101
101
  - `unclear`: the program executed a small quantity of code that it wrote. This can be code that changes itself.
102
- - `unlikely`: the program executed no code that it wrote. If the program waits for a key or a joystick, it can move code after that input. Then use the c64-emulator skill.
102
+ - `unlikely`: the program executed no code that it wrote. If the program waits for a key or a joystick, it can move code after that input. Then use the emulator skill.
103
103
  3. Find the address where the unpacked program starts:
104
104
  - Run `stages`. The `entry` of the last stage is usually the start of the program. A routine that a stage writes and calls is part of that stage when it returns to the stage.
105
105
  - Or use `runningRange.start` from `trace`, or `suggestedUntil`. The CPU gets to `suggestedUntil` after the unpacking.
106
- - Or use the c64-emulator skill: set a breakpoint after the unpack loop, or look at the last JMP of the unpacker.
107
- - Disassemble the code at the address with the c64-emulator skill. Make sure that it is the start of the program. The start of a program often sets the stack pointer, the interrupts and the vectors.
106
+ - Or use the emulator skill: set a breakpoint after the unpack loop, or look at the last JMP of the unpacker.
107
+ - Disassemble the code at the address with the emulator skill. Make sure that it is the start of the program. The start of a program often sets the stack pointer, the interrupts and the vectors.
108
108
  - A program can be relocated and not packed. Then a short copier moves the code and jumps to it. The moved code is the last stage. Make sure that the `entry` of the last stage is not code that the program writes later. An example is a routine that the program makes at run time. Disassemble the entry to make sure.
109
109
  4. Run `capture` with that address and a directory in `--out`. Give the same `--steps` as before. The directory gets:
110
110
  - `image.bin`: all 64 KiB of RAM at the entry.
@@ -162,7 +162,7 @@ For `loads`: `captures`, with the name, the PC, the segments, `differsFromReset`
162
162
 
163
163
  - `traced: false` or `followed: false`: the emulator did not load the program into memory in the time limit. The reason gives the load address. Make sure that the file is a PRG that the C64 can load.
164
164
  - `traced: false` or `followed: false` with `stopReason`: the CPU stopped before the frames ran, for example at a JAM instruction. `pc` gives the address. Make sure that `--entry` is the start of the code that the file holds at that time, and that the steps are correct.
165
- - `captured: false`: the program did not get to the address in the time limit. The reason tells where it stopped. Find a better address with the c64-emulator skill, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
165
+ - `captured: false`: the program did not get to the address in the time limit. The reason tells where it stopped. Find a better address with the emulator skill, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
166
166
  - A step did not reach its target: the reason names the step. Change the step or give it more frames.
167
167
  - `loaded: false` with an empty `captures` and the reason `BASIC ran no program line`: the PRG has no BASIC start line. Use `capture` with `--entry`.
168
168
  - `loaded: false` and no capture has a segment: the program did not load a part, or it did not start. `keyWait: true` on a capture tells that the C64 waited for a key at the READY prompt or at an INPUT statement. For a tape image, read `emulatorFlaw`. A known VICE flaw can stop a tape load. Tell the user to install the latest VICE.
@@ -174,4 +174,4 @@ For `loads`: `captures`, with the name, the PC, the segments, `differsFromReset`
174
174
  ## Handoffs
175
175
 
176
176
  - Unpacked machine code → c64-static-analysis
177
- - Find the start address at run time → c64-emulator
177
+ - Find the start address at run time → emulator
@@ -0,0 +1,137 @@
1
+ ---
2
+ name: emulator
3
+ description: Use this skill to operate and debug the live emulator through the MCP tools of the c64-re-tools machine server. For the C64, the tool names start with c64_. It loads programs and disks, controls and steps the CPU, and sets breakpoints and watchpoints. It reads and writes memory and registers, gives keyboard and joystick input, advances frames and captures the screen. Do not use it for static analysis, project knowledge, assembly or disk inspection.
4
+ ---
5
+
6
+ # emulator
7
+
8
+ ## Purpose
9
+
10
+ Operate and debug the one live machine that belongs to this MCP session. Get runtime evidence and runtime state from it.
11
+
12
+ This skill does not analyse code statically. It does not write project knowledge. It does not assemble source code.
13
+
14
+ The MCP server knows the machine and the emulator. Its instructions, its tool descriptions, its result fields and its error messages give the facts of the machine and the known flaws of the emulator. This skill tells how to use the tools for a task. If this skill and a tool description do not agree, obey the tool description.
15
+
16
+ ## Inputs
17
+
18
+ - The machine action or the runtime question.
19
+ - The target address, state or condition, when the question needs one.
20
+ - The project path of the program or disk to load, when the question needs one.
21
+
22
+ A tool takes addresses, not names. The server instructions give the address format. Get the address of a name with `knowledge.ts at <name>` of the c64-knowledge skill.
23
+
24
+ ## Tools / execution path
25
+
26
+ Use only the MCP tools. Each MCP session has its own machine. Nothing else can change that machine.
27
+
28
+ | Need | C64 tool |
29
+ |---|---|
30
+ | Run state, warp mode, window, version of the MCP server | `c64_status` |
31
+ | Reset, power cycle | `c64_reset` |
32
+ | Fast emulation | `c64_warp` |
33
+ | Show the machine to the user in a window, hide it again | `c64_window` |
34
+ | Stop, start, step, step over, step out, exact frames | `c64_execution` |
35
+ | Run until an address, a memory value or a raster position | `c64_run_until` |
36
+ | Run to a place and read the machine there in one call | `c64_run_until` with `observe` and `history` |
37
+ | Each access or routine entry over many frames | `c64_trace` |
38
+ | Stop on an instruction address, stop on a memory access | `c64_breakpoint`, `c64_watchpoint` |
39
+ | Memory | `c64_memory_read`, `c64_memory_write`, `c64_memory_search`, `c64_memory_compare` |
40
+ | CPU registers | `c64_registers` |
41
+ | Code as it is in memory now | `c64_disassemble` |
42
+ | Executed instructions, call chain | `c64_cpu_history`, `c64_backtrace` |
43
+ | Cycles of each routine, memory use, cycles between two points | `c64_profile`, `c64_memmap`, `c64_timing` |
44
+ | Chips of the machine | `c64_vicii`, `c64_sprite`, `c64_cia`, `c64_sid` |
45
+ | Screen image, screen compare | `c64_screen` |
46
+ | Several of these from one moment | `c64_observe` |
47
+ | Keyboard, joystick | `c64_keyboard`, `c64_joystick` |
48
+ | Program and disk media | `c64_autostart`, `c64_program_load`, `c64_disk_attach` |
49
+ | Machine state to go back to, also in a later session | `c64_snapshot` |
50
+
51
+ Read the description of a tool before you use it for the first time. It gives the limits of the tool and the facts of the machine that change the result.
52
+
53
+ A result field `emulatorFlaw` names a known flaw of the emulator. Tell the user about the flaw. Do not use a result that the flaw can make wrong as a fact.
54
+
55
+ For a large result, give `out`. Write a file that is only for your work in `.c64-re-tools/local/` of the project. Git ignores that folder. When a tool needs `project`, give the same folder as the `--project` of the skill scripts.
56
+
57
+ To keep a coverage run:
58
+
59
+ 1. Clear the memory map with `c64_memmap` action `clear`.
60
+ 2. Run the part of the program that you want to keep.
61
+ 3. Read the map with `c64_memmap` action `read` and `out`, for example to `.c64-re-tools/local/attract.bin`.
62
+ 4. Add the file to the knowledge with `coverage` of the c64-knowledge skill.
63
+
64
+ ## Workflow
65
+
66
+ 1. Read the project knowledge for the addresses in the question. Use the c64-knowledge skill.
67
+ 2. Get the machine state with `c64_status`.
68
+ 3. Load the subject if it is not loaded. Use `c64_autostart` to start it as a user does. Use `c64_program_load` to put a program in memory with no start.
69
+ 4. Set the stop condition. Use a breakpoint, a watchpoint or a `c64_run_until` target. Add a condition when the stop must occur only in one state.
70
+ 5. Run, step or give input. Prefer `c64_run_until` and `advance-frames` to waits. They stop at the same emulated time on every run.
71
+ 6. Read only the state that answers the question. To read several things from one moment, use `c64_observe`.
72
+ 7. Interpret the evidence. Keep the observed facts apart from your conclusions.
73
+
74
+ Before a risky experiment, save the state with `c64_snapshot`. Restore it to try again from the same point.
75
+
76
+ ### Input that the tools cannot give
77
+
78
+ Some programs read input in a way that the input tools cannot give. The tool description tells when. Then use one of these ways:
79
+
80
+ - Open the window and ask the user to give the input.
81
+ - Record a session with a `press` step. Use `testing.ts record` of the c64-testing skill.
82
+
83
+ Do not change the program to make it accept the input.
84
+
85
+ ### The window
86
+
87
+ The emulator has no window. When the user must type, play or look at the machine, do these steps:
88
+
89
+ 1. Open the window with `c64_window` action `open`.
90
+ 2. Tell the user that the window is open and what to do in it.
91
+ 3. Wait until the user tells you that they finished.
92
+ 4. Close the window with `c64_window` action `close`.
93
+
94
+ The result field `notCarried` names the data that the move cleared.
95
+
96
+ ## Knowledge
97
+
98
+ Read:
99
+ - the current knowledge for each address and range that the question touches.
100
+
101
+ Automatic write:
102
+ - none.
103
+
104
+ Write after interpretation:
105
+ - a symbol, a region or a comment that the runtime evidence justifies. Record it with the c64-knowledge skill.
106
+
107
+ Do not store:
108
+ - breakpoints or watchpoints
109
+ - memory reads
110
+ - temporary machine state
111
+ - a screen capture, unless the user asks for it as an artifact
112
+
113
+ ## Result
114
+
115
+ The result is the runtime state or evidence that the question asks for.
116
+
117
+ If you cannot get the machine into the necessary state, say which state you could not get. Say what you tried.
118
+
119
+ ## Failure and conflicts
120
+
121
+ An error is `{"error": {"code": "...", "message": "..."}}`. The message tells what is wrong and what to do. Obey the message. These rules also apply:
122
+
123
+ - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script. Do not try to repair the installation.
124
+ - `machine-unavailable` with a message that names a pause or a dialog in the window: do not send more operations. Give the message to the user. When the user tells you that the emulator runs again, do the operation again.
125
+ - `machine-unavailable` for a different cause: wait a few seconds. Then do the operation again one time. If you get the same error again, stop the task. Tell the user to restart the c64-re-tools MCP server, and wait for the user.
126
+ - `machine-state-lost`: do not use results from before the error. Do what the message tells. Then read the machine state again.
127
+ - `stopReason` `timeout` or `jam`: this is evidence too. Report it. For `jam`, report the address.
128
+ - A different code: the message names the cause. Change the call, or report the cause.
129
+
130
+ If the runtime evidence does not agree with the current knowledge, do not change the knowledge. Report the conflict and hand it to c64-knowledge.
131
+
132
+ ## Handoffs
133
+
134
+ - Static explanation of code → c64-static-analysis
135
+ - Durable conclusion or a knowledge conflict → c64-knowledge
136
+ - Comparison or assertion between runs → c64-testing
137
+ - Meaning of a C64 address or register → c64-memory-map
package/src/cli/main.ts CHANGED
@@ -36,7 +36,7 @@ project folder below the root uses that install; a project is a folder with
36
36
  through npx. The Host Runtime runs on the machine with VICE: start it there
37
37
  with npx -y --package=${PACKAGE.name}@${PACKAGE.tag} c64-re-tools-host.
38
38
  It runs VICE and the tools that come with it (c1541, petcat). The skill
39
- scripts run ACME, DXA, Ghidra and c64run in the dev container.`;
39
+ scripts run ACME, DXA, Exomizer, Ghidra and c64run in the dev container.`;
40
40
 
41
41
  const here = dirname(fileURLToPath(import.meta.url));
42
42
 
@@ -1,7 +1,7 @@
1
- // The byte check of a build: the assembled program against the program
2
- // in the knowledge, segment by segment.
1
+ // The byte check of a program: a PRG against a reference program, for example
2
+ // the program in the knowledge, segment by segment.
3
3
 
4
- import { formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
4
+ import { formatC64Address, formatC64Byte, prgRange } from "./c64.ts";
5
5
 
6
6
  export interface SegmentCheck {
7
7
  start: string;
package/src/mcp/output.ts CHANGED
@@ -7,7 +7,7 @@ import { z } from "zod";
7
7
 
8
8
  import { projectFolder, writeReported, type Written } from "../host-client/transfer.ts";
9
9
 
10
- export const OutInput = z.string().min(1).describe("write the data to this file, relative to the project folder. An existing file is overwritten. The tool description tells what the result then gives");
10
+ export const OutInput = z.string().min(1).describe("write the data to this file, relative to the project folder. An existing file is overwritten. The result then gives the file (out), the number of bytes (bytes) and a SHA-256 (sha256) in place of the data");
11
11
 
12
12
  /** The project of a tool with a path. */
13
13
  export const ProjectInput = z
@@ -17,9 +17,9 @@ export const ProjectInput = z
17
17
 
18
18
  /** The fields of a result with out, optional in an output schema that also has the inline form. */
19
19
  export const WrittenOutput = {
20
- out: z.string().optional(),
21
- bytes: z.number().int().min(0).optional(),
22
- sha256: z.string().regex(/^[0-9a-f]{64}$/).optional(),
20
+ out: z.string().optional().describe("with out: the file that the tool wrote"),
21
+ bytes: z.number().int().min(0).optional().describe("with out: the number of bytes in the file"),
22
+ sha256: z.string().regex(/^[0-9a-f]{64}$/).optional().describe("with out: the SHA-256 of the file"),
23
23
  };
24
24
 
25
25
  /** Lines as file text: each line ends with a newline, and no lines give an empty file. */
package/src/mcp/server.ts CHANGED
@@ -274,10 +274,15 @@ function packageVersion(): string {
274
274
  const INSTRUCTIONS =
275
275
  "These tools control one live Commodore 64 emulator that belongs to this session. " +
276
276
  "An address is a dollar sign and 1 to 4 hex digits, for example $c000 or $fb. A result gives four hex digits. " +
277
- "An error is {\"error\": {\"code\", \"message\"}}. " +
277
+ "An error is {\"error\": {\"code\", \"message\"}}. The message tells what is wrong and what to do. " +
278
278
  "Memory data is lowercase hex without separators. " +
279
279
  "Other register values and chip values are decimal numbers. " +
280
- "A read does not change the run state of the machine.";
280
+ "A read does not change the run state of the machine. " +
281
+ "Space c64 is the computer. Space drive8 is the CPU of the 1541 disk drive. " +
282
+ "Memory view cpu gives what the CPU sees now, with ROM and I/O where the memory configuration puts them. Memory view ram gives the RAM under them. " +
283
+ "A write to memory or registers needs a stopped CPU: stop it with c64_execution action pause. " +
284
+ "Paths are relative to the project folder, the folder that holds .c64-re-tools/. " +
285
+ "With out, a tool writes a large result to a project file in place of the result.";
281
286
 
282
287
  export function createMcpServer(options: { tools: readonly ToolDefinition[]; session: SessionSource; log?: (line: string) => void }): Server {
283
288
  const tools = new Map(options.tools.map((tool) => [tool.name, tool]));
@@ -44,7 +44,8 @@ export const c64Breakpoint = defineTool({
44
44
  "Action add sets one at address in space c64 or drive8. With a condition, it stops only when the condition is true. " +
45
45
  "add returns the new id. Breakpoints and watchpoints take their ids from one counter, so the ids of one kind can have gaps. " +
46
46
  "Actions remove, enable and disable take that id. remove returns removed true and the id. Action list gives all breakpoints. Each breakpoint shows its condition, when it has one. " +
47
- "Breakpoints stay through a reset.",
47
+ "Breakpoints stay through a reset. " +
48
+ "In space drive8, the drive can execute a few more instructions before it stops. pc in the stop result is the drive address where it stopped.",
48
49
  inputSchema: z
49
50
  .object({
50
51
  action: z.enum(CHECKPOINT_ACTIONS),
@@ -87,7 +88,8 @@ export const c64Watchpoint = defineTool({
87
88
  `Action add sets one from start to end (at most ${MAX_WATCH_SIZE} bytes, end defaults to start), with access read, write or read-write. ` +
88
89
  "With a condition, it stops only when the condition is true. For a write, a memory condition sees the memory after the write. " +
89
90
  "add returns the new id. Breakpoints and watchpoints take their ids from one counter, so the ids of one kind can have gaps. " +
90
- "Actions remove, enable and disable take that id. remove returns removed true and the id. Action list gives all watchpoints. Each watchpoint shows its condition, when it has one.",
91
+ "Actions remove, enable and disable take that id. remove returns removed true and the id. Action list gives all watchpoints. Each watchpoint shows its condition, when it has one. " +
92
+ "In space drive8, the drive can execute a few more instructions before it stops. pc in the stop result is the drive address where it stopped.",
91
93
  inputSchema: z
92
94
  .object({
93
95
  action: z.enum(CHECKPOINT_ACTIONS),
@@ -139,6 +141,7 @@ export const c64CpuHistory = defineTool({
139
141
  "Each entry gives the address, the bytes, the instruction and the registers a, x, y and sp before the instruction executed. " +
140
142
  "In space c64, it also gives the raster line and cycle when the instruction started. " +
141
143
  "With out, it writes the entries as text lines to that project file, and the result gives the file in place of the entries. " +
144
+ "After a JAM, the emulator records no history until the next reset. If the CPU ran again after a snapshot restore, this tool refuses. Then use c64_reset, or use c64_trace. " +
142
145
  "This does not change the run state of the machine.",
143
146
  inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_HISTORY).default(50), space: SpaceInput, out: OutInput.optional(), project: ProjectInput.optional() }).strict(),
144
147
  outputSchema: z.object({
@@ -349,7 +352,7 @@ export const c64Memmap = defineTool({
349
352
  start: AddressInput.optional().describe("read and summary. Default $0000"),
350
353
  end: AddressInput.optional().describe("read and summary. Default $ffff"),
351
354
  maxRanges: z.number().int().min(1).max(MAX_MEMMAP_RANGES).optional().describe("read without out only. Default 256"),
352
- out: OutInput.optional().describe("read only: write a coverage map to this project file, one byte for each address. An existing file is overwritten"),
355
+ out: OutInput.optional().describe("read only: write a coverage map to this project file, one byte for each address. An existing file is overwritten. The result then gives the file, the number of bytes and a SHA-256"),
353
356
  project: ProjectInput.optional().describe("read with out only: the project folder, relative to the folder where the agent started. Give it when that folder is not in a project and has projects below it"),
354
357
  })
355
358
  .strict(),
@@ -75,6 +75,7 @@ export const c64RunUntil = defineTool({
75
75
  "reached tells if the target occurred. stopReason tells why the CPU stopped: target, breakpoint, watchpoint, jam (a JAM opcode) or timeout. " +
76
76
  "pointId gives the id of the breakpoint or watchpoint that stopped the CPU. " +
77
77
  "space tells which CPU stopped: c64, or drive8 for a stop in the disk drive. pc is the address in that space. " +
78
+ "The drive can execute a few more instructions before it stops. " +
78
79
  "With observe, the result also gives what c64_observe gives at the stop, in observed. " +
79
80
  `With history (1 to ${MAX_HISTORY}), it also gives the last instructions before the stop, as c64_cpu_history gives them. ` +
80
81
  "Thus one call runs to a place and reads the machine there. " +
@@ -18,6 +18,7 @@ export const c64Keyboard = defineTool({
18
18
  "No tool presses one key of the keyboard matrix. For one specific key, ask the user to press it in the window, or give a press step in a record file of c64-testing. " +
19
19
  'Mode text types text, for example "RUN\\n". Letters of either case type the normal (unshifted) key. A line break types RETURN. ' +
20
20
  "Mode petscii types PETSCII codes 1 to 255 in bytes, for example [147] to clear the screen. " +
21
+ "While c64_autostart loads a program, this tool refuses keys: see c64_autostart. " +
21
22
  "This does not change the run state of the machine. emulatorFlaw in the result names a known flaw of the emulator version that affects input, and the version that fixes it.",
22
23
  inputSchema: TOOL_INPUTS.keyboard,
23
24
  outputSchema: z.object({ queuedBytes: z.number().int().min(1).max(MAX_KEYBOARD_BYTES), emulatorFlaw: EMULATOR_FLAW }),
@@ -76,7 +76,7 @@ export const c64Reset = defineTool({
76
76
  description:
77
77
  "Reset the C64. Mode soft is the reset button. Mode hard is a power cycle that also resets the disk drive. " +
78
78
  "With run false (the default), the CPU stops at the first instruction of the reset routine, and the result gives that program counter (pc). " +
79
- "With run true, the C64 starts normally. Breakpoints and watchpoints stay.",
79
+ "With run true, the C64 starts normally. Breakpoints and watchpoints stay. The c64_timing stopwatch starts again from zero.",
80
80
  inputSchema: z
81
81
  .object({
82
82
  mode: z.enum(RESET_MODES).describe("soft is the reset button. hard is a power cycle"),
@@ -29,7 +29,9 @@ export const c64Autostart = defineTool({
29
29
  "Both joysticks are centred first: joystick port 1 uses the keyboard lines, and a held direction changes the RUN that the autostart types. " +
30
30
  "Without index, a disk image loads like LOAD\"*\",8,1. index selects one directory entry by its number in the c64-disk directory list (0 is the first entry). " +
31
31
  "The tool refuses an index of a DEL entry, or an index after the last entry. " +
32
- "The machine runs when this tool returns, and the load continues.",
32
+ "The machine runs when this tool returns, and the load continues. The emulator keeps warp mode on until it types RUN. " +
33
+ "A key in that time stops the autostart, so c64_keyboard refuses keys until then. Run frames with c64_execution advance-frames until c64_status gives warp false. " +
34
+ "The c64_timing stopwatch starts again from zero.",
33
35
  inputSchema: z
34
36
  .object({
35
37
  path: ProjectPath,
@@ -107,7 +109,7 @@ export const c64Snapshot = defineTool({
107
109
  .object({
108
110
  action: z.enum(["save", "restore", "list", "remove"]),
109
111
  name: TransientName.optional().describe("save and remove, and restore without file: 1 to 64 letters, digits, dots, underscores or hyphens"),
110
- out: OutInput.optional().describe("save only: also write the snapshot to this project file, for example snapshots/room0.vsf. An existing file is overwritten"),
112
+ out: OutInput.optional().describe("save only: also write the snapshot to this project file, for example snapshots/room0.vsf. An existing file is overwritten. The result then also gives the file, the number of bytes and a SHA-256"),
111
113
  file: ProjectPath.optional().describe("restore only: a .vsf file in the project, in place of name"),
112
114
  project: ProjectInput.optional().describe("save with out, and restore with file: the project folder, relative to the folder where the agent started. Give it when that folder is not in a project and has projects below it"),
113
115
  })
@@ -55,6 +55,14 @@ export const DXA: ToolSpec = {
55
55
  remedy: INSTALL_STEPS,
56
56
  };
57
57
 
58
+ export const EXOMIZER: ToolSpec = {
59
+ name: "Exomizer",
60
+ envVar: "C64RT_EXOMIZER",
61
+ binaries: ["exomizer"],
62
+ where: "on this machine",
63
+ remedy: INSTALL_STEPS,
64
+ };
65
+
58
66
  export const C64RUN: ToolSpec = {
59
67
  name: "c64run",
60
68
  envVar: "C64RT_C64RUN",
@@ -0,0 +1,90 @@
1
+ // The Exomizer adapter: packs PRG files into one C64 program that unpacks
2
+ // itself (exomizer sfx), then unpacks that program again in the 6502
3
+ // emulator of Exomizer (exomizer desfx), so the caller can check the bytes
4
+ // and the entry of the result before anyone runs it.
5
+
6
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+
9
+ import { formatC64Address } from "../c64.ts";
10
+ import { WireFailure } from "../protocol/messages.ts";
11
+ import { EXOMIZER, findTool } from "./discover.ts";
12
+ import { outputTail, runToolOrFail, type ToolContext } from "./run.ts";
13
+ import { Workspace } from "./staging.ts";
14
+
15
+ /** A full 64 KiB program with all optimization passes can take minutes. */
16
+ const TIMEOUT_MS = 600_000;
17
+ const PACKED = "packed.prg";
18
+ const UNPACKED = "unpacked.prg";
19
+
20
+ /** The unpacker of Exomizer runs below $0400; the emulator of desfx stops when the program counter leaves that area. */
21
+ export const MIN_ENTRY = 0x0400;
22
+
23
+ export interface PackParams {
24
+ /** The PRG files in load order: where two overlap, the later one wins. */
25
+ programs: readonly Uint8Array[];
26
+ /** Where the unpacked program starts, at MIN_ENTRY or above. */
27
+ entry: number;
28
+ /** The value of $01 when the program starts, $34 to $37. Without it, the value at the start of the packed program ($37). */
29
+ exitMemory?: number;
30
+ }
31
+
32
+ export interface Packed {
33
+ /** The packed PRG: a BASIC SYS line at $0801 with the unpacker, then the packed data. */
34
+ program: Buffer;
35
+ /** What the emulator of Exomizer unpacked: a PRG of the largest range that the unpacker wrote. */
36
+ unpacked: Buffer;
37
+ /** Where the unpacker jumped when it was done. */
38
+ entry: number;
39
+ /** The CPU cycles of the unpacking, when Exomizer gives them. */
40
+ cycles?: number;
41
+ }
42
+
43
+ /** The argv of the pack: the entry comes first, then the options, then the input files in load order. */
44
+ export function sfxArguments(executable: string, params: Omit<PackParams, "programs">, inputs: readonly string[], output: string): string[] {
45
+ const argv = [executable, "sfx", String(params.entry), "-t64", "-n", "-o", output];
46
+ if (params.exitMemory !== undefined) argv.push(`-Di_ram_exit=${params.exitMemory}`);
47
+ argv.push(...inputs);
48
+ return argv;
49
+ }
50
+
51
+ /** The entry and the cycles in the output of desfx: ' Decrunch took 1.234567 Mcycles, ...' and ' Writing "x" as prg, saving from $0801 to $9000, entry at $0810.' */
52
+ export function parseDesfx(output: string): { entry: number; cycles?: number } | undefined {
53
+ const entry = /entry at \$([0-9a-fA-F]{4})\./.exec(output)?.[1];
54
+ if (entry === undefined) return undefined;
55
+ const mcycles = /Decrunch took ([0-9.]+) Mcycles/.exec(output)?.[1];
56
+ return { entry: Number.parseInt(entry, 16), ...(mcycles === undefined ? {} : { cycles: Math.round(Number(mcycles) * 1_000_000) }) };
57
+ }
58
+
59
+ /** Lines of Exomizer output that tell why it stopped. */
60
+ const PROBLEM = /error|warning|can't|cannot|overlap/i;
61
+
62
+ export async function pack(params: PackParams, context: ToolContext): Promise<Packed> {
63
+ if (params.programs.length === 0) throw new WireFailure("invalid-input", "Give at least one PRG to pack.");
64
+ if (params.entry < MIN_ENTRY) throw new WireFailure("invalid-input", `The entry ${formatC64Address(params.entry)} is below $0400. The unpacker of Exomizer runs there. Give an entry at $0400 or above.`);
65
+ const executable = findTool(EXOMIZER, context.env);
66
+ const workspace = Workspace.create(context.supervisor);
67
+ try {
68
+ // Plain names: Exomizer reads "name,address" as a file with a new load address.
69
+ const input = workspace.directory("in");
70
+ const inputs = params.programs.map((program, index) => {
71
+ const path = join(input, `${index}.prg`);
72
+ writeFileSync(path, program, { flag: "wx" });
73
+ return path;
74
+ });
75
+ const output = workspace.directory("out");
76
+ const packedPath = join(output, PACKED);
77
+ const packing = await runToolOrFail("Exomizer", "The pack", { argv: sfxArguments(executable, params, inputs, packedPath), cwd: workspace.root, timeoutMs: TIMEOUT_MS }, context);
78
+ if (packing.code !== 0) throw new WireFailure("operation-failed", `Exomizer could not pack the program (exit ${packing.code}).${outputTail("Exomizer", packing, workspace.root, PROBLEM)}`);
79
+ if (!existsSync(packedPath)) throw new WireFailure("operation-failed", "Exomizer reported success but wrote no program.");
80
+ const unpackedPath = join(output, UNPACKED);
81
+ const unpacking = await runToolOrFail("Exomizer", "The unpack check", { argv: [executable, "desfx", "-o", unpackedPath, packedPath], cwd: workspace.root, timeoutMs: TIMEOUT_MS }, context);
82
+ const found = parseDesfx(`${unpacking.stdout}\n${unpacking.stderr}`);
83
+ if (unpacking.code !== 0 || found === undefined || !existsSync(unpackedPath)) {
84
+ throw new WireFailure("operation-failed", `Exomizer could not unpack the packed program in its emulator (exit ${unpacking.code}).${outputTail("Exomizer", unpacking, workspace.root)}`);
85
+ }
86
+ return { program: readFileSync(packedPath), unpacked: readFileSync(unpackedPath), ...found };
87
+ } finally {
88
+ workspace.remove();
89
+ }
90
+ }
@@ -1,14 +1,14 @@
1
1
  // Tool status: finds each native tool the way its operations do and runs it
2
2
  // once with a version option, so a user can see in advance which tools work.
3
3
  // The Host Runtime reports VICE and its tools (host.status); the CLI reports
4
- // the tools that skill scripts run themselves (ACME, DXA, Ghidra).
4
+ // the tools that skill scripts run themselves (ACME, DXA, Exomizer, Ghidra).
5
5
 
6
6
  import { tmpdir } from "node:os";
7
7
  import { stripVTControlCharacters } from "node:util";
8
8
 
9
9
  import { isRefusal } from "../errors.ts";
10
10
  import { type ToolStatus } from "../protocol/tools.ts";
11
- import { ACME, C64RUN, DXA, findTool, INSTALL_STEPS } from "./discover.ts";
11
+ import { ACME, C64RUN, DXA, EXOMIZER, findTool, INSTALL_STEPS } from "./discover.ts";
12
12
  import { findGhidra, ghidraVersion, NO_USABLE_JDK, noJdk } from "./ghidra/index.ts";
13
13
  import { runTool, type ToolContext } from "./run.ts";
14
14
  import { Workspace } from "./staging.ts";
@@ -129,6 +129,7 @@ export async function localToolStatus(context: ToolContext): Promise<ToolStatus[
129
129
  // dxa -V prints its version and exits with status 1. It names itself by argv[0], without the
130
130
  // directory only where that uses "/": on Windows the line starts with the full path.
131
131
  { name: "dxa", find: (env) => findTool(DXA, env), args: ["-V"], pattern: DXA_VERSION },
132
+ { name: "Exomizer", find: (env) => findTool(EXOMIZER, env), args: ["-v"], pattern: /^Exomizer v\d/ },
132
133
  ];
133
134
  return [...(await probeTools(probes, context)), await probeGhidra(context), await probeC64run(context)];
134
135
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bash
2
2
  # The native tools of the skill scripts in a Debian or Ubuntu dev container,
3
- # as root: ACME, dxa, c64run with its C64 ROMs, and Ghidra. The dev container
3
+ # as root: ACME, dxa, Exomizer, c64run with its C64 ROMs, and Ghidra. The dev container
4
4
  # Feature runs the copy of this script that comes with the toolkit version it
5
5
  # installs, so the tools and the skills are always of the same version.
6
6
  # A tool is installed again only when its install files changed: a stamp in
@@ -55,6 +55,7 @@ tool() {
55
55
 
56
56
  packages acme unzip curl ca-certificates build-essential
57
57
  tool dxa install-dxa.sh
58
+ tool exomizer install-exomizer.sh
58
59
  tool c64run install-chips.sh c64run.c
59
60
  tool ghidra install-ghidra.sh
60
61
 
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env bash
2
+
3
+ set -Eeuo pipefail
4
+
5
+ # ------------------------------------------------------------
6
+ # Exomizer installer. install-container.sh runs it as root, with
7
+ # build-essential and curl.
8
+ #
9
+ # Installs:
10
+ # /usr/local/bin/exomizer
11
+ #
12
+ # Exomizer version:
13
+ # 3.1.2 (tag 3.1.2, commit df77c879ce2a)
14
+ # ------------------------------------------------------------
15
+
16
+ EXOMIZER_VERSION="3.1.2"
17
+
18
+ # Bitbucket makes the archive of the tag on request, so its bytes can change.
19
+ # The check is on the source files that the build uses: the SHA-256 of the
20
+ # sorted list of "sha256 ./path" lines of src/.
21
+ EXOMIZER_URL="https://bitbucket.org/magli143/exomizer/get/${EXOMIZER_VERSION}.tar.gz"
22
+ EXOMIZER_SOURCE_SHA256="0824d19bdf5a2cc752d2c21e1e6314f7d5feb398bc2d42510aebc1a2e4f08c72"
23
+
24
+ BIN_DIR="/usr/local/bin"
25
+
26
+ BUILD_DIR=""
27
+
28
+ error()
29
+ {
30
+ printf '\nERROR: %s\n' "$*" >&2
31
+ exit 1
32
+ }
33
+
34
+ cleanup()
35
+ {
36
+ if [[ -n "${BUILD_DIR}" && -d "${BUILD_DIR}" ]]; then
37
+ rm -rf "${BUILD_DIR}"
38
+ fi
39
+ }
40
+
41
+ trap cleanup EXIT
42
+
43
+ [[ "$(id -u)" -eq 0 ]] || error "Run as root."
44
+
45
+ printf '\n==> Installing Exomizer %s to %s/exomizer\n' "${EXOMIZER_VERSION}" "${BIN_DIR}"
46
+
47
+ BUILD_DIR="$(mktemp -d -t exomizer-build-XXXXXXXX)"
48
+ cd "${BUILD_DIR}"
49
+
50
+ curl --fail --location --show-error --silent --retry 3 --output exomizer.tar.gz "${EXOMIZER_URL}"
51
+ tar -xzf exomizer.tar.gz
52
+
53
+ # The archive holds one folder, named after the repository and the commit.
54
+ SOURCE_DIR="$(find "${BUILD_DIR}" -mindepth 2 -maxdepth 2 -type d -name src -print -quit)"
55
+ [[ -n "${SOURCE_DIR}" ]] || error "The archive has no src folder."
56
+ cd "${SOURCE_DIR}"
57
+
58
+ ACTUAL_SHA256="$(find . -type f | LC_ALL=C sort | xargs sha256sum | sha256sum | cut -d' ' -f1)"
59
+ if [[ "${ACTUAL_SHA256}" != "${EXOMIZER_SOURCE_SHA256}" ]]; then
60
+ error "The source files of Exomizer ${EXOMIZER_VERSION} have the SHA-256 ${ACTUAL_SHA256}, not ${EXOMIZER_SOURCE_SHA256}. Refusing to compile them."
61
+ fi
62
+
63
+ make CC=gcc exomizer
64
+
65
+ [[ "$(./exomizer -v 2>&1 || true)" == *"Exomizer v${EXOMIZER_VERSION} "* ]] || error "The compiled exomizer does not run or is not version ${EXOMIZER_VERSION}."
66
+
67
+ install -d -m 0755 "${BIN_DIR}"
68
+ install -m 0755 exomizer "${BIN_DIR}/exomizer"
69
+
70
+ printf '\nExomizer %s is installed: %s/exomizer\n' "${EXOMIZER_VERSION}" "${BIN_DIR}"