@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +5 -2
- package/skills/c64-assembler/scripts/assembler.ts +55 -48
- package/skills/c64-disk/scripts/disk.ts +3 -3
- package/skills/c64-disk/scripts/lib/containers.ts +2 -2
- package/skills/c64-docs/SKILL.md +1 -1
- package/skills/c64-docs/scripts/docs.ts +12 -20
- package/skills/c64-docs/scripts/lib/links.ts +1 -1
- package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
- package/skills/c64-docs/scripts/lib/reference.ts +59 -13
- package/skills/c64-knowledge/SKILL.md +17 -8
- package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
- package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
- package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
- package/skills/c64-packer/scripts/packer.ts +3 -3
- package/skills/c64-provenance/SKILL.md +25 -16
- package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
- package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
- package/skills/c64-provenance/scripts/lib/library.ts +10 -10
- package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
- package/skills/c64-provenance/scripts/provenance.ts +129 -98
- package/skills/c64-source/references/loader.md +2 -1
- package/skills/c64-source/scripts/lib/export.ts +54 -303
- package/skills/c64-source/scripts/lib/loader.ts +31 -51
- package/skills/c64-source/scripts/lib/source.ts +51 -41
- package/skills/c64-source/scripts/lib/stage.ts +9 -25
- package/skills/c64-source/scripts/source.ts +134 -294
- package/skills/c64-static-analysis/SKILL.md +10 -5
- package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
- package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
- package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
- package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
- package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
- package/skills/c64-testing/SKILL.md +13 -7
- package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
- package/skills/c64-testing/scripts/lib/recording.ts +47 -66
- package/skills/c64-testing/scripts/lib/replay.ts +53 -9
- package/skills/c64-testing/scripts/lib/runs.ts +11 -29
- package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
- package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
- package/skills/c64-testing/scripts/testing.ts +32 -7
- package/skills/c64-unpacker/SKILL.md +9 -7
- package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
- package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
- package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
- package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
- package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
- package/skills/emulator/SKILL.md +1 -0
- package/src/c64.ts +117 -10
- package/src/cli/ap-sdk.ts +1 -1
- package/src/cli/cleanup.ts +4 -2
- package/src/compare.ts +36 -16
- package/src/errors.ts +10 -1
- package/src/host/main.ts +2 -1
- package/src/host/server.ts +7 -11
- package/src/host/tools/c1541.ts +9 -3
- package/src/host/vice/adapter.ts +20 -43
- package/src/host/vice/binary-monitor.ts +22 -21
- package/src/host/vice/process.ts +31 -40
- package/src/host/vice/session.ts +187 -247
- package/src/host/vice/text-monitor.ts +3 -3
- package/src/host-client/autostart.ts +1 -1
- package/src/host-client/connect.ts +2 -1
- package/src/host-client/coverage.ts +0 -3
- package/src/host-client/entry-state.ts +4 -11
- package/src/host-client/image.ts +6 -11
- package/src/host-client/steps.ts +13 -113
- package/src/host-client/tools.ts +4 -4
- package/src/host-client/transfer.ts +10 -0
- package/src/host-client/vice-session.ts +10 -6
- package/src/knowledge/code-reach.ts +364 -0
- package/src/knowledge/conflicts.ts +34 -72
- package/src/knowledge/database.ts +40 -28
- package/src/knowledge/evidence.ts +2 -2
- package/src/knowledge/graph.ts +3 -3
- package/src/knowledge/history.ts +50 -90
- package/src/knowledge/import.ts +28 -68
- package/src/knowledge/join.ts +1 -1
- package/src/knowledge/names.ts +12 -7
- package/src/knowledge/program.ts +25 -46
- package/src/knowledge/read.ts +104 -100
- package/src/knowledge/schema.ts +9 -3
- package/src/knowledge/separate.ts +47 -19
- package/src/knowledge/start-screen.ts +7 -5
- package/src/knowledge/text.ts +56 -33
- package/src/knowledge/write.ts +274 -515
- package/src/loader.ts +7 -25
- package/src/mcp/inputs.ts +3 -3
- package/src/mcp/server.ts +19 -38
- package/src/mcp/session-source.ts +2 -1
- package/src/mcp/tools/debug.ts +97 -24
- package/src/mcp/tools/execution.ts +1 -1
- package/src/mcp/tools/input.ts +3 -3
- package/src/mcp/tools/machine.ts +3 -3
- package/src/mcp/tools/media.ts +4 -4
- package/src/mcp/tools/memory.ts +13 -17
- package/src/mcp/tools/video.ts +11 -25
- package/src/native/acme.ts +3 -3
- package/src/native/c64run.ts +2 -1
- package/src/native/decompiler/analyze.ts +10 -7
- package/src/native/decompiler/walk.ts +3 -4
- package/src/native/decompiler/wasm.ts +2 -2
- package/src/native/discover.ts +1 -1
- package/src/native/dxa.ts +9 -11
- package/src/native/exomizer.ts +1 -1
- package/src/native/processes.ts +4 -1
- package/src/native/run.ts +3 -3
- package/src/native/types.ts +5 -6
- package/src/opcodes.ts +3 -0
- package/src/platform.ts +9 -10
- package/src/program-code.ts +151 -0
- package/src/project.ts +8 -5
- package/src/protocol/framing.ts +51 -18
- package/src/protocol/messages.ts +1 -11
- package/src/protocol/tools.ts +0 -3
- package/src/protocol/vice.ts +588 -773
- package/src/script.ts +9 -14
- package/src/time.ts +1 -1
- package/src/trace.ts +3 -2
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// The code reach of a program: which blocks of its decoded instructions it
|
|
2
|
+
// can run. The reachability runs two times over the blocks. Pass A starts at
|
|
3
|
+
// the entry, the hardware vectors and the entries of the tables in use: it
|
|
4
|
+
// tells what the program can reach. Pass B also starts at each block that a
|
|
5
|
+
// run executed and at the kept and changed ranges: it tells what stays. Code
|
|
6
|
+
// that pass B does not reach and that no run executed is unused. Without
|
|
7
|
+
// coverage no code is unused. While the code that stays has a flow whose
|
|
8
|
+
// targets the knowledge does not give (an indirect jump through a vector that
|
|
9
|
+
// the code's own immediates do not set, a jump whose address a run wrote, or
|
|
10
|
+
// an RTS to an address that the code pushed), that code is unknown, not
|
|
11
|
+
// unused. The leftovers of a generated source, the free ranges of an export
|
|
12
|
+
// and the dead and unknown code of the provenance all come from here. The
|
|
13
|
+
// decode of the program and the input of the code reach are in
|
|
14
|
+
// src/program-code.ts.
|
|
15
|
+
|
|
16
|
+
import type { DatabaseSync } from "node:sqlite";
|
|
17
|
+
|
|
18
|
+
import { type AddressRange, COVERAGE, inRanges, mergeRanges, pointerTableEntries, POINTER_TABLE_TYPES, type PointerTableType, rangesOverlap, subtract } from "../c64.ts";
|
|
19
|
+
import { OPCODES } from "../opcodes.ts";
|
|
20
|
+
import { programCoverage, requireProgram, type ProgramImage } from "./program.ts";
|
|
21
|
+
import { currentStartScreen, listAnalyzerNames, listOperands, listPatches, listReferences, listRegions, listSymbols, type OperandRow, type PatchRow, type ReferenceRow, type RegionRow, type StartScreenRow, type SymbolRow } from "./read.ts";
|
|
22
|
+
import { DEFAULT_SPACE, INSTRUCTION_REGION_TYPES, isSemantic, type RegionType, type Space } from "./schema.ts";
|
|
23
|
+
import { computedFlows, NO_FALL_THROUGH, type Root, separate, type UnresolvedFlow, vectorHigh, WRITES_A, WRITES_X, WRITES_Y } from "./separate.ts";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The coverage flags that can be a use of the RAM byte: a read or a run of the
|
|
27
|
+
* ROM uses the ROM, not the RAM under it, so a JSR into the KERNAL keeps no byte
|
|
28
|
+
* of the image. The I/O flags stay, as VICE gives each access at $d000-$dfff as I/O.
|
|
29
|
+
*/
|
|
30
|
+
export const RAM_ACCESS = 0xff & ~(COVERAGE.romRead | COVERAGE.romExecute);
|
|
31
|
+
|
|
32
|
+
/** The I/O area: two immediates stored there are chip values, such as a timer latch, not an address. */
|
|
33
|
+
const IO_AREA: AddressRange = { start: 0xd000, end: 0xdfff };
|
|
34
|
+
|
|
35
|
+
/** The registers that a JSR gets an address in, low byte first, as the KERNAL and BASIC routines get a pointer. */
|
|
36
|
+
const CALL_PAIRS = [
|
|
37
|
+
["x", "y"],
|
|
38
|
+
["a", "y"],
|
|
39
|
+
["a", "x"],
|
|
40
|
+
] as const;
|
|
41
|
+
|
|
42
|
+
export interface CodeReachInput {
|
|
43
|
+
segments: readonly AddressRange[];
|
|
44
|
+
/** 64 KiB with the program at its addresses. */
|
|
45
|
+
memory: Uint8Array;
|
|
46
|
+
entry?: number;
|
|
47
|
+
/** The decoded instructions of the program: start and length. */
|
|
48
|
+
instructions: ReadonlyMap<number, number>;
|
|
49
|
+
coverage?: Uint8Array;
|
|
50
|
+
regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
|
|
51
|
+
/** A jump or call reference of the user or the LLM resolves the flow of its instruction. */
|
|
52
|
+
references: ReadonlyArray<{ from: number; to: number; kind: string; origin?: string }>;
|
|
53
|
+
/** The addresses that the operand expression of an instruction names, by the address of each instruction with an operand expression; none for a constant. */
|
|
54
|
+
operandTargets: ReadonlyMap<number, readonly number[]>;
|
|
55
|
+
/** The ranges where the CPU sees ROM and not the RAM of the image: code does not go there, and no address points there. */
|
|
56
|
+
rom?: readonly AddressRange[];
|
|
57
|
+
/** The patch ranges whose bytes can change: their code stays, and a reference from them does not count. */
|
|
58
|
+
changed: readonly AddressRange[];
|
|
59
|
+
/** The ranges whose code stays. */
|
|
60
|
+
keep: readonly AddressRange[];
|
|
61
|
+
/** The ranges whose code is gone. */
|
|
62
|
+
drop: readonly AddressRange[];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A place where code goes or reads: the instruction (or table) at `from`, and what it names. */
|
|
66
|
+
export interface Flow {
|
|
67
|
+
from: number;
|
|
68
|
+
to: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface DataReference {
|
|
72
|
+
from: number;
|
|
73
|
+
start: number;
|
|
74
|
+
end: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A region of the input, cut to a segment. */
|
|
78
|
+
export interface ReachRegion {
|
|
79
|
+
start: number;
|
|
80
|
+
end: number;
|
|
81
|
+
type: RegionType;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface CodeReach {
|
|
85
|
+
/** The regions, cut to the segments. */
|
|
86
|
+
regions: ReachRegion[];
|
|
87
|
+
/** The blocks of the decoded instructions outside the data regions. */
|
|
88
|
+
blocks: AddressRange[];
|
|
89
|
+
flows: Flow[];
|
|
90
|
+
reads: DataReference[];
|
|
91
|
+
/** The tables of addresses or of jumps among the regions, with the targets of their entries. */
|
|
92
|
+
targetsOf: ReadonlyMap<ReachRegion, number[]>;
|
|
93
|
+
/** False when the program has no entry, no hardware vector and no table in use: then no code is unused. */
|
|
94
|
+
rooted: boolean;
|
|
95
|
+
/** For each block: pass A reaches it, or the program has no root. */
|
|
96
|
+
reachable: boolean[];
|
|
97
|
+
/** For each block: a run executed an instruction of it. */
|
|
98
|
+
executed: boolean[];
|
|
99
|
+
/** The blocks that nothing that stays reaches and that no run executed, while no flow is open. */
|
|
100
|
+
unused: AddressRange[];
|
|
101
|
+
/** Code that nothing that stays reaches and that no run executed, which stays because of the flows in `unresolved`. */
|
|
102
|
+
unknown: AddressRange[];
|
|
103
|
+
/** The flows in the code that stays whose targets the knowledge does not give. */
|
|
104
|
+
unresolved: UnresolvedFlow[];
|
|
105
|
+
/** The blocks that stay: the blocks outside `drop` and outside `unused`. */
|
|
106
|
+
stays: AddressRange[];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const within = (a: AddressRange, b: AddressRange) => a.start >= b.start && a.end <= b.end;
|
|
110
|
+
|
|
111
|
+
/** The blocks of the instructions: a block ends after an instruction that does not run on, and before a gap. An instruction inside the one before stays in its block. */
|
|
112
|
+
export function blocksOf(instructions: ReadonlyMap<number, number>, memory: Uint8Array): AddressRange[] {
|
|
113
|
+
const blocks: AddressRange[] = [];
|
|
114
|
+
let open = false;
|
|
115
|
+
for (const start of [...instructions.keys()].sort((a, b) => a - b)) {
|
|
116
|
+
const end = Math.min(0xffff, start + instructions.get(start)! - 1);
|
|
117
|
+
const last = blocks.at(-1);
|
|
118
|
+
if (last !== undefined && (start <= last.end || (open && start === last.end + 1))) last.end = Math.max(last.end, end);
|
|
119
|
+
else blocks.push({ start, end });
|
|
120
|
+
open = !NO_FALL_THROUGH.has(memory[start]!);
|
|
121
|
+
}
|
|
122
|
+
return blocks;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The code flows and the data references of the instructions, the knowledge
|
|
127
|
+
* references and the operand expressions. `indexedEnd` gives the last address
|
|
128
|
+
* that an indexed operand can read.
|
|
129
|
+
*/
|
|
130
|
+
function flowsOf(input: CodeReachInput, inImage: (address: number) => boolean, indexedEnd: (operand: number) => number) {
|
|
131
|
+
const flows: Flow[] = [];
|
|
132
|
+
const reads: DataReference[] = [];
|
|
133
|
+
const { memory } = input;
|
|
134
|
+
const word = (at: number) => memory[at]! | (memory[(at + 1) & 0xffff]! << 8);
|
|
135
|
+
const rom = (address: number) => inRanges(input.rom ?? [], address);
|
|
136
|
+
// The address of a vector, a table or an RTS target in two immediates of one block: the low byte and the high byte
|
|
137
|
+
// go into a pointer (two stores to N and N+1), into the registers of a JSR, or onto the stack (PHA high, PHA low).
|
|
138
|
+
type Immediate = { at: number; value: number } | undefined;
|
|
139
|
+
const registers: { a: Immediate; x: Immediate; y: Immediate } = { a: undefined, x: undefined, y: undefined };
|
|
140
|
+
const stores = new Map<number, NonNullable<Immediate>>();
|
|
141
|
+
const pushes: Immediate[] = [];
|
|
142
|
+
const pair = (low: Immediate, high: Immediate) => {
|
|
143
|
+
if (low === undefined || high === undefined) return;
|
|
144
|
+
const target = low.value | (high.value << 8);
|
|
145
|
+
if (!inImage(target) || rom(target)) return;
|
|
146
|
+
flows.push({ from: low.at, to: target }, { from: low.at, to: (target + 1) & 0xffff });
|
|
147
|
+
reads.push({ from: low.at, start: target, end: target });
|
|
148
|
+
};
|
|
149
|
+
const endBlock = () => {
|
|
150
|
+
registers.a = registers.x = registers.y = undefined;
|
|
151
|
+
stores.clear();
|
|
152
|
+
pushes.length = 0;
|
|
153
|
+
};
|
|
154
|
+
let previousEnd = -2;
|
|
155
|
+
for (const at of [...input.instructions.keys()].sort((a, b) => a - b)) {
|
|
156
|
+
const opcode = memory[at]!;
|
|
157
|
+
const { mnemonic, mode } = OPCODES[opcode]!;
|
|
158
|
+
if (at > previousEnd + 1) endBlock();
|
|
159
|
+
previousEnd = at + input.instructions.get(at)! - 1;
|
|
160
|
+
const operand = input.instructions.get(at) === 3 ? word(at + 1) : memory[at + 1]!;
|
|
161
|
+
// The registers: a load of an immediate that no operand expression explains, a transfer, a store, a push, a call.
|
|
162
|
+
const loaded = mode === "imm" && !input.operandTargets.has(at) ? { at, value: operand } : undefined;
|
|
163
|
+
if (WRITES_A.has(mnemonic) || (mode === "imp" && ["asl", "lsr", "rol", "ror"].includes(mnemonic))) registers.a = mnemonic === "lda" ? loaded : undefined;
|
|
164
|
+
if (WRITES_X.has(mnemonic)) registers.x = mnemonic === "ldx" ? loaded : undefined;
|
|
165
|
+
if (WRITES_Y.has(mnemonic)) registers.y = mnemonic === "ldy" ? loaded : undefined;
|
|
166
|
+
if (mnemonic === "tax") registers.x = registers.a;
|
|
167
|
+
if (mnemonic === "tay") registers.y = registers.a;
|
|
168
|
+
if (mnemonic === "txa") registers.a = registers.x;
|
|
169
|
+
if (mnemonic === "tya") registers.a = registers.y;
|
|
170
|
+
const stored = { sta: registers.a, stx: registers.x, sty: registers.y }[mnemonic];
|
|
171
|
+
if ((mode === "zp" || mode === "abs") && ["sta", "stx", "sty"].includes(mnemonic) && !inRanges([IO_AREA], operand)) {
|
|
172
|
+
stores.delete(operand);
|
|
173
|
+
if (stored !== undefined) {
|
|
174
|
+
stores.set(operand, stored);
|
|
175
|
+
pair(stored, stores.get((operand + 1) & 0xffff));
|
|
176
|
+
pair(stores.get((operand - 1) & 0xffff), stored);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (mnemonic === "pha") {
|
|
180
|
+
pushes.push(registers.a);
|
|
181
|
+
if (pushes.length >= 2) pair(pushes.at(-1), pushes.at(-2));
|
|
182
|
+
}
|
|
183
|
+
if (mnemonic === "pla") pushes.pop();
|
|
184
|
+
if (mnemonic === "jsr") {
|
|
185
|
+
for (const [low, high] of CALL_PAIRS) pair(registers[low], registers[high]);
|
|
186
|
+
registers.a = registers.x = registers.y = undefined;
|
|
187
|
+
}
|
|
188
|
+
switch (mode) {
|
|
189
|
+
case "rel":
|
|
190
|
+
flows.push({ from: at, to: (at + 2 + (operand < 0x80 ? operand : operand - 0x100)) & 0xffff });
|
|
191
|
+
break;
|
|
192
|
+
case "ind": {
|
|
193
|
+
const high = vectorHigh(operand);
|
|
194
|
+
reads.push({ from: at, start: operand, end: operand }, { from: at, start: high, end: high });
|
|
195
|
+
if (inImage(operand) && inImage(high)) flows.push({ from: at, to: memory[operand]! | (memory[high]! << 8) });
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case "abs":
|
|
199
|
+
case "zp":
|
|
200
|
+
if (opcode === 0x20 || opcode === 0x4c) {
|
|
201
|
+
if (!rom(operand)) flows.push({ from: at, to: operand });
|
|
202
|
+
} else reads.push({ from: at, start: operand, end: operand });
|
|
203
|
+
break;
|
|
204
|
+
case "abx":
|
|
205
|
+
case "aby":
|
|
206
|
+
case "zpx":
|
|
207
|
+
case "zpy":
|
|
208
|
+
reads.push({ from: at, start: operand, end: indexedEnd(operand) });
|
|
209
|
+
break;
|
|
210
|
+
case "izx":
|
|
211
|
+
case "izy":
|
|
212
|
+
reads.push({ from: at, start: operand, end: (operand + 1) & 0xff });
|
|
213
|
+
break;
|
|
214
|
+
default:
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
if (NO_FALL_THROUGH.has(opcode)) endBlock();
|
|
218
|
+
}
|
|
219
|
+
for (const reference of input.references) {
|
|
220
|
+
if (inRanges(input.changed, reference.from)) continue;
|
|
221
|
+
if (reference.kind === "call" || reference.kind === "jump" || reference.kind === "pointer") flows.push({ from: reference.from, to: reference.to });
|
|
222
|
+
reads.push({ from: reference.from, start: reference.to, end: reference.to });
|
|
223
|
+
}
|
|
224
|
+
for (const [at, targets] of input.operandTargets) {
|
|
225
|
+
for (const target of targets) {
|
|
226
|
+
flows.push({ from: at, to: target });
|
|
227
|
+
reads.push({ from: at, start: target, end: target });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return { flows, reads };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** The entries of a table of addresses or of jumps. */
|
|
234
|
+
function tableTargets(table: { start: number; end: number; type: RegionType }, memory: Uint8Array): number[] {
|
|
235
|
+
if (table.type === "jumps") return Array.from({ length: Math.floor((table.end - table.start + 1) / 3) }, (_, index) => table.start + 3 * index);
|
|
236
|
+
return pointerTableEntries(table as { start: number; end: number; type: PointerTableType }, (address) => memory[address]!).map((entry) => entry.target);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export const isTable = (type: RegionType) => type === "jumps" || (POINTER_TABLE_TYPES as readonly string[]).includes(type);
|
|
240
|
+
|
|
241
|
+
/** The code reach of the program: see the head of this file. */
|
|
242
|
+
export function codeReach(input: CodeReachInput): CodeReach {
|
|
243
|
+
const inImage = (address: number) => inRanges(input.segments, address);
|
|
244
|
+
const touched = (address: number) => input.coverage !== undefined && (input.coverage[address]! & RAM_ACCESS) !== 0;
|
|
245
|
+
const executed = (address: number) => input.coverage !== undefined && (input.coverage[address]! & COVERAGE.ramExecute) !== 0;
|
|
246
|
+
const regions = input.regions.flatMap((region) => input.segments.filter((segment) => rangesOverlap(region, segment)).map((segment): ReachRegion => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end), type: region.type })));
|
|
247
|
+
// The source writes a data region as data, also where the decompiler decoded instructions in it: those are no code.
|
|
248
|
+
const inData = new Uint8Array(0x10000);
|
|
249
|
+
for (const region of regions) if (!INSTRUCTION_REGION_TYPES.includes(region.type)) inData.fill(1, region.start, region.end + 1);
|
|
250
|
+
const instructions = new Map([...input.instructions].filter(([start, length]) => !inData.subarray(start, start + length).includes(1)));
|
|
251
|
+
const blocks = blocksOf(instructions, input.memory);
|
|
252
|
+
// An indexed operand reads in the region that holds it, and in the next region when it is the last byte (table-1,x).
|
|
253
|
+
// Without a region, it can read the 256 bytes from the operand.
|
|
254
|
+
const holding = (address: number) => regions.find((region) => address >= region.start && address <= region.end);
|
|
255
|
+
const indexedEnd = (operand: number) => {
|
|
256
|
+
const holder = holding(operand);
|
|
257
|
+
const next = holder === undefined || holder.end === operand ? holding((operand + 1) & 0xffff) : undefined;
|
|
258
|
+
return next?.end ?? holder?.end ?? Math.min(0xffff, operand + 0xff);
|
|
259
|
+
};
|
|
260
|
+
const { flows, reads } = flowsOf({ ...input, instructions }, inImage, indexedEnd);
|
|
261
|
+
|
|
262
|
+
// Tables that a run read or that the knowledge names: their entries can be the only way to code, so they are roots.
|
|
263
|
+
const targetsOf = new Map(regions.filter((region) => isTable(region.type)).map((table) => [table, tableTargets(table, input.memory)]));
|
|
264
|
+
const tableUsers = (table: AddressRange) => reads.filter((read) => read.start <= table.end && table.start <= read.end).map((read) => read.from);
|
|
265
|
+
const tableRoots: Root[] = [];
|
|
266
|
+
for (const [table, targets] of targetsOf) {
|
|
267
|
+
let read = false;
|
|
268
|
+
for (let address = table.start; address <= table.end && !read; address++) read = touched(address);
|
|
269
|
+
if (read || input.references.some((reference) => reference.to >= table.start && reference.to <= table.end)) for (const target of targets) tableRoots.push({ address: target, from: "table entry" });
|
|
270
|
+
for (const from of tableUsers(table)) for (const target of targets) flows.push({ from, to: target });
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const asRegions = (list: readonly AddressRange[]) => list.map((block) => ({ ...block, type: "code" }));
|
|
274
|
+
const references = flows.map((flow) => ({ ...flow, kind: "jump" }));
|
|
275
|
+
const passA = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(blocks), references, roots: tableRoots });
|
|
276
|
+
const rooted = passA.codeRegions.every((region) => region.reachable !== undefined);
|
|
277
|
+
const ran = (block: AddressRange) => {
|
|
278
|
+
for (let address = block.start; address <= block.end; address++) if (executed(address)) return true;
|
|
279
|
+
return false;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
// Pass B: what stays. Blocks in a drop range are gone.
|
|
283
|
+
const candidates = blocks.filter((block) => !input.drop.some((range) => within(block, range)));
|
|
284
|
+
const extra: Root[] = [...tableRoots];
|
|
285
|
+
for (const block of candidates) {
|
|
286
|
+
if (ran(block)) extra.push({ address: block.start, from: "executed code" });
|
|
287
|
+
else if ([...input.keep, ...input.changed].some((range) => rangesOverlap(block, range))) extra.push({ address: block.start, from: "kept range" });
|
|
288
|
+
}
|
|
289
|
+
const passB = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(candidates), references, roots: extra });
|
|
290
|
+
const automatic = input.coverage !== undefined && rooted;
|
|
291
|
+
const unreachableCode = candidates.filter((_, index) => automatic && passB.codeRegions[index]!.reachable === false);
|
|
292
|
+
// A flow that nobody resolved can go to any of that code: it stays, as unknown. Only a flow in code that stays can run.
|
|
293
|
+
const live = candidates.filter((block) => !unreachableCode.includes(block));
|
|
294
|
+
const unresolved =
|
|
295
|
+
unreachableCode.length === 0
|
|
296
|
+
? []
|
|
297
|
+
: computedFlows({ starts: [...instructions.keys()], memory: input.memory, inImage, coverage: input.coverage, references: input.references }).unresolved.filter((flow) => live.some((block) => flow.at >= block.start && flow.at <= block.end));
|
|
298
|
+
const unused = unresolved.length === 0 ? unreachableCode : [];
|
|
299
|
+
return {
|
|
300
|
+
regions,
|
|
301
|
+
blocks,
|
|
302
|
+
flows,
|
|
303
|
+
reads,
|
|
304
|
+
targetsOf,
|
|
305
|
+
rooted,
|
|
306
|
+
reachable: blocks.map((_, index) => !rooted || passA.codeRegions[index]!.reachable === true),
|
|
307
|
+
executed: blocks.map(ran),
|
|
308
|
+
unused,
|
|
309
|
+
unknown: unresolved.length === 0 ? [] : mergeRanges(unreachableCode),
|
|
310
|
+
unresolved,
|
|
311
|
+
stays: candidates.filter((block) => !unused.includes(block)),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// --- The knowledge of the code -------------------------------------------------
|
|
316
|
+
|
|
317
|
+
/** The knowledge of one space that the decode and the code reach read. */
|
|
318
|
+
export interface CodeKnowledge {
|
|
319
|
+
program: ProgramImage;
|
|
320
|
+
coverage: Uint8Array | undefined;
|
|
321
|
+
symbols: SymbolRow[];
|
|
322
|
+
/** The routines of every origin: an analyzer routine is an entry point for the decode too. */
|
|
323
|
+
routines: number[];
|
|
324
|
+
regions: RegionRow[];
|
|
325
|
+
references: ReferenceRow[];
|
|
326
|
+
operands: OperandRow[];
|
|
327
|
+
patches: PatchRow[];
|
|
328
|
+
startScreen: StartScreenRow | undefined;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** The knowledge of one space that the decode and the code reach read, read once. */
|
|
332
|
+
export function codeKnowledge(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): CodeKnowledge {
|
|
333
|
+
const symbols = listSymbols(db, undefined, undefined, undefined, space);
|
|
334
|
+
return {
|
|
335
|
+
program: requireProgram(db, space),
|
|
336
|
+
// The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
|
|
337
|
+
coverage: programCoverage(db, space)?.map,
|
|
338
|
+
symbols,
|
|
339
|
+
routines: [...symbols, ...listAnalyzerNames(db, undefined, undefined, undefined, space)].filter((symbol) => symbol.kind === "routine").map((symbol) => symbol.address),
|
|
340
|
+
regions: listRegions(db, undefined, undefined, undefined, space),
|
|
341
|
+
references: listReferences(db, undefined, undefined, undefined, space),
|
|
342
|
+
operands: listOperands(db, undefined, undefined, space),
|
|
343
|
+
patches: listPatches(db, undefined, undefined, undefined, space),
|
|
344
|
+
// The start screen is of the C64 program: the loader shows it.
|
|
345
|
+
startScreen: space === DEFAULT_SPACE ? currentStartScreen(db, space) : undefined,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The parts of a region outside the holes. A part that is not the whole region has no element size: its length need not be a multiple of it. */
|
|
350
|
+
export function clipped<R extends { start: number; end: number; element?: number }>(region: R, holes: readonly AddressRange[]): R[] {
|
|
351
|
+
return subtract(region, [...holes]).map((piece) => {
|
|
352
|
+
if (piece.start === region.start && piece.end === region.end) return region;
|
|
353
|
+
const part = { ...region, ...piece };
|
|
354
|
+
delete part.element;
|
|
355
|
+
return part;
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** The regions that decide the memory map: the user and LLM regions, and the parts of analyzer regions outside them. */
|
|
360
|
+
export function effectiveRegions(regions: RegionRow[]): RegionRow[] {
|
|
361
|
+
const semantic = regions.filter((region) => isSemantic(region.origin));
|
|
362
|
+
const holes = semantic.map((region) => ({ start: region.start, end: region.end }));
|
|
363
|
+
return [...semantic, ...regions.filter((region) => !isSemantic(region.origin)).flatMap((region) => clipped(region, holes))].sort((a, b) => a.start - b.start);
|
|
364
|
+
}
|
|
@@ -7,34 +7,8 @@
|
|
|
7
7
|
import type { DatabaseSync } from "node:sqlite";
|
|
8
8
|
|
|
9
9
|
import type { HistoryEntry } from "./history.ts";
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
MACRO_COLUMNS,
|
|
13
|
-
MACRO_USE_COLUMNS,
|
|
14
|
-
MODULE_COLUMNS,
|
|
15
|
-
OPERAND_COLUMNS,
|
|
16
|
-
PATCH_COLUMNS,
|
|
17
|
-
REFERENCE_COLUMNS,
|
|
18
|
-
RELEASE_COLUMNS,
|
|
19
|
-
START_SCREEN_COLUMNS,
|
|
20
|
-
SWITCH_COLUMNS,
|
|
21
|
-
REGION_COLUMNS,
|
|
22
|
-
SUPPRESSION_COLUMNS,
|
|
23
|
-
SYMBOL_COLUMNS,
|
|
24
|
-
toComment,
|
|
25
|
-
toMacro,
|
|
26
|
-
toMacroUse,
|
|
27
|
-
toModule,
|
|
28
|
-
toOperand,
|
|
29
|
-
toPatch,
|
|
30
|
-
toReference,
|
|
31
|
-
toRelease,
|
|
32
|
-
toStartScreen,
|
|
33
|
-
toSwitch,
|
|
34
|
-
toRegion,
|
|
35
|
-
toSuppression,
|
|
36
|
-
toSymbol,
|
|
37
|
-
} from "./read.ts";
|
|
10
|
+
import { prepare } from "./database.ts";
|
|
11
|
+
import { FACTS, type Fact } from "./read.ts";
|
|
38
12
|
import type { Space } from "./schema.ts";
|
|
39
13
|
import { compareText, sqlName } from "./text.ts";
|
|
40
14
|
|
|
@@ -78,10 +52,7 @@ type Raw = Record<string, unknown>;
|
|
|
78
52
|
|
|
79
53
|
interface TableRule {
|
|
80
54
|
rule: ConflictRule;
|
|
81
|
-
|
|
82
|
-
entity: HistoryEntry["entity"];
|
|
83
|
-
columns: string;
|
|
84
|
-
map: (raw: Raw) => HistoryEntry["row"];
|
|
55
|
+
fact: Fact;
|
|
85
56
|
/**
|
|
86
57
|
* The columns that must differ between current rows, "overlap" for address
|
|
87
58
|
* ranges, or "partial" for ranges that may only overlap when they are equal.
|
|
@@ -92,40 +63,32 @@ interface TableRule {
|
|
|
92
63
|
}
|
|
93
64
|
|
|
94
65
|
const RULES: readonly TableRule[] = [
|
|
95
|
-
{ rule: "symbol-address",
|
|
96
|
-
{ rule: "symbol-name",
|
|
97
|
-
{ rule: "analyzer-name-address",
|
|
98
|
-
{ rule: "analyzer-name-name",
|
|
99
|
-
{ rule: "region",
|
|
100
|
-
{ rule: "comment",
|
|
101
|
-
{ rule: "reference",
|
|
102
|
-
{ rule: "operand",
|
|
103
|
-
{ rule: "module-start",
|
|
104
|
-
{ rule: "module-file",
|
|
105
|
-
{ rule: "suppression-symbol",
|
|
106
|
-
{
|
|
107
|
-
|
|
108
|
-
table: "suppressions",
|
|
109
|
-
entity: "suppression",
|
|
110
|
-
columns: SUPPRESSION_COLUMNS,
|
|
111
|
-
map: toSuppression,
|
|
112
|
-
key: ["start_address", "to_address", "kind"],
|
|
113
|
-
where: "entity = 'reference'",
|
|
114
|
-
},
|
|
115
|
-
{ rule: "suppression-region", table: "suppressions", entity: "suppression", columns: SUPPRESSION_COLUMNS, map: toSuppression, key: "overlap", where: "entity = 'region'" },
|
|
66
|
+
{ rule: "symbol-address", fact: FACTS.symbols, key: ["address"] },
|
|
67
|
+
{ rule: "symbol-name", fact: FACTS.symbols, key: ["name"] },
|
|
68
|
+
{ rule: "analyzer-name-address", fact: FACTS.analyzer_names, key: ["address", "origin"] },
|
|
69
|
+
{ rule: "analyzer-name-name", fact: FACTS.analyzer_names, key: ["name", "origin"] },
|
|
70
|
+
{ rule: "region", fact: FACTS.regions, key: "overlap" },
|
|
71
|
+
{ rule: "comment", fact: FACTS.comments, key: ["address", "placement"] },
|
|
72
|
+
{ rule: "reference", fact: FACTS.references, key: ["from_address", "to_address", "kind"] },
|
|
73
|
+
{ rule: "operand", fact: FACTS.operands, key: ["address"] },
|
|
74
|
+
{ rule: "module-start", fact: FACTS.modules, key: ["start_address"] },
|
|
75
|
+
{ rule: "module-file", fact: FACTS.modules, key: ["file"] },
|
|
76
|
+
{ rule: "suppression-symbol", fact: FACTS.suppressions, key: ["start_address"], where: "entity = 'symbol'" },
|
|
77
|
+
{ rule: "suppression-reference", fact: FACTS.suppressions, key: ["start_address", "to_address", "kind"], where: "entity = 'reference'" },
|
|
78
|
+
{ rule: "suppression-region", fact: FACTS.suppressions, key: "overlap", where: "entity = 'region'" },
|
|
116
79
|
// Patches of different switches at the same range are alternatives; any other overlap is a conflict.
|
|
117
|
-
{ rule: "patch",
|
|
118
|
-
{ rule: "patch-switch",
|
|
119
|
-
{ rule: "switch",
|
|
120
|
-
{ rule: "release",
|
|
121
|
-
{ rule: "release-base",
|
|
122
|
-
{ rule: "start-screen",
|
|
123
|
-
{ rule: "macro",
|
|
124
|
-
{ rule: "macro-use",
|
|
80
|
+
{ rule: "patch", fact: FACTS.patches, key: "partial" },
|
|
81
|
+
{ rule: "patch-switch", fact: FACTS.patches, key: ["start_address", "end_address", "switch_name"] },
|
|
82
|
+
{ rule: "switch", fact: FACTS.switches, key: ["name"] },
|
|
83
|
+
{ rule: "release", fact: FACTS.releases, key: ["label"] },
|
|
84
|
+
{ rule: "release-base", fact: FACTS.releases, key: ["base"], where: "base = 1" },
|
|
85
|
+
{ rule: "start-screen", fact: FACTS.start_screens, key: [] },
|
|
86
|
+
{ rule: "macro", fact: FACTS.macros, key: ["name"] },
|
|
87
|
+
{ rule: "macro-use", fact: FACTS.macro_uses, key: "overlap" },
|
|
125
88
|
];
|
|
126
89
|
|
|
127
90
|
function conflictRow(rule: TableRule, raw: Raw): ConflictRow {
|
|
128
|
-
return { entity: rule.entity, row: rule.map(raw), from: raw.valid_from_revision as string, id: raw.id as string } as ConflictRow;
|
|
91
|
+
return { entity: rule.fact.entity, row: rule.fact.map(raw), from: raw.valid_from_revision as string, id: raw.id as string } as ConflictRow;
|
|
129
92
|
}
|
|
130
93
|
|
|
131
94
|
const byAge = (a: ConflictRow, b: ConflictRow) => compareText(a.from, b.from) || compareText(a.id, b.id);
|
|
@@ -134,9 +97,8 @@ const byAge = (a: ConflictRow, b: ConflictRow) => compareText(a.from, b.from) ||
|
|
|
134
97
|
function sameKey(db: DatabaseSync, rule: TableRule, key: readonly string[]): Conflict[] {
|
|
135
98
|
const where = `valid_to_revision IS NULL${rule.where === undefined ? "" : ` AND ${rule.where}`}`;
|
|
136
99
|
const columns = ["space", ...key].join(", ");
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
.all() as Raw[];
|
|
100
|
+
const table = sqlName(rule.fact.table);
|
|
101
|
+
const rows = prepare(db, `SELECT ${rule.fact.columns}, id FROM ${table} WHERE ${where} AND (${columns}) IN (SELECT ${columns} FROM ${table} WHERE ${where} GROUP BY ${columns} HAVING count(*) > 1)`).all() as Raw[];
|
|
140
102
|
const groups = new Map<string, Conflict>();
|
|
141
103
|
for (const raw of rows) {
|
|
142
104
|
const id = JSON.stringify(["space", ...key].map((column) => raw[column]));
|
|
@@ -153,9 +115,7 @@ function sameKey(db: DatabaseSync, rule: TableRule, key: readonly string[]): Con
|
|
|
153
115
|
* range is no conflict.
|
|
154
116
|
*/
|
|
155
117
|
function overlapping(db: DatabaseSync, rule: TableRule, sameRange = false): Conflict[] {
|
|
156
|
-
const rows = db
|
|
157
|
-
.prepare(`SELECT ${rule.columns}, id FROM ${sqlName(rule.table)} WHERE valid_to_revision IS NULL${rule.where === undefined ? "" : ` AND ${rule.where}`} ORDER BY space, start_address, end_address`)
|
|
158
|
-
.all() as Raw[];
|
|
118
|
+
const rows = prepare(db, `SELECT ${rule.fact.columns}, id FROM ${sqlName(rule.fact.table)} WHERE valid_to_revision IS NULL${rule.where === undefined ? "" : ` AND ${rule.where}`} ORDER BY space, start_address, end_address`).all() as Raw[];
|
|
159
119
|
const conflicts: Conflict[] = [];
|
|
160
120
|
let group: Conflict | undefined;
|
|
161
121
|
let end = -1;
|
|
@@ -177,13 +137,15 @@ function overlapping(db: DatabaseSync, rule: TableRule, sameRange = false): Conf
|
|
|
177
137
|
});
|
|
178
138
|
}
|
|
179
139
|
|
|
180
|
-
/** Every conflict of the knowledge, rule by rule; the rows of each, oldest first. */
|
|
181
|
-
export function conflicts(db: DatabaseSync | undefined): Conflict[] {
|
|
140
|
+
/** Every conflict of the knowledge, rule by rule; the rows of each, oldest first. With `tables`, only the rules of those tables. */
|
|
141
|
+
export function conflicts(db: DatabaseSync | undefined, tables?: ReadonlySet<string>): Conflict[] {
|
|
182
142
|
if (db === undefined) return [];
|
|
183
|
-
return RULES.
|
|
143
|
+
return RULES.filter((rule) => tables === undefined || tables.has(rule.fact.table))
|
|
144
|
+
.flatMap((rule) => (rule.key === "overlap" || rule.key === "partial" ? overlapping(db, rule, rule.key === "partial") : sameKey(db, rule, rule.key)))
|
|
145
|
+
.map((conflict) => ({ ...conflict, rows: conflict.rows.sort(byAge) }));
|
|
184
146
|
}
|
|
185
147
|
|
|
186
148
|
/** The table of a conflict rule. */
|
|
187
149
|
export function conflictTable(rule: ConflictRule): string {
|
|
188
|
-
return RULES.find((item) => item.rule === rule)!.table;
|
|
150
|
+
return RULES.find((item) => item.rule === rule)!.fact.table;
|
|
189
151
|
}
|