@henols/c64-re-tools 2.6.0-rc.8 → 2.6.0
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.
- package/package.json +2 -2
- package/skills/c64-assembler/SKILL.md +3 -3
- package/skills/c64-assembler/scripts/assembler.ts +4 -3
- package/skills/c64-development/SKILL.md +3 -3
- package/skills/c64-docs/SKILL.md +6 -4
- package/skills/c64-docs/scripts/docs.ts +23 -10
- package/skills/c64-docs/scripts/lib/reference.ts +117 -31
- package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
- package/skills/c64-knowledge/SKILL.md +10 -9
- package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
- package/skills/c64-reverse-engineering/SKILL.md +9 -3
- package/skills/c64-source/SKILL.md +13 -10
- package/skills/c64-source/scripts/lib/export.ts +13 -2
- package/skills/c64-source/scripts/lib/loader.ts +51 -28
- package/skills/c64-source/scripts/lib/source.ts +24 -7
- package/skills/c64-source/scripts/source.ts +65 -47
- package/skills/c64-static-analysis/SKILL.md +26 -22
- package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
- package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
- package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
- package/skills/c64-static-analysis/scripts/static-analysis.ts +51 -35
- package/skills/c64-testing/SKILL.md +11 -4
- package/skills/c64-testing/references/recording-format.md +19 -7
- package/skills/c64-testing/references/scenario-format.md +6 -5
- package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
- package/skills/c64-testing/scripts/lib/play.ts +39 -37
- package/skills/c64-testing/scripts/lib/recording.ts +213 -65
- package/skills/c64-testing/scripts/lib/replay.ts +31 -5
- package/skills/c64-testing/scripts/lib/runs.ts +8 -3
- package/skills/c64-testing/scripts/lib/scenario.ts +4 -6
- package/skills/c64-testing/scripts/testing.ts +23 -2
- package/skills/c64-unpacker/SKILL.md +6 -3
- package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
- package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
- package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
- package/skills/emulator/SKILL.md +2 -5
- package/src/build-name.ts +9 -4
- package/src/c64-keys.ts +98 -0
- package/src/c64.ts +1 -1
- package/src/host/main.ts +2 -2
- package/src/host/server.ts +3 -1
- package/src/host/tools/index.ts +1 -1
- package/src/host/vice/process.ts +34 -17
- package/src/host/vice/session.ts +132 -30
- package/src/host-client/steps.ts +21 -18
- package/src/host-client/tools.ts +1 -1
- package/src/host-client/vice-session.ts +7 -1
- package/src/knowledge/evidence.ts +66 -0
- package/src/knowledge/history.ts +5 -5
- package/src/knowledge/import.ts +12 -5
- package/src/knowledge/program.ts +81 -33
- package/src/knowledge/read.ts +12 -3
- package/src/knowledge/schema.ts +7 -7
- package/src/knowledge/start-screen.ts +2 -0
- package/src/knowledge/text.ts +28 -3
- package/src/knowledge/write.ts +6 -6
- package/src/mcp/inputs.ts +12 -0
- package/src/mcp/server.ts +1 -0
- package/src/mcp/tools/debug.ts +23 -21
- package/src/mcp/tools/input.ts +38 -5
- package/src/mcp/tools/memory.ts +12 -9
- package/src/native/c64run.ts +7 -4
- package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
- package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
- package/src/native/{ghidra → decompiler}/walk.ts +6 -6
- package/src/native/discover.ts +3 -3
- package/src/native/processes.ts +3 -3
- package/src/native/types.ts +25 -25
- package/src/opcodes.ts +1 -1
- package/src/protocol/vice.ts +47 -0
- package/src/reference-pages.ts +64 -0
- package/src/script.ts +1 -1
- package/src/vsf.ts +98 -0
- package/tools/c64run.c +158 -15
- package/skills/c64-testing/scripts/lib/keys.ts +0 -36
- /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
- /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
- /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The c64-static-analysis script: analyzes the program in the knowledge
|
|
2
|
-
// with DXA (fast first pass) or
|
|
2
|
+
// with DXA (fast first pass) or the decompiler (deeper), which it runs itself, seeded
|
|
3
3
|
// from current knowledge and the coverage of the knowledge, and imports the
|
|
4
4
|
// structural findings into .c64-re-tools/knowledge/.
|
|
5
5
|
|
|
@@ -9,19 +9,19 @@ import { WireFailure } from "#src/host-client/tools.ts";
|
|
|
9
9
|
import { writeReported } from "#src/host-client/transfer.ts";
|
|
10
10
|
import { knowledgeNames } from "#src/knowledge/names.ts";
|
|
11
11
|
import { analyze as analyzeWithDxa } from "#src/native/dxa.ts";
|
|
12
|
-
import { analyze as
|
|
12
|
+
import { analyze as analyzeWithDecompiler } from "#src/native/decompiler/analyze.ts";
|
|
13
13
|
import { localToolContext } from "#src/native/local.ts";
|
|
14
|
-
import {
|
|
14
|
+
import { DECOMPILER_LIMITS } from "#src/native/types.ts";
|
|
15
15
|
import { openForRead, withWrite } from "#src/knowledge/database.ts";
|
|
16
16
|
import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
|
|
17
17
|
import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
|
|
18
|
-
import { importFindings, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
|
|
18
|
+
import { importFindings, lastToolVersion, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
|
|
19
19
|
import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
|
|
20
20
|
import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
|
|
21
21
|
import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
|
|
22
22
|
import { listed, OPTIONS, reply, runScript, UsageError, type Call } from "#src/script.ts";
|
|
23
23
|
import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, type ImageByte } from "./lib/coverage.ts";
|
|
24
|
-
import { dxaFindings,
|
|
24
|
+
import { dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
|
|
25
25
|
import { findIdioms } from "./lib/idioms.ts";
|
|
26
26
|
import { instructionList } from "./lib/instructions.ts";
|
|
27
27
|
import { CATALOGUE, findMacroUses, type MacroCandidate } from "./lib/macros.ts";
|
|
@@ -36,8 +36,13 @@ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them
|
|
|
36
36
|
* analyzer data over executed code to classify, and macro candidates to write.
|
|
37
37
|
* The envelope adds the sentence for a cut list.
|
|
38
38
|
*/
|
|
39
|
-
function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }) {
|
|
39
|
+
function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number) {
|
|
40
40
|
const hints: string[] = [];
|
|
41
|
+
if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
|
|
42
|
+
hints.push(`The last analysis of this program used ${version.last}. Thus a change in revision ${version.revision} can come from the new analyzer version, and not from the program or the project knowledge.`);
|
|
43
|
+
}
|
|
44
|
+
// A leftover is data that no reference reads: a retired reference can make one.
|
|
45
|
+
if (retiredReferences > 0) hints.push("The analysis retired references. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.");
|
|
41
46
|
if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
|
|
42
47
|
if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
|
|
43
48
|
if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
|
|
@@ -75,11 +80,11 @@ function showMacro(candidate: MacroCandidate) {
|
|
|
75
80
|
* the ROMs that the program uses, as c64-source names them. A candidate is left out when
|
|
76
81
|
* a name or a reference target is inside it, or a patch or a use overlaps it:
|
|
77
82
|
* c64-source would write its instructions. The same use in the knowledge is
|
|
78
|
-
* known. The writes are the candidates with the macros they need
|
|
79
|
-
*
|
|
80
|
-
* candidates out of the writes.
|
|
83
|
+
* known. The writes are the candidates with the macros they need, without the
|
|
84
|
+
* candidates that start at an address of `skip`. A macro of the catalogue that
|
|
85
|
+
* the knowledge has with another body leaves its candidates out of the writes.
|
|
81
86
|
*/
|
|
82
|
-
function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
|
|
87
|
+
function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
|
|
83
88
|
const db = openForRead();
|
|
84
89
|
try {
|
|
85
90
|
// The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
|
|
@@ -104,16 +109,18 @@ function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
|
|
|
104
109
|
const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
|
|
105
110
|
const writes: BatchOperation[] = [];
|
|
106
111
|
const other = new Set<string>();
|
|
107
|
-
|
|
112
|
+
const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
|
|
113
|
+
for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
|
|
108
114
|
const existing = macros.get(idiom.name);
|
|
109
115
|
if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
|
|
110
116
|
else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
|
|
111
117
|
}
|
|
112
|
-
for (const candidate of
|
|
118
|
+
for (const candidate of chosen) {
|
|
113
119
|
if (other.has(candidate.macro)) continue;
|
|
114
120
|
writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
|
|
115
121
|
}
|
|
116
|
-
|
|
122
|
+
const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
|
|
123
|
+
return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
|
|
117
124
|
} finally {
|
|
118
125
|
db?.close();
|
|
119
126
|
}
|
|
@@ -173,13 +180,15 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
173
180
|
const decompile = call.addresses("decompile");
|
|
174
181
|
if (decompile.length > 32) throw new UsageError("--decompile takes at most 32 routines");
|
|
175
182
|
const max = call.count("max-listed")!;
|
|
176
|
-
const analyzer = call.string("analyzer") as "dxa" | "
|
|
183
|
+
const analyzer = call.string("analyzer") as "dxa" | "decompiler";
|
|
177
184
|
const listingPath = call.string("out-listing");
|
|
178
185
|
const instructionsPath = call.string("out-instructions");
|
|
179
186
|
const applyMacros = call.flag("apply-macros");
|
|
180
|
-
|
|
181
|
-
if (
|
|
182
|
-
if (analyzer === "dxa" &&
|
|
187
|
+
const skip = new Set(call.addresses("skip"));
|
|
188
|
+
if (skip.size > 0 && !applyMacros) throw new UsageError("--skip works only with --apply-macros: it names a macro candidate that the run does not write");
|
|
189
|
+
if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer decompiler");
|
|
190
|
+
if (analyzer === "decompiler" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
|
|
191
|
+
if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer decompiler");
|
|
183
192
|
const space = call.space;
|
|
184
193
|
const reader = openForRead();
|
|
185
194
|
const program = requireProgram(reader, space);
|
|
@@ -199,31 +208,33 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
199
208
|
const revision = currentRevision(reader);
|
|
200
209
|
const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
|
|
201
210
|
// Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
|
|
202
|
-
// at most
|
|
203
|
-
//
|
|
211
|
+
// at most DECOMPILER_LIMITS.entryPoints (1024) entry points for both analyzers, and for the decompiler at most
|
|
212
|
+
// DECOMPILER_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
|
|
204
213
|
const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
|
|
205
214
|
const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
|
|
206
|
-
//
|
|
215
|
+
// The decompiler takes the coverage as code starts without a function; DXA has one list.
|
|
207
216
|
const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
|
|
208
217
|
const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
|
|
209
|
-
seeds.entryPoints = ordered.slice(0,
|
|
210
|
-
const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0,
|
|
218
|
+
seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
|
|
219
|
+
const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0, DECOMPILER_LIMITS.codeStarts);
|
|
211
220
|
// Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
|
|
212
221
|
// A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
|
|
213
222
|
const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
|
|
214
223
|
const dataRanges = [...seeds.dataRanges];
|
|
215
224
|
for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
|
|
216
|
-
seeds.dataRanges = dataRanges.slice(0,
|
|
225
|
+
seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
|
|
217
226
|
const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
|
|
218
227
|
const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
|
|
219
228
|
// Platform names are C64 names: drive code and banks get none.
|
|
220
229
|
const platform = space === DEFAULT_SPACE ? platformNames() : [];
|
|
230
|
+
/** The analyzer version of the last analysis of these bytes: a new version can change the findings by itself. */
|
|
231
|
+
const lastVersion = reader === undefined ? undefined : lastToolVersion(reader, analyzer, bytes);
|
|
221
232
|
reader?.close();
|
|
222
233
|
/** Imports the idioms as their own revision, after the analyzer's, and gives their part of the result. */
|
|
223
234
|
const idiomsResult = () => {
|
|
224
235
|
const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
|
|
225
236
|
// The macro candidates read the code regions after both imports.
|
|
226
|
-
const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state));
|
|
237
|
+
const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state), skip);
|
|
227
238
|
// With --apply-macros, the candidates and their macros are a third revision of the LLM.
|
|
228
239
|
const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
|
|
229
240
|
const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
|
|
@@ -253,6 +264,8 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
253
264
|
...(macros.known === 0 ? {} : { known: macros.known }),
|
|
254
265
|
...(macros.leftOut === 0 ? {} : { leftOut: macros.leftOut }),
|
|
255
266
|
...(written === undefined ? {} : { revision: written.revision, writes: macros.writes.length }),
|
|
267
|
+
...(macros.skipped === 0 ? {} : { skipped: macros.skipped }),
|
|
268
|
+
...(macros.notCandidates.length === 0 ? {} : { notCandidates: macros.notCandidates.map(formatC64Address) }),
|
|
256
269
|
...(macros.otherMacros.length === 0 ? {} : { otherMacros: macros.otherMacros }),
|
|
257
270
|
},
|
|
258
271
|
},
|
|
@@ -292,6 +305,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
292
305
|
const found = idiomsResult();
|
|
293
306
|
const body = {
|
|
294
307
|
analyzer: "dxa",
|
|
308
|
+
...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
|
|
295
309
|
...(space === DEFAULT_SPACE ? {} : { space }),
|
|
296
310
|
...found,
|
|
297
311
|
...coverageResult(),
|
|
@@ -301,13 +315,13 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
301
315
|
labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
|
|
302
316
|
...(written === undefined ? {} : { listing: written }),
|
|
303
317
|
};
|
|
304
|
-
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision });
|
|
318
|
+
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
|
|
305
319
|
}
|
|
306
320
|
|
|
307
|
-
const { result } = await
|
|
308
|
-
// Executed instruction starts that
|
|
321
|
+
const { result } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
|
|
322
|
+
// Executed instruction starts that the decompiler did not decode: the instruction list and the source miss them.
|
|
309
323
|
const decoded = new Set(result.instructions.map((instruction) => instruction.address));
|
|
310
|
-
const imported = record({ ...
|
|
324
|
+
const imported = record({ ...decompilerFindings(result), space, ...executed }, revision, "Decompiler analysis of the program", runProvenance(bytes, result.toolVersion));
|
|
311
325
|
const found = idiomsResult();
|
|
312
326
|
// A start inside a dual-use region is a known overlap, for example the second instruction of a BIT skip: one list cannot hold both.
|
|
313
327
|
// Read after the idioms, which write those regions.
|
|
@@ -321,7 +335,8 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
321
335
|
instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
|
|
322
336
|
}
|
|
323
337
|
const body = {
|
|
324
|
-
analyzer: "
|
|
338
|
+
analyzer: "decompiler",
|
|
339
|
+
...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
|
|
325
340
|
...(space === DEFAULT_SPACE ? {} : { space }),
|
|
326
341
|
...(instructions === undefined ? {} : { instructions }),
|
|
327
342
|
...found,
|
|
@@ -335,28 +350,29 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
335
350
|
? {}
|
|
336
351
|
: { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
|
|
337
352
|
};
|
|
338
|
-
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision });
|
|
353
|
+
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
|
|
339
354
|
}
|
|
340
355
|
|
|
341
356
|
await runScript({
|
|
342
357
|
name: "static-analysis",
|
|
343
|
-
summary: "Analyzes the program in the knowledge with DXA or
|
|
358
|
+
summary: "Analyzes the program in the knowledge with DXA or the decompiler, seeded from the knowledge and its coverage, and imports the structural findings into the knowledge.",
|
|
344
359
|
names: knowledgeNames,
|
|
345
360
|
commands: [
|
|
346
361
|
{
|
|
347
362
|
name: "analyze",
|
|
348
363
|
summary: "Runs the analyzer over the program in the knowledge and imports what it finds as one revision, then the 6502 idioms as a second one.",
|
|
349
364
|
options: {
|
|
350
|
-
analyzer: { kind: "choice", value: "<dxa|
|
|
365
|
+
analyzer: { kind: "choice", value: "<dxa|decompiler>", choices: ["dxa", "decompiler"], default: "decompiler", help: "dxa (a fast first pass) or decompiler (deeper, the default)" },
|
|
351
366
|
entry: { ...OPTIONS.entry, multiple: true, help: "an entry point of the program" },
|
|
352
|
-
decompile: { kind: "address", value: "<address>", multiple: true, help: "
|
|
367
|
+
decompile: { kind: "address", value: "<address>", multiple: true, help: "decompiler: a routine to decompile, at most 32" },
|
|
353
368
|
space: OPTIONS.space,
|
|
354
369
|
"max-listed": { ...OPTIONS["max-listed"], help: "list at most n labels, functions or candidates (default 50, 0 for none). The counts are always given, and the knowledge has all labels and functions" },
|
|
355
370
|
"out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
|
|
356
|
-
"out-instructions": { kind: "path", output: "file", value: "<file>", help: "
|
|
371
|
+
"out-instructions": { kind: "path", output: "file", value: "<file>", help: "decompiler: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
|
|
357
372
|
"apply-macros": { kind: "flag", help: "write the macro candidates (the macros and their uses) to the project knowledge as one revision of the LLM" },
|
|
373
|
+
skip: { kind: "address", value: "<address>", multiple: true, help: "with --apply-macros: the start of a macro candidate that is not correct. The run does not write it" },
|
|
358
374
|
},
|
|
359
|
-
notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too.
|
|
375
|
+
notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. The decompiler needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
|
|
360
376
|
run: analyze,
|
|
361
377
|
},
|
|
362
378
|
],
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: c64-testing
|
|
3
|
-
description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on
|
|
3
|
+
description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on the default build of the rebuild. Use it to find what changed between two machine states, and to make a checklist for a human playtest. It does not find the cause of a difference. It does not build the program.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# C64 testing
|
|
@@ -48,6 +48,7 @@ To get the command list, run the script with no arguments.
|
|
|
48
48
|
- `--state` and `--pin` take a name or a `$` address, with `:size` for more than one byte, for example `room:2`. Use the names that the project knowledge has at the time of the replay.
|
|
49
49
|
- The joystick port of `--joystick` is the port that the program reads. Port 2 is `$DC00`, and port 1 is `$DC01`. Find the port in the code or in the project knowledge. If you do not know the port, use 2.
|
|
50
50
|
- `diff` takes two states of one kind. A state is a snapshot file (`.vsf`), a memory file (`.bin`) of a run, or an observation of a run (`results.json:<name>`). A `save` step of a run writes a snapshot file. A snapshot save in the emulator also writes one.
|
|
51
|
+
- Each command starts its own emulator. Thus many commands can run at the same time. For example, other commands can run while a long `record` runs in the background.
|
|
51
52
|
|
|
52
53
|
### Paths and the project folder
|
|
53
54
|
|
|
@@ -178,6 +179,8 @@ A recording keeps a session of the original program, for example a play through
|
|
|
178
179
|
- Make the recordings early, before you change the program.
|
|
179
180
|
- Ask the user to play first. Tell the user which parts of the program the recordings must have, for example each room, a fight and a lost life.
|
|
180
181
|
- Record a session from steps only for a part that the sessions of the user do not have, or when the user cannot play.
|
|
182
|
+
- Replay each recording on the default build. Do not replay a release build or a build with a switch that is not at its default.
|
|
183
|
+
- When the generated source has a loader, the default build is `build/clean_loader.prg`. Give `--symbols build/symbols/clean_loader.json` with it. Else the default build is `build/clean.prg`, with `--symbols build/symbols/clean.json`.
|
|
181
184
|
- Commit the recording folder with the scenarios. Do not put a recording into the project knowledge. Do not put test results, screenshots or playtest results into it.
|
|
182
185
|
- A finding that a recording shows can go into the project knowledge. Give the `recording.json` of the recording as its test evidence.
|
|
183
186
|
- The C64 of a recording has no disk drive. For a program that loads more files from a disk, use a scenario with `test`.
|
|
@@ -204,10 +207,12 @@ The script does the steps of the record file on the original program. Then it wr
|
|
|
204
207
|
- `executed`: the number of instructions in the coverage map.
|
|
205
208
|
- `coverageFrom`: the `frame` and the `pc` where the coverage map starts. `null` when the coverage did not start.
|
|
206
209
|
- `reason`: with a FAIL, why the session did not complete.
|
|
210
|
+
- `evidence`: only when the project knowledge gives a file of `--out` as evidence, and this record changed the file. Each item has the `file`, its `state` and the `revisions` that give the file.
|
|
207
211
|
|
|
208
212
|
Do this for each result:
|
|
209
213
|
|
|
210
|
-
- `PASS`: `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
|
|
214
|
+
- `PASS`: for a folder in `tests/recordings/`, `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. Git ignores `.c64-re-tools/local/`, thus the project knowledge must not name a file in it. For a folder there, `hint` tells you to record again with `--out tests/recordings/<name>`. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
|
|
215
|
+
- `PASS` with `evidence`: you recorded into the folder of an earlier recording. Put the new `coverage.bin` into the project knowledge as coverage. It replaces the map of the earlier recording. For another file in `evidence`, examine the facts of its revisions against the new recording.
|
|
211
216
|
- `FAIL` after a cancel on the page: `hint` tells you to ask the user what to do. Do not record a session from steps in place of the session of the user.
|
|
212
217
|
- Another `FAIL`: `reason` names the step that did not complete. Examples are a `runUntil` step that did not get to its target, and a `type` step with too many keys. Change the step, then run `record` again.
|
|
213
218
|
- `coverageFrom` is `null` and `executed` is 0: the coverage did not start, so the coverage map is empty. The recording can still replay.
|
|
@@ -236,6 +241,8 @@ A `$` address is an address of the original. On the rebuild, it moves with the n
|
|
|
236
241
|
|
|
237
242
|
A rebuild can be a loader with a start screen that RUN starts. If the symbols of the rebuild have `loader_start_screen_wait` and `loader_start_screen_continue`, the script runs the rebuild to the wait. Then it sets the PC to `loader_start_screen_continue`. The cycles before the wait do not count.
|
|
238
243
|
|
|
244
|
+
A rebuild can be the loader program of a generated source. Give its symbols. Then the replay counts from the entry of the program, where the loader jumps to. The checkpoints of both sides start at that entry. At the entry, the rebuild gets the raster position, the CIA timers and the interrupt state of the original. The loader cannot set them as the original has them in the replay. A runUntil step to an address does not count the code of the loader, or the code that the original runs before that entry. If another step of the recording runs before the entry, the result is INCONCLUSIVE. Then start the steps of the record file after the entry.
|
|
245
|
+
|
|
239
246
|
`body` holds `result`, `side`, `firstDifference`, `reason` and `files`. The section "Replay" of `references/recording-format.md` gives each field.
|
|
240
247
|
|
|
241
248
|
Do this for each result:
|
|
@@ -251,8 +258,8 @@ Do this for each result:
|
|
|
251
258
|
|
|
252
259
|
Traps:
|
|
253
260
|
|
|
254
|
-
- `idleReads` counts the input reads of the rebuild that the recording had no value for. On the original, such a read makes the result INCONCLUSIVE.
|
|
255
|
-
- The script refuses a recording of version
|
|
261
|
+
- `idleReads` counts the input reads of the rebuild that the recording had no value for. On the original, such a read makes the result INCONCLUSIVE. The rebuild can read input where the original does not, for example in its loader before the start screen. Such reads do not change a PASS of the rebuild.
|
|
262
|
+
- The script refuses a recording of an older version in an old form with `invalid-input`. Record the session again.
|
|
256
263
|
|
|
257
264
|
---
|
|
258
265
|
|
|
@@ -37,7 +37,7 @@ A record file is one JSON object in a project file.
|
|
|
37
37
|
The steps have the form of the steps of a scenario. Two steps behave differently:
|
|
38
38
|
|
|
39
39
|
- `type` puts at most 10 keys into the keyboard queue of the KERNAL. It is an event: a replay does it again.
|
|
40
|
-
- `press` pushes keys of the keyboard matrix. It is input.
|
|
40
|
+
- `press` pushes keys of the keyboard matrix. It is input.
|
|
41
41
|
|
|
42
42
|
A record file has no `raster` target and no `condition`. `write` and `runUntil` have only the space `c64`.
|
|
43
43
|
|
|
@@ -45,28 +45,40 @@ A record file has no `raster` target and no `condition`. `write` and `runUntil`
|
|
|
45
45
|
|---|---|
|
|
46
46
|
| `{ "frames": 300 }` | Run 300 frames (19656 cycles each). |
|
|
47
47
|
| `{ "joystick": { "port": 2, "direction": "left", "fire": true } }` | Set a joystick. It stays in this state until the next joystick step. |
|
|
48
|
-
| `{ "press": "RUN\n" }` | Press
|
|
48
|
+
| `{ "press": { "keys": "RUN\n" } }` | Press the keys of the keyboard matrix. Each tap holds its keys for 3 frames, then releases them for 3 frames. `frames` sets a different number, from 1 to 3000. |
|
|
49
49
|
| `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 10 keys into the keyboard queue of the KERNAL, after the keys that wait there. |
|
|
50
50
|
| `{ "write": { "address": "next_room", "data": "01" } }` | Write bytes into RAM. |
|
|
51
51
|
| `{ "registers": { "pc": "change_room", "a": 16 } }` | Set registers at the next instruction. `pc` continues the program at that address. |
|
|
52
52
|
| `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 300 } }` | Run until the CPU gets to an address. |
|
|
53
53
|
| `{ "runUntil": { "target": { "kind": "memory", "address": "room", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a byte compares true with `value`. The script reads the byte at the end of each frame. |
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
Each character of `keys` is one tap. a to z press the same keys as A to Z. `\n` presses RETURN. A character with SHIFT, for example `!`, also presses the left SHIFT.
|
|
56
|
+
|
|
57
|
+
The program runs while a `press` step taps its keys. An event in these frames is past when the next step starts. After a `press` step, run until an address that the program gets to later. For example, after F1 starts a game, run until the main loop of the game, not until the routine that starts the game.
|
|
56
58
|
|
|
57
59
|
A key without a character has its name in braces, in upper or lower case. `{STOP}` is RUN/STOP, and `{CBM}` is the Commodore key. The names are:
|
|
58
60
|
|
|
59
61
|
- `{F1}` to `{F8}`, `{RETURN}`, `{SPACE}`, `{DEL}`, `{INST}`, `{HOME}`, `{CLR}`
|
|
60
|
-
- `{STOP}`, `{RUN}`, `{CTRL}`, `{CBM}`, `{LSHIFT}`, `{RSHIFT}`
|
|
62
|
+
- `{STOP}`, `{RUN}`, `{RESTORE}`, `{CTRL}`, `{CBM}`, `{LSHIFT}`, `{RSHIFT}`
|
|
61
63
|
- `{UP}`, `{DOWN}`, `{LEFT}`, `{RIGHT}`, `{POUND}`, `{UPARROW}`, `{LEFTARROW}`
|
|
62
64
|
|
|
63
|
-
|
|
65
|
+
`{F2}`, `{F4}`, `{F6}`, `{F8}`, `{RUN}`, `{CLR}`, `{INST}`, `{UP}` and `{LEFT}` also press the left SHIFT.
|
|
66
|
+
|
|
67
|
+
To hold keys together in one tap, join them with `+` in braces. For example, `{ "press": { "keys": "{LSHIFT+CBM}" } }` holds the left SHIFT and the Commodore key together. One tap holds at most 4 keys. RESTORE counts as a key.
|
|
64
68
|
|
|
65
69
|
The keyboard queue of the KERNAL holds 10 keys. If the keys of a `type` step and the keys that wait in the queue do not fit, the session stops. A program that reads the keyboard hardware does not see the keys of a `type` step. Use `press` for that program.
|
|
66
70
|
|
|
67
71
|
`joystick`, `press` and `frames` steps are input and time. The recording keeps their effect in the reads, so a replay does not do these steps again.
|
|
68
72
|
|
|
69
|
-
|
|
73
|
+
RESTORE starts an NMI and is not a read. The recording keeps each RESTORE of a `press` step as an event of that step. The replay presses RESTORE again at the same read of the program.
|
|
74
|
+
|
|
75
|
+
`type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. A replay does the event again at the same point:
|
|
76
|
+
|
|
77
|
+
- A `runUntil` step to an address: the point is the number of times that the CPU got to that address. This step does not need an input read.
|
|
78
|
+
- An event that comes directly after another event runs at once after that event.
|
|
79
|
+
- Each other event: the point is the next read at the input site with the most reads. That site is not in ROM. If the program does not read input in 600 frames, the session stops.
|
|
80
|
+
|
|
81
|
+
Some parts of a program read no input, for example an intro or a bonus screen. To do an event in such a part, put a `runUntil` step to an address before the event.
|
|
70
82
|
|
|
71
83
|
## Play
|
|
72
84
|
|
|
@@ -115,7 +127,7 @@ The page sends input only between Start and End. The input of the page goes into
|
|
|
115
127
|
|
|
116
128
|
A site is the address of the instruction that reads. The values are hex. `<from>` and `<count>` are decimal.
|
|
117
129
|
|
|
118
|
-
`replay` examines `recording.json` before the replay starts. A recording of version
|
|
130
|
+
`replay` examines `recording.json` before the replay starts. A recording of an older version can have events or a comparison in an old form. For example, `"at"` is in place of `"address"`, or a `runUntil` step to an address has no count of the CPU at its target. The script refuses such a recording with `invalid-input`, and the message names the event. Record the session again.
|
|
119
131
|
|
|
120
132
|
## Replay
|
|
121
133
|
|
|
@@ -46,8 +46,9 @@ Before the first step of each side, the script does a hard reset. The CPU stops
|
|
|
46
46
|
| `{ "write": { "address": "seed", "data": "0102" } }` | Write 1 to 4096 bytes into memory. Optional: `space` (`c64` or `drive8`, default `c64`) and `view` (`cpu` or `ram`, default `cpu`). |
|
|
47
47
|
| `{ "registers": { "pc": "start", "a": 0, "flags": { "i": true } } }` | Set registers: `pc`, `a`, `x`, `y`, `sp` and `flags` (`n`, `v`, `b`, `d`, `i`, `z`, `c`). Only `pc` can be a name. |
|
|
48
48
|
| `{ "joystick": { "port": 2, "direction": "left", "fire": true } }` | Set a joystick. `fire` is `false` by default. The joystick stays in this state until the next joystick step. |
|
|
49
|
-
| `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 1024 keys into the keyboard queue of the KERNAL. A program that reads the keyboard hardware does not see them. |
|
|
49
|
+
| `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 1024 keys into the keyboard queue of the KERNAL. A program that reads the keyboard hardware does not see them. Use `press` for that program. |
|
|
50
50
|
| `{ "type": { "mode": "petscii", "bytes": [147] } }` | Put PETSCII codes from 1 to 255 into the keyboard queue of the KERNAL. Use it for keys that mode `text` does not have. |
|
|
51
|
+
| `{ "press": { "keys": "{F1}" } }` | Press keys of the keyboard matrix and RESTORE. A program that reads the keyboard hardware sees them. Each tap holds its keys for 3 frames, then releases them for 3 frames. Optional: `frames` from 1 to 3000. The keys are the same as the keys of a `press` step of a record file. |
|
|
51
52
|
| `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 600 } }` | Run until the CPU gets to an address. |
|
|
52
53
|
| `{ "runUntil": { "target": { "kind": "memory", "address": "game_state", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a write to the byte makes the comparison with `value` true. `operator` is `eq`, `ne`, `lt`, `lte`, `gt` or `gte`. The run does not stop for a byte that is already true at the start. It also does not stop for a register that the hardware changes, for example `$d012`. For a raster line, use a `raster` target. |
|
|
53
54
|
| `{ "runUntil": { "target": { "kind": "raster", "line": 250 }, "timeoutFrames": 5 } }` | Run until the raster beam gets to a line (0 to 311 for PAL, 0 to 262 for NTSC). Optional: `cycle` from 0 to 64. |
|
|
@@ -56,14 +57,14 @@ Before the first step of each side, the script does a hard reset. The CPU stops
|
|
|
56
57
|
| `{ "normalize": true }` | Write pages 0 to 3 and `$00`/`$01` from the entry state in the project knowledge. The entry state comes from a capture of the unpacked program. Then both sides have the same zero page, stack and KERNAL work area. |
|
|
57
58
|
| `{ "observe": "moved", ... }` | Record a checkpoint. |
|
|
58
59
|
|
|
60
|
+
The `timeoutFrames` of a `runUntil` step is from 1 to 30000. The default is 3000. For a longer wait, put `frames` steps before the `runUntil` step.
|
|
61
|
+
|
|
59
62
|
The `port` of a joystick is 1 or 2. The `direction` is `center`, `up`, `down`, `left`, `right`, `up-left`, `up-right`, `down-left` or `down-right`.
|
|
60
63
|
|
|
61
64
|
A `condition` has the `kind` `register`, `memory` or `raster`. A `register` condition has `register` (`a`, `x`, `y` or `sp`), `operator` and `value`. A `memory` condition has `address`, `operator` and `value`. A `raster` condition has `line` and an optional `cycle`.
|
|
62
65
|
|
|
63
66
|
`timeoutFrames` is from 1 to 30000, and 3000 by default. A `runUntil` that does not get to its target in `timeoutFrames` frames makes the result INCONCLUSIVE.
|
|
64
67
|
|
|
65
|
-
A scenario has no `press` step. Only a record file has `press` for keys of the keyboard matrix.
|
|
66
|
-
|
|
67
68
|
Each step except `observe` can have `"side": "original"` or `"side": "rebuild"`. Then only that side does the step. Use it when only one side needs a step, for example a key for the intro of the original. An `observe` step has no `side`, because it compares both sides.
|
|
68
69
|
|
|
69
70
|
Each side finds a name in its own symbols.
|
|
@@ -96,7 +97,7 @@ A run file is one JSON object in a project file. It has:
|
|
|
96
97
|
- `start`: required. `{ "program": "game.prg" }` to autostart a program with a BASIC start line, `{ "program": "game.prg", "load": true }` to load it with the CPU stopped (set `pc` in a step), or `{ "snapshot": ".c64-re-tools/local/snapshots/room0.vsf" }`.
|
|
97
98
|
- `symbols`: optional, `knowledge`, `none` (default), or a JSON file as for a subject. Without `symbols`, a run has no names: give `"symbols": "knowledge"` to use the names of the knowledge.
|
|
98
99
|
- `videoStandard`: optional, `pal` (default) or `ntsc`.
|
|
99
|
-
- `steps`: required. At least one step. The steps `write`, `registers`, `joystick`, `type`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
|
|
100
|
+
- `steps`: required. At least one step. The steps `write`, `registers`, `joystick`, `type`, `press`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
|
|
100
101
|
|
|
101
102
|
The run steps have these effects:
|
|
102
103
|
|
|
@@ -113,7 +114,7 @@ The run steps have these effects:
|
|
|
113
114
|
|
|
114
115
|
A `trace` step has a name, `points` (1 to 8), `frames` (1 to 3000) and an optional `maxHits` (at most 20000). A point has `kind` (`exec`, `read` or `write`), `start` and an optional `end`. The step writes `<name>.json` with each hit. `results.json` gives the file, the count of hits, the frames and why the trace ended. A trace that a breakpoint, a watchpoint or a JAM ends also ends the run.
|
|
115
116
|
|
|
116
|
-
In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites`. `registers` and `vicii` are `true` or `false`, not a list. `"registers": true` gives all registers. A scenario takes a list of register names, a run does not. `sprites` is a list of sprite numbers from 0 to 7.
|
|
117
|
+
In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites`. `registers` and `vicii` are `true` or `false`, not a list. `"registers": true` gives all registers. A scenario takes a list of register names, a run does not. `sprites` is a list of sprite numbers from 0 to 7. In a run, the screen is not a key of `observe`. Write it with a `screen` step, for example `{ "screen": "room3" }`.
|
|
117
118
|
|
|
118
119
|
In a run, a memory item has `address`, `size` (1 to 65536) and `view`. An item larger than 4096 bytes goes into the file `<observe>-<address>.bin`, without the `$`. `results.json` gives the file name.
|
|
119
120
|
|
|
@@ -10,8 +10,9 @@ import { isObject } from "#src/host-client/steps.ts";
|
|
|
10
10
|
import { WireFailure } from "#src/host-client/tools.ts";
|
|
11
11
|
import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
|
|
12
12
|
import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
|
|
13
|
-
import { checkSnapshotFile
|
|
13
|
+
import { checkSnapshotFile } from "#src/media.ts";
|
|
14
14
|
import { listed, UsageError } from "#src/script.ts";
|
|
15
|
+
import { snapshotModule } from "#src/vsf.ts";
|
|
15
16
|
import { diffStates, type ChangedRange, type MachineState } from "./diff.ts";
|
|
16
17
|
|
|
17
18
|
type Kind = "snapshot" | "memory" | "observation";
|
|
@@ -58,29 +59,14 @@ function cpuValues(registers: Record<string, unknown>): Record<string, number |
|
|
|
58
59
|
return values;
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
/** The size of the header of a module in a VICE snapshot file: the name (16 bytes), the version (2 bytes) and the size (4 bytes). */
|
|
62
|
-
const MODULE_HEADER = 22;
|
|
63
|
-
const VSF_VERSION = "VICE Version\x1a";
|
|
64
|
-
|
|
65
62
|
/**
|
|
66
63
|
* The data of the C64MEM module of a VICE snapshot file: the data and the
|
|
67
64
|
* direction register of the CPU port, the cartridge lines (2 bytes), then
|
|
68
65
|
* the 64 KiB of RAM. Undefined when the file has no such module.
|
|
69
66
|
*/
|
|
70
67
|
function c64Memory(file: Uint8Array): Buffer | undefined {
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
// The magic, the version (2 bytes) and the machine name (16 bytes); a newer VICE adds its own version (8 bytes).
|
|
74
|
-
let at = VSF_SIGNATURE.length + 2 + 16;
|
|
75
|
-
if (bytes.subarray(at, at + VSF_VERSION.length).toString("latin1") === VSF_VERSION) at += VSF_VERSION.length + 8;
|
|
76
|
-
while (at + MODULE_HEADER <= bytes.length) {
|
|
77
|
-
const name = bytes.subarray(at, at + 16).toString("latin1").replace(/\0+$/, "");
|
|
78
|
-
const size = bytes.readUInt32LE(at + 18);
|
|
79
|
-
if (size < MODULE_HEADER) return undefined;
|
|
80
|
-
if (name === "C64MEM") return at + MODULE_HEADER + 4 + 0x10000 <= bytes.length ? bytes.subarray(at + MODULE_HEADER, at + MODULE_HEADER + 4 + 0x10000) : undefined;
|
|
81
|
-
at += size;
|
|
82
|
-
}
|
|
83
|
-
return undefined;
|
|
68
|
+
const data = snapshotModule(Buffer.from(file), "C64MEM")?.data;
|
|
69
|
+
return data !== undefined && data.length >= 4 + 0x10000 ? data.subarray(0, 4 + 0x10000) : undefined;
|
|
84
70
|
}
|
|
85
71
|
|
|
86
72
|
/** The 64 KiB of C64 RAM that a VICE snapshot file holds, also the RAM under the CPU port at $00/$01. Undefined when the file has no C64MEM module. */
|
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
|
|
9
9
|
import { createServer, type ServerResponse } from "node:http";
|
|
10
10
|
|
|
11
|
+
import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
|
|
11
12
|
import { PAL_FRAME_CYCLES, type C64RunSession } from "#src/native/c64run.ts";
|
|
12
|
-
import { C64_KEYS, F_KEYS } from "./keys.ts";
|
|
13
13
|
|
|
14
14
|
const FRAME_MS = 20;
|
|
15
15
|
|
|
@@ -27,45 +27,46 @@ export interface PlayOptions {
|
|
|
27
27
|
restore: () => Promise<string | undefined>;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
const C64 = C64_KEYS;
|
|
31
30
|
const LETTERS = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
|
|
32
31
|
const DIGITS = [..."0123456789"];
|
|
33
|
-
const
|
|
32
|
+
const F_KEYS = [1, 2, 3, 4, 5, 6, 7, 8].map((number) => `{F${number}}`);
|
|
33
|
+
/** The matrix places of one key, as a press step names it: a character, or a name in braces. */
|
|
34
|
+
const places = (key: string) => (keyTaps(key) as KeyTap[])[0]!.keys;
|
|
34
35
|
|
|
35
36
|
/**
|
|
36
|
-
* The key maps of the page. Each one maps a KeyboardEvent property to
|
|
37
|
-
* The symbolic map (event.key) gives the character on the PC key;
|
|
38
|
-
* map (event.code) gives the C64 key at the place of the PC key, with each SHIFT alone.
|
|
37
|
+
* The key maps of the page. Each one maps a KeyboardEvent property to the matrix places
|
|
38
|
+
* that go down together. The symbolic map (event.key) gives the character on the PC key;
|
|
39
|
+
* the positional map (event.code) gives the C64 key at the place of the PC key, with each SHIFT alone.
|
|
39
40
|
*/
|
|
40
41
|
export const KEY_MAPS = {
|
|
41
42
|
/** event.code, in both maps. */
|
|
42
|
-
both: { Tab:
|
|
43
|
+
both: { Tab: places("{CTRL}"), AltLeft: places("{CBM}") },
|
|
43
44
|
/** event.code, when the arrow keys and space are keyboard keys. */
|
|
44
|
-
arrows: { ArrowUp:
|
|
45
|
+
arrows: { ArrowUp: places("{UP}"), ArrowDown: places("{DOWN}"), ArrowLeft: places("{LEFT}"), ArrowRight: places("{RIGHT}"), Space: places(" ") },
|
|
45
46
|
/** event.code */
|
|
46
47
|
positional: {
|
|
47
|
-
...Object.fromEntries(LETTERS.map((letter) => ["Key" + letter,
|
|
48
|
-
...Object.fromEntries(DIGITS.map((digit) => ["Digit" + digit,
|
|
49
|
-
...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), key])),
|
|
50
|
-
Backquote:
|
|
51
|
-
BracketLeft:
|
|
52
|
-
Escape:
|
|
53
|
-
ShiftLeft:
|
|
54
|
-
} as Record<string, number>,
|
|
48
|
+
...Object.fromEntries(LETTERS.map((letter) => ["Key" + letter, places(letter)])),
|
|
49
|
+
...Object.fromEntries(DIGITS.map((digit) => ["Digit" + digit, places(digit)])),
|
|
50
|
+
...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), places(key)])),
|
|
51
|
+
Backquote: places("{LEFTARROW}"), Minus: places("+"), Equal: places("-"), Insert: places("{POUND}"), Home: places("{HOME}"), Backspace: places("{DEL}"),
|
|
52
|
+
BracketLeft: places("@"), BracketRight: places("*"), Delete: places("{UPARROW}"),
|
|
53
|
+
Escape: places("{STOP}"), Semicolon: places(":"), Quote: places(";"), Backslash: places("="), Enter: places("{RETURN}"),
|
|
54
|
+
ShiftLeft: places("{LSHIFT}"), ShiftRight: places("{RSHIFT}"), Comma: places(","), Period: places("."), Slash: places("/"),
|
|
55
|
+
} as Record<string, number[]>,
|
|
55
56
|
/** event.key; a-z are the C64 letters, A-Z the letters with SHIFT. */
|
|
56
57
|
symbolic: {
|
|
57
|
-
...Object.fromEntries(LETTERS.flatMap((letter) => [[letter.toLowerCase(),
|
|
58
|
-
...Object.fromEntries([...DIGITS, ..."+-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character,
|
|
59
|
-
...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), key])),
|
|
60
|
-
"£":
|
|
61
|
-
Enter:
|
|
62
|
-
} as Record<string, number>,
|
|
58
|
+
...Object.fromEntries(LETTERS.flatMap((letter) => [[letter.toLowerCase(), places(letter)], [letter, places(`{LSHIFT+${letter}}`)]])),
|
|
59
|
+
...Object.fromEntries([...DIGITS, ..."+-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, places(character)])),
|
|
60
|
+
...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), places(key)])),
|
|
61
|
+
"£": places("{POUND}"), "^": places("{UPARROW}"), "`": places("{LEFTARROW}"),
|
|
62
|
+
Enter: places("{RETURN}"), Backspace: places("{DEL}"), Delete: places("{DEL}"), Insert: places("{INST}"), Home: places("{HOME}"), Escape: places("{STOP}"),
|
|
63
|
+
} as Record<string, number[]>,
|
|
63
64
|
/** event.key with SHIFT held, in the symbolic map. */
|
|
64
|
-
symbolicShift: { Home:
|
|
65
|
+
symbolicShift: { Home: places("{CLR}"), Backspace: places("{INST}"), Escape: places("{RUN}"), F1: places("{F2}"), F3: places("{F4}"), F5: places("{F6}"), F7: places("{F8}") } as Record<string, number[]>,
|
|
65
66
|
};
|
|
66
67
|
|
|
67
|
-
/** The
|
|
68
|
-
const PAGE_KEYS = new Set(Object.values(KEY_MAPS).flatMap((map) => Object.values(map)));
|
|
68
|
+
/** The matrix places that the page can send: every place of the key maps. */
|
|
69
|
+
const PAGE_KEYS = new Set(Object.values(KEY_MAPS).flatMap((map) => Object.values(map).flat()));
|
|
69
70
|
|
|
70
71
|
const PAGE = String.raw`<!doctype html>
|
|
71
72
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
@@ -96,7 +97,7 @@ const BITS = { ArrowUp: 1, ArrowDown: 2, ArrowLeft: 4, ArrowRight: 8, Space: 16
|
|
|
96
97
|
const $ = (id) => document.getElementById(id);
|
|
97
98
|
const canvas = $("screen"), context = canvas.getContext("2d"), state = $("state");
|
|
98
99
|
let palette = [], image = context.createImageData(392, 272), frames = 0, phase = "connecting", port = 2, arrows = "joystick", keyMap = "symbolic", sent = -1;
|
|
99
|
-
// The
|
|
100
|
+
// The matrix places of each PC key that is down (by event.code), and the joystick keys that are down.
|
|
100
101
|
const pressed = new Map(), stick = new Set();
|
|
101
102
|
// One request at a time, so that the core gets each key down before its key up.
|
|
102
103
|
let queue = Promise.resolve();
|
|
@@ -116,7 +117,7 @@ function show() {
|
|
|
116
117
|
else state.textContent = phase;
|
|
117
118
|
}
|
|
118
119
|
function releaseAll() {
|
|
119
|
-
for (const
|
|
120
|
+
for (const keys of pressed.values()) send("key?keys=" + keys.join(",") + "&down=0");
|
|
120
121
|
pressed.clear();
|
|
121
122
|
stick.clear();
|
|
122
123
|
}
|
|
@@ -176,19 +177,19 @@ function key(event, down) {
|
|
|
176
177
|
}
|
|
177
178
|
if (arrows === "joystick" && event.code in BITS) { event.preventDefault(); down ? stick.add(event.code) : stick.delete(event.code); return; }
|
|
178
179
|
if (!down) {
|
|
179
|
-
const
|
|
180
|
-
if (
|
|
180
|
+
const keys = pressed.get(event.code);
|
|
181
|
+
if (keys === undefined) return;
|
|
181
182
|
event.preventDefault();
|
|
182
183
|
pressed.delete(event.code);
|
|
183
|
-
send("key?
|
|
184
|
+
send("key?keys=" + keys.join(",") + "&down=0");
|
|
184
185
|
return;
|
|
185
186
|
}
|
|
186
|
-
const
|
|
187
|
-
if (
|
|
187
|
+
const keys = c64Key(event);
|
|
188
|
+
if (keys === undefined) return;
|
|
188
189
|
event.preventDefault();
|
|
189
190
|
if (event.repeat || phase !== "playing" || pressed.has(event.code)) return;
|
|
190
|
-
pressed.set(event.code,
|
|
191
|
-
send("key?
|
|
191
|
+
pressed.set(event.code, keys);
|
|
192
|
+
send("key?keys=" + keys.join(",") + "&down=1");
|
|
192
193
|
}
|
|
193
194
|
addEventListener("keydown", (event) => key(event, true));
|
|
194
195
|
addEventListener("keyup", (event) => key(event, false));
|
|
@@ -258,9 +259,10 @@ export async function play(core: Pick<C64RunSession, "command" | "status">, opti
|
|
|
258
259
|
if (phase === "playing") mask = Number(url.searchParams.get("mask")) & 0x1f;
|
|
259
260
|
answer(phase === "playing");
|
|
260
261
|
} else if (request.method === "POST" && url.pathname === "/key") {
|
|
261
|
-
const
|
|
262
|
-
if (!PAGE_KEYS.has(key)) return void response.writeHead(400).end();
|
|
263
|
-
|
|
262
|
+
const keys = (url.searchParams.get("keys") ?? "").split(",").map((key) => (/^\d{1,2}$/.test(key) ? Number(key) : -1));
|
|
263
|
+
if (!keys.every((key) => PAGE_KEYS.has(key))) return void response.writeHead(400).end();
|
|
264
|
+
const state = url.searchParams.get("down") === "1" ? "down" : "up";
|
|
265
|
+
if (phase === "playing") for (const key of keys) pending.push("key " + (0x80 + key).toString(16) + " " + state);
|
|
264
266
|
answer(phase === "playing");
|
|
265
267
|
} else if (request.method === "POST" && url.pathname === "/restore") {
|
|
266
268
|
if (phase === "playing") pending.push(RESTORE);
|