@henols/c64-re-tools 2.8.0-rc.4 → 2.8.0-rc.6

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.
Files changed (67) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +78 -24
  4. package/skills/c64-docs/scripts/docs.ts +31 -10
  5. package/skills/c64-knowledge/SKILL.md +11 -7
  6. package/skills/c64-knowledge/references/batches.md +2 -1
  7. package/skills/c64-knowledge/references/source-knowledge.md +1 -1
  8. package/skills/c64-knowledge/scripts/knowledge.ts +46 -29
  9. package/skills/c64-packer/scripts/packer.ts +9 -2
  10. package/skills/c64-provenance/SKILL.md +2 -2
  11. package/skills/c64-provenance/scripts/lib/runtime.ts +45 -10
  12. package/skills/c64-provenance/scripts/provenance.ts +10 -3
  13. package/skills/c64-source/references/loader.md +8 -7
  14. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  15. package/skills/c64-source/scripts/lib/source.ts +3 -1
  16. package/skills/c64-source/scripts/source.ts +49 -78
  17. package/skills/c64-static-analysis/SKILL.md +2 -2
  18. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  19. package/skills/c64-static-analysis/scripts/lib/idioms.ts +92 -42
  20. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  21. package/skills/c64-testing/SKILL.md +7 -0
  22. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  23. package/skills/c64-testing/scripts/lib/recording.ts +278 -27
  24. package/skills/c64-testing/scripts/lib/replay.ts +9 -8
  25. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  26. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  27. package/skills/c64-testing/scripts/testing.ts +30 -11
  28. package/skills/c64-unpacker/SKILL.md +13 -11
  29. package/skills/c64-unpacker/scripts/lib/loads.ts +10 -5
  30. package/skills/c64-unpacker/scripts/lib/machine.ts +163 -3
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +13 -6
  32. package/skills/c64-unpacker/scripts/unpacker.ts +34 -15
  33. package/skills/emulator/SKILL.md +2 -2
  34. package/src/c64.ts +21 -0
  35. package/src/host/vice/adapter.ts +2 -1
  36. package/src/host/vice/chips.ts +6 -9
  37. package/src/host/vice/session.ts +2 -2
  38. package/src/host-client/image.ts +40 -4
  39. package/src/host-client/tools.ts +1 -1
  40. package/src/host-client/transfer.ts +48 -26
  41. package/src/host-client/vice-session.ts +15 -0
  42. package/src/knowledge/database.ts +72 -19
  43. package/src/knowledge/import.ts +32 -7
  44. package/src/knowledge/join.ts +50 -2
  45. package/src/knowledge/names.ts +2 -2
  46. package/src/knowledge/program.ts +103 -24
  47. package/src/knowledge/schema.ts +6 -0
  48. package/src/knowledge/start-screen.ts +57 -7
  49. package/src/knowledge/write.ts +20 -13
  50. package/src/loader.ts +101 -33
  51. package/src/mcp/output.ts +13 -12
  52. package/src/mcp/server.ts +33 -22
  53. package/src/mcp/tools/debug.ts +21 -24
  54. package/src/mcp/tools/media.ts +27 -27
  55. package/src/mcp/tools/memory.ts +13 -17
  56. package/src/mcp/tools/video.ts +10 -12
  57. package/src/native/c64run.ts +39 -1
  58. package/src/native/decompiler/analyze.ts +1 -1
  59. package/src/native/dxa.ts +2 -2
  60. package/src/native/types.ts +26 -7
  61. package/src/opcodes.ts +5 -0
  62. package/src/program-code.ts +4 -2
  63. package/src/project.ts +224 -71
  64. package/src/protocol/vice.ts +5 -3
  65. package/src/script.ts +60 -15
  66. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  67. package/tools/c64run.c +18 -5
@@ -27,7 +27,7 @@ import { conflicts } from "#src/knowledge/conflicts.ts";
27
27
  import { withRead, withWrite } from "#src/knowledge/database.ts";
28
28
  import { identifiers } from "#src/knowledge/expression.ts";
29
29
  import { clipped, codeKnowledge, effectiveRegions } from "#src/knowledge/code-reach.ts";
30
- import { memoryRows, releaseImage, type ProgramImage } from "#src/knowledge/program.ts";
30
+ import { memoryRows, releaseImage, type ProgramImage, startScreenKey } from "#src/knowledge/program.ts";
31
31
  import { ANALYZER_NAME_ORDER, baseValue, currentRevision, sourceRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listReleases, listSpaces, listSwitches, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
32
32
  import { DEFAULT_SPACE, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
33
33
  import { write } from "#src/knowledge/write.ts";
@@ -35,7 +35,7 @@ import { assemble, symbolsFileText } from "#src/native/acme.ts";
35
35
  import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
36
36
  import { decodeProgram, leftoverInput, reachInput } from "#src/program-code.ts";
37
37
  import { localToolContext } from "#src/native/local.ts";
38
- import type { AssembledSymbol, Diagnostic } from "#src/native/types.ts";
38
+ import { type AssembledSymbol, type Diagnostic, requiredLabel, symbolValues } from "#src/native/types.ts";
39
39
  import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
40
40
  import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
41
41
  import { generatedReferences } from "#src/reference-pages.ts";
@@ -43,26 +43,22 @@ import { isoCet } from "#src/time.ts";
43
43
  import { zipFiles } from "#src/zip.ts";
44
44
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
45
45
  import { knowledgeNames } from "#src/knowledge/names.ts";
46
- import { COPIER_SOURCE, leftoverRange, loaderSymbols, packLoader, packParts, type PackedLoader } from "#src/loader.ts";
46
+ import { COPIER_SOURCE, leftoverRange, loaderSymbols, packLoader, type PackedLoader, settingsLines } from "#src/loader.ts";
47
47
  import {
48
48
  loaderLimits,
49
49
  planLoader,
50
- startScreenPlan,
51
50
  rasterLine,
52
51
  loaderState,
53
- settingsLines,
54
52
  simulate,
55
53
  START_SCREEN_CODE,
56
- START_SCREEN_FILE,
57
54
  stopCause,
58
55
  VIC_DISPLAY_REGISTERS,
59
56
  type EntryState,
60
57
  type LoaderPlan,
61
- type StartScreenPlan,
62
58
  } from "./lib/loader.ts";
63
59
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
64
- import { capturedColourRam, LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
65
- import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
60
+ import { capturedColourRam, LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_FILE, START_SCREEN_WAIT, startScreenLabels, type StartScreenPlan } from "#src/knowledge/start-screen.ts";
61
+ import { packStage, type PackedStage, STAGE_FILE, type StageBytes, type StagePart } from "#src/stage.ts";
66
62
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
67
63
  import type { UnresolvedFlow } from "#src/knowledge/separate.ts";
68
64
  import { configText, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
@@ -244,7 +240,7 @@ async function probeUses(laid: Layout, rendered: Rendered, image: ProgramImage):
244
240
  for (const [start, reason] of refused) blamed.set(start, reason);
245
241
  continue;
246
242
  }
247
- const ends = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
243
+ const ends = symbolValues(built.symbols ?? []);
248
244
  let offset = 2 + PROBE_BASE - built.start!;
249
245
  uses.forEach((use, index) => {
250
246
  const length = ends.get(`probe_end_${index}`)! - use.start;
@@ -620,6 +616,9 @@ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FI
620
616
  /** The source files of the show stage. A run writes them only with a loader program whose check ran, so only such a run removes them. */
621
617
  const STAGE_FILES: ReadonlySet<string> = new Set([START_SCREEN_FILE, STAGE_FILE]);
622
618
 
619
+ /** The loader program of the defaults of config.asm: the default build of a source with a loader. */
620
+ const DEFAULT_LOADER = `${BUILD_DIRECTORY}/${buildName("loader.asm", { values: new Map(), defaults: new Map() })}.prg`;
621
+
623
622
  /** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
624
623
  const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
625
624
 
@@ -902,16 +901,13 @@ async function buildLoader(
902
901
  if (loaderBuilt.start !== (loader.packed?.start ?? 0x0801) || loaderBuilt.start + program.length - 3 !== loader.end || wrongPacking !== undefined) {
903
902
  throw new WireFailure("operation-failed", `The assembled loader does not have the planned layout${wrongPacking === undefined ? "" : ` (${wrongPacking.what})`}. This is a defect of the script.`);
904
903
  }
905
- const symbolValue = (name: string) => {
906
- const symbol = loaderBuilt.symbols?.find((item) => item.name === name);
907
- if (symbol === undefined) throw new WireFailure("operation-failed", `The assembled loader has no ${name} label. This is a defect of the script.`);
908
- return symbol.kind === "address" ? symbol.address : symbol.value;
909
- };
910
- const jump = symbolValue(LOADER_JUMP);
904
+ const labels = symbolValues(loaderBuilt.symbols ?? []);
905
+ const labelValue = (name: string) => requiredLabel(labels, name, "The assembled loader");
906
+ const jump = labelValue(LOADER_JUMP);
911
907
  const wrong = simulate(memory, loader.copies, expected);
912
908
  if (wrong !== undefined) throw new WireFailure("operation-failed", `The simulated loader writes a wrong byte at ${formatC64Address(wrong)}. This is a defect of the script.`);
913
- const startScreen = loader.startScreen === undefined ? undefined : { wait: symbolValue(START_SCREEN_WAIT), continue: symbolValue(START_SCREEN_CONTINUE) };
914
- return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: symbolValue(COPIER_SOURCE), expected, ...(startScreen === undefined ? {} : { startScreen }) };
909
+ const startScreen = loader.startScreen === undefined ? undefined : { wait: labelValue(START_SCREEN_WAIT), continue: labelValue(START_SCREEN_CONTINUE) };
910
+ return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: labelValue(COPIER_SOURCE), expected, ...(startScreen === undefined ? {} : { startScreen }) };
915
911
  }
916
912
 
917
913
  /**
@@ -921,7 +917,7 @@ async function buildLoader(
921
917
  * of the stage whose switch default is not its base value is in, as in the
922
918
  * default build. Pages 0-3 are left out: the unpacker of Exomizer uses them.
923
919
  */
924
- async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; colourRam?: Uint8Array }> {
920
+ async function stageBytes(row: StartScreenRow): Promise<StageBytes> {
925
921
  const stage = row.stage!;
926
922
  const knowledge = readKnowledge(stage);
927
923
  const colourRam = row.colourRam === true ? capturedColourRam(knowledge.program.state) : undefined;
@@ -955,42 +951,16 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
955
951
  }
956
952
 
957
953
  /** What the show stage gives: the loader program, the source of the stage, and what its check needs. */
958
- interface BuiltStage {
959
- program: Buffer;
960
- text: string;
961
- /** The labels of the build of start_screen_stage.asm. */
962
- symbols: AssembledSymbol[];
963
- plan: StagePlan;
964
- parts: StagePart[];
965
- colourRam?: Uint8Array;
966
- packed: PackedLoader;
967
- wait: number;
968
- continue: number;
969
- screen: StartScreenPlan;
970
- }
954
+ type BuiltStage = PackedStage & StageBytes;
971
955
 
972
956
  /**
973
- * Builds the show stage of a start screen from a captured stage: plans it,
974
- * assembles start_screen_stage.asm and packs it with the loader as the loader
975
- * is in memory before it starts. Refuses by name.
957
+ * Builds the show stage of a start screen from a captured stage around the
958
+ * packed program, with the bytes of the stage from the knowledge. A text of
959
+ * start_screen_stage.asm that does not assemble goes to the local folder.
960
+ * Refuses by name.
976
961
  */
977
962
  async function buildStage(files: Array<{ name: string; text: string }>, laid: Layout, program: PackedLoader, row: StartScreenRow, values: ReadonlyMap<string, number>, header: string[], mark: string): Promise<BuiltStage> {
978
- const { parts: stage, colourRam } = await stageBytes(row);
979
- // The packed program, as RUN would start it: its unpacker unpacks it over the start screen after the wait.
980
- const inner: StagePart[] = [{ start: 0x0801, body: program.program.subarray(2) }];
981
- const screen = startScreenPlan(row);
982
- const input: StageInput = {
983
- inner,
984
- innerStart: 0x080d,
985
- innerPort: 0x37,
986
- stage,
987
- ...(colourRam === undefined ? {} : { colourRam }),
988
- row,
989
- plan: screen,
990
- settings: settingsLines({ switches: hasSwitchFile(laid), config: hasConfigFile(laid) }),
991
- header,
992
- codeSize: 0,
993
- };
963
+ const stage = await stageBytes(row);
994
964
  const support = [...withValues(files, laid, values).filter((file) => file.name === CONFIG_FILE || file.name === "switches.asm"), { name: START_SCREEN_FILE, text: START_SCREEN_CODE }];
995
965
  const assembleStage = async (text: string) => {
996
966
  const built = await assembleFiles([...support, { name: STAGE_FILE, text }], STAGE_FILE);
@@ -1002,25 +972,13 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
1002
972
  writeFileSync(resolveProjectPath(kept), `${mark}\n${text}`);
1003
973
  throw new WireFailure("operation-failed", `${STAGE_FILE} does not assemble: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ")}. The source that failed is ${kept}. This is a defect of the script.`);
1004
974
  }
1005
- const labels = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1006
- const label = (name: string) => {
1007
- const value = labels.get(name);
1008
- if (value === undefined) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} has no ${name} label. This is a defect of the script.`);
1009
- return value;
1010
- };
1011
- return { program: built.program, symbols: built.symbols ?? [], label };
975
+ return { program: built.program, symbols: built.symbols ?? [] };
1012
976
  };
1013
- // The size of the show code does not depend on its address: one build without a stash and without the parts gives it.
1014
- const probe = await assembleStage(stageText({ ...input, stage: [] }, 0x1000, []));
1015
- input.codeSize = probe.label(STAGE_CODE_END) - probe.label(STAGE_START) - 2;
1016
- const plan = planStage(input);
1017
- const built = await assembleStage(plan.text);
1018
- if (built.label(STAGE_START) !== plan.code || built.label(STAGE_CODE_END) - plan.code !== input.codeSize + 6 * plan.stash.length + 2) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} does not have the planned layout. This is a defect of the script.`);
1019
- const parts = stageParts(input, plan, built.program, built.label);
1020
- const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
1021
- const end = 0x0801 + packed.program.length - 3;
1022
- if (end > 0xcfff) throw new Refusal("invalid-input", `The loader with the start screen of ${row.stage} would end at ${formatC64Address(end)}, after $cfff: loading it would write the I/O area. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
1023
- return { program: packed.program, text: `${mark}\n${plan.text}`, symbols: built.symbols, plan, parts: stage, ...(colourRam === undefined ? {} : { colourRam }), packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
977
+ const settings = settingsLines({ switches: hasSwitchFile(laid), config: hasConfigFile(laid) });
978
+ // The key of the start screen goes into the file: a build with other switch values uses its bytes only for that start screen.
979
+ const key = withRead((db) => startScreenKey(db, row));
980
+ const built = await packStage(program.program, stage, row, { settings, header, key }, assembleStage, localToolContext());
981
+ return { ...built, text: `${mark}\n${built.text}`, ...stage };
1024
982
  }
1025
983
 
1026
984
  /** An operand expression that the source writes as a number, as a result lists it. */
@@ -1240,7 +1198,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1240
1198
  return { output: { ...output, loader: notVerified({ reason: `The show stage of the start screen from ${stageRow.stage} cannot be built. ${error.message}` }) }, removed, failed: true };
1241
1199
  }
1242
1200
  }
1243
- const program = stage?.program ?? packed?.program ?? copierBuild;
1201
+ const program = stage?.packed.program ?? packed?.program ?? copierBuild;
1244
1202
  // The check runs the new loader from a scratch file. Only a loader whose check ran goes to the build folder, so a check
1245
1203
  // that cannot run (no host, or a host of another release) keeps the loader program of an earlier run.
1246
1204
  ensureLocal(projectRoot());
@@ -1250,17 +1208,21 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1250
1208
  writeFileSync(resolveProjectPath(checkPath), program);
1251
1209
  // The unpack runs before the copier, or before the show stage, which then starts the loader.
1252
1210
  const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
1253
- const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : unpackFrames(packed.cycles);
1211
+ // A build with START_SCREEN = 0 or LEFTOVERS = 1 has the labels of the start screen, but goes on at once: the check waits only for a start screen that shows.
1212
+ const shows = (symbols: readonly AssembledSymbol[]) => startScreenLabels(symbolValues(symbols)) !== undefined;
1213
+ const stageShown = stage !== undefined && shows(stage.symbols);
1214
+ // A show stage that goes on at once unpacks the loader right after its own unpack.
1215
+ const copierFrames = (packed === undefined ? RUN_LIMIT_FRAMES : unpackFrames(packed.cycles)) + (stage === undefined || stageShown ? 0 : unpackFrames(stage.packed.cycles));
1254
1216
  // The check compares the bytes of the screen of the stage: a routine of the stage can change its other bytes.
1255
1217
  const stageByte = (address: number) => {
1256
1218
  const part = stage!.parts.find((item) => address >= item.start && address < item.start + item.body.length)!;
1257
1219
  return part.body[address - part.start]!;
1258
1220
  };
1259
1221
  const screenParts = stage === undefined ? [] : startScreenRanges(stageRow!).map(({ range }) => ({ start: range.start, body: Uint8Array.from({ length: range.end - range.start + 1 }, (_, offset) => stageByte(range.start + offset)) }));
1260
- const stageRun = stage === undefined ? {} : { stage: { name: stageRow!.stage!, wait: stage.wait, continue: stage.continue, screen: stage.screen, parts: screenParts, ...(stage.colourRam === undefined ? {} : { colourRam: stage.colourRam }), frames: unpackFrames(stage.packed.cycles) + LOADER_FRAMES } };
1222
+ const stageRun = stage === undefined || !stageShown ? {} : { stage: { name: stageRow!.stage!, wait: stage.wait, continue: stage.continue, screen: stage.screen, parts: screenParts, ...(stage.colourRam === undefined ? {} : { colourRam: stage.colourRam }), frames: unpackFrames(stage.packed.cycles) + LOADER_FRAMES } };
1261
1223
  let ran: LoaderRun;
1262
1224
  try {
1263
- ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
1225
+ ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined || !shows(loaderBuilt.symbols) ? {} : { startScreen }), ...stageRun }, expected);
1264
1226
  } catch (error) {
1265
1227
  if (!isRefusal(error)) throw error;
1266
1228
  const what = loaderPrograms().length > 0 ? "kept the loader program of an earlier run" : "wrote no loader program";
@@ -1505,7 +1467,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1505
1467
  // 7. The tests of the project, changed for the new project.
1506
1468
  const testsFolder = join(project, "tests");
1507
1469
  const testFiles = existsSync(testsFolder) ? readdirSync(testsFolder, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort() : [];
1508
- const symbolMap = new Map(shownSymbols.map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1470
+ const symbolMap = symbolValues(shownSymbols);
1509
1471
  const tests: Array<{ file: string; kind: "scenario" | "run"; text: string }> = [];
1510
1472
  const testsLeftOut: Array<{ file: string; reason: string }> = [];
1511
1473
  for (const file of testFiles) {
@@ -1640,9 +1602,18 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1640
1602
  }
1641
1603
  if ([body.asBytes, body.operandsAsNumbers, body.macrosAsInstructions, body.patchesNotWritten].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
1642
1604
  const staleLoader = body.staleLoader as { noEntryState?: boolean } | undefined;
1643
- // The reference is made from the source: it is the step after this run, also when the run has no finding.
1644
- const reference = body.staleReference === undefined ? "" : " The reference pages in staleReference are from an earlier revision of this source. Generate the reference pages again from this source.";
1645
- if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: `Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again.${reference}` });
1605
+ // The default loader program goes when config.asm has other values, and the replays of the default build need it.
1606
+ const loaderGone = body.config !== undefined && ((body.removed as string[] | undefined) ?? []).includes(DEFAULT_LOADER);
1607
+ // The notes after the steps. The reference is made from the source: it is the step after this run, also when the run has no finding.
1608
+ const notes = [
1609
+ ...(loaderGone
1610
+ ? [`The run removed the default loader program ${DEFAULT_LOADER}, because config.asm does not have the default switch values (config.notDefault). To make it again, set the defaults in config.asm, and generate with --loader. To get the loader program of other switch values without a change to the source, build main.asm with the build option --switch.`]
1611
+ : []),
1612
+ ...(body.staleReference === undefined ? [] : ["The reference pages in staleReference are from an earlier revision of this source. Generate the reference pages again from this source."]),
1613
+ ]
1614
+ .map((note) => ` ${note}`)
1615
+ .join("");
1616
+ if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: `Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again.${notes}` });
1646
1617
  if (again) steps.push("Then generate again.");
1647
1618
  // The run with --loader writes the loader again, so it is the next action also for the other findings.
1648
1619
  const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
@@ -1650,7 +1621,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1650
1621
  steps.push("The loader files in staleLoader.files are of another knowledge revision or toolkit version, and the run kept them.");
1651
1622
  steps.push(loaderAgain ? "To write the loader of this revision, generate with --loader." : "The knowledge has no entry state, so --loader cannot write them again. Remove them when the build does not use them.");
1652
1623
  }
1653
- return reply(body, { hint: `${steps.join(" ")}${reference}`, ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1624
+ return reply(body, { hint: `${steps.join(" ")}${notes}`, ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1654
1625
  }
1655
1626
 
1656
1627
  /** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
@@ -102,7 +102,7 @@ The script records only structure: code and data regions, analyzer names, and th
102
102
 
103
103
  - `analyzer`: `dxa` or `decompiler`. `analyzerVersion` gives the version of the analyzer when the analyzer tells it. `space` is in `body` only for a space that is not `c64`.
104
104
  - `revision`: the revision of the findings, or `null` when the knowledge did not change.
105
- - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `references.inData` counts the references that start in a data region of the user, the LLM or an idiom. The analyzer decoded these data bytes as code. `regions.onExecutedCode` counts the data findings on code that a run executed and that the project knowledge holds as code. The script does not record these findings, and they are not conflicts.
105
+ - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `references.inData` counts the references that start in a data region of the user, the LLM or an idiom. The analyzer decoded these data bytes as code. `regions.onExecutedCode` and `names.onExecutedCode` count the data findings on code that a run executed and that the project knowledge holds as code. The script does not record these findings, and they are not conflicts.
106
106
  - `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement. A conflict of code and data also gives these facts about its range:
107
107
  - `access`: only with coverage. `executed` counts the instructions in the range that a run executed. `read` and `written` count the bytes that a run read and wrote.
108
108
  - `references`: the references of the project knowledge into the range from outside it, each with `from` and `kind`.
@@ -160,7 +160,7 @@ Each item of `seeds.refused` and `coverageGaps` has a `reason`. `at` gives the i
160
160
  | `not-decodable` | No instruction decodes at the address. Correct the entry point or the routine. |
161
161
  | `not-reached` | Only in `coverageGaps`: no flow and no seed reached the start. Give it with `--entry`, or record a routine there. |
162
162
 
163
- A start in a `dual-use` region is a known overlap, for example a BIT skip. It is not a gap.
163
+ A start in a `dual-use` region is a known overlap, for example a BIT skip. It is not a gap. `seeds.refused` does not list a seed that the analysis refused because of a known overlap.
164
164
 
165
165
  #### The candidates
166
166
 
@@ -1,13 +1,13 @@
1
1
  // Runtime evidence for static analysis: the coverage as entry points,
2
- // user/LLM code regions and JMP tables as entry points, and the check that
3
- // shows analyzer data over executed code.
2
+ // user/LLM code regions, JMP tables and jump and call targets as entry
3
+ // points, and the check that shows analyzer data over executed code.
4
4
 
5
5
  import type { DatabaseSync } from "node:sqlite";
6
6
 
7
- import { COVERAGE } from "#src/c64.ts";
7
+ import { type AddressRange, COVERAGE, inRanges } from "#src/c64.ts";
8
8
  import type { RefusedSeed, RefusedSeedReason } from "#src/native/types.ts";
9
9
  import { listReferences, listRegions, type RegionRow } from "#src/knowledge/read.ts";
10
- import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Analyzer, type Space } from "#src/knowledge/schema.ts";
10
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, INSTRUCTION_REGION_TYPES, isAnalyzer, isSemantic, type Analyzer, type Space } from "#src/knowledge/schema.ts";
11
11
 
12
12
  /** The byte at an address of the analyzed image, or undefined outside it. */
13
13
  export type ImageByte = (address: number) => number | undefined;
@@ -34,6 +34,43 @@ export function codeEntries(db: DatabaseSync | undefined, image: ImageByte, spac
34
34
  return entries;
35
35
  }
36
36
 
37
+ /** The classes of an address for referenceTargets, as bits of a 64 KiB map. */
38
+ const CODE = 1;
39
+ const SEMANTIC_DATA = 2;
40
+ const NO_TARGET = 4;
41
+
42
+ /**
43
+ * The targets of the jump and call references from code in the knowledge,
44
+ * inside the image: entry points for DXA. DXA drops code that it
45
+ * reaches on one route only when another route runs into an instruction, for
46
+ * example into the operand of a BIT skip; which code it drops changes with
47
+ * the seeds. A target in a data range would make that range code, and DXA
48
+ * cannot decode both instructions of a dual-use region: such targets are left out.
49
+ * `dualUse` adds the dual-use regions that this run found and that the knowledge
50
+ * does not have yet. The references of the analyzer that runs are left out: fed back, a wrong
51
+ * decode would seed itself, and a re-analysis could not retire it. A
52
+ * reference from a data region of the user or the LLM is left out too: their
53
+ * regions win over the code region of an analyzer.
54
+ */
55
+ export function referenceTargets(db: DatabaseSync | undefined, analyzer: Analyzer, image: ImageByte, ranges: { data: readonly AddressRange[]; dualUse: readonly AddressRange[] }, space: Space = DEFAULT_SPACE): number[] {
56
+ const map = new Uint8Array(0x10000);
57
+ const mark = (range: AddressRange, bit: number) => {
58
+ for (let address = range.start; address <= range.end; address++) map[address]! |= bit;
59
+ };
60
+ for (const region of listRegions(db, undefined, undefined, undefined, space)) {
61
+ if (INSTRUCTION_REGION_TYPES.includes(region.type)) mark(region, CODE);
62
+ else if (isSemantic(region.origin)) mark(region, SEMANTIC_DATA);
63
+ if (region.type === "dual-use") mark(region, NO_TARGET);
64
+ }
65
+ for (const range of [...ranges.data, ...ranges.dualUse]) mark(range, NO_TARGET);
66
+ const targets = new Set<number>();
67
+ for (const reference of listReferences(db, undefined, undefined, undefined, space)) {
68
+ if (reference.kind !== "jump" && reference.kind !== "call") continue;
69
+ if (reference.origin !== analyzer && (map[reference.from]! & (CODE | SEMANTIC_DATA)) === CODE) targets.add(reference.to);
70
+ }
71
+ return [...targets].filter((address) => image(address) !== undefined && (map[address]! & NO_TARGET) === 0).sort((a, b) => a - b);
72
+ }
73
+
37
74
  /** Analyzer data regions that hold executed instruction starts: the coverage shows code there. */
38
75
  export function coverageConflicts(db: DatabaseSync | undefined, map: Uint8Array): Array<{ region: RegionRow; executed: number }> {
39
76
  const conflicts: Array<{ region: RegionRow; executed: number }> = [];
@@ -68,6 +105,21 @@ export function writtenNotExecuted(db: DatabaseSync | undefined, analyzer: Analy
68
105
  return found;
69
106
  }
70
107
 
108
+ /**
109
+ * The refused seeds without the known overlaps. An instruction that starts
110
+ * inside another instruction, in a dual-use region, is a known overlap, for
111
+ * example the second instruction of a BIT skip: one list of instructions cannot
112
+ * hold both, so the analysis refuses the seed of one of them. That seed is not
113
+ * a fault of the knowledge.
114
+ */
115
+ export function withoutOverlaps(refused: readonly RefusedSeed[], dualUse: readonly AddressRange[]): RefusedSeed[] {
116
+ const inner = (seed: RefusedSeed) => (seed.reason === "inside-instruction" ? seed.address : seed.reason === "into-instruction" ? seed.at : undefined);
117
+ return refused.filter((seed) => {
118
+ const start = inner(seed);
119
+ return start === undefined || !inRanges(dualUse, start);
120
+ });
121
+ }
122
+
71
123
  /** Why an executed instruction start has no decoded instruction. */
72
124
  export interface GapReason {
73
125
  address: number;
@@ -5,11 +5,21 @@
5
5
  // gives its two start vectors as entry points. A self-modified opcode is one that one run wrote
6
6
  // and executed, in either order, since a coverage file holds no order:
7
7
  // a copier's writes in one run and their execution in another do not count. A table's length is not known statically: entries
8
- // count while each target is a plausible instruction in the program.
8
+ // count while each target is a plausible instruction in the program. An RTS
9
+ // table ends before the low or the high bytes of another RTS dispatch start,
10
+ // but not one entry in: a table of one entry is no dispatch, so there the
11
+ // other dispatch reads the same table with an index one higher. An RTS table
12
+ // also ends before an entry that a run wrote when no run wrote its first
13
+ // entry: there the program holds other bytes than the dispatch reads. A JMP
14
+ // table ends before a JMP that a run wrote and no run executed, when no run
15
+ // executed a JMP of the table that a run wrote: the program wrote other bytes
16
+ // over it. A coverage map holds no order, so the writes of an unpacker or a
17
+ // copier, which write the whole table before its use, tell nothing.
9
18
  // The knowledge of the user and the LLM wins: an idiom gives no region, no
10
19
  // reference and no entry point where their region has another type or a
11
- // removal holds the bytes, and a table ends where their region ends. A $2c in
12
- // an instruction that a run executed is an operand, not a BIT.
20
+ // removal holds the bytes, and a table ends where their region ends. A BIT
21
+ // skip hides whole instructions in its 2 operand bytes: one of 2 bytes or two
22
+ // of 1 byte. A $2c in an instruction that a run executed is an operand, not a BIT.
13
23
 
14
24
  import { COVERAGE, instructionLength, type ReferenceKind } from "#src/c64.ts";
15
25
  import type { NormalizedFindings } from "#src/knowledge/import.ts";
@@ -118,6 +128,10 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
118
128
  }
119
129
  return false;
120
130
  };
131
+ /** True when a run wrote the byte at the address; never without coverage. */
132
+ const written = (address: number) => coverage !== undefined && (coverage[address]! & COVERAGE.ramWrite) !== 0;
133
+ /** True when a run executed an instruction at the address; never without coverage. */
134
+ const executed = (address: number) => coverage !== undefined && (coverage[address]! & COVERAGE.ramExecute) !== 0;
121
135
  const regions: NormalizedFindings["regions"] = [];
122
136
  const references: NormalizedFindings["references"] = [];
123
137
  const entryPoints = new Set<number>();
@@ -145,54 +159,81 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
145
159
  }
146
160
  }
147
161
 
162
+ // RTS dispatches: LDA high,X / PHA / LDA low,X / PHA / RTS. A table is data: it ends where the decided range at its start ends.
163
+ const dispatches: Array<{ rts: number; low: number; high: number }> = [];
148
164
  for (let at = range.start; at + 8 <= range.end; at++) {
149
- // RTS dispatch: LDA high,X / PHA / LDA low,X / PHA / RTS.
150
165
  if (LDA_INDEXED.has(byteAt(at)!) && byteAt(at + 3) === 0x48 && LDA_INDEXED.has(byteAt(at + 4)!) && byteAt(at + 7) === 0x48 && byteAt(at + 8) === 0x60) {
151
166
  const high = word(byteAt, at + 1)!;
152
167
  const low = word(byteAt, at + 5)!;
153
- const interleaved = high === low + 1;
154
- const step = interleaved ? 2 : 1;
155
- // A table is data: it ends where the decided range at its start ends.
156
- if (!fits(low, low, "bytes") || !fits(high, high, "bytes")) continue;
157
- const lowRange = decidedAt(low);
158
- const highRange = decidedAt(high);
159
- const targets: number[] = [];
160
- for (let index = 0; index < MAX_TABLE; index++) {
161
- if (decidedAt(low + index * step) !== lowRange || decidedAt(high + index * step) !== highRange) break;
162
- const lowByte = byteAt(low + index * step);
163
- const highByte = byteAt(high + index * step);
164
- if (lowByte === undefined || highByte === undefined) break;
165
- const target = ((highByte << 8) | lowByte) + 1;
166
- if (!plausible(byteAt, target, range)) break;
167
- targets.push(target);
168
- }
169
- if (targets.length === 0) continue;
170
- const n = targets.length;
171
- const parts: Parameters<typeof addRegions>[1] = interleaved
172
- ? [{ start: low, end: low + 2 * n - 1, type: "rts-addresses" }]
173
- : low + n === high
174
- ? [{ start: low, end: high + n - 1, type: "rts-addresses-split" }]
175
- : [{ start: low, end: low + n - 1, type: "bytes" }, { start: high, end: high + n - 1, type: "bytes" }];
176
- // Another dispatch through the same table: the table is recorded, and this RTS goes to its targets too.
177
- const known = parts.every((part) => regions.some((region) => region.start === part.start && region.end === part.end && region.type === part.type));
178
- if (!known) {
179
- if (!addRegions("rts-table", parts)) continue;
180
- counts.rtsTables++;
181
- }
182
- // A target in data of the user or the LLM, or a reference that they removed, gives no reference and no entry point.
183
- for (const target of targets) {
184
- const reference = { from: at + 8, to: target, kind: "jump" as const };
185
- if (!mayBeCode(target) || decided.removedReference(reference)) continue;
186
- references.push(reference);
187
- entryPoints.add(target);
188
- }
168
+ if (fits(low, low, "bytes") && fits(high, high, "bytes")) dispatches.push({ rts: at + 8, low, high });
169
+ }
170
+ }
171
+ /** The target of the entry with these bytes, or undefined when a byte is outside the program. */
172
+ const targetAt = (lowAt: number, highAt: number) => {
173
+ const lowByte = byteAt(lowAt);
174
+ const highByte = byteAt(highAt);
175
+ return lowByte === undefined || highByte === undefined ? undefined : ((highByte << 8) | lowByte) + 1;
176
+ };
177
+ // Where the low and the high bytes of each table start whose first entry is a plausible target: a table ends before one of them.
178
+ const tableStarts = new Set(dispatches.flatMap(({ low, high }) => {
179
+ const target = targetAt(low, high);
180
+ return target !== undefined && plausible(byteAt, target, range) ? [low, high] : [];
181
+ }));
182
+ // The lowest table first: a dispatch that reads it from a later entry then finds it recorded.
183
+ dispatches.sort((a, b) => a.low - b.low);
184
+ const rtsRegions: Array<{ start: number; end: number }> = [];
185
+ for (const { rts, low, high } of dispatches) {
186
+ const interleaved = high === low + 1;
187
+ const step = interleaved ? 2 : 1;
188
+ const lowRange = decidedAt(low);
189
+ const highRange = decidedAt(high);
190
+ // A run that wrote the first entry wrote the table before its use.
191
+ const writesTell = !written(low) && !written(high);
192
+ const targets: number[] = [];
193
+ for (let index = 0; index < MAX_TABLE; index++) {
194
+ const lowAt = low + index * step;
195
+ const highAt = high + index * step;
196
+ if (decidedAt(lowAt) !== lowRange || decidedAt(highAt) !== highRange) break;
197
+ if (index > 1 && (tableStarts.has(lowAt) || tableStarts.has(highAt))) break;
198
+ if (writesTell && (written(lowAt) || written(highAt))) break;
199
+ const target = targetAt(lowAt, highAt);
200
+ if (target === undefined || !plausible(byteAt, target, range)) break;
201
+ targets.push(target);
202
+ }
203
+ if (targets.length === 0) continue;
204
+ const n = targets.length;
205
+ const parts: Parameters<typeof addRegions>[1] = interleaved
206
+ ? [{ start: low, end: low + 2 * n - 1, type: "rts-addresses" }]
207
+ : low + n === high
208
+ ? [{ start: low, end: high + n - 1, type: "rts-addresses-split" }]
209
+ : [{ start: low, end: low + n - 1, type: "bytes" }, { start: high, end: high + n - 1, type: "bytes" }];
210
+ // Another dispatch through the same table, or from a later entry of it: the table is recorded, and this RTS goes to its targets too.
211
+ const known = parts.every((part) => rtsRegions.some((region) => region.start <= part.start && part.end <= region.end));
212
+ if (!known) {
213
+ if (!addRegions("rts-table", parts)) continue;
214
+ rtsRegions.push(...parts);
215
+ counts.rtsTables++;
216
+ }
217
+ // A target in data of the user or the LLM, or a reference that they removed, gives no reference and no entry point.
218
+ for (const target of targets) {
219
+ const reference = { from: rts, to: target, kind: "jump" as const };
220
+ if (!mayBeCode(target) || decided.removedReference(reference)) continue;
221
+ references.push(reference);
222
+ entryPoints.add(target);
189
223
  }
190
224
  }
191
225
 
192
226
  // JMP tables: at least three JMP abs in a row.
227
+ const writtenJmp = (jmp: number) => written(jmp) && written(jmp + 1) && written(jmp + 2);
193
228
  for (let at = range.start; at + 3 * MIN_JUMPS - 1 <= range.end; at++) {
194
229
  let n = 0;
195
230
  while (at + 3 * n + 2 <= range.end && byteAt(at + 3 * n) === 0x4c) n++;
231
+ // A JMP that a run wrote and then executed: the code that wrote the table put it there.
232
+ const jmps = Array.from({ length: n }, (_, index) => at + 3 * index);
233
+ if (!jmps.some((jmp) => writtenJmp(jmp) && executed(jmp))) {
234
+ const stale = jmps.findIndex((jmp) => writtenJmp(jmp) && !executed(jmp));
235
+ if (stale !== -1) n = stale;
236
+ }
196
237
  if (n < MIN_JUMPS) continue;
197
238
  // The JMPs inside the run are the same table: a run that is left out is left out once.
198
239
  const run = n;
@@ -210,15 +251,24 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
210
251
  at += 3 * run - 1;
211
252
  }
212
253
 
213
- // BIT skips: BIT abs ($2c) whose operand bytes are an instruction that a JMP, a JSR or the coverage enters.
254
+ // BIT skips: BIT abs ($2c) whose operand bytes are whole instructions that a JMP, a JSR or the coverage enters.
214
255
  // A $2c in an executed instruction is its operand; the BIT is code and its operand bytes are dual-use.
256
+ /** True when the 2 operand bytes of the BIT at the address are one instruction of 2 bytes or two of 1 byte, with no JAM. */
257
+ const hidesInstructions = (bit: number) => {
258
+ let next = bit + 1;
259
+ while (next < bit + 3) {
260
+ if (!plausible(byteAt, next, range)) return false;
261
+ next += instructionLength(byteAt(next)!);
262
+ }
263
+ return next === bit + 3;
264
+ };
215
265
  const entered = new Set<number>();
216
266
  for (let at = range.start; at + 2 <= range.end; at++) {
217
267
  if (byteAt(at) === 0x4c || byteAt(at) === 0x20) entered.add(word(byteAt, at + 1)!);
218
268
  }
219
269
  if (coverage !== undefined) for (let address = range.start; address <= range.end; address++) if ((coverage[address]! & COVERAGE.ramExecute) !== 0) entered.add(address);
220
270
  for (let at = range.start; at + 2 <= range.end; at++) {
221
- if (byteAt(at) !== 0x2c || !entered.has(at + 1) || !plausible(byteAt, at + 1, range) || inExecutedOperand(at)) continue;
271
+ if (byteAt(at) !== 0x2c || !entered.has(at + 1) || !hidesInstructions(at) || inExecutedOperand(at)) continue;
222
272
  if (!fits(at, at, "code") || !fits(at + 1, at + 2, "dual-use")) continue;
223
273
  if (!addRegions("bit-skip", [{ start: at + 1, end: at + 2, type: "dual-use" }])) continue;
224
274
  counts.bitSkips++;