@henols/c64-re-tools 2.7.0 → 2.8.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +23 -38
  3. package/skills/c64-assembler/scripts/assembler.ts +114 -16
  4. package/skills/c64-basic/SKILL.md +11 -31
  5. package/skills/c64-basic/scripts/basic.ts +4 -1
  6. package/skills/c64-development/SKILL.md +2 -2
  7. package/skills/c64-disk/SKILL.md +11 -32
  8. package/skills/c64-docs/SKILL.md +27 -45
  9. package/skills/c64-docs/references/page-types.md +20 -18
  10. package/skills/c64-docs/references/style.md +10 -4
  11. package/skills/c64-docs/scripts/docs.ts +13 -2
  12. package/skills/c64-docs/scripts/lib/reference.ts +47 -5
  13. package/skills/c64-knowledge/SKILL.md +138 -267
  14. package/skills/c64-knowledge/references/batches.md +48 -0
  15. package/skills/c64-knowledge/references/coverage.md +29 -0
  16. package/skills/c64-knowledge/references/source-knowledge.md +72 -0
  17. package/skills/c64-knowledge/references/start-screen.md +44 -0
  18. package/skills/c64-knowledge/scripts/knowledge.ts +266 -61
  19. package/skills/c64-knowledge/scripts/lib/check.ts +133 -0
  20. package/skills/c64-knowledge/scripts/lib/listing.ts +72 -8
  21. package/skills/c64-memory-map/SKILL.md +11 -32
  22. package/skills/c64-packer/SKILL.md +11 -31
  23. package/skills/c64-provenance/SKILL.md +40 -62
  24. package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
  25. package/skills/c64-provenance/scripts/provenance.ts +64 -55
  26. package/skills/c64-reverse-engineering/SKILL.md +20 -47
  27. package/skills/c64-reverse-engineering/references/comment-check.md +42 -0
  28. package/skills/c64-reverse-engineering/references/versions.md +47 -0
  29. package/skills/c64-source/SKILL.md +43 -235
  30. package/skills/c64-source/references/export.md +50 -0
  31. package/skills/c64-source/references/loader.md +78 -0
  32. package/skills/c64-source/references/source-format.md +46 -0
  33. package/skills/c64-source/scripts/lib/export.ts +20 -7
  34. package/skills/c64-source/scripts/lib/loader.ts +116 -104
  35. package/skills/c64-source/scripts/source.ts +62 -52
  36. package/skills/c64-static-analysis/SKILL.md +51 -52
  37. package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
  38. package/skills/c64-static-analysis/scripts/lib/idioms.ts +28 -9
  39. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -15
  40. package/skills/c64-testing/SKILL.md +77 -59
  41. package/skills/c64-testing/references/recording-format.md +5 -79
  42. package/skills/c64-testing/references/scenario-format.md +4 -12
  43. package/skills/c64-testing/scripts/lib/play.ts +16 -8
  44. package/skills/c64-testing/scripts/lib/recording.ts +76 -9
  45. package/skills/c64-testing/scripts/lib/replay.ts +14 -0
  46. package/skills/c64-testing/scripts/lib/runs.ts +112 -1
  47. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  48. package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
  49. package/skills/c64-testing/scripts/testing.ts +37 -15
  50. package/skills/c64-unpacker/SKILL.md +10 -30
  51. package/skills/emulator/SKILL.md +7 -36
  52. package/src/build-name.ts +12 -1
  53. package/src/knowledge/history.ts +8 -0
  54. package/src/knowledge/program.ts +73 -1
  55. package/src/knowledge/read.ts +46 -2
  56. package/src/knowledge/recording-files.ts +32 -0
  57. package/src/knowledge/schema.ts +3 -1
  58. package/src/knowledge/separate.ts +90 -3
  59. package/src/knowledge/start-screen.ts +99 -17
  60. package/src/knowledge/text.ts +2 -1
  61. package/src/knowledge/write.ts +15 -8
  62. package/src/loader.ts +167 -0
  63. package/src/native/c64run.ts +11 -0
  64. package/src/native/decompiler/analyze.ts +7 -6
  65. package/src/native/decompiler/walk.ts +32 -2
  66. package/src/native/dxa.ts +4 -4
  67. package/src/native/types.ts +32 -4
  68. package/src/script.ts +87 -17
  69. package/skills/c64-export/SKILL.md +0 -63
@@ -16,7 +16,7 @@ import { basename, dirname, join, relative, sep } from "node:path";
16
16
  import { isRefusal, Refusal } from "#src/errors.ts";
17
17
  import { PACKAGE } from "#src/package.ts";
18
18
  import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
19
- import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
19
+ import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
20
20
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
21
21
  import { IO_RAM } from "#src/host-client/coverage.ts";
22
22
  import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
@@ -40,17 +40,14 @@ import { isoCet } from "#src/time.ts";
40
40
  import { zipFiles } from "#src/zip.ts";
41
41
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
42
42
  import { knowledgeNames } from "#src/knowledge/names.ts";
43
+ import { COPIER_SOURCE, leftoverRange, loaderSymbols, packLoader, packParts, type PackedLoader } from "#src/loader.ts";
43
44
  import {
44
- COPIER_SOURCE,
45
45
  LOADER_JUMP,
46
46
  loaderLimits,
47
- packLoader,
48
- packParts,
49
47
  planLoader,
50
48
  startScreenPlan,
51
49
  rasterLine,
52
50
  loaderState,
53
- loaderSymbols,
54
51
  simulate,
55
52
  START_SCREEN_CODE,
56
53
  START_SCREEN_CONTINUE,
@@ -60,13 +57,13 @@ import {
60
57
  VIC_DISPLAY_REGISTERS,
61
58
  type EntryState,
62
59
  type LoaderPlan,
63
- type PackedLoader,
64
60
  type StartScreenPlan,
65
61
  } from "./lib/loader.ts";
66
62
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
67
63
  import { capturedColourRam } from "#src/knowledge/start-screen.ts";
68
64
  import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
69
65
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
66
+ import type { UnresolvedFlow } from "#src/knowledge/separate.ts";
70
67
  import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
71
68
 
72
69
  /** At most this many diagnostics or differences of one check. */
@@ -651,6 +648,12 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
651
648
  const wanted = rasterLine(state.vic.registers);
652
649
  if (line !== wanted && line !== wanted + 1) differences.push(`the raster line is ${line}, not ${wanted}`);
653
650
  }
651
+ if (plan.colours !== undefined && state.colourRam !== undefined) {
652
+ // The colour RAM: the first wrong colour.
653
+ const colours = Buffer.from((await client.ioRead(0xd800, state.colourRam.length)).data, "hex");
654
+ const wrong = state.colourRam.findIndex((value, offset) => (colours[offset]! & 0x0f) !== value);
655
+ if (wrong >= 0) differences.push(`the colour RAM has ${colours[wrong]! & 0x0f} at ${formatC64Address(0xd800 + wrong)}, not ${state.colourRam[wrong]}`);
656
+ }
654
657
  if (plan.cia !== undefined) {
655
658
  // The CIA timers: at the jump a running timer is 3 cycles, the JMP, before its value at the entry.
656
659
  const chips = (await client.cia("both")).chips;
@@ -681,8 +684,6 @@ function leftOutNames(used: ReadonlyArray<{ name: string }>): Set<string> {
681
684
 
682
685
  /** The first words of every file that the script writes. */
683
686
  const GENERATED_MARK = "; Generated by c64-source";
684
- /** The file with every range of instructions that no run executed. */
685
- const NOT_EXECUTED_FILE = "not_executed.json";
686
687
  /** The line of each name and address in the source, for links from the documentation. */
687
688
  const SOURCE_MAP_FILE = "source-map.json";
688
689
 
@@ -744,9 +745,6 @@ function staleLoader(out: string, revision: string): { files: string[]; revision
744
745
  return { files, ...(old === undefined ? {} : { revision: old }), ...(version === undefined ? {} : { version }) };
745
746
  }
746
747
 
747
- /** The line of a leftover file that gives its range. */
748
- const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
749
-
750
748
  /**
751
749
  * The leftovers of the earlier run: the ranges of its generated leftover
752
750
  * files in the leftovers folder of `out`. Undefined when `out` has no
@@ -760,10 +758,7 @@ function earlierLeftovers(out: string): AddressRange[] | undefined {
760
758
  if (!existsSync(directory)) return [];
761
759
  return readdirSync(directory)
762
760
  .filter((name) => /^leftover_[0-9a-f]{4}\.asm$/.test(name))
763
- .flatMap((name) => {
764
- const found = LEFTOVER_RANGE.exec(readFileSync(join(directory, name), "utf8"));
765
- return found === null ? [] : [{ start: parseC64Address(found[1]!), end: parseC64Address(found[2]!) }];
766
- });
761
+ .flatMap((name) => leftoverRange(readFileSync(join(directory, name), "utf8")) ?? []);
767
762
  }
768
763
 
769
764
  /** The bytes of `ranges` that are not in `others`, as ranges in address order. */
@@ -773,22 +768,14 @@ function outside(ranges: readonly AddressRange[], others: readonly AddressRange[
773
768
 
774
769
  /**
775
770
  * Removes the generated .asm files of an earlier run that this run does not
776
- * write, and the reports of the earlier run (its source map and
777
- * not_executed.json). An earlier loader.asm stays unless this run has
778
- * --loader: a source of the user can include loader.asm. The files of a
779
- * module are in `out` or in one folder of it: a folder that the run leaves
780
- * empty goes too. A folder with a generated main.asm is the source of another
781
- * space, and it stays. Other files stay. Gives the paths it removed.
771
+ * write. An earlier loader.asm stays unless this run has --loader: a source of
772
+ * the user can include loader.asm. The files of a module are in `out` or in
773
+ * one folder of it: a folder that the run leaves empty goes too. A folder
774
+ * with a generated main.asm is the source of another space, and it stays.
775
+ * Other files stay. Gives the paths it removed.
782
776
  */
783
777
  function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
784
778
  const removed: string[] = [];
785
- const reports = generatedDirectory(projectRelative(out));
786
- for (const name of [SOURCE_MAP_FILE, NOT_EXECUTED_FILE]) {
787
- const path = resolveProjectPath(`${reports}/${name}`);
788
- if (!existsSync(path)) continue;
789
- rmSync(path, { force: true });
790
- removed.push(`${reports}/${name}`);
791
- }
792
779
  const root = resolveProjectPath(out);
793
780
  if (!existsSync(root)) return removed;
794
781
  /** Removes the old generated files of a folder ("" for `out` itself), and gives how many. */
@@ -859,7 +846,8 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
859
846
  const romUse = romUseOfProgram(coverage, image.state);
860
847
  const platform = platformNamesFor(romUse);
861
848
  const { instructions, dataOnly } = options.decoded ?? (await decode(image, knowledge, options.entries, coverage));
862
- const leftovers = options.leftovers === true && !dataOnly ? leftoversOf(knowledge, instructions) : [];
849
+ const leftoverPlan = options.leftovers === true && !dataOnly ? leftoversOf(knowledge, instructions) : { ranges: [], unknown: [], unresolved: [] };
850
+ const leftovers = leftoverPlan.ranges;
863
851
  const laid = layout({
864
852
  segments: image.segments,
865
853
  byteAt: image.byteAt,
@@ -943,7 +931,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
943
931
  }
944
932
  }
945
933
  if (loader !== undefined) files = [...files, ...marked([{ name: "loader.asm", text: loader.text }, ...(loader.startScreen === undefined ? [] : [{ name: START_SCREEN_FILE, text: START_SCREEN_CODE }])])];
946
- return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused };
934
+ return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused, unknownCode: { unknown: leftoverPlan.unknown, unresolved: leftoverPlan.unresolved } };
947
935
  }
948
936
 
949
937
  /** The ranges that the loader loads, each with its files: the segments without the leftovers. */
@@ -987,7 +975,14 @@ async function buildLoader(
987
975
  const program = loaderBuilt.program;
988
976
  const memory = new Int16Array(0x10000).fill(-1);
989
977
  program.subarray(2).forEach((byte, offset) => (memory[loaderBuilt.start! + offset] = byte));
990
- const expected = (address: number) => (loader.loaded.some((part) => address >= part.start && address <= part.end) ? main.program[2 + address - main.start]! : state.pages[address]!);
978
+ // The plain form also copies the colours of the colour RAM to a free range, where the copier reads them.
979
+ const colours = loader.colours;
980
+ const expected = (address: number) =>
981
+ loader.loaded.some((part) => address >= part.start && address <= part.end)
982
+ ? main.program[2 + address - main.start]!
983
+ : colours !== undefined && address >= colours.start && address <= colours.end
984
+ ? state.colourRam![address - colours.start]!
985
+ : state.pages[address]!;
991
986
  const wrongPacking = loader.blocks.find((block) => {
992
987
  for (let address = block.range.start; address <= block.range.end; address++) if (memory[block.packedAt + address - block.range.start] !== block.bytes(address)) return true;
993
988
  return false;
@@ -1040,7 +1035,7 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
1040
1035
  // The call is the entry of the stage: what it does not reach and its run did not touch stays out.
1041
1036
  const called = { ...knowledge, program: { ...image, entry: row.call } };
1042
1037
  const { instructions } = await decode(called.program, called, [row.call], knowledge.coverage);
1043
- const free = leftoversOf(called, instructions, screen);
1038
+ const free = leftoversOf(called, instructions, screen).ranges;
1044
1039
  ranges = [...screen, ...image.segments.flatMap((segment) => subtract(segment, free))];
1045
1040
  }
1046
1041
  const parts: AddressRange[] = [];
@@ -1147,7 +1142,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1147
1142
  const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
1148
1143
  const header = [`Generated by c64-source from knowledge revision ${knowledge.sourceRevision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
1149
1144
  const loaderHeader = [loaderLine(knowledge.sourceRevision), "It copies the segments into place, sets the entry state and jumps to the entry."];
1150
- const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
1145
+ const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused, unknownCode } = await buildSource(knowledge, {
1151
1146
  space,
1152
1147
  entries,
1153
1148
  header,
@@ -1177,19 +1172,13 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1177
1172
  .map((reference) => ({ folder: reference.folder, revision: reference.revision }));
1178
1173
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
1179
1174
  const inData = entriesInData(entries, knowledge.regions);
1180
- if (rendered.notExecuted !== undefined) {
1181
- // Each range with the file of the source that holds it and the routine before it, as a report groups them.
1182
- const routines = knowledge.symbols.filter((symbol) => symbol.kind === "routine").sort((a, b) => a.address - b.address);
1183
- const placed = rendered.notExecuted.ranges.map((range) => {
1184
- const file = laid.pieces.find((piece) => range.start >= piece.start && range.start <= piece.end)?.file;
1185
- const routine = routines.filter((symbol) => symbol.address <= range.start).at(-1)?.name;
1186
- return { ...showRange(range), ...(file === undefined ? {} : { file }), ...(routine === undefined ? {} : { routine }) };
1187
- });
1188
- const files: Record<string, number> = {};
1189
- for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
1190
- const all = { revision: knowledge.sourceRevision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
1191
- written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
1192
- }
1175
+ // Each range of code that no run executed, with the file of the source that holds it and the routine before it, as a report groups them.
1176
+ const routines = knowledge.symbols.filter((symbol) => symbol.kind === "routine").sort((a, b) => a.address - b.address);
1177
+ const placeRange = (range: AddressRange) => {
1178
+ const file = laid.pieces.find((piece) => range.start >= piece.start && range.start <= piece.end)?.file;
1179
+ const routine = routines.filter((symbol) => symbol.address <= range.start).at(-1)?.name;
1180
+ return { ...showRange(range), ...(file === undefined ? {} : { file }), ...(routine === undefined ? {} : { routine }) };
1181
+ };
1193
1182
  // The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
1194
1183
  const added = earlier === undefined ? [] : outside(laid.leftovers, earlier);
1195
1184
  const dropped = earlier === undefined ? [] : outside(earlier, laid.leftovers);
@@ -1223,7 +1212,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1223
1212
  ...(rendered.notExecuted === undefined
1224
1213
  ? {}
1225
1214
  : {
1226
- notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `a larger --max-listed, or read ${reports}/${NOT_EXECUTED_FILE}`) },
1215
+ notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, placeRange) },
1227
1216
  }),
1228
1217
  ...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
1229
1218
  // The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
@@ -1234,6 +1223,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1234
1223
  ? {}
1235
1224
  : { leftovers: { bytes: 0, changed } }
1236
1225
  : { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `${LEFTOVER_FOLDER}/leftover_${range.start.toString(16).padStart(4, "0")}.asm` })), ...(changed === undefined ? {} : { changed }) } }),
1226
+ ...(unknownCode.unknown.length === 0 ? {} : { unknownCode: showUnknown(unknownCode, max) }),
1237
1227
  ...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
1238
1228
  ...(rendered.operandsAsNumbers.length === 0
1239
1229
  ? {}
@@ -1476,7 +1466,7 @@ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions
1476
1466
  * patch names and the ranges of `keep` stay, so each switch builds with
1477
1467
  * LEFTOVERS = 0.
1478
1468
  */
1479
- function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): AddressRange[] {
1469
+ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): UnknownCode & { ranges: AddressRange[] } {
1480
1470
  const image = knowledge.program;
1481
1471
  const inImage = (range: AddressRange) => image.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
1482
1472
  const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
@@ -1484,12 +1474,29 @@ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<numbe
1484
1474
  const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
1485
1475
  const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1486
1476
  const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
1487
- const free = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
1477
+ const plan = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] });
1478
+ const free = plan.free.map((range) => ({ start: range.start, end: range.end }));
1488
1479
  // A macro use in code that nothing uses goes with that code. A leftover never cuts a use in two: its edge stops at the use.
1489
1480
  const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => use.start <= range.end && range.start <= use.end && (use.start < range.start || use.end > range.end));
1490
- return free.flatMap((range) => subtract(range, cut(range)));
1481
+ return { ranges: free.flatMap((range) => subtract(range, cut(range))), unknown: plan.unknown, unresolved: plan.unresolved };
1491
1482
  }
1492
1483
 
1484
+ /** Code that no flow reaches and no run executed, which stays because a flow in `unresolved` can go to it. */
1485
+ interface UnknownCode {
1486
+ unknown: AddressRange[];
1487
+ unresolved: UnresolvedFlow[];
1488
+ }
1489
+
1490
+ /** The unknown code of a result: its ranges, and the flows whose targets the knowledge does not give. */
1491
+ function showUnknown(code: UnknownCode, max: number) {
1492
+ return {
1493
+ ...listed(code.unknown, max, (range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end), bytes: range.end - range.start + 1 })),
1494
+ unresolved: listed(code.unresolved, max, (flow) => ({ at: formatC64Address(flow.at), kind: flow.kind })),
1495
+ };
1496
+ }
1497
+
1498
+ const UNKNOWN_HINT = "The code in unknownCode stays in the build: no run executed it, and a flow in unknownCode.unresolved can go to it. Find the targets of each flow in the emulator. Record a jump reference from the flow to each target in the project knowledge, also to an address outside the program. Then run the command again.";
1499
+
1493
1500
  /** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
1494
1501
  function filesIn(root: string, skip: (path: string) => boolean, folder = ""): Array<{ path: string; bytes: Buffer }> {
1495
1502
  const found: Array<{ path: string; bytes: Buffer }> = [];
@@ -1717,6 +1724,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1717
1724
  ...(knowledge.coverage === undefined ? { noCoverage: "The knowledge has no coverage, so nothing became free by itself. Only --drop makes a range free." } : {}),
1718
1725
  free: { bytes: freeBytes, ...listed(free, max, (range) => ({ ...shownRange(range), bytes: range.end - range.start + 1, what: range.what, label: freeName(range) })) },
1719
1726
  unreachableExecuted: listed(plan.unreachableExecuted, max, (range) => ({ ...shownRange(range), ...(range.routine === undefined ? {} : { routine: range.routine }), drop: `--drop '${formatC64Address(range.start)}-${formatC64Address(range.end)}'` })),
1727
+ ...(plan.unknown.length === 0 ? {} : { unknownCode: showUnknown(plan, max) }),
1720
1728
  knowledge: kept,
1721
1729
  tests: { written: tests.map((test) => test.file), leftOut: listed(testsLeftOut, max, (item) => item) },
1722
1730
  ...(spacesLeftOut.length === 0 ? {} : { spacesLeftOut }),
@@ -1777,6 +1785,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1777
1785
  }
1778
1786
  if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
1779
1787
  if ((body.leftovers as { noCoverage?: string } | undefined)?.noCoverage !== undefined && call.flag("loader")) steps.push("To leave out the bytes that nothing uses, put the coverage of the runs into the project knowledge. Then generate again.");
1788
+ if (body.unknownCode !== undefined) steps.push(UNKNOWN_HINT);
1780
1789
  if (body.dataOnly !== undefined) {
1781
1790
  steps.push("The source has only data. If the space has code, give --entry, or record a code region in the project knowledge.");
1782
1791
  again = true;
@@ -1818,6 +1827,7 @@ function exportReply(body: Record<string, unknown>): Reply {
1818
1827
  const steps = ["Build and test the new project as its README.md tells."];
1819
1828
  if (body.noCoverage !== undefined) steps.push("To make unused code and data free, put the coverage of a run into the project knowledge. Then remove the new folder and its zip file, and export again.");
1820
1829
  if (((body.unreachableExecuted as { count: number } | undefined)?.count ?? 0) > 0) steps.push("To make the code in unreachableExecuted free, remove the new folder and its zip file. Then export again with the drop value of the code.");
1830
+ if (body.unknownCode !== undefined) steps.push(UNKNOWN_HINT.replace("Then run the command again.", "Then remove the new folder and its zip file, and export again."));
1821
1831
  if ([body.free, body.unreachableExecuted, body.operandsAsNumbers, body.macrosAsInstructions, (body.tests as { leftOut?: unknown } | undefined)?.leftOut].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
1822
1832
  return reply(body, { hint: steps.join(" ") });
1823
1833
  }
@@ -1829,7 +1839,7 @@ await runScript({
1829
1839
  commands: [
1830
1840
  {
1831
1841
  name: "generate",
1832
- summary: "Writes the source files to --out and checks them. The source map and not_executed.json go to .c64-re-tools/local/generated/<dir>/. result is PASS when every check passes, else FAIL.",
1842
+ summary: "Writes the source files to --out and checks them. result is PASS when every check passes, else FAIL.",
1833
1843
  options: {
1834
1844
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
1835
1845
  entry: { ...OPTIONS.entry, multiple: true, help: "an address where code starts. The entry of the program, the routines and the code regions of the knowledge are entry points too" },
@@ -1838,7 +1848,7 @@ await runScript({
1838
1848
  "analyzer-names": { kind: "flag", help: "name an address that has no name of the user or the LLM, and no platform name, with its analyzer name" },
1839
1849
  "max-listed": OPTIONS["max-listed"],
1840
1850
  },
1841
- notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed, and .c64-re-tools/local/generated/<dir>/not_executed.json has all of its ranges. Without --analyzer-names, an address without a name gets a name of the source, for example l_17e2.",
1851
+ notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed, each range with its file and the routine before it. Without --analyzer-names, an address without a name gets a name of the source, for example l_17e2.",
1842
1852
  run: async (call) => {
1843
1853
  const { output, failed, removed } = await generate(call);
1844
1854
  // A file of an earlier run that this run removed and did not write again.
@@ -45,12 +45,11 @@ To get the command list, run the script with no arguments.
45
45
  - A vector or an interrupt target that you found in the emulator.
46
46
  - An address in `functions` of an earlier decompiler result.
47
47
  - The decompiler needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
48
- - Each routine, each `code` region and each entry of a `jumps` table in the project knowledge is also an entry point. Each name in the project knowledge is a label in the listing and in the decompiled code.
48
+ - Each routine, each `code` region and each entry of a `jumps` table that the user or the LLM recorded is also an entry point. Each name in the project knowledge is a label in the listing and in the decompiled code.
49
49
  - The two start vectors of a `CBM80` header at `$8000` are entry points without help.
50
- - Each region that is not code in the project knowledge stays data. Each `data` or `variable` symbol also keeps its region as data. If the region holds an entry point or executed code, only the byte of the symbol stays data.
50
+ - A region of the user or the LLM that is not code stays data in the analysis. A `data` or `variable` symbol keeps its region as data.
51
51
  - If an analyzer decodes data as code, classify the region as data in the project knowledge. Then run `analyze` again.
52
- - The facts of an analyzer are not entry points or data for the next analysis. Thus a new analysis can correct them.
53
- - With coverage, the analysis keeps as data the RAM under ROM that the runs did not read or execute. A call into the KERNAL thus does not decode the RAM under it. If the program has code there, give its address with `--entry`.
52
+ - With coverage, the RAM under ROM that the runs did not read or execute stays data. If the program has code there, give its address with `--entry`.
54
53
  - The decompiler does not follow BRK. If the program removes the KERNAL and uses the BRK vector, give the target of the vector with `--entry`.
55
54
  - `--decompile` takes the address of a routine. Get it from `functions` of an earlier decompiler result, or from the routines in the project knowledge.
56
55
 
@@ -64,12 +63,11 @@ To get the command list, run the script with no arguments.
64
63
  - A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
65
64
  - Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
66
65
  - Write each file that you make for your work in `.c64-re-tools/local/` of the project. Git ignores that folder. Examples are results, batches, step files, runs, snapshots and memory dumps.
67
- - The script refuses an `--out` path in `.c64-re-tools/knowledge/` and the index of the knowledge. Change the project knowledge only with the commands that change it.
66
+ - The script refuses an `--out` path in `.c64-re-tools/knowledge/`. Change the project knowledge only with the commands that change it.
68
67
  - The script refuses a folder where the command writes a file. It refuses a file where the command writes a folder.
69
68
  - When a test or another file is the evidence for a finding in the project knowledge, move it out of `.c64-re-tools/local/` first. The project knowledge refuses that evidence in that folder.
70
- - A coverage map can stay in `.c64-re-tools/local/`. The project knowledge keeps its ranges and its SHA-256.
71
- - Do not move a coverage map after you put it into the project knowledge. The knowledge refers to the map by its path at that time.
72
- - Put a run that is evidence in `runs/<name>/`, with its run file, its results and its snapshot files. Change the paths in the run file to the new paths. Then git keeps them, and another person can do the run again.
69
+ - A coverage map can stay in `.c64-re-tools/local/`. Do not move a coverage map after you put it into the project knowledge.
70
+ - To keep a run as evidence, use the command that keeps a run. It copies the run, its results and its snapshot files into `runs/<name>/`, and it changes the paths in the copy. Then git keeps them, and another person can do the run again.
73
71
  - A shell redirect (`>`) is relative to the working directory, not to the project folder. From the folder above the project, write `<folder>/.c64-re-tools/local/result.json`.
74
72
 
75
73
  ---
@@ -104,72 +102,92 @@ The script records only structure: code and data regions, analyzer names, and th
104
102
 
105
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`.
106
104
  - `revision`: the revision of the findings, or `null` when the knowledge did not change.
107
- - `coverage`: the ranges that the analyzer examined.
108
- - `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 the script did not record, because they start in a data region of the user, the LLM or a heuristic. The analyzer decoded these data bytes as code. `symbols.retired` counts the old symbols of the analyzer that became analyzer names.
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.
109
106
  - `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement.
107
+ - `seeds`: what the analyzer got and what it did not use.
108
+ - `entryPoints`, `codeStarts` (decompiler only) and `dataRanges` count the seeds that the analyzer got.
109
+ - `overLimit` counts the seeds over the limit of the analyzer. The analyzer did not get them.
110
+ - `refused` lists each seed that the analyzer did not decode, with `address` and `reason`. `byReason` counts the seeds for each reason. See "Refused seeds and coverage gaps".
111
+ - `dataRangesLeftOut` lists each data range that the analyzer did not keep as data, because the seed at `code` is in it.
110
112
  - `coverageSeeds`: only with coverage. `entryPoints` and `used` give how many entry points the coverage gave, and how many the analysis used. `romOnlyRanges` and `romOnlyUsed` give the same counts for the data ranges under ROM.
111
113
  - `coverageConflicts`: only with coverage. Each analyzer data region where the coverage shows executed code.
112
- - `idioms`: the 6502 idioms that the script found by pattern. The counts are `rtsTables`, `jumpTables`, `bitSkips` and `cartridgeHeaders`. `revision`, `changes` and `conflicts` are for the idioms, as above. `candidates` holds what the script did not record.
114
+ - `writtenNotExecuted`: only with coverage. Each code region of the analyzer on bytes that the runs wrote and never executed, with `start` and `end`. `from` gives the call and jump instructions outside the region that reach it.
115
+ - `idioms`: the 6502 idioms that the script found by pattern. The counts are `rtsTables`, `jumpTables`, `bitSkips` and `cartridgeHeaders`. `revision`, `changes` and `conflicts` are for the idioms, as above. `leftOut` lists each idiom that the script found but did not record, with `kind` and `reason`: `overlaps-idiom` or `leaves-program`. `candidates` holds what the script did not record. See "The candidates".
116
+ - `coverage`: the ranges that the analyzer examined.
113
117
 
114
118
  DXA also gives:
115
119
 
116
- - `regions`: the code and data regions, each with `start`, `end` and `classification`.
120
+ - `regions`: the code and data regions as a list, each with `start`, `end` and `classification`.
117
121
  - `labels`: the names that DXA found, as a list.
118
122
  - `listing`: the listing file, with `--out-listing`.
119
123
 
120
124
  The decompiler also gives:
121
125
 
126
+ - `coverageGaps`: only with coverage. Each executed instruction start that is not an instruction of the decompiler, with `address` and `reason`. See "Refused seeds and coverage gaps".
122
127
  - `functions`: the routines that the decompiler found, as a list, each with `entry` and `name`.
123
128
  - `decompilations`: the C-like code of each `--decompile` routine, with `entry` and `text`. `truncated` tells that the text is cut.
124
129
  - `notDecompiled`: the routines that the decompiler did not decompile, each with a `reason`.
125
130
  - `instructions`: the file and the `count`, with `--out-instructions`. Each instruction has `address`, `bytes`, `mnemonic`, `mode` and `operand` in 6502 syntax. A branch, a jump or a call also has `target`. With coverage, `executed` tells if the instruction ran.
126
- - `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of the decompiler.
127
131
 
128
132
  The `hint` gives each of these cases:
129
133
 
130
134
  - `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
131
135
  - `coverageConflicts` is not empty. Classify each range as code in the project knowledge, or as `dual-use` when its bytes are also data. For many ranges, write all classifications in one batch of changes.
136
+ - `seeds.refused` is not empty. See "Refused seeds and coverage gaps".
137
+ - `writtenNotExecuted` is not empty. A wrong entry point leads an analyzer from code into data. Examine the routine that holds the instructions in `from`. Correct the routine or its region in the project knowledge. Then run `analyze` again.
132
138
  - `idioms.candidates.macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write the correct candidates to the project knowledge, run the analysis again with `--apply-macros`. Give `--skip` with the start of each candidate that is not correct. Then generate the source again.
133
139
  - The last analysis of the same program bytes used another analyzer version. Thus a change in `revision` can come from the new analyzer, and not from the program or the project knowledge.
134
140
  - `changes.references.retired` is more than 0. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.
135
- - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
141
+ - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels`, `functions` and DXA `regions`.
136
142
 
137
143
  There is no `nextAction`.
138
144
 
145
+ #### Refused seeds and coverage gaps
146
+
147
+ Each item of `seeds.refused` and `coverageGaps` has a `reason`. `at` gives the instruction that holds the address, or that its instruction runs into.
148
+
149
+ | `reason` | Action |
150
+ |---|---|
151
+ | `inside-instruction` | Another instruction holds the address. Examine both in the listing. If the address is a wrong routine or region in the project knowledge, correct it. If both instructions run, classify the bytes as `dual-use`. |
152
+ | `into-instruction` | The instruction at the address runs into the instruction at `at`. Do as for `inside-instruction`. |
153
+ | `in-data`, `into-data` | A data range of the analysis holds the address or its instruction. `range` gives the data range of a gap. If the code runs, correct the data region in the project knowledge. |
154
+ | `outside-program`, `past-end` | The address or its instruction is not in the program. Correct the entry point or the routine. |
155
+ | `not-decodable` | No instruction decodes at the address. Correct the entry point or the routine. |
156
+ | `not-reached` | Only in `coverageGaps`: no flow and no seed reached the start. Give it with `--entry`, or record a routine there. |
157
+
158
+ A start in a `dual-use` region is a known overlap, for example a BIT skip. It is not a gap.
159
+
139
160
  #### The candidates
140
161
 
141
162
  The script does not record the candidates. Examine each candidate and decide.
142
163
 
143
164
  - `dop`: DOP padding.
144
- - `selfModified`: opcodes that the program wrote and then executed. The write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro, the game, or a loader that copies code. Clear the memory map between the parts.
165
+ - `selfModified`: opcodes that the program wrote and then executed in one coverage map. A candidate can also be code that ran first and that the program then wrote over. To prevent this, save one coverage map for each part of the program, for example the intro, the game, or a loader that copies code. Clear the memory map between the parts.
145
166
  - `pointers`: code that makes an address from immediates. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at `$0400` in VIC bank 0. For each correct candidate, record a low and a high operand expression to its `target` in the project knowledge. Then a rebuild can move the target.
146
167
  - `pitfalls`: code that a C64 runs in a different way than it reads. For `raster-bit-8`, the instruction at `at` reads `$D011`, and the instruction at `store` writes the value back. The write can move the raster interrupt to line 256 or later. On PAL, past line 311, the interrupt never comes. Where the code must not keep bit 7, add a comment and test the program.
147
168
  - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. A value of `set16` below $0100 is a number. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch over them, or with another use of the project knowledge over them. With `--apply-macros`, `revision` gives the revision of the writes, and `writes` counts them. The writes hold the macros that the project knowledge does not have, with their bodies, and the uses. Do not write these macros yourself. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro. `skipped` counts the candidates that `--skip` left out. `notCandidates` lists each `--skip` address that starts no candidate.
148
169
 
149
- #### Which facts the analysis replaces
170
+ #### What the analysis replaces
150
171
 
151
- - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`.
152
- - DXA and the decompiler do not replace the facts of each other, with one exception. With coverage, a code finding replaces DXA or decompiler data where a run executed an instruction start. Thus put all coverage maps into the project knowledge first. Then run DXA, then the decompiler.
153
- - An analyzer can find data where a run executed an instruction start, or at a `label` or `routine` symbol of the user or the LLM. Then the script does not record that data region, and the earlier region stays. The conflict has `executed` or `knowledge`.
154
- - An idiom region (origin `heuristic`) replaces the part of a DXA or decompiler region where it lies. DXA and the decompiler never replace an idiom region. If they find code there, the result shows a conflict.
172
+ - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`. A conflict with `executed` or `knowledge` shows data where a run executed code, or where the user or the LLM named code.
173
+ - Put all coverage maps into the project knowledge first. Then run DXA, then the decompiler.
155
174
  - An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
156
- - A new analysis replaces the earlier facts of the same analyzer in its `coverage`, also its analyzer names. The history keeps the earlier facts.
175
+ - A new analysis replaces the earlier findings of the same analyzer in its `coverage`.
157
176
  - A fact that the user or the LLM removed does not come back. To remove a wrong fact, remove it in the project knowledge.
158
- - An analyzer name is a second name of the address, not a symbol. Each analyzer keeps its own name at an address. The generated source does not use an analyzer name by default. To use a name in the source, give the address a name in the project knowledge.
177
+ - An analyzer name is a second name of the address, not a symbol. The generated source does not use it. To use a name in the source, give the address a name in the project knowledge.
159
178
  - A decompiler function that only branches and jumps reach is a `label`, not a `routine`.
160
179
 
161
180
  #### Traps
162
181
 
163
182
  - A conflict with the problem "another address has this name": the project knowledge has the generated name at a different address. The knowledge stays unchanged.
164
183
  - A false reference through a vector: the code jumps through a vector, for example `JMP ($0408)`, and the program writes the vector at run time. The analyzer follows the bytes that the program has there. Do these steps:
165
- 1. Find the real targets in the emulator, or in a coverage file.
184
+ 1. Find the real targets in the emulator, or in a coverage map.
166
185
  2. If the vector bytes are also code at another time, classify them as `dual-use` in the project knowledge.
167
186
  3. Remove the false reference in the project knowledge. It does not come back.
168
187
  4. Record a `jump` reference from the JMP to each real target in the project knowledge. Record each target as a routine.
169
- - `coverageGaps` has starts. Normally its count is 0. Each start is not in `--out-instructions` and not in the generated source. Examine the code at the start. Overlapped instructions and self-modified code can cause a gap. A start in a `dual-use` region is a known overlap, for example a BIT skip, and is not in the list.
170
- - `coverageSeeds.used` is smaller than `coverageSeeds.entryPoints`. The analysis did not use all entry points of the coverage. Give the important entry points with `--entry`, or record them as routines in the project knowledge. These come first.
188
+ - `coverageSeeds.used` is smaller than `coverageSeeds.entryPoints`, or `seeds.overLimit` is not empty. The analysis did not use all seeds. Give the important entry points with `--entry`, or record them as routines in the project knowledge. These come first.
171
189
  - `romOnlyUsed` is smaller than `romOnlyRanges`. The analysis did not keep all RAM under ROM as data. Classify the RAM under ROM that is not code as data in the project knowledge.
172
- - `notDecompiled` has a routine. The `reason` tells why the decompiler did not decompile it. Read the instructions of that routine in the file of `--out-instructions`.
190
+ - `notDecompiled` has a routine. The `reason` tells why the decompiler did not decompile it. Read the lines of that routine in the listing of the project knowledge.
173
191
 
174
192
  #### Failures
175
193
 
@@ -196,24 +214,15 @@ The script does not record the candidates. Examine each candidate and decide.
196
214
 
197
215
  Each command prints one JSON envelope on one line on stdout. Notes go to stderr.
198
216
 
199
- On success, the exit code is 0:
200
-
201
- ```json
202
- {"ok": true, "command": "<command>", "body": {}, "hint": "...", "nextAction": "..."}
203
- ```
204
-
205
- On failure, the exit code is 2:
206
-
207
- ```json
208
- {"ok": false, "command": "<command>", "code": "<code>", "error": "...", "hint": "...", "nextAction": "..."}
209
- ```
210
-
217
+ - On success, the exit code is 0: `{"ok": true, "command": "<command>", "body": {}, "hint": "...", "nextAction": "..."}`
218
+ - On failure, the exit code is 2: `{"ok": false, "command": "<command>", "code": "<code>", "error": "...", "hint": "...", "nextAction": "..."}`
211
219
  - `body` holds the result. The section of each command gives the fields of its body.
212
220
  - A check gives its verdict in `body.result`: `PASS`, `FAIL` or `INCONCLUSIVE`. The exit code is 0 for each verdict. Thus read `body.result`, not the exit code.
213
- - `error` is one sentence. It tells what is wrong.
214
- - `hint` tells what to do or what to examine. Read it before your next step. Some envelopes have no `hint`.
215
- - `nextAction` is a full command line. It runs from any directory. Run it when it agrees with your task. Some envelopes have no `nextAction`.
216
- - `code` does not change between versions. Do the action for the code:
221
+ - `error` is one sentence. It tells what is wrong. `hint` tells what to do or what to examine. Read it before your next step.
222
+ - `nextAction` is a full command line. It runs from any directory. Run it when it agrees with your task.
223
+ - A list has `count`, `listed` and `rest`. `listed` holds at most `--max-listed` items. `rest` tells how to get the other items. A file that the command wrote has `out`, `bytes` and `sha256`.
224
+ - To get only some fields of `body`, give `--fields <path>,<path>`, for example `--fields count,listed.start`. A path through a list gives that field of each item. Do not write code to filter an envelope.
225
+ - To get the command list, run the script with no arguments. To get the subjects and the flags of one command, run `<command> --help`.
217
226
 
218
227
  | `code` | Action |
219
228
  |---|---|
@@ -221,13 +230,3 @@ On failure, the exit code is 2:
221
230
  | `invalid-input`, `not-found` | Correct the call as `hint` tells. Then run the command again. |
222
231
  | `operation-failed` | Give `error` and `hint` to the user. |
223
232
  | Another code | Do as `hint` tells. |
224
-
225
- These fields have the same meaning in each body:
226
-
227
- | Field | Meaning |
228
- |---|---|
229
- | `out`, `bytes`, `sha256` | A file that the command wrote: its path, its size and its SHA-256. |
230
- | `count`, `listed`, `rest` | A list. `count` is the number of items. `listed` holds the first items, at most `--max-listed`. `rest` tells how to get the other items. |
231
-
232
- To get the command list, run the script with no arguments. The envelope has `command: "help"`, and `body.commands` gives the name, the summary and the synopsis of each command.
233
- To get the subjects and the flags of one command, run `<command> --help`. Then `body.subjects` and `body.options` give them.
@@ -5,10 +5,11 @@
5
5
  import type { DatabaseSync } from "node:sqlite";
6
6
 
7
7
  import { COVERAGE, coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges } from "#src/c64.ts";
8
+ import type { RefusedSeed, RefusedSeedReason } from "#src/native/types.ts";
8
9
 
9
10
  export { coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges };
10
- import { listRegions, type RegionRow } from "#src/knowledge/read.ts";
11
- import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Space } from "#src/knowledge/schema.ts";
11
+ import { listReferences, listRegions, type RegionRow } from "#src/knowledge/read.ts";
12
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Analyzer, type Space } from "#src/knowledge/schema.ts";
12
13
 
13
14
  /** The byte at an address of the analyzed image, or undefined outside it. */
14
15
  export type ImageByte = (address: number) => number | undefined;
@@ -46,3 +47,55 @@ export function coverageConflicts(db: DatabaseSync | undefined, map: Uint8Array)
46
47
  }
47
48
  return conflicts;
48
49
  }
50
+
51
+ /**
52
+ * The code regions of an analyzer on bytes that a run wrote and that no run
53
+ * executed, each with the call and jump instructions outside it that reach it:
54
+ * a wrong entry point leads an analyzer from code into data.
55
+ */
56
+ export function writtenNotExecuted(db: DatabaseSync | undefined, analyzer: Analyzer, coverage: Uint8Array, space: Space = DEFAULT_SPACE): Array<{ start: number; end: number; from: number[] }> {
57
+ const found: Array<{ start: number; end: number; from: number[] }> = [];
58
+ for (const region of listRegions(db, undefined, "code", [analyzer], space)) {
59
+ let written = false;
60
+ let executed = false;
61
+ for (let address = region.start; address <= region.end && !executed; address++) {
62
+ executed = (coverage[address]! & COVERAGE.ramExecute) !== 0;
63
+ written ||= (coverage[address]! & COVERAGE.ramWrite) !== 0;
64
+ }
65
+ if (executed || !written) continue;
66
+ const outside = (address: number) => address < region.start || address > region.end;
67
+ const from = listReferences(db, region, undefined, undefined, space).filter((reference) => (reference.kind === "call" || reference.kind === "jump") && !outside(reference.to) && outside(reference.from));
68
+ found.push({ start: region.start, end: region.end, from: [...new Set(from.map((reference) => reference.from))].sort((a, b) => a - b) });
69
+ }
70
+ return found;
71
+ }
72
+
73
+ /** Why an executed instruction start has no decoded instruction. */
74
+ export interface GapReason {
75
+ address: number;
76
+ reason: RefusedSeedReason | "not-reached";
77
+ /** The instruction that holds the start or that its instruction runs into. */
78
+ at?: number;
79
+ /** The data range of the analysis that holds the start. */
80
+ range?: { start: number; end: number };
81
+ }
82
+
83
+ /**
84
+ * The reason of each coverage gap: the reason of the analysis when the gap
85
+ * was a seed that it refused; else inside a decoded instruction, in a data
86
+ * range of the analysis, or not reached by any flow or seed.
87
+ */
88
+ export function explainGaps(gaps: readonly number[], instructions: ReadonlyArray<{ address: number; bytes: string }>, refused: readonly RefusedSeed[], dataRanges: ReadonlyArray<{ start: number; end: number }>): GapReason[] {
89
+ const holder = new Map<number, number>();
90
+ for (const instruction of instructions) for (let offset = 1; offset < instruction.bytes.length / 2; offset++) holder.set(instruction.address + offset, instruction.address);
91
+ const refusedAt = new Map(refused.map((seed) => [seed.address, seed]));
92
+ return gaps.map((address): GapReason => {
93
+ const seed = refusedAt.get(address);
94
+ if (seed !== undefined) return { ...seed };
95
+ const at = holder.get(address);
96
+ if (at !== undefined) return { address, reason: "inside-instruction", at };
97
+ const range = dataRanges.find((item) => address >= item.start && address <= item.end);
98
+ if (range !== undefined) return { address, reason: "in-data", range: { start: range.start, end: range.end } };
99
+ return { address, reason: "not-reached" };
100
+ });
101
+ }