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

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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +12 -7
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +10 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +43 -71
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -102,14 +102,17 @@ 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.
106
- - `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement.
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.
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
+ - `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
+ - `references`: the references of the project knowledge into the range from outside it, each with `from` and `kind`.
109
+ - `reachable`: only with coverage. `true` tells that static flow from executed code goes into the range, also through a branch that no run took. The flow follows branches, jumps, calls and the jump and call references of the user, the LLM and the idioms. It does not follow a reference that the user or the LLM removed. It stops at data of the user or the LLM.
107
110
  - `seeds`: what the analyzer got and what it did not use.
108
111
  - `entryPoints`, `codeStarts` (decompiler only) and `dataRanges` count the seeds that the analyzer got.
109
112
  - `overLimit` counts the seeds over the limit of the analyzer. The analyzer did not get them.
110
113
  - `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
114
  - `dataRangesLeftOut` lists each data range that the analyzer did not keep as data, because the seed at `code` is in it.
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.
115
+ - `coverageSeeds`: only with coverage. `entryPoints` and `used` give how many entry points the coverage gave, and how many the analysis used. DXA does not get an entry point that directly follows the executed code of another seed, for example the instruction after a JSR. DXA decodes that instruction from the other seed. Thus `used` counts the entry point. `romOnlyRanges` and `romOnlyUsed` give the same counts for the data ranges under ROM.
113
116
  - `coverageConflicts`: only with coverage. Each analyzer data region where the coverage shows executed code.
114
117
  - `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
118
  - `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".
@@ -131,9 +134,10 @@ The decompiler also gives:
131
134
 
132
135
  The `hint` gives each of these cases:
133
136
 
134
- - `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
137
+ - `conflicts` is not empty. Use `access`, `references` and `reachable` of each conflict. Code that a run executed is code. A range that static flow reaches and that no run executed is usually code on a branch that no run took. A range that no flow reaches and that a run read or wrote is usually data. If these facts do not decide, find the answer in the emulator. Then correct the project knowledge.
135
138
  - `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
139
  - `seeds.refused` has a seed with a reason that is not `outside-program`, or an `--entry` outside the program. See "Refused seeds and coverage gaps".
140
+ - `seeds.overLimit` is not empty. The hint gives the addresses of the seeds that the analyzer did not get. See "Traps".
137
141
  - `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.
138
142
  - `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.
139
143
  - 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.
@@ -170,9 +174,10 @@ The script does not record the candidates. Examine each candidate and decide.
170
174
 
171
175
  #### What the analysis replaces
172
176
 
173
- - 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.
177
+ - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`. A conflict with `executed` shows data where a run executed code that the project knowledge does not hold as code. A conflict with `knowledge` shows data where the user or the LLM named code.
174
178
  - Put all coverage maps into the project knowledge first. Then run DXA, then the decompiler.
175
- - An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
179
+ - An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it, and the table stops at the end of your region. The next analysis removes the references and the entry points of the idiom after that end.
180
+ - The idioms obey the regions of the user and the LLM. An example is a `code` region over the bytes of a BIT skip. Where your region has a different type, the idiom gives no region, no reference and no entry point. A reference that you removed gives no entry point.
176
181
  - A new analysis replaces the earlier findings of the same analyzer in its `coverage`.
177
182
  - A fact that the user or the LLM removed does not come back. To remove a wrong fact, remove it in the project knowledge.
178
183
  - 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.
@@ -186,7 +191,7 @@ The script does not record the candidates. Examine each candidate and decide.
186
191
  2. If the vector bytes are also code at another time, classify them as `dual-use` in the project knowledge.
187
192
  3. Remove the false reference in the project knowledge. It does not come back.
188
193
  4. Record a `jump` reference from the JMP to each real target in the project knowledge. Record each target as a routine.
189
- - `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.
194
+ - `seeds.overLimit` is not empty, or `coverageSeeds.used` is smaller than `coverageSeeds.entryPoints`. The analyzer did not get all seeds, because they are over its limits. The `hint` gives the addresses of these seeds. A finding or a conflict at these addresses can come from this cut, and not from the program. Do not correct the project knowledge for such a finding. After a DXA run, use the findings of the decompiler at these addresses. The decompiler gets more coverage seeds. A routine in the project knowledge or an `--entry` does not help, because it is also a seed.
190
195
  - `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.
191
196
  - `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.
192
197
 
@@ -4,10 +4,8 @@
4
4
 
5
5
  import type { DatabaseSync } from "node:sqlite";
6
6
 
7
- import { COVERAGE, coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges } from "#src/c64.ts";
7
+ import { COVERAGE } from "#src/c64.ts";
8
8
  import type { RefusedSeed, RefusedSeedReason } from "#src/native/types.ts";
9
-
10
- export { coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges };
11
9
  import { listReferences, listRegions, type RegionRow } from "#src/knowledge/read.ts";
12
10
  import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Analyzer, type Space } from "#src/knowledge/schema.ts";
13
11
 
@@ -3,10 +3,12 @@
3
3
 
4
4
  import type { DatabaseSync } from "node:sqlite";
5
5
 
6
+ import { hexWord } from "#src/c64.ts";
6
7
  import type { NormalizedFindings } from "#src/knowledge/import.ts";
7
- import { listRegions, listSymbols } from "#src/knowledge/read.ts";
8
- import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, type Space } from "#src/knowledge/schema.ts";
8
+ import { listRegions, listSuppressions, listSymbols } from "#src/knowledge/read.ts";
9
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, SEMANTIC_ORIGINS, type Space } from "#src/knowledge/schema.ts";
9
10
  import type { DxaResult, DecompilerParams, DecompilerResult } from "#src/native/types.ts";
11
+ import type { Decided } from "./idioms.ts";
10
12
 
11
13
  export type Seeds = Pick<DecompilerParams, "entryPoints" | "dataRanges" | "labels">;
12
14
 
@@ -47,6 +49,17 @@ export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoint
47
49
  };
48
50
  }
49
51
 
52
+ /** What the user and the LLM decided in a space, for the idiom pass: their regions, their region removals and their reference removals. */
53
+ export function decidedFromKnowledge(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): Decided {
54
+ const suppressions = listSuppressions(db, undefined, space);
55
+ const removed = new Set(suppressions.filter((row) => row.entity === "reference").map((row) => `${row.start}|${row.to}|${row.kind}`));
56
+ return {
57
+ regions: listRegions(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).map(({ start, end, type }) => ({ start, end, type })),
58
+ removedRegions: suppressions.filter((row) => row.entity === "region").map(({ start, end }) => ({ start, end })),
59
+ removedReference: (reference) => removed.has(`${reference.from}|${reference.to}|${reference.kind}`),
60
+ };
61
+ }
62
+
50
63
  /**
51
64
  * The 6510 opcodes with a low nibble of 1 or 3 use (zp,x) or (zp),y, also the
52
65
  * undocumented ones. The decompiler gives such an instruction a reference to the target
@@ -81,7 +94,7 @@ export function decompilerFindings(result: DecompilerResult): NormalizedFindings
81
94
  const uses = new Map<string, number>();
82
95
  for (const fn of result.functions) uses.set(fn.name, (uses.get(fn.name) ?? 0) + 1);
83
96
  const nameOf = (fn: DecompilerResult["functions"][number]) =>
84
- fn.nameSource !== "seed" && uses.get(fn.name)! > 1 ? `${fn.name}_${fn.entry.toString(16).padStart(4, "0")}` : fn.name;
97
+ fn.nameSource !== "seed" && uses.get(fn.name)! > 1 ? `${fn.name}_${hexWord(fn.entry)}` : fn.name;
85
98
  // A function that branches and jumps reach, and no call, is a place in a routine: a label.
86
99
  const called = new Set(result.references.filter((reference) => reference.type === "call").map((reference) => reference.to));
87
100
  const jumped = new Set(result.references.filter((reference) => reference.type === "jump").map((reference) => reference.to));
@@ -6,9 +6,14 @@
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
8
  // count while each target is a plausible instruction in the program.
9
+ // The knowledge of the user and the LLM wins: an idiom gives no region, no
10
+ // 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.
9
13
 
10
- import { COVERAGE } from "#src/c64.ts";
14
+ import { COVERAGE, instructionLength, type ReferenceKind } from "#src/c64.ts";
11
15
  import type { NormalizedFindings } from "#src/knowledge/import.ts";
16
+ import { CODE_REGION_TYPES, type RegionType } from "#src/knowledge/schema.ts";
12
17
  import type { ImageByte } from "./coverage.ts";
13
18
 
14
19
  const MAX_TABLE = 64;
@@ -28,6 +33,32 @@ export interface LeftOutIdiom {
28
33
  reason: "leaves-program" | "overlaps-idiom";
29
34
  }
30
35
 
36
+ /** What the user and the LLM decided: their regions, the ranges where they removed a region, and the references that they removed. */
37
+ export interface Decided {
38
+ regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
39
+ removedRegions: ReadonlyArray<{ start: number; end: number }>;
40
+ removedReference: (reference: { from: number; to: number; kind: ReferenceKind }) => boolean;
41
+ }
42
+
43
+ const NOTHING_DECIDED: Decided = { regions: [], removedRegions: [], removedReference: () => false };
44
+
45
+ /** A decided range: a region of the user or the LLM, or a range where they removed a region (no type). */
46
+ type DecidedRange = { start: number; end: number; type?: RegionType };
47
+
48
+ /**
49
+ * True when an idiom can claim bytes of the type `claim` in a decided range:
50
+ * the same type, or code against code and data against data. A removal never
51
+ * agrees. dual-use bytes are code and data, so a claim of code or data agrees
52
+ * with them, but only dual-use agrees with a claim of dual-use.
53
+ */
54
+ function agrees(claim: RegionType, decided: DecidedRange): boolean {
55
+ if (decided.type === undefined) return false;
56
+ if (decided.type === claim) return true;
57
+ if (claim === "dual-use") return false;
58
+ if (decided.type === "dual-use") return true;
59
+ return CODE_REGION_TYPES.includes(claim) === CODE_REGION_TYPES.includes(decided.type);
60
+ }
61
+
31
62
  export interface Idioms {
32
63
  findings: NormalizedFindings;
33
64
  /** Entry points for the same analysis run: analyzer facts are never seeds. */
@@ -57,9 +88,36 @@ const word = (byteAt: ImageByte, address: number) => {
57
88
  * `byteAt` gives the bytes of the program and undefined outside it, so a
58
89
  * table and its targets stay inside the program. `covered` is the coverage of
59
90
  * the knowledge: the joined map, and the addresses that one run wrote and executed.
91
+ * `decided` is the knowledge of the user and the LLM.
60
92
  */
61
- export function findIdioms(byteAt: ImageByte, range: { start: number; end: number }, covered?: { map: Uint8Array; selfModified: Uint8Array }): Idioms {
93
+ export function findIdioms(byteAt: ImageByte, range: { start: number; end: number }, covered?: { map: Uint8Array; selfModified: Uint8Array }, decided: Decided = NOTHING_DECIDED): Idioms {
62
94
  const coverage = covered?.map;
95
+ // The decided range at each address: its index in `ranges`, or -1.
96
+ const ranges: DecidedRange[] = [...decided.regions, ...decided.removedRegions.map(({ start, end }) => ({ start, end }))];
97
+ const holder = new Int32Array(0x10000).fill(-1);
98
+ ranges.forEach((item, index) => holder.fill(index, Math.max(0, item.start), Math.min(0xffff, item.end) + 1));
99
+ const decidedAt = (address: number) => (address >= 0 && address <= 0xffff ? holder[address]! : -1);
100
+ /** True when the bytes of one part of an idiom are all in one decided range that agrees with the claim, or in none. */
101
+ const fits = (start: number, end: number, claim: RegionType) => {
102
+ const first = decidedAt(start);
103
+ for (let address = start + 1; address <= end; address++) if (decidedAt(address) !== first) return false;
104
+ return first === -1 || agrees(claim, ranges[first]!);
105
+ };
106
+ /** True when no region of the user or the LLM holds the address with a type that is not code. */
107
+ const mayBeCode = (address: number) => {
108
+ const index = decidedAt(address);
109
+ return index === -1 || ranges[index]!.type === undefined || agrees("code", ranges[index]!);
110
+ };
111
+ /** True when a run executed an instruction that holds the address as an operand byte, and no run executed an instruction at the address. */
112
+ const inExecutedOperand = (address: number) => {
113
+ if (coverage === undefined || (coverage[address]! & COVERAGE.ramExecute) !== 0) return false;
114
+ for (let back = 1; back <= 2; back++) {
115
+ const start = address - back;
116
+ const opcode = byteAt(start);
117
+ if (opcode !== undefined && (coverage[start]! & COVERAGE.ramExecute) !== 0 && instructionLength(opcode) > back) return true;
118
+ }
119
+ return false;
120
+ };
63
121
  const regions: NormalizedFindings["regions"] = [];
64
122
  const references: NormalizedFindings["references"] = [];
65
123
  const entryPoints = new Set<number>();
@@ -80,8 +138,8 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
80
138
  };
81
139
 
82
140
  if (range.start <= 0x8000 && range.end >= 0x8008 && CBM80.every((byte, index) => byteAt(0x8004 + index) === byte)) {
83
- const vectors = [word(byteAt, 0x8000)!, word(byteAt, 0x8002)!].filter((target) => plausible(byteAt, target, range));
84
- if (addRegions("cartridge-header", [{ start: 0x8000, end: 0x8003, type: "addresses" }, { start: 0x8004, end: 0x8008, type: "petscii" }])) {
141
+ const vectors = [word(byteAt, 0x8000)!, word(byteAt, 0x8002)!].filter((target) => plausible(byteAt, target, range) && mayBeCode(target));
142
+ if (fits(0x8000, 0x8003, "addresses") && fits(0x8004, 0x8008, "petscii") && addRegions("cartridge-header", [{ start: 0x8000, end: 0x8003, type: "addresses" }, { start: 0x8004, end: 0x8008, type: "petscii" }])) {
85
143
  counts.cartridgeHeaders++;
86
144
  for (const target of vectors) entryPoints.add(target);
87
145
  }
@@ -94,8 +152,13 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
94
152
  const low = word(byteAt, at + 5)!;
95
153
  const interleaved = high === low + 1;
96
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);
97
159
  const targets: number[] = [];
98
160
  for (let index = 0; index < MAX_TABLE; index++) {
161
+ if (decidedAt(low + index * step) !== lowRange || decidedAt(high + index * step) !== highRange) break;
99
162
  const lowByte = byteAt(low + index * step);
100
163
  const highByte = byteAt(high + index * step);
101
164
  if (lowByte === undefined || highByte === undefined) break;
@@ -116,8 +179,11 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
116
179
  if (!addRegions("rts-table", parts)) continue;
117
180
  counts.rtsTables++;
118
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.
119
183
  for (const target of targets) {
120
- references.push({ from: at + 8, to: target, kind: "jump" });
184
+ const reference = { from: at + 8, to: target, kind: "jump" as const };
185
+ if (!mayBeCode(target) || decided.removedReference(reference)) continue;
186
+ references.push(reference);
121
187
  entryPoints.add(target);
122
188
  }
123
189
  }
@@ -128,26 +194,32 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
128
194
  let n = 0;
129
195
  while (at + 3 * n + 2 <= range.end && byteAt(at + 3 * n) === 0x4c) n++;
130
196
  if (n < MIN_JUMPS) continue;
131
- if (addRegions("jump-table", [{ start: at, end: at + 3 * n - 1, type: "jumps" }])) {
197
+ // The JMPs inside the run are the same table: a run that is left out is left out once.
198
+ const run = n;
199
+ // A JMP table is code: it ends where the decided range at its start ends.
200
+ if (fits(at, at, "jumps")) while (n > 0 && !fits(at, at + 3 * n - 1, "jumps")) n--;
201
+ else n = 0;
202
+ if (n >= MIN_JUMPS && addRegions("jump-table", [{ start: at, end: at + 3 * n - 1, type: "jumps" }])) {
132
203
  counts.jumpTables++;
133
204
  for (let index = 0; index < n; index++) {
134
205
  entryPoints.add(at + 3 * index);
135
206
  const target = word(byteAt, at + 3 * index + 1)!;
136
- if (plausible(byteAt, target, range)) entryPoints.add(target);
207
+ if (plausible(byteAt, target, range) && mayBeCode(target)) entryPoints.add(target);
137
208
  }
138
209
  }
139
- // The JMPs inside the run are the same table: a run that is left out is left out once.
140
- at += 3 * n - 1;
210
+ at += 3 * run - 1;
141
211
  }
142
212
 
143
213
  // BIT skips: BIT abs ($2c) whose operand bytes are an instruction that a JMP, a JSR or the coverage enters.
214
+ // A $2c in an executed instruction is its operand; the BIT is code and its operand bytes are dual-use.
144
215
  const entered = new Set<number>();
145
216
  for (let at = range.start; at + 2 <= range.end; at++) {
146
217
  if (byteAt(at) === 0x4c || byteAt(at) === 0x20) entered.add(word(byteAt, at + 1)!);
147
218
  }
148
219
  if (coverage !== undefined) for (let address = range.start; address <= range.end; address++) if ((coverage[address]! & COVERAGE.ramExecute) !== 0) entered.add(address);
149
220
  for (let at = range.start; at + 2 <= range.end; at++) {
150
- if (byteAt(at) !== 0x2c || !entered.has(at + 1) || !plausible(byteAt, at + 1, range)) continue;
221
+ if (byteAt(at) !== 0x2c || !entered.has(at + 1) || !plausible(byteAt, at + 1, range) || inExecutedOperand(at)) continue;
222
+ if (!fits(at, at, "code") || !fits(at + 1, at + 2, "dual-use")) continue;
151
223
  if (!addRegions("bit-skip", [{ start: at + 1, end: at + 2, type: "dual-use" }])) continue;
152
224
  counts.bitSkips++;
153
225
  entryPoints.add(at);
@@ -0,0 +1,112 @@
1
+ // The facts that decide a disagreement of code and data in a range: what the
2
+ // runs did there, the references into it, and whether static flow from code
3
+ // that a run executed reaches it, also through branches that no run took.
4
+
5
+ import { COVERAGE, instructionLength, type ReferenceKind } from "#src/c64.ts";
6
+ import { computedFlows, NO_FALL_THROUGH } from "#src/knowledge/separate.ts";
7
+ import { isSemantic } from "#src/knowledge/schema.ts";
8
+ import { OPCODES } from "#src/opcodes.ts";
9
+
10
+ export interface FlowInput {
11
+ /** 64 KiB with the program bytes at their addresses. */
12
+ memory: Uint8Array;
13
+ inImage: (address: number) => boolean;
14
+ /** The joined coverage of the knowledge: its executed instruction starts are the roots. */
15
+ coverage: Uint8Array;
16
+ /** The references of the knowledge. A jump or call of the user, the LLM or the idiom pass is a flow. */
17
+ references: ReadonlyArray<{ from: number; to: number; kind: string; origin?: string | undefined }>;
18
+ /** True for an address in data of the user or the LLM: a flow goes into it and ends there. */
19
+ isData: (address: number) => boolean;
20
+ /** True for a reference that the user or the LLM removed: the flow does not go there. */
21
+ removedReference: (reference: { from: number; to: number; kind: ReferenceKind }) => boolean;
22
+ }
23
+
24
+ /**
25
+ * The addresses that static flow from executed code goes to: the instruction
26
+ * starts that a run executed, and from each instruction that the flow
27
+ * decodes, the run on to the next instruction, a branch target, a JMP or JSR
28
+ * target, a jump or call reference of the user, the LLM or the idiom pass,
29
+ * and the computed flows that the bytes of the program resolve (as for the
30
+ * reachability of the code regions). A JMP or JSR whose address bytes a run
31
+ * wrote goes only where the computed flows go. A flow outside the program or
32
+ * into data of the user or the LLM ends there, and a flow whose jump or call
33
+ * reference the user or the LLM removed does not go.
34
+ */
35
+ export function flowFromExecuted(input: FlowInput): Set<number> {
36
+ const { memory, coverage } = input;
37
+ const follow = new Map<number, number[]>();
38
+ for (const reference of input.references) {
39
+ if ((reference.kind !== "jump" && reference.kind !== "call") || !(isSemantic(reference.origin) || reference.origin === "heuristic")) continue;
40
+ follow.set(reference.from, [...(follow.get(reference.from) ?? []), reference.to]);
41
+ }
42
+ const written = (address: number) => (coverage[address & 0xffff]! & COVERAGE.ramWrite) !== 0;
43
+ const entered = new Set<number>();
44
+ const decoded = new Set<number>();
45
+ const queue: number[] = [];
46
+ const removed = (from: number, to: number) => input.removedReference({ from, to, kind: "jump" }) || input.removedReference({ from, to, kind: "call" });
47
+ const enter = (to: number, from?: number) => {
48
+ const address = to & 0xffff;
49
+ if (entered.has(address) || (from !== undefined && removed(from, address))) return;
50
+ entered.add(address);
51
+ if (input.inImage(address) && !input.isData(address)) queue.push(address);
52
+ };
53
+ const walk = () => {
54
+ while (queue.length > 0) {
55
+ const at = queue.pop()!;
56
+ if (decoded.has(at)) continue;
57
+ decoded.add(at);
58
+ const opcode = memory[at]!;
59
+ if (!NO_FALL_THROUGH.has(opcode)) enter(at + instructionLength(opcode));
60
+ if (OPCODES[opcode]!.mode === "rel") {
61
+ const offset = memory[(at + 1) & 0xffff]!;
62
+ enter(at + 2 + (offset < 0x80 ? offset : offset - 0x100), at);
63
+ }
64
+ if ((opcode === 0x4c || opcode === 0x20) && !written(at + 1) && !written(at + 2)) enter(memory[(at + 1) & 0xffff]! | (memory[(at + 2) & 0xffff]! << 8), at);
65
+ for (const to of follow.get(at) ?? []) enter(to);
66
+ }
67
+ };
68
+ for (let address = 0; address < 0x10000; address++) if ((coverage[address]! & COVERAGE.ramExecute) !== 0 && input.inImage(address)) enter(address);
69
+ walk();
70
+ // The computed flows read the stores of all decoded code: new code can resolve more of them.
71
+ for (;;) {
72
+ const before = entered.size;
73
+ for (const flow of computedFlows({ starts: [...decoded], memory, inImage: input.inImage, coverage, references: input.references }).targets) if (decoded.has(flow.from)) enter(flow.to, flow.from);
74
+ if (entered.size === before) return entered;
75
+ walk();
76
+ }
77
+ }
78
+
79
+ /** The facts of one range in disagreement. */
80
+ export interface RangeFacts {
81
+ /** With coverage: the executed instruction starts, and the bytes that a run read and wrote, in the range. */
82
+ access?: { executed: number; read: number; written: number };
83
+ /** The references of the knowledge into the range from outside it, one for each source and kind. */
84
+ references: Array<{ from: number; kind: ReferenceKind }>;
85
+ /** With coverage: true when static flow from executed code goes into the range. */
86
+ reachable?: boolean;
87
+ }
88
+
89
+ /** The facts of each range, read from the coverage, the references of the knowledge and the flow from executed code. */
90
+ export function rangeFacts(coverage: Uint8Array | undefined, references: ReadonlyArray<{ from: number; to: number; kind: ReferenceKind }>, flow: Set<number> | undefined): (range: { start: number; end: number }) => RangeFacts {
91
+ return ({ start, end }) => {
92
+ const inside = (address: number) => address >= start && address <= end;
93
+ const into = new Map<string, { from: number; kind: ReferenceKind }>();
94
+ for (const reference of references) if (inside(reference.to) && !inside(reference.from)) into.set(`${reference.from}|${reference.kind}`, { from: reference.from, kind: reference.kind });
95
+ const facts: RangeFacts = { references: [...into.values()].sort((a, b) => a.from - b.from || a.kind.localeCompare(b.kind)) };
96
+ if (coverage !== undefined) {
97
+ const access = { executed: 0, read: 0, written: 0 };
98
+ for (let address = start; address <= end; address++) {
99
+ if ((coverage[address]! & COVERAGE.ramExecute) !== 0) access.executed++;
100
+ if ((coverage[address]! & COVERAGE.ramRead) !== 0) access.read++;
101
+ if ((coverage[address]! & COVERAGE.ramWrite) !== 0) access.written++;
102
+ }
103
+ facts.access = access;
104
+ }
105
+ if (flow !== undefined) {
106
+ let reachable = false;
107
+ for (let address = start; address <= end && !reachable; address++) reachable = flow.has(address);
108
+ facts.reachable = reachable;
109
+ }
110
+ return facts;
111
+ };
112
+ }